From 9738afb90b2268e566f84e04e0e60429def56758 Mon Sep 17 00:00:00 2001 From: Viren Baraiya Date: Thu, 12 Nov 2026 09:49:17 -0800 Subject: [PATCH 01/28] native workflows in code --- .../ConductorClientAutoConfiguration.java | 12 + .../ConductorWorkflowAutoConfiguration.java | 46 + .../client/spring/ConductorWorkflowHost.java | 147 + ...ot.autoconfigure.AutoConfiguration.imports | 3 +- .../ConductorClientAutoConfigurationTest.java | 24 + ...onductorWorkflowAutoConfigurationTest.java | 125 + .../spring/sample/AutowiredTasksWorkflow.java | 28 + .../client/spring/sample/NotAWorkflow.java | 20 + .../spring/sample/SampleApplication.java | 23 + .../client/spring/sample/SampleTasks.java | 26 + .../client/spring/sample/SampleWorkflow.java | 41 + .../ConductorClientAutoConfiguration.java | 12 + .../ConductorWorkflowAutoConfiguration.java | 46 + .../client/spring/ConductorWorkflowHost.java | 147 + ...ot.autoconfigure.AutoConfiguration.imports | 3 +- .../ConductorClientAutoConfigurationTest.java | 25 + ...onductorWorkflowAutoConfigurationTest.java | 125 + .../spring/sample/AutowiredTasksWorkflow.java | 28 + .../client/spring/sample/NotAWorkflow.java | 20 + .../spring/sample/SampleApplication.java | 23 + .../client/spring/sample/SampleTasks.java | 26 + .../client/spring/sample/SampleWorkflow.java | 41 + conductor-client/build.gradle | 51 +- .../client/http/ConductorClient.java | 9 + .../conductor/common/metadata/tasks/Task.java | 16 + .../metadata/tasks/TaskContinuation.java | 230 + .../conductor/common/run/NativeState.java | 132 + .../conductor/common/run/Workflow.java | 27 + .../executor/task/AnnotatedWorker.java | 21 +- .../sdk/workflow/task/WorkerTask.java | 9 + .../conductoross/conductor/sdk/AgentCall.java | 94 + .../conductoross/conductor/sdk/Backoff.java | 69 + .../conductoross/conductor/sdk/Conductor.java | 679 + .../conductoross/conductor/sdk/EventCall.java | 40 + .../conductor/sdk/ExternalWait.java | 45 + .../conductoross/conductor/sdk/Functions.java | 82 + .../org/conductoross/conductor/sdk/Http.java | 67 + .../conductoross/conductor/sdk/HttpCall.java | 100 + .../conductoross/conductor/sdk/HumanCall.java | 66 + .../conductoross/conductor/sdk/LlmCall.java | 63 + .../conductoross/conductor/sdk/McpCall.java | 113 + .../sdk/NonDeterminismException.java | 25 + .../conductoross/conductor/sdk/Promise.java | 22 + .../org/conductoross/conductor/sdk/Query.java | 27 + .../conductor/sdk/Registration.java | 240 + .../conductoross/conductor/sdk/Schedule.java | 53 + .../conductoross/conductor/sdk/Schedules.java | 25 + .../conductoross/conductor/sdk/Signal.java | 27 + .../conductoross/conductor/sdk/TaskCall.java | 60 + .../conductor/sdk/TaskFailure.java | 44 + .../conductoross/conductor/sdk/Update.java | 27 + .../conductoross/conductor/sdk/Variable.java | 31 + .../conductoross/conductor/sdk/Workers.java | 587 + .../conductoross/conductor/sdk/Workflow.java | 52 + .../sdk/WorkflowFailedException.java | 24 + .../conductor/sdk/WorkflowHandle.java | 263 + .../conductor/sdk/internal/ActionCase.java | 24 + .../conductor/sdk/internal/CodeLoops.java | 132 + .../conductor/sdk/internal/CodeReader.java | 1361 + .../conductor/sdk/internal/Command.java | 87 + .../conductor/sdk/internal/Conductors.java | 26 + .../conductor/sdk/internal/Engine.java | 83 + .../conductor/sdk/internal/Entries.java | 135 + .../conductor/sdk/internal/Execution.java | 234 + .../conductor/sdk/internal/Json.java | 145 + .../conductor/sdk/internal/MethodRefs.java | 138 + .../conductor/sdk/internal/Replayer.java | 1711 ++ .../conductor/sdk/internal/TaskStubs.java | 216 + .../conductor/sdk/internal/WorkflowSpec.java | 229 + .../conductor/sdk/testing/DirectEngine.java | 433 + .../conductor/sdk/testing/DurableReplay.java | 64 + .../sdk/testing/DurableTestEnvironment.java | 255 + .../conductor/sdk/testing/TestRun.java | 131 + .../executor/task/AnnotatedWorkerTests.java | 25 + .../test/java/loopfixture/CodeLoopsTest.java | 149 + .../sdk/ConductorClientOwnershipTest.java | 57 + .../conductor/sdk/ServerOutageTest.java | 96 + .../conductor/sdk/WorkerProtocolTest.java | 105 + .../sdk/WorkflowHandleQueryTest.java | 110 + .../sdk/internal/CodeReaderTest.java | 279 + .../conductor/sdk/internal/DiscoveryTest.java | 176 + .../conductor/sdk/internal/SwitchOnTest.java | 477 + .../conductor/sdk/internal/TaskStubsTest.java | 248 + .../java/plainbranches/PlainBranchesTest.java | 696 + .../test/java/stubsite/StubCallSiteTest.java | 84 + design/native-workflows/README.md | 556 + design/native-workflows/server-changes.md | 165 + native-examples-spring/README.md | 27 + native-examples-spring/build.gradle | 27 + .../src/main/java/orders/Catalog.java | 32 + .../src/main/java/orders/OrderController.java | 64 + .../src/main/java/orders/OrderTasks.java | 57 + .../src/main/java/orders/OrderWorkflow.java | 53 + .../src/main/java/orders/Orders.java | 27 + .../main/java/orders/OrdersApplication.java | 30 + .../src/main/resources/application.properties | 2 + native-examples/DURABILITY-BENCH.md | 324 + native-examples/bench.sh | 25 + native-examples/build.gradle | 33 + native-examples/chaos.sh | 51 + native-examples/independent/check.sh | 22 + native-examples/independent/elle/build.gradle | 29 + .../MutableAcc-Object-Object-Object.class | Bin 0 -> 219 bytes .../core/MutableAcc-Object-Object.class | Bin 0 -> 199 bytes .../independent/elle/settings.gradle | 1 + .../durability/independent/ElleCheck.java | 123 + native-examples/independent/porcupine/go.mod | 5 + native-examples/independent/porcupine/go.sum | 2 + native-examples/independent/porcupine/main.go | 176 + native-examples/kitchensink-chaos.sh | 16 + .../mutants/sdk/drop-some-signals.patch | 13 + .../mutants/sdk/no-message-dedupe.patch | 12 + .../mutants/sdk/no-reply-prune.patch | 13 + .../mutants/server/destructive-pull.patch | 29 + .../mutants/server/ignore-epoch.patch | 12 + .../mutants/server/join-ignores-lanes.patch | 13 + .../mutants/server/no-claim-fence.patch | 12 + .../server/no-completion-deferral.patch | 13 + .../mutants/server/no-stale-write-guard.patch | 13 + .../mutants/server/no-variable-fencing.patch | 22 + .../server/terminate-on-storage-errors.patch | 13 + .../mutants/server/workflow-saved-last.patch | 15 + .../main/java/conformance/Conformance.java | 673 + .../src/main/java/durability/Balancer.java | 37 + .../src/main/java/durability/Bench.java | 561 + .../src/main/java/durability/BenchWorker.java | 38 + .../src/main/java/durability/Checker.java | 774 + .../src/main/java/durability/History.java | 112 + .../java/durability/KitchenSinkChaos.java | 179 + .../src/main/java/durability/Ledger.java | 107 + .../src/main/java/durability/LedgerChild.java | 32 + .../src/main/java/durability/LedgerModel.java | 46 + .../src/main/java/durability/LedgerTasks.java | 56 + .../main/java/durability/LedgerWorkflow.java | 126 + .../src/main/java/durability/Nemesis.java | 238 + .../src/main/java/durability/Processes.java | 413 + .../src/main/java/durability/Proxy.java | 160 + .../src/main/java/durability/UpdateFlood.java | 147 + .../src/main/java/failures/Failures.java | 136 + .../src/main/java/hello/Hello.java | 67 + native-examples/src/main/java/hold/Held.java | 116 + .../src/main/java/kitchensink/ChaosTasks.java | 97 + .../java/kitchensink/KitchenSinkModel.java | 76 + .../java/kitchensink/KitchenSinkTasks.java | 137 + .../java/kitchensink/KitchenSinkWorkflow.java | 469 + .../src/main/java/kitchensink/Main.java | 267 + .../src/main/java/kitchensink/SubFlow.java | 39 + .../src/main/java/kitchensink/Worker.java | 40 + .../main/java/operator/ForkedWorkflow.java | 37 + .../java/operator/LaneFailureWorkflow.java | 38 + .../main/java/operator/LoopedWorkflow.java | 45 + .../main/java/operator/OperatorChecks.java | 395 + .../src/main/java/operator/PingWorkflow.java | 36 + .../src/main/java/operator/RouteWorkflow.java | 41 + .../operator/ShipmentFailureWorkflow.java | 38 + .../src/main/java/operator/ShipmentTasks.java | 145 + .../main/java/operator/ShipmentWorkflow.java | 51 + .../java/operator/SwitchLaneWorkflow.java | 40 + .../src/main/java/reuse/ExistingWorkers.java | 72 + .../src/main/java/reuse/Reuse.java | 64 + .../src/main/java/switches/Switches.java | 115 + .../main/resources/simplelogger.properties | 2 + .../src/test/java/durability/CheckerTest.java | 289 + .../java/durability/LedgerWorkflowTest.java | 56 + .../kitchensink/FailureSemanticsTest.java | 132 + .../java/kitchensink/KitchenSinkTest.java | 159 + .../resources/executions/kitchensink-odd.json | 23378 ++++++++++++++++ native-examples/stubs/ai_stub.py | 89 + settings.gradle | 2 + 169 files changed, 44706 insertions(+), 5 deletions(-) create mode 100644 conductor-client-spring-boot4/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfiguration.java create mode 100644 conductor-client-spring-boot4/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowHost.java create mode 100644 conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfigurationTest.java create mode 100644 conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/AutowiredTasksWorkflow.java create mode 100644 conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/NotAWorkflow.java create mode 100644 conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/SampleApplication.java create mode 100644 conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/SampleTasks.java create mode 100644 conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/SampleWorkflow.java create mode 100644 conductor-client-spring/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfiguration.java create mode 100644 conductor-client-spring/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowHost.java create mode 100644 conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfigurationTest.java create mode 100644 conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/AutowiredTasksWorkflow.java create mode 100644 conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/NotAWorkflow.java create mode 100644 conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/SampleApplication.java create mode 100644 conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/SampleTasks.java create mode 100644 conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/SampleWorkflow.java create mode 100644 conductor-client/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskContinuation.java create mode 100644 conductor-client/src/main/java/com/netflix/conductor/common/run/NativeState.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/AgentCall.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/Backoff.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/Conductor.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/EventCall.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/ExternalWait.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/Functions.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/Http.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/HttpCall.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/HumanCall.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/LlmCall.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/McpCall.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/NonDeterminismException.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/Promise.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/Query.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/Registration.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/Schedule.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/Schedules.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/Signal.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/TaskCall.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/TaskFailure.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/Update.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/Variable.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/Workers.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/Workflow.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/WorkflowFailedException.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/WorkflowHandle.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/ActionCase.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/CodeLoops.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/CodeReader.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Command.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Conductors.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Engine.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Entries.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Execution.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Json.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/MethodRefs.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Replayer.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/TaskStubs.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/WorkflowSpec.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/DirectEngine.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/DurableReplay.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/DurableTestEnvironment.java create mode 100644 conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/TestRun.java create mode 100644 conductor-client/src/test/java/loopfixture/CodeLoopsTest.java create mode 100644 conductor-client/src/test/java/org/conductoross/conductor/sdk/ConductorClientOwnershipTest.java create mode 100644 conductor-client/src/test/java/org/conductoross/conductor/sdk/ServerOutageTest.java create mode 100644 conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkerProtocolTest.java create mode 100644 conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkflowHandleQueryTest.java create mode 100644 conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/CodeReaderTest.java create mode 100644 conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/DiscoveryTest.java create mode 100644 conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/SwitchOnTest.java create mode 100644 conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/TaskStubsTest.java create mode 100644 conductor-client/src/test/java/plainbranches/PlainBranchesTest.java create mode 100644 conductor-client/src/test/java/stubsite/StubCallSiteTest.java create mode 100644 design/native-workflows/README.md create mode 100644 design/native-workflows/server-changes.md create mode 100644 native-examples-spring/README.md create mode 100644 native-examples-spring/build.gradle create mode 100644 native-examples-spring/src/main/java/orders/Catalog.java create mode 100644 native-examples-spring/src/main/java/orders/OrderController.java create mode 100644 native-examples-spring/src/main/java/orders/OrderTasks.java create mode 100644 native-examples-spring/src/main/java/orders/OrderWorkflow.java create mode 100644 native-examples-spring/src/main/java/orders/Orders.java create mode 100644 native-examples-spring/src/main/java/orders/OrdersApplication.java create mode 100644 native-examples-spring/src/main/resources/application.properties create mode 100644 native-examples/DURABILITY-BENCH.md create mode 100755 native-examples/bench.sh create mode 100644 native-examples/build.gradle create mode 100755 native-examples/chaos.sh create mode 100755 native-examples/independent/check.sh create mode 100644 native-examples/independent/elle/build.gradle create mode 100644 native-examples/independent/elle/dom_top/core/MutableAcc-Object-Object-Object.class create mode 100644 native-examples/independent/elle/dom_top/core/MutableAcc-Object-Object.class create mode 100644 native-examples/independent/elle/settings.gradle create mode 100644 native-examples/independent/elle/src/main/java/durability/independent/ElleCheck.java create mode 100644 native-examples/independent/porcupine/go.mod create mode 100644 native-examples/independent/porcupine/go.sum create mode 100644 native-examples/independent/porcupine/main.go create mode 100755 native-examples/kitchensink-chaos.sh create mode 100644 native-examples/mutants/sdk/drop-some-signals.patch create mode 100644 native-examples/mutants/sdk/no-message-dedupe.patch create mode 100644 native-examples/mutants/sdk/no-reply-prune.patch create mode 100644 native-examples/mutants/server/destructive-pull.patch create mode 100644 native-examples/mutants/server/ignore-epoch.patch create mode 100644 native-examples/mutants/server/join-ignores-lanes.patch create mode 100644 native-examples/mutants/server/no-claim-fence.patch create mode 100644 native-examples/mutants/server/no-completion-deferral.patch create mode 100644 native-examples/mutants/server/no-stale-write-guard.patch create mode 100644 native-examples/mutants/server/no-variable-fencing.patch create mode 100644 native-examples/mutants/server/terminate-on-storage-errors.patch create mode 100644 native-examples/mutants/server/workflow-saved-last.patch create mode 100644 native-examples/src/main/java/conformance/Conformance.java create mode 100644 native-examples/src/main/java/durability/Balancer.java create mode 100644 native-examples/src/main/java/durability/Bench.java create mode 100644 native-examples/src/main/java/durability/BenchWorker.java create mode 100644 native-examples/src/main/java/durability/Checker.java create mode 100644 native-examples/src/main/java/durability/History.java create mode 100644 native-examples/src/main/java/durability/KitchenSinkChaos.java create mode 100644 native-examples/src/main/java/durability/Ledger.java create mode 100644 native-examples/src/main/java/durability/LedgerChild.java create mode 100644 native-examples/src/main/java/durability/LedgerModel.java create mode 100644 native-examples/src/main/java/durability/LedgerTasks.java create mode 100644 native-examples/src/main/java/durability/LedgerWorkflow.java create mode 100644 native-examples/src/main/java/durability/Nemesis.java create mode 100644 native-examples/src/main/java/durability/Processes.java create mode 100644 native-examples/src/main/java/durability/Proxy.java create mode 100644 native-examples/src/main/java/durability/UpdateFlood.java create mode 100644 native-examples/src/main/java/failures/Failures.java create mode 100644 native-examples/src/main/java/hello/Hello.java create mode 100644 native-examples/src/main/java/hold/Held.java create mode 100644 native-examples/src/main/java/kitchensink/ChaosTasks.java create mode 100644 native-examples/src/main/java/kitchensink/KitchenSinkModel.java create mode 100644 native-examples/src/main/java/kitchensink/KitchenSinkTasks.java create mode 100644 native-examples/src/main/java/kitchensink/KitchenSinkWorkflow.java create mode 100644 native-examples/src/main/java/kitchensink/Main.java create mode 100644 native-examples/src/main/java/kitchensink/SubFlow.java create mode 100644 native-examples/src/main/java/kitchensink/Worker.java create mode 100644 native-examples/src/main/java/operator/ForkedWorkflow.java create mode 100644 native-examples/src/main/java/operator/LaneFailureWorkflow.java create mode 100644 native-examples/src/main/java/operator/LoopedWorkflow.java create mode 100644 native-examples/src/main/java/operator/OperatorChecks.java create mode 100644 native-examples/src/main/java/operator/PingWorkflow.java create mode 100644 native-examples/src/main/java/operator/RouteWorkflow.java create mode 100644 native-examples/src/main/java/operator/ShipmentFailureWorkflow.java create mode 100644 native-examples/src/main/java/operator/ShipmentTasks.java create mode 100644 native-examples/src/main/java/operator/ShipmentWorkflow.java create mode 100644 native-examples/src/main/java/operator/SwitchLaneWorkflow.java create mode 100644 native-examples/src/main/java/reuse/ExistingWorkers.java create mode 100644 native-examples/src/main/java/reuse/Reuse.java create mode 100644 native-examples/src/main/java/switches/Switches.java create mode 100644 native-examples/src/main/resources/simplelogger.properties create mode 100644 native-examples/src/test/java/durability/CheckerTest.java create mode 100644 native-examples/src/test/java/durability/LedgerWorkflowTest.java create mode 100644 native-examples/src/test/java/kitchensink/FailureSemanticsTest.java create mode 100644 native-examples/src/test/java/kitchensink/KitchenSinkTest.java create mode 100644 native-examples/src/test/resources/executions/kitchensink-odd.json create mode 100644 native-examples/stubs/ai_stub.py diff --git a/conductor-client-spring-boot4/src/main/java/com/netflix/conductor/client/spring/ConductorClientAutoConfiguration.java b/conductor-client-spring-boot4/src/main/java/com/netflix/conductor/client/spring/ConductorClientAutoConfiguration.java index 0baf28177..a1ddbe794 100644 --- a/conductor-client-spring-boot4/src/main/java/com/netflix/conductor/client/spring/ConductorClientAutoConfiguration.java +++ b/conductor-client-spring-boot4/src/main/java/com/netflix/conductor/client/spring/ConductorClientAutoConfiguration.java @@ -18,6 +18,7 @@ import java.util.Optional; import org.apache.commons.lang3.StringUtils; +import org.conductoross.conductor.sdk.Conductor; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; @@ -61,6 +62,17 @@ public ConductorClient conductorClient(ClientProperties properties) { return builder.build(); } + /** + * Native workflows over the configured client (an Orkes {@code ApiClient} with keys when one is + * configured). Closing it stops the workers it started; the client bean is left to Spring. + */ + @Bean(destroyMethod = "close") + @ConditionalOnBean(ConductorClient.class) + @ConditionalOnMissingBean + public Conductor conductor(ConductorClient client) { + return Conductor.of(client); + } + @Bean @ConditionalOnBean(ConductorClient.class) @ConditionalOnMissingBean diff --git a/conductor-client-spring-boot4/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfiguration.java b/conductor-client-spring-boot4/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfiguration.java new file mode 100644 index 000000000..283f6d0b0 --- /dev/null +++ b/conductor-client-spring-boot4/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfiguration.java @@ -0,0 +1,46 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring; + +import org.conductoross.conductor.sdk.Conductor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.AutoConfigureOrder; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.core.Ordered; +import org.springframework.core.env.Environment; + +/** + * Hosts the application's native workflows: every class under the application's packages with a + * {@code @Workflow} method. Set {@code conductor.workflows.enabled=false} in a service that only + * starts workflows. + */ +// Last, like the other Conductor auto-configurations: an earlier position would also move the +// client auto-configuration ahead of the Orkes one, and both would then define a TaskClient. +@AutoConfiguration(after = ConductorClientAutoConfiguration.class) +@AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) +@ConditionalOnBean(Conductor.class) +@ConditionalOnProperty(prefix = "conductor.workflows", name = "enabled", matchIfMissing = true) +public class ConductorWorkflowAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + public ConductorWorkflowHost conductorWorkflowHost(Conductor conductor, + ConfigurableListableBeanFactory beanFactory, + Environment environment) { + return new ConductorWorkflowHost(conductor, beanFactory, environment); + } +} diff --git a/conductor-client-spring-boot4/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowHost.java b/conductor-client-spring-boot4/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowHost.java new file mode 100644 index 000000000..1535742d0 --- /dev/null +++ b/conductor-client-spring-boot4/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowHost.java @@ -0,0 +1,147 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.Workers; +import org.conductoross.conductor.sdk.Workflow; +import org.conductoross.conductor.sdk.internal.TaskStubs; +import org.springframework.aop.support.AopUtils; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.config.DependencyDescriptor; +import org.springframework.boot.autoconfigure.AutoConfigurationPackages; +import org.springframework.context.SmartLifecycle; +import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; +import org.springframework.core.MethodParameter; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; + +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +import lombok.extern.slf4j.Slf4j; + +/** + * Finds the classes with {@code @Workflow} methods under the application's packages and hosts + * them once the application has started, stopping before the context closes. + * + *

A workflow class need not be a bean. Each replay gets a new instance: a constructor parameter + * of a class with {@code @WorkerTask} methods gets a stub whose calls schedule those tasks, and + * any other parameter or {@code @Autowired} field is injected from the context. A field holding a + * real task object is rejected, since its calls would run in the workflow on every replay. Task beans keep running on the worker auto-configuration's executor; this only + * registers their task definitions, from the {@code @WorkerTask} attributes. + * + *

Properties under {@code conductor.workflows}: {@code worker-id}, {@code build-id}, + * {@code threads}, {@code continuation-timeout} and {@code dev-mode}. + */ +@Slf4j +public class ConductorWorkflowHost implements SmartLifecycle { + + private final Conductor conductor; + private final ConfigurableListableBeanFactory beanFactory; + private final Environment environment; + private volatile Workers workers; + + public ConductorWorkflowHost(Conductor conductor, ConfigurableListableBeanFactory beanFactory, + Environment environment) { + this.conductor = conductor; + this.beanFactory = beanFactory; + this.environment = environment; + } + + @Override + public void start() { + Set> types = workflowTypes(); + if (types.isEmpty()) { + log.info("No @Workflow classes under {}", packages()); + return; + } + Workers w = conductor.host(); + String workerId = environment.getProperty("conductor.workflows.worker-id"); + if (workerId != null) { + w.workerId(workerId); + } + w.buildId(environment.getProperty("conductor.workflows.build-id")); + w.threads(environment.getProperty("conductor.workflows.threads", Integer.class, 8)); + w.continuationTimeout(environment.getProperty("conductor.workflows.continuation-timeout", Duration.class, + Duration.ofSeconds(30))); + w.devMode(environment.getProperty("conductor.workflows.dev-mode", Boolean.class, false)); + types.forEach(type -> host(w, type)); + w.taskDefinitions(taskBeans().toArray()); + workers = w.start(); + } + + @Override + public void stop() { + Workers w = workers; + workers = null; + if (w != null) { + w.shutdown(); + } + } + + @Override + public boolean isRunning() { + return workers != null; + } + + private void host(Workers w, Class type) { + w.workflow(type, () -> { + // task classes come as stubs, so their calls schedule tasks; anything else from the context + T workflow = TaskStubs.newWorkflow(type, + p -> beanFactory.resolveDependency(new DependencyDescriptor(MethodParameter.forParameter(p), true), null)); + beanFactory.autowireBean(workflow); + return workflow; + }); + } + + private List packages() { + return AutoConfigurationPackages.has(beanFactory) ? AutoConfigurationPackages.get(beanFactory) : List.of(); + } + + Set> workflowTypes() { + ClassPathScanningCandidateComponentProvider scanner = + new ClassPathScanningCandidateComponentProvider(false, environment); + scanner.addIncludeFilter((reader, factory) -> + reader.getAnnotationMetadata().hasAnnotatedMethods(Workflow.class.getName())); + Set> types = new LinkedHashSet<>(); + for (String pkg : packages()) { + for (BeanDefinition candidate : scanner.findCandidateComponents(pkg)) { + types.add(ClassUtils.resolveClassName(candidate.getBeanClassName(), beanFactory.getBeanClassLoader())); + } + } + return types; + } + + /** The same beans the worker auto-configuration polls: components with {@code @WorkerTask} methods. */ + private List taskBeans() { + List beans = new ArrayList<>(); + for (Object bean : beanFactory.getBeansWithAnnotation(Component.class).values()) { + boolean[] found = {false}; + ReflectionUtils.doWithMethods(AopUtils.getTargetClass(bean), + m -> found[0] = true, m -> m.isAnnotationPresent(WorkerTask.class)); + if (found[0]) { + beans.add(bean); + } + } + return beans; + } +} diff --git a/conductor-client-spring-boot4/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/conductor-client-spring-boot4/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 90baca5e3..40accbabb 100644 --- a/conductor-client-spring-boot4/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/conductor-client-spring-boot4/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1,3 +1,4 @@ com.netflix.conductor.client.spring.ConductorClientAutoConfiguration com.netflix.conductor.client.spring.ConductorWorkerAutoConfiguration -io.orkes.conductor.client.spring.OrkesConductorClientAutoConfiguration \ No newline at end of file +io.orkes.conductor.client.spring.OrkesConductorClientAutoConfiguration +com.netflix.conductor.client.spring.ConductorWorkflowAutoConfiguration diff --git a/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/ConductorClientAutoConfigurationTest.java b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/ConductorClientAutoConfigurationTest.java index 67686f4ad..c8392c7cd 100644 --- a/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/ConductorClientAutoConfigurationTest.java +++ b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/ConductorClientAutoConfigurationTest.java @@ -15,6 +15,7 @@ import java.lang.reflect.Method; import java.time.Duration; +import org.conductoross.conductor.sdk.Conductor; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; @@ -32,6 +33,9 @@ import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; import com.netflix.conductor.sdk.workflow.executor.task.AnnotatedWorkerExecutor; +import io.orkes.conductor.client.ApiClient; +import io.orkes.conductor.client.spring.OrkesConductorClientAutoConfiguration; + import static org.assertj.core.api.Assertions.assertThat; class ConductorClientAutoConfigurationTest { @@ -162,4 +166,24 @@ ConductorClient conductorClient() { return USER_CLIENT; } } + + @Test + void conductorBeanWrapsTheClientBean() { + contextRunner + .withPropertyValues("conductor.client.base-path=http://localhost:8080/api") + .run(context -> { + assertThat(context).hasSingleBean(Conductor.class); + assertThat(context.getBean(Conductor.class).client()) + .isSameAs(context.getBean(ConductorClient.class)); + }); + } + + @Test + void conductorBeanUsesTheOrkesClientWhenOneIsConfigured() { + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + OrkesConductorClientAutoConfiguration.class, ConductorClientAutoConfiguration.class)) + .withPropertyValues("conductor.client.root-uri=http://localhost:8080/api") + .run(context -> assertThat(context.getBean(Conductor.class).client()).isInstanceOf(ApiClient.class)); + } } diff --git a/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfigurationTest.java b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfigurationTest.java new file mode 100644 index 000000000..9fe7d7b44 --- /dev/null +++ b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfigurationTest.java @@ -0,0 +1,125 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring; + +import java.util.function.Supplier; + +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.Workers; +import org.conductoross.conductor.sdk.internal.TaskStubs; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.netflix.conductor.client.http.TaskClient; +import com.netflix.conductor.client.spring.sample.AutowiredTasksWorkflow; +import com.netflix.conductor.client.spring.sample.SampleApplication; +import com.netflix.conductor.client.spring.sample.SampleTasks; +import com.netflix.conductor.client.spring.sample.SampleWorkflow; + +import io.orkes.conductor.client.spring.OrkesConductorClientAutoConfiguration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.RETURNS_SELF; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class ConductorWorkflowAutoConfigurationTest { + + private final Workers workers = mock(Workers.class, RETURNS_SELF); + + /** A Conductor whose workers are recorded, so no server is needed. */ + @Configuration + static class RecordingConductor { + static Workers workers; + + @Bean + Conductor conductor() { + Conductor conductor = mock(Conductor.class); + when(conductor.host()).thenReturn(workers); + return conductor; + } + } + + private ApplicationContextRunner runner() { + RecordingConductor.workers = workers; + return new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(ConductorWorkflowAutoConfiguration.class)) + .withUserConfiguration(SampleApplication.class, RecordingConductor.class); + } + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void hostsWorkflowClassesThatAreNotBeansWithStubsForTheirTasks() { + runner().run(context -> { + assertThat(context).hasSingleBean(ConductorWorkflowHost.class); + assertThat(context).doesNotHaveBean(SampleWorkflow.class); + ArgumentCaptor factory = ArgumentCaptor.forClass(Supplier.class); + verify(workers).workflow(eq(SampleWorkflow.class), factory.capture()); + SampleWorkflow first = (SampleWorkflow) factory.getValue().get(); + assertThat(first).isNotSameAs(factory.getValue().get()); + assertThat(first.tasks()).isInstanceOf(TaskStubs.Stub.class).isNotSameAs(context.getBean(SampleTasks.class)); + assertThat(first.environment()).isSameAs(context.getEnvironment()); + verify(workers).start(); + }); + } + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void rejectsAWorkflowThatGetsTheRealTaskBeanInjected() { + runner().run(context -> { + ArgumentCaptor factory = ArgumentCaptor.forClass(Supplier.class); + verify(workers).workflow(eq(AutowiredTasksWorkflow.class), factory.capture()); + assertThatThrownBy(() -> TaskStubs.check(factory.getValue().get())) + .hasMessageContaining("field tasks of"); + }); + } + + @Test + void registersTheTaskDefinitionsOfTaskBeansWithoutPollingThemTwice() { + runner().run(context -> { + verify(workers).taskDefinitions(context.getBean(SampleTasks.class)); + verify(workers, never()).tasks(any()); + }); + } + + @Test + void stopsTheWorkersWhenTheContextCloses() { + runner().run(context -> verify(workers, never()).shutdown()); + verify(workers).shutdown(); + } + + @Test + void aServiceThatOnlyStartsWorkflowsCanTurnHostingOff() { + runner().withPropertyValues("conductor.workflows.enabled=false") + .run(context -> assertThat(context).doesNotHaveBean(ConductorWorkflowHost.class)); + } + + @Test + void leavesASingleTaskClientWhenTheOrkesClientIsConfigured() { + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(OrkesConductorClientAutoConfiguration.class, + ConductorClientAutoConfiguration.class, ConductorWorkerAutoConfiguration.class, + ConductorWorkflowAutoConfiguration.class)) + .withPropertyValues("conductor.client.root-uri=http://localhost:1/api", "conductor.workflows.enabled=false") + .run(context -> assertThat(context).hasSingleBean(TaskClient.class)); + } +} diff --git a/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/AutowiredTasksWorkflow.java b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/AutowiredTasksWorkflow.java new file mode 100644 index 000000000..9e73b415d --- /dev/null +++ b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/AutowiredTasksWorkflow.java @@ -0,0 +1,28 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring.sample; + +import org.conductoross.conductor.sdk.Workflow; +import org.springframework.beans.factory.annotation.Autowired; + +/** Gets the real task bean injected into a field, which must be rejected. */ +public class AutowiredTasksWorkflow { + + @Autowired + private SampleTasks tasks; + + @Workflow(name = "spring_autowired", version = 1) + public String run(String input) { + return tasks.echo(input); + } +} diff --git a/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/NotAWorkflow.java b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/NotAWorkflow.java new file mode 100644 index 000000000..a65b3ea18 --- /dev/null +++ b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/NotAWorkflow.java @@ -0,0 +1,20 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring.sample; + +public class NotAWorkflow { + + public String run(String input) { + return input; + } +} diff --git a/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/SampleApplication.java b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/SampleApplication.java new file mode 100644 index 000000000..efb380e18 --- /dev/null +++ b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/SampleApplication.java @@ -0,0 +1,23 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring.sample; + +import org.springframework.boot.autoconfigure.AutoConfigurationPackage; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +/** Stands in for an application class: its package is the one scanned for workflows. */ +@Configuration +@AutoConfigurationPackage +@ComponentScan +public class SampleApplication {} diff --git a/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/SampleTasks.java b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/SampleTasks.java new file mode 100644 index 000000000..27fb1e302 --- /dev/null +++ b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/SampleTasks.java @@ -0,0 +1,26 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring.sample; + +import org.springframework.stereotype.Component; + +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +@Component +public class SampleTasks { + + @WorkerTask("spring_sample_task") + public String echo(String input) { + return input; + } +} diff --git a/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/SampleWorkflow.java b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/SampleWorkflow.java new file mode 100644 index 000000000..016631d4f --- /dev/null +++ b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/SampleWorkflow.java @@ -0,0 +1,41 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring.sample; + +import org.conductoross.conductor.sdk.Workflow; +import org.springframework.core.env.Environment; + +/** A workflow class that is not a bean: a task class and a dependency from the context. */ +public class SampleWorkflow { + + private final SampleTasks tasks; + private final Environment environment; + + public SampleWorkflow(SampleTasks tasks, Environment environment) { + this.tasks = tasks; + this.environment = environment; + } + + public SampleTasks tasks() { + return tasks; + } + + public Environment environment() { + return environment; + } + + @Workflow(name = "spring_sample", version = 1) + public String run(String input) { + return tasks.echo(input); + } +} diff --git a/conductor-client-spring/src/main/java/com/netflix/conductor/client/spring/ConductorClientAutoConfiguration.java b/conductor-client-spring/src/main/java/com/netflix/conductor/client/spring/ConductorClientAutoConfiguration.java index 0dc00aa29..9352fd86a 100644 --- a/conductor-client-spring/src/main/java/com/netflix/conductor/client/spring/ConductorClientAutoConfiguration.java +++ b/conductor-client-spring/src/main/java/com/netflix/conductor/client/spring/ConductorClientAutoConfiguration.java @@ -20,6 +20,7 @@ import org.apache.commons.lang3.StringUtils; import org.conductoross.conductor.client.FileClient; import org.conductoross.conductor.client.FileClientProperties; +import org.conductoross.conductor.sdk.Conductor; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; @@ -64,6 +65,17 @@ public ConductorClient conductorClient(ClientProperties properties) { return builder.build(); } + /** + * Native workflows over the configured client (an Orkes {@code ApiClient} with keys when one is + * configured). Closing it stops the workers it started; the client bean is left to Spring. + */ + @Bean(destroyMethod = "close") + @ConditionalOnBean(ConductorClient.class) + @ConditionalOnMissingBean + public Conductor conductor(ConductorClient client) { + return Conductor.of(client); + } + @Bean @ConditionalOnBean(ConductorClient.class) @ConditionalOnMissingBean diff --git a/conductor-client-spring/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfiguration.java b/conductor-client-spring/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfiguration.java new file mode 100644 index 000000000..283f6d0b0 --- /dev/null +++ b/conductor-client-spring/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfiguration.java @@ -0,0 +1,46 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring; + +import org.conductoross.conductor.sdk.Conductor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.AutoConfigureOrder; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.core.Ordered; +import org.springframework.core.env.Environment; + +/** + * Hosts the application's native workflows: every class under the application's packages with a + * {@code @Workflow} method. Set {@code conductor.workflows.enabled=false} in a service that only + * starts workflows. + */ +// Last, like the other Conductor auto-configurations: an earlier position would also move the +// client auto-configuration ahead of the Orkes one, and both would then define a TaskClient. +@AutoConfiguration(after = ConductorClientAutoConfiguration.class) +@AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) +@ConditionalOnBean(Conductor.class) +@ConditionalOnProperty(prefix = "conductor.workflows", name = "enabled", matchIfMissing = true) +public class ConductorWorkflowAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + public ConductorWorkflowHost conductorWorkflowHost(Conductor conductor, + ConfigurableListableBeanFactory beanFactory, + Environment environment) { + return new ConductorWorkflowHost(conductor, beanFactory, environment); + } +} diff --git a/conductor-client-spring/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowHost.java b/conductor-client-spring/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowHost.java new file mode 100644 index 000000000..1535742d0 --- /dev/null +++ b/conductor-client-spring/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowHost.java @@ -0,0 +1,147 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.Workers; +import org.conductoross.conductor.sdk.Workflow; +import org.conductoross.conductor.sdk.internal.TaskStubs; +import org.springframework.aop.support.AopUtils; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.config.DependencyDescriptor; +import org.springframework.boot.autoconfigure.AutoConfigurationPackages; +import org.springframework.context.SmartLifecycle; +import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; +import org.springframework.core.MethodParameter; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; + +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +import lombok.extern.slf4j.Slf4j; + +/** + * Finds the classes with {@code @Workflow} methods under the application's packages and hosts + * them once the application has started, stopping before the context closes. + * + *

A workflow class need not be a bean. Each replay gets a new instance: a constructor parameter + * of a class with {@code @WorkerTask} methods gets a stub whose calls schedule those tasks, and + * any other parameter or {@code @Autowired} field is injected from the context. A field holding a + * real task object is rejected, since its calls would run in the workflow on every replay. Task beans keep running on the worker auto-configuration's executor; this only + * registers their task definitions, from the {@code @WorkerTask} attributes. + * + *

Properties under {@code conductor.workflows}: {@code worker-id}, {@code build-id}, + * {@code threads}, {@code continuation-timeout} and {@code dev-mode}. + */ +@Slf4j +public class ConductorWorkflowHost implements SmartLifecycle { + + private final Conductor conductor; + private final ConfigurableListableBeanFactory beanFactory; + private final Environment environment; + private volatile Workers workers; + + public ConductorWorkflowHost(Conductor conductor, ConfigurableListableBeanFactory beanFactory, + Environment environment) { + this.conductor = conductor; + this.beanFactory = beanFactory; + this.environment = environment; + } + + @Override + public void start() { + Set> types = workflowTypes(); + if (types.isEmpty()) { + log.info("No @Workflow classes under {}", packages()); + return; + } + Workers w = conductor.host(); + String workerId = environment.getProperty("conductor.workflows.worker-id"); + if (workerId != null) { + w.workerId(workerId); + } + w.buildId(environment.getProperty("conductor.workflows.build-id")); + w.threads(environment.getProperty("conductor.workflows.threads", Integer.class, 8)); + w.continuationTimeout(environment.getProperty("conductor.workflows.continuation-timeout", Duration.class, + Duration.ofSeconds(30))); + w.devMode(environment.getProperty("conductor.workflows.dev-mode", Boolean.class, false)); + types.forEach(type -> host(w, type)); + w.taskDefinitions(taskBeans().toArray()); + workers = w.start(); + } + + @Override + public void stop() { + Workers w = workers; + workers = null; + if (w != null) { + w.shutdown(); + } + } + + @Override + public boolean isRunning() { + return workers != null; + } + + private void host(Workers w, Class type) { + w.workflow(type, () -> { + // task classes come as stubs, so their calls schedule tasks; anything else from the context + T workflow = TaskStubs.newWorkflow(type, + p -> beanFactory.resolveDependency(new DependencyDescriptor(MethodParameter.forParameter(p), true), null)); + beanFactory.autowireBean(workflow); + return workflow; + }); + } + + private List packages() { + return AutoConfigurationPackages.has(beanFactory) ? AutoConfigurationPackages.get(beanFactory) : List.of(); + } + + Set> workflowTypes() { + ClassPathScanningCandidateComponentProvider scanner = + new ClassPathScanningCandidateComponentProvider(false, environment); + scanner.addIncludeFilter((reader, factory) -> + reader.getAnnotationMetadata().hasAnnotatedMethods(Workflow.class.getName())); + Set> types = new LinkedHashSet<>(); + for (String pkg : packages()) { + for (BeanDefinition candidate : scanner.findCandidateComponents(pkg)) { + types.add(ClassUtils.resolveClassName(candidate.getBeanClassName(), beanFactory.getBeanClassLoader())); + } + } + return types; + } + + /** The same beans the worker auto-configuration polls: components with {@code @WorkerTask} methods. */ + private List taskBeans() { + List beans = new ArrayList<>(); + for (Object bean : beanFactory.getBeansWithAnnotation(Component.class).values()) { + boolean[] found = {false}; + ReflectionUtils.doWithMethods(AopUtils.getTargetClass(bean), + m -> found[0] = true, m -> m.isAnnotationPresent(WorkerTask.class)); + if (found[0]) { + beans.add(bean); + } + } + return beans; + } +} diff --git a/conductor-client-spring/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/conductor-client-spring/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 90baca5e3..40accbabb 100644 --- a/conductor-client-spring/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/conductor-client-spring/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1,3 +1,4 @@ com.netflix.conductor.client.spring.ConductorClientAutoConfiguration com.netflix.conductor.client.spring.ConductorWorkerAutoConfiguration -io.orkes.conductor.client.spring.OrkesConductorClientAutoConfiguration \ No newline at end of file +io.orkes.conductor.client.spring.OrkesConductorClientAutoConfiguration +com.netflix.conductor.client.spring.ConductorWorkflowAutoConfiguration diff --git a/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/ConductorClientAutoConfigurationTest.java b/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/ConductorClientAutoConfigurationTest.java index ddf0623a0..986b0715d 100644 --- a/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/ConductorClientAutoConfigurationTest.java +++ b/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/ConductorClientAutoConfigurationTest.java @@ -14,10 +14,16 @@ import org.conductoross.conductor.client.FileClient; import org.conductoross.conductor.client.FileClientProperties; +import org.conductoross.conductor.sdk.Conductor; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import com.netflix.conductor.client.http.ConductorClient; + +import io.orkes.conductor.client.ApiClient; +import io.orkes.conductor.client.spring.OrkesConductorClientAutoConfiguration; + import static org.assertj.core.api.Assertions.assertThat; class ConductorClientAutoConfigurationTest { @@ -49,4 +55,23 @@ void multipartThresholdOverrideIsRespected() { }); } + @Test + void conductorBeanWrapsTheClientBean() { + contextRunner + .withPropertyValues("conductor.client.base-path=http://localhost:8080/api") + .run(context -> { + assertThat(context).hasSingleBean(Conductor.class); + assertThat(context.getBean(Conductor.class).client()) + .isSameAs(context.getBean(ConductorClient.class)); + }); + } + + @Test + void conductorBeanUsesTheOrkesClientWhenOneIsConfigured() { + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + OrkesConductorClientAutoConfiguration.class, ConductorClientAutoConfiguration.class)) + .withPropertyValues("conductor.client.root-uri=http://localhost:8080/api") + .run(context -> assertThat(context.getBean(Conductor.class).client()).isInstanceOf(ApiClient.class)); + } } diff --git a/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfigurationTest.java b/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfigurationTest.java new file mode 100644 index 000000000..9fe7d7b44 --- /dev/null +++ b/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/ConductorWorkflowAutoConfigurationTest.java @@ -0,0 +1,125 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring; + +import java.util.function.Supplier; + +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.Workers; +import org.conductoross.conductor.sdk.internal.TaskStubs; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.netflix.conductor.client.http.TaskClient; +import com.netflix.conductor.client.spring.sample.AutowiredTasksWorkflow; +import com.netflix.conductor.client.spring.sample.SampleApplication; +import com.netflix.conductor.client.spring.sample.SampleTasks; +import com.netflix.conductor.client.spring.sample.SampleWorkflow; + +import io.orkes.conductor.client.spring.OrkesConductorClientAutoConfiguration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.RETURNS_SELF; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class ConductorWorkflowAutoConfigurationTest { + + private final Workers workers = mock(Workers.class, RETURNS_SELF); + + /** A Conductor whose workers are recorded, so no server is needed. */ + @Configuration + static class RecordingConductor { + static Workers workers; + + @Bean + Conductor conductor() { + Conductor conductor = mock(Conductor.class); + when(conductor.host()).thenReturn(workers); + return conductor; + } + } + + private ApplicationContextRunner runner() { + RecordingConductor.workers = workers; + return new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(ConductorWorkflowAutoConfiguration.class)) + .withUserConfiguration(SampleApplication.class, RecordingConductor.class); + } + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void hostsWorkflowClassesThatAreNotBeansWithStubsForTheirTasks() { + runner().run(context -> { + assertThat(context).hasSingleBean(ConductorWorkflowHost.class); + assertThat(context).doesNotHaveBean(SampleWorkflow.class); + ArgumentCaptor factory = ArgumentCaptor.forClass(Supplier.class); + verify(workers).workflow(eq(SampleWorkflow.class), factory.capture()); + SampleWorkflow first = (SampleWorkflow) factory.getValue().get(); + assertThat(first).isNotSameAs(factory.getValue().get()); + assertThat(first.tasks()).isInstanceOf(TaskStubs.Stub.class).isNotSameAs(context.getBean(SampleTasks.class)); + assertThat(first.environment()).isSameAs(context.getEnvironment()); + verify(workers).start(); + }); + } + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void rejectsAWorkflowThatGetsTheRealTaskBeanInjected() { + runner().run(context -> { + ArgumentCaptor factory = ArgumentCaptor.forClass(Supplier.class); + verify(workers).workflow(eq(AutowiredTasksWorkflow.class), factory.capture()); + assertThatThrownBy(() -> TaskStubs.check(factory.getValue().get())) + .hasMessageContaining("field tasks of"); + }); + } + + @Test + void registersTheTaskDefinitionsOfTaskBeansWithoutPollingThemTwice() { + runner().run(context -> { + verify(workers).taskDefinitions(context.getBean(SampleTasks.class)); + verify(workers, never()).tasks(any()); + }); + } + + @Test + void stopsTheWorkersWhenTheContextCloses() { + runner().run(context -> verify(workers, never()).shutdown()); + verify(workers).shutdown(); + } + + @Test + void aServiceThatOnlyStartsWorkflowsCanTurnHostingOff() { + runner().withPropertyValues("conductor.workflows.enabled=false") + .run(context -> assertThat(context).doesNotHaveBean(ConductorWorkflowHost.class)); + } + + @Test + void leavesASingleTaskClientWhenTheOrkesClientIsConfigured() { + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(OrkesConductorClientAutoConfiguration.class, + ConductorClientAutoConfiguration.class, ConductorWorkerAutoConfiguration.class, + ConductorWorkflowAutoConfiguration.class)) + .withPropertyValues("conductor.client.root-uri=http://localhost:1/api", "conductor.workflows.enabled=false") + .run(context -> assertThat(context).hasSingleBean(TaskClient.class)); + } +} diff --git a/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/AutowiredTasksWorkflow.java b/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/AutowiredTasksWorkflow.java new file mode 100644 index 000000000..9e73b415d --- /dev/null +++ b/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/AutowiredTasksWorkflow.java @@ -0,0 +1,28 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring.sample; + +import org.conductoross.conductor.sdk.Workflow; +import org.springframework.beans.factory.annotation.Autowired; + +/** Gets the real task bean injected into a field, which must be rejected. */ +public class AutowiredTasksWorkflow { + + @Autowired + private SampleTasks tasks; + + @Workflow(name = "spring_autowired", version = 1) + public String run(String input) { + return tasks.echo(input); + } +} diff --git a/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/NotAWorkflow.java b/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/NotAWorkflow.java new file mode 100644 index 000000000..a65b3ea18 --- /dev/null +++ b/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/NotAWorkflow.java @@ -0,0 +1,20 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring.sample; + +public class NotAWorkflow { + + public String run(String input) { + return input; + } +} diff --git a/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/SampleApplication.java b/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/SampleApplication.java new file mode 100644 index 000000000..efb380e18 --- /dev/null +++ b/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/SampleApplication.java @@ -0,0 +1,23 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring.sample; + +import org.springframework.boot.autoconfigure.AutoConfigurationPackage; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +/** Stands in for an application class: its package is the one scanned for workflows. */ +@Configuration +@AutoConfigurationPackage +@ComponentScan +public class SampleApplication {} diff --git a/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/SampleTasks.java b/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/SampleTasks.java new file mode 100644 index 000000000..27fb1e302 --- /dev/null +++ b/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/SampleTasks.java @@ -0,0 +1,26 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring.sample; + +import org.springframework.stereotype.Component; + +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +@Component +public class SampleTasks { + + @WorkerTask("spring_sample_task") + public String echo(String input) { + return input; + } +} diff --git a/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/SampleWorkflow.java b/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/SampleWorkflow.java new file mode 100644 index 000000000..016631d4f --- /dev/null +++ b/conductor-client-spring/src/test/java/com/netflix/conductor/client/spring/sample/SampleWorkflow.java @@ -0,0 +1,41 @@ +/* + * Copyright 2020 Conductor 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 com.netflix.conductor.client.spring.sample; + +import org.conductoross.conductor.sdk.Workflow; +import org.springframework.core.env.Environment; + +/** A workflow class that is not a bean: a task class and a dependency from the context. */ +public class SampleWorkflow { + + private final SampleTasks tasks; + private final Environment environment; + + public SampleWorkflow(SampleTasks tasks, Environment environment) { + this.tasks = tasks; + this.environment = environment; + } + + public SampleTasks tasks() { + return tasks; + } + + public Environment environment() { + return environment; + } + + @Workflow(name = "spring_sample", version = 1) + public String run(String input) { + return tasks.echo(input); + } +} diff --git a/conductor-client/build.gradle b/conductor-client/build.gradle index 7d8b6d2d1..20d59b3aa 100644 --- a/conductor-client/build.gradle +++ b/conductor-client/build.gradle @@ -3,10 +3,12 @@ plugins { id 'idea' id 'maven-publish' id 'signing' - id 'com.github.johnrengelman.shadow' version '8.1.1' + id 'com.gradleup.shadow' version '8.3.5' id 'groovy' } +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar + ext { artifactName = 'Conductor Client' artifactDescription = 'Conductor OSS client (http)' @@ -14,9 +16,25 @@ ext { apply plugin: 'publish-config' +configurations { + // compiled and tested against, shipped inside the jar, never listed in the POM + bundled + compileOnly.extendsFrom bundled + testImplementation.extendsFrom bundled +} + dependencies { api "com.squareup.okhttp3:okhttp:${versions.okHttp}" + // Bundled into the jar under org.conductoross.conductor.shaded (see bundledJar below), so they + // are not dependencies of the published artifact and cannot clash with an application's own. + // ASM reads compiled workflow code to draw untaken branches and definitions; ByteBuddy + // generates the task stubs a workflow's task calls go through. + bundled 'org.ow2.asm:asm:9.9' + bundled 'org.ow2.asm:asm-tree:9.9' + bundled 'org.ow2.asm:asm-analysis:9.9' + bundled 'net.bytebuddy:byte-buddy:1.18.3' + // test dependencies testImplementation "org.junit.jupiter:junit-jupiter-api:${versions.junit}" testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:${versions.junit}" @@ -39,9 +57,40 @@ test { maxParallelForks = 1 } +def relocateBundled = { task -> + task.relocate 'net.bytebuddy', 'org.conductoross.conductor.shaded.bytebuddy' + task.relocate 'org.objectweb.asm', 'org.conductoross.conductor.shaded.asm' + task.exclude 'module-info.class', 'META-INF/versions/*/module-info.class' + // ByteBuddy is a multi-release jar: keep its Java 9 and Java 24 classes in use + task.manifest { attributes 'Multi-Release': 'true' } +} + shadowJar { archiveFileName = "conductor-client-$version-all.jar" + configurations = [project.configurations.runtimeClasspath, project.configurations.bundled] mergeServiceFiles() + relocateBundled(it) +} + +// The module's jar: its classes plus the bundled libraries, relocated. It replaces the plain jar +// for everything that uses this module, the published artifact and the other modules here alike. +def bundledJar = tasks.register('bundledJar', ShadowJar) { + from sourceSets.main.output + configurations = [project.configurations.bundled] + archiveClassifier = '' + mergeServiceFiles() + relocateBundled(it) +} + +jar { + archiveClassifier = 'plain' +} + +['apiElements', 'runtimeElements'].each { name -> + configurations.named(name) { + outgoing.artifacts.clear() + outgoing.artifact(bundledJar) + } } tasks.build { diff --git a/conductor-client/src/main/java/com/netflix/conductor/client/http/ConductorClient.java b/conductor-client/src/main/java/com/netflix/conductor/client/http/ConductorClient.java index 089848454..6697a18e8 100644 --- a/conductor-client/src/main/java/com/netflix/conductor/client/http/ConductorClient.java +++ b/conductor-client/src/main/java/com/netflix/conductor/client/http/ConductorClient.java @@ -154,6 +154,15 @@ public ConductorClient(String basePath) { this(new Builder<>().basePath(basePath)); } + /** + * A client configured from the environment: the server from {@code CONDUCTOR_SERVER_URL} + * (default {@code http://localhost:8080/api}), and key credentials from {@code + * CONDUCTOR_AUTH_KEY} and {@code CONDUCTOR_AUTH_SECRET} when both are set. + */ + public static ConductorClient fromEnvironment() { + return new io.orkes.conductor.client.ApiClient(); + } + public String getBasePath() { return basePath; } diff --git a/conductor-client/src/main/java/com/netflix/conductor/common/metadata/tasks/Task.java b/conductor-client/src/main/java/com/netflix/conductor/common/metadata/tasks/Task.java index 720d8df23..f89678bf1 100644 --- a/conductor-client/src/main/java/com/netflix/conductor/common/metadata/tasks/Task.java +++ b/conductor-client/src/main/java/com/netflix/conductor/common/metadata/tasks/Task.java @@ -186,6 +186,21 @@ public boolean isRetriable() { */ private Map runtimeMetadata; + /** + * Set on a task of a native (code-first) workflow that the code paused on: when the task + * finishes, the server hands this continuation to a host of the workflow code. + */ + @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) + private TaskContinuation continuation; + + public TaskContinuation getContinuation() { + return continuation; + } + + public void setContinuation(TaskContinuation continuation) { + this.continuation = continuation; + } + public void setInputData(Map inputData) { if (inputData == null) { inputData = new HashMap<>(); @@ -300,6 +315,7 @@ public Task copy() { copy.setSubworkflowChanged(subworkflowChanged); copy.setParentTaskId(parentTaskId); copy.setFirstStartTime(firstStartTime); + copy.setContinuation(continuation); return copy; } diff --git a/conductor-client/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskContinuation.java b/conductor-client/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskContinuation.java new file mode 100644 index 000000000..c5b9e4e56 --- /dev/null +++ b/conductor-client/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskContinuation.java @@ -0,0 +1,230 @@ +/* + * Copyright 2021 Conductor 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 com.netflix.conductor.common.metadata.tasks; + +import java.util.HashMap; +import java.util.Map; + +/** + * The continuation of a native (code-defined) workflow that runs when this task finishes. + * + *

Native workflow code pauses only on a task. The task it paused on carries this marker: which + * lane of the code waits on it, which continuation of that lane runs next, whether that + * continuation is waiting for the task, queued for a worker, leased by one, or applied. Once + * applied, the marker is the record of what the continuation produced, which a worker replays from. + * The workflow's first continuation and its handler runs have no task to wait on; the workflow + * record carries their markers (see {@code NativeState}). + */ +public class TaskContinuation { + + public static final String WAITING = "WAITING"; + public static final String RUNNABLE = "RUNNABLE"; + public static final String LEASED = "LEASED"; + public static final String APPLIED = "APPLIED"; + + private String lane; + private int n; + private String state = WAITING; + + private long epoch; + private String worker; + private String queue; + private long queuedAt; + private long leasedAt; + private long appliedAt; + private int attempts; + private String deferred; + + private long step; + private Map recorded = new HashMap<>(); + private Map resumedWith = new HashMap<>(); + private boolean done; + private Map result; + private Map error; + + public TaskContinuation() {} + + public TaskContinuation(String lane, int n) { + this.lane = lane; + this.n = n; + } + + /** A fresh marker for the same lane and continuation, as a retried attempt carries. */ + public TaskContinuation reset() { + return new TaskContinuation(lane, n); + } + + public boolean isWaiting() { + return WAITING.equals(state); + } + + public boolean isRunnable() { + return RUNNABLE.equals(state); + } + + public boolean isLeased() { + return LEASED.equals(state); + } + + public boolean isApplied() { + return APPLIED.equals(state); + } + + public String getLane() { + return lane; + } + + public void setLane(String lane) { + this.lane = lane; + } + + public int getN() { + return n; + } + + public void setN(int n) { + this.n = n; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public long getEpoch() { + return epoch; + } + + public void setEpoch(long epoch) { + this.epoch = epoch; + } + + public String getWorker() { + return worker; + } + + public void setWorker(String worker) { + this.worker = worker; + } + + public String getQueue() { + return queue; + } + + public void setQueue(String queue) { + this.queue = queue; + } + + public long getQueuedAt() { + return queuedAt; + } + + public void setQueuedAt(long queuedAt) { + this.queuedAt = queuedAt; + } + + public long getLeasedAt() { + return leasedAt; + } + + public void setLeasedAt(long leasedAt) { + this.leasedAt = leasedAt; + } + + public long getAppliedAt() { + return appliedAt; + } + + public void setAppliedAt(long appliedAt) { + this.appliedAt = appliedAt; + } + + public int getAttempts() { + return attempts; + } + + public void setAttempts(int attempts) { + this.attempts = attempts; + } + + public String getDeferred() { + return deferred; + } + + public void setDeferred(String deferred) { + this.deferred = deferred; + } + + public long getStep() { + return step; + } + + public void setStep(long step) { + this.step = step; + } + + public Map getRecorded() { + return recorded; + } + + public void setRecorded(Map recorded) { + this.recorded = recorded; + } + + public Map getResumedWith() { + return resumedWith; + } + + public void setResumedWith(Map resumedWith) { + this.resumedWith = resumedWith; + } + + public boolean isDone() { + return done; + } + + public void setDone(boolean done) { + this.done = done; + } + + public Map getResult() { + return result; + } + + public void setResult(Map result) { + this.result = result; + } + + public Map getError() { + return error; + } + + public void setError(Map error) { + this.error = error; + } + + @Override + public String toString() { + return "TaskContinuation{" + + lane + + "#" + + n + + " " + + state + + (epoch > 0 ? " epoch " + epoch : "") + + "}"; + } +} diff --git a/conductor-client/src/main/java/com/netflix/conductor/common/run/NativeState.java b/conductor-client/src/main/java/com/netflix/conductor/common/run/NativeState.java new file mode 100644 index 000000000..c14a7cd33 --- /dev/null +++ b/conductor-client/src/main/java/com/netflix/conductor/common/run/NativeState.java @@ -0,0 +1,132 @@ +/* + * Copyright 2021 Conductor 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 com.netflix.conductor.common.run; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.netflix.conductor.common.metadata.tasks.TaskContinuation; + +/** + * Engine state of a native (code-defined) workflow that has no task to live on. Everything else + * about the code's progress is on the tasks it paused on ({@link TaskContinuation}), so this stays + * small however long the execution runs. + */ +public class NativeState { + + private int protocol; + private String codeType; + private int continuationTimeoutSeconds; + private long step; + + /** The main lane's first continuation, which runs before any task exists. */ + private TaskContinuation bootstrap; + + /** The handler lane: signal and update handlers schedule no tasks. Null without handlers. */ + private TaskContinuation handlers; + + private Map replies = new HashMap<>(); + private List seen = new ArrayList<>(); + + /** + * The continuation (queue message id) leased right now. One continuation of an execution runs + * at a time, on any host: reference names and recorded values are allocated from what its + * replay saw, so two running at once could pick the same ones. + */ + private String activeContinuation; + + /** When {@link #activeContinuation}'s lease ends, in epoch millis. */ + private long activeUntil; + + public String getActiveContinuation() { + return activeContinuation; + } + + public void setActiveContinuation(String activeContinuation) { + this.activeContinuation = activeContinuation; + } + + public long getActiveUntil() { + return activeUntil; + } + + public void setActiveUntil(long activeUntil) { + this.activeUntil = activeUntil; + } + + public int getProtocol() { + return protocol; + } + + public void setProtocol(int protocol) { + this.protocol = protocol; + } + + public String getCodeType() { + return codeType; + } + + public void setCodeType(String codeType) { + this.codeType = codeType; + } + + public int getContinuationTimeoutSeconds() { + return continuationTimeoutSeconds; + } + + public void setContinuationTimeoutSeconds(int continuationTimeoutSeconds) { + this.continuationTimeoutSeconds = continuationTimeoutSeconds; + } + + public long getStep() { + return step; + } + + public void setStep(long step) { + this.step = step; + } + + public TaskContinuation getBootstrap() { + return bootstrap; + } + + public void setBootstrap(TaskContinuation bootstrap) { + this.bootstrap = bootstrap; + } + + public TaskContinuation getHandlers() { + return handlers; + } + + public void setHandlers(TaskContinuation handlers) { + this.handlers = handlers; + } + + public Map getReplies() { + return replies; + } + + public void setReplies(Map replies) { + this.replies = replies; + } + + public List getSeen() { + return seen; + } + + public void setSeen(List seen) { + this.seen = seen; + } +} diff --git a/conductor-client/src/main/java/com/netflix/conductor/common/run/Workflow.java b/conductor-client/src/main/java/com/netflix/conductor/common/run/Workflow.java index 0f280230c..f155bbc8e 100644 --- a/conductor-client/src/main/java/com/netflix/conductor/common/run/Workflow.java +++ b/conductor-client/src/main/java/com/netflix/conductor/common/run/Workflow.java @@ -105,6 +105,33 @@ public boolean isSuccessful() { private String idempotencyKey; + /** The engine's state of a native (code-first) workflow execution; null for other workflows. */ + @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) + private NativeState nativeState; + + /** + * The task a FAILED workflow failed at: the task whose failure ended it, or for a native + * workflow the mark where its code threw. Null when no task caused the end. + */ + @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) + private String failedTaskId; + + public String getFailedTaskId() { + return failedTaskId; + } + + public void setFailedTaskId(String failedTaskId) { + this.failedTaskId = failedTaskId; + } + + public NativeState getNativeState() { + return nativeState; + } + + public void setNativeState(NativeState nativeState) { + this.nativeState = nativeState; + } + private String rateLimitKey; private boolean rateLimited; diff --git a/conductor-client/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/AnnotatedWorker.java b/conductor-client/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/AnnotatedWorker.java index 3a1b5bfd6..2f81434d0 100644 --- a/conductor-client/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/AnnotatedWorker.java +++ b/conductor-client/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/AnnotatedWorker.java @@ -134,6 +134,11 @@ private Object[] getParameters(Task task, Class[] parameterTypes, Parameter[] Type type = parameters[i].getParameterizedType(); Class parameterType = parameterTypes[i]; values[i] = getInputValue(task, parameterType, type, paramAnnotation); + } else if (parameters[i].isNamePresent() + && task.getInputData().containsKey(parameters[i].getName())) { + // Compiled with -parameters and the input has a key with the parameter's name, as + // native workflows send it: bind that value. + values[i] = convertNamed(task.getInputData().get(parameters[i].getName()), parameters[i]); } else { values[i] = convertValue(task.getInputData(), parameterTypes[i]); } @@ -189,6 +194,13 @@ private Object getInputValue( } } + private Object convertNamed(Object value, Parameter parameter) { + if (value == null) { + return parameter.getType().isPrimitive() ? convertValue(0, parameter.getType()) : null; + } + return om.convertValue(value, om.getTypeFactory().constructType(parameter.getParameterizedType())); + } + private Object convertValue(Object source, Class targetType) { JsonNode tree = om.valueToTree(source); try (JsonParser parser = tree.traverse(om)) { @@ -257,8 +269,13 @@ private TaskResult setValue(Object invocationResult, TaskResult result) { return result; } else { - Map resultAsMap = om.convertValue(invocationResult, Map.class); - result.getOutputData().putAll(resultAsMap); + // an object spreads into the output; anything else (an enum, a date, an array) is one value + Object plain = om.convertValue(invocationResult, Object.class); + if (plain instanceof Map) { + result.getOutputData().putAll((Map) plain); + } else { + result.getOutputData().put("result", plain); + } result.setStatus(TaskResult.Status.COMPLETED); return result; } diff --git a/conductor-client/src/main/java/com/netflix/conductor/sdk/workflow/task/WorkerTask.java b/conductor-client/src/main/java/com/netflix/conductor/sdk/workflow/task/WorkerTask.java index 6562e56c0..0840da5ba 100644 --- a/conductor-client/src/main/java/com/netflix/conductor/sdk/workflow/task/WorkerTask.java +++ b/conductor-client/src/main/java/com/netflix/conductor/sdk/workflow/task/WorkerTask.java @@ -37,4 +37,13 @@ // default is 1 which is good enough for most use cases // a number higher than 1 will have concurrent pollers doing poll and execute int pollerCount() default 1; + + /** Retries after a failure, registered with the task definition; -1 keeps the default. */ + int retryCount() default -1; + + /** Seconds between retries, registered with the task definition; -1 keeps the default. */ + int retryDelaySeconds() default -1; + + /** Seconds a worker may hold the task before it is rescheduled; 0 keeps the default. */ + int responseTimeoutSeconds() default 0; } diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/AgentCall.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/AgentCall.java new file mode 100644 index 000000000..c6067784d --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/AgentCall.java @@ -0,0 +1,94 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.conductoross.conductor.sdk.internal.Command; +import org.conductoross.conductor.sdk.internal.Engine; +import org.conductoross.conductor.sdk.internal.Entries; + +/** + * Calls an AI agent from the Conductor server (an AGENT task): a remote agent over the A2A + * protocol, or a Conductor agent by name. The server holds the conversation, polls long-running + * agent tasks, and records the result; the workflow waits without a worker. + */ +public final class AgentCall { + + /** What the agent returned: its text reply, final state, and any structured output. */ + public record AgentResult(String text, String state, Map output, String taskId, String contextId) {} + + private final Command command; + private int retries = 3; + private Duration retryDelay = Duration.ofSeconds(1); + + AgentCall(String ref) { + command = new Command(Command.Kind.AGENT, ref, ref); + command.explicitRef = ref; + } + + /** + * A remote A2A agent: its JSON-RPC endpoint, or its agent card URL ending in {@code .json}, from + * which the endpoint is discovered. + */ + public AgentCall remote(String agentUrl) { + command.input.put("agentType", "a2a"); + command.input.put("agentUrl", agentUrl); + return this; + } + + /** A Conductor agent by name and version. */ + public AgentCall conductor(String agentName, int version) { + command.input.put("agentType", "conductor"); + command.input.put("agentName", agentName); + command.input.put("agentVersion", version); + return this; + } + + public AgentCall header(String name, String value) { + @SuppressWarnings("unchecked") + Map headers = + (Map) command.input.computeIfAbsent("headers", k -> new LinkedHashMap()); + headers.put(name, value); + return this; + } + + /** Continues an earlier conversation with the agent. */ + public AgentCall context(String contextId) { + command.input.put("contextId", contextId); + return this; + } + + /** Longest time to wait for a long-running agent task. */ + public AgentCall maxDuration(Duration duration) { + command.input.put("maxDurationSeconds", (int) duration.toSeconds()); + return this; + } + + public AgentCall retries(int count, Duration delay) { + this.retries = count; + this.retryDelay = delay; + return this; + } + + /** Sends the message and waits for the agent's result. */ + public AgentResult ask(String text) { + command.input.put("text", text); + command.fields.put( + "taskDefinition", Entries.retryingDefinition(command.name, retries, Math.max(1, retryDelay.toSeconds()))); + command.resultType = AgentResult.class; + return (AgentResult) Engine.current().call(command); + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/Backoff.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Backoff.java new file mode 100644 index 000000000..7cd5af2c5 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Backoff.java @@ -0,0 +1,69 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.time.Duration; + +/** Interval policy for {@link Conductor#repeatUntil}: the first check runs after one interval. */ +public final class Backoff { + + private final Duration interval; + private final double factor; + private final Duration max; + private final int attempts; + + private Backoff(Duration interval, double factor, Duration max, int attempts) { + this.interval = interval; + this.factor = factor; + this.max = max; + this.attempts = attempts; + } + + public static Backoff every(Duration interval) { + return new Backoff(interval, 1.0, interval, 10); + } + + public Backoff factor(double factor) { + return new Backoff(interval, factor, factor > 1.0 && max.equals(interval) ? Duration.ofDays(1) : max, attempts); + } + + public Backoff max(Duration max) { + return new Backoff(interval, factor, max, attempts); + } + + public Backoff attempts(int attempts) { + return new Backoff(interval, factor, max, attempts); + } + + public Duration interval() { + return interval; + } + + public double factor() { + return factor; + } + + public Duration max() { + return max; + } + + public int attempts() { + return attempts; + } + + /** The wait before check number {@code iteration}, counting from 1. */ + public Duration delay(int iteration) { + double seconds = interval.toSeconds() * Math.pow(factor, Math.max(0, iteration - 1)); + return Duration.ofSeconds(Math.max(1, Math.min(Math.round(seconds), max.toSeconds()))); + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/Conductor.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Conductor.java new file mode 100644 index 000000000..a8317931f --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Conductor.java @@ -0,0 +1,679 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BooleanSupplier; +import java.util.function.Function; +import java.util.function.Supplier; + +import org.conductoross.conductor.sdk.Functions.Fn0; +import org.conductoross.conductor.sdk.Functions.Fn1; +import org.conductoross.conductor.sdk.Functions.Fn2; +import org.conductoross.conductor.sdk.Functions.Fn3; +import org.conductoross.conductor.sdk.Functions.Fn4; +import org.conductoross.conductor.sdk.Functions.Pred; +import org.conductoross.conductor.sdk.Functions.Proc0; +import org.conductoross.conductor.sdk.Functions.Proc1; +import org.conductoross.conductor.sdk.Functions.Proc2; +import org.conductoross.conductor.sdk.Functions.Proc3; +import org.conductoross.conductor.sdk.Functions.Proc4; +import org.conductoross.conductor.sdk.internal.Command; +import org.conductoross.conductor.sdk.internal.Conductors; +import org.conductoross.conductor.sdk.internal.Engine; +import org.conductoross.conductor.sdk.internal.Json; +import org.conductoross.conductor.sdk.internal.MethodRefs; +import org.conductoross.conductor.sdk.internal.TaskStubs; +import org.conductoross.conductor.sdk.internal.WorkflowSpec; + +import com.netflix.conductor.client.http.ConductorClient; +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +/** + * Native workflows for Conductor. + * + *

Inside a {@link Workflow} method, the static methods of this class are the workflow's calls + * to the server: each one becomes a task in the execution's graph. Everything else in the method + * is ordinary Java. Import them statically: + * + *

{@code
+ * import static org.conductoross.conductor.sdk.Conductor.*;
+ *
+ * @Workflow(name = "order", version = 1)
+ * public OrderResult process(OrderRequest order) {
+ *     Payment payment = task(PaymentTasks::charge, order.id(), order.total());
+ *     if (payment.declined()) return OrderResult.declined();
+ *     sleep(Duration.ofMinutes(5));
+ *     return OrderResult.ok(payment);
+ * }
+ * }
+ * + *

Outside workflow code, an instance of this class runs native workflows over a {@link + * ConductorClient}: create one with {@link #of(ConductorClient)}, host workflows and tasks with + * {@link #host()}, and start executions with {@link #start}. The client is configured as for any + * Conductor client (its builder, {@link ConductorClient#fromEnvironment()}, an Orkes {@code + * ApiClient} with keys, or the Spring bean), and stays its creator's to shut down. + * + *

{@code
+ * ConductorClient client = ConductorClient.fromEnvironment();
+ * try (Conductor conductor = Conductor.of(client)) {
+ *     conductor.host().workflows(OrderWorkflow.class).tasks(new PaymentTasks()).start();
+ *     OrderResult result = conductor.execute(OrderWorkflow::process, order, Duration.ofMinutes(1));
+ * }
+ * client.shutdown();
+ * }
+ * + *

Rules for workflow code: anything non-deterministic or with a side effect that is not a task + * goes through {@link #once}, {@link #now} or {@link #random}; blocking I/O belongs in tasks. + */ +public final class Conductor implements AutoCloseable { + + private static final Map SPECS = new ConcurrentHashMap<>(); + + // ================================================================== workflow code + + // ------------------------------------------------------------------ tasks by method reference + + public static R task(Fn0 task) { + return call(task); + } + + public static R task(Fn1 task, A a) { + return call(task, a); + } + + public static R task(Fn2 task, A a, B b) { + return call(task, a, b); + } + + public static R task(Fn3 task, A a, B b, C c) { + return call(task, a, b, c); + } + + public static R task(Fn4 task, A a, B b, C c, D d) { + return call(task, a, b, c, d); + } + + public static void task(Proc0 task) { + call(task); + } + + public static void task(Proc1 task, A a) { + call(task, a); + } + + public static void task(Proc2 task, A a, B b) { + call(task, a, b); + } + + public static void task(Proc3 task, A a, B b, C c) { + call(task, a, b, c); + } + + public static void task(Proc4 task, A a, B b, C c, D d) { + call(task, a, b, c, d); + } + + /** + * A task stub: an instance of a class with {@code @WorkerTask} methods whose calls schedule + * those tasks. Conductor passes one for each task-class parameter of a workflow's + * constructor; this is for a factory given to {@code host().workflow(Type.class, factory)}, + * when the constructor also takes something else: + * + *

{@code
+     * host().workflow(OrderWorkflow.class, () -> new OrderWorkflow(Conductor.stub(OrderTasks.class), config))
+     * }
+ */ + public static T stub(Class taskClass) { + return TaskStubs.stub(taskClass); + } + + /** A task by name: for names known only at runtime, or tasks owned by another team. */ + public static TaskCall task(String name) { + return new TaskCall(name); + } + + @SuppressWarnings("unchecked") + private static R call(Serializable ref, Object... args) { + return (R) Engine.current().call(taskCommand(ref, args)); + } + + /** The command for a call to a {@code @WorkerTask} method. */ + public static Command taskCommand(Serializable ref, Object... args) { + return taskCommand(MethodRefs.resolve(ref), args); + } + + /** The command for a call to a {@code @WorkerTask} method, by a reference or on a task stub. */ + public static Command taskCommand(Method method, Object[] args) { + WorkerTask annotation = method.getAnnotation(WorkerTask.class); + if (annotation == null) { + throw new IllegalArgumentException( + method.getDeclaringClass().getSimpleName() + "." + method.getName() + " is not a @WorkerTask method"); + } + Command command = new Command(Command.Kind.SIMPLE, annotation.value(), annotation.value()); + String[] names = MethodRefs.parameterNames(method); + for (int i = 0; i < names.length; i++) { + command.input.put(names[i], Json.plain(args[i])); + } + command.resultType = method.getGenericReturnType(); + command.method = method; + command.args = args; + return command; + } + + // ------------------------------------------------------------------ values recorded once + + /** Runs the supplier here, once, and records the result; a re-run returns the recorded value. */ + @SuppressWarnings("unchecked") + public static T once(String name, Supplier supplier) { + return (T) Engine.current().once(name, supplier); + } + + /** The current time, recorded so that a re-run sees the same instant. */ + public static Instant now() { + return Engine.current().now(); + } + + /** A random number in [0, 1), recorded. */ + public static double random() { + return Engine.current().random(); + } + + /** The id of the execution this code is running for. */ + public static String workflowId() { + return Engine.current().workflowId(); + } + + // ------------------------------------------------------------------ parallelism + + /** + * Runs the block as a parallel branch (a lane of its own in a FORK_JOIN) and carries on without + * waiting for it. {@link #join} or {@link Promise#get} waits. A lane that is never joined still + * runs, the workflow stays running until it finishes, and its failure does not fail the workflow. + */ + public static Promise async(Supplier body) { + return Engine.current().async(body); + } + + /** Waits for the given lanes and everything they started, and raises the first failure. */ + public static void join(Promise... promises) { + Engine.current().join(List.of(promises)); + } + + /** Runs the body once per item, in parallel; each item is a branch of a FORK_JOIN. */ + public static Promise> fanOut(String name, List items, Function body) { + List results = Engine.current().fanOut(name, new ArrayList<>(items), body); + return new Promise<>() { + @Override + public List get() { + return results; + } + + @Override + public boolean isDone() { + return true; + } + }; + } + + public static Promise> fanOut(List items, Function body) { + return fanOut("fanout", items, body); + } + + // ------------------------------------------------------------------ control flow helpers + + /** + * A switch the engine can see. Declares every case up front, so the execution's graph shows + * the decision with all its branches and which one the value took (a SWITCH task, with the + * taken case in its output); the body of the taken case runs as ordinary workflow code, and + * its calls appear inside that branch. + * + *
{@code
+     * switchOn("oddEvenDecision", stats.oddEven())
+     *     .when("0", () -> { task(Tasks::even); })
+     *     .when("1", () -> { task(Tasks::odd); })
+     *     .otherwise(() -> notes.add("unexpected"))
+     *     .run();
+     *
+     * String carrier = switchOn("region", region)
+     *     .when("eu", () -> task(Tasks::euCarrier, item))
+     *     .otherwise(() -> task(Tasks::hold, item))
+     *     .get();
+     * }
+ * + * A case with no task calls is an empty branch; a value no case handles runs {@code otherwise}, + * or fails the workflow when there is none. Plain {@code if}/{@code else} remains ordinary + * code; use this when the branch should be visible in the execution. + */ + public static SwitchStart switchOn(String name, Object value) { + return new SwitchStart(name, value); + } + + /** A switch before its first case; the first case's body fixes the result type. */ + public static final class SwitchStart { + private final String name; + private final Object value; + + SwitchStart(String name, Object value) { + this.name = name; + this.value = value; + } + + /** The body for this case; the key is compared with the value's string form. */ + public Switch when(Object key, Functions.CaseBody body) { + return new Switch(name, value).when(key, body); + } + + public Switch when(Object key, Functions.CaseAction body) { + return new Switch(name, value).when(key, body); + } + } + + /** A switch under construction; see {@link #switchOn(String, Object)}. */ + public static final class Switch { + private final String name; + private final Object value; + private final java.util.LinkedHashMap> cases = new java.util.LinkedHashMap<>(); + private Supplier otherwise; + + Switch(String name, Object value) { + this.name = name; + this.value = value; + } + + /** The body for this case; the key is compared with the value's string form. */ + public Switch when(Object key, Functions.CaseBody body) { + if (cases.putIfAbsent(String.valueOf(key), body) != null) { + throw new IllegalArgumentException("case " + key + " of " + name + " is declared twice"); + } + return this; + } + + public Switch when(Object key, Functions.CaseAction body) { + return when(key, new org.conductoross.conductor.sdk.internal.ActionCase(body)); + } + + /** The body when no case matches; without it an unmatched value fails the workflow. */ + public Switch otherwise(Functions.CaseBody body) { + this.otherwise = body; + return this; + } + + public Switch otherwise(Functions.CaseAction body) { + return otherwise(new org.conductoross.conductor.sdk.internal.ActionCase(body)); + } + + /** Runs the taken case and returns its value. */ + @SuppressWarnings("unchecked") + public T get() { + return (T) Engine.current().switchOn(name, value, cases, otherwise); + } + + /** Runs the taken case. */ + public void run() { + get(); + } + } + + /** Waits on the server (a WAIT task); the code resumes when the timer fires. */ + public static void sleep(Duration duration) { + Command wait = new Command(Command.Kind.WAIT, "sleep", "sleep"); + wait.input.put("duration", Conductors.duration(duration)); + wait.resultType = Void.class; + wait.seconds = duration.toSeconds(); + Engine.current().call(wait); + } + + /** + * Waits on the server until the given instant (a WAIT task with {@code until}). The server + * resolves {@code until} to the minute, so the wait ends at the start of the minute after + * {@code when} at the latest. + */ + public static void sleepUntil(Instant when) { + Instant minute = when.truncatedTo(java.time.temporal.ChronoUnit.MINUTES); + if (minute.isBefore(when)) { + minute = minute.plus(java.time.Duration.ofMinutes(1)); + } + String until = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm 'UTC'") + .withZone(java.time.ZoneOffset.UTC) + .format(minute); + Command wait = new Command(Command.Kind.WAIT, "sleep_until", "sleep_until"); + wait.input.put("until", until); + wait.resultType = Void.class; + Engine.current().call(wait); + } + + /** + * Runs a task once per item, one after another, on the server (a DO_WHILE over the items), + * and returns the results in order. The code is woken once, when all items are done. The + * task method takes the item as its only parameter. For items in parallel, use {@link + * #fanOut}. + */ + @SuppressWarnings("unchecked") + public static List forEach(String name, List items, Fn1 task) { + Command command = taskCommand(task, new Object[] {null}); + String itemParameter = command.input.keySet().iterator().next(); + command.input.clear(); + return (List) (List) Engine.current().forEach(name, new ArrayList<>(items), command, itemParameter); + } + + public static List forEach(List items, Fn1 task) { + return forEach("for_each", items, task); + } + + /** + * The same, naming the task through a stub, as the rest of the workflow calls it: + * {@code forEach("labels", items, tasks::labelItem)}. The stub is not called; the server runs + * the task once per item. + */ + @SuppressWarnings("unchecked") + public static List forEach(String name, List items, Functions.TaskOf task) { + Command command = taskCommand(task, new Object[] {null}); + String itemParameter = command.input.keySet().iterator().next(); + command.input.clear(); + return (List) (List) Engine.current().forEach(name, new ArrayList<>(items), command, itemParameter); + } + + public static List forEach(List items, Functions.TaskOf task) { + return forEach("for_each", items, task); + } + + /** + * Repeats a single task call on the server until the condition holds or the attempts run out, + * waiting between attempts (a DO_WHILE with a WAIT). The code is woken once, at the end. The + * condition is a method reference to a boolean property of the result, e.g. {@code + * JobStatus::done}, so that the server can evaluate it. + */ + @SuppressWarnings("unchecked") + public static T repeatUntil(Supplier body, Pred until, Backoff backoff) { + return (T) Engine.current().repeatUntil(body, until, backoff); + } + + /** + * Waits until the condition, typically over variables a signal handler changes, holds; returns + * whether it holds at the end of the wait. + */ + public static boolean awaitCondition(BooleanSupplier condition, Duration timeout) { + return Engine.current().awaitCondition(condition, timeout); + } + + // ------------------------------------------------------------------ other workflows + + /** Runs a {@code @Workflow} method as a child workflow (SUB_WORKFLOW) and waits for its result. */ + @SuppressWarnings("unchecked") + public static R child(Fn1 workflow, A input) { + Method method = MethodRefs.resolve(workflow); + WorkflowSpec spec = spec(method); + Command command = new Command(Command.Kind.SUB_WORKFLOW, spec.name, spec.name); + command.fields.put("subWorkflowParam", Map.of("name", spec.name, "version", spec.version)); + command.input.putAll(WorkflowSpec.encodeInput(method, new Object[] {input})); + command.resultType = method.getGenericReturnType(); + command.childMethod = method; + command.childInput = input; + return (R) Engine.current().call(command); + } + + /** Starts a {@code @Workflow} method as an independent execution and does not wait. */ + public static void startWorkflow(Fn1 workflow, A input) { + Method method = MethodRefs.resolve(workflow); + WorkflowSpec spec = spec(method); + startWorkflowCommand(spec.name, spec.version, WorkflowSpec.encodeInput(method, new Object[] {input}), method, input); + } + + /** Starts any registered workflow by name and does not wait. */ + public static void startWorkflow(String name, int version, Map input) { + Map plain = new LinkedHashMap<>(); + input.forEach((k, v) -> plain.put(k, Json.plain(v))); + startWorkflowCommand(name, version, plain, null, null); + } + + private static void startWorkflowCommand(String name, int version, Map input, Method method, Object childInput) { + Command command = new Command(Command.Kind.START_WORKFLOW, "start_" + name, "start_" + name); + Map start = new LinkedHashMap<>(); + start.put("name", name); + start.put("version", version); + start.put("input", input); + command.input.put("startWorkflow", start); + command.childMethod = method; + command.childInput = childInput; + Engine.current().fire(command); + } + + // ------------------------------------------------------------------ server steps + + public static HttpCall http(String ref) { + return new HttpCall(ref); + } + + public static HumanCall human(String ref) { + return new HumanCall(ref); + } + + public static ExternalWait awaitExternal(String ref, Class type) { + return new ExternalWait<>(ref, type); + } + + public static EventCall event(String ref) { + return new EventCall(ref); + } + + public static LlmCall llm(String ref) { + return new LlmCall(ref); + } + + /** Calls an MCP server's tools from the Conductor server. */ + public static McpCall mcp(String ref) { + return new McpCall(ref); + } + + /** Calls an AI agent (remote over A2A, or a Conductor agent) from the Conductor server. */ + public static AgentCall agent(String ref) { + return new AgentCall(ref); + } + + public static WorkflowSpec spec(Method method) { + return SPECS.computeIfAbsent(method, WorkflowSpec::of); + } + + // ================================================================== client + + private final ConductorClient client; + private final List started = new ArrayList<>(); + + private Conductor(ConductorClient client) { + this.client = client; + } + + /** + * Native workflows over a client. The client is not owned: {@link #close()} stops the workers + * this instance started and leaves the client to its creator, so a shared or injected client + * keeps working. + */ + public static Conductor of(ConductorClient client) { + return new Conductor(java.util.Objects.requireNonNull(client, "client")); + } + + public ConductorClient client() { + return client; + } + + /** Hosts workflow classes and task classes in this process. */ + /** + * Registers the definitions of these workflow classes (and the task definitions of these + * task objects, if any) without starting workers: for a deploy step that publishes what a + * build contains. {@link Workers#start()} does the same on start-up. + */ + public void register(Class... workflows) { + List specs = new java.util.ArrayList<>(); + for (Class type : workflows) { + specs.addAll(org.conductoross.conductor.sdk.internal.WorkflowSpec.of(type)); + } + Registration.register(client, specs, List.of(), 30); + } + + /** + * The definition that would be registered for a workflow class: its discovered graph, input + * parameters and native metadata, as JSON. For review, or to diff in a change. + */ + public static List> definitions(Class workflow) { + List> defs = new java.util.ArrayList<>(); + for (org.conductoross.conductor.sdk.internal.WorkflowSpec spec : org.conductoross.conductor.sdk.internal.WorkflowSpec.of(workflow)) { + defs.add(Registration.skeleton(spec, 30)); + } + return defs; + } + + /** + * A new set of workflows and tasks to host in this process: add them, then {@code start()}. + * Each call returns a new set; closing this Conductor stops them all. + */ + public Workers host() { + Workers workers = new Workers(this); + started.add(workers); + return workers; + } + + /** Starts an execution of a {@code @Workflow} method. */ + public WorkflowHandle start(Fn1 workflow, A input) { + return workflow(workflow).start(input); + } + + /** Start options: correlation id, idempotency key. */ + public StartBuilder workflow(Fn1 workflow) { + return new StartBuilder<>(this, MethodRefs.resolve(workflow)); + } + + /** Starts an execution and waits for its result. */ + public R execute(Fn1 workflow, A input, Duration timeout) { + return start(workflow, input).result(timeout); + } + + /** Attaches to an existing execution of a {@code @Workflow} method. */ + public WorkflowHandle attach(Fn1 workflow, String workflowId) { + return new WorkflowHandle<>(this, workflowId, MethodRefs.resolve(workflow).getGenericReturnType()); + } + + /** Stops the workers this instance started. The client is left running: it is its creator's. */ + @Override + public void close() { + started.forEach(Workers::shutdown); + } + + /** Options for starting an execution. */ + public static final class StartBuilder { + private final Conductor conductor; + private final Method method; + private String correlationId; + private String idempotencyKey; + private Map taskToDomain; + private Integer priority; + + StartBuilder(Conductor conductor, Method method) { + this.conductor = conductor; + this.method = method; + } + + public StartBuilder correlationId(String correlationId) { + this.correlationId = correlationId; + return this; + } + + /** A second start with the same key returns the execution the first one created. */ + public StartBuilder idempotencyKey(String idempotencyKey) { + this.idempotencyKey = idempotencyKey; + return this; + } + + /** Queue priority of the execution's tasks, 0 (lowest, the default) to 99. */ + /** + * Sends a task to workers polling in a domain, for reusing workers that already run + * in one: {@code taskToDomain(Map.of("legacy_lookup", "team-a"))}. + */ + public StartBuilder taskToDomain(Map taskToDomain) { + this.taskToDomain = taskToDomain; + return this; + } + + public StartBuilder priority(int priority) { + if (priority < 0 || priority > 99) { + throw new IllegalArgumentException("priority must be between 0 and 99"); + } + this.priority = priority; + return this; + } + + public WorkflowHandle start(A input) { + WorkflowSpec spec = spec(method); + // a host of this process registers in the background: a start right after it waits + for (Workers host : conductor.started) { + host.awaitRegistered(spec, java.time.Duration.ofSeconds(30)); + } + Map request = new LinkedHashMap<>(); + request.put("name", spec.name); + request.put("version", spec.version); + request.put("input", WorkflowSpec.encodeInput(method, new Object[] {input})); + if (correlationId != null) { + request.put("correlationId", correlationId); + } + if (priority != null) { + request.put("priority", priority); + } + if (taskToDomain != null) { + request.put("taskToDomain", taskToDomain); + } + if (idempotencyKey != null) { + request.put("idempotencyKey", idempotencyKey); + request.put("idempotencyStrategy", "RETURN_EXISTING"); + } + String id = idempotencyKey == null + ? Http.post(conductor.client, "/workflow", request, String.class) + : postIdempotent(request); + return new WorkflowHandle<>(conductor, id, method.getGenericReturnType()); + } + + /** + * A start with an idempotency key can be repeated safely, so a server error or a lost + * connection is retried for up to two minutes; the server returns the execution the first + * attempt created if it got that far. A refusal (4xx) is not retried. A start without a key + * is never retried, since a repeat could create a second execution. + */ + private String postIdempotent(Map request) { + long deadline = System.currentTimeMillis() + java.time.Duration.ofMinutes(2).toMillis(); + while (true) { + try { + return Http.post(conductor.client, "/workflow", request, String.class); + } catch (RuntimeException e) { + boolean refused = e instanceof io.orkes.conductor.client.http.ApiException api + && api.getStatusCode() >= 400 && api.getStatusCode() < 500; + if (refused || System.currentTimeMillis() > deadline) { + throw e; + } + try { + Thread.sleep(1000); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + throw e; + } + } + } + } + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/EventCall.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/EventCall.java new file mode 100644 index 000000000..337408f74 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/EventCall.java @@ -0,0 +1,40 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import org.conductoross.conductor.sdk.internal.Command; +import org.conductoross.conductor.sdk.internal.Engine; +import org.conductoross.conductor.sdk.internal.Json; + +/** Publishes an event to a sink such as {@code conductor}, {@code sqs:queue} or {@code kafka:topic}. */ +public final class EventCall { + + private final Command command; + + EventCall(String ref) { + command = new Command(Command.Kind.EVENT, ref, ref); + command.explicitRef = ref; + } + + public EventCall to(String sink) { + command.fields.put("sink", sink); + return this; + } + + /** Fire and forget: a failure to publish shows in the UI but is not raised here. */ + public void send(Object payload) { + command.input.putAll(Json.encodeOutput(payload)); + command.fields.putIfAbsent("sink", "conductor"); + Engine.current().fire(command); + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/ExternalWait.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/ExternalWait.java new file mode 100644 index 000000000..f3357200b --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/ExternalWait.java @@ -0,0 +1,45 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.time.Duration; +import java.util.Optional; + +import org.conductoross.conductor.sdk.internal.Command; +import org.conductoross.conductor.sdk.internal.Conductors; +import org.conductoross.conductor.sdk.internal.Engine; + +/** + * Waits for an external system to call {@code POST /api/tasks/{workflowId}/{ref}/COMPLETED} with + * a JSON body, which becomes the result. + */ +public final class ExternalWait { + + private final Command command; + + ExternalWait(String ref, Class type) { + command = new Command(Command.Kind.WAIT, ref, ref); + command.explicitRef = ref; + command.resultType = type; + command.optional = true; + command.emptyIsEmpty = true; + } + + /** The posted body, or empty when nothing arrives within the timeout. */ + @SuppressWarnings("unchecked") + public Optional await(Duration timeout) { + command.input.put("duration", Conductors.duration(timeout)); + command.seconds = timeout.toSeconds(); + return (Optional) Engine.current().call(command); + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/Functions.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Functions.java new file mode 100644 index 000000000..77161743e --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Functions.java @@ -0,0 +1,82 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.io.Serializable; +import java.util.function.Predicate; + +/** + * Serializable functional interfaces for method references. A method reference such as {@code + * KitchenSinkTasks::task1} passed where one of these is expected can be resolved, through {@code + * SerializedLambda}, to the method it names, so the SDK reads the task name from the annotation + * and the parameter and return types from the method. Nothing depends on generic type arguments + * surviving compilation. + */ +public final class Functions { + + private Functions() {} + + public interface Fn0 extends Serializable { + R apply(T target); + } + + public interface Fn1 extends Serializable { + R apply(T target, A a); + } + + /** A task method of a stub, by bound reference, such as {@code tasks::labelItem}. */ + public interface TaskOf extends Serializable { + R apply(A a); + } + + public interface Fn2 extends Serializable { + R apply(T target, A a, B b); + } + + public interface Fn3 extends Serializable { + R apply(T target, A a, B b, C c); + } + + public interface Fn4 extends Serializable { + R apply(T target, A a, B b, C c, D d); + } + + public interface Proc0 extends Serializable { + void apply(T target); + } + + public interface Proc1 extends Serializable { + void apply(T target, A a); + } + + public interface Proc2 extends Serializable { + void apply(T target, A a, B b); + } + + public interface Proc3 extends Serializable { + void apply(T target, A a, B b, C c); + } + + public interface Proc4 extends Serializable { + void apply(T target, A a, B b, C c, D d); + } + + /** A condition given as a method reference to a boolean property, e.g. {@code JobStatus::done}. */ + public interface Pred extends Predicate, Serializable {} + + /** The body of a switch case. Serializable so that its compiled code can be located. */ + public interface CaseBody extends java.util.function.Supplier, Serializable {} + + /** A switch case body with no result. */ + public interface CaseAction extends Runnable, Serializable {} +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/Http.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Http.java new file mode 100644 index 000000000..1171629c6 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Http.java @@ -0,0 +1,67 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.util.List; +import java.util.Map; + +import com.netflix.conductor.client.http.ConductorClient; +import com.netflix.conductor.client.http.ConductorClientRequest; +import com.netflix.conductor.client.http.ConductorClientResponse; + +import com.fasterxml.jackson.core.type.TypeReference; + +/** Raw JSON requests, used where the client model classes would drop fields. */ +final class Http { + + private Http() {} + + static T post(ConductorClient client, String path, Object body, Class type) { + ConductorClientRequest req = + ConductorClientRequest.builder().method(ConductorClientRequest.Method.POST).path(path).body(body).build(); + ConductorClientResponse resp = client.execute(req, ref(type)); + return resp == null ? null : resp.getData(); + } + + static void put(ConductorClient client, String path, Object body) { + ConductorClientRequest req = + ConductorClientRequest.builder().method(ConductorClientRequest.Method.PUT).path(path).body(body).build(); + client.execute(req); + } + + static Map getMap(ConductorClient client, String path, Map query) { + ConductorClientRequest.Builder b = + ConductorClientRequest.builder().method(ConductorClientRequest.Method.GET).path(path); + if (query != null) { + query.forEach(b::addQueryParam); + } + ConductorClientResponse> resp = client.execute(b.build(), new TypeReference<>() {}); + return resp == null ? null : resp.getData(); + } + + static List> getList(ConductorClient client, String path) { + ConductorClientRequest req = + ConductorClientRequest.builder().method(ConductorClientRequest.Method.GET).path(path).build(); + ConductorClientResponse>> resp = client.execute(req, new TypeReference<>() {}); + return resp == null ? null : resp.getData(); + } + + private static TypeReference ref(Class type) { + return new TypeReference<>() { + @Override + public java.lang.reflect.Type getType() { + return type; + } + }; + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/HttpCall.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/HttpCall.java new file mode 100644 index 000000000..b61090d9a --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/HttpCall.java @@ -0,0 +1,100 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.conductoross.conductor.sdk.internal.Command; +import org.conductoross.conductor.sdk.internal.Engine; +import org.conductoross.conductor.sdk.internal.Json; + +import com.fasterxml.jackson.databind.JsonNode; + +/** An HTTP call executed by the server: no worker, no client library in workflow code. */ +public final class HttpCall { + + private final Command command; + private final Map request = new LinkedHashMap<>(); + private final Map headers = new LinkedHashMap<>(); + + HttpCall(String ref) { + command = new Command(Command.Kind.HTTP, ref, ref); + command.explicitRef = ref; + command.httpBody = true; + request.put("method", "GET"); + request.put("connectionTimeOut", 3000); + request.put("readTimeOut", 10000); + retries(3, java.time.Duration.ofSeconds(1)); + } + + /** Retries after a failure, with exponential backoff from the given delay; default 3 and 1s. */ + public HttpCall retries(int count, java.time.Duration delay) { + command.fields.put( + "taskDefinition", + org.conductoross.conductor.sdk.internal.Entries.retryingDefinition( + command.name, count, Math.max(1, delay.toSeconds()))); + return this; + } + + public HttpCall get(String uri) { + return method("GET", uri); + } + + public HttpCall post(String uri) { + return method("POST", uri); + } + + public HttpCall put(String uri) { + return method("PUT", uri); + } + + public HttpCall delete(String uri) { + return method("DELETE", uri); + } + + private HttpCall method(String method, String uri) { + request.put("method", method); + request.put("uri", uri); + return this; + } + + public HttpCall body(Object body) { + request.put("body", Json.plain(body)); + return this; + } + + public HttpCall header(String name, String value) { + headers.put(name, value); + return this; + } + + private Object run(Class type) { + if (!headers.isEmpty()) { + request.put("headers", headers); + } + command.input.put("http_request", request); + command.resultType = type; + return Engine.current().call(command); + } + + public T as(Class type) { + return type.cast(run(type)); + } + + /** The response body as a JSON tree. */ + public JsonNode asJson() { + Object body = run(Object.class); + return Json.MAPPER.valueToTree(body); + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/HumanCall.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/HumanCall.java new file mode 100644 index 000000000..9e0b36f81 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/HumanCall.java @@ -0,0 +1,66 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; + +import org.conductoross.conductor.sdk.internal.Command; +import org.conductoross.conductor.sdk.internal.Engine; +import org.conductoross.conductor.sdk.internal.Json; + +/** + * A HUMAN task: shown in the UI and the human task API, completed by a person (or any system) + * with {@code POST /api/tasks/{workflowId}/{ref}/COMPLETED}. + */ +public final class HumanCall { + + private final Command command; + + HumanCall(String ref) { + command = new Command(Command.Kind.HUMAN, ref, ref); + command.explicitRef = ref; + } + + public HumanCall assignee(String assignee) { + command.input.put("assignee", assignee); + return this; + } + + public HumanCall input(Map input) { + input.forEach((k, v) -> command.input.put(k, Json.plain(v))); + return this; + } + + /** Waits for the answer; empty when nobody answers within the timeout. */ + @SuppressWarnings("unchecked") + public Optional await(Class type, Duration timeout) { + Map def = new LinkedHashMap<>(); + def.put("name", command.name); + def.put("timeoutSeconds", Math.max(1, timeout.toSeconds())); + def.put("responseTimeoutSeconds", Math.max(1, timeout.toSeconds())); + // A timeout policy of RETRY with no retries makes a timeout a TIMED_OUT task the code + // sees as an empty result; TIME_OUT_WF would end the workflow instead. + def.put("timeoutPolicy", "RETRY"); + def.put("retryCount", 0); + def.put("ownerEmail", "native@conductor.local"); + command.fields.put("taskDefinition", def); + command.resultType = type; + command.optional = true; + command.timeoutIsEmpty = true; + command.seconds = timeout.toSeconds(); + return (Optional) Engine.current().call(command); + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/LlmCall.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/LlmCall.java new file mode 100644 index 000000000..3147e7472 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/LlmCall.java @@ -0,0 +1,63 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import org.conductoross.conductor.sdk.internal.Command; +import org.conductoross.conductor.sdk.internal.Engine; + +/** A chat completion executed by the server (LLM_CHAT_COMPLETE). Models are {@code provider/model}. */ +public final class LlmCall { + + private final Command command; + + LlmCall(String ref) { + command = new Command(Command.Kind.LLM, ref, ref); + command.explicitRef = ref; + retries(3, java.time.Duration.ofSeconds(1)); + } + + /** Retries after a failure, with exponential backoff from the given delay; default 3 and 1s. */ + public LlmCall retries(int count, java.time.Duration delay) { + command.fields.put( + "taskDefinition", + org.conductoross.conductor.sdk.internal.Entries.retryingDefinition( + command.name, count, Math.max(1, delay.toSeconds()))); + return this; + } + + public LlmCall model(String providerAndModel) { + int slash = providerAndModel.indexOf('/'); + if (slash > 0) { + command.input.put("llmProvider", providerAndModel.substring(0, slash)); + command.input.put("model", providerAndModel.substring(slash + 1)); + } else { + command.input.put("model", providerAndModel); + } + return this; + } + + public LlmCall system(String instructions) { + command.input.put("instructions", instructions); + return this; + } + + public LlmCall prompt(String prompt) { + command.input.put("userInput", prompt); + return this; + } + + public T as(Class type) { + command.resultType = type; + return type.cast(Engine.current().call(command)); + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/McpCall.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/McpCall.java new file mode 100644 index 000000000..7bf157a80 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/McpCall.java @@ -0,0 +1,113 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.conductoross.conductor.sdk.internal.Command; +import org.conductoross.conductor.sdk.internal.Engine; +import org.conductoross.conductor.sdk.internal.Entries; +import org.conductoross.conductor.sdk.internal.Json; + +/** + * Calls an MCP (Model Context Protocol) server from the Conductor server: no MCP client in the + * worker. {@code listTools()} is a LIST_MCP_TOOLS task and {@code call(...)} a CALL_MCP_TOOL task, + * each visible in the graph and retried like any task. + */ +public final class McpCall { + + /** A tool an MCP server offers. */ + public record McpTool(String name, String description, Object inputSchema) {} + + /** The result of a tool call; {@code isError} is the tool's own error flag. */ + public record McpResult(List> content, Boolean isError) { + + /** The text of all text content items, joined by newlines. */ + public String text() { + StringBuilder sb = new StringBuilder(); + if (content != null) { + for (Map item : content) { + Object text = item.get("text"); + if (text != null) { + if (sb.length() > 0) { + sb.append('\n'); + } + sb.append(text); + } + } + } + return sb.toString(); + } + } + + private final String ref; + private String server; + private final Map headers = new LinkedHashMap<>(); + private int retries = 3; + private Duration retryDelay = Duration.ofSeconds(1); + + McpCall(String ref) { + this.ref = ref; + } + + /** The MCP server's streamable HTTP or SSE endpoint, e.g. {@code https://tools.example.com/mcp}. */ + public McpCall server(String url) { + this.server = url; + return this; + } + + public McpCall header(String name, String value) { + headers.put(name, value); + return this; + } + + public McpCall retries(int count, Duration delay) { + this.retries = count; + this.retryDelay = delay; + return this; + } + + private Command command(Command.Kind kind, String type) { + Command c = new Command(kind, ref, ref); + c.explicitRef = ref; + c.input.put("mcpServer", server); + if (!headers.isEmpty()) { + c.input.put("headers", headers); + } + c.fields.put("taskDefinition", Entries.retryingDefinition(ref, retries, Math.max(1, retryDelay.toSeconds()))); + return c; + } + + /** The tools the server offers. */ + @SuppressWarnings("unchecked") + public List listTools() { + Command c = command(Command.Kind.MCP_LIST, "LIST_MCP_TOOLS"); + c.outputKey = "tools"; + c.resultType = Json.MAPPER.getTypeFactory().constructCollectionType(List.class, McpTool.class); + return (List) Engine.current().call(c); + } + + /** Calls a tool with arguments. */ + public McpResult call(String tool, Map arguments) { + Command c = command(Command.Kind.MCP_CALL, "CALL_MCP_TOOL"); + c.input.put("method", tool); + Map args = new LinkedHashMap<>(); + arguments.forEach((k, v) -> args.put(k, Json.plain(v))); + c.input.put("arguments", args); + c.resultType = McpResult.class; + return (McpResult) Engine.current().call(c); + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/NonDeterminismException.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/NonDeterminismException.java new file mode 100644 index 000000000..0f7d914ef --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/NonDeterminismException.java @@ -0,0 +1,25 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +/** + * Raised when re-running workflow code against an execution's recorded tasks does not reach the + * same calls the original run made: the code changed in a way that conflicts with an execution in + * flight. The continuation being processed fails terminally with this message. + */ +public class NonDeterminismException extends RuntimeException { + + public NonDeterminismException(String message) { + super(message); + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/Promise.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Promise.java new file mode 100644 index 000000000..465538e7f --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Promise.java @@ -0,0 +1,22 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +/** The result of an {@link Conductor#async} lane. {@link #get()} waits for it. */ +public interface Promise { + + /** The lane's result; waits for the lane, and rethrows what the lane threw. */ + T get(); + + boolean isDone(); +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/Query.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Query.java new file mode 100644 index 000000000..7e49e9218 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Query.java @@ -0,0 +1,27 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** A read-only method a caller can invoke on a running execution; computed on the worker from the current variables. */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Query { + + /** Handler name; defaults to the method name. */ + String value() default ""; +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/Registration.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Registration.java new file mode 100644 index 000000000..b06fc8df4 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Registration.java @@ -0,0 +1,240 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.conductoross.conductor.sdk.internal.WorkflowSpec; + +import com.netflix.conductor.client.http.ConductorClient; +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +/** Registers skeleton workflow definitions and task definitions from annotations. */ +final class Registration { + + /** The owner of task definitions this SDK created; any other owner's are left alone. */ + private static final String NATIVE_OWNER = "native@conductor.local"; + + private Registration() {} + + static Map workerMethods(Class type) { + Map methods = new LinkedHashMap<>(); + for (Class c = type; c != null && c != Object.class; c = c.getSuperclass()) { + for (Method m : c.getDeclaredMethods()) { + WorkerTask wt = m.getAnnotation(WorkerTask.class); + if (wt != null && !methods.containsKey(wt.value())) { + m.setAccessible(true); + methods.put(wt.value(), m); + } + } + } + return methods; + } + + static void register(ConductorClient client, Collection specs, List taskObjects, + long continuationTimeoutSeconds) { + register(client, specs, taskObjects, continuationTimeoutSeconds, true); + } + + static void register(ConductorClient client, Collection specs, List taskObjects, + long continuationTimeoutSeconds, boolean discover) { + List> taskDefs = new ArrayList<>(); + for (Object o : taskObjects) { + for (Map.Entry e : workerMethods(o.getClass()).entrySet()) { + WorkerTask wt = e.getValue().getAnnotation(WorkerTask.class); + Map def = new LinkedHashMap<>(); + def.put("name", e.getKey()); + // Conductor's default of three retries, with exponential backoff from one second + def.put("retryCount", wt.retryCount() >= 0 ? wt.retryCount() : 3); + def.put("retryLogic", "EXPONENTIAL_BACKOFF"); + def.put("retryDelaySeconds", wt.retryDelaySeconds() >= 0 ? wt.retryDelaySeconds() : 1); + def.put("timeoutSeconds", 0); + def.put("responseTimeoutSeconds", wt.responseTimeoutSeconds() > 0 ? wt.responseTimeoutSeconds() : 120); + // a worker that dies holding a task: the response timeout reschedules it + def.put("timeoutPolicy", "RETRY"); + def.put("ownerEmail", NATIVE_OWNER); + taskDefs.add(def); + } + } + if (!taskDefs.isEmpty()) { + // a task another team already defined keeps its definition: its retries and + // timeouts are theirs, and this process just becomes one more worker of it + Map owners = new LinkedHashMap<>(); + for (Map existing : Http.getList(client, "/metadata/taskdefs")) { + owners.put(String.valueOf(existing.get("name")), existing.get("ownerEmail")); + } + taskDefs.removeIf(d -> owners.containsKey(d.get("name")) && !NATIVE_OWNER.equals(owners.get(d.get("name")))); + } + List> workflowDefs = new ArrayList<>(); + for (WorkflowSpec spec : specs) { + workflowDefs.add(skeleton(spec, continuationTimeoutSeconds, discover)); + } + if (!taskDefs.isEmpty()) { + Http.post(client, "/metadata/taskdefs", taskDefs, String.class); + } + if (!workflowDefs.isEmpty()) { + Http.put(client, "/metadata/workflow", workflowDefs); + } + registerSchedules(client, specs); + } + + /** Creates or updates a scheduler entry for each {@code @Schedule} on a workflow method. */ + @SuppressWarnings("unchecked") + static void registerSchedules(ConductorClient client, Collection specs) { + for (WorkflowSpec spec : specs) { + int n = 0; + for (org.conductoross.conductor.sdk.Schedule s : spec.schedules) { + n++; + String name = !s.name().isBlank() ? s.name() : spec.name + "_schedule" + (n > 1 ? "_" + n : ""); + Map start = new LinkedHashMap<>(); + start.put("name", spec.name); + start.put("version", spec.version); + try { + start.put("input", org.conductoross.conductor.sdk.internal.Json.MAPPER.readValue(s.input(), Map.class)); + } catch (Exception e) { + throw new IllegalArgumentException("@Schedule input of " + spec.name + " is not a JSON object: " + s.input(), e); + } + Map schedule = new LinkedHashMap<>(); + schedule.put("name", name); + schedule.put("cronExpression", s.cron()); + schedule.put("zoneId", s.zone()); + schedule.put("paused", s.paused()); + schedule.put("description", s.description().isBlank() ? "Schedule of native workflow " + spec.name : s.description()); + schedule.put("startWorkflowRequest", start); + try { + Http.post(client, "/scheduler/schedules", schedule, Map.class); + } catch (RuntimeException e) { + org.slf4j.LoggerFactory.getLogger(Registration.class) + .warn("Could not register schedule {} (is conductor.scheduler.enabled=true?): {}", name, e.toString()); + } + } + } + } + + /** + * The registered definition: no tasks, and the native metadata the engine needs to run the + * first continuation of the workflow method (and the handler lane, when the class has + * handlers). The execution's own copy grows from here, one fragment per continuation. + */ + static Map skeleton(WorkflowSpec spec, long continuationTimeoutSeconds) { + return skeleton(spec, continuationTimeoutSeconds, true); + } + + static Map skeleton(WorkflowSpec spec, long continuationTimeoutSeconds, boolean discover) { + Map def = new LinkedHashMap<>(); + def.put("name", spec.name); + def.put("version", spec.version); + def.put("description", spec.description.isBlank() ? "Native workflow " + spec.type.getSimpleName() + "." + spec.method.getName() : spec.description); + def.put("schemaVersion", 2); + def.put("ownerEmail", spec.ownerEmail); + if (spec.timeoutSeconds > 0) { + def.put("timeoutSeconds", spec.timeoutSeconds); + def.put("timeoutPolicy", "TIME_OUT_WF"); + } + if (!spec.failureWorkflow.isBlank()) { + def.put("failureWorkflow", spec.failureWorkflow); + if (spec.failureWorkflowVersion > 0) { + def.put("failureWorkflowVersion", spec.failureWorkflowVersion); + } + } + Map nativeMeta = new LinkedHashMap<>(); + nativeMeta.put("sdk", "java"); + nativeMeta.put("protocol", 2); + nativeMeta.put("class", spec.type.getName()); + nativeMeta.put("method", spec.method.getName()); + nativeMeta.put("codeType", spec.codeTaskName()); + // how long the server waits for a continuation it handed to a worker before handing it + // to another (the lease) + nativeMeta.put("continuationTimeoutSeconds", continuationTimeoutSeconds); + nativeMeta.put("handlers", spec.hasHandlers()); + nativeMeta.put("signals", new ArrayList<>(spec.signals.keySet())); + nativeMeta.put("updates", new ArrayList<>(spec.updates.keySet())); + nativeMeta.put("queries", new ArrayList<>(spec.queries.keySet())); + // The graph discovered from the code, for the definition view and inventory. An + // execution's own copy of the definition starts empty and grows with what the code calls. + List> discovered; + try { + discovered = discover ? org.conductoross.conductor.sdk.internal.Replayer.discover(spec) : List.of(); + nativeMeta.put("discovered", discover); + } catch (RuntimeException e) { + discovered = List.of(); + nativeMeta.put("discovered", false); + nativeMeta.put("discoveryError", e.getMessage()); + org.slf4j.LoggerFactory.getLogger(Registration.class) + .warn("Could not discover the graph of workflow {}: {}", spec.name, e.getMessage()); + } + inlineTaskDefinitions(discovered); + def.put("metadata", Map.of("native", nativeMeta)); + def.put("inputParameters", inputParameters(spec)); + def.put("tasks", discovered); + return def; + } + + /** The workflow method's parameter names (a single record's components), for the definition. */ + static List inputParameters(WorkflowSpec spec) { + java.lang.reflect.Method m = spec.method; + if (m.getParameterCount() == 0) { + return List.of(); + } + if (m.getParameterCount() == 1 && !org.conductoross.conductor.sdk.internal.Json.isWrapped(m.getGenericParameterTypes()[0])) { + Class type = m.getParameterTypes()[0]; + if (type.isRecord()) { + List names = new ArrayList<>(); + for (var c : type.getRecordComponents()) { + names.add(c.getName()); + } + return names; + } + return List.of(); + } + return List.of(org.conductoross.conductor.sdk.internal.MethodRefs.parameterNames(m)); + } + + /** Discovered SIMPLE tasks carry an inline definition, so registration validates without one. */ + @SuppressWarnings("unchecked") + private static void inlineTaskDefinitions(List> entries) { + for (Map e : entries) { + if ("SIMPLE".equals(e.get("type")) && !e.containsKey("taskDefinition")) { + Map td = new LinkedHashMap<>(); + td.put("name", e.get("name")); + td.put("retryCount", 3); + td.put("timeoutSeconds", 0); + td.put("responseTimeoutSeconds", 120); + td.put("timeoutPolicy", "RETRY"); + td.put("ownerEmail", "native@conductor.local"); + e.put("taskDefinition", td); + } + if (e.get("forkTasks") instanceof List branches) { + for (Object b : branches) { + inlineTaskDefinitions((List>) b); + } + } + if (e.get("decisionCases") instanceof Map dc) { + for (Object v : dc.values()) { + inlineTaskDefinitions((List>) v); + } + } + if (e.get("defaultCase") instanceof List d) { + inlineTaskDefinitions((List>) d); + } + if (e.get("loopOver") instanceof List l) { + inlineTaskDefinitions((List>) l); + } + } + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/Schedule.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Schedule.java new file mode 100644 index 000000000..bff89f3b1 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Schedule.java @@ -0,0 +1,53 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Runs a {@link Workflow} method on a schedule. Registered with the Conductor scheduler when the + * host starts, and updated in place on every start, so the annotation is the source of truth. + * Repeat it for several schedules. + * + *

{@code
+ * @Schedule(cron = "0 0 9 * * MON-FRI", zone = "America/New_York", input = "{\"region\": \"us\"}")
+ * @Workflow(name = "daily_report")
+ * public Report report(ReportRequest request) { ... }
+ * }
+ */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@Repeatable(Schedules.class) +public @interface Schedule { + + /** Spring cron expression with six fields, seconds first: {@code "0 0 9 * * MON-FRI"}. */ + String cron(); + + /** Time zone the expression is evaluated in. */ + String zone() default "UTC"; + + /** Schedule name; defaults to {@code _schedule}, then {@code _2}, {@code _3}. */ + String name() default ""; + + /** Workflow input for each run, as JSON. */ + String input() default "{}"; + + /** Register the schedule paused. */ + boolean paused() default false; + + String description() default ""; +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/Schedules.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Schedules.java new file mode 100644 index 000000000..30ae8b5e8 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Schedules.java @@ -0,0 +1,25 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** Container for repeated {@link Schedule} annotations. */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Schedules { + Schedule[] value(); +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/Signal.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Signal.java new file mode 100644 index 000000000..de25924b8 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Signal.java @@ -0,0 +1,27 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** A method that handles a signal sent to a running execution. Runs between pauses of the workflow code, never concurrently with it, and may change variables. */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Signal { + + /** Handler name; defaults to the method name. */ + String value() default ""; +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/TaskCall.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/TaskCall.java new file mode 100644 index 000000000..50d48f659 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/TaskCall.java @@ -0,0 +1,60 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.util.Map; + +import org.conductoross.conductor.sdk.internal.Command; +import org.conductoross.conductor.sdk.internal.Engine; +import org.conductoross.conductor.sdk.internal.Json; + +/** A task called by name, for task names known only at runtime or owned by another team. */ +public final class TaskCall { + + private final Command command; + + TaskCall(String name) { + this.command = new Command(Command.Kind.SIMPLE, name, name); + } + + public TaskCall ref(String taskReferenceName) { + command.explicitRef = taskReferenceName; + return this; + } + + public TaskCall input(String key, Object value) { + command.input.put(key, Json.plain(value)); + return this; + } + + public TaskCall input(Map input) { + input.forEach(this::input); + return this; + } + + public T as(Class type) { + command.resultType = type; + return type.cast(Engine.current().call(command)); + } + + @SuppressWarnings("unchecked") + public Map asMap() { + command.resultType = Map.class; + return (Map) Engine.current().call(command); + } + + public void run() { + command.resultType = Void.class; + Engine.current().call(command); + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/TaskFailure.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/TaskFailure.java new file mode 100644 index 000000000..2da2b3c2a --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/TaskFailure.java @@ -0,0 +1,44 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +/** + * Thrown at the call site in workflow code when a task the code waited on failed and its retries + * are exhausted. Catch it to compensate or continue; let it propagate and the workflow fails with + * its reason. The task shows FAILED in the UI either way. + */ +public class TaskFailure extends RuntimeException { + + private final String taskReferenceName; + private final String status; + + public TaskFailure(String taskReferenceName, String status, String reason) { + super( + "task " + + taskReferenceName + + " " + + status + + (reason == null || reason.isBlank() ? "" : ": " + reason)); + this.taskReferenceName = taskReferenceName; + this.status = status; + } + + public String getTaskReferenceName() { + return taskReferenceName; + } + + /** The task's terminal status: FAILED, FAILED_WITH_TERMINAL_ERROR, TIMED_OUT or CANCELED. */ + public String getStatus() { + return status; + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/Update.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Update.java new file mode 100644 index 000000000..944a842e9 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Update.java @@ -0,0 +1,27 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** A signal whose return value is sent back to the caller. */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Update { + + /** Handler name; defaults to the method name. */ + String value() default ""; +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/Variable.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Variable.java new file mode 100644 index 000000000..d7da20486 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Variable.java @@ -0,0 +1,31 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * A field of a workflow class that is a workflow variable: written to {@code workflow.variables} + * at every continuation, visible in the UI and the API, and shared with signal, update and query + * handlers. Other fields are ordinary fields and are never persisted. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Variable { + + /** Variable name; defaults to the field name. */ + String value() default ""; +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/Workers.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Workers.java new file mode 100644 index 000000000..f0f54b0d2 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Workers.java @@ -0,0 +1,587 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.lang.reflect.Method; +import java.net.InetAddress; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; + +import org.conductoross.conductor.sdk.internal.Execution; +import org.conductoross.conductor.sdk.internal.Json; +import org.conductoross.conductor.sdk.internal.Replayer; +import org.conductoross.conductor.sdk.internal.WorkflowSpec; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.netflix.conductor.client.automator.TaskRunnerConfigurer; +import com.netflix.conductor.client.http.TaskClient; +import com.netflix.conductor.client.worker.Worker; +import com.netflix.conductor.common.metadata.tasks.Task; +import com.netflix.conductor.common.metadata.tasks.TaskContinuation; +import com.netflix.conductor.common.metadata.tasks.TaskResult; +import com.netflix.conductor.sdk.workflow.executor.task.AnnotatedWorker; + +/** + * Hosts workflow classes and task classes in this process. + * + *

{@link #start()} registers, from the annotations, a skeleton definition for each workflow and + * a task definition for each task, then starts polling: one poller per {@code @WorkerTask} method, + * and one per workflow for its continuations (the workflow's code type, polled like any task + * type). A continuation arrives as the task the code paused on, carrying its continuation marker; + * it is processed by re-running the workflow method against the execution's recorded tasks, so any + * host of the same code can process any continuation. Continuations of one execution are processed + * one at a time, and completed through the ordinary task update. + */ +public final class Workers { + + private static final Logger LOGGER = LoggerFactory.getLogger(Workers.class); + + private final Conductor conductor; + private final TaskClient taskClient; + private final Map specsByCodeType = new LinkedHashMap<>(); + private final List taskObjects = new ArrayList<>(); + private final List definedTaskObjects = new ArrayList<>(); + private String workerId; + private String buildId; + private boolean devMode; + private boolean discovery = true; + private double timeScale = 20; + private int threads = 8; + private java.time.Duration continuationTimeout = java.time.Duration.ofSeconds(30); + private TaskRunnerConfigurer taskRunner; + private ExecutorService codeExecutor; + private final List pollers = new ArrayList<>(); + private volatile boolean running; + private volatile boolean registered; + + /** + * Waits between attempts while the server cannot be reached: 1, 2, 4... seconds, at most a + * minute, each shortened by up to half at random so that many hosts do not retry in step. + */ + static final Backoff OUTAGE = Backoff.every(java.time.Duration.ofSeconds(1)).factor(2).max(java.time.Duration.ofMinutes(1)); + + Workers(Conductor conductor) { + this.conductor = conductor; + this.taskClient = new TaskClient(conductor.client()); + // Identifies this host in poll data and on the tasks it runs. Set CONDUCTOR_WORKER_ID when + // several hosts share a machine, so that they can be told apart. + String id = System.getenv("CONDUCTOR_WORKER_ID"); + if (id == null || id.isBlank()) { + try { + id = InetAddress.getLocalHost().getHostName(); + } catch (Exception e) { + id = "native-worker"; + } + } + this.workerId = id; + } + + public Workers workerId(String workerId) { + this.workerId = workerId; + return this; + } + + /** A task domain this host also polls for continuations; see {@code taskToDomain} on a start. */ + public Workers buildId(String buildId) { + this.buildId = buildId; + return this; + } + + /** + * Development mode: generous continuation timeouts (for breakpoints) and timers divided by the + * time scale, when the server has {@code conductor.app.nativeWorkflow.waitTimeScaleEnabled}. + */ + public Workers devMode(boolean devMode) { + this.devMode = devMode; + return this; + } + + public Workers timeScale(double timeScale) { + this.timeScale = timeScale; + return this; + } + + /** + * How long the server waits for a continuation it handed to a worker before retrying it + * elsewhere (the continuation lease); default 30 seconds. It bounds how long an + * execution stalls when a poll response is lost to a network failure or the worker dies while + * processing. It must exceed the longest replay of an execution. Dev mode uses an hour, so a + * breakpoint does not trigger a retry. + */ + public Workers continuationTimeout(java.time.Duration timeout) { + this.continuationTimeout = timeout; + return this; + } + + /** + * Whether the registered definition carries the graph read from the compiled workflow code. + * On by default. Reading runs nothing; the untaken cases of a {@code switchOn} are always read. + */ + public Workers discovery(boolean discovery) { + this.discovery = discovery; + return this; + } + + public Workers threads(int threads) { + this.threads = threads; + return this; + } + + public Workers workflows(Class... types) { + for (Class t : types) { + for (WorkflowSpec spec : WorkflowSpec.of(t)) { + specsByCodeType.put(spec.codeTaskName(), spec); + } + } + return this; + } + + /** A workflow class whose instances need constructor arguments. */ + @SuppressWarnings("unchecked") + public Workers workflow(Class type, Supplier factory) { + for (WorkflowSpec spec : WorkflowSpec.of(type)) { + spec.factory((Supplier) factory); + specsByCodeType.put(spec.codeTaskName(), spec); + } + return this; + } + + /** Objects with {@code @WorkerTask} methods. */ + public Workers tasks(Object... objects) { + taskObjects.addAll(List.of(objects)); + return this; + } + + /** + * Objects with {@code @WorkerTask} methods that another executor polls (Spring's worker + * auto-configuration, for one): their task definitions are registered on start, and no poller + * is started for them here. + */ + public Workers taskDefinitions(Object... objects) { + definedTaskObjects.addAll(List.of(objects)); + return this; + } + + public String workerId() { + return workerId; + } + + /** + * Starts hosting and returns at once. The definitions are registered in the background, + * retried with backoff for as long as the server cannot be reached, and polling starts now: + * a server that is down, even for hours, never fails this, it only delays the work and logs + * an error for each failed attempt. A workflow class that cannot be created fails here, since + * that is a fault in the code that no retry fixes. + */ + public Workers start() { + // fail now, not on the first continuation, when a workflow class cannot be created + specsByCodeType.values().forEach(WorkflowSpec::newInstance); + for (WorkflowSpec spec : specsByCodeType.values()) { + for (String site : org.conductoross.conductor.sdk.internal.CodeReader.threadSleeps(spec.method)) { + LOGGER.warn("Workflow {} calls Thread.sleep at {}: workflow code runs again each time it continues," + + " so the sleep is repeated on every replay and holds a worker thread. Use" + + " Conductor.sleep(Duration) for a durable wait.", spec.name, site); + } + } + running = true; + Thread registrar = Thread.ofVirtual().name("conductor-register").start(this::registerUntilDone); + pollers.add(registrar); + List workers = new ArrayList<>(); + for (Object o : taskObjects) { + for (Map.Entry e : Registration.workerMethods(o.getClass()).entrySet()) { + workers.add(new AnnotatedWorker(e.getKey(), e.getValue(), o)); + } + } + if (!workers.isEmpty()) { + taskRunner = + new TaskRunnerConfigurer.Builder(taskClient, workers) + .withThreadCount(Math.max(threads, workers.size())) + .withTaskPollTimeout(100) + .build(); + taskRunner.init(); + } + codeExecutor = Executors.newVirtualThreadPerTaskExecutor(); + for (String codeType : specsByCodeType.keySet()) { + // the shared queue, and the build's domain when one is set: an execution started with + // task domains for it prefers this build and falls back when none of it is polling + List domains = new ArrayList<>(); + if (buildId != null && !buildId.isBlank()) { + domains.add(buildId); + } + domains.add(null); + for (String domain : domains) { + Thread t = Thread.ofVirtual().name("conductor-code-" + codeType + "-" + domain).start(() -> poll(codeType, domain)); + pollers.add(t); + } + } + LOGGER.info("Hosting workflows {} and {} tasks as {}", specsByCodeType.keySet(), workers.size(), workerId); + return this; + } + + public void shutdown() { + running = false; + pollers.forEach(Thread::interrupt); + if (taskRunner != null) { + taskRunner.shutdown(); + } + if (codeExecutor != null) { + codeExecutor.shutdownNow(); + } + } + + private void poll(String codeType, String domain) { + int failures = 0; + while (running) { + try { + List tasks = taskClient.batchPollTasksInDomain(codeType, domain, workerId, 10, 500); + failures = 0; + if (tasks == null || tasks.isEmpty()) { + Thread.sleep(50); + continue; + } + for (Task task : tasks) { + codeExecutor.submit(() -> process(codeType, task)); + } + } catch (InterruptedException e) { + return; + } catch (Exception e) { + if (running) { + failures++; + java.time.Duration wait = OUTAGE.delay(failures); + LOGGER.error("Polling {} failed ({} in a row), retrying in about {}s: {}", + codeType, failures, wait.toSeconds(), e.toString()); + if (!pause(wait)) { + return; + } + } + } + } + } + + /** + * Registers the definitions, retrying for up to two minutes: registration is an idempotent + * upsert, and a worker starting while the server restarts, or while other workers register + * the same definitions, should wait rather than exit. + */ + /** + * Waits, up to {@code max}, for this host to register its definitions when it hosts + * {@code spec} and has not registered yet; returns at once otherwise. A start in the same + * process right after {@link #start()} would otherwise find no definition. + */ + void awaitRegistered(WorkflowSpec spec, java.time.Duration max) { + boolean hosted = specsByCodeType.values().stream() + .anyMatch(s -> s.name.equals(spec.name) && s.version == spec.version); + long until = System.nanoTime() + max.toNanos(); + while (hosted && running && !registered && System.nanoTime() < until) { + if (!pause(java.time.Duration.ofMillis(50))) { + return; + } + } + } + + /** Whether the definitions have been registered since {@link #start()}. */ + public boolean registered() { + return registered; + } + + private void registerUntilDone() { + for (int attempt = 1; running; attempt++) { + try { + List defined = new ArrayList<>(taskObjects); + defined.addAll(definedTaskObjects); + Registration.register(conductor.client(), specsByCodeType.values(), defined, + devMode ? 3600 : Math.max(1, continuationTimeout.toSeconds()), discovery); + registered = true; + LOGGER.info("Registered the definitions of {} after {} attempt(s)", specsByCodeType.keySet(), attempt); + return; + } catch (RuntimeException e) { + java.time.Duration wait = OUTAGE.delay(attempt); + LOGGER.error("Registering the definitions of {} failed (attempt {}), retrying in about {}s: {}", + specsByCodeType.keySet(), attempt, wait.toSeconds(), e.toString()); + if (!pause(wait)) { + return; + } + } + } + } + + /** Sleeps for between half and all of {@code wait}; false when interrupted by shutdown. */ + private boolean pause(java.time.Duration wait) { + long ms = wait.toMillis(); + try { + Thread.sleep(ms / 2 + java.util.concurrent.ThreadLocalRandom.current().nextLong(ms / 2 + 1)); + return running; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + + /** How long an update's reply is kept for its caller; the caller waits at most 3 minutes. */ + static final long REPLY_TTL_MILLIS = java.time.Duration.ofMinutes(10).toMillis(); + + /** At most this many replies are kept, newest first, whatever their age. */ + static final int REPLY_LIMIT = 500; + + private static Map reply(String key, Object value) { + Map r = new LinkedHashMap<>(); + r.put(key, value); + r.put("at", System.currentTimeMillis()); + return r; + } + + /** + * Drops replies older than {@link #REPLY_TTL_MILLIS} and keeps at most {@link #REPLY_LIMIT}, + * so an execution that serves many updates does not grow its variables without bound. + * Replies without a timestamp, from older workers, count as expired. + */ + static Map pruneReplies(Map replies, long now) { + List> fresh = new ArrayList<>(); + for (Map.Entry e : replies.entrySet()) { + if (e.getValue() instanceof Map r && r.get("at") instanceof Number at + && now - at.longValue() <= REPLY_TTL_MILLIS) { + fresh.add(e); + } + } + int from = Math.max(0, fresh.size() - REPLY_LIMIT); + Map kept = new LinkedHashMap<>(); + for (Map.Entry e : fresh.subList(from, fresh.size())) { + kept.put(e.getKey(), e.getValue()); + } + return kept; + } + + /** How many handled message ids an execution remembers for de-duplication. */ + static final int SEEN_LIMIT = 500; + + /** Processes one continuation (or handler run) of an execution. */ + void process(String codeType, Task task) { + String snapshot = "(not fetched)"; + try { + WorkflowSpec spec = specsByCodeType.get(codeType); + TaskContinuation marker = task.getContinuation(); + if (marker == null) { + throw new IllegalStateException("task " + task.getTaskId() + " carries no continuation"); + } + Execution exec = fetch(task.getWorkflowInstanceId()); + snapshot = describe(exec, marker); + if ("handlers".equals(marker.getLane())) { + processHandlers(codeType, spec, exec, task); + return; + } + Map extra = null; + if (devMode && "main".equals(marker.getLane()) && marker.getN() == 1) { + extra = Map.of("__timeScale", timeScale); + } + Replayer.Outcome outcome = + new Replayer(spec, spec.newInstance(), exec) + .process(marker.getLane(), marker.getN(), extra); + logLaneError(task, marker.getLane(), outcome.output); + complete(codeType, task, TaskResult.Status.COMPLETED, outcome.output, null); + } catch (NonDeterminismException e) { + LOGGER.error("Execution {} diverged from its code: {}", task.getWorkflowInstanceId(), e.getMessage()); + LOGGER.error("Execution {} as replayed: {}", task.getWorkflowInstanceId(), snapshot); + complete(codeType, task, TaskResult.Status.FAILED_WITH_TERMINAL_ERROR, Map.of(), e.getMessage()); + } catch (Exception e) { + LOGGER.error("Processing {} of execution {} failed", task.getReferenceTaskName(), task.getWorkflowInstanceId(), e); + complete(codeType, task, TaskResult.Status.FAILED, Map.of(), e.toString()); + } + } + + /** + * A lane started with {@code async} that ended with an exception fails the workflow only when + * the code waits for it, with {@code join} or {@code get}; one nothing waits for would leave no + * trace in the execution's status. Its exception goes to the log of the task the lane ran last, + * where the execution page shows it. + */ + @SuppressWarnings("unchecked") + private void logLaneError(Task task, String lane, Map output) { + if ("main".equals(lane) || !Boolean.TRUE.equals(output.get("done")) || !(output.get("error") instanceof Map)) { + return; + } + Map error = (Map) output.get("error"); + String message = "Lane " + lane + " ended with " + error.get("message") + "." + + " It fails the workflow only if the code waits for this lane with join or get."; + try { + taskClient.logMessageForTask(task.getTaskId(), message); + } catch (RuntimeException e) { + LOGGER.warn("Could not log the error of lane {} of execution {}: {}", lane, task.getWorkflowInstanceId(), e.toString()); + } + LOGGER.warn("Execution {}: {}", task.getWorkflowInstanceId(), message); + } + + /** + * Runs signal, update and query handlers for the messages the server claimed for this handler + * run, on an instance restored from the current variables; then names the condition waits + * whose condition now holds, which the server completes with the same update. + */ + @SuppressWarnings("unchecked") + private void processHandlers(String codeType, WorkflowSpec spec, Execution exec, Task task) { + List> messages = + (List>) task.getInputData().getOrDefault("messages", List.of()); + Object instance = spec.newInstance(); + spec.restoreVariables(instance, exec.variables); + Map replies = new LinkedHashMap<>(exec.replies()); + List seen = exec.seen(); + for (Map message : messages) { + Map payload = (Map) message.getOrDefault("payload", Map.of()); + String kind = String.valueOf(payload.get("kind")); + String name = String.valueOf(payload.get("name")); + // the sender's id survives a retried send; the queue's id does not + String id = payload.get("id") != null ? String.valueOf(payload.get("id")) : String.valueOf(message.get("id")); + if (seen.contains(id)) { + LOGGER.debug("message {} of execution {} was already handled", id, exec.workflowId); + continue; + } + seen.add(id); + // a query (sent as a message by older clients) must not change the execution: + // whatever its handler does to the instance is undone + Map beforeQuery = "query".equals(kind) ? spec.captureVariables(instance) : null; + try { + Method handler = spec.handler(kind, name); + Object value = Replayer.invokeHandler(instance, handler, payload.get("args")); + if (!"signal".equals(kind)) { + replies.put(id, reply("value", Json.plain(value) == null ? "" : Json.plain(value))); + } + } catch (RuntimeException e) { + LOGGER.warn("handler {} {} of execution {} failed: {}", kind, name, exec.workflowId, e.toString()); + if (!"signal".equals(kind)) { + replies.put(id, reply("error", e.toString())); + } + } finally { + if (beforeQuery != null) { + spec.restoreVariables(instance, beforeQuery); + } + } + } + Map vars = spec.captureVariables(instance); + TaskContinuation marker = task.getContinuation(); + Map output = new LinkedHashMap<>(); + output.put("protocol", 2); + output.put("n", marker.getN()); + output.put("fragment", List.of()); + output.put("variables", vars); + // what this handler started from: the server applies only what the handler changed, + // and runs it again if another completion changed the same variables meanwhile + output.put("resumedWith", spec.captureVariablesOf(exec.variables)); + output.put("replies", pruneReplies(replies, System.currentTimeMillis())); + // the ids of recent messages, so a message queued twice by a retried send applies once + output.put("seen", seen.size() > SEEN_LIMIT ? new ArrayList<>(seen.subList(seen.size() - SEEN_LIMIT, seen.size())) : seen); + output.put("releases", releases(spec, exec, vars)); + output.put("done", false); + complete(codeType, task, TaskResult.Status.COMPLETED, output, null); + } + + /** The condition waits whose condition holds over the variables the handlers produced. */ + private List> releases(WorkflowSpec spec, Execution exec, Map vars) { + boolean waiting = exec.tasks.stream().anyMatch(t -> t.ref.startsWith("condition") && "IN_PROGRESS".equals(t.status)); + if (!waiting) { + return List.of(); + } + List> releases = new ArrayList<>(); + Replayer.Outcome outcome = new Replayer(spec, spec.newInstance(), exec).process(null, 0, null); + spec.restoreVariables(outcome.instance, vars); + for (Map.Entry c : outcome.pendingConditions.entrySet()) { + if (c.getValue().getAsBoolean()) { + Map release = new LinkedHashMap<>(); + release.put("ref", c.getKey()); + release.put("output", Map.of("satisfied", true)); + releases.add(release); + } + } + return releases; + } + + /** What a replay saw, for the log when the code diverges: status, tasks, markers, replay order. */ + private static String describe(Execution exec, TaskContinuation active) { + StringBuilder sb = new StringBuilder(); + sb.append("status=").append(exec.status).append(" active=").append(active.getLane()).append('#').append(active.getN()); + sb.append(" replay="); + for (Execution.Marker m : exec.segments()) { + sb.append(m.lane).append('#').append(m.n).append("@").append(m.step).append(m.done ? "!" : "").append(' '); + } + sb.append("tasks="); + for (Execution.TaskView t : exec.tasks) { + sb.append(t.seq).append(':').append(t.ref).append('=').append(t.status); + if (t.marker != null) { + sb.append('[').append(t.marker.lane).append('#').append(t.marker.n).append(' ').append(t.marker.state).append('@').append(t.marker.step).append(']'); + } + sb.append(' '); + } + sb.append("entries=").append(exec.entries.keySet()); + return sb.toString(); + } + + private Execution fetch(String workflowId) { + return new Execution(Http.getMap(conductor.client(), "/workflow/" + workflowId, Map.of("includeTasks", "true"))); + } + + private void complete(String codeType, Task task, TaskResult.Status status, Map output, String reason) { + TaskResult result = new TaskResult(task); + result.setStatus(status); + result.setWorkerId(workerId); + result.setOutputData(new LinkedHashMap<>(output)); + TaskContinuation marker = task.getContinuation(); + if (marker != null) { + // the server applies the completion only to the lease it handed out; the protocol + // marks the result as the code's, also when the code failed, so that it never + // lands on the task the code paused on + result.getOutputData().put("protocol", 2); + result.getOutputData().put("n", marker.getN()); + result.getOutputData().put("epoch", marker.getEpoch()); + } + if (reason != null) { + result.setReasonForIncompletion(reason.length() > 1000 ? reason.substring(0, 1000) : reason); + } + // A server error (the workflow briefly busy) is retried for about 2 s; a refusal (4xx, e.g. + // the lease was superseded) is final. Longer retries hold a code thread, and under a + // database outage every code thread ends up waiting (found by the durability bench); + // past 2 s the server's continuation timeout retries the continuation instead. + for (int attempt = 1; ; attempt++) { + try { + // update-v2 hands back this worker's next continuation, if one is queued: it is + // leased to us now, so it must be processed, not dropped + Task next = taskClient.updateTaskV2(result); + if (next != null && next.getContinuation() != null && next.getContinuation().isLeased() && running) { + codeExecutor.submit(() -> process(codeType, next)); + } + return; + } catch (Exception e) { + boolean refused = e instanceof io.orkes.conductor.client.http.ApiException api + && api.getStatusCode() >= 400 && api.getStatusCode() < 500; + if (!running) { + // shutting down: the server retries the continuation if this one did not land + LOGGER.debug("completing {} of execution {} interrupted by shutdown", task.getReferenceTaskName(), task.getWorkflowInstanceId()); + return; + } + if (refused || attempt >= 4) { + LOGGER.warn("completing {} of execution {} was refused: {}", task.getReferenceTaskName(), task.getWorkflowInstanceId(), e.toString()); + return; + } + try { + Thread.sleep(250L * attempt); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + return; + } + } + } + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/Workflow.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Workflow.java new file mode 100644 index 000000000..81590a982 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Workflow.java @@ -0,0 +1,52 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Marks a method as a native workflow. Any method of any class can be a workflow: its body is + * ordinary Java, and every static call imported from {@link Conductor} goes to the server and shows + * in the workflow graph. + * + *

The class must have a no-argument constructor, or be registered with a factory. A new instance + * serves each execution. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Workflow { + + /** Workflow name; defaults to the method name in snake case. */ + String name() default ""; + + int version() default 1; + + String ownerEmail() default "native@conductor.local"; + + /** Execution timeout as an ISO-8601 duration such as {@code PT2H} or {@code P3D}; empty for none. */ + String timeout() default ""; + + String description() default ""; + + /** + * A workflow started when this one fails or times out, with the failed execution's id, status + * and reason as input. Any registered workflow, native or JSON. + */ + String failureWorkflow() default ""; + + /** Version of the failure workflow; 0 means the latest. */ + int failureWorkflowVersion() default 0; +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/WorkflowFailedException.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/WorkflowFailedException.java new file mode 100644 index 000000000..8115a068b --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/WorkflowFailedException.java @@ -0,0 +1,24 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +/** + * Thrown from workflow code to fail the execution with a reason. Thrown to a client waiting for the + * result of an execution that failed. + */ +public class WorkflowFailedException extends RuntimeException { + + public WorkflowFailedException(String reason) { + super(reason); + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/WorkflowHandle.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/WorkflowHandle.java new file mode 100644 index 000000000..8a7105e9a --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/WorkflowHandle.java @@ -0,0 +1,263 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.conductoross.conductor.sdk.Functions.Fn0; +import org.conductoross.conductor.sdk.Functions.Fn1; +import org.conductoross.conductor.sdk.Functions.Proc0; +import org.conductoross.conductor.sdk.Functions.Proc1; +import org.conductoross.conductor.sdk.internal.Json; +import org.conductoross.conductor.sdk.internal.MethodRefs; +import org.conductoross.conductor.sdk.internal.Replayer; +import org.conductoross.conductor.sdk.internal.WorkflowSpec; + +/** + * A running or finished execution, seen from the client. Handlers are addressed by method + * reference, so renaming a handler is a compile error at every call site. + */ +public final class WorkflowHandle { + + private static final Set TERMINAL = Set.of("COMPLETED", "FAILED", "TERMINATED", "TIMED_OUT"); + + private final Conductor conductor; + private final String workflowId; + private final Type resultType; + + WorkflowHandle(Conductor conductor, String workflowId, Type resultType) { + this.conductor = conductor; + this.workflowId = workflowId; + this.resultType = resultType; + } + + public String workflowId() { + return workflowId; + } + + /** The execution in the Conductor UI. */ + public String url() { + String base = conductor.client().getBasePath().replaceAll("/api/?$", ""); + return base + "/execution/" + workflowId; + } + + public void signal(Proc1 handler, A argument) { + send("signal", name(handler, Signal.class), argument); + } + + public void signal(Proc0 handler) { + send("signal", name(handler, Signal.class), null); + } + + /** Sends an update and waits for the handler's return value. */ + @SuppressWarnings("unchecked") + public V update(Fn1 handler, A argument) { + Method m = MethodRefs.resolve(handler); + String id = send("update", name(handler, Update.class), argument); + return (V) Json.convert(awaitReply(id), m.getGenericReturnType()); + } + + /** + * Runs a query against the execution's current state and returns its value. The query runs + * here, in the client, on an instance of the workflow class restored from the execution's + * {@code @Variable} values, which is the state a worker would restore to run it. So a query + * writes nothing, cannot change the execution, works on a completed execution, and does not + * wait for the workflow's handler lane. It sees every signal and update the execution has + * applied; one that was sent but not yet applied is not visible yet. + */ + @SuppressWarnings("unchecked") + public V query(Fn0 handler) { + Method m = MethodRefs.resolve(handler); + name(handler, Query.class); // checks the annotation + WorkflowSpec spec = WorkflowSpec.of(workflowMethodOf(m.getDeclaringClass())); + Object variables = execution(false).get("variables"); + Object instance = spec.newInstance(); + spec.restoreVariables(instance, variables instanceof Map v ? (Map) v : Map.of()); + Object value = Replayer.invokeHandler(instance, m, null); + return (V) Json.convert(Json.plain(value), m.getGenericReturnType()); + } + + private static Method workflowMethodOf(Class type) { + for (Method method : type.getDeclaredMethods()) { + if (method.isAnnotationPresent(Workflow.class)) { + return method; + } + } + throw new IllegalArgumentException(type.getName() + " has no @Workflow method"); + } + + /** Waits for the execution to finish and returns its result. */ + @SuppressWarnings("unchecked") + public R result(Duration timeout) { + long deadline = System.currentTimeMillis() + timeout.toMillis(); + while (true) { + Map wf = execution(false); + String status = (String) wf.get("status"); + if (TERMINAL.contains(status)) { + if ("COMPLETED".equals(status)) { + return (R) Json.decodeOutput((Map) wf.get("output"), resultType); + } + throw new WorkflowFailedException(status + ": " + wf.get("reasonForIncompletion")); + } + if (System.currentTimeMillis() > deadline) { + throw new IllegalStateException("execution " + workflowId + " still " + status + " after " + timeout); + } + sleep(250); + } + } + + public String status() { + return (String) execution(false).get("status"); + } + + @SuppressWarnings("unchecked") + public Map variables() { + Object v = execution(false).get("variables"); + return v == null ? Map.of() : (Map) v; + } + + /** + * Waits until a task with this reference name is pending, then completes it with the given + * output, the way a person answering a human task or an external callback would. + */ + @SuppressWarnings("unchecked") + public void completeTask(String taskReferenceName, Object output, Duration timeout) { + long deadline = System.currentTimeMillis() + timeout.toMillis(); + while (true) { + Map wf = execution(true); + List> tasks = (List>) wf.get("tasks"); + boolean pending = tasks != null && tasks.stream().anyMatch(t -> taskReferenceName.equals(t.get("referenceTaskName")) + && ("IN_PROGRESS".equals(t.get("status")) || "SCHEDULED".equals(t.get("status")))); + if (pending) { + try { + Http.post(conductor.client(), "/tasks/" + workflowId + "/" + taskReferenceName + "/COMPLETED", + Json.encodeOutput(output), String.class); + return; + } catch (RuntimeException e) { + // the server may be restarting; the loop re-reads and tries again + } + } + if (TERMINAL.contains(wf.get("status"))) { + throw new IllegalStateException("execution ended before task " + taskReferenceName + " was pending"); + } + if (System.currentTimeMillis() > deadline) { + throw new IllegalStateException("task " + taskReferenceName + " was not pending within " + timeout); + } + sleep(250); + } + } + + /** + * Sends a message and returns its id. The id is chosen here and travels in the payload, so a + * send retried after an ambiguous failure carries the same id: the handler lane applies each + * id once, and replies are keyed by it. + */ + private String send(String kind, String name, Object argument) { + String id = java.util.UUID.randomUUID().toString(); + Map message = new LinkedHashMap<>(); + message.put("kind", kind); + message.put("name", name); + message.put("id", id); + if (argument != null) { + message.put("args", Json.plain(argument)); + } + long deadline = System.currentTimeMillis() + Duration.ofMinutes(2).toMillis(); + while (true) { + try { + Http.post(conductor.client(), "/workflow/" + workflowId + "/messages", message, String.class); + return id; + } catch (RuntimeException e) { + // a restarting server: retry. A message accepted just before a failure may be + // queued twice; the handler lane applies its id once. A refusal (4xx, such as an + // execution that is no longer running) is definite and is not retried. + if (isRefusal(e) || System.currentTimeMillis() > deadline) { + throw e; + } + sleep(1000); + } + } + } + + private static boolean isRefusal(RuntimeException e) { + return e instanceof io.orkes.conductor.client.http.ApiException api + && api.getStatusCode() >= 400 && api.getStatusCode() < 500; + } + + @SuppressWarnings("unchecked") + private Object awaitReply(String messageId) { + long deadline = System.currentTimeMillis() + Duration.ofMinutes(3).toMillis(); + while (System.currentTimeMillis() < deadline) { + Map execution = execution(false); + Object state = execution.get("nativeState"); + Object replies = state instanceof Map v ? v.get("replies") : null; + if (replies instanceof Map m && m.containsKey(messageId)) { + Map reply = (Map) m.get(messageId); + if (reply.containsKey("error")) { + throw new IllegalStateException("handler failed: " + reply.get("error")); + } + return reply.get("value"); + } + Object status = execution.get("status"); + if (status != null && !"RUNNING".equals(status) && !"PAUSED".equals(status)) { + // the handler lane is gone: no reply will ever come + throw new IllegalStateException("workflow " + workflowId + " ended with status " + status + + " before replying to message " + messageId); + } + sleep(200); + } + throw new IllegalStateException("no reply to message " + messageId + " within 3 minutes; is the workflow's host running?"); + } + + /** + * Reads the execution, riding out a server that is restarting: connection failures and + * server errors are retried for up to two minutes. + */ + private Map execution(boolean includeTasks) { + long deadline = System.currentTimeMillis() + Duration.ofMinutes(2).toMillis(); + while (true) { + try { + return Http.getMap(conductor.client(), "/workflow/" + workflowId, Map.of("includeTasks", String.valueOf(includeTasks))); + } catch (RuntimeException e) { + if (System.currentTimeMillis() > deadline) { + throw e; + } + sleep(1000); + } + } + } + + private static String name(java.io.Serializable handler, Class kind) { + Method m = MethodRefs.resolve(handler); + java.lang.annotation.Annotation a = m.getAnnotation(kind); + if (a == null) { + throw new IllegalArgumentException(m.getName() + " is not annotated with @" + kind.getSimpleName()); + } + String value = a instanceof Signal s ? s.value() : a instanceof Update u ? u.value() : ((Query) a).value(); + return value.isBlank() ? m.getName() : value; + } + + private static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/ActionCase.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/ActionCase.java new file mode 100644 index 000000000..4d447c06a --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/ActionCase.java @@ -0,0 +1,24 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import org.conductoross.conductor.sdk.Functions; + +/** A case body with no result, keeping the code's own lambda so that it can be read. */ +public record ActionCase(Functions.CaseAction action) implements Functions.CaseBody { + @Override + public T get() { + action.run(); + return null; + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/CodeLoops.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/CodeLoops.java new file mode 100644 index 000000000..998883119 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/CodeLoops.java @@ -0,0 +1,132 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.JumpInsnNode; +import org.objectweb.asm.tree.LineNumberNode; +import org.objectweb.asm.tree.MethodNode; + +/** + * Which Java loops the calling code is inside. A {@code for} or {@code while} compiles to a backward + * jump, so the compiled method says which lines each loop covers; the call stack says which line + * each method is on. A step's loops only name what the execution diagram groups: nothing depends on + * them when the code is replayed. + */ +public final class CodeLoops { + + private record Loop(int first, int last, String id) {} + + private static final StackWalker WALKER = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE); + /** Loops of each method, outermost first, by class, method name and descriptor. */ + private static final Map> LOOPS = new ConcurrentHashMap<>(); + + private CodeLoops() {} + + /** The loops around the calling code, outermost first: through lambdas and helper methods. */ + public static List here() { + List path = new ArrayList<>(); + WALKER.forEach(frame -> { + String c = frame.getClassName(); + if (c.startsWith("org.conductoross.conductor.sdk.") || c.startsWith("java.") || c.startsWith("jdk.") + || TaskStubs.isStubClass(c)) { + return; + } + List inFrame = new ArrayList<>(); + for (Loop loop : loopsOf(frame)) { + if (loop.first <= frame.getLineNumber() && frame.getLineNumber() <= loop.last) { + inFrame.add(loop.id); + } + } + path.addAll(0, inFrame); + }); + return List.copyOf(path); + } + + /** The loops of a method around a line, outermost first. */ + public static List around(Class type, String method, String descriptor, int line) { + List ids = new ArrayList<>(); + for (Loop loop : loopsOf(type, method, descriptor)) { + if (loop.first <= line && line <= loop.last) { + ids.add(loop.id); + } + } + return ids; + } + + private static List loopsOf(StackWalker.StackFrame frame) { + return loopsOf(frame.getDeclaringClass(), frame.getMethodName(), frame.getDescriptor()); + } + + private static List loopsOf(Class type, String method, String descriptor) { + String key = type.getName() + "#" + method + descriptor; + return LOOPS.computeIfAbsent(key, k -> read(type, method, descriptor)); + } + + private static List read(Class type, String methodName, String descriptor) { + String resource = type.getName().replace('.', '/') + ".class"; + try (InputStream in = type.getClassLoader().getResourceAsStream(resource)) { + if (in == null) { + return List.of(); + } + ClassNode node = new ClassNode(); + new ClassReader(in).accept(node, ClassReader.SKIP_FRAMES); + for (MethodNode method : node.methods) { + if (method.name.equals(methodName) && method.desc.equals(descriptor)) { + return loops(method, type.getSimpleName()); + } + } + } catch (IOException | RuntimeException e) { + return List.of(); // loops only draw the diagram; never fail a workflow over one + } + return List.of(); + } + + /** A backward jump closes a loop: the lines between its target and the jump are the loop. */ + private static List loops(MethodNode method, String className) { + InsnList code = method.instructions; + Map lastByFirst = new TreeMap<>(); + for (int at = 0; at < code.size(); at++) { + if (code.get(at) instanceof JumpInsnNode jump && code.indexOf(jump.label) < at) { + int first = Integer.MAX_VALUE; + int last = 0; + for (int i = code.indexOf(jump.label); i <= at; i++) { + AbstractInsnNode insn = code.get(i); + if (insn instanceof LineNumberNode line) { + first = Math.min(first, line.line); + last = Math.max(last, line.line); + } + } + if (last > 0) { + lastByFirst.merge(first, last, Math::max); + } + } + } + List loops = new ArrayList<>(); + lastByFirst.forEach((first, last) -> loops.add(new Loop(first, last, className + "_loop_" + first))); + loops.sort(Comparator.comparingInt(Loop::first).thenComparing(Comparator.comparingInt(Loop::last).reversed())); + return loops; + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/CodeReader.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/CodeReader.java new file mode 100644 index 000000000..0cab92d93 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/CodeReader.java @@ -0,0 +1,1361 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.ArrayDeque; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.Handle; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.FieldNode; +import org.objectweb.asm.tree.IntInsnNode; +import org.objectweb.asm.tree.InvokeDynamicInsnNode; +import org.objectweb.asm.tree.JumpInsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.LdcInsnNode; +import org.objectweb.asm.tree.LineNumberNode; +import org.objectweb.asm.tree.LocalVariableNode; +import org.objectweb.asm.tree.LookupSwitchInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.TableSwitchInsnNode; +import org.objectweb.asm.tree.TryCatchBlockNode; +import org.objectweb.asm.tree.VarInsnNode; +import org.objectweb.asm.tree.analysis.Analyzer; +import org.objectweb.asm.tree.analysis.AnalyzerException; +import org.objectweb.asm.tree.analysis.Frame; +import org.objectweb.asm.tree.analysis.SourceInterpreter; +import org.objectweb.asm.tree.analysis.SourceValue; + +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +/** + * Finds the steps a piece of workflow code would take by reading its compiled bytecode. Nothing is + * run, so no value is needed: every arm of an {@code if} or {@code switch} and the body of a loop + * are all seen, and no plain Java executes. An {@code if} or {@code switch} whose arms call the + * server is a {@link Branch}: drawn as a SWITCH with every arm, as {@code switchOn} is. Calls are followed into lambdas and into methods of the workflow's own + * package. What cannot be known statically stays unknown: inputs are not read, a task name computed + * at run time shows as {@code task}, and a call through an interface or into another package is not + * followed. + */ +public final class CodeReader { + + private static final String SDK = "org/conductoross/conductor/sdk/"; + private static final String CONDUCTOR = SDK + "Conductor"; + private static final String PROMISE = SDK + "Promise"; + private static final String LAMBDA_FACTORY = "java/lang/invoke/LambdaMetafactory"; + + /** What the code would do at one point. */ + public sealed interface Step { + String site(); + } + + /** One task. */ + public record Call(Command command, String site) implements Step {} + + /** A decision with every case; {@code otherwise} is empty when there is none. */ + public record Decision(String name, Map> cases, List otherwise, String site) implements Step {} + + /** {@code async} bodies, one branch each; {@code joined} when the code waits for them at once. */ + public record Fork(List> branches, boolean joined, String site) implements Step {} + + /** A {@code join} or {@code get} on lanes forked earlier, with other calls in between. */ + public record Wait(String site) implements Step {} + + /** A {@code fanOut}: its items, and so its branches, exist only at run time. */ + public record FanOut(String name, String site) implements Step {} + + /** A {@code forEach} or {@code repeatUntil}: the server repeats these steps. */ + public record Loop(String name, boolean perItem, List body, String site) implements Step {} + + /** + * A plain Java {@code if} or {@code switch} whose arms call the server, drawn as a SWITCH. An + * {@code if} has the arms {@code true} and {@code false} (the default case); a {@code switch} + * has one arm per case, keyed by its labels, and {@code default}. {@code line} is the line the + * code decides on and {@code lastLine} the last line of its arms. + */ + public record Branch(String name, int line, int lastLine, List arms, String site) { + /** The arm whose calls are made from this line, or null. */ + public Arm armAt(int callLine) { + for (Arm arm : arms) { + if (arm.lines().contains(callLine)) { + return arm; + } + } + return null; + } + + /** Whether {@code other} lies inside one of this branch's arms. */ + public boolean contains(Branch other) { + return line < other.line && other.lastLine <= lastLine; + } + + /** The arm to draw as taken when the code went past without a call: the only one that can. */ + public Arm onlyArmWithoutCalls() { + Arm only = null; + for (Arm arm : arms) { + if (arm.canSkip()) { + if (only != null) { + return null; + } + only = arm; + } + } + return only; + } + + Decision decision() { + Map> cases = new LinkedHashMap<>(); + List otherwise = List.of(); + for (Arm arm : arms) { + if (arm.otherwise()) { + otherwise = arm.steps(); + } else { + cases.put(arm.key(), arm.steps()); + } + } + return new Decision(name, cases, otherwise, site); + } + } + + /** + * One arm of a {@link Branch}: its case key, the lines its calls are made from (no other code + * of the method calls from them), what it would call, whether the code can go through it + * without a call, and the loops inside it (first and last line). + */ + public record Arm(String key, boolean otherwise, Set lines, List steps, boolean canSkip, List loops) {} + + /** What following a method as it runs needs: its branches, outermost first; its loops; the lines it returns from. */ + public record Shape(List branches, List loops, Set returnLines) { + static final Shape NONE = new Shape(List.of(), List.of(), Set.of()); + } + + private static final Map> CACHE = new ConcurrentHashMap<>(); + private static final Map CLASSES = new ConcurrentHashMap<>(); + private static final Map SHAPES = new ConcurrentHashMap<>(); + /** Where each method, or code it calls, calls Thread.sleep. */ + private static final Map> SLEEPS = new ConcurrentHashMap<>(); + + /** + * Where a workflow method, or a lambda or helper it calls, calls {@code Thread.sleep}, as + * {@code Class.method:line}. Plain Java runs again on every replay, so such a sleep is repeated + * each time the code continues and holds a worker thread meanwhile. + */ + public static List threadSleeps(Method method) { + String owner = Type.getInternalName(method.getDeclaringClass()); + CodeReader reader = new CodeReader(method.getDeclaringClass().getClassLoader(), owner); + String key = reader.key(owner, method.getName(), Type.getMethodDescriptor(method)); + try { + reader.walk(owner, method.getName(), Type.getMethodDescriptor(method), new HashSet<>()); + } catch (RuntimeException e) { + return List.of(); + } + return SLEEPS.getOrDefault(key, List.of()); + } + + private final ClassLoader loader; + private final String scope; + + private CodeReader(ClassLoader loader, String rootClass) { + this.loader = loader; + int slash = rootClass.lastIndexOf('/'); + this.scope = slash < 0 ? "" : rootClass.substring(0, slash); + } + + /** The steps of a method, such as a {@code @Workflow} method. */ + public static List read(Method method) { + String owner = Type.getInternalName(method.getDeclaringClass()); + return new CodeReader(method.getDeclaringClass().getClassLoader(), owner) + .walk(owner, method.getName(), Type.getMethodDescriptor(method), new HashSet<>()); + } + + /** The steps of a lambda or method reference, which must be serializable. */ + public static List read(Serializable body) { + MethodRefs.Implementation impl = MethodRefs.implementation(body); + return new CodeReader(body.getClass().getClassLoader(), impl.owner()) + .walk(impl.owner(), impl.name(), impl.descriptor(), new HashSet<>()); + } + + /** + * What a method would call after the code on {@code line}, had it gone on: read from the + * compiled code, nothing runs. One list per level: the rest of the innermost drawn if or + * switch arm the line is in, then of each arm around it, then of the method. Empty when the + * method cannot be read. + */ + public static List> stepsAfter(Class type, String name, String descriptor, int line) { + Set branchLines = new HashSet<>(); + for (Branch b : shape(type, name, descriptor).branches()) { + branchLines.add(b.line()); + } + String owner = Type.getInternalName(type); + CodeReader reader = new CodeReader(type.getClassLoader(), owner); + try { + ClassNode node = reader.classNode(owner); + MethodNode method = node == null ? null : find(node, name, descriptor); + if (method == null || method.instructions.size() == 0) { + return List.of(); + } + Set active = new HashSet<>(); + active.add(reader.key(owner, name, descriptor)); + return reader.new Reading(owner, method, active).stepsAfter(line, branchLines); + } catch (RuntimeException e) { + return List.of(); + } + } + + /** + * The branches, loops and returns of one method, for following it while it runs. A method + * that cannot be read has none: it is then drawn as the calls it makes. + */ + public static Shape shape(Class type, String name, String descriptor) { + String owner = Type.getInternalName(type); + CodeReader reader = new CodeReader(type.getClassLoader(), owner); + String key = reader.key(owner, name, descriptor); + Shape known = SHAPES.get(key); + if (known != null) { + return known; + } + try { + reader.walk(owner, name, descriptor, new HashSet<>()); + } catch (RuntimeException e) { + // drawing never fails a workflow + } + return SHAPES.computeIfAbsent(key, k -> Shape.NONE); + } + + private String key(String owner, String name, String descriptor) { + return System.identityHashCode(loader) + ":" + owner + "." + name + descriptor; + } + + private List walk(String owner, String name, String descriptor, Set active) { + String key = key(owner, name, descriptor); + if (!active.add(key)) { + return List.of(); // recursion: its steps are already being read + } + try { + List known = CACHE.get(key); + if (known != null) { + return known; + } + String declaring = owner; + MethodNode method = null; + while (declaring != null && inScope(declaring) && method == null) { + ClassNode node = classNode(declaring); + method = node == null ? null : find(node, name, descriptor); + if (method == null) { + declaring = node == null ? null : node.superName; + } + } + if (method == null || method.instructions.size() == 0) { + return List.of(); + } + Reading reading = new Reading(declaring, method, active); + List steps = Collections.unmodifiableList(reading.steps()); + SHAPES.put(key, reading.shape()); + SLEEPS.put(key, List.copyOf(new java.util.LinkedHashSet<>(reading.sleeps))); + CACHE.put(key, steps); + return steps; + } finally { + active.remove(key); + } + } + + private boolean inScope(String owner) { + int slash = owner.lastIndexOf('/'); + String pkg = slash < 0 ? "" : owner.substring(0, slash); + return scope.isEmpty() ? pkg.isEmpty() : pkg.equals(scope) || pkg.startsWith(scope + "/"); + } + + private ClassNode classNode(String owner) { + String key = System.identityHashCode(loader) + ":" + owner; + ClassNode cached = CLASSES.get(key); + if (cached != null) { + return cached; + } + try (InputStream in = loader == null ? ClassLoader.getSystemResourceAsStream(owner + ".class") : loader.getResourceAsStream(owner + ".class")) { + if (in == null) { + return null; + } + ClassNode node = new ClassNode(); + new ClassReader(in).accept(node, ClassReader.SKIP_FRAMES); + CLASSES.put(key, node); + return node; + } catch (IOException e) { + throw new IllegalStateException("cannot read the class " + owner, e); + } + } + + private static MethodNode find(ClassNode node, String name, String descriptor) { + for (MethodNode m : node.methods) { + if (m.name.equals(name) && m.desc.equals(descriptor)) { + return m; + } + } + return null; + } + + /** + * An if or switch read from the instructions: the instruction that decides, the arms as + * instruction ranges with their keys, which one is the default, and where the arms meet. + */ + private record Candidate(int b, String name, int end, List ranges, List keys, int otherwise) {} + + /** One method's instructions, read in order. */ + private final class Reading { + private final String owner; + private final MethodNode method; + private final Set active; + private final Frame[] frames; + private final AbstractInsnNode[] insns; + /** Lambdas handed to the SDK: read as that call's body, or not at all (a once supplier). */ + private final Set consumed = Collections.newSetFromMap(new IdentityHashMap<>()); + private final List steps = new ArrayList<>(); + private final List> branches = new ArrayList<>(); + /** Forks drawn without a join that a later join or get may still wait for. */ + private int unjoined; + /** javac copies a finally block to every exit; each copy is the same step on the same line. */ + private final boolean hasFinally; + private final Set seenInFinally = new HashSet<>(); + private int line; + /** The source line of each instruction. */ + private final int[] lineAt; + /** Ifs and switches that may be drawn as branches, by the instruction that decides. */ + private final Map candidates = new HashMap<>(); + /** Instructions that call the server, or call code that does. */ + private final Set stepAt = new HashSet<>(); + /** Branches read, by the instruction that decides. */ + private final Map found = new TreeMap<>(); + /** Thread.sleep calls in this method and in the code it calls. */ + private final List sleeps = new ArrayList<>(); + private int current; + + Reading(String owner, MethodNode method, Set active) { + this.owner = owner; + this.method = method; + this.active = active; + this.insns = method.instructions.toArray(); + this.hasFinally = method.tryCatchBlocks.stream().anyMatch(b -> b.type == null); + try { + this.frames = new Analyzer<>(new SourceInterpreter()).analyze(owner, method); + } catch (AnalyzerException e) { + throw new IllegalStateException("cannot read " + owner + "." + method.name, e); + } + this.lineAt = new int[insns.length]; + int at = 0; + for (int i = 0; i < insns.length; i++) { + if (insns[i] instanceof LineNumberNode n) { + at = n.line; + } + lineAt[i] = at; + } + findCandidates(); + } + + List steps() { + consumeLambdas(); + readRange(0, insns.length); + flushFork(false); + return steps; + } + + /** + * The steps the method takes after the code on {@code line}, had it gone on: the rest of + * the method from the end of that line. Inside an arm of an if or switch it goes on after + * the if or switch, not into the other arms. + */ + List> stepsAfter(int line, Set branchLines) { + consumeLambdas(); + int at = -1; + for (int i = 0; i < insns.length; i++) { + if (frames[i] != null && insns[i].getOpcode() >= 0 && lineAt[i] == line) { + at = i; + } else if (at >= 0 && insns[i].getOpcode() >= 0 && lineAt[i] != line) { + break; // the first block of code on that line + } + } + if (at < 0) { + return List.of(); + } + List> segments = new ArrayList<>(); + int pos = at + 1; + while (pos < insns.length) { + Candidate around = null; // the innermost arm the position is in + int armEnd = 0; + int armSize = Integer.MAX_VALUE; + for (Candidate c : candidates.values()) { + for (int[] r : c.ranges()) { + if (r[0] <= pos && pos < r[1] && r[1] - r[0] < armSize) { + around = c; + armEnd = r[1]; + armSize = r[1] - r[0]; + } + } + } + if (around == null) { + readRange(pos, insns.length); + break; + } + readRange(pos, armEnd); + if (branchLines.contains(lineAt[around.b()])) { + flushFork(false); + segments.add(List.copyOf(steps)); // the code leaves a drawn if or switch here + steps.clear(); + } + pos = around.end(); + } + flushFork(false); + segments.add(List.copyOf(steps)); + return segments; + } + + private void consumeLambdas() { + for (int i = 0; i < insns.length; i++) { + if (frames[i] != null && insns[i] instanceof MethodInsnNode m && m.owner.startsWith(SDK) && !inScope(m.owner)) { + int argc = Type.getArgumentTypes(m.desc).length; + for (int a = 0; a < argc; a++) { + AbstractInsnNode source = source(i, argc, a); + if (source instanceof InvokeDynamicInsnNode) { + consumed.add(source); + } + } + } + } + } + + /** Reads the instructions from {@code from} up to {@code to}, adding their steps. */ + private void readRange(int from, int to) { + for (int i = from; i < to; i++) { + AbstractInsnNode insn = insns[i]; + line = lineAt[i]; + if (frames[i] == null) { + continue; // unreachable + } + current = i; + Candidate candidate = candidates.get(i); + if (candidate != null && candidate.end() <= to && branch(candidate)) { + i = candidate.end() - 1; + continue; + } + if (insn instanceof InvokeDynamicInsnNode indy && !consumed.contains(insn) && implementation(indy) != null) { + // a lambda given to plain code, such as list.forEach(i -> task(...)) + Handle h = implementation(indy); + add(walk(h.getOwner(), h.getName(), h.getDesc(), active)); + sleeps.addAll(SLEEPS.getOrDefault(key(h.getOwner(), h.getName(), h.getDesc()), List.of())); + } else if (insn instanceof MethodInsnNode m) { + if (CONDUCTOR.equals(m.owner) && m.getOpcode() == Opcodes.INVOKESTATIC) { + sdkCall(i, m); + } else if (PROMISE.equals(m.owner) && m.name.equals("get")) { + joinPoint(); + } else if (m.name.equals("") && taskType(m.owner) != null) { + throw new IllegalStateException(site() + " creates a " + taskType(m.owner).getSimpleName() + + ", so its task methods would run in the workflow on every replay: take it as a" + + " constructor parameter of the workflow instead, and Conductor supplies one that" + + " schedules the tasks"); + } else if (m.getOpcode() != Opcodes.INVOKESTATIC && !m.name.equals("") && taskMethod(m) != null) { + // a call on a task stub, such as tasks.reserve(order) + call(named(Command.Kind.SIMPLE, taskMethod(m).getAnnotation(WorkerTask.class).value())); + } else if ("java/lang/Thread".equals(m.owner) && m.name.equals("sleep")) { + sleeps.add(site()); + } else if (!m.name.equals("") && inScope(m.owner)) { + add(walk(m.owner, m.name, m.desc, active)); + sleeps.addAll(SLEEPS.getOrDefault(key(m.owner, m.name, m.desc), List.of())); + } + } + } + } + + private void add(List more) { + if (!more.isEmpty()) { + stepAt.add(current); + flushFork(false); + steps.addAll(more); + } + } + + /** The code waits here: for the lanes just started, or for a fork left running earlier. */ + private void joinPoint() { + branches.removeIf(List::isEmpty); + if (!branches.isEmpty()) { + flushFork(true); + } else if (unjoined > 0) { + unjoined--; + add(new Wait(site())); + } + } + + private void add(Step step) { + add(List.of(step)); + } + + private void flushFork(boolean joined) { + branches.removeIf(List::isEmpty); + if (!branches.isEmpty()) { + steps.add(new Fork(List.copyOf(branches), joined, site())); + if (!joined) { + unjoined++; + } + } + branches.clear(); + } + + private void call(Command command) { + if (hasFinally && !seenInFinally.add(line + ":" + command.name)) { + return; + } + add(new Call(command, site())); + } + + private String site() { + String simple = owner.substring(owner.lastIndexOf('/') + 1); + return simple + "." + method.name + ":" + line; + } + + // ------------------------------------------------------------ plain ifs and switches + + /** + * Reads an if or switch: each arm on its own. When an arm calls the server the whole is a + * branch, drawn with every arm; otherwise it is plain code and nothing of it is drawn. + */ + private boolean branch(Candidate c) { + List> armSteps = new ArrayList<>(); + boolean calls = false; + for (int[] range : c.ranges()) { + List savedSteps = new ArrayList<>(steps); + List> savedForks = new ArrayList<>(branches); + int savedUnjoined = unjoined; + steps.clear(); + branches.clear(); + readRange(range[0], range[1]); + flushFork(false); + List arm = List.copyOf(steps); + steps.clear(); + steps.addAll(savedSteps); + branches.clear(); + branches.addAll(savedForks); + unjoined = savedUnjoined; + armSteps.add(arm); + calls |= !arm.isEmpty(); + } + if (!calls) { + return false; + } + line = lineAt[c.b()]; + int last = line; + List arms = new ArrayList<>(); + for (int k = 0; k < c.ranges().size(); k++) { + int[] range = c.ranges().get(k); + Set lines = new TreeSet<>(); + for (int i = range[0]; i < range[1]; i++) { + if (frames[i] != null && insns[i].getOpcode() >= 0) { + last = Math.max(last, lineAt[i]); + if (isCall(insns[i])) { + lines.add(lineAt[i]); + } + } + } + arms.add(new Arm(c.keys().get(k), k == c.otherwise(), Collections.unmodifiableSet(lines), armSteps.get(k), + canSkip(range[0], range[1]), loopsIn(range[0], range[1]))); + } + Branch b = new Branch(c.name(), lineAt[c.b()], last, List.copyOf(arms), site()); + found.put(c.b(), b); + flushFork(false); + steps.add(b.decision()); + return true; + } + + Shape shape() { + Set returns = new TreeSet<>(); + for (int i = 0; i < insns.length; i++) { + int op = insns[i].getOpcode(); + if (frames[i] != null && op >= Opcodes.IRETURN && op <= Opcodes.RETURN) { + returns.add(lineAt[i]); + } + } + List sorted = new ArrayList<>(found.values()); + sorted.sort(Comparator.comparingInt(Branch::line).thenComparing(Comparator.comparingInt(Branch::lastLine).reversed())); + return new Shape(List.copyOf(sorted), loopsIn(0, insns.length), Collections.unmodifiableSet(returns)); + } + + /** Whether the code can go from {@code from} out of the range without making a call. */ + private boolean canSkip(int from, int to) { + if (from >= to) { + return true; + } + ArrayDeque todo = new ArrayDeque<>(List.of(from)); + Set seen = new HashSet<>(); + while (!todo.isEmpty()) { + int i = todo.pop(); + if (i < from || i >= to || exits(insns[i])) { + return true; + } + if (!seen.add(i) || stepAt.contains(i) || frames[i] == null) { + continue; + } + todo.addAll(successors(i)); + } + return false; + } + + /** The loops in a range, as their first and last line: a backward jump closes one. */ + private List loopsIn(int from, int to) { + List loops = new ArrayList<>(); + for (int i = from; i < to; i++) { + if (frames[i] != null && insns[i] instanceof JumpInsnNode j && index(j.label) <= i && index(j.label) >= from) { + int first = Integer.MAX_VALUE; + int last = 0; + for (int k = index(j.label); k <= i; k++) { + if (insns[k].getOpcode() >= 0 && lineAt[k] > 0) { + first = Math.min(first, lineAt[k]); + last = Math.max(last, lineAt[k]); + } + } + if (last > 0) { + loops.add(new int[] {first, last}); + } + } + } + return List.copyOf(loops); + } + + private void findCandidates() { + Map backEdge = new HashMap<>(); + for (int i = 0; i < insns.length; i++) { + if (frames[i] != null && insns[i] instanceof JumpInsnNode j && index(j.label) <= i) { + backEdge.merge(index(j.label), i, Math::max); + } + } + // javac evaluates `a && b` as one jump per operand, all to the same place: the last decides + Map ifs = new LinkedHashMap<>(); + List all = new ArrayList<>(); + for (int b = 0; b < insns.length; b++) { + if (frames[b] == null) { + continue; + } + if (insns[b] instanceof JumpInsnNode j && conditional(j.getOpcode())) { + Candidate c = ifCandidate(b, index(j.label), backEdge); + if (c != null) { + long key = ((long) c.ranges().get(1)[0] << 32) | c.end(); + Candidate before = ifs.put(key, c); + if (before != null && !sameCondition(before.b(), b)) { + all.add(before); + } + } + } else if (insns[b] instanceof TableSwitchInsnNode || insns[b] instanceof LookupSwitchInsnNode) { + Candidate c = switchCandidate(b); + if (c != null) { + all.add(c); + } + } + } + all.addAll(ifs.values()); + for (Candidate c : all) { + if (valid(c)) { + candidates.put(c.b(), c); + } + } + } + + /** Two jumps of one condition: the same line, no statement between them. */ + private boolean sameCondition(int first, int second) { + for (int i = first + 1; i < second; i++) { + if (insns[i] instanceof LineNumberNode) { + return false; + } + } + return lineAt[first] == lineAt[second]; + } + + /** + * An if: the jump at {@code b} skips the then-arm to {@code t}. A then-arm ending in a jump + * past the else-arm has one; a jump back to before {@code b} that closes a loop makes the + * jump the loop's condition, not an if. + */ + private Candidate ifCandidate(int b, int t, Map backEdge) { + if (t <= b) { + return null; + } + int before = prevReal(t); + if (before <= b) { + return null; + } + AbstractInsnNode last = insns[before]; + int end = t; + if (last instanceof JumpInsnNode lj) { + int target = index(lj.label); + if (conditional(lj.getOpcode()) && target > before) { + return null; // one operand of an `a || b` + } + if (lj.getOpcode() == Opcodes.GOTO && target <= b && backEdge.get(target) == before) { + return null; // the condition of a loop + } + if (lj.getOpcode() == Opcodes.GOTO && target > t) { + boolean leaves = false; + for (int i = t; i < target && !leaves; i++) { + for (int to : targets(i)) { + leaves |= frames[i] != null && to < t; + } + } + if (!leaves) { + end = target; // an else arm; otherwise the jump is a break or continue + } + } + } + return new Candidate(b, name("if", b), end, List.of(new int[] {b + 1, t}, new int[] {t, end}), + List.of("true", "false"), 1); + } + + /** A switch: an arm per case target, in order, each ending in a break, a return or a throw. */ + private Candidate switchCandidate(int b) { + List keys = new ArrayList<>(); + List labels; + LabelNode dflt; + if (insns[b] instanceof TableSwitchInsnNode t) { + for (int k = t.min; k <= t.max; k++) { + keys.add(k); + } + labels = t.labels; + dflt = t.dflt; + } else { + LookupSwitchInsnNode l = (LookupSwitchInsnNode) insns[b]; + keys.addAll(l.keys); + labels = l.labels; + dflt = l.dflt; + } + Map names = caseNames(b); + int d = index(dflt); + TreeMap> byStart = new TreeMap<>(); + for (int k = 0; k < keys.size(); k++) { + int start = index(labels.get(k)); + if (start <= b) { + return null; + } + if (start != d) { + byStart.computeIfAbsent(start, x -> new ArrayList<>()) + .add(names.getOrDefault(keys.get(k), String.valueOf(keys.get(k)))); + } + } + if (d <= b) { + return null; + } + List starts = new ArrayList<>(new TreeSet<>(byStart.keySet())); + if (!starts.contains(d)) { + starts.add(d); + starts.sort(null); + } + int lastStart = starts.get(starts.size() - 1); + Integer end = null; + for (int k = 1; k < starts.size(); k++) { + AbstractInsnNode prev = insns[prevReal(starts.get(k))]; + if (prev instanceof JumpInsnNode g && g.getOpcode() == Opcodes.GOTO && index(g.label) >= lastStart) { + if (end != null && end != index(g.label)) { + return null; + } + end = index(g.label); + } else if (!exits(prev) && !(prev instanceof JumpInsnNode g2 && g2.getOpcode() == Opcodes.GOTO)) { + return null; // falls through into the next case + } + } + if (end == null) { + end = reachEnd(lastStart); + } + List ranges = new ArrayList<>(); + List armKeys = new ArrayList<>(); + int otherwise = -1; + for (int k = 0; k < starts.size(); k++) { + int a = starts.get(k); + if (a >= end) { + continue; // no default: the switch's default goes to the code after it + } + int z = k + 1 < starts.size() ? Math.min(starts.get(k + 1), end) : end; + if (a == d) { + otherwise = ranges.size(); + armKeys.add("default"); + } else { + armKeys.add(String.join(",", byStart.get(a))); + } + ranges.add(new int[] {a, z}); + } + if (otherwise < 0) { + otherwise = ranges.size(); + armKeys.add("default"); + ranges.add(new int[] {end, end}); + } + return new Candidate(b, name("switch", b), end, List.copyOf(ranges), List.copyOf(armKeys), otherwise); + } + + /** One past the last instruction reachable from {@code from} without going back before it. */ + private int reachEnd(int from) { + int max = from; + ArrayDeque todo = new ArrayDeque<>(List.of(from)); + Set seen = new HashSet<>(); + while (!todo.isEmpty()) { + int i = todo.pop(); + if (i < from || i >= insns.length || !seen.add(i)) { + continue; + } + max = Math.max(max, i); + if (!exits(insns[i])) { + todo.addAll(successors(i)); + } + } + return max + 1; + } + + /** + * Whether a candidate can be followed from the lines calls are made on: each line with a + * call is in one arm or outside them all, and an arm is entered only from its start. + */ + private boolean valid(Candidate c) { + Map regionOfLine = new HashMap<>(); + for (int i = 0; i < insns.length; i++) { + if (frames[i] != null && isCall(insns[i])) { + Integer seen = regionOfLine.putIfAbsent(lineAt[i], region(c, i)); + if (seen != null && seen != region(c, i)) { + return false; + } + } + } + for (int s = 0; s < insns.length; s++) { + if (frames[s] == null) { + continue; + } + for (int t : targets(s)) { + for (int[] r : c.ranges()) { + boolean from = s >= r[0] && s < r[1]; + if (t < r[0] || t >= r[1] || from) { + continue; + } + boolean chain = s < c.b() && lineAt[s] == lineAt[c.b()] && insns[s] instanceof JumpInsnNode; + if (t > r[0] || (s != c.b() && !chain)) { + return false; + } + } + } + } + for (TryCatchBlockNode tc : method.tryCatchBlocks) { + int h = index(tc.handler); + for (int[] r : c.ranges()) { + if (h >= r[0] && h < r[1] && (index(tc.start) < r[0] || index(tc.end) > r[1])) { + return false; + } + } + } + return true; + } + + private int region(Candidate c, int i) { + for (int k = 0; k < c.ranges().size(); k++) { + if (i >= c.ranges().get(k)[0] && i < c.ranges().get(k)[1]) { + return k; + } + } + return -1; + } + + /** The case labels of a switch by key: string and enum cases as written, others as numbers. */ + private Map caseNames(int b) { + Map names = new HashMap<>(); + AbstractInsnNode source = source(b, 1, 0); + if (source instanceof MethodInsnNode m && m.name.equals("ordinal") && m.desc.equals("()I")) { + List constants = enumConstants(m.owner); + for (int k = 0; k < constants.size(); k++) { + names.put(k, constants.get(k)); + } + } else if (source instanceof InsnNode n && n.getOpcode() == Opcodes.IALOAD + && source(indexOf(n), 2, 0) instanceof FieldInsnNode map && map.name.startsWith("$SwitchMap$")) { + names.putAll(switchMap(map)); + } else if (source instanceof VarInsnNode v && v.getOpcode() == Opcodes.ILOAD) { + // a string switch: javac numbers the strings, matched by equals, into a local + for (int i = 0; i < insns.length; i++) { + if (frames[i] != null && insns[i] instanceof VarInsnNode store && store.getOpcode() == Opcodes.ISTORE + && store.var == v.var) { + String k = constant(i, 1, 0); + for (int j = i - 1; j >= Math.max(0, i - 8) && k != null; j--) { + if (insns[j] instanceof LdcInsnNode ldc && ldc.cst instanceof String text) { + names.put(Integer.parseInt(k), text); + break; + } + } + } + } + } else if (source instanceof InvokeDynamicInsnNode indy && indy.bsm.getOwner().equals("java/lang/runtime/SwitchBootstraps")) { + for (int k = 0; k < indy.bsmArgs.length; k++) { + Object arg = indy.bsmArgs[k]; + String text = arg instanceof Type type ? simpleName(type.getClassName()) : String.valueOf(arg); + names.put(k, text); + } + names.put(-1, "null"); + } + return names; + } + + private List enumConstants(String enumOwner) { + ClassNode node = classNode(enumOwner); + List constants = new ArrayList<>(); + if (node != null) { + for (FieldNode f : node.fields) { + if ((f.access & Opcodes.ACC_ENUM) != 0) { + constants.add(f.name); + } + } + } + return constants; + } + + /** javac's table from an enum's ordinal to a case number, read from where it is filled in. */ + private Map switchMap(FieldInsnNode map) { + Map names = new HashMap<>(); + ClassNode holder = classNode(map.owner); + MethodNode init = holder == null ? null : find(holder, "", "()V"); + if (init == null) { + return names; + } + AbstractInsnNode[] code = init.instructions.toArray(); + for (int i = 0; i < code.length; i++) { + if (code[i].getOpcode() == Opcodes.IASTORE) { + AbstractInsnNode value = prevRealIn(code, i); + AbstractInsnNode ordinal = prevRealIn(code, indexIn(code, value)); + AbstractInsnNode constant = ordinal == null ? null : prevRealIn(code, indexIn(code, ordinal)); + Integer k = intValue(value); + if (k != null && constant instanceof FieldInsnNode f && f.getOpcode() == Opcodes.GETSTATIC) { + names.put(k, f.name); + } + } + } + return names; + } + + private AbstractInsnNode prevRealIn(AbstractInsnNode[] code, int i) { + for (int j = i - 1; j >= 0; j--) { + if (code[j].getOpcode() >= 0) { + return code[j]; + } + } + return null; + } + + private int indexIn(AbstractInsnNode[] code, AbstractInsnNode insn) { + for (int j = 0; j < code.length; j++) { + if (code[j] == insn) { + return j; + } + } + return 0; + } + + private Integer intValue(AbstractInsnNode insn) { + if (insn instanceof InsnNode n && n.getOpcode() >= Opcodes.ICONST_M1 && n.getOpcode() <= Opcodes.ICONST_5) { + return n.getOpcode() - Opcodes.ICONST_0; + } + if (insn instanceof IntInsnNode n && n.getOpcode() != Opcodes.NEWARRAY) { + return n.operand; + } + if (insn instanceof LdcInsnNode ldc && ldc.cst instanceof Integer k) { + return k; + } + return null; + } + + private static final Set PLUMBING = Set.of("equals", "hashCode", "ordinal", "booleanValue", "intValue", + "longValue", "doubleValue", "floatValue", "shortValue", "byteValue", "charValue", "valueOf", + "getClass", "toString", "name", "compareTo", "requireNonNull"); + + /** + * A branch is named after what it decides on: the last method its condition calls, else a + * field it reads, else a local variable, as in {@code if_flagged} or {@code switch_kind}. + */ + private String name(String kind, int b) { + int s = b; + while (s > 0 && !(insns[s] instanceof LineNumberNode)) { + s--; + } + for (int i = b - 1; i >= s; i--) { + if (insns[i] instanceof MethodInsnNode m && !PLUMBING.contains(m.name) && !m.name.startsWith("<") + && !m.name.startsWith("lambda$")) { + return kind + "_" + clean(m.name); + } + } + for (int i = b - 1; i >= s; i--) { + if (insns[i] instanceof FieldInsnNode f && !f.name.startsWith("$")) { + return kind + "_" + clean(f.name); + } + } + for (int i = s; i < b; i++) { + if (insns[i] instanceof VarInsnNode v && v.getOpcode() >= Opcodes.ILOAD && v.getOpcode() <= Opcodes.ALOAD) { + String local = localName(v.var, i); + if (local != null && !local.equals("this")) { + return kind + "_" + clean(local); + } + } + } + return kind; + } + + private String localName(int var, int at) { + if (method.localVariables == null) { + return null; + } + String any = null; + for (LocalVariableNode local : method.localVariables) { + if (local.index == var) { + if (index(local.start) <= at + 1 && at < index(local.end)) { + return local.name; + } + any = local.name; + } + } + return any; + } + + private String clean(String name) { + return name.replaceAll("[^A-Za-z0-9_]", "_"); + } + + private String simpleName(String className) { + return className.substring(Math.max(className.lastIndexOf('.'), className.lastIndexOf('$')) + 1); + } + + private int index(LabelNode label) { + return method.instructions.indexOf(label); + } + + private int prevReal(int i) { + int j = i - 1; + while (j >= 0 && insns[j].getOpcode() < 0) { + j--; + } + return j; + } + + private List targets(int i) { + List out = new ArrayList<>(); + if (insns[i] instanceof JumpInsnNode j) { + out.add(index(j.label)); + } else if (insns[i] instanceof TableSwitchInsnNode t) { + out.add(index(t.dflt)); + t.labels.forEach(l -> out.add(index(l))); + } else if (insns[i] instanceof LookupSwitchInsnNode l) { + out.add(index(l.dflt)); + l.labels.forEach(x -> out.add(index(x))); + } + return out; + } + + private List successors(int i) { + List out = targets(i); + boolean jumpsAlways = insns[i].getOpcode() == Opcodes.GOTO || insns[i] instanceof TableSwitchInsnNode + || insns[i] instanceof LookupSwitchInsnNode; + if (!jumpsAlways && !exits(insns[i])) { + out.add(i + 1); + } + return out; + } + + private boolean exits(AbstractInsnNode insn) { + int op = insn.getOpcode(); + return (op >= Opcodes.IRETURN && op <= Opcodes.RETURN) || op == Opcodes.ATHROW; + } + + private boolean conditional(int opcode) { + return (opcode >= Opcodes.IFEQ && opcode <= Opcodes.IF_ACMPNE) || opcode == Opcodes.IFNULL || opcode == Opcodes.IFNONNULL; + } + + private boolean isCall(AbstractInsnNode insn) { + return insn instanceof MethodInsnNode || insn instanceof InvokeDynamicInsnNode; + } + + private void sdkCall(int i, MethodInsnNode m) { + int argc = Type.getArgumentTypes(m.desc).length; + switch (m.name) { + case "task" -> { + if (m.desc.startsWith("(Ljava/lang/String;")) { + Command c = named(Command.Kind.SIMPLE, text(i, argc, 0, "task")); + chainArg(i, "ref").ifPresent(r -> c.explicitRef = r); + call(c); + } else { + Method target = target(i, argc, 0); + WorkerTask annotation = target == null ? null : target.getAnnotation(WorkerTask.class); + call(named(Command.Kind.SIMPLE, annotation == null ? "task" : annotation.value())); + } + } + case "sleep" -> call(named(Command.Kind.WAIT, "sleep")); + case "sleepUntil" -> call(named(Command.Kind.WAIT, "sleep_until")); + case "awaitCondition" -> call(named(Command.Kind.WAIT, "condition")); + case "awaitExternal" -> call(step(Command.Kind.WAIT, text(i, argc, 0, "external"))); + case "human" -> call(withDefinition(step(Command.Kind.HUMAN, text(i, argc, 0, "human")), 0)); + case "llm" -> call(withDefinition(step(Command.Kind.LLM, text(i, argc, 0, "llm")), 3)); + case "agent" -> call(withDefinition(step(Command.Kind.AGENT, text(i, argc, 0, "agent")), 3)); + case "mcp" -> { + boolean lists = chain(i).stream().anyMatch(c -> c.name.equals("listTools")); + call(withDefinition(step(lists ? Command.Kind.MCP_LIST : Command.Kind.MCP_CALL, text(i, argc, 0, "mcp")), 3)); + } + case "http" -> { + Command c = withDefinition(step(Command.Kind.HTTP, text(i, argc, 0, "http")), 3); + Map request = new LinkedHashMap<>(); + request.put("method", "GET"); + for (MethodInsnNode link : chain(i)) { + if (Set.of("get", "post", "put", "delete").contains(link.name)) { + request.put("method", link.name.toUpperCase(java.util.Locale.ROOT)); + String uri = textOf(indexOf(link), 1, 0); + if (uri != null) { + request.put("uri", uri); + } + } + } + c.input.put("http_request", request); + call(c); + } + case "event" -> { + Command c = step(Command.Kind.EVENT, text(i, argc, 0, "event")); + c.fields.put("sink", chainArg(i, "to").orElse("conductor")); + call(c); + } + case "child" -> { + Command c = workflowCommand(target(i, argc, 0), Command.Kind.SUB_WORKFLOW, ""); + if (c != null) { + WorkflowSpec spec = WorkflowSpec.of(target(i, argc, 0)); + c.fields.put("subWorkflowParam", Map.of("name", spec.name, "version", spec.version)); + call(c); + } + } + case "startWorkflow" -> { + String name; + int version = 1; + if (m.desc.startsWith("(Ljava/lang/String;")) { + name = text(i, argc, 0, "workflow"); + } else { + Method target = target(i, argc, 0); + if (target == null) { + return; + } + WorkflowSpec spec = WorkflowSpec.of(target); + name = spec.name; + version = spec.version; + } + Command c = named(Command.Kind.START_WORKFLOW, "start_" + name); + Map start = new LinkedHashMap<>(); + start.put("name", name); + start.put("version", version); + c.input.put("startWorkflow", start); + call(c); + } + case "async" -> { + List body = bodyOf(i, argc, 0); + if (!body.isEmpty()) { + stepAt.add(current); + } + branches.add(body); + } + case "join" -> joinPoint(); + case "fanOut" -> add(new FanOut(m.desc.startsWith("(Ljava/lang/String;") ? text(i, argc, 0, "fanout") : "fanout", site())); + case "forEach" -> { + boolean named = m.desc.startsWith("(Ljava/lang/String;"); + Method target = target(i, argc, argc - 1); + WorkerTask annotation = target == null ? null : target.getAnnotation(WorkerTask.class); + Step inner = new Call(named(Command.Kind.SIMPLE, annotation == null ? "task" : annotation.value()), site()); + add(new Loop(named ? text(i, argc, 0, "for_each") : "for_each", true, List.of(inner), site())); + } + case "repeatUntil" -> add(new Loop("poll", false, bodyOf(i, argc, 0), site())); + case "switchOn" -> switchOn(i, argc); + default -> { + // once, now, random, workflowId: recorded values, not steps + } + } + } + + private void switchOn(int i, int argc) { + Map> cases = new LinkedHashMap<>(); + List otherwise = List.of(); + int unnamed = 0; + for (MethodInsnNode link : chain(i)) { + int at = indexOf(link); + int links = Type.getArgumentTypes(link.desc).length; + if (link.name.equals("when")) { + String key = constant(at, links, 0); + cases.put(key != null ? key : "unknown_" + ++unnamed, bodyOf(at, links, 1)); + } else if (link.name.equals("otherwise")) { + otherwise = bodyOf(at, links, 0); + } + } + add(new Decision(text(i, argc, 0, "switch"), cases, otherwise, site())); + } + + private Command named(Command.Kind kind, String name) { + return new Command(kind, name, name); + } + + /** A server step, whose first argument is its reference name. */ + private Command step(Command.Kind kind, String ref) { + Command c = named(kind, ref); + c.explicitRef = ref; + return c; + } + + private Command withDefinition(Command c, int retries) { + c.fields.put("taskDefinition", Entries.retryingDefinition(c.name, retries, 1)); + return c; + } + + private Command workflowCommand(Method target, Command.Kind kind, String prefix) { + return target == null ? null : named(kind, prefix + WorkflowSpec.of(target).name); + } + + private List bodyOf(int i, int argc, int arg) { + if (source(i, argc, arg) instanceof InvokeDynamicInsnNode indy && implementation(indy) != null) { + Handle h = implementation(indy); + List body = walk(h.getOwner(), h.getName(), h.getDesc(), active); + sleeps.addAll(SLEEPS.getOrDefault(key(h.getOwner(), h.getName(), h.getDesc()), List.of())); + return body; + } + return List.of(); + } + + /** The {@code @WorkerTask} method an instance call names, or null. */ + private Method taskMethod(MethodInsnNode m) { + if (taskType(m.owner) == null) { + return null; + } + int tag = m.getOpcode() == Opcodes.INVOKEINTERFACE ? Opcodes.H_INVOKEINTERFACE : Opcodes.H_INVOKEVIRTUAL; + Method method = MethodRefs.method(loader, new Handle(tag, m.owner, m.name, m.desc, m.itf)); + return method != null && method.isAnnotationPresent(WorkerTask.class) ? method : null; + } + + /** The class an owner names when it has {@code @WorkerTask} methods, or null. */ + private Class taskType(String owner) { + if (owner.startsWith("java/") || owner.startsWith("javax/") || owner.startsWith("jdk/") + || owner.startsWith("sun/") || owner.startsWith("[") || (owner.startsWith(SDK) && !inScope(owner))) { + return null; + } + try { + Class type = Class.forName(owner.replace('/', '.'), false, loader); + return TaskStubs.isTaskType(type) ? type : null; + } catch (ClassNotFoundException | LinkageError e) { + return null; + } + } + + private Method target(int i, int argc, int arg) { + if (source(i, argc, arg) instanceof InvokeDynamicInsnNode indy && implementation(indy) != null) { + return MethodRefs.method(loader, implementation(indy)); + } + return null; + } + + private Handle implementation(InvokeDynamicInsnNode indy) { + if (LAMBDA_FACTORY.equals(indy.bsm.getOwner()) && indy.bsmArgs.length > 1 && indy.bsmArgs[1] instanceof Handle h) { + return h; + } + return null; + } + + private int indexOf(AbstractInsnNode insn) { + return method.instructions.indexOf(insn); + } + + /** The instruction that produced an argument, when exactly one did. */ + private AbstractInsnNode source(int i, int argc, int arg) { + Frame frame = frames[i]; + int at = frame.getStackSize() - argc + arg; + if (at < 0) { + return null; + } + Set sources = frame.getStack(at).insns; + return sources.size() == 1 ? sources.iterator().next() : null; + } + + private String text(int i, int argc, int arg, String otherwise) { + String text = textOf(i, argc, arg); + return text != null ? text : otherwise; + } + + private String textOf(int i, int argc, int arg) { + return source(i, argc, arg) instanceof LdcInsnNode ldc && ldc.cst instanceof String s ? s : null; + } + + /** A compile-time value in its string form: text, a number, a boolean or an enum constant. */ + private String constant(int i, int argc, int arg) { + AbstractInsnNode source = source(i, argc, arg); + if (source instanceof LdcInsnNode ldc) { + return String.valueOf(ldc.cst); + } + if (source instanceof IntInsnNode n) { + return String.valueOf(n.operand); + } + if (source instanceof InsnNode n && n.getOpcode() >= Opcodes.ICONST_M1 && n.getOpcode() <= Opcodes.ICONST_5) { + return String.valueOf(n.getOpcode() - Opcodes.ICONST_0); + } + if (source instanceof FieldInsnNode f && f.getOpcode() == Opcodes.GETSTATIC) { + return f.name; + } + if (source instanceof MethodInsnNode m && m.name.equals("valueOf") && m.getOpcode() == Opcodes.INVOKESTATIC) { + String boxed = constant(indexOf(m), Type.getArgumentTypes(m.desc).length, 0); + if ("java/lang/Boolean".equals(m.owner) && boxed != null) { + return String.valueOf(!"0".equals(boxed)); + } + return boxed; + } + return null; + } + + /** The builder calls made on the result of the call at {@code i}, in order. */ + private List chain(int i) { + List links = new ArrayList<>(); + AbstractInsnNode current = insns[i]; + for (int j = i + 1; j < insns.length; j++) { + if (frames[j] != null && insns[j] instanceof MethodInsnNode m && m.getOpcode() != Opcodes.INVOKESTATIC) { + int argc = Type.getArgumentTypes(m.desc).length; + int at = frames[j].getStackSize() - argc - 1; + if (at >= 0) { + Set receiver = frames[j].getStack(at).insns; + if (receiver.size() == 1 && receiver.contains(current)) { + links.add(m); + current = m; + } + } + } + } + return links; + } + + private java.util.Optional chainArg(int i, String name) { + for (MethodInsnNode link : chain(i)) { + if (link.name.equals(name)) { + return java.util.Optional.ofNullable(textOf(indexOf(link), Type.getArgumentTypes(link.desc).length, 0)); + } + } + return java.util.Optional.empty(); + } + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Command.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Command.java new file mode 100644 index 000000000..81db658e7 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Command.java @@ -0,0 +1,87 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * One call from workflow code to the server, described independently of how it is executed. The + * replay engine turns it into a workflow task definition; the in-memory test engine answers it + * directly. + */ +public final class Command { + + public enum Kind { + SIMPLE, + SUB_WORKFLOW, + START_WORKFLOW, + WAIT, + HUMAN, + HTTP, + EVENT, + LLM, + MCP_LIST, + MCP_CALL, + AGENT + } + + public final Kind kind; + /** Task name: the worker task name, sub-workflow name, or a server step's name. */ + public final String name; + /** Base for the derived reference name when no explicit reference is given. */ + public final String refBase; + public String explicitRef; + public final Map input = new LinkedHashMap<>(); + /** Type-specific definition fields: subWorkflowParam, sink, taskDefinition and so on. */ + public final Map fields = new LinkedHashMap<>(); + /** Type the result decodes into. */ + public Type resultType = Object.class; + /** A TIMED_OUT task means "no result" rather than a failure (human tasks). */ + public boolean timeoutIsEmpty; + /** A completed task with empty output means "no result" (external waits). */ + public boolean emptyIsEmpty; + /** Whether the result is wrapped in Optional. */ + public boolean optional; + /** HTTP responses are read from response.body. */ + public boolean httpBody; + /** The result is this key of the task output rather than the whole output. */ + public String outputKey; + /** Input values that are server expressions, placed without escaping. */ + public final Map rawInput = new LinkedHashMap<>(); + + /** For the in-memory engine: the worker method and arguments, when known. */ + public Method method; + public Object[] args; + /** For the in-memory engine: the child workflow method. */ + public Method childMethod; + public Object childInput; + /** For the in-memory engine: duration of a WAIT, in seconds. */ + public long seconds; + + public Command(Kind kind, String name, String refBase) { + this.kind = kind; + this.name = name; + this.refBase = refBase; + } + + public boolean blocking() { + return kind != Kind.EVENT && kind != Kind.START_WORKFLOW; + } + + public String ref(String allocated) { + return explicitRef != null ? explicitRef : allocated; + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Conductors.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Conductors.java new file mode 100644 index 000000000..1049ff131 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Conductors.java @@ -0,0 +1,26 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.time.Duration; + +/** Small shared helpers. */ +public final class Conductors { + + private Conductors() {} + + /** A duration in the server's WAIT format; never zero, since a zero WAIT waits forever. */ + public static String duration(Duration d) { + return Math.max(1, d.toSeconds()) + "s"; + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Engine.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Engine.java new file mode 100644 index 000000000..859a28d90 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Engine.java @@ -0,0 +1,83 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.function.BooleanSupplier; +import java.util.function.Function; +import java.util.function.Supplier; + +import org.conductoross.conductor.sdk.Backoff; +import org.conductoross.conductor.sdk.Functions; +import org.conductoross.conductor.sdk.Promise; + +/** + * What workflow code can ask of whatever is running it. The static API in {@code Conductor} + * forwards every call to the engine bound to the current thread: the replay engine when the code + * runs against a server, the in-memory engine in tests. + */ +public interface Engine { + + /** A call that needs a result; returns it decoded, or throws TaskFailure. */ + Object call(Command command); + + /** A call that needs no result (events, fire-and-forget workflows). */ + void fire(Command command); + + Object once(String name, Supplier supplier); + + Instant now(); + + double random(); + + Promise async(Supplier body); + + void join(List> promises); + + List fanOut(String name, List items, Function body); + + boolean awaitCondition(BooleanSupplier condition, Duration timeout); + + Object repeatUntil(Supplier body, Functions.Pred condition, Backoff backoff); + + /** Runs one task per item, sequentially, on the server (a DO_WHILE over the items). */ + List forEach(String name, List items, Command task, String itemParameter); + + /** + * A SWITCH on {@code value}: emits the switch with every declared case so the graph shows + * all branches, runs the body of the case the value selects (or {@code otherwise}), and + * returns what it returned. Cases are keyed by the value's string form. + */ + Object switchOn(String name, Object value, java.util.Map> cases, Supplier otherwise); + + String workflowId(); + + // ------------------------------------------------------------------ binding + + /** Throws when the engine is shutting this code down and no call may take effect. */ + default void assertRunning() {} + + ThreadLocal CURRENT = new ThreadLocal<>(); + + static Engine current() { + Engine engine = CURRENT.get(); + if (engine == null) { + throw new IllegalStateException( + "this call is only valid inside a @Workflow method run by Conductor"); + } + engine.assertRunning(); + return engine; + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Entries.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Entries.java new file mode 100644 index 000000000..47527809f --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Entries.java @@ -0,0 +1,135 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Builds workflow task definitions, as JSON maps, from commands. */ +public final class Entries { + + private static final StackWalker WALKER = StackWalker.getInstance(); + + private Entries() {} + + public static Map of(Command c, String ref, String lane) { + Map e = new LinkedHashMap<>(); + e.put("name", c.name); + e.put("taskReferenceName", ref); + e.put("type", type(c.kind)); + Map input = escape(c.input); + input.putAll(c.rawInput); + e.put("inputParameters", input); + e.putAll(c.fields); + // Optional, so that once its retries are exhausted a failure continues to the lane's next + // continuation, where the code receives it as TaskFailure, instead of failing the + // workflow. In native workflows the task keeps its real status (FAILED, TIMED_OUT). + e.putIfAbsent("optional", true); + e.put("metadata", metadata(lane)); + return e; + } + + public static Map metadata(String lane) { + Map m = new LinkedHashMap<>(); + m.put("lane", lane); + String site = site(); + if (site != null) { + m.put("site", site); + } + return m; + } + + /** + * Marks {@code entry} as the task the code paused on: when it finishes, the server runs + * continuation {@code n} of {@code lane}, which appends what the code does next after it. + */ + @SuppressWarnings("unchecked") + public static Map continuation(Map entry, String lane, int n) { + Map m = (Map) entry.computeIfAbsent("metadata", k -> new LinkedHashMap<>()); + Map c = new LinkedHashMap<>(); + c.put("lane", lane); + c.put("n", n); + m.put("continuation", c); + return entry; + } + + /** + * An inline task definition with a retry policy, for server steps such as HTTP and LLM calls + * that have no registered definition: retried like any Conductor task, with exponential + * backoff, before the failure reaches the code. + */ + public static Map retryingDefinition(String name, int retryCount, long delaySeconds) { + Map def = new LinkedHashMap<>(); + def.put("name", name); + def.put("retryCount", retryCount); + def.put("retryLogic", "EXPONENTIAL_BACKOFF"); + def.put("retryDelaySeconds", delaySeconds); + def.put("timeoutSeconds", 0); + def.put("responseTimeoutSeconds", 0); + def.put("timeoutPolicy", "RETRY"); + def.put("ownerEmail", "native@conductor.local"); + return def; + } + + public static String type(Command.Kind kind) { + return switch (kind) { + case LLM -> "LLM_CHAT_COMPLETE"; + case MCP_LIST -> "LIST_MCP_TOOLS"; + case MCP_CALL -> "CALL_MCP_TOOL"; + default -> kind.name(); + }; + } + + /** The first stack frame outside the SDK and the JDK: where workflow code made the call. */ + public static String site() { + return WALKER.walk( + frames -> + frames.filter(f -> { + String c = f.getClassName(); + return !c.startsWith("org.conductoross.conductor.sdk.") + && !c.startsWith("java.") + && !c.startsWith("jdk.") + && !TaskStubs.isStubClass(c); + }) + .findFirst() + .map(f -> { + String c = f.getClassName(); + return c.substring(c.lastIndexOf('.') + 1) + "." + f.getMethodName() + ":" + f.getLineNumber(); + }) + .orElse(null)); + } + + /** + * Makes data safe to place in task input: the server treats {@code ${...}} as an expression, so + * every literal {@code ${} in a string is written as {@code $${}. + */ + @SuppressWarnings("unchecked") + public static T escape(T value) { + if (value instanceof String s) { + return (T) s.replace("${", "$${"); + } + if (value instanceof Map m) { + Map out = new LinkedHashMap<>(); + m.forEach((k, v) -> out.put(String.valueOf(k), escape(v))); + return (T) out; + } + if (value instanceof List l) { + List out = new ArrayList<>(); + l.forEach(v -> out.add(escape(v))); + return (T) out; + } + return value; + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Execution.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Execution.java new file mode 100644 index 000000000..5293207a5 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Execution.java @@ -0,0 +1,234 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * A read-only view of an execution as the server returns it ({@code GET /workflow/{id}} with + * tasks): its own grown definition, its tasks, its variables, and the continuation markers (the + * bootstrap marker in {@code nativeState}, and one on each task the code paused on). Plain JSON + * maps are used throughout because the definition carries fields (task metadata) that the client + * model classes drop. + */ +public final class Execution { + + private static final Set SUCCESS = Set.of("COMPLETED", "COMPLETED_WITH_ERRORS", "SKIPPED"); + private static final Set TERMINAL = + Set.of("COMPLETED", "COMPLETED_WITH_ERRORS", "SKIPPED", "FAILED", "FAILED_WITH_TERMINAL_ERROR", "TIMED_OUT", "CANCELED"); + + /** Set on a failed task the server marked COMPLETED_WITH_ERRORS: how the task really ended. */ + private static final String FAILED_STATUS = "conductor.failedStatus"; + + public final String workflowId; + public final String status; + public final Map input; + public final Map output; + public final Map variables; + public final Map definition; + /** The engine's native state: bootstrap and handler markers, replies, seen message ids. */ + public final Map nativeState; + public final List tasks = new ArrayList<>(); + /** Every definition entry at any depth, by reference name. */ + public final Map> entries = new java.util.LinkedHashMap<>(); + /** Every value the code recorded ({@code once}, {@code now}, {@code random}), by name. */ + public final Map recorded = new HashMap<>(); + private final Map latest = new HashMap<>(); + + @SuppressWarnings("unchecked") + public Execution(Map json) { + this.workflowId = (String) json.get("workflowId"); + this.status = (String) json.get("status"); + this.input = orEmpty((Map) json.get("input")); + this.output = orEmpty((Map) json.get("output")); + this.variables = orEmpty((Map) json.get("variables")); + this.definition = orEmpty((Map) json.get("workflowDefinition")); + this.nativeState = orEmpty((Map) json.get("nativeState")); + collect((List>) definition.get("tasks")); + List> raw = (List>) json.get("tasks"); + if (raw != null) { + for (Map t : raw) { + TaskView view = new TaskView(t); + tasks.add(view); + TaskView prev = latest.get(view.ref); + if (prev == null || prev.seq < view.seq) { + latest.put(view.ref, view); + } + } + } + tasks.sort(Comparator.comparingInt(t -> t.seq)); + for (Marker m : segments()) { + recorded.putAll(m.recorded); + } + } + + @SuppressWarnings("unchecked") + private void collect(List> list) { + if (list == null) { + return; + } + for (Map e : list) { + entries.put((String) e.get("taskReferenceName"), e); + List>> forks = (List>>) e.get("forkTasks"); + if (forks != null) { + forks.forEach(this::collect); + } + Map>> cases = (Map>>) e.get("decisionCases"); + if (cases != null) { + cases.values().forEach(this::collect); + } + collect((List>) e.get("defaultCase")); + collect((List>) e.get("loopOver")); + } + } + + /** The latest attempt of the task with exactly this reference name. */ + public TaskView latest(String ref) { + return latest.get(ref); + } + + /** The latest task whose reference name is {@code base} or {@code base__}. */ + public TaskView latestByBase(String base) { + TaskView best = null; + for (TaskView t : tasks) { + if (t.ref.equals(base) || t.ref.startsWith(base + "__")) { + if (best == null || t.seq > best.seq) { + best = t; + } + } + } + return best; + } + + /** The bootstrap marker: the first continuation of the workflow method. */ + @SuppressWarnings("unchecked") + public Marker bootstrap() { + Object b = nativeState.get("bootstrap"); + return b instanceof Map ? new Marker((Map) b) : null; + } + + /** The replies to updates and queries, by message id. */ + @SuppressWarnings("unchecked") + public Map replies() { + Object r = nativeState.get("replies"); + return r instanceof Map ? (Map) r : Map.of(); + } + + /** The ids of recently handled messages. */ + public List seen() { + List ids = new ArrayList<>(); + if (nativeState.get("seen") instanceof List l) { + l.forEach(x -> ids.add(String.valueOf(x))); + } + return ids; + } + + /** + * The continuations the server has applied, in the order it applied them (their {@code step}): + * the recording a replay follows. The handler lane is not part of it. For a task that was + * retried, the latest attempt's marker counts. + */ + public List segments() { + List segments = new ArrayList<>(); + Marker bootstrap = bootstrap(); + if (bootstrap != null && bootstrap.applied()) { + segments.add(bootstrap); + } + for (TaskView t : latest.values()) { + if (t.marker != null && t.marker.applied() && !"handlers".equals(t.marker.lane)) { + segments.add(t.marker); + } + } + segments.sort(Comparator.comparingLong((Marker m) -> m.step).thenComparingInt(m -> m.n)); + return segments; + } + + private static Map orEmpty(Map m) { + return m == null ? new LinkedHashMap<>() : m; + } + + /** A continuation marker: where the code paused, and what its completion recorded. */ + public static final class Marker { + public final String lane; + public final int n; + public final String state; + public final long step; + public final boolean done; + public final Map resumedWith; + public final Map recorded; + + @SuppressWarnings("unchecked") + Marker(Map m) { + this.lane = String.valueOf(m.get("lane")); + this.n = m.get("n") instanceof Number x ? x.intValue() : 0; + this.state = String.valueOf(m.get("state")); + this.step = m.get("step") instanceof Number x ? x.longValue() : 0L; + this.done = Boolean.TRUE.equals(m.get("done")); + this.resumedWith = orEmpty((Map) m.get("resumedWith")); + this.recorded = orEmpty((Map) m.get("recorded")); + } + + public boolean applied() { + return "APPLIED".equals(state); + } + } + + /** One task of the execution. */ + public static final class TaskView { + public final String taskId; + public final String ref; + public final String taskType; + public final String status; + public final int seq; + public final int iteration; + public final Map input; + public final Map output; + public final String reason; + public final String definitionType; + /** The continuation marker, when the code paused on this task; else null. */ + public final Marker marker; + + @SuppressWarnings("unchecked") + TaskView(Map t) { + this.taskId = (String) t.get("taskId"); + this.ref = (String) t.get("referenceTaskName"); + this.taskType = (String) t.get("taskType"); + this.seq = t.get("seq") instanceof Number n ? n.intValue() : 0; + this.iteration = t.get("iteration") instanceof Number n ? n.intValue() : 0; + this.input = orEmpty((Map) t.get("inputData")); + this.output = orEmpty((Map) t.get("outputData")); + this.status = this.output.get(FAILED_STATUS) instanceof String failed + ? failed + : (String) t.get("status"); + this.reason = (String) t.get("reasonForIncompletion"); + Map wt = (Map) t.get("workflowTask"); + this.definitionType = wt == null ? null : (String) wt.get("type"); + Object c = t.get("continuation"); + this.marker = c instanceof Map ? new Marker((Map) c) : null; + } + + public boolean terminal() { + return TERMINAL.contains(status); + } + + public boolean successful() { + return SUCCESS.contains(status); + } + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Json.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Json.java new file mode 100644 index 000000000..dd310c3ce --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Json.java @@ -0,0 +1,145 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; + +/** + * JSON conventions shared by workflow code, workers and the client. Task output follows the same + * rule as annotated workers: a scalar, string, enum or collection is {@code {"result": value}}, a + * map is the output itself, and any other object is converted to a map of its properties. + */ +public final class Json { + + public static final ObjectMapper MAPPER = create(); + + private Json() {} + + private static ObjectMapper create() { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.registerModule(new JavaTimeModule()); + return mapper; + } + + /** Converts a value to plain JSON structures: maps, lists, strings, numbers, booleans. */ + public static Object plain(Object value) { + return value == null ? null : MAPPER.convertValue(value, Object.class); + } + + public static T convert(Object value, Type type) { + if (value == null) { + return null; + } + JavaType javaType = MAPPER.getTypeFactory().constructType(type); + return MAPPER.convertValue(value, javaType); + } + + @SuppressWarnings("unchecked") + public static Map map(Object value) { + if (value == null) { + return new LinkedHashMap<>(); + } + return MAPPER.convertValue(value, LinkedHashMap.class); + } + + /** Whether values of this type travel as {@code {"result": value}}. */ + public static boolean isWrapped(Type type) { + Class raw = raw(type); + return raw.isPrimitive() + || CharSequence.class.isAssignableFrom(raw) + || Number.class.isAssignableFrom(raw) + || Boolean.class == raw + || Character.class == raw + || raw.isEnum() + || Collection.class.isAssignableFrom(raw) + || raw.isArray() + || java.time.temporal.Temporal.class.isAssignableFrom(raw); + } + + /** Encodes a task result or workflow result as an output map. */ + public static Map encodeOutput(Object value) { + Map out = new LinkedHashMap<>(); + if (value == null) { + return out; + } + if (value instanceof Map m) { + m.forEach((k, v) -> out.put(String.valueOf(k), plain(v))); + return out; + } + if (isWrapped(value.getClass())) { + out.put("result", plain(value)); + return out; + } + return map(value); + } + + /** Decodes an output map produced by {@link #encodeOutput} into the given type. */ + public static Object decodeOutput(Map output, Type type) { + Class raw = raw(type); + if (raw == void.class || raw == Void.class) { + return null; + } + if (output == null) { + return null; + } + if (isWrapped(type)) { + return convert(output.get("result"), type); + } + if (Object.class == raw) { + return output.containsKey("result") && output.size() == 1 ? output.get("result") : output; + } + try { + return convert(output, type); + } catch (IllegalArgumentException e) { + // a value that is not a JSON object (a UUID, say) is carried under "result" + if (output.size() == 1 && output.containsKey("result")) { + return convert(output.get("result"), type); + } + throw e; + } + } + + public static Class raw(Type type) { + if (type instanceof Class c) { + return c; + } + if (type instanceof ParameterizedType p) { + return (Class) p.getRawType(); + } + return Object.class; + } + + public static String write(Object value) { + try { + return MAPPER.writeValueAsString(value); + } catch (Exception e) { + throw new IllegalArgumentException("cannot serialize " + value, e); + } + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/MethodRefs.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/MethodRefs.java new file mode 100644 index 000000000..f411a398e --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/MethodRefs.java @@ -0,0 +1,138 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.io.Serializable; +import java.lang.invoke.MethodType; +import java.lang.invoke.SerializedLambda; +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Resolves a serializable method reference to the {@link Method} it names. The JVM gives every + * serializable lambda a {@code writeReplace} method returning a {@link SerializedLambda}, which + * records the implementation class, method name and descriptor. Reflection only; no bytecode is + * read or generated. + */ +public final class MethodRefs { + + private static final Map, Method> CACHE = new ConcurrentHashMap<>(); + + private MethodRefs() {} + + public static Method resolve(Serializable ref) { + return CACHE.computeIfAbsent(ref.getClass(), c -> doResolve(ref)); + } + + /** The compiled method behind a serializable lambda or method reference. */ + public record Implementation(String owner, String name, String descriptor) {} + + public static Implementation implementation(Serializable ref) { + SerializedLambda lambda = serialized(ref); + return new Implementation(lambda.getImplClass(), lambda.getImplMethodName(), lambda.getImplMethodSignature()); + } + + /** The method a bytecode method handle names, or null when it cannot be loaded. */ + static Method method(ClassLoader loader, org.objectweb.asm.Handle handle) { + try { + Class owner = Class.forName(handle.getOwner().replace('/', '.'), false, loader); + MethodType type = MethodType.fromMethodDescriptorString(handle.getDesc(), loader); + for (Class c = owner; c != null; c = c.getSuperclass()) { + try { + return c.getDeclaredMethod(handle.getName(), type.parameterArray()); + } catch (NoSuchMethodException ignored) { + // keep looking up the hierarchy + } + } + return owner.getMethod(handle.getName(), type.parameterArray()); + } catch (ReflectiveOperationException | TypeNotPresentException e) { + return null; + } + } + + private static SerializedLambda serialized(Serializable ref) { + try { + Method writeReplace = ref.getClass().getDeclaredMethod("writeReplace"); + writeReplace.setAccessible(true); + return (SerializedLambda) writeReplace.invoke(ref); + } catch (ReflectiveOperationException e) { + throw new IllegalArgumentException("not a serializable method reference: " + ref, e); + } + } + + private static Method doResolve(Serializable ref) { + SerializedLambda lambda = serialized(ref); + String name = lambda.getImplMethodName(); + if (name.startsWith("lambda$")) { + throw new IllegalArgumentException( + "expected a method reference such as Tasks::method, got a lambda"); + } + try { + ClassLoader loader = ref.getClass().getClassLoader(); + Class owner = Class.forName(lambda.getImplClass().replace('/', '.'), false, loader); + MethodType type = MethodType.fromMethodDescriptorString(lambda.getImplMethodSignature(), loader); + for (Class c = owner; c != null; c = c.getSuperclass()) { + try { + Method m = c.getDeclaredMethod(name, type.parameterArray()); + m.setAccessible(true); + return m; + } catch (NoSuchMethodException ignored) { + // keep looking up the hierarchy + } + } + Method m = owner.getMethod(name, type.parameterArray()); + m.setAccessible(true); + return m; + } catch (ReflectiveOperationException e) { + throw new IllegalArgumentException("cannot resolve method reference " + name, e); + } + } + + /** Parameter names, which need {@code -parameters} at compile time. */ + public static String[] parameterNames(Method method) { + Parameter[] params = method.getParameters(); + String[] names = new String[params.length]; + for (int i = 0; i < params.length; i++) { + com.netflix.conductor.sdk.workflow.task.InputParam ip = + params[i].getAnnotation(com.netflix.conductor.sdk.workflow.task.InputParam.class); + if (ip != null) { + names[i] = ip.value(); + } else if (params[i].isNamePresent()) { + names[i] = params[i].getName(); + } else { + throw new IllegalStateException( + "parameter names of " + + method.getDeclaringClass().getSimpleName() + + "." + + method.getName() + + " are not available: compile with -parameters, or annotate each" + + " parameter with @InputParam(\"name\")"); + } + } + return names; + } + + /** The property a boolean accessor reads: {@code done()}, {@code isDone()} and {@code getDone()} all read {@code done}. */ + public static String propertyName(Method accessor) { + String n = accessor.getName(); + if (n.startsWith("is") && n.length() > 2 && Character.isUpperCase(n.charAt(2))) { + return Character.toLowerCase(n.charAt(2)) + n.substring(3); + } + if (n.startsWith("get") && n.length() > 3 && Character.isUpperCase(n.charAt(3))) { + return Character.toLowerCase(n.charAt(3)) + n.substring(4); + } + return n; + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Replayer.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Replayer.java new file mode 100644 index 000000000..76dcce0a6 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Replayer.java @@ -0,0 +1,1711 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.Semaphore; +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.BooleanSupplier; +import java.util.function.Function; +import java.util.function.Supplier; + +import org.conductoross.conductor.sdk.Backoff; +import org.conductoross.conductor.sdk.Functions; +import org.conductoross.conductor.sdk.NonDeterminismException; +import org.conductoross.conductor.sdk.Promise; +import org.conductoross.conductor.sdk.TaskFailure; +import org.conductoross.conductor.sdk.WorkflowFailedException; + +/** + * Runs workflow code against an execution's recorded tasks and produces the next fragment. + * + *

The worker is stateless: every continuation is processed by re-running the workflow method + * from the top. Each lane (the workflow method, and each {@code async} block) runs on its own + * virtual thread, but only one runs at a time and control is handed between them explicitly, so + * the code observes a single-threaded world. + * + *

Segments are replayed in the order the live run processed them (the {@code step} the server + * recorded on each continuation marker), which reproduces reference-name allocation exactly. A + * call whose reference name is already in the definition returns the recorded result, or pauses + * the lane if that task has not finished. Before a lane resumes at a continuation, the + * {@code @Variable} fields are restored to the values recorded when that continuation was first + * processed, so code between two pauses sees exactly what it saw the first time. The active + * continuation (the one being processed now) runs against the current variables, and every new + * call it makes goes into the fragment; the last entry of the fragment carries the marker of the + * continuation that follows it. + */ +public final class Replayer { + + private enum Mode { + REPLAY, + ACTIVE + } + + private enum State { + NEW, + RUNNING, + PAUSED, + DONE + } + + /** Result of processing a continuation. */ + public static final class Outcome { + public final Map output = new LinkedHashMap<>(); + public final Map pendingConditions = new LinkedHashMap<>(); + public Object instance; + } + + private final WorkflowSpec spec; + private final Object instance; + private final Execution exec; + private final Set used = new HashSet<>(); + private final Map lanes = new LinkedHashMap<>(); + private final Participant driver = new Participant(); + private final Map pendingConditions = new LinkedHashMap<>(); + private int groupCounter; + private Mode mode = Mode.REPLAY; + private volatile boolean aborting; + private volatile RuntimeException fatal; + /** Values recorded by the active continuation, for its marker. */ + private final Map recorded = new LinkedHashMap<>(); + private String activeLaneId; + private int activeN; + public Replayer(WorkflowSpec spec, Object instance, Execution exec) { + this.spec = spec; + this.instance = instance; + this.exec = exec; + } + + /** + * Replays every applied continuation, then runs the active one (lane and number of the + * continuation being processed) and returns its completion. With a null active lane only the + * replay runs, which checks that the code still matches the recording. + */ + public Outcome process(String activeLane, int activeContinuation, Map extraVariables) { + Outcome outcome = new Outcome(); + outcome.instance = instance; + Lane main = new Lane("main", true, this::invokeWorkflowMethod); + main.counter = 1; + main.waitingFor = 1; + lanes.put(main.id, main); + try { + for (Execution.Marker seg : exec.segments()) { + runSegment(seg.lane, seg.n, Mode.REPLAY, seg.resumedWith); + } + assertNothingRecordedWasDropped(); + if (activeLane == null) { + outcome.pendingConditions.putAll(pendingConditions); + return outcome; + } + Map current = new LinkedHashMap<>(exec.variables); + this.activeLaneId = activeLane; + this.activeN = activeContinuation; + Lane lane = runSegment(activeLane, activeContinuation, Mode.ACTIVE, current); + Map out = outcome.output; + out.put("protocol", 2); + out.put("n", activeContinuation); + out.put("resumedWith", spec.captureVariablesOf(current)); + out.put("recorded", recorded); + List> fragment = lane.root; + if (lane.state == State.DONE) { + out.put("done", true); + if (lane.error != null) { + Map error = errorOf(lane.error); + if (lane.thrownRef != null) { + error.put("ref", lane.thrownRef); + } + out.put("error", error); + } else if (lane.main) { + // the workflow's output + out.put("result", Json.encodeOutput(lane.result)); + } else { + out.put("result", Map.of("value", Json.plain(lane.result))); + } + } else { + out.put("done", false); + } + out.put("fragment", fragment); + Map vars = spec.captureVariables(instance); + if (extraVariables != null) { + vars.putAll(extraVariables); + } + out.put("variables", vars); + outcome.pendingConditions.putAll(pendingConditions); + return outcome; + } finally { + abortAll(); + } + } + + /** + * The graph the code describes, read from the compiled workflow method by {@link CodeReader}: + * every call becomes an entry (switches with all their cases, async blocks as forks, loops as + * DO_WHILE). No workflow code runs. + */ + public static List> discover(WorkflowSpec spec) { + return new Replayer(spec, null, null).new Drawing("main", false, null).draw(CodeReader.read(spec.method)); + } + + /** Turns steps read from the code into definition entries. Nothing here runs workflow code. */ + private final class Drawing { + private final String lane; + private final boolean preview; + /** The case key this drawing is for, composed for nested cases, in preview names. */ + private final String key; + + Drawing(String lane, boolean preview, String key) { + this.lane = lane; + this.preview = preview; + this.key = key; + } + + @SuppressWarnings("unchecked") + List> draw(List steps) { + List> entries = new ArrayList<>(); + java.util.ArrayDeque running = new java.util.ArrayDeque<>(); + for (CodeReader.Step step : steps) { + if (step instanceof CodeReader.Call c) { + Command cmd = c.command(); + entries.add(finish(Entries.of(cmd, ref(cmd.explicitRef != null ? cmd.explicitRef : cmd.refBase), lane), c.site())); + } else if (step instanceof CodeReader.Decision d) { + entries.add(decision(d)); + } else if (step instanceof CodeReader.Fork f) { + String ref = ref("fork"); + List>> branches = new ArrayList<>(); + f.branches().forEach(b -> branches.add(draw(b))); + Map fork = structural("fork", ref, "FORK_JOIN", f.site()); + fork.put("forkTasks", branches); + entries.add(fork); + Map join = join("fork", ref, f.site()); + if (!f.joined()) { + // the engine needs a JOIN after a FORK_JOIN; this one does not wait + ((Map) join.get("metadata")).put("detached", true); + running.push(ref); + } + entries.add(join); + } else if (step instanceof CodeReader.Wait w) { + Map wait = structural("fork_wait", ref("fork_wait"), "JOIN", w.site()); + wait.put("joinOn", List.of()); + if (!running.isEmpty()) { + ((Map) wait.get("metadata")).put("waitForFork", running.pop()); + } + entries.add(wait); + } else if (step instanceof CodeReader.FanOut f) { + String ref = ref(f.name()); + Map fork = structural(f.name(), ref, "FORK_JOIN_DYNAMIC", f.site()); + fork.put("dynamicForkTasksParam", "dynamicTasks"); + fork.put("dynamicForkTasksInputParamName", "dynamicTasksInput"); + entries.add(fork); + entries.add(join(f.name(), ref, f.site())); + } else if (step instanceof CodeReader.Loop l) { + entries.add(loop(l)); + } + } + return entries; + } + + @SuppressWarnings("unchecked") + private Map decision(CodeReader.Decision d) { + Map sw = new LinkedHashMap<>(); + String ref = ref(d.name()); + sw.put("name", ref); + sw.put("taskReferenceName", ref); + sw.put("type", "SWITCH"); + sw.put("evaluatorType", "value-param"); + sw.put("expression", "switchCaseValue"); + sw.put("inputParameters", Map.of("switchCaseValue", "")); + Map>> cases = new LinkedHashMap<>(); + d.cases().forEach((k, body) -> cases.put(k, nested(k).draw(body))); + sw.put("decisionCases", cases); + sw.put("defaultCase", nested("default").draw(d.otherwise())); + sw.put("metadata", Entries.metadata(lane)); + return finish(sw, d.site()); + } + + private Map loop(CodeReader.Loop l) { + String ref = ref(l.name()); + Map entry = structural(ref, ref, "DO_WHILE", l.site()); + entry.put("loopCondition", "false"); + List> body = new ArrayList<>(); + for (CodeReader.Step step : l.body()) { + if (step instanceof CodeReader.Call c && l.perItem()) { + body.add(finish(Entries.of(c.command(), ref + "_task", lane), c.site())); + } else { + body.addAll(draw(List.of(step))); + } + } + entry.put("loopOver", body); + return entry; + } + + private Drawing nested(String caseKey) { + return new Drawing(lane, preview, key == null ? caseKey : key + "_" + caseKey); + } + + private Map structural(String name, String ref, String type, String site) { + Map entry = new LinkedHashMap<>(); + entry.put("name", name); + entry.put("taskReferenceName", ref); + entry.put("type", type); + entry.put("metadata", Entries.metadata(lane)); + return finish(entry, site); + } + + private Map join(String forkName, String forkRef, String site) { + Map entry = structural(forkName + "_join", forkRef + "_join", "JOIN", site); + entry.put("joinOn", List.of()); + return entry; + } + + @SuppressWarnings("unchecked") + private Map finish(Map entry, String site) { + Map metadata = (Map) entry.get("metadata"); + metadata.put("site", site); + if (preview) { + metadata.put("preview", true); + entry.remove("optional"); + } + return entry; + } + + /** The name of an entry: as an execution would allocate it, or marked with its case. */ + private String ref(String base) { + if (!preview) { + return alloc(base); + } + String stem = base + "_if_" + (key == null ? "preview" : key.replaceAll("[^A-Za-z0-9]", "_")); + String ref = stem; + // previews are drawn only when a switch is first emitted, so a name an earlier + // fragment took is not in used; the recording has it + for (int n = 2; used.contains(ref) || (exec != null && exec.entries.containsKey(ref)); n++) { + ref = stem + "_" + n; + } + used.add(ref); + return ref; + } + } + + private Lane runSegment(String laneId, int continuation, Mode m, Map vars) { + Lane lane = lanes.get(laneId); + if (lane == null) { + throw new NonDeterminismException("the recording continues lane " + laneId + ", which the code never started"); + } + if (lane.state == State.DONE) { + throw new NonDeterminismException("the recording continues lane " + laneId + ", which already returned"); + } + if (lane.waitingFor != continuation) { + throw new NonDeterminismException( + "lane " + laneId + " paused at continuation " + lane.waitingFor + " but the recording resumes continuation " + continuation); + } + mode = m; + spec.restoreVariables(instance, vars); + if (m == Mode.ACTIVE) { + lane.root = new ArrayList<>(); + lane.out = lane.root; + } + resume(lane); + return lane; + } + + private Object invokeWorkflowMethod() { + Object[] args = WorkflowSpec.decodeInput(spec.method, exec.input); + try { + return spec.method.invoke(instance, args); + } catch (InvocationTargetException e) { + Throwable cause = e.getCause(); + if (cause instanceof RuntimeException re) { + throw re; + } + if (cause instanceof Error err) { + throw err; + } + throw new WorkflowFailedException(cause.toString()); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + + // ------------------------------------------------------------------ control transfer + + private static class Participant { + final Semaphore sem = new Semaphore(0); + } + + private static final class LaneAbort extends Error { + LaneAbort() { + super(null, null, false, false); + } + } + + private static final class Capture extends RuntimeException { + final Command command; + + Capture(Command command) { + super(null, null, false, false); + this.command = command; + } + } + + private void transfer(Participant from, Participant to, boolean fromWaits) { + to.sem.release(); + if (fromWaits) { + from.sem.acquireUninterruptibly(); + if (aborting && from instanceof Lane) { + throw new LaneAbort(); + } + } + } + + private void resume(Lane lane) { + lane.returnTo = driver; + if (lane.state == State.NEW) { + lane.start(); + } + transfer(driver, lane, true); + if (fatal != null) { + throw fatal; + } + } + + private void pause(Lane lane) { + lane.counter++; + lane.waitingFor = lane.counter; + lane.state = State.PAUSED; + transfer(lane, lane.returnTo, true); + lane.state = State.RUNNING; + } + + /** The name of the first call recorded for a lane that this replay has not reached, or null. */ + private String nextRecordedCall(String laneId) { + for (Map.Entry> entry : exec.entries.entrySet()) { + if (used.contains(entry.getKey()) + || !(entry.getValue().get("metadata") instanceof Map metadata) + || !laneId.equals(metadata.get("lane")) + || Boolean.TRUE.equals(metadata.get("preview"))) { + continue; + } + return String.valueOf(entry.getValue().get("name")); + } + return null; + } + + /** After replay every recorded step must have been reached: the code may not have dropped one. */ + @SuppressWarnings("unchecked") + private void assertNothingRecordedWasDropped() { + Set inLoops = new HashSet<>(); + for (Map entry : exec.entries.values()) { + if ("DO_WHILE".equals(entry.get("type")) && entry.get("loopOver") instanceof List body) { + addRefs((List>) body, inLoops); + } + } + for (Map.Entry> entry : exec.entries.entrySet()) { + if (!used.contains(entry.getKey()) + && !inLoops.contains(entry.getKey()) + && entry.getValue().get("metadata") instanceof Map metadata + && metadata.get("lane") != null + && !Boolean.TRUE.equals(metadata.get("preview"))) { + throw diverged("the recorded execution has " + entry.getKey() + " but the code no longer reaches it"); + } + } + } + + /** Adds the reference names of the entries at any depth. */ + @SuppressWarnings("unchecked") + private static void addRefs(List> entries, Set refs) { + for (Map e : entries) { + refs.add((String) e.get("taskReferenceName")); + if (e.get("forkTasks") instanceof List branches) { + branches.forEach(b -> addRefs((List>) b, refs)); + } + if (e.get("decisionCases") instanceof Map cases) { + cases.values().forEach(c -> addRefs((List>) c, refs)); + } + if (e.get("defaultCase") instanceof List d) { + addRefs((List>) d, refs); + } + if (e.get("loopOver") instanceof List l) { + addRefs((List>) l, refs); + } + } + } + + private RuntimeException diverged(String message) { + NonDeterminismException e = new NonDeterminismException(message); + fatal = e; + return e; + } + + private void abortAll() { + aborting = true; + for (Lane lane : lanes.values()) { + if (lane.thread != null && lane.thread.isAlive()) { + lane.sem.release(); + } + } + for (Lane lane : lanes.values()) { + if (lane.thread != null) { + try { + lane.thread.join(2000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } + } + + // ------------------------------------------------------------------ allocation + + private String alloc(String base) { + String ref = base; + for (int n = 2; used.contains(ref); n++) { + ref = base + "_" + n; + } + used.add(ref); + return ref; + } + + private String allocExact(String ref) { + if (!used.add(ref)) { + throw new IllegalArgumentException("reference name " + ref + " is used twice in this workflow"); + } + return ref; + } + + /** The error a lane ended with; for the main lane its message is the workflow's failure reason. */ + private static Map errorOf(Throwable t) { + Map e = new LinkedHashMap<>(); + e.put("type", t.getClass().getName()); + e.put( + "message", + t instanceof WorkflowFailedException || t instanceof TaskFailure + ? t.getMessage() + : t.getClass().getSimpleName() + ": " + t.getMessage()); + if (t instanceof TaskFailure tf) { + e.put("ref", tf.getTaskReferenceName()); + } + return e; + } + + // ------------------------------------------------------------------ lanes + + private final class Group { + final int index; + final String forkName; + final List members = new ArrayList<>(); + /** The fork's reference, once it has been emitted. */ + String forkRef; + /** The Java loops the group was started in: it may be emitted after they end. */ + List loops = List.of(); + + Group(int index, String forkName) { + this.index = index; + this.forkName = forkName; + } + } + + private boolean allDone(Group g) { + return g.members.stream().allMatch(l -> l.state == State.DONE); + } + + /** + * Runs before anything durable the code does next, and when a lane returns. Lanes that finished + * without pausing go inline. Lanes still running are forked with a JOIN that does not wait, so + * they run on their own; a later join or get waits for them with a JOIN of its own. + */ + @SuppressWarnings("unchecked") + private void flushSyncGroup(Lane lane) { + Group g = lane.pendingGroup; + if (g == null) { + return; + } + lane.pendingGroup = null; + if (allDone(g)) { + if (mode == Mode.ACTIVE) { + for (Lane l : g.members) { + for (Map e : l.root) { + lane.keepLoops(e, g.loops); + lane.emit(e); + } + } + } + return; + } + String forkRef = alloc(g.forkName != null ? g.forkName : "fork"); + g.forkRef = forkRef; + String joinRef = alloc(forkRef + "_join"); + if (mode == Mode.ACTIVE) { + lane.emitFork(g, forkRef); + Map join = lane.joinEntry(joinRef); + ((Map) join.get("metadata")).put("detached", true); + lane.tagLoops(join, g.loops); + lane.emit(join); + } else if (!exec.entries.containsKey(forkRef)) { + throw lane.divergedAt("the code forks as " + forkRef + " but the recorded execution has no such fork"); + } + } + + /** The lanes a wait on this one needs: itself, or what it left running if it has returned. */ + private void unfinished(Lane lane, List out) { + if (lane.state != State.DONE) { + if (!out.contains(lane)) { + out.add(lane); + } + return; + } + for (Group g : lane.groups) { + for (Lane member : g.members) { + unfinished(member, out); + } + } + } + + /** An arm of a plain Java if or switch a lane is in, and how it was drawn. */ + private static final class Inside { + final int depth; + final CodeReader.Branch branch; + final CodeReader.Arm arm; + String ref; + boolean drawn; + List> outer; + List> caseList; + int pausesBefore; + int lastLine; + + Inside(int depth, CodeReader.Branch branch, CodeReader.Arm arm) { + this.depth = depth; + this.branch = branch; + this.arm = arm; + } + } + + /** A frame of workflow code: its method and the line it calls from. */ + private record Site(Class type, String method, String descriptor, int line) { + boolean sameMethod(Site other) { + return type == other.type && method.equals(other.method) && descriptor.equals(other.descriptor); + } + + CodeReader.Shape shape() { + return CodeReader.shape(type, method, descriptor); + } + } + + private static final StackWalker FRAMES = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE); + + /** The workflow-code line an exception was thrown from, as {@code Class.method:line}. */ + private static String siteOf(Throwable t) { + for (StackTraceElement f : t.getStackTrace()) { + String c = f.getClassName(); + if (!c.startsWith("org.conductoross.conductor.sdk.") && !c.startsWith("java.") && !c.startsWith("jdk.") + && !c.startsWith("sun.") && !TaskStubs.isStubClass(c) && f.getLineNumber() > 0) { + return c.substring(c.lastIndexOf('.') + 1) + "." + f.getMethodName() + ":" + f.getLineNumber(); + } + } + return null; + } + + /** The frames of workflow code making the current call, outermost first. */ + private static List sites() { + List sites = new ArrayList<>(); + FRAMES.forEach(f -> { + String c = f.getClassName(); + if (c.startsWith("org.conductoross.conductor.sdk.") || c.startsWith("java.") || c.startsWith("jdk.") + || c.startsWith("sun.") || TaskStubs.isStubClass(c) || f.getLineNumber() < 0) { + return; + } + sites.add(0, new Site(f.getDeclaringClass(), f.getMethodName(), f.getDescriptor(), f.getLineNumber())); + }); + return sites; + } + + private final class Lane extends Participant implements Engine { + /** A finally block running while the lane is torn down at a pause must not make calls. */ + @Override + public void assertRunning() { + if (aborting) { + throw new LaneAbort(); + } + } + + final String id; + final boolean main; + final Supplier body; + Thread thread; + State state = State.NEW; + int counter; + int waitingFor; + Object result; + Throwable error; + Participant returnTo; + /** The fragment this continuation produces (what is sent to the server). */ + List> root = new ArrayList<>(); + /** Where new entries go: the fragment, or the case list of a switch the lane is inside. */ + List> out = root; + /** Set when the lane left a switch case: the next entry goes after the switch itself. */ + String anchorAfter; + /** The entry that marks where the main lane's code threw, when it did. */ + String thrownRef; + /** The plain Java ifs and switches the lane's code is inside, outermost first. */ + final List inside = new ArrayList<>(); + /** The workflow frames of the lane's last call, outermost first. */ + List lastSites = List.of(); + Group pendingGroup; + /** Every group this lane started, for joins that wait on what it left running. */ + final List groups = new ArrayList<>(); + /** The group this lane belongs to. */ + Group group; + boolean capture; + final LanePromise promise = new LanePromise<>(this); + + Lane(String id, boolean main, Supplier body) { + this.id = id; + this.main = main; + this.body = body; + } + + void start() { + // A throwaway replay runs code that may never yield, on a thread that can be abandoned + // without pinning a carrier of the virtual-thread pool. + Thread.Builder builder = Thread.ofVirtual(); + thread = builder.name("conductor-lane-" + id).unstarted(this::run); + thread.start(); + } + + /** The Java loops around the code that started this lane, which its stack cannot show. */ + List startedInLoops = List.of(); + + private List loopsHere() { + List all = new ArrayList<>(startedInLoops); + all.addAll(CodeLoops.here()); + return all; + } + + /** An entry emitted later, from elsewhere, stays in the loops it was started in. */ + @SuppressWarnings("unchecked") + private void keepLoops(Map entry, List loops) { + if (!((Map) entry.computeIfAbsent("metadata", k -> new LinkedHashMap<>())) + .containsKey("loops")) { + tagLoops(entry, loops); + } + } + + /** Marks an entry as inside these Java loops, for the execution diagram. */ + @SuppressWarnings("unchecked") + private void tagLoops(Map entry, List loops) { + Map metadata = + (Map) entry.computeIfAbsent("metadata", k -> new LinkedHashMap<>()); + metadata.put("loops", loops); + } + + /** Adds an entry to the fragment, anchored after a switch the lane has just left. */ + @SuppressWarnings("unchecked") + private Map emit(Map entry) { + if (!((Map) entry.computeIfAbsent("metadata", k -> new LinkedHashMap<>())) + .containsKey("loops")) { + List around = loopsHere(); + if (!around.isEmpty()) { + tagLoops(entry, around); + } + } + if (anchorAfter != null) { + ((Map) entry.computeIfAbsent("metadata", k -> new LinkedHashMap<>())) + .put("after", anchorAfter); + anchorAfter = null; + } + out.add(entry); + return entry; + } + + private void run() { + sem.acquireUninterruptibly(); + if (aborting) { + return; + } + Engine.CURRENT.set(this); + state = State.RUNNING; + try { + result = body.get(); + ended(); + } catch (LaneAbort abort) { + return; + } catch (Throwable t) { + error = t; + } + try { + flushSyncGroup(this); // lanes it never joined still run + } catch (LaneAbort abort) { + return; + } catch (Throwable t) { + if (error == null) { + error = t; + } + } + if (error != null && main && fatal == null + && !(error instanceof TaskFailure) && !(error instanceof NonDeterminismException)) { + // the ifs and switches the code threw inside, as at a call; the mark's reference + // is claimed on every run, so a replay of the failed execution finds its entries + List at = sitesOf(error); + try { + if (!at.isEmpty()) { + follow(at); + } + thrownRef = alloc("throw"); + if (mode == Mode.ACTIVE && !exec.entries.containsKey(thrownRef)) { + emitThrown(error, thrownRef, at); + } + } catch (RuntimeException e) { + error.addSuppressed(e); // drawing never hides the exception itself + } + } + state = State.DONE; + transfer(this, returnTo, false); + } + + /** + * Marks where the code threw: a TERMINATE entry named after the exception, at the line it + * was thrown from, where the next call would have gone (inside the switch case the code + * was in, for one). The server makes it the workflow's failed task, so the execution shows + * where it failed; it is never scheduled. + */ + private void emitThrown(Throwable t, String ref, List at) { + Map entry = new LinkedHashMap<>(); + entry.put("name", t.getClass().getSimpleName()); + entry.put("taskReferenceName", ref); + entry.put("type", "TERMINATE"); + entry.put("inputParameters", Map.of( + "terminationStatus", "FAILED", + "terminationReason", Entries.escape(String.valueOf(errorOf(t).get("message"))))); + Map metadata = Entries.metadata(id); + String site = siteOf(t); + if (site != null) { + metadata.put("site", site); + } + metadata.put("thrown", t.getClass().getName()); + entry.put("metadata", metadata); + emit(entry); + // what the code would have called next, had it not thrown: previews, never scheduled. + // The rest of each arm it threw inside goes in that arm's case, what follows after it. + for (int d = at.size() - 1; d >= 0; d--) { + Site frame = at.get(d); + List> segments = + CodeReader.stepsAfter(frame.type(), frame.method(), frame.descriptor(), frame.line()); + for (int k = 0; k < segments.size(); k++) { + for (Map preview : new Drawing(id, true, "no_error").draw(segments.get(k))) { + @SuppressWarnings("unchecked") + Map md = (Map) preview.get("metadata"); + md.put("previewAfter", ref); + emit(preview); + } + if (k < segments.size() - 1) { + leaveInnermost(d); + } + } + } + } + + /** Leaves the innermost if or switch the lane is inside in the frame at depth {@code d}. */ + private void leaveInnermost(int d) { + for (int i = inside.size() - 1; i >= 0; i--) { + if (inside.get(i).depth == d) { + while (inside.size() > i) { + leave(inside.remove(inside.size() - 1)); + } + return; + } + } + } + + /** + * The workflow frames an exception was thrown from, outermost first, as the frames of a + * call: empty when it did not come from this lane's workflow method (a lane's failure + * raised at a join keeps that lane's stack) or a frame's method is overloaded. + */ + private List sitesOf(Throwable t) { + List at = new ArrayList<>(); + for (StackTraceElement f : t.getStackTrace()) { + String c = f.getClassName(); + if (c.startsWith("org.conductoross.conductor.sdk.") || c.startsWith("java.") || c.startsWith("jdk.") + || c.startsWith("sun.") || TaskStubs.isStubClass(c) || f.getLineNumber() <= 0) { + continue; + } + Method m = uniqueMethod(c, f.getMethodName()); + if (m == null) { + return List.of(); + } + at.add(0, new Site(m.getDeclaringClass(), m.getName(), + org.objectweb.asm.Type.getMethodDescriptor(m), f.getLineNumber())); + if (m.equals(spec.method)) { + return at; + } + } + return List.of(); + } + + private Method uniqueMethod(String className, String name) { + try { + Class type = Class.forName(className, false, spec.type.getClassLoader()); + Method found = null; + for (Method m : type.getDeclaredMethods()) { + if (m.getName().equals(name)) { + if (found != null) { + return null; + } + found = m; + } + } + return found; + } catch (ClassNotFoundException | LinkageError e) { + return null; + } + } + + // ---------------------------------------------------------------- Engine + + @Override + public String workflowId() { + return exec.workflowId; + } + + @Override + public Object call(Command cmd) { + if (capture) { + throw new Capture(cmd); + } + flushSyncGroup(this); + follow(); + String ref = cmd.explicitRef != null ? allocExact(cmd.explicitRef) : alloc(cmd.refBase); + if (exec.entries.containsKey(ref)) { + if (!cmd.blocking()) { + return null; + } + // Every blocking call was a pause in the live run, so it is a pause in the replay + // too, even when the result is already recorded: the lane continues only when the + // continuation that followed this call is replayed. + pause(this); + Execution.TaskView t = exec.latest(ref); + if (t == null || !t.terminal()) { + throw diverged("lane " + id + " resumed before task " + ref + " finished"); + } + return decode(cmd, ref, t); + } + if (mode != Mode.ACTIVE) { + String recorded = nextRecordedCall(id); + throw diverged( + "The running code differs from what this execution recorded: at " + Entries.site() + + " it calls " + cmd.name + ", but the recording has " + + (recorded == null ? "no further call" : recorded) + + " there. Deploy a compatible build to continue."); + } + Map entry = emit(Entries.of(cmd, ref, id)); + if (!cmd.blocking()) { + return null; + } + Entries.continuation(entry, id, counter + 1); + pause(this); + throw new IllegalStateException("a lane resumed within the continuation that paused it"); + } + + @Override + public void fire(Command cmd) { + call(cmd); + } + + /** + * A value computed once: the live run computes it and the continuation's marker records + * it ({@code recorded}); every replay reads it back. + */ + @SuppressWarnings("unchecked") + private Object recordValue(String ref, Supplier supplier) { + Object known = exec.recorded.containsKey(ref) ? exec.recorded.get(ref) : recorded.get(ref); + if (known instanceof Map record) { + Object v = record.get("value"); + Object type = record.get("type"); + if (v == null || type == null) { + return v; + } + try { + return Json.convert(v, Class.forName(type.toString(), false, spec.type.getClassLoader())); + } catch (ClassNotFoundException e) { + return v; + } + } + if (mode != Mode.ACTIVE) { + throw diverged("the code records " + ref + " (" + Entries.site() + ") but the recorded execution has no such value"); + } + Object v = supplier.get(); + Map record = new LinkedHashMap<>(); + record.put("value", Json.plain(v)); + if (v != null) { + record.put("type", v.getClass().getName()); + } + recorded.put(ref, record); + return v; + } + + @Override + public Object once(String name, Supplier supplier) { + return recordValue(alloc(name), supplier); + } + + @Override + public Instant now() { + return (Instant) recordValue(alloc("now"), Instant::now); + } + + @Override + public double random() { + return ((Number) recordValue(alloc("random"), () -> ThreadLocalRandom.current().nextDouble())).doubleValue(); + } + + @Override + @SuppressWarnings("unchecked") + public Promise async(Supplier asyncBody) { + follow(); + if (pendingGroup == null) { + pendingGroup = new Group(++groupCounter, null); + pendingGroup.loops = loopsHere(); + } + return (Promise) spawn(pendingGroup, asyncBody).promise; + } + + private Lane spawn(Group g, Supplier laneBody) { + Lane child = new Lane("fork_" + g.index + "." + g.members.size(), false, laneBody); + child.startedInLoops = loopsHere(); + g.members.add(child); + child.group = g; + if (!groups.contains(g)) { + groups.add(g); + } + lanes.put(child.id, child); + child.returnTo = this; + child.start(); + transfer(this, child, true); + if (fatal != null) { + throw fatal; + } + return child; + } + + /** + * Waits for the lanes, then raises the first failure among the joined promises, in the + * order given, so a lane's uncaught failure fails the caller even without a get(). + */ + @Override + public void join(List> promises) { + follow(); + joinGroup(promises); + for (Promise p : promises) { + p.get(); + } + } + + /** + * Waits for the promised lanes, or for the whole pending group when none are named. Lanes + * not forked yet are forked here with a JOIN on the ones wanted; lanes already running get + * a JOIN of their own, which names them. A lane that finished waits for nothing. + */ + @SuppressWarnings("unchecked") + private void joinGroup(List> promises) { + Group g = pendingGroup; + if (g != null && allDone(g)) { + flushSyncGroup(this); + g = null; + } + List wanted = new ArrayList<>(); + if (promises.isEmpty() && g != null) { + g.members.forEach(l -> unfinished(l, wanted)); + } + for (Promise p : promises) { + if (p instanceof LanePromise lp) { + unfinished(lp.lane, wanted); + } + } + if (wanted.isEmpty()) { + return; + } + if (g != null && wanted.stream().noneMatch(g.members::contains)) { + flushSyncGroup(this); + g = null; + } + String joinRef; + boolean whole = false; + if (g != null) { + String forkRef = alloc(g.forkName != null ? g.forkName : "fork"); + g.forkRef = forkRef; + joinRef = alloc(forkRef + "_join"); + List running = new ArrayList<>(); + g.members.forEach(l -> unfinished(l, running)); + whole = running.containsAll(wanted) && wanted.containsAll(running); + if (mode == Mode.ACTIVE) { + emitFork(g, forkRef); + } else if (!exec.entries.containsKey(forkRef)) { + throw diverged("the code forks as " + forkRef + " but the recorded execution has no such fork"); + } + pendingGroup = null; + } else { + joinRef = alloc((wanted.get(0).group.forkRef != null ? wanted.get(0).group.forkRef : "fork") + "_wait"); + } + if (mode == Mode.ACTIVE) { + Map join = joinEntry(joinRef); + if (!whole) { + ((Map) join.get("metadata")).put("waitFor", wanted.stream().map(l -> l.id).toList()); + } + emit(Entries.continuation(join, id, counter + 1)); + } else if (!exec.entries.containsKey(joinRef)) { + throw diverged("the code waits at " + joinRef + " but the recorded execution has no such join"); + } + pause(this); + for (Lane l : wanted) { + if (l.state != State.DONE) { + throw diverged("lane " + id + " resumed after " + joinRef + " but a joined lane has not finished"); + } + } + } + + private void emitFork(Group g, String forkRef) { + List>> branches = new ArrayList<>(); + for (Lane l : g.members) { + if (l.state == State.DONE) { + for (Map e : l.root) { + keepLoops(e, g.loops); + emit(e); + } + } else { + branches.add(l.root); + } + } + Map fork = new LinkedHashMap<>(); + fork.put("name", forkRef); + fork.put("taskReferenceName", forkRef); + fork.put("type", "FORK_JOIN"); + fork.put("forkTasks", branches); + fork.put("metadata", Entries.metadata(id)); + tagLoops(fork, g.loops); + emit(fork); + } + + private Map joinEntry(String joinRef) { + Map join = new LinkedHashMap<>(); + join.put("name", joinRef); + join.put("taskReferenceName", joinRef); + join.put("type", "JOIN"); + join.put("joinOn", List.of()); + join.put("metadata", Entries.metadata(id)); + return join; + } + + RuntimeException divergedAt(String message) { + return diverged(message); + } + + @Override + @SuppressWarnings("unchecked") + public List fanOut(String name, List items, Function fn) { + flushSyncGroup(this); + follow(); + Group g = new Group(++groupCounter, name); + g.loops = loopsHere(); + pendingGroup = g; + for (I item : items) { + spawn(g, () -> fn.apply(item)); + } + joinGroup(List.of()); + List results = new ArrayList<>(); + for (Lane l : g.members) { + results.add((R) l.promise.get()); + } + return results; + } + + @Override + public boolean awaitCondition(BooleanSupplier condition, Duration timeout) { + flushSyncGroup(this); + follow(); + if (condition.getAsBoolean()) { + return true; + } + String ref = alloc("condition"); + if (exec.entries.containsKey(ref)) { + Execution.TaskView t = exec.latest(ref); + if (t == null || !t.terminal()) { + pendingConditions.put(ref, condition); + } + pause(this); + pendingConditions.remove(ref); + return condition.getAsBoolean(); + } + if (mode != Mode.ACTIVE) { + throw diverged("the code waits for a condition as " + ref + " but the recorded execution has no such wait"); + } + Command wait = new Command(Command.Kind.WAIT, ref, ref); + wait.input.put("duration", Conductors.duration(timeout)); + emit(Entries.continuation(Entries.of(wait, ref, id), id, counter + 1)); + pause(this); + throw new IllegalStateException("a lane resumed within the continuation that paused it"); + } + + /** + * A SWITCH task with every declared case, and the taken case's body run inline: its + * calls go inside that case (in this fragment, or after the task the code paused on + * there); the first call after the body goes after the switch itself. + */ + @Override + @SuppressWarnings("unchecked") + public Object switchOn(String name, Object value, Map> cases, Supplier otherwise) { + flushSyncGroup(this); + follow(); + String ref = alloc(name); + Object plain = Json.plain(value); + String key = plain == null ? "null" : String.valueOf(plain); + Supplier body = cases.containsKey(key) ? cases.get(key) : otherwise; + if (body == null) { + if (mode == Mode.ACTIVE && !exec.entries.containsKey(ref)) { + // the decision is still drawn, with what every case would call + Map sw = switchEntry(ref, key, cases.keySet()); + drawUntaken(sw, key, cases, null); + emit(sw); + } + throw new WorkflowFailedException("switch " + name + " has no case for " + key); + } + Map entry = exec.entries.get(ref); + List> outer = out; + List> caseList = null; + int pausesBefore = counter; + if (entry != null) { + Map in = (Map) entry.get("inputParameters"); + Object recorded = in == null ? null : in.get("switchCaseValue"); + if (!Entries.escape(key).equals(String.valueOf(recorded))) { + throw diverged("switch " + ref + " took case " + recorded + " in the recorded execution but the code now takes " + key); + } + } else { + if (mode != Mode.ACTIVE) { + throw diverged("the code switches as " + ref + " (" + Entries.site() + ") but the recorded execution has no such switch"); + } + Map sw = switchEntry(ref, key, cases.keySet()); + Map>> decisionCases = (Map>>) sw.get("decisionCases"); + List> defaultCase = (List>) sw.get("defaultCase"); + emit(sw); + drawUntaken(sw, key, cases, otherwise); + caseList = cases.containsKey(key) ? decisionCases.get(key) : defaultCase; + out = caseList; + + } + int insideBefore = inside.size(); + try { + return body.get(); + } finally { + while (inside.size() > insideBefore) { + leave(inside.remove(inside.size() - 1)); // ifs and switches in the body end with it + } + if (caseList != null && out == caseList) { + out = outer; // the body made no pause: back to the list that holds the switch + } else if (mode == Mode.ACTIVE && counter != pausesBefore) { + // this continuation resumed inside the case (the task the code paused on is in + // there) and the body has now returned: the next entry goes after the switch + anchorAfter = ref; + } + } + } + + /** + * Fills the untaken cases with what each would have called, read from the compiled code: + * entries the engine never schedules. Nothing runs. + */ + @SuppressWarnings("unchecked") + private void drawUntaken(Map sw, String key, Map> cases, Supplier otherwise) { + Map>> decisionCases = (Map>>) sw.get("decisionCases"); + for (Map.Entry> c : cases.entrySet()) { + if (!c.getKey().equals(key)) { + decisionCases.get(c.getKey()).addAll(previewOf(c.getValue(), c.getKey())); + } + } + if (otherwise != null && cases.containsKey(key)) { + ((List>) sw.get("defaultCase")).addAll(previewOf(otherwise, "default")); + } + } + + /** What an untaken case would call, read from its compiled body. */ + private List> previewOf(Supplier body, String caseKey) { + try { + java.io.Serializable source = body instanceof ActionCase action ? action.action() : (java.io.Serializable) body; + return new Drawing(id, true, caseKey).draw(CodeReader.read(source)); + } catch (RuntimeException e) { + return new ArrayList<>(); // a case that cannot be read is drawn empty; the run goes on + } + } + + /** What an arm not taken would call. */ + private List> previewOf(List steps, String caseKey) { + try { + return new Drawing(id, true, caseKey).draw(steps); + } catch (RuntimeException e) { + return new ArrayList<>(); + } + } + + // ------------------------------------------------------------ plain ifs and switches + + /** + * Keeps the plain Java ifs and switches the code is inside in step with where it calls from. + * The compiled code says which lines each arm calls from, so the frames of a call say + * which arms it is in: leaving an arm ends its case; entering one draws its if or switch + * as a SWITCH with every arm, the others shown as previews, and the calls that follow go + * in that case, as in a {@code switchOn}. An if or switch the code went past without a + * call is drawn too, with the arm taken, when only one arm can be passed without a call. + */ + private void follow() { + if (capture) { + return; + } + follow(sites()); + } + + private void follow(List sites) { + int same = 0; + while (same < sites.size() && same < lastSites.size() && sites.get(same).sameMethod(lastSites.get(same))) { + same++; + if (sites.get(same - 1).line() != lastSites.get(same - 1).line()) { + break; // a different call from this frame: the frames below it are new + } + } + List path = new ArrayList<>(); + for (int d = 0; d < sites.size(); d++) { + for (CodeReader.Branch b : sites.get(d).shape().branches()) { + CodeReader.Arm arm = b.armAt(sites.get(d).line()); + if (arm != null) { + path.add(new Inside(d, b, arm)); + } + } + } + int keep = 0; + while (keep < inside.size() && keep < path.size() && stillIn(inside.get(keep), path.get(keep), sites, same)) { + keep++; + } + while (inside.size() > keep) { + leave(inside.remove(inside.size() - 1)); + } + if (same > 0) { + int d = same - 1; + passed(sites, d, lastSites.get(d).line(), sites.get(d).line()); + } else if (lastSites.isEmpty() && !sites.isEmpty()) { + passed(sites, 0, 0, sites.get(0).line()); // the lane's first call: from the top of its code + } + for (Inside in : path.subList(keep, path.size())) { + enter(in, sites); + } + for (Inside in : inside) { + in.lastLine = sites.get(in.depth).line(); + } + lastSites = sites; + } + + /** Whether a call is still in the same pass through an arm, not in a later one. */ + private boolean stillIn(Inside open, Inside wanted, List sites, int same) { + if (open.depth != wanted.depth || open.branch != wanted.branch || open.arm != wanted.arm || open.depth >= same) { + return false; + } + int d = open.depth; + if (d < same - 1) { + return true; // the frame still calls from the same line + } + int q = sites.get(d).line(); + int l = open.lastLine; + boolean deepest = d == sites.size() - 1 && d == lastSites.size() - 1; + if (q > l || (q == l && !deepest)) { + return true; + } + for (int[] loop : open.arm.loops()) { + if (loop[0] <= q && l <= loop[1]) { + return true; // around a loop inside the arm + } + } + return false; // around a loop outside it: the if or switch was decided again + } + + /** Draws the ifs and switches a frame went past without a call, between lines p and q. */ + private void passed(List sites, int d, int p, int q) { + if (q <= p) { + return; + } + CodeReader.Shape shape = sites.get(d).shape(); + for (CodeReader.Branch b : shape.branches()) { + if (b.line() < p || b.lastLine() >= q || !outermost(b, shape, d)) { + continue; + } + boolean looped = false; + for (int[] loop : shape.loops()) { + looped |= loop[0] <= b.line() && b.lastLine() <= loop[1] && (p < loop[0] || q > loop[1]); + } + CodeReader.Arm taken = b.onlyArmWithoutCalls(); + if (!looped && taken != null) { + drawPassed(b, taken, loopsAt(sites, d, b.line())); + } + } + } + + /** The Java loops around a line of the frame at depth {@code d}: those of its callers, and its own. */ + private List loopsAt(List sites, int d, int line) { + List loops = new ArrayList<>(startedInLoops); + for (int i = 0; i <= d; i++) { + Site s = sites.get(i); + loops.addAll(CodeLoops.around(s.type(), s.method(), s.descriptor(), i == d ? line : s.line())); + } + return loops; + } + + /** Not inside another if or switch of the method, except one the lane is in. */ + private boolean outermost(CodeReader.Branch b, CodeReader.Shape shape, int d) { + for (CodeReader.Branch other : shape.branches()) { + if (other != b && other.contains(b) + && inside.stream().noneMatch(i -> i.depth == d && i.branch == other)) { + return false; + } + } + return true; + } + + /** + * The lane's code returned: its ifs and switches end, and one it went past after its last + * call is drawn when every return of the method comes after it. + */ + private void ended() { + while (!inside.isEmpty()) { + leave(inside.remove(inside.size() - 1)); + } + if (lastSites.isEmpty()) { + return; + } + Site root = lastSites.get(0); + CodeReader.Shape shape = root.shape(); + for (CodeReader.Branch b : shape.branches()) { + if (b.line() < root.line() || !outermost(b, shape, -1)) { + continue; + } + boolean unsure = shape.loops().stream().anyMatch(l -> l[0] <= b.line() && b.lastLine() <= l[1]) + || shape.returnLines().stream().anyMatch(r -> r <= b.lastLine()); + CodeReader.Arm taken = b.onlyArmWithoutCalls(); + if (!unsure && taken != null) { + drawPassed(b, taken, loopsAt(List.of(root), 0, b.line())); + } + } + } + + private void enter(Inside in, List sites) { + in.ref = alloc(in.branch.name()); + in.pausesBefore = counter; + in.outer = out; + inside.add(in); + Map entry = exec.entries.get(in.ref); + if (entry != null) { + checkTaken(in.ref, entry, in.arm); + in.drawn = true; // the calls go in this fragment, after the task paused on in there + return; + } + if (mode != Mode.ACTIVE) { + return; // recorded by a build that did not draw it: the calls go where they went + } + Map sw = branchEntry(in.branch, in.ref, in.arm); + tagLoops(sw, loopsAt(sites, in.depth, in.branch.line())); + emit(sw); + in.caseList = caseList(sw, in.arm); + out = in.caseList; + in.drawn = true; + } + + private void leave(Inside in) { + if (!in.drawn) { + return; + } + if (in.caseList != null && out == in.caseList) { + out = in.outer; + } else if (mode == Mode.ACTIVE && counter != in.pausesBefore) { + anchorAfter = in.ref; // it ended in a later continuation: what follows goes after it + } + } + + private void drawPassed(CodeReader.Branch b, CodeReader.Arm taken, List loops) { + String ref = alloc(b.name()); + Map entry = exec.entries.get(ref); + if (entry != null) { + checkTaken(ref, entry, taken); + } else if (mode == Mode.ACTIVE) { + Map sw = branchEntry(b, ref, taken); + tagLoops(sw, loops); + emit(sw); + } + } + + @SuppressWarnings("unchecked") + private void checkTaken(String ref, Map entry, CodeReader.Arm arm) { + Map in = (Map) entry.get("inputParameters"); + Object recorded = in == null ? null : in.get("switchCaseValue"); + if (!Entries.escape(arm.key()).equals(String.valueOf(recorded))) { + throw diverged(ref + " took " + recorded + " in the recorded execution but the code now takes " + arm.key()); + } + } + + @SuppressWarnings("unchecked") + private Map branchEntry(CodeReader.Branch b, String ref, CodeReader.Arm taken) { + java.util.Set keys = new java.util.LinkedHashSet<>(); + for (CodeReader.Arm arm : b.arms()) { + if (!arm.otherwise()) { + keys.add(arm.key()); + } + } + Map sw = switchEntry(ref, taken.key(), keys); + for (CodeReader.Arm arm : b.arms()) { + if (arm != taken) { + caseList(sw, arm).addAll(previewOf(arm.steps(), arm.key())); + } + } + ((Map) sw.get("metadata")).put("site", b.site()); + return sw; + } + + @SuppressWarnings("unchecked") + private List> caseList(Map sw, CodeReader.Arm arm) { + return arm.otherwise() + ? (List>) sw.get("defaultCase") + : ((Map>>) sw.get("decisionCases")).get(arm.key()); + } + + private Map switchEntry(String ref, String key, java.util.Set caseKeys) { + Map>> decisionCases = new LinkedHashMap<>(); + for (String k : caseKeys) { + decisionCases.put(k, new ArrayList<>()); + } + Map sw = new LinkedHashMap<>(); + sw.put("name", ref); + sw.put("taskReferenceName", ref); + sw.put("type", "SWITCH"); + sw.put("evaluatorType", "value-param"); + sw.put("expression", "switchCaseValue"); + sw.put("inputParameters", Map.of("switchCaseValue", Entries.escape(key))); + sw.put("decisionCases", decisionCases); + sw.put("defaultCase", new ArrayList>()); + sw.put("metadata", Entries.metadata(id)); + return sw; + } + + @Override + public Object repeatUntil(Supplier loopBody, Functions.Pred condition, Backoff backoff) { + flushSyncGroup(this); + Command check; + capture = true; + try { + loopBody.get(); + throw new IllegalArgumentException("the repeatUntil body must make exactly one task call"); + } catch (Capture c) { + check = c.command; + } finally { + capture = false; + } + String property = MethodRefs.propertyName(MethodRefs.resolve(condition)); + follow(); + String loopRef = alloc("poll"); + String checkRef = loopRef + "_check"; + used.add(loopRef + "_backoff"); + used.add(loopRef + "_wait"); + used.add(checkRef); + if (exec.entries.containsKey(loopRef)) { + pause(this); + Execution.TaskView loop = exec.latest(loopRef); + if (loop == null || !loop.terminal()) { + throw diverged("lane " + id + " resumed before loop " + loopRef + " finished"); + } + Execution.TaskView last = exec.latestByBase(checkRef); + if (last == null) { + throw new TaskFailure(loopRef, loop.status, loop.reason); + } + return decode(check, checkRef, last); + } + if (mode != Mode.ACTIVE) { + throw diverged("the code repeats " + check.name + " as " + loopRef + " but the recorded execution has no such loop"); + } + emit(Entries.continuation(loopEntry(loopRef, check, checkRef, property, backoff), id, counter + 1)); + pause(this); + throw new IllegalStateException("a lane resumed within the continuation that paused it"); + } + + /** + * One task per item, run sequentially by the server as a DO_WHILE over the items; the + * code is woken once, when every item is done. Each iteration's task reads its item from + * the loop's {@code loopItem} output. + */ + @Override + public List forEach(String name, List items, Command task, String itemParameter) { + flushSyncGroup(this); + follow(); + if (items.isEmpty()) { + return new ArrayList<>(); + } + String loopRef = alloc(name); + String taskRef = loopRef + "_task"; + used.add(taskRef); + if (exec.entries.containsKey(loopRef)) { + pause(this); + Execution.TaskView loop = exec.latest(loopRef); + if (loop == null || !loop.terminal()) { + throw diverged("lane " + id + " resumed before loop " + loopRef + " finished"); + } + List results = new ArrayList<>(); + for (int i = 1; i <= items.size(); i++) { + Execution.TaskView t = exec.latest(taskRef + "__" + i); + if (t == null) { + throw new TaskFailure(loopRef, loop.status, "item " + i + " did not run: " + loop.reason); + } + results.add(decode(task, taskRef, t)); + } + return results; + } + if (mode != Mode.ACTIVE) { + throw diverged("the code iterates " + task.name + " as " + loopRef + " but the recorded execution has no such loop"); + } + task.rawInput.put(itemParameter, "${" + loopRef + ".output.loopItem}"); + Map loop = new LinkedHashMap<>(); + loop.put("name", loopRef); + loop.put("taskReferenceName", loopRef); + loop.put("type", "DO_WHILE"); + loop.put("inputParameters", Map.of("_items", Entries.escape(Json.plain(items)))); + loop.put("loopCondition", "true"); + loop.put("loopOver", List.of(Entries.of(task, taskRef, id))); + loop.put("metadata", Entries.metadata(id)); + emit(Entries.continuation(loop, id, counter + 1)); + pause(this); + throw new IllegalStateException("a lane resumed within the continuation that paused it"); + } + + private Map loopEntry(String loopRef, Command check, String checkRef, String property, Backoff b) { + Map backoffInput = new LinkedHashMap<>(); + backoffInput.put("evaluatorType", "graaljs"); + backoffInput.put( + "expression", + "(function(){ var i = $.iteration || 1; var s = Math.round(" + + b.interval().toSeconds() + " * Math.pow(" + b.factor() + ", i - 1)); return Math.max(1, Math.min(s, " + + b.max().toSeconds() + ")) + 's'; })()"); + backoffInput.put("iteration", "${" + loopRef + ".output.iteration}"); + Map backoffTask = new LinkedHashMap<>(); + backoffTask.put("name", loopRef + "_backoff"); + backoffTask.put("taskReferenceName", loopRef + "_backoff"); + backoffTask.put("type", "INLINE"); + backoffTask.put("inputParameters", backoffInput); + backoffTask.put("metadata", Entries.metadata(id)); + Map waitTask = new LinkedHashMap<>(); + waitTask.put("name", loopRef + "_wait"); + waitTask.put("taskReferenceName", loopRef + "_wait"); + waitTask.put("type", "WAIT"); + waitTask.put("inputParameters", Map.of("duration", "${" + loopRef + "_backoff.output.result}")); + waitTask.put("metadata", Entries.metadata(id)); + Map checkTask = Entries.of(check, checkRef, id); + Map loop = new LinkedHashMap<>(); + loop.put("name", loopRef); + loop.put("taskReferenceName", loopRef); + loop.put("type", "DO_WHILE"); + loop.put("inputParameters", new LinkedHashMap<>()); + loop.put( + "loopCondition", + "$." + checkRef + "['" + property + "'] != true && $." + loopRef + "['iteration'] < " + b.attempts()); + loop.put("loopOver", List.of(backoffTask, waitTask, checkTask)); + loop.put("metadata", Entries.metadata(id)); + return loop; + } + } + + private Object decode(Command cmd, String ref, Execution.TaskView t) { + if (t.successful()) { + Map output = t.output; + if (cmd.emptyIsEmpty && (output == null || output.isEmpty())) { + return Optional.empty(); + } + Object v; + if (cmd.httpBody) { + Object response = output.get("response"); + Object body = response instanceof Map r ? r.get("body") : null; + v = Json.convert(body, cmd.resultType); + } else if (cmd.outputKey != null) { + v = Json.convert(output.get(cmd.outputKey), cmd.resultType); + } else { + v = Json.decodeOutput(output, cmd.resultType); + } + return cmd.optional ? Optional.ofNullable(v) : v; + } + if (cmd.timeoutIsEmpty && "TIMED_OUT".equals(t.status)) { + return Optional.empty(); + } + throw new TaskFailure(ref, t.status, t.reason); + } + + /** The promise of an async lane. */ + private final class LanePromise implements Promise { + private final Lane lane; + + LanePromise(Lane lane) { + this.lane = lane; + } + + @Override + @SuppressWarnings("unchecked") + public T get() { + ((Lane) Engine.current()).joinGroup(List.of(this)); + if (lane.error instanceof RuntimeException re) { + throw re; + } + if (lane.error instanceof Error err) { + throw err; + } + if (lane.error != null) { + throw new WorkflowFailedException(lane.error.toString()); + } + return (T) lane.result; + } + + @Override + public boolean isDone() { + return lane.state == State.DONE; + } + } + + /** Invokes a handler method on the instance with arguments decoded from a message. */ + public static Object invokeHandler(Object instance, Method handler, Object args) { + Object[] values; + if (handler.getParameterCount() == 0) { + values = new Object[0]; + } else if (handler.getParameterCount() == 1) { + values = new Object[] {Json.convert(args, handler.getGenericParameterTypes()[0])}; + } else { + List list = args instanceof List l ? l : List.of(); + values = new Object[handler.getParameterCount()]; + for (int i = 0; i < values.length; i++) { + values[i] = i < list.size() ? Json.convert(list.get(i), handler.getGenericParameterTypes()[i]) : null; + } + } + try { + handler.setAccessible(true); + return handler.invoke(instance, values); + } catch (InvocationTargetException e) { + Throwable c = e.getCause(); + throw c instanceof RuntimeException re ? re : new IllegalStateException(c); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/TaskStubs.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/TaskStubs.java new file mode 100644 index 000000000..becf56d84 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/TaskStubs.java @@ -0,0 +1,216 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.Parameter; +import java.util.Arrays; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; + +import org.conductoross.conductor.sdk.Conductor; + +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +import net.bytebuddy.ByteBuddy; +import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; +import net.bytebuddy.implementation.InvocationHandlerAdapter; + +import static net.bytebuddy.matcher.ElementMatchers.isDeclaredBy; +import static net.bytebuddy.matcher.ElementMatchers.isFinal; +import static net.bytebuddy.matcher.ElementMatchers.isStatic; +import static net.bytebuddy.matcher.ElementMatchers.not; + +/** + * Task classes as a workflow sees them. A workflow takes its task classes as constructor + * parameters and gets a stub for each: a subclass whose {@code @WorkerTask} methods schedule the + * task, as {@code Conductor.task(Tasks::method, ...)} does, instead of running the method. The + * real objects run on the workers. + */ +public final class TaskStubs { + + private static final Map, Boolean> TASK_TYPES = new ConcurrentHashMap<>(); + private static final Map, Constructor> STUB_TYPES = new ConcurrentHashMap<>(); + + /** Marks a stub. */ + public interface Stub {} + + /** Ends the name of each stub class. */ + public static final String STUB_SUFFIX = "$$ConductorStub"; + + /** Whether a stack frame's class is a stub, which is never the workflow's own code. */ + public static boolean isStubClass(String className) { + return className.endsWith(STUB_SUFFIX); + } + + private TaskStubs() {} + + /** Whether a class has {@code @WorkerTask} methods. */ + public static boolean isTaskType(Class type) { + return TASK_TYPES.computeIfAbsent(type, t -> { + for (Class c = t; c != null && c != Object.class; c = c.getSuperclass()) { + for (Method m : c.getDeclaredMethods()) { + if (m.isAnnotationPresent(WorkerTask.class)) { + return true; + } + } + } + return false; + }); + } + + @SuppressWarnings("unchecked") + public static T stub(Class type) { + try { + return (T) STUB_TYPES.computeIfAbsent(type, TaskStubs::stubType).newInstance(); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("cannot create a task stub of " + type.getName(), e); + } + } + + /** + * A new instance of a workflow class: through its no-argument constructor, or else its only + * constructor, with a stub for each task-class parameter and {@code other} supplying the rest. + * The instance is then checked: see {@link #check}. + */ + public static T newWorkflow(Class type, Function other) { + Constructor constructor = constructorOf(type); + Parameter[] parameters = constructor.getParameters(); + Object[] args = new Object[parameters.length]; + for (int i = 0; i < parameters.length; i++) { + args[i] = isTaskType(parameters[i].getType()) ? stub(parameters[i].getType()) : other.apply(parameters[i]); + } + try { + constructor.setAccessible(true); + return type.cast(constructor.newInstance(args)); + } catch (java.lang.reflect.InvocationTargetException e) { + throw new IllegalStateException("constructor of " + type.getName() + " failed", e.getCause()); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("cannot create " + type.getName(), e); + } + } + + /** For a parameter nothing supplies: only task classes are supplied outside Spring. */ + public static Object unsupplied(Parameter parameter) { + Class owner = parameter.getDeclaringExecutable().getDeclaringClass(); + throw new IllegalStateException("the constructor of " + owner.getName() + " takes a " + + parameter.getType().getSimpleName() + ", which is not a class with @WorkerTask methods:" + + " register the workflow with host().workflow(" + owner.getSimpleName() + + ".class, factory), using Conductor.stub(...) for its task classes"); + } + + /** + * Fails when a field of a workflow instance holds a real task object: its calls would run the + * method in the workflow's code, again on each replay, instead of scheduling the task. + */ + public static void check(Object workflow) { + for (Class c = workflow.getClass(); c != null && c != Object.class; c = c.getSuperclass()) { + for (Field f : c.getDeclaredFields()) { + if (Modifier.isStatic(f.getModifiers()) || !isTaskType(f.getType())) { + continue; + } + Object value; + try { + f.setAccessible(true); + value = f.get(workflow); + } catch (ReflectiveOperationException | RuntimeException e) { + continue; + } + if (value != null && !(value instanceof Stub)) { + throw new IllegalStateException("field " + f.getName() + " of " + c.getName() + " holds a " + + f.getType().getSimpleName() + " created by the workflow, so its task methods would run" + + " in the workflow on every replay: take it as a constructor parameter instead, and" + + " Conductor supplies one that schedules the tasks"); + } + } + } + } + + private static Constructor constructorOf(Class type) { + Constructor[] constructors = type.getDeclaredConstructors(); + for (Constructor c : constructors) { + if (c.getParameterCount() == 0) { + return c; + } + } + if (constructors.length == 1) { + return constructors[0]; + } + throw new IllegalStateException(type.getName() + " has several constructors and none without arguments:" + + " keep one, or register it with host().workflow(" + type.getSimpleName() + ".class, factory)"); + } + + private static Constructor stubType(Class type) { + if (Modifier.isFinal(type.getModifiers())) { + throw new IllegalStateException(type.getName() + " is final, so a workflow cannot call its tasks:" + + " make it non-final"); + } + for (Class c = type; c != null && c != Object.class; c = c.getSuperclass()) { + for (Method m : c.getDeclaredMethods()) { + if (m.isAnnotationPresent(WorkerTask.class) && Modifier.isFinal(m.getModifiers())) { + throw new IllegalStateException(c.getSimpleName() + "." + m.getName() + " is final, so a workflow" + + " cannot call it: make it non-final"); + } + } + } + try { + Class stub = new ByteBuddy() + .subclass(type) + .name(type.getName() + STUB_SUFFIX) + .implement(Stub.class) + .method(not(isDeclaredBy(Object.class)).and(not(isFinal())).and(not(isStatic()))) + .intercept(InvocationHandlerAdapter.of(handler(type))) + .make() + .load(type.getClassLoader(), + ClassLoadingStrategy.UsingLookup.of(MethodHandles.privateLookupIn(type, MethodHandles.lookup()))) + .getLoaded(); + // a stub holds no state: create it without running the task class's constructor + @SuppressWarnings("removal") + Constructor constructor = sun.reflect.ReflectionFactory.getReflectionFactory() + .newConstructorForSerialization(stub, Object.class.getDeclaredConstructor()); + return constructor; + } catch (IllegalAccessException | NoSuchMethodException e) { + throw new IllegalStateException("cannot create a task stub of " + type.getName(), e); + } + } + + private static InvocationHandler handler(Class type) { + Map targets = new ConcurrentHashMap<>(); + return (proxy, method, args) -> { + Method target = targets.computeIfAbsent(method, m -> declared(type, m)); + if (!target.isAnnotationPresent(WorkerTask.class)) { + throw new UnsupportedOperationException(type.getSimpleName() + "." + method.getName() + + " is not a @WorkerTask method: a workflow calls only the tasks of " + type.getSimpleName()); + } + return Engine.current().call(Conductor.taskCommand(target, args == null ? new Object[0] : args)); + }; + } + + /** The method as the task class declares it, with its annotations. */ + private static Method declared(Class type, Method method) { + for (Class c = type; c != null; c = c.getSuperclass()) { + try { + return c.getDeclaredMethod(method.getName(), method.getParameterTypes()); + } catch (NoSuchMethodException ignored) { + // keep looking up the hierarchy + } + } + throw new IllegalStateException("no " + method + " in " + type.getName() + Arrays.toString(method.getParameterTypes())); + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/WorkflowSpec.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/WorkflowSpec.java new file mode 100644 index 000000000..fdfe0d2ad --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/WorkflowSpec.java @@ -0,0 +1,229 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +import org.conductoross.conductor.sdk.Query; +import org.conductoross.conductor.sdk.Signal; +import org.conductoross.conductor.sdk.Update; +import org.conductoross.conductor.sdk.Variable; +import org.conductoross.conductor.sdk.Workflow; + +/** Everything the SDK reads from a class with a {@link Workflow} method. */ +public final class WorkflowSpec { + + public final Class type; + public final Method method; + public final String name; + public final int version; + public final String ownerEmail; + public final String description; + public final long timeoutSeconds; + public final String failureWorkflow; + public final int failureWorkflowVersion; + public final List schedules = new ArrayList<>(); + public final Map variables = new LinkedHashMap<>(); + public final Map signals = new LinkedHashMap<>(); + public final Map updates = new LinkedHashMap<>(); + public final Map queries = new LinkedHashMap<>(); + private Supplier factory; + + private WorkflowSpec(Method method) { + Workflow wf = method.getAnnotation(Workflow.class); + this.type = method.getDeclaringClass(); + this.method = method; + method.setAccessible(true); + this.name = wf.name().isBlank() ? snake(method.getName()) : wf.name(); + this.version = wf.version(); + this.ownerEmail = wf.ownerEmail(); + this.description = wf.description(); + this.timeoutSeconds = wf.timeout().isBlank() ? 0 : Duration.parse(wf.timeout()).toSeconds(); + this.failureWorkflow = wf.failureWorkflow(); + this.failureWorkflowVersion = wf.failureWorkflowVersion(); + schedules.addAll(List.of(method.getAnnotationsByType(org.conductoross.conductor.sdk.Schedule.class))); + for (Class c = type; c != null && c != Object.class; c = c.getSuperclass()) { + for (Field f : c.getDeclaredFields()) { + Variable v = f.getAnnotation(Variable.class); + if (v != null) { + if (Modifier.isStatic(f.getModifiers()) || Modifier.isFinal(f.getModifiers())) { + throw new IllegalStateException( + "@Variable field " + f.getName() + " must be neither static nor final"); + } + f.setAccessible(true); + variables.put(v.value().isBlank() ? f.getName() : v.value(), f); + } + } + } + for (Method m : type.getMethods()) { + Signal s = m.getAnnotation(Signal.class); + Update u = m.getAnnotation(Update.class); + Query q = m.getAnnotation(Query.class); + if (s != null) { + signals.put(s.value().isBlank() ? m.getName() : s.value(), m); + } + if (u != null) { + updates.put(u.value().isBlank() ? m.getName() : u.value(), m); + } + if (q != null) { + queries.put(q.value().isBlank() ? m.getName() : q.value(), m); + } + } + this.factory = defaultFactory(type); + } + + public static WorkflowSpec of(Method method) { + if (method.getAnnotation(Workflow.class) == null) { + throw new IllegalArgumentException(method + " is not annotated with @Workflow"); + } + return new WorkflowSpec(method); + } + + /** All @Workflow methods of a class. */ + public static List of(Class type) { + List specs = new ArrayList<>(); + for (Method m : type.getMethods()) { + if (m.getAnnotation(Workflow.class) != null) { + specs.add(new WorkflowSpec(m)); + } + } + if (specs.isEmpty()) { + throw new IllegalArgumentException(type.getName() + " has no @Workflow method"); + } + return specs; + } + + public void factory(Supplier factory) { + this.factory = factory; + } + + public Object newInstance() { + Object instance = factory.get(); + TaskStubs.check(instance); + return instance; + } + + public String codeTaskName() { + return name + ".v" + version + ".code"; + } + + public boolean hasHandlers() { + return !signals.isEmpty() || !updates.isEmpty() || !queries.isEmpty(); + } + + public Method handler(String kind, String handlerName) { + Map handlers = + switch (kind) { + case "signal" -> signals; + case "update" -> updates; + case "query" -> queries; + default -> Map.of(); + }; + Method m = handlers.get(handlerName); + if (m == null) { + throw new IllegalArgumentException("no @" + kind + " handler named " + handlerName + " on " + type.getSimpleName()); + } + return m; + } + + // ------------------------------------------------------------------ input and variables + + /** Workflow input from method arguments: a single object parameter is the input itself. */ + public static Map encodeInput(Method method, Object[] args) { + if (method.getParameterCount() == 1 && !Json.isWrapped(method.getGenericParameterTypes()[0])) { + return Json.map(args[0]); + } + String[] names = MethodRefs.parameterNames(method); + Map input = new LinkedHashMap<>(); + for (int i = 0; i < names.length; i++) { + input.put(names[i], Json.plain(args[i])); + } + return input; + } + + public static Object[] decodeInput(Method method, Map input) { + if (method.getParameterCount() == 0) { + return new Object[0]; + } + if (method.getParameterCount() == 1 && !Json.isWrapped(method.getGenericParameterTypes()[0])) { + return new Object[] {Json.convert(input == null ? Map.of() : input, method.getGenericParameterTypes()[0])}; + } + String[] names = MethodRefs.parameterNames(method); + Object[] args = new Object[names.length]; + for (int i = 0; i < names.length; i++) { + Object v = input == null ? null : input.get(names[i]); + args[i] = v == null && method.getParameterTypes()[i].isPrimitive() + ? Json.convert(0, method.getGenericParameterTypes()[i]) + : Json.convert(v, method.getGenericParameterTypes()[i]); + } + return args; + } + + public Map captureVariables(Object instance) { + Map vars = new LinkedHashMap<>(); + variables.forEach( + (n, f) -> { + try { + vars.put(n, Json.plain(f.get(instance))); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + }); + return vars; + } + + /** Only the variables this class declares, from a map of workflow variables. */ + public Map captureVariablesOf(Map values) { + Map vars = new LinkedHashMap<>(); + for (String n : variables.keySet()) { + if (values.containsKey(n)) { + vars.put(n, values.get(n)); + } + } + return vars; + } + + public void restoreVariables(Object instance, Map values) { + if (values == null) { + return; + } + variables.forEach( + (n, f) -> { + if (values.containsKey(n)) { + try { + Object v = values.get(n); + f.set(instance, v == null && f.getType().isPrimitive() ? f.get(instance) : Json.convert(v, f.getGenericType())); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + }); + } + + /** Its no-argument constructor, or its only constructor with a task stub for each task class. */ + private static Supplier defaultFactory(Class type) { + return () -> TaskStubs.newWorkflow(type, TaskStubs::unsupplied); + } + + static String snake(String camel) { + return camel.replaceAll("([a-z0-9])([A-Z])", "$1_$2").toLowerCase(); + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/DirectEngine.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/DirectEngine.java new file mode 100644 index 000000000..9d638be46 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/DirectEngine.java @@ -0,0 +1,433 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.testing; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.BooleanSupplier; +import java.util.function.Function; +import java.util.function.Supplier; + +import org.conductoross.conductor.sdk.Backoff; +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.Functions; +import org.conductoross.conductor.sdk.Promise; +import org.conductoross.conductor.sdk.TaskFailure; +import org.conductoross.conductor.sdk.internal.Command; +import org.conductoross.conductor.sdk.internal.Engine; +import org.conductoross.conductor.sdk.internal.Json; +import org.conductoross.conductor.sdk.internal.MethodRefs; +import org.conductoross.conductor.sdk.internal.WorkflowSpec; + +/** + * Runs workflow code in process, answering every server call at once: tasks call the registered + * task objects (typically Mockito mocks), timers are skipped, forks run their lanes one after the + * other, child workflows run inline, and HTTP, human, external and LLM steps answer from the test's + * stubs. Reference names are derived exactly as against a server, so the graph is assertable. + */ +final class DirectEngine implements Engine { + + private final DurableTestEnvironment env; + private final String workflowId; + private final Set used = new HashSet<>(); + final List ran = new ArrayList<>(); + private Group pendingGroup; + private int blockingCalls; + private boolean capture; + + DirectEngine(DurableTestEnvironment env, String workflowId) { + this.env = env; + this.workflowId = workflowId; + } + + private static final class Group { + final String forkName; + final List> members = new ArrayList<>(); + boolean blocked; + + Group(String forkName) { + this.forkName = forkName; + } + } + + private static final class Capture extends RuntimeException { + final Command command; + + Capture(Command command) { + super(null, null, false, false); + this.command = command; + } + } + + private String alloc(String base) { + String ref = base; + for (int n = 2; used.contains(ref); n++) { + ref = base + "_" + n; + } + used.add(ref); + return ref; + } + + private String allocExact(String ref) { + if (!used.add(ref)) { + throw new IllegalArgumentException("reference name " + ref + " is used twice in this workflow"); + } + return ref; + } + + private void settleGroup() { + if (pendingGroup != null) { + Group g = pendingGroup; + pendingGroup = null; + closeGroup(g); + } + } + + private void closeGroup(Group g) { + if (g.blocked) { + String fork = alloc(g.forkName != null ? g.forkName : "fork"); + ran.add(fork); + ran.add(alloc(fork + "_join")); + } + } + + @Override + public String workflowId() { + return workflowId; + } + + @Override + public Object call(Command cmd) { + if (capture) { + throw new Capture(cmd); + } + settleGroup(); + String ref = cmd.explicitRef != null ? allocExact(cmd.explicitRef) : alloc(cmd.refBase); + return execute(cmd, ref); + } + + private Object execute(Command cmd, String ref) { + ran.add(ref); + if (cmd.blocking()) { + blockingCalls++; + } + return switch (cmd.kind) { + case SIMPLE -> decode(cmd, invokeTask(cmd, ref)); + case SUB_WORKFLOW -> decode(cmd, Json.encodeOutput(env.runChild(cmd.childMethod, cmd.childInput))); + case START_WORKFLOW, EVENT -> null; + case WAIT -> { + if (!cmd.emptyIsEmpty) { + yield null; + } + DurableTestEnvironment.Answer a = env.answers.get("external:" + ref); + yield a == null || a.timeout ? Optional.empty() : Optional.ofNullable(Json.convert(a.value, cmd.resultType)); + } + case HUMAN -> { + DurableTestEnvironment.Answer a = env.answers.get("human:" + ref); + yield a == null || a.timeout ? Optional.empty() : Optional.ofNullable(Json.convert(a.value, cmd.resultType)); + } + case HTTP -> { + DurableTestEnvironment.Answer a = env.answers.get("http:" + ref); + if (a == null || a.failure != null) { + throw new TaskFailure(ref, "FAILED", a == null ? "no http stub for " + ref : a.failure); + } + yield Json.convert(parse(String.valueOf(a.value)), cmd.resultType); + } + case MCP_LIST, MCP_CALL, AGENT -> { + String kind = cmd.kind == Command.Kind.AGENT ? "agent:" : "mcp:"; + DurableTestEnvironment.Answer a = env.answers.get(kind + ref); + if (a == null || a.failure != null) { + throw new TaskFailure(ref, "FAILED", a == null ? "no stub for " + ref : a.failure); + } + if (cmd.outputKey != null) { + yield Json.convert(a.value, cmd.resultType); + } + yield decode(cmd, Json.encodeOutput(a.value)); + } + case LLM -> { + DurableTestEnvironment.Answer a = env.answers.get("llm:" + ref); + if (a == null || a.failure != null) { + throw new TaskFailure(ref, "FAILED", a == null ? "no llm stub for " + ref : a.failure); + } + yield decode(cmd, Map.of("result", a.value)); + } + }; + } + + private static Object parse(String json) { + try { + return Json.MAPPER.readValue(json, Object.class); + } catch (Exception e) { + return json; + } + } + + private Object decode(Command cmd, Map output) { + Object v = Json.decodeOutput(output, cmd.resultType); + return cmd.optional ? Optional.ofNullable(v) : v; + } + + private Map invokeTask(Command cmd, String ref) { + Method method = cmd.method; + Object target; + Object[] args; + if (method != null) { + target = env.taskObjectFor(method.getDeclaringClass()); + args = cmd.args; + } else { + Map.Entry found = env.taskByName(cmd.name); + target = found.getKey(); + method = found.getValue(); + String[] names = MethodRefs.parameterNames(method); + args = new Object[names.length]; + for (int i = 0; i < names.length; i++) { + Object v = cmd.input.get(names[i]); + args[i] = v == null && method.getParameterTypes()[i].isPrimitive() + ? Json.convert(0, method.getGenericParameterTypes()[i]) + : Json.convert(v, method.getGenericParameterTypes()[i]); + } + } + // Retried like the server retries it: the @WorkerTask retry count (default 3), except + // after a NonRetryableException. Delays are skipped. + com.netflix.conductor.sdk.workflow.task.WorkerTask wt = + method.getAnnotation(com.netflix.conductor.sdk.workflow.task.WorkerTask.class); + int retries = wt != null && wt.retryCount() >= 0 ? wt.retryCount() : 3; + method.setAccessible(true); + for (int attempt = 0; ; attempt++) { + try { + return Json.encodeOutput(method.invoke(target, args)); + } catch (InvocationTargetException e) { + Throwable c = e.getCause(); + boolean terminal = c instanceof com.netflix.conductor.sdk.workflow.executor.task.NonRetryableException; + if (terminal || attempt >= retries) { + throw new TaskFailure( + ref, + terminal ? "FAILED_WITH_TERMINAL_ERROR" : "FAILED", + c.getMessage() == null ? c.toString() : c.getMessage()); + } + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + } + + @Override + public void fire(Command cmd) { + call(cmd); + } + + @Override + public Object switchOn(String name, Object value, Map> cases, Supplier otherwise) { + settleGroup(); + ran.add(alloc(name)); + Object plain = Json.plain(value); + String key = plain == null ? "null" : String.valueOf(plain); + Supplier body = cases.containsKey(key) ? cases.get(key) : otherwise; + if (body == null) { + throw new org.conductoross.conductor.sdk.WorkflowFailedException("switch " + name + " has no case for " + key); + } + return body.get(); + } + + @Override + public Object once(String name, Supplier supplier) { + settleGroup(); + ran.add(alloc(name)); + return supplier.get(); + } + + @Override + public Instant now() { + settleGroup(); + ran.add(alloc("now")); + return Instant.now(); + } + + @Override + public double random() { + settleGroup(); + ran.add(alloc("random")); + return ThreadLocalRandom.current().nextDouble(); + } + + @Override + public Promise async(Supplier body) { + if (pendingGroup == null) { + pendingGroup = new Group(null); + } + return run(pendingGroup, body); + } + + private DirectPromise run(Group g, Supplier body) { + int before = blockingCalls; + Group saved = pendingGroup; + pendingGroup = null; + DirectPromise p = new DirectPromise<>(); + try { + p.value = body.get(); + } catch (RuntimeException e) { + p.error = e; + } + pendingGroup = saved; + if (blockingCalls > before) { + g.blocked = true; + } + g.members.add(p); + return p; + } + + @Override + public void join(List> promises) { + settleGroup(); + for (Promise p : promises) { + p.get(); + } + } + + @Override + @SuppressWarnings("unchecked") + public List fanOut(String name, List items, Function body) { + settleGroup(); + Group g = new Group(name); + for (I item : items) { + run(g, () -> body.apply(item)); + } + closeGroup(g); + List results = new ArrayList<>(); + for (DirectPromise p : g.members) { + results.add((R) p.get()); + } + return results; + } + + @Override + public boolean awaitCondition(BooleanSupplier condition, Duration timeout) { + settleGroup(); + if (condition.getAsBoolean()) { + return true; + } + ran.add(alloc("condition")); + blockingCalls++; + return condition.getAsBoolean(); + } + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public Object repeatUntil(Supplier body, Functions.Pred condition, Backoff backoff) { + settleGroup(); + Command check; + capture = true; + try { + body.get(); + throw new IllegalArgumentException("the repeatUntil body must make exactly one task call"); + } catch (Capture c) { + check = c.command; + } finally { + capture = false; + } + MethodRefs.resolve(condition); + String loopRef = alloc("poll"); + String checkRef = loopRef + "_check"; + used.add(loopRef + "_backoff"); + used.add(loopRef + "_wait"); + used.add(checkRef); + ran.add(loopRef); + Object result = null; + for (int i = 0; i < backoff.attempts(); i++) { + try { + result = execute(check, checkRef); + } catch (TaskFailure e) { + result = null; + continue; + } + if (result != null && ((Functions.Pred) condition).test(result)) { + break; + } + } + return result; + } + + @Override + public List forEach(String name, List items, Command task, String itemParameter) { + settleGroup(); + List results = new ArrayList<>(); + if (items.isEmpty()) { + return results; + } + String loopRef = alloc(name); + String taskRef = loopRef + "_task"; + used.add(taskRef); + ran.add(loopRef); + blockingCalls++; + for (Object item : items) { + task.input.put(itemParameter, Json.plain(item)); + task.args = new Object[] {item}; + results.add(execute(task, taskRef)); + } + return results; + } + + private static final class DirectPromise implements Promise { + T value; + RuntimeException error; + + @Override + public T get() { + if (error != null) { + throw error; + } + return value; + } + + @Override + public boolean isDone() { + return true; + } + } + + static Object runWorkflow(WorkflowSpec spec, Object instance, Map input, DirectEngine engine) { + Engine previous = Engine.CURRENT.get(); + Engine.CURRENT.set(engine); + try { + return spec.method.invoke(instance, WorkflowSpec.decodeInput(spec.method, input)); + } catch (InvocationTargetException e) { + Throwable c = e.getCause(); + if (c instanceof RuntimeException re) { + throw re; + } + throw new IllegalStateException(c); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } finally { + Engine.CURRENT.set(previous); + } + } + + static Map plainInput(Method method, Object input) { + return input == null ? new LinkedHashMap<>() : WorkflowSpec.encodeInput(method, new Object[] {input}); + } + + static WorkflowSpec spec(Method method) { + return Conductor.spec(method); + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/DurableReplay.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/DurableReplay.java new file mode 100644 index 000000000..40ce2479d --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/DurableReplay.java @@ -0,0 +1,64 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.testing; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import java.util.function.Supplier; + +import org.conductoross.conductor.sdk.NonDeterminismException; +import org.conductoross.conductor.sdk.internal.Execution; +import org.conductoross.conductor.sdk.internal.Json; +import org.conductoross.conductor.sdk.internal.Replayer; +import org.conductoross.conductor.sdk.internal.WorkflowSpec; + +/** + * Checks that the current code still matches a recorded execution: re-runs the workflow method + * against the execution's tasks, exactly as a worker does when it processes a continuation, and + * fails on any divergence. Record executions with {@code GET /api/workflow/{id}?includeTasks=true} + * (or {@code conductor workflow get }) and keep a few in the test resources, so a change that + * would break executions in flight fails in CI. + */ +public final class DurableReplay { + + private DurableReplay() {} + + public static void assertCompatible(Class workflowClass, Path recordedExecution) { + assertCompatible(workflowClass, null, recordedExecution); + } + + @SuppressWarnings("unchecked") + public static void assertCompatible(Class workflowClass, Supplier factory, Path recordedExecution) { + Map json; + try { + json = Json.MAPPER.readValue(Files.readString(recordedExecution), Map.class); + } catch (IOException e) { + throw new AssertionError("cannot read recorded execution " + recordedExecution + ": " + e.getMessage(), e); + } + Execution exec = new Execution(json); + String name = String.valueOf(exec.definition.get("name")); + WorkflowSpec spec = + WorkflowSpec.of(workflowClass).stream() + .filter(s -> s.name.equals(name)) + .findFirst() + .orElseThrow(() -> new AssertionError(workflowClass.getSimpleName() + " has no @Workflow named " + name)); + Object instance = factory != null ? factory.get() : spec.newInstance(); + try { + new Replayer(spec, instance, exec).process(null, 0, null); + } catch (NonDeterminismException e) { + throw new AssertionError("the code no longer matches execution " + exec.workflowId + ": " + e.getMessage(), e); + } + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/DurableTestEnvironment.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/DurableTestEnvironment.java new file mode 100644 index 000000000..3f0967be0 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/DurableTestEnvironment.java @@ -0,0 +1,255 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.testing; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Supplier; + +import org.conductoross.conductor.sdk.Functions.Fn1; +import org.conductoross.conductor.sdk.internal.MethodRefs; +import org.conductoross.conductor.sdk.internal.WorkflowSpec; + +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +/** + * Tests for native workflows without a server or Docker. {@link #inMemory()} runs the workflow + * code in process: tasks call the registered task objects, typically Mockito mocks of the task + * classes; timers are skipped; HTTP, human, external and LLM steps answer from stubs given here. + * + *

{@code
+ * try (DurableTestEnvironment env = DurableTestEnvironment.inMemory()) {
+ *     env.workflows(OrderWorkflow.class);
+ *     env.tasks(mock(PaymentTasks.class));
+ *     env.http("fraud").respond("{\"flagged\": false}");
+ *     OrderResult r = env.start(OrderWorkflow::process, order).result();
+ * }
+ * }
+ */ +public final class DurableTestEnvironment implements AutoCloseable { + + final Map answers = new HashMap<>(); + private final Map, Supplier> factories = new LinkedHashMap<>(); + private final List taskObjects = new ArrayList<>(); + + private DurableTestEnvironment() {} + + public static DurableTestEnvironment inMemory() { + return new DurableTestEnvironment(); + } + + /** + * Workflow classes, created as the host creates them: a constructor taking task classes gets + * stubs whose calls go to the task objects registered with {@link #tasks}, or a no-argument + * constructor. A constructor that also takes other parameters needs {@link #workflow(Class, + * Supplier)}. Classes used as children must be listed too. + */ + public DurableTestEnvironment workflows(Class... types) { + for (Class t : types) { + factories.putIfAbsent(t, null); + } + return this; + } + + /** A workflow class created by {@code factory}; {@code Conductor.stub(Tasks.class)} gives it task stubs. */ + public DurableTestEnvironment workflow(Class type, Supplier factory) { + factories.put(type, factory); + return this; + } + + /** Objects with {@code @WorkerTask} methods; mocks of task classes work. */ + public DurableTestEnvironment tasks(Object... objects) { + taskObjects.addAll(List.of(objects)); + return this; + } + + public HttpStub http(String ref) { + return new HttpStub(ref); + } + + public HumanStub human(String ref) { + return new HumanStub(ref); + } + + public ExternalStub external(String ref) { + return new ExternalStub(ref); + } + + public LlmStub llm(String ref) { + return new LlmStub(ref); + } + + /** Answers for an MCP step: a list of {@code McpTool} for listTools, an {@code McpResult} for a call. */ + public OutputStub mcp(String ref) { + return new OutputStub("mcp:" + ref); + } + + /** Answers for an agent step: an {@code AgentResult}. */ + public OutputStub agent(String ref) { + return new OutputStub("agent:" + ref); + } + + public final class OutputStub { + private final String key; + + OutputStub(String key) { + this.key = key; + } + + public DurableTestEnvironment respond(Object result) { + answer(key, result, null, false); + return DurableTestEnvironment.this; + } + + public DurableTestEnvironment fail(String reason) { + answer(key, null, reason, false); + return DurableTestEnvironment.this; + } + } + + public TestRun start(Fn1 workflow, A input) { + Method method = MethodRefs.resolve(workflow); + return new TestRun<>(this, method, input); + } + + @Override + public void close() {} + + // ------------------------------------------------------------------ internals + + Object newInstance(WorkflowSpec spec) { + Supplier factory = factories.get(spec.type); + return factory != null ? factory.get() : spec.newInstance(); + } + + Object runChild(Method childMethod, Object input) { + WorkflowSpec spec = DirectEngine.spec(childMethod); + DirectEngine engine = new DirectEngine(this, "child-" + UUID.randomUUID()); + return DirectEngine.runWorkflow(spec, newInstance(spec), DirectEngine.plainInput(childMethod, input), engine); + } + + Object taskObjectFor(Class type) { + for (Object o : taskObjects) { + if (type.isInstance(o)) { + return o; + } + } + throw new IllegalStateException("no task object of type " + type.getSimpleName() + "; register one with env.tasks(...)"); + } + + Map.Entry taskByName(String name) { + for (Object o : taskObjects) { + for (Class c = o.getClass(); c != null && c != Object.class; c = c.getSuperclass()) { + for (Method m : c.getDeclaredMethods()) { + WorkerTask wt = m.getAnnotation(WorkerTask.class); + if (wt != null && wt.value().equals(name)) { + return Map.entry(o, m); + } + } + } + } + throw new IllegalStateException("no @WorkerTask named " + name + " among the registered task objects"); + } + + static final class Answer { + Object value; + String failure; + boolean timeout; + } + + private void answer(String key, Object value, String failure, boolean timeout) { + Answer a = new Answer(); + a.value = value; + a.failure = failure; + a.timeout = timeout; + answers.put(key, a); + } + + public final class HttpStub { + private final String ref; + + HttpStub(String ref) { + this.ref = ref; + } + + /** The response body, as JSON text. */ + public DurableTestEnvironment respond(String body) { + answer("http:" + ref, body, null, false); + return DurableTestEnvironment.this; + } + + public DurableTestEnvironment fail(String reason) { + answer("http:" + ref, null, reason, false); + return DurableTestEnvironment.this; + } + } + + public final class HumanStub { + private final String ref; + + HumanStub(String ref) { + this.ref = ref; + } + + public DurableTestEnvironment answer(Object form) { + DurableTestEnvironment.this.answer("human:" + ref, form, null, false); + return DurableTestEnvironment.this; + } + + public DurableTestEnvironment timeout() { + DurableTestEnvironment.this.answer("human:" + ref, null, null, true); + return DurableTestEnvironment.this; + } + } + + public final class ExternalStub { + private final String ref; + + ExternalStub(String ref) { + this.ref = ref; + } + + public DurableTestEnvironment complete(Object body) { + answer("external:" + ref, body, null, false); + return DurableTestEnvironment.this; + } + + public DurableTestEnvironment timeout() { + answer("external:" + ref, null, null, true); + return DurableTestEnvironment.this; + } + } + + public final class LlmStub { + private final String ref; + + LlmStub(String ref) { + this.ref = ref; + } + + public DurableTestEnvironment respond(String text) { + answer("llm:" + ref, text, null, false); + return DurableTestEnvironment.this; + } + + public DurableTestEnvironment fail(String reason) { + answer("llm:" + ref, null, reason, false); + return DurableTestEnvironment.this; + } + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/TestRun.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/TestRun.java new file mode 100644 index 000000000..e080780db --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/TestRun.java @@ -0,0 +1,131 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.testing; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.conductoross.conductor.sdk.Functions.Fn1; +import org.conductoross.conductor.sdk.Functions.Proc0; +import org.conductoross.conductor.sdk.Functions.Proc1; +import org.conductoross.conductor.sdk.Signal; +import org.conductoross.conductor.sdk.TaskFailure; +import org.conductoross.conductor.sdk.Update; +import org.conductoross.conductor.sdk.WorkflowFailedException; +import org.conductoross.conductor.sdk.internal.Json; +import org.conductoross.conductor.sdk.internal.MethodRefs; +import org.conductoross.conductor.sdk.internal.Replayer; +import org.conductoross.conductor.sdk.internal.WorkflowSpec; + +/** + * An in-memory execution. Signals sent before {@link #result()} are delivered before the workflow + * code starts; {@link #result()} runs the code to the end. + */ +public final class TestRun { + + private final DurableTestEnvironment env; + private final Method method; + private final Object input; + private final List signals = new ArrayList<>(); + private DirectEngine engine; + private Object instance; + private R result; + private RuntimeException failure; + + TestRun(DurableTestEnvironment env, Method method, Object input) { + this.env = env; + this.method = method; + this.input = input; + } + + public TestRun signal(Proc1 handler, A argument) { + signals.add(new Object[] {MethodRefs.resolve(handler), argument}); + return this; + } + + public TestRun signal(Proc0 handler) { + signals.add(new Object[] {MethodRefs.resolve(handler), null}); + return this; + } + + /** Applies an update to the instance before the run (or after it, on the finished instance). */ + @SuppressWarnings("unchecked") + public V update(Fn1 handler, A argument) { + Method m = MethodRefs.resolve(handler); + if (m.getAnnotation(Update.class) == null) { + throw new IllegalArgumentException(m.getName() + " is not an @Update handler"); + } + return (V) Replayer.invokeHandler(instance(), m, Json.plain(argument)); + } + + /** Runs the workflow to the end and returns its result. */ + @SuppressWarnings("unchecked") + public R result() { + if (engine == null) { + WorkflowSpec spec = DirectEngine.spec(method); + engine = new DirectEngine(env, "test-" + UUID.randomUUID()); + Object target = instance(); + for (Object[] s : signals) { + Method handler = (Method) s[0]; + if (handler.getAnnotation(Signal.class) == null) { + throw new IllegalArgumentException(handler.getName() + " is not a @Signal handler"); + } + Replayer.invokeHandler(target, handler, Json.plain(s[1])); + } + try { + Object value = DirectEngine.runWorkflow(spec, target, DirectEngine.plainInput(method, input), engine); + result = (R) Json.decodeOutput(Json.encodeOutput(value), method.getGenericReturnType()); + } catch (TaskFailure | WorkflowFailedException e) { + failure = new WorkflowFailedException(e.getMessage()); + } catch (RuntimeException e) { + failure = e; + } + } + if (failure != null) { + throw failure; + } + return result; + } + + /** Whether a server step with this reference name ran (or was attempted). */ + public boolean ran(String ref) { + result(); + return engine.ran.contains(ref); + } + + /** Reference names that ran with this base: {@code base}, {@code base_2}, and so on. */ + public List tasks(String base) { + result(); + return engine.ran.stream().filter(r -> r.equals(base) || r.matches(java.util.regex.Pattern.quote(base) + "_\\d+")).toList(); + } + + /** All reference names, in the order they ran. */ + public List ranTasks() { + result(); + return List.copyOf(engine.ran); + } + + private Object instance() { + if (instance == null) { + instance = env.newInstance(DirectEngine.spec(method)); + } + return instance; + } + + Map variables() { + return DirectEngine.spec(method).captureVariables(instance()); + } +} diff --git a/conductor-client/src/test/java/com/netflix/conductor/sdk/workflow/executor/task/AnnotatedWorkerTests.java b/conductor-client/src/test/java/com/netflix/conductor/sdk/workflow/executor/task/AnnotatedWorkerTests.java index abc4a19fd..316e23c8a 100644 --- a/conductor-client/src/test/java/com/netflix/conductor/sdk/workflow/executor/task/AnnotatedWorkerTests.java +++ b/conductor-client/src/test/java/com/netflix/conductor/sdk/workflow/executor/task/AnnotatedWorkerTests.java @@ -414,4 +414,29 @@ void invalidWorkflowInstanceIdInputParam() throws NoSuchMethodException { final RuntimeException runtimeException = assertThrows(RuntimeException.class, () -> annotatedWorker.execute(task)); assertInstanceOf(IllegalArgumentException.class, runtimeException.getCause()); } + + public enum Shade { + DARK + } + + public static class EnumWorker { + @com.netflix.conductor.sdk.workflow.task.WorkerTask("enum_result") + public Shade doWork() { + return Shade.DARK; + } + } + + @Test + @DisplayName("a result that is not a JSON object is carried under result") + void enumResult() throws NoSuchMethodException { + var worker = new EnumWorker(); + var annotatedWorker = + new AnnotatedWorker("enum_result", worker.getClass().getMethod("doWork"), worker); + var task = new Task(); + task.setStatus(Task.Status.IN_PROGRESS); + + var result = annotatedWorker.execute(task); + + assertEquals("DARK", result.getOutputData().get("result")); + } } diff --git a/conductor-client/src/test/java/loopfixture/CodeLoopsTest.java b/conductor-client/src/test/java/loopfixture/CodeLoopsTest.java new file mode 100644 index 000000000..bcc47ea8c --- /dev/null +++ b/conductor-client/src/test/java/loopfixture/CodeLoopsTest.java @@ -0,0 +1,149 @@ +/* + * Copyright 2026 Conductor 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 loopfixture; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +import org.conductoross.conductor.sdk.internal.CodeLoops; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Lives outside the SDK's packages: the stack is read for user code only. */ +class CodeLoopsTest { + + @Test + void codeOutsideALoopIsInNone() throws Exception { + onOwnThread(CodeLoopsTest::codeOutsideALoopIsInNoneBody); + } + + private static void codeOutsideALoopIsInNoneBody() { + assertTrue(CodeLoops.here().isEmpty()); + } + + @Test + void forWhileAndDoWhileAreLoops() throws Exception { + onOwnThread(CodeLoopsTest::forWhileAndDoWhileAreLoopsBody); + } + + private static void forWhileAndDoWhileAreLoopsBody() { + List> seen = new ArrayList<>(); + for (int i = 0; i < 1; i++) { + seen.add(CodeLoops.here()); + } + int w = 0; + while (w < 1) { + seen.add(CodeLoops.here()); + w++; + } + int d = 0; + do { + seen.add(CodeLoops.here()); + d++; + } while (d < 1); + for (String ignored : List.of("x")) { + seen.add(CodeLoops.here()); + } + seen.forEach(path -> assertEquals(1, path.size(), path.toString())); + assertEquals(4, seen.stream().distinct().count(), "each loop has its own name"); + } + + @Test + void nestedLoopsAreListedOutermostFirst() throws Exception { + onOwnThread(CodeLoopsTest::nestedLoopsAreListedOutermostFirstBody); + } + + private static void nestedLoopsAreListedOutermostFirstBody() { + List outerOnly = null; + List both = null; + for (int i = 0; i < 1; i++) { + outerOnly = CodeLoops.here(); + for (int j = 0; j < 1; j++) { + both = CodeLoops.here(); + } + } + assertEquals(1, outerOnly.size()); + assertEquals(2, both.size()); + assertEquals(outerOnly.get(0), both.get(0)); + assertNotEquals(both.get(0), both.get(1)); + } + + @Test + void aLoopIsSeenThroughALambdaAndAHelperMethod() throws Exception { + onOwnThread(CodeLoopsTest::aLoopIsSeenThroughALambdaAndAHelperMethodBody); + } + + private static void aLoopIsSeenThroughALambdaAndAHelperMethodBody() { + List viaLambda = null; + List viaHelper = null; + for (int i = 0; i < 1; i++) { + Supplier> body = CodeLoops::here; + viaLambda = call(() -> CodeLoops.here()); + viaHelper = helper(); + assertEquals(1, body.get().size()); + } + assertEquals(1, viaLambda.size()); + assertEquals(1, viaHelper.size()); + } + + @Test + void aLoopInAHelperIsInsideTheLoopThatCalledIt() throws Exception { + onOwnThread(CodeLoopsTest::aLoopInAHelperIsInsideTheLoopThatCalledItBody); + } + + private static void aLoopInAHelperIsInsideTheLoopThatCalledItBody() { + List path = null; + for (int i = 0; i < 1; i++) { + path = helperWithLoop(); + } + assertEquals(2, path.size()); + assertNotEquals(path.get(0), path.get(1)); + } + + /** Like a lane, on a thread whose stack holds only this code, not the test framework's loops. */ + private static void onOwnThread(Runnable body) throws Exception { + Throwable[] failure = new Throwable[1]; + Thread thread = new Thread(() -> { + try { + body.run(); + } catch (Throwable t) { + failure[0] = t; + } + }); + thread.start(); + thread.join(); + if (failure[0] != null) { + throw new AssertionError(failure[0]); + } + } + + private static List call(Supplier> s) { + return s.get(); + } + + private static List helper() { + return CodeLoops.here(); + } + + private static List helperWithLoop() { + List path = null; + for (int i = 0; i < 1; i++) { + path = CodeLoops.here(); + } + return path; + } +} diff --git a/conductor-client/src/test/java/org/conductoross/conductor/sdk/ConductorClientOwnershipTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/ConductorClientOwnershipTest.java new file mode 100644 index 000000000..273ef960f --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/ConductorClientOwnershipTest.java @@ -0,0 +1,57 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import org.junit.jupiter.api.Test; + +import com.netflix.conductor.client.http.ConductorClient; + +import io.orkes.conductor.client.ApiClient; + +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +/** {@link Conductor} runs over a client it does not own, so an injected client keeps working. */ +class ConductorClientOwnershipTest { + + @Test + void closingLeavesTheClientToItsCreator() { + ConductorClient client = mock(ConductorClient.class); + Conductor conductor = Conductor.of(client); + assertSame(client, conductor.client()); + + conductor.close(); + + verify(client, never()).shutdown(); + } + + @Test + void aClientIsRequired() { + assertThrows(NullPointerException.class, () -> Conductor.of(null)); + } + + @Test + void theEnvironmentClientCanCarryKeys() { + ConductorClient client = ConductorClient.fromEnvironment(); + try { + assertTrue(client instanceof ApiClient, "an ApiClient, which reads CONDUCTOR_AUTH_KEY/SECRET"); + assertTrue(client.getBasePath().endsWith("/api"), client.getBasePath()); + } finally { + client.shutdown(); + } + } +} diff --git a/conductor-client/src/test/java/org/conductoross/conductor/sdk/ServerOutageTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/ServerOutageTest.java new file mode 100644 index 000000000..1cee0c238 --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/ServerOutageTest.java @@ -0,0 +1,96 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.net.ServerSocket; +import java.time.Duration; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.Test; + +import com.netflix.conductor.client.http.ConductorClient; +import com.netflix.conductor.sdk.workflow.task.InputParam; + +import okhttp3.mockwebserver.Dispatcher; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** A server that is down never fails hosting: registration is retried until it succeeds. */ +class ServerOutageTest { + + public static class Flow { + @Workflow(name = "outage_flow") + public String run(@InputParam("x") String x) { + return x; + } + } + + @Test + void registrationIsRetriedInTheBackgroundUntilTheServerAcceptsIt() throws Exception { + AtomicInteger rejected = new AtomicInteger(); + AtomicInteger registered = new AtomicInteger(); + MockWebServer server = new MockWebServer(); + server.setDispatcher(new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) { + String path = request.getPath(); + if (path.startsWith("/api/metadata/") && rejected.get() < 2) { + rejected.incrementAndGet(); + return new MockResponse().setResponseCode(503).setBody("down"); + } + if (path.startsWith("/api/metadata/workflow") && "PUT".equals(request.getMethod())) { + registered.incrementAndGet(); + } + String body = path.startsWith("/api/metadata/taskdefs") && "GET".equals(request.getMethod()) + || path.startsWith("/api/tasks/poll") ? "[]" : "{}"; + return new MockResponse().setHeader("Content-Type", "application/json").setBody(body); + } + }); + server.start(); + Conductor conductor = Conductor.of(ConductorClient.builder().basePath(server.url("/api").toString()).build()); + try { + long started = System.nanoTime(); + Workers workers = conductor.host().workflows(Flow.class).start(); + assertTrue(Duration.ofNanos(System.nanoTime() - started).toMillis() < 1000, "start does not wait for the server"); + + long deadline = System.currentTimeMillis() + 15_000; + while (!workers.registered() && System.currentTimeMillis() < deadline) { + Thread.sleep(50); + } + assertTrue(workers.registered(), "registered once the server accepted it"); + assertEquals(2, rejected.get()); + assertEquals(1, registered.get()); + } finally { + conductor.close(); + server.shutdown(); + } + } + + @Test + void anUnreachableServerDoesNotFailTheStart() throws Exception { + int port; + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); // closed again: nothing listens there + } + Conductor conductor = Conductor.of(ConductorClient.builder().basePath("http://localhost:" + port + "/api").build()); + Workers workers = conductor.host().workflows(Flow.class).start(); + Thread.sleep(1500); + assertFalse(workers.registered()); + conductor.close(); // stops the retries + } +} diff --git a/conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkerProtocolTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkerProtocolTest.java new file mode 100644 index 000000000..f0f4e8a75 --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkerProtocolTest.java @@ -0,0 +1,105 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.util.List; +import java.util.Map; + +import org.conductoross.conductor.sdk.internal.Json; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.netflix.conductor.client.http.ConductorClient; +import com.netflix.conductor.common.metadata.tasks.Task; +import com.netflix.conductor.common.metadata.tasks.TaskContinuation; +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** What a worker sends the server: failed continuations, and task definitions it does not own. */ +class WorkerProtocolTest { + + public static class Mine { + @WorkerTask("shared_task") + public void shared() {} + + @WorkerTask("my_task") + public void mine() {} + } + + private MockWebServer server; + private Conductor conductor; + + @BeforeEach + void start() throws Exception { + server = new MockWebServer(); + server.start(); + conductor = Conductor.of(ConductorClient.builder().basePath(server.url("/api").toString()).build()); + } + + @AfterEach + void stop() throws Exception { + server.shutdown(); + } + + private static MockResponse json(String body) { + return new MockResponse().setHeader("Content-Type", "application/json").setBody(body); + } + + @Test + @SuppressWarnings("unchecked") + void aContinuationThatFailsIsReportedAsTheCodesResultNotTheTasks() throws Exception { + server.enqueue(json("{\"workflowId\":\"wf-1\",\"status\":\"RUNNING\"}")); + server.enqueue(new MockResponse().setResponseCode(204)); + TaskContinuation marker = new TaskContinuation("main", 2); + marker.setState(TaskContinuation.LEASED); + marker.setEpoch(3); + Task task = new Task(); + task.setTaskId("t-1"); + task.setWorkflowInstanceId("wf-1"); + task.setReferenceTaskName("t"); + task.setStatus(Task.Status.IN_PROGRESS); + task.setContinuation(marker); + + conductor.host().process("not.hosted.code", task); // no such workflow: replay fails + + server.takeRequest(); // the fetch of the execution + RecordedRequest update = server.takeRequest(); + assertEquals("/api/tasks/update-v2", update.getPath()); + Map body = Json.MAPPER.readValue(update.getBody().readUtf8(), Map.class); + assertEquals("FAILED", body.get("status")); + Map output = (Map) body.get("outputData"); + assertEquals(2, output.get("protocol")); + assertEquals(2, output.get("n")); + assertEquals(3, output.get("epoch")); + } + + @Test + @SuppressWarnings("unchecked") + void aTaskDefinitionOwnedBySomeoneElseIsLeftAlone() throws Exception { + server.enqueue(json("[{\"name\":\"shared_task\",\"ownerEmail\":\"team-a@example.com\",\"retryCount\":7}]")); + server.enqueue(json("\"ok\"")); + + Registration.register(conductor.client(), List.of(), List.of(new Mine()), 30); + + server.takeRequest(); + RecordedRequest post = server.takeRequest(); + List> defs = Json.MAPPER.readValue(post.getBody().readUtf8(), List.class); + assertEquals(List.of("my_task"), defs.stream().map(d -> d.get("name")).toList()); + } +} diff --git a/conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkflowHandleQueryTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkflowHandleQueryTest.java new file mode 100644 index 000000000..da34e971b --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkflowHandleQueryTest.java @@ -0,0 +1,110 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.netflix.conductor.client.http.ConductorClient; + +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Queries run in the client on state restored from the execution's variables. */ +class WorkflowHandleQueryTest { + + /** A workflow whose query tries to change state, which must not stick. */ + public static class Ledger { + @Variable private List deposits = new ArrayList<>(); + + @Query("deposits") + public List deposits() { + List copy = List.copyOf(deposits); + deposits.add("written-by-a-query"); + return copy; + } + + @Workflow(name = "query_test", version = 1) + public String run(String input) { + return input; + } + } + + private MockWebServer server; + private Conductor conductor; + + @BeforeEach + void start() throws Exception { + server = new MockWebServer(); + server.start(); + conductor = Conductor.of(ConductorClient.builder().basePath(server.url("/api").toString()).build()); + } + + @AfterEach + void stop() throws Exception { + server.shutdown(); + } + + private void execution(String status, String depositsJson) { + server.enqueue(new MockResponse().setHeader("Content-Type", "application/json").setBody( + "{\"workflowId\":\"wf-1\",\"status\":\"" + status + "\",\"variables\":{\"deposits\":" + depositsJson + + "},\"nativeState\":{\"replies\":{}}}")); + } + + @Test + void aQueryReadsTheAppliedStateWithoutSendingAMessage() throws Exception { + execution("RUNNING", "[\"dep-1\",\"dep-2\"]"); + List answer = conductor.attach(Ledger::run, "wf-1").query(Ledger::deposits); + assertEquals(List.of("dep-1", "dep-2"), answer); + + assertEquals(1, server.getRequestCount()); + RecordedRequest read = server.takeRequest(); + assertEquals("GET", read.getMethod()); // a read, no message pushed, nothing written + assertTrue(read.getPath().startsWith("/api/workflow/wf-1")); + } + + @Test + void aQueryWorksOnACompletedExecutionAndItsChangesDoNotStick() { + execution("COMPLETED", "[\"dep-1\"]"); + execution("COMPLETED", "[\"dep-1\"]"); + WorkflowHandle handle = conductor.attach(Ledger::run, "wf-1"); + assertEquals(List.of("dep-1"), handle.query(Ledger::deposits)); + // the first query added to its own copy; the second sees the stored state again + assertEquals(List.of("dep-1"), handle.query(Ledger::deposits)); + assertEquals(2, server.getRequestCount()); + } + + @Test + void repliesExpireAndAreCapped() { + long now = 1_000_000_000L; + Map replies = new java.util.LinkedHashMap<>(); + replies.put("legacy", Map.of("value", 1)); // no timestamp: an older worker's reply + replies.put("old", Map.of("value", 2, "at", now - Workers.REPLY_TTL_MILLIS - 1)); + for (int i = 0; i < Workers.REPLY_LIMIT + 5; i++) { + replies.put("r" + i, Map.of("value", i, "at", now - 1000 + i)); + } + Map kept = Workers.pruneReplies(replies, now); + assertEquals(Workers.REPLY_LIMIT, kept.size()); + assertTrue(!kept.containsKey("legacy") && !kept.containsKey("old") && !kept.containsKey("r0")); + assertTrue(kept.containsKey("r" + (Workers.REPLY_LIMIT + 4))); // the newest is kept + } +} diff --git a/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/CodeReaderTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/CodeReaderTest.java new file mode 100644 index 000000000..83a959eaa --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/CodeReaderTest.java @@ -0,0 +1,279 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.Workflow; +import org.junit.jupiter.api.Test; + +import com.netflix.conductor.sdk.workflow.task.InputParam; +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +import static org.conductoross.conductor.sdk.Conductor.fanOut; +import static org.conductoross.conductor.sdk.Conductor.once; +import static org.conductoross.conductor.sdk.Conductor.sleep; +import static org.conductoross.conductor.sdk.Conductor.switchOn; +import static org.conductoross.conductor.sdk.Conductor.task; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** Steps come from the compiled code: nothing runs, so no value can stop the reading. */ +class CodeReaderTest { + + public record Plan(List items, boolean needsApproval, Map owner) {} + + public enum Tier { + GOLD + } + + static final AtomicInteger PLAIN_JAVA = new AtomicInteger(); + + public static class Tasks { + @WorkerTask("plan") + public Plan plan(@InputParam("x") String x) { + return null; + } + + @WorkerTask("approve") + public String approve(@InputParam("x") String x) { + return x; + } + + @WorkerTask("ship") + public String ship(@InputParam("x") String x) { + return x; + } + + @WorkerTask("notify") + public String tell(@InputParam("x") String x) { + return x; + } + } + + public static class Flows { + @Workflow(name = "needs_real_values") + public String needsRealValues(String x) { + Plan plan = task(Tasks::plan, x); + String first = plan.items().get(0); + int size = Integer.parseInt(plan.owner().get("size").trim()) / plan.items().size(); + task(Tasks::ship, first + size); + return task(Tasks::tell, x); + } + + @Workflow(name = "branches_and_loops") + public String branchesAndLoops(String x) { + Plan plan = task(Tasks::plan, x); + if (plan.needsApproval()) { + task(Tasks::approve, x); + } else { + task(Tasks::tell, x); + } + for (String item : plan.items()) { + task(Tasks::ship, item); + } + return "done"; + } + + @Workflow(name = "no_plain_java") + public String noPlainJava(String x) { + PLAIN_JAVA.incrementAndGet(); + String v = once("v", () -> "id-" + PLAIN_JAVA.incrementAndGet()); + return task(Tasks::ship, v); + } + + @Workflow(name = "finally_once") + public String finallyOnce(String x) { + try { + if (x.isEmpty()) { + return task(Tasks::ship, x); + } + return task(Tasks::approve, x); + } finally { + task(Tasks::tell, x); + } + } + + @Workflow(name = "helpers") + public String helpers(String x) { + List.of("a").forEach(i -> task(Tasks::ship, i)); + return helper(x); + } + + private String helper(String x) { + return task(Tasks::tell, x); + } + + @Workflow(name = "recursive") + public String recursive(String x) { + task(Tasks::ship, x); + return x.isEmpty() ? "done" : recursive(x.substring(1)); + } + + @Workflow(name = "keys") + public String keys(String x) { + switchOn("s", x) + .when("text", () -> task(Tasks::ship, x)) + .when(5, () -> task(Tasks::approve, x)) + .when(true, () -> task(Tasks::tell, x)) + .when(Tier.GOLD, () -> { + sleep(Duration.ofSeconds(1)); + }) + .otherwise(() -> task(Tasks::plan, x)) + .get(); + return "done"; + } + + @Workflow(name = "fans") + public String fans(String x) { + fanOut("spread", List.of("a"), i -> task(Tasks::ship, i)).get(); + return "done"; + } + + @Workflow(name = "joined_at_once") + public String joinedAtOnce(String x) { + org.conductoross.conductor.sdk.Promise p = Conductor.async(() -> task(Tasks::ship, x)); + Conductor.join(p); + return p.get(); + } + + @Workflow(name = "never_joined") + public String neverJoined(String x) { + Conductor.async(() -> task(Tasks::ship, x)); + return task(Tasks::tell, x); + } + + @Workflow(name = "joined_later") + public String joinedLater(String x) { + org.conductoross.conductor.sdk.Promise p = Conductor.async(() -> task(Tasks::ship, x)); + task(Tasks::tell, x); + Conductor.join(p); + return p.get(); + } + + @Workflow(name = "registers") + public String registers(String x) { + Conductor.http("get_it").get("http://example.test/a").as(String.class); + Conductor.event("fire").to("kafka:topic").send(x); + return "done"; + } + } + + private static List> discover(String workflow) { + WorkflowSpec spec = WorkflowSpec.of(Flows.class).stream().filter(s -> s.name.equals(workflow)).findFirst().orElseThrow(); + return Replayer.discover(spec); + } + + private static List refs(List> entries) { + return entries.stream().map(e -> e.get("taskReferenceName")).toList(); + } + + @Test + void codeThatWouldNeedRealValuesIsReadToTheEnd() { + assertEquals(List.of("plan", "ship", "notify"), refs(discover("needs_real_values"))); + } + + @Test + @SuppressWarnings("unchecked") + void bothSidesOfAnIfAndTheBodyOfALoopAreSeen() { + List> entries = discover("branches_and_loops"); + assertEquals(List.of("plan", "if_needsApproval", "ship"), refs(entries)); + Map sw = entries.get(1); + assertEquals("SWITCH", sw.get("type"), "an if whose arms call the server is drawn with both arms"); + assertEquals(List.of("approve"), refs(((Map>>) sw.get("decisionCases")).get("true"))); + assertEquals(List.of("notify"), refs((List>) sw.get("defaultCase"))); + } + + @Test + void noPlainJavaRuns() { + int before = PLAIN_JAVA.get(); + assertEquals(List.of("ship"), refs(discover("no_plain_java"))); + assertEquals(before, PLAIN_JAVA.get()); + } + + @Test + void aFinallyBlockCopiedToEveryExitIsOneStep() { + assertEquals(List.of("ship", "notify", "approve"), refs(discover("finally_once"))); + } + + @Test + void callsAreFollowedIntoLambdasAndHelpers() { + assertEquals(List.of("ship", "notify"), refs(discover("helpers"))); + } + + @Test + void recursionEnds() { + assertEquals(List.of("ship"), refs(discover("recursive"))); + } + + @SuppressWarnings("unchecked") + @Test + void everyKindOfConstantCaseKeyIsRead() { + Map sw = discover("keys").get(0); + assertEquals(List.of("text", "5", "true", "GOLD"), List.copyOf(((Map) sw.get("decisionCases")).keySet())); + assertEquals(List.of("plan"), refs((List>) sw.get("defaultCase"))); + } + + @Test + void aFanOutIsADynamicForkAndJoin() { + List> entries = discover("fans"); + assertEquals(List.of("spread", "spread_join"), refs(entries)); + assertEquals("FORK_JOIN_DYNAMIC", entries.get(0).get("type")); + } + + @SuppressWarnings("unchecked") + private static Map metadata(Map entry) { + return (Map) entry.get("metadata"); + } + + @Test + void aForkTheCodeJoinsHasAWaitingJoinAndOneGetAddsNothing() { + List> entries = discover("joined_at_once"); + assertEquals(List.of("fork", "fork_join"), refs(entries)); + assertEquals(null, metadata(entries.get(1)).get("detached")); + } + + @Test + void aForkNothingJoinsIsMarkedSoItDrawsAsJustAFork() { + List> entries = discover("never_joined"); + assertEquals(List.of("fork", "fork_join", "notify"), refs(entries)); + assertEquals(true, metadata(entries.get(1)).get("detached")); + } + + @Test + void aJoinAfterOtherCallsIsItsOwnStepNamingTheFork() { + List> entries = discover("joined_later"); + assertEquals(List.of("fork", "fork_join", "notify", "fork_wait"), refs(entries)); + assertEquals(true, metadata(entries.get(1)).get("detached")); + assertEquals("fork", metadata(entries.get(3)).get("waitForFork")); + } + + @SuppressWarnings("unchecked") + @Test + void constantBuilderArgumentsAreKept() { + List> entries = discover("registers"); + Map request = (Map) ((Map) entries.get(0).get("inputParameters")).get("http_request"); + assertEquals("http://example.test/a", request.get("uri")); + assertEquals("kafka:topic", entries.get(1).get("sink")); + } + + @SuppressWarnings("unchecked") + @Test + void stepsRecordTheirSourceLine() { + Map metadata = (Map) discover("fans").get(0).get("metadata"); + assertEquals(true, metadata.get("site").toString().startsWith("CodeReaderTest$Flows.fans:"), metadata.toString()); + } +} diff --git a/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/DiscoveryTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/DiscoveryTest.java new file mode 100644 index 000000000..5f7143570 --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/DiscoveryTest.java @@ -0,0 +1,176 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.time.Duration; +import java.util.List; +import java.util.Map; + +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.Promise; +import org.conductoross.conductor.sdk.Signal; +import org.conductoross.conductor.sdk.Workflow; +import org.junit.jupiter.api.Test; + +import com.netflix.conductor.sdk.workflow.task.InputParam; +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +import static org.conductoross.conductor.sdk.Conductor.async; +import static org.conductoross.conductor.sdk.Conductor.join; +import static org.conductoross.conductor.sdk.Conductor.sleep; +import static org.conductoross.conductor.sdk.Conductor.switchOn; +import static org.conductoross.conductor.sdk.Conductor.task; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** The definition registered for a workflow class is discovered from its code. */ +class DiscoveryTest { + + public static class Tasks { + @WorkerTask("pick") + public String pick(@InputParam("item") String item) { + return item; + } + + @WorkerTask("pack") + public String pack(@InputParam("item") String item) { + return item; + } + + @WorkerTask("ship") + public String ship(@InputParam("item") String item) { + return item; + } + } + + public record Order(String item, String region, int quantity) {} + + public static class Fulfilment { + boolean cancelled; + + @Signal + public void cancel() { + cancelled = true; + } + + @Workflow(name = "fulfilment", description = "Picks, packs and ships an order") + public String run(Order order) { + String picked = task(Tasks::pick, order.item()); + Promise a = async(() -> task(Tasks::pack, picked + "-a")); + Promise b = async(() -> task(Tasks::pack, picked + "-b")); + join(a, b); + sleep(Duration.ofSeconds(order.quantity() + 1)); + switchOn("region", order.region()) + .when("eu", () -> task(Tasks::ship, "eu")) + .when("us", () -> task(Tasks::ship, "us")) + .otherwise(() -> "hold") + .run(); + return picked; + } + } + + @SuppressWarnings("unchecked") + @Test + void theDefinitionHoldsTheGraphTheCodeDescribes() { + Map def = Conductor.definitions(Fulfilment.class).get(0); + + assertEquals("fulfilment", def.get("name")); + assertEquals("Picks, packs and ships an order", def.get("description")); + assertEquals(List.of("item", "region", "quantity"), def.get("inputParameters")); + Map nativeMeta = (Map) ((Map) def.get("metadata")).get("native"); + assertEquals(true, nativeMeta.get("discovered")); + assertEquals(List.of("cancel"), nativeMeta.get("signals")); + + List> tasks = (List>) def.get("tasks"); + assertEquals(List.of("pick", "fork", "fork_join", "sleep", "region"), + tasks.stream().map(t -> (String) t.get("taskReferenceName")).toList()); + // plain names, no preview marks, an inline task definition for every SIMPLE task + assertEquals("pick", tasks.get(0).get("name")); + assertFalse(((Map) tasks.get(0).get("metadata")).containsKey("preview")); + assertEquals("pick", ((Map) tasks.get(0).get("taskDefinition")).get("name")); + // the async bodies as the fork's branches + List>> branches = (List>>) tasks.get(1).get("forkTasks"); + assertEquals(2, branches.size()); + assertEquals("pack", branches.get(0).get(0).get("taskReferenceName")); + assertEquals("pack_2", branches.get(1).get(0).get("taskReferenceName")); + // the switch with every case, each holding what it would call + Map>> cases = (Map>>) tasks.get(4).get("decisionCases"); + assertEquals("ship", cases.get("eu").get(0).get("taskReferenceName")); + assertEquals("ship_2", cases.get("us").get(0).get("taskReferenceName")); + assertTrue(((List) tasks.get(4).get("defaultCase")).isEmpty()); + } + + @Test + void discoveryReadsCodeThatWouldNeedARealValue() { + WorkflowSpec spec = WorkflowSpec.of(Fragile.class).get(0); + List> tasks = Replayer.discover(spec); + assertEquals(List.of("pick", "if_length"), tasks.stream().map(t -> t.get("taskReferenceName")).toList()); + Map>> cases = (Map>>) tasks.get(1).get("decisionCases"); + assertEquals("ship", cases.get("true").get(0).get("taskReferenceName")); + } + + static final java.util.concurrent.atomic.AtomicInteger SIDE_EFFECTS = new java.util.concurrent.atomic.AtomicInteger(); + static volatile boolean releaseSpin; + + public static class Spins { + @Workflow(name = "spins") + public String run(Order order) { + task(Tasks::pick, order.item()); + while (!releaseSpin) { + Thread.onSpinWait(); // plain code that never calls a task + } + return "done"; + } + } + + public static class Once { + @Workflow(name = "once") + public String run(Order order) { + String id = Conductor.once("id", () -> "id-" + SIDE_EFFECTS.incrementAndGet()); + return task(Tasks::pick, String.valueOf(id)); + } + } + + @Test + void codeThatLoopsForeverIsReadWithoutRunningIt() { + WorkflowSpec spec = WorkflowSpec.of(Spins.class).get(0); + Map def = Registration_skeleton(spec); + Map nativeMeta = (Map) ((Map) def.get("metadata")).get("native"); + assertEquals(true, nativeMeta.get("discovered")); + assertEquals(1, ((List) def.get("tasks")).size()); + } + + private static Map Registration_skeleton(WorkflowSpec spec) { + return Conductor.definitions(spec.type).get(0); + } + + @Test + void discoveryDoesNotRunOnceSuppliers() { + int before = SIDE_EFFECTS.get(); + List> tasks = Replayer.discover(WorkflowSpec.of(Once.class).get(0)); + assertEquals(List.of("pick"), tasks.stream().map(t -> t.get("taskReferenceName")).toList()); + assertEquals(before, SIDE_EFFECTS.get()); + } + + public static class Fragile { + @Workflow(name = "fragile") + public String run(Order order) { + String picked = task(Tasks::pick, order.item()); + if (picked.length() > 3) { + return task(Tasks::ship, picked); + } + throw new IllegalStateException("too short"); + } + } +} diff --git a/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/SwitchOnTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/SwitchOnTest.java new file mode 100644 index 000000000..ed602d23a --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/SwitchOnTest.java @@ -0,0 +1,477 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.conductoross.conductor.sdk.NonDeterminismException; +import org.conductoross.conductor.sdk.Workflow; +import org.junit.jupiter.api.Test; + +import com.netflix.conductor.sdk.workflow.task.InputParam; +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +import static org.conductoross.conductor.sdk.Conductor.switchOn; +import static org.conductoross.conductor.sdk.Conductor.task; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** switchOn lowers to a SWITCH entry with every case; the taken case's calls land inside it. */ +class SwitchOnTest { + + public static class Tasks { + @WorkerTask("shipA") + public String a(@InputParam("x") String x) { + return x; + } + + @WorkerTask("shipB") + public String b(@InputParam("x") String x) { + return x; + } + + @WorkerTask("notify") + public String send(@InputParam("x") String x) { + return x; + } + } + + public static class Flow { + @Workflow(name = "switch_flow") + public String run(Map input) { + String route = String.valueOf(input.get("route")); + String r = switchOn("route", route) + .when("a", () -> task(Tasks::a, "x")) + .when("none", () -> "nothing") + .otherwise(() -> task(Tasks::b, "y")) + .get(); + return task(Tasks::send, r); + } + } + + public static class NoOtherwise { + @Workflow(name = "no_otherwise") + public String run(Map input) { + switchOn("route", input.get("route")).when("a", () -> task(Tasks::a, "x")).run(); + return "done"; + } + } + + public static class ChangedFirstCall { + @Workflow(name = "switch_flow") + public String run(Map input) { + return task(Tasks::b, "x"); + } + } + + private static WorkflowSpec spec(Class type) { + return WorkflowSpec.of(type).get(0); + } + + /** An execution with the given definition entries, tasks and applied markers. */ + private static Execution execution(Map input, List> defTasks, + List> tasks, Map bootstrap) { + Map json = new LinkedHashMap<>(); + json.put("workflowId", "wf-1"); + json.put("status", "RUNNING"); + json.put("input", input); + json.put("workflowDefinition", Map.of("name", "switch_flow", "tasks", defTasks)); + json.put("tasks", tasks); + json.put("nativeState", Map.of("bootstrap", bootstrap)); + return new Execution(json); + } + + private static Map marker(String lane, int n, String state, long step) { + Map m = new LinkedHashMap<>(); + m.put("lane", lane); + m.put("n", n); + m.put("state", state); + m.put("step", step); + m.put("resumedWith", Map.of()); + m.put("recorded", Map.of()); + return m; + } + + @SuppressWarnings("unchecked") + private static Map switchEntry(String taken, List> inCase) { + Map sw = new LinkedHashMap<>(); + sw.put("name", "route"); + sw.put("taskReferenceName", "route"); + sw.put("type", "SWITCH"); + sw.put("inputParameters", Map.of("switchCaseValue", taken)); + Map>> cases = new LinkedHashMap<>(); + cases.put("a", "a".equals(taken) ? inCase : new ArrayList<>()); + cases.put("none", new ArrayList<>()); + sw.put("decisionCases", cases); + sw.put("defaultCase", "a".equals(taken) ? new ArrayList<>() : inCase); + return sw; + } + + private static Map taskEntry(String ref, String name, Map continuation) { + Map e = new LinkedHashMap<>(); + e.put("name", name); + e.put("taskReferenceName", ref); + e.put("type", "SIMPLE"); + Map md = new LinkedHashMap<>(); + md.put("lane", "main"); + if (continuation != null) { + md.put("continuation", continuation); + } + e.put("metadata", md); + return e; + } + + private static Map doneTask(String ref, String type, int seq, Map output, Map continuation) { + Map t = new LinkedHashMap<>(); + t.put("taskId", "id-" + ref); + t.put("referenceTaskName", ref); + t.put("taskType", type); + t.put("status", "COMPLETED"); + t.put("seq", seq); + t.put("outputData", output); + t.put("workflowTask", Map.of("type", "SIMPLE".equals(type) ? "SIMPLE" : type)); + if (continuation != null) { + t.put("continuation", continuation); + } + return t; + } + + @SuppressWarnings("unchecked") + @Test + void theFirstContinuationEmitsTheSwitchWithEveryCaseAndTheTakenBodyInsideIt() { + Execution exec = execution(Map.of("route", "a"), List.of(), List.of(), marker("main", 1, "LEASED", 0)); + Replayer.Outcome out = new Replayer(spec(Flow.class), new Flow(), exec).process("main", 1, null); + + List> fragment = (List>) out.output.get("fragment"); + assertEquals(1, fragment.size(), "only the switch is at the top level: the code paused inside it"); + Map sw = fragment.get(0); + assertEquals("SWITCH", sw.get("type")); + assertEquals("value-param", sw.get("evaluatorType")); + assertEquals(Map.of("switchCaseValue", "a"), sw.get("inputParameters")); + Map>> cases = (Map>>) sw.get("decisionCases"); + assertEquals(List.of("a", "none"), new ArrayList<>(cases.keySet()), "every declared case is present"); + assertEquals(1, cases.get("a").size()); + assertEquals("shipA", cases.get("a").get(0).get("name")); + assertEquals(Map.of("lane", "main", "n", 2), ((Map) cases.get("a").get(0).get("metadata")).get("continuation")); + assertTrue(cases.get("none").isEmpty(), "an untaken case with no calls is an empty branch"); + // the untaken default case shows the task it would have called, as a preview + List> defaultCase = (List>) sw.get("defaultCase"); + assertEquals("shipB_if_default", defaultCase.get(0).get("taskReferenceName")); + assertEquals(true, ((Map) defaultCase.get(0).get("metadata")).get("preview")); + assertEquals(false, out.output.get("done")); + } + + @SuppressWarnings("unchecked") + @Test + void anEmptyCaseContinuesInlineAfterTheSwitch() { + Execution exec = execution(Map.of("route", "none"), List.of(), List.of(), marker("main", 1, "LEASED", 0)); + Replayer.Outcome out = new Replayer(spec(Flow.class), new Flow(), exec).process("main", 1, null); + + List> fragment = (List>) out.output.get("fragment"); + assertEquals(List.of("route", "notify"), fragment.stream().map(e -> e.get("taskReferenceName")).toList()); + Map sw = fragment.get(0); + assertTrue(((Map>) sw.get("decisionCases")).get("none").isEmpty()); + assertNull(((Map) fragment.get(1).get("metadata")).get("after"), "same fragment: no anchor needed"); + } + + @SuppressWarnings("unchecked") + @Test + void anUnhandledValueTakesTheDefaultCase() { + Execution exec = execution(Map.of("route", "zzz"), List.of(), List.of(), marker("main", 1, "LEASED", 0)); + Replayer.Outcome out = new Replayer(spec(Flow.class), new Flow(), exec).process("main", 1, null); + + Map sw = ((List>) out.output.get("fragment")).get(0); + assertEquals(Map.of("switchCaseValue", "zzz"), sw.get("inputParameters")); + List> defaultCase = (List>) sw.get("defaultCase"); + assertEquals("shipB", defaultCase.get(0).get("name")); + assertEquals("shipB", defaultCase.get(0).get("taskReferenceName"), "the taken body's call is real"); + Map>> cases = (Map>>) sw.get("decisionCases"); + assertEquals("shipA_if_a", cases.get("a").get(0).get("taskReferenceName"), "untaken case a previews its call"); + assertTrue(cases.get("none").isEmpty()); + } + + @Test + void anUnhandledValueWithoutOtherwiseFailsTheWorkflow() { + Execution exec = execution(Map.of("route", "zzz"), List.of(), List.of(), marker("main", 1, "LEASED", 0)); + Replayer.Outcome out = new Replayer(spec(NoOtherwise.class), new NoOtherwise(), exec).process("main", 1, null); + assertEquals(true, out.output.get("done")); + assertTrue(String.valueOf(((Map) out.output.get("error")).get("message")).contains("no case for zzz")); + } + + @SuppressWarnings("unchecked") + @Test + void resumingInsideACaseAnchorsTheNextCallAfterTheSwitch() { + // the recording: the switch took case a, whose task finished; this continuation resumes + // after it and the code leaves the case + Map aEntry = taskEntry("shipA", "shipA", Map.of("lane", "main", "n", 2)); + Execution exec = execution(Map.of("route", "a"), + List.of(switchEntry("a", List.of(aEntry))), + List.of(doneTask("route", "SWITCH", 1, Map.of("selectedCase", "a"), null), + doneTask("shipA", "shipA", 2, Map.of("result", "x"), marker("main", 2, "LEASED", 0))), + marker("main", 1, "APPLIED", 1)); + Replayer.Outcome out = new Replayer(spec(Flow.class), new Flow(), exec).process("main", 2, null); + + List> fragment = (List>) out.output.get("fragment"); + assertEquals(1, fragment.size()); + assertEquals("notify", fragment.get(0).get("taskReferenceName")); + assertEquals("route", ((Map) fragment.get(0).get("metadata")).get("after"), + "the call after the case goes after the switch, not inside the case"); + } + + public static class DroppedCall { + @Workflow(name = "dropped_call") + public String run(Map input) { + return task(Tasks::a, "x"); + } + } + + @Test + void aRecordedCallTheCodeNoLongerMakesIsADivergence() { + Execution exec = execution(Map.of(), + List.of(taskEntry("shipA", "shipA", Map.of("lane", "main", "n", 2)), taskEntry("notify", "notify", null)), + List.of(doneTask("shipA", "shipA", 1, Map.of("result", "x"), marker("main", 2, "APPLIED", 2)), + doneTask("notify", "notify", 2, Map.of("result", "y"), null)), + marker("main", 1, "APPLIED", 1)); + org.junit.jupiter.api.Assertions.assertThrows(org.conductoross.conductor.sdk.NonDeterminismException.class, + () -> new Replayer(spec(DroppedCall.class), new DroppedCall(), exec).process(null, 0, null)); + } + + public static class Previewed { + @org.conductoross.conductor.sdk.Variable + public List notes = new ArrayList<>(); + + @Workflow(name = "previewed") + public String run(Map input) { + switchOn("route", input.get("route")) + .when("a", () -> task(Tasks::a, "x")) + .when("b", () -> { + // a body that keeps going past its first call, forks, and mutates a variable + String first = task(Tasks::b, "y"); + notes.add("previewed " + first); + org.conductoross.conductor.sdk.Promise p1 = org.conductoross.conductor.sdk.Conductor.async(() -> task(Tasks::a, "left")); + org.conductoross.conductor.sdk.Promise p2 = org.conductoross.conductor.sdk.Conductor.async(() -> task(Tasks::b, "right")); + org.conductoross.conductor.sdk.Conductor.join(p1, p2); + return task(Tasks::send, first.toUpperCase()); + }) + .when("c", () -> { + switchOn("inner", "?").when("x", () -> task(Tasks::a, "ix")).otherwise(() -> task(Tasks::b, "iy")).run(); + return "c"; + }) + .otherwise(() -> task(Tasks::send, "fallback")) + .get(); + return "done"; + } + } + + @SuppressWarnings("unchecked") + @Test + void aValueNoCaseHandlesIsDrawnBeforeTheWorkflowFails() { + Execution exec = execution(Map.of("route", "nowhere"), List.of(), List.of(), marker("main", 1, "LEASED", 0)); + Map out = new Replayer(WorkflowSpec.of(NoOtherwise.class).get(0), new NoOtherwise(), exec).process("main", 1, null).output; + Map sw = ((List>) out.get("fragment")).get(0); + assertEquals("SWITCH", sw.get("type")); + assertTrue(((Map>) sw.get("decisionCases")).values().stream().anyMatch(c -> !c.isEmpty()), sw.toString()); + assertTrue(((Map) out.get("error")).get("message").toString().contains("no case"), out.toString()); + } + + public static class SameNameInALoop { + @Workflow(name = "same_name") + public String run(Map input) { + for (int i = 0; i < 2; i++) { + switchOn("route", String.valueOf(i)).when("x", () -> "none").otherwise(() -> "none").get(); + } + return task(Tasks::send, "after"); + } + } + + public static class DollarValue { + @Workflow(name = "dollar_value") + public String run(Map input) { + return switchOn("route", "${workflow.input}").when("${workflow.input}", () -> task(Tasks::a, "x")).get(); + } + } + + public static class TaskInFinally { + @Workflow(name = "task_in_finally") + public String run(Map input) { + try { + return task(Tasks::a, "x"); + } finally { + task(Tasks::b, "y"); + } + } + } + + public static class Unjoined { + @Workflow(name = "unjoined") + public String run(Map input) { + org.conductoross.conductor.sdk.Conductor.async(() -> task(Tasks::a, "x")); + return "done"; + } + } + + public static class CallBeforeJoin { + @Workflow(name = "call_before_join") + public String run(Map input) { + org.conductoross.conductor.sdk.Conductor.async(() -> task(Tasks::a, "x")); + return task(Tasks::b, "y"); + } + } + + @SuppressWarnings("unchecked") + private static List> fragmentOf(Class flow, Object instance) { + Execution exec = execution(Map.of(), List.of(), List.of(), marker("main", 1, "LEASED", 0)); + return (List>) new Replayer(WorkflowSpec.of(flow).get(0), instance, exec).process("main", 1, null).output.get("fragment"); + } + + @Test + void theSameSwitchNameInALoopGetsANumberedReference() { + List> fragment = fragmentOf(SameNameInALoop.class, new SameNameInALoop()); + assertEquals(List.of("route", "route_2", "notify"), fragment.stream().map(e -> e.get("taskReferenceName")).toList()); + } + + @SuppressWarnings("unchecked") + @Test + void aSwitchValueIsNeverEvaluatedAsAnExpression() { + Map sw = fragmentOf(DollarValue.class, new DollarValue()).get(0); + assertEquals(Map.of("switchCaseValue", "$${workflow.input}"), sw.get("inputParameters")); + assertTrue(((Map) sw.get("decisionCases")).containsKey("${workflow.input}")); + } + + @Test + void aTaskInAFinallyBlockDoesNotRunWhenTheLanePauses() { + List> fragment = fragmentOf(TaskInFinally.class, new TaskInFinally()); + assertEquals(List.of("shipA"), fragment.stream().map(e -> e.get("taskReferenceName")).toList()); + } + + @SuppressWarnings("unchecked") + @Test + void lanesThatAreNeverJoinedAreForkedWithAJoinThatDoesNotWait() { + Execution exec = execution(Map.of(), List.of(), List.of(), marker("main", 1, "LEASED", 0)); + Map out = new Replayer(WorkflowSpec.of(Unjoined.class).get(0), new Unjoined(), exec).process("main", 1, null).output; + assertEquals(true, out.get("done")); + assertNull(out.get("error")); + List> fragment = (List>) out.get("fragment"); + assertEquals(List.of("fork", "fork_join"), fragment.stream().map(e -> e.get("taskReferenceName")).toList()); + assertEquals(true, ((Map) fragment.get(1).get("metadata")).get("detached")); + } + + @Test + void aCallBeforeTheJoinRunsAlongsideTheLane() { + List> fragment = fragmentOf(CallBeforeJoin.class, new CallBeforeJoin()); + assertEquals(List.of("fork", "fork_join", "shipB"), fragment.stream().map(e -> e.get("taskReferenceName")).toList()); + } + + @Test + void aValueThatIsNotAnObjectDecodesFromResult() { + java.util.UUID id = java.util.UUID.randomUUID(); + assertEquals(id, Json.decodeOutput(Map.of("result", id.toString()), java.util.UUID.class)); + } + + public static class FannedOut { + @Workflow(name = "fanned_out") + public String run(Map input) { + switchOn("route", input.get("route")) + .when("a", () -> task(Tasks::a, "x")) + .when("b", () -> { + List items = new ArrayList<>(); // what a stand-in result looks like + org.conductoross.conductor.sdk.Conductor.fanOut("spread", items, i -> task(Tasks::b, i)).get(); + return task(Tasks::send, "after"); + }) + .get(); + return "done"; + } + } + + @SuppressWarnings("unchecked") + @Test + void anUntakenFanOutIsADynamicForkAndJoinEvenWithNoItemsToShow() { + Execution exec = execution(Map.of("route", "a"), List.of(), List.of(), marker("main", 1, "LEASED", 0)); + Replayer.Outcome out = new Replayer(WorkflowSpec.of(FannedOut.class).get(0), new FannedOut(), exec).process("main", 1, null); + + Map sw = ((List>) out.output.get("fragment")).get(0); + List> b = ((Map>>) sw.get("decisionCases")).get("b"); + assertEquals(List.of("spread_if_b", "spread_if_b_join", "notify_if_b"), b.stream().map(e -> e.get("taskReferenceName")).toList()); + assertEquals("FORK_JOIN_DYNAMIC", b.get(0).get("type")); + assertEquals("dynamicTasks", b.get(0).get("dynamicForkTasksParam")); + assertEquals("dynamicTasksInput", b.get(0).get("dynamicForkTasksInputParamName")); + assertEquals("JOIN", b.get(1).get("type")); + assertTrue(b.stream().allMatch(e -> Boolean.TRUE.equals(((Map) e.get("metadata")).get("preview")))); + } + + @SuppressWarnings("unchecked") + @Test + void untakenCasesShowTheTasksTheyWouldHaveCalled() { + Execution exec = execution(Map.of("route", "a"), List.of(), List.of(), marker("main", 1, "LEASED", 0)); + Previewed instance = new Previewed(); + Replayer.Outcome out = new Replayer(WorkflowSpec.of(Previewed.class).get(0), instance, exec).process("main", 1, null); + + Map sw = ((List>) out.output.get("fragment")).get(0); + Map>> cases = (Map>>) sw.get("decisionCases"); + // the taken case holds the real call, paused on + assertEquals(List.of("shipA"), cases.get("a").stream().map(e -> e.get("taskReferenceName")).toList()); + // case b: its first call, the fork of its two async bodies, and the call after the join + List b = cases.get("b").stream().map(e -> (String) e.get("taskReferenceName")).toList(); + assertEquals(List.of("shipB_if_b", "fork_if_b", "fork_if_b_join", "notify_if_b"), b, b.toString()); + assertTrue(cases.get("b").stream().allMatch(e -> Boolean.TRUE.equals(((Map) e.get("metadata")).get("preview")))); + assertTrue(cases.get("b").stream().noneMatch(e -> ((Map) e.get("metadata")).containsKey("continuation"))); + List>> branches = (List>>) cases.get("b").get(1).get("forkTasks"); + assertEquals(2, branches.size()); + assertEquals("shipA_if_b", branches.get(0).get(0).get("taskReferenceName")); + assertEquals("shipB_if_b_2", branches.get(1).get(0).get("taskReferenceName")); + // case c: a nested switch with both of its cases previewed + Map inner = cases.get("c").get(0); + assertEquals("SWITCH", inner.get("type")); + assertEquals("inner_if_c", inner.get("taskReferenceName")); + assertEquals("shipA_if_c_x", ((Map>>) inner.get("decisionCases")).get("x").get(0).get("taskReferenceName")); + assertEquals("shipB_if_c_default", ((List>) inner.get("defaultCase")).get(0).get("taskReferenceName")); + // the default case too + assertEquals("notify_if_default", ((List>) sw.get("defaultCase")).get(0).get("taskReferenceName")); + // the preview left no trace on the instance + assertTrue(instance.notes.isEmpty(), instance.notes.toString()); + assertEquals(Map.of("notes", List.of()), out.output.get("variables")); + } + + @Test + void aSwitchThatTakesAnotherCaseOnReplayIsADivergence() { + Map aEntry = taskEntry("shipA", "shipA", Map.of("lane", "main", "n", 2)); + Execution exec = execution(Map.of("route", "none"), // the code now takes "none" ... + List.of(switchEntry("a", List.of(aEntry))), // ... but the recording took "a" + List.of(doneTask("route", "SWITCH", 1, Map.of("selectedCase", "a"), null), + doneTask("shipA", "shipA", 2, Map.of("result", "x"), marker("main", 2, "LEASED", 0))), + marker("main", 1, "APPLIED", 1)); + NonDeterminismException e = assertThrows(NonDeterminismException.class, + () -> new Replayer(spec(Flow.class), new Flow(), exec).process("main", 2, null)); + assertTrue(e.getMessage().contains("took case a"), e.getMessage()); + } + + @Test + void aDivergenceNamesWhatTheCodeCallsAndWhatWasRecordedThere() { + Execution exec = execution(Map.of(), + List.of(taskEntry("shipA", "shipA", Map.of("lane", "main", "n", 2))), + List.of(doneTask("shipA", "shipA", 1, Map.of("result", "x"), marker("main", 2, "LEASED", 0))), + marker("main", 1, "APPLIED", 1)); + NonDeterminismException e = assertThrows(NonDeterminismException.class, + () -> new Replayer(spec(ChangedFirstCall.class), new ChangedFirstCall(), exec).process("main", 2, null)); + assertTrue(e.getMessage().startsWith("The running code differs from what this execution recorded: at "), + e.getMessage()); + assertTrue(e.getMessage().endsWith( + " it calls shipB, but the recording has shipA there. Deploy a compatible build to continue."), + e.getMessage()); + } +} diff --git a/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/TaskStubsTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/TaskStubsTest.java new file mode 100644 index 000000000..da739e4ba --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/TaskStubsTest.java @@ -0,0 +1,248 @@ +/* + * Copyright 2026 Conductor 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 org.conductoross.conductor.sdk.internal; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.conductoross.conductor.sdk.Workflow; +import org.junit.jupiter.api.Test; + +import com.netflix.conductor.sdk.workflow.task.InputParam; +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +import static org.conductoross.conductor.sdk.Conductor.task; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** A workflow takes its task classes as constructor parameters and calls them directly. */ +class TaskStubsTest { + + public record Order(String item, int quantity) {} + + public static class Inventory {} + + /** A task class whose constructor needs a dependency: the stub never runs it. */ + public static class Tasks { + private final Inventory inventory; + + public Tasks(Inventory inventory) { + this.inventory = java.util.Objects.requireNonNull(inventory); + } + + @WorkerTask("stub_reserve") + public String reserve(@InputParam("order") Order order) { + return "real " + inventory; + } + + @WorkerTask("stub_ship") + public void ship(@InputParam("id") String id) {} + + @WorkerTask("stub_ship2") + public String ship2(@InputParam("id") String id) { + return id; + } + + public String helper() { + return "not a task"; + } + } + + public static class Direct { + private final Tasks tasks; + + public Direct(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "stub_direct") + public String run(Order order) { + String id = tasks.reserve(order); + tasks.ship(id); + return id; + } + } + + public static class EachByStub { + private final Tasks tasks; + + public EachByStub(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "stub_each") + public List run(Order order) { + return org.conductoross.conductor.sdk.Conductor.forEach("ship_each", List.of("a", "b"), tasks::ship2); + } + } + + public static class EachByReference { + @Workflow(name = "stub_each") + public List run(Order order) { + return org.conductoross.conductor.sdk.Conductor.forEach("ship_each", List.of("a", "b"), Tasks::ship2); + } + } + + public static class ByReference { + @Workflow(name = "stub_direct") + public String run(Order order) { + String id = task(Tasks::reserve, order); + task(Tasks::ship, id); + return id; + } + } + + public static class CreatesItsTasks { + private final Tasks tasks = new Tasks(new Inventory()); + + @Workflow(name = "stub_field") + public String run(Order order) { + return tasks.reserve(order); + } + } + + public static class CreatesTasksInItsCode { + @Workflow(name = "stub_new") + public String run(Order order) { + return new Tasks(new Inventory()).reserve(order); + } + } + + public static class NeedsSomethingElse { + public NeedsSomethingElse(Tasks tasks, Inventory inventory) {} + + @Workflow(name = "stub_other") + public String run(Order order) { + return ""; + } + } + + public static final class FinalTasks { + @WorkerTask("stub_final") + public String run(@InputParam("x") String x) { + return x; + } + } + + @Test + void aWorkflowGetsAStubForEachTaskClassItsConstructorTakes() { + Object instance = WorkflowSpec.of(Direct.class).get(0).newInstance(); + Tasks tasks = ((Direct) instance).tasks; + assertInstanceOf(TaskStubs.Stub.class, tasks); + assertInstanceOf(Tasks.class, tasks); + assertNotSame(instance, WorkflowSpec.of(Direct.class).get(0).newInstance(), "a new instance per replay"); + } + + @SuppressWarnings("unchecked") + @Test + void aCallOnTheStubSchedulesTheTaskAsAMethodReferenceDoes() { + List> direct = firstFragment(Direct.class); + List> byReference = firstFragment(ByReference.class); + assertEquals("stub_reserve", direct.get(0).get("name")); + assertEquals(Map.of("order", Map.of("item", "book", "quantity", 2)), direct.get(0).get("inputParameters")); + assertEquals(byReference.get(0).get("name"), direct.get(0).get("name")); + assertEquals(byReference.get(0).get("inputParameters"), direct.get(0).get("inputParameters")); + } + + @Test + void forEachThroughAStubIsTheSameLoopAsByMethodReference() throws Exception { + List> byStub = firstFragment(EachByStub.class); + assertEquals(firstFragment(EachByReference.class), byStub); + assertTrue(byStub.toString().contains("stub_ship2"), byStub.toString()); + CodeReader.Loop loop = (CodeReader.Loop) CodeReader.read(EachByStub.class.getMethod("run", Order.class)).get(0); + assertEquals("ship_each", loop.name()); + assertEquals("stub_ship2", ((CodeReader.Call) loop.body().get(0)).command().name); + } + + @Test + void conductorStubGivesAFactoryTheSameStub() { + Tasks stub = org.conductoross.conductor.sdk.Conductor.stub(Tasks.class); + assertInstanceOf(TaskStubs.Stub.class, stub); + assertInstanceOf(Tasks.class, stub); + } + + @Test + void aMethodThatIsNotATaskCannotBeCalledOnAStub() { + Tasks stub = TaskStubs.stub(Tasks.class); + UnsupportedOperationException e = assertThrows(UnsupportedOperationException.class, stub::helper); + assertTrue(e.getMessage().contains("Tasks.helper is not a @WorkerTask method"), e.getMessage()); + } + + @Test + void aStubIsOnlyUsableInsideAWorkflow() { + Tasks stub = TaskStubs.stub(Tasks.class); + IllegalStateException e = assertThrows(IllegalStateException.class, () -> stub.reserve(new Order("book", 1))); + assertTrue(e.getMessage().contains("only valid inside a @Workflow method"), e.getMessage()); + } + + @Test + void aWorkflowThatCreatesItsOwnTaskObjectIsRejected() { + IllegalStateException e = assertThrows(IllegalStateException.class, + () -> WorkflowSpec.of(CreatesItsTasks.class).get(0).newInstance()); + assertTrue(e.getMessage().contains("field tasks of"), e.getMessage()); + assertTrue(e.getMessage().contains("take it as a constructor parameter"), e.getMessage()); + } + + @Test + void readingTheCodeRejectsATaskObjectCreatedInTheWorkflowMethod() throws Exception { + IllegalStateException e = assertThrows(IllegalStateException.class, + () -> CodeReader.read(CreatesTasksInItsCode.class.getMethod("run", Order.class))); + assertTrue(e.getMessage().contains("creates a Tasks"), e.getMessage()); + } + + @Test + void readingTheCodeSeesStubCallsAsTasks() throws Exception { + List steps = CodeReader.read(Direct.class.getMethod("run", Order.class)); + assertEquals(List.of("stub_reserve", "stub_ship"), + steps.stream().map(s -> ((CodeReader.Call) s).command().name).toList()); + } + + @Test + void outsideSpringOnlyTaskClassesAreSupplied() { + IllegalStateException e = assertThrows(IllegalStateException.class, + () -> WorkflowSpec.of(NeedsSomethingElse.class).get(0).newInstance()); + assertTrue(e.getMessage().contains("takes a Inventory"), e.getMessage()); + assertTrue(e.getMessage().contains("host().workflow(NeedsSomethingElse.class, factory)"), e.getMessage()); + } + + @Test + void aFinalTaskClassCannotBeStubbed() { + IllegalStateException e = assertThrows(IllegalStateException.class, () -> TaskStubs.stub(FinalTasks.class)); + assertTrue(e.getMessage().contains("is final"), e.getMessage()); + } + + @SuppressWarnings("unchecked") + private static List> firstFragment(Class type) { + WorkflowSpec spec = WorkflowSpec.of(type).get(0); + Map json = new LinkedHashMap<>(); + json.put("workflowId", "wf-1"); + json.put("status", "RUNNING"); + json.put("input", Map.of("item", "book", "quantity", 2)); + json.put("workflowDefinition", Map.of("name", "stub_direct", "tasks", List.of())); + json.put("tasks", List.of()); + Map marker = new LinkedHashMap<>(); + marker.put("lane", "main"); + marker.put("n", 1); + marker.put("state", "LEASED"); + marker.put("step", 0L); + marker.put("resumedWith", Map.of()); + marker.put("recorded", Map.of()); + json.put("nativeState", Map.of("bootstrap", marker)); + Replayer.Outcome out = new Replayer(spec, spec.newInstance(), new Execution(json)).process("main", 1, null); + return (List>) out.output.get("fragment"); + } +} diff --git a/conductor-client/src/test/java/plainbranches/PlainBranchesTest.java b/conductor-client/src/test/java/plainbranches/PlainBranchesTest.java new file mode 100644 index 000000000..0c36dda79 --- /dev/null +++ b/conductor-client/src/test/java/plainbranches/PlainBranchesTest.java @@ -0,0 +1,696 @@ +/* + * Copyright 2026 Conductor 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 plainbranches; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.NonDeterminismException; +import org.conductoross.conductor.sdk.Workflow; +import org.conductoross.conductor.sdk.internal.Execution; +import org.conductoross.conductor.sdk.internal.Replayer; +import org.conductoross.conductor.sdk.internal.WorkflowSpec; +import org.conductoross.conductor.sdk.testing.DurableTestEnvironment; +import org.conductoross.conductor.sdk.testing.TestRun; +import org.junit.jupiter.api.Test; + +import com.netflix.conductor.sdk.workflow.task.InputParam; +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Plain Java ifs and switches whose arms call the server are drawn as SWITCH tasks, read from the + * compiled code. Outside the SDK's packages, as application code is. + */ +@SuppressWarnings("unchecked") +class PlainBranchesTest { + + public static class Tasks { + @WorkerTask("pb_a") + public String a(@InputParam("x") String x) { + return x; + } + + @WorkerTask("pb_b") + public String b(@InputParam("x") String x) { + return x; + } + + @WorkerTask("pb_done") + public String done(@InputParam("x") String x) { + return x; + } + } + + public static class IfElse { + private final Tasks tasks; + + public IfElse(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "pb_if_else") + public String run(@InputParam("route") String route) { + if (route.equals("a")) { + tasks.a("x"); + } else { + tasks.b("y"); + } + return tasks.done("z"); + } + } + + public static class IfOnly { + private final Tasks tasks; + + public IfOnly(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "pb_if_only") + public String run(@InputParam("route") String route) { + if (route.equals("a")) { + tasks.a("x"); + } + return tasks.done("z"); + } + } + + public static class Kinds { + private final Tasks tasks; + + public Kinds(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "pb_kinds") + public String run(@InputParam("kind") String kind) { + switch (kind) { + case "odd" -> tasks.a("o"); + case "even", "zero" -> tasks.b("e"); + default -> {} + } + return tasks.done("z"); + } + } + + public enum Speed { + FAST, + SLOW, + NONE + } + + public static class Speeds { + private final Tasks tasks; + + public Speeds(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "pb_speeds") + public String run(@InputParam("speed") Speed speed) { + switch (speed) { + case FAST: + tasks.a("f"); + break; + case SLOW: + tasks.b("s"); + break; + default: + break; + } + return tasks.done("z"); + } + } + + public static class Loops { + private final Tasks tasks; + + public Loops(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "pb_loops") + public String run(@InputParam("routes") List routes) { + for (String route : routes) { + if (route.equals("a")) { + tasks.a(route); + } + } + int i = 0; + while (i < 2) { + tasks.b("w" + i); + i++; + } + do { + tasks.done("d" + i); + i--; + } while (i > 0); + return "ok"; + } + } + + public static class Conditions { + private final Tasks tasks; + + public Conditions(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "pb_conditions") + public String run(@InputParam("route") String route) { + if (route == null) { + return "none"; // a guard without a call is plain code + } + if (route.length() > 3 && route.startsWith("x")) { + tasks.a("and"); + } + if (route.isEmpty() || route.startsWith("y")) { + tasks.b("or"); + } + return tasks.done("z"); + } + } + + public static class Tail { + private final Tasks tasks; + + public Tail(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "pb_tail") + public String run(@InputParam("route") String route) { + tasks.a("first"); + if (route.equals("x")) { + tasks.b("only when x"); + } + return "ok"; + } + } + + public static class LoopInArm { + private final Tasks tasks; + + public LoopInArm(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "pb_loop_in_arm") + public String run(@InputParam("route") String route) { + if (route.equals("a")) { + for (int i = 0; i < 2; i++) { + tasks.a("x" + i); + } + } + return "ok"; + } + } + + // ------------------------------------------------------------------ the definition + + private static WorkflowSpec spec(Class type) { + return WorkflowSpec.of(type).get(0); + } + + private static List refs(List> entries) { + return entries.stream().map(e -> String.valueOf(e.get("taskReferenceName"))).toList(); + } + + private static Map>> cases(Map sw) { + return (Map>>) sw.get("decisionCases"); + } + + private static List> defaultCase(Map sw) { + return (List>) sw.get("defaultCase"); + } + + @Test + void anIfElseIsASwitchWithATrueCaseAndTheElseAsDefault() { + List> entries = Replayer.discover(spec(IfElse.class)); + assertEquals(List.of("if_route", "pb_done"), refs(entries)); + Map sw = entries.get(0); + assertEquals("SWITCH", sw.get("type")); + assertEquals(List.of("true"), new ArrayList<>(cases(sw).keySet())); + assertEquals(List.of("pb_a"), refs(cases(sw).get("true"))); + assertEquals(List.of("pb_b"), refs(defaultCase(sw))); + } + + @Test + void aStringSwitchHasACasePerArmLabelledAsWritten() { + Map sw = Replayer.discover(spec(Kinds.class)).get(0); + assertEquals("switch_kind", sw.get("taskReferenceName")); + assertEquals(List.of("odd", "even,zero"), new ArrayList<>(cases(sw).keySet())); + assertEquals(List.of("pb_a"), refs(cases(sw).get("odd"))); + assertEquals(List.of("pb_b"), refs(cases(sw).get("even,zero"))); + assertTrue(defaultCase(sw).isEmpty()); + } + + @Test + void anEnumSwitchIsLabelledByTheConstants() { + Map sw = Replayer.discover(spec(Speeds.class)).get(0); + assertEquals("switch_speed", sw.get("taskReferenceName")); + assertEquals(List.of("FAST", "SLOW"), new ArrayList<>(cases(sw).keySet())); + } + + @Test + void loopConditionsAreNotBranchesButAnIfInsideALoopIs() { + List> entries = Replayer.discover(spec(Loops.class)); + assertEquals(List.of("if_route", "pb_b", "pb_done"), refs(entries)); + } + + @Test + void aCompoundConditionIsOneBranchAndAGuardWithoutACallIsPlainCode() { + List> entries = Replayer.discover(spec(Conditions.class)); + assertEquals(List.of("if_startsWith", "if_startsWith_2", "pb_done"), refs(entries)); + assertEquals(List.of("pb_a"), refs(cases(entries.get(0)).get("true"))); + assertEquals(List.of("pb_b"), refs(cases(entries.get(1)).get("true"))); + } + + // ------------------------------------------------------------------ executions + + private static Execution execution(Map input, List> defTasks, + List> tasks, Map bootstrap) { + Map json = new LinkedHashMap<>(); + json.put("workflowId", "wf-1"); + json.put("status", "RUNNING"); + json.put("input", input); + json.put("workflowDefinition", Map.of("name", "pb", "tasks", defTasks)); + json.put("tasks", tasks); + json.put("nativeState", Map.of("bootstrap", bootstrap)); + return new Execution(json); + } + + private static Map marker(int n, String state, long step) { + Map m = new LinkedHashMap<>(); + m.put("lane", "main"); + m.put("n", n); + m.put("state", state); + m.put("step", step); + m.put("resumedWith", Map.of()); + m.put("recorded", Map.of()); + return m; + } + + private static Map taskEntry(String ref, String name, Map continuation) { + Map e = new LinkedHashMap<>(); + e.put("name", name); + e.put("taskReferenceName", ref); + e.put("type", "SIMPLE"); + Map md = new LinkedHashMap<>(); + md.put("lane", "main"); + if (continuation != null) { + md.put("continuation", continuation); + } + e.put("metadata", md); + return e; + } + + private static Map switchEntry(String ref, String taken, Map>> cases, + List> otherwise) { + Map sw = new LinkedHashMap<>(); + sw.put("name", ref); + sw.put("taskReferenceName", ref); + sw.put("type", "SWITCH"); + sw.put("inputParameters", Map.of("switchCaseValue", taken)); + sw.put("decisionCases", cases); + sw.put("defaultCase", otherwise); + return sw; + } + + private static Map done(String ref, String type, int seq, Map output, Map continuation) { + Map t = new LinkedHashMap<>(); + t.put("taskId", "id-" + ref); + t.put("referenceTaskName", ref); + t.put("taskType", type); + t.put("status", "COMPLETED"); + t.put("seq", seq); + t.put("outputData", output); + t.put("workflowTask", Map.of("type", type)); + if (continuation != null) { + t.put("continuation", continuation); + } + return t; + } + + private static Replayer.Outcome first(Class type, Map input) { + WorkflowSpec spec = spec(type); + return new Replayer(spec, spec.newInstance(), execution(input, List.of(), List.of(), marker(1, "LEASED", 0))) + .process("main", 1, null); + } + + private static List> fragment(Replayer.Outcome out) { + return (List>) out.output.get("fragment"); + } + + private static Map metadata(Map entry) { + return (Map) entry.get("metadata"); + } + + @Test + void theTakenArmsCallsGoInsideItsCaseAndTheOtherArmIsPreviewed() { + List> fragment = fragment(first(IfElse.class, Map.of("route", "a"))); + assertEquals(List.of("if_route"), refs(fragment), "the code paused inside the if"); + Map sw = fragment.get(0); + assertEquals(Map.of("switchCaseValue", "true"), sw.get("inputParameters")); + Map a = cases(sw).get("true").get(0); + assertEquals("pb_a", a.get("taskReferenceName")); + assertEquals(Map.of("lane", "main", "n", 2), metadata(a).get("continuation")); + Map preview = defaultCase(sw).get(0); + assertEquals("pb_b_if_false", preview.get("taskReferenceName")); + assertEquals(true, metadata(preview).get("preview")); + assertTrue(String.valueOf(metadata(sw).get("site")).startsWith("PlainBranchesTest$IfElse.run:")); + } + + @Test + void anIfPassedWithoutACallIsDrawnWithTheArmThatMustHaveBeenTaken() { + List> fragment = fragment(first(IfOnly.class, Map.of("route", "b"))); + assertEquals(List.of("if_route", "pb_done"), refs(fragment)); + Map sw = fragment.get(0); + assertEquals(Map.of("switchCaseValue", "false"), sw.get("inputParameters")); + assertEquals("pb_a_if_true", cases(sw).get("true").get(0).get("taskReferenceName")); + assertTrue(defaultCase(sw).isEmpty()); + } + + @Test + void aSwitchDefaultPassedWithoutACallIsDrawnToo() { + List> fragment = fragment(first(Kinds.class, Map.of("kind", "prime"))); + assertEquals(List.of("switch_kind", "pb_done"), refs(fragment)); + assertEquals(Map.of("switchCaseValue", "default"), fragment.get(0).get("inputParameters")); + } + + @Test + void anEnumCaseIsTakenByItsConstant() { + List> fragment = fragment(first(Speeds.class, Map.of("speed", "SLOW"))); + Map sw = fragment.get(0); + assertEquals(Map.of("switchCaseValue", "SLOW"), sw.get("inputParameters")); + assertEquals(List.of("pb_b"), refs(cases(sw).get("SLOW"))); + assertEquals(List.of("pb_a_if_FAST"), refs(cases(sw).get("FAST"))); + } + + /** The recording of IfElse with route a: the if took true and pb_a finished. */ + private static Execution ifElseAfterA(String recordedCase) { + Map inCase = taskEntry("pb_a", "pb_a", Map.of("lane", "main", "n", 2)); + Map>> cases = new LinkedHashMap<>(); + cases.put("true", "true".equals(recordedCase) ? List.of(inCase) : new ArrayList<>()); + return execution(Map.of("route", "a"), + List.of(switchEntry("if_route", recordedCase, cases, "true".equals(recordedCase) ? List.of() : List.of(inCase))), + List.of(done("if_route", "SWITCH", 1, Map.of("selectedCase", recordedCase), null), + done("pb_a", "pb_a", 2, Map.of("result", "x"), marker(2, "LEASED", 0))), + marker(1, "APPLIED", 1)); + } + + @Test + void theCallAfterAnArmEndedInAnEarlierContinuationGoesAfterTheSwitch() { + WorkflowSpec spec = spec(IfElse.class); + Replayer.Outcome out = new Replayer(spec, spec.newInstance(), ifElseAfterA("true")).process("main", 2, null); + List> fragment = fragment(out); + assertEquals(List.of("pb_done"), refs(fragment)); + assertEquals("if_route", metadata(fragment.get(0)).get("after")); + } + + @Test + void anotherArmThanTheRecordedOneIsADivergence() { + WorkflowSpec spec = spec(IfElse.class); + NonDeterminismException e = assertThrows(NonDeterminismException.class, + () -> new Replayer(spec, spec.newInstance(), ifElseAfterA("false")).process(null, 0, null)); + assertTrue(e.getMessage().contains("if_route took false in the recorded execution but the code now takes true"), e.getMessage()); + } + + @Test + void anExecutionRecordedWithoutTheSwitchReplaysAndContinuesAsItWas() { + Execution exec = execution(Map.of("route", "a"), + List.of(taskEntry("pb_a", "pb_a", Map.of("lane", "main", "n", 2))), + List.of(done("pb_a", "pb_a", 1, Map.of("result", "x"), marker(2, "LEASED", 0))), + marker(1, "APPLIED", 1)); + WorkflowSpec spec = spec(IfElse.class); + Replayer.Outcome out = assertDoesNotThrow(() -> new Replayer(spec, spec.newInstance(), exec).process("main", 2, null)); + List> fragment = fragment(out); + assertEquals(List.of("pb_done"), refs(fragment)); + assertNull(metadata(fragment.get(0)).get("after")); + } + + @Test + void anIfPassedAfterTheLastCallIsDrawnWhenTheCodeReturns() { + Execution exec = execution(Map.of("route", "y"), + List.of(taskEntry("pb_a", "pb_a", Map.of("lane", "main", "n", 2))), + List.of(done("pb_a", "pb_a", 1, Map.of("result", "x"), marker(2, "LEASED", 0))), + marker(1, "APPLIED", 1)); + WorkflowSpec spec = spec(Tail.class); + Replayer.Outcome out = new Replayer(spec, spec.newInstance(), exec).process("main", 2, null); + assertEquals(true, out.output.get("done")); + List> fragment = fragment(out); + assertEquals(List.of("if_route"), refs(fragment)); + assertEquals(Map.of("switchCaseValue", "false"), fragment.get(0).get("inputParameters")); + } + + @Test + void theSwitchIsInTheLoopsAroundTheIfNotThoseInsideItsArm() { + Map sw = fragment(first(LoopInArm.class, Map.of("route", "a"))).get(0); + assertEquals(List.of(), metadata(sw).get("loops")); + Map a = cases(sw).get("true").get(0); + assertEquals(1, ((List) metadata(a).get("loops")).size(), "the call is inside the arm's loop"); + } + + @Test + void anIfInALoopIsDrawnOncePerPass() { + Map first = taskEntry("pb_a", "pb_a", Map.of("lane", "main", "n", 2)); + Map>> cases = new LinkedHashMap<>(); + cases.put("true", List.of(first)); + Execution exec = execution(Map.of("routes", List.of("a", "a")), + List.of(switchEntry("if_route", "true", cases, List.of())), + List.of(done("if_route", "SWITCH", 1, Map.of("selectedCase", "true"), null), + done("pb_a", "pb_a", 2, Map.of("result", "a"), marker(2, "LEASED", 0))), + marker(1, "APPLIED", 1)); + WorkflowSpec spec = spec(Loops.class); + List> fragment = fragment(new Replayer(spec, spec.newInstance(), exec).process("main", 2, null)); + assertEquals(List.of("if_route_2"), refs(fragment)); + assertEquals("if_route", metadata(fragment.get(0)).get("after")); + assertEquals(1, ((List) metadata(fragment.get(0)).get("loops")).size(), "the if is inside the for loop"); + assertEquals(List.of("pb_a_2"), refs(cases(fragment.get(0)).get("true"))); + } + + // ------------------------------------------------------------------ in memory + + @Test + void inMemoryAWorkflowTakingTaskClassesCallsTheRegisteredTaskObjects() { + Tasks tasks = org.mockito.Mockito.mock(Tasks.class); + org.mockito.Mockito.when(tasks.b("y")).thenReturn("from b"); + org.mockito.Mockito.when(tasks.done("z")).thenReturn("finished"); + try (DurableTestEnvironment env = DurableTestEnvironment.inMemory()) { + env.workflows(IfElse.class).tasks(tasks); + TestRun run = env.start(IfElse::run, "b"); + assertEquals("finished", run.result()); + assertEquals(List.of("pb_b", "pb_done"), run.ranTasks()); + org.mockito.Mockito.verify(tasks, org.mockito.Mockito.never()).a(org.mockito.ArgumentMatchers.anyString()); + } + } + + @Test + void inMemoryAFactoryGivesTheWorkflowTaskStubsFromConductorStub() { + Tasks tasks = org.mockito.Mockito.mock(Tasks.class); + org.mockito.Mockito.when(tasks.done("z")).thenReturn("finished"); + try (DurableTestEnvironment env = DurableTestEnvironment.inMemory()) { + env.workflow(IfElse.class, () -> new IfElse(Conductor.stub(Tasks.class))).tasks(tasks); + assertEquals("finished", env.start(IfElse::run, "a").result()); + org.mockito.Mockito.verify(tasks).a("x"); + } + } + + // ------------------------------------------------------------------ Thread.sleep + + public static class Sleepy { + private final Tasks tasks; + + public Sleepy(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "pb_sleepy") + public String run(@InputParam("x") String x) throws InterruptedException { + Thread.sleep(10); // SLEEP_DIRECT + nap(); + org.conductoross.conductor.sdk.Conductor.async(() -> { + pause(); // SLEEP_LAMBDA_CALL + return tasks.a(x); + }); + return tasks.done(x); + } + + private static void nap() throws InterruptedException { + Thread.sleep(10); // SLEEP_HELPER + } + + private static void pause() { + try { + Thread.sleep(10); // SLEEP_LAMBDA + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } + + @Test + void everyThreadSleepTheWorkflowCanReachIsFoundWithItsLine() throws Exception { + List source = java.nio.file.Files.readAllLines( + java.nio.file.Path.of("src/test/java/plainbranches/PlainBranchesTest.java")); + java.util.function.Function line = mark -> { + for (int i = 0; i < source.size(); i++) { + if (source.get(i).trim().endsWith("// " + mark)) { + return i + 1; + } + } + throw new AssertionError(mark); + }; + List sites = org.conductoross.conductor.sdk.internal.CodeReader.threadSleeps( + Sleepy.class.getMethod("run", String.class)); + assertEquals(List.of( + "PlainBranchesTest$Sleepy.run:" + line.apply("SLEEP_DIRECT"), + "PlainBranchesTest$Sleepy.nap:" + line.apply("SLEEP_HELPER"), + "PlainBranchesTest$Sleepy.pause:" + line.apply("SLEEP_LAMBDA")), + sites); + assertEquals(List.of(), org.conductoross.conductor.sdk.internal.CodeReader.threadSleeps( + IfElse.class.getMethod("run", String.class))); + } + + // ------------------------------------------------------------------ an exception, and what it skipped + + public static class Between { + private final Tasks tasks; + + public Between(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "pb_between") + public String run(@InputParam("x") String x) { + String raw = tasks.a(x); + int n = Integer.parseInt(raw); // THROWS_HERE + return tasks.b("n" + n); + } + } + + public static class Guard { + private final Tasks tasks; + + public Guard(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "pb_guard") + public String run(@InputParam("x") String x) { + String raw = tasks.a(x); + if (raw.startsWith("s")) { + Integer.parseInt(raw); + tasks.b("parsed"); + } else { + tasks.b("unparsed"); + } + return tasks.done(raw); + } + } + + public static class Nested { + private final Tasks tasks; + + public Nested(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "pb_nested") + public String run(@InputParam("x") String x) { + String raw = tasks.a(x); + String checked = check(raw); + return tasks.done(checked); + } + + private String check(String raw) { + Integer.parseInt(raw); + return tasks.b(raw); + } + } + + /** The recording after task a returned {@code value}; continuation 2 resumes after it. */ + private static Execution afterA(String value) { + return execution(Map.of("x", "in"), + List.of(taskEntry("pb_a", "pb_a", Map.of("lane", "main", "n", 2))), + List.of(done("pb_a", "pb_a", 1, Map.of("result", value), marker(2, "LEASED", 0))), + marker(1, "APPLIED", 1)); + } + + private static Replayer.Outcome second(Class type, String value) { + WorkflowSpec spec = spec(type); + return new Replayer(spec, spec.newInstance(), afterA(value)).process("main", 2, null); + } + + @Test + void anExceptionBetweenTwoTasksMarksWhereItThrewAndPreviewsWhatWasSkipped() throws Exception { + Replayer.Outcome out = second(Between.class, "seven"); + assertEquals(true, out.output.get("done")); + Map error = (Map) out.output.get("error"); + assertEquals("throw", error.get("ref")); + List> fragment = fragment(out); + assertEquals(List.of("throw", "pb_b_if_no_error"), refs(fragment)); + Map thrown = fragment.get(0); + assertEquals("TERMINATE", thrown.get("type")); + assertEquals("NumberFormatException", thrown.get("name")); + int line = 1; + List source = java.nio.file.Files.readAllLines(java.nio.file.Path.of("src/test/java/plainbranches/PlainBranchesTest.java")); + while (!source.get(line - 1).trim().endsWith("// THROWS_HERE")) { + line++; + } + assertEquals("PlainBranchesTest$Between.run:" + line, metadata(thrown).get("site")); + Map skipped = fragment.get(1); + assertEquals("pb_b", skipped.get("name")); + assertEquals(true, metadata(skipped).get("preview")); + assertEquals("throw", metadata(skipped).get("previewAfter")); + } + + @Test + void anExceptionInAnArmPreviewsTheRestOfTheArmThenWhatFollowsTheIfNotTheOtherArm() { + List> fragment = fragment(second(Guard.class, "seven")); + // the if the code threw inside is drawn, the mark and the rest of that arm in its case + assertEquals(List.of("if_startsWith", "pb_done_if_no_error"), refs(fragment)); + Map sw = fragment.get(0); + assertEquals(Map.of("switchCaseValue", "true"), sw.get("inputParameters")); + assertEquals(List.of("throw", "pb_b_if_no_error"), refs(cases(sw).get("true"))); + assertEquals(List.of("pb_b_if_false"), refs(defaultCase(sw)), "the other arm is previewed as an untaken arm"); + } + + @Test + void anExceptionInAHelperPreviewsTheRestOfTheHelperThenOfTheWorkflow() { + List> fragment = fragment(second(Nested.class, "x")); + assertEquals(List.of("throw", "pb_b_if_no_error", "pb_done_if_no_error"), refs(fragment)); + } + + @Test + void aReplayOfTheFailedExecutionFindsTheMarkAndItsPreviews() { + Replayer.Outcome out = second(Between.class, "seven"); + List> defs = new ArrayList<>(); + defs.add(taskEntry("pb_a", "pb_a", Map.of("lane", "main", "n", 2))); + defs.addAll(fragment(out)); + Execution failed = execution(Map.of("x", "in"), defs, + List.of(done("pb_a", "pb_a", 1, Map.of("result", "seven"), marker(2, "APPLIED", 2))), + marker(1, "APPLIED", 1)); + WorkflowSpec spec = spec(Between.class); + assertDoesNotThrow(() -> new Replayer(spec, spec.newInstance(), failed).process(null, 0, null)); + } +} diff --git a/conductor-client/src/test/java/stubsite/StubCallSiteTest.java b/conductor-client/src/test/java/stubsite/StubCallSiteTest.java new file mode 100644 index 000000000..753e4ea5c --- /dev/null +++ b/conductor-client/src/test/java/stubsite/StubCallSiteTest.java @@ -0,0 +1,84 @@ +/* + * Copyright 2026 Conductor 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 stubsite; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.conductoross.conductor.sdk.Workflow; +import org.conductoross.conductor.sdk.internal.Execution; +import org.conductoross.conductor.sdk.internal.Replayer; +import org.conductoross.conductor.sdk.internal.WorkflowSpec; +import org.junit.jupiter.api.Test; + +import com.netflix.conductor.sdk.workflow.task.InputParam; +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** Outside the SDK's packages, as application code is: the site is the workflow's line, not the stub's. */ +class StubCallSiteTest { + + public static class Tasks { + @WorkerTask("site_greet") + public String greet(@InputParam("name") String name) { + return name; + } + } + + public static class Flow { + private final Tasks tasks; + + public Flow(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "site_flow") + public String run(@InputParam("name") String name) { + return tasks.greet(name); // CALL_LINE + } + } + + @SuppressWarnings("unchecked") + @Test + void theSiteOfAStubCallIsTheLineInTheWorkflow() throws Exception { + WorkflowSpec spec = WorkflowSpec.of(Flow.class).get(0); + Map json = new LinkedHashMap<>(); + json.put("workflowId", "wf-1"); + json.put("status", "RUNNING"); + json.put("input", Map.of("name", "World")); + json.put("workflowDefinition", Map.of("name", "site_flow", "tasks", List.of())); + json.put("tasks", List.of()); + Map marker = new LinkedHashMap<>(); + marker.put("lane", "main"); + marker.put("n", 1); + marker.put("state", "LEASED"); + marker.put("step", 0L); + marker.put("resumedWith", Map.of()); + marker.put("recorded", Map.of()); + json.put("nativeState", Map.of("bootstrap", marker)); + Replayer.Outcome out = new Replayer(spec, spec.newInstance(), new Execution(json)).process("main", 1, null); + + List> fragment = (List>) out.output.get("fragment"); + assertEquals(1, fragment.size(), "the replay paused on the task: " + out.output); + Map entry = fragment.get(0); + List source = java.nio.file.Files.readAllLines( + java.nio.file.Path.of("src/test/java/stubsite/StubCallSiteTest.java")); + int line = 1; + while (!source.get(line - 1).contains("// CALL_" + "LINE")) { + line++; + } + assertEquals("StubCallSiteTest$Flow.run:" + line, ((Map) entry.get("metadata")).get("site")); + } +} diff --git a/design/native-workflows/README.md b/design/native-workflows/README.md new file mode 100644 index 000000000..983017d60 --- /dev/null +++ b/design/native-workflows/README.md @@ -0,0 +1,556 @@ +# Native workflows + +Status: implemented. The SDK lives in `conductor-client` under `org.conductoross.conductor.sdk` +(public API), `.internal` (replay engine, host internals) and `.testing` (in-memory test +environment and replay check). The runnable kitchensink is the `native-examples` module. The +server side is on `conductor-oss/conductor` branch `design/native-workflows`; its +`proposals/native-workflows/06-implementation.md` lists what was validated and where the +implementation differs from this design (fan-out lanes instead of dynamic-fork stages, a +stateless always-replaying worker, `startWorkflow` returning nothing, and the embedded test tier +and debugger not yet built). + +Workflows written as ordinary Java. Any method on any class becomes a workflow with `@Workflow`. +Tasks are today's `@WorkerTask` classes, unchanged. A workflow takes its task classes as +constructor parameters and calls them directly (`tasks.reserve(order)`), or calls them by method +reference (`task(OrderTasks::reserve, order)`); the two schedule the same task. Real `if`, +`switch`, loops, `try`/`catch`, local variables and helper methods. No base class, no interface, +no compiler, no annotation processor. The SDK uses `SerializedLambda` to resolve method +references, reflection on the referenced methods for input and output types, `StackWalker` for +call sites, ASM to read compiled code when it draws the graph, and ByteBuddy for task stubs. ASM +and ByteBuddy are bundled inside the `conductor-client` jar under +`org.conductoross.conductor.shaded`, not dependencies of it, so an application's own versions +never clash with them. + +**Task stubs.** The SDK creates the workflow object, a new one for each replay, and passes a stub +for each constructor parameter whose class has `@WorkerTask` methods. A call on the stub schedules +the task (on replay it returns the recorded result), as `task(...)` does; calling a method that is +not a `@WorkerTask` method throws. The stub is a generated subclass, created without running the +task class's constructor, so a task class with dependencies needs nothing extra; a final task +class or task method fails with a clear message. A real task object in the workflow would run its +methods inside the workflow on every replay, so it is rejected: a field holding one fails when the +workflow is created, and `new` of a task class in workflow code fails when the code is read. +Outside Spring a workflow constructor may take only task classes; anything else needs +`host().workflow(Type.class, factory)`, whose factory gets the task stubs from +`Conductor.stub(OrderTasks.class)`. In Spring other parameters are injected. + +**The one sentence:** every static call imported from `Conductor` goes to the server and shows in +the graph; everything else is just Java. + +## Files + +| File | What it is | +|---|---| +| `native-examples/src/main/java/kitchensink/KitchenSinkWorkflow.java` | a plain class whose `@Workflow` method mirrors `rest/src/main/resources/kitchensink/kitchensink.json` in section 1, and adds timers, loops, signals, updates, queries, human tasks, callbacks, compensation and LLM in section 2; its decisions are plain `if` and `switch`, its loops plain `for` and `while` | +| `native-examples/src/main/java/kitchensink/SubFlow.java` | `sub_flow_1` as a `@Workflow` method, called as a typed child | +| `native-examples/src/main/java/kitchensink/KitchenSinkTasks.java` | the tasks: today's `@WorkerTask` class, unchanged | +| `native-examples/src/main/java/kitchensink/KitchenSinkModel.java` | input, output and payload records | +| `native-examples/src/main/java/kitchensink/Main.java` | host and client through one `Conductor` entry point | +| `native-examples/src/main/java/conformance/Conformance.java` | 151 scenarios against a server, each with an expected result and graph; exits non-zero on any failure | +| `native-examples/src/main/java/switches/Switches.java` | `switchOn` edge cases against a server: a case with tasks, a nested switch, an empty case, the default case, and a value no case handles (the workflow fails) | +| `native-examples/src/main/java/failures/Failures.java` | an unchecked exception from workflow code: thrown by the workflow method it fails the workflow with the exception as the reason; thrown in an `async` lane nothing joins, the workflow completes and the exception is in the log of the task the lane ran last | +| `native-examples/src/test/java/kitchensink/KitchenSinkTest.java` | unit tests with a mocked task class and the in-memory environment, plus a replay test | + +## Round 4: what changed and why + +| Before | Now | Why | +|---|---|---| +| `class X extends DurableWorkflow` with an abstract `run` | `@Workflow` on any method of any class | the annotation is the whole contract; nothing to extend or implement | +| `ActivityInterface` + `ActivityImpl`, stub by proxy | one `@WorkerTask` class, taken as a constructor parameter and called directly, `tasks.task1(mod, oddEven)`, or by method reference, `task(KitchenSinkTasks::task1, mod, oddEven)` | today's worker model, no interface to write; the SDK generates the stub, the compiler checks the arguments, reflection on the method gives the types at runtime | +| "activities" | "tasks" everywhere: `task(...)`, `TaskFailure`, `.tasks(...)` on the host | Conductor's term | +| inherited methods | static methods on `Conductor`, normally static-imported so calls read bare | no base class to occupy the inheritance slot | +| all fields durable, `transient` opts out | `@Variable` fields are workflow variables; other fields are ordinary | a service class has injected clients and caches; those must never be persisted, and `@Variable` maps to `workflow.variables` by name | +| `run(name, () -> ...)` | `once(name, () -> ...)` | `run` collided with the natural name for a workflow method | +| generics on the workflow class | generics only where Java infers them: `Promise`, `WorkflowHandle`, `Optional` | erasure never matters because the runtime takes every type from the referenced method, not from a type parameter | +| `switchOn(...)` for a decision the graph should show; a plain `if` or `switch` left no trace | a plain `if` or `switch` whose arms call the server is a SWITCH with every arm, read from the compiled code; `switchOn` stays for a name and keys of your choosing | workflow code reads as ordinary Java, and the graph still shows every branch and which one was taken | + +## How it reads + +```java +public class OrderService { + + private final InventoryTasks inventory; // stubs from Conductor: calls schedule the tasks + private final PaymentTasks payments; + + public OrderService(InventoryTasks inventory, PaymentTasks payments) { + this.inventory = inventory; + this.payments = payments; + } + + @Variable private String stage = "new"; + + @Signal("cancel") + public void cancel(CancelRequest r) { stage = "cancelled"; } + + @Workflow(name = "order", version = 1) + public OrderResult processOrder(OrderRequest order) { + Promise fraud = async(() -> http("fraud").post(FRAUD_URL).body(order).as(FraudResult.class)); + Promise> reserved = fanOut(order.items(), item -> inventory.reserve(item)); + join(fraud, reserved); + if (fraud.get().flagged()) return OrderResult.rejected(); + + Payment payment = switch (order.paymentMethod()) { + case CARD -> payments.chargeCard(order); + case INVOICE -> payments.issueInvoice(order, + human("approval").assignee("finance").await(Approval.class, Duration.ofDays(2)).orElseThrow()); + }; + sleep(Duration.ofMinutes(5)); + return OrderResult.ok(payment); + } +} +``` + +`InventoryTasks.reserve` and `PaymentTasks.chargeCard` are `@WorkerTask` methods, exactly as a +worker is written today. The workflow takes the task classes as constructor parameters and gets +task stubs, so each call schedules the task (see Task stubs above). The workflow has a compile-time dependency on the task classes, which is +what makes the arguments type-checked; a task owned by another team or written in another language +is called by name with `task("name").input(...).as(T)`, or through a typed interface of +`@WorkerTask` methods that nothing in this process implements or hosts (`reuse/Reuse.java`). A +worker that polls in a domain is reached with `.taskToDomain(...)` on the start builder. A task +definition owned by someone else is never overwritten at registration, so its retries and timeouts +stay its owner's. + +If deployed code stops matching a running execution, the execution is held, not failed: it stays +running, shows why on the execution page, and continues when a compatible build is running. Graph +discovery and switch previews read the compiled code and run nothing; `workers.discovery(false)` +leaves the graph out of the registered definition. + +The `switch` on the payment method is plain Java, and because its arms call the server the +execution shows it as a SWITCH, `switch_paymentMethod`: every arm, the one taken, and what the +others would have called (see Plain ifs and switches below). The fraud check returns without a +call, so it is plain code and shows nothing. `switchOn` is the same SWITCH with a name and case +keys of your choosing, and the value itself recorded: + +```java +Payment payment = switchOn("payment", order.paymentMethod()) + .when(CARD, () -> payments.chargeCard(order)) + .when(INVOICE, () -> payments.issueInvoice(order, + human("approval").assignee("finance").await(Approval.class, Duration.ofDays(2)).orElseThrow())) + .get(); +``` + +## The API, in one table + +Static methods on `org.conductoross.conductor.sdk.Conductor`. + +| Call in workflow code | Server task | Wakes the code | +|---|---|---| +| `tasks.method(args...)` on a task stub, or `task(Tasks::method, args...)` | SIMPLE, named by `@WorkerTask`; retried per its definition (3 retries, exponential backoff by default), then marked optional so a final failure reaches the code | when the task completes, or fails after its retries | +| `task(name).input(...).as(T)` | SIMPLE, name chosen at runtime | when the task completes | +| `once(name, () -> ...)` | none; the value is recorded (`recorded`) on the continuation marker of the task the code pauses on next | never; runs in place | +| an `if` or `switch` whose arms call the server | SWITCH named after what it decides on (`if_flagged`, `switch_paymentMethod`; `value-param` on `switchCaseValue`). An `if` has the case `true` and its else as the default case; a `switch` has a case per arm, keyed by its labels (`CARD`, `odd`, `even,zero`), and `default`. The arm taken holds the calls it made; the others show what they would call, as previews. Read from the compiled code; see Plain ifs and switches | never by itself; the arm's calls wake the code as usual | +| a Java `for`, `while` or `do`-`while` | ordinary code, so it may hold ifs, switches, forks, sub workflows and other loops. There is no `DO_WHILE` task: the compiled method says which lines a loop covers, each step is tagged with the loops around it in `metadata.loops`, and the execution diagram draws those steps as one loop | at each call inside it | +| `async(() -> ...)`, `join(p1, p2)`, `Promise.get()` | FORK_JOIN + JOIN, one branch per async block that calls the server, each with its own continuation points; a block that returns without a server call is plain Java. `async` does not wait: lanes still running at the next durable call get a JOIN that completes at once, and a later `join` or `get` adds a JOIN naming those lanes. It works inside another `async` block, and a join waits for what the lane started | each branch when its own task completes | +| `fanOut(items, item -> ...)` | FORK_JOIN with one branch per item + JOIN; drawn as FORK_JOIN_DYNAMIC + JOIN in an untaken case or the registered definition, where the items are not known | once | +| `child(Other::method, input)` / `childAsync(...)` | SUB_WORKFLOW, typed by the referenced `@Workflow` method | when the child completes | +| `startWorkflow(name, version, input)` / `startWorkflow(Other::method, input)` | START_WORKFLOW | never (fire and forget); a failure shows in the UI only | +| `sleep(duration)` | WAIT with duration | when the timer fires | +| `repeatUntil(body, condition, backoff)` | DO_WHILE { WAIT, task }; the first check runs after one interval | once, when the loop ends | +| `sleepUntil(instant)` | WAIT with `until`; the server resolves it to the minute, so the instant is rounded up to the next minute | when the time is reached | +| `forEach(name, items, tasks::method)` on a task stub, or `forEach(name, items, Tasks::method)` | DO_WHILE over `items`, one task per item, one after another; the method takes the item as its only parameter; the stub is not called | once, when every item is done | +| `mcp(ref).server(url).listTools()` / `.call(tool, args)` | LIST_MCP_TOOLS / CALL_MCP_TOOL, run by the server's MCP client; retried like HTTP (`.retries(count, delay)`) | when the call completes | +| `agent(ref).remote(cardUrl).ask(text)` / `agent(ref).conductor(name, version).ask(text)` | AGENT: an A2A call to a remote agent (an agent card URL is discovered), or a Conductor agent | when the agent replies | +| `awaitExternal(ref, T).await(timeout)` | WAIT completed by `POST /api/tasks/{workflowId}/{ref}/COMPLETED` | when completed or timed out | +| `awaitCondition(() -> ..., timeout)` | WAIT completed by the handler lane | when the condition holds or times out | +| `human(ref)...await(T, timeout)` | HUMAN with a retry-style timeout policy, so a timeout is an empty result, not a failed workflow | when answered or timed out | +| `http(ref).get/post(...).as(T)` / `.asJson()` | HTTP | when the call completes | +| `event(ref).to(sink).send(payload)` | EVENT | never | +| `llm(ref).model(...).prompt(...).as(T)` | LLM_CHAT_COMPLETE | when the call completes | +| `switchOn(name, value).when(key, body)…otherwise(body).get()` / `.run()` | SWITCH named `name` (`evaluatorType: value-param`, `switchCaseValue` the value's string form), with every declared case as a branch and a default branch: the taken case's body runs inline as ordinary workflow code and its calls land inside that branch, in the fragment or after the task the code paused on there; each untaken case shows a preview of the calls its body would have made (`_if_` entries, never run); the first call after the body is anchored after the switch (`metadata.after`). The server records `selectedCase` in the task's output and the UI marks that branch. A key is compared with the value's string form; declaring a key twice is an error at the call | never by itself; the body's calls wake the code as usual | +| `now()`, `random()` | none; recorded with the continuation | never | +| `@Variable` fields | workflow variables, written by every continuation's completion (only what changed); readable as `workflow.variables` | never | +| `@Signal`, `@Update` methods | handler lane: no task; a marker on the execution (`nativeState.handlers`) that each message wakes, and whose poll hands the worker the claimed messages; each message applied once (the client's message id is de-duplicated through `nativeState.seen`); update replies in `nativeState.replies`, kept 10 minutes, at most 500 | handler runs on a worker between continuations | +| `@Query` methods | none: the client restores an instance from the execution's `@Variable` values and runs the method itself | never; works on completed executions, writes nothing, and any change the method makes is discarded. It sees messages the execution has applied, not ones still queued | +| `return value` / `throw WorkflowFailedException` | workflow output / FAILED with reason | | +| any other unchecked exception the workflow method throws | FAILED, with `: ` as the reason; tasks that ran stay as they are, and a FAILED task named after the exception (a `TERMINATE` entry the code appends, never scheduled) marks where it threw, with that line as its site, inside the if or switch arm the code was in; what the code would have called next, had it not thrown, follows as previews (`task2_if_no_error`), read from the compiled code. An uncaught `TaskFailure` shows its own task FAILED instead. A retry removes the mark and runs the code again from its last continuation, so a fixed build continues the execution. In an `async` lane it is raised where the code waits for the lane (`join`, `get`); a lane nothing waits for does not fail the workflow, and the worker writes the exception to the log of the task the lane ran last | | +| `catch (TaskFailure e)` | none; the task stays FAILED in the UI, the lane continues | | + +Plain Java control flow costs nothing: a branch or loop that does not call the server is invisible +to it. Seeing every branch and which one was taken is a core Conductor capability, so an `if` or +`switch` whose arms call the server is a real SWITCH task with all its arms, and the arms not taken +show what they would have run (see Plain ifs and switches under "How an execution runs"). +`switchOn` is the explicit form: a name and case keys of your choosing, the value recorded as +`switchCaseValue`, and a value no case handles runs `otherwise`, or fails the workflow with +`switch has no case for ` when there is none. On replay either kind must take the arm +it recorded; another is a divergence ("took case X in the recorded execution but the code now +takes Y"). + +Input and output mapping: a `@Workflow` method with one record parameter takes the record's fields +as the workflow input, which is how the JSON kitchensink's `{"mod", "oddEven", "task2Name"}` maps +onto `KitchenSinkInput`. Several parameters map by name. The return value is the workflow output. +Task methods map the same way. Parameter names need `-parameters` or `@InputParam`, as today, and +registration fails fast with that message when neither is present. + +Method references and overloads: a `@WorkerTask` or `@Workflow` method that is overloaded cannot be +referenced unambiguously, and the compiler says so. Do not overload them. + +### Workflow options + +| Option | Where | Server behaviour | +|---|---|---| +| failure workflow | `@Workflow(failureWorkflow = "name", failureWorkflowVersion = n)` | started when the execution fails or times out, with `workflowId`, `reason` and `failureStatus` in its input; the failed execution's output gets `conductor.failure_workflow` | +| schedule | `@Schedule(cron = "0 0 9 * * MON-FRI", zone = "UTC", input = "{}")` on the `@Workflow` method, repeatable | registered with the Conductor scheduler (`POST /api/scheduler/schedules`) when the workers start; needs `conductor.scheduler.enabled=true`. Registration overwrites the schedule, including `paused`, so a schedule paused in the UI is resumed by the next worker start unless the annotation says `paused = true` | +| priority | `conductor.workflow(X::run).priority(5).start(input)` | the execution's priority (0 to 99), used to order its tasks in the queues | +| continuation timeout | `conductor.host().continuationTimeout(Duration.ofSeconds(30))` | the continuation lease (`metadata.native.continuationTimeoutSeconds`): how long a continuation handed to a worker may go unanswered before the server hands it to another worker; 30 s by default, an hour in dev mode; must exceed the longest replay | + +## The developer's day + +### First five minutes + +```bash +conductor server start # local server and UI, as today +conductor init java order-service # scaffolds a Maven project: one workflow, one task class, one test +cd order-service && ./mvnw -q compile exec:java +``` + +- `Conductor.of(client)` is the single entry point, over any `ConductorClient`: one from its + builder, `ConductorClient.fromEnvironment()` (reads `CONDUCTOR_SERVER_URL` and + `CONDUCTOR_AUTH_KEY`/`CONDUCTOR_AUTH_SECRET`, falling back to the local server), an Orkes + `ApiClient` with keys, or the Spring bean. `conductor.host()...start()` hosts, + `conductor.start(Cls::method, input)` runs. Closing a `Conductor` stops its workers; the client + stays its creator's to shut down. +- A server that is down never fails the application. `start()` returns at once; the definitions + are registered in the background, retried for as long as it takes with waits of 1, 2, 4... + seconds up to a minute (randomised, so that many hosts do not retry in step), and each failed + attempt is logged as an error. Polling backs off the same way. Only a fault in the code, such as + a workflow class that cannot be created, fails `start()`. +- Spring Boot: the starter auto-configures a `Conductor` bean over the configured `ConductorClient` + bean (the Orkes `ApiClient`, with keys, when one is configured), so it can be injected, and + hosts the application's workflows with no setup code: every class with a `@Workflow` method + under the application's packages, found as JPA entities are. A workflow class need not be a + bean; each replay gets a new instance, with task stubs (below) for its task-class constructor + parameters and other parameters and `@Autowired` fields injected from the context. + `@WorkerTask` beans stay on the starter's worker executor (one poller per task); the starter also registers their task definitions. Hosting + starts when the application has started and stops before the context closes; + `conductor.workflows.enabled=false` turns it off in a service that only starts workflows. + Example: `native-examples-spring`. Planned: `spring-boot-devtools` hot restart with in-flight + executions surviving it. The build sets `-parameters`. +- Existing users: a `@WorkerTask` class is already a task class. Add a `@Workflow` method that + calls it. Nothing else changes. + +### Writing + +- Names are optional everywhere except `once()`. Tasks are named by `@WorkerTask`, server steps by + call site. The `.ref("task_2")` and `"fanout1"` in the kitchensink exist only to match the JSON. +- `@Workflow` without arguments names the workflow after the method in snake case, version 1. +- Records in, records out. The SDK's Jackson is preconfigured for records, `Optional`, `java.time` + and enums. +- Execution metadata is static too: `workflowId()`, `correlationId()`, `attempt()`. +- Logging: SLF4J works as is; the SDK sets `workflowId` and `taskId` in the MDC on workflow and + task threads. + +### Running and debugging + +- Breakpoints just work: the code runs on a plain thread while a continuation is processed. + `devMode()` stretches the continuation lease to an hour so a pause at a breakpoint is not + mistaken for a dead worker, scales timers down, and logs every pause with its source line and + the UI link. +- Attach to any execution: `DurableDebugger.attach(KitchenSinkWorkflow.class, workflowId)` re-runs + the class in the IDE against the recorded results of a real execution, local or production, with + breakpoints and the real data. The CLI prints the invocation: `conductor workflow debug `. +- Stack traces point at your code; SDK frames are stripped. `TaskFailure` carries the worker's + exception class, message and stack. +- Every task links to source: the call site shows in the UI as `KitchenSinkWorkflow.kitchenSink:98`. +- Change code and keep going: restart the worker, in-flight executions continue by name matching. + +### Testing + +- Tier 1, in memory: `DurableTestEnvironment.inMemory()` runs the workflow code in process and + simulates server steps. The task class is a Mockito mock, and `tasks.task1(...)` + in the workflow lands on it. Milliseconds per test. `KitchenSinkTest` shows it. +- Tier 2, embedded: same API on the real server in the same JVM, in-memory persistence, timers + scaled with the WAIT time-scale knob. +- The graph is assertable: `run.ran("forkx")`, `run.tasks("sub_flow_1")`, `run.task("charge").input()`; + a `switchOn` counts as ran under its name (`run.ran("route")`), and in memory + (`DirectEngine.switchOn`) the taken body simply runs; a plain `if` or `switch` is code there, + not a step. +- The definition is assertable too, with no server: `Conductor.definitions(Fulfilment.class)` + returns the JSON that would be registered (`DiscoveryTest` checks the task names, the fork + branches, the switch cases, `inputParameters` and the handler inventory). +- Replay tests: `DurableReplay.assertCompatible(cls, recordedExecution)` re-runs current code + against an execution exported with `conductor workflow export ` and reports divergence. +- Task classes are plain classes; test them with nothing. + +### Deploying + +- Continuations are fully distributed by default: any machine polling the shared queue can run + any of them. Build pinning is opt-in: `buildId(...)` on the host adds that build as a polled + domain, and a start names it with a fallback, `conductor.workflow(X::run).taskToDomain(Map.of(".v1.code", + "build-7,NO_DOMAIN"))`. The first domain with a poller in the last 10 s wins, else the last + entry, `NO_DOMAIN` meaning the shared queue, so when old workers are gone name matching continues + the run on the new code. A worker's build is never captured automatically. The `*` key also + applies to ordinary tasks, and only workers polling that domain receive them; the SDK's task + workers poll the shared queue, so name the code type, or end a `*` list with `NO_DOMAIN`. +- Definitions in GitOps: `start()` registers definitions from the annotations by default; + `conductor.register(OrderService.class, …)` registers them without starting workers, for a + deploy step, and the static `Conductor.definitions(OrderService.class)` returns the same JSON + for review or to diff in a change. +- What gets registered is a real definition, not an empty one. `Registration.skeleton` calls + `Replayer.discover`, which reads the compiled workflow method (`CodeReader`, on ASM) and runs + nothing. Every call becomes a definition entry under the plain reference name an execution would + allocate: switches with all their cases (`switchCaseValue: ""`), plain ifs and switches whose + arms call the server the same way, `async` blocks as FORK_JOIN + + JOIN when the code joins them and as a fork with a non-waiting JOIN when it does not, a later + `join` as a JOIN of its own, `fanOut` as FORK_JOIN_DYNAMIC + JOIN, `repeatUntil` and `forEach` as DO_WHILE, `sleep` and + `awaitCondition` as WAIT, child, HTTP, event, LLM, MCP and agent entries; no `metadata.preview` + marks. Every SIMPLE entry gets an inline `taskDefinition` so registration validates without a + registered task definition. The definition also carries `inputParameters` (the components of a + single record parameter, or the parameter names) and, under `metadata.native`, the handler + inventory (`signals`, `updates`, `queries`) and `discovered` (`false` with a `discoveryError` when + the code could not be read). It shows every call the code can make, not one path: every arm of + an `if` or `switch`, a loop body once, and a catch block after its try. + Reading follows lambdas and methods of the workflow's own package. Inputs are not read beyond + constant reference names, case keys, an HTTP method and URI and an event sink; a task name + computed at run time shows as `task`; a call through an interface or into another package is not + followed. +- Migration: `conductor workflow convert --java ` generates a `@Workflow` method from an + existing JSON definition. Existing workers and JSON sub-workflows keep working, since task names + are task names and `child("legacy_flow", 2, input, Out.class)` calls any registered definition. + +### Errors a developer will actually hit + +| Situation | What happens | +|---|---| +| Parameter names missing (no `-parameters`) | registration fails with the flag to add, or `@InputParam("name")` | +| A `@Variable` field is not serializable | registration fails naming the field | +| Method reference to an overloaded task method | compile error (ambiguous reference) | +| No worker in this process for a referenced task | warning at start: tasks will wait for another worker | +| `once()` lambda throws | the exception is raised in the code at once, without retries; uncaught, the workflow fails with it | +| A task fails and nothing catches `TaskFailure` | the workflow fails with that reason; the task shows FAILED, the failure is one continuation later than a JSON workflow's | +| A task fails inside an `async` lane and the lane does not catch it | `join(...)` and `get()` raise it in the caller | +| An `async` block makes no server call | allowed; it is plain Java and never appears in the graph | +| Replay diverges | the execution is held with a message naming the call and its source line, and retried with backoff until a compatible build runs it | +| `switchOn` value matches no case and there is no `otherwise` | the SWITCH is drawn with every case, then `WorkflowFailedException` at the call: the workflow fails with `switch has no case for ` | +| A task is called before `async` lanes are joined | both run; the code goes on and the lanes run on their own | +| The method returns with lanes never joined | they still run: the execution stays `RUNNING` until they finish | +| A lane nothing joins fails | the execution is not failed; the failure shows on the lane's task | +| A `switchOn` case key is declared twice | `IllegalArgumentException` at the call (`case of is declared twice`) | +| The code now takes a different `switchOn` case than the recorded execution did | a divergence: the execution is held, naming both cases | +| Two workers hold the same continuation | only one holds the lease; the other's completion is refused (409) and that worker stops | + +## How an execution runs + +**Lanes and continuation markers.** The `@Workflow` method is a lane. Each `async` block is +another lane. A lane pauses when it needs a result from the server, and the pause is not a task: +the last entry the lane scheduled, the task it waits on, carries `metadata.continuation = {lane, +n}`, and the server copies it onto the task as a continuation marker. Everything the lane +scheduled since its last pause is sent as the completion of its previous continuation, and the +server appends it right after the task that lane last paused on: at the top level, inside a fork +branch, or inside a switch case. An execution holds exactly the tasks the code called. Lanes never +wait for each other except at `join` and `Promise.get()`. + +**Switches.** `switchOn` emits the SWITCH entry with every declared case (`Replayer.Lane.switchOn`) +and then runs the taken case's body inline, with the lane's output redirected into that case's +list: the body's calls are placed inside the case in the same fragment, and when the body pauses, +the lane's marker is on a task inside the case, so the next continuation's fragment is inserted +there too. Nesting is automatic; a `switchOn` inside a case does the same one level down. When a +continuation resumes inside a case and the body then returns, the lane remembers the switch +(`anchorAfter`) and the next entry it emits carries `metadata.after = `, so the server +inserts it after the switch rather than after the task the code paused on inside the case. An +anchor the server cannot find is a rejected fragment, and the workflow fails. A body that makes no +call is an empty branch and the code continues inline, with no anchor needed. + +**Untaken cases are previewed.** When the switch is first emitted, every case the value did not +take (and the `otherwise` body, when a declared case was taken) is read from its compiled code +(`Replayer.previewOf`, `CodeReader`); nothing runs, so the live run cannot be touched and no value +can stop the reading. Case bodies are serializable lambdas, so the runtime lambda names its compiled +method. Each call becomes an entry with `metadata.preview: true` and a reference name +`_if_` (nested previews compose the keys, `shipA_if_c_x`; `_2`, `_3` on a clash; the +names are reserved so later real calls never reuse them). `once`, `now` and `random` are not steps; +`async` bodies become the branches of one `fork_if_` FORK_JOIN with its `_join`, marked as not +waiting when the code does not join them, and a later `join` or `get` a JOIN of its own; `fanOut` becomes +a FORK_JOIN_DYNAMIC + JOIN; `repeatUntil` and `forEach` become a DO_WHILE with `loopCondition: "false"`; +a nested `switchOn` becomes a SWITCH with `switchCaseValue: ""` and every case previewed; `awaitCondition` +a WAIT. A case that cannot be read is drawn empty and the run goes on. Preview +entries are never scheduled, since the switch takes another case; the server validates them like +any fragment entry (unique references, known types, lane). In the kitchensink's odd run, case +`"0"` shows `task_4_if_0`, then the dynamic fork `fanout1_if_0` and its join. + +**Plain ifs and switches.** When `CodeReader` reads a method, each `if` and `switch` whose arms +call the server (directly, or through a lambda or a helper it follows) becomes a branch: its arms +as instruction ranges, the lines each arm's calls are made from, what each arm would call, and +whether the code can go through an arm without a call. javac's shapes are recognised: the jumps of +an `a && b` or `a || b` condition are one if; a jump that ends a loop is the loop's condition, not +an if; an else is the code a then-arm jumps over (a then-arm ending in `return`, `throw`, `break` +or `continue` has none, and the code after it follows the switch); string switches are labelled by +their strings and enum switches by their constants. A branch is named after what it decides on: +the last method its condition calls, else a field, else a local variable (`if_flagged`, +`switch_kind`, `if_pass`), numbered when repeated (`if_pass_2`). + +While the code runs, each call reports the lines its workflow frames are on (`StackWalker`), and +those lines say which arms it is in, since no other code of the method calls from an arm's lines. +The lane (`Replayer.Lane.follow`) keeps the branches it is inside: a call in an arm it has not +entered draws the branch as a SWITCH with every arm and the others previewed, and the calls that +follow go in that arm's case, exactly as for a `switchOn`, including resuming inside it in a later +continuation (`metadata.after`). A call outside the arm ends it. A call from a line before the last +one in the same arm means a loop around the branch came round: the branch is drawn again. A branch +the code went past without a call, between two calls of the same frame, is drawn with the arm that +must have been taken, when only one arm can be passed without a call and no loop around it could +have run it more than once; after the lane's last call, also only when every return of the method +comes after it. + +What is not drawn stays plain code, as it was before: an `if` whose arms share a line with each +other or with code outside them (a one-line ternary with a call in each arm), a switch whose cases +fall through, a branch passed without a call where more than one arm could have been. An execution +recorded by a build that did not draw a branch replays without it, and its calls stay where they +were; one recorded with another arm than the code now takes is a divergence. + +**How a continuation reaches a worker.** When the task a lane paused on finishes, its marker +becomes runnable and the server pushes a message to the continuation queue, the workflow's code +type (`.v.code`). By default that is one shared queue and any worker can run +any continuation; a start can name domains instead (see Deploying). The SDK holds no per-execution +lock: the server's one-continuation-per-execution slot (`nativeState.activeContinuation`) is what +serializes an execution. Workers poll with the ordinary batch task poll; the poll leases the marker (`LEASED`, with an epoch) and hands back the finished +task itself. The worker completes with the ordinary task update (`update-v2`), naming the lease's +`n` and `epoch`; a completion from a stale lease is refused with 409. The first continuation +(`|main`) and each handler run (`|handlers`) have no task, so the poll +builds one from the execution's `nativeState`, with the workflow input or the claimed messages. + +**Every continuation is a replay.** The worker is stateless. For each continuation it creates a +fresh instance of the class, fetches the execution with its tasks, replays every applied +continuation in the order the server applied them (`step` on the markers, with `@Variable` fields +restored to each one's `resumedWith`), then runs the active continuation against the current +variables. Each call is matched by lane, task name and ordinal; a recorded result is returned, a +missing one is scheduled. Handler runs are not replayed; their effect is in the variables. This is +a replay engine, a small one: its input is the markers and the task list, not a generic event +history. The same mechanism powers `DurableReplay`. + +**Failures.** A task the code waits on is first retried like any Conductor task: worker tasks +three times with exponential backoff by default (`@WorkerTask(retryCount, retryDelaySeconds)`), +HTTP and LLM steps with the same policy (`http(ref).retries(count, delay)`). A worker that throws +`NonRetryableException` is not retried. When retries are exhausted the task is FAILED in the UI +and, because it is emitted as `optional`, the server schedules the lane's next continuation +instead of failing the workflow. The SDK throws `TaskFailure` at the call. Caught, the code +decides; uncaught, the lane ends with the error: the main lane fails the workflow with that +reason, and an `async` lane raises it in whoever calls `get()`. Fire-and-forget steps, events and +started workflows, never throw; their failures are visible in the UI. Timeouts take the same path: +a human task that nobody answers returns an empty result, and the task shows TIMED_OUT. + +**Divergence policy.** Divergence is strict. A replay that reaches a call, fork, loop, wait, +switch or recorded value the recording does not have raises `NonDeterminismException`, with a +message naming the call and its source line, and the server holds the execution, retrying with +backoff, until a compatible build runs it. A `switchOn` replays against the recorded `switchCaseValue`: the code +taking another case is a divergence too ("switch took case X in the recorded execution but +the code now takes Y"). + +**Variables.** `@Variable` fields are written to `workflow.variables` by every continuation's +completion, together with the values the continuation started from (`resumedWith`); the server +applies only what changed and defers a completion whose base another completion has moved. A +replay restores the fields to each continuation's `resumedWith`, so handler writes are seen at the +same points as the first time. + +## Rules for workflow code + +1. Anything non-deterministic or with a side effect that is not a task goes through `once()`, + `now()` or `random()`. `once()` is at-least-once on worker loss, like any task. +2. Calls are matched by task name and ordinal within their lane on a re-run. Adding a log line, + reordering independent calls, or adding a call in code that running executions have not reached yet is safe. A call added + before the point they have reached holds them. +3. Blocking I/O belongs in tasks, which are retried, or in `once()` when it is small and safe to fail. Both are recorded and + visible. +4. Wait with `sleep(Duration)`, never `Thread.sleep`: plain code runs again on every replay, so a + `Thread.sleep` is repeated each time the code continues and holds a worker thread. The host + reads the compiled workflow code at `start()` and logs a warning naming the workflow and the line + of every `Thread.sleep` it can reach, through lambdas and helpers. +5. Plain code in a `finally` block also runs each time the lane pauses, as the lane is torn down. + Keep side effects out of it. An untaken case or arm is only read from the compiled code, so + nothing in it runs. + +## The diagram + +The live execution shows the path taken, with status, inputs, outputs and source line per task. +There is nothing to fold: the execution holds exactly the tasks the code called, and a task the +code paused on shows its continuation (lane, number, state, worker, applied time) in its panel. + +A `switchOn` shows as a SWITCH node with every declared case as a branch, the default included, +and the taken case marked from the task's `selectedCase`; the calls its body made sit inside that +branch, and the other branches show their preview entries (`_if_`) without a status, +as the untaken branches of a JSON switch do (`ui-next`'s switch mapper, unchanged). A plain `if` +or `switch` whose arms call the server shows the same way, named after what it decides on. + +**Reading a definition against an execution.** The definition page shows the discovered graph: +everything the code can call, every switch with all its cases, every fork, every loop, with the +reference names an execution would use (`pick`, `fork`, `fork_join`, `sleep`, `region`, `ship`, +`ship_2` for `DiscoveryTest`'s fulfilment workflow). An execution shows what the code did: the +server empties the discovered tasks from the execution's own copy of the definition at start +(`NativeContinuationService.initialize`), and that copy grows one fragment per continuation, so it +holds exactly the tasks the code called plus the previews of the switch cases it did not take. +A hello world registered as `[greet, shout]` runs with exactly two tasks; the kitchensink +registers 37 top-level entries and an odd-path execution grows a 45-entry copy. Every entry still +records its source line (`metadata.site`, via `StackWalker` skipping SDK frames), so both views +link to the code. + +## Mapping to the JSON kitchensink + +| JSON task | Type | In `KitchenSinkWorkflow.kitchenSink` | +|---|---|---| +| `task_1` | SIMPLE | `tasks.task1(...)` | +| `event_0` | EVENT | `event("event_0").to("conductor").send(stats)` | +| `task_2` | DYNAMIC | `task(input.task2Name()).ref("task_2")...as(OddEven.class)` | +| `oddEvenDecision` | DECISION | `switch (oddEven.oddEven()) { case "0" -> {...} case "1" -> {...} default -> throw new WorkflowFailedException(...); }`, a plain Java switch drawn as the SWITCH `switch_oddEven` (`value-param` on `switchCaseValue`) with cases `"0"` and `"1"`; the taken case holds the calls below. The JSON's reference name would need `switchOn("oddEvenDecision", ...)` | +| `task_4`, `fanout1`, `join1` | SIMPLE, FORK_JOIN_DYNAMIC, JOIN | `tasks.task4(...)`, `fanOut("fanout1", ...)`, inside case `"0"`; on the odd path the case shows the preview `task_4_if_0` | +| `forkx`, `task_10`, `wf3`, `task_11`, `wf4`, `join2` | FORK_JOIN, SIMPLE, SUB_WORKFLOW, JOIN | two `async` blocks and `join(wf3, wf4)`, inside case `"1"`; each branch is `task → child` as in the JSON; fork and join refs derive as `fork`, `fork_join`, child refs as `sub_flow_1`, `sub_flow_1_2` | +| `get_es_1` | HTTP | `http("get_es_1").get(...).asJson()` | +| `task_30` | SIMPLE | `tasks.task30(...)` | +| `outputParameters` | | the returned record | + +## Server and CLI changes + +Phase A runs the kitchensink with no server change: an outer DO_WHILE with a step task and an +inline SUB_WORKFLOW per fragment, the pattern the harness SDK proved. Branch independence and the +flat graph need Phase B: + +1. Continuation markers: `continuation` on the task the code paused on (copied from the entry's + `metadata.continuation`), and `nativeState` on the execution for the first continuation and + the handler lane. The ordinary batch poll of the code type leases a marker and hands back the + task; the ordinary `update-v2` completes it with a fragment the server appends immediately + after that task, including inside a FORK_JOIN branch or a SWITCH case, or after the entry the + fragment's first element names in `metadata.after` (code that left a `switchOn` case). +2. JOIN with live targets: a fork branch ends when its last task is terminal and its marker, if + any, is applied and ended the lane. +3. Lease epoch: the server accepts a completion only for the current lease (`n` and `epoch`). +4. Recorded values: `once`, `now` and `random` ride in the completion's `recorded` map and are + stored on the marker; no task. +5. The definition view: planned as an observed graph merged from executions by call site; built + instead as the graph the SDK discovers from the code at registration (above), with the server + clearing it from each execution's copy (`NativeContinuationService.initialize`). +6. Per-execution time scale for WAIT, used by dev mode and the embedded test environment. +7. Standing items: JOIN any-of, early-signal buffering in the per-workflow message queue, + idempotency key on the public start endpoint, hide-by-metadata and source links in the diagram. + +SDK: `retryCount`, `retryDelay` and `responseTimeout` attributes on `@WorkerTask`, so the task +definition comes from the annotation. + +CLI: `conductor init java`, `conductor workflow debug `, `conductor workflow export `, +`conductor workflow convert --java `. + +Latency (push transport) and very large loops (incremental decide) are deferred to their own rounds. + +## Open questions for review + +1. **Compile-time dependency on task classes.** Calling by method reference means the workflow + module depends on the task class, which may carry heavy dependencies. Teams can put task + classes in a thin module, or call by name. Worth a stated convention. +2. **In-memory test fidelity.** Tier 1 simulates server steps rather than running the server. If + the embedded server can boot in a second or two, it could be the only tier. +3. **`fanOut` stages.** Resolved: `fanOut` runs one lane per item (a FORK_JOIN generated at run + time), so items progress independently; there are no stages and no hidden tasks. +4. **`once()` visibility versus cost.** Resolved: a recorded value costs nothing beyond its bytes + on the continuation marker; it is visible in the task panel of the task the code paused on. + +## Durability + +The guarantees and how each was verified are in the server repository's +`proposals/native-workflows/DURABILITY.md`; how they compare with other durable execution engines +is in `proposals/native-workflows/COMPARISON.md`. `native-examples/chaos.sh` runs the +kitchensink while killing and restarting the worker and the server; every check must still pass. + +## Running the kitchensink + +```bash +export CONDUCTOR_SERVER_URL=http://localhost:8099/api # a server built from the conductor branch +./gradlew :native-examples:run # odd path, even path and charge-failure path, with checks +./gradlew :native-examples:test # in-memory tests and the replay test against a recorded execution +``` + +`operator.OperatorChecks` in the same module exercises retry, rerun from a task and restart on a +native execution. diff --git a/design/native-workflows/server-changes.md b/design/native-workflows/server-changes.md new file mode 100644 index 000000000..752745c0f --- /dev/null +++ b/design/native-workflows/server-changes.md @@ -0,0 +1,165 @@ +# Server changes for native workflows + +Companion to `README.md`. Status: implemented in the server repository (`conductor-oss/conductor`, +branch `design/native-workflows`), as protocol 2; its `proposals/native-workflows/` has the full +design (`01` to `03`), the test plan and the implementation status. Every item below names the +code it touches there. Paths are relative to that repository. + +## Phase A: no server change + +The SDK could have run the kitchensink on an unchanged server: + +- Each continuation as a SIMPLE task named `.v.code` that the owning worker + polls, and each fragment as an inline sub-workflow: `SubWorkflowParams.workflowDefinition` + (`common/.../workflow/SubWorkflowParams.java`) is mapped by `SubWorkflowTaskMapper`. +- Owner affinity through `taskToDomain` with the ordered fallback that `setTaskDomains` and + `getActiveDomain` implement (`core/.../execution/WorkflowExecutorOps.java`). +- External completion through `POST /api/tasks/{workflowId}/{taskRefName}/{status}` + (`rest/.../controllers/TaskResource.java`). +- Variables through SET_VARIABLE (`core/.../tasks/SetVariable.java`). + +Limits of Phase A: every fragment is a child execution, so the diagram nests, and fork branches +share one continuation, so a branch cannot advance until its siblings pause. Phase B removed both, +and its second round removed the pause tasks themselves. + +## Phase B: the flat graph, with exactly the code's tasks + +### B1. Engine state: continuation markers and `nativeState` (small) + +The code only ever pauses on a task, so the state the engine needs to drive the code lives on +those tasks. + +- `common/.../tasks/TaskContinuation.java`, and a `continuation` field on `Task` and `TaskModel`: + `lane`, `n`, `state` (`WAITING` → `RUNNABLE` → `LEASED` → `APPLIED`), `epoch`, `worker`, + `queue`, `queuedAt`, `leasedAt`, `appliedAt`, `attempts`, `deferred`, and once applied the + record a replay reads: `step`, `recorded`, `resumedWith`, `done`, `result`, `error`. +- `common/.../run/NativeState.java`, and a `nativeState` field on `Workflow` and `WorkflowModel`: + `protocol`, `codeType`, `continuationTimeoutSeconds`, `step`, `activeContinuation`, `activeUntil`, `bootstrap` and + `handlers` (markers for the two lanes that have no task), `replies`, `seen`. O(1) in the length + of the execution. +- `TaskMapperContext.createTaskModel` copies an entry's `metadata.continuation` onto the scheduled + task as a `WAITING` marker. `NativeContinuationService.initialize` builds `nativeState` at start + and restart from the skeleton's `metadata.native`. +- The registered definition carries the graph the SDK discovered from the code + (`Registration.skeleton` → `Replayer.discover`), with inline task definitions on its SIMPLE + entries so it validates; `WorkflowDef` also allows `tasks: []` when `metadata.native` is + present (the harness registers that). `NativeContinuationService.initialize` clears the tasks + from the execution's own copy at start and restart, so an execution still starts empty and + holds only what the code calls. `MetadataServiceImpl` refuses native definitions when + `conductor.app.nativeWorkflow.enabled=false`. + +### B2. Wake, lease, complete (medium, the core change) + +- Wake: `DeciderService.decide` calls `NativeContinuationService.onEvaluated` when it evaluates a + terminal task; a `WAITING` marker becomes `RUNNABLE`. `WorkflowExecutorOps.decide` then runs + `repairAndWake`, saves the touched tasks and the workflow row, and pushes one message per + runnable or expired marker (`pushIfNotExists`) to the continuation queue: the shared queue of + the code type, unless the workflow's `taskToDomain` names the code type or `*`, resolved by + `ExecutorUtils.activeDomain` (the code `getActiveDomain` also uses): the first domain with a + poller in the last 10 s, else the last entry, `NO_DOMAIN` meaning the shared queue. While a marker + is `RUNNABLE` or `LEASED` (`NativeContinuationService.needsPromptRevisit`), `decide` caps the + workflow's decider-queue postpone at `workflowOffsetTimeout` (30 s) instead of the + `maxPostponeDurationSeconds` (an hour) the in-progress tasks would allow, and always writes it, + replacing a longer earlier postpone, so the next decide runs `repairAndWake` soon enough to + re-route a wake-up queued for a domain whose workers are gone. Found by `chaos.sh` under the + earlier per-worker routing: a worker killed right after its continuation was queued to its own + domain queue, with the workflow postponed by an hour. +- Offer and lease: a decide, under the lock it already takes, offers the next continuation + (`NativeContinuationService.offer` from `repairAndWake`): the marker `LEASED` with `epoch + 1`, + the slot, the queue, then the push. `ExecutionService.poll` hands a continuation queue's + messages to `NativeContinuationService.lease`, which takes no lock and writes nothing: it checks + the message is the one offered, leaves it unacknowledged for `continuationTimeoutSeconds`, and + returns the finished task itself, or a synthetic task (`|main`, `|handlers`) built + from `nativeState` with the workflow input or the claimed messages. +- Complete: `WorkflowExecutorOps.updateTask` routes a synthetic id, or a `LEASED` task whose + result carries `protocol`, to `completeContinuation`, which runs inside the decide the + completion triggers and calls `NativeContinuationService.complete` under that decide's lock: lease check (`n`, `epoch`; else 409), + protocol check, variable conflict and pending-message deferral (a main lane that returned while + the handler lane has work is deferred with `waiting for handlers: ` and not re-queued; + `repairAndWake` wakes it once that lane has settled), fragment validation and + `WorkflowDef.insertAfter` (after the awaited task, or after the entry the fragment's first + element names in `metadata.after`: the SDK sets it on the first call after a `switchOn` case + the lane resumed in, so that call lands after the switch and not inside the case; + `NativeContinuationService.anchorOf`; an anchor that names no entry is a rejected fragment), + variables, replies, seen, releases, the marker's record, the awaited task's + `executed = false`; then the workflow row is saved before the task, the message is acknowledged, + and the workflow is completed or failed when the main lane is done. +- `DeciderService.checkForWorkflowCompletion` returns false for native workflows; the start path + schedules nothing for an empty native definition. + +Checks that mattered: + +- `isLazyEvaluateWorkflow` needs no exemption: a task in a fork whose JOIN has `joinOn: []` is + listed by no join, so its completion decides at once. +- Definition size: each append rewrites the workflow row. Long plain-Java loops grow it without + bound; `conductor.app.nativeWorkflow.maxDefinitionTasks` (5000) caps it. This is the "very + large loops" round. + +### B3. JOIN with live targets (small) + +`Join.execute`, for a native JOIN whose `joinOn` is empty: targets are the last entry of each +branch of the preceding fork in the current definition; the JOIN waits while the fork is not in +the definition it read, and while any target is not terminal or carries a marker that is not +`APPLIED` with `done` (`NativeContinuationService.lanesSettled`). `inputParameters.joinStrategy: +ANY` completes on the first settled success. + +### B4. Recorded values (none) + +`once`, `now` and `random` are reported in the completion's `recorded` map and stored on the +marker. No task type; the earlier plan's RECORD task was dropped with protocol 2. + +### B5. UI: continuation on the task panel, engine state on the summary (small) + +`ui-next/src/pages/execution/TaskSummary.tsx` shows a task's `continuation` (lane, number, +state, deferred reason, worker, applied time); `ExecutionSummary.tsx` shows `nativeState` (code +type, continuations applied, bootstrap state while pending, handler run). There are +no hidden tasks to fold. `metadata.site = "Class.method:line"` on every entry gives the source +line. A SWITCH emitted by `switchOn` needs nothing new on either side: `SwitchTaskMapper` +evaluates `value-param` on `switchCaseValue` and records `selectedCase` and `evaluationResult`; +`ui-next`'s switch mapper (`src/components/features/flow/nodes/mapper/switch.ts`) draws every +`decisionCases` key, empty lists and the default case included, and marks the selected one. The +preview entries the SDK puts in untaken cases (`metadata.preview: true`, `_if_`) are +ordinary definition entries to the server, validated like any other and never scheduled; neither +the server nor `ui-next` reads `metadata.preview`. + +### B6. Per-execution time scale for WAIT (small) + +`WaitTaskMapper` divides the duration by `variables.__timeScale` when +`conductor.app.nativeWorkflow.waitTimeScaleEnabled` is true. Dev mode sets the variable in the +first continuation's completion; production never does. + +## Standing items from earlier passes + +### S1. Idempotency key on the public start (done) + +`WorkflowExecutorOps.startWorkflow(StartWorkflowInput)` routes through `startWorkflowIdempotent` +when `idempotencyKey` is set; `RETURN_EXISTING` or `FAIL`. + +### S2. Signals and early signals (done) + +- Targeted completion of a specific WAIT: `POST /api/tasks/{workflowId}/{taskRefName}/{status}`, + used for `awaitExternal` and human tasks. +- Signals, updates and queries: `POST /api/workflow/{workflowId}/messages` pushes to the durable + per-workflow message queue (`JdbcWorkflowMessageQueueDAO`, SQLite, Postgres and MySQL) inside a + decide, which wakes and offers the handler marker. The handler lane's poll claims the messages under + `handlers#`, fenced by `n`. `awaitCondition` waits are completed through the handler + completion's `releases`. + +### S3. JOIN any-of (done) + +`inputParameters.joinStrategy: ANY` on the JOIN; the other branches are not cancelled. + +## Not server changes + +- Replay, divergence detection, the in-memory test environment and `DurableReplay` are SDK work + on top of the markers and the task list the server exposes. +- Build pinning is opt-in: `buildId` on the host adds a polled domain, and a domain list in the + start's `taskToDomain` uses it. The SDK sends no routing data in a completion. +- `@WorkerTask` registration attributes (`retryCount`, `retryDelaySeconds`, + `responseTimeoutSeconds`) are SDK changes that produce ordinary task definitions. + +## Deferred to their own rounds + +- Latency: a push transport for continuations, replacing long-poll for the owning worker, and an + in-memory fast path that skips the replay. +- Very large loops: incremental decide and bounded definition growth (`continueAsNew`). diff --git a/native-examples-spring/README.md b/native-examples-spring/README.md new file mode 100644 index 000000000..d35a22bee --- /dev/null +++ b/native-examples-spring/README.md @@ -0,0 +1,27 @@ +# Native workflows in a Spring Boot service + +The starter (`conductor-client-spring`) does the wiring. The application has no Conductor setup +code: + +| File | What it shows | +|---|---| +| `OrderWorkflow.java` | The workflow: a plain class with a `@Workflow` method. It is not a bean; the starter finds it under the application's package and creates a new instance for each replay. It takes `OrderTasks` as a constructor parameter and calls the tasks directly: Conductor passes a stand-in whose calls schedule the tasks, so `tasks.charge(...)` runs once, on a worker, however often the workflow is replayed. The `if` that ships an order of 100 or more insured is plain Java; because its arms call tasks, the execution shows it as a SWITCH named `if_amount`, with both arms and the one taken. | +| `OrderTasks.java` | The tasks: an ordinary `@Component` with an injected dependency. The starter polls its `@WorkerTask` methods and registers their task definitions from the annotation attributes (`retryCount = 5` on `charge`). | +| `OrderController.java` | Starts executions and reads them back through the injected `Conductor` bean. | +| `application.properties` | The server URL, and the port of this service. | + +Run it against a server (`CONDUCTOR_SERVER_URL`, default `http://localhost:8080/api`): + +```shell +./gradlew :native-examples-spring:run +curl -s -X POST localhost:8095/orders -H 'Content-Type: application/json' -d '{"item":"book","quantity":2}' +curl -s -X POST localhost:8095/orders -H 'Content-Type: application/json' -d '{"item":"book","quantity":10}' +curl -s localhost:8095/orders/ +``` + +The service starts even when the Conductor server is down: the definitions are registered in the +background, retried with backoff until the server answers, with an error logged for each failed +attempt. + +Settings under `conductor.workflows`: `enabled` (set `false` in a service that only starts +workflows), `worker-id`, `build-id`, `threads`, `continuation-timeout` and `dev-mode`. diff --git a/native-examples-spring/build.gradle b/native-examples-spring/build.gradle new file mode 100644 index 000000000..121dca0c3 --- /dev/null +++ b/native-examples-spring/build.gradle @@ -0,0 +1,27 @@ +plugins { + id 'java' + id 'application' +} + +// A Spring Boot service hosting native workflows through auto-configuration. Against a server +// (CONDUCTOR_SERVER_URL, default http://localhost:8080/api): +// ./gradlew :native-examples-spring:run +// curl -s -X POST localhost:8095/orders -H 'Content-Type: application/json' -d '{"item":"book","quantity":2}' +application { + mainClass = 'orders.OrdersApplication' +} + +dependencies { + implementation project(':conductor-client-spring') + implementation 'org.springframework.boot:spring-boot-starter-web:3.5.13' + + testImplementation 'org.springframework.boot:spring-boot-starter-test:3.5.13' +} + +// Task inputs are keyed by parameter name, read reflectively +compileJava.options.compilerArgs << '-parameters' +compileTestJava.options.compilerArgs << '-parameters' + +test { + useJUnitPlatform() +} diff --git a/native-examples-spring/src/main/java/orders/Catalog.java b/native-examples-spring/src/main/java/orders/Catalog.java new file mode 100644 index 000000000..4b18176c9 --- /dev/null +++ b/native-examples-spring/src/main/java/orders/Catalog.java @@ -0,0 +1,32 @@ +/* + * Copyright 2026 Conductor 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 orders; + +import java.util.Map; + +import org.springframework.stereotype.Service; + +/** A dependency of the tasks, to show they are ordinary beans. */ +@Service +public class Catalog { + + private final Map prices = Map.of("book", 12.5, "pen", 1.25); + + public double price(String item) { + Double price = prices.get(item); + if (price == null) { + throw new IllegalArgumentException("no such item: " + item); + } + return price; + } +} diff --git a/native-examples-spring/src/main/java/orders/OrderController.java b/native-examples-spring/src/main/java/orders/OrderController.java new file mode 100644 index 000000000..e87408024 --- /dev/null +++ b/native-examples-spring/src/main/java/orders/OrderController.java @@ -0,0 +1,64 @@ +/* + * Copyright 2026 Conductor 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 orders; + +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.WorkflowHandle; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import orders.Orders.OrderRequest; +import orders.Orders.OrderResult; + +/** Starts executions and reads them back, through the {@code Conductor} bean. */ +@RestController +@RequestMapping("/orders") +public class OrderController { + + private final Conductor conductor; + + public OrderController(Conductor conductor) { + this.conductor = conductor; + } + + @PostMapping + public Map create(@RequestBody OrderRequest order) { + WorkflowHandle run = conductor.start(OrderWorkflow::process, order); + return view(run); + } + + @GetMapping("/{workflowId}") + public Map get(@PathVariable String workflowId) { + return view(conductor.attach(OrderWorkflow::process, workflowId)); + } + + private static Map view(WorkflowHandle run) { + Map view = new LinkedHashMap<>(); + view.put("workflowId", run.workflowId()); + view.put("url", run.url()); + String status = run.status(); + view.put("status", status); + if ("COMPLETED".equals(status)) { + view.put("result", run.result(Duration.ofSeconds(5))); + } + return view; + } +} diff --git a/native-examples-spring/src/main/java/orders/OrderTasks.java b/native-examples-spring/src/main/java/orders/OrderTasks.java new file mode 100644 index 000000000..3b2bd2f90 --- /dev/null +++ b/native-examples-spring/src/main/java/orders/OrderTasks.java @@ -0,0 +1,57 @@ +/* + * Copyright 2026 Conductor 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 orders; + +import java.util.UUID; + +import org.springframework.stereotype.Component; + +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +import orders.Orders.OrderRequest; +import orders.Orders.Receipt; +import orders.Orders.Reservation; + +/** + * The tasks: an ordinary bean with its dependencies injected. The starter polls its + * {@code @WorkerTask} methods and registers their task definitions from the annotation attributes. + */ +@Component +public class OrderTasks { + + private final Catalog catalog; + + public OrderTasks(Catalog catalog) { + this.catalog = catalog; + } + + @WorkerTask("spring_order_reserve") + public Reservation reserve(OrderRequest order) { + return new Reservation("res-" + UUID.randomUUID(), order.item(), order.quantity()); + } + + @WorkerTask(value = "spring_order_charge", retryCount = 5, retryDelaySeconds = 2) + public Receipt charge(Reservation reservation) { + return new Receipt("rcpt-" + UUID.randomUUID(), catalog.price(reservation.item()) * reservation.quantity()); + } + + @WorkerTask("spring_order_ship") + public String ship(Reservation reservation) { + return "trk-" + reservation.id().substring(4, 12); + } + + @WorkerTask("spring_order_ship_insured") + public String shipInsured(Reservation reservation, double insuredValue) { + return "ins-" + reservation.id().substring(4, 12); + } +} diff --git a/native-examples-spring/src/main/java/orders/OrderWorkflow.java b/native-examples-spring/src/main/java/orders/OrderWorkflow.java new file mode 100644 index 000000000..cd844fc54 --- /dev/null +++ b/native-examples-spring/src/main/java/orders/OrderWorkflow.java @@ -0,0 +1,53 @@ +/* + * Copyright 2026 Conductor 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 orders; + +import org.conductoross.conductor.sdk.Workflow; + +import orders.Orders.OrderRequest; +import orders.Orders.OrderResult; +import orders.Orders.Receipt; +import orders.Orders.Reservation; + +/** + * The workflow: plain code, and not a bean. The starter finds it by its {@code @Workflow} method. + * + *

It takes its task class as a constructor parameter and calls the tasks directly. What it gets + * is not the {@code OrderTasks} bean but a stand-in whose calls schedule each task, to run on + * whichever instance of this service polls it; the method is replayed against the recorded tasks + * to continue after each one, and a replayed call returns the recorded result. Its ifs, switches + * and loops are plain Java. + */ +public class OrderWorkflow { + + private final OrderTasks tasks; + + public OrderWorkflow(OrderTasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "spring_order", version = 1) + public OrderResult process(OrderRequest order) { + Reservation reservation = tasks.reserve(order); + Receipt receipt = tasks.charge(reservation); + // A plain if: its arms call tasks, so the execution shows it as a SWITCH (if_amount) with + // both arms and the one taken; the arm not taken shows the task it would have called. + String tracking; + if (receipt.amount() >= 100) { + tracking = tasks.shipInsured(reservation, receipt.amount()); + } else { + tracking = tasks.ship(reservation); + } + return new OrderResult(reservation.id(), receipt.id(), receipt.amount(), tracking); + } +} diff --git a/native-examples-spring/src/main/java/orders/Orders.java b/native-examples-spring/src/main/java/orders/Orders.java new file mode 100644 index 000000000..37604fee2 --- /dev/null +++ b/native-examples-spring/src/main/java/orders/Orders.java @@ -0,0 +1,27 @@ +/* + * Copyright 2026 Conductor 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 orders; + +/** The data the workflow and its tasks pass around. */ +public final class Orders { + + private Orders() {} + + public record OrderRequest(String item, int quantity) {} + + public record Reservation(String id, String item, int quantity) {} + + public record Receipt(String id, double amount) {} + + public record OrderResult(String reservation, String receipt, double amount, String tracking) {} +} diff --git a/native-examples-spring/src/main/java/orders/OrdersApplication.java b/native-examples-spring/src/main/java/orders/OrdersApplication.java new file mode 100644 index 000000000..2d7fd64af --- /dev/null +++ b/native-examples-spring/src/main/java/orders/OrdersApplication.java @@ -0,0 +1,30 @@ +/* + * Copyright 2026 Conductor 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 orders; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * A Spring Boot service with a native workflow. The Conductor starter does all the wiring: it finds + * {@link OrderWorkflow} (any class with a {@code @Workflow} method under this package), registers + * its definition and the task definitions of {@link OrderTasks}, polls for both, and provides the + * {@code Conductor} bean that {@link OrderController} starts executions with. + */ +@SpringBootApplication +public class OrdersApplication { + + public static void main(String[] args) { + SpringApplication.run(OrdersApplication.class, args); + } +} diff --git a/native-examples-spring/src/main/resources/application.properties b/native-examples-spring/src/main/resources/application.properties new file mode 100644 index 000000000..7a85a478f --- /dev/null +++ b/native-examples-spring/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.port=8095 +conductor.client.root-uri=${CONDUCTOR_SERVER_URL:http://localhost:8080/api} diff --git a/native-examples/DURABILITY-BENCH.md b/native-examples/DURABILITY-BENCH.md new file mode 100644 index 000000000..43f4ae58f --- /dev/null +++ b/native-examples/DURABILITY-BENCH.md @@ -0,0 +1,324 @@ +# Durability bench for native workflows + +A failure-testing bench in the style of Jepsen's analysis of Orkes Conductor 5.3.2 +(jepsen.io/analyses/orkes-conductor-5.3.2), aimed at what native workflows add: code that replays, +continuations that move between workers, recorded values, signals and updates. It runs a workload +on several worker processes while a nemesis kills, pauses and partitions the workers and the +server. It records what every client and worker did, then checks the records against the +guarantees in the server repository's `proposals/native-workflows/DURABILITY.md`. + +The code is in `src/main/java/durability/`. + +## Running it + +```bash +./gradlew :native-examples:installDist +BENCH_SERVER_PORT=8099 \ +BENCH_SERVER_SCRIPT=/path/to/run-server.sh \ +./native-examples/bench.sh run # exit 0: valid, 1: a check failed +./native-examples/bench.sh check native-examples/build/durability/ # re-check a run +``` + +`BENCH_SERVER_SCRIPT` runs the server in the foreground and should `exec java ...`, so that the +process the bench kills is the server itself. The bench starts the server with it after a kill. +The server must have `conductor.workflow-message-queue.enabled=true`. With +`conductor.app.nativeWorkflow.waitTimeScaleEnabled=true` the workers' time scale shortens timers. + +| Variable | Default | Meaning | +|---|---|---| +| `BENCH_SERVER_PORT` | 8099 | server under test; 8080 is refused | +| `BENCH_PROXY_PORT` | 18097 | the partitioning proxy the workers connect through | +| `BENCH_WORKERS` | 3 | worker processes | +| `BENCH_WORKFLOWS` | 30 | executions started | +| `BENCH_MAIN_SECONDS` | 180 | length of the fault phase | +| `BENCH_RECOVERY_SECONDS` | 600 | how long executions get to finish after healing | +| `BENCH_FAULTS` | all five | `worker-kill,worker-pause,server-kill,server-pause,partition`, or `none` | +| `BENCH_FAULT_INTERVAL` | 12 | mean seconds between faults, exponentially distributed | +| `BENCH_SIGNAL_MS`, `BENCH_UPDATE_MS` | 250, 1500 | client operation rates | +| `BENCH_STEP_MAX_MS`, `BENCH_STEP_FAIL_RATE` | 800, 0.1 | task duration bound and injected transient failure rate | +| `BENCH_SEED` | time | seed for the fault schedule | +| `BENCH_OUT` | `build/durability/` | output directory | + +## Workload + +`LedgerWorkflow` exercises every part of the engine a failure can break: + +1. Recorded values: `once` (a UUID), `random()` and `now()`. Every replay writes what it saw to the + ledger. +2. A task, then two `async` lanes (two tasks; a timer then a task), joined. Then a child workflow + running a task, then a condition wait released by a `close` signal, then a last task. +3. Handlers: `deposit` signals append an id to a list, `bump` updates increment a counter and + return it, and `close` releases the wait. A `deposits` query returns the list, and also tries + to append to it, which must never take effect. + +Every task (`durability_step`) is a pure function of the execution id and step number. It sleeps a +random time and fails transiently at a configured rate, so retries happen all the time. Each +attempt writes start, end or fail to the worker's ledger, an append-only file written with one +`write` per line, so a SIGKILL cannot lose earlier lines. The workflow returns the sum of its six +steps, the deposits it saw in order, and the counter. + +## Phases + +1. **Main.** A starter starts executions with an idempotency key and correlation id per execution, + retrying failed starts with the same key. A signaler sends `deposit` to a random running + execution every 250 ms. Three updaters send `bump`. Two queriers run `deposits` every 400 ms. + The nemesis injects faults. After recovery, every execution is queried once more. +2. **Recovery.** Heal everything, restart dead workers and the server. Wait for updates in flight, + retry any start that never succeeded, send `close` to every execution, and wait until all are + terminal. +3. **Final.** Read every execution by correlation id and by the id each start returned, then check. + +Every client operation is recorded in `history.jsonl` as `invoke` followed by `ok`, `fail` or +`info`. `fail` means the operation definitely did not happen: connection refused, or a 4xx. `info` +means it may have happened: a timeout, a reset, or a 5xx. Faults are recorded in the same file. + +## Faults + +| Fault | How | What it tests | +|---|---|---| +| `worker-kill` | SIGKILL a worker. After 1 to 20 s, restart it: half the time with the same worker id, half with a new one | continuations held by a dead worker; replay on a new host; tasks killed mid-attempt | +| `worker-pause` | SIGSTOP a worker for 5 to 45 s, then SIGCONT | a zombie worker that wakes up and completes stale continuations | +| `server-kill` | SIGKILL the server, restart it after 1 to 10 s | crash between the writes of one operation; in-flight requests with unknown outcome | +| `server-pause` | SIGSTOP the server for 5 to 25 s | client and worker timeouts; long polls that never return | +| `partition` | the proxy resets every worker connection and holds new ones unanswered for 5 to 40 s | workers cut off from the server while clients still reach it | + +Not covered: database faults (the bench runs on SQLite in the server process, so a server kill is +also a database crash), clock skew, disk faults, and partitions between clients and server. + +## Checks + +Errors violate a guarantee. Information is allowed by the guarantees, and is measured. + +| Check | Level | Violation | +|---|---|---| +| `lost-execution` | error | a start was acknowledged, but the execution is gone | +| `duplicate-execution` | error | more than one execution for one idempotency key | +| `idempotency-mismatch` | error | two acknowledged starts of one key returned different ids | +| `null-workflow-id` | error | a start was acknowledged with no id | +| `never-acknowledged` | error | no start of a key succeeded, even after recovery | +| `incomplete` | error | an execution is not COMPLETED after recovery | +| `wrong-output` | error | the output's total or id is not what the steps return | +| `nondeterminism` | error | a replay diverged: a failed continuation or a NonDeterminismException in a worker log | +| `replay-divergence` | error | replays observed different `once`, `random` or `now` values, or values that differ from the output | +| `lost-signal` | error | an acknowledged deposit is missing from the output | +| `duplicate-signal` | error | a deposit was applied twice | +| `phantom-signal` | error | a deposit was applied that nobody sent | +| `signal-reordered` | error | acknowledged deposits from one client were applied out of order | +| `lost-update` | error | acknowledged updates returned the same counter value, or the final counter is below what was acknowledged | +| `phantom-update` | error | the counter is above the number of updates sent | +| `update-order` | error | an update acknowledged before another was sent returned the larger counter value: updates are not applied in one real-time order | +| `query-not-prefix` | error | a query answer is not a prefix of the execution's final deposits | +| `query-went-back` | error | one client's later answer is shorter than its earlier one | +| `query-final-mismatch` | error | a query after the execution ended differs from its output | +| `query-mutated` | error | the `deposits` query's attempt to write state reached the execution | +| `task-never-executed` | error | a completed execution has a step with no successful attempt in any worker ledger | +| `task-output-mismatch` | error | the server recorded a step output that no step returns | +| `indefinite-start-took-effect` | info | a start that failed or timed out created the execution anyway; the retry with the same key found it | +| `indefinite-signal-applied`, `indefinite-signal-dropped` | info | what happened to signals whose outcome the client did not know | +| `duplicate-task-execution` | info | a step succeeded more than once (at-least-once task execution) | +| `concurrent-task-execution` | info | two attempts of one step overlapped in time | +| `continuation-retried` | info | a continuation was offered more than once (`attempts > 1` on its marker), or its completion was deferred: a failover or a re-run. A redelivery to a second worker after the first died runs the same offer and does not raise `attempts` | +| `query-lag` | info | a query missed deposits acknowledged before it was sent but not yet applied | +| `continuation-stalled` | info | a continuation took more than 20 s from queued to applied (`appliedAt - queuedAt` on its marker); the stats give continuation latency percentiles | + +`CheckerTest` plants each error in a synthetic run and asserts that exactly that check fires. + +## Mutant runs + +A mutant is a deliberate bug that the bench must catch: a mutant run must exit 1, failing a check +(`lost-signal`, `duplicate-signal`, `incomplete`, ...) or an independent check. The bugs are not in +the shipped server or SDK. Each is a patch in `mutants/`: + +| Directory | Applies to | Mutants | +|---|---|---| +| `mutants/server/` | the server repository | `no-completion-deferral`, `no-variable-fencing`, `ignore-epoch`, `join-ignores-lanes`, `workflow-saved-last`, `no-claim-fence`, `destructive-pull`, `no-stale-write-guard`, `terminate-on-storage-errors` | +| `mutants/sdk/` | this repository | `no-message-dedupe`, `drop-some-signals`, `no-reply-prune` | + +Apply a patch to a scratch copy, build it, and bench the copy. For a server mutant: + +```bash +git -C /path/to/conductor worktree add /tmp/conductor-mutant +git -C /tmp/conductor-mutant apply "$PWD/native-examples/mutants/server/ignore-epoch.patch" +(cd /tmp/conductor-mutant && ./gradlew :conductor-server:bootJar -x test) +# BENCH_SERVER_SCRIPT runs /tmp/conductor-mutant/server/build/libs/conductor-server-*-boot.jar +BENCH_SERVER_SCRIPT=/path/to/run-mutant-server.sh ./native-examples/bench.sh run # must exit 1 +git -C /path/to/conductor worktree remove /tmp/conductor-mutant +``` + +For an SDK mutant, apply the patch to a worktree of this repository and run the bench from there +(`./gradlew :native-examples:installDist`, then `./native-examples/bench.sh run`), against an +unpatched server. A worktree starts from the last commit, so commit the code under test first. + +## Independent checks + +`independent/check.sh ` checks a run with two tools that share no code with this bench, +so a bug in the bench's checker cannot hide a failure from them: + +| Tool | What it is given | Property | +|---|---|---| +| Elle (Jepsen, `elle:elle:0.2.8`) | each deposit as `[:append N]`, each query answer as `[:r [...]]`; a client that saw an indefinite result is retired, as Jepsen does | **serializable**: one order of appends explains every read; no failed append is read, nothing duplicated, no contradictory orders. **strict serializable over the signals and the queries made after every execution ended**: by then everything acknowledged is applied, so a lost signal is a real-time violation | +| Porcupine 1.3.1 | each `bump` update as a fetch-and-increment returning the new value (an indefinite one may or may not have happened), each execution's final count as a read at the end | **linearizable**: one order consistent with real time in which every returned value is the counter's value | + +Elle also reports strict serializability over all queries. It fails by design: a query reads +applied state, so it can miss a signal acknowledged just before it. + +```bash +native-examples/independent/check.sh native-examples/build/durability/ +``` + +Elle runs from its own small Gradle project (`independent/elle`, pulling Elle from Clojars); +Porcupine from a Go module (`independent/porcupine`). + +Both were shown to reject bad histories: Elle flags a query answer with a duplicated element +(`:duplicate-elements`, `:incompatible-order`) and, on the run that lost signals to a stale pull, +fails the final-reads check on the same lost deposit this bench's checker reported; Porcupine +rejects a history in which two updates return the same value. + +## Update flood + +`durability.UpdateFlood` sends many concurrent updates and queries to one execution and checks +that the returned counter values are exactly 1..N (each update applied once, in one order), that +the stored update replies stay within their 500-reply limit, and that the execution still +completes. + +```bash +CONDUCTOR_SERVER_URL=http://127.0.0.1:8100/api \ +java -cp "native-examples/build/install/native-examples/lib/*" durability.UpdateFlood 1000 20 +``` + +Against the three-server cluster: 1000 updates from 20 threads in 40 s, values exactly 1..1000, +79 queries answered meanwhile, replies at the 500 cap. + +## Output + +The run directory holds `config.json`, `history.jsonl`, `ledger/*.jsonl`, `final.json`, +`report.json`, worker logs, and the server start logs. `final.json` summarizes every execution +with its `nativeState` (bootstrap and handler markers, replies, seen ids) and, per task, +its `continuation` marker next to the usual fields. The report prints a table of every check with +its count, statistics (operations by outcome, faults injected, execution statuses, duration +percentiles, step attempts, continuations), and the first 40 errors. + +## What it found + +Each row is a problem a run exposed, and the fix. All are fixed on the `design/native-workflows` +branches of the server and this SDK. + +| Run | Finding | Fix | +|---|---|---| +| no faults | a JOIN completed while a lane's last continuation still had tasks to append; the execution failed | a completed continuation ends its lane only after it was applied and appended nothing | +| no faults | an update sent to an execution that then failed waited three minutes for a reply | the client stops waiting when the execution is terminal | +| all faults | 39 acknowledged signals lost: a lost poll response stalled the handler lane, the execution completed, and its queue was deleted | completion is deferred while messages are queued or a handler runs; discarded messages are logged and counted; continuation timeout 30 s instead of 120 s (an hour in dev mode) | +| heavy pauses and partitions | signals applied twice, and one update applied twice, after the client re-sent a message whose first send had succeeded | client-chosen message ids, de-duplicated by the handler lane | +| heavy pauses and partitions | an execution failed when a JOIN read a refused, about-to-be-retried continuation | live-target JOINs wait until the branch's continuation marker is applied and ended the lane | +| worker and server kills | signals lost: a continuation's stale copy of the variables overwrote a handler's write | completions apply only the variables they changed (`resumedWith`), and a conflicting completion runs again on the current values | +| server kills | executions failed after a deferral: the loop that drove the handler lane read the set-aside attempt | a deferred completion puts the marker back to runnable with the reason; nothing is set aside | +| server kills | an execution stuck forever: the server died mid-apply after saving the continuation as applied but before saving the definition with its fragment | the workflow row is saved before the task that carries the marker when a continuation is applied | +| chaos script | a start failed with a retryable server error right after a restart, and the client gave up | starts with an idempotency key retry server errors for up to two minutes | +| server pauses | an execution failed as diverged: a worker replayed a completion the server had saved but not yet applied, and expected tasks that did not exist yet | the SDK replays only `APPLIED` continuation markers | +| chaos script, protocol 2, with per-worker queues (since removed) | a worker was killed right after its continuation was queued to its own domain queue; the sweeper had postponed the workflow's decide by an hour on the strength of its in-progress tasks, so nothing re-routed the wake-up and the execution waited | `WorkflowExecutorOps.decide` caps the postpone at the normal workflow offset (30 s) while a continuation marker is `RUNNABLE`, so `repairAndWake` re-pushes the wake-up to a live queue on the next decide | + +The bench had a bug of its own. After a server kill it could start the server twice: its health +wait saw no process on the port while the new server booted, and started another. The instance +that lost the race for the port never exited. It kept running sweepers and system-task workers +against the shared database with no HTTP endpoint. Runs before the fix therefore had several +headless servers on one database. That load also slowed restarts to two minutes. The bench now +tracks the server process it started and never starts a second while it boots. + +The earliest finding came from the kitchensink, before the bench existed. Concurrent pulls and +pushes on SQLite failed with SQLITE_BUSY_SNAPSHOT, and the failed pull stopped the handler lane. + +## Last runs + +Both ran on the final builds, with one server process, and passed every check. + +| Seed | Faults injected | Executions | Signals | Updates | Result | +|---|---|---|---|---|---| +| 2027 | 4 server kills, 4 server pauses, 3 worker pauses | 40 | 544 | 113 | valid | +| 2026 | 5 worker kills, 1 server kill, 2 server pauses, 3 worker pauses | 40 | 895 | 90 | valid | + +In every run, some steps succeeded more than once and some continuations were retried. +At-least-once task execution allows both. Continuations that took over 20 s were all ones caught +by a pause, a partition or a server restart. + +One failure seen once is not explained. An execution failed with "Error scheduling tasks": an +exception while creating or starting newly scheduled tasks terminates the execution. Its server +log was overwritten by a restart before it could be read, and the failure did not recur in later +runs with logs kept. A transient database error during task creation is the likely trigger. If +so, Conductor terminating an execution on a transient error while scheduling is worth changing. + +## Cluster mode + +With `BENCH_CLUSTER=8101,8102,8103` the bench runs against several Conductor servers sharing one +Postgres database (database, queues, index and the execution lock, `workflow-execution-lock.type=postgres`). +The workers connect through a load-balancing proxy across all servers, which the `partition` +fault cuts. Each server reaches the database through its own proxy, so `db-partition` isolates +one server from the database while the others keep running. Clients use their own balancer and +are never partitioned. Four more faults apply: + +| Fault | How | +|---|---| +| `db-pause` | `docker pause` the database container for 5 to 25 s | +| `db-kill` | `docker kill` the database (SIGKILL), then start it again; Postgres recovers from its WAL | +| `db-partition` | reset and hold one server's database connections for 5 to 30 s | +| `cluster-kill` | SIGKILL every server, then start them one at a time | + +`BENCH_NEMESES=2` or `3` runs that many fault injectors at once, so faults overlap; each fault +holds the process it acts on, so two never act on the same server or worker at once. + +The server script receives the HTTP port and the database port. The one used here: + +```bash +java -jar conductor-server-boot.jar --server.port="$1" \ + --conductor.db.type=postgres --conductor.queue.type=postgres \ + --conductor.indexing.enabled=true --conductor.indexing.type=postgres \ + --conductor.workflow-execution-lock.type=postgres \ + --spring.datasource.url="jdbc:postgresql://127.0.0.1:$2/conductor" \ + --conductor.workflow-message-queue.enabled=true +``` + +### Cluster findings + +| Run | Finding | Fix | +|---|---|---| +| no faults | two of three workers crashed at startup: concurrent registration of the same definitions raced in Postgres and failed on the primary key | atomic `INSERT ... ON CONFLICT DO UPDATE` for task and workflow definitions; the SDK retries registration | +| overlapping faults | a handler lane stalled for an hour: the server running its message pull died, and the executor had reserved the pull's queue message for the hour-long default response timeout | messages are claimed, not popped, so a re-run returns the same ones: the handler lane's poll claims them under `handlers#` with a 30 s lease; a JSON workflow's `PULL_WORKFLOW_MESSAGES` claims under its reference name and, like JOIN, declares itself safe to re-run for a one-minute reservation | +| overlapping faults | a database kill failed a handler loop: scheduling the next DO_WHILE iteration hit a closed connection, and the loop failed itself and the workflow | storage outages (lost connection, rolled-back transaction, database shutdown, HikariCP's stateless "Connection is closed") abort the decide for a retry instead of terminating; DO_WHILE rethrows | + +| three overlapping nemeses, with queries | the close signal and three deposits lost: a completed pull ran again after a pause, claimed the newest messages under its old name and overwrote its record; the current pull deleted them as delivered | claims fenced by an ordinal (the handler run number `n`; a loop iteration for a JSON workflow's pull); the executor does not save over a task another run completed | + +Also fixed after reading the code against Jepsen's Orkes findings, without the bench hitting them: +starts queue the workflow before writing it (abandoned workflows), starts never delete a workflow +they may have written (lost workflows), and the sweeper re-reads a task before re-queueing it +(concurrent execution of a task a worker had just polled). + +### Cluster runs on the final builds + +| Seed | Nemeses | Faults injected | Executions | Signals | Updates | Result | +|---|---|---|---|---|---|---| +| 4 | 2 | 3 cluster kills, 5 db kills, 3 db pauses, 1 db partition, 1 partition, 3 server pauses, 3 worker kills, 2 worker pauses | 50 | 877 | 85 | valid | +| 5 | 2 | 5 cluster kills, 1 db kill, 1 db pause, 2 db partitions, 4 partitions, 2 server pauses, 3 worker kills, 4 worker pauses | 50 | 945 | 54 | valid | +| 6 | 3 | 4 cluster kills, 1 db kill, 1 db pause, 3 partitions, 3 server kills, 2 server pauses, 1 worker kill | 50 | 1105 | 316 | valid | + +With queries and the update-order check, on the final builds: + +| Seed | Nemeses | Faults injected | Signals | Updates | Queries | Result | +|---|---|---|---|---|---|---| +| 8 | 3 | 2 cluster kills, 1 db kill, 3 db pauses, 3 db partitions, 4 partitions, 4 server kills, 5 server pauses, 3 worker kills, 3 worker pauses | 971 | 118 | 1440 | valid | +| 9 | 3 | 2 cluster kills, 2 db kills, 1 db pause, 4 db partitions, 1 partition, 1 server kill, 3 server pauses, 1 worker kill, 2 worker pauses | 1101 | 480 | 1499 | valid | + +Between 20 and 45 percent of queries missed a signal acknowledged before the query was sent +(`query-lag`): queries read applied state, and under faults the handler lane runs behind. + +Earlier cluster runs with one nemesis (database-heavy, all faults, 40 to 50 executions) also +passed. The kitchensink and the operator checks pass against the cluster through a balancer, with +three worker processes, and a `@Schedule` workflow runs exactly once per tick with three +schedulers. + +## Known limits of the bench + +- Single machine: every process shares one host, so there is no clock skew between nodes and no + real network latency. Partitions are made by proxies, not by the network. +- Redis queues and MySQL are not exercised by the bench (MySQL only by its unit tests). +- Clients are never partitioned from the servers. +- Runs last minutes, not hours, so rare interleavings need many runs. Vary `BENCH_SEED` and run it + in a loop to search longer. diff --git a/native-examples/bench.sh b/native-examples/bench.sh new file mode 100755 index 000000000..9c580b90c --- /dev/null +++ b/native-examples/bench.sh @@ -0,0 +1,25 @@ +#!/bin/bash +# Jepsen-style failure bench for native workflows. See src/main/java/durability/Bench.java for the +# phases, faults and checks, and DURABILITY-BENCH.md for how to read the report. +# +# BENCH_SERVER_PORT port of a server built from the conductor branch (default 8099; never 8080) +# BENCH_SERVER_SCRIPT script that runs that server in the foreground (exec java ...); required +# for the server-kill fault, and to start the server if it is down +# BENCH_CLUSTER cluster mode: server ports, e.g. 8101,8102,8103; the script is then called +# as