-
Notifications
You must be signed in to change notification settings - Fork 431
/
GRpcRecoveryTest.java
322 lines (235 loc) · 11.6 KB
/
GRpcRecoveryTest.java
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
package org.lognet.springboot.grpc.recovery;
import io.grpc.*;
import io.grpc.examples.custom.Custom;
import io.grpc.examples.custom.CustomServiceGrpc;
import io.grpc.stub.StreamObserver;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.lognet.springboot.grpc.GRpcService;
import org.lognet.springboot.grpc.GrpcServerTestBase;
import org.lognet.springboot.grpc.demo.DemoApp;
import org.lognet.springboot.grpc.security.*;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.context.annotation.Import;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isA;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {DemoApp.class}, webEnvironment = NONE)
@Import(GRpcRecoveryTest.Cfg.class)
public class GRpcRecoveryTest extends GrpcServerTestBase {
static class CheckedException extends Exception {
}
static class CheckedException1 extends Exception {
}
static class ExceptionA extends RuntimeException {
}
static class ExceptionB extends ExceptionA {
}
static class Exception1 extends RuntimeException {
}
private static User user1 = new User("test1", "test1", Collections.EMPTY_LIST);
private AuthHeader.AuthHeaderBuilder user1AuthHeaderBuilder =
AuthHeader.builder().basic(user1.getUsername(), user1.getPassword().getBytes());
@TestConfiguration
static class Cfg extends GrpcSecurityConfigurerAdapter {
@Override
public void configure(GrpcSecurity builder) throws Exception {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
UserDetailsService users = new InMemoryUserDetailsManager(user1);
provider.setUserDetailsService(users);
provider.setPasswordEncoder(NoOpPasswordEncoder.getInstance());
builder
.authenticationProvider(provider)
.authorizeRequests()
.anyMethod().authenticated();
}
@GRpcServiceAdvice
static class CustomErrorHandler {
@GRpcExceptionHandler
public Status handleA(ExceptionA e, GRpcExceptionScope scope) {
return Status.NOT_FOUND;
}
@GRpcExceptionHandler
public Status handleB(ExceptionB e, GRpcExceptionScope scope) {
return Status.ALREADY_EXISTS;
}
@GRpcExceptionHandler
public Status handleCheckedException(CheckedException e, GRpcExceptionScope scope) {
return Status.OUT_OF_RANGE;
}
@GRpcExceptionHandler
public Status handle(Exception e, GRpcExceptionScope scope) {
return Status.DATA_LOSS;
}
}
@GRpcService
static class CustomService extends CustomServiceGrpc.CustomServiceImplBase {
@Override
public void custom(Custom.CustomRequest request, StreamObserver<Custom.CustomReply> responseObserver) {
super.custom(request, responseObserver);
}
@Override
public StreamObserver<Custom.CustomRequest> customStream(StreamObserver<Custom.CustomReply> responseObserver) {
return new StreamObserver<Custom.CustomRequest>() {
@Override
public void onNext(Custom.CustomRequest value) {
if ("onNext".equalsIgnoreCase(value.getName())) {
throw new GRpcRuntimeExceptionWrapper(new CheckedException1());
}
responseObserver.onNext(Custom.CustomReply.newBuilder().build());
}
@Override
public void onError(Throwable t) {
}
@Override
public void onCompleted() {
throw new GRpcRuntimeExceptionWrapper(new CheckedException1());
}
};
}
@GRpcExceptionHandler
public Status handle(CheckedException1 e, GRpcExceptionScope scope) {
return Status.RESOURCE_EXHAUSTED;
}
@GRpcExceptionHandler
public Status handleB(ExceptionB e, GRpcExceptionScope scope) {
assertThat(scope.getResponseHeaders(), notNullValue());
scope.getResponseHeaders().put(Metadata.Key.of("test", Metadata.ASCII_STRING_MARSHALLER), "5");
assertThat(scope.getRequest(), notNullValue());
assertThat(scope.getRequest(), isA(Custom.CustomRequest.class));
assertThat(scope.getCallHeaders(), notNullValue());
assertThat(scope.getMethodCallAttributes(), notNullValue());
assertThat(scope.getMethodDescriptor(), notNullValue());
return Status.FAILED_PRECONDITION;
}
}
}
@SpyBean
private Cfg.CustomService srv;
@SpyBean
private Cfg.CustomErrorHandler handler;
protected Channel getChannel() {
return ClientInterceptors.intercept(super.getChannel(), new AuthClientInterceptor(user1AuthHeaderBuilder));
}
@Test
public void parameterizedStreamingServiceErrorHandlerTest() throws ExecutionException, InterruptedException, TimeoutException {
String[] phases = new String[]{
"onNext", // exception will be thrown onNext
"onCompleted" // exception will be thrown onCompleted
};
for (String errorPhase : phases) {
streamingServiceErrorHandlerTest(errorPhase);
Mockito.clearInvocations(srv);
}
}
public void streamingServiceErrorHandlerTest(String errorName) throws ExecutionException, InterruptedException, TimeoutException {
final CompletableFuture<Throwable> errorFuture = new CompletableFuture<>();
final StreamObserver<Custom.CustomReply> reply = new StreamObserver<Custom.CustomReply>() {
@Override
public void onNext(Custom.CustomReply value) {
}
@Override
public void onError(Throwable t) {
errorFuture.complete(t);
}
@Override
public void onCompleted() {
errorFuture.complete(null);
}
};
final StreamObserver<Custom.CustomRequest> requests = CustomServiceGrpc.newStub(getChannel())
.customStream(reply);
requests.onNext(Custom.CustomRequest.newBuilder().setName(errorName).build());
requests.onCompleted();
final Throwable actual = errorFuture.get(20, TimeUnit.SECONDS);
assertThat(actual, notNullValue());
assertThat(actual, isA(StatusRuntimeException.class));
assertThat(((StatusRuntimeException) actual).getStatus(), is(Status.RESOURCE_EXHAUSTED));
Mockito.verify(srv, times(1)).handle(any(CheckedException1.class), any());
}
@Test
public void checkedExceptionHandlerTest() {
Mockito.doThrow(new GRpcRuntimeExceptionWrapper(new CheckedException()))
.when(srv)
.custom(any(Custom.CustomRequest.class), any(StreamObserver.class));
final StatusRuntimeException statusRuntimeException = assertThrows(StatusRuntimeException.class, () ->
CustomServiceGrpc.newBlockingStub(getChannel())
.custom(Custom.CustomRequest.newBuilder().build())
);
assertThat(statusRuntimeException.getStatus(), is(Status.OUT_OF_RANGE));
Mockito.verify(srv, never()).handleB(any(), any());
Mockito.verify(handler, never()).handle(any(), any());
Mockito.verify(handler, never()).handleA(any(), any());
Mockito.verify(handler, times(1)).handleCheckedException(any(CheckedException.class), any());
Mockito.verify(handler, never()).handleB(any(), any());
}
@Test
public void globalHandlerTest() {
Mockito.doThrow(ExceptionA.class)
.when(srv)
.custom(any(Custom.CustomRequest.class), any(StreamObserver.class));
final StatusRuntimeException statusRuntimeException = assertThrows(StatusRuntimeException.class, () ->
CustomServiceGrpc.newBlockingStub(getChannel())
.custom(Custom.CustomRequest.newBuilder().build())
);
assertThat(statusRuntimeException.getStatus(), is(Status.NOT_FOUND));
Mockito.verify(srv, never()).handleB(any(), any());
Mockito.verify(handler, never()).handle(any(), any());
Mockito.verify(handler, times(1)).handleA(any(), any());
Mockito.verify(handler, never()).handleB(any(), any());
}
@Test
public void globalHandlerWithExceptionHierarchyTest() {
Mockito.doThrow(Exception1.class)
.when(srv)
.custom(any(Custom.CustomRequest.class), any(StreamObserver.class));
final StatusRuntimeException statusRuntimeException = assertThrows(StatusRuntimeException.class, () ->
CustomServiceGrpc.newBlockingStub(getChannel())
.custom(Custom.CustomRequest.newBuilder().build())
);
assertThat(statusRuntimeException.getStatus(), is(Status.DATA_LOSS));
Mockito.verify(srv, never()).handleB(any(), any());
Mockito.verify(handler, never()).handleA(any(), any());
Mockito.verify(handler, never()).handleB(any(), any());
Mockito.verify(handler, times(1)).handle(any(), any());
}
@Test
public void privateHandlerHasHigherPrecedence() {
Mockito.doThrow(ExceptionB.class)
.when(srv)
.custom(any(Custom.CustomRequest.class), any(StreamObserver.class));
final StatusRuntimeException statusRuntimeException = assertThrows(StatusRuntimeException.class, () ->
CustomServiceGrpc.newBlockingStub(getChannel())
.custom(Custom.CustomRequest.newBuilder().build())
);
assertThat(statusRuntimeException.getStatus(), is(Status.FAILED_PRECONDITION));
Mockito.verify(srv, times(1)).handleB(any(), any());
final String testTrailer = statusRuntimeException.getTrailers().get(Metadata.Key.of("test", Metadata.ASCII_STRING_MARSHALLER));
assertThat(testTrailer, is("5"));
Mockito.verify(handler, never()).handle(any(), any());
Mockito.verify(handler, never()).handleA(any(), any());
Mockito.verify(handler, never()).handleB(any(), any());
}
}