/** * Equivalent to {@code andThen("andThen", task)}. * @see #andThen(String, Task) */ default <R> Task<R> andThen(final Task<R> task) { return andThen("andThen: " + task.getName(), task); }
/** * Equivalent to {@code andThen("andThen", consumer)}. * @see #andThen(String, Consumer1) */ default Task<T> andThen(final Consumer1<? super T> consumer) { return andThen("andThen: " + _taskDescriptor.getDescription(consumer.getClass().getName()), consumer); }
private Task<?> truthMapQueryClassifyTask(final String name, final int remainder, final Classification classification) { final Task<Map<Long, Boolean>> svcCall = clientRequestTask(new TruthMapRequest("get" + name, remainder, _unclassified)); final Task<?> classifyResult = truthMapClassifyTask(name, classification, svcCall); return svcCall.andThen(classifyResult); }
@Override public Task<Map<Integer, Try<String>>> taskForBatch(Integer group, Set<Integer> keys) { return super.taskForBatch(group, keys).andThen(map -> map.remove(1)); } };
@Override public Promise<List<Integer>> run(final Context ctx) { // Save the start time so we can determine when to finish _startMillis = System.currentTimeMillis(); // Set up timeouts for responses long lastWaitTime = Integer.MAX_VALUE; for (final long waitTime : WAIT_TIMES) { if (waitTime < lastWaitTime && waitTime > 0) { ctx.createTimer(waitTime, TimeUnit.MILLISECONDS, checkDone()); lastWaitTime = waitTime; } } // Issue requests for (int i = 0; i < REQUEST_LATENCIES.length; i++) { final long requestLatency = REQUEST_LATENCIES[i]; final Task<Integer> callSvc = callService("subSearch[" + i + "]", _service, new SimpleMockRequest<Integer>(requestLatency, i), i); ctx.run(callSvc.andThen(addResponse(callSvc)).andThen(checkDone())); } return _result; }
@Test public void testWithTimeoutFailure() { Task<Integer> failure = getSuccessTask().andThen(delayedValue(0, 110, TimeUnit.MILLISECONDS)).withTimeout(100, TimeUnit.MILLISECONDS); try { runAndWait("AbstractTaskTest.testWithTimeoutFailure", failure); fail("should have failed!"); } catch (Exception ex) { assertEquals(ex.getCause().getClass(), Exceptions.TIMEOUT_EXCEPTION.getClass()); assertEquals(ex.getCause().getMessage(), "task: 'andThen: 0 delayed 110 ms' withTimeout 100ms"); } assertEquals(countTasks(failure.getTrace()), 5); }
@Override protected void doRunExample(final Engine engine) throws Exception { final MockService<String> httpClient = getService(); final Task<Integer> fetchAndLength = fetchUrl(httpClient, "http://www.google.com", 10000) .withTimeout(5000, TimeUnit.MILLISECONDS) .recover("default", t -> "") .map("length", s -> s.length()) .andThen("big bang", x -> System.exit(1)); engine.run(fetchAndLength); Thread.sleep(20); fetchAndLength.cancel(new Exception("because I said so")); fetchAndLength.await(); System.out.println(!fetchAndLength.isFailed() ? "Received result: " + fetchAndLength.get() : "Error: " + fetchAndLength.getError()); ExampleUtil.printTracingResults(fetchAndLength); } }
public void testAndThenConsumer(int expectedNumberOfTasks) { final AtomicReference<String> variable = new AtomicReference<String>(); Task<String> task = getSuccessTask().andThen(variable::set); runAndWait("AbstractTaskTest.testAndThenConsumer", task); assertEquals(task.get(), TASK_VALUE); assertEquals(variable.get(), TASK_VALUE); assertEquals(countTasks(task.getTrace()), expectedNumberOfTasks); }
@Test public void testLastTaskAlreadyResolvedShareable() { final AtomicInteger counter = new AtomicInteger(); final Task<String> bob = Task.value("bob", "bob"); runAndWait("TestTaskReuse.testLastTaskAlreadyResolvedShareable-bob", bob); Task<String> task = Task.callable("increaser", () -> { counter.incrementAndGet(); return "hello"; } ); Task<String> test1 = task.andThen(bob.shareable()); runAndWait("TestTaskReuse.testLastTaskAlreadyResolvedShareable", test1); assertEquals(counter.get(), 1); }
@Test public void testWithTimeoutTwiceFailure() { Task<Integer> failure = getSuccessTask().andThen(delayedValue(0, 2000, TimeUnit.MILLISECONDS)) .withTimeout(5000, TimeUnit.MILLISECONDS).withTimeout(100, TimeUnit.MILLISECONDS); try { runAndWait("AbstractTaskTest.testWithTimeoutTwiceFailure", failure); fail("should have failed!"); } catch (Exception ex) { assertEquals(ex.getCause().getClass(), Exceptions.TIMEOUT_EXCEPTION.getClass()); } assertEquals(countTasks(failure.getTrace()), 7); }
/** * In this case the "increaser" task is not being executed because * the "bob" task has already been resolved and test1 task is * resolved immediately. */ @Test public void testLastTaskAlreadyResolved() { final AtomicInteger counter = new AtomicInteger(); final Task<String> bob = Task.value("bob", "bob"); runAndWait("TestTaskReuse.testLastTaskResolved-bob", bob); Task<String> task = Task.callable("increaser", () -> { counter.incrementAndGet(); return "hello"; } ); Task<String> test1 = task.andThen(bob); runAndWait("TestTaskReuse.testLastTaskResolved", test1); assertEquals(counter.get(), 0); }
@Test public void testSingleTask() { Task<?> task = value("taskName", "value").andThen(value("value2")); runAndWait(task); Assert.assertTrue(_traceCaptureListener.isDone()); }
@Test public void testWithTimeoutSuccess() { Task<Integer> success = getSuccessTask().andThen(delayedValue(0, 30, TimeUnit.MILLISECONDS)).withTimeout(100, TimeUnit.MILLISECONDS); runAndWait("AbstractTaskTest.testWithTimeoutSuccess", success); assertEquals((int) success.get(), 0); assertEquals(countTasks(success.getTrace()), 5); }
public void testAndThenTask(int expectedNumberOfTasks) { Task<Integer> task = getSuccessTask().andThen(Task.callable("life", () -> 42)); runAndWait("AbstractTaskTest.testAndThenTask", task); assertEquals((int) task.get(), 42); assertEquals(countTasks(task.getTrace()), expectedNumberOfTasks); }
@Test public void testWithTimeoutTwiceSuccess() { Task<Integer> success = getSuccessTask().andThen(delayedValue(0, 30, TimeUnit.MILLISECONDS)) .withTimeout(100, TimeUnit.MILLISECONDS).withTimeout(5000, TimeUnit.MILLISECONDS); runAndWait("AbstractTaskTest.testWithTimeoutTwiceSuccess", success); assertEquals((int) success.get(), 0); assertEquals(countTasks(success.getTrace()), 7); }
@Test public void testWithSideEffectCancel() throws Exception { Task<String> cancelMain = delayedValue("value", 6000, TimeUnit.MILLISECONDS); Task<String> fastSideEffect = getSuccessTask(); Task<String> cancel = cancelMain.withSideEffect(s -> fastSideEffect); // test cancel, side effect task should not be run // add 10 ms delay so that we can reliably cancel it before it's run by the engine Task<String> mainTaks = delayedValue("value", 10, TimeUnit.MILLISECONDS).andThen(cancel); run(mainTaks); assertTrue(cancelMain.cancel(new Exception("canceled"))); cancel.await(); fastSideEffect.await(10, TimeUnit.MILLISECONDS); assertTrue(cancel.isDone()); assertFalse(fastSideEffect.isDone()); logTracingResults("AbstractTaskTest.testWithSideEffectCancel", mainTaks); }
@Override protected void executeBatchWithContext(final G group, final Batch<K, T> batch, final Context ctx) { Task<Map<K, Try<T>>> task = taskForBatch(group, batch.keys()); Task<Map<K, Try<T>>> completing = task.andThen("completePromises", map -> { batch.foreach((key, promise) -> { Try<T> result = map.get(key); if (result != null) { if (result.isFailed()) { promise.fail(result.getError()); } else { promise.done(result.get()); } } else { promise.fail(new Exception("Result for key: " + key + " not found in batch response")); } }); }); completing.getShallowTraceBuilder().setSystemHidden(true); Task<Map<K, Try<T>>> withFailureHandling = completing.onFailure("handleFailures", t -> { batch.failAll(t); }); withFailureHandling.getShallowTraceBuilder().setSystemHidden(true); ctx.run(withFailureHandling); }
@Test public void testSideEffectCancelled() throws InterruptedException { // this task will not complete. Task<String> settableTask = new BaseTask<String>() { @Override protected Promise<? extends String> run(Context context) throws Exception { return Promises.settable(); } }; Task<String> fastTask = new BaseTask<String>() { @Override protected Promise<? extends String> run(Context context) throws Exception { return Promises.value("fast"); } }; Task<String> withSideEffect = settableTask.withSideEffect(x -> fastTask); // add 10 ms delay so that we can cancel settableTask reliably getEngine().run(delayedValue("value", 10, TimeUnit.MILLISECONDS).andThen(withSideEffect)); assertTrue(settableTask.cancel(new Exception("task cancelled"))); withSideEffect.await(); fastTask.await(10, TimeUnit.MILLISECONDS); assertTrue(withSideEffect.isDone()); assertFalse(fastTask.isDone()); }
@Test public void testTraceWithPredecessorTrace() throws InterruptedException { final Task<String> predecessor = value("predecessor", "predecessorValue"); final Task<String> successor = value("successor", "successorValue"); final Task<?> seq = predecessor.andThen(successor); runAndWait("TestTaskToTrace.testTraceWithPredecessorTrace", seq); verifyShallowTrace(successor); verifyShallowTrace(predecessor); assertEquals(predecessor.getTrace(), successor.getTrace()); //expected relationship: PARENT_OF and SUCCESSOR_OF assertEquals(2, getRelationships(successor.getTrace(), successor.getId()).size()); assertTrue(successor.getTrace().getRelationships() .contains(new TraceRelationship(successor.getShallowTraceBuilder(), predecessor.getShallowTraceBuilder(), Relationship.SUCCESSOR_OF))); }
@Test public void testShutdownWithRunningAndSuccessorTask() throws InterruptedException { final CountDownLatch finishLatch = new CountDownLatch(1); final String predValue = "task executed"; final String sucValue = "task executed"; final Task<String> predTask = new BaseTask<String>() { @Override protected Promise<? extends String> run(final Context context) throws Exception { finishLatch.await(); return Promises.value(predValue); } }; final Task<String> sucTask = Task.value(sucValue); final Task<String> seq = predTask.andThen(sucTask); _engine.run(seq); _engine.shutdown(); // shutdown should not complete until after our task is done assertFalse(_engine.awaitTermination(50, TimeUnit.MILLISECONDS)); assertTrue(_engine.isShutdown()); assertFalse(_engine.isTerminated()); finishLatch.countDown(); assertTrue(_engine.awaitTermination(50, TimeUnit.MILLISECONDS)); assertTrue(_engine.isShutdown()); assertTrue(_engine.isTerminated()); // Tasks should finish shortly assertTrue(predTask.await(50, TimeUnit.MILLISECONDS)); assertEquals(predValue, predTask.get()); assertTrue(sucTask.await(50, TimeUnit.MILLISECONDS)); assertEquals(sucValue, sucTask.get()); }