/
AsyncFailsafeTest.java
468 lines (403 loc) · 15.7 KB
/
AsyncFailsafeTest.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
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package net.jodah.failsafe;
import net.jodah.concurrentunit.Waiter;
import net.jodah.failsafe.Testing.ConnectException;
import net.jodah.failsafe.Testing.Service;
import net.jodah.failsafe.function.*;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.time.Duration;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import static net.jodah.failsafe.Asserts.assertThrows;
import static net.jodah.failsafe.Asserts.matches;
import static net.jodah.failsafe.Testing.failures;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
@Test
public class AsyncFailsafeTest extends AbstractFailsafeTest {
private ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
private Waiter waiter;
// Results from a getAsync against a future that wraps an asynchronous Failsafe call
private @SuppressWarnings("unchecked") Class<? extends Throwable>[] futureAsyncThrowables = new Class[] {
ExecutionException.class, ConnectException.class };
@BeforeMethod
protected void beforeMethod() {
reset(service);
waiter = new Waiter();
counter = new AtomicInteger();
}
@Override
ScheduledExecutorService getExecutor() {
return executor;
}
private void assertRunAsync(Object runnable) throws Throwable {
// Given - Fail twice then succeed
when(service.connect()).thenThrow(failures(2, new ConnectException())).thenReturn(true);
AtomicInteger expectedExecutions = new AtomicInteger(3);
// When / Then
Future<?> future = runAsync(Failsafe.with(retryAlways).with(executor).onComplete(e -> {
waiter.assertEquals(expectedExecutions.get(), e.getAttemptCount());
waiter.assertNull(e.getResult());
waiter.assertNull(e.getFailure());
waiter.resume();
}), runnable);
assertNull(future.get());
waiter.await(3000);
verify(service, times(3)).connect();
// Given - Fail three times
reset(service);
counter.set(0);
when(service.connect()).thenThrow(failures(10, new ConnectException()));
// When
Future<?> future2 = runAsync(Failsafe.with(retryTwice).with(executor).onComplete(e -> {
waiter.assertEquals(expectedExecutions.get(), e.getAttemptCount());
waiter.assertNull(e.getResult());
waiter.assertTrue(e.getFailure() instanceof ConnectException);
waiter.resume();
}), runnable);
// Then
assertThrows(future2::get, futureAsyncThrowables);
waiter.await(3000);
verify(service, times(3)).connect();
}
public void shouldRunWithExecutor() throws Throwable {
assertRunAsync((CheckedRunnable) service::connect);
}
public void shouldRunContextualWithExecutor() throws Throwable {
assertRunAsync((ContextualRunnable) context -> {
assertEquals(context.getAttemptCount(), counter.getAndIncrement());
service.connect();
});
}
public void shouldRunAsync() throws Throwable {
assertRunAsync((AsyncRunnable) exec -> {
try {
service.connect();
exec.complete();
} catch (Exception failure) {
// Alternate between automatic and manual retries
if (exec.getAttemptCount() % 2 == 0)
throw failure;
if (!exec.retryOn(failure))
throw failure;
}
});
}
private void assertGetAsync(Object supplier) throws Throwable {
// Given - Fail twice then succeed
when(service.connect()).thenThrow(failures(2, new ConnectException())).thenReturn(false, false, true);
RetryPolicy<Boolean> retryPolicy = new RetryPolicy<Boolean>().handleResult(false);
AtomicInteger expectedExecutions = new AtomicInteger(5);
// When / Then
Future<Boolean> future = getAsync(Failsafe.with(retryPolicy).with(executor).onComplete(e -> {
waiter.assertEquals(expectedExecutions.get(), e.getAttemptCount());
waiter.assertTrue(e.getResult());
waiter.assertNull(e.getFailure());
waiter.resume();
}), supplier);
assertTrue(future.get());
waiter.await(3000);
verify(service, times(expectedExecutions.get())).connect();
// Given - Fail three times
reset(service);
counter.set(0);
when(service.connect()).thenThrow(failures(10, new ConnectException()));
expectedExecutions.set(3);
// When / Then
Future<Boolean> future2 = getAsync(Failsafe.with(retryTwice).with(executor).onComplete(e -> {
waiter.assertEquals(expectedExecutions.get(), e.getAttemptCount());
waiter.assertNull(e.getResult());
waiter.assertTrue(e.getFailure() instanceof ConnectException);
waiter.resume();
}), supplier);
assertThrows(future2::get, futureAsyncThrowables);
waiter.await(3000);
verify(service, times(expectedExecutions.get())).connect();
}
public void shouldGetWithExecutor() throws Throwable {
assertGetAsync((CheckedSupplier<?>) service::connect);
}
public void shouldGetContextualWithExecutor() throws Throwable {
assertGetAsync((ContextualSupplier<Boolean>) context -> {
assertEquals(context.getAttemptCount(), counter.getAndIncrement());
return service.connect();
});
}
public void shouldGetAsync() throws Throwable {
assertGetAsync((AsyncSupplier<?>) exec -> {
try {
boolean result = service.connect();
if (!exec.complete(result))
exec.retry();
return result;
} catch (Exception failure) {
// Alternate between automatic and manual retries
if (exec.getAttemptCount() % 2 == 0)
throw failure;
if (!exec.retryOn(failure))
throw failure;
return null;
}
});
}
private void assertFuture(Object supplier) throws Throwable {
// Given - Fail twice then succeed
when(service.connect()).thenThrow(failures(2, new ConnectException())).thenReturn(false, false, true);
RetryPolicy<Boolean> retryPolicy = new RetryPolicy<Boolean>().handleResult(false);
// When
CompletableFuture<Boolean> future = futureAsync(Failsafe.with(retryPolicy).with(executor), supplier);
// Then
future.whenComplete((result, failure) -> {
waiter.assertTrue(result);
waiter.assertNull(failure);
waiter.resume();
});
assertTrue(future.get());
waiter.await(3000);
verify(service, times(5)).connect();
// Given - Fail three times
reset(service);
when(service.connect()).thenThrow(failures(10, new ConnectException()));
// When
CompletableFuture<Boolean> future2 = futureAsync(Failsafe.with(retryTwice).with(executor), supplier);
// Then
future2.whenComplete((result, failure) -> {
waiter.assertNull(result);
waiter.assertTrue(matches(failure, ConnectException.class));
waiter.resume();
});
assertThrows(future2::get, futureAsyncThrowables);
waiter.await(3000);
verify(service, times(3)).connect();
}
public void shouldGetFutureAsync() throws Throwable {
assertFuture((CheckedSupplier<?>) () -> CompletableFuture.supplyAsync(service::connect));
}
public void shouldGetFutureAsyncContextual() throws Throwable {
assertFuture((ContextualSupplier<?>) context -> CompletableFuture.supplyAsync(service::connect));
}
public void shouldGetFutureAsyncExecution() throws Throwable {
assertFuture((AsyncSupplier<?>) exec -> CompletableFuture.supplyAsync(() -> {
try {
boolean result = service.connect();
if (!exec.complete(result))
exec.retryFor(result);
return result;
} catch (Exception failure) {
// Alternate between automatic and manual retries
if (exec.getAttemptCount() % 2 == 0)
throw failure;
if (!exec.retryOn(failure))
throw failure;
return null;
}
}));
}
private void assertCancel(Function<FailsafeExecutor<?>, Future<?>> executorCallable) throws Throwable {
// Given
Waiter waiter = new Waiter();
Future<?> future = executorCallable.apply(Failsafe.with(retryAlways).with(executor).onComplete(e -> {
waiter.assertNull(e.getResult());
waiter.assertTrue(e.getFailure() instanceof CancellationException);
waiter.resume();
}));
Testing.sleep(300);
// When
assertTrue(future.cancel(true));
waiter.await(1000);
// Then
assertTrue(future.isCancelled());
assertTrue(future.isDone());
Asserts.assertThrows(future::get, CancellationException.class);
}
public void shouldCancelOnGetAsync() throws Throwable {
assertCancel(executor -> getAsync(executor, (CheckedSupplier<?>) () -> {
Thread.sleep(1000);
return "test";
}));
}
public void shouldCancelOnGetAsyncExecutor() throws Throwable {
assertCancel(executor -> getAsync(executor, (AsyncSupplier<?>) (e) -> {
Thread.sleep(1000);
e.complete();
return null;
}));
}
public void shouldCancelOnRunAsync() throws Throwable {
assertCancel(executor -> runAsync(executor, (CheckedRunnable) () -> {
Thread.sleep(1000);
}));
}
public void shouldCancelOnRunAsyncExecutor() throws Throwable {
assertCancel(executor -> runAsync(executor, (AsyncRunnable) (e) -> {
Thread.sleep(1000);
e.complete();
}));
}
public void shouldCancelOnFutureAsync() throws Throwable {
assertCancel(executor -> futureAsync(executor, (CheckedSupplier<?>) () -> {
Thread.sleep(1000);
return CompletableFuture.completedFuture("test");
}));
}
public void shouldCancelOnFutureAsyncExecutor() throws Throwable {
assertCancel(executor -> futureAsync(executor, (AsyncSupplier<?>) (e) -> {
Thread.sleep(1000);
CompletableFuture<?> result = CompletableFuture.completedFuture("test");
e.complete(result);
return result;
}));
}
public void shouldManuallyRetryAndComplete() throws Throwable {
Failsafe.with(retryAlways).with(executor).onComplete(e -> {
waiter.assertTrue(e.getResult());
waiter.assertNull(e.getFailure());
waiter.resume();
}).getAsyncExecution(exec -> {
if (exec.getAttemptCount() < 2)
exec.retryOn(new ConnectException());
else
exec.complete(true);
return true;
});
waiter.await(3000);
}
/**
* Assert handles a supplier that throws instead of returning a future.
*/
public void shouldHandleThrowingFutureSupplier() {
assertThrows(() -> Failsafe.with(retryTwice).with(executor).getStageAsync(() -> {
throw new IllegalArgumentException();
}).get(), ExecutionException.class, IllegalArgumentException.class);
assertThrows(() -> Failsafe.with(retryTwice).with(executor).getStageAsync(context -> {
throw new IllegalArgumentException();
}).get(), ExecutionException.class, IllegalArgumentException.class);
assertThrows(() -> Failsafe.with(retryTwice).with(executor).getStageAsyncExecution(exec -> {
throw new IllegalArgumentException();
}).get(), ExecutionException.class, IllegalArgumentException.class);
}
/**
* Asserts that asynchronous completion via an execution is supported.
*/
public void shouldCompleteAsync() throws Throwable {
Waiter waiter = new Waiter();
Failsafe.with(retryAlways).with(executor).runAsyncExecution(exec -> executor.schedule(() -> {
try {
exec.complete();
waiter.resume();
} catch (Exception e) {
waiter.fail(e);
}
}, 100, TimeUnit.MILLISECONDS));
waiter.await(5000);
}
public void shouldOpenCircuitWhenTimeoutExceeded() throws Throwable {
// Given
CircuitBreaker<Object> breaker = new CircuitBreaker<>().withTimeout(Duration.ofMillis(10));
assertTrue(breaker.isClosed());
// When
Failsafe.with(breaker).with(executor).runAsyncExecution(exec -> {
Thread.sleep(20);
exec.complete();
waiter.resume();
});
// Then
waiter.await(1000);
assertTrue(breaker.isOpen());
}
public void shouldSkipExecutionWhenCircuitOpen() {
// Given
CircuitBreaker<Object> breaker = new CircuitBreaker<>().withDelay(Duration.ofMillis(10));
breaker.open();
AtomicBoolean executed = new AtomicBoolean();
// When
Future future = Failsafe.with(breaker).with(executor).runAsync(() -> executed.set(true));
// Then
assertFalse(executed.get());
assertThrows(future::get, ExecutionException.class, CircuitBreakerOpenException.class);
}
/**
* Asserts that Failsafe handles an initial scheduling failure.
*/
public void shouldHandleInitialSchedulingFailure() {
// Given
ScheduledExecutorService executor = Executors.newScheduledThreadPool(0);
executor.shutdownNow();
Waiter waiter = new Waiter();
// When
Future future = Failsafe.with(Fallback.of(false), new RetryPolicy<>(), new CircuitBreaker<>())
.with(executor)
.runAsync(() -> waiter.fail("Should not execute supplier since executor has been shutdown"));
assertThrows(future::get, ExecutionException.class, RejectedExecutionException.class);
}
/**
* Asserts that Failsafe handles a rpRetry scheduling failure.
*/
public void shouldHandleRejectedRetryExecution() throws Throwable {
// Given
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
AtomicInteger counter = new AtomicInteger();
// When
Future future = Failsafe.with(new RetryPolicy<>().handleResult(null).handle(Exception.class))
.with(executor)
.getAsync(() -> {
counter.incrementAndGet();
Thread.sleep(200);
return null;
});
Thread.sleep(150);
executor.shutdownNow();
assertThrows(future::get, ExecutionException.class, RejectedExecutionException.class);
assertEquals(counter.get(), 1, "Supplier should have been executed before executor was shutdown");
}
@SuppressWarnings("unused")
public void shouldSupportCovariance() {
FastService fastService = mock(FastService.class);
CompletionStage<Service> stage = Failsafe.with(new RetryPolicy<Service>())
.with(executor)
.getAsync(() -> fastService);
}
private Future<?> runAsync(FailsafeExecutor<?> failsafe, Object runnable) {
if (runnable instanceof CheckedRunnable)
return failsafe.runAsync((CheckedRunnable) runnable);
else if (runnable instanceof ContextualRunnable)
return failsafe.runAsync((ContextualRunnable) runnable);
else
return failsafe.runAsyncExecution((AsyncRunnable) runnable);
}
@SuppressWarnings("unchecked")
private <T> Future<T> getAsync(FailsafeExecutor<T> failsafe, Object supplier) {
if (supplier instanceof CheckedSupplier)
return failsafe.getAsync((CheckedSupplier<T>) supplier);
else if (supplier instanceof ContextualSupplier)
return failsafe.getAsync((ContextualSupplier<T>) supplier);
else
return failsafe.getAsyncExecution((AsyncSupplier<T>) supplier);
}
@SuppressWarnings("unchecked")
private <T> CompletableFuture<T> futureAsync(FailsafeExecutor<T> failsafe, Object supplier) {
if (supplier instanceof CheckedSupplier)
return failsafe.getStageAsync((CheckedSupplier<CompletableFuture<T>>) supplier);
else if (supplier instanceof ContextualSupplier)
return failsafe.getStageAsync((ContextualSupplier<CompletableFuture<T>>) supplier);
else
return failsafe.getStageAsyncExecution((AsyncSupplier<CompletableFuture<T>>) supplier);
}
}