Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public class TaskContext implements TaskContextData {
private int iteration;
private AuthorizationDescriptor authorization;
private Optional<Integer> tryRetryCount = Optional.empty();
private boolean skipped;

public TaskContext(
WorkflowModel input,
Expand Down Expand Up @@ -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 =
Expand All @@ -214,6 +228,8 @@ public String toString() {
+ taskName
+ ", completedAt="
+ completedAt
+ ", skipped="
+ skipped
+ ", retryAttempt="
+ retryAttempt);
tryRetryCount.ifPresent(s -> sb.append(", tryRetryCount=").append(s));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ public CompletableFuture<TaskContext> apply(
}
return executeNext(completable, workflowContext);
} else {
taskContext.transition(getSkipTransition());
taskContext.transition(getSkipTransition()).skip();
return executeNext(completable, workflowContext);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -36,8 +38,11 @@ public class ForkExecutor extends RegularTaskExecutor<ForkTask> {

private final ExecutorService service;
private final Map<String, TaskExecutor<?>> taskExecutors;

private static final Comparator<TaskContext> BY_COMPLETION =
Comparator.comparing(
TaskContext::completedAt, Comparator.nullsLast(Comparator.naturalOrder()));
private final boolean compete;
private final WorkflowModelFactory modelFactory;

public static class ForkExecutorBuilder
extends RegularTaskExecutorBuilder<ForkTask, ForkExecutor> {
Expand Down Expand Up @@ -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
Expand All @@ -82,29 +88,27 @@ protected CompletableFuture<WorkflowModel> 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<String, TaskContext> futures) {
private WorkflowModel combine(TaskContext taskContext, Map<String, TaskContext> branches) {
Stream<Entry<String, TaskContext>> 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<Entry<String, TaskContext>> finished, TaskContext taskContext) {
return finished.findFirst().map(e -> e.getValue().output()).orElseGet(taskContext::input);
}

Stream<Entry<String, TaskContext>> 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<Entry<String, TaskContext>> finished) {
Map<String, WorkflowModel> outputs = new LinkedHashMap<>();
finished.forEach(e -> outputs.put(e.getKey(), e.getValue().output()));
return modelFactory.combine(outputs);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@

public class SwitchExecutor extends AbstractTaskExecutor<SwitchTask> {

private final Map<WorkflowPredicate, TransitionInfo> workflowFilters;
private final TransitionInfo defaultTask;
private Map<WorkflowPredicate, TransitionInfo> workflowFilters;
private TransitionInfo defaultTask;

public static class SwitchExecutorBuilder
extends AbstractTaskExecutorBuilder<SwitchTask, SwitchExecutor> {
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,12 @@ public static TaskExecutor<?> createExecutorList(

public static Map<String, TaskExecutor<?>> createBranchList(
WorkflowMutablePosition position, List<TaskItem> taskItems, WorkflowDefinition definition) {
return createExecutorBuilderList(position, taskItems, definition, "branch").entrySet().stream()
Map<String, TaskExecutorBuilder<?>> executors =
createExecutorBuilderList(position, taskItems, definition, "branch");

executors.forEach((name, builder) -> builder.connect(Map.of(name, builder)));
Comment thread
mathecruz marked this conversation as resolved.
Resolved
Comment thread
mathecruz marked this conversation as resolved.
Resolved

return executors.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().build()));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,26 @@
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;
import java.util.Arrays;
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;
Expand All @@ -59,6 +64,46 @@ void testWorkflowExecution(String fileName, Consumer<WorkflowDefinition> 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<Arguments> provideParameters() {
return Stream.of(
args(
Expand Down Expand Up @@ -120,7 +165,27 @@ private static Stream<Arguments> 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(
Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading