diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/TaskContext.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/TaskContext.java index 408ed6597..b1e52d5c5 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/TaskContext.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/TaskContext.java @@ -41,6 +41,7 @@ public class TaskContext implements TaskContextData { private int iteration; private AuthorizationDescriptor authorization; private Optional tryRetryCount = Optional.empty(); + private boolean skipped; public TaskContext( WorkflowModel input, @@ -202,6 +203,19 @@ public void iteration(int iteration) { this.iteration = iteration; } + public boolean isSkipped() { + return skipped; + } + + public void skip() { + this.skipped = true; + this.output = rawInput; + } + + public boolean isCompletedOrSkipped() { + return isCompleted() || isSkipped(); + } + @Override public String toString() { StringBuilder sb = @@ -214,6 +228,8 @@ public String toString() { + taskName + ", completedAt=" + completedAt + + ", skipped=" + + skipped + ", retryAttempt=" + retryAttempt); tryRetryCount.ifPresent(s -> sb.append(", tryRetryCount=").append(s)); diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/AbstractTaskExecutor.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/AbstractTaskExecutor.java index 165f214d3..839a0b3d4 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/AbstractTaskExecutor.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/AbstractTaskExecutor.java @@ -280,7 +280,7 @@ public CompletableFuture apply( } return executeNext(completable, workflowContext); } else { - taskContext.transition(getSkipTransition()); + taskContext.transition(getSkipTransition()).skip(); return executeNext(completable, workflowContext); } } diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/ForkExecutor.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/ForkExecutor.java index 6124a5aad..4b48c3505 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/ForkExecutor.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/ForkExecutor.java @@ -21,7 +21,9 @@ import cloud.openworkflow.sdk.impl.WorkflowContext; import cloud.openworkflow.sdk.impl.WorkflowDefinition; import cloud.openworkflow.sdk.impl.WorkflowModel; +import cloud.openworkflow.sdk.impl.WorkflowModelFactory; import cloud.openworkflow.sdk.impl.WorkflowMutablePosition; +import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; @@ -36,8 +38,11 @@ public class ForkExecutor extends RegularTaskExecutor { private final ExecutorService service; private final Map> taskExecutors; - + private static final Comparator BY_COMPLETION = + Comparator.comparing( + TaskContext::completedAt, Comparator.nullsLast(Comparator.naturalOrder())); private final boolean compete; + private final WorkflowModelFactory modelFactory; public static class ForkExecutorBuilder extends RegularTaskExecutorBuilder { @@ -65,6 +70,7 @@ protected ForkExecutor(ForkExecutorBuilder builder) { service = builder.application.executorService(); this.taskExecutors = builder.taskExecutors; this.compete = builder.compete; + this.modelFactory = builder.application.modelFactory(); } @Override @@ -82,29 +88,27 @@ protected CompletableFuture internalExecute( futures.values().toArray(new CompletableFuture[futures.size()])) .thenApply(i -> combine( - workflow, + taskContext, futures.entrySet().stream() .collect(Collectors.toMap(Entry::getKey, e -> e.getValue().join())))); } - private WorkflowModel combine(WorkflowContext context, Map futures) { + private WorkflowModel combine(TaskContext taskContext, Map branches) { + Stream> finished = + branches.entrySet().stream() + .filter(e -> e.getValue().isCompletedOrSkipped()) + .sorted(Entry.comparingByValue(BY_COMPLETION)); + return compete ? winnerOutput(finished, taskContext) : allOutputs(finished); + } + + private static WorkflowModel winnerOutput( + Stream> finished, TaskContext taskContext) { + return finished.findFirst().map(e -> e.getValue().output()).orElseGet(taskContext::input); + } - Stream> sortedStream = - futures.entrySet().stream() - .sorted((arg1, arg2) -> - arg1.getValue().completedAt().compareTo(arg2.getValue().completedAt())); - return compete - ? sortedStream.map(e -> e.getValue().output()).findFirst().orElseThrow() - : context - .definition() - .application() - .modelFactory() - .combine( - sortedStream.collect( - Collectors.toMap( - Entry::getKey, - e -> e.getValue().output(), - (x, y) -> y, - LinkedHashMap::new))); + private WorkflowModel allOutputs(Stream> finished) { + Map outputs = new LinkedHashMap<>(); + finished.forEach(e -> outputs.put(e.getKey(), e.getValue().output())); + return modelFactory.combine(outputs); } } diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/SwitchExecutor.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/SwitchExecutor.java index 41925b280..bb83161c8 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/SwitchExecutor.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/SwitchExecutor.java @@ -34,8 +34,8 @@ public class SwitchExecutor extends AbstractTaskExecutor { - private final Map workflowFilters; - private final TransitionInfo defaultTask; + private Map workflowFilters; + private TransitionInfo defaultTask; public static class SwitchExecutorBuilder extends AbstractTaskExecutorBuilder { @@ -77,7 +77,12 @@ protected SwitchExecutor buildInstance() { } @Override - protected void buildTransition(SwitchExecutor ex) {} + protected void buildTransition(SwitchExecutor switchExecutor) { + switchExecutor.defaultTask = TransitionInfo.build(this.defaultTask); + switchExecutor.workflowFilters = + this.switchFilters.entrySet().stream() + .collect(Collectors.toMap(Entry::getKey, e -> TransitionInfo.build(e.getValue()))); + } } @Override @@ -87,10 +92,6 @@ protected TransitionInfo getSkipTransition() { private SwitchExecutor(SwitchExecutorBuilder builder) { super(builder); - this.defaultTask = TransitionInfo.build(builder.defaultTask); - this.workflowFilters = - builder.switchFilters.entrySet().stream() - .collect(Collectors.toMap(Entry::getKey, e -> TransitionInfo.build(e.getValue()))); } @Override diff --git a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/TaskExecutorHelper.java b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/TaskExecutorHelper.java index ab9659210..7accb302d 100644 --- a/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/TaskExecutorHelper.java +++ b/impl/core/src/main/java/cloud/openworkflow/sdk/impl/executors/TaskExecutorHelper.java @@ -81,7 +81,12 @@ public static TaskExecutor createExecutorList( public static Map> createBranchList( WorkflowMutablePosition position, List taskItems, WorkflowDefinition definition) { - return createExecutorBuilderList(position, taskItems, definition, "branch").entrySet().stream() + Map> executors = + createExecutorBuilderList(position, taskItems, definition, "branch"); + + executors.forEach((name, builder) -> builder.connect(Map.of(name, builder))); + + return executors.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().build())); } diff --git a/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/WorkflowDefinitionTest.java b/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/WorkflowDefinitionTest.java index 20857e1b2..01e6f9878 100644 --- a/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/WorkflowDefinitionTest.java +++ b/impl/test/src/test/java/cloud/openworkflow/sdk/impl/test/WorkflowDefinitionTest.java @@ -20,11 +20,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowableOfType; +import cloud.openworkflow.sdk.impl.ExecutorServiceFactory; import cloud.openworkflow.sdk.impl.WorkflowApplication; import cloud.openworkflow.sdk.impl.WorkflowDefinition; import cloud.openworkflow.sdk.impl.WorkflowException; import cloud.openworkflow.sdk.impl.WorkflowInstance; import cloud.openworkflow.sdk.impl.WorkflowModel; +import cloud.openworkflow.sdk.impl.WorkflowStatus; import cloud.openworkflow.sdk.impl.jackson.JsonUtils; import java.io.IOException; import java.time.Instant; @@ -32,9 +34,12 @@ import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.function.Consumer; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -59,6 +64,46 @@ void testWorkflowExecution(String fileName, Consumer asserti assertions.accept(appl.workflowDefinition(readWorkflowFromClasspath(fileName, validation()))); } + @Test + void testForkBranchThenEnd() throws Exception { + ExecutorService singleThread = Executors.newSingleThreadExecutor(); + ExecutorServiceFactory executorFactory = + new ExecutorServiceFactory() { + @Override + public ExecutorService get() { + return singleThread; + } + + @Override + public void close() { + singleThread.shutdown(); + } + }; + try (WorkflowApplication application = + WorkflowApplication.builder().withExecutorFactory(executorFactory).build()) { + WorkflowInstance instance = + application + .workflowDefinition( + readWorkflowFromClasspath( + "workflows-samples/fork-branch-then-end.yaml", validation())) + .instance(Map.of()); + JsonNode out = + instance + .start() + .join() + .as(JsonNode.class) + .orElseThrow( + () -> new IllegalArgumentException("Model cannot be converted to json node")); + assertThat(instance.status()).isEqualTo(WorkflowStatus.COMPLETED); + assertThat(out).isInstanceOf(ArrayNode.class); + assertThat(out).hasSize(1); + assertThat(out.get(0)) + .isIn( + createObjectNode("callNurse", "patientId", "John", "room", 1), + createObjectNode("callDoctor", "patientId", "Smith", "room", 2)); + } + } + private static Stream provideParameters() { return Stream.of( args( @@ -120,7 +165,27 @@ private static Stream provideParameters() { argsJson( "workflows-samples/fork-no-compete.yaml", Map.of(), - WorkflowDefinitionTest::checkNotCompeteOuput)); + WorkflowDefinitionTest::checkNotCompeteOuput), + argsJson( + "workflows-samples/fork-try-branch.yaml", + Map.of(), + WorkflowDefinitionTest::checkForkTryBranchOutput), + argsJson( + "workflows-samples/fork-switch-self-branch.yaml", + Map.of("patientId", "John", "room", 1), + WorkflowDefinitionTest::checkForkSwitchSelfBranchOutput), + argsJson( + "workflows-samples/fork-single-skipped-branch-with-compete-true.yaml", + Map.of("isCallNurseEnabled", false), + WorkflowDefinitionTest::checkForkSingleSkippedBranchWithCompeteTrue), + argsJson( + "workflows-samples/fork-single-skipped-branch-with-compete-false.yaml", + Map.of("isCallNurseEnabled", false), + WorkflowDefinitionTest::checkForkSingleSkippedBranchWithCompeteFalse), + argsJson( + "workflows-samples/fork-one-skipped-branch-with-compete-false.yaml", + Map.of("isCallNurseEnabled", false), + WorkflowDefinitionTest::checkForOneSkippedBranchWithCompeteFalse)); } private static Arguments args( @@ -197,6 +262,80 @@ private static void checkNotCompeteOuput(WorkflowModel model) { createObjectNode("callDoctor", "patientId", "Smith", "room", 2)); } + private static void checkForkTryBranchOutput(WorkflowModel model) { + JsonNode out = + model + .as(JsonNode.class) + .orElseThrow( + () -> new IllegalArgumentException("Model cannot be converted to json node")); + assertThat(out).isInstanceOf(ArrayNode.class); + assertThat(out).hasSize(2); + ArrayNode array = (ArrayNode) out; + assertThat(array) + .containsExactlyInAnyOrder( + createObjectNode("tryNurse", "patientId", "Lucy", "room", 1), + createObjectNode("callDoctor", "patientId", "Smith", "room", 2)); + } + + private static void checkForkSwitchSelfBranchOutput(WorkflowModel model) { + JsonNode out = + model + .as(JsonNode.class) + .orElseThrow( + () -> new IllegalArgumentException("Model cannot be converted to json node")); + assertThat(out).isInstanceOf(ArrayNode.class); + assertThat(out).hasSize(2); + ArrayNode array = (ArrayNode) out; + assertThat(array) + .containsExactlyInAnyOrder( + createObjectNode("checkNurse", "patientId", "John", "room", 1), + createObjectNode("callDoctor", "patientId", "Smith", "room", 2)); + } + + private static void checkForOneSkippedBranchWithCompeteFalse(WorkflowModel model) { + JsonNode out = + model + .as(JsonNode.class) + .orElseThrow( + () -> new IllegalArgumentException("Model cannot be converted to json node")); + // A skipped branch is part of the result, with its raw input as output. + assertThat(out).isInstanceOf(ArrayNode.class); + assertThat(out).hasSize(2); + ArrayNode array = (ArrayNode) out; + assertThat(array) + .containsExactlyInAnyOrder( + skippedCallNurseNode(), createObjectNode("callDoctor", "patientId", "Lucy", "room", 2)); + } + + private static void checkForkSingleSkippedBranchWithCompeteTrue(WorkflowModel model) { + JsonNode out = + model + .as(JsonNode.class) + .orElseThrow( + () -> new IllegalArgumentException("Model cannot be converted to json node")); + // The skipped branch wins, and its output is its raw input. + assertThat(out) + .isEqualTo(JsonUtils.mapper().createObjectNode().put("isCallNurseEnabled", false)); + } + + private static void checkForkSingleSkippedBranchWithCompeteFalse(WorkflowModel model) { + JsonNode out = + model + .as(JsonNode.class) + .orElseThrow( + () -> new IllegalArgumentException("Model cannot be converted to json node")); + // Without compete the result is always an array, even with a single skipped branch. + assertThat(out).isInstanceOf(ArrayNode.class); + assertThat(out).hasSize(1); + assertThat(out).containsExactly(skippedCallNurseNode()); + } + + private static JsonNode skippedCallNurseNode() { + return JsonUtils.mapper() + .createObjectNode() + .set("callNurse", JsonUtils.mapper().createObjectNode().put("isCallNurseEnabled", false)); + } + private static JsonNode createObjectNode( String parent, String key1, String value1, String key2, int value2) { return JsonUtils.mapper() diff --git a/impl/test/src/test/resources/workflows-samples/fork-branch-then-end.yaml b/impl/test/src/test/resources/workflows-samples/fork-branch-then-end.yaml new file mode 100644 index 000000000..5a15672f9 --- /dev/null +++ b/impl/test/src/test/resources/workflows-samples/fork-branch-then-end.yaml @@ -0,0 +1,21 @@ +# yaml-language-server: $schema=../../../../../../types/src/main/resources/schema/workflow.yaml +document: + dsl: '1.0.0-alpha5' + namespace: test + name: fork-branch-then-end + version: '0.1.0' +do: + - callSomeone: + fork: + compete: false + branches: + - callNurse: + set: + patientId: John + room: 1 + then: end + - callDoctor: + set: + patientId: Smith + room: 2 + then: end diff --git a/impl/test/src/test/resources/workflows-samples/fork-one-skipped-branch-with-compete-false.yaml b/impl/test/src/test/resources/workflows-samples/fork-one-skipped-branch-with-compete-false.yaml new file mode 100644 index 000000000..df69d7002 --- /dev/null +++ b/impl/test/src/test/resources/workflows-samples/fork-one-skipped-branch-with-compete-false.yaml @@ -0,0 +1,20 @@ +# yaml-language-server: $schema=../../../../../../types/src/main/resources/schema/workflow.yaml +document: + dsl: '1.0.0-alpha5' + namespace: test + name: fork-one-skipped-branch-with-compete-false + version: '0.1.0' +do: + - forkOneSkippedBranch: + fork: + compete: false + branches: + - callNurse: + if: ${ .isCallNurseEnabled } + set: + patientId: John + room: 1 + - callDoctor: + set: + patientId: Lucy + room: 2 \ No newline at end of file diff --git a/impl/test/src/test/resources/workflows-samples/fork-single-skipped-branch-with-compete-false.yaml b/impl/test/src/test/resources/workflows-samples/fork-single-skipped-branch-with-compete-false.yaml new file mode 100644 index 000000000..62fabdb62 --- /dev/null +++ b/impl/test/src/test/resources/workflows-samples/fork-single-skipped-branch-with-compete-false.yaml @@ -0,0 +1,16 @@ +# yaml-language-server: $schema=../../../../../../types/src/main/resources/schema/workflow.yaml +document: + dsl: '1.0.0-alpha5' + namespace: test + name: fork-single-skipped-branch-with-compete-false + version: '0.1.0' +do: + - forkSingleBranch: + fork: + compete: false + branches: + - callNurse: + if: ${ .isCallNurseEnabled } + set: + patientId: John + room: 1 \ No newline at end of file diff --git a/impl/test/src/test/resources/workflows-samples/fork-single-skipped-branch-with-compete-true.yaml b/impl/test/src/test/resources/workflows-samples/fork-single-skipped-branch-with-compete-true.yaml new file mode 100644 index 000000000..fc2b843bd --- /dev/null +++ b/impl/test/src/test/resources/workflows-samples/fork-single-skipped-branch-with-compete-true.yaml @@ -0,0 +1,16 @@ +# yaml-language-server: $schema=../../../../../../types/src/main/resources/schema/workflow.yaml +document: + dsl: '1.0.0-alpha5' + namespace: test + name: fork-single-skipped-branch-with-compete-true + version: '0.1.0' +do: + - forkSingleBranch: + fork: + compete: true + branches: + - callNurse: + if: ${ .isCallNurseEnabled } + set: + patientId: John + room: 1 \ No newline at end of file diff --git a/impl/test/src/test/resources/workflows-samples/fork-switch-self-branch.yaml b/impl/test/src/test/resources/workflows-samples/fork-switch-self-branch.yaml new file mode 100644 index 000000000..92ffc2088 --- /dev/null +++ b/impl/test/src/test/resources/workflows-samples/fork-switch-self-branch.yaml @@ -0,0 +1,22 @@ +# yaml-language-server: $schema=../../../../../../types/src/main/resources/schema/workflow.yaml +document: + dsl: '1.0.0-alpha5' + namespace: test + name: fork-switch-self-branch + version: '0.1.0' +do: + - callSomeone: + fork: + compete: false + branches: + - checkNurse: + switch: + - neverTrue: + when: ${ false } + then: checkNurse + - default: + then: end + - callDoctor: + set: + patientId: Smith + room: 2 diff --git a/impl/test/src/test/resources/workflows-samples/fork-try-branch.yaml b/impl/test/src/test/resources/workflows-samples/fork-try-branch.yaml new file mode 100644 index 000000000..43cc5fed7 --- /dev/null +++ b/impl/test/src/test/resources/workflows-samples/fork-try-branch.yaml @@ -0,0 +1,35 @@ +# yaml-language-server: $schema=../../../../../../types/src/main/resources/schema/workflow.yaml +document: + dsl: '1.0.0-alpha5' + namespace: test + name: fork-try-branch + version: '0.1.0' +do: + - callSomeone: + fork: + compete: false + branches: + - tryNurse: + try: + - callNurse: + set: + patientId: John + room: 1 + - throwError: + raise: + error: + type: https://serverlessworkflow.io/spec/1.0.0/errors/runtime + status: 500 + catch: + errors: + with: + type: https://serverlessworkflow.io/spec/1.0.0/errors/runtime + do: + - catchDo: + set: + patientId: Lucy + room: 1 + - callDoctor: + set: + patientId: Smith + room: 2