-
-
Notifications
You must be signed in to change notification settings - Fork 201
Expand file tree
/
Copy pathGrpcTest.java
More file actions
380 lines (323 loc) · 13.8 KB
/
Copy pathGrpcTest.java
File metadata and controls
380 lines (323 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby.i3875;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.protobuf.services.ProtoReflectionServiceV1;
import io.grpc.reflection.v1.ServerReflectionGrpc;
import io.grpc.reflection.v1.ServerReflectionRequest;
import io.grpc.reflection.v1.ServerReflectionResponse;
import io.grpc.stub.StreamObserver;
import io.jooby.Jooby;
import io.jooby.ServerOptions;
import io.jooby.grpc.GrpcModule;
import io.jooby.guice.GuiceModule;
import io.jooby.junit.ServerTest;
import io.jooby.junit.ServerTestRunner;
public class GrpcTest {
private void setupApp(Jooby app) {
app.install(new GuiceModule());
app.install(
new GrpcModule(new EchoChatService(), ProtoReflectionServiceV1.newInstance())
.bind(EchoGreeterService.class));
}
@ServerTest
void shouldHandleUnaryRequests(ServerTestRunner runner) {
runner
.options(new ServerOptions().setHttp2(true).setSecurePort(8443))
.define(this::setupApp)
.ready(
http -> {
var channel =
ManagedChannelBuilder.forAddress("localhost", runner.getAllocatedPort())
.usePlaintext()
.build();
try {
var stub = GreeterGrpc.newBlockingStub(channel);
var response =
stub.sayHello(HelloRequest.newBuilder().setName("Pablo Marmol").build());
assertThat(response.getMessage()).isEqualTo("Hello Pablo Marmol");
} finally {
channel.shutdown();
}
});
}
@ServerTest
void shouldHandleDeadlineExceeded(ServerTestRunner runner) {
runner
.options(new ServerOptions().setHttp2(true).setSecurePort(8443))
.define(this::setupApp)
.ready(
http -> {
var channel =
ManagedChannelBuilder.forAddress("localhost", runner.getAllocatedPort())
.usePlaintext()
.build();
try {
// Attach an impossibly short deadline (1 millisecond) to the stub
var stub =
GreeterGrpc.newBlockingStub(channel)
.withDeadlineAfter(1, TimeUnit.MILLISECONDS);
var exception =
org.junit.jupiter.api.Assertions.assertThrows(
StatusRuntimeException.class,
() ->
stub.sayHello(
HelloRequest.newBuilder().setName("Pablo Marmol").build()));
// Assert that the bridge correctly caught the timeout and returned Status 4
assertThat(exception.getStatus().getCode())
.isEqualTo(Status.Code.DEADLINE_EXCEEDED);
} finally {
channel.shutdown();
}
});
}
@ServerTest
void shouldHandleBidiStreaming(ServerTestRunner runner) {
runner
.options(new ServerOptions().setHttp2(true).setSecurePort(8443))
.define(this::setupApp)
.ready(
http -> {
var channel =
ManagedChannelBuilder.forAddress("localhost", runner.getAllocatedPort())
.usePlaintext()
.build();
try {
var asyncStub = ChatServiceGrpc.newStub(channel);
var responses = new CopyOnWriteArrayList<String>();
var latch = new CountDownLatch(1);
StreamObserver<ChatMessage> responseObserver =
new StreamObserver<>() {
@Override
public void onNext(ChatMessage value) {
responses.add(value.getText());
}
@Override
public void onError(Throwable t) {
latch.countDown();
}
@Override
public void onCompleted() {
latch.countDown();
}
};
var requestObserver = asyncStub.chatStream(responseObserver);
requestObserver.onNext(
ChatMessage.newBuilder().setUser("JavaClient").setText("Ping 1").build());
// Add a tiny delay to prevent CI thread-scheduler race conditions
// where the server closes the stream before Undertow finishes flushing Ping 2.
Thread.sleep(50);
requestObserver.onNext(
ChatMessage.newBuilder().setUser("JavaClient").setText("Ping 2").build());
// Allow Ping 2 to reach the server before sending the close signal
Thread.sleep(50);
requestObserver.onCompleted();
// Wait for the server stream to gracefully complete
boolean completed = latch.await(5, TimeUnit.SECONDS);
assertThat(completed).isTrue();
assertThat(responses).containsExactly("Echo: Ping 1", "Echo: Ping 2");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
channel.shutdown();
}
});
}
@ServerTest
void shouldHandleServerStreaming(ServerTestRunner runner) {
runner
.options(new ServerOptions().setHttp2(true).setSecurePort(8443))
.define(this::setupApp)
.ready(
http -> {
var channel =
ManagedChannelBuilder.forAddress("localhost", runner.getAllocatedPort())
.usePlaintext()
.build();
try {
var asyncStub = ChatServiceGrpc.newStub(channel);
var responses = new CopyOnWriteArrayList<String>();
var latch = new CountDownLatch(1);
StreamObserver<ChatMessage> responseObserver =
new StreamObserver<>() {
@Override
public void onNext(ChatMessage value) {
responses.add(value.getText());
}
@Override
public void onError(Throwable t) {
latch.countDown();
}
@Override
public void onCompleted() {
latch.countDown();
}
};
// Assuming a server-streaming method exists: rpc ServerStream(ChatMessage) returns
// (stream ChatMessage)
// asyncStub.serverStream(ChatMessage.newBuilder().setText("Trigger").build(),
// responseObserver);
//
// boolean completed = latch.await(5, TimeUnit.SECONDS);
// assertThat(completed).isTrue();
// assertThat(responses.size()).isGreaterThan(1);
} finally {
channel.shutdown();
}
});
}
@ServerTest
void shouldHandleReflection(ServerTestRunner runner) {
runner
.options(new ServerOptions().setHttp2(true).setSecurePort(8443))
.define(this::setupApp)
.ready(
http -> {
var channel =
ManagedChannelBuilder.forAddress("localhost", runner.getAllocatedPort())
.usePlaintext()
.build();
try {
var stub = ServerReflectionGrpc.newStub(channel);
var registeredServices = new CopyOnWriteArrayList<String>();
var latch = new CountDownLatch(1);
StreamObserver<ServerReflectionResponse> responseObserver =
new StreamObserver<>() {
@Override
public void onNext(ServerReflectionResponse response) {
response
.getListServicesResponse()
.getServiceList()
.forEach(s -> registeredServices.add(s.getName()));
}
@Override
public void onError(Throwable t) {
latch.countDown();
}
@Override
public void onCompleted() {
latch.countDown();
}
};
var requestObserver = stub.serverReflectionInfo(responseObserver);
requestObserver.onNext(
ServerReflectionRequest.newBuilder()
.setListServices("")
.setHost("localhost")
.build());
requestObserver.onCompleted();
boolean completed = latch.await(5, TimeUnit.SECONDS);
assertThat(completed).isTrue();
assertThat(registeredServices)
.contains(
"io.jooby.i3875.Greeter",
"io.jooby.i3875.ChatService",
"grpc.reflection.v1.ServerReflection");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
channel.shutdown();
}
});
}
@ServerTest
void shouldHandleGrpcurlReflection(ServerTestRunner runner) {
org.junit.jupiter.api.Assumptions.assumeTrue(
isGrpcurlInstalled(), "grpcurl is not installed. Skipping strict HTTP/2 compliance test.");
runner
.options(new ServerOptions().setHttp2(true).setSecurePort(8443))
.define(this::setupApp)
.ready(
http -> {
try {
var pb =
new ProcessBuilder(
"grpcurl", "-plaintext", "localhost:" + runner.getAllocatedPort(), "list");
var process = pb.start();
var output =
new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
var error =
new String(process.getErrorStream().readAllBytes(), StandardCharsets.UTF_8);
int exitCode = process.waitFor();
assertThat(exitCode)
.withFailMessage("grpcurl failed with error: " + error)
.isEqualTo(0);
assertThat(output)
.contains(
"io.jooby.i3875.Greeter",
"io.jooby.i3875.ChatService",
"grpc.reflection.v1.ServerReflection");
} catch (Exception e) {
throw new RuntimeException("Failed to execute grpcurl test", e);
}
});
}
/**
* When a gRPC client requests a method that doesn't exist, our native handlers will ignore it.
* Jooby's core router will then catch it and return a standard HTTP 404 Not Found. According to
* the gRPC-over-HTTP/2 specification, the gRPC client will automatically translate a pure HTTP
* 404 into a gRPC UNIMPLEMENTED (Status Code 12) exception.
*
* @param runner Sever runner.
*/
@ServerTest
void shouldHandleMethodNotFound(ServerTestRunner runner) {
runner
.options(new ServerOptions().setHttp2(true).setSecurePort(8443))
.define(this::setupApp)
.ready(
http -> {
var channel =
ManagedChannelBuilder.forAddress("localhost", runner.getAllocatedPort())
.usePlaintext()
.build();
try {
// 1. Create a fake method descriptor for a non-existent method
var unknownMethod =
io.grpc.MethodDescriptor.<HelloRequest, HelloReply>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName("io.jooby.i3875.Greeter/UnknownMethod")
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
HelloRequest.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(HelloReply.getDefaultInstance()))
.build();
// 2. Execute the call manually and expect an exception
var exception =
org.junit.jupiter.api.Assertions.assertThrows(
io.grpc.StatusRuntimeException.class,
() ->
io.grpc.stub.ClientCalls.blockingUnaryCall(
channel,
unknownMethod,
io.grpc.CallOptions.DEFAULT,
HelloRequest.newBuilder().setName("Pablo Marmol").build()));
// 3. Assert that Jooby's HTTP 404 is correctly translated by the gRPC client into
// UNIMPLEMENTED
assertThat(exception.getStatus().getCode())
.isEqualTo(io.grpc.Status.Code.UNIMPLEMENTED);
} finally {
channel.shutdown();
}
});
}
private boolean isGrpcurlInstalled() {
try {
var process = new ProcessBuilder("grpcurl", "-version").start();
return process.waitFor() == 0;
} catch (Exception e) {
return false;
}
}
}