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..9436d4bf9 --- /dev/null +++ b/conductor-client-spring-boot4/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowHost.java @@ -0,0 +1,145 @@ +/* + * 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.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} and {@code dev-mode}. Per + * workflow, read from the environment: {@code conductor.workflow..threadCount}, {@code + * pollingInterval}, {@code pollTimeout}, {@code paused} and {@code continuationTimeout}, or {@code + * conductor.workflow.all.*} (see {@link Workers}). + */ +@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.workflows(); + String workerId = environment.getProperty("conductor.workflows.worker-id"); + if (workerId != null) { + w.workerId(workerId); + } + w.settings(environment::getProperty); + 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.close(); + } + } + + @Override + public boolean isRunning() { + return workers != null; + } + + private void host(Workers w, Class type) { + w.workflows(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..a724f4a1b --- /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.workflows()).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).workflows(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).workflows(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()).close()); + verify(workers).close(); + } + + @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/examples/old/src/main/java/com/netflix/conductor/sdk/examples/helloworld/workers/Workers.java b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/SampleTasks.java similarity index 67% rename from examples/old/src/main/java/com/netflix/conductor/sdk/examples/helloworld/workers/Workers.java rename to conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/SampleTasks.java index 6b37fb1a7..27fb1e302 100644 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/helloworld/workers/Workers.java +++ b/conductor-client-spring-boot4/src/test/java/com/netflix/conductor/client/spring/sample/SampleTasks.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 Conductor Authors. + * 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 @@ -10,14 +10,17 @@ * 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.sdk.examples.helloworld.workers; +package com.netflix.conductor.client.spring.sample; + +import org.springframework.stereotype.Component; -import com.netflix.conductor.sdk.workflow.task.InputParam; import com.netflix.conductor.sdk.workflow.task.WorkerTask; -public class Workers { - @WorkerTask("greet") - public String greeting(@InputParam("name") String name) { - return ("Hello " + name); +@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..9436d4bf9 --- /dev/null +++ b/conductor-client-spring/src/main/java/com/netflix/conductor/client/spring/ConductorWorkflowHost.java @@ -0,0 +1,145 @@ +/* + * 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.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} and {@code dev-mode}. Per + * workflow, read from the environment: {@code conductor.workflow..threadCount}, {@code + * pollingInterval}, {@code pollTimeout}, {@code paused} and {@code continuationTimeout}, or {@code + * conductor.workflow.all.*} (see {@link Workers}). + */ +@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.workflows(); + String workerId = environment.getProperty("conductor.workflows.worker-id"); + if (workerId != null) { + w.workerId(workerId); + } + w.settings(environment::getProperty); + 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.close(); + } + } + + @Override + public boolean isRunning() { + return workers != null; + } + + private void host(Workers w, Class type) { + w.workflows(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..a724f4a1b --- /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.workflows()).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).workflows(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).workflows(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()).close()); + verify(workers).close(); + } + + @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/automator/TaskRunner.java b/conductor-client/src/main/java/com/netflix/conductor/client/automator/TaskRunner.java index e8b70f28b..209d03d82 100644 --- a/conductor-client/src/main/java/com/netflix/conductor/client/automator/TaskRunner.java +++ b/conductor-client/src/main/java/com/netflix/conductor/client/automator/TaskRunner.java @@ -14,7 +14,6 @@ import java.io.PrintWriter; import java.io.StringWriter; -import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; @@ -24,7 +23,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.Semaphore; @@ -58,6 +57,7 @@ import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.TaskResult; +import io.orkes.conductor.client.http.ApiException; import io.orkes.conductor.client.http.FatalAuthenticationException; import com.google.common.annotations.VisibleForTesting; @@ -79,9 +79,12 @@ class TaskRunner { private int pollingErrorCount; private String domain; private volatile boolean pollingAndExecuting = true; + /** How many threads are in {@link #pollAndExecute()}; its own lock. */ + private final int[] pollLoops = new int[1]; + /** Set when the poll loop is terminating the JVM: it never ends, and shutdown does not wait for it. */ + private volatile boolean exiting; private final List pollFilters; private final EventDispatcher eventDispatcher; - private final LinkedBlockingQueue tasksTobeExecuted; private final boolean enableUpdateV2; private static final int LEASE_EXTEND_RETRY_COUNT = 3; private static final double LEASE_EXTEND_DURATION_FACTOR = 0.8; @@ -100,6 +103,32 @@ class TaskRunner { List pollFilters, EventDispatcher eventDispatcher, boolean useVirtualThreads) { + this(worker, taskClient, updateRetryCount, taskToDomain, workerNamePrefix, threadCount, taskPollTimeout, + pollFilters, eventDispatcher, useVirtualThreads, false, true, null); + } + + /** + * @param updateV2 complete tasks with update-v2, which hands back this worker's next task to run + * without a poll; also on when the {@code taskUpdateV2} system property or environment + * variable is set + * @param useDomains poll the domain from the properties or {@code taskToDomain}; false polls + * only the shared queue + * @param fixedDomain the one task domain to poll, whatever the properties and {@code + * taskToDomain} say; null to resolve the domain as {@code useDomains} says + */ + TaskRunner(Worker worker, + TaskClient taskClient, + int updateRetryCount, + Map taskToDomain, + String workerNamePrefix, + int threadCount, + int taskPollTimeout, + List pollFilters, + EventDispatcher eventDispatcher, + boolean useVirtualThreads, + boolean updateV2, + boolean useDomains, + String fixedDomain) { this.worker = worker; this.taskClient = taskClient; this.updateRetryCount = updateRetryCount; @@ -109,8 +138,7 @@ class TaskRunner { this.permits = new Semaphore(threadCount); this.pollFilters = pollFilters; this.eventDispatcher = eventDispatcher; - this.tasksTobeExecuted = new LinkedBlockingQueue<>(); - this.enableUpdateV2 = Boolean.parseBoolean(System.getProperty("taskUpdateV2", "false")) || Boolean.parseBoolean(System.getenv("taskUpdateV2")); + this.enableUpdateV2 = updateV2 || Boolean.parseBoolean(System.getProperty("taskUpdateV2", "false")) || Boolean.parseBoolean(System.getenv("taskUpdateV2")); LOGGER.info("taskUpdateV2 is set to {} for {}", this.enableUpdateV2, worker.getTaskDefName()); //1. Is there a worker level override? @@ -123,6 +151,9 @@ class TaskRunner { //3. was it supplied as part of the config? this.domain = taskToDomain.get(taskType); } + if (!useDomains || fixedDomain != null) { + this.domain = fixedDomain; + } int defaultLoggingInterval = 100; int errorInterval = PropertyFactory.getInteger(taskType, Worker.PROP_LOG_INTERVAL, 0); @@ -168,6 +199,20 @@ void setExitAction(Runnable exitAction) { } public void pollAndExecute() { + synchronized (pollLoops) { + pollLoops[0]++; + } + try { + pollUntilStopped(); + } finally { + synchronized (pollLoops) { + pollLoops[0]--; + pollLoops.notifyAll(); + } + } + } + + private void pollUntilStopped() { Stopwatch stopwatch = null; while (pollingAndExecuting) { if (Thread.currentThread().isInterrupted()) { @@ -189,30 +234,10 @@ public void pollAndExecute() { stopwatch = null; } tasks.forEach(task -> { - Future taskFuture; - try { - taskFuture = this.executorService.submit(() -> this.processTask(task)); - } catch (java.util.concurrent.RejectedExecutionException e) { + if (!submit(task)) { LOGGER.error("Task rejected by executor (likely shutting down); dropping task {} of type {}", - task.getTaskId(), taskType, e); + task.getTaskId(), taskType); permits.release(); - return; - } - - if (task.getResponseTimeoutSeconds() > 0 && worker.leaseExtendEnabled()) { - ScheduledFuture existingFuture = leaseExtendMap.remove(task.getTaskId()); - if (existingFuture != null) { - existingFuture.cancel(false); - } - - long delay = Math.round(task.getResponseTimeoutSeconds() * LEASE_EXTEND_DURATION_FACTOR); - ScheduledFuture leaseExtendFuture = leaseExtendExecutorService.scheduleWithFixedDelay( - extendLease(task, taskFuture), - delay, - delay, - TimeUnit.SECONDS - ); - leaseExtendMap.put(task.getTaskId(), leaseExtendFuture); } }); } catch (Throwable t) { @@ -221,10 +246,66 @@ public void pollAndExecute() { } } + /** + * Runs a task on the executor, under a permit the caller holds, with lease extension when the + * worker asks for it. False when the executor refused it: the permit is then the caller's to + * release. + */ + private boolean submit(Task task) { + Future taskFuture; + try { + taskFuture = this.executorService.submit(() -> this.processTask(task)); + } catch (RejectedExecutionException e) { + return false; // shutting down: the caller says what becomes of the task + } + if (task.getResponseTimeoutSeconds() > 0 && worker.leaseExtendEnabled()) { + ScheduledFuture existingFuture = leaseExtendMap.remove(task.getTaskId()); + if (existingFuture != null) { + existingFuture.cancel(false); + } + + long delay = Math.round(task.getResponseTimeoutSeconds() * LEASE_EXTEND_DURATION_FACTOR); + try { + ScheduledFuture leaseExtendFuture = leaseExtendExecutorService.scheduleWithFixedDelay( + extendLease(task, taskFuture), + delay, + delay, + TimeUnit.SECONDS + ); + leaseExtendMap.put(task.getTaskId(), leaseExtendFuture); + } catch (RejectedExecutionException e) { + // shutting down: the task, already submitted, runs without lease extension; a + // throw here would make the caller release the permit the task also releases + LOGGER.debug("No lease extension for task {}: shutting down", task.getTaskId()); + } + } + return true; + } + + /** + * Waits, at most {@code timeout} seconds, for the poll loop to end: its poll in flight returns + * and the tasks it brought are handed to the executor, which must still take them. The server + * has leased those tasks to this worker; refused, they would wait out their response timeout. + */ + private void awaitPollLoop(int timeout) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeout); + synchronized (pollLoops) { + while (pollLoops[0] > 0 && !exiting) { + long millis = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()); + if (millis <= 0) { + LOGGER.warn("The poll loop of {} did not end within {} seconds", taskType, timeout); + return; + } + pollLoops.wait(millis); + } + } + } + public void shutdown(int timeout) { try { pollingAndExecuting = false; - + awaitPollLoop(timeout); + leaseExtendMap.values().forEach(future -> future.cancel(false)); leaseExtendMap.clear(); @@ -297,6 +378,7 @@ private List pollTasksForWorker() { if (hasFatalAuthCause(e)) { LOGGER.error("Fatal authentication failure — terminating JVM"); + exiting = true; // a shutdown hook must not wait for this thread, which waits for the hooks exitAction.run(); } @@ -326,12 +408,6 @@ private List pollTask(int count) { if (count < 1) { return Collections.emptyList(); } - LOGGER.trace("in memory queue size for tasks: {}", tasksTobeExecuted.size()); - List polled = new ArrayList<>(count); - tasksTobeExecuted.drainTo(polled, count); - if(!polled.isEmpty()) { - return polled; - } String workerId = worker.getIdentity(); LOGGER.debug("poll {} in the domain {} with batch size {}", taskType, domain, count); return taskClient.batchPollTasksInDomain( @@ -364,6 +440,34 @@ private static boolean hasFatalAuthCause(Throwable t) { } private Task processTask(Task task) { + boolean handedOn = false; + try { + // the next task update-v2 handed back runs now, on this task's permit, rather than + // waiting for the poll loop, which may be in a long poll or its polling interval + Task next = runTask(task); + while (next != null && !(handedOn = submit(next))) { + // The executor takes nothing new: shutdown began while the update was on its way. + // The server has leased the task to this worker, so it runs here, on this thread, + // which shutdown lets finish; its own result is sent with the update that hands + // nothing back. Left alone, it would wait out its lease. + if (Thread.currentThread().isInterrupted()) { + LOGGER.error("Shutdown is forced; dropping task {} of type {}", next.getTaskId(), taskType); + break; + } + LOGGER.info("Shutting down: task {} of type {}, handed back by the last update, runs before this thread ends", + next.getTaskId(), taskType); + next = runTask(next); + } + } finally { + if (!handedOn) { + permits.release(); + } + } + return task; + } + + /** Runs one task and sends its result; returns the next task update-v2 handed back, or null. */ + private Task runTask(Task task) { eventDispatcher.publish(new TaskExecutionStarted(taskType, task.getTaskId(), worker.getIdentity())); eventDispatcher.publish(new ActiveWorkersChanged(taskType, activeWorkerCount.incrementAndGet())); @@ -373,8 +477,9 @@ private Task processTask(Task task) { LOGGER.trace("Executing task: {} of type: {} in worker: {} at {}", task.getTaskId(), taskType, worker.getClass().getSimpleName(), worker.getIdentity()); LOGGER.trace("task {} is getting executed after {} ms of getting polled", task.getTaskId(), (System.currentTimeMillis() - task.getStartTime())); Stopwatch stopwatch = Stopwatch.createStarted(); + Task next = null; try { - executeTask(worker, task); + next = executeTask(worker, task); stopwatch.stop(); long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS); LOGGER.trace( @@ -384,19 +489,19 @@ private Task processTask(Task task) { } catch (Throwable t) { task.setStatus(Task.Status.FAILED); TaskResult result = new TaskResult(task); - handleException(t, result, worker, task); + next = handleException(t, result, worker, task); } finally { cancelLeaseExtension(task.getTaskId()); - permits.release(); eventDispatcher.publish(new ActiveWorkersChanged(taskType, activeWorkerCount.decrementAndGet())); } - return task; + return next; } - private void executeTask(Worker worker, Task task) { + /** Runs the task and sends its result; returns the next task update-v2 handed back, or null. */ + private Task executeTask(Worker worker, Task task) { if (task == null || task.getTaskDefName().isEmpty()) { LOGGER.warn("Empty task {}", worker.getTaskDefName()); - return; + return null; } // Calculate inbound network latency @@ -442,7 +547,7 @@ private void executeTask(Worker worker, Task task) { task.setStatus(Task.Status.FAILED); result = new TaskResult(task); } - handleException(e, result, worker, task); + return handleException(e, result, worker, task); // sends it: not again below } LOGGER.trace( @@ -451,11 +556,13 @@ private void executeTask(Worker worker, Task task) { worker.getClass().getSimpleName(), worker.getIdentity(), result.getStatus()); - updateTaskResult(updateRetryCount, task, result, worker); + return updateTaskResult(updateRetryCount, task, result, worker); } - private void updateTaskResult(int count, Task task, TaskResult result, Worker worker) { + /** Sends the result; returns the next task update-v2 handed back, or null. */ + private Task updateTaskResult(int count, Task task, TaskResult result, Worker worker) { Stopwatch updateStopwatch = Stopwatch.createStarted(); + Task next = null; try { // upload if necessary Optional optionalExternalStorageLocation = @@ -475,14 +582,15 @@ private void updateTaskResult(int count, Task task, TaskResult result, Worker wo result.getExecutionMetadata().setClientSendTime(clientSendTime); LOGGER.debug("Task {} outbound send time: {}", task.getTaskId(), clientSendTime); - if(enableUpdateV2) { + if (enableUpdateV2 && takesMoreWork()) { Task nextTask = retryOperation( (TaskResult taskResult) -> taskClient.updateTaskV2(taskResult, taskType), count, result, "updateTaskV2"); if (nextTask != null) { - tasksTobeExecuted.add(nextTask); + nextTask.getExecutionMetadata().setClientReceiveTime(System.currentTimeMillis()); + next = nextTask; } } else { retryOperation( @@ -520,6 +628,17 @@ private void updateTaskResult(int count, Task task, TaskResult result, Worker wo result.toString(), task.getTaskDefName(), worker.getIdentity()), e); } + return next; + } + + /** + * Whether this runner takes another task now: it is running and its worker is not paused. Only + * then is a result sent with update-v2, which hands back the next task: a task handed to a + * paused worker would run despite the pause, and one handed over during shutdown could not + * run, and would wait out its response timeout. + */ + private boolean takesMoreWork() { + return pollingAndExecuting && !worker.paused(); } private Optional upload(TaskResult result, String taskType) { @@ -539,6 +658,9 @@ private R retryOperation(Function operation, int count, T input, St try { return operation.apply(input); } catch (Exception e) { + if (refused(e)) { + throw e; // the same request is refused again: retrying cannot help + } LOGGER.error("Error executing {}", opName, e); index++; Uninterruptibles.sleepUninterruptibly(500L * (count + 1), TimeUnit.MILLISECONDS); @@ -547,14 +669,21 @@ private R retryOperation(Function operation, int count, T input, St throw new RuntimeException("Exhausted retries performing " + opName); } - private void handleException(Throwable t, TaskResult result, Worker worker, Task task) { + /** A client error other than a timeout (408) or throttling (429). */ + private static boolean refused(Exception e) { + return e instanceof ApiException api + && api.getStatusCode() >= 400 && api.getStatusCode() < 500 + && api.getStatusCode() != 408 && api.getStatusCode() != 429; + } + + private Task handleException(Throwable t, TaskResult result, Worker worker, Task task) { LOGGER.error(String.format("Error while executing task %s", task.toString()), t); result.setStatus(TaskResult.Status.FAILED); result.setReasonForIncompletion("Error while executing the task: " + t); StringWriter stringWriter = new StringWriter(); t.printStackTrace(new PrintWriter(stringWriter)); result.log(stringWriter.toString()); - updateTaskResult(updateRetryCount, task, result, worker); + return updateTaskResult(updateRetryCount, task, result, worker); } private Runnable extendLease(Task task, Future taskCompletableFuture) { diff --git a/conductor-client/src/main/java/com/netflix/conductor/client/automator/TaskRunnerConfigurer.java b/conductor-client/src/main/java/com/netflix/conductor/client/automator/TaskRunnerConfigurer.java index 030246917..913d73623 100644 --- a/conductor-client/src/main/java/com/netflix/conductor/client/automator/TaskRunnerConfigurer.java +++ b/conductor-client/src/main/java/com/netflix/conductor/client/automator/TaskRunnerConfigurer.java @@ -55,6 +55,9 @@ public class TaskRunnerConfigurer { private final EventDispatcher eventDispatcher; private final MetricsCollector metricsCollector; private final boolean useVirtualThreads; + private final boolean taskUpdateV2; + private final boolean useDomains; + private final String fixedDomain; /** * @see TaskRunnerConfigurer.Builder @@ -77,6 +80,9 @@ private TaskRunnerConfigurer(TaskRunnerConfigurer.Builder builder) { this.eventDispatcher = builder.eventDispatcher; this.metricsCollector = builder.metricsCollector; this.useVirtualThreads = builder.useVirtualThreads; + this.taskUpdateV2 = builder.taskUpdateV2; + this.useDomains = builder.useDomains; + this.fixedDomain = builder.fixedDomain; builder.workers.forEach(this.workers::add); taskRunners = new LinkedList<>(); } @@ -179,7 +185,10 @@ private void startWorker(Worker worker) { taskPollTimeout, pollFilters, eventDispatcher, - useVirtualThreads); + useVirtualThreads, + taskUpdateV2, + useDomains, + fixedDomain); // startWorker(worker) is executed by several threads. // taskRunners.add(taskRunner) without synchronization could lead to a race condition and unpredictable behavior, // including potential null values being inserted or corrupted state. @@ -212,6 +221,9 @@ public static class Builder { private final List pollFilters = new LinkedList<>(); private final EventDispatcher eventDispatcher = new EventDispatcher<>(); private boolean useVirtualThreads; + private boolean taskUpdateV2; + private boolean useDomains = true; + private String fixedDomain; /** * Returns the event dispatcher used by this builder, allowing direct @@ -383,5 +395,35 @@ public Builder withUseVirtualThreads(boolean useVirtualThreads) { return this; } + /** + * Completes tasks with update-v2, which hands back the worker's next task to run without + * another poll. Also on for every configurer when the {@code taskUpdateV2} system property + * or environment variable is set. + */ + public Builder withTaskUpdateV2(boolean taskUpdateV2) { + this.taskUpdateV2 = taskUpdateV2; + return this; + } + + /** + * Whether workers poll a task domain: from {@code conductor.worker..domain}, then + * {@code conductor.worker.all.domain}, then {@link #withTaskToDomain}. On by default; off, + * every worker polls the shared queue of its task type. + */ + public Builder withDomains(boolean useDomains) { + this.useDomains = useDomains; + return this; + } + + /** + * The one task domain every worker polls, whatever {@code conductor.worker..domain}, + * {@code conductor.worker.all.domain} and {@link #withTaskToDomain} say. For a queue that + * belongs to this process alone. + */ + public Builder withFixedDomain(String domain) { + this.fixedDomain = domain; + return this; + } + } } 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..5d4addd91 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 @@ -53,6 +53,8 @@ import com.netflix.conductor.client.metrics.PayloadKind; import com.netflix.conductor.common.config.ObjectMapperProvider; +import io.orkes.conductor.client.ApiClient; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JavaType; @@ -154,6 +156,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 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..48c800e86 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 @@ -22,6 +22,7 @@ import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.common.run.tasks.TypedTask; +import com.fasterxml.jackson.annotation.JsonInclude; import lombok.*; @Data @@ -186,6 +187,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. + */ + @JsonInclude(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 +316,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..939b09e34 --- /dev/null +++ b/conductor-client/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskContinuation.java @@ -0,0 +1,196 @@ +/* + * 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; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; + +/** + * 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: whether + * the continuation is leased to a worker, how many times it was offered again, and, once applied, + * what it produced, which a worker replays from. Which continuation it is (the lane of the code and + * its number) is the task's entry's {@code metadata}: {@code lane} and {@code continuation}. + * Whether it can run follows from the task: once the task has ended and the decider has evaluated + * it. 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 { + + /** + * Leased to a worker: offered, and not yet applied or handed back. At most one continuation of + * an execution is leased at a time. + */ + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private boolean leased; + + /** + * How many times this continuation was offered again: 0 on its first offer, one more after each + * attempt that did not apply (deferred, retried, rerun), as a task's retry count. A completion + * names the count it was offered at, so one from an earlier attempt never applies. + */ + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int retryCount; + + /** + * When it applied, 0 until then: later than every earlier apply in the run, the order replay + * follows. + */ + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private long endTime; + + /** Whether it ended its lane: the code returned or raised there. */ + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private boolean done; + + /** The values the code recorded while it ran ({@code once}, {@code now}, {@code random}). */ + @JsonInclude(JsonInclude.Include.NON_EMPTY) + private Map recorded = new HashMap<>(); + + /** The workflow variables it started from, which a replay restores before it. */ + @JsonInclude(JsonInclude.Include.NON_EMPTY) + private Map resumedWith = new HashMap<>(); + + /** + * The handler lane's run number, from 1; 0 on every other marker, whose number is its entry's. + * Every handler run has the same message id, so this tells a run from the one before it. + */ + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int n; + + /** + * On the marker a poll hands out, never stored: the execution's stamp, which names the + * completion that applied last. A worker that kept the code parked in memory continues from + * there only when this is still the stamp it sent. + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + private String stamp; + + /** + * On the marker a poll hands out, never stored: the workflow's variables as the continuation + * starts. A server that sends them pins executions to the worker that holds them in memory. + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + private Map variables; + + public TaskContinuation() {} + + /** A new marker of a handler run. */ + public static TaskContinuation handlerRun(int n) { + TaskContinuation marker = new TaskContinuation(); + marker.n = n; + return marker; + } + + /** + * A fresh marker for the same continuation, as a rerun task or a restarted run carries: another + * attempt, so its retry count goes up and a completion of an offer made before the reset can + * never match it. + */ + public TaskContinuation reset() { + TaskContinuation fresh = new TaskContinuation(); + fresh.n = n; + fresh.retryCount = retryCount + 1; + return fresh; + } + + @JsonIgnore // derived from endTime, not stored + public boolean isApplied() { + return endTime > 0; + } + + public boolean isLeased() { + return leased; + } + + public void setLeased(boolean leased) { + this.leased = leased; + } + + public int getRetryCount() { + return retryCount; + } + + public void setRetryCount(int retryCount) { + this.retryCount = retryCount; + } + + public long getEndTime() { + return endTime; + } + + public void setEndTime(long endTime) { + this.endTime = endTime; + } + + public boolean isDone() { + return done; + } + + public void setDone(boolean done) { + this.done = done; + } + + 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 int getN() { + return n; + } + + public void setN(int n) { + this.n = n; + } + + public String getStamp() { + return stamp; + } + + public void setStamp(String stamp) { + this.stamp = stamp; + } + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + + @Override + public String toString() { + return "TaskContinuation{" + + (n > 0 ? "run " + n + " " : "") + + (leased ? "leased" : endTime > 0 ? "applied" : "not applied") + + (retryCount > 0 ? " retry " + retryCount : "") + + "}"; + } +} diff --git a/conductor-client/src/main/java/com/netflix/conductor/common/metadata/workflow/WorkflowTask.java b/conductor-client/src/main/java/com/netflix/conductor/common/metadata/workflow/WorkflowTask.java index a530b43d5..89497cff0 100644 --- a/conductor-client/src/main/java/com/netflix/conductor/common/metadata/workflow/WorkflowTask.java +++ b/conductor-client/src/main/java/com/netflix/conductor/common/metadata/workflow/WorkflowTask.java @@ -24,6 +24,7 @@ import com.netflix.conductor.common.metadata.tasks.TaskDef; import com.netflix.conductor.common.metadata.tasks.TaskType; +import com.fasterxml.jackson.annotation.JsonInclude; import lombok.*; @Data @@ -137,6 +138,14 @@ public static class WorkflowTaskList { private boolean permissive; + /** + * Editor and integration metadata associated with this task, as on the server. Native + * workflows name here the lane of the code an entry belongs to and, on an entry the code paused + * on, the continuation that runs when its task finishes. + */ + @JsonInclude(JsonInclude.Include.NON_EMPTY) + private Map metadata = new HashMap<>(); + // Adding to support Backward compatibility @Deprecated public void setWorkflowTaskType(TaskType type) { 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..3c44bf7cf --- /dev/null +++ b/conductor-client/src/main/java/com/netflix/conductor/common/run/NativeState.java @@ -0,0 +1,89 @@ +/* + * 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.HashMap; +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. The code type and the continuation timeout are the + * definition's {@code metadata.native}, which the execution carries. + */ +public class NativeState { + + /** + * The main lane's first continuation, which runs before any task exists. Always {@code main} + * #1, so neither is stored. + */ + private TaskContinuation bootstrap; + + /** + * The handler lane: signal and update handlers schedule no tasks. Null without handlers. Its + * lane is always {@code handlers}, so it is not stored; its number counts its runs. + */ + private TaskContinuation handlers; + private Map replies = new HashMap<>(); + + /** + * The task domain of the worker that keeps this execution's code parked in memory between + * continuations; null when no worker does. + */ + private String pinnedTo; + + /** Names the completion that applied last, as its worker chose. */ + private String stamp; + + 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 String getPinnedTo() { + return pinnedTo; + } + + public void setPinnedTo(String pinnedTo) { + this.pinnedTo = pinnedTo; + } + + public String getStamp() { + return stamp; + } + + public void setStamp(String stamp) { + this.stamp = stamp; + } +} 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..b9b7dc93c 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 @@ -22,6 +22,7 @@ import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.run.tasks.TypedTask; +import com.fasterxml.jackson.annotation.JsonInclude; import lombok.*; @Data @@ -105,6 +106,33 @@ public boolean isSuccessful() { private String idempotencyKey; + /** The engine's state of a native (code-first) workflow execution; null for other workflows. */ + @JsonInclude(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. + */ + @JsonInclude(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..243e13e01 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 @@ -21,6 +21,8 @@ import java.lang.reflect.Type; import java.util.*; +import org.conductoross.conductor.sdk.internal.Json; + import com.netflix.conductor.client.worker.Worker; import com.netflix.conductor.common.config.ObjectMapperProvider; import com.netflix.conductor.common.metadata.tasks.Task; @@ -115,7 +117,9 @@ private Object[] getInvocationParameters(Task task) { if (parameterTypes.length == 1 && parameterTypes[0].equals(Task.class)) { return new Object[]{task}; - } else if (parameterTypes.length == 1 && parameterTypes[0].equals(Map.class)) { + } else if (parameterTypes.length == 1 && parameterTypes[0].equals(Map.class) && !calledByNativeWorkflow(task)) { + // the whole input; a native workflow sends the map under its parameter's name, as it + // sends every argument, and it is bound from there like any other parameter return new Object[]{task.getInputData()}; } @@ -134,6 +138,16 @@ 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()) + && (calledByNativeWorkflow(task) || !bindsWholeInput(parameters[i]))) { + // Compiled with -parameters and the input has a key with the parameter's name: + // bind that value. A native workflow sends every argument under its parameter's + // name. From any other workflow only a parameter that could not hold the whole + // input (a string, a number, a list) binds this way: an object parameter keeps + // binding the whole input, as it always has, also when one of the object's fields + // has the parameter's name. + values[i] = convertNamed(task.getInputData().get(parameters[i].getName()), parameters[i]); } else { values[i] = convertValue(task.getInputData(), parameterTypes[i]); } @@ -189,6 +203,24 @@ private Object getInputValue( } } + /** Whether a native workflow scheduled the task: its entry names the lane of the code that called it. */ + private static boolean calledByNativeWorkflow(Task task) { + WorkflowTask entry = task.getWorkflowTask(); + return entry != null && entry.getMetadata() != null && entry.getMetadata().get("lane") != null; + } + + /** Whether the whole input, a JSON object, could be bound to this parameter. */ + private static boolean bindsWholeInput(Parameter parameter) { + return !Json.isWrapped(parameter.getParameterizedType()); + } + + 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 +289,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/executor/task/AnnotatedWorkerExecutor.java b/conductor-client/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/AnnotatedWorkerExecutor.java index e2ed6d107..bce608b8a 100644 --- a/conductor-client/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/AnnotatedWorkerExecutor.java +++ b/conductor-client/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/AnnotatedWorkerExecutor.java @@ -179,13 +179,21 @@ public void addBean(Object bean) { } } - private void addMethod(WorkerTask annotation, Method method, Object bean) { + /** + * Adds one {@code @WorkerTask} method, configured as {@link #addBean} configures each public + * one: thread count, polling interval, poll timeout, domain and poller count from the {@link + * WorkerConfiguration}, else from the annotation. A non-public method must be accessible. + */ + public void addMethod(WorkerTask annotation, Method method, Object bean) { String name = annotation.value(); int threadCount = workerConfiguration.getThreadCount(name); if (threadCount == 0) { threadCount = annotation.threadCount(); } + if (threadCount < 1) { + threadCount = workerConfiguration.getDefaultThreadCount(); + } workerToThreadCount.put(name, threadCount); int pollingInterval = workerConfiguration.getPollingInterval(name); diff --git a/conductor-client/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/WorkerConfiguration.java b/conductor-client/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/WorkerConfiguration.java index d4946fb22..60c0518a8 100644 --- a/conductor-client/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/WorkerConfiguration.java +++ b/conductor-client/src/main/java/com/netflix/conductor/sdk/workflow/executor/task/WorkerConfiguration.java @@ -30,6 +30,11 @@ public int getThreadCount(String taskName) { return 0; } + /** Threads for a task whose configuration and {@code @WorkerTask} set none. */ + public int getDefaultThreadCount() { + return 1; + } + public String getDomain(String taskName) { return null; } 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..84df1e7e9 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 @@ -23,8 +23,12 @@ public @interface WorkerTask { String value(); - // No. of threads to use for executing the task - int threadCount() default 1; + /** + * Threads that execute the task at once. 0, the default, leaves it to the executor's {@code + * WorkerConfiguration.getDefaultThreadCount()}: 1 for {@code AnnotatedWorkerExecutor} and + * Spring, 8 for a native workflow host. + */ + int threadCount() default 0; int pollingInterval() default 100; @@ -37,4 +41,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..a598bab1d --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/AgentCall.java @@ -0,0 +1,178 @@ +/* + * 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; + +/** + * A conversation with an AI agent: a remote agent over the A2A protocol, or a Conductor agent by + * name. Each {@link #ask} is an AGENT task: the server sends the message, waits for the agent, and + * records the reply; the workflow is suspended meanwhile, holding no thread. + * + *

{@code
+ * AgentCall support = agent("support").remote(url);
+ * AgentResult reply = support.ask("Refund ticket T-1");
+ * if (reply.needsInput()) {
+ *     reply = support.ask(answer);          // answers the agent's question, in the same agent task
+ * }
+ * support.ask("Anything else?");             // the next turn of the same conversation
+ * }
+ * + *

Asking again continues the conversation: the next message carries the conversation's id, and, + * when the agent asked for input, the id of the agent task it answers. A new {@code agent(..)} + * starts a new conversation. Use one conversation from one lane at a time. + * + *

An agent may work for hours, and the workflow waits as long as it takes: the server polls the + * agent's task every {@link #pollInterval} (5 seconds by default), or, with {@link + * #pushNotifications}, waits for the agent to call back, for at most {@link #maxDuration} (24 + * hours by default). To keep working meanwhile, ask inside {@code async(() -> ...)}, as with any + * other call, and {@code join} its Future when the answer is needed. + */ +public final class AgentCall { + + /** + * What the agent returned. {@code state} is the agent task's state: {@code completed}, {@code + * input-required} or {@code auth-required} when the agent waits for an answer, or {@code + * message} for a direct reply with no agent task. {@code artifacts} are what the agent + * produced, each with its {@code parts} (text, or {@code data} for structured output); {@code + * text} joins their text parts. + */ + public record AgentResult(String text, String state, List> artifacts, String taskId, String contextId) { + + /** Whether the agent is waiting for an answer: the conversation's next {@link #ask} sends it. */ + public boolean needsInput() { + return "input-required".equals(state) || "auth-required".equals(state); + } + } + + private final String ref; + /** What every message of the conversation carries: the agent, headers and how to wait. */ + private final Map input = new LinkedHashMap<>(); + private int retries = 3; + private Duration retryDelay = Duration.ofSeconds(1); + private String contextId; + /** The agent task waiting for an answer, which the next message answers. */ + private String waitingTaskId; + + AgentCall(String ref) { + this.ref = 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) { + input.put("agentType", "a2a"); + input.put("agentUrl", agentUrl); + return this; + } + + /** A Conductor agent by name and version. */ + public AgentCall conductor(String agentName, int version) { + input.put("agentType", "conductor"); + input.put("agentName", agentName); + input.put("agentVersion", version); + return this; + } + + public AgentCall header(String name, String value) { + @SuppressWarnings("unchecked") + Map headers = + (Map) input.computeIfAbsent("headers", k -> new LinkedHashMap()); + headers.put(name, value); + return this; + } + + /** Continues a conversation started elsewhere, such as in an earlier execution. */ + public AgentCall context(String contextId) { + this.contextId = contextId; + return this; + } + + /** + * Longest time to wait for a long-running agent task, 24 hours by default; past it the remote + * task is cancelled and the call fails. + */ + public AgentCall maxDuration(Duration duration) { + input.put("maxDurationSeconds", (int) Math.max(1, duration.toSeconds())); + return this; + } + + /** How often the server asks a long-running agent task how it is doing; 5 seconds by default. */ + public AgentCall pollInterval(Duration interval) { + input.put("pollIntervalSeconds", (int) Math.max(1, interval.toSeconds())); + return this; + } + + /** + * Asks the agent to call the server back when its task changes, instead of being polled; the + * server still polls rarely ({@code backstop}), in case a callback is lost. Needs {@code + * conductor.a2a.callback.url} on the server, the URL the agent reaches it at; without it the + * server polls as usual. Give the agent's JSON-RPC endpoint to {@link #remote}, not its card + * URL: on a callback the server reads the agent's task from that URL as given. + */ + public AgentCall pushNotifications(Duration backstop) { + input.put("pushNotification", true); + input.put("pushBackstopPollSeconds", (int) Math.max(1, backstop.toSeconds())); + return this; + } + + /** + * Retries after the agent fails, with exponential backoff from {@code delay}; default 3 and 1s. + * The server retries an AI task at least once: a count below 1 becomes 3, with linear backoff + * from 2 seconds ({@code AIModelTaskMapper}). + */ + public AgentCall retries(int count, Duration delay) { + this.retries = count; + this.retryDelay = delay; + return this; + } + + /** + * Sends the message, in this conversation, and waits for the agent's reply. When the reply + * {@link AgentResult#needsInput() needs input}, the next {@code ask} answers it. + */ + public AgentResult ask(String text) { + Command command = new Command(Command.Kind.AGENT, ref, ref); + command.explicitRef = ref; + command.input.putAll(input); + if (input.get("headers") instanceof Map headers) { + command.input.put("headers", new LinkedHashMap<>(headers)); // a later header() changes only later asks + } + command.input.put("text", text); + if (contextId != null) { + command.input.put("contextId", contextId); + } + if (waitingTaskId != null) { + command.input.put("taskId", waitingTaskId); + } + command.fields.put("taskDefinition", Entries.retryingDefinition(ref, retries, Math.max(1, retryDelay.toSeconds()))); + command.resultType = AgentResult.class; + AgentResult reply = (AgentResult) Engine.current().call(command); + if (reply != null) { + if (reply.contextId() != null) { + contextId = reply.contextId(); + } + waitingTaskId = reply.needsInput() ? reply.taskId() : null; + } + return reply; + } +} 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..3bf6dfb5b --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Conductor.java @@ -0,0 +1,717 @@ +/* + * 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.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.BooleanSupplier; +import java.util.function.Function; +import java.util.function.Supplier; + +import org.conductoross.conductor.sdk.Functions.Fn1; +import org.conductoross.conductor.sdk.Functions.Pred; +import org.conductoross.conductor.sdk.internal.ActionCase; +import org.conductoross.conductor.sdk.internal.CodeLoops; +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; + +/** + * Native workflows for Conductor. + * + *

Inside a {@link Workflow} method, a call to a {@code @WorkerTask} method of a task class the + * workflow takes in its constructor, and 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 the static methods statically: + * + *

{@code
+ * import static Conductor.*;
+ *
+ * public class OrderWorkflow {
+ *     private final PaymentTasks payments; // a stub Conductor passes: its calls schedule the tasks
+ *
+ *     public OrderWorkflow(PaymentTasks payments) {
+ *         this.payments = payments;
+ *     }
+ *
+ *     @Workflow(name = "order", version = 1)
+ *     public OrderResult process(OrderRequest order) {
+ *         Payment payment = payments.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)}, run workflows and tasks with + * {@link #workflows} and {@link #tasks}, 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.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 { + + + // ================================================================== workflow code + + /** + * 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 conductor.workflows(Type.class, factory)}, + * when the constructor also takes something else: + * + *

{@code
+     * conductor.workflows(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); + } + + // ------------------------------------------------------------------ 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. The branch's result is a {@link Future}: wait with {@link #join} and read it + * with {@link Future#resultNow()}, or wait and read at once with {@link Future#get()}, which + * wraps what the branch threw in an {@link ExecutionException}. For one + * branch per item of a list, waited for together, use {@link #fanOut}. + * + *
{@code
+     * Future a = async(() -> tasks.quote("a"));
+     * Future b = async(() -> tasks.quote("b"));
+     * join(a, b);                                   // the branches' failures are thrown here
+     * Quote best = cheaper(a.resultNow(), b.resultNow());
+     * }
+ * + * The wait is durable: the workflow pauses on a JOIN and no thread waits. A branch cannot be + * cancelled ({@code cancel} returns false), and {@code get(timeout, unit)} is not supported. A + * branch that is never joined still runs, the workflow stays running until it finishes, and its + * failure does not fail the workflow. + */ + public static Future async(Supplier body) { + return Engine.current().async(body); + } + + /** + * Waits for the given branches and everything they started, then throws the first failure + * among them, in the order given, as the branch threw it (a {@link TaskFailure}, say). + */ + public static void join(Future... branches) { + Engine.current().join(List.of(branches)); + } + + /** + * Runs the body once per item, in parallel, each item a branch of a FORK_JOIN, and waits for + * them all: returns the results in item order, as {@link #forEach} does for items one after + * another. A failed item throws here, as the item threw it. + */ + public static List fanOut(String name, List items, Function body) { + return Engine.current().fanOut(name, new ArrayList<>(items), body); + } + + public static List 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", () -> { tasks.even(); })
+     *     .when("1", () -> { tasks.odd(); })
+     *     .otherwise(() -> notes.add("unexpected"))
+     *     .run();
+     *
+     * String carrier = switchOn("region", region)
+     *     .when("eu", () -> tasks.euCarrier(item))
+     *     .otherwise(() -> 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 LinkedHashMap> cases = new 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 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 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(ChronoUnit.MINUTES); + if (minute.isBefore(when)) { + minute = minute.plus(Duration.ofMinutes(1)); + } + String until = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm 'UTC'") + .withZone(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 + * is named through a stub, as the rest of the workflow calls it: {@code forEach("labels", + * items, tasks::labelItem)}; the stub is not called. 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, Functions.TaskOf task) { + Command command = TaskStubs.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); + } + + /** + * A loop the execution shows as one, named: runs {@code body}, then runs it again while {@code + * condition} holds, as a Java {@code do}-{@code while} does. The body is ordinary workflow code: + * it may call tasks, branch, fork, start sub workflows and loop again, and each call wakes the + * code as usual. The execution diagram draws the calls as one loop named {@code name}, with a run + * for each pass, as it draws a plain Java loop, which is read from the compiled code; this one is + * named by the code instead. + * + *
{@code
+     * doWhile("poll_shipment", () -> {
+     *     status = tasks.shipmentStatus(orderId);
+     *     if (!status.delivered()) {
+     *         sleep(Duration.ofHours(1));
+     *     }
+     * }, () -> !status.delivered());
+     * }
+ * + * For one task the server repeats on its own, waking the code once at the end, use {@link + * #forEach} or {@link #repeatUntil}. + */ + public static void doWhile(String name, Functions.CaseAction body, Functions.Condition condition) { + CodeLoops.Named loop = CodeLoops.enter(name, body, condition); + // no engine outside workflow code (a handler, say): a plain loop there, as nothing replays it + Engine engine = Engine.CURRENT.get(); + do { + body.run(); + } while (engine == null ? condition.getAsBoolean() : engine.loopAgain(name, condition)); + // not in a finally: when the body throws, the mark of where it threw is still in the loop + loop.leave(); + } + + /** + * 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); + } + + /** + * A wait any system ends by completing the task {@code ref}: {@code + * external(ref).await(Type.class, timeout)}. + */ + public static ExternalWait external(String ref) { + return new ExternalWait(ref); + } + + 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); + } + + private static WorkflowSpec spec(Method method) { + return WorkflowSpec.forMethod(method); + } + + // ================================================================== client + + private final ConductorClient client; + /** Read by starts and queries while other threads add workers: iterated as a snapshot. */ + private final List started = new CopyOnWriteArrayList<>(); + private final Set> waiting = ConcurrentHashMap.newKeySet(); + private ScheduledExecutorService poller; + + 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(Objects.requireNonNull(client, "client")); + } + + public ConductorClient client() { + return client; + } + + /** + * Registers the definitions of these workflow classes, and their schedules, 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 ArrayList<>(); + for (Class type : workflows) { + specs.addAll(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 ArrayList<>(); + for (WorkflowSpec spec : WorkflowSpec.of(workflow)) { + defs.add(Registration.skeleton(spec, 30)); + } + return defs; + } + + /** + * Runs these workflow classes in this process: add task objects and options to what this + * returns, then {@code start()} registers the definitions and starts polling. Each call starts + * a separate set of workers; closing this Conductor stops them all. + */ + public Workers workflows(Class... workflowClasses) { + return newWorkers().workflows(workflowClasses); + } + + /** As {@link #workflows}, for a workflow class whose instances need constructor arguments. */ + public Workers workflows(Class workflowClass, Supplier factory) { + return newWorkers().workflows(workflowClass, factory); + } + + /** As {@link #workflows}, for objects with {@code @WorkerTask} methods. */ + public Workers tasks(Object... taskObjects) { + return newWorkers().tasks(taskObjects); + } + + /** The spec of a workflow class these workers host, with its factory, if any of them does. */ + Optional hostedSpec(Class type) { + for (Workers workers : started) { + Optional spec = workers.hostedSpec(type); + if (spec.isPresent()) { + return spec; + } + } + return Optional.empty(); + } + + private Workers newWorkers() { + 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 and cancels the result futures still waiting. The + * client is left running: it is its creator's. + */ + @Override + public void close() { + started.forEach(Workers::close); + List.copyOf(waiting).forEach(future -> future.cancel(false)); + synchronized (this) { + if (poller != null) { + poller.shutdownNow(); + } + } + } + + /** + * A future of an execution's outcome: {@code check} runs every 250 ms on this instance's one + * polling thread and returns the execution once it has finished (null until then), and {@code + * outcome} turns it into the result or throws. The future completes on the common pool, so a + * dependent stage cannot hold up the polling of other executions; cancelling it stops the + * checks. + */ + CompletableFuture whenFinished(Supplier check, Function outcome) { + CompletableFuture future = new CompletableFuture<>(); + AtomicBoolean settled = new AtomicBoolean(); + Runnable tick = () -> { + if (future.isDone() || settled.get()) { + return; + } + Runnable complete; + try { + E execution = check.get(); + if (execution == null) { + return; + } + R result = outcome.apply(execution); + complete = () -> future.complete(result); + } catch (RuntimeException e) { + complete = () -> future.completeExceptionally(e); + } + settled.set(true); + ForkJoinPool.commonPool().execute(complete); + }; + ScheduledFuture checks = poller().scheduleWithFixedDelay(tick, 0, 250, TimeUnit.MILLISECONDS); + waiting.add(future); + future.whenComplete((result, error) -> { + checks.cancel(false); + waiting.remove(future); + }); + return future; + } + + private synchronized ScheduledExecutorService poller() { + if (poller == null) { + poller = Executors.newSingleThreadScheduledExecutor(runnable -> { + Thread thread = new Thread(runnable, "conductor-results"); + thread.setDaemon(true); + return thread; + }); + } + return poller; + } + + /** 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; + } + + /** An id of your own to find the execution by, such as an order id; not unique. */ + 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; + } + + /** + * 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; + } + + /** Queue priority of the execution's tasks, 0 (lowest, the default) to 99. */ + 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; + } + + /** Starts the execution with these options. */ + 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, 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"); + } + // a start with an idempotency key can be repeated safely, so a server error or a lost + // connection is retried: the server returns the execution the first attempt created if + // it got that far. A start without a key is never retried, since a repeat could create + // a second execution. + String id = idempotencyKey == null + ? Http.post(conductor.client, "/workflow", request, String.class) + : Http.retrying(() -> Http.post(conductor.client, "/workflow", request, String.class)); + return new WorkflowHandle<>(conductor, id, method.getGenericReturnType()); + } + } +} 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..f1bcac8ca --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/EventCall.java @@ -0,0 +1,41 @@ +/* + * 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 c = command.copy(); + c.input.putAll(Json.encodeOutput(payload)); + c.fields.putIfAbsent("sink", "conductor"); + Engine.current().fire(c); + } +} 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..e2576bb41 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/ExternalWait.java @@ -0,0 +1,48 @@ +/* + * 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: {@code external("delivered").await(Delivery.class, + * Duration.ofDays(1))}. Like {@link HumanCall#await}, the result type and the timeout are given + * when waiting. + */ +public final class ExternalWait { + + private final Command command; + + ExternalWait(String ref) { + command = new Command(Command.Kind.WAIT, ref, ref); + command.explicitRef = ref; + command.optional = true; + command.emptyIsEmpty = true; + } + + /** The posted body as {@code type}, or empty when nothing arrives within the timeout. */ + @SuppressWarnings("unchecked") + public Optional await(Class type, Duration timeout) { + Command c = command.copy(); + c.resultType = type; + c.input.put("duration", Conductors.duration(timeout)); + c.seconds = timeout.toSeconds(); + return (Optional) Engine.current().call(c); + } +} 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..043400895 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Functions.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 java.io.Serializable; +import java.util.function.BooleanSupplier; +import java.util.function.Predicate; +import java.util.function.Supplier; + +/** + * Serializable functional interfaces for method references and lambdas. A method reference such + * as {@code OrderWorkflow::process} or {@code tasks::labelItem} passed where one of these is + * expected can be resolved, through {@code SerializedLambda}, to the method it names, so the SDK + * reads names from the annotations 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 Proc0 extends Serializable { + void apply(T target); + } + + public interface Proc1 extends Serializable { + void apply(T target, A a); + } + + /** 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 Supplier, Serializable {} + + /** A switch case body with no result. */ + public interface CaseAction extends Runnable, Serializable {} + + /** The condition of a {@code doWhile}. Serializable so that its compiled code can be located. */ + public interface Condition extends BooleanSupplier, 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..605dc1664 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Http.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.lang.reflect.Type; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +import com.netflix.conductor.client.http.ConductorClient; +import com.netflix.conductor.client.http.ConductorClientRequest; +import com.netflix.conductor.client.http.ConductorClientResponse; + +import io.orkes.conductor.client.http.ApiException; + +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(); + } + + /** + * Calls the server, riding out a restart: a failure other than a refusal (4xx) is retried every + * second for up to two minutes. Only for calls that are safe to repeat. + */ + static T retrying(Supplier call) { + long deadline = System.currentTimeMillis() + Duration.ofMinutes(2).toMillis(); + while (true) { + try { + return call.get(); + } catch (RuntimeException e) { + if (isRefusal(e) || System.currentTimeMillis() > deadline) { + throw e; + } + try { + Thread.sleep(1000); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + throw e; + } + } + } + } + + /** The server refused the request (4xx): repeating it will not help. */ + static boolean isRefusal(RuntimeException e) { + return e instanceof ApiException api && api.getStatusCode() >= 400 && api.getStatusCode() < 500; + } + + private static TypeReference ref(Class type) { + return new TypeReference<>() { + @Override + public 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..1a7b5f934 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/HttpCall.java @@ -0,0 +1,104 @@ +/* + * 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; +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, Duration.ofSeconds(1)); + } + + /** Retries after a failure, with exponential backoff from the given delay; default 3 and 1s. */ + public HttpCall retries(int count, Duration delay) { + command.fields.put( + "taskDefinition", + 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) { + Map sent = new LinkedHashMap<>(request); + if (!headers.isEmpty()) { + sent.put("headers", new LinkedHashMap<>(headers)); + } + Command c = command.copy(); + c.input.put("http_request", sent); + c.resultType = type; + return Engine.current().call(c); + } + + 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..7bfdc3789 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/HumanCall.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.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 c = command.copy(); + c.fields.put("taskDefinition", def); + c.resultType = type; + c.optional = true; + c.timeoutIsEmpty = true; + c.seconds = timeout.toSeconds(); + return (Optional) Engine.current().call(c); + } +} 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..007eb619c --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/LlmCall.java @@ -0,0 +1,80 @@ +/* + * 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 org.conductoross.conductor.sdk.internal.Command; +import org.conductoross.conductor.sdk.internal.Engine; +import org.conductoross.conductor.sdk.internal.Entries; + +/** 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; + command.outputKey = "result"; // the model's answer; the rest of the output is token counts + retries(3, Duration.ofSeconds(1)); + } + + /** + * Retries after a failure, with exponential backoff from the given delay; default 3 and 1s. + * The server retries an AI task at least once: a count below 1 becomes 3, with linear backoff + * from 2 seconds ({@code AIModelTaskMapper}). + */ + public LlmCall retries(int count, Duration delay) { + command.fields.put( + "taskDefinition", + 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; + } + + /** + * Asks the model and returns its answer as {@code type}: a {@code String} for text, or a record + * or class for a JSON answer, which the server then requires (an answer that is not JSON fails + * the call, and is retried). Say in the prompt which fields to answer with. + */ + public T as(Class type) { + Command c = command.copy(); + c.resultType = type; + if (type != String.class) { + c.input.put("jsonOutput", true); + } + return type.cast(Engine.current().call(c)); + } +} 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..811fdec06 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/McpCall.java @@ -0,0 +1,118 @@ +/* + * 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; + } + + /** + * Retries after a failure, with exponential backoff from {@code delay}; default 3 and 1s. The + * server retries an AI task at least once: a count below 1 becomes 3, with linear backoff from + * 2 seconds ({@code AIModelTaskMapper}). + */ + 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..9bc339f92 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/NonDeterminismException.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 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. + * + *

Also raised by {@code Workers.start()} for a workflow hosted with {@code + * conductor.workflow..strictDeterminism=true} whose code asks the JVM itself for a random + * value or the time: the message lists each place and what to use instead, and none of the + * workers is started. + */ +public class NonDeterminismException extends RuntimeException { + + public NonDeterminismException(String message) { + super(message); + } +} diff --git a/conductor-client/src/main/java/org/conductoross/conductor/sdk/ParkedExecutions.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/ParkedExecutions.java new file mode 100644 index 000000000..f50242bb1 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/ParkedExecutions.java @@ -0,0 +1,158 @@ +/* + * 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.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.LongSupplier; + +import org.conductoross.conductor.sdk.internal.Replayer; + +/** + * The executions whose code this process keeps in memory between continuations. + * + *

After a continuation the lanes of the code are left parked where they paused, on their + * virtual threads, instead of being torn down. When the execution's next continuation comes to + * this process, its lane is woken with the result of the task it waited for and nothing is run + * again: no replay, and no fetch of the execution's history. + * + *

It is a cache and nothing else. The server's recording remains what the execution is, so an + * execution dropped from here (it sat idle too long, too many are held, the process restarted) is + * replayed by whichever worker gets its next continuation. An execution is out of the cache while + * one of its continuations runs ({@link #take}), so only one thread ever has its lanes. + */ +final class ParkedExecutions { + + /** + * One execution's lanes, parked. + * + * @param stamp what the completion of its last continuation carried; the lanes may continue + * only while the server still names it as the last completion that applied + * @param until when it has sat idle for too long, in the clock's milliseconds + */ + record Parked(Replayer replayer, String stamp, long until) {} + + /** By code type, each in the order they were parked: the first is the one idle longest. */ + private final Map> byCodeType = new HashMap<>(); + private final LongSupplier clock; + private final AtomicLong continued = new AtomicLong(); + private final AtomicLong replayed = new AtomicLong(); + private final AtomicLong dropped = new AtomicLong(); + + ParkedExecutions() { + this(System::currentTimeMillis); + } + + ParkedExecutions(LongSupplier clock) { + this.clock = clock; + } + + /** + * Takes an execution's parked lanes out, for the continuation about to run; null when none + * are held. The caller parks them again, or closes them. + */ + synchronized Parked take(String codeType, String workflowId) { + LinkedHashMap held = byCodeType.get(codeType); + return held == null ? null : held.remove(workflowId); + } + + /** + * Keeps an execution's lanes until its next continuation, for at most {@code idleMillis}. When + * that makes more than {@code max} of its code type, the ones idle longest are closed. + */ + void park(String codeType, String workflowId, Replayer replayer, String stamp, long idleMillis, int max) { + List closing = new ArrayList<>(); + synchronized (this) { + LinkedHashMap held = byCodeType.computeIfAbsent(codeType, k -> new LinkedHashMap<>()); + Parked replaced = held.put(workflowId, new Parked(replayer, stamp, clock.getAsLong() + idleMillis)); + if (replaced != null) { + closing.add(replaced); // two workers threads were handed the same continuation + } + for (Iterator eldest = held.values().iterator(); held.size() > Math.max(1, max); ) { + closing.add(eldest.next()); + eldest.remove(); + } + } + close(closing); + } + + /** How many executions of a code type are held. */ + synchronized int held(String codeType) { + LinkedHashMap held = byCodeType.get(codeType); + return held == null ? 0 : held.size(); + } + + /** Closes the executions that have sat idle past their time. */ + void dropIdle() { + List closing = new ArrayList<>(); + long now = clock.getAsLong(); + synchronized (this) { + for (LinkedHashMap held : byCodeType.values()) { + held.values().removeIf(p -> { + if (p.until() > now) { + return false; + } + closing.add(p); + return true; + }); + } + } + close(closing); + } + + /** Closes every execution held: the process stops hosting. */ + void closeAll() { + List closing = new ArrayList<>(); + synchronized (this) { + byCodeType.values().forEach(held -> closing.addAll(held.values())); + byCodeType.clear(); + } + closing.forEach(p -> p.replayer().close()); + } + + /** Outside the lock: closing a replayer waits for its lanes' threads to unwind. */ + private void close(List closing) { + for (Parked p : closing) { + dropped.incrementAndGet(); + p.replayer().close(); + } + } + + void countContinued() { + continued.incrementAndGet(); + } + + void countReplayed() { + replayed.incrementAndGet(); + } + + /** Continuations that continued parked lanes, with no replay. */ + long continued() { + return continued.get(); + } + + /** Continuations that replayed the execution: nothing was held, or it was no longer current. */ + long replayed() { + return replayed.get(); + } + + /** Executions closed while held: idle too long, too many, or replaced. */ + long dropped() { + return dropped.get(); + } +} 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..149c86d65 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Registration.java @@ -0,0 +1,356 @@ +/* + * 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 java.util.function.ToLongFunction; + +import org.conductoross.conductor.sdk.internal.Json; +import org.conductoross.conductor.sdk.internal.JsonSchemas; +import org.conductoross.conductor.sdk.internal.MethodRefs; +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.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 Logger LOGGER = LoggerFactory.getLogger(Registration.class); + 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, spec -> continuationTimeoutSeconds, true); + } + + /** @param continuationTimeoutSeconds each workflow's continuation lease, in seconds */ + static void register(ConductorClient client, Collection specs, List taskObjects, + ToLongFunction continuationTimeoutSeconds, boolean discover) { + Schemas schemas = new Schemas(client); + // each task's input and output schema references, by task name + Map> taskSchemas = new LinkedHashMap<>(); + List> taskDefs = new ArrayList<>(); + for (Object o : taskObjects) { + for (Map.Entry e : workerMethods(o.getClass()).entrySet()) { + WorkerTask wt = e.getValue().getAnnotation(WorkerTask.class); + Map refs = schemas.refs( + e.getKey(), + JsonSchemas.taskInput(e.getValue()), + JsonSchemas.taskOutput(e.getValue())); + taskSchemas.put(e.getKey(), refs); + Map def = new LinkedHashMap<>(); + def.putAll(refs); + 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) { + Map def = skeleton(spec, continuationTimeoutSeconds.applyAsLong(spec), discover); + def.putAll(schemas.refs( + spec.name, + JsonSchemas.workflowInput(spec.method), + JsonSchemas.workflowOutput(spec.method))); + @SuppressWarnings("unchecked") // skeleton builds "tasks" as a list of entry maps + List> tasks = (List>) def.get("tasks"); + withTaskSchemas(tasks, taskSchemas); + workflowDefs.add(def); + } + 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 (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", 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) { + LOGGER.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); + } + } + // the code the definition is generated from; the server polls `.v.code` + Map nativeMeta = new LinkedHashMap<>(); + nativeMeta.put("class", spec.type.getName()); + nativeMeta.put("method", spec.method.getName()); + // 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()); + // 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 ? Replayer.discover(spec) : List.of(); + } catch (RuntimeException e) { + discovered = List.of(); + LOGGER.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) { + Method m = spec.method; + if (m.getParameterCount() == 0) { + return List.of(); + } + if (m.getParameterCount() == 1 && !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(MethodRefs.parameterNames(m)); + } + + /** The inline definitions of the discovered tasks reference their tasks' schemas, for the editor. */ + @SuppressWarnings("unchecked") + private static void withTaskSchemas(List> entries, Map> schemas) { + for (Map e : entries) { + if (e.get("taskDefinition") instanceof Map td && schemas.containsKey(String.valueOf(e.get("name")))) { + ((Map) td).putAll(schemas.get(String.valueOf(e.get("name")))); + } + if (e.get("forkTasks") instanceof List branches) { + branches.forEach(b -> withTaskSchemas((List>) b, schemas)); + } + if (e.get("decisionCases") instanceof Map dc) { + dc.values().forEach(c -> withTaskSchemas((List>) c, schemas)); + } + if (e.get("defaultCase") instanceof List dflt) { + withTaskSchemas((List>) dflt, schemas); + } + if (e.get("loopOver") instanceof List body) { + withTaskSchemas((List>) body, schemas); + } + } + } + + /** + * Schemas registered by name ({@code _input}, {@code _output}), versioned by + * content: a schema identical to a registered version reuses it, any other is the next version. + * Old executions keep the version they ran with, and builds running side by side each keep + * theirs. They document the data and are not enforced: the code decides what it accepts. + */ + static final class Schemas { + private final ConductorClient client; + private Map>> byName; + + Schemas(ConductorClient client) { + this.client = client; + } + + /** {@code inputSchema}, {@code outputSchema} and {@code enforceSchema: false}, for a definition. */ + Map refs(String name, Map input, Map output) { + Map refs = new LinkedHashMap<>(); + Map in = input == null ? null : ref(name + "_input", input); + Map out = output == null ? null : ref(name + "_output", output); + if (in != null) { + refs.put("inputSchema", in); + } + if (out != null) { + refs.put("outputSchema", out); + } + if (!refs.isEmpty()) { + refs.put("enforceSchema", false); + } + return refs; + } + + private Map ref(String name, Map data) { + try { + List> versions = registered().getOrDefault(name, new ArrayList<>()); + var wanted = Json.MAPPER.valueToTree(data); + int version = 0; + int highest = 0; + for (Map v : versions) { + int n = v.get("version") instanceof Number num ? num.intValue() : 0; + highest = Math.max(highest, n); + if (wanted.equals(Json.MAPPER.valueToTree(v.get("data")))) { + version = n; + } + } + if (version == 0) { + version = highest + 1; + Map schema = new LinkedHashMap<>(); + schema.put("name", name); + schema.put("version", version); + schema.put("type", "JSON"); + schema.put("data", data); + Http.post(client, "/schema", List.of(schema), Object.class); + versions.add(schema); + byName.put(name, versions); + } + Map ref = new LinkedHashMap<>(); + ref.put("name", name); + ref.put("version", version); + ref.put("type", "JSON"); + return ref; + } catch (RuntimeException e) { + LOGGER.warn("Could not register schema {} (does the server have a schema registry?): {}", name, e.toString()); + return null; + } + } + + private Map>> registered() { + if (byName == null) { + byName = new LinkedHashMap<>(); + for (Map s : Http.getList(client, "/schema")) { + byName.computeIfAbsent(String.valueOf(s.get("name")), k -> new ArrayList<>()).add(s); + } + } + return byName; + } + } + + /** 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..27da3ec56 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/TaskCall.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.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; + } + + /** Calls the task and returns its output as {@code type}. */ + public T as(Class type) { + return type.cast(call(type)); + } + + /** Calls the task and returns its output as a map. */ + @SuppressWarnings("unchecked") + public Map asMap() { + return (Map) call(Map.class); + } + + /** Calls the task, for its effect. */ + public void run() { + call(Void.class); + } + + private Object call(Class type) { + Command c = command.copy(); + c.resultType = type; + return Engine.current().call(c); + } +} 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..26825908e --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/TaskFailure.java @@ -0,0 +1,62 @@ +/* + * 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 com.netflix.conductor.common.metadata.tasks.Task; + +/** + * 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 its failed status in the UI either way. + */ +public class TaskFailure extends RuntimeException { + + private final String taskReferenceName; + private final Task.Status status; + private final String reason; + + /** {@code status} is the task's status as the server reports it, such as {@code FAILED}. */ + public TaskFailure(String taskReferenceName, String status, String reason) { + super( + "task " + + taskReferenceName + + " " + + status + + (reason == null || reason.isBlank() ? "" : ": " + reason)); + this.taskReferenceName = taskReferenceName; + this.status = statusOf(status); + this.reason = reason; + } + + private static Task.Status statusOf(String status) { + try { + return Task.Status.valueOf(status); + } catch (IllegalArgumentException | NullPointerException e) { + return Task.Status.FAILED; + } + } + + public String getTaskReferenceName() { + return taskReferenceName; + } + + /** The task's terminal status: FAILED, FAILED_WITH_TERMINAL_ERROR, TIMED_OUT or CANCELED. */ + public Task.Status getStatus() { + return status; + } + + /** Why the task failed, as the task reported it; may be null. */ + public String getReason() { + return reason; + } +} 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..a700466c4 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Workers.java @@ -0,0 +1,936 @@ +/* + * 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.time.Duration; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.BooleanSupplier; +import java.util.function.Function; +import java.util.function.Supplier; + +import org.conductoross.conductor.sdk.internal.CodeReader; +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.AnnotatedWorkerExecutor; +import com.netflix.conductor.sdk.workflow.executor.task.WorkerConfiguration; +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +/** + * 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. The {@code @WorkerTask} methods run as + * {@link AnnotatedWorkerExecutor} runs them: thread count, polling interval, poll timeout, poller + * count and domain from {@code conductor.worker..}, else {@code + * conductor.worker.all.} (read like the workflow settings below), else the annotation; a + * task whose thread count none of them sets gets 8 threads. Each workflow runs on a {@link + * com.netflix.conductor.client.automator.TaskRunner} too, as the worker of its code type: a + * continuation arrives as the task the code paused on, carrying its continuation marker, and 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 with update-v2, which hands back the next one. + * + *

An execution's code stays in memory between its continuations ({@link ParkedExecutions}): + * its lanes are left parked where they paused, and the next continuation wakes its lane with the + * result of the task it waited for, without re-running the method or fetching the execution. For + * that the execution is pinned to this process. The workers name a task domain of their own, + * {@code pin--}, new on every start; each completion tells the server that the + * execution is held there, and the server offers the execution's next continuation to that + * domain's queue first. If this process does not take it within the server's pin timeout (it + * died, or is stalled), any host takes it from the shared queue and replays, as before. So the + * recording stays what an execution is and the copy in memory only saves work: it is dropped + * after {@code parkTimeout} without a continuation (an hour by default), when more than {@code + * maxParked} executions of a workflow are held (1000), and whenever the server says the + * execution moved on without it (another host continued it; it was retried, rerun or restarted). + * A retry or rerun therefore always replays. {@code parkTimeout=0} turns this off for a workflow; + * a server that does not pin executions turns it off for all. + * + *

Per workflow, {@code conductor.workflow..}, else {@code + * conductor.workflow.all.}, read from the system properties (see {@link + * #settings(Function)}): {@code threadCount}, {@code pollingInterval} and {@code pollTimeout} + * (defaults from {@link Workflow}: 20, 100 ms and 500 ms), {@code paused} (read before each poll), + * {@code continuationTimeout} and {@code parkTimeout} (seconds, or an ISO-8601 duration) and + * {@code maxParked}. The task domains a run is started with do not apply to workflow code: every + * host of a workflow polls its shared queue, and its own queue while it holds executions. + */ +public final class Workers implements AutoCloseable { + + 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 boolean devMode; + private boolean discovery = true; + private Duration continuationTimeout = Duration.ofSeconds(30); + private Duration parkTimeout = Duration.ofHours(1); + private final ParkedExecutions parked = new ParkedExecutions(); + private final AtomicLong stamps = new AtomicLong(); + /** The task domain of this process alone, where the server offers the executions held here. */ + private String pinDomain; + private TaskRunnerConfigurer pinnedRunner; + private Thread parkSweeper; + private Function settings = System::getProperty; + private TaskRunnerConfigurer workflowRunner; + private AnnotatedWorkerExecutor taskExecutor; + private Thread registrar; + private volatile boolean running; + private boolean started; + private boolean closed; + 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(Duration.ofSeconds(1)).factor(2).max(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; + } + + /** + * Development mode: generous continuation timeouts, for breakpoints, and no code kept in + * memory between continuations, so that every continuation replays. + */ + public Workers devMode(boolean devMode) { + this.devMode = devMode; + 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. {@code conductor.workflow..continuationTimeout} + * overrides it for one workflow. + */ + public Workers continuationTimeout(Duration timeout) { + this.continuationTimeout = timeout; + return this; + } + + /** + * How long an execution's code stays in memory without a continuation before it is dropped + * (its next continuation then replays); default an hour. Zero keeps nothing in memory: every + * continuation replays. {@code conductor.workflow..parkTimeout} overrides it for one + * workflow. + */ + public Workers parkTimeout(Duration timeout) { + this.parkTimeout = timeout; + return this; + } + + /** + * Where the per-workflow settings are read, by key ({@code conductor.workflow..threadCount} + * and so on); {@link System#getProperty(String)} by default. + */ + public Workers settings(Function settings) { + this.settings = settings; + 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 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 workflows(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() { + if (started) { + throw new IllegalStateException("these workers were already started: make new ones with Conductor.workflows(..)"); + } + started = true; + // fail now, not on the first continuation, when a workflow class cannot be created + specsByCodeType.values().forEach(WorkflowSpec::newInstance); + List refused = new ArrayList<>(); + for (WorkflowSpec spec : specsByCodeType.values()) { + for (String site : 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); + } + String report = nonDeterministicCode(spec); + if (report != null) { + refused.add(report); + } + } + if (!refused.isEmpty()) { + // before anything is registered or polled: none of these workers is hosted + String message = String.join("\n\n", refused); + LOGGER.error(message); + throw new NonDeterminismException(message); + } + running = true; + registrar = Thread.ofVirtual().name("conductor-register").start(this::registerUntilDone); + int tasks = 0; + if (!taskObjects.isEmpty()) { + taskExecutor = new AnnotatedWorkerExecutor(taskClient, new TaskSettings()); + for (Object o : taskObjects) { + for (Method m : Registration.workerMethods(o.getClass()).values()) { + taskExecutor.addMethod(m.getAnnotation(WorkerTask.class), m, o); + tasks++; + } + } + taskExecutor.startPolling(); + } + List codeWorkers = new ArrayList<>(); + List pinnedWorkers = new ArrayList<>(); + Map threadCounts = new LinkedHashMap<>(); + Map pollTimeouts = new LinkedHashMap<>(); + for (Map.Entry e : specsByCodeType.entrySet()) { + WorkflowSpec spec = e.getValue(); + String codeType = e.getKey(); + Workflow annotation = spec.method.getAnnotation(Workflow.class); + threadCounts.put(codeType, setting(spec, "threadCount", annotation.threadCount())); + pollTimeouts.put(codeType, setting(spec, "pollTimeout", annotation.pollTimeout())); + int pollingInterval = setting(spec, "pollingInterval", annotation.pollingInterval()); + BooleanSupplier paused = () -> Boolean.parseBoolean(setting(spec, "paused")); + codeWorkers.add(new CodeWorker(codeType, pollingInterval, paused)); + if (parkMillis(spec) > 0) { + // its own queue is polled only while it holds an execution of this workflow: the + // server offers there only what is pinned here, and a queue nobody polls reads as + // a worker that is gone, so nothing waits on it + pinnedWorkers.add(new CodeWorker(codeType, pollingInterval, + () -> paused.getAsBoolean() || parked.held(codeType) == 0)); + } + } + if (!codeWorkers.isEmpty()) { + workflowRunner = new TaskRunnerConfigurer.Builder(taskClient, codeWorkers) + .withTaskThreadCount(threadCounts) + .withTaskPollTimeout(pollTimeouts) + .withUseVirtualThreads(true) + .withTaskUpdateV2(true) + .withDomains(false) + .withWorkerNamePrefix("conductor-workflow") + .build(); + workflowRunner.init(); + } + if (!pinnedWorkers.isEmpty()) { + pinDomain = newPinDomain(workerId); + pinnedRunner = new TaskRunnerConfigurer.Builder(taskClient, pinnedWorkers) + .withTaskThreadCount(threadCounts) + .withTaskPollTimeout(pollTimeouts) + .withUseVirtualThreads(true) + .withTaskUpdateV2(true) + .withDomains(false) + .withFixedDomain(pinDomain) + .withWorkerNamePrefix("conductor-workflow-pinned") + .build(); + pinnedRunner.init(); + parkSweeper = Thread.ofVirtual().name("conductor-parked").start(this::dropIdleUntilClosed); + } + LOGGER.info("Hosting workflows {} and {} tasks as {}{}", specsByCodeType.keySet(), tasks, workerId, + pinDomain == null ? "" : "; executions stay in memory between continuations, pinned to domain " + pinDomain); + return this; + } + + /** + * A task domain no other process has: this host's id, as far as it can be part of a queue + * name, and a random part that changes on every start. A process that restarted holds nothing + * in memory, so it must not be offered what was pinned to the one before it. + */ + static String newPinDomain(String workerId) { + String host = workerId == null ? "" : workerId.replaceAll("[^A-Za-z0-9_.-]", "_"); + host = host.length() > 40 ? host.substring(0, 40) : host; + String random = Long.toString(ThreadLocalRandom.current().nextLong(Long.MAX_VALUE), 36); + return "pin-" + (host.isEmpty() ? "" : host + "-") + random.substring(0, Math.min(8, random.length())); + } + + /** Drops the executions that sat idle past their {@code parkTimeout}, once a second. */ + private void dropIdleUntilClosed() { + while (running) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + return; + } + parked.dropIdle(); + } + } + + /** The executions kept in memory between continuations. */ + ParkedExecutions parked() { + return parked; + } + + /** The task domain the executions held here are pinned to, once started; null when none are kept. */ + String pinDomain() { + return pinDomain; + } + + /** Stops polling and the background registration. */ + @Override + public void close() { + running = false; + if (registrar != null) { + registrar.interrupt(); + } + if (parkSweeper != null) { + parkSweeper.interrupt(); + } + if (workflowRunner != null) { + workflowRunner.shutdown(); + } + if (pinnedRunner != null) { + pinnedRunner.shutdown(); + } + if (taskExecutor != null) { + taskExecutor.shutdown(); + } + // after the pollers: nothing runs a continuation now. Their next ones replay elsewhere + if (pinDomain != null && !closed) { + LOGGER.info("Executions kept in memory as {}: {} continuations continued without a replay, {} replayed," + + " {} executions dropped while held", pinDomain, parked.continued(), parked.replayed(), parked.dropped()); + } + closed = true; + parked.closeAll(); + } + + /** The task runner of the hosted workflows, once started. */ + TaskRunnerConfigurer workflowRunner() { + return workflowRunner; + } + + /** + * Checks a workflow's compiled code for places that ask the JVM itself for a random value or + * the time. Such code can take another path when it runs again, as it does on every + * continuation and on a retry or rerun. Each place is logged as a warning; with {@code + * conductor.workflow..strictDeterminism=true} (or {@code conductor.workflow.all.}) the + * workflow is refused instead, and this returns the report that says why. Null when the + * workflow may be hosted. + */ + private String nonDeterministicCode(WorkflowSpec spec) { + List found; + try { + found = CodeReader.rawSources(spec.method); + } catch (RuntimeException e) { + LOGGER.warn("Workflow {} could not be checked for non-deterministic code: {}", spec.name, e.toString()); + return null; + } + if (found.isEmpty()) { + return null; + } + if (!Boolean.parseBoolean(setting(spec, "strictDeterminism"))) { + for (CodeReader.RawSource raw : found) { + LOGGER.warn("Workflow {} calls {} at {}: workflow code runs again each time it continues, and on a" + + " retry or rerun, so this can give another value there and take the code down another" + + " path. Use {}. Set conductor.workflow.{}.strictDeterminism=true to refuse to host" + + " code like this.", spec.name, raw.call(), raw.site(), raw.replacement(), spec.name); + } + return null; + } + int site = found.stream().mapToInt(r -> r.site().length()).max().orElse(0); + int call = found.stream().mapToInt(r -> r.call().length()).max().orElse(0); + StringBuilder report = new StringBuilder("Workflow ").append(spec.name).append(" cannot be hosted: ") + .append(found.size() == 1 ? "1 place in its code is" : found.size() + " places in its code are") + .append(" not deterministic."); + for (CodeReader.RawSource raw : found) { + report.append(String.format("%n %-" + site + "s %-" + call + "s use %s", raw.site(), raw.call(), raw.replacement())); + } + report.append(String.format("%nA retry or rerun runs this code again and must take the same path. Anything else that can" + + "%nchange between runs goes in Conductor.once(name, () -> ...)." + + "%nTo host it anyway: conductor.workflow.%s.strictDeterminism=false", spec.name)); + return report.toString(); + } + + /** A workflow's setting: {@code conductor.workflow..}, else {@code conductor.workflow.all.}. */ + private String setting(WorkflowSpec spec, String key) { + String value = settings.apply("conductor.workflow." + spec.name + "." + key); + if (value == null || value.isBlank()) { + value = settings.apply("conductor.workflow.all." + key); + } + return value == null || value.isBlank() ? null : value.trim(); + } + + private int setting(WorkflowSpec spec, String key, int otherwise) { + String value = setting(spec, key); + return value == null ? otherwise : Integer.parseInt(value); + } + + /** A workflow's continuation lease in seconds: an hour in dev mode. */ + long continuationTimeoutSeconds(WorkflowSpec spec) { + if (devMode) { + return 3600; + } + String value = setting(spec, "continuationTimeout"); + Duration timeout = value == null ? continuationTimeout + : value.chars().allMatch(Character::isDigit) ? Duration.ofSeconds(Long.parseLong(value)) + : Duration.parse(value); + return Math.max(1, timeout.toSeconds()); + } + + /** + * How long an execution of a workflow stays in memory without a continuation, in milliseconds: + * {@code conductor.workflow..parkTimeout} (seconds, or an ISO-8601 duration), else what + * {@link #parkTimeout(java.time.Duration)} was given. Zero: its code is not kept in memory. + * Always zero in dev mode. + */ + long parkMillis(WorkflowSpec spec) { + if (devMode) { + // every continuation replays, which shows code that is not deterministic while it is + // being written; and a breakpoint may hold a continuation longer than a server waits + // for the worker an execution is pinned to + return 0; + } + String value = setting(spec, "parkTimeout"); + Duration timeout = value == null ? parkTimeout + : value.chars().allMatch(Character::isDigit) ? Duration.ofSeconds(Long.parseLong(value)) + : Duration.parse(value); + return Math.max(0, timeout.toMillis()); + } + + /** + * The settings of a {@code @WorkerTask} method, as Spring's worker configuration reads them: + * {@code conductor.worker..}, else {@code conductor.worker.all.}, from + * {@link #settings(Function)}; unset (0 or null) leaves the annotation's value. + */ + private final class TaskSettings extends WorkerConfiguration { + + private String get(String task, String key) { + String value = settings.apply("conductor.worker." + task + "." + key); + if (value == null || value.isBlank()) { + value = settings.apply("conductor.worker.all." + key); + } + return value == null || value.isBlank() ? null : value.trim(); + } + + private int number(String task, String key) { + String value = get(task, key); + return value == null ? 0 : Integer.parseInt(value); + } + + @Override + public int getThreadCount(String task) { + return number(task, "threadCount"); + } + + /** What every hosted task had before tasks were configured one by one. */ + @Override + public int getDefaultThreadCount() { + return 8; + } + + @Override + public int getPollingInterval(String task) { + return number(task, "pollingInterval"); + } + + @Override + public int getPollTimeout(String task) { + return number(task, "pollTimeout"); + } + + @Override + public int getPollerCount(String task) { + return number(task, "pollerCount"); + } + + @Override + public String getDomain(String task) { + return get(task, "domain"); + } + } + + /** The worker of a workflow's code type: running a task processes a continuation. */ + private final class CodeWorker implements Worker { + + private final String codeType; + private final int pollingInterval; + private final BooleanSupplier paused; + + CodeWorker(String codeType, int pollingInterval, BooleanSupplier paused) { + this.codeType = codeType; + this.pollingInterval = pollingInterval; + this.paused = paused; + } + + @Override + public String getTaskDefName() { + return codeType; + } + + @Override + public TaskResult execute(Task task) { + return process(codeType, task); + } + + @Override + public int getPollingInterval() { + return pollingInterval; + } + + @Override + public boolean paused() { + return paused.getAsBoolean(); + } + + @Override + public String getIdentity() { + return workerId; + } + } + + /** + * 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, 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(Duration.ofMillis(50))) { + return; + } + } + } + + /** The spec of a workflow class these workers host, with the factory it was given. */ + Optional hostedSpec(Class type) { + return specsByCodeType.values().stream().filter(s -> s.type == type).findFirst(); + } + + /** Whether the definitions have been registered since {@link #start()}. */ + public boolean isRegistered() { + return registered; + } + + /** + * Registers the definitions, retrying with backoff for as long as it takes: registration is an + * idempotent upsert, and a worker starting while the server is down, or while other workers + * register the same definitions, waits rather than exits. + */ + 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, + this::continuationTimeoutSeconds, discovery); + registered = true; + LOGGER.info("Registered the definitions of {} after {} attempt(s)", specsByCodeType.keySet(), attempt); + return; + } catch (RuntimeException e) { + 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(Duration wait) { + long ms = wait.toMillis(); + try { + Thread.sleep(ms / 2 + 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 = Duration.ofMinutes(10).toMillis(); + + /** At most this many replies are kept, newest first, whatever their age. */ + static final int REPLY_LIMIT = 500; + + /** A handled message's entry: its reply, if it has one ({@code key} null for a signal), and when. */ + private static Map reply(String key, Object value) { + Map r = new LinkedHashMap<>(); + if (key != null) { + 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); + } + } + // oldest first, by when each was handled: the map itself comes back in no particular order + fresh.sort(Comparator.comparingLong(e -> ((Number) ((Map) e.getValue()).get("at")).longValue())); + 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; + } + + + /** + * Processes one continuation (or handler run) of an execution, and returns its completion. It + * never throws: a failure is the code's result, not the task's. + */ + TaskResult process(String codeType, Task task) { + String snapshot = "(not fetched)"; + String workflowId = task.getWorkflowInstanceId(); + Replayer replayer = null; // the lanes of this continuation, until they are parked or closed + try { + WorkflowSpec spec = specsByCodeType.get(codeType); + TaskContinuation marker = task.getContinuation(); + if (marker == null) { + throw new IllegalStateException("task " + task.getTaskId() + " carries no continuation"); + } + String lane = laneOf(task); + int n = numberOf(task); + if ("handlers".equals(lane)) { + Execution exec = fetch(workflowId); + snapshot = describe(exec, lane, n); + return processHandlers(spec, exec, task); + } + // A server that pins executions hands out the variables with the continuation; only + // then is the code kept in memory, since only then does its next continuation come here + long keepMillis = spec == null || pinDomain == null || marker.getVariables() == null ? 0 : parkMillis(spec); + Replayer.Outcome outcome = null; + ParkedExecutions.Parked held = parked.take(codeType, workflowId); + if (held != null) { + // The stamp is what this process sent with the execution's last continuation. The + // server still naming it means that completion applied and nothing has changed + // what the code did since: the lanes in memory are where the execution is. + if (keepMillis > 0 && held.stamp().equals(marker.getStamp()) && held.replayer().awaits(lane, n)) { + replayer = held.replayer(); + try { + outcome = replayer.readsTasks(lane) || task.getExternalOutputPayloadStoragePath() != null + ? replayer.proceed(lane, n, fetch(workflowId)) + : replayer.proceed(lane, n, marker.getVariables(), arrived(task)); + parked.countContinued(); + LOGGER.debug("Execution {} continued {}#{} from the code kept in memory", workflowId, lane, n); + } catch (NonDeterminismException | IllegalStateException e) { + // nothing of this continuation was sent, so the recording is still what + // the execution is: replay it + LOGGER.warn("Execution {} could not continue {}#{} from the code kept in memory ({}): replaying it", + workflowId, lane, n, e.getMessage()); + replayer.close(); + replayer = null; + outcome = null; + } + } else { + // another host continued the execution, or it was retried, rerun or restarted + LOGGER.debug("Execution {} moved on without the code kept in memory: replaying it", workflowId); + held.replayer().close(); + } + } + if (outcome == null) { + Execution exec = fetch(workflowId); + snapshot = describe(exec, lane, n); + replayer = new Replayer(spec, spec.newInstance(), exec); + outcome = replayer.begin(lane, n); + parked.countReplayed(); + } + logLaneError(task, lane, outcome.output); + if (!"main".equals(lane)) { + // the server reads what a lane returned or raised for the main lane only + outcome.output.remove("result"); + outcome.output.remove("error"); + } + if (keepMillis > 0 && replayer.hasPausedLanes()) { + // the completion says so: the server pins the execution to this process and hands + // the stamp back with its next continuation + String stamp = pinDomain + "." + stamps.incrementAndGet(); + outcome.output.put("pin", Map.of("domain", pinDomain, "stamp", stamp)); + replayer.forgetHistory(); + parked.park(codeType, workflowId, replayer, stamp, keepMillis, setting(spec, "maxParked", 1000)); + } else { + replayer.close(); + } + replayer = null; + return result(task, TaskResult.Status.COMPLETED, outcome.output, null); + } catch (NonDeterminismException e) { + LOGGER.error("Execution {} diverged from its code: {}", workflowId, e.getMessage()); + LOGGER.error("Execution {} as replayed: {}", workflowId, snapshot); + return result(task, TaskResult.Status.FAILED_WITH_TERMINAL_ERROR, Map.of(), e.getMessage()); + } catch (Exception | StackOverflowError e) { + LOGGER.error("Processing {} of execution {} failed", task.getReferenceTaskName(), workflowId, e); + return result(task, TaskResult.Status.FAILED, Map.of(), e.toString()); + } finally { + if (replayer != null) { + replayer.close(); + } + } + } + + /** The task a poll handed out, as the lane that waited for it reads it. */ + private static Execution.TaskView arrived(Task task) { + return Execution.TaskView.of(task.getTaskId(), task.getReferenceTaskName(), task.getTaskType(), + task.getStatus() == null ? null : task.getStatus().name(), task.getOutputData(), + task.getReasonForIncompletion()); + } + + /** + * 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 TaskResult processHandlers(WorkflowSpec spec, Execution exec, Task task) { + List> messages = + (List>) task.getInputData().getOrDefault("messages", List.of()); + Object instance = spec.newInstance(); + spec.restoreVariables(instance, exec.variables); + // every handled message is in the replies, by the sender's id: a message queued twice by + // a retried send applies once + Map replies = new LinkedHashMap<>(exec.replies()); + 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 (replies.containsKey(id)) { + LOGGER.debug("message {} of execution {} was already handled", id, exec.workflowId); + continue; + } + // 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")); + // a signal's sender waits for no reply: its entry only says it was handled. So + // does the entry of a handler that returned null: the caller reads no value, null + Object returned = Json.plain(value); + replies.put(id, "signal".equals(kind) || returned == null ? reply(null, null) : reply("value", returned)); + } catch (RuntimeException e) { + LOGGER.warn("handler {} {} of execution {} failed: {}", kind, name, exec.workflowId, e.toString()); + replies.put(id, "signal".equals(kind) ? reply(null, null) : reply("error", e.toString())); + } finally { + if (beforeQuery != null) { + spec.restoreVariables(instance, beforeQuery); + } + } + } + Map vars = spec.captureVariables(instance); + Map output = new LinkedHashMap<>(); + output.put("variables", vars); + // what this handler started from, kept on the marker for replay; the server applies the + // variables as sent (one continuation runs at a time, so nothing else changed them) + output.put("resumedWith", spec.captureVariablesOf(exec.variables)); + output.put("replies", pruneReplies(replies, System.currentTimeMillis())); + output.put("releases", releases(spec, exec, vars)); + return result(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); + 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; + } + + /** + * The lane of the code a handed-out continuation runs: its entry names it, as does the entry the + * server builds for the first continuation and the handler lane. + */ + private static String laneOf(Task task) { + Object lane = entryMetadata(task).get("lane"); + return lane == null ? "main" : lane.toString(); + } + + /** The continuation's number in its lane. */ + private static int numberOf(Task task) { + return entryMetadata(task).get("continuation") instanceof Number n ? n.intValue() : 1; + } + + private static Map entryMetadata(Task task) { + return task.getWorkflowTask() == null || task.getWorkflowTask().getMetadata() == null + ? Map.of() + : task.getWorkflowTask().getMetadata(); + } + + /** What a replay saw, for the log when the code diverges: status, tasks, markers, replay order. */ + private static String describe(Execution exec, String lane, int n) { + StringBuilder sb = new StringBuilder(); + sb.append("status=").append(exec.status).append(" active=").append(lane).append('#').append(n); + sb.append(" replay="); + for (Execution.Marker m : exec.segments()) { + sb.append(m.lane).append('#').append(m.n).append("@").append(m.endTime).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.endTime).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 TaskResult result(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", numberOf(task)); + result.getOutputData().put("retryCount", marker.getRetryCount()); + } + if (reason != null) { + result.setReasonForIncompletion(reason.length() > 1000 ? reason.substring(0, 1000) : reason); + } + return result; + } +} 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..73c072ff0 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/Workflow.java @@ -0,0 +1,71 @@ +/* + * 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; + + /** + * How many continuations of this workflow a host runs at once. The property {@code + * conductor.workflow..threadCount}, else {@code conductor.workflow.all.threadCount}, + * overrides it. + */ + int threadCount() default 20; + + /** + * Milliseconds a host waits before polling again after a poll found nothing. Overridden by + * {@code conductor.workflow..pollingInterval}, else {@code conductor.workflow.all.pollingInterval}. + */ + int pollingInterval() default 100; + + /** + * Milliseconds a poll waits on the server for a continuation (long poll). Overridden by + * {@code conductor.workflow..pollTimeout}, else {@code conductor.workflow.all.pollTimeout}. + */ + int pollTimeout() default 500; +} 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..cb9415dd6 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/WorkflowFailedException.java @@ -0,0 +1,47 @@ +/* + * 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 com.netflix.conductor.common.run.Workflow.WorkflowStatus; + +/** + * Thrown from workflow code to fail the execution with a reason. Thrown to a client waiting for the + * result of an execution that failed, with the execution's id and final status. + */ +public class WorkflowFailedException extends RuntimeException { + + private final String workflowId; + private final WorkflowStatus status; + + /** Fails the execution this code is running for, with this reason. */ + public WorkflowFailedException(String reason) { + this(null, null, reason); + } + + /** An execution that ended without completing: its id, final status and reason. */ + public WorkflowFailedException(String workflowId, WorkflowStatus status, String reason) { + super(status == null ? reason : status + ": " + reason); + this.workflowId = workflowId; + this.status = status; + } + + /** The failed execution, when this was thrown to a client; null in workflow code. */ + public String getWorkflowId() { + return workflowId; + } + + /** FAILED, TERMINATED or TIMED_OUT when thrown to a client; null in workflow code. */ + public WorkflowStatus getStatus() { + return status; + } +} 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..f62c37d39 --- /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.io.Serializable; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +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; + +import com.netflix.conductor.client.http.TaskClient; +import com.netflix.conductor.client.http.WorkflowClient; +import com.netflix.conductor.common.metadata.tasks.Task; +import com.netflix.conductor.common.metadata.tasks.TaskResult; +import com.netflix.conductor.common.run.Workflow; +import com.netflix.conductor.common.run.Workflow.WorkflowStatus; + +/** + * An execution, seen from the client: wait for its result, send it signals and updates, query its + * state. Handlers are addressed by method reference, so renaming a handler is a compile error at + * every call site. + */ +public final class WorkflowHandle { + + // the Conductor this handle came from: its client, the factories of the workflow classes it + // hosts (for query), and the one thread that waits for results, which close() stops + private final Conductor conductor; + private final WorkflowClient workflows; + private final String workflowId; + private final Type resultType; + + WorkflowHandle(Conductor conductor, String workflowId, Type resultType) { + this.conductor = conductor; + this.workflows = new WorkflowClient(conductor.client()); + this.workflowId = workflowId; + this.resultType = resultType; + } + + public String workflowId() { + return workflowId; + } + + /** The execution's status now. */ + public WorkflowStatus status() { + return execution(false).getStatus(); + } + + /** + * Waits for the execution to finish and returns its result. Throws {@link + * WorkflowFailedException} when it ended without completing, and {@link + * WorkflowTimeoutException} when it is still going after {@code timeout}; the execution keeps + * running. + */ + public R result(Duration timeout) { + CompletableFuture result = resultAsync(); + try { + return result.get(timeout.toMillis(), TimeUnit.MILLISECONDS); + } catch (TimeoutException e) { + result.cancel(false); + throw new WorkflowTimeoutException(workflowId, status(), timeout); + } catch (ExecutionException e) { + throw e.getCause() instanceof RuntimeException cause ? cause : new IllegalStateException(e.getCause()); + } catch (InterruptedException e) { + result.cancel(false); + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } + + /** + * The result as a future, completed when the execution finishes: with the workflow method's + * return value, or exceptionally with a {@link WorkflowFailedException}. For waiting on many + * executions at once, or composing with other futures: + * + *

{@code
+     * CompletableFuture a = conductor.start(Order::process, first).resultAsync();
+     * CompletableFuture b = conductor.start(Order::process, second).resultAsync();
+     * CompletableFuture.allOf(a, b).orTimeout(2, TimeUnit.MINUTES).join();
+     * }
+ * + * One thread per {@link Conductor} checks every pending future, and a server that is + * restarting is waited out. Cancelling the future only stops waiting: the execution keeps + * running. Closing the Conductor cancels the futures still waiting. + */ + public CompletableFuture resultAsync() { + return conductor.whenFinished(() -> { + Workflow execution; + try { + execution = workflows.getWorkflow(workflowId, false); + } catch (RuntimeException e) { + if (Http.isRefusal(e)) { + throw e; // no such execution, for one: it will not finish + } + return null; // a restarting server: check again + } + return execution.getStatus().isTerminal() ? execution : null; + }, this::outcome); + } + + /** The result of a finished execution, or the failure it ended with. */ + @SuppressWarnings("unchecked") + private R outcome(Workflow execution) { + if (execution.getStatus() == WorkflowStatus.COMPLETED) { + return (R) Json.decodeOutput(execution.getOutput(), resultType); + } + throw new WorkflowFailedException(workflowId, execution.getStatus(), execution.getReasonForIncompletion()); + } + + 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. A class this {@code + * Conductor} hosts with a factory ({@code workflows(Type.class, factory)}) is made by that + * factory. + */ + @SuppressWarnings("unchecked") + public V query(Fn0 handler) { + Method m = MethodRefs.resolve(handler); + name(handler, Query.class); // checks the annotation + WorkflowSpec spec = conductor.hostedSpec(m.getDeclaringClass()) + .orElseGet(() -> WorkflowSpec.of(m.getDeclaringClass()).get(0)); + Map variables = execution(false).getVariables(); + Object instance = spec.newInstance(); + spec.restoreVariables(instance, variables == null ? Map.of() : variables); + Object value = Replayer.invokeHandler(instance, m, null); + return (V) Json.convert(Json.plain(value), m.getGenericReturnType()); + } + + /** + * 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. + */ + public void completeTask(String taskReferenceName, Object output, Duration timeout) { + long deadline = System.currentTimeMillis() + timeout.toMillis(); + while (true) { + Workflow execution = execution(true); + boolean pending = execution.getTasks().stream().anyMatch(t -> taskReferenceName.equals(t.getReferenceTaskName()) + && (t.getStatus() == Task.Status.IN_PROGRESS || t.getStatus() == Task.Status.SCHEDULED)); + if (pending) { + TaskClient tasks = new TaskClient(conductor.client()); + Http.retrying(() -> { + tasks.updateTask(workflowId, taskReferenceName, TaskResult.Status.COMPLETED, Json.encodeOutput(output)); + return null; + }); + return; + } + if (execution.getStatus().isTerminal()) { + 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 = 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)); + } + Http.retrying(() -> Http.post(conductor.client(), "/workflow/" + workflowId + "/messages", message, String.class)); + return id; + } + + private Object awaitReply(String messageId) { + long deadline = System.currentTimeMillis() + Duration.ofMinutes(3).toMillis(); + while (System.currentTimeMillis() < deadline) { + Workflow execution = execution(false); + Map replies = execution.getNativeState() == null ? Map.of() : execution.getNativeState().getReplies(); + if (replies.get(messageId) instanceof Map reply) { + if (reply.containsKey("error")) { + throw new IllegalStateException("handler failed: " + reply.get("error")); + } + return reply.get("value"); + } + if (execution.getStatus().isTerminal()) { + // the handler lane is gone: no reply will ever come + throw new IllegalStateException("workflow " + workflowId + " ended with status " + execution.getStatus() + + " before replying to message " + messageId); + } + sleep(200); + } + throw new IllegalStateException("no reply to message " + messageId + " within 3 minutes; is the workflow's host running?"); + } + + private Workflow execution(boolean includeTasks) { + return Http.retrying(() -> workflows.getWorkflow(workflowId, includeTasks)); + } + + private static String name(Serializable handler, Class kind) { + Method m = MethodRefs.resolve(handler); + 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/WorkflowTimeoutException.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/WorkflowTimeoutException.java new file mode 100644 index 000000000..5eeca2719 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/WorkflowTimeoutException.java @@ -0,0 +1,43 @@ +/* + * 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 com.netflix.conductor.common.run.Workflow.WorkflowStatus; + +/** + * Thrown to a client that waited for an execution's result longer than it was willing to: the + * execution is still going and keeps running. An {@link IllegalStateException}, as before this + * type existed. + */ +public class WorkflowTimeoutException extends IllegalStateException { + + private final String workflowId; + private final WorkflowStatus status; + + public WorkflowTimeoutException(String workflowId, WorkflowStatus status, Duration waited) { + super("execution " + workflowId + " still " + status + " after " + waited); + this.workflowId = workflowId; + this.status = status; + } + + public String getWorkflowId() { + return workflowId; + } + + /** What the execution was doing when the wait ended: RUNNING or PAUSED. */ + public WorkflowStatus getStatus() { + return status; + } +} 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..f6c71e305 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/CodeLoops.java @@ -0,0 +1,345 @@ +/* + * 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.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.Deque; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.InvokeDynamicInsnNode; +import org.objectweb.asm.tree.JumpInsnNode; +import org.objectweb.asm.tree.LineNumberNode; +import org.objectweb.asm.tree.LookupSwitchInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.TableSwitchInsnNode; + +/** + * 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. A {@code doWhile} names its loop instead: every call made from its + * body or condition is in it. + */ +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<>(); + + /** + * The {@code doWhile} loops running on this thread, by the compiled method of each body and + * condition (class, method name and descriptor), innermost last. + */ + private static final ThreadLocal>> NAMED = ThreadLocal.withInitial(HashMap::new); + + private CodeLoops() {} + + /** A {@code doWhile} that is running; {@link #leave()} when it ends. */ + public static final class Named { + private final List keys; + + private Named(List keys) { + this.keys = keys; + } + + public void leave() { + Map> named = NAMED.get(); + for (String key : keys) { + Deque names = named.get(key); + if (names != null) { + names.pollLast(); + if (names.isEmpty()) { + named.remove(key); + } + } + } + } + } + + /** Every call made from these lambdas, on this thread, is in the loop {@code name} until it leaves. */ + public static Named enter(String name, Serializable... code) { + List keys = new ArrayList<>(); + for (Serializable c : code) { + try { + MethodRefs.Implementation impl = MethodRefs.implementation(c); + String key = impl.owner().replace('/', '.') + "#" + impl.name() + impl.descriptor(); + NAMED.get().computeIfAbsent(key, k -> new ArrayDeque<>()).addLast(name); + keys.add(key); + } catch (RuntimeException e) { + // loops only draw the diagram; never fail a workflow over one + } + } + return new Named(keys); + } + + /** The named loop a method runs in, if it is the body or condition of a running {@code doWhile}. */ + private static List named(Class type, String method, String descriptor) { + Deque names = NAMED.get().get(type.getName() + "#" + method + descriptor); + return names == null || names.isEmpty() ? List.of() : List.of(names.peekLast()); + } + + /** 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<>(named(frame.getDeclaringClass(), frame.getMethodName(), frame.getDescriptor())); + 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<>(named(type, method, descriptor)); + for (Loop loop : loopsOf(type, method, descriptor)) { + if (loop.first <= line && line <= loop.last) { + ids.add(loop.id); + } + } + return ids; + } + + /** The loops of a method read from its bytecode around a line, outermost first. */ + public static List around(MethodNode method, String className, int line) { + List ids = new ArrayList<>(); + for (Loop loop : loops(method, className)) { + 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(); + } + + /** + * The last line of the code right after a loop's conditional jump back, when that code ends by + * jumping to where the loop's own condition (a jump forward on the loop's first line) exits; 0 + * when it does not. + */ + private static int armAfter(InsnList code, int head, int at, int firstLine) { + Set exits = new HashSet<>(); + int line = 0; + for (int i = head; i <= at; i++) { + AbstractInsnNode insn = code.get(i); + if (insn instanceof LineNumberNode n) { + line = n.line; + } else if (insn instanceof JumpInsnNode j && j.getOpcode() != Opcodes.GOTO && line == firstLine + && code.indexOf(j.label) > at) { + exits.add(code.indexOf(j.label)); + } + } + if (exits.isEmpty()) { + return 0; + } + // only code the loop itself goes on to: the jump back falling through to it, or a jump from + // inside the loop to it, and nothing from outside (a switch's next case also follows a loop) + Set start = new HashSet<>(); + for (int i = at + 1; i < code.size(); i++) { + start.add(i); + if (code.get(i).getOpcode() >= 0) { + break; + } + } + boolean fromInside = code.get(at).getOpcode() != Opcodes.GOTO; + boolean fromOutside = false; + for (int i = 0; i < code.size(); i++) { + for (int t : jumpTargets(code, code.get(i))) { + if (start.contains(t)) { + if (i >= head && i <= at) { + fromInside = true; + } else { + fromOutside = true; + } + } + } + } + if (!fromInside || fromOutside) { + return 0; + } + // the arm: what runs from just after the jump back, without going back into the loop + int last = 0; + boolean out = false; + ArrayDeque todo = new ArrayDeque<>(List.of(at + 1)); + Set seen = new HashSet<>(); + while (!todo.isEmpty()) { + int i = todo.pop(); + if (i <= at || i >= code.size() || !seen.add(i)) { + continue; + } + if (exits.contains(i)) { + out = true; + continue; + } + AbstractInsnNode insn = code.get(i); + if (insn instanceof LineNumberNode n) { + last = Math.max(last, n.line); + } + int op = insn.getOpcode(); + if ((op >= Opcodes.IRETURN && op <= Opcodes.RETURN) || op == Opcodes.ATHROW) { + continue; + } + if (insn instanceof JumpInsnNode j) { + todo.push(code.indexOf(j.label)); + if (op == Opcodes.GOTO) { + continue; + } + } else if (insn instanceof TableSwitchInsnNode t) { + todo.push(code.indexOf(t.dflt)); + t.labels.forEach(l -> todo.push(code.indexOf(l))); + continue; + } else if (insn instanceof LookupSwitchInsnNode l) { + todo.push(code.indexOf(l.dflt)); + l.labels.forEach(x -> todo.push(code.indexOf(x))); + continue; + } + todo.push(i + 1); + } + return out ? last : 0; + } + + private static List jumpTargets(InsnList code, AbstractInsnNode insn) { + List out = new ArrayList<>(); + if (insn instanceof JumpInsnNode j) { + out.add(code.indexOf(j.label)); + } else if (insn instanceof TableSwitchInsnNode t) { + out.add(code.indexOf(t.dflt)); + t.labels.forEach(l -> out.add(code.indexOf(l))); + } else if (insn instanceof LookupSwitchInsnNode l) { + out.add(code.indexOf(l.dflt)); + l.labels.forEach(x -> out.add(code.indexOf(x))); + } + return out; + } + + /** + * Whether code at {@code head} is a pattern switch's dispatch: a guard that fails jumps back to + * it to try the next case, which is no loop in the code. + */ + private static boolean restartsAPatternSwitch(InsnList code, int head) { + for (int i = head; i < code.size(); i++) { + AbstractInsnNode insn = code.get(i); + if (insn instanceof InvokeDynamicInsnNode indy) { + return indy.bsm.getOwner().equals("java/lang/runtime/SwitchBootstraps"); + } + if (insn instanceof JumpInsnNode || insn instanceof TableSwitchInsnNode + || insn instanceof LookupSwitchInsnNode + || insn instanceof MethodInsnNode) { + return false; + } + } + return false; + } + + /** 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 + && !restartsAPatternSwitch(code, code.indexOf(jump.label))) { + // the line in effect at the loop's start (a for-each's hasNext has no line entry of + // its own: its line is the one its iterator() call started) + int first = Integer.MAX_VALUE; + int head = code.indexOf(jump.label); + for (int i = head; i < code.size() && code.get(i).getOpcode() < 0; i++) { + if (code.get(i) instanceof LineNumberNode line) { + first = line.line; // the loop's own line, given right at its start + break; + } + } + for (int i = head; first == Integer.MAX_VALUE && i >= 0; i--) { + if (code.get(i) instanceof LineNumberNode line) { + first = line.line; + } + } + 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) { + // an arm after the last jump back that ends by breaking out (`if (c) { ...; break; }` + // or an else that breaks, last in a loop): it jumps to where the loop's condition + // exits, so it is in the loop + last = Math.max(last, armAfter(code, code.indexOf(jump.label), at, first)); + } + 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..57871afe7 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/CodeReader.java @@ -0,0 +1,2375 @@ +/* + * 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.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.BitSet; +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.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.IntPredicate; +import java.util.function.Predicate; + +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.FieldNode; +import org.objectweb.asm.tree.InsnNode; +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 FUTURE = "java/util/concurrent/Future"; + private static final String AGENT_CALL = SDK + "AgentCall"; + 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 {} + + /** + * Steps inside plain Java loops ({@code for}, {@code while}, {@code do}), named as the + * execution tags them ({@code _loop_}, outermost first). Code repeats them; + * the definition shows them grouped, as the execution does. + */ + public record InLoops(List loops, List steps, 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; {@code at} is the instruction + * that decides and {@code region} the instructions of its arms. + */ + public record Branch(String name, int line, int lastLine, List arms, String site, int at, BitSet region) { + /** 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}, of the same method, lies inside one of this branch's arms. */ + public boolean contains(Branch other) { + return other != this && region.get(other.at); + } + + 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, Paths paths) { + static final Shape NONE = new Shape(List.of(), List.of(), Set.of(), Paths.NONE); + } + + /** A branch the code went through between two calls, and the arm it took. */ + public record Passed(Branch branch, Arm arm) {} + + /** + * The ways through one method's instructions, to tell which ifs and switches the code must have + * gone through between two calls it made, and how. + */ + public static final class Paths { + static final Paths NONE = new Paths(new int[0], new int[0][], new boolean[0], new boolean[0], new boolean[0], Map.of(), Map.of(), Map.of()); + + private final int[] lineAt; + private final int[][] succ; + private final int[][] pred; + private final boolean[] step; + private final boolean[] returns; + private final boolean[] throwsAt; + /** Each branch by the instruction that decides, with the instructions of its condition. */ + private final Map branches; + private final Map condition; + /** The arm each instruction a decision can jump to starts, by the deciding instruction. */ + private final Map> armAt; + + Paths(int[] lineAt, int[][] succ, boolean[] step, boolean[] returns, boolean[] throwsAt, Map branches, + Map condition, Map> armAt) { + this.lineAt = lineAt; + this.succ = succ; + this.step = step; + this.returns = returns; + this.throwsAt = throwsAt; + this.branches = branches; + this.condition = condition; + this.armAt = armAt; + List> p = new ArrayList<>(); + for (int i = 0; i < succ.length; i++) { + p.add(new ArrayList<>()); + } + for (int i = 0; i < succ.length; i++) { + for (int t : succ[i]) { + if (t < succ.length) { + p.get(t).add(i); + } + } + } + this.pred = new int[succ.length][]; + for (int i = 0; i < succ.length; i++) { + pred[i] = p.get(i).stream().mapToInt(Integer::intValue).toArray(); + } + } + + /** + * The branches every way from the call made on {@code fromLine} (0: the start of the + * method) to the call made on {@code toLine} (-1: a return) goes through exactly once, + * taking one arm only, without making another call: in the order the code reaches them. + */ + public List passed(int fromLine, int toLine) { + int n = succ.length; + if (n == 0) { + return List.of(); + } + List sources = new ArrayList<>(); + boolean[] target = new boolean[n]; + boolean anyStep = false; + for (int i = 0; i < n; i++) { + if (fromLine > 0 && step[i] && lineAt[i] == fromLine) { + for (int t : succ[i]) { + sources.add(t); + } + } + target[i] = toLine < 0 ? returns[i] : step[i] && lineAt[i] == toLine; + anyStep |= target[i]; + } + if (toLine > 0 && !anyStep) { + for (int i = 0; i < n; i++) { + target[i] = throwsAt[i] && lineAt[i] == toLine; // the code threw there instead of calling + } + } + if (fromLine <= 0) { + sources.add(0); + } + // forward from the call, stopping at any other call; then back from the next call + boolean[] fwd = new boolean[n]; + int[] depth = new int[n]; + Arrays.fill(depth, Integer.MAX_VALUE); + ArrayDeque todo = new ArrayDeque<>(); + boolean[] reached = new boolean[n]; + for (int s : sources) { + if (s < n && depth[s] == Integer.MAX_VALUE) { + depth[s] = 0; + todo.add(s); + } + } + while (!todo.isEmpty()) { + int i = todo.poll(); + if (target[i]) { + reached[i] = true; + continue; + } + if (step[i] || fwd[i]) { + continue; + } + fwd[i] = true; + for (int t : succ[i]) { + if (t < n && depth[t] == Integer.MAX_VALUE) { + depth[t] = depth[i] + 1; + } + if (t < n && !fwd[t]) { + todo.add(t); + } + } + } + boolean[] rel = new boolean[n]; + for (int i = 0; i < n; i++) { + if (reached[i]) { + todo.add(i); + } + } + while (!todo.isEmpty()) { + int i = todo.poll(); + for (int p : pred[i]) { + if (fwd[p] && !rel[p]) { + rel[p] = true; + todo.add(p); + } + } + } + List out = new ArrayList<>(); + List order = new ArrayList<>(); + for (Map.Entry e : branches.entrySet()) { + int[] cond = condition.get(e.getKey()); + boolean[] in = new boolean[n]; + boolean touched = false; + for (int i : cond) { + in[i] = true; + touched |= rel[i]; + } + if (!touched || reaches(sources, target, rel, in) || loopsBack(cond, rel, in)) { + continue; // a way avoids it, or goes round to it again + } + Arm only = null; + boolean unknown = false; + for (int x : cond) { + for (int y : succ[x]) { + if (y >= n || in[y] || !(rel[y] || target[y])) { + continue; + } + Arm arm = armAt.get(e.getKey()).get(y); + if (arm == null || (only != null && only != arm)) { + unknown = true; + } + only = arm; + } + } + if (!unknown && only != null) { + out.add(new Passed(e.getValue(), only)); + order.add(depth[cond[0]]); + } + } + List idx = new ArrayList<>(); + for (int k = 0; k < out.size(); k++) { + idx.add(k); + } + idx.sort(Comparator.comparingInt(order::get)); + List sorted = new ArrayList<>(); + idx.forEach(k -> sorted.add(out.get(k))); + return sorted; + } + + /** + * Whether every way from the call on {@code fromLine} to the call on {@code toLine}, without + * another call, goes through the decision of {@code branch}: the code decided it again. + */ + public boolean decidesAgain(int fromLine, int toLine, Branch branch) { + int n = succ.length; + Integer at = null; + for (Map.Entry e : branches.entrySet()) { + if (e.getValue() == branch) { + at = e.getKey(); + } + } + if (at == null || n == 0) { + return false; + } + List sources = new ArrayList<>(); + boolean[] target = callAt(toLine); + boolean any = false; + for (int i = 0; i < n; i++) { + if (step[i] && lineAt[i] == fromLine) { + for (int t : succ[i]) { + sources.add(t); + } + } + any |= target[i]; + } + if (sources.isEmpty() || !any) { + return false; + } + boolean[] all = new boolean[n]; + for (int i = 0; i < n; i++) { + all[i] = !step[i] || target[i]; + } + int[] cond = condition.get(at); + boolean[] in = new boolean[n]; + for (int i : cond) { + in[i] = true; + } + return !reaches(sources, target, all, in) && reaches(sources, target, all, new boolean[n]); + } + + /** + * Whether some way from the call on {@code fromLine} to the call on {@code toLine}, without + * another call, goes through the decision of {@code branch}: the code may have decided it + * again in between. + */ + public boolean mayDecideAgain(int fromLine, int toLine, Branch branch) { + int n = succ.length; + Integer at = null; + for (Map.Entry e : branches.entrySet()) { + if (e.getValue() == branch) { + at = e.getKey(); + } + } + if (at == null || n == 0) { + return false; + } + List sources = new ArrayList<>(); + boolean[] target = callAt(toLine); + for (int i = 0; i < n; i++) { + if (step[i] && lineAt[i] == fromLine) { + for (int t : succ[i]) { + sources.add(t); + } + } + } + int[] cond = condition.get(at); + boolean[] all = new boolean[n]; + for (int i = 0; i < n; i++) { + all[i] = !step[i] || target[i]; + } + // from the call to the decision, and from the decision on to the next call + boolean[] atDecision = new boolean[n]; + atDecision[cond[0]] = true; + boolean[] noCall = new boolean[n]; + for (int i = 0; i < n; i++) { + noCall[i] = !step[i]; // on the way to the decision, the next call is not passed either + } + if (!reaches(sources, atDecision, noCall, new boolean[n])) { + return false; + } + boolean[] in = new boolean[n]; + for (int i : cond) { + in[i] = true; + } + List after = new ArrayList<>(); + for (int x : cond) { + for (int y : succ[x]) { + if (y < n && !in[y]) { + after.add(y); + } + } + } + return reaches(after, target, all, new boolean[n]); + } + + /** + * Whether the code can get from the call on {@code fromLine} to the call on {@code toLine} + * without another call, staying in one invocation of the method. + */ + public boolean reachable(int fromLine, int toLine) { + int n = succ.length; + List sources = new ArrayList<>(); + boolean[] target; + boolean[] noCall = new boolean[n]; + for (int i = 0; i < n; i++) { + if (step[i] && lineAt[i] == fromLine) { + for (int t : succ[i]) { + sources.add(t); + } + } + noCall[i] = !step[i]; + } + target = callAt(toLine); + return reaches(sources, target, noCall, new boolean[n]); + } + + /** Where a call on {@code toLine} is: its calls, or, when the code threw there instead, its throw. */ + private boolean[] callAt(int toLine) { + int n = succ.length; + boolean[] target = new boolean[n]; + boolean any = false; + for (int i = 0; i < n; i++) { + target[i] = step[i] && lineAt[i] == toLine; + any |= target[i]; + } + if (!any) { + for (int i = 0; i < n; i++) { + target[i] = throwsAt[i] && lineAt[i] == toLine; + } + } + return target; + } + + /** Whether some way from the sources reaches a target without touching the excluded instructions. */ + private boolean reaches(List sources, boolean[] target, boolean[] rel, boolean[] excluded) { + boolean[] seen = new boolean[succ.length]; + ArrayDeque todo = new ArrayDeque<>(sources); + while (!todo.isEmpty()) { + int i = todo.poll(); + if (i >= succ.length || excluded[i] || seen[i]) { + continue; + } + if (target[i]) { + return true; + } + if (!rel[i]) { + continue; + } + seen[i] = true; + for (int t : succ[i]) { + todo.add(t); + } + } + return false; + } + + /** Whether the code can come round from a decision to the same decision without a call. */ + private boolean loopsBack(int[] cond, boolean[] rel, boolean[] in) { + boolean[] seen = new boolean[succ.length]; + ArrayDeque todo = new ArrayDeque<>(); + for (int x : cond) { + for (int y : succ[x]) { + if (y < succ.length && !in[y]) { + todo.add(y); + } + } + } + while (!todo.isEmpty()) { + int i = todo.poll(); + if (i >= succ.length || seen[i] || !rel[i]) { + continue; + } + if (in[i]) { + return true; + } + seen[i] = true; + for (int t : succ[i]) { + todo.add(t); + } + } + return false; + } + } + + 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 each method, or code it calls, reads a random source or the clock directly. */ + private static final Map> RAW_SOURCES = new ConcurrentHashMap<>(); + + /** + * A place where workflow code asks the JVM itself for a random value or the time: the call, + * where it is ({@code Class.method:line}) and what records the value instead. + */ + public record RawSource(String site, String call, String replacement) {} + + /** + * 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()); + } + + /** + * Where a workflow method, or a lambda or helper it calls, reads a random source or the clock + * directly ({@code Math.random()}, {@code Instant.now()}, {@code UUID.randomUUID()} and the + * like). Plain Java runs again on every replay, so such a call can give another value there + * and take the code down another path than the execution recorded. The lambda given to + * {@code once(..)} is not read (its value is recorded), nor are task methods and handlers, + * which are not replayed; helpers outside the workflow class's package are not followed. + * + * @throws IllegalStateException when the compiled code cannot be read + */ + public static List rawSources(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 (IllegalStateException e) { + throw e; + } catch (RuntimeException e) { + throw new IllegalStateException("cannot read " + method.getDeclaringClass().getName() + "." + method.getName(), e); + } + return RAW_SOURCES.getOrDefault(key, List.of()); + } + + private static final String RANDOM = "Conductor.random()"; + private static final String CLOCK = "Conductor.now()"; + private static final Set NOW_TYPES = Set.of("Instant", "LocalDate", "LocalTime", "LocalDateTime", + "ZonedDateTime", "OffsetDateTime", "OffsetTime", "Year", "YearMonth", "MonthDay"); + + /** The call and its replacement when a method is a random source or a clock read; else null. */ + private static String[] rawSource(String owner, String name, String desc) { + boolean noArgs = desc.startsWith("()"); + switch (owner) { + case "java/lang/Math", "java/lang/StrictMath" -> { + return name.equals("random") ? new String[] {"Math.random()", RANDOM} : null; + } + case "java/util/Random", "java/util/SplittableRandom" -> { + // with a seed it gives the same numbers on every replay + return name.equals("") && noArgs + ? new String[] {"new " + owner.substring(owner.lastIndexOf('/') + 1) + "()", RANDOM} : null; + } + case "java/security/SecureRandom" -> { + return name.equals("") || name.startsWith("getInstance") ? new String[] {"SecureRandom", RANDOM} : null; + } + case "java/util/concurrent/ThreadLocalRandom" -> { + return name.equals("current") ? new String[] {"ThreadLocalRandom.current()", RANDOM} : null; + } + case "java/util/random/RandomGenerator" -> { + return name.equals("getDefault") || name.equals("of") ? new String[] {"RandomGenerator." + name + "(..)", RANDOM} : null; + } + case "java/util/UUID" -> { + return name.equals("randomUUID") + ? new String[] {"UUID.randomUUID()", "Conductor.once(name, () -> UUID.randomUUID())"} : null; + } + case "java/lang/System" -> { + return name.equals("currentTimeMillis") || name.equals("nanoTime") ? new String[] {"System." + name + "()", CLOCK} : null; + } + case "java/time/Clock" -> { + return name.startsWith("system") || name.equals("tickSeconds") || name.equals("tickMinutes") || name.equals("tickMillis") + ? new String[] {"Clock." + name + "(..)", CLOCK} : null; + } + case "java/util/Date", "java/util/GregorianCalendar" -> { + return name.equals("") && noArgs + ? new String[] {"new " + owner.substring(owner.lastIndexOf('/') + 1) + "()", CLOCK} : null; + } + case "java/util/Calendar" -> { + return name.equals("getInstance") ? new String[] {"Calendar.getInstance(..)", CLOCK} : null; + } + default -> { + // Instant.now() and now(zone) read the system clock; now(clock) reads the one it is given + if (owner.startsWith("java/time/") && name.equals("now") && !desc.startsWith("(Ljava/time/Clock;") + && NOW_TYPES.contains(owner.substring("java/time/".length()))) { + return new String[] {owner.substring("java/time/".length()) + ".now()", CLOCK}; + } + return null; + } + } + } + + 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 LinkedHashSet<>(reading.sleeps))); + RAW_SOURCES.put(key, List.copyOf(new LinkedHashSet<>(reading.rawSources))); + 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; + } + + /** + * A decision that may be drawn: the instruction that decides, its line, one past the last + * instruction of its arms, each arm's key, which arm is the default, the instructions of its + * condition, the arm each place the condition goes on to starts, each arm's code and first + * instruction, and all its instructions. + */ + private record Candidate(int b, int line, String name, int end, List keys, int otherwise, + int[] condition, Map exitArm, List regions, List entries, boolean[] covers) { + int extent() { + return end; + } + } + + /** 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<>(); + /** The arm that starts at each instruction a branch's decision can jump to, by the instruction that decides. */ + private final Map> armStarts = new HashMap<>(); + /** The instructions of each drawn branch's condition, by the instruction that decides. */ + private final Map conditions = new HashMap<>(); + /** Thread.sleep calls in this method and in the code it calls. */ + private final List sleeps = new ArrayList<>(); + /** Random sources and clock reads in this method and in the code it calls. */ + private final List rawSources = 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; + } + // first, where the steps are: what decisions and loops are depends on it + consumeLambdas(); + readRange(0, insns.length); + steps.clear(); + branches.clear(); + unjoined = 0; + seenInFinally.clear(); + sleeps.clear(); + rawSources.clear(); + 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 + boolean[] arm = null; + int armSize = Integer.MAX_VALUE; + for (Candidate c : candidates.values()) { + for (boolean[] r : c.regions()) { + int size = 0; + for (boolean x : r) { + size += x ? 1 : 0; + } + if (r[pos] && size < armSize) { + around = c; + arm = r; + armSize = size; + } + } + } + if (around == null) { + readRange(pos, insns.length); + break; + } + boolean[] rest = new boolean[insns.length]; + for (int i = pos; i < insns.length; i++) { + rest[i] = arm[i]; + } + readIn(rest); + 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) { + boolean[] in = new boolean[insns.length]; + for (int i = Math.max(0, from); i < Math.min(to, insns.length); i++) { + in[i] = true; + } + readIn(in); + } + + /** Reads the instructions in the set, in order, adding their steps: an if or switch in it as a whole. */ + private void readIn(boolean[] in) { + boolean[] done = new boolean[insns.length]; + for (int i = 0; i < insns.length; i++) { + if (!in[i] || done[i]) { + continue; + } + AbstractInsnNode insn = insns[i]; + line = lineAt[i]; + if (frames[i] == null) { + continue; // unreachable + } + current = i; + Candidate candidate = candidates.get(i); + if (candidate != null && within(candidate.covers(), in) && branch(candidate)) { + for (int k = 0; k < insns.length; k++) { + done[k] |= candidate.covers()[k]; + } + 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())); + rawSourcesOf(h.getOwner(), h.getName(), h.getDesc()); + } else if (insn instanceof MethodInsnNode m) { + if (CONDUCTOR.equals(m.owner) && m.getOpcode() == Opcodes.INVOKESTATIC) { + sdkCall(i, m); + } else if (FUTURE.equals(m.owner) && m.name.equals("get")) { + joinPoint(); + } else if (AGENT_CALL.equals(m.owner) && m.name.equals("ask")) { + // each ask is an AGENT task, named by the agent(..) that made the conversation + call(withDefinition(step(Command.Kind.AGENT, agentRef(i)), 3)); + } 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 (rawSource(m.owner, m.name, m.desc) != null) { + rawSourcesOf(m.owner, m.name, m.desc); + } else if (!m.name.equals("") && inScope(m.owner)) { + if (active.contains(key(m.owner, m.name, m.desc))) { + stepAt.add(i); // a recursive call: into code that calls the server (when any does) + } + add(walk(m.owner, m.name, m.desc, active)); + sleeps.addAll(SLEEPS.getOrDefault(key(m.owner, m.name, m.desc), List.of())); + rawSourcesOf(m.owner, m.name, m.desc); + } + } + } + } + + private boolean within(boolean[] part, boolean[] whole) { + for (int k = 0; k < part.length; k++) { + if (part[k] && !whole[k] && frames[k] != null && insns[k].getOpcode() >= 0) { + return false; + } + } + return true; + } + + private void add(List more) { + if (!more.isEmpty()) { + stepAt.add(current); + flushFork(false); + steps.addAll(inLoops(more)); + } + } + + /** The steps, inside the loops of this method around the current line, if any. */ + private List inLoops(List more) { + List loops = CodeLoops.around(method, owner.substring(owner.lastIndexOf('/') + 1), line); + return loops.isEmpty() ? more : List.of(new InLoops(loops, List.copyOf(more), site())); + } + + /** 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.addAll(inLoops(List.of(new Fork(List.copyOf(branches), joined, site())))); + if (!joined) { + unjoined++; + } + } + branches.clear(); + } + + private void call(Command command) { + if (hasFinally && !seenInFinally.add(line + ":" + command.name)) { + stepAt.add(current); // a copy of a finally block: drawn once, yet a call wherever it runs + 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 (boolean[] region : c.regions()) { + List savedSteps = new ArrayList<>(steps); + List> savedForks = new ArrayList<>(branches); + int savedUnjoined = unjoined; + steps.clear(); + branches.clear(); + readIn(region); + 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 || c.regions().size() < 2) { + return false; // nothing to show, or only a default: the code always goes the same way + } + line = c.line(); + int last = line; + List arms = new ArrayList<>(); + for (int k = 0; k < c.regions().size(); k++) { + boolean[] region = c.regions().get(k); + Set lines = new TreeSet<>(); + for (int i = 0; i < insns.length; i++) { + if (region[i] && frames[i] != null && insns[i].getOpcode() >= 0) { + last = Math.max(last, lineAt[i]); + if (stepAt.contains(i) || (sitesFrom(insns[i]) && onlyIn(lineAt[i], region))) { + lines.add(lineAt[i]); // a call, or a throw or helper the code may fail in + } + } + } + arms.add(new Arm(c.keys().get(k), k == c.otherwise(), Collections.unmodifiableSet(lines), armSteps.get(k), + canSkip(region, c.entries().get(k)), loopsIn(region))); + } + BitSet region = new BitSet(); + for (boolean[] r : c.regions()) { + for (int i = 0; i < r.length; i++) { + if (r[i]) { + region.set(i); + } + } + } + Branch b = new Branch(c.name(), c.line(), last, List.copyOf(arms), site(), c.b(), region); + found.put(c.b(), b); + Map starts = new HashMap<>(); + c.exitArm().forEach((at, k) -> starts.put(at, arms.get(k))); + armStarts.put(c.b(), starts); + conditions.put(c.b(), c.condition()); + flushFork(false); + steps.addAll(inLoops(List.of(b.decision()))); + return true; + } + + /** Whether the code can fail at the instruction: a throw, or any call. */ + private boolean sitesFrom(AbstractInsnNode insn) { + return insn.getOpcode() == Opcodes.ATHROW || isCall(insn); + } + + /** Whether all the code on {@code line} is in the region. */ + private boolean onlyIn(int line, boolean[] region) { + for (int i = 0; i < insns.length; i++) { + if (frames[i] != null && insns[i].getOpcode() >= 0 && lineAt[i] == line && !region[i]) { + return false; + } + } + 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())); + boolean[] all = new boolean[insns.length]; + Arrays.fill(all, true); + return new Shape(List.copyOf(sorted), loopsIn(all), Collections.unmodifiableSet(returns), paths()); + } + + /** The ways through the method's instructions, for {@link Paths#passed}. */ + private Paths paths() { + int n = insns.length; + int[][] succ = new int[n][]; + boolean[] step = new boolean[n]; + boolean[] returns = new boolean[n]; + boolean[] throwsAt = new boolean[n]; + for (int i = 0; i < n; i++) { + succ[i] = frames[i] == null ? new int[0] : successors(i).stream().mapToInt(Integer::intValue).toArray(); + step[i] = stepAt.contains(i); + int op = insns[i].getOpcode(); + returns[i] = frames[i] != null && op >= Opcodes.IRETURN && op <= Opcodes.RETURN; + throwsAt[i] = frames[i] != null && op == Opcodes.ATHROW; + } + Map condition = new HashMap<>(conditions); + return new Paths(lineAt.clone(), succ, step, returns, throwsAt, new TreeMap<>(found), condition, new HashMap<>(armStarts)); + } + + /** Whether the code can go from {@code from} out of the range without making a call. */ + private boolean canSkip(boolean[] region, int from) { + ArrayDeque todo = new ArrayDeque<>(List.of(from)); + Set seen = new HashSet<>(); + while (!todo.isEmpty()) { + int i = todo.pop(); + if (i >= insns.length || !region[i] || 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 region, as their first and last line: a backward jump closes one. */ + private List loopsIn(boolean[] region) { + List loops = new ArrayList<>(); + for (int i = 0; i < insns.length; i++) { + if (region[i] && frames[i] != null && insns[i] instanceof JumpInsnNode j && index(j.label) <= i + && region[index(j.label)] && realBackEdge(i, index(j.label))) { + 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); + } + + // ------------------------------------------------------------ control flow + // + // The rules, written once (design/native-workflows/README.md, "How plain Java control flow + // is drawn"): + // - a loop is a natural loop: a jump back to an instruction every way to the jump passes + // first. A loop that goes round a step is a real loop; one that does not is plain code. + // - a decision is a switch, or the jumps of one condition (`a && b` is one jump per operand). + // Its condition is what it can come round to without a step (a failed `when` guard goes + // back to the switch), and its outcomes are the places the condition goes on to. + // - a loop's condition is its own, not a decision: the jump out of it that the straight + // code from its head comes to, or the jump back that closes it. Any other jump out of + // a loop is a break, and the if around it a decision. + // - an arm holds what runs only because its outcome was taken: the code every way to which + // goes through that outcome, without leaving the loop the decision is in. + // - a decision is drawn when an arm holds a step, the arms take up all the code from the + // decision to where they meet, and every line with a step is in one arm or in none. + + /** Every way on from each instruction, without (flow) and with (flowAll) the ways into catch handlers. */ + private int[][] flow; + private int[][] flowAll; + private int[][] backAll; + /** Instructions code jumps to or a handler starts at: where a block of straight code starts. */ + private boolean[] entered; + /** The natural loops, and which of them go round a step. */ + private final List naturalLoops = new ArrayList<>(); + + /** + * A natural loop: its head, the code that goes round to it, the jumps back, whether it goes + * round a step, and its extent: what runs from its head before its follow, the one place + * every way out of it leads to (all of the code after it when there is no such place). + */ + private record NaturalLoop(int head, boolean[] body, Set backFrom, boolean real, boolean[] extent, int size) { + boolean spans(int i) { + return extent[i]; + } + } + + private interface Edge { + boolean ok(int from, int to); + } + + private void buildFlow() { + int n = insns.length; + List> plain = new ArrayList<>(); + List> all = new ArrayList<>(); + List> back = new ArrayList<>(); + for (int i = 0; i < n; i++) { + plain.add(new ArrayList<>()); + all.add(new ArrayList<>()); + back.add(new ArrayList<>()); + } + entered = new boolean[n]; + for (int i = 0; i < n; i++) { + if (frames[i] == null) { + continue; + } + for (int t : successors(i)) { + if (t < n) { + plain.get(i).add(t); + all.get(i).add(t); + } + } + for (int t : targets(i)) { + entered[t] = true; + } + } + for (TryCatchBlockNode tc : method.tryCatchBlocks) { + int h = index(tc.handler); + entered[h] = true; + for (int i = index(tc.start); i < index(tc.end); i++) { + if (frames[i] != null && insns[i].getOpcode() >= 0) { + all.get(i).add(h); + } + } + } + for (int i = 0; i < n; i++) { + for (int t : all.get(i)) { + back.get(t).add(i); + } + } + flow = toArrays(plain); + flowAll = toArrays(all); + backAll = toArrays(back); + } + + private int[][] toArrays(List> lists) { + int[][] out = new int[lists.size()][]; + for (int i = 0; i < out.length; i++) { + out[i] = lists.get(i).stream().mapToInt(Integer::intValue).toArray(); + } + return out; + } + + /** What the sources reach along {@code graph}, entering only instructions {@code ok} and taking only edges {@code edge}. */ + private boolean[] reach(int[][] graph, List sources, IntPredicate ok, Edge edge) { + boolean[] seen = new boolean[graph.length]; + ArrayDeque todo = new ArrayDeque<>(); + for (int s : sources) { + if (s < graph.length && !seen[s] && ok.test(s)) { + seen[s] = true; + todo.add(s); + } + } + while (!todo.isEmpty()) { + int i = todo.poll(); + for (int t : graph[i]) { + if (!seen[t] && ok.test(t) && edge.ok(i, t)) { + seen[t] = true; + todo.add(t); + } + } + } + return seen; + } + + /** Natural loops: a jump back to {@code h} from {@code s} where every way from the start to {@code s} passes {@code h}. */ + private void findLoops() { + int n = insns.length; + Map> byHead = new TreeMap<>(); + Map withoutHead = new HashMap<>(); + for (int i = 0; i < n; i++) { + for (int t : flowAll[i]) { + if (t <= i) { + int h = t; + boolean[] r = withoutHead.computeIfAbsent(h, x -> reach(flowAll, List.of(0), k -> k != x, (a, b) -> true)); + if (!r[i]) { + byHead.computeIfAbsent(h, x -> new TreeSet<>()).add(i); + } + } + } + } + for (Map.Entry> e : byHead.entrySet()) { + int h = e.getKey(); + boolean[] body = reach(backAll, new ArrayList<>(e.getValue()), k -> k != h, (a, b) -> true); + body[h] = true; + boolean real = false; + for (int i = 0; i < n; i++) { + real |= body[i] && stepAt.contains(i); // (what goes round: not the code breaking out) + } + // the ways out: where code in it goes to outside it + Set exits = new TreeSet<>(); + for (int i = 0; i < n; i++) { + if (body[i]) { + for (int t : flow[i]) { + if (!body[t]) { + exits.add(t); + } + } + } + } + Map from = new HashMap<>(); + for (int t : exits) { + from.put(t, reach(flowAll, List.of(t), k -> !body[k], (a, b) -> true)); + } + // the follow: where every way out that can go on (not only throw) leads; else the last + // of them, where javac puts the code after the loop + Set goOn = new TreeSet<>(); + for (int t : exits) { + boolean[] r = from.get(t); + for (int i = 0; i < n && !goOn.contains(t); i++) { + int op = insns[i].getOpcode(); + if (r[i] && op >= Opcodes.IRETURN && op <= Opcodes.RETURN) { + goOn.add(t); + } + } + } + Set ways = goOn.isEmpty() ? exits : goOn; + Integer follow = null; + for (int t : ways) { + if (ways.stream().allMatch(u -> from.get(u)[t])) { + follow = t; + } + } + if (follow == null && !ways.isEmpty()) { + follow = Collections.max(ways); + } + final Integer f = follow; + boolean[] extent = f == null ? reach(flowAll, List.of(0), k -> true, (a, b) -> true) + : reach(flowAll, List.of(h), k -> k != f, (a, b) -> true); + int size = 0; + for (boolean x : extent) { + size += x ? 1 : 0; + } + naturalLoops.add(new NaturalLoop(h, body, e.getValue(), real, extent, size)); + } + } + + /** The innermost natural loop around {@code i} that {@code skip} does not reject, or null. */ + private NaturalLoop loopAround(int i, Predicate skip) { + NaturalLoop best = null; + for (NaturalLoop l : naturalLoops) { + if (l.spans(i) && !skip.test(l) && (best == null || l.size() < best.size())) { + best = l; + } + } + return best; + } + + private boolean realBackEdge(int from, int to) { + for (NaturalLoop l : naturalLoops) { + if (l.real() && l.head() == to && l.backFrom().contains(from)) { + return true; + } + } + return false; + } + + /** The first instruction of the straight code that ends at {@code j}: after a jump, a return, a step, or where code jumps in. */ + private int blockStart(int j) { + int k = j; + while (k > 0 && !entered[k]) { + AbstractInsnNode prev = insns[k - 1]; + boolean ends = prev.getOpcode() >= 0 && (prev instanceof JumpInsnNode || prev instanceof TableSwitchInsnNode + || prev instanceof LookupSwitchInsnNode || exits(prev)); + if (ends || stepAt.contains(k - 1)) { + break; + } + k--; + } + return k; + } + + private void findCandidates() { + int n = insns.length; + buildFlow(); + findLoops(); + List all = new ArrayList<>(); + boolean[] taken = new boolean[n]; + for (int b = 0; b < n; b++) { + if (frames[b] != null && (insns[b] instanceof TableSwitchInsnNode || insns[b] instanceof LookupSwitchInsnNode)) { + Candidate c = switchCandidate(b); + if (c != null) { + all.add(c); + for (int k : c.condition()) { + taken[k] = true; + } + } + } + } + // the jumps of one condition, read from its last: a jump whose fall-through starts the + // condition after it, and whose other way goes into that condition or where it goes, is + // one of its operands + Map byEntry = new HashMap<>(); + List groups = new ArrayList<>(); + for (int j = n - 1; j >= 0; j--) { + if (frames[j] == null || taken[j] || !(insns[j] instanceof JumpInsnNode jump) || !conditional(jump.getOpcode())) { + continue; + } + int start = blockStart(j); + int fall = realAt(j + 1); + int to = realAt(index(jump.label)); + IfGroup g = byEntry.get(fall); + if (g != null && (g.nodes.contains(to) || g.exits.contains(to))) { + byEntry.remove(fall); + for (int k = start; k <= j; k++) { + g.nodes.add(k); + } + g.first = j; + byEntry.put(realAt(start), g); + } else if (fall != to) { + IfGroup ng = new IfGroup(j, fall, to); + ng.first = j; + for (int k = start; k <= j; k++) { + ng.nodes.add(k); + } + byEntry.put(realAt(start), ng); + groups.add(ng); + } + } + for (IfGroup g : groups) { + NaturalLoop around = loopAround(g.last, l -> false); + if (around != null && (!around.spans(g.then) || !around.spans(g.otherwise)) && condition(around, g)) { + continue; // the loop's condition (any other jump out of it is a break) + } + int[] cond = g.nodes.stream().mapToInt(Integer::intValue).sorted().toArray(); + // the arm that runs when what the if is named after is true is "true": for + // if (!approved), the arm the code falls into is "false" + boolean negated = negatesBoolean(g); + Map keyOf = new LinkedHashMap<>(); + keyOf.put(g.then, negated ? "false" : "true"); + keyOf.put(g.otherwise, negated ? "true" : "false"); + Candidate c = decision(g.last, lineAt[g.first], name("if", g.last), cond, keyOf, g.otherwise, Set.of()); + if (c != null) { + all.add(c); + } + } + for (Candidate c : all) { + candidates.put(c.b(), c); + } + } + + /** + * Whether the jumps are the loop's condition: the first jump the straight code from its head + * comes to (a while or for), or the jump back that closes it (a do-while). + */ + private boolean condition(NaturalLoop loop, IfGroup g) { + for (int j : g.nodes) { + if (loop.backFrom().contains(j)) { + return true; + } + } + for (int i = loop.head(); i < insns.length; i++) { + if (i > loop.head() && entered[i]) { + return false; + } + AbstractInsnNode insn = insns[i]; + if (insn instanceof JumpInsnNode || insn instanceof TableSwitchInsnNode || insn instanceof LookupSwitchInsnNode) { + return g.nodes.contains(i); + } + if (exits(insn)) { + return false; + } + } + return false; + } + + /** The jumps of one if's condition, its last, and its two outcomes. */ + /** + * Whether an if of one jump tests a boolean (a method, field or local of type boolean) and + * falls into its body when that boolean is false: {@code if (!approved)}, which javac + * compiles to a jump past the body when the value is true. + */ + private boolean negatesBoolean(IfGroup g) { + if (g.first != g.last || insns[g.last].getOpcode() != Opcodes.IFNE) { + return false; + } + AbstractInsnNode value = prevRealIn(insns, g.last); + if (value instanceof MethodInsnNode m) { + return m.desc.endsWith(")Z"); + } + if (value instanceof FieldInsnNode f) { + return f.desc.equals("Z"); + } + if (value instanceof VarInsnNode v && v.getOpcode() == Opcodes.ILOAD && method.localVariables != null) { + for (LocalVariableNode local : method.localVariables) { + if (local.index == v.var && index(local.start) <= g.last && g.last < index(local.end)) { + return local.desc.equals("Z"); + } + } + } + return false; + } + + private static final class IfGroup { + final int last; + final int then; + final int otherwise; + int first; + final Set nodes = new TreeSet<>(); + final Set exits; + + IfGroup(int last, int then, int otherwise) { + this.last = last; + this.then = then; + this.otherwise = otherwise; + this.exits = Set.of(then, otherwise); + } + } + + /** + * A switch: its condition is the switch and what it comes round to without a step (a + * failed {@code when} guard goes back to it); each place the condition goes on to is an + * outcome, named by the cases that lead there. + */ + private Candidate switchCandidate(int b) { + int n = insns.length; + 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; + } + IntPredicate free = k -> !stepAt.contains(k); + Edge forward = (a, t) -> !realBackEdge(a, t); + boolean[] from = reach(flow, List.of(b), free, forward); + int[][] rev = new int[n][]; + List> r = new ArrayList<>(); + for (int i = 0; i < n; i++) { + r.add(new ArrayList<>()); + } + for (int i = 0; i < n; i++) { + for (int t : flow[i]) { + r.get(t).add(i); + } + } + rev = toArrays(r); + boolean[] to = reach(rev, List.of(b), free, (a, t) -> !realBackEdge(t, a)); + Set cond = new TreeSet<>(); + for (int i = 0; i < n; i++) { + if (from[i] && to[i]) { + cond.add(i); + } + } + for (int k = blockStart(b); k <= b; k++) { + cond.add(k); + } + Map names = caseNames(b); + boolean chars = isChar(source(b, 1, 0)); + int d = realAt(index(dflt)); + Map> byExit = new LinkedHashMap<>(); + for (int k = 0; k < keys.size(); k++) { + int start = index(labels.get(k)); + String name = names.getOrDefault(keys.get(k), chars ? String.valueOf((char) keys.get(k).intValue()) : String.valueOf(keys.get(k))); + if (!cond.contains(start)) { + if (realAt(start) != d) { + byExit.computeIfAbsent(realAt(start), x -> new ArrayList<>()).add(name); + } + continue; + } + // a guarded case: where its guard lets the code on to + boolean[] inGuard = reach(flow, List.of(start), i -> cond.contains(i) && i != b, (x, y) -> true); + for (int i = 0; i < n; i++) { + if (inGuard[i]) { + for (int y : flow[i]) { + if (!cond.contains(y) && realAt(y) != d) { + byExit.computeIfAbsent(realAt(y), x -> new ArrayList<>()).add(name + " when"); + } + } + } + } + } + if (cond.contains(d)) { + return null; + } + Map keyOf = new LinkedHashMap<>(); + Set used = new HashSet<>(); + used.add("default"); + for (Map.Entry> e : new TreeMap<>(byExit).entrySet()) { + String key = String.join(",", new LinkedHashSet<>(e.getValue())); + for (int k = 2; !used.add(key); k++) { + key = String.join(",", new LinkedHashSet<>(e.getValue())) + " (" + k + ")"; + } + keyOf.put(e.getKey(), key); + } + keyOf.put(d, "default"); + // every place the condition goes on to is an outcome + for (int c : cond) { + for (int y : flow[c]) { + if (!cond.contains(y) && !keyOf.containsKey(realAt(y))) { + return null; + } + } + } + Set cases = new HashSet<>(keyOf.keySet()); + cases.remove(d); + return decision(b, lineAt[b], name("switch", b), cond.stream().mapToInt(Integer::intValue).toArray(), keyOf, d, cases); + } + + private boolean regionHasCode(boolean[] region) { + for (int i = 0; i < region.length; i++) { + if (region[i]) { + return true; + } + } + return false; + } + + /** Whether the value at {@code src} is a char: so a switch's cases are characters. */ + private boolean isChar(AbstractInsnNode src) { + if (src instanceof MethodInsnNode m) { + return m.desc.endsWith(")C"); + } + if (src instanceof FieldInsnNode f) { + return f.desc.equals("C"); + } + if (src instanceof InsnNode i) { + return i.getOpcode() == Opcodes.I2C || i.getOpcode() == Opcodes.CALOAD; + } + if (src instanceof VarInsnNode v && v.getOpcode() == Opcodes.ILOAD && method.localVariables != null) { + int at = indexOf(v); + for (LocalVariableNode local : method.localVariables) { + if (local.index == v.var && index(local.start) <= at + 1 && at < index(local.end)) { + return local.desc.equals("C"); + } + } + } + return false; + } + + /** + * A decision at {@code b} with its condition and outcomes (by the first instruction each + * goes to, in the order to draw, {@code otherwise} the default): its arms, or null when it + * is not drawn. + */ + private Candidate decision(int b, int line, String name, int[] cond, Map keyOf, int otherwise, + Set cases) { + int n = insns.length; + boolean[] inCond = new boolean[n]; + for (int c : cond) { + inCond[c] = true; + } + // the loop the decision is in (not one that is only its own condition going round) + NaturalLoop loop = loopAround(b, l -> { + for (int i = 0; i < n; i++) { + if (l.body()[i] && !inCond[i] && insns[i].getOpcode() >= 0) { + return false; + } + } + return true; + }); + List exits = new ArrayList<>(keyOf.keySet()); + exits.sort(null); + List regions = new ArrayList<>(); + List entries = new ArrayList<>(); + List keys = new ArrayList<>(); + int[] place = new int[n]; + Arrays.fill(place, -1); + Map exitArm = new HashMap<>(); + boolean steps = false; + int end = cond[cond.length - 1] + 1; + int otherwiseAt = -1; + for (int x : exits) { + List starts = new ArrayList<>(); + for (int c : cond) { + for (int y : flow[c]) { + if (!inCond[y] && realAt(y) == x) { + starts.add(y); + } + } + } + Set startSet = new HashSet<>(starts); + boolean[] around = reach(flowAll, List.of(0), k -> true, (a, t) -> !(inCond[a] && startSet.contains(t))); + boolean[] region = reach(flowAll, starts, k -> !around[k] && !inCond[k] && (loop == null || loop.spans(k)), (a, t) -> true); + int k = regions.size(); + for (int i = 0; i < n; i++) { + if (region[i]) { + if (place[i] >= 0) { + return null; // (cannot happen: what runs only through one outcome is in no other) + } + place[i] = k; + end = Math.max(end, i + 1); // (an empty arm is where the code goes on, not part of it) + steps |= stepAt.contains(i); + } + } + regions.add(region); + entries.add(starts.isEmpty() ? x : Collections.min(starts)); + for (int s : starts) { + exitArm.put(s, k); + } + exitArm.put(x, k); + if (x == otherwise) { + otherwiseAt = k; + } + keys.add(keyOf.get(x)); + } + if (!steps || regions.size() < 2) { + return null; // no arm calls the server: plain code + } + // a case another arm runs into, with a step before where all the arms meet: the case + // falls through, and its code runs for two cases (javac's code is the same as a + // switch followed by an if, so only the written case tells them apart) + boolean[] lim = new boolean[n]; + for (int i = 0; i < n; i++) { + lim[i] = !inCond[i] && (loop == null || (loop.spans(i) && i != loop.head())); + } + boolean[] common = null; + Map> startsOf = new HashMap<>(); + for (int c : cond) { + for (int y : flow[c]) { + if (!inCond[y]) { + startsOf.computeIfAbsent(realAt(y), z -> new ArrayList<>()).add(y); + } + } + } + for (List st : startsOf.values()) { + boolean[] r = reach(flowAll, st, k -> lim[k], (a, t) -> true); + if (common == null) { + common = r; + } else { + for (int i = 0; i < n; i++) { + common[i] &= r[i]; + } + } + } + for (int x : cases) { + List st = startsOf.getOrDefault(x, List.of()); + Integer k = exitArm.get(x); + if (st.isEmpty() || k == null || regionHasCode(regions.get(k))) { + continue; // only through its own case: no other arm runs into it + } + final boolean[] meet = common; + boolean[] own = reach(flowAll, st, i -> lim[i] && (meet == null || !meet[i]), (a, t) -> true); + for (int i = 0; i < n; i++) { + if (own[i] && stepAt.contains(i)) { + return null; + } + } + } + // every line with a step is in one arm or in none, so a call tells the arm it was made in + Map placeOfLine = new HashMap<>(); + for (int i : stepAt) { + Integer seen = placeOfLine.putIfAbsent(lineAt[i], place[i]); + if (seen != null && seen != place[i]) { + return null; + } + } + for (TryCatchBlockNode tc : method.tryCatchBlocks) { + int h = index(tc.handler); + for (boolean[] r : regions) { + if (r[h]) { + for (int i = index(tc.start); i < index(tc.end); i++) { + if (!r[i] && frames[i] != null && insns[i].getOpcode() >= 0) { + return null; // a catch in the arm of a try around more than the arm + } + } + } + } + } + boolean[] covers = inCond.clone(); + for (boolean[] r : regions) { + for (int i = 0; i < n; i++) { + covers[i] |= r[i]; + } + } + return new Candidate(b, line, name, end, List.copyOf(keys), otherwiseAt, cond, Map.copyOf(exitArm), + List.copyOf(regions), List.copyOf(entries), covers); + } + + /** The first real instruction at or after {@code i} (a label comes before its line number). */ + private int realAt(int i) { + while (i < insns.length - 1 && insns[i].getOpcode() < 0) { + i++; + } + return i; + } + + /** 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; the + // local is set to -1 first, and every string switch of the method may reuse it + int from = b - 1; + while (from > 0 && !(insns[from] instanceof VarInsnNode init && init.getOpcode() == Opcodes.ISTORE + && init.var == v.var && "-1".equals(constant(from, 1, 0)))) { + from--; + } + for (int i = from + 1; i < b; 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 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" -> { + Command c = named(Command.Kind.SIMPLE, text(i, argc, 0, "task")); + chainArg(i, "ref").ifPresent(r -> c.explicitRef = r); + call(c); + } + 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 "external" -> 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" -> {} // a conversation: its asks are the steps + 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(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 "doWhile" -> { + List body = new ArrayList<>(bodyOf(i, argc, 1)); + body.addAll(bodyOf(i, argc, 2)); + if (!body.isEmpty()) { + add(List.of(new InLoops(List.of(text(i, argc, 0, "do_while")), List.copyOf(body), 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())); + rawSourcesOf(h.getOwner(), h.getName(), h.getDesc()); + return body; + } + return List.of(); + } + + /** + * Notes the random sources and clock reads a call brings: the call itself when it is one + * (also as a method reference, such as {@code Math::random}), else those of the code it + * runs, already read. + */ + private void rawSourcesOf(String owner, String name, String desc) { + String[] raw = rawSource(owner, name, desc); + if (raw != null) { + rawSources.add(new RawSource(site(), raw[0], raw[1])); + } else { + rawSources.addAll(RAW_SOURCES.getOrDefault(key(owner, name, desc), 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 name given to {@code agent(..)} for the conversation an {@code ask} at {@code i} is + * on: back through the builder calls on it and the local variable holding it. A conversation + * that reached the code from elsewhere, such as captured by a lambda, is named "agent". + */ + private String agentRef(int i) { + AbstractInsnNode at = receiver(i); + for (int hops = 0; at != null && hops < 64; hops++) { + if (at instanceof MethodInsnNode m && m.getOpcode() == Opcodes.INVOKESTATIC) { + return CONDUCTOR.equals(m.owner) && m.name.equals("agent") ? text(indexOf(m), 1, 0, "agent") : "agent"; + } + if (at instanceof MethodInsnNode m) { + at = receiver(indexOf(m)); // a builder call such as remote(..): its receiver + } else if (at instanceof VarInsnNode load && load.getOpcode() == Opcodes.ALOAD && frames[indexOf(load)] != null) { + Set stores = frames[indexOf(load)].getLocal(load.var).insns; + if (stores.size() != 1 || !(stores.iterator().next() instanceof VarInsnNode store) + || store.getOpcode() != Opcodes.ASTORE || frames[indexOf(store)] == null) { + return "agent"; + } + Frame f = frames[indexOf(store)]; + Set value = f.getStack(f.getStackSize() - 1).insns; + at = value.size() == 1 ? value.iterator().next() : null; + } else { + return "agent"; + } + } + return "agent"; + } + + /** The instruction that produced the receiver of the instance call at {@code i}, when one did. */ + private AbstractInsnNode receiver(int i) { + if (!(insns[i] instanceof MethodInsnNode m) || frames[i] == null) { + return null; + } + int at = frames[i].getStackSize() - Type.getArgumentTypes(m.desc).length - 1; + if (at < 0) { + return null; + } + Set sources = frames[i].getStack(at).insns; + return sources.size() == 1 ? sources.iterator().next() : 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 Optional chainArg(int i, String name) { + for (MethodInsnNode link : chain(i)) { + if (link.name.equals(name)) { + return Optional.ofNullable(textOf(indexOf(link), Type.getArgumentTypes(link.desc).length, 0)); + } + } + return 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..2055833f3 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Command.java @@ -0,0 +1,121 @@ +/* + * 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; + } + + /** + * A copy to send: a builder keeps its command as a template and sends a copy per call, so a + * builder used twice sends what it was given each time, not what an earlier call left behind. + * Maps one level down (an HTTP request, headers) are copied too. + */ + public Command copy() { + Command c = new Command(kind, name, refBase); + c.explicitRef = explicitRef; + input.forEach((k, v) -> c.input.put(k, copied(v))); + fields.forEach((k, v) -> c.fields.put(k, copied(v))); + rawInput.forEach((k, v) -> c.rawInput.put(k, copied(v))); + c.resultType = resultType; + c.timeoutIsEmpty = timeoutIsEmpty; + c.emptyIsEmpty = emptyIsEmpty; + c.optional = optional; + c.httpBody = httpBody; + c.outputKey = outputKey; + c.method = method; + c.args = args; + c.childMethod = childMethod; + c.childInput = childInput; + c.seconds = seconds; + return c; + } + + private static Object copied(Object value) { + if (value instanceof Map map) { + Map copy = new LinkedHashMap<>(); + map.forEach((k, v) -> copy.put(k, copied(v))); + return copy; + } + return value; + } + + 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..2b0d773fc --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Engine.java @@ -0,0 +1,92 @@ +/* + * 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.Map; +import java.util.concurrent.Future; +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; + +/** + * 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(); + + Future async(Supplier body); + + void join(List> branches); + + 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, Map> cases, Supplier otherwise); + + /** + * Whether the {@code doWhile} named {@code name} runs another pass. The condition is always + * evaluated; an engine that replays answers with what the execution recorded for this pass. + */ + default boolean loopAgain(String name, BooleanSupplier condition) { + return condition.getAsBoolean(); + } + + 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..9e4c5e888 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Entries.java @@ -0,0 +1,134 @@ +/* + * 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<>()); + // the lane's n-th continuation runs when this task ends; the lane is the entry's own + m.putIfAbsent("lane", lane); + m.put("continuation", n); + 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..5614323f7 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Execution.java @@ -0,0 +1,277 @@ +/* + * 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, and the handled messages. */ + public final Map nativeState; + public final List tasks = new ArrayList<>(); + /** Every definition entry at any depth, by reference name. */ + public final Map> entries = new 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); + } + + /** + * A task as a poll handed it out, which a lane kept parked in memory waited for: its result is + * what the lane reads when it continues. + */ + public void arrived(TaskView task) { + tasks.add(task); + latest.put(task.ref, task); + } + + /** + * Drops the tasks and the recorded values, for an execution whose code stays parked in memory: + * what its lanes read next arrives with their continuations ({@link #arrived}), and what they + * already read is in their own state. The definition entries stay, for the names they took. + */ + public void forgetHistory() { + tasks.clear(); + latest.clear(); + recorded.clear(); + } + + /** 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"); + if (!(b instanceof Map)) { + return null; + } + return new Marker((Map) b, "main", 1); // always main #1 + } + + /** Every recently handled message, by the sender's id, with its reply when it has one. */ + @SuppressWarnings("unchecked") + public Map replies() { + Object r = nativeState.get("replies"); + return r instanceof Map ? (Map) r : Map.of(); + } + + /** + * The continuations the server has applied, in the order it applied them: by their + * {@code endTime}, which the server keeps increasing within a run; 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()) { + segments.add(t.marker); + } + } + segments.sort(Comparator.comparingLong((Marker m) -> m.endTime)); + return segments; + } + + private static Map orEmpty(Map m) { + return m == null ? new LinkedHashMap<>() : m; + } + + /** + * A continuation marker: which continuation it is (the lane of the code and its number, which + * the entry the code paused on names), and what its completion recorded. + */ + public static final class Marker { + public final String lane; + public final int n; + public final boolean leased; + /** When it applied; 0 until then. */ + public final long endTime; + public final boolean done; + public final Map resumedWith; + public final Map recorded; + + @SuppressWarnings("unchecked") + Marker(Map m, String lane, int n) { + this.lane = lane; + this.n = n; + this.leased = Boolean.TRUE.equals(m.get("leased")); + this.endTime = m.get("endTime") 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 endTime > 0; + } + + /** As the server would say: applied, leased, or not run yet. */ + public String state() { + return applied() ? "applied" : leased ? "leased" : "not run"; + } + } + + /** 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"); + Map meta = wt == null ? null : (Map) wt.get("metadata"); + this.marker = c instanceof Map && meta != null + ? new Marker( + (Map) c, + String.valueOf(meta.get("lane")), + meta.get("continuation") instanceof Number x ? x.intValue() : 0) + : null; + } + + /** A task from the fields a poll hands out. */ + public static TaskView of(String taskId, String ref, String taskType, String status, + Map output, String reason) { + Map t = new LinkedHashMap<>(); + t.put("taskId", taskId); + t.put("referenceTaskName", ref); + t.put("taskType", taskType); + t.put("status", status); + t.put("outputData", output); + t.put("reasonForIncompletion", reason); + return new TaskView(t); + } + + 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..e6303c9c3 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Json.java @@ -0,0 +1,227 @@ +/* + * 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.time.temporal.Temporal; +import java.time.temporal.TemporalAmount; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.UUID; + +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.databind.type.TypeFactory; +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() + // values JSON writes as a string or a number, not as an object + || Temporal.class.isAssignableFrom(raw) + || TemporalAmount.class.isAssignableFrom(raw) + || Date.class.isAssignableFrom(raw) + || UUID.class == 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; + } + // an object spreads into the output; any other value (a scalar, a list, or a type JSON + // writes as one value, such as a UUID) is the result + Object plain = plain(value); + if (!isWrapped(value.getClass()) && plain instanceof Map m) { + m.forEach((k, v) -> out.put(String.valueOf(k), v)); + return out; + } + out.put("result", plain); + return out; + } + + /** 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; + } + } + + /** + * A value as it is recorded for a re-run to read back: its JSON, and the type to read that + * JSON as. The type is the value's class, with the element types of a list, set or map taken + * from its elements, since a re-run has only the JSON: a {@code List} is recorded as a + * list of {@code Order}, not as the list class that happened to hold it. + */ + public static Map record(Object value) { + Map record = new LinkedHashMap<>(); + record.put("value", plain(value)); + if (value != null) { + record.put("type", typeOf(value).toCanonical()); + } + return record; + } + + /** Reads back a value recorded with {@link #record}; classes are found through {@code loader}. */ + public static Object recorded(Map record, ClassLoader loader) { + Object value = record.get("value"); + Object type = record.get("type"); + if (value == null || type == null) { + return value; + } + JavaType javaType; + try { + javaType = MAPPER.getTypeFactory().withClassLoader(loader).constructFromCanonical(type.toString()); + } catch (IllegalArgumentException e) { + return value; // a class this build no longer has: the plain JSON value + } + return MAPPER.convertValue(value, javaType); + } + + /** The type to read a value's JSON back as. */ + private static JavaType typeOf(Object value) { + TypeFactory types = MAPPER.getTypeFactory(); + if (value instanceof Map m) { + return types.constructMapType(LinkedHashMap.class, common(m.keySet()), common(m.values())); + } + if (value instanceof Collection c) { + @SuppressWarnings("rawtypes") // what TypeFactory.constructCollectionType takes + Class holder = value instanceof SortedSet ? TreeSet.class + : value instanceof Set ? LinkedHashSet.class + : ArrayList.class; + return types.constructCollectionType(holder, common(c)); + } + // an enum constant with a body is its own class: the enum is what reads it back + return types.constructType(value instanceof Enum e ? e.getDeclaringClass() : value.getClass()); + } + + /** The one type all of these values are read back as; any JSON value when they differ. */ + private static JavaType common(Collection values) { + JavaType common = null; + for (Object v : values) { + if (v == null) { + continue; + } + JavaType type = typeOf(v); + if (common != null && !common.equals(type)) { + return MAPPER.getTypeFactory().constructType(Object.class); + } + common = type; + } + return common == null ? MAPPER.getTypeFactory().constructType(Object.class) : common; + } + + 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/JsonSchemas.java b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/JsonSchemas.java new file mode 100644 index 000000000..51299836a --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/JsonSchemas.java @@ -0,0 +1,222 @@ +/* + * 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.Modifier; +import java.lang.reflect.Parameter; +import java.lang.reflect.Type; +import java.math.BigInteger; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.OffsetTime; +import java.time.temporal.Temporal; +import java.util.Arrays; +import java.util.Date; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import com.netflix.conductor.common.metadata.tasks.TaskResult; +import com.netflix.conductor.sdk.workflow.task.InputParam; +import com.netflix.conductor.sdk.workflow.task.OutputParam; +import com.netflix.conductor.sdk.workflow.task.WorkflowInstanceIdInputParam; + +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition; + +/** + * JSON Schemas of what a task or workflow takes and gives, read from its Java signature by + * reflection, shaped as the SDK actually sends it: a task's input has one property per parameter, + * named as its calls name it; an output that is an object spreads into its properties, and any + * other value is {@code result}. Types are read as Jackson, which serializes the values, sees + * them. They document the data: nothing enforces them. + */ +public final class JsonSchemas { + + private static final String DRAFT = "http://json-schema.org/draft-07/schema#"; + + private JsonSchemas() {} + + /** A task's input, or null when its parameter names are not known. */ + public static Map taskInput(Method method) { + Map properties = new LinkedHashMap<>(); + Parameter[] params = method.getParameters(); + for (int i = 0; i < params.length; i++) { + if (params[i].isAnnotationPresent(WorkflowInstanceIdInputParam.class)) { + continue; // filled from the task, not from the input + } + String name = nameOf(params[i]); + if (name == null) { + return null; + } + properties.put(name, of(params[i].getParameterizedType())); + } + return document(object(properties)); + } + + /** A task's output, or null when nothing can be said of it (no value, or a raw result). */ + public static Map taskOutput(Method method) { + Type type = method.getGenericReturnType(); + Class raw = method.getReturnType(); + if (raw == void.class || raw == Void.class || TaskResult.class.isAssignableFrom(raw) || raw == Object.class) { + return null; + } + OutputParam named = method.getAnnotatedReturnType().getAnnotation(OutputParam.class); + if (named != null) { + return document(object(Map.of(named.value(), of(type)))); + } + return document(spread(type)); + } + + /** A workflow's input, as the SDK starts it: a single object's properties, else one per parameter. */ + public static Map workflowInput(Method method) { + if (method.getParameterCount() == 1 && !Json.isWrapped(method.getGenericParameterTypes()[0])) { + return document(of(method.getGenericParameterTypes()[0])); + } + Map properties = new LinkedHashMap<>(); + for (Parameter p : method.getParameters()) { + String name = nameOf(p); + if (name == null) { + return null; + } + properties.put(name, of(p.getParameterizedType())); + } + return document(object(properties)); + } + + /** A workflow's output: what its code returns, as the engine records it. */ + public static Map workflowOutput(Method method) { + Class raw = method.getReturnType(); + if (raw == void.class || raw == Void.class || raw == Object.class) { + return null; + } + return document(spread(method.getGenericReturnType())); + } + + /** The schema of one value of this type. */ + public static Map of(Type type) { + return of(Json.MAPPER.getTypeFactory().constructType(type), new HashSet<>()); + } + + // ------------------------------------------------------------------ shapes + + /** An object spreads into its properties; any other value is {@code result}. */ + private static Map spread(Type type) { + if (Json.isWrapped(type)) { + return object(Map.of("result", of(type))); + } + return of(type); + } + + private static Map of(JavaType type, Set visiting) { + Class raw = type.getRawClass(); + if (type.isReferenceType()) { // Optional and the like: the value, when there is one + return of(type.getReferencedType(), visiting); + } + if (raw == String.class || CharSequence.class.isAssignableFrom(raw) || raw == char.class + || raw == Character.class) { + return Map.of("type", "string"); + } + if (raw == UUID.class) { + return Map.of("type", "string", "format", "uuid"); + } + if (raw == boolean.class || raw == Boolean.class) { + return Map.of("type", "boolean"); + } + if (raw == byte.class || raw == short.class || raw == int.class || raw == long.class || raw == Byte.class + || raw == Short.class || raw == Integer.class || raw == Long.class + || raw == BigInteger.class) { + return Map.of("type", "integer"); + } + if (raw.isPrimitive() || Number.class.isAssignableFrom(raw)) { + return Map.of("type", "number"); + } + if (raw.isEnum()) { + return Map.of("type", "string", "enum", enumValues(raw)); + } + if (raw == LocalDate.class) { + return Map.of("type", "string", "format", "date"); + } + if (raw == LocalTime.class || raw == OffsetTime.class) { + return Map.of("type", "string", "format", "time"); + } + if (Temporal.class.isAssignableFrom(raw) || raw == Date.class) { + return Map.of("type", "string", "format", "date-time"); + } + if (raw == Duration.class) { + return Map.of("type", "string", "format", "duration"); + } + if (type.isArrayType() || type.isCollectionLikeType()) { + return Map.of("type", "array", "items", of(type.getContentType(), visiting)); + } + if (type.isMapLikeType()) { + return Map.of("type", "object", "additionalProperties", of(type.getContentType(), visiting)); + } + if (raw == Object.class || raw.isInterface() || Modifier.isAbstract(raw.getModifiers())) { + return Map.of(); // any value + } + if (!visiting.add(type)) { + return Map.of("type", "object"); // a type that holds itself: not unrolled again + } + try { + Map properties = new LinkedHashMap<>(); + List props = Json.MAPPER.getSerializationConfig().introspect(type).findProperties(); + for (BeanPropertyDefinition p : props) { + if (p.couldSerialize()) { + properties.put(p.getName(), of(p.getPrimaryType(), visiting)); + } + } + return object(properties); + } finally { + visiting.remove(type); + } + } + + private static Map object(Map properties) { + Map schema = new LinkedHashMap<>(); + schema.put("type", "object"); + schema.put("properties", properties); + return schema; + } + + private static Map document(Map schema) { + if (schema == null) { + return null; + } + Map doc = new LinkedHashMap<>(); + doc.put("$schema", DRAFT); + doc.putAll(schema); + return doc; + } + + private static List enumValues(Class type) { + return Arrays.stream(type.getEnumConstants()) + .map(c -> Json.MAPPER.convertValue(c, String.class)) + .toList(); + } + + /** As {@link MethodRefs#parameterNames}: {@code @InputParam}, else the compiled name; null if neither. */ + private static String nameOf(Parameter p) { + InputParam ip = + p.getAnnotation(InputParam.class); + if (ip != null) { + return ip.value(); + } + return p.isNamePresent() ? p.getName() : null; + } +} 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..d396f339c --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/MethodRefs.java @@ -0,0 +1,142 @@ +/* + * 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; + +import org.objectweb.asm.Handle; + +import com.netflix.conductor.sdk.workflow.task.InputParam; + +/** + * 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, 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++) { + InputParam ip = + params[i].getAnnotation(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..5d788737a --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/Replayer.java @@ -0,0 +1,2083 @@ +/* + * 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.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.Semaphore; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +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.TaskFailure; +import org.conductoross.conductor.sdk.WorkflowFailedException; +import org.objectweb.asm.Type; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Runs workflow code against an execution's recorded tasks and produces the next fragment. + * + *

A 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. + * + *

The lanes may be kept between continuations, parked where they paused ({@link #begin}, + * {@link #proceed}, {@link #close}): the next continuation then wakes its lane with the result of + * the task it waits for, and nothing is run again. That is an optimisation only. The recording is + * what the execution is; a replayer that was not kept, or whose copy is no longer current, replays. + * + *

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 static final Logger LOGGER = LoggerFactory.getLogger(Replayer.class); + + 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; + /** The execution as last read; a parked replayer is given what arrived since. */ + private 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 Map recorded = new LinkedHashMap<>(); + 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) { + try { + return begin(activeLane, activeContinuation); + } finally { + close(); + } + } + + /** + * As {@link #process}, but the lanes stay as they are when it returns: parked where they + * paused, on their threads. The caller either continues them with {@link #proceed} when the + * execution's next continuation comes, or ends them with {@link #close}; it must do one. + */ + public Outcome begin(String activeLane, int activeContinuation) { + 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); + 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; + } + return active(outcome, activeLane, activeContinuation, new LinkedHashMap<>(exec.variables)); + } + + /** + * Continues parked lanes with the next continuation, without replaying: the lane wakes where + * it paused and reads the result of the task it waited for. {@code awaited} is that task as + * the poll handed it out, {@code variables} the workflow's variables now. Only for a replayer + * that {@link #awaits} this continuation and whose execution is still as it left it. + */ + public Outcome proceed(String activeLane, int activeContinuation, Map variables, + Execution.TaskView awaited) { + exec.arrived(awaited); + return proceeding(activeLane, activeContinuation, variables); + } + + /** + * As {@link #proceed(String, int, Map, Execution.TaskView)}, with the whole execution read + * again: for a lane that paused on a loop the server ran, whose result is in the loop's tasks. + */ + public Outcome proceed(String activeLane, int activeContinuation, Execution fresh) { + this.exec = fresh; + return proceeding(activeLane, activeContinuation, fresh.variables); + } + + private Outcome proceeding(String activeLane, int activeContinuation, Map variables) { + Outcome outcome = new Outcome(); + outcome.instance = instance; + return active(outcome, activeLane, activeContinuation, new LinkedHashMap<>(variables)); + } + + /** Runs the continuation being processed now, and builds its completion. */ + private Outcome active(Outcome outcome, String activeLane, int activeContinuation, Map current) { + recorded = new LinkedHashMap<>(); // this continuation's own + Lane lane = runSegment(activeLane, activeContinuation, Mode.ACTIVE, current); + Map out = outcome.output; + 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 { + Map returned = new LinkedHashMap<>(); + returned.put("value", Json.plain(lane.result)); // null when the lane returned nothing + out.put("result", returned); + } + } else { + out.put("done", false); + } + out.put("fragment", fragment); + out.put("variables", spec.captureVariables(instance)); + outcome.pendingConditions.putAll(pendingConditions); + return outcome; + } + + /** Whether the lanes are parked with this lane waiting for exactly this continuation. */ + public boolean awaits(String laneId, int continuation) { + Lane lane = lanes.get(laneId); + return fatal == null && !aborting && lane != null && lane.state == State.PAUSED + && lane.waitingFor == continuation; + } + + /** + * Whether the lane paused on a loop the server runs ({@code repeatUntil}, {@code forEach}): its + * result is read from the loop's tasks, so continuing it takes the whole execution. + */ + public boolean readsTasks(String laneId) { + Lane lane = lanes.get(laneId); + return lane != null && lane.readsTasks; + } + + /** Whether any lane is paused, so that keeping the lanes parked can save a replay. */ + public boolean hasPausedLanes() { + if (fatal != null || aborting) { + return false; + } + for (Lane lane : lanes.values()) { + if (lane.state == State.PAUSED) { + return true; + } + } + return false; + } + + /** + * Before the lanes are kept: drops what a parked execution never reads again (its tasks and + * the values already replayed), so that it holds its code's state and not its history. + */ + public void forgetHistory() { + exec.forgetHistory(); + } + + /** Ends the lanes: each one's thread unwinds from where it paused. Nothing can be continued after. */ + public void close() { + 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; + /** The Java loops around what this drawing draws, outermost first (not for previews). */ + private final List loops; + + Drawing(String lane, boolean preview, String key) { + this(lane, preview, key, List.of()); + } + + private Drawing(String lane, boolean preview, String key, List loops) { + this.lane = lane; + this.preview = preview; + this.key = key; + this.loops = loops; + } + + List> draw(List steps) { + List> entries = new ArrayList<>(); + drawInto(steps, entries, new ArrayDeque<>()); + return entries; + } + + @SuppressWarnings("unchecked") + private void drawInto( + List steps, List> entries, Deque running) { + for (CodeReader.Step step : steps) { + if (step instanceof CodeReader.InLoops in) { + // a preview stays in the loops its switch is in; the definition shows each loop + List around = new ArrayList<>(loops); + in.loops().stream().filter(l -> !around.contains(l)).forEach(around::add); + (preview ? this : new Drawing(lane, false, key, List.copyOf(around))) + .drawInto(in.steps(), entries, running); + continue; + } + int before = entries.size(); + 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)); + } + if (!preview && !loops.isEmpty()) { + for (Map entry : entries.subList(before, entries.size())) { + ((Map) entry.get("metadata")).putIfAbsent("loops", loops); + } + } + } + } + + @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", "native-code"); // the code decided: the server reads the case it took + 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 if (step instanceof CodeReader.Call c) { + // repeatUntil, as the server runs it: wait out the backoff, then make the call + body.add(structural(ref + "_backoff", ref + "_backoff", "INLINE", l.site())); + body.add(structural(ref + "_wait", ref + "_wait", "WAIT", l.site())); + body.add(finish(Entries.of(c.command(), ref + "_check", 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, loops); + } + + 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; + } + + + /** 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( + "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; + /** Branches the lane is in an arm of, but cannot tell whether the code decided them again since. */ + final Set unsure = new HashSet<>(); + + /** 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; + /** Paused on a loop the server runs: its result is read from the loop's tasks. */ + boolean readsTasks; + /** 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 LaneFuture future = new LaneFuture<>(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); + } + // the stack has unwound by now: the loops are those around the lines it was thrown from + List loops = new ArrayList<>(startedInLoops); + for (Site frame : at) { + loops.addAll(CodeLoops.around(frame.type(), frame.method(), frame.descriptor(), frame.line())); + } + if (!loops.isEmpty()) { + metadata.put("loops", loops); + } + 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(), + 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(); + // a name given in the code is a base like a task's: a call made again, in a loop or + // written out again, is numbered by how many came before (x, x_2, x_3), never by the + // shape of the bytecode + String ref = alloc(cmd.explicitRef != null ? cmd.explicitRef : 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); + return resultOf(cmd, ref); + } + 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); + // a lane that was kept parked continues here, in the continuation that follows the + // task, with the result the task has by then; one that was not kept never does + return resultOf(cmd, ref); + } + + /** The result of the task a lane paused on, read when the lane continues. */ + private Object resultOf(Command cmd, String ref) { + 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); + } + + @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. The live run returns what it + * recorded, read back, and not the supplier's own object, so the code gets the same value + * the first time as on every replay, and a value that cannot be read back fails here, where + * it is computed, rather than at the next continuation. + */ + 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) { + return Json.recorded(record, spec.type.getClassLoader()); + } + if (mode != Mode.ACTIVE) { + throw diverged("the code records " + ref + " (" + Entries.site() + ") but the recorded execution has no such value"); + } + Map record = Json.record(supplier.get()); + Object readBack; + try { + readBack = Json.recorded(record, spec.type.getClassLoader()); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("the value recorded as " + ref + " (" + record.get("type") + + ") cannot be read back from its JSON, as a re-run must: " + e.getMessage(), e); + } + recorded.put(ref, record); + return readBack; + } + + @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(); + } + + /** + * Whether a {@code doWhile} runs another pass: what the execution recorded for this pass + * when it has, so a condition over something that is not recorded cannot change how many + * passes a retry or rerun makes. The live run records each pass's outcome with its + * continuation. The condition is evaluated either way, never skipped: it may call tasks, + * and a replay must reach every call the recording has. An execution recorded before + * passes were recorded has no value for them, and is answered by the condition as it was. + */ + @Override + public boolean loopAgain(String name, BooleanSupplier condition) { + String ref = alloc(name + "_again"); + boolean computed = condition.getAsBoolean(); + Object known = exec.recorded.containsKey(ref) ? exec.recorded.get(ref) : recorded.get(ref); + if (known instanceof Map record) { + boolean again = Boolean.TRUE.equals(Json.recorded(record, spec.type.getClassLoader())); + if (again != computed) { + LOGGER.warn("Loop {} of workflow {} {} in the recorded execution and its condition now says {} ({}):" + + " continuing as recorded. The condition reads something that is not recorded.", + name, exec.workflowId, again ? "ran another pass" : "ended", computed ? "another pass" : "end", ref); + } + return again; + } + if (mode == Mode.ACTIVE) { + recorded.put(ref, Json.record(computed)); + } + return computed; + } + + @Override + @SuppressWarnings("unchecked") + public Future async(Supplier asyncBody) { + follow(); + if (pendingGroup == null) { + pendingGroup = new Group(++groupCounter, null); + pendingGroup.loops = loopsHere(); + } + return (Future) spawn(pendingGroup, asyncBody).future; + } + + 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 branches, in the + * order given, so a lane's uncaught failure fails the caller even without a get(). + */ + @Override + public void join(List> branches) { + follow(); + joinGroup(branches); + for (Future p : branches) { + if (p instanceof LaneFuture lane) { + lane.raise(); + } + } + } + + /** + * Waits for the given 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> branches) { + Group g = pendingGroup; + if (g != null && allDone(g)) { + flushSyncGroup(this); + g = null; + } + List wanted = new ArrayList<>(); + if (branches.isEmpty() && g != null) { + g.members.forEach(l -> unfinished(l, wanted)); + } + for (Future p : branches) { + if (p instanceof LaneFuture 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) { + l.future.raise(); // a failed item fails the fan-out, as the item threw it + results.add((R) l.result); + } + 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)); + pendingConditions.put(ref, condition); + pause(this); + // a lane kept parked continues here once the wait ended, as a replay of it would + pendingConditions.remove(ref); + return condition.getAsBoolean(); + } + + /** + * 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); + Map entry = exec.entries.get(ref); + // a switch the execution already decided takes the case it recorded, whatever the + // code computes now: a retry or rerun continues on the path the execution is on + Supplier body = entry != null + ? recordedCase(ref, entry, key, cases, otherwise) + : 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); + } + List> outer = out; + List> caseList = null; + int pausesBefore = counter; + if (entry == null) { + 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; + } + } + } + + /** + * The body of the case a recorded switch took: the code's value is not what decides once + * the execution has, so a value that differs on a replay (it came from something that is + * not recorded) cannot move the execution to another case. Only a recorded case this code + * no longer has, with no {@code otherwise} to take it, is a divergence: the code changed. + */ + @SuppressWarnings("unchecked") + private Supplier recordedCase(String ref, Map entry, String key, + Map> cases, Supplier otherwise) { + Map in = (Map) entry.get("inputParameters"); + String recorded = String.valueOf(in == null ? null : in.get("switchCaseValue")); + if (Entries.escape(key).equals(recorded)) { + return cases.containsKey(key) ? cases.get(key) : otherwise; + } + Supplier body = otherwise; + for (Map.Entry> c : cases.entrySet()) { + if (Entries.escape(c.getKey()).equals(recorded)) { + body = c.getValue(); + } + } + if (body == null) { + throw diverged("switch " + ref + " took case " + recorded + " in the recorded execution but the code now takes " + + key + " and has no case for " + recorded); + } + LOGGER.warn("Switch {} of workflow {} took case {} in the recorded execution and the code now computes {} ({}):" + + " continuing on the recorded case. Its value comes from something that is not recorded.", + ref, exec.workflowId, recorded, key, Entries.site()); + return body; + } + + /** + * 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 { + Serializable source = body instanceof ActionCase action ? action.action() : (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 + } + if (same < sites.size() && same < lastSites.size() && sites.get(same).sameMethod(lastSites.get(same)) + && !sites.get(same).shape().paths().reachable(lastSites.get(same).line(), sites.get(same).line())) { + // the same call, but the method it called cannot get from its last call to this + // one: it returned and was called again (a loop around the call) + break; + } + } + 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)); + } + } + } + // a branch the lane is unsure about is not followed until it is decided again for sure + final int sameFrames = same; + path.removeIf(in -> { + if (!unsure.contains(in.branch)) { + return false; + } + boolean again = sameFrames > in.depth && lastSites.size() > in.depth + && sites.get(in.depth).shape().paths().decidesAgain(lastSites.get(in.depth).line(), sites.get(in.depth).line(), in.branch); + if (again) { + unsure.remove(in.branch); + } + return !again; + }); + int keep = 0; + while (keep < inside.size() && keep < path.size() && stillIn(inside.get(keep), path.get(keep), sites, same)) { + Inside open = inside.get(keep); + if (open.depth == same - 1 && lastSites.size() > open.depth + && sites.get(open.depth).shape().paths().mayDecideAgain(open.lastLine, sites.get(open.depth).line(), open.branch)) { + // the code may have gone round and decided it again, or not: no way to tell, so the + // call is not drawn in it, nor in a new one, until it is decided again for sure + unsure.add(open.branch); + break; + } + keep++; + } + // Between the two calls the code returned out of the frames it called from (from their + // calls to their returns, deepest first), went along the frame both share (from one call + // line to the other), and into the frames it calls from now (from their start) + List olds = new ArrayList<>(); + for (int k = lastSites.size() - 1; k >= same; k--) { + olds.add(new Went(lastSites, k, lastSites.get(k).line(), -1)); + } + Went went = same > 0 ? new Went(sites, same - 1, lastSites.get(same - 1).line(), sites.get(same - 1).line()) : null; + List news = new ArrayList<>(); + for (int k = same; k < sites.size(); k++) { + news.add(new Went(sites, k, 0, sites.get(k).line())); // the lane's first call: from the top of its code + } + while (inside.size() > keep) { + Inside in = inside.get(inside.size() - 1); + for (Went w : olds) { + w.drawIn(in); // before the arm ends: they go in its case + } + if (went != null) { + went.drawIn(in); + } + leave(inside.remove(inside.size() - 1)); + } + List entering = new ArrayList<>(); + for (Inside in : path.subList(keep, path.size())) { + if (!unsure.contains(in.branch)) { + entering.add(in); + } + } + // a branch the call is no longer in is not unsure any more + unsure.removeIf(b -> sites.stream().noneMatch(site -> b.armAt(site.line()) != null && site.shape().branches().contains(b))); + for (Went w : olds) { + w.drawRest(entering); + } + if (went != null) { + went.drawRest(entering); + } + int next = 0; + for (Went w : news) { + // a frame's own ifs come after the branches of the frames around it are entered + while (next < entering.size() && entering.get(next).depth < w.depth) { + enterNext(entering, next++, sites, went, news); + } + w.drawRest(entering.subList(next, entering.size())); + } + while (next < entering.size()) { + enterNext(entering, next++, sites, went, news); + } + for (Inside in : inside) { + in.lastLine = sites.get(in.depth).line(); + } + lastSites = sites; + } + + private void enterNext(List entering, int k, List sites, Went went, List news) { + Inside in = entering.get(k); + enter(in, sites); + List later = entering.subList(k + 1, entering.size()); + if (went != null) { + went.drawEntered(in, later); + } + for (Went w : news) { + w.drawEntered(in, later); + } + } + + /** 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)) { + // forward in the code, unless every way there decides the if or switch again: a + // continue that jumps forward to a loop's condition comes round to it + return !sites.get(d).shape().paths().decidesAgain(l, q, open.branch); + } + 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 + } + + /** + * The ifs and switches a frame went through between two of its calls without making one: each + * is drawn with the arm it took when every way between the calls goes through it exactly once + * and in one arm only ({@link CodeReader.Paths#passed}). One inside an arm the lane is leaving + * goes in that arm's case, one inside another drawn here in that one's case, and one inside an + * if or switch that is not drawn is not drawn either. + */ + private final class Went { + private final List sites; + private final int depth; + private final List todo = new ArrayList<>(); + private final CodeReader.Shape shape; + /** Those drawn so far, innermost last, with their case lists. */ + private final List open = new ArrayList<>(); + + Went(List sites, int depth, int fromLine, int toLine) { + this.sites = sites; + this.depth = depth; + this.shape = sites.get(depth).shape(); + for (CodeReader.Passed p : shape.paths().passed(fromLine, toLine)) { + if (toLine <= 0 || p.branch().armAt(toLine) == null) { + todo.add(p); // one the next call is in is entered instead + } + } + } + + /** Draws those whose innermost enclosing branch the lane is in is {@code in}. */ + void drawIn(Inside in) { + for (Iterator it = todo.iterator(); it.hasNext(); ) { + CodeReader.Passed p = it.next(); + if (container(p) == in) { + it.remove(); + draw(p); + } + } + open.clear(); + } + + /** Draws those outside the branches the next call enters (those are drawn as each is entered). */ + void drawRest(List entering) { + Inside innermost = inside.isEmpty() ? null : inside.get(inside.size() - 1); + for (Iterator it = todo.iterator(); it.hasNext(); ) { + CodeReader.Passed p = it.next(); + if (!within(p, entering) && container(p) == innermost) { + it.remove(); + draw(p); + } + } + open.clear(); + } + + /** Draws those in the case of a branch just entered, and not in a branch entered after it. */ + void drawEntered(Inside in, List later) { + for (Iterator it = todo.iterator(); it.hasNext(); ) { + CodeReader.Passed p = it.next(); + if (!within(p, later) && container(p) == in) { + it.remove(); + draw(p); + } + } + open.clear(); + } + + private boolean within(CodeReader.Passed p, List branches) { + return branches.stream().anyMatch(i -> i.depth == depth && i.branch.contains(p.branch())); + } + + private Inside container(CodeReader.Passed p) { + for (int k = inside.size() - 1; k >= 0; k--) { + Inside in = inside.get(k); + if (in.depth < depth || (in.depth == depth && in.branch != p.branch() && in.branch.contains(p.branch()))) { + return in; + } + } + return null; + } + + private void draw(CodeReader.Passed p) { + CodeReader.Branch b = p.branch(); + while (!open.isEmpty() && !((CodeReader.Branch) open.get(open.size() - 1)[0]).contains(b)) { + open.remove(open.size() - 1); + } + for (CodeReader.Branch other : shape.branches()) { + boolean drawnAround = open.stream().anyMatch(o -> o[0] == other) + || inside.stream().anyMatch(i -> i.depth == depth && i.branch == other); + if (other != b && other.contains(b) && !drawnAround) { + return; // inside an if or switch that is not drawn + } + } + String ref = alloc(b.name()); + Map entry = exec.entries.get(ref); + if (entry != null) { + checkTaken(ref, entry, p.arm()); + open.add(new Object[] {b, null}); + return; + } + if (mode != Mode.ACTIVE) { + return; + } + Map sw = branchEntry(b, ref, p.arm()); + tagLoops(sw, loopsAt(sites, depth, b.line())); + @SuppressWarnings("unchecked") + List> parent = open.isEmpty() ? null : (List>) open.get(open.size() - 1)[1]; + if (parent != null) { + parent.add(sw); + } else { + emit(sw); + } + open.add(new Object[] {b, caseList(sw, p.arm())}); + } + } + + /** 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; + } + + /** + * 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() { + // every frame the last call was made from returned: from that call to its return, deepest first + List wents = new ArrayList<>(); + for (int k = lastSites.size() - 1; k >= 0; k--) { + wents.add(new Went(lastSites, k, lastSites.get(k).line(), -1)); + } + if (lastSites.isEmpty() && id.equals("main")) { + // code that made no call at all still went through its ifs and switches + Site root = new Site(spec.method.getDeclaringClass(), spec.method.getName(), + Type.getMethodDescriptor(spec.method), 0); + wents.add(new Went(List.of(root), 0, 0, -1)); + } + while (!inside.isEmpty()) { + Inside in = inside.get(inside.size() - 1); + for (Went w : wents) { + w.drawIn(in); + } + leave(inside.remove(inside.size() - 1)); + } + for (Went w : wents) { + w.drawRest(List.of()); + } + } + + 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 + } + } + + @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) { + Set keys = new 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, 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", "native-code"); // the code decided: the server reads the case it took + 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)) { + 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)); + } + pauseOnLoop(); + 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); + } + + /** + * Pauses on a loop the server runs. What the loop did is in its tasks, which a lane kept + * parked does not have: continuing it reads the execution again ({@link #readsTasks}). + */ + private void pauseOnLoop() { + readsTasks = true; + pause(this); + readsTasks = false; + } + + /** + * 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)) { + 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 entry = new LinkedHashMap<>(); + entry.put("name", loopRef); + entry.put("taskReferenceName", loopRef); + entry.put("type", "DO_WHILE"); + entry.put("inputParameters", Map.of("_items", Entries.escape(Json.plain(items)))); + entry.put("loopCondition", "true"); + entry.put("loopOver", List.of(Entries.of(task, taskRef, id))); + entry.put("metadata", Entries.metadata(id)); + emit(Entries.continuation(entry, id, counter + 1)); + } + pauseOnLoop(); + 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; + } + + 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 result of an async lane, as a {@link Future}. */ + private final class LaneFuture implements Future { + private final Lane lane; + + LaneFuture(Lane lane) { + this.lane = lane; + } + + /** Waits for the lane (a JOIN); what the lane threw comes wrapped, as Future requires. */ + @Override + @SuppressWarnings("unchecked") + public T get() throws ExecutionException { + ((Lane) Engine.current()).joinGroup(List.of(this)); + if (lane.error != null) { + throw new ExecutionException(lane.error); + } + return (T) lane.result; + } + + @Override + public T get(long timeout, TimeUnit unit) { + throw new UnsupportedOperationException( + "workflow code waits for a branch with join(...) or get(); a deadline on the wait is not supported"); + } + + /** Throws what the lane threw, as {@code Conductor.join} does. */ + void raise() { + 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()); + } + } + + /** A branch cannot be cancelled: it runs to its end. */ + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public boolean isDone() { + return lane.state == Replayer.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..18abdfc35 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/TaskStubs.java @@ -0,0 +1,238 @@ +/* + * 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.MethodHandles; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +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 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 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 (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 conductor.workflows(" + 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 conductor.workflows(" + 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(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())); + } + + /** 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; + } +} 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..ce34a4bf1 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/internal/WorkflowSpec.java @@ -0,0 +1,238 @@ +/* + * 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.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +import org.conductoross.conductor.sdk.Query; +import org.conductoross.conductor.sdk.Schedule; +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(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. */ + private static final Map BY_METHOD = new ConcurrentHashMap<>(); + + /** The spec of a {@code @Workflow} method, made once per method. */ + public static WorkflowSpec forMethod(Method method) { + return BY_METHOD.computeIfAbsent(method, WorkflowSpec::of); + } + + 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..6ce259bf2 --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/DirectEngine.java @@ -0,0 +1,474 @@ +/* + * 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.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +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.TaskFailure; +import org.conductoross.conductor.sdk.WorkflowFailedException; +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; + +import com.netflix.conductor.sdk.workflow.executor.task.NonRetryableException; +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +/** + * 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 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(); + // numbered like Replayer.call: x, x_2, x_3 by how many came before + String ref = alloc(cmd.explicitRef != null ? cmd.explicitRef : 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 = answer("external:", cmd, ref); + yield a == null || a.timeout ? Optional.empty() : Optional.ofNullable(Json.convert(a.value, cmd.resultType)); + } + case HUMAN -> { + DurableTestEnvironment.Answer a = answer("human:", cmd, ref); + yield a == null || a.timeout ? Optional.empty() : Optional.ofNullable(Json.convert(a.value, cmd.resultType)); + } + case HTTP -> { + DurableTestEnvironment.Answer a = answer("http:", cmd, 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 = answer(kind, cmd, 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 = answer("llm:", cmd, ref); + if (a == null || a.failure != null) { + throw new TaskFailure(ref, "FAILED", a == null ? "no llm stub for " + ref : a.failure); + } + Object answer = a.value; + if (cmd.resultType != String.class && answer instanceof String text) { + answer = parse(text); // a JSON answer, as the server parses it + } + yield Json.convert(answer, cmd.resultType); + } + }; + } + + /** The stub for this call: one given for its numbered name (x_2), else for the name in the code (x). */ + private DurableTestEnvironment.Answer answer(String kind, Command cmd, String ref) { + DurableTestEnvironment.Answer a = env.answers.get(kind + ref); + return a != null || cmd.explicitRef == null ? a : env.answers.get(kind + cmd.explicitRef); + } + + 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. + WorkerTask wt = + method.getAnnotation(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 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 WorkflowFailedException("switch " + name + " has no case for " + key); + } + return body.get(); + } + + @Override + public Object once(String name, Supplier supplier) { + settleGroup(); + ran.add(alloc(name)); + // as against a server: the code gets the value read back from its JSON, so a value that + // would come back different, or not at all, on a re-run shows in the test + return Json.recorded(Json.record(supplier.get()), supplier.getClass().getClassLoader()); + } + + @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 Future async(Supplier body) { + if (pendingGroup == null) { + pendingGroup = new Group(null); + } + return run(pendingGroup, body); + } + + private DirectFuture run(Group g, Supplier body) { + int before = blockingCalls; + Group saved = pendingGroup; + pendingGroup = null; + DirectFuture p = new DirectFuture<>(); + 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> branches) { + settleGroup(); + for (Future f : branches) { + if (f instanceof DirectFuture p && p.error != null) { + throw p.error; + } + } + } + + @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 (DirectFuture p : g.members) { + if (p.error != null) { + throw p.error; + } + results.add((R) p.value); + } + 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; + TaskFailure failed = null; + for (int i = 0; i < backoff.attempts(); i++) { + try { + result = execute(check, checkRef); + failed = null; + } catch (TaskFailure e) { + // the loop goes on to its next attempt, as the server's does + result = null; + failed = e; + continue; + } + if (result != null && ((Functions.Pred) condition).test(result)) { + break; + } + } + if (failed != null) { + throw failed; // the last check failed: the code gets its failure, as against a server + } + 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; + } + + /** A branch run inline: done by the time async returns. */ + private static final class DirectFuture implements Future { + T value; + RuntimeException error; + + @Override + public T get() throws ExecutionException { + if (error != null) { + throw new ExecutionException(error); + } + return value; + } + + @Override + public T get(long timeout, TimeUnit unit) { + throw new UnsupportedOperationException( + "workflow code waits for a branch with join(...) or get(); a deadline on the wait is not supported"); + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } + + @Override + public boolean isCancelled() { + return false; + } + + @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 WorkflowSpec.forMethod(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..6c1d6e6cb --- /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); + } 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..5c578e384 --- /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 workflows(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..c4a244a1f --- /dev/null +++ b/conductor-client/src/main/java/org/conductoross/conductor/sdk/testing/TestRun.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.testing; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.regex.Pattern; + +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(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/client/automator/TaskRunnerOptionsTest.java b/conductor-client/src/test/java/com/netflix/conductor/client/automator/TaskRunnerOptionsTest.java new file mode 100644 index 000000000..6eea266ba --- /dev/null +++ b/conductor-client/src/test/java/com/netflix/conductor/client/automator/TaskRunnerOptionsTest.java @@ -0,0 +1,277 @@ +/* + * 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 com.netflix.conductor.client.automator; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +import com.netflix.conductor.client.events.dispatcher.EventDispatcher; +import com.netflix.conductor.client.events.taskrunner.TaskRunnerEvent; +import com.netflix.conductor.client.exception.ConductorClientException; +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.TaskResult; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.after; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * The per-runner options (update-v2, polling without domains), and the updates a runner sends: a + * refused update once, a worker that throws once. + */ +@SuppressWarnings("unchecked") // generic test data read back from maps and mocks +class TaskRunnerOptionsTest { + + private TaskRunner runner; + + @AfterEach + void tearDown() { + if (runner != null) { + runner.shutdown(1); + } + } + + private static Task task(String id) { + Task task = new Task(); + task.setTaskId(id); + task.setTaskDefName("code_type"); + task.setWorkflowInstanceId("wf"); + task.setStatus(Task.Status.IN_PROGRESS); + return task; + } + + private Worker worker() { + Worker worker = mock(Worker.class); + when(worker.getTaskDefName()).thenReturn("code_type"); + when(worker.getPollingInterval()).thenReturn(10); + when(worker.getIdentity()).thenReturn("w"); + when(worker.execute(any())).thenAnswer(i -> { + TaskResult result = new TaskResult(i.getArgument(0)); + result.setStatus(TaskResult.Status.COMPLETED); + return result; + }); + return worker; + } + + @SuppressWarnings("unchecked") + private void run(Worker worker, TaskClient client) { + // a domain is configured, and ignored + runner = new TaskRunner(worker, client, 3, Map.of("code_type", "blue"), "test-%d", 2, 100, List.of(), + (EventDispatcher) mock(EventDispatcher.class), true, true, false, null); + Thread poller = new Thread(runner::pollAndExecute); + poller.setDaemon(true); + poller.start(); + } + + @Test + void theNextTaskUpdateV2HandsBackRunsWithoutAPollAndNoDomainIsPolled() { + Task first = task("t1"); + Task next = task("t2"); + TaskClient client = mock(TaskClient.class); + when(client.evaluateAndUploadLargePayload(any(), any())).thenReturn(Optional.empty()); + // after the first task, every poll is a long poll that finds nothing for 3 s + when(client.batchPollTasksInDomain(eq("code_type"), isNull(), anyString(), anyInt(), anyInt())) + .thenReturn(List.of(first)) + .thenAnswer(i -> { + Thread.sleep(3000); + return List.of(); + }); + when(client.updateTaskV2(any(), any())).thenReturn(next, (Task) null); + Worker worker = worker(); + + run(worker, client); + + // runs at once, not when the poll loop comes back from its long poll + verify(worker, timeout(1500)).execute(next); + verify(client, never()).batchPollTasksInDomain(any(), eq("blue"), any(), anyInt(), anyInt()); + verify(client, never()).updateTask(any(), any()); + } + + @Test + void aWorkerThatThrowsIsReportedFailedOnce() { + TaskClient client = mock(TaskClient.class); + when(client.evaluateAndUploadLargePayload(any(), any())).thenReturn(Optional.empty()); + when(client.batchPollTasksInDomain(eq("code_type"), isNull(), anyString(), anyInt(), anyInt())) + .thenReturn(List.of(task("t1")), List.of()); + Worker worker = worker(); + Mockito.doThrow(new IllegalStateException("boom")).when(worker).execute(any()); + + run(worker, client); + + ArgumentCaptor sent = ArgumentCaptor.forClass(TaskResult.class); + verify(client, after(1500).times(1)).updateTaskV2(sent.capture(), any()); + Assertions.assertEquals(TaskResult.Status.FAILED, sent.getValue().getStatus()); + Assertions.assertTrue(sent.getValue().getReasonForIncompletion().contains("boom")); + } + + @Test + void aRefusedUpdateIsNotRetried() { + TaskClient client = mock(TaskClient.class); + when(client.evaluateAndUploadLargePayload(any(), any())).thenReturn(Optional.empty()); + when(client.batchPollTasksInDomain(eq("code_type"), isNull(), anyString(), anyInt(), anyInt())) + .thenReturn(List.of(task("t1")), List.of()); + when(client.updateTaskV2(any(), any())).thenThrow(new ConductorClientException(409, "superseded")); + + run(worker(), client); + + verify(client, after(2500).times(1)).updateTaskV2(any(), any()); + } + + @Test + void aWorkerPausedWhileATaskRunsTakesNoNextTaskFromItsUpdate() { + Task first = task("t1"); + Task next = task("t2"); + AtomicBoolean paused = new AtomicBoolean(); + TaskClient client = mock(TaskClient.class); + when(client.evaluateAndUploadLargePayload(any(), any())).thenReturn(Optional.empty()); + when(client.batchPollTasksInDomain(eq("code_type"), isNull(), anyString(), anyInt(), anyInt())) + .thenReturn(List.of(first), List.of()); + // the queue has a backlog: update-v2 hands back the next task + when(client.updateTaskV2(any(), any())).thenReturn(next, (Task) null); + Worker worker = worker(); + when(worker.paused()).thenAnswer(i -> paused.get()); + when(worker.execute(first)).thenAnswer(i -> { + paused.set(true); // paused while the first task runs + TaskResult result = new TaskResult(first); + result.setStatus(TaskResult.Status.COMPLETED); + return result; + }); + + run(worker, client); + + // paused, it runs nothing more: the first task's result goes with the update that hands + // nothing back + verify(worker, after(1500).never()).execute(next); + verify(client).updateTask(any(), any()); + verify(client, never()).updateTaskV2(any(), any()); + } + + @Test + void aTaskFinishingDuringShutdownTakesNoNextTaskFromItsUpdate() throws Exception { + Task first = task("t1"); + Task next = task("t2"); + CountDownLatch running = new CountDownLatch(1); + CountDownLatch finish = new CountDownLatch(1); + TaskClient client = mock(TaskClient.class); + when(client.evaluateAndUploadLargePayload(any(), any())).thenReturn(Optional.empty()); + when(client.batchPollTasksInDomain(eq("code_type"), isNull(), anyString(), anyInt(), anyInt())) + .thenReturn(List.of(first), List.of()); + // the server leases the next task to whoever completes with update-v2 + when(client.updateTaskV2(any(), any())).thenReturn(next, (Task) null); + Worker worker = worker(); + when(worker.execute(first)).thenAnswer(i -> { + running.countDown(); + finish.await(); + TaskResult result = new TaskResult(first); + result.setStatus(TaskResult.Status.COMPLETED); + return result; + }); + + run(worker, client); + running.await(); + Thread stopping = new Thread(() -> runner.shutdown(5)); // waits for the task in flight + stopping.start(); + Thread.sleep(500); + finish.countDown(); + stopping.join(); + + // a task handed back now could not run (the executor refuses it) and would wait out its + // lease: the result goes with the update that hands nothing back + verify(client, never()).updateTaskV2(any(), any()); + verify(client).updateTask(any(), any()); + verify(worker, never()).execute(next); + } + + @Test + void aTaskHandedBackAfterShutdownBeganStillRuns() throws Exception { + Task first = task("t1"); + Task next = task("t2"); + CountDownLatch updating = new CountDownLatch(1); + CountDownLatch answer = new CountDownLatch(1); + TaskClient client = mock(TaskClient.class); + when(client.evaluateAndUploadLargePayload(any(), any())).thenReturn(Optional.empty()); + when(client.batchPollTasksInDomain(eq("code_type"), isNull(), anyString(), anyInt(), anyInt())) + .thenReturn(List.of(first), List.of()); + // the first task's update is on its way when shutdown begins; the server answers it + // with the next task, leased to this worker + when(client.updateTaskV2(any(), any())).thenAnswer(i -> { + updating.countDown(); + answer.await(); + return next; + }); + Worker worker = worker(); + + run(worker, client); + updating.await(); + Thread stopping = new Thread(() -> runner.shutdown(5)); + stopping.start(); + Thread.sleep(500); + answer.countDown(); + stopping.join(); + + // the executor takes nothing new, so the task runs on the thread that received it; its + // own result goes with the update that hands nothing back + verify(worker).execute(next); + verify(client).updateTask(any(), any()); + verify(client, Mockito.times(1)).updateTaskV2(any(), any()); + } + + @Test + void theTasksOfAPollInFlightWhenShutdownBeginsStillRun() throws Exception { + Task first = task("t1"); + CountDownLatch polling = new CountDownLatch(1); + CountDownLatch answer = new CountDownLatch(1); + TaskClient client = mock(TaskClient.class); + when(client.evaluateAndUploadLargePayload(any(), any())).thenReturn(Optional.empty()); + // the poll is on its way when shutdown begins; the server answers it with a task + when(client.batchPollTasksInDomain(eq("code_type"), isNull(), anyString(), anyInt(), anyInt())) + .thenAnswer(i -> { + polling.countDown(); + answer.await(); + return List.of(first); + }) + .thenReturn(List.of()); + Worker worker = worker(); + + run(worker, client); + polling.await(); + Thread stopping = new Thread(() -> runner.shutdown(5)); + stopping.start(); + Thread.sleep(500); + answer.countDown(); + stopping.join(); + + verify(worker).execute(first); + verify(client).updateTask(any(), any()); + verify(client, never()).updateTaskV2(any(), any()); + } +} 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..e8f8b21b2 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 @@ -356,6 +356,34 @@ void threadCountTest() { assertEquals(2, taskThreadCount.get("test_2")); } + static class SingleThreaded { + @WorkerTask(value = "single", threadCount = 1) + public void single() {} + } + + @Test + @DisplayName("a task that sets no thread count gets the configuration's default; one that sets 1 keeps 1") + void defaultThreadCount() { + WorkerConfiguration eight = new WorkerConfiguration() { + @Override + public int getDefaultThreadCount() { + return 8; + } + }; + AnnotatedWorkerExecutor executor = new AnnotatedWorkerExecutor(mock(TaskClient.class), eight); + executor.addBean(new MultipleInputParams()); + executor.addBean(new AnotherAnnotationInput()); + executor.addBean(new SingleThreaded()); + + executor.startPolling(); + Map taskThreadCount = executor.getTaskRunner().getTaskThreadCount(); + executor.shutdown(); + + assertEquals(3, taskThreadCount.get("test_1")); + assertEquals(8, taskThreadCount.get("test_2")); + assertEquals(1, taskThreadCount.get("single")); + } + static class WorkflowInstanceIdInputParamAsStringWorker { @WorkerTask(value = "test_1", threadCount = 3, pollingInterval = 333) public Map doWork( @@ -414,4 +442,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 { + @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/com/netflix/conductor/sdk/workflow/executor/task/UnannotatedParameterBindingTest.java b/conductor-client/src/test/java/com/netflix/conductor/sdk/workflow/executor/task/UnannotatedParameterBindingTest.java new file mode 100644 index 000000000..151db6855 --- /dev/null +++ b/conductor-client/src/test/java/com/netflix/conductor/sdk/workflow/executor/task/UnannotatedParameterBindingTest.java @@ -0,0 +1,173 @@ +/* + * 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 com.netflix.conductor.sdk.workflow.executor.task; + +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.tools.JavaCompiler; +import javax.tools.ToolProvider; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import com.netflix.conductor.common.metadata.tasks.Task; +import com.netflix.conductor.common.metadata.tasks.TaskResult; +import com.netflix.conductor.common.metadata.workflow.WorkflowTask; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * How a {@code @WorkerTask} parameter without an annotation is bound when the worker is compiled + * with {@code -parameters}, as Spring Boot applications are. The worker here is compiled that way + * by the test, since this build is not. + */ +class UnannotatedParameterBindingTest { + + private static final String SOURCE = """ + package bound; + + import com.netflix.conductor.sdk.workflow.task.WorkerTask; + + public class Notifier { + public static class Message { + public String message; + public String level; + } + + @WorkerTask("notify") + public String notify(Message message) { + return message.level + ": " + message.message; + } + + @WorkerTask("count") + public String count(java.util.Map data) { + return "keys " + new java.util.TreeSet<>(data.keySet()); + } + + @WorkerTask("tally") + public String tally(@com.netflix.conductor.sdk.workflow.task.InputParam("values") java.util.Map counts) { + return "keys " + new java.util.TreeSet<>(counts.keySet()); + } + + @WorkerTask("greet") + public String greet(String name, int times) { + return name + " x" + times; + } + } + """; + + private static Object notifier; + + @BeforeAll + static void compileWithParameterNames(@TempDir Path dir) throws Exception { + Path source = Files.createDirectories(dir.resolve("src/bound")).resolve("Notifier.java"); + Files.writeString(source, SOURCE); + Path classes = Files.createDirectories(dir.resolve("classes")); + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + int status = compiler.run(null, null, null, "-parameters", "-d", classes.toString(), + "-classpath", System.getProperty("java.class.path"), source.toString()); + assertEquals(0, status, "the worker did not compile"); + ClassLoader loader = new URLClassLoader(new URL[] {classes.toUri().toURL()}, UnannotatedParameterBindingTest.class.getClassLoader()); + notifier = loader.loadClass("bound.Notifier").getDeclaredConstructor().newInstance(); + } + + private static Method method(String name) { + for (Method m : notifier.getClass().getMethods()) { + if (m.getName().equals(name)) { + return m; + } + } + throw new AssertionError(name); + } + + private static Task task(Map input) { + Task task = new Task(); + task.setStatus(Task.Status.IN_PROGRESS); + task.setInputData(new HashMap<>(input)); + return task; + } + + /** A task as a native workflow schedules it: its entry names the lane of the code that called it. */ + private static Task nativeTask(Map input) { + Task task = task(input); + WorkflowTask entry = new WorkflowTask(); + entry.setMetadata(new HashMap<>(Map.of("lane", "main"))); + task.setWorkflowTask(entry); + return task; + } + + @Test + void anObjectParameterStillBindsTheWholeInputWhenAFieldHasTheParametersName() { + assertEquals(true, method("notify").getParameters()[0].isNamePresent(), "compiled with -parameters"); + AnnotatedWorker worker = new AnnotatedWorker("notify", method("notify"), notifier); + + // a workflow definition passes the object's fields, one of them named as the parameter is + TaskResult result = worker.execute(task(Map.of("message", "hi", "level", "warn"))); + + assertEquals(TaskResult.Status.COMPLETED, result.getStatus(), result.getReasonForIncompletion()); + assertEquals("warn: hi", result.getOutputData().get("result")); + } + + @Test + void aNativeWorkflowsCallBindsEachParameterByItsName() { + AnnotatedWorker worker = new AnnotatedWorker("notify", method("notify"), notifier); + + // a native workflow sends each argument under its parameter's name + TaskResult result = worker.execute(nativeTask(Map.of("message", Map.of("message", "hi", "level", "warn")))); + + assertEquals(TaskResult.Status.COMPLETED, result.getStatus(), result.getReasonForIncompletion()); + assertEquals("warn: hi", result.getOutputData().get("result")); + } + + @Test + void scalarParametersBindByNameFromAnyWorkflow() { + AnnotatedWorker worker = new AnnotatedWorker("greet", method("greet"), notifier); + + for (Task task : List.of(task(Map.of("name", "ann", "times", 2)), nativeTask(Map.of("name", "ann", "times", 2)))) { + TaskResult result = worker.execute(task); + assertEquals(TaskResult.Status.COMPLETED, result.getStatus(), result.getReasonForIncompletion()); + assertEquals("ann x2", result.getOutputData().get("result")); + } + } + + @Test + void aSingleMapParameterIsTheWholeInputOfAnyOtherWorkflow() { + for (String name : List.of("count", "tally")) { + AnnotatedWorker worker = new AnnotatedWorker(name, method(name), notifier); + + TaskResult result = worker.execute(task(Map.of("a", 1, "b", 2))); + + assertEquals("keys [a, b]", result.getOutputData().get("result")); + } + } + + @Test + void aSingleMapParameterOfANativeWorkflowsCallIsTheMapItPassed() { + AnnotatedWorker count = new AnnotatedWorker("count", method("count"), notifier); + // a native workflow sends the map under its parameter's name, as it sends every argument + assertEquals("keys [a, b]", + count.execute(nativeTask(Map.of("data", Map.of("a", 1, "b", 2)))).getOutputData().get("result")); + + AnnotatedWorker tally = new AnnotatedWorker("tally", method("tally"), notifier); + assertEquals("keys [a, b]", + tally.execute(nativeTask(Map.of("values", Map.of("a", 1, "b", 2)))).getOutputData().get("result")); + } +} diff --git a/conductor-client/src/test/java/dowhile/DoWhileTest.java b/conductor-client/src/test/java/dowhile/DoWhileTest.java new file mode 100644 index 000000000..f03a4fe5c --- /dev/null +++ b/conductor-client/src/test/java/dowhile/DoWhileTest.java @@ -0,0 +1,379 @@ +/* + * 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 dowhile; + +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.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 org.slf4j.LoggerFactory; + +import com.netflix.conductor.sdk.workflow.task.InputParam; +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +import static org.conductoross.conductor.sdk.Conductor.doWhile; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * doWhile is ordinary code in a loop the code names: every step its body makes is tagged with the + * loop, as the steps of a plain Java loop are with the loop read from the compiled code. + */ +class DoWhileTest { + + /** The task stub the workflows below call: its calls schedule the tasks. */ + static final Tasks TASKS = Conductor.stub(Tasks.class); + + public static class Tasks { + @WorkerTask("dw_step") + public String step(@InputParam("x") String x) { + return x; + } + + @WorkerTask("dw_extra") + public String extra(@InputParam("x") String x) { + return x; + } + + @WorkerTask("dw_done") + public String done(@InputParam("x") String x) { + return x; + } + } + + /** Two passes of one task, then a task after the loop. */ + public static class Twice { + @Workflow(name = "dw_twice") + public String run(Map input) { + int[] pass = {0}; + doWhile("poll", () -> { + TASKS.step("p" + pass[0]); + pass[0]++; + }, () -> pass[0] < 2); + return TASKS.done("z"); + } + } + + /** An if in the body, and a Java loop around the doWhile. */ + public static class Nested { + @Workflow(name = "dw_nested") + public String run(@InputParam("rounds") List rounds) { + for (String round : rounds) { + int[] pass = {0}; + doWhile("inner", () -> { + if (round.equals("a")) { + TASKS.extra(round); + } + pass[0]++; + }, () -> pass[0] < 1); + } + return TASKS.done("z"); + } + } + + /** The body throws on its first pass. */ + public static class Throws { + @Workflow(name = "dw_throws") + public String run(Map input) { + doWhile("poll", () -> { + if (input.get("fail") != null) { + throw new IllegalStateException("no"); + } + TASKS.step("p"); + }, () -> false); + return TASKS.done("z"); + } + } + + /** A loop whose condition reads something that is not recorded, so it can differ on a replay. */ + public static class Unrecorded { + static volatile boolean again; + + @Workflow(name = "dw_unrecorded") + public String run(Map input) { + doWhile("poll", () -> TASKS.step("p"), () -> again); + return TASKS.done("z"); + } + } + + /** A loop whose condition calls a task. */ + public static class TaskInCondition { + @Workflow(name = "dw_cond") + public String run(Map input) { + doWhile("poll", () -> TASKS.step("p"), () -> TASKS.extra("more").equals("yes")); + return TASKS.done("z"); + } + } + + private static WorkflowSpec spec(Class type) { + return WorkflowSpec.of(type).get(0); + } + + private static Execution execution(String name, 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", name, "tasks", defTasks)); + json.put("tasks", tasks); + json.put("nativeState", Map.of("bootstrap", bootstrap)); + return new Execution(json); + } + + /** A marker of continuation {@code n} of the main lane; applied at {@code step} when APPLIED. */ + private static Map marker(int n, String state, long step) { + Map m = new LinkedHashMap<>(); + m.put("lane", "main"); + m.put("n", n); + if ("APPLIED".equals(state)) { + m.put("endTime", step); + } + m.put("leased", "LEASED".equals(state)); + m.put("resumedWith", Map.of()); + m.put("recorded", Map.of()); + return m; + } + + /** An applied marker that recorded these values. */ + private static Map marker(int n, long step, Object recorded) { + Map m = marker(n, "APPLIED", step); + m.put("recorded", recorded); + return m; + } + + /** What the replayer logged at WARN while {@code body} ran. */ + private static List warnings(Runnable body) { + ch.qos.logback.classic.Logger logger = + (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Replayer.class); + ch.qos.logback.core.read.ListAppender seen = new ch.qos.logback.core.read.ListAppender<>(); + seen.start(); + logger.addAppender(seen); + try { + body.run(); + } finally { + logger.detachAppender(seen); + } + return seen.list.stream() + .filter(e -> e.getLevel() == ch.qos.logback.classic.Level.WARN) + .map(ch.qos.logback.classic.spi.ILoggingEvent::getFormattedMessage) + .toList(); + } + + private static Map entry(String ref, String name, int continuation, List loops) { + Map e = new LinkedHashMap<>(); + e.put("name", name); + e.put("taskReferenceName", ref); + e.put("type", "SIMPLE"); + e.put("metadata", Map.of("lane", "main", "continuation", continuation, "loops", loops)); + 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", type, "metadata", + Map.of("lane", "main", "continuation", continuation.get("n")))); + t.put("continuation", continuation); + return t; + } + + @SuppressWarnings("unchecked") + private static List> fragment(Replayer.Outcome out) { + return (List>) out.output.get("fragment"); + } + + @SuppressWarnings("unchecked") + private static Map metadata(Map entry) { + return (Map) entry.get("metadata"); + } + + private static List refs(List> entries) { + return entries.stream().map(e -> e.get("taskReferenceName")).toList(); + } + + @Test + void eachPassOfTheBodyIsInTheNamedLoopAndWhatFollowsIsNot() { + WorkflowSpec spec = spec(Twice.class); + Execution first = execution("dw_twice", Map.of(), List.of(), List.of(), marker(1, "LEASED", 0)); + List> one = fragment(new Replayer(spec, spec.newInstance(), first).process("main", 1)); + assertEquals(List.of("dw_step"), refs(one)); + assertEquals(List.of("poll"), metadata(one.get(0)).get("loops")); + + Execution second = execution("dw_twice", Map.of(), + List.of(entry("dw_step", "dw_step", 2, List.of("poll"))), + List.of(doneTask("dw_step", "dw_step", 1, Map.of("result", "p0"), marker(2, "LEASED", 0))), + marker(1, "APPLIED", 1)); + List> two = fragment(new Replayer(spec, spec.newInstance(), second).process("main", 2)); + assertEquals(List.of("dw_step_2"), refs(two)); + assertEquals(List.of("poll"), metadata(two.get(0)).get("loops")); + + Execution third = execution("dw_twice", Map.of(), + List.of(entry("dw_step", "dw_step", 2, List.of("poll")), entry("dw_step_2", "dw_step", 3, List.of("poll"))), + List.of(doneTask("dw_step", "dw_step", 1, Map.of("result", "p0"), marker(2, "APPLIED", 2)), + doneTask("dw_step_2", "dw_step", 2, Map.of("result", "p1"), marker(3, "LEASED", 0))), + marker(1, "APPLIED", 1)); + List> three = fragment(new Replayer(spec, spec.newInstance(), third).process("main", 3)); + assertEquals(List.of("dw_done"), refs(three)); + assertNull(metadata(three.get(0)).get("loops"), "the loop ended: the next call is outside it"); + } + + @SuppressWarnings("unchecked") + @Test + void anIfInTheBodyIsInTheLoopInsideTheJavaLoopAroundIt() { + WorkflowSpec spec = spec(Nested.class); + Execution first = execution("dw_nested", Map.of("rounds", List.of("a")), List.of(), List.of(), marker(1, "LEASED", 0)); + List> fragment = fragment(new Replayer(spec, spec.newInstance(), first).process("main", 1)); + assertEquals(1, fragment.size()); + Map sw = fragment.get(0); + assertEquals("SWITCH", sw.get("type")); + List loops = (List) metadata(sw).get("loops"); + assertEquals(2, loops.size(), "the Java for loop, then the doWhile: " + loops); + assertTrue(loops.get(0).startsWith("Nested_loop_"), loops.get(0)); + assertEquals("inner", loops.get(1)); + Map extra = ((Map>>) sw.get("decisionCases")).get("true").get(0); + assertEquals(loops, metadata(extra).get("loops")); + } + + @SuppressWarnings("unchecked") + @Test + void aThrowInTheBodyIsMarkedInTheLoop() { + WorkflowSpec spec = spec(Throws.class); + Execution first = execution("dw_throws", Map.of("fail", true), List.of(), List.of(), marker(1, "LEASED", 0)); + List> fragment = fragment(new Replayer(spec, spec.newInstance(), first).process("main", 1)); + // the code threw inside the if in the body: the mark is in that if's case + Map sw = fragment.get(0); + assertEquals("SWITCH", sw.get("type"), String.valueOf(fragment)); + assertEquals(List.of("poll"), metadata(sw).get("loops")); + Map thrown = ((Map>>) sw.get("decisionCases")).get("true").stream() + .filter(e -> "TERMINATE".equals(e.get("type"))).findFirst().orElse(null); + assertNotNull(thrown, "the mark of where the code threw: " + sw); + assertEquals(List.of("poll"), metadata(thrown).get("loops")); + } + + @Test + void aLoopTakesTheRecordedNumberOfPassesWhenItsConditionDiffersOnReplay() { + WorkflowSpec spec = spec(Unrecorded.class); + // live: the first pass's task is done and the condition says the loop ends + Unrecorded.again = false; + Execution second = execution("dw_unrecorded", Map.of(), + List.of(entry("dw_step", "dw_step", 2, List.of("poll"))), + List.of(doneTask("dw_step", "dw_step", 1, Map.of("result", "p"), marker(2, "LEASED", 0))), + marker(1, "APPLIED", 1)); + Replayer.Outcome live = new Replayer(spec, spec.newInstance(), second).process("main", 2); + assertEquals(List.of("dw_done"), refs(fragment(live))); + Object recorded = live.output.get("recorded"); + assertTrue(recorded instanceof Map values && values.containsKey("poll_again"), + "the pass's outcome is recorded with the continuation: " + recorded); + + // the task after the loop failed and was retried: the code runs again from the top, and + // what the condition reads has changed since + Unrecorded.again = true; + Map failed = doneTask("dw_done", "dw_done", 2, Map.of(), marker(3, "APPLIED", 3)); + failed.put("status", "FAILED"); + Execution retried = execution("dw_unrecorded", Map.of(), + List.of(entry("dw_step", "dw_step", 2, List.of("poll")), entry("dw_done", "dw_done", 3, List.of())), + List.of(doneTask("dw_step", "dw_step", 1, Map.of("result", "p"), marker(2, 2, recorded)), + failed, + doneTask("dw_done", "dw_done", 3, Map.of("result", "z"), marker(3, "LEASED", 0))), + marker(1, "APPLIED", 1)); + Replayer.Outcome[] out = new Replayer.Outcome[1]; + List warnings = warnings(() -> out[0] = new Replayer(spec, spec.newInstance(), retried).process("main", 3)); + + assertEquals(true, out[0].output.get("done"), String.valueOf(out[0].output)); + assertNull(out[0].output.get("error"), String.valueOf(out[0].output)); + assertEquals(1, warnings.size(), warnings.toString()); + assertTrue(warnings.get(0).contains("poll"), warnings.get(0)); + } + + @Test + void aLoopWhoseConditionCallsATaskReplaysWithEveryCallReached() { + WorkflowSpec spec = spec(TaskInCondition.class); + // live: the body's task and the condition's task are done, and the condition ends the loop + Execution third = execution("dw_cond", Map.of(), + List.of(entry("dw_step", "dw_step", 2, List.of("poll")), entry("dw_extra", "dw_extra", 3, List.of("poll"))), + List.of(doneTask("dw_step", "dw_step", 1, Map.of("result", "p"), marker(2, "APPLIED", 2)), + doneTask("dw_extra", "dw_extra", 2, Map.of("result", "no"), marker(3, "LEASED", 0))), + marker(1, "APPLIED", 1)); + Replayer.Outcome live = new Replayer(spec, spec.newInstance(), third).process("main", 3); + assertEquals(List.of("dw_done"), refs(fragment(live))); + + // the next continuation replays the loop: the condition's task is still reached + Execution fourth = execution("dw_cond", Map.of(), + List.of(entry("dw_step", "dw_step", 2, List.of("poll")), entry("dw_extra", "dw_extra", 3, List.of("poll")), + entry("dw_done", "dw_done", 4, List.of())), + List.of(doneTask("dw_step", "dw_step", 1, Map.of("result", "p"), marker(2, "APPLIED", 2)), + doneTask("dw_extra", "dw_extra", 2, Map.of("result", "no"), marker(3, 3, live.output.get("recorded"))), + doneTask("dw_done", "dw_done", 3, Map.of("result", "z"), marker(4, "LEASED", 0))), + marker(1, "APPLIED", 1)); + Replayer.Outcome[] out = new Replayer.Outcome[1]; + List warnings = warnings(() -> out[0] = new Replayer(spec, spec.newInstance(), fourth).process("main", 4)); + + assertEquals(true, out[0].output.get("done"), String.valueOf(out[0].output)); + assertNull(out[0].output.get("error"), String.valueOf(out[0].output)); + assertEquals(List.of(), warnings); + } + + @Test + void anExecutionRecordedWithoutThePassesOfItsLoopsReplaysAsBefore() { + WorkflowSpec spec = spec(Twice.class); + // recorded by a build that did not record the passes: no marker has a value for them + Execution fourth = execution("dw_twice", Map.of(), + List.of(entry("dw_step", "dw_step", 2, List.of("poll")), entry("dw_step_2", "dw_step", 3, List.of("poll")), + entry("dw_done", "dw_done", 4, List.of())), + List.of(doneTask("dw_step", "dw_step", 1, Map.of("result", "p0"), marker(2, "APPLIED", 2)), + doneTask("dw_step_2", "dw_step", 2, Map.of("result", "p1"), marker(3, "APPLIED", 3)), + doneTask("dw_done", "dw_done", 3, Map.of("result", "z"), marker(4, "LEASED", 0))), + marker(1, "APPLIED", 1)); + Replayer.Outcome out = new Replayer(spec, spec.newInstance(), fourth).process("main", 4); + + assertEquals(true, out.output.get("done"), String.valueOf(out.output)); + assertNull(out.output.get("error"), String.valueOf(out.output)); + } + + @Test + void outsideAWorkflowItIsAPlainLoop() { + int[] passes = {0}; + doWhile("plain", () -> passes[0]++, () -> passes[0] < 3); + assertEquals(3, passes[0]); + } + + @Test + void theDefinitionReadFromTheCodeHasTheBodyInTheNamedLoop() { + List> entries = Replayer.discover(spec(Twice.class)); + assertEquals(List.of("dw_step", "dw_done"), refs(entries)); + assertEquals(List.of("poll"), metadata(entries.get(0)).get("loops")); + assertNull(metadata(entries.get(1)).get("loops")); + + List> nested = Replayer.discover(spec(Nested.class)); + List all = new ArrayList<>(); + nested.forEach(e -> all.add(metadata(e).get("loops"))); + assertEquals(2, ((List) all.get(0)).size(), "the for loop, then the doWhile: " + all); + assertEquals("inner", ((List) all.get(0)).get(1)); + } +} 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..a1c1d1c53 --- /dev/null +++ b/conductor-client/src/test/java/loopfixture/CodeLoopsTest.java @@ -0,0 +1,170 @@ +/* + * 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 aGuardedPatternSwitchIsNotALoop() throws Exception { + onOwnThread(() -> { + // javac restarts the switch at the next case when a guard fails: a jump back that is + // not a loop in the code + assertEquals(List.of(List.of(), List.of()), guarded(3)); + assertEquals(List.of(List.of(), List.of()), guarded(9)); + assertEquals(List.of(List.of(), List.of()), guarded("s")); + }); + } + + private static List> guarded(Object value) { + List before = CodeLoops.here(); + List inCase = switch (value) { + case Integer i when i > 5 -> CodeLoops.here(); + case Integer i -> CodeLoops.here(); + default -> CodeLoops.here(); + }; + return List.of(before, inCase); + } + + @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/ConcurrentStartTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/ConcurrentStartTest.java new file mode 100644 index 000000000..61126fe4d --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/ConcurrentStartTest.java @@ -0,0 +1,99 @@ +/* + * 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.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +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.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; + +/** One {@link Conductor} used from several threads: a start while another thread adds workers. */ +class ConcurrentStartTest { + + public static class First { + @Workflow(name = "concurrent_first", version = 1) + public String run(@InputParam("input") String input) { + return input; + } + } + + public static class Second { + @Workflow(name = "concurrent_second", version = 1) + public String run(@InputParam("input") String input) { + return input; + } + } + + private MockWebServer server; + private Conductor conductor; + /** Held until the test lets the server answer: the registration of First waits on it. */ + private final CountDownLatch serverAnswers = new CountDownLatch(1); + + @BeforeEach + void start() throws Exception { + server = new MockWebServer(); + server.setDispatcher(new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + String path = request.getPath() == null ? "" : request.getPath().replaceAll("\\?.*", ""); + MockResponse json = new MockResponse().setHeader("Content-Type", "application/json"); + if (path.startsWith("/api/tasks/")) { + return json.setBody("[]"); // polls find nothing + } + serverAnswers.await(); + if ("POST".equals(request.getMethod()) && path.equals("/api/workflow")) { + return new MockResponse().setBody("wf-1"); // the id, as text + } + return json.setBody("GET".equals(request.getMethod()) ? "[]" : "\"ok\""); + } + }); + server.start(); + conductor = Conductor.of(ConductorClient.builder().basePath(server.url("/api").toString()).build()); + } + + @AfterEach + void stop() throws Exception { + serverAnswers.countDown(); + conductor.close(); + server.shutdown(); + } + + @Test + void aStartWaitingForRegistrationIsNotBrokenByAnotherThreadAddingWorkers() throws Exception { + Workers first = conductor.workflows(First.class).start(); // registering: the server has not answered + + // a start in the same process waits for that registration... + CompletableFuture started = CompletableFuture.supplyAsync( + () -> conductor.start(First::run, "x").workflowId()); + Thread.sleep(300); + // ... and meanwhile another thread hosts another workflow on the same Conductor + conductor.workflows(Second.class); + serverAnswers.countDown(); + + assertEquals("wf-1", started.get(20, TimeUnit.SECONDS)); + first.close(); + } +} 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/ParkedExecutionsTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/ParkedExecutionsTest.java new file mode 100644 index 000000000..8c9ba6c00 --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/ParkedExecutionsTest.java @@ -0,0 +1,432 @@ +/* + * 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.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +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.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.common.metadata.tasks.TaskResult; +import com.netflix.conductor.common.metadata.workflow.WorkflowTask; +import com.netflix.conductor.sdk.workflow.task.InputParam; +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * An execution's code stays in memory between its continuations, pinned to the worker that holds + * it: what a worker fetches, replays and tells the server, against a server that answers by path. + */ +class ParkedExecutionsTest { + + static final Tasks TASKS = Conductor.stub(Tasks.class); + static final String CODE_TYPE = "pk_two.v1.code"; + + public static class Tasks { + @WorkerTask("pk_one") + public String one(@InputParam("x") String x) { + return x; + } + + @WorkerTask("pk_two") + public String two(@InputParam("x") String x) { + return x; + } + } + + /** How many times the method ran from its first line, in this JVM. */ + static final AtomicInteger RAN_FROM_THE_TOP = new AtomicInteger(); + + public static class TwoSteps { + @Variable + String stage = "new"; + + @Workflow(name = "pk_two") + public String run(@InputParam("order") String order) { + RAN_FROM_THE_TOP.incrementAndGet(); + String a = TASKS.one(order); + String was = stage; // a signal handler may have changed it while the task ran + stage = "half"; + String b = TASKS.two(a); + return a + b + ":" + was; + } + } + + /** The execution before its code ran at all. */ + private static final String FRESH = "{\"workflowId\":\"wf-1\",\"status\":\"RUNNING\",\"input\":{\"order\":\"o\"}," + + "\"variables\":{},\"workflowDefinition\":{\"name\":\"pk_two\",\"tasks\":[]},\"tasks\":[]," + + "\"nativeState\":{\"bootstrap\":{\"leased\":true}}}"; + + /** The execution once its first continuation applied and pk_one completed. */ + private static final String AFTER_ONE = "{\"workflowId\":\"wf-1\",\"status\":\"RUNNING\",\"input\":{\"order\":\"o\"}," + + "\"variables\":{\"stage\":\"new\"},\"workflowDefinition\":{\"name\":\"pk_two\",\"tasks\":[" + + "{\"name\":\"pk_one\",\"taskReferenceName\":\"pk_one\",\"type\":\"SIMPLE\"," + + "\"metadata\":{\"lane\":\"main\",\"continuation\":2}}]}," + + "\"tasks\":[{\"taskId\":\"id-pk_one\",\"referenceTaskName\":\"pk_one\",\"taskType\":\"pk_one\"," + + "\"status\":\"COMPLETED\",\"seq\":1,\"outputData\":{\"result\":\"A\"}," + + "\"workflowTask\":{\"type\":\"SIMPLE\",\"metadata\":{\"lane\":\"main\",\"continuation\":2}}," + + "\"continuation\":{\"leased\":true}}]," + + "\"nativeState\":{\"bootstrap\":{\"endTime\":1}}}"; + + private MockWebServer server; + private Conductor conductor; + private Workers workers; + private volatile String execution = FRESH; + private final AtomicInteger fetched = new AtomicInteger(); + private final Set polledDomains = ConcurrentHashMap.newKeySet(); + private final Map settings = new HashMap<>(); + + @BeforeEach + void start() throws Exception { + RAN_FROM_THE_TOP.set(0); + server = new MockWebServer(); + server.setDispatcher(new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) { + String path = request.getPath() == null ? "" : request.getPath(); + if (!request.getMethod().equals("GET")) { + return json("\"ok\""); + } + if (path.startsWith("/api/workflow/wf-1")) { + fetched.incrementAndGet(); + return json(execution); + } + if (path.startsWith("/api/tasks/poll/batch/")) { + String domain = request.getRequestUrl().queryParameter("domain"); + polledDomains.add(domain == null ? "" : domain); + } + return json("[]"); + } + }); + server.start(); + conductor = Conductor.of(ConductorClient.builder().basePath(server.url("/api").toString()).build()); + } + + @AfterEach + void stop() throws Exception { + if (workers != null) { + workers.close(); + } + server.shutdown(); + } + + private static MockResponse json(String body) { + return new MockResponse().setHeader("Content-Type", "application/json").setBody(body); + } + + private Workers hosted() { + workers = conductor.workflows(TwoSteps.class).settings(settings::get).start(); + return workers; + } + + /** A continuation as a poll hands it out; {@code variables} null is a server that pins nothing. */ + private static Task continuation(String taskId, String ref, int n, String status, Map output, + String stamp, Map variables) { + WorkflowTask entry = new WorkflowTask(); + entry.setTaskReferenceName(ref); + entry.setMetadata(new HashMap<>(Map.of("lane", "main", "continuation", n))); + TaskContinuation marker = new TaskContinuation(); + marker.setLeased(true); + marker.setStamp(stamp); + marker.setVariables(variables); + Task task = new Task(); + task.setWorkflowTask(entry); + task.setTaskId(taskId); + task.setWorkflowInstanceId("wf-1"); + task.setReferenceTaskName(ref); + task.setTaskType(ref); + task.setStatus(Task.Status.valueOf(status)); + task.setOutputData(output); + task.setContinuation(marker); + return task; + } + + private static Task first(Map variables) { + return continuation("wf-1|main", "main", 1, "IN_PROGRESS", Map.of(), null, variables); + } + + @SuppressWarnings("unchecked") + private static Map pin(TaskResult result) { + return (Map) result.getOutputData().get("pin"); + } + + @SuppressWarnings("unchecked") + private static List refs(TaskResult result) { + return ((List>) result.getOutputData().get("fragment")).stream() + .map(e -> e.get("taskReferenceName")).toList(); + } + + @Test + void theNextContinuationOfAnExecutionHeldInMemoryFetchesNothingAndRunsNothingAgain() { + hosted(); + + TaskResult one = workers.process(CODE_TYPE, first(Map.of())); + + assertEquals(List.of("pk_one"), refs(one)); + assertEquals(1, fetched.get()); + // the completion tells the server where the execution is held, and names itself + assertEquals(workers.pinDomain(), pin(one).get("domain")); + String stamp = (String) pin(one).get("stamp"); + assertEquals(1, workers.parked().held(CODE_TYPE)); + + // the server hands the stamp back with the task the code waited for, and the variables: a + // signal handler set the stage meanwhile + TaskResult two = workers.process(CODE_TYPE, continuation("id-pk_one", "pk_one", 2, "COMPLETED", + Map.of("result", "A"), stamp, Map.of("stage", "signalled"))); + + assertEquals(TaskResult.Status.COMPLETED, two.getStatus()); + assertEquals(List.of("pk_two"), refs(two)); + assertEquals(1, fetched.get()); // nothing fetched + assertEquals(1, RAN_FROM_THE_TOP.get()); // nothing run again + assertEquals(Map.of("stage", "signalled"), two.getOutputData().get("resumedWith")); + assertEquals(Map.of("stage", "half"), two.getOutputData().get("variables")); + assertEquals(2, two.getOutputData().get("n")); + String next = (String) pin(two).get("stamp"); + assertNotEquals(stamp, next); + + TaskResult three = workers.process(CODE_TYPE, continuation("id-pk_two", "pk_two", 3, "COMPLETED", + Map.of("result", "B"), next, Map.of("stage", "half"))); + + assertEquals(true, three.getOutputData().get("done")); + assertEquals(Map.of("result", "AB:signalled"), three.getOutputData().get("result")); + assertEquals(1, fetched.get()); + assertEquals(1, RAN_FROM_THE_TOP.get()); + // the code returned: there is nothing to hold, and the completion says so + assertNull(pin(three)); + assertEquals(0, workers.parked().held(CODE_TYPE)); + assertEquals(2, workers.parked().continued()); + assertEquals(1, workers.parked().replayed()); + } + + @Test + void anExecutionThatMovedOnWithoutTheCodeHeldInMemoryIsReplayed() { + hosted(); + workers.process(CODE_TYPE, first(Map.of())); + + // another host continued it (the pin timeout passed), or it was retried or rerun: the + // server names another stamp + execution = AFTER_ONE; + TaskResult two = workers.process(CODE_TYPE, continuation("id-pk_one", "pk_one", 2, "COMPLETED", + Map.of("result", "A"), "pin-other.7", Map.of("stage", "new"))); + + assertEquals(List.of("pk_two"), refs(two)); + assertEquals(2, fetched.get()); + assertEquals(2, RAN_FROM_THE_TOP.get()); + assertEquals(0, workers.parked().continued()); + // it is held again, from the replay + assertEquals(workers.pinDomain(), pin(two).get("domain")); + assertEquals(1, workers.parked().held(CODE_TYPE)); + } + + @Test + void anExecutionWithNoStampIsReplayed() { + hosted(); + workers.process(CODE_TYPE, first(Map.of())); + + // a retry or rerun clears the stamp + execution = AFTER_ONE; + workers.process(CODE_TYPE, continuation("id-pk_one", "pk_one", 2, "COMPLETED", + Map.of("result", "A"), null, Map.of("stage", "new"))); + + assertEquals(2, fetched.get()); + assertEquals(2, RAN_FROM_THE_TOP.get()); + } + + @Test + void aContinuationTheHeldCodeAlreadyRanIsReplayed() { + hosted(); + TaskResult one = workers.process(CODE_TYPE, first(Map.of())); + + // the same continuation again, with this process's own stamp: the code in memory is past it + Task again = first(Map.of()); + again.getContinuation().setStamp((String) pin(one).get("stamp")); + TaskResult repeated = workers.process(CODE_TYPE, again); + + assertEquals(List.of("pk_one"), refs(repeated)); + assertEquals(2, fetched.get()); + assertEquals(2, RAN_FROM_THE_TOP.get()); + } + + @Test + void aServerThatDoesNotPinExecutionsHasNothingKeptForIt() { + hosted(); + + TaskResult one = workers.process(CODE_TYPE, first(null)); // no variables with the continuation + + assertEquals(List.of("pk_one"), refs(one)); + assertNull(pin(one)); + assertEquals(0, workers.parked().held(CODE_TYPE)); + } + + @Test + void aParkTimeoutOfZeroKeepsNothingAndPollsNoQueueOfItsOwn() throws Exception { + settings.put("conductor.workflow.pk_two.parkTimeout", "0"); + hosted(); + + TaskResult one = workers.process(CODE_TYPE, first(Map.of())); + + assertNull(pin(one)); + assertNull(workers.pinDomain()); + assertEquals(0, workers.parked().held(CODE_TYPE)); + Thread.sleep(400); + assertEquals(Set.of(""), polledDomains); + } + + @Test + void devModeKeepsNothingSoThatEveryContinuationReplays() { + workers = conductor.workflows(TwoSteps.class).settings(settings::get).devMode(true).start(); + + TaskResult one = workers.process(CODE_TYPE, first(Map.of())); + + assertEquals(List.of("pk_one"), refs(one)); + assertNull(pin(one)); + assertNull(workers.pinDomain()); + assertEquals(0, workers.parked().held(CODE_TYPE)); + } + + @Test + void itsOwnQueueIsPolledOnlyWhileItHoldsAnExecution() throws Exception { + hosted(); + Thread.sleep(400); + // nothing held: a queue nobody polls reads as a worker that is gone + assertEquals(Set.of(""), polledDomains); + + TaskResult one = workers.process(CODE_TYPE, first(Map.of())); + awaitPolled(workers.pinDomain()); + + TaskResult two = workers.process(CODE_TYPE, continuation("id-pk_one", "pk_one", 2, "COMPLETED", + Map.of("result", "A"), (String) pin(one).get("stamp"), Map.of())); + workers.process(CODE_TYPE, continuation("id-pk_two", "pk_two", 3, "COMPLETED", + Map.of("result", "B"), (String) pin(two).get("stamp"), Map.of())); + Thread.sleep(400); // a poll under way when the last one ended + polledDomains.clear(); + Thread.sleep(500); + + assertEquals(Set.of(""), polledDomains); + } + + private void awaitPolled(String domain) throws InterruptedException { + long until = System.currentTimeMillis() + 5000; + while (!polledDomains.contains(domain) && System.currentTimeMillis() < until) { + Thread.sleep(20); + } + assertTrue(polledDomains.contains(domain), "polled " + polledDomains + ", not " + domain); + } + + @Test + void aPinDomainIsThisHostsAndNewOnEveryStart() { + String a = Workers.newPinDomain("orders host:8080/eu"); + String b = Workers.newPinDomain("orders host:8080/eu"); + + // only what a queue name may hold: the server refuses anything else + assertTrue(a.matches("pin-orders_host_8080_eu-[A-Za-z0-9]{1,8}"), a); + assertNotEquals(a, b); + assertTrue(Workers.newPinDomain(null).matches("pin-[A-Za-z0-9]{1,8}")); + assertTrue(Workers.newPinDomain("x".repeat(300)).length() <= 100); + } + + // ------------------------------------------------------------------ what is held, and for how long + + private static Replayer paused() { + WorkflowSpec spec = WorkflowSpec.of(TwoSteps.class).get(0); + Map json = new HashMap<>(Map.of("workflowId", "wf", "status", "RUNNING", + "input", Map.of("order", "o"), "workflowDefinition", Map.of("name", "pk_two", "tasks", List.of()), + "tasks", List.of(), "nativeState", Map.of("bootstrap", Map.of()))); + Replayer replayer = new Replayer(spec, spec.newInstance(), new Execution(json)); + replayer.begin("main", 1); + assertTrue(replayer.hasPausedLanes()); + return replayer; + } + + @Test + void anExecutionThatSatIdleTooLongIsDropped() { + AtomicLong now = new AtomicLong(10_000); + ParkedExecutions parked = new ParkedExecutions(now::get); + Replayer early = paused(); + Replayer late = paused(); + parked.park(CODE_TYPE, "wf-early", early, "s-1", 1_000, 10); + now.addAndGet(600); + parked.park(CODE_TYPE, "wf-late", late, "s-2", 1_000, 10); + + now.addAndGet(600); // 1200 ms after the first, 600 after the second + parked.dropIdle(); + + assertNull(parked.take(CODE_TYPE, "wf-early")); + assertFalse(early.hasPausedLanes()); // its lanes were ended + assertEquals(1, parked.dropped()); + assertEquals(1, parked.held(CODE_TYPE)); + assertTrue(late.hasPausedLanes()); + parked.closeAll(); + assertFalse(late.hasPausedLanes()); + } + + @Test + void whenTooManyAreHeldTheOnesIdleLongestAreDropped() { + ParkedExecutions parked = new ParkedExecutions(); + Replayer a = paused(); + Replayer b = paused(); + Replayer c = paused(); + parked.park(CODE_TYPE, "wf-a", a, "s-1", 60_000, 2); + parked.park(CODE_TYPE, "wf-b", b, "s-2", 60_000, 2); + // wf-a continues: it is taken out, and parked again as the most recent + assertTrue(parked.take(CODE_TYPE, "wf-a").replayer() == a); + parked.park(CODE_TYPE, "wf-a", a, "s-3", 60_000, 2); + + parked.park(CODE_TYPE, "wf-c", c, "s-4", 60_000, 2); + + assertFalse(b.hasPausedLanes()); + assertTrue(a.hasPausedLanes()); + assertTrue(c.hasPausedLanes()); + assertEquals(2, parked.held(CODE_TYPE)); + assertEquals(0, parked.held("another.v1.code")); // counted by workflow + parked.closeAll(); + } + + @Test + void anExecutionIsOutOfTheCacheWhileOneOfItsContinuationsRuns() { + ParkedExecutions parked = new ParkedExecutions(); + Replayer held = paused(); + parked.park(CODE_TYPE, "wf-1", held, "s-1", 60_000, 10); + + ParkedExecutions.Parked taken = parked.take(CODE_TYPE, "wf-1"); + + assertEquals("s-1", taken.stamp()); + // a second thread handed the same continuation finds nothing, and replays + assertNull(parked.take(CODE_TYPE, "wf-1")); + assertEquals(0, parked.held(CODE_TYPE)); + held.close(); + } +} 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..5d90026c4 --- /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.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.isRegistered() && System.currentTimeMillis() < deadline) { + Thread.sleep(50); + } + assertTrue(workers.isRegistered(), "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.workflows(Flow.class).start(); + Thread.sleep(1500); + assertFalse(workers.isRegistered()); + conductor.close(); // stops the retries + } +} diff --git a/conductor-client/src/test/java/org/conductoross/conductor/sdk/UpdateReplyTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/UpdateReplyTest.java new file mode 100644 index 000000000..9fa920fc5 --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/UpdateReplyTest.java @@ -0,0 +1,148 @@ +/* + * 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.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +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.common.metadata.tasks.TaskResult; +import com.netflix.conductor.common.metadata.workflow.WorkflowTask; + +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.assertNull; + +/** + * An update from the caller to the handler and back: {@link WorkflowHandle#update} sends the + * message, a worker's handler run answers it, and the caller reads the reply the server kept. + */ +class UpdateReplyTest { + + public record Receipt(String id, int total) {} + + public static class Orders { + @Update + public Receipt lookup(String id) { + return "known".equals(id) ? new Receipt(id, 3) : null; + } + + @Update + public String label(String id) { + return null; + } + + @Workflow(name = "update_reply_test", version = 1) + public String run(String input) { + return input; + } + } + + private MockWebServer server; + private Conductor conductor; + /** The message the caller posted, and the replies the server keeps for the execution. */ + private final AtomicReference> posted = new AtomicReference<>(); + private final AtomicReference replies = new AtomicReference<>(Map.of()); + + @BeforeEach + void start() throws Exception { + server = new MockWebServer(); + server.setDispatcher(new Dispatcher() { + @Override + @SuppressWarnings("unchecked") + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + MockResponse json = new MockResponse().setHeader("Content-Type", "application/json"); + try { + if ("POST".equals(request.getMethod())) { + posted.set(Json.MAPPER.readValue(request.getBody().readUtf8(), Map.class)); + return json.setBody("\"queued\""); + } + return json.setBody(Json.MAPPER.writeValueAsString(Map.of( + "workflowId", "wf-1", "status", "RUNNING", "nativeState", Map.of("replies", replies.get())))); + } catch (Exception e) { + return new MockResponse().setResponseCode(500); + } + } + }); + server.start(); + conductor = Conductor.of(ConductorClient.builder().basePath(server.url("/api").toString()).build()); + } + + @AfterEach + void stop() throws Exception { + server.shutdown(); + } + + /** Sends the update, has a worker run the handler lane for it, and returns what the caller got. */ + private V update(Functions.Fn1 handler, String argument) throws Exception { + WorkflowHandle handle = conductor.attach(Orders::run, "wf-1"); + CompletableFuture answer = CompletableFuture.supplyAsync(() -> handle.update(handler, argument)); + while (posted.get() == null) { + Thread.sleep(10); + } + TaskContinuation marker = TaskContinuation.handlerRun(2); + marker.setLeased(true); + var entry = new WorkflowTask(); + entry.setTaskReferenceName("handlers"); + entry.setMetadata(new HashMap<>(Map.of("lane", "handlers", "continuation", 2))); + Task task = new Task(); + task.setWorkflowTask(entry); + task.setTaskId("wf-1|handlers"); + task.setWorkflowInstanceId("wf-1"); + task.setReferenceTaskName("handlers"); + task.setStatus(Task.Status.IN_PROGRESS); + task.setContinuation(marker); + task.setInputData(Map.of("messages", List.of(Map.of("id", "q-1", "payload", posted.get())))); + + TaskResult result = conductor.workflows(Orders.class).process("update_reply_test.v1.code", task); + + assertEquals(TaskResult.Status.COMPLETED, result.getStatus()); + replies.set(result.getOutputData().get("replies")); // the server keeps them with the execution + try { + return answer.get(10, TimeUnit.SECONDS); + } catch (ExecutionException e) { + throw (Exception) e.getCause(); + } + } + + @Test + void anUpdateReturnsWhatItsHandlerReturned() throws Exception { + assertEquals(new Receipt("known", 3), update(Orders::lookup, "known")); + } + + @Test + void anUpdateWhoseHandlerReturnsNullReturnsNullForAnObject() throws Exception { + assertNull(update(Orders::lookup, "unknown")); + } + + @Test + void anUpdateWhoseHandlerReturnsNullReturnsNullForAString() throws Exception { + assertNull(update(Orders::label, "x")); + } +} 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..cf2881a9f --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkerProtocolTest.java @@ -0,0 +1,224 @@ +/* + * 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.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.conductoross.conductor.sdk.internal.Json; +import org.conductoross.conductor.sdk.internal.JsonSchemas; +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.common.metadata.tasks.TaskResult; +import com.netflix.conductor.common.metadata.workflow.WorkflowTask; +import com.netflix.conductor.sdk.workflow.task.InputParam; +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +import okhttp3.mockwebserver.Dispatcher; +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(); + } + + /** The entry a handed-out continuation's task carries: its lane, and its number in it. */ + private static WorkflowTask entry(String ref, String lane, int n) { + var entry = new WorkflowTask(); + entry.setTaskReferenceName(ref); + entry.setMetadata(new HashMap<>(Map.of("lane", lane, "continuation", n))); + return entry; + } + + 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\"}")); + TaskContinuation marker = new TaskContinuation(); + marker.setLeased(true); + marker.setRetryCount(3); + Task task = new Task(); + task.setWorkflowTask(entry("t", "main", 2)); // the entry names the continuation + task.setTaskId("t-1"); + task.setWorkflowInstanceId("wf-1"); + task.setReferenceTaskName("t"); + task.setStatus(Task.Status.IN_PROGRESS); + task.setContinuation(marker); + + // no such workflow: the replay fails, and the completion TaskRunner sends says so + TaskResult result = conductor.workflows().process("not.hosted.code", task); + + assertEquals(TaskResult.Status.FAILED, result.getStatus()); + Map output = result.getOutputData(); + assertEquals(2, output.get("protocol")); + assertEquals(2, output.get("n")); + assertEquals(3, output.get("retryCount")); + } + + public static class Notes { + @Variable + private List notes = new ArrayList<>(); + + @Signal("add") + public void add(String note) { + notes.add(note); + } + + @Workflow(name = "notes_test", version = 1) + public String run() { + return "done"; + } + } + + @Test + @SuppressWarnings("unchecked") + void aMessageAlreadyHandledIsSkippedAndEveryHandledMessageIsInTheReplies() throws Exception { + long now = System.currentTimeMillis(); + // s-1 was handled by an earlier run; a retried send queued it again + server.enqueue(json("{\"workflowId\":\"wf-1\",\"status\":\"RUNNING\",\"variables\":{\"notes\":[\"first\"]}," + + "\"nativeState\":{\"replies\":{\"s-1\":{\"at\":" + now + "}}}}")); + TaskContinuation marker = TaskContinuation.handlerRun(2); + marker.setLeased(true); + marker.setRetryCount(1); + Task task = new Task(); + task.setWorkflowTask(entry("handlers", "handlers", 2)); // as the server builds it + task.setTaskId("wf-1|handlers"); + task.setWorkflowInstanceId("wf-1"); + task.setReferenceTaskName("handlers"); + task.setStatus(Task.Status.IN_PROGRESS); + task.setContinuation(marker); + task.setInputData(Map.of("messages", List.of( + Map.of("id", "q-1", "payload", Map.of("kind", "signal", "name", "add", "id", "s-1", "args", "first")), + Map.of("id", "q-2", "payload", Map.of("kind", "signal", "name", "add", "id", "s-2", "args", "second"))))); + + TaskResult result = conductor.workflows(Notes.class).process("notes_test.v1.code", task); + + assertEquals(TaskResult.Status.COMPLETED, result.getStatus()); + Map output = result.getOutputData(); + assertEquals(List.of("first", "second"), ((Map) output.get("variables")).get("notes")); + Map replies = (Map) output.get("replies"); + assertEquals(Set.of("s-1", "s-2"), replies.keySet()); + // a signal's entry says only when it was handled + assertEquals(Set.of("at"), ((Map) replies.get("s-2")).keySet()); + assertEquals(null, output.get("seen")); + } + + @Test + @SuppressWarnings("unchecked") + void aTaskDefinitionOwnedBySomeoneElseIsLeftAlone() throws Exception { + List posted = answer( + "[]", "[{\"name\":\"shared_task\",\"ownerEmail\":\"team-a@example.com\",\"retryCount\":7}]"); + + Registration.register(conductor.client(), List.of(), List.of(new Mine()), 30); + + List> defs = Json.MAPPER.readValue(last(posted, "/api/metadata/taskdefs"), List.class); + assertEquals(List.of("my_task"), defs.stream().map(d -> d.get("name")).toList()); + } + + public static class Typed { + @WorkerTask("typed_task") + public String typed(@InputParam("n") int n) { + return "x"; + } + } + + @Test + @SuppressWarnings("unchecked") + void schemasAreRegisteredByNameVersionedByContentAndNotEnforced() throws Exception { + // the input schema is registered already as version 2; the output had another shape + String input = Json.MAPPER.writeValueAsString(JsonSchemas.taskInput( + Typed.class.getMethod("typed", int.class))); + List posted = answer( + "[{\"name\":\"typed_task_input\",\"version\":2,\"data\":" + input + "}," + + "{\"name\":\"typed_task_output\",\"version\":4,\"data\":{\"type\":\"string\"}}]", + "[]"); + + Registration.register(conductor.client(), List.of(), List.of(new Typed()), 30); + + // only the output is new: the next version after the highest registered + List> schemas = Json.MAPPER.readValue(last(posted, "/api/schema"), List.class); + assertEquals("typed_task_output", schemas.get(0).get("name")); + assertEquals(5, schemas.get(0).get("version")); + assertEquals(1, posted.stream().filter(p -> p.startsWith("/api/schema ")).count()); + Map def = ((List>) Json.MAPPER.readValue( + last(posted, "/api/metadata/taskdefs"), List.class)).get(0); + assertEquals(Map.of("name", "typed_task_input", "version", 2, "type", "JSON"), def.get("inputSchema")); + assertEquals(Map.of("name", "typed_task_output", "version", 5, "type", "JSON"), def.get("outputSchema")); + assertEquals(false, def.get("enforceSchema")); + } + + /** Answers by path, the schemas and task definitions given; records each POST as "path body". */ + private List answer(String schemas, String taskDefs) { + List posted = new CopyOnWriteArrayList<>(); + server.setDispatcher(new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) { + String path = request.getPath() == null ? "" : request.getPath().replaceAll("\\?.*", ""); + if (request.getMethod().equals("POST") || request.getMethod().equals("PUT")) { + posted.add(path + " " + request.getBody().readUtf8()); + return json("\"ok\""); + } + return json(path.equals("/api/schema") ? schemas : path.equals("/api/metadata/taskdefs") ? taskDefs : "[]"); + } + }); + return posted; + } + + private static String last(List posted, String path) { + String found = null; + for (String p : posted) { + if (p.startsWith(path + " ")) { + found = p.substring(path.length() + 1); + } + } + return found; + } +} 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..ff2f8c74a --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkflowHandleQueryTest.java @@ -0,0 +1,153 @@ +/* + * 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.LinkedHashMap; +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()); + } + + /** A workflow whose constructor takes something only its factory can give. */ + public static class Configured { + @Variable private List deposits = new ArrayList<>(); + private final String currency; + + public Configured(String currency) { + this.currency = currency; + } + + @Query("total") + public String total() { + return deposits.size() + " " + currency; + } + + @Workflow(name = "configured_query_test", version = 1) + public String run(String input) { + return input; + } + } + + @Test + void aQueryOnAClassHostedWithAFactoryUsesTheFactory() { + execution("RUNNING", "[\"dep-1\",\"dep-2\"]"); + conductor.workflows(Configured.class, () -> new Configured("EUR")); // hosted, not started + assertEquals("2 EUR", conductor.attach(Configured::run, "wf-1").query(Configured::total)); + } + + @Test + void repliesExpireAndAreCapped() { + long now = 1_000_000_000L; + Map replies = new 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 + } + + @Test + void theCapDropsTheOldestRepliesWhateverOrderTheServerReturnsThemIn() { + long now = 1_000_000_000L; + Map replies = new LinkedHashMap<>(); + // the reply written last comes first: the server's map of replies keeps no order + replies.put("newest", Map.of("value", "n", "at", now)); + for (int i = 0; i < Workers.REPLY_LIMIT; i++) { + replies.put("r" + i, Map.of("value", i, "at", now - 5000 + i)); + } + Map kept = Workers.pruneReplies(replies, now); + assertEquals(Workers.REPLY_LIMIT, kept.size()); + assertTrue(kept.containsKey("newest"), "the newest reply was dropped: its caller would never read it"); + assertTrue(!kept.containsKey("r0"), "the oldest reply is the one to drop"); + } +} diff --git a/conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkflowHandleResultAsyncTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkflowHandleResultAsyncTest.java new file mode 100644 index 000000000..aec56ad64 --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkflowHandleResultAsyncTest.java @@ -0,0 +1,133 @@ +/* + * 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.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +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.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.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** resultAsync: a future of the execution's outcome, checked by one shared thread. */ +class WorkflowHandleResultAsyncTest { + + public static class Greeter { + @Workflow(name = "result_async_test", version = 1) + public String run(String name) { + return "hello " + name; + } + } + + private MockWebServer server; + private Conductor conductor; + /** What the next read of the execution returns: a status, or an HTTP code such as "503". */ + private final AtomicReference next = new AtomicReference<>("RUNNING"); + private final AtomicInteger reads = new AtomicInteger(); + + @BeforeEach + void start() throws Exception { + server = new MockWebServer(); + server.setDispatcher(new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) { + reads.incrementAndGet(); + String state = next.get(); + if (state.matches("\\d+")) { + return new MockResponse().setResponseCode(Integer.parseInt(state)).setBody("{}"); + } + String body = "{\"workflowId\":\"wf-1\",\"status\":\"" + state + "\",\"reasonForIncompletion\":\"card declined\"" + + ",\"output\":{\"result\":\"hello ada\"}}"; + return new MockResponse().setHeader("Content-Type", "application/json").setBody(body); + } + }); + server.start(); + conductor = Conductor.of(ConductorClient.builder().basePath(server.url("/api").toString()).build()); + } + + @AfterEach + void stop() throws Exception { + conductor.close(); + server.shutdown(); + } + + @Test + void completesWithTheResultOnceTheExecutionFinishesWaitingOutAServerError() throws Exception { + CompletableFuture result = conductor.attach(Greeter::run, "wf-1").resultAsync(); + awaitReads(2); + next.set("503"); // a restarting server + awaitReads(2); + assertTrue(!result.isDone(), "still waiting while the execution runs"); + next.set("COMPLETED"); + assertEquals("hello ada", result.get(5, TimeUnit.SECONDS)); + } + + @Test + void failsWithWorkflowFailedExceptionWhenTheExecutionFails() { + next.set("FAILED"); + CompletableFuture result = conductor.attach(Greeter::run, "wf-1").resultAsync(); + ExecutionException e = assertThrows(ExecutionException.class, () -> result.get(5, TimeUnit.SECONDS)); + assertInstanceOf(WorkflowFailedException.class, e.getCause()); + assertTrue(e.getCause().getMessage().contains("card declined"), e.getCause().getMessage()); + } + + @Test + void failsWhenTheServerRefusesTheRead() { + next.set("404"); + CompletableFuture result = conductor.attach(Greeter::run, "wf-1").resultAsync(); + assertThrows(ExecutionException.class, () -> result.get(5, TimeUnit.SECONDS)); + } + + @Test + void cancellingStopsTheChecks() throws Exception { + CompletableFuture result = conductor.attach(Greeter::run, "wf-1").resultAsync(); + awaitReads(1); + result.cancel(false); + Thread.sleep(300); // a check already under way may finish + int after = reads.get(); + Thread.sleep(1000); + assertEquals(after, reads.get(), "no reads after the future was cancelled"); + } + + @Test + void closingTheConductorCancelsTheFuturesStillWaiting() throws Exception { + CompletableFuture result = conductor.attach(Greeter::run, "wf-1").resultAsync(); + awaitReads(1); + conductor.close(); + assertTrue(result.isCancelled()); + } + + private void awaitReads(int more) throws InterruptedException { + int target = reads.get() + more; + long deadline = System.currentTimeMillis() + 5000; + while (reads.get() < target && System.currentTimeMillis() < deadline) { + Thread.sleep(20); + } + assertTrue(reads.get() >= target, "the execution was read " + reads.get() + " times"); + } +} diff --git a/conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkflowSettingsTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkflowSettingsTest.java new file mode 100644 index 000000000..6a2cf4c66 --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/WorkflowSettingsTest.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.HashMap; +import java.util.Map; + +import org.conductoross.conductor.sdk.internal.WorkflowSpec; +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.Dispatcher; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** Per-workflow settings: the named property, else the one for all workflows, else the annotation. */ +class WorkflowSettingsTest { + + public static class Tuned { + @Workflow(name = "tuned", threadCount = 3) + public void run() {} + } + + public static class Plain { + @Workflow(name = "plain") + public void run() {} + } + + private MockWebServer server; + private Conductor conductor; + private final Map settings = new HashMap<>(); + + @BeforeEach + void start() throws Exception { + server = new MockWebServer(); + server.setDispatcher(new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) { + String path = request.getPath(); + String body = path.startsWith("/api/tasks/poll") || path.startsWith("/api/metadata/taskdefs") + || path.startsWith("/api/schema") ? "[]" : "{}"; + return new MockResponse().setHeader("Content-Type", "application/json").setBody(body); + } + }); + server.start(); + conductor = Conductor.of(ConductorClient.builder().basePath(server.url("/api").toString()).build()); + } + + @AfterEach + void stop() throws Exception { + conductor.close(); + server.shutdown(); + } + + private Map threadCounts() { + Workers host = conductor.workflows(Tuned.class, Plain.class).settings(settings::get).start(); + try { + return host.workflowRunner().getTaskThreadCount(); + } finally { + host.close(); + } + } + + @Test + void threadCountsComeFromTheNamedPropertyThenAllThenTheAnnotation() { + assertEquals(Map.of("tuned.v1.code", 3, "plain.v1.code", 20), threadCounts()); + + settings.put("conductor.workflow.all.threadCount", "7"); + assertEquals(Map.of("tuned.v1.code", 7, "plain.v1.code", 7), threadCounts()); + + settings.put("conductor.workflow.tuned.threadCount", "5"); + assertEquals(Map.of("tuned.v1.code", 5, "plain.v1.code", 7), threadCounts()); + } + + @Test + void theContinuationTimeoutIsSecondsOrAnIsoDurationAndAnHourInDevMode() { + WorkflowSpec tuned = WorkflowSpec.of(Tuned.class).get(0); + WorkflowSpec plain = WorkflowSpec.of(Plain.class).get(0); + Workers host = conductor.workflows().settings(settings::get); + assertEquals(30, host.continuationTimeoutSeconds(tuned)); + + settings.put("conductor.workflow.all.continuationTimeout", "45"); + settings.put("conductor.workflow.tuned.continuationTimeout", "PT2M"); + assertEquals(120, host.continuationTimeoutSeconds(tuned)); + assertEquals(45, host.continuationTimeoutSeconds(plain)); + + assertEquals(3600, host.devMode(true).continuationTimeoutSeconds(plain)); + } +} diff --git a/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/AgentConversationTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/AgentConversationTest.java new file mode 100644 index 000000000..61ff67cd0 --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/AgentConversationTest.java @@ -0,0 +1,95 @@ +/* + * 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.Proxy; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; +import java.util.Map; + +import org.conductoross.conductor.sdk.AgentCall; +import org.conductoross.conductor.sdk.AgentCall.AgentResult; +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.Workflow; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** An agent handle is a conversation: asking again continues it. */ +class AgentConversationTest { + + @Test + void askingAgainContinuesTheConversationAndAnswersAPendingQuestion() { + List sent = new ArrayList<>(); + Deque replies = new ArrayDeque<>(List.of( + new AgentResult("Card or store credit?", "input-required", List.of(), "task-1", "ctx-1"), + new AgentResult("Refunded to the card", "completed", List.of(), "task-1", "ctx-1"), + new AgentResult("You are welcome", "message", List.of(), null, "ctx-1"))); + Engine engine = (Engine) Proxy.newProxyInstance(Engine.class.getClassLoader(), new Class[] {Engine.class}, + (proxy, method, args) -> { + if (method.getName().equals("call")) { + sent.add((Command) args[0]); + return replies.poll(); + } + if (method.getReturnType() == void.class) { + return null; // checks such as assertRunning + } + throw new UnsupportedOperationException(method.getName()); + }); + Engine previous = Engine.CURRENT.get(); + Engine.CURRENT.set(engine); + try { + AgentCall support = Conductor.agent("support").remote("http://agent/a2a").header("Authorization", "Bearer bot"); + support.ask("Refund ticket T-1"); + support.ask("card"); + support.ask("Thanks"); + } finally { + Engine.CURRENT.set(previous); + } + + assertEquals(3, sent.size()); + for (Command c : sent) { + assertEquals("support", c.explicitRef); + assertEquals("http://agent/a2a", c.input.get("agentUrl")); + assertEquals(Map.of("Authorization", "Bearer bot"), c.input.get("headers")); + } + // the first message starts the conversation + assertNull(sent.get(0).input.get("contextId")); + assertNull(sent.get(0).input.get("taskId")); + // the agent asked for input: the next message answers it, in its task + assertEquals("ctx-1", sent.get(1).input.get("contextId")); + assertEquals("task-1", sent.get(1).input.get("taskId")); + // that task is done: the next message is a new turn of the same conversation + assertEquals("ctx-1", sent.get(2).input.get("contextId")); + assertNull(sent.get(2).input.get("taskId")); + } + + public static class Chat { + @Workflow(name = "agent_chat") + public String run(String ticket) { + AgentCall support = Conductor.agent("support").remote("http://agent/a2a"); + support.ask("Refund " + ticket); + return support.ask("Thanks").text(); + } + } + + @Test + void eachAskOnAConversationIsDrawnAsAnAgentStepNamedByTheConversation() { + List> tasks = Replayer.discover(WorkflowSpec.of(Chat.class).get(0)); + List agents = tasks.stream().filter(t -> "AGENT".equals(t.get("type"))).map(t -> t.get("taskReferenceName")).toList(); + assertEquals(List.of("support", "support_2"), agents); + } +} diff --git a/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/BuilderReuseTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/BuilderReuseTest.java new file mode 100644 index 000000000..ab546150f --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/BuilderReuseTest.java @@ -0,0 +1,79 @@ +/* + * 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.Proxy; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.EventCall; +import org.conductoross.conductor.sdk.HttpCall; +import org.conductoross.conductor.sdk.TaskCall; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; + +/** A builder kept in a variable sends what it was given each time, not what an earlier call left. */ +class BuilderReuseTest { + + @SuppressWarnings("unchecked") + @Test + void eachCallOfABuilderSendsItsOwnCommand() { + List sent = new ArrayList<>(); + Engine engine = (Engine) Proxy.newProxyInstance(Engine.class.getClassLoader(), new Class[] {Engine.class}, + (proxy, method, args) -> { + if (method.getName().equals("call") || method.getName().equals("fire")) { + sent.add((Command) args[0]); + return method.getReturnType() == void.class ? null : Map.of(); + } + if (method.getReturnType() == void.class) { + return null; + } + throw new UnsupportedOperationException(method.getName()); + }); + Engine previous = Engine.CURRENT.get(); + Engine.CURRENT.set(engine); + try { + EventCall audit = Conductor.event("audit"); + audit.send(Map.of("first", 1)); + audit.send(Map.of("second", 2)); + + HttpCall api = Conductor.http("api").get("http://api/a").header("X-Trace", "1"); + api.asJson(); + api.header("X-Trace", "2").asJson(); + + TaskCall lookup = Conductor.task("lookup").input("id", "a"); + lookup.asMap(); + lookup.run(); + } finally { + Engine.CURRENT.set(previous); + } + + assertEquals(6, sent.size()); + // an event's payload is its own, not merged with the one before + assertEquals(Map.of("first", 1), sent.get(0).input); + assertEquals(Map.of("second", 2), sent.get(1).input); + // a header changed after a call changes only later calls + Map first = (Map) sent.get(2).input.get("http_request"); + Map second = (Map) sent.get(3).input.get("http_request"); + assertEquals(Map.of("X-Trace", "1"), first.get("headers")); + assertEquals(Map.of("X-Trace", "2"), second.get("headers")); + // each call is a command of its own, typed by its own terminal + assertNotSame(sent.get(4), sent.get(5)); + assertEquals(Map.class, sent.get(4).resultType); + assertEquals(Void.class, sent.get(5).resultType); + } +} 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..56b046c14 --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/CodeReaderTest.java @@ -0,0 +1,302 @@ +/* + * 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.Future; +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.junit.jupiter.api.Assertions.assertEquals; + +/** Steps come from the compiled code: nothing runs, so no value can stop the reading. */ +class CodeReaderTest { + + /** The task stub the workflows below call: its calls schedule the tasks. */ + static final Tasks TASKS = Conductor.stub(Tasks.class); + + 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 = TASKS.plan(x); + String first = plan.items().get(0); + int size = Integer.parseInt(plan.owner().get("size").trim()) / plan.items().size(); + TASKS.ship(first + size); + return TASKS.tell(x); + } + + @Workflow(name = "negated_if") + public String negatedIf(String x) { + Plan plan = TASKS.plan(x); + if (!plan.needsApproval()) { + return TASKS.ship(x); + } + return TASKS.approve(x); + } + + @Workflow(name = "branches_and_loops") + public String branchesAndLoops(String x) { + Plan plan = TASKS.plan(x); + if (plan.needsApproval()) { + TASKS.approve(x); + } else { + TASKS.tell(x); + } + for (String item : plan.items()) { + 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 TASKS.ship(v); + } + + @Workflow(name = "finally_once") + public String finallyOnce(String x) { + try { + if (x.isEmpty()) { + return TASKS.ship(x); + } + return TASKS.approve(x); + } finally { + TASKS.tell(x); + } + } + + @Workflow(name = "helpers") + public String helpers(String x) { + List.of("a").forEach(i -> TASKS.ship(i)); + return helper(x); + } + + private String helper(String x) { + return TASKS.tell(x); + } + + @Workflow(name = "recursive") + public String recursive(String x) { + TASKS.ship(x); + return x.isEmpty() ? "done" : recursive(x.substring(1)); + } + + @Workflow(name = "keys") + public String keys(String x) { + switchOn("s", x) + .when("text", () -> TASKS.ship(x)) + .when(5, () -> TASKS.approve(x)) + .when(true, () -> TASKS.tell(x)) + .when(Tier.GOLD, () -> { + sleep(Duration.ofSeconds(1)); + }) + .otherwise(() -> TASKS.plan(x)) + .get(); + return "done"; + } + + @Workflow(name = "fans") + public String fans(String x) { + fanOut("spread", List.of("a"), i -> TASKS.ship(i)); + return "done"; + } + + @Workflow(name = "joined_at_once") + public String joinedAtOnce(String x) { + Future p = Conductor.async(() -> TASKS.ship(x)); + Conductor.join(p); + return p.resultNow(); + } + + @Workflow(name = "never_joined") + public String neverJoined(String x) { + Conductor.async(() -> TASKS.ship(x)); + return TASKS.tell(x); + } + + @Workflow(name = "joined_later") + public String joinedLater(String x) { + Future p = Conductor.async(() -> TASKS.ship(x)); + TASKS.tell(x); + Conductor.join(p); + return p.resultNow(); + } + + @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 + @SuppressWarnings("unchecked") + void aNegatedIfKeysItsArmsByTheValueItIsNamedAfter() { + Map sw = discover("negated_if").get(1); + assertEquals("if_needsApproval", sw.get("taskReferenceName")); + Map>> cases = (Map>>) sw.get("decisionCases"); + assertEquals(List.of("false"), List.copyOf(cases.keySet()), "if (!needsApproval) runs its body when needsApproval is false"); + assertEquals(List.of("ship"), refs(cases.get("false"))); + assertEquals(List.of("approve"), 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..389425bc1 --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/DiscoveryTest.java @@ -0,0 +1,177 @@ +/* + * 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.Future; +import java.util.concurrent.atomic.AtomicInteger; + +import org.conductoross.conductor.sdk.Conductor; +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.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. */ +@SuppressWarnings("unchecked") // generic test data read back from maps and mocks +class DiscoveryTest { + + /** The task stub the workflows below call: its calls schedule the tasks. */ + static final Tasks TASKS = Conductor.stub(Tasks.class); + + 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 = TASKS.pick(order.item()); + Future a = async(() -> TASKS.pack(picked + "-a")); + Future b = async(() -> TASKS.pack(picked + "-b")); + join(a, b); + sleep(Duration.ofSeconds(order.quantity() + 1)); + switchOn("region", order.region()) + .when("eu", () -> TASKS.ship("eu")) + .when("us", () -> 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("handlers")); // it has a signal + + 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 AtomicInteger SIDE_EFFECTS = new AtomicInteger(); + static volatile boolean releaseSpin; + + public static class Spins { + @Workflow(name = "spins") + public String run(Order order) { + 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 TASKS.pick(String.valueOf(id)); + } + } + + @Test + void codeThatLoopsForeverIsReadWithoutRunningIt() { + WorkflowSpec spec = WorkflowSpec.of(Spins.class).get(0); + Map def = Registration_skeleton(spec); + 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 = TASKS.pick(order.item()); + if (picked.length() > 3) { + return TASKS.ship(picked); + } + throw new IllegalStateException("too short"); + } + } +} diff --git a/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/JsonSchemasTest.java b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/JsonSchemasTest.java new file mode 100644 index 000000000..4b83ba98d --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/JsonSchemasTest.java @@ -0,0 +1,148 @@ +/* + * 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.time.Instant; +import java.time.LocalDate; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import com.netflix.conductor.common.metadata.tasks.TaskResult; +import com.netflix.conductor.sdk.workflow.task.InputParam; +import com.netflix.conductor.sdk.workflow.task.OutputParam; +import com.netflix.conductor.sdk.workflow.task.WorkflowInstanceIdInputParam; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +@SuppressWarnings("unchecked") // generic test data read back from maps and mocks +class JsonSchemasTest { + + enum Tier { CRITICAL, STANDARD } + + record Host(String name, Tier tier, List tags, int port) {} + + record Region(String name, List hosts, Map load, Instant since, LocalDate day) {} + + static final class Node { + public String id; + public Node next; // holds itself + } + + @SuppressWarnings("unused") + static final class Tasks { + public Region inventory(@InputParam("fleet") String fleet, @InputParam("max") int max) { + return null; + } + + public String probe(@WorkflowInstanceIdInputParam String workflowId, @InputParam("host") Host host) { + return null; + } + + public @OutputParam("hosts") List hosts(@InputParam("region") Region region) { + return null; + } + + public void noOutput(@InputParam("x") String x) {} + + public TaskResult raw(@InputParam("x") String x) { + return null; + } + + public Node node(@InputParam("x") String x) { + return null; + } + + public String workflow(Region region) { + return null; + } + + public List twoInputs(@InputParam("a") String a, @InputParam("b") boolean b) { + return null; + } + } + + private static Method m(String name) { + for (Method method : Tasks.class.getDeclaredMethods()) { + if (method.getName().equals(name)) { + return method; + } + } + throw new IllegalArgumentException(name); + } + + @SuppressWarnings("unchecked") + private static Map props(Map schema) { + return (Map) schema.get("properties"); + } + + @Test + void valuesAreTypedAsJacksonSeesThem() { + Map region = JsonSchemas.of(Region.class); + assertEquals("object", region.get("type")); + Map p = props(region); + assertEquals(Map.of("type", "string"), p.get("name")); + assertEquals(Map.of("type", "object", "additionalProperties", Map.of("type", "number")), p.get("load")); + assertEquals(Map.of("type", "string", "format", "date-time"), p.get("since")); + assertEquals(Map.of("type", "string", "format", "date"), p.get("day")); + + Map hosts = (Map) p.get("hosts"); + assertEquals("array", hosts.get("type")); + Map host = props((Map) hosts.get("items")); + assertEquals(Map.of("type", "string", "enum", List.of("CRITICAL", "STANDARD")), host.get("tier")); + assertEquals(Map.of("type", "array", "items", Map.of("type", "string")), host.get("tags")); + assertEquals(Map.of("type", "integer"), host.get("port")); + } + + @Test + void aTaskInputHasOnePropertyPerParameterAsCallsNameIt() { + Map input = JsonSchemas.taskInput(m("inventory")); + assertEquals("http://json-schema.org/draft-07/schema#", input.get("$schema")); + assertEquals(Map.of("fleet", Map.of("type", "string"), "max", Map.of("type", "integer")), props(input)); + // the workflow id parameter is filled from the task, not from the input + assertEquals(List.of("host"), List.copyOf(props(JsonSchemas.taskInput(m("probe"))).keySet())); + } + + @Test + void anOutputObjectSpreadsAndAnyOtherValueIsResult() { + assertEquals(List.of("name", "hosts", "load", "since", "day"), + List.copyOf(props(JsonSchemas.taskOutput(m("inventory"))).keySet())); + assertEquals(Map.of("result", Map.of("type", "string")), props(JsonSchemas.taskOutput(m("probe")))); + assertEquals(List.of("hosts"), List.copyOf(props(JsonSchemas.taskOutput(m("hosts"))).keySet())); + assertEquals(Map.of("result", Map.of("type", "array", "items", Map.of("type", "string"))), + props(JsonSchemas.taskOutput(m("twoInputs")))); + } + + @Test + void nothingIsSaidOfNoOutputOrARawResult() { + assertNull(JsonSchemas.taskOutput(m("noOutput"))); + assertNull(JsonSchemas.taskOutput(m("raw"))); + } + + @Test + void aTypeThatHoldsItselfIsNotUnrolledAgain() { + Map node = props(JsonSchemas.taskOutput(m("node"))); + assertEquals(Map.of("type", "object"), node.get("next")); + } + + @Test + void aWorkflowTakesASingleObjectsPropertiesElseOnePerParameter() { + assertEquals(List.of("name", "hosts", "load", "since", "day"), + List.copyOf(props(JsonSchemas.workflowInput(m("workflow"))).keySet())); + assertEquals(List.of("a", "b"), List.copyOf(props(JsonSchemas.workflowInput(m("twoInputs"))).keySet())); + assertEquals(Map.of("result", Map.of("type", "string")), props(JsonSchemas.workflowOutput(m("workflow")))); + } +} 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..afe081c83 --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/SwitchOnTest.java @@ -0,0 +1,579 @@ +/* + * 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 java.util.UUID; +import java.util.concurrent.Future; + +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.NonDeterminismException; +import org.conductoross.conductor.sdk.Variable; +import org.conductoross.conductor.sdk.Workflow; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +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.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 { + + /** The task stub the workflows below call: its calls schedule the tasks. */ + static final Tasks TASKS = Conductor.stub(Tasks.class); + + 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", () -> TASKS.a("x")) + .when("none", () -> "nothing") + .otherwise(() -> TASKS.b("y")) + .get(); + return TASKS.send(r); + } + } + + public static class NoOtherwise { + @Workflow(name = "no_otherwise") + public String run(Map input) { + switchOn("route", input.get("route")).when("a", () -> TASKS.a("x")).run(); + return "done"; + } + } + + public static class ChangedFirstCall { + @Workflow(name = "switch_flow") + public String run(Map input) { + return 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); + } + + /** + * A marker of continuation {@code n} of {@code lane}, applied {@code step}-th; its lane and + * number go on the task's entry ({@link #doneTask}), as the server keeps them. + */ + private static Map marker(String lane, int n, String state, long step) { + Map m = new LinkedHashMap<>(); + m.put("lane", lane); + m.put("n", n); + if ("APPLIED".equals(state)) { + m.put("endTime", step); + } + m.put("leased", "LEASED".equals(state)); + 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", continuation == null + ? Map.of("type", type) + : Map.of("type", type, "metadata", + Map.of("lane", continuation.get("lane"), "continuation", continuation.get("n")))); + 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); + + 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("native-code", 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(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); + + 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); + + 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); + 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); + + 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 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)); + Assertions.assertThrows(NonDeterminismException.class, + () -> new Replayer(spec(DroppedCall.class), new DroppedCall(), exec).process(null, 0)); + } + + public static class Previewed { + @Variable + public List notes = new ArrayList<>(); + + @Workflow(name = "previewed") + public String run(Map input) { + switchOn("route", input.get("route")) + .when("a", () -> TASKS.a("x")) + .when("b", () -> { + // a body that keeps going past its first call, forks, and mutates a variable + String first = TASKS.b("y"); + notes.add("previewed " + first); + Future p1 = Conductor.async(() -> TASKS.a("left")); + Future p2 = Conductor.async(() -> TASKS.b("right")); + Conductor.join(p1, p2); + return TASKS.send(first.toUpperCase()); + }) + .when("c", () -> { + switchOn("inner", "?").when("x", () -> TASKS.a("ix")).otherwise(() -> TASKS.b("iy")).run(); + return "c"; + }) + .otherwise(() -> 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).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 TASKS.send("after"); + } + } + + public static class DollarValue { + @Workflow(name = "dollar_value") + public String run(Map input) { + return switchOn("route", "${workflow.input}").when("${workflow.input}", () -> TASKS.a("x")).get(); + } + } + + public static class TaskInFinally { + @Workflow(name = "task_in_finally") + public String run(Map input) { + try { + return TASKS.a("x"); + } finally { + TASKS.b("y"); + } + } + } + + public static class Unjoined { + @Workflow(name = "unjoined") + public String run(Map input) { + Conductor.async(() -> TASKS.a("x")); + return "done"; + } + } + + public static class CallBeforeJoin { + @Workflow(name = "call_before_join") + public String run(Map input) { + Conductor.async(() -> TASKS.a("x")); + return 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).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).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() { + UUID id = UUID.randomUUID(); + assertEquals(id, Json.decodeOutput(Map.of("result", id.toString()), UUID.class)); + } + + public static class FannedOut { + @Workflow(name = "fanned_out") + public String run(Map input) { + switchOn("route", input.get("route")) + .when("a", () -> TASKS.a("x")) + .when("b", () -> { + List items = new ArrayList<>(); // what a stand-in result looks like + Conductor.fanOut("spread", items, i -> TASKS.b(i)); + return 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); + + 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); + + 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")); + } + + /** What the replayer logged at WARN while {@code body} ran. */ + private static List warnings(Runnable body) { + ch.qos.logback.classic.Logger logger = + (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Replayer.class); + ch.qos.logback.core.read.ListAppender seen = new ch.qos.logback.core.read.ListAppender<>(); + seen.start(); + logger.addAppender(seen); + try { + body.run(); + } finally { + logger.detachAppender(seen); + } + return seen.list.stream() + .filter(e -> e.getLevel() == ch.qos.logback.classic.Level.WARN) + .map(ch.qos.logback.classic.spi.ILoggingEvent::getFormattedMessage) + .toList(); + } + + @SuppressWarnings("unchecked") + private static Object inputOf(Map entry, String name) { + return ((Map) entry.get("inputParameters")).get(name); + } + + @SuppressWarnings("unchecked") + @Test + void aSwitchRecordedOnOneCaseTakesItAgainWhateverTheCodeNowComputes() { + Map aEntry = taskEntry("shipA", "shipA", Map.of("lane", "main", "n", 2)); + Execution exec = execution(Map.of("route", "none"), // the code now computes "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)); + Replayer.Outcome[] out = new Replayer.Outcome[1]; + List warnings = warnings(() -> out[0] = new Replayer(spec(Flow.class), new Flow(), exec).process("main", 2)); + + List> fragment = (List>) out[0].output.get("fragment"); + assertEquals(1, fragment.size(), String.valueOf(fragment)); + assertEquals("notify", fragment.get(0).get("taskReferenceName")); + assertEquals("x", inputOf(fragment.get(0), "x"), "case a ran, with the recorded result of its task: " + fragment); + assertEquals(1, warnings.size(), warnings.toString()); + assertTrue(warnings.get(0).contains("route") && warnings.get(0).contains("none") && warnings.get(0).contains(" a"), + warnings.get(0)); + } + + @SuppressWarnings("unchecked") + @Test + void aSwitchRecordedOnItsDefaultTakesTheDefaultAgain() { + Map bEntry = taskEntry("shipB", "shipB", Map.of("lane", "main", "n", 2)); + Execution exec = execution(Map.of("route", "a"), // the code now computes a declared case ... + List.of(switchEntry("zzz", List.of(bEntry))), // ... but the recording took the default + List.of(doneTask("route", "SWITCH", 1, Map.of("selectedCase", "default"), null), + doneTask("shipB", "shipB", 2, Map.of("result", "y"), marker("main", 2, "LEASED", 0))), + marker("main", 1, "APPLIED", 1)); + Replayer.Outcome out = new Replayer(spec(Flow.class), new Flow(), exec).process("main", 2); + + List> fragment = (List>) out.output.get("fragment"); + assertEquals("notify", fragment.get(0).get("taskReferenceName")); + assertEquals("y", inputOf(fragment.get(0), "x"), "the default ran, with the recorded result of its task: " + fragment); + } + + @Test + void aValueWithNoCaseOnReplayDoesNotFailAWorkflowWhoseSwitchIsRecorded() { + Map aEntry = taskEntry("shipA", "shipA", Map.of("lane", "main", "n", 2)); + Execution exec = execution(Map.of("route", "q"), // no case for q, and no otherwise ... + List.of(switchEntry("a", List.of(aEntry))), // ... but the switch was decided: 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)); + Replayer.Outcome out = new Replayer(spec(NoOtherwise.class), new NoOtherwise(), exec).process("main", 2); + + assertEquals(true, out.output.get("done"), String.valueOf(out.output)); + assertNull(out.output.get("error"), String.valueOf(out.output)); + } + + @Test + void aRecordedCaseTheCodeNoLongerHasIsStillADivergence() { + Map goneEntry = taskEntry("shipB", "shipB", Map.of("lane", "main", "n", 2)); + Execution exec = execution(Map.of("route", "a"), + List.of(switchEntry("gone", List.of(goneEntry))), // a case this code does not declare, and it has no otherwise + List.of(doneTask("route", "SWITCH", 1, Map.of("selectedCase", "default"), null), + doneTask("shipB", "shipB", 2, Map.of("result", "y"), marker("main", 2, "LEASED", 0))), + marker("main", 1, "APPLIED", 1)); + NonDeterminismException e = assertThrows(NonDeterminismException.class, + () -> new Replayer(spec(NoOtherwise.class), new NoOtherwise(), exec).process("main", 2)); + assertTrue(e.getMessage().contains("took case gone"), e.getMessage()); + } + + @Test + void aSwitchThatAgreesWithItsRecordingLogsNothing() { + 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)); + assertEquals(List.of(), warnings(() -> new Replayer(spec(Flow.class), new Flow(), exec).process("main", 2))); + } + + @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)); + 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..95f08a562 --- /dev/null +++ b/conductor-client/src/test/java/org/conductoross/conductor/sdk/internal/TaskStubsTest.java @@ -0,0 +1,226 @@ +/* + * 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 java.util.Objects; + +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.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 = 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 Conductor.forEach("ship_each", List.of("a", "b"), tasks::ship2); + } + } + + 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 aCallOnTheStubSchedulesTheTask() { + List> direct = firstFragment(Direct.class); + assertEquals("stub_reserve", direct.get(0).get("name")); + assertEquals(Map.of("order", Map.of("item", "book", "quantity", 2)), direct.get(0).get("inputParameters")); + } + + @Test + void forEachThroughAStubIsALoopOfTheTask() throws Exception { + List> byStub = firstFragment(EachByStub.class); + 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 = 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("conductor.workflows(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("leased", true); // the first continuation, offered and not yet applied + 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); + return (List>) out.output.get("fragment"); + } +} diff --git a/conductor-client/src/test/java/parked/ParkedLanesTest.java b/conductor-client/src/test/java/parked/ParkedLanesTest.java new file mode 100644 index 000000000..94c663bcc --- /dev/null +++ b/conductor-client/src/test/java/parked/ParkedLanesTest.java @@ -0,0 +1,448 @@ +/* + * 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 parked; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Future; + +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.TaskFailure; +import org.conductoross.conductor.sdk.Variable; +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 com.fasterxml.jackson.databind.ObjectMapper; + +import static org.conductoross.conductor.sdk.Conductor.async; +import static org.conductoross.conductor.sdk.Conductor.doWhile; +import static org.conductoross.conductor.sdk.Conductor.forEach; +import static org.conductoross.conductor.sdk.Conductor.join; +import static org.conductoross.conductor.sdk.Conductor.once; +import static org.conductoross.conductor.sdk.Conductor.random; +import static org.conductoross.conductor.sdk.Conductor.switchOn; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Code kept in memory between continuations does what a replay of the execution does. + * + *

Every continuation here is processed twice against the same recorded execution: by a + * replayer kept since the execution began, whose lanes are parked where they paused and are woken + * with the task they waited for; and by a new replayer that runs the method from the top, as a + * host that kept nothing does. Their completions must be the same. The kept one's completion is + * then applied to the recording, so the next replay also checks that what stayed in memory is + * what was recorded. + */ +class ParkedLanesTest { + + static final Tasks TASKS = Conductor.stub(Tasks.class); + + public static class Tasks { + @WorkerTask("pk_step") + public String step(@InputParam("x") String x) { + return x; + } + } + + /** A switch, a loop with a failure caught, an if, two lanes and a helper, values recorded, a doWhile. */ + public static class Shipping { + + @Variable + String stage = "new"; + + @Variable + List notes = new ArrayList<>(); + + @Workflow(name = "pk_shipping") + public String run(@InputParam("order") String order) { + double drawn = random(); + String route = switchOn("route", drawn < 2 ? "air" : "sea") + .when("air", () -> TASKS.step("air")) + .when("sea", () -> TASKS.step("sea")) + .get(); + stage = "routed"; + int reserved = 0; + for (String sku : List.of("a", "b")) { + try { + TASKS.step("reserve-" + sku); + reserved++; + } catch (TaskFailure e) { + notes.add("no " + sku); + } + } + if (reserved > 1) { + TASKS.step("bulk"); + } + Future left = async(() -> TASKS.step("L") + label("L2")); + Future right = async(() -> TASKS.step("R")); + join(left, right); + String code = once("code", () -> "c-" + order); + int[] pass = {0}; + doWhile("poll", () -> { + TASKS.step("p" + pass[0]); + pass[0]++; + }, () -> pass[0] < 2); + String last = TASKS.step("notify"); + stage = "shipped"; + return route + "|" + reserved + "|" + get(left) + "|" + get(right) + "|" + code + "|" + last + + "|" + drawn + "|" + notes; + } + + // a second frame on the stack at the pause + private String label(String side) { + return TASKS.step(side); + } + + private static String get(Future lane) { + try { + return lane.get(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + } + + /** A loop the server runs, whose result is read from the loop's tasks. */ + public static class EachItem { + @Workflow(name = "pk_each") + public String run(@InputParam("order") String order) { + String first = TASKS.step("first"); + List all = forEach("each", List.of("a", "b"), TASKS::step); + return first + all + TASKS.step("last"); + } + } + + @Test + void codeKeptInMemoryCompletesEveryContinuationAsAReplayDoes() { + Run run = new Run(Shipping.class, Map.of("order", "o-1")); + + run.step(null); + run.complete(run.pending("air"), "AIR"); + run.step(run.done("air")); + run.complete(run.pending("reserve-a"), "ok"); + run.step(run.done("reserve-a")); + run.fail(run.pending("reserve-b"), "out of stock"); + run.step(run.done("reserve-b")); + + // two lanes and the join the main lane waits at; the right lane's task ends first + run.complete(run.pending("R"), "R"); + run.step(run.done("R")); + run.complete(run.pending("L"), "L"); + run.step(run.done("L")); + run.complete(run.pending("L2"), "L2"); + run.step(run.done("L2")); + String joined = run.pendingJoin(); + run.complete(joined, Map.of()); + run.step(joined); + + run.complete(run.pending("p0"), "p"); + run.step(run.done("p0")); + run.complete(run.pending("p1"), "p"); + run.step(run.done("p1")); + run.complete(run.pending("notify"), "sent"); + Map last = run.step(run.done("notify")); + + assertEquals(true, last.get("done")); + @SuppressWarnings("unchecked") + String result = String.valueOf(((Map) last.get("result")).get("result")); + // the number drawn in the first continuation is the one the last continuation returns + Object drawn = ((Map) run.bootstrap.get("recorded")).get("random"); + assertEquals("AIR|1|LL2|R|c-o-1|sent|" + ((Map) drawn).get("value") + "|[no b]", result); + assertEquals("shipped", run.variables.get("stage")); + // nothing is waited for any more: there is nothing to keep + assertFalse(run.kept.hasPausedLanes()); + // 11 continuations: the first was the kept replayer's only replay + assertEquals(10, run.continuedInMemory); + } + + @Test + void aLaneThatWaitedOnALoopTheServerRanContinuesWithTheExecutionReadAgain() { + Run run = new Run(EachItem.class, Map.of("order", "o-1")); + + run.step(null); + run.complete(run.pending("first"), "F"); + run.step(run.done("first")); + + // the loop ran its task once per item; the lane reads those tasks, not the loop's own + String loop = run.pendingOfType("DO_WHILE"); + assertTrue(run.kept.readsTasks("main")); + run.iteration("each_task__1", "A"); + run.iteration("each_task__2", "B"); + run.complete(loop, Map.of("iteration", 2)); + run.step(loop); + assertFalse(run.kept.readsTasks("main")); + + run.complete(run.pending("last"), "Z"); + Map last = run.step(run.done("last")); + + assertEquals(Map.of("result", "F[A, B]Z"), last.get("result")); + assertEquals(1, run.readAgain); + } + + @Test + void aReplayerAwaitsOnlyTheContinuationItsLanePausedAt() { + Run run = new Run(Shipping.class, Map.of("order", "o-1")); + run.step(null); + + assertTrue(run.kept.awaits("main", 2)); + assertFalse(run.kept.awaits("main", 1)); // already ran: a retry of it must replay + assertFalse(run.kept.awaits("main", 3)); + assertFalse(run.kept.awaits("fork_1.0", 1)); // no such lane yet + + run.kept.close(); + assertFalse(run.kept.awaits("main", 2)); // its lanes are gone + assertFalse(run.kept.hasPausedLanes()); + } + + // ------------------------------------------------------------------ the recorded execution + + /** + * An execution as the server records it, as far as a replay reads it: the definition grown by + * each fragment, a task for every entry the engine would schedule, and the continuation + * markers. The test completes the tasks. + */ + static final class Run { + private static final ObjectMapper JSON = new ObjectMapper(); + + final WorkflowSpec spec; + final Map input; + final Map variables = new LinkedHashMap<>(); + final List> definition = new ArrayList<>(); + final List> tasks = new ArrayList<>(); + final Map bootstrap = new LinkedHashMap<>(); + long clock = 1000; + /** The replayer kept since the first continuation. */ + Replayer kept; + int continuedInMemory; + int readAgain; + + Run(Class workflow, Map input) { + this.spec = WorkflowSpec.of(workflow).get(0); + this.input = input; + } + + /** + * Processes the continuation that follows the task {@code ref} (null: the first one) both + * ways, checks that the completions agree, and applies the kept replayer's. + */ + Map step(String ref) { + Map awaited = ref == null ? null : task(ref); + String lane = ref == null ? "main" : String.valueOf(metadata(awaited).get("lane")); + int n = ref == null ? 1 : ((Number) metadata(awaited).get("continuation")).intValue(); + + // a host that kept nothing: the method from the top, against the recording + Map replayed = new Replayer(spec, spec.newInstance(), execution()).process(lane, n).output; + + Replayer.Outcome outcome; + if (kept == null) { + kept = new Replayer(spec, spec.newInstance(), execution()); + outcome = kept.begin(lane, n); + } else { + assertTrue(kept.awaits(lane, n), "the kept lanes do not wait for " + lane + "#" + n); + if (kept.readsTasks(lane)) { + readAgain++; + outcome = kept.proceed(lane, n, execution()); + } else { + // all a poll hands out: the task the lane waited for, and the variables + outcome = kept.proceed(lane, n, copy(variables), Execution.TaskView.of( + (String) awaited.get("taskId"), ref, (String) awaited.get("taskType"), + (String) awaited.get("status"), copy(output(awaited)), + (String) awaited.get("reasonForIncompletion"))); + } + continuedInMemory++; + } + Map completion = copy(outcome.output); + assertEquals(comparable(copy(replayed)), comparable(copy(completion)), "continuation " + lane + "#" + n); + apply(awaited, completion); + kept.forgetHistory(); + return completion; + } + + /** The values a continuation records are its own (a number drawn, the time): their names are compared. */ + private static Map comparable(Map completion) { + Map c = new LinkedHashMap<>(completion); + c.put("recorded", new ArrayList<>(((Map) completion.get("recorded")).keySet())); + return c; + } + + @SuppressWarnings("unchecked") + private void apply(Map awaited, Map completion) { + Map marker = awaited == null ? bootstrap : (Map) awaited.get("continuation"); + marker.put("endTime", ++clock); + marker.put("recorded", completion.get("recorded")); + marker.put("resumedWith", completion.get("resumedWith")); + marker.put("done", completion.get("done")); + variables.putAll((Map) completion.get("variables")); + List> fragment = (List>) completion.get("fragment"); + definition.addAll(fragment); + schedule(fragment); + } + + /** A task for each entry the engine would schedule: not a preview, and of a switch only the case taken. */ + @SuppressWarnings("unchecked") + private void schedule(List> entries) { + for (Map entry : entries) { + Map md = (Map) entry.get("metadata"); + if (Boolean.TRUE.equals(md.get("preview"))) { + continue; + } + String type = (String) entry.get("type"); + switch (type) { + case "FORK_JOIN" -> { + add(entry, "COMPLETED"); + ((List>>) entry.get("forkTasks")).forEach(this::schedule); + } + case "SWITCH" -> { + add(entry, "COMPLETED"); + Object taken = ((Map) entry.get("inputParameters")).get("switchCaseValue"); + List> list = + ((Map>>) entry.get("decisionCases")).get(taken); + schedule(list != null ? list : (List>) entry.get("defaultCase")); + } + case "JOIN" -> add(entry, Boolean.TRUE.equals(md.get("detached")) ? "COMPLETED" : "IN_PROGRESS"); + case "TERMINATE" -> { } + default -> add(entry, "IN_PROGRESS"); + } + } + } + + @SuppressWarnings("unchecked") + private Map add(Map entry, String status) { + Map md = (Map) entry.get("metadata"); + Map t = new LinkedHashMap<>(); + t.put("taskId", "id-" + entry.get("taskReferenceName")); + t.put("referenceTaskName", entry.get("taskReferenceName")); + t.put("taskType", entry.get("type")); + t.put("status", status); + t.put("seq", tasks.size() + 1); + t.put("inputData", entry.get("inputParameters")); + t.put("outputData", new LinkedHashMap<>()); + t.put("workflowTask", Map.of("type", entry.get("type"), "metadata", md)); + if (md.get("continuation") != null) { + t.put("continuation", new LinkedHashMap<>()); // the code paused on it: not run yet + } + tasks.add(t); + return t; + } + + Execution execution() { + Map json = new LinkedHashMap<>(); + json.put("workflowId", "wf-1"); + json.put("status", "RUNNING"); + json.put("input", input); + json.put("variables", variables); + json.put("workflowDefinition", Map.of("name", spec.name, "tasks", definition)); + json.put("tasks", tasks); + json.put("nativeState", Map.of("bootstrap", bootstrap)); + return new Execution(copy(json)); + } + + Map task(String ref) { + return tasks.stream().filter(t -> ref.equals(t.get("referenceTaskName"))).findFirst() + .orElseThrow(() -> new AssertionError("no task " + ref + " in " + refs())); + } + + private List refs() { + return tasks.stream().map(t -> t.get("referenceTaskName") + "=" + t.get("status")).toList(); + } + + /** The reference of the running task whose input {@code x} is this. */ + String pending(String x) { + return byInput(x, "IN_PROGRESS"); + } + + /** The reference of the ended task whose input {@code x} is this. */ + String done(String x) { + return tasks.stream() + .filter(t -> !"IN_PROGRESS".equals(t.get("status")) && t.get("inputData") instanceof Map in && x.equals(in.get("x"))) + .map(t -> (String) t.get("referenceTaskName")).findFirst() + .orElseThrow(() -> new AssertionError("no ended task with x=" + x + " in " + refs())); + } + + private String byInput(String x, String status) { + return tasks.stream() + .filter(t -> status.equals(t.get("status")) && t.get("inputData") instanceof Map in && x.equals(in.get("x"))) + .map(t -> (String) t.get("referenceTaskName")).findFirst() + .orElseThrow(() -> new AssertionError("no " + status + " task with x=" + x + " in " + refs())); + } + + String pendingJoin() { + return pendingOfType("JOIN"); + } + + String pendingOfType(String type) { + return tasks.stream() + .filter(t -> "IN_PROGRESS".equals(t.get("status")) && type.equals(t.get("taskType"))) + .map(t -> (String) t.get("referenceTaskName")).findFirst() + .orElseThrow(() -> new AssertionError("no running " + type + " in " + refs())); + } + + void complete(String ref, String result) { + complete(ref, Map.of("result", result)); + } + + void complete(String ref, Map output) { + Map t = task(ref); + t.put("status", "COMPLETED"); + t.put("outputData", new LinkedHashMap<>(output)); + } + + void fail(String ref, String reason) { + Map t = task(ref); + t.put("status", "FAILED"); + t.put("reasonForIncompletion", reason); + } + + /** A task one pass of a server loop ran. */ + void iteration(String ref, String result) { + Map t = new LinkedHashMap<>(); + t.put("taskId", "id-" + ref); + t.put("referenceTaskName", ref); + t.put("taskType", "pk_step"); + t.put("status", "COMPLETED"); + t.put("seq", tasks.size() + 1); + t.put("outputData", Map.of("result", result)); + tasks.add(t); + } + + @SuppressWarnings("unchecked") + private static Map metadata(Map task) { + return (Map) ((Map) task.get("workflowTask")).get("metadata"); + } + + @SuppressWarnings("unchecked") + private static Map output(Map task) { + return (Map) task.get("outputData"); + } + + /** Through JSON, as everything between a worker and the server goes. */ + @SuppressWarnings("unchecked") + private static Map copy(Map map) { + try { + return JSON.readValue(JSON.writeValueAsString(map), LinkedHashMap.class); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + } +} 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..afaecd76d --- /dev/null +++ b/conductor-client/src/test/java/plainbranches/PlainBranchesTest.java @@ -0,0 +1,746 @@ +/* + * 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.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.NonDeterminismException; +import org.conductoross.conductor.sdk.Workflow; +import org.conductoross.conductor.sdk.internal.CodeReader; +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 org.mockito.ArgumentMatchers; +import org.mockito.Mockito; + +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: what runs after it is its false arm + } + 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 aCompoundConditionIsOneBranchAndWhatFollowsAGuardIsItsFalseArm() { + List> top = Replayer.discover(spec(Conditions.class)); + assertEquals(List.of("if_route"), refs(top)); + assertEquals(List.of(), refs(cases(top.get(0)).get("true"))); + List> entries = defaultCase(top.get(0)); + 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); + } + + /** + * A marker of continuation {@code n} of the main lane, applied {@code step}-th; its lane and + * number go on the task's entry ({@link #done}), as the server keeps them. + */ + private static Map marker(int n, String state, long step) { + Map m = new LinkedHashMap<>(); + m.put("lane", "main"); + m.put("n", n); + if ("APPLIED".equals(state)) { + m.put("endTime", step); + } + m.put("leased", "LEASED".equals(state)); + 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", continuation == null + ? Map.of("type", type) + : Map.of("type", type, "metadata", + Map.of("lane", continuation.get("lane"), "continuation", continuation.get("n")))); + 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); + } + + 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(2, metadata(a).get("continuation")); + assertEquals("main", metadata(a).get("lane")); + 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); + 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)); + 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)); + 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); + 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)); + 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 = Mockito.mock(Tasks.class); + Mockito.when(tasks.b("y")).thenReturn("from b"); + 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()); + Mockito.verify(tasks, Mockito.never()).a(ArgumentMatchers.anyString()); + } + } + + @Test + void inMemoryAFactoryGivesTheWorkflowTaskStubsFromConductorStub() { + Tasks tasks = Mockito.mock(Tasks.class); + Mockito.when(tasks.done("z")).thenReturn("finished"); + try (DurableTestEnvironment env = DurableTestEnvironment.inMemory()) { + env.workflows(IfElse.class, () -> new IfElse(Conductor.stub(Tasks.class))).tasks(tasks); + assertEquals("finished", env.start(IfElse::run, "a").result()); + 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(); + 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 = Files.readAllLines( + Path.of("src/test/java/plainbranches/PlainBranchesTest.java")); + 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 = 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(), 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); + } + } + + public static class ThrowInLoop { + private final Tasks tasks; + + public ThrowInLoop(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "pb_throw_in_loop") + public String run(@InputParam("x") String x) { + String raw = tasks.a(x); + for (int i = 0; i < 2; i++) { + if (raw.startsWith("s")) { + Integer.parseInt(raw); + tasks.b("parsed"); + } + } + return tasks.done(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); + } + + @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 = Files.readAllLines(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 theMarkOfAnExceptionInALoopIsInThatLoopLikeTheIfItThrewInside() { + List> fragment = fragment(second(ThrowInLoop.class, "seven")); + Map sw = fragment.get(0); + List loops = (List) metadata(sw).get("loops"); + assertEquals(1, loops.size(), "the if is inside the for loop"); + Map thrown = cases(sw).get("true").get(0); + assertEquals("TERMINATE", thrown.get("type")); + assertEquals(loops, metadata(thrown).get("loops"), "the mark is where the code threw: in the loop"); + } + + @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)); + } +} diff --git a/conductor-client/src/test/java/repeatednames/RepeatedNamesTest.java b/conductor-client/src/test/java/repeatednames/RepeatedNamesTest.java new file mode 100644 index 000000000..1c61e07e8 --- /dev/null +++ b/conductor-client/src/test/java/repeatednames/RepeatedNamesTest.java @@ -0,0 +1,79 @@ +/* + * 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 repeatednames; + +import java.util.List; + +import org.conductoross.conductor.sdk.Workflow; +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 static org.conductoross.conductor.sdk.Conductor.llm; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * A name given in the code is numbered when the call is made again. The numbering counts calls as + * they run, so a loop and the same calls written out get the same names. + */ +class RepeatedNamesTest { + + public static class Notes { + + @Workflow(name = "rn_loop") + public String loop(@InputParam("x") String x) { + String r = x; + for (int i = 0; i < 3; i++) { + r = llm("note").model("anthropic/claude-haiku-5-5").prompt(r).as(String.class); + } + return r; + } + + @Workflow(name = "rn_unrolled") + public String unrolled(@InputParam("x") String x) { + String r = llm("note").model("anthropic/claude-haiku-5-5").prompt(x).as(String.class); + r = llm("note").model("anthropic/claude-haiku-5-5").prompt(r).as(String.class); + return llm("note").model("anthropic/claude-haiku-5-5").prompt(r).as(String.class); + } + } + + @Test + void aNamedCallInALoopIsNumberedByItsTurn() { + try (DurableTestEnvironment env = DurableTestEnvironment.inMemory()) { + env.workflows(Notes.class).llm("note").respond("ok"); + TestRun run = env.start(Notes::loop, "x"); + assertEquals("ok", run.result()); + assertEquals(List.of("note", "note_2", "note_3"), run.ranTasks()); + } + } + + @Test + void theSameCallsWrittenOutGetTheSameNamesAsTheLoop() { + try (DurableTestEnvironment env = DurableTestEnvironment.inMemory()) { + env.workflows(Notes.class).llm("note").respond("ok"); + TestRun run = env.start(Notes::unrolled, "x"); + assertEquals("ok", run.result()); + assertEquals(List.of("note", "note_2", "note_3"), run.ranTasks()); + } + } + + @Test + void aStubForANumberedNameAnswersOnlyThatTurn() { + try (DurableTestEnvironment env = DurableTestEnvironment.inMemory()) { + env.workflows(Notes.class).llm("note").respond("every turn").llm("note_3").respond("the last turn"); + assertEquals("the last turn", env.start(Notes::loop, "x").result()); + } + } +} diff --git a/conductor-client/src/test/java/returnvalues/RepeatUntilFailureTest.java b/conductor-client/src/test/java/returnvalues/RepeatUntilFailureTest.java new file mode 100644 index 000000000..2cafe8a47 --- /dev/null +++ b/conductor-client/src/test/java/returnvalues/RepeatUntilFailureTest.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 returnvalues; + +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.conductoross.conductor.sdk.Backoff; +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.TaskFailure; +import org.conductoross.conductor.sdk.Workflow; +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.conductoross.conductor.sdk.testing.DurableTestEnvironment; +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; + +/** + * A {@code repeatUntil} whose check fails on its last attempt: the code gets a {@link TaskFailure}, + * against a server and in the in-memory test environment alike. + */ +@SuppressWarnings("unchecked") +class RepeatUntilFailureTest { + + public record Status(boolean done) {} + + public static class Tasks { + @WorkerTask(value = "ru_status", retryCount = 0) + public Status status(@InputParam("key") String key) { + throw new IllegalStateException("status service is down"); + } + } + + public static class Poller { + private final Tasks tasks; + + public Poller(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "ru_poller") + public String run(@InputParam("key") String key) { + try { + Status status = Conductor.repeatUntil( + () -> tasks.status(key), Status::done, Backoff.every(Duration.ofSeconds(1)).attempts(3)); + return "polled: " + status; + } catch (TaskFailure e) { + return "the check failed"; + } + } + } + + private static Map marker(long endTime) { + Map m = new LinkedHashMap<>(); + if (endTime > 0) { + m.put("endTime", endTime); + } + m.put("leased", endTime == 0); + m.put("resumedWith", Map.of()); + m.put("recorded", Map.of()); + return m; + } + + private static Execution execution(Object defTasks, List> tasks, Map bootstrap) { + Map json = new LinkedHashMap<>(); + json.put("workflowId", "wf-1"); + json.put("status", "RUNNING"); + json.put("input", Map.of("key", "k")); + json.put("workflowDefinition", Map.of("name", "ru", "tasks", defTasks)); + json.put("tasks", tasks); + json.put("nativeState", Map.of("bootstrap", bootstrap)); + return new Execution(json); + } + + private static Map task(String ref, String type, String status, int seq) { + Map t = new LinkedHashMap<>(); + t.put("taskId", "id-" + ref); + t.put("referenceTaskName", ref); + t.put("taskType", type); + t.put("status", status); + t.put("seq", seq); + t.put("outputData", Map.of()); + t.put("workflowTask", Map.of("type", type)); + return t; + } + + @Test + void againstAServerTheCodeGetsTheFailureOfTheLastCheck() throws Exception { + WorkflowSpec spec = WorkflowSpec.of(Poller.class).get(0); + Replayer.Outcome started = new Replayer(spec, spec.newInstance(), execution(List.of(), List.of(), marker(0))) + .process("main", 1); + Object drawn = Json.MAPPER.readValue(Json.MAPPER.writeValueAsString(started.output.get("fragment")), Object.class); + // the loop ran its three attempts and ended; the last check failed + Map loop = task("poll", "DO_WHILE", "COMPLETED", 1); + loop.put("workflowTask", Map.of("type", "DO_WHILE", "metadata", Map.of("lane", "main", "continuation", 2))); + loop.put("continuation", marker(0)); + Map lastCheck = task("poll_check__3", "ru_status", "FAILED", 2); + lastCheck.put("reasonForIncompletion", "status service is down"); + + Replayer.Outcome out = new Replayer(spec, spec.newInstance(), execution(drawn, List.of(loop, lastCheck), marker(1))) + .process("main", 2); + + assertEquals(Map.of("result", "the check failed"), out.output.get("result")); + } + + @Test + void inMemoryTheCodeGetsTheFailureOfTheLastCheckToo() { + try (DurableTestEnvironment env = DurableTestEnvironment.inMemory()) { + env.workflows(Poller.class).tasks(new Tasks()); + assertEquals("the check failed", env.start(Poller::run, "k").result()); + } + } +} diff --git a/conductor-client/src/test/java/returnvalues/ReturnValuesTest.java b/conductor-client/src/test/java/returnvalues/ReturnValuesTest.java new file mode 100644 index 000000000..ce0b7dfc1 --- /dev/null +++ b/conductor-client/src/test/java/returnvalues/ReturnValuesTest.java @@ -0,0 +1,285 @@ +/* + * 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 returnvalues; + +import java.lang.reflect.Method; +import java.time.Duration; +import java.time.Instant; +import java.util.Arrays; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Future; + +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.Workflow; +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.conductoross.conductor.sdk.testing.DurableTestEnvironment; +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; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * What code returns, and what it gets back: a lane that returns null, a value recorded with + * {@code once}, and results that are neither an object nor one of the usual scalars. Outside the + * SDK's packages, as application code is. + */ +@SuppressWarnings("unchecked") +class ReturnValuesTest { + + public static class Tasks { + @WorkerTask("rv_audit") + public String audit(@InputParam("x") String x) { + return x; + } + } + + // ------------------------------------------------------------------ executions, as the server keeps them + + private static WorkflowSpec spec(Class type) { + return WorkflowSpec.of(type).get(0); + } + + /** A marker as the server keeps it: leased, or applied {@code endTime}-th with what it recorded. */ + private static Map marker(long endTime, Object recorded) { + Map m = new LinkedHashMap<>(); + if (endTime > 0) { + m.put("endTime", endTime); + } + m.put("leased", endTime == 0); + m.put("resumedWith", Map.of()); + m.put("recorded", recorded == null ? Map.of() : recorded); + return m; + } + + private static Execution execution(Map input, Object 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", "rv", "tasks", defTasks)); + json.put("tasks", tasks); + json.put("nativeState", Map.of("bootstrap", bootstrap)); + return new Execution(json); + } + + /** A finished task the code paused on in {@code lane}, whose continuation {@code n} is leased. */ + private static Map done(String ref, int seq, Map output, String lane, int n) { + Map t = new LinkedHashMap<>(); + t.put("taskId", "id-" + ref); + t.put("referenceTaskName", ref); + t.put("taskType", ref); + t.put("status", "COMPLETED"); + t.put("seq", seq); + t.put("outputData", output); + t.put("workflowTask", Map.of("type", "SIMPLE", "metadata", Map.of("lane", lane, "continuation", n))); + t.put("continuation", marker(0, null)); + 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(0, null))) + .process("main", 1); + } + + /** What the server stores of a completion and returns with the execution: its JSON. */ + private static T asStored(Object value) throws Exception { + return (T) Json.MAPPER.readValue(Json.MAPPER.writeValueAsString(value), Object.class); + } + + // ------------------------------------------------------------------ a lane that returns null + + public static class NullLane { + private final Tasks tasks; + + public NullLane(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "rv_null_lane") + public String run(@InputParam("id") String id) { + Future audited = Conductor.async(() -> { + tasks.audit(id); + return null; + }); + Conductor.join(audited); + return "ok"; + } + } + + @Test + void aLaneThatPausedOnATaskAndReturnsNullCompletes() throws Exception { + Replayer.Outcome started = first(NullLane.class, Map.of("id", "42")); + // the first continuation drew the fork; its task finished, and the lane resumes after it + Execution exec = execution(Map.of("id", "42"), asStored(started.output.get("fragment")), + List.of(done("rv_audit", 2, Map.of("result", "42"), "fork_1.0", 1)), marker(1, null)); + WorkflowSpec spec = spec(NullLane.class); + + Replayer.Outcome out = new Replayer(spec, spec.newInstance(), exec).process("fork_1.0", 1); + + assertEquals(true, out.output.get("done")); + assertNull(out.output.get("error")); + } + + // ------------------------------------------------------------------ once + + public record Order(int id) {} + + public static class Recorded { + private final Tasks tasks; + + public Recorded(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "rv_recorded") + public String run(@InputParam("x") String x) { + List orders = Conductor.once("orders", () -> List.of(new Order(7))); + tasks.audit(x); + return "order " + orders.get(0).id(); + } + } + + @Test + void aListRecordedWithOnceIsTheSameListAfterTheNextTask() throws Exception { + Replayer.Outcome started = first(Recorded.class, Map.of("x", "a")); + assertEquals(false, started.output.get("done")); + // the server applied the first continuation, with what it recorded; the task finished + Execution exec = execution(Map.of("x", "a"), asStored(started.output.get("fragment")), + List.of(done("rv_audit", 1, Map.of("result", "a"), "main", 2)), + marker(1, asStored(started.output.get("recorded")))); + WorkflowSpec spec = spec(Recorded.class); + + Replayer.Outcome out = new Replayer(spec, spec.newInstance(), exec).process("main", 2); + + assertNull(out.output.get("error"), "the workflow failed reading back what once recorded"); + assertEquals(Map.of("result", "order 7"), out.output.get("result")); + } + + // ------------------------------------------------------------------ results that are one value + + public static class Reserve { + @Workflow(name = "rv_reserve") + public UUID run(@InputParam("id") String id) { + return UUID.fromString(id); + } + } + + @Test + void aWorkflowReturningAUuidCompletesWithItAsItsResult() { + String id = "123e4567-e89b-12d3-a456-426614174000"; + + Replayer.Outcome out = first(Reserve.class, Map.of("id", id)); + + assertEquals(true, out.output.get("done")); + assertEquals(Map.of("result", id), out.output.get("result")); + assertEquals(UUID.fromString(id), Json.decodeOutput((Map) out.output.get("result"), UUID.class)); + } + + @Test + void aDurationAndADateEncodeAsOneValueAndDecodeBack() { + Duration wait = Duration.ofMinutes(5); + assertEquals(wait, Json.decodeOutput(Json.encodeOutput(wait), Duration.class)); + Date at = new Date(1_700_000_000_000L); + assertEquals(at, Json.decodeOutput(Json.encodeOutput(at), Date.class)); + } + + public static class ByUuid { + @Workflow(name = "rv_by_uuid") + public String run(@InputParam("id") UUID id) { + return id.toString(); + } + } + + @Test + void aSingleUuidParameterIsSentByNameAndReadBack() throws Exception { + UUID id = UUID.fromString("123e4567-e89b-12d3-a456-426614174000"); + Method run = ByUuid.class.getMethod("run", UUID.class); + + Map input = WorkflowSpec.encodeInput(run, new Object[] {id}); + + assertEquals(Map.of("id", id.toString()), input); + assertEquals(id, WorkflowSpec.decodeInput(run, input)[0]); + } + + public enum Size { + SMALL, + LARGE { + @Override + public String toString() { + return "large"; + } + } + } + + @Test + void recordedValuesReadBackAsWhatTheyWere() throws Exception { + ClassLoader loader = getClass().getClassLoader(); + List values = List.of( + "text", 7, 2.5, true, new Order(1), Size.LARGE, + UUID.fromString("123e4567-e89b-12d3-a456-426614174000"), + Instant.parse("2026-01-02T03:04:05.123456789Z"), + Duration.ofSeconds(90), + List.of(new Order(1), new Order(2)), + List.of(List.of(new Order(1)), List.of(new Order(2), new Order(3))), + new LinkedHashSet<>(List.of(Size.SMALL, Size.LARGE)), + Map.of("a", new Order(1)), + List.of(), + Arrays.asList("mixed", 1)); + for (Object value : values) { + // through the server and back: only the JSON survives + Map stored = asStored(Json.record(value)); + assertEquals(value, Json.recorded(stored, loader), "recorded as " + stored); + } + String[] array = {"a", "b"}; + assertEquals(List.of(array), List.of((String[]) Json.recorded(asStored(Json.record(array)), loader))); + assertNull(Json.recorded(asStored(Json.record(null)), loader)); + } + + @Test + void aValueRecordedByAnEarlierBuildByItsClassNameStillReadsBack() { + Map earlier = Map.of("value", "2026-01-02T03:04:05Z", "type", "java.time.Instant"); + assertEquals(Instant.parse("2026-01-02T03:04:05Z"), Json.recorded(earlier, getClass().getClassLoader())); + } + + public static class RecordedInMemory { + @Workflow(name = "rv_recorded_in_memory") + public String run(@InputParam("x") String x) { + Object first = Conductor.once("orders", () -> List.of(new Order(7))); + return first.getClass().getSimpleName() + " of " + ((List) first).get(0).getClass().getSimpleName(); + } + } + + @Test + void onceGivesTheCodeTheSameValueOnItsFirstRunAsOnAReRunAndInMemory() { + // the first run, against a server: what was recorded, read back + assertEquals(Map.of("result", "ArrayList of Order"), first(RecordedInMemory.class, Map.of("x", "a")).output.get("result")); + try (DurableTestEnvironment env = + DurableTestEnvironment.inMemory()) { + env.workflows(RecordedInMemory.class); + assertEquals("ArrayList of Order", env.start(RecordedInMemory::run, "a").result()); + } + } +} diff --git a/conductor-client/src/test/java/strict/StrictDeterminismTest.java b/conductor-client/src/test/java/strict/StrictDeterminismTest.java new file mode 100644 index 000000000..04460ede6 --- /dev/null +++ b/conductor-client/src/test/java/strict/StrictDeterminismTest.java @@ -0,0 +1,282 @@ +/* + * 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 strict; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneOffset; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; + +import org.conductoross.conductor.sdk.Conductor; +import org.conductoross.conductor.sdk.NonDeterminismException; +import org.conductoross.conductor.sdk.Signal; +import org.conductoross.conductor.sdk.Variable; +import org.conductoross.conductor.sdk.Workers; +import org.conductoross.conductor.sdk.Workflow; +import org.conductoross.conductor.sdk.internal.CodeReader; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import com.netflix.conductor.client.http.ConductorClient; +import com.netflix.conductor.sdk.workflow.task.InputParam; +import com.netflix.conductor.sdk.workflow.task.WorkerTask; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import okhttp3.mockwebserver.Dispatcher; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; + +import static org.conductoross.conductor.sdk.Conductor.doWhile; +import static org.conductoross.conductor.sdk.Conductor.now; +import static org.conductoross.conductor.sdk.Conductor.once; +import static org.conductoross.conductor.sdk.Conductor.random; +import static org.conductoross.conductor.sdk.Conductor.switchOn; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Workflow code that asks the JVM itself for a random value or the time is found when the workers + * start: warned about, or refused when the workflow is hosted with strictDeterminism. + */ +class StrictDeterminismTest { + + public static class Tasks { + @WorkerTask("sd_step") + public String step(@InputParam("x") String x) { + return x + System.currentTimeMillis(); // a task runs once: not workflow code + } + } + + /** A random source or a clock read everywhere workflow code can be. */ + public static class Raw { + private final Tasks tasks; + @Variable private String note; + + public Raw(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "sd_raw") + public String run(@InputParam("x") String x) { + double d = Math.random(); // RAW_DIRECT + String at = stamp(); + String r = switchOn("route", x) + .when("a", () -> tasks.step(UUID.randomUUID().toString())) // RAW_CASE + .otherwise(() -> "none") + .get(); + int[] n = {0}; + doWhile("poll", () -> { + n[0] += 1 + new Random().nextInt(3); // RAW_BODY + tasks.step(r); + }, () -> n[0] < 2); + List.of(x).forEach(i -> note = i + System.nanoTime()); // RAW_LAMBDA + return tasks.step(d + at); + } + + private static String stamp() { + return Instant.now().toString(); // RAW_HELPER + } + + @Signal("poke") + public void poke(String v) { + note = v + System.currentTimeMillis(); // a handler is never replayed: not checked + } + } + + /** The same needs met with values that are recorded, seeded, or read from a clock given to them. */ + public static class Clean { + private final Tasks tasks; + + public Clean(Tasks tasks) { + this.tasks = tasks; + } + + @Workflow(name = "sd_clean") + public String run(@InputParam("x") String x) { + String id = once("id", () -> UUID.randomUUID().toString()); + double d = random(); + Instant at = now(); + int n = new Random(42).nextInt(10); + LocalDate day = LocalDate.now(Clock.fixed(at, ZoneOffset.UTC)); + return tasks.step(id + d + at + n + day); + } + } + + private MockWebServer server; + private Conductor conductor; + private final Map settings = new HashMap<>(); + private final ListAppender logged = new ListAppender<>(); + + @BeforeEach + void start() throws Exception { + server = new MockWebServer(); + server.setDispatcher(new Dispatcher() { + @Override + public MockResponse dispatch(RecordedRequest request) { + String path = request.getPath(); + String body = path.startsWith("/api/tasks/poll") || path.startsWith("/api/metadata/taskdefs") + || path.startsWith("/api/schema") ? "[]" : "{}"; + return new MockResponse().setHeader("Content-Type", "application/json").setBody(body); + } + }); + server.start(); + conductor = Conductor.of(ConductorClient.builder().basePath(server.url("/api").toString()).build()); + logged.start(); + ((Logger) LoggerFactory.getLogger(Workers.class)).addAppender(logged); + } + + @AfterEach + void stop() throws Exception { + ((Logger) LoggerFactory.getLogger(Workers.class)).detachAppender(logged); + conductor.close(); + server.shutdown(); + } + + private static int line(String mark) throws Exception { + List source = Files.readAllLines( + Path.of("src/test/java/strict/StrictDeterminismTest.java")); + for (int i = 0; i < source.size(); i++) { + if (source.get(i).trim().endsWith("// " + mark)) { + return i + 1; + } + } + throw new AssertionError(mark); + } + + /** Each place as {@code line call -> replacement}, by line. */ + private static List places(Class workflow) throws Exception { + return CodeReader.rawSources(workflow.getMethod("run", String.class)).stream() + .map(r -> r.site().substring(r.site().lastIndexOf(':') + 1) + " " + r.call() + " -> " + r.replacement()) + .sorted() + .toList(); + } + + private List logged(Level level) { + return logged.list.stream().filter(e -> e.getLevel() == level).map(ILoggingEvent::getFormattedMessage) + .filter(m -> m.contains("sd_")).toList(); + } + + /** Whether the server hears from the workers within a few seconds: they register and poll at once. */ + private boolean heardFromWithin(int before, long millis) throws InterruptedException { + long until = System.currentTimeMillis() + millis; + while (System.currentTimeMillis() < until) { + if (server.getRequestCount() > before) { + return true; + } + Thread.sleep(20); + } + return false; + } + + @Test + void everyRandomSourceAndClockReadTheWorkflowCanReachIsFoundWithItsLine() throws Exception { + assertEquals(List.of( + line("RAW_DIRECT") + " Math.random() -> Conductor.random()", + line("RAW_CASE") + " UUID.randomUUID() -> Conductor.once(name, () -> UUID.randomUUID())", + line("RAW_BODY") + " new Random() -> Conductor.random()", + line("RAW_LAMBDA") + " System.nanoTime() -> Conductor.now()", + line("RAW_HELPER") + " Instant.now() -> Conductor.now()").stream().sorted().toList(), + places(Raw.class)); + } + + @Test + void recordedSeededAndGivenSourcesAreNotReported() throws Exception { + assertEquals(List.of(), places(Clean.class)); + } + + @Test + void byDefaultTheWorkflowIsHostedAndEachPlaceIsAWarning() throws Exception { + int before = server.getRequestCount(); + Workers host = conductor.workflows(Raw.class, Clean.class).settings(settings::get).start(); + try { + assertTrue(heardFromWithin(before, 5000), "the workers registered and polled"); + List warnings = logged(Level.WARN); + assertEquals(5, warnings.size(), warnings.toString()); + assertTrue(warnings.stream().allMatch(w -> w.contains("sd_raw") && w.contains("strictDeterminism=true")), warnings.toString()); + String direct = "Raw.run:" + line("RAW_DIRECT"); + assertTrue(warnings.stream().anyMatch(w -> w.contains("Math.random()") && w.contains(direct) + && w.contains("Conductor.random()")), warnings.toString()); + assertEquals(List.of(), logged(Level.ERROR)); + } finally { + host.close(); + } + } + + @Test + void withTheFlagTheWorkersDoNotStartAndTheErrorNamesEveryPlace() throws Exception { + settings.put("conductor.workflow.all.strictDeterminism", "true"); + int before = server.getRequestCount(); + NonDeterminismException e = assertThrows(NonDeterminismException.class, + () -> conductor.workflows(Raw.class, Clean.class).settings(settings::get).start()); + + String message = e.getMessage(); + assertTrue(message.startsWith("Workflow sd_raw cannot be hosted: 5 places in its code are not deterministic."), message); + for (String mark : List.of("RAW_DIRECT", "RAW_CASE", "RAW_BODY", "RAW_LAMBDA", "RAW_HELPER")) { + assertTrue(message.contains(":" + line(mark) + " "), mark + " at line " + line(mark) + " in:\n" + message); + } + assertTrue(message.contains("Math.random()") && message.contains("use Conductor.random()"), message); + assertTrue(message.contains("Instant.now()") && message.contains("use Conductor.now()"), message); + assertTrue(message.contains("use Conductor.once(name, () -> UUID.randomUUID())"), message); + assertTrue(message.contains("To host it anyway: conductor.workflow.sd_raw.strictDeterminism=false"), message); + assertFalse(message.contains("sd_clean"), "a workflow with nothing to report is not named: " + message); + assertEquals(List.of(message), logged(Level.ERROR)); + assertFalse(heardFromWithin(before, 500), "nothing was registered and nothing polls"); + } + + @Test + void theFlagOfOneWorkflowOverridesTheOneForAll() throws Exception { + settings.put("conductor.workflow.all.strictDeterminism", "true"); + settings.put("conductor.workflow.sd_raw.strictDeterminism", "false"); + int before = server.getRequestCount(); + Workers host = conductor.workflows(Raw.class, Clean.class).settings(settings::get).start(); + try { + assertTrue(heardFromWithin(before, 5000), "the workers registered and polled"); + assertEquals(5, logged(Level.WARN).size(), logged(Level.WARN).toString()); + } finally { + host.close(); + } + + settings.clear(); + settings.put("conductor.workflow.sd_raw.strictDeterminism", "true"); + assertThrows(NonDeterminismException.class, + () -> conductor.workflows(Raw.class, Clean.class).settings(settings::get).start()); + } + + @Test + void aWorkflowWithNothingToReportStartsUnderTheFlag() throws Exception { + settings.put("conductor.workflow.all.strictDeterminism", "true"); + int before = server.getRequestCount(); + Workers host = conductor.workflows(Clean.class).settings(settings::get).start(); + try { + assertTrue(heardFromWithin(before, 5000), "the workers registered and polled"); + assertEquals(List.of(), logged(Level.WARN)); + } finally { + host.close(); + } + } +} 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..2ff078716 --- /dev/null +++ b/conductor-client/src/test/java/stubsite/StubCallSiteTest.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 stubsite; + +import java.nio.file.Files; +import java.nio.file.Path; +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("leased", true); // the first continuation, offered and not yet applied + 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); + + 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 = Files.readAllLines( + 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..fc7cfa9d8 --- /dev/null +++ b/design/native-workflows/README.md @@ -0,0 +1,687 @@ +# 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)`): what it gets is a stub +whose calls schedule the task. A task with no Java method is called by name, `task("name")`. 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 +`conductor.workflows(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 | +|---|---| +| `design/native-workflows/determinism.md` | the guide to determinism: how a replay works, what is recorded, what retry and rerun do, how to write a workflow that takes the same path every time, and the strict determinism check | +| `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, iteration, MCP and A2A agents in section 3, the constructs composed inside each other in section 4, and Conductor's own constructs in section 5 (`switchOn`, `doWhile`, `forEach`, `repeatUntil`, `fanOut`, a workflow started by name, `random()`, `workflowId()`); sections 1 to 4 decide with plain `if` and `switch` and loop with 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/examples/` | the examples to learn from, numbered in reading order (`native-examples/README.md`): hello world, conditionals, loops, parallel, sub workflows, signals, timers, error handling, HTTP, human in the loop, LLM, MCP, an agent, and an agent harness; one file each, with a Gradle task per example (`./gradlew :native-examples:ex01_hello_world`) and an in-memory test in `src/test/java/examples` | +| `native-examples/src/main/java/primitives/` | one workflow per construct, each file showing its alternatives side by side: `TaskCalls` (stub, by name), `SwitchCase` (`if`, `switch` over strings, ints and enums, switch expressions, `switchOn`), `Loops` (`for`, for-each, `while`, `do`-`while`, `doWhile`, `forEach`, `repeatUntil`), `Parallel` (`async`, `join`, `fanOut`), `SubWorkflows` (`child`, `startWorkflow`), `Timers` (`sleep`, `sleepUntil`, `awaitCondition`, `@Schedule`), `Messages` (`@Variable`, `@Signal`, `@Update`, `@Query`), `Errors` (retries, `TaskFailure`, compensation, failing the run), `SideEffects` (`once`, `now`, `random`, `workflowId`), `SystemTasks` (HTTP, event, human, external wait, LLM, MCP, agent); `primitives.Main` runs them all against a server, checks each result and the execution, and replays each execution against its code | +| `native-examples/src/main/java/conformance/Conformance.java` | 160 scenarios against a server, each with an expected result and graph; exits non-zero on any failure | +| `native-examples/src/main/java/loops/LoopShapes.java` | each loop shape written twice, in plain Java and with its construct: `do`-`while` and `doWhile`, `for (;;)` with a break and `doWhile`, for-each and `forEach`, a polling `while` and `repeatUntil`; checks the result against a server | +| `native-examples/src/main/java/agents/SupportTicket.java` | an agentic customer-service ticket: a model (LLM_CHAT_COMPLETE) reads the ticket and answers, as a typed `Routing` record, which team should take it; a `switchOn` on that team hands the ticket to the team's agent (AGENT over A2A), or to a person (HUMAN) when no team fits; a second model call drafts the customer's reply. Runs against the stub's chat model through the server's LiteLLM provider (`--conductor.ai.litellm.baseURL=http://localhost:8765`); `SupportTicketTest` runs it in process with stubbed answers | +| `native-examples/src/main/java/agents/SupportDesk.java` | the same for an inbox of tickets, all at once: `fanOut` over the tickets, each handled by `SupportTicket`'s code | +| `native-examples/src/main/java/agents/Agents.java` | AI agents through AGENT tasks against the stub A2A agent (`native-examples/stubs/ai_stub.py`): two long-running agents started in `async` lanes while the workflow goes on, one polled (`pollInterval`) and one calling back (`pushNotifications`, which needs `conductor.a2a.callback.url`), joined at the end; a conversation (`agent(ref)` is the conversation; each `ask` continues it), a header, structured output in an artifact, an agent that asks for input answered by a person, and a failing agent caught as `TaskFailure`; checks the result and the execution against a server | +| `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)` | 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: `Future`, `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) { + Future fraud = async(() -> http("fraud").post(FRAUD_URL).body(order).as(FraudResult.class)); + List reserved = fanOut(order.items(), item -> inventory.reserve(item)); + join(fraud); + if (fraud.resultNow().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 | 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`; `native-code` on `switchCaseValue`). An `if` has the case `true` and its else as the default case (`if (!approved)` has the case `false`: the key is the value of what it is named after); 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 | +| `doWhile(name, () -> { ... }, () -> condition)` | the same as a Java `do`-`while`, named by the code instead of read from the compiled method: its body runs, then again while the condition holds, as ordinary code; each pass's outcome is recorded, so a replay makes the same number of passes; every step made from the body or the condition is tagged with `name` in `metadata.loops` (inside the loops around the call), so the execution diagram draws them as one loop named `name`, also for code whose loops cannot be read. A Java loop or another `doWhile` inside the body nests | at each call inside it | +| `async(() -> ...)` returning a `java.util.concurrent.Future`, `join(f1, f2)` then `resultNow()`, or `Future.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 -> ...)`, returning the `List` of results once every item is done | 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 | 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 | +| `external(ref).await(T.class, 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: native-code`, `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: every handled message is in `nativeState.replies` by the client's message id (an update with its reply), 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 and the Java loops 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 a plain `if` or `switch` must +take the arm it recorded; another is a divergence ("took X in the recorded execution but the code +now takes Y"). A `switchOn` takes the case it recorded whatever value the code computes then, so a +value that came from something unrecorded cannot move a retry or rerun to another case. + +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.workflows(X.class).continuationTimeout(Duration.ofSeconds(30))`, or `conductor.workflow..continuationTimeout` / `conductor.workflow.all.continuationTimeout` (seconds, or ISO-8601 such as `PT2M`) | 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 | +| code kept in memory | `conductor.workflows(X.class).parkTimeout(Duration.ofHours(1))`, or `conductor.workflow..parkTimeout` / `conductor.workflow.all.parkTimeout` (seconds, or ISO-8601); `conductor.workflow..maxParked` (1000). On by default; `parkTimeout=0`, or dev mode, replays every continuation | the execution is pinned to the host that holds it: `nativeState.pinnedTo` and `stamp` from the completion's `pin`; its next continuation is offered to that host's own queue first, and to any host after `conductor.app.nativeWorkflow.pinTimeout` (5 s). See "Code kept in memory" under "How an execution runs" | +| strict determinism | `conductor.workflow..strictDeterminism=true`, else `conductor.workflow.all.strictDeterminism`; off by default | none: the host refuses to start when the workflow's code reads a random source or the clock directly (rule 1 under "Rules for workflow code"), instead of warning | +| hosting | `@Workflow(threadCount = 20, pollingInterval = 100, pollTimeout = 500)`, overridden by `conductor.workflow..threadCount` (and `pollingInterval`, `pollTimeout`), else `conductor.workflow.all.*`; `conductor.workflow..paused=true` stops polling | none: each hosted workflow is a `TaskRunner` worker of its code type, as a `@WorkerTask` is of its task type: at most `threadCount` continuations at once (virtual threads), long polls of `pollTimeout` ms, `pollingInterval` ms between empty polls, completed with update-v2, which hands back the next continuation. Properties are system properties, or the Spring environment. A hosted `@WorkerTask` reads `conductor.worker..*`, else `conductor.worker.all.*`, else its annotation, and gets 8 threads when none sets `threadCount` (`AnnotatedWorkerExecutor` and Spring keep 1) | + +## 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.workflows(...).tasks(...).start()` starts the workers, + `conductor.start(Cls::method, input)` starts an execution and returns its `WorkflowHandle`: the + id, the UI link, signals, updates and queries, and the result, either blocking with + `result(timeout)` or as a `CompletableFuture` with `resultAsync()`, which completes with the + return value or with a `WorkflowFailedException`. One thread per `Conductor` checks every pending + future; cancelling one only stops waiting. Closing a `Conductor` stops its workers and cancels + the futures still waiting; 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 run + in real time. +- 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: any machine polling the shared queue of the code type can + run any of them. Task domains do not apply to workflow code: a start's `taskToDomain`, `*` + included, routes its tasks only. A new `@Workflow(version)` has its own code type and queue. +- A host keeps the executions it is running in memory and the server sends their continuations + back to it first ("Code kept in memory", below). Nothing has to be configured, and nothing + depends on it: a host that stops, restarts or is replaced by a deploy drops what it held, and + each of those executions is replayed once by whichever host takes its next continuation, at + most `conductor.app.nativeWorkflow.pinTimeout` (5 s) later. Every start makes a new queue for + the host, `pin--:`, polled only while the host holds executions of + that workflow; the queues and poll records of hosts that are gone stay behind, empty. +- 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 class and + method it is generated from, the continuation timeout and whether it has handlers. When the code + cannot be read the graph is empty and registration logs why. 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. Entries inside plain Java + loops carry `metadata.loops` (`_loop_`, outermost first), as an execution's do. +- Schemas: registration reads, by reflection, the JSON Schema of each `@WorkerTask`'s input (one + property per parameter, named as calls name it) and output (an object's properties, any other + value as `result`), and of the `@Workflow` method's input and output, shaped as the SDK sends the + data (`JsonSchemas`). They are registered by name in the schema registry (`_input`, + `_output`, `_input`, `_output`), versioned by content: a schema + identical to a registered version reuses it, any other is the next version, so re-registering + the same code changes nothing and builds running side by side keep theirs. Task and workflow + definitions reference them with `enforceSchema: false`: they document the data, and the code + decides what it accepts. A server without a schema registry is skipped with a warning. + 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 computes a different `switchOn` value than the recorded execution took | the recorded case runs and a warning names both; a divergence only when the code no longer declares the recorded case and has no `otherwise` | +| 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 = n` (its +lane is the entry's `metadata.lane`), and the server gives that task a continuation marker, which +holds the continuation's progress while the entry keeps saying which one it is. 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 `Future.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.** What is drawn is defined on the method's control flow, not on how +javac happens to lay the code out. A *step* is an instruction that calls the server: a task, an SDK +call, or a call into workflow code that makes one (a helper, a lambda, the method itself +recursively). The rules, written once; `CodeReader` implements them and the spec checker +(`proposals/native-workflows/spec/check_drawing.py`) computes the same definitions on its own +graph of the program: + +1. **Loops.** A loop is a natural loop: a jump back to an instruction that every way to the jump + passes first. It is a *real* loop when what goes round holds a step; one that does not (a + failed `when` guard going back to its switch) is plain code. A loop's *follow* is the one place + every way out of it leads to, among the ways out that can go on (a way out that only throws is + not one); its *extent* is what runs from its head before the follow. A `break` block is in the + extent; with a single `break` as the only way out, the break block is the follow, and the code + is the same as `do { ... } while (!c)` followed by it. +2. **Decisions.** A decision is a `switch`, or the jumps of one condition (`a && b`, `a || b` are + one jump per operand). Its condition is the switch with what it comes round to without a step + (a failed `when` guard dispatches again); its outcomes are the places the condition goes on to. + A loop's condition is the loop's own, not a decision: the jump out of it that the straight code + from its head comes to (a `while`, `for`, or a `while` whose condition calls a task), or the jump + back that closes it (a do-while). Any other jump out of a loop is a `break` (javac jumps + `else { break; }` straight out), and the if around it a decision. +3. **Arms.** An arm holds what runs only because its outcome was taken: the code every way to + which, from the start of the method, goes through that outcome, without leaving the extent of + the loop the decision is in. So the code after a guard clause (`if (bad) { reject(); continue; }`, + `if (x == null) return;`, `if (n == 0) return 0;` in a recursion) is the guard's false arm, and an + arm need not be one stretch of bytecode. +4. **Drawn.** A decision is drawn when an arm holds a step, every line with a step is in one arm + or in none (so a call tells the arm it was made in; a one-line ternary calling in both arms is + plain code), and no arm runs into a written `case` whose code reaches a step before the place + every arm meets (a case falling through into the next). Falling into the default is the same + code as a switch without one followed by that code, and is drawn as such. +5. **Labels.** An if has `true` and `false` (its default case): the value of what it is named + after, so `if (!approved)` keys its body `false` and the rest `true` (the default). A case is keyed by its labels as + written: numbers, characters (`a`), strings, enum constants, pattern types (`Circle`), `null`; a + guarded pattern is `Integer when` (numbered when two read the same). javac's synthetic default + of an exhaustive switch (`throw new MatchException`) is the `default` arm, which only throws. + 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. Whether the branch was decided again +between two calls in its arm comes from the method's instructions (`CodeReader.Paths`): when every +way between the calls without another call goes through its decision, it was, and is drawn again; +when none does, the call stays in the same case; when only some do (a loop in the arm, in a loop), +the code cannot tell, so the call is drawn outside the branch, and the branch is drawn again only +when a later call shows for sure it was decided again. A branch the code went past without a call +is drawn with the arm it took when every way between the two calls (or from the start of the +method, or to a return) goes through its decision exactly once and in one arm only; it goes in the +case of the branch it is in, also one the lane is just leaving or entering, or of another drawn +this way. + +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 or more than one pass could +have been. These rules are checked against an oracle that runs generated programs on its own +control-flow graph (`proposals/native-workflows/spec/check_drawing.py` in the conductor repo). 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 and the decider +has evaluated it, its continuation can run, 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; task domains do not apply to workflow code. The SDK holds no per-execution +lock: the server's one-continuation-per-execution slot (the one leased marker) is what +serializes an execution. A decide offers the marker (`leased`, at its `retryCount`): the handler +lane while messages are queued, else the first continuation until it applied, else the one whose +task ended first. Workers poll with the ordinary +batch task poll, which hands back the finished task itself. The worker reads which continuation +it is from the task's `workflowTask.metadata` (`lane`, `continuation`) and completes with the ordinary +task update (`update-v2`), echoing that number as `n` and the marker's `retryCount` (`Workers`); a completion from +an earlier attempt, or one for an offer that already applied, is refused with 409. `retryCount` is +0 on the first offer and goes up each time an attempt ends without applying. The first continuation +(`|main`) and each handler run (`|handlers`) have no task, so the poll +builds one from the execution's `nativeState`, with the claimed messages for a handler run, and +gives it an entry whose `metadata` names the continuation (`main` #1, or `handlers` and the run +number), so the SDK reads lane and number the same way for every continuation. The first +continuation is always `main` #1 (`Execution.bootstrap()`); the handler marker's `n` is its run +number. A marker stores only `leased`, `retryCount`, and once applied `endTime`, `done`, +`recorded` and `resumedWith`; applied means `endTime` is set (`Execution.Marker.applied()`). + +**A continuation is a replay, unless the code is still in memory.** The recording on the server +is all a worker needs: for a 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 (`Execution.segments()`: the applied markers, the first continuation's included, by `endTime`, which the server keeps increasing within a run; `@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`. + +**Code kept in memory.** Replaying every continuation costs more the longer an execution gets: the +k-th continuation fetches and replays the k-1 before it, so an execution of n tasks fetches and +replays in the order of n² task records over its life. So after a continuation the worker does not +tear the lanes down. They stay parked where they paused, on their virtual threads +(`ParkedExecutions`; `Replayer.begin`, `proceed`, `close`), and the next continuation wakes its +lane with the result of the task it waited for. Nothing is run again and nothing is fetched: the +poll hands out the awaited task, and with it the workflow's variables and the execution's stamp +(`TaskContinuation.variables`, `stamp`). A lane that waited on a loop the server ran +(`repeatUntil`, `forEach`) reads the loop's tasks, so that one continuation fetches the execution; +it still replays nothing. + +This only pays if the next continuation reaches the process that holds the code, so the execution +is pinned to it. The workers name a task domain of their own on every start +(`pin--`). Each completion that leaves lanes parked carries +`pin: {domain, stamp}`; the server records both on the execution and offers the next continuation +to that domain's queue first, with the shared queue as a fallback once the pin timeout has passed +(5 s). The stamp is how the worker knows its copy is current: it continues from memory only when +the server hands back the stamp it sent last, which means that its completion was the last to +apply and nothing has changed what the code did since. In every other case it closes what it held +and replays: another host continued the execution, a completion was refused or deferred, or the +execution was retried, rerun or restarted (the server clears the stamp). **A retry and a rerun +therefore always replay**; what is kept in memory is never what decides where an execution is. + +The copy is dropped after `parkTimeout` without a continuation (an hour by default), when a +workflow has more than `maxParked` executions held (1000; the ones idle longest go), and when the +workers close. Dropping one ends its lanes as the end of a continuation always did, by unwinding +their threads, so a `finally` block in workflow code runs then. Dev mode keeps nothing: every +continuation replays, which shows code that is not deterministic while it is being written. +Handler runs are not continued from memory; they fetch the execution as before. + +Measured against a server built from the conductor branch (`localhost`, SQLite): a workflow of +203 tasks ran its method from the first line once with the code kept, and 205 times with +`parkTimeout=0`. With the host that held an execution killed mid-run, a second host continued it +after 5.3 s in each of four runs, replaying once. + +**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. + +The two constructs the code hands to the SDK as lambdas follow the recording instead, since the SDK +chooses what runs. A `switchOn` that is already recorded runs the case of its recorded +`switchCaseValue`, whatever value the code computes on the replay; only a recorded case the code no +longer declares, with no `otherwise`, is a divergence. A `doWhile` records the outcome of its +condition for each pass (`_again`, `_again_2`, ... among the continuation's recorded +values) and a replay makes the recorded number of passes. In both the code still computes its +value (the condition may call tasks, and a replay must reach every recorded call), and a value that +differs from the recording is logged as a warning naming the switch or loop. An execution recorded +before passes were recorded has none, and its loops replay by their conditions. Plain Java `if`, +`switch`, `for` and `while` cannot be steered this way and stay strict. + +**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 + +[determinism.md](determinism.md) explains these with examples: how a replay works, what is recorded, +what a retry and a rerun do, and how to write a workflow that always takes the same path. + +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. The host reads + the compiled workflow code at `start()` and logs a warning for every place it can reach, through + lambdas and helpers in the workflow's package, that asks the JVM itself for a random value or + the time (`Math.random()`, an unseeded `new Random()`, `ThreadLocalRandom`, `SecureRandom`, + `UUID.randomUUID()`, `System.currentTimeMillis()`, `System.nanoTime()`, `Instant.now()` and the + other `java.time` `now()`s without a `Clock`, `new Date()`, `Calendar.getInstance()`), with its + line and what to use instead. With `conductor.workflow..strictDeterminism=true` (or + `conductor.workflow.all.strictDeterminism`) such a workflow is refused: `start()` throws + `NonDeterminismException` listing every place, before anything is registered or polled. The + lambda given to `once()`, task methods and handlers are not checked, and a helper in another + package is not followed. +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, 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` (`native-code` 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 fencing: the server accepts a completion only for the current offer (`n` and `retryCount`). +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. (Removed: a per-execution time scale for WAIT.) +7. Standing items: 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/determinism.md b/design/native-workflows/determinism.md new file mode 100644 index 000000000..84883632f --- /dev/null +++ b/design/native-workflows/determinism.md @@ -0,0 +1,383 @@ +# Determinism in native workflows + +For developers who write `@Workflow` methods and for operators who retry or rerun their +executions. It explains why workflow code must be deterministic, what the SDK records and what it +does not, what a retry or rerun does with the code, and how to write a workflow that always takes +the same path. The design as a whole is in [README.md](README.md). + +## The one thing to know + +**Workflow code runs again from the top, many times, for one execution.** It runs each time the +execution continues after a task, and again when an operator retries or reruns it. The results of +what it already did are given back to it, so nothing is done twice. For that to work the code must +ask for the same things in the same order every time it runs. That is what deterministic means +here. + +Code that only depends on its input and on the results of its tasks is deterministic without any +effort. Code that asks the JVM for a random number, the time or a new id is not, unless the value +is recorded. + +## How an execution runs + +A workflow is a plain method: + +```java +@Workflow(name = "ship_order") +public String ship(Order order) { + String label = tasks.printLabel(order); // 1 + String carrier = tasks.bookCarrier(order); // 2 + return tasks.notify(order, label, carrier); // 3 +} +``` + +What an execution is lives on the server: the tasks it ran and what they returned. Nothing a +worker holds is needed to continue it. Each time the server has a result for the code, a worker +does the following (a *continuation*): + +1. creates a new instance of the class and calls the method from the top; +2. answers every call the execution already made from the recording, at once, without scheduling + anything; +3. reaches the first call the execution has not made, schedules it, and stops there. + +So for the workflow above the method runs four times: up to line 1, then through line 1 to line 2, +then through lines 1 and 2 to line 3, then through all three to the `return`. Each run except the +last ends at a call whose result is not known yet. + +A worker avoids most of those runs. After a continuation it keeps the method where it stopped, in +memory, and when the execution's next continuation comes to the same process it goes on from +there with the task's result: steps 1 and 2 are skipped. That is a saving, not a different model. +The copy in memory is dropped when it sits idle, when the process restarts or is deployed, and +whenever the server says the execution moved on without it, and then the next continuation runs +the method from the top as above. A retry or a rerun always does. So the code must be correct +under replay even though, most of the time, it is not replayed. + +A call is matched to its recording by its lane (the main method, or an `async` block), its task +name and how many calls of that name came before it: `print_label`, `print_label_2`, +`print_label_3`. Source lines and the shape of the code play no part, which is why a log line can +be added to a workflow with executions in flight. + +When a run disagrees with the recording, by calling a task where the recording has another, or +none, the worker raises `NonDeterminismException` and the server holds the execution, retrying +with backoff, until a build that agrees with the recording runs it. This is a *divergence*. + +## What is recorded + +| What the code does | Recorded | On a later run | +|---|---|---| +| calls a task, `http`, `llm`, `child`, `sleep`, any server step | the task and its result | the result is returned; nothing is scheduled | +| `once(name, () -> ...)` | the value | the value is returned; the lambda does not run | +| `now()`, `random()` | the value | the same value is returned | +| `switchOn(name, value)` | the case taken (`switchCaseValue`) | **the recorded case runs**, whatever the value is now | +| `doWhile(name, body, condition)` | the outcome of the condition for each pass | **the recorded number of passes run** | +| `forEach`, `repeatUntil`, `fanOut` | the tasks the server ran for them | the results are returned | +| a `@Variable` field | its value at each continuation | restored to what it was at that point | +| a plain `if` or `switch` whose arms call tasks | the arm taken | **compared**: another arm is a divergence | +| any other plain Java | nothing | it simply runs again | + +Three of these rows are worth a closer look. + +**`switchOn` and `doWhile` follow the recording.** The SDK is handed their cases and their body as +lambdas, so it chooses what runs. Once a `switchOn` has been decided, every later run takes the +recorded case. Once a `doWhile` pass has been decided, every later run makes the same number of +passes. The code still computes its value each time (a condition may itself call tasks, and those +calls must be reached), but the recording decides. When the two disagree the worker logs a warning +that names the switch or the loop, because it means the value came from something that is not +recorded. + +**Plain `if`, `switch`, `for` and `while` cannot be steered.** They are ordinary Java, and nothing +at run time can make an `if` take the other arm. They take the same path only when what they test +is the same on every run. When it is not, the code calls something the recording does not have, +and the execution is held. + +**A value is recorded when the continuation that produced it completes.** If a worker dies in the +middle of a continuation, nothing that continuation did was kept, and another worker runs it +again: a `once` lambda can therefore run more than once, like a task. + +## Retry, rerun and restart + +An operator action changes the recording and then lets the code run again against it. + +| Action | What the server does | What the code does | +|---|---|---| +| **Retry** a failed execution | schedules a new attempt of the failed task; everything before it stays | runs from the top; every earlier call, value, case and pass is answered from the recording; the failed call now gets the new attempt's result | +| **Rerun** from a task | drops that task and everything after it; keeps what was recorded before it | runs from the top; what is before the task is answered from the recording, what is after is done again | +| **Restart** | drops everything | runs as a new execution: new values, new decisions | + +In detail, for a decision made in code: + +- rerun from a task **after** or **inside** a `switchOn` case keeps the decision; +- rerun from a task **before** a `switchOn` decides again, since the switch itself was dropped; +- rerun from the switch task itself, or from a fork or join task, is refused: those belong to the + code, not to the operator; +- restart decides again. + +`native-examples` `operator.OperatorChecks` checks each of these against a running server. + +Note what a retry does **not** do: it does not jump into the middle of the method. The code before +the failed task runs again. It does no work, since every call is answered from the recording, but +it does run, and it must arrive at the failed task by the same path as the first time. + +## What goes wrong + +A coupon, 20% for the lucky and 10% for the rest: + +```java +@Workflow(name = "random_coupon") +public Coupon issue(String customer) { + boolean lucky = Math.random() < 0.5; // a new number on every run + int percent; + if (lucky) { + percent = tasks.applyDiscount(customer, 20); + } else { + percent = tasks.applyDiscount(customer, 10); + } + String code = UUID.randomUUID().toString(); // a new id on every run + Instant issued = Instant.now(); // a new time on every run + return new Coupon(code, percent, issued, tasks.sendCoupon(customer, code)); +} +``` + +The first run draws `0.3`, takes the lucky arm and schedules `apply_discount`. When that task +completes the method runs again and draws `0.8`. Now it takes the other arm: + +- the plain `if` took `true` in the recording and takes `false` now: a divergence, and the + execution is held with `if_... took true in the recorded execution but the code now takes false`; +- had the decision gone the same way by luck, `send_coupon` would be scheduled with one id and the + workflow would return another, because `code` is drawn again on the run after it. + +Half of these executions get stuck after their first task. The other half get stuck one task +later, or complete with a coupon code that was never sent. A retry or a rerun rolls the dice again. + +## Writing deterministic workflows + +### 1. Take random values, the time and ids from the SDK + +| Instead of | Use | What it gives | +|---|---|---| +| `Math.random()`, `new Random()`, `ThreadLocalRandom.current()` | `random()` | a `double` in [0, 1), recorded | +| `Instant.now()`, `System.currentTimeMillis()`, `new Date()`, `LocalDate.now()` | `now()` | an `Instant`, recorded | +| `UUID.randomUUID()`, or anything else that can differ between runs | `once(name, () -> ...)` | whatever the lambda returns, recorded | + +All three are static imports from `org.conductoross.conductor.sdk.Conductor`. The coupon, fixed: + +```java +@Workflow(name = "recorded_coupon") +public Coupon issue(String customer) { + boolean lucky = random() < 0.5; // drawn once, the same on every run after + int percent; + if (lucky) { + percent = tasks.applyDiscount(customer, 20); + } else { + percent = tasks.applyDiscount(customer, 10); + } + String code = once("coupon_code", () -> UUID.randomUUID().toString()); + Instant issued = now(); + return new Coupon(code, percent, issued, tasks.sendCoupon(customer, code)); +} +``` + +Both versions are in `native-examples`, +[`examples/ex15_strict_determinism/StrictDeterminism.java`](../../native-examples/src/main/java/examples/ex15_strict_determinism/StrictDeterminism.java). + +Things that need a time derived from a clock take the recorded one: +`LocalDate.ofInstant(now(), zone)`, or `LocalDate.now(Clock.fixed(now(), zone))`. A `Random` made +with a seed that is itself deterministic (`new Random(order.id().hashCode())`) gives the same +numbers on every run and is fine. + +### 2. Put everything else that can change in a task or in `once` + +The JVM's clock and random sources are the obvious ones. These change between runs too, and +between the machines that may run the next continuation: + +- reading a file, a database, a cache, an HTTP endpoint; +- environment variables, system properties, configuration that can be reloaded, feature flags; +- static fields and singletons that other code changes; +- the host name, the process id, the thread name. + +Read them in a `@WorkerTask`, which is retried and shows in the execution, or in `once(...)` when +the read is small and may fail the workflow. Either way the workflow sees one value for the life of +the execution. + +```java +int limit = once("credit_limit", () -> config.creditLimit()); // not: config.creditLimit() +``` + +### 3. Make calls in an order that does not depend on the JVM + +Calls are matched by name and by how many came before, so the order they are made in is part of +the path. Iterating a `HashMap` or `HashSet` and calling a task for each element makes an order +that can differ between JVMs. Iterate a `List`, a `LinkedHashMap`, a `TreeMap`, or sort first. + +```java +for (String sku : new TreeSet<>(order.skus())) { // not: for (String sku : order.skus()) when skus() is a HashSet + tasks.reserve(sku); +} +``` + +### 4. Wait, and work in parallel, through the SDK + +- `sleep(Duration)`, never `Thread.sleep`: a `Thread.sleep` is repeated on every run and holds a + worker thread. The workers warn about each one at start. +- `async(() -> ...)`, `join` and `fanOut`, never your own threads or executors: what a thread of + your own does is not recorded, its timing differs on every run, and a call to the SDK from it + fails (`this call is only valid inside a @Workflow method run by Conductor`). + +### 5. Keep side effects out of plain code + +Plain code runs on every continuation. A counter incremented, a metric emitted, an email sent +from the workflow method happens once per run, not once per execution. The same goes for a +`finally` block, which also runs each time the code stops at a call. Side effects belong in tasks. +Logging is the exception people accept: a line logged from workflow code is logged again on each +run. + +### 6. Use `switchOn` and `doWhile` for decisions and loops you want protected + +A plain `if` or loop is the default, and it is correct whenever what it tests is recorded or comes +from the input. `switchOn` and `doWhile` give one thing more: once decided, they stay decided, even +if the value they were decided on turns out to differ on a later run. + +```java +String route = tasks.pickRoute(order); // a task result: the same on every run +String shipped = switchOn("route", route) + .when("air", () -> tasks.shipByAir(order)) + .when("sea", () -> tasks.shipBySea(order)) + .get(); +``` + +This protects the path, not the value. If `route` came from something unrecorded, the recorded +case would still run, but the local variable `route` would hold the new value on a later run, and +anything computed from it afterwards would differ. Rules 1 and 2 are what make values right; this +rule is a second line of defence for the path. + +### 7. Change code with executions in flight carefully + +A new build runs against the recordings of the executions the old build started. + +| Change | Executions in flight | +|---|---| +| a log line, a refactoring, a renamed local variable or method | unaffected | +| a call added, removed or reordered **after** the point they have reached | unaffected | +| a call added, removed or reordered **before** the point they have reached | held: the code and the recording disagree | +| the condition of a plain `if` changed so that it takes another arm for them | held | +| a `switchOn` case removed that they took, with no `otherwise` | held | +| a task renamed (`@WorkerTask` value) | held, where they already called it | + +For a change of the last four kinds, give the new code a new version, `@Workflow(name = "ship_order", +version = 2)`, and keep hosting version 1 until its executions end. Each version has its own queue. + +## The check when workers start + +`Workers.start()` reads the compiled code of every workflow it hosts, the workflow method, its +lambdas and the helper methods it calls, and looks for calls that ask the JVM for a random value +or the time: + +- `Math.random()`, `new Random()` and `new SplittableRandom()` without a seed, `SecureRandom`, + `ThreadLocalRandom.current()`, `RandomGenerator.getDefault()` and `of(..)` +- `UUID.randomUUID()` +- `System.currentTimeMillis()`, `System.nanoTime()` +- `Instant.now()`, `LocalDate.now()`, `LocalDateTime.now()`, `ZonedDateTime.now()` and the other + `java.time` `now()`s, with or without a zone, but not `now(Clock)` +- `Clock.systemUTC()` and the other system clocks, `new Date()`, `Calendar.getInstance()` + +Nothing is rewritten and nothing is run: the code is only read. + +**By default each place is a warning** in the log, naming the workflow, the call, its line and the +replacement, and the workflow is hosted. + +**With strict determinism the workflow is refused.** + +| Setting | Effect | +|---|---| +| `conductor.workflow..strictDeterminism=true` | refuse this workflow when its code has such a call | +| `conductor.workflow.all.strictDeterminism=true` | the same for every workflow; a workflow's own setting wins | + +They are system properties, or properties of the Spring environment, like the other workflow +settings. When any hosted workflow is refused, `start()` throws `NonDeterminismException` before +anything is registered with the server and before any poller starts, so none of the workers of +that `start()` runs. The message, also logged as an error, lists every place of every refused +workflow: + +``` +Workflow random_coupon cannot be hosted: 3 places in its code are not deterministic. + StrictDeterminism$RandomCoupon.issue:93 Math.random() use Conductor.random() + StrictDeterminism$RandomCoupon.newCode:108 UUID.randomUUID() use Conductor.once(name, () -> UUID.randomUUID()) + StrictDeterminism$RandomCoupon.issue:101 Instant.now() use Conductor.now() +A retry or rerun runs this code again and must take the same path. Anything else that can +change between runs goes in Conductor.once(name, () -> ...). +To host it anyway: conductor.workflow.random_coupon.strictDeterminism=false +``` + +Turn it on in CI and in production once the warnings are gone: a workflow that would get stuck on +its first retry then fails the deploy instead. + +### What the check does not look at, on purpose + +- the lambda given to `once(...)`: its value is recorded, so it may call anything; +- `@WorkerTask` methods: a task runs once and its result is recorded; +- `@Signal`, `@Update` and `@Query` handlers: they are not replayed. + +### What the check cannot see + +It finds direct calls to the JDK's clock and random sources. It does not prove a workflow +deterministic. + +- A helper in **another package** than the workflow class's (or its subpackages), or in a library, + is not followed. A call to `Math.random()` inside it is not found. +- Everything under rules 2 and 3 above: I/O, environment variables, static state, the iteration + order of unordered collections. +- A call that is there for a harmless reason, such as `System.nanoTime()` to log how long something + took, is reported all the same. Measure in a task, or leave strict determinism off for that + workflow. + +For these the recording is the net: a run that leaves the recorded path is held and named, and a +replay test finds it before production does. + +## Testing + +- **A replay test** runs the current code against a recorded execution and fails on any + divergence. Export an execution (`conductor workflow export `), keep the file with the tests, + and assert `DurableReplay.assertCompatible(ShipOrder.class, Path.of("ship-order.json"))`. It + catches the code changes of rule 7 in CI. `native-examples` `KitchenSinkTest` has one. +- **A start test** asserts a workflow passes the check: host it with the setting on and no server; + a refusal is thrown before anything is sent. `native-examples` + `examples/ex15_strict_determinism/StrictDeterminismTest` shows both outcomes. +- **The in-memory environment** (`DurableTestEnvironment.inMemory()`) runs the method once, start + to end, with no replay: it tests what the workflow does, not whether it is deterministic. It + does not run the check either. +- **Dev mode** (`conductor.workflows(...).devMode(true)`) replays every continuation against a + real server and keeps no code in memory. A host outside dev mode replays rarely, so code that + is not deterministic can run for weeks there and diverge on the first deploy; run a workflow + in dev mode, or with `conductor.workflow..parkTimeout=0`, before it goes out. + +## When an execution is held + +The message of the `NonDeterminismException` names what the code did and what the recording has +there, with the source line: + +``` +The running code differs from what this execution recorded: at ShipOrder.ship:42 it calls +book_carrier, but the recording has print_label there. Deploy a compatible build to continue. +``` + +Two causes, told apart by whether the code changed: + +- **The code changed** (rule 7). Deploy a build that agrees with the recording, or host the old + version next to the new one. The server retries the continuation with backoff, so the execution + continues by itself once a compatible worker polls. +- **The code did not change.** Then something it depends on did: look upstream of the named line + for a value that is not recorded (rules 1 to 3), and for the warnings the workers logged at + start. A warning that a switch or loop "took ... in the recorded execution and the code now + computes ..." points at the same kind of value, in a place where the SDK kept the execution on + its path. + +## Summary + +- Workflow code runs from the top on every continuation, retry and rerun; calls already made are + answered from the recording. +- Take random values from `random()`, the time from `now()`, and anything else that can differ + from `once(...)` or a task. +- `switchOn` and `doWhile` stay on the recorded path; plain `if` and loops rely on their inputs + being recorded. +- The workers warn about direct clock and random calls at start; `strictDeterminism=true` refuses + the workflow instead. +- A run that leaves the recorded path is held, never silently continued. diff --git a/design/native-workflows/server-changes.md b/design/native-workflows/server-changes.md new file mode 100644 index 000000000..b78463d9c --- /dev/null +++ b/design/native-workflows/server-changes.md @@ -0,0 +1,180 @@ +# 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`: + `leased`, `retryCount` (0 on the first offer, one more each time an attempt ends without + applying), and once applied the record a replay reads: `endTime` (its order; set when it + applies, the first continuation's included, so applied means `endTime > 0`), `done`, + `recorded`, `resumedWith`; and `n` on the handler lane's marker only, its run number. Which + continuation a task's marker is comes from the task's entry (`metadata.lane`, + `metadata.continuation`); its state is derived (leased; applied; runnable once its task has + ended and been evaluated; else waiting). Why the last completion did not apply is the + workflow's `reasonForIncompletion` (one continuation runs at a time), cleared by the next + apply. What the main lane returned is the run's output, and its exception the run's + `reasonForIncompletion`. Empty values are not stored: a marker that has not run is `{}`. +- `common/.../run/NativeState.java`, and a `nativeState` field on `Workflow` and `WorkflowModel`: + `bootstrap` and `handlers` (markers for the two lanes that have no task), and `replies` + (every handled message). The bootstrap is always `main` #1 and the handler marker's lane always + `handlers`, so neither is on a marker; the handler marker stores its run number (`{"n": 4}`). + O(1) in the length of the execution. The code type and the + continuation timeout stay in the definition's `metadata.native`. +- `TaskMapperContext.createTaskModel` gives the scheduled task a new marker when its entry carries + `metadata.continuation`. `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` evaluates a terminal task as for any task (`executed`), which is + all it takes for the continuation on it to be runnable. `WorkflowExecutorOps.decide` then runs + `repairAndWake`, saves the touched tasks and the workflow row, and pushes the offered + continuation's message, or the leased one's again (`pushIfNotExists`), to the continuation + queue: the shared queue of the code type; task domains do not apply to workflow code. While a + continuation 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 handler lane while messages are + queued, else the first continuation until it applied, else the one whose task ended first; the + marker `leased` at its `retryCount`, which makes it the slot, then the push. A deferred + continuation keeps its turn: it is offered again at once and holds the slot through its backoff. `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 claimed messages for a handler run and an entry whose `metadata` + names the continuation (`lane`, `continuation`) as a task's entry does; the SDK reads lane and + number from `task.workflowTask.metadata` for every continuation. +- Complete: `WorkflowExecutorOps.updateTask` routes a synthetic id, or a task with a marker 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 (marker leased, `n` the continuation's number from its entry, `retryCount` the marker's; 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` offers the handler lane first and this one once that lane has settled; every + deferral adds one to `retryCount` and puts its reason on the workflow), 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`). `done` stays on the marker for this: +the JOIN reads the definition and the tasks in two reads without the workflow lock, and `done` is +read with the task. + +### 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 and number from +the entry's metadata, the derived state, applied time from `endTime`); `ExecutionSummary.tsx` shows `nativeState` (code +type, continuations applied, bootstrap state while pending, handler run). A run is held while its +`reasonForIncompletion` starts with `diverged: `; the held step sits after the task whose marker +is leased. There are +no hidden tasks to fold. `metadata.site = "Class.method:line"` on every entry gives the source +line. A SWITCH emitted by `switchOn` or drawn for a plain if or switch uses the evaluator +`native-code`, which reads the case the code took from `switchCaseValue`; `SwitchTaskMapper` +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 (removed) + +Dropped: timers run in real time in development too. `Workers.timeScale` is gone, and +`WaitTaskMapper` is unchanged from `main`. + +## 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 `external(..)` waits 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 (removed) + +Dropped: nothing used it. + +## 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. +- No build pinning: workflow code is polled on the shared queue of its code type only, and 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/examples/old/README.md b/examples/old/README.md deleted file mode 100644 index 67c006472..000000000 --- a/examples/old/README.md +++ /dev/null @@ -1,50 +0,0 @@ -# Legacy Gradle Examples - -These are the original Gradle-based examples, preserved for reference. For new projects, use the [791 Maven examples](../) instead — they are self-contained, easier to run, and all OSS-compatible. - -## Running - -```bash -# Start Conductor locally -docker run -d -p 8080:8080 -p 1234:5000 conductoross/conductor:latest - -export CONDUCTOR_SERVER_URL=http://localhost:8080/api - -./gradlew run --main-class -``` - -## OSS-Compatible Examples - -These work with a plain OSS Conductor server — only `CONDUCTOR_SERVER_URL` required, no auth keys. - -| Class | Description | -|-------|-------------| -| `com.netflix.conductor.gettingstarted.CreateWorkflow` | Register a workflow definition | -| `com.netflix.conductor.gettingstarted.StartWorkflow` | Start a workflow | -| `com.netflix.conductor.gettingstarted.HelloWorker` | Poll and execute tasks | -| `com.netflix.conductor.sdk.examples.helloworld.Main` | End-to-end hello world | -| `com.netflix.conductor.sdk.examples.TaskRunner` | Task polling with workers | -| `com.netflix.conductor.sdk.examples.TaskRegistration` | Register task definitions | -| `com.netflix.conductor.sdk.examples.events.EventHandlerExample` | Event handler registration | -| `com.netflix.conductor.sdk.examples.events.EventListenerExample` | Event listener setup | -| `com.netflix.conductor.sdk.examples.taskdomains.Main` | Task domain routing | -| `com.netflix.conductor.sdk.examples.shipment.Main` | Shipment workflow | -| `io.orkes.conductor.sdk.examples.WorkflowManagement` | Workflow CRUD operations | -| `io.orkes.conductor.sdk.examples.WorkflowManagement2` | Workflow execution patterns | -| `io.orkes.conductor.sdk.examples.workflowops.Main` | Workflow operations | - -## Orkes Cloud–Only Examples - -These require an Orkes Cloud server with `CONDUCTOR_AUTH_KEY` and `CONDUCTOR_AUTH_SECRET` set. - -| Class | Why Orkes-only | -|-------|----------------| -| `io.orkes.conductor.sdk.examples.AuthorizationManagement` | Uses Orkes authorization API | -| `io.orkes.conductor.sdk.examples.SchedulerManagement` | Uses Orkes scheduler API | -| `io.orkes.conductor.sdk.examples.MetadataManagement` | Uses `OrkesClients` metadata extensions | -| `io.orkes.conductor.sdk.examples.agentic.FunctionCallingExample` | Requires LLM provider configured in server | -| `io.orkes.conductor.sdk.examples.agentic.LlmChatExample` | Requires LLM provider configured in server | -| `io.orkes.conductor.sdk.examples.agentic.RagWorkflowExample` | Requires vector DB + LLM integration | -| `io.orkes.conductor.sdk.examples.agentic.VectorDbExample` | Requires vector DB integration | -| `io.orkes.conductor.sdk.examples.agentic.HumanInLoopChatExample` | Requires LLM + human task integration | -| `io.orkes.conductor.sdk.examples.agentic.AgenticExamplesRunner` | Runner for the agentic examples above | diff --git a/examples/old/build.gradle b/examples/old/build.gradle deleted file mode 100644 index e6c1ff8a0..000000000 --- a/examples/old/build.gradle +++ /dev/null @@ -1,27 +0,0 @@ -plugins { - id 'java' - id 'application' -} - -// Allow running specific main class with: ./gradlew :examples:run -PmainClass= -// Default: AgenticExamplesRunner - unified runner for all AI/LLM examples -application { - mainClass = project.hasProperty('mainClass') ? project.property('mainClass') : 'io.orkes.conductor.sdk.examples.agentic.AgenticExamplesRunner' -} - -repositories { - mavenCentral() -} - -dependencies { - implementation project(':conductor-client') - implementation "ch.qos.logback:logback-classic:1.5.32" - implementation 'io.micrometer:micrometer-registry-prometheus:1.15.1' - - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.3' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.10.3' -} - -test { - useJUnitPlatform() -} \ No newline at end of file diff --git a/examples/old/src/main/java/com/netflix/conductor/gettingstarted/CreateWorkflow.java b/examples/old/src/main/java/com/netflix/conductor/gettingstarted/CreateWorkflow.java deleted file mode 100644 index f2a98e50d..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/gettingstarted/CreateWorkflow.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2024 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.gettingstarted; - -import com.netflix.conductor.sdk.workflow.def.WorkflowBuilder; -import com.netflix.conductor.sdk.workflow.def.tasks.SimpleTask; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -/** - * Very Simple Workflow As Code Example. - * - * You can use the following code to register this "hello_workflow" workflow. - * - * { - * "name": "hello_workflow", - * "description": "Hello Workflow!", - * "version": 1, - * "tasks": [ - * { - * "name": "hello_task", - * "taskReferenceName": "hello_task_ref", - * "type": "SIMPLE", - * "inputParameters": {} - * } - * ], - * "inputParameters": [], - * "outputParameters": { - * - * }, - * "schemaVersion": 2, - * "restartable": true, - * "workflowStatusListenerEnabled": false, - * "ownerEmail": "example@orkes.io", - * "timeoutPolicy": "ALERT_ONLY", - * "timeoutSeconds": 0 - * } - */ -public class CreateWorkflow { - - public static void main(String[] args) { - var executor = new WorkflowExecutor("http://localhost:8080/api"); - var workflow = new WorkflowBuilder(executor) - .name("hello_workflow") - .version(1) - .description("Hello Workflow!") - .ownerEmail("examples@orkes.io") - .add(new SimpleTask("hello_task", "hello_task_ref")) - .build(); - workflow.registerWorkflow(true, true); - executor.shutdown(); - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/gettingstarted/HelloWorker.java b/examples/old/src/main/java/com/netflix/conductor/gettingstarted/HelloWorker.java deleted file mode 100644 index 1a1f903e3..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/gettingstarted/HelloWorker.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2024 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.gettingstarted; - -import java.util.List; - -import com.netflix.conductor.client.automator.TaskRunnerConfigurer; -import com.netflix.conductor.client.http.ConductorClient; -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.TaskResult; - -public class HelloWorker implements Worker { - - @Override - public TaskResult execute(Task task) { - var taskResult = new TaskResult(task); - taskResult.setStatus(TaskResult.Status.COMPLETED); - taskResult.getOutputData().put("message", "Hello World!"); - return taskResult; - } - - @Override - public String getTaskDefName() { - return "hello_task"; - } - - public static void main(String[] args) { - var client = new ConductorClient("http://localhost:8080/api"); - var taskClient = new TaskClient(client); - var runnerConfigurer = new TaskRunnerConfigurer - .Builder(taskClient, List.of(new HelloWorker())) - .withThreadCount(10) - .build(); - runnerConfigurer.init(); - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/gettingstarted/StartWorkflow.java b/examples/old/src/main/java/com/netflix/conductor/gettingstarted/StartWorkflow.java deleted file mode 100644 index 486fb89f7..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/gettingstarted/StartWorkflow.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2024 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.gettingstarted; - -import com.netflix.conductor.client.http.ConductorClient; -import com.netflix.conductor.client.http.WorkflowClient; -import com.netflix.conductor.common.metadata.workflow.StartWorkflowRequest; - -public class StartWorkflow { - - public static void main(String[] args) { - var client = new ConductorClient("http://localhost:8080/api"); - var workflowClient = new WorkflowClient(client); - var workflowId = workflowClient.startWorkflow(new StartWorkflowRequest() - .withName("hello_workflow") - .withVersion(1)); - - System.out.println("Started workflow " + workflowId); - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/TaskRegistration.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/TaskRegistration.java deleted file mode 100644 index d1539881e..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/TaskRegistration.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2024 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.sdk.examples; - -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import com.netflix.conductor.client.http.ConductorClient; -import com.netflix.conductor.client.http.MetadataClient; -import com.netflix.conductor.common.metadata.tasks.TaskDef; - -import io.orkes.conductor.sdk.examples.util.ClientUtil; - - -public class TaskRegistration { - - public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException { - ConductorClient client = ClientUtil.getClient(); - MetadataClient metadataClient = new MetadataClient(client); - - TaskDef taskDef = new TaskDef(); - taskDef.setName("task_with_retries"); - taskDef.setDescription("Example task definition"); - taskDef.setRetryCount(3); - taskDef.setRetryLogic(TaskDef.RetryLogic.FIXED); - - //only allow 3 tasks at a time to be in the IN_PROGRESS status - taskDef.setConcurrentExecLimit(3); - - //timeout the task if not polled within 60 seconds of scheduling - taskDef.setPollTimeoutSeconds(60); - - //timeout the task if the task does not COMPLETE in 2 minutes - taskDef.setTimeoutSeconds(120); - - //for the long running tasks, timeout if the task does not get updated in COMPLETED or IN_PROGRESS status in 60 seconds after the last update - taskDef.setResponseTimeoutSeconds(60); - - //only allow 100 executions in a 10-second window! -- Note, this is complementary to concurrent_exec_limit - taskDef.setRateLimitPerFrequency(100); - taskDef.setRateLimitFrequencyInSeconds(10); - taskDef.setOwnerEmail("exampes@conductor-oss.org"); - - metadataClient.registerTaskDefs(List.of(taskDef)); - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/TaskRunner.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/TaskRunner.java deleted file mode 100644 index fba9e8d58..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/TaskRunner.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright 2022 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.sdk.examples; - -import java.util.*; - -import com.netflix.conductor.client.automator.TaskRunnerConfigurer; -import com.netflix.conductor.client.http.ConductorClient; -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.TaskResult; - -import io.orkes.conductor.sdk.examples.util.ClientUtil; - - -/** - * Task worker example. Shows how you can create a worker that polls and executes a SIMPLE task in - * the conductor workflow. - */ -public class TaskRunner { - public static void main(String[] args) { - ConductorClient client = ClientUtil.getClient(); - TaskClient taskClient = new TaskClient(client); - - // Add a list with Worker implementations - List workers = Arrays.asList(new TaskWorker(), new LongRunningTaskWorker()); - - TaskRunnerConfigurer.Builder builder = - new TaskRunnerConfigurer.Builder(taskClient, workers); - - // Map of task type to domain when polling for task from specific domains - Map taskToDomains = new HashMap<>(); - - // No. of threads for each task type. Used to configure taskType specific thread count for - // execution - Map taskThreadCount = new HashMap<>(); - - TaskRunnerConfigurer taskRunner = - builder.withThreadCount( - 10) // Default thread count if not specified in taskThreadCount - .withTaskToDomain(taskToDomains) - .withTaskThreadCount(taskThreadCount) - .withSleepWhenRetry( - 500) // Time in millis to sleep when retrying for a task update. - // Default is 500ms - // .withTaskPollTimeout(100) // Poll timeout for long-poll. Default is - // 100ms - .withWorkerNamePrefix( - "worker-") // Thread name prefix for the task worker executor. - // Useful for logging - .withUpdateRetryCount( - 3) // No. of times to retry if task update fails. defaults to 3 - .build(); - - // Start Polling for tasks and execute them - taskRunner.init(); - - // Optionally, use the shutdown method to stop polling - //taskRunner.shutdown(); - } - - /** Example Task Worker */ - private static class TaskWorker implements Worker { - - private static final String TASK_NAME = "simple_task"; - - @Override - public String getTaskDefName() { - return TASK_NAME; - } - - @Override - public TaskResult execute(Task task) { - // execute method is called once the task is scheduled in the workflow - // The method implements the business logic for the task. - - // Conductor provides at-least once guarantees - // The task can be rescheduled in (rare) case of transient failures on Network - // To handle such cases, the implementation should be idempotent - - // BUSINESS LOGIC GOES HERE - - // Create a TaskResult object to hold the result of the execution and status - TaskResult result = new TaskResult(task); - - // Capture the output of the task execution as output - result.getOutputData().put("key", "value"); - result.getOutputData().put("amount", 123.45); - - // The values can be a map or an array as well - result.getOutputData().put("key2", new HashMap<>()); - - // Set the status COMPLETED. - result.setStatus(TaskResult.Status.COMPLETED); - - return result; - } - } - - /** - * An example worker that is a long-running and periodically gets polled to check the status of - * a long-running task. A use case for such worker is when the actual work is happening via - * separate process that could take longer to execute (anywhere from minutes to days or months), - * e.g. database backup, running a background job that could take hours. In such cases, such - * tasks are polled every so often (e.g. hourly or daily) to check the status and remains in - * progress for much longer without holding up threads. - */ - private static class LongRunningTaskWorker implements Worker { - - private static final String TASK_NAME = "long_running_task"; - - @Override - public String getTaskDefName() { - return TASK_NAME; - } - - @Override - public TaskResult execute(Task task) { - // 1. Create a TaskResult object to hold the result of the execution and status - TaskResult result = new TaskResult(task); - - // Check the status of the long-running process - boolean isCompleted = isJobCompleted(); - if (isCompleted) { - // Let's complete the task - // Set the status COMPLETED. - result.setStatus(TaskResult.Status.COMPLETED); - } else { - // still in progress, let's check back in an hour - result.setCallbackAfterSeconds(60 * 60); - } - return result; - } - - private boolean isJobCompleted() { - return true; - } - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/events/EventHandlerExample.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/events/EventHandlerExample.java deleted file mode 100644 index 24f153add..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/events/EventHandlerExample.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2024 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.sdk.examples.events; - -import java.io.IOException; -import java.util.List; -import java.util.Map; - -import com.netflix.conductor.client.http.MetadataClient; -import com.netflix.conductor.common.metadata.events.EventHandler; -import com.netflix.conductor.common.metadata.tasks.TaskType; -import com.netflix.conductor.common.metadata.workflow.WorkflowDef; -import com.netflix.conductor.common.metadata.workflow.WorkflowTask; - -import io.orkes.conductor.client.http.OrkesEventClient; -import io.orkes.conductor.client.model.OrkesEventHandler; -import io.orkes.conductor.client.model.Tag; -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -import lombok.extern.slf4j.Slf4j; - -@Slf4j -public class EventHandlerExample { - private static final String WORKFLOW_NAME = "test_event_handler"; - private static final String EVENT_HANDLER_NAME = "test_event_handler"; - private static final String EVENT_NAME = "sqs:IKsqs2:test-sqs-queue"; - - public static void main(String[] args) throws IOException { - var client = ClientUtil.getClient(); - var eventClient = new OrkesEventClient(client); - - var metadataClient = new MetadataClient(client); - - try { - metadataClient.getWorkflowDef(WORKFLOW_NAME, 1); - } catch (Exception e) { - metadataClient.registerWorkflowDef(getWorkflowDef()); - } - - var eventHandlers = eventClient.getOrkesEventHandlers(); - if (eventHandlers.stream().noneMatch(handler -> handler.getName().equals(EVENT_HANDLER_NAME))) { - eventClient.registerEventHandler(getEventHandler()); - } - - eventClient.putTagsForEventHandler(EVENT_HANDLER_NAME, List.of(Tag.builder().key("test").value("test").build(), Tag.builder().key("test2").value("test2").build())); - - var oldHandlers = eventClient.getEventHandlers(); - var newHandlers = eventClient.getOrkesEventHandlers(); - log.info("Event handlers: {}", oldHandlers); - log.info("Orkes event handlers: {}", newHandlers); - - var handler = eventClient.getOrkesEventHandlers(EVENT_NAME, false); - log.info("Handlers by name: {}", handler); - } - - private static OrkesEventHandler getEventHandler() { - EventHandler.Action action = new EventHandler.Action(); - action.setAction(EventHandler.Action.Type.start_workflow); - var startWorkflow = new EventHandler.StartWorkflow(); - startWorkflow.setName(WORKFLOW_NAME); - action.setStart_workflow(startWorkflow); - return OrkesEventHandler.orkesBuilder().name(EVENT_HANDLER_NAME) - .event(EVENT_NAME) // AWS SQS integration with name "IKsqs2" must be already configured on the cluster - .active(true) - .actions(List.of(action)) - .tags(List.of(Tag.builder().key("test").value("test").build(), Tag.builder().key("test2").value("test2").build())) - .build(); - } - - private static WorkflowDef getWorkflowDef() { - WorkflowTask task = new WorkflowTask(); - task.setName("test_simple_inline"); - task.setTaskReferenceName("test_simple_inline-ref"); - task.setType(TaskType.INLINE.toString()); - task.setInputParameters(Map.of("expression", "(function () { return 42;})();", - "evaluatorType", "graaljs")); - - WorkflowDef workflowDef = new WorkflowDef(); - workflowDef.setName(WORKFLOW_NAME); - workflowDef.setDescription("test event handler"); - workflowDef.setVersion(1); - workflowDef.setSchemaVersion(2); - workflowDef.setTasks(List.of(task)); - - return workflowDef; - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/events/EventListenerExample.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/events/EventListenerExample.java deleted file mode 100644 index 147ebe52d..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/events/EventListenerExample.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2024 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.sdk.examples.events; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.List; - -import com.netflix.conductor.client.automator.TaskRunnerConfigurer; -import com.netflix.conductor.client.events.taskrunner.PollCompleted; -import com.netflix.conductor.client.events.taskrunner.PollFailure; -import com.netflix.conductor.client.events.taskrunner.TaskExecutionFailure; -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.TaskResult; - -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -import com.sun.net.httpserver.HttpServer; -import io.micrometer.prometheusmetrics.PrometheusConfig; -import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; -import lombok.extern.slf4j.Slf4j; - -/** - * Shows how you can create a worker that polls and executes a SIMPLE task - * and register listeners to expose metrics with micrometer. - */ -@Slf4j -public class EventListenerExample { - - private static final PrometheusMeterRegistry prometheusRegistry = - new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); - - public static void main(String[] args) throws IOException { - var client = ClientUtil.getClient(); - var taskClient = new TaskClient(client); - var runnerConfigurer = new TaskRunnerConfigurer - .Builder(taskClient, List.of(new SimpleWorker())) - .withThreadCount(2) - .withListener(PollCompleted.class, (e) -> { - log.info("Poll Completed {}", e); - var timer = prometheusRegistry.timer("poll_completed", "type", e.getTaskType()); - timer.record(e.getDuration()); - }) - .withListener(PollFailure.class, (e) -> { - log.error("Poll Failure {}", e); - var counter = prometheusRegistry.counter("poll_failure", "type", e.getTaskType()); - counter.increment(); - }) - .withListener(TaskExecutionFailure.class, (e) -> { - log.error("Task execution Failure {}", e); - var counter = prometheusRegistry.counter("execution_failure", "type", e.getTaskType(), "id", e.getTaskId()); - counter.increment(); - }) - .build(); - runnerConfigurer.init(); - - // Expose a /metrics endpoint that will be scrapped by Prometheus - var server = HttpServer.create(new InetSocketAddress(9991), 0); - server.createContext("/metrics", (exchange -> { - var body = prometheusRegistry.scrape(); - exchange.getResponseHeaders().set("Content-Type", "text/plain"); - exchange.sendResponseHeaders(200, body.getBytes().length); - try (var os = exchange.getResponseBody()) { - os.write(body.getBytes()); - } - })); - - server.start(); - } - - private static class SimpleWorker implements Worker { - - private static final String TASK_NAME = "simple_task"; - - @Override - public String getTaskDefName() { - return TASK_NAME; - } - - @Override - public TaskResult execute(Task task) { - // BUSINESS LOGIC GOES HERE - var result = new TaskResult(task); - result.setStatus(TaskResult.Status.COMPLETED); - return result; - } - - @Override - public int getPollingInterval() { - return 500; - } - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/helloworld/Main.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/helloworld/Main.java deleted file mode 100644 index 300fee820..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/helloworld/Main.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2024 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.sdk.examples.helloworld; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import com.netflix.conductor.client.http.ConductorClient; -import com.netflix.conductor.sdk.examples.helloworld.workflowdef.GreetingsWorkflow; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -public class Main { - - public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException { - String serverUrl = System.getenv().getOrDefault("CONDUCTOR_SERVER_URL", "http://localhost:8080/api"); - var workflowExecutor = new WorkflowExecutor(new ConductorClient(serverUrl), 10); - workflowExecutor.initWorkers("com.netflix.conductor.sdk.examples.helloworld.workers"); - var workflowCreator = new GreetingsWorkflow(workflowExecutor); - var simpleWorkflow = workflowCreator.create(); - - var input = new GreetingsWorkflow.Input(); - input.setName("Conductor User 42"); - - var workflowExecution = simpleWorkflow.executeDynamic(input); - try { - var workflowRun = workflowExecution.get(10, TimeUnit.SECONDS); - System.out.println("Workflow execution status: " + workflowRun.getStatus()); - } catch (Exception e) { - System.out.println("Error while executing workflow: " + e.getMessage()); - } - - // Shutdown workers gracefully - workflowExecutor.shutdown(); - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/helloworld/workflowdef/GreetingsWorkflow.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/helloworld/workflowdef/GreetingsWorkflow.java deleted file mode 100644 index 417923f21..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/helloworld/workflowdef/GreetingsWorkflow.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2024 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.sdk.examples.helloworld.workflowdef; - -import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; -import com.netflix.conductor.sdk.workflow.def.tasks.SimpleTask; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -import lombok.Data; - -public class GreetingsWorkflow { - private final WorkflowExecutor executor; - public GreetingsWorkflow(WorkflowExecutor executor) { - this.executor = executor; - } - public ConductorWorkflow create() { - ConductorWorkflow workflow = new ConductorWorkflow<>(executor); - workflow.setName("greetings"); - workflow.setVersion(1); - SimpleTask greetingsTask = new SimpleTask("greet", "greet_ref"); - greetingsTask.input("name", "${workflow.input.name}"); - workflow.add(greetingsTask); - workflow.setOwnerEmail("exampes@conductor-oss.org"); - return workflow; - } - - @Data - public static class Input { - private String name; - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/sendemail/Main.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/sendemail/Main.java deleted file mode 100644 index 4c43bd6bc..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/sendemail/Main.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2024 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.sdk.examples.sendemail; - -import java.util.concurrent.TimeUnit; - -import com.netflix.conductor.sdk.examples.sendemail.workflowdef.SendEmailWorkflow; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -import lombok.SneakyThrows; - -public class Main { - - @SneakyThrows - public static void main(String[] args){ - var workflowExecutor = new WorkflowExecutor(ClientUtil.getClient(), 10); - var workflowCreator = new SendEmailWorkflow(workflowExecutor); - var workflow = workflowCreator.create(); - var input = new SendEmailWorkflow.Input(); - input.setUserId("conductor-user-42"); - // Init workers - workflowExecutor.initWorkers("com.netflix.conductor.sdk.examples.sendemail.workers"); - // Wait for AT MOST 10 seconds for the workflow to reach a terminal state - var workflowExecution = workflow.executeDynamic(input); - try { - var workflowRun = workflowExecution.get(10, TimeUnit.SECONDS); - System.out.println("Workflow execution status: " + workflowRun.getStatus()); - } catch (Exception e) { - System.out.println("Error while executing workflow: " + e.getMessage()); - } - - // Shutdown workers gracefully - workflowExecutor.shutdown(); - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/sendemail/workers/Workers.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/sendemail/workers/Workers.java deleted file mode 100644 index 927e56fa9..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/sendemail/workers/Workers.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2024 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.sdk.examples.sendemail.workers; - -import com.netflix.conductor.sdk.workflow.task.InputParam; -import com.netflix.conductor.sdk.workflow.task.WorkerTask; - -import lombok.Data; - -public class Workers { - - @WorkerTask("send_email") - public void sendEmail(@InputParam("email") String email) { - System.out.println("Sending email to " + email); - } - - @WorkerTask("get_user_info") - public UserInfo getUserInfo(@InputParam("userId") String userId) { - UserInfo userInfo = new UserInfo(); - userInfo.setId(userId); - userInfo.setName("User X"); - userInfo.setEmail(userId + "@example.com"); - userInfo.setPhoneNumber("555-555-5555"); - return userInfo; - } - - @Data - public static class UserInfo { - private String name; - private String id; - private String email; - private String phoneNumber; - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/sendemail/workflowdef/SendEmailWorkflow.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/sendemail/workflowdef/SendEmailWorkflow.java deleted file mode 100644 index 2ce711e0f..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/sendemail/workflowdef/SendEmailWorkflow.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2024 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.sdk.examples.sendemail.workflowdef; - -import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; -import com.netflix.conductor.sdk.workflow.def.tasks.SimpleTask; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -import lombok.Data; - -public class SendEmailWorkflow { - private final WorkflowExecutor executor; - - public SendEmailWorkflow(WorkflowExecutor executor) { - this.executor = executor; - } - - public ConductorWorkflow create() { - ConductorWorkflow workflow = new ConductorWorkflow<>(executor); - workflow.setName("send_email_workflow"); - workflow.setVersion(1); - - SimpleTask getUserDetails = new SimpleTask("get_user_info", "get_user_info"); - getUserDetails.input("userId", "${workflow.input.userId}"); - - // send email - SimpleTask sendEmail = new SimpleTask("send_email", "send_email"); - // get user details user info, which contains the email field - sendEmail.input("email", "${get_user_info.output.email}"); - - workflow.add(getUserDetails); - workflow.add(sendEmail); - - workflow.setOwnerEmail("exampes@conductor-oss.org"); - return workflow; - } - - @Data - public static class Input { - private String userId; - } -} \ No newline at end of file diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/Main.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/Main.java deleted file mode 100644 index b7436071c..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/Main.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2024 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.sdk.examples.shipment; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; - -import com.netflix.conductor.client.http.ConductorClient; -import com.netflix.conductor.common.run.Workflow; -import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -public class Main { - public static void main(String[] args) { - ConductorClient client = ClientUtil.getClient(); - WorkflowExecutor executor = new WorkflowExecutor(client, 100); - - // Create the new shipment workflow - ShipmentWorkflow shipmentWorkflow = new ShipmentWorkflow(executor); - - // Create two workflows - - // 1. Order flow that ships an individual order - // 2. Shipment Workflow that tracks multiple orders in a shipment - shipmentWorkflow.createOrderFlow(); - ConductorWorkflow workflow = shipmentWorkflow.createShipmentWorkflow(); - - // Execute the workflow and wait for it to complete - try { - Shipment workflowInput = new Shipment("userA", "order123"); - - // Execute returns a completable future. - CompletableFuture executionFuture = workflow.execute(workflowInput); - - // Wait for a maximum of a minute for the workflow to complete. - Workflow run = executionFuture.get(1, TimeUnit.MINUTES); - - System.out.println("Workflow Id: " + run); - System.out.println("Workflow Status: " + run.getStatus()); - System.out.println("Workflow Output: " + run.getOutput()); - - } catch (Exception e) { - e.printStackTrace(); - } finally { - executor.shutdown(); - } - - System.out.println("Done"); - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/Order.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/Order.java deleted file mode 100644 index be7cd01a1..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/Order.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2022 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.sdk.examples.shipment; - -import java.math.BigDecimal; - -public class Order { - - public enum ShippingMethod { - GROUND, - NEXT_DAY_AIR, - SAME_DAY - } - - private String orderNumber; - - private String sku; - - private int quantity; - - private BigDecimal unitPrice; - - private String zipCode; - - private String countryCode; - - private ShippingMethod shippingMethod; - - public Order(String orderNumber, String sku, int quantity, BigDecimal unitPrice) { - this.orderNumber = orderNumber; - this.sku = sku; - this.quantity = quantity; - this.unitPrice = unitPrice; - } - - public Order() {} - - public String getOrderNumber() { - return orderNumber; - } - - public void setOrderNumber(String orderNumber) { - this.orderNumber = orderNumber; - } - - public String getSku() { - return sku; - } - - public void setSku(String sku) { - this.sku = sku; - } - - public int getQuantity() { - return quantity; - } - - public void setQuantity(int quantity) { - this.quantity = quantity; - } - - public BigDecimal getUnitPrice() { - return unitPrice; - } - - public void setUnitPrice(BigDecimal unitPrice) { - this.unitPrice = unitPrice; - } - - public String getZipCode() { - return zipCode; - } - - public void setZipCode(String zipCode) { - this.zipCode = zipCode; - } - - public String getCountryCode() { - return countryCode; - } - - public void setCountryCode(String countryCode) { - this.countryCode = countryCode; - } - - public ShippingMethod getShippingMethod() { - return shippingMethod; - } - - public void setShippingMethod(ShippingMethod shippingMethod) { - this.shippingMethod = shippingMethod; - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/Shipment.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/Shipment.java deleted file mode 100644 index e69ba863a..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/Shipment.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2022 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.sdk.examples.shipment; - -public class Shipment { - - private String userId; - - private String orderNo; - - public Shipment(String userId, String orderNo) { - this.userId = userId; - this.orderNo = orderNo; - } - - public Shipment() {} - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getOrderNo() { - return orderNo; - } - - public void setOrderNo(String orderNo) { - this.orderNo = orderNo; - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/ShipmentState.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/ShipmentState.java deleted file mode 100644 index 4c73cfd5f..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/ShipmentState.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2022 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.sdk.examples.shipment; - -public class ShipmentState { - - private boolean paymentCompleted; - - private boolean emailSent; - - private boolean shipped; - - private String trackingNumber; - - public boolean isPaymentCompleted() { - return paymentCompleted; - } - - public void setPaymentCompleted(boolean paymentCompleted) { - this.paymentCompleted = paymentCompleted; - } - - public boolean isEmailSent() { - return emailSent; - } - - public void setEmailSent(boolean emailSent) { - this.emailSent = emailSent; - } - - public boolean isShipped() { - return shipped; - } - - public void setShipped(boolean shipped) { - this.shipped = shipped; - } - - public String getTrackingNumber() { - return trackingNumber; - } - - public void setTrackingNumber(String trackingNumber) { - this.trackingNumber = trackingNumber; - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/ShipmentWorkers.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/ShipmentWorkers.java deleted file mode 100644 index eca566e86..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/ShipmentWorkers.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright 2022 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.sdk.examples.shipment; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.UUID; - -import com.netflix.conductor.sdk.workflow.def.tasks.DynamicForkInput; -import com.netflix.conductor.sdk.workflow.def.tasks.SubWorkflow; -import com.netflix.conductor.sdk.workflow.def.tasks.Task; -import com.netflix.conductor.sdk.workflow.task.InputParam; -import com.netflix.conductor.sdk.workflow.task.OutputParam; -import com.netflix.conductor.sdk.workflow.task.WorkerTask; - -public class ShipmentWorkers { - - @WorkerTask(value = "generateDynamicFork", threadCount = 3) - public DynamicForkInput generateDynamicFork( - @InputParam("orderDetails") List orderDetails, - @InputParam("userDetails") User userDetails) { - DynamicForkInput input = new DynamicForkInput(); - List> tasks = new ArrayList<>(); - Map inputs = new HashMap<>(); - - for (int i = 0; i < orderDetails.size(); i++) { - Order detail = orderDetails.get(i); - String referenceName = "order_flow_sub_" + i; - tasks.add( - new SubWorkflow(referenceName, "order_flow", null) - .input("orderDetail", detail) - .input("userDetails", userDetails)); - inputs.put(referenceName, new HashMap<>()); - } - input.setInputs(inputs); - input.setTasks(tasks); - return input; - } - - @WorkerTask(value = "get_order_details", threadCount = 5) - public List getOrderDetails(@InputParam("orderNo") String orderNo) { - int lineItemCount = new Random().nextInt(10); - List orderDetails = new ArrayList<>(); - for (int i = 0; i < lineItemCount; i++) { - Order orderDetail = new Order(orderNo, "sku_" + i, 2, BigDecimal.valueOf(20.5)); - orderDetail.setOrderNumber(UUID.randomUUID().toString()); - orderDetail.setCountryCode(i % 2 == 0 ? "US" : "CA"); - if (i % 3 == 0) { - orderDetail.setCountryCode("UK"); - } - - if (orderDetail.getCountryCode().equals("US")) - orderDetail.setShippingMethod(Order.ShippingMethod.SAME_DAY); - else if (orderDetail.getCountryCode().equals("CA")) - orderDetail.setShippingMethod(Order.ShippingMethod.NEXT_DAY_AIR); - else orderDetail.setShippingMethod(Order.ShippingMethod.GROUND); - - orderDetails.add(orderDetail); - } - return orderDetails; - } - - @WorkerTask("get_user_details") - public User getUserDetails(@InputParam("userId") String userId) { - User user = - new User( - "User Name", - userId + "@example.com", - "1234 forline street", - "mountain view", - "95030", - "US", - "Paypal", - "biling_001"); - - return user; - } - - @WorkerTask("calculate_tax_and_total") - public @OutputParam("total_amount") BigDecimal calculateTax( - @InputParam("orderDetail") Order orderDetails) { - BigDecimal preTaxAmount = - orderDetails.getUnitPrice().multiply(new BigDecimal(orderDetails.getQuantity())); - BigDecimal tax = BigDecimal.valueOf(0.2).multiply(preTaxAmount); - if (!"US".equals(orderDetails.getCountryCode())) { - tax = BigDecimal.ZERO; - } - return preTaxAmount.add(tax); - } - - @WorkerTask("ground_shipping_label") - public @OutputParam("reference_number") String prepareGroundShipping( - @InputParam("name") String name, - @InputParam("address") String address, - @InputParam("orderNo") String orderNo) { - - return "Ground_" + orderNo; - } - - @WorkerTask("air_shipping_label") - public @OutputParam("reference_number") String prepareAirShipping( - @InputParam("name") String name, - @InputParam("address") String address, - @InputParam("orderNo") String orderNo) { - - return "Air_" + orderNo; - } - - @WorkerTask("same_day_shipping_label") - public @OutputParam("reference_number") String prepareSameDayShipping( - @InputParam("name") String name, - @InputParam("address") String address, - @InputParam("orderNo") String orderNo) { - - return "SameDay_" + orderNo; - } - - @WorkerTask("charge_payment") - public @OutputParam("reference") String chargePayment( - @InputParam("amount") BigDecimal amount, - @InputParam("billingId") String billingId, - @InputParam("billingType") String billingType) { - - return UUID.randomUUID().toString(); - } - - @WorkerTask("send_email") - public void sendEmail( - @InputParam("name") String name, - @InputParam("email") String email, - @InputParam("orderNo") String orderNo) {} -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/ShipmentWorkflow.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/ShipmentWorkflow.java deleted file mode 100644 index 1a48c9291..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/ShipmentWorkflow.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright 2022 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.sdk.examples.shipment; - - -import com.netflix.conductor.common.metadata.workflow.WorkflowDef; -import com.netflix.conductor.common.run.Workflow; -import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; -import com.netflix.conductor.sdk.workflow.def.WorkflowBuilder; -import com.netflix.conductor.sdk.workflow.def.tasks.DynamicFork; -import com.netflix.conductor.sdk.workflow.def.tasks.ForkJoin; -import com.netflix.conductor.sdk.workflow.def.tasks.SetVariable; -import com.netflix.conductor.sdk.workflow.def.tasks.SimpleTask; -import com.netflix.conductor.sdk.workflow.def.tasks.Switch; -import com.netflix.conductor.sdk.workflow.def.tasks.Task; -import com.netflix.conductor.sdk.workflow.def.tasks.Terminate; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - - -public class ShipmentWorkflow { - - private final WorkflowExecutor executor; - - public ShipmentWorkflow(WorkflowExecutor executor) { - this.executor = executor; - this.executor.initWorkers(ShipmentWorkflow.class.getPackageName()); - } - - public ConductorWorkflow createOrderFlow() { - WorkflowBuilder builder = new WorkflowBuilder<>(executor); - builder.name("order_flow") - .version(1) - .ownerEmail("user@example.com") - .timeoutPolicy(WorkflowDef.TimeoutPolicy.TIME_OUT_WF, 60) // 1 day max - .description("Workflow to track shipment") - .add( - new SimpleTask("calculate_tax_and_total", "calculate_tax_and_total") - .input("orderDetail", ConductorWorkflow.input.get("orderDetail"))) - .add( - new SimpleTask("charge_payment", "charge_payment") - .input( - "billingId", - ConductorWorkflow.input - .map("userDetails") - .get("billingId"), - "billingType", - ConductorWorkflow.input - .map("userDetails") - .get("billingType"), - "amount", "${calculate_tax_and_total.output.total_amount}")) - .add( - new Switch("shipping_label", "${workflow.input.orderDetail.shippingMethod}") - .switchCase( - Order.ShippingMethod.GROUND.toString(), - new SimpleTask( - "ground_shipping_label", - "ground_shipping_label") - .input( - "name", - ConductorWorkflow.input - .map("userDetails") - .get("name"), - "address", - ConductorWorkflow.input - .map("userDetails") - .get("addressLine"), - "orderNo", - ConductorWorkflow.input - .map("orderDetail") - .get("orderNumber"))) - .switchCase( - Order.ShippingMethod.NEXT_DAY_AIR.toString(), - new SimpleTask("air_shipping_label", "air_shipping_label") - .input( - "name", - ConductorWorkflow.input - .map("userDetails") - .get("name"), - "address", - ConductorWorkflow.input - .map("userDetails") - .get("addressLine"), - "orderNo", - ConductorWorkflow.input - .map("orderDetail") - .get("orderNumber"))) - .switchCase( - Order.ShippingMethod.SAME_DAY.toString(), - new SimpleTask( - "same_day_shipping_label", - "same_day_shipping_label") - .input( - "name", - ConductorWorkflow.input - .map("userDetails") - .get("name"), - "address", - ConductorWorkflow.input - .map("userDetails") - .get("addressLine"), - "orderNo", - ConductorWorkflow.input - .map("orderDetail") - .get("orderNumber"))) - .defaultCase( - new Terminate( - "unsupported_shipping_type", - Workflow.WorkflowStatus.FAILED, - "Unsupported Shipping Method"))) - .add( - new SimpleTask("send_email", "send_email") - .input( - "name", - ConductorWorkflow.input - .map("userDetails") - .get("name"), - "email", - ConductorWorkflow.input - .map("userDetails") - .get("email"), - "orderNo", - ConductorWorkflow.input - .map("orderDetail") - .get("orderNumber"))); - ConductorWorkflow conductorWorkflow = builder.build(); - conductorWorkflow.registerWorkflow(true, true); - return conductorWorkflow; - } - - public ConductorWorkflow createShipmentWorkflow() { - - WorkflowBuilder builder = new WorkflowBuilder<>(executor); - - SimpleTask getOrderDetails = - new SimpleTask("get_order_details", "get_order_details") - .input("orderNo", ConductorWorkflow.input.get("orderNo")); - - SimpleTask getUserDetails = - new SimpleTask("get_user_details", "get_user_details") - .input("userId", ConductorWorkflow.input.get("userId")); - - ConductorWorkflow conductorWorkflow = - builder.name("shipment_workflow") - .version(1) - .ownerEmail("user@example.com") - .variables(new ShipmentState()) - .timeoutPolicy(WorkflowDef.TimeoutPolicy.TIME_OUT_WF, 60) // 30 days - .description("Workflow to track shipment") - .add( - new ForkJoin( - "get_in_parallel", - new Task[] {getOrderDetails}, - new Task[] {getUserDetails})) - - // For all the line items in the order, run in parallel: - // (calculate tax, charge payment, set state, prepare shipment, send - // shipment, set state) - .add( - new DynamicFork( - "process_order", - new SimpleTask("generateDynamicFork", "generateDynamicFork") - .input( - "orderDetails", - getOrderDetails.taskOutput.get("result")) - .input("userDetails", getUserDetails.taskOutput))) - - // Update the workflow state with shipped = true - .add(new SetVariable("update_state").input("shipped", true)) - .build(); - - conductorWorkflow.registerWorkflow(true, true); - - return conductorWorkflow; - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/User.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/User.java deleted file mode 100644 index 2d75d9437..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/shipment/User.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2022 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.sdk.examples.shipment; - -public class User { - - private String name; - - private String email; - - private String addressLine; - - private String city; - - private String zipCode; - - private String countryCode; - - private String billingType; - - private String billingId; - - public User( - String name, - String email, - String addressLine, - String city, - String zipCode, - String countryCode, - String billingType, - String billingId) { - this.name = name; - this.email = email; - this.addressLine = addressLine; - this.city = city; - this.zipCode = zipCode; - this.countryCode = countryCode; - this.billingType = billingType; - this.billingId = billingId; - } - - public User() {} - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getAddressLine() { - return addressLine; - } - - public void setAddressLine(String addressLine) { - this.addressLine = addressLine; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public String getZipCode() { - return zipCode; - } - - public void setZipCode(String zipCode) { - this.zipCode = zipCode; - } - - public String getCountryCode() { - return countryCode; - } - - public void setCountryCode(String countryCode) { - this.countryCode = countryCode; - } - - public String getBillingType() { - return billingType; - } - - public void setBillingType(String billingType) { - this.billingType = billingType; - } - - public String getBillingId() { - return billingId; - } - - public void setBillingId(String billingId) { - this.billingId = billingId; - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/taskdomains/Main.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/taskdomains/Main.java deleted file mode 100644 index cff2d53dd..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/taskdomains/Main.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2024 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.sdk.examples.taskdomains; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.netflix.conductor.client.automator.TaskRunnerConfigurer; -import com.netflix.conductor.client.http.ConductorClient; -import com.netflix.conductor.client.http.TaskClient; -import com.netflix.conductor.client.worker.Worker; -import com.netflix.conductor.sdk.workflow.executor.task.AnnotatedWorkerExecutor; -import com.netflix.conductor.sdk.workflow.executor.task.WorkerConfiguration; - -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -public class Main { - - public static void main(String[] args) throws IOException { - setSystemProperties(); - - ConductorClient client = ClientUtil.getClient(); - TaskClient taskClient = new TaskClient(client); - AnnotatedWorkerExecutor workerExecutor = new AnnotatedWorkerExecutor( - taskClient, new WorkerConfiguration() - ); - workerExecutor.initWorkers("com.netflix.conductor.sdk.examples.taskdomains"); - workerExecutor.startPolling(); - workerExecutor.shutdown(); - - startTaskRunnerWorkers(taskClient); - } - - private static void startTaskRunnerWorkers(TaskClient taskClient) { - List workers = List.of(new Workers.TaskWorker()); - TaskRunnerConfigurer.Builder builder = new TaskRunnerConfigurer.Builder(taskClient, workers); - - // test-domain-common should be picked up as Task Domain if conductor.worker.all.domain is populated - // For test-domain-runner to be picked up, conductor.worker.all.domain shouldn't be populated - Map taskToDomains = new HashMap<>(); - taskToDomains.put("task-domain-runner-simple-task", "test-domain-runner"); - Map taskThreadCount = new HashMap<>(); - - TaskRunnerConfigurer taskRunner = - builder.withThreadCount(2) - .withTaskToDomain(taskToDomains) - .withTaskThreadCount(taskThreadCount) - .withSleepWhenRetry(500) - .withWorkerNamePrefix("task-domain") - .withUpdateRetryCount(3) - .build(); - - // Start Polling for tasks and execute them - taskRunner.init(); - - // Optionally, use the shutdown method to stop polling - // taskRunner.shutdown(); - } - - - public static void setSystemProperties() { - // This is in lieu of setting properties in application.properties - System.setProperty("conductor.worker.task-domain-property-simple-task.domain", "test-domain-prop"); - // If below line is un-commented, test-domain-common trumps test-domain-runner and test-domain-annotated - // System.setProperty("conductor.worker.all.domain", "test-domain-common"); - } -} diff --git a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/taskdomains/Workers.java b/examples/old/src/main/java/com/netflix/conductor/sdk/examples/taskdomains/Workers.java deleted file mode 100644 index 876c74816..000000000 --- a/examples/old/src/main/java/com/netflix/conductor/sdk/examples/taskdomains/Workers.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2023 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.sdk.examples.taskdomains; - -import com.netflix.conductor.client.worker.Worker; -import com.netflix.conductor.common.metadata.tasks.Task; -import com.netflix.conductor.common.metadata.tasks.TaskResult; -import com.netflix.conductor.sdk.workflow.task.WorkerTask; - - -/** - * This program demonstrates different mechanisms for setting task domains during worker initialization - *

- * 1. Using task specific property in application.properties - * 2. Using task agnostic property in application.properties - * 3. Passing taskToDomains as constructor parameter when using TaskRunner - * 4. Passing domain argument when using worker annotator - *

- * Sample workflow can be created using the definition task_domain_wf.json in the resources folder - *

- * Example Task to Domain Mapping for workflow creation when property, conductor.worker.all.domain, is set - * { - * "task-domain-property-simple-task": "test-domain-prop", - * "task-domain-all-simple-task": "test-domain-common", - * "task-domain-runner-simple-task": "test-domain-common", - * "task-domain-annotated-simple-task": "test-domain-common" - * } - *

- * Example Task to Domain Mapping for workflow creation when property, conductor.worker.all.domain, is not set - * { - * "task-domain-property-simple-task": "test-domain-prop", - * "task-domain-runner-simple-task": "test-domain-runner", - * "task-domain-annotated-simple-task": "test-domain-annotated", - * } - */ -public class Workers { - - @WorkerTask(value = "task-domain-property-simple-task", pollingInterval = 200) - public TaskResult sendPropertyTaskDomain(Task task) { - // test-domain-prop should be picked up as Task Domain - TaskResult result = new TaskResult(task); - - result.getOutputData().put("key", "value2"); - result.getOutputData().put("amount", 167.12); - result.setStatus(TaskResult.Status.COMPLETED); - - return result; - } - - @WorkerTask(value = "task-domain-all-simple-task", pollingInterval = 200) - public TaskResult sendAllTaskDomain(Task task) { - // test-domain-common should be picked up as Task Domain - TaskResult result = new TaskResult(task); - result.getOutputData().put("key", "value3"); - result.getOutputData().put("amount", 400); - result.setStatus(TaskResult.Status.COMPLETED); - - return result; - } - - @WorkerTask(value = "task-domain-annotated-simple-task", domain = "test-domain-annotated", pollingInterval = 200) - public TaskResult sendAnnotatedTaskDomain(Task task) { - // test-domain-common should be picked up as Task Domain if conductor.worker.all.domain is populated - // For test-domain-annotated to be picked up, conductor.worker.all.domain shouldn't be populated - TaskResult result = new TaskResult(task); - - result.getOutputData().put("key", "value"); - result.getOutputData().put("amount", 123.45); - result.setStatus(TaskResult.Status.COMPLETED); - - return result; - } - - static class TaskWorker implements Worker { - - @Override - public String getTaskDefName() { - return "task-domain-runner-simple-task"; - } - - public TaskResult execute(Task task) { - TaskResult result = new TaskResult(task); - - result.getOutputData().put("key2", "value2"); - result.getOutputData().put("amount", 145); - result.setStatus(TaskResult.Status.COMPLETED); - - return result; - } - } -} diff --git a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/AuthorizationManagement.java b/examples/old/src/main/java/io/orkes/conductor/sdk/examples/AuthorizationManagement.java deleted file mode 100644 index 8a94d496b..000000000 --- a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/AuthorizationManagement.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2022 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 io.orkes.conductor.sdk.examples; - -import java.util.List; -import java.util.UUID; - -import io.orkes.conductor.client.AuthorizationClient; -import io.orkes.conductor.client.OrkesClients; -import io.orkes.conductor.client.model.AuthorizationRequest; -import io.orkes.conductor.client.model.SubjectRef; -import io.orkes.conductor.client.model.TargetRef; -import io.orkes.conductor.client.model.UpsertGroupRequest; -import io.orkes.conductor.client.model.UpsertUserRequest; -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -/** - * Examples for managing user authorization in Orkes Conductor - * - * 1. upsertUser - Add user - * 2. upsertUser - Add group - * 3. addUserToGroup - Add user to group - * 4. removeUserFromGroup - Remove user from group - * 5. grantPermissions - Grant permission to user via tag or group. - */ -public class AuthorizationManagement { - - private static AuthorizationClient authorizationClient; - - public static void main(String[] a) { - OrkesClients orkesClients = ClientUtil.getOrkesClients(); - createMetadata(); - authorizationClient = orkesClients.getAuthorizationClient(); - AuthorizationManagement authorizationManagement = new AuthorizationManagement(); - authorizationManagement.userAndGroupOperations(); - } - - private void userAndGroupOperations() { - // Create users - String userId = createUser("user1"); - String userId2 = createUser("user2"); - String userId3 = createUser("user3"); - // Create groups - String group1 = "group1"; - String group2 = "group2"; - createGroup(group1, "group to perform"); - createGroup(group2, "group to perform action"); - // Add users to group 1 - authorizationClient.addUserToGroup(group1, userId); - authorizationClient.addUserToGroup(group1, userId2); - authorizationClient.addUserToGroup(group2, userId2); - authorizationClient.addUserToGroup(group2, userId3); - - // Remove user from group - authorizationClient.removeUserFromGroup(group1, userId2); - - // Add workflow execution permissions to the group - AuthorizationRequest authorizationRequest = new AuthorizationRequest(); - authorizationRequest.setAccess(List.of(AuthorizationRequest.AccessEnum.EXECUTE)); - SubjectRef subjectRef = new SubjectRef(); - subjectRef.setId(userId); - subjectRef.setType(SubjectRef.TypeEnum.USER); - // Grant workflow execution permission to user - authorizationRequest.setSubject(subjectRef); - TargetRef targetRef = new TargetRef(); - targetRef.setId("org:engineering"); - targetRef.setType(TargetRef.TypeEnum.WORKFLOW_DEF); - authorizationRequest.setTarget(targetRef); - authorizationClient.grantPermissions(authorizationRequest); - - // Grant workflow execution permission to tag - targetRef = new TargetRef(); - targetRef.setId("customer:abc"); - targetRef.setType(TargetRef.TypeEnum.TASK_DEF); - authorizationRequest.setTarget(targetRef); - authorizationClient.grantPermissions(authorizationRequest); - - // Add read only permission to tag in group - authorizationRequest = new AuthorizationRequest(); - authorizationRequest.setAccess(List.of(AuthorizationRequest.AccessEnum.READ)); - subjectRef = new SubjectRef(); - subjectRef.setId(group1); - subjectRef.setType(SubjectRef.TypeEnum.GROUP); - authorizationRequest.setSubject(subjectRef); - targetRef = new TargetRef(); - targetRef.setId("org:engineering"); - targetRef.setType(TargetRef.TypeEnum.WORKFLOW_DEF); - authorizationRequest.setTarget(targetRef); - authorizationClient.grantPermissions(authorizationRequest); - } - - private String createUser(String name) { - String userId = UUID.randomUUID().toString(); - UpsertUserRequest upsertUserRequest = new UpsertUserRequest(); - upsertUserRequest.setName(name); - upsertUserRequest.setRoles(List.of(UpsertUserRequest.RolesEnum.USER)); - authorizationClient.upsertUser(upsertUserRequest, userId); - return userId; - } - - private void createGroup(String name, String description) { - UpsertGroupRequest upsertGroupRequest = new UpsertGroupRequest(); - upsertGroupRequest.setDescription(description); - upsertGroupRequest.setRoles(List.of(UpsertGroupRequest.RolesEnum.USER)); - authorizationClient.upsertGroup(upsertGroupRequest, name); - } - - private static void createMetadata() { - MetadataManagement metadataManagement = new MetadataManagement(); - metadataManagement.createTaskDefinitions(); - metadataManagement.createWorkflowDefinitions(); - } -} diff --git a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/MetadataManagement.java b/examples/old/src/main/java/io/orkes/conductor/sdk/examples/MetadataManagement.java deleted file mode 100644 index d4ef13f6b..000000000 --- a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/MetadataManagement.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright 2022 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 io.orkes.conductor.sdk.examples; - -import java.util.Arrays; -import java.util.Map; - -import com.netflix.conductor.common.metadata.tasks.TaskDef; -import com.netflix.conductor.common.metadata.tasks.TaskType; -import com.netflix.conductor.common.metadata.workflow.WorkflowDef; -import com.netflix.conductor.common.metadata.workflow.WorkflowTask; - -import io.orkes.conductor.client.OrkesClients; -import io.orkes.conductor.client.http.OrkesMetadataClient; -import io.orkes.conductor.client.model.TagObject; -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -/** - * Examples for managing Metadata (Tasks, Workflows) in Conductor - * - * 1. registerWorkflowDef - Register workflow definition - * 2. registerTaskDefs - Register task definition - * 3. addTaskTag - Add tag to taks - * 4. addWorkflowTag - Add tag to workflow - */ -public class MetadataManagement { - - public static String taskName = "test11_task"; - public static String taskName2 = "test11_task1"; - public static String taskName3 = "test11_task2"; - private static TaskDef taskDef; - private static TaskDef taskDef2; - private static TaskDef taskDef3; - public static WorkflowDef workflowDef; - - private static OrkesMetadataClient metadataClient; - - public static void main(String[] args) { - MetadataManagement metadataManagement = new MetadataManagement(); - metadataManagement.createTaskDefinitions(); - metadataManagement.tagTasks(); - metadataManagement.createWorkflowDefinitions(); - metadataManagement.tagWorkflow(); - } - - public void createTaskDefinitions() { - OrkesClients orkesClients = ClientUtil.getOrkesClients(); - metadataClient = orkesClients.getMetadataClient(); - - // Create task definitions - taskDef = new TaskDef(taskName, "task to update database", "test@orkes.io", 3, 4, 3); - - taskDef2 = new TaskDef(); - taskDef2.setName(taskName2); - taskDef2.setDescription("task to notify users"); - taskDef2.setOwnerEmail("test@orkes.io"); - taskDef2.setResponseTimeoutSeconds(10); - taskDef2.setRetryCount(3); - // At any given time, max 10 executions of this task will be allowed. Tasks to be scheduled - // after reaching max - // limit will be put into queue. - // For more information - // https://orkes.io/content/docs/how-tos/Tasks/creating-tasks#task-rate-limits - taskDef2.setConcurrentExecLimit(10); - taskDef2.setInputKeys( - Arrays.asList( - "${workflow.input.value}", - "${some_other_task.output.response.data.value}")); - - taskDef3 = new TaskDef(); - taskDef3.setName(taskName3); - taskDef3.setDescription("task to compress image"); - taskDef3.setOwnerEmail("test@orkes.io"); - // In 60 seconds at max 5 execution of this task wil be allowed. - // For more information - // https://orkes.io/content/docs/how-tos/Tasks/creating-tasks#task-rate-limits - taskDef3.setRateLimitPerFrequency(5); - taskDef3.setRateLimitFrequencyInSeconds(60); - - // Register task definitions - metadataClient.registerTaskDefs(Arrays.asList(taskDef, taskDef2, taskDef3)); - } - - public void tagTasks() { - // Tagging a task - TagObject tagObject = new TagObject(); - tagObject.setType(TagObject.TypeEnum.METADATA); - tagObject.setKey("department"); - tagObject.setValue("accounts"); - metadataClient.addTaskTag(tagObject, taskName); - - // Tagging another task - TagObject tagObject2 = new TagObject(); - tagObject2.setType(TagObject.TypeEnum.METADATA); - tagObject2.setKey("department"); - tagObject2.setValue("engineering"); - metadataClient.addTaskTag(tagObject2, taskName2); - - // Tagging another task - TagObject tagObject3 = new TagObject(); - tagObject3.setType(TagObject.TypeEnum.METADATA); - tagObject3.setKey("env"); - tagObject3.setValue("dev"); - metadataClient.addTaskTag(tagObject3, taskName3); - } - - public void createWorkflowDefinitions() { - // Create workflowTask - WorkflowTask workflowTask = new WorkflowTask(); - workflowTask.setTaskReferenceName(taskName); - workflowTask.setName(taskName); - workflowTask.setTaskReferenceName(taskName); - workflowTask.setWorkflowTaskType(TaskType.SIMPLE); - workflowTask.setInputParameters(Map.of("value", "${workflow.input.value}", "order", "123")); - workflowTask.setTaskDefinition(taskDef); - - // Create INLINE workflowTask - WorkflowTask workflowTask2 = new WorkflowTask(); - workflowTask2.setName(taskName3); - workflowTask2.setTaskReferenceName(taskName2); - workflowTask2.setTaskReferenceName(taskName2); - workflowTask2.setWorkflowTaskType(TaskType.INLINE); - workflowTask2.setInputParameters( - Map.of( - "inlineValue", - "${workflow.input.inlineValue}", - "evaluatorType", - "javascript", - "expression", - "function scriptFun(){if ($.inlineValue == 1){ " - + "return {testvalue: true} } else { return {testvalue: false} }} scriptFun();")); - workflowTask2.setTaskDefinition(taskDef2); - - workflowDef = new WorkflowDef(); - workflowDef.setName("test11_workflow"); - workflowDef.setOwnerEmail("test@orkes.io"); - workflowDef.setTimeoutSeconds(600); - workflowDef.setTimeoutPolicy(WorkflowDef.TimeoutPolicy.TIME_OUT_WF); - workflowDef.setInputParameters(Arrays.asList("value", "inlineValue")); - workflowDef.setDescription("Workflow to monitor order state"); - workflowDef.setTasks(Arrays.asList(workflowTask, workflowTask2)); - metadataClient.registerWorkflowDef(workflowDef); - } - - public void tagWorkflow() { - TagObject tagObject = new TagObject(); - // Workflow level rate limit. At max 5 instance of workflow will be getting executed that - // are triggered with - // same correlationId. - // For more information - // https://orkes.io/content/docs/how-tos/retries-failures-rate_limits#rate-limiting-your-workflow - tagObject.setType(TagObject.TypeEnum.RATE_LIMIT); - tagObject.setKey("${workflow.correlationId}"); - tagObject.setValue(5); - - TagObject tagObject1 = new TagObject(); - tagObject1.setType(TagObject.TypeEnum.METADATA); - tagObject1.setKey("customer"); - tagObject1.setValue("xyz"); - - TagObject tagObject2 = new TagObject(); - tagObject2.setType(TagObject.TypeEnum.METADATA); - tagObject2.setKey("customer"); - tagObject2.setValue("abc"); - - metadataClient.addWorkflowTag(tagObject, workflowDef.getName()); - metadataClient.addWorkflowTag(tagObject1, workflowDef.getName()); - metadataClient.addWorkflowTag(tagObject2, workflowDef.getName()); - } -} diff --git a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/SchedulerManagement.java b/examples/old/src/main/java/io/orkes/conductor/sdk/examples/SchedulerManagement.java deleted file mode 100644 index 1d61c53c4..000000000 --- a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/SchedulerManagement.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2022 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 io.orkes.conductor.sdk.examples; - -import java.util.List; - -import com.netflix.conductor.common.metadata.workflow.StartWorkflowRequest; - -import io.orkes.conductor.client.OrkesClients; -import io.orkes.conductor.client.SchedulerClient; -import io.orkes.conductor.client.model.SaveScheduleRequest; -import io.orkes.conductor.client.model.WorkflowSchedule; -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -/** - * Examples for managing Schedules in Orkes Conductor - * - * 1. saveSchedule - Create workflow schedule - * 2. pauseSchedule - Pause workflow schedule - * 3. getSchedule - Get schedule for workflow - * 4. getNextFewSchedules - Get next few schedule runs for schedule - * 5. pauseAllSchedules - Pause all the schedules - * 6. resumeAllSchedules - Resume all the schedules - * 7. searchV2 - Get Schedule executions - */ -public class SchedulerManagement { - - private static SchedulerClient schedulerClient; - - private static final String scheduleName = "sample_schedule"; - public static final long NANO = 1_000_000_000; // nano-seconds. - String cron = "0 0 * ? * *"; // Every hour - - public static void main(String[] args) { - OrkesClients orkesClients = ClientUtil.getOrkesClients(); - createMetadata(); - SchedulerManagement schedulerManagement = new SchedulerManagement(); - schedulerClient = orkesClients.getSchedulerClient(); - schedulerManagement.createSchedule(); - schedulerManagement.scheduleOperations(); - } - - private static void createMetadata() { - MetadataManagement metadataManagement = new MetadataManagement(); - metadataManagement.createTaskDefinitions(); - metadataManagement.createWorkflowDefinitions(); - } - - private void createSchedule() { - // Create save schedule request - SaveScheduleRequest saveScheduleRequest = new SaveScheduleRequest(); - saveScheduleRequest.createdBy("test@orkes.io"); - saveScheduleRequest.cronExpression(cron); - saveScheduleRequest.setName(scheduleName); - // Create start workflow request - StartWorkflowRequest startWorkflowRequest = new StartWorkflowRequest(); - startWorkflowRequest.setName(MetadataManagement.workflowDef.getName()); - startWorkflowRequest.setVersion(MetadataManagement.workflowDef.getVersion()); - startWorkflowRequest.setCorrelationId("testing"); - saveScheduleRequest.setStartWorkflowRequest(startWorkflowRequest); - - // Save schedule - schedulerClient.saveSchedule(saveScheduleRequest); - - // Verify that schedule is saved - WorkflowSchedule workflowSchedule = schedulerClient.getSchedule(scheduleName); - assert cron.equals(workflowSchedule.getCronExpression()); - } - - private void scheduleOperations() { - // Pause Schedule - schedulerClient.pauseSchedule(scheduleName); - - // Verify the schedule is paused - WorkflowSchedule workflowSchedule = schedulerClient.getSchedule(scheduleName); - System.out.println(workflowSchedule.isPaused()); - - /// Resume schedule - schedulerClient.resumeSchedule(scheduleName); - // Verify the schedule is resumed - WorkflowSchedule workflowSchedule1 = schedulerClient.getSchedule(scheduleName); - System.out.println(!workflowSchedule1.isPaused()); - - // Example to get schedule, pause, resume, find next schedules, list scheduled executions - - // Find the next run - List schedules = - schedulerClient.getNextFewSchedules( - cron, System.nanoTime(), System.nanoTime() + 6 * 60 * 60 * NANO, 5); - System.out.println(schedules.size() == 5); - schedulerClient.pauseSchedule(scheduleName); - - // Get Scheduled executions - // TODO - } -} diff --git a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/WorkflowManagement.java b/examples/old/src/main/java/io/orkes/conductor/sdk/examples/WorkflowManagement.java deleted file mode 100644 index 3ea6fb956..000000000 --- a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/WorkflowManagement.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2022 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 io.orkes.conductor.sdk.examples; - -import java.util.Arrays; - -import com.netflix.conductor.client.http.ConductorClient; -import com.netflix.conductor.common.metadata.workflow.StartWorkflowRequest; - -import io.orkes.conductor.client.http.OrkesWorkflowClient; -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -import static io.orkes.conductor.sdk.examples.MetadataManagement.workflowDef; - -/** - * Examples for managing Workflow operations in Conductor - * - * 1. startWorkflow - Start a new workflow - * 2. getWorkflow - Get workflow execution status - * 3. pauseWorkflow - Pause workflow - * 4. resumeWorkflow - Resume workflow - * 5. terminateWorkflow - Terminate workflow - * 6. deleteWorkflow - Delete workflow - * - */ -public class WorkflowManagement { - - private static OrkesWorkflowClient workflowClient; - - public static void main(String[] args) { - ConductorClient client = ClientUtil.getClient(); - createMetadata(); - WorkflowManagement workflowManagement = new WorkflowManagement(); - workflowClient = new OrkesWorkflowClient(client); - workflowManagement.workflowOperations(); - client.shutdown(); - } - - private static void createMetadata() { - MetadataManagement metadataManagement = new MetadataManagement(); - metadataManagement.createTaskDefinitions(); - metadataManagement.createWorkflowDefinitions(); - } - - private void workflowOperations() { - StartWorkflowRequest startWorkflowRequest = new StartWorkflowRequest(); - startWorkflowRequest.setName(workflowDef.getName()); - startWorkflowRequest.setVersion(workflowDef.getVersion()); - startWorkflowRequest.setCorrelationId("test_workflow"); - - // Start the workflow - String workflowId = workflowClient.startWorkflow(startWorkflowRequest); - // Get the workflow execution status - workflowClient.getWorkflow(workflowId, true); - // Pause the workflow - workflowClient.pauseWorkflow(workflowId); - // Resume the workflow - workflowClient.resumeWorkflow(workflowId); - // Terminate the workflow - workflowClient.terminateWorkflow(workflowId, "Terminated"); - // Retry workflow - workflowClient.retryWorkflow(Arrays.asList(workflowId)); - // Terminate the workflow - workflowClient.terminateWorkflow(workflowId, "Terminated"); - // Restart workflow - workflowClient.restartWorkflow(Arrays.asList(workflowId), false); - // Terminate the workflow - workflowClient.terminateWorkflow(workflowId, "Terminated"); - // Restart workflow using latest workflow definitions - workflowClient.restartWorkflow(Arrays.asList(workflowId), true); - // Terminate the workflow - workflowClient.terminateWorkflow(workflowId, "Terminated"); - // Delete the workflow without archiving - workflowClient.deleteWorkflow(workflowId, false); - // Delete the workflow with archiving to persistent store. - workflowClient.deleteWorkflow(workflowId, true); - } -} diff --git a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/WorkflowManagement2.java b/examples/old/src/main/java/io/orkes/conductor/sdk/examples/WorkflowManagement2.java deleted file mode 100644 index 3de4c17c6..000000000 --- a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/WorkflowManagement2.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2024 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 io.orkes.conductor.sdk.examples; - -import java.time.Duration; -import java.util.Map; - -import com.netflix.conductor.client.http.ConductorClient; -import com.netflix.conductor.client.http.TaskClient; -import com.netflix.conductor.client.http.WorkflowClient; -import com.netflix.conductor.common.metadata.tasks.Task; -import com.netflix.conductor.common.metadata.tasks.TaskResult; -import com.netflix.conductor.common.metadata.workflow.StartWorkflowRequest; -import com.netflix.conductor.common.run.SearchResult; -import com.netflix.conductor.common.run.Workflow; -import com.netflix.conductor.common.run.WorkflowSummary; -import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; -import com.netflix.conductor.sdk.workflow.def.tasks.Http; -import com.netflix.conductor.sdk.workflow.def.tasks.Wait; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -//TODO review this example -public class WorkflowManagement2 { - private final WorkflowClient workflowClient; - private final TaskClient taskClient; - private final WorkflowExecutor workflowExecutor; - - public static void main(String[] args) { - new WorkflowManagement2().execute(); - } - - public WorkflowManagement2() { - ConductorClient client = ClientUtil.getClient(); - this.workflowClient = new WorkflowClient(client); - this.taskClient = new TaskClient(client); - this.workflowExecutor = new WorkflowExecutor(client, 100); - } - - public String startWorkflow() { - ConductorWorkflow workflow = new ConductorWorkflow<>(workflowExecutor); - workflow.setName("workflow_signals_demo"); - workflow.setVersion(1); - Wait waitForTwoSec = new Wait("wait_for_2_sec", Duration.ofSeconds(2)); - Http httpCall = new Http("call_remote_api"); - httpCall.url("https://orkes-api-tester.orkesconductor.com/api"); - - Wait waitForSignal = new Wait("wait_for_signal"); - - workflow.add(waitForTwoSec); - workflow.add(waitForSignal); - workflow.add(httpCall); - - workflow.registerWorkflow(true); - StartWorkflowRequest request = new StartWorkflowRequest(); - request.setVersion(1); - request.setName(workflow.getName()); - request.setInput(Map.of()); - - return workflowClient.startWorkflow(request); - } - - public void execute() { - String workflowId = startWorkflow(); - System.out.println("Started workflow with id " + workflowId); - - try { - Thread.sleep(3000); // Wait for 3 seconds - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - - Workflow workflow = workflowClient.getWorkflow(workflowId, true); - Task lastTask = workflow.getTasks().get(workflow.getTasks().size() - 1); - System.out.println("Workflow status is " + workflow.getStatus() + " and currently running task is " + lastTask.getReferenceTaskName()); - - workflowClient.terminateWorkflow(workflowId, "testing termination"); - - // Other operations like retry, update tasks, etc. - - // Example of task completion - TaskResult taskResult = new TaskResult(); - taskResult.setWorkflowInstanceId(workflowId); - taskResult.setTaskId(lastTask.getTaskId()); - taskResult.setStatus(TaskResult.Status.COMPLETED); - taskResult.setOutputData(Map.of("greetings", "hello from Orkes")); - taskClient.updateTask(taskResult); - - // Handling workflow lifecycle: terminate, restart, pause, resume - workflowClient.terminateWorkflow(workflowId, "terminating so we can do a restart"); - workflowClient.restart(workflowId, true); - workflowClient.pauseWorkflow(workflowId); - - try { - Thread.sleep(3000); // Simulating a wait - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - - workflowClient.resumeWorkflow(workflowId); - - // Search workflow examples - SearchResult searchResults = workflowClient.search(0, 100, "", "*", "correlationId = 'correlation_123'"); - System.out.println("Found " + searchResults.getTotalHits() + " executions with correlation_id 'correlation_123'"); - workflowExecutor.shutdown(); - } -} diff --git a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/AgenticExamplesRunner.java b/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/AgenticExamplesRunner.java deleted file mode 100644 index 50209bc7e..000000000 --- a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/AgenticExamplesRunner.java +++ /dev/null @@ -1,2008 +0,0 @@ -/* - * Copyright 2024 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 io.orkes.conductor.sdk.examples.agentic; - -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.time.Duration; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Scanner; -import java.util.concurrent.TimeUnit; - -import org.conductoross.conductor.sdk.ai.LlmChatComplete; -import org.conductoross.conductor.sdk.ai.LlmGenerateEmbeddings; -import org.conductoross.conductor.sdk.ai.LlmIndexText; -import org.conductoross.conductor.sdk.ai.LlmSearchIndex; -import org.conductoross.conductor.sdk.ai.LlmTextComplete; - -import com.netflix.conductor.client.automator.TaskRunnerConfigurer; -import com.netflix.conductor.client.http.ConductorClient; -import com.netflix.conductor.client.http.MetadataClient; -import com.netflix.conductor.client.http.TaskClient; -import com.netflix.conductor.client.http.WorkflowClient; -import com.netflix.conductor.client.worker.Worker; -import com.netflix.conductor.common.metadata.tasks.Task; -import com.netflix.conductor.common.metadata.tasks.TaskDef; -import com.netflix.conductor.common.metadata.tasks.TaskResult; -import com.netflix.conductor.common.metadata.workflow.StartWorkflowRequest; -import com.netflix.conductor.common.run.Workflow; -import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; -import com.netflix.conductor.sdk.workflow.def.tasks.DoWhile; -import com.netflix.conductor.sdk.workflow.def.tasks.ForkJoin; -import com.netflix.conductor.sdk.workflow.def.tasks.Http; -import com.netflix.conductor.sdk.workflow.def.tasks.SetVariable; -import com.netflix.conductor.sdk.workflow.def.tasks.SimpleTask; -import com.netflix.conductor.sdk.workflow.def.tasks.Switch; -import com.netflix.conductor.sdk.workflow.def.tasks.Wait; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * Unified runner for all Agentic/AI examples in the Conductor Java SDK. - *

- * This class provides a single entry point to: - *

    - *
  • Run all examples end-to-end
  • - *
  • Run individual examples interactively
  • - *
  • Validate SDK functionality with workers
  • - *
  • Execute LLM workflows using worker-based OpenAI/Claude calls
  • - *
- * - *

Usage: - *

- * # Run all examples
- * ./gradlew :examples:run -PmainClass=io.orkes.conductor.sdk.examples.agentic.AgenticExamplesRunner
- * 
- * # Run with specific mode
- * ./gradlew :examples:run --args="--all"
- * ./gradlew :examples:run --args="--menu"
- * ./gradlew :examples:run --args="--validate"
- * 
- * - *

Environment variables: - *

    - *
  • CONDUCTOR_SERVER_URL - Conductor server URL (default: http://localhost:8080/api)
  • - *
  • OPENAI_API_KEY - OpenAI API key for LLM workers
  • - *
  • ANTHROPIC_API_KEY - Anthropic API key for Claude (optional)
  • - *
- */ -public class AgenticExamplesRunner { - - private static final String BANNER = """ - ╔══════════════════════════════════════════════════════════════════╗ - ║ Conductor Java SDK - Agentic Examples Runner ║ - ╚══════════════════════════════════════════════════════════════════╝ - """; - - // Configuration - prefer Anthropic if available, fall back to OpenAI - private static final String OPENAI_API_KEY = System.getenv().getOrDefault("OPENAI_API_KEY", ""); - private static final String ANTHROPIC_API_KEY = System.getenv().getOrDefault("ANTHROPIC_API_KEY", ""); - private static final boolean USE_ANTHROPIC = !ANTHROPIC_API_KEY.isEmpty(); - private static final boolean HAS_LLM_KEY = USE_ANTHROPIC || !OPENAI_API_KEY.isEmpty(); - private static final ObjectMapper objectMapper = new ObjectMapper(); - private static final HttpClient httpClient = HttpClient.newBuilder() - .connectTimeout(Duration.ofSeconds(30)) - .build(); - - // Clients - private ConductorClient client; - private WorkflowExecutor executor; - private WorkflowClient workflowClient; - private TaskClient taskClient; - private MetadataClient metadataClient; - private TaskRunnerConfigurer taskRunner; - - // Test tracking - private int passedTests = 0; - private int failedTests = 0; - private List failedTestNames = new ArrayList<>(); - private List executedWorkflows = new ArrayList<>(); - - // Record of an executed workflow - private record WorkflowExecution(String workflowName, String workflowId, String status) {} - - public static void main(String[] args) { - System.out.println(BANNER); - - AgenticExamplesRunner runner = new AgenticExamplesRunner(); - - try { - runner.initialize(); - - if (args.length == 0 || "--all".equals(args[0])) { - runner.runAllExamples(); - } else if ("--menu".equals(args[0])) { - runner.runInteractiveMenu(); - } else if ("--validate".equals(args[0])) { - runner.runValidation(); - } else if ("--help".equals(args[0])) { - printHelp(); - } else { - System.out.println("Unknown option: " + args[0]); - printHelp(); - } - } catch (Exception e) { - System.err.println("\nFatal error: " + e.getMessage()); - e.printStackTrace(); - System.exit(1); - } finally { - runner.shutdown(); - } - } - - private static void printHelp() { - System.out.println(""" - Usage: AgenticExamplesRunner [option] - - Options: - --all Run all examples end-to-end (default) - --menu Interactive menu to select examples - --validate Run SDK validation tests only - --help Show this help message - - Environment variables: - CONDUCTOR_SERVER_URL - Conductor server URL - OPENAI_API_KEY - OpenAI API key for LLM examples - ANTHROPIC_API_KEY - Anthropic API key (optional) - """); - } - - /** - * Initialize all clients and workers. - */ - public void initialize() { - String serverUrl = System.getenv().getOrDefault("CONDUCTOR_SERVER_URL", "http://localhost:8080/api"); - System.out.println("Connecting to: " + serverUrl); - - client = ClientUtil.getClient(); - executor = new WorkflowExecutor(client, 100); - workflowClient = new WorkflowClient(client); - taskClient = new TaskClient(client); - metadataClient = new MetadataClient(client); - - // Verify connectivity - try { - metadataClient.getAllWorkflowsWithLatestVersions(); - System.out.println("Connected to Conductor server successfully"); - } catch (Exception e) { - throw new RuntimeException("Failed to connect to Conductor server: " + e.getMessage(), e); - } - - // Check for API keys - if (USE_ANTHROPIC) { - System.out.println("LLM Provider: Anthropic Claude (API key configured)"); - } else if (!OPENAI_API_KEY.isEmpty()) { - System.out.println("LLM Provider: OpenAI (API key configured)"); - } else { - System.out.println("LLM Provider: not configured (set OPENAI_API_KEY or ANTHROPIC_API_KEY)"); - } - System.out.println(); - - // Start workers for validation - startWorkers(); - } - - /** - * Start workers needed for examples. - */ - private void startWorkers() { - List workers = new ArrayList<>(); - - // Basic validation workers - workers.add(createWorker("get_weather", this::executeWeatherTask)); - workers.add(createWorker("search_web", this::executeSearchTask)); - workers.add(createWorker("calculate", this::executeCalculateTask)); - workers.add(createWorker("direct_response", this::executeDirectResponseTask)); - workers.add(createWorker("validation_task_1", this::executeValidationTask)); - workers.add(createWorker("validation_task_2", this::executeValidationTask)); - workers.add(createWorker("validation_task_3", this::executeValidationTask)); - - // Dispatch function worker (for function calling workflow - parses LLM JSON and calls function) - workers.add(createWorker("dispatch_function", this::executeDispatchFunctionTask)); - - // Workers for multi-agent and multi-turn chat workflows - workers.add(createWorker("chat_collect_history", this::executeChatCollectHistoryTask)); - workers.add(createWorker("build_moderator_messages", this::executeBuildModeratorMessagesTask)); - workers.add(createWorker("update_multiagent_history", this::executeUpdateMultiagentHistoryTask)); - - // MCP workers (bridge to MCP server via HTTP when Conductor doesn't have native MCP support) - workers.add(createWorker("mcp_list_tools_worker", this::executeMcpListToolsTask)); - workers.add(createWorker("mcp_call_tool_worker", this::executeMcpCallToolTask)); - - // LLM workers (only if API key is configured) - if (HAS_LLM_KEY) { - workers.add(createWorker("llm_chat", this::executeLlmChatTask)); - workers.add(createWorker("llm_text_complete", this::executeLlmTextCompleteTask)); - workers.add(createWorker("llm_function_selector", this::executeLlmFunctionSelectorTask)); - workers.add(createWorker("llm_response_formatter", this::executeLlmResponseFormatterTask)); - } - - // Register task definitions - for (Worker worker : workers) { - try { - TaskDef taskDef = new TaskDef(worker.getTaskDefName()); - taskDef.setOwnerEmail("examples@conductor-oss.org"); - taskDef.setRetryCount(0); - taskDef.setTimeoutSeconds(120); - metadataClient.registerTaskDefs(List.of(taskDef)); - } catch (Exception e) { - // Task may already exist - } - } - - taskRunner = new TaskRunnerConfigurer.Builder(taskClient, workers) - .withThreadCount(10) - .build(); - taskRunner.init(); - - System.out.println("Workers started: " + workers.size() + " task types\n"); - } - - /** - * Shutdown all resources. - */ - public void shutdown() { - if (taskRunner != null) { - taskRunner.shutdown(); - } - if (executor != null) { - executor.shutdown(); - } - } - - /** - * Run all examples end-to-end. - */ - public void runAllExamples() { - System.out.println("═══════════════════════════════════════════════════════════════════"); - System.out.println(" Running All Examples "); - System.out.println("═══════════════════════════════════════════════════════════════════\n"); - - // 1. SDK Validation - runTest("SDK Validation", this::runValidation); - - // 2. LLM Task Classes - runTest("LLM Task Classes Instantiation", this::testLlmTaskClasses); - - // 3. Workflow Task Types - runTest("Complex Task Types", this::testComplexTaskTypes); - - // 4. Simple Workflow Execution - runTest("Simple Workflow Execution", this::runSimpleWorkflow); - - // 5. LLM Examples (if API key is configured) - if (HAS_LLM_KEY) { - runTest("LLM Chat Workflow", this::runLlmChatWorkflow); - runTest("Function Calling Workflow", this::runFunctionCallingWorkflow); - runTest("Multi-turn Conversation Workflow", this::runMultiTurnConversationWorkflow); - runTest("Multi-Agent Chat Workflow", this::runMultiAgentChatWorkflow); - runTest("Human-in-the-Loop Chat", this::runHumanInLoopChatWorkflow); - runTest("MCP Weather Agent", this::runMcpWeatherAgentWorkflow); - } else { - System.out.println("\n─────────────────────────────────────────────────────────────────"); - System.out.println(" LLM Examples (SKIPPED - Set OPENAI_API_KEY or ANTHROPIC_API_KEY)"); - System.out.println("─────────────────────────────────────────────────────────────────"); - } - - // Print summary - printSummary(); - } - - /** - * Run a test with error handling. - */ - private void runTest(String testName, Runnable test) { - System.out.println("\n─────────────────────────────────────────────────────────────────"); - System.out.println(" " + testName); - System.out.println("─────────────────────────────────────────────────────────────────"); - - try { - test.run(); - pass(testName + " completed"); - } catch (Exception e) { - fail(testName + " failed: " + e.getMessage()); - failedTestNames.add(testName); - e.printStackTrace(); - } - } - - /** - * SDK validation tests. - */ - public void runValidation() { - // Test workflow definition - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName("sdk_validation_workflow"); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - - SimpleTask task1 = new SimpleTask("validation_task_1", "task1_ref"); - task1.input("input_name", "${workflow.input.name}"); - workflow.add(task1); - - SimpleTask task2 = new SimpleTask("validation_task_2", "task2_ref"); - task2.input("previous_output", "${task1_ref.output.result}"); - workflow.add(task2); - - SimpleTask task3 = new SimpleTask("validation_task_3", "task3_ref"); - task3.input("all_results", Map.of("task1", "${task1_ref.output.result}", "task2", "${task2_ref.output.result}")); - workflow.add(task3); - - Map output = new HashMap<>(); - output.put("finalResult", "${task3_ref.output.result}"); - workflow.setWorkflowOutput(output); - - // Register - workflow.registerWorkflow(true, true); - pass("Workflow registered: sdk_validation_workflow"); - - // Execute - Map input = new HashMap<>(); - input.put("name", "Validation Test"); - - try { - var workflowRun = workflow.execute(input); - Workflow result = workflowRun.get(30, TimeUnit.SECONDS); - - String workflowId = result.getWorkflowId(); - String status = result.getStatus().toString(); - executedWorkflows.add(new WorkflowExecution("sdk_validation_workflow", workflowId, status)); - - if (result.getStatus() == Workflow.WorkflowStatus.COMPLETED) { - pass("Workflow executed: " + workflowId + " [" + status + "]"); - } else { - fail("Workflow failed: " + workflowId + " [" + status + "]"); - } - } catch (Exception e) { - fail("Workflow execution error: " + e.getMessage()); - } - } - - /** - * Test all LLM task classes can be instantiated. - */ - private void testLlmTaskClasses() { - // LlmTextComplete - LlmTextComplete textTask = new LlmTextComplete("test_text", "text_ref") - .llmProvider("openai") - .model("gpt-4o-mini") - .promptName("test-prompt") - .temperature(0.7); - pass("LlmTextComplete instantiated"); - - // LlmChatComplete - LlmChatComplete chatTask = new LlmChatComplete("test_chat", "chat_ref") - .llmProvider("openai") - .model("gpt-4o-mini") - .messages(List.of(Map.of("role", "user", "content", "test"))) - .temperature(0.7); - pass("LlmChatComplete instantiated"); - - // LlmIndexText - LlmIndexText indexTask = new LlmIndexText("test_index", "index_ref") - .vectorDb("pinecone") - .namespace("test") - .index("test-index") - .embeddingModel("text-embedding-ada-002") - .text("test document"); - pass("LlmIndexText instantiated"); - - // LlmSearchIndex - LlmSearchIndex searchTask = new LlmSearchIndex("test_search", "search_ref") - .vectorDb("pinecone") - .namespace("test") - .index("test-index") - .query("test query") - .maxResults(5); - pass("LlmSearchIndex instantiated"); - - // LlmGenerateEmbeddings - LlmGenerateEmbeddings embedTask = new LlmGenerateEmbeddings("test_embed", "embed_ref") - .llmProvider("openai") - .model("text-embedding-ada-002") - .text("test text"); - pass("LlmGenerateEmbeddings instantiated"); - } - - /** - * Test complex task types. - */ - private void testComplexTaskTypes() { - // Switch task - Switch switchTask = new Switch("switch_ref", "${workflow.input.condition}"); - switchTask.switchCase("case1", new SimpleTask("task1", "task1_ref")); - switchTask.switchCase("case2", new SimpleTask("task2", "task2_ref")); - switchTask.defaultCase(new SimpleTask("default", "default_ref")); - pass("Switch task created with 2 cases + default"); - - // DoWhile task - DoWhile doWhile = new DoWhile("loop_ref", 3, - new SimpleTask("loop_task", "loop_task_ref")); - pass("DoWhile task created with 3 iterations"); - - // ForkJoin task - SimpleTask fork1 = new SimpleTask("fork1", "fork1_ref"); - SimpleTask fork2 = new SimpleTask("fork2", "fork2_ref"); - @SuppressWarnings("unchecked") - ForkJoin forkJoin = new ForkJoin("fork_ref", - new com.netflix.conductor.sdk.workflow.def.tasks.Task[]{fork1}, - new com.netflix.conductor.sdk.workflow.def.tasks.Task[]{fork2}); - pass("ForkJoin task created with 2 parallel branches"); - - // Http task - Http httpTask = new Http("http_ref"); - httpTask.url("https://httpbin.org/get") - .method(Http.Input.HttpMethod.GET); - pass("Http task created"); - - // SetVariable task - SetVariable setVar = new SetVariable("setvar_ref"); - setVar.input("myVar", "myValue"); - pass("SetVariable task created"); - } - - /** - * Run a simple workflow end-to-end. - */ - private void runSimpleWorkflow() { - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName("simple_agentic_test"); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - - SimpleTask task = new SimpleTask("validation_task_1", "test_ref"); - task.input("message", "${workflow.input.message}"); - workflow.add(task); - - workflow.setWorkflowOutput(Map.of("result", "${test_ref.output.result}")); - workflow.registerWorkflow(true, true); - - try { - var run = workflow.execute(Map.of("message", "Hello from Agentic Runner!")); - Workflow result = run.get(30, TimeUnit.SECONDS); - - String workflowId = result.getWorkflowId(); - String status = result.getStatus().toString(); - executedWorkflows.add(new WorkflowExecution("simple_agentic_test", workflowId, status)); - - if (result.getStatus() == Workflow.WorkflowStatus.COMPLETED) { - pass("Workflow executed: " + workflowId + " [" + status + "]"); - } else { - fail("Workflow failed: " + workflowId + " [" + status + "]"); - } - } catch (Exception e) { - fail("Simple workflow error: " + e.getMessage()); - } - } - - /** - * Run LLM Chat workflow using LLM_CHAT_COMPLETE system task. - */ - private void runLlmChatWorkflow() { - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName("llm_chat_workflow"); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - workflow.setDescription("LLM chat using LLM_CHAT_COMPLETE system task"); - - // LLM Chat Complete system task - LlmChatComplete chatTask = new LlmChatComplete("llm_chat_complete", "chat_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .messages("${workflow.input.messages}") - .temperature(0.7) - .maxTokens(500); - workflow.add(chatTask); - - workflow.setWorkflowOutput(Map.of( - "response", "${chat_ref.output.result}", - "model", "${workflow.input.model}" - )); - workflow.registerWorkflow(true, true); - pass("LLM Chat workflow registered (using LLM_CHAT_COMPLETE)"); - - // Execute the workflow - Map input = new HashMap<>(); - input.put("llmProvider", "openai"); - input.put("model", "gpt-4o-mini"); - input.put("messages", List.of( - Map.of("role", "system", "message", "You are a helpful assistant that gives concise answers."), - Map.of("role", "user", "message", "What is Conductor workflow orchestration? Answer in 2-3 sentences.") - )); - - try { - var run = workflow.execute(input); - Workflow result = run.get(90, TimeUnit.SECONDS); - - String workflowId = result.getWorkflowId(); - String status = result.getStatus().toString(); - executedWorkflows.add(new WorkflowExecution("llm_chat_workflow", workflowId, status)); - - if (result.getStatus() == Workflow.WorkflowStatus.COMPLETED) { - pass("Workflow executed: " + workflowId + " [" + status + "]"); - String response = (String) result.getOutput().get("response"); - if (response != null && response.length() > 100) { - response = response.substring(0, 100) + "..."; - } - pass("LLM Response: " + response); - } else { - fail("Workflow failed: " + workflowId + " [" + status + "] - " + result.getReasonForIncompletion()); - } - } catch (Exception e) { - String errorMsg = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName(); - fail("LLM Chat workflow error: " + errorMsg); - e.printStackTrace(); - } - } - - /** - * Run Function Calling workflow using LLM_CHAT_COMPLETE with JSON output. - * Follows Python SDK pattern: LLM returns JSON with function name and parameters, - * then a dispatch worker calls the appropriate function. - */ - private void runFunctionCallingWorkflow() { - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName("function_calling_workflow"); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - workflow.setDescription("LLM function calling with JSON output and dispatch worker"); - - // System prompt describing available tools (same pattern as Python SDK) - String systemPrompt = """ - You are a helpful assistant with access to the following tools (functions): - - 1. get_weather(city: string) - Get current weather for a city - 2. get_price(product: string) - Look up the price of a product - 3. calculate(expression: string) - Evaluate a math expression - - When you need to use a tool, respond with ONLY this JSON (no other text): - {"function": "FUNCTION_NAME", "function_parameters": {"param1": "value1"}} - - If you don't need a tool, respond with: - {"function": "direct_response", "function_parameters": {"answer": "your answer here"}} - """; - - // Step 1: LLM decides which function to call (returns JSON) - LlmChatComplete selectorTask = new LlmChatComplete("function_selector", "selector_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .messages("${workflow.input.messages}") - .temperature(0.0) - .maxTokens(200); - workflow.add(selectorTask); - - // Step 2: Dispatch worker parses JSON and calls the function - SimpleTask dispatchTask = new SimpleTask("dispatch_function", "dispatch_ref"); - dispatchTask.input("llm_response", "${selector_ref.output.result}"); - workflow.add(dispatchTask); - - workflow.setWorkflowOutput(Map.of( - "llm_decision", "${selector_ref.output.result}", - "function_result", "${dispatch_ref.output.result}", - "function_called", "${dispatch_ref.output.function}" - )); - workflow.registerWorkflow(true, true); - pass("Function Calling workflow registered (using LLM_CHAT_COMPLETE with JSON)"); - - // Execute the workflow - Map input = new HashMap<>(); - input.put("llmProvider", "openai"); - input.put("model", "gpt-4o-mini"); - input.put("messages", List.of( - Map.of("role", "system", "message", systemPrompt), - Map.of("role", "user", "message", "What's the weather like in San Francisco?") - )); - - try { - var run = workflow.execute(input); - Workflow result = run.get(90, TimeUnit.SECONDS); - - String workflowId = result.getWorkflowId(); - String status = result.getStatus().toString(); - executedWorkflows.add(new WorkflowExecution("function_calling_workflow", workflowId, status)); - - if (result.getStatus() == Workflow.WorkflowStatus.COMPLETED) { - pass("Workflow executed: " + workflowId + " [" + status + "]"); - pass("Function called: " + result.getOutput().get("function_called")); - Object functionResult = result.getOutput().get("function_result"); - String resultStr = functionResult != null ? functionResult.toString() : "null"; - if (resultStr.length() > 100) { - resultStr = resultStr.substring(0, 100) + "..."; - } - pass("Result: " + resultStr); - } else { - fail("Workflow failed: " + workflowId + " [" + status + "] - " + result.getReasonForIncompletion()); - } - } catch (Exception e) { - fail("Function Calling workflow error: " + e.getMessage()); - } - } - - /** - * Run Multi-turn Conversation workflow using LLM_CHAT_COMPLETE system tasks. - */ - private void runMultiTurnConversationWorkflow() { - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName("multi_turn_conversation"); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - workflow.setDescription("Multi-turn conversation using LLM_CHAT_COMPLETE"); - - // Turn 1: Initial question - LlmChatComplete turn1 = new LlmChatComplete("turn1_chat", "turn1_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .messages(List.of( - Map.of("role", "system", "message", "You are a helpful assistant. Be concise."), - Map.of("role", "user", "message", "${workflow.input.question1}") - )) - .temperature(0.7) - .maxTokens(200); - workflow.add(turn1); - - // Turn 2: Follow-up question with context from turn 1 - LlmChatComplete turn2 = new LlmChatComplete("turn2_chat", "turn2_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .messages(List.of( - Map.of("role", "system", "message", "You are a helpful assistant. Consider the previous context."), - Map.of("role", "user", "message", "${workflow.input.question1}"), - Map.of("role", "assistant", "message", "${turn1_ref.output.result}"), - Map.of("role", "user", "message", "${workflow.input.question2}") - )) - .temperature(0.7) - .maxTokens(200); - workflow.add(turn2); - - workflow.setWorkflowOutput(Map.of( - "turn1_response", "${turn1_ref.output.result}", - "turn2_response", "${turn2_ref.output.result}" - )); - workflow.registerWorkflow(true, true); - pass("Multi-turn Conversation workflow registered (using LLM_CHAT_COMPLETE)"); - - // Execute the workflow - Map input = new HashMap<>(); - input.put("question1", "What is the capital of France?"); - input.put("question2", "What is its population?"); - input.put("llmProvider", "openai"); - input.put("model", "gpt-4o-mini"); - - try { - var run = workflow.execute(input); - Workflow result = run.get(90, TimeUnit.SECONDS); - - String workflowId = result.getWorkflowId(); - String status = result.getStatus().toString(); - executedWorkflows.add(new WorkflowExecution("multi_turn_conversation", workflowId, status)); - - if (result.getStatus() == Workflow.WorkflowStatus.COMPLETED) { - pass("Workflow executed: " + workflowId + " [" + status + "]"); - String turn1Response = (String) result.getOutput().get("turn1_response"); - String turn2Response = (String) result.getOutput().get("turn2_response"); - if (turn1Response != null && turn1Response.length() > 80) { - turn1Response = turn1Response.substring(0, 80) + "..."; - } - if (turn2Response != null && turn2Response.length() > 80) { - turn2Response = turn2Response.substring(0, 80) + "..."; - } - pass("Turn 1: " + turn1Response); - pass("Turn 2: " + turn2Response); - } else { - fail("Workflow failed: " + workflowId + " [" + status + "] - " + result.getReasonForIncompletion()); - } - } catch (Exception e) { - String errorMsg = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName(); - fail("Multi-turn workflow error: " + errorMsg); - e.printStackTrace(); - } - } - - /** - * Interactive menu for selecting examples. - */ - public void runInteractiveMenu() { - Scanner scanner = new Scanner(System.in); - - while (true) { - System.out.println("\n═══════════════════════════════════════════════════════════════════"); - System.out.println(" Agentic Examples Menu "); - System.out.println("═══════════════════════════════════════════════════════════════════"); - System.out.println(" 1. Run SDK Validation"); - System.out.println(" 2. Test LLM Task Classes"); - System.out.println(" 3. Test Complex Task Types"); - System.out.println(" 4. Run Simple Workflow"); - if (HAS_LLM_KEY) { - System.out.println(" 5. Run LLM Chat Workflow"); - System.out.println(" 6. Run Function Calling Workflow"); - System.out.println(" 7. Run Multi-turn Conversation"); - } - System.out.println(" 8. Run All Examples"); - System.out.println(" 0. Exit"); - System.out.println("═══════════════════════════════════════════════════════════════════"); - System.out.print("\nSelect option: "); - - String input = scanner.nextLine().trim(); - - switch (input) { - case "1" -> runTest("SDK Validation", this::runValidation); - case "2" -> runTest("LLM Task Classes", this::testLlmTaskClasses); - case "3" -> runTest("Complex Task Types", this::testComplexTaskTypes); - case "4" -> runTest("Simple Workflow", this::runSimpleWorkflow); - case "5" -> { - if (HAS_LLM_KEY) { - runTest("LLM Chat Workflow", this::runLlmChatWorkflow); - } else { - System.out.println("No LLM API key configured"); - } - } - case "6" -> { - if (HAS_LLM_KEY) { - runTest("Function Calling Workflow", this::runFunctionCallingWorkflow); - } else { - System.out.println("No LLM API key configured"); - } - } - case "7" -> { - if (HAS_LLM_KEY) { - runTest("Multi-turn Conversation", this::runMultiTurnConversationWorkflow); - } else { - System.out.println("No LLM API key configured"); - } - } - case "8" -> runAllExamples(); - case "0" -> { - System.out.println("\nGoodbye!"); - return; - } - default -> System.out.println("Invalid option. Please try again."); - } - } - } - - /** - * Print test summary. - */ - private void printSummary() { - System.out.println("\n╔══════════════════════════════════════════════════════════════════╗"); - System.out.println("║ TEST SUMMARY ║"); - System.out.println("╠══════════════════════════════════════════════════════════════════╣"); - System.out.printf("║ Passed: %-5d ║%n", passedTests); - System.out.printf("║ Failed: %-5d ║%n", failedTests); - System.out.println("╠══════════════════════════════════════════════════════════════════╣"); - if (failedTests == 0) { - System.out.println("║ Result: ALL TESTS PASSED ║"); - } else { - System.out.println("║ Result: SOME TESTS FAILED ║"); - System.out.println("╠══════════════════════════════════════════════════════════════════╣"); - System.out.println("║ Failed tests: ║"); - for (String name : failedTestNames) { - System.out.printf("║ - %-58s ║%n", name); - } - } - System.out.println("╚══════════════════════════════════════════════════════════════════╝"); - - // Print executed workflows - if (!executedWorkflows.isEmpty()) { - System.out.println("\n╔══════════════════════════════════════════════════════════════════╗"); - System.out.println("║ EXECUTED WORKFLOWS ║"); - System.out.println("╠══════════════════════════════════════════════════════════════════╣"); - for (WorkflowExecution wf : executedWorkflows) { - System.out.printf("║ %-30s ║%n", wf.workflowName()); - System.out.printf("║ ID: %-56s ║%n", wf.workflowId()); - System.out.printf("║ Status: %-52s ║%n", wf.status()); - } - System.out.println("╚══════════════════════════════════════════════════════════════════╝"); - } - - System.exit(failedTests > 0 ? 1 : 0); - } - - private void pass(String message) { - System.out.println(" ✓ " + message); - passedTests++; - } - - private void fail(String message) { - System.out.println(" ✗ " + message); - failedTests++; - } - - // ═══════════════════════════════════════════════════════════════════ - // WORKER IMPLEMENTATIONS - // ═══════════════════════════════════════════════════════════════════ - - private Worker createWorker(String taskDefName, java.util.function.Function executor) { - return new Worker() { - @Override - public String getTaskDefName() { - return taskDefName; - } - - @Override - public TaskResult execute(Task task) { - return executor.apply(task); - } - }; - } - - private TaskResult executeWeatherTask(Task task) { - TaskResult result = new TaskResult(task); - result.setStatus(TaskResult.Status.COMPLETED); - String location = (String) task.getInputData().get("location"); - if (location == null) location = "Unknown"; - result.addOutputData("result", "Weather in " + location + ": Sunny, 72°F (22°C), clear skies"); - result.addOutputData("temperature", 72); - result.addOutputData("condition", "sunny"); - result.addOutputData("location", location); - return result; - } - - private TaskResult executeSearchTask(Task task) { - TaskResult result = new TaskResult(task); - result.setStatus(TaskResult.Status.COMPLETED); - String query = (String) task.getInputData().get("query"); - if (query == null) query = "Unknown"; - result.addOutputData("result", "Search results for: " + query); - result.addOutputData("results", List.of( - Map.of("title", "Result 1 for " + query, "url", "https://example.com/1"), - Map.of("title", "Result 2 for " + query, "url", "https://example.com/2") - )); - return result; - } - - private TaskResult executeCalculateTask(Task task) { - TaskResult result = new TaskResult(task); - result.setStatus(TaskResult.Status.COMPLETED); - String expression = (String) task.getInputData().get("expression"); - if (expression == null) expression = "0"; - result.addOutputData("result", "Calculated: " + expression + " = 42"); - result.addOutputData("value", 42); - return result; - } - - private TaskResult executeDirectResponseTask(Task task) { - TaskResult result = new TaskResult(task); - result.setStatus(TaskResult.Status.COMPLETED); - String query = (String) task.getInputData().get("query"); - result.addOutputData("result", "I can help answer: " + query); - return result; - } - - private TaskResult executeValidationTask(Task task) { - TaskResult result = new TaskResult(task); - result.setStatus(TaskResult.Status.COMPLETED); - result.addOutputData("result", "Processed by " + task.getTaskDefName()); - result.addOutputData("inputReceived", task.getInputData()); - result.addOutputData("timestamp", System.currentTimeMillis()); - return result; - } - - /** - * Dispatch function worker - parses LLM JSON response and calls the appropriate function. - * This follows the Python SDK pattern where the LLM returns JSON like: - * {"function": "function_name", "function_parameters": {"param1": "value1"}} - */ - @SuppressWarnings("unchecked") - private TaskResult executeDispatchFunctionTask(Task task) { - TaskResult result = new TaskResult(task); - - Object llmResponseObj = task.getInputData().get("llm_response"); - if (llmResponseObj == null) { - result.setStatus(TaskResult.Status.FAILED); - result.setReasonForIncompletion("No LLM response provided"); - return result; - } - - try { - String functionName; - Map functionParams; - String rawResponse; - - // Handle both String and Map (already parsed JSON) responses - if (llmResponseObj instanceof Map) { - // Already parsed by Conductor - the LLM_CHAT_COMPLETE task may return parsed JSON - Map responseMap = (Map) llmResponseObj; - functionName = (String) responseMap.get("function"); - Object paramsObj = responseMap.get("function_parameters"); - functionParams = paramsObj instanceof Map ? (Map) paramsObj : Map.of(); - rawResponse = objectMapper.writeValueAsString(responseMap); - } else { - // String response - parse it - String llmResponse = llmResponseObj.toString(); - rawResponse = llmResponse; - - // Clean up the response - sometimes LLM wraps JSON in markdown code blocks - String cleanedResponse = llmResponse.trim(); - if (cleanedResponse.startsWith("```json")) { - cleanedResponse = cleanedResponse.substring(7); - } else if (cleanedResponse.startsWith("```")) { - cleanedResponse = cleanedResponse.substring(3); - } - if (cleanedResponse.endsWith("```")) { - cleanedResponse = cleanedResponse.substring(0, cleanedResponse.length() - 3); - } - cleanedResponse = cleanedResponse.trim(); - - // Parse the JSON - JsonNode json = objectMapper.readTree(cleanedResponse); - functionName = json.path("function").asText(); - JsonNode paramsNode = json.path("function_parameters"); - functionParams = paramsNode.isMissingNode() ? Map.of() : objectMapper.convertValue(paramsNode, Map.class); - } - - if (functionName == null || functionName.isEmpty()) { - result.setStatus(TaskResult.Status.FAILED); - result.setReasonForIncompletion("No function name in LLM response: " + rawResponse); - return result; - } - - // Dispatch to the appropriate function - String functionResult; - switch (functionName) { - case "get_weather" -> { - String city = (String) functionParams.getOrDefault("city", - functionParams.getOrDefault("location", "")); // Alternative param name - functionResult = getWeather(city); - } - case "get_price" -> { - String product = (String) functionParams.getOrDefault("product", ""); - functionResult = getPrice(product); - } - case "calculate" -> { - String expression = (String) functionParams.getOrDefault("expression", ""); - functionResult = calculate(expression); - } - case "direct_response" -> { - String answer = (String) functionParams.getOrDefault("answer", ""); - functionResult = answer.isEmpty() ? "No direct answer provided" : answer; - } - default -> { - functionResult = "Unknown function: " + functionName; - } - } - - result.setStatus(TaskResult.Status.COMPLETED); - result.addOutputData("function", functionName); - result.addOutputData("parameters", functionParams); - result.addOutputData("result", functionResult); - result.addOutputData("llm_raw_response", rawResponse); - - } catch (Exception e) { - result.setStatus(TaskResult.Status.FAILED); - result.setReasonForIncompletion("Failed to parse LLM response: " + e.getMessage() + " - Response was: " + llmResponseObj); - } - - return result; - } - - // Function implementations for dispatch_function worker - private String getWeather(String city) { - if (city == null || city.isEmpty()) { - city = "Unknown"; - } - // Simulated weather data - return String.format("Weather in %s: Sunny, 72°F (22°C), humidity 45%%, winds 10 mph from the west.", city); - } - - private String getPrice(String product) { - if (product == null || product.isEmpty()) { - return "No product specified"; - } - // Simulated price data - Map prices = Map.of( - "laptop", "$999.99", - "phone", "$699.99", - "tablet", "$449.99", - "headphones", "$199.99" - ); - String price = prices.get(product.toLowerCase()); - return price != null ? String.format("The price of %s is %s", product, price) - : String.format("Price for '%s' not found in catalog", product); - } - - private String calculate(String expression) { - if (expression == null || expression.isEmpty()) { - return "No expression provided"; - } - // Simple evaluation for basic expressions (for demo purposes) - try { - // Handle simple arithmetic for demo - expression = expression.replaceAll("\\s+", ""); - if (expression.matches("\\d+\\+\\d+")) { - String[] parts = expression.split("\\+"); - int result = Integer.parseInt(parts[0]) + Integer.parseInt(parts[1]); - return expression + " = " + result; - } else if (expression.matches("\\d+\\-\\d+")) { - String[] parts = expression.split("\\-"); - int result = Integer.parseInt(parts[0]) - Integer.parseInt(parts[1]); - return expression + " = " + result; - } else if (expression.matches("\\d+\\*\\d+")) { - String[] parts = expression.split("\\*"); - int result = Integer.parseInt(parts[0]) * Integer.parseInt(parts[1]); - return expression + " = " + result; - } else if (expression.matches("\\d+/\\d+")) { - String[] parts = expression.split("/"); - double result = Double.parseDouble(parts[0]) / Double.parseDouble(parts[1]); - return expression + " = " + result; - } - return "Calculated: " + expression + " (complex expression - result: 42)"; - } catch (Exception e) { - return "Error calculating: " + expression; - } - } - - // ═══════════════════════════════════════════════════════════════════ - // LLM WORKER IMPLEMENTATIONS - // ═══════════════════════════════════════════════════════════════════ - - /** - * LLM Chat worker - calls OpenAI or Anthropic API based on configuration. - */ - private TaskResult executeLlmChatTask(Task task) { - TaskResult result = new TaskResult(task); - - String prompt = (String) task.getInputData().get("prompt"); - // Always use the appropriate model for the configured provider - String model = USE_ANTHROPIC ? "claude-haiku-4-5" : "gpt-4o-mini"; - String systemPrompt = (String) task.getInputData().getOrDefault("systemPrompt", "You are a helpful assistant."); - - try { - String response = USE_ANTHROPIC ? callClaudeChat(prompt, model, systemPrompt) : callOpenAiChat(prompt, model, systemPrompt); - result.setStatus(TaskResult.Status.COMPLETED); - result.addOutputData("response", response); - result.addOutputData("model", model); - result.addOutputData("provider", USE_ANTHROPIC ? "anthropic" : "openai"); - result.addOutputData("usage", Map.of("model", model, "prompt_length", prompt.length())); - } catch (Exception e) { - result.setStatus(TaskResult.Status.FAILED); - result.setReasonForIncompletion("LLM API error: " + e.getMessage()); - e.printStackTrace(); - } - - return result; - } - - /** - * LLM Text Complete worker. - */ - private TaskResult executeLlmTextCompleteTask(Task task) { - return executeLlmChatTask(task); // Same implementation for simplicity - } - - /** - * LLM Function Selector worker - uses tool/function calling. - */ - private TaskResult executeLlmFunctionSelectorTask(Task task) { - TaskResult result = new TaskResult(task); - - String query = (String) task.getInputData().get("query"); - - try { - Map functionCall = USE_ANTHROPIC ? callClaudeFunctionSelection(query) : callOpenAiFunctionSelection(query); - result.setStatus(TaskResult.Status.COMPLETED); - result.addOutputData("selectedFunction", functionCall.get("name")); - result.addOutputData("functionArgs", functionCall.get("arguments")); - result.addOutputData("reasoning", functionCall.get("reasoning")); - } catch (Exception e) { - result.setStatus(TaskResult.Status.FAILED); - result.setReasonForIncompletion("LLM API error: " + e.getMessage()); - } - - return result; - } - - /** - * LLM Response Formatter worker. - */ - private TaskResult executeLlmResponseFormatterTask(Task task) { - TaskResult result = new TaskResult(task); - - String query = (String) task.getInputData().get("query"); - String functionCalled = (String) task.getInputData().get("functionCalled"); - Object functionResult = task.getInputData().get("functionResult"); - - try { - String prompt = String.format( - "The user asked: %s\n\nI called the '%s' function and got this result: %s\n\nPlease provide a natural, helpful response to the user based on this information.", - query, functionCalled, functionResult - ); - String model = USE_ANTHROPIC ? "claude-haiku-4-5" : "gpt-4o-mini"; - String response = USE_ANTHROPIC ? callClaudeChat(prompt, model, "You are a helpful assistant that formats function results into natural responses.") - : callOpenAiChat(prompt, model, "You are a helpful assistant that formats function results into natural responses."); - result.setStatus(TaskResult.Status.COMPLETED); - result.addOutputData("response", response); - } catch (Exception e) { - result.setStatus(TaskResult.Status.FAILED); - result.setReasonForIncompletion("LLM API error: " + e.getMessage()); - } - - return result; - } - - /** - * Call OpenAI Chat Completion API. - */ - private String callOpenAiChat(String prompt, String model, String systemPrompt) throws IOException, InterruptedException { - Map requestBody = Map.of( - "model", model, - "messages", List.of( - Map.of("role", "system", "content", systemPrompt), - Map.of("role", "user", "content", prompt) - ), - "max_tokens", 500, - "temperature", 0.7 - ); - - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create("https://api.openai.com/v1/chat/completions")) - .header("Content-Type", "application/json") - .header("Authorization", "Bearer " + OPENAI_API_KEY) - .POST(HttpRequest.BodyPublishers.ofString(objectMapper.writeValueAsString(requestBody))) - .timeout(Duration.ofSeconds(60)) - .build(); - - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - - if (response.statusCode() != 200) { - throw new IOException("OpenAI API error: " + response.statusCode() + " - " + response.body()); - } - - JsonNode json = objectMapper.readTree(response.body()); - return json.path("choices").path(0).path("message").path("content").asText(); - } - - /** - * Call OpenAI with function calling to select appropriate tool. - */ - private Map callOpenAiFunctionSelection(String query) throws IOException, InterruptedException { - List> tools = List.of( - createToolDefinition("get_weather", "Get the current weather for a location", - Map.of("type", "object", "properties", Map.of( - "location", Map.of("type", "string", "description", "City name") - ), "required", List.of("location"))), - createToolDefinition("search_web", "Search the web for information", - Map.of("type", "object", "properties", Map.of( - "query", Map.of("type", "string", "description", "Search query") - ), "required", List.of("query"))), - createToolDefinition("calculate", "Perform mathematical calculations", - Map.of("type", "object", "properties", Map.of( - "expression", Map.of("type", "string", "description", "Math expression") - ), "required", List.of("expression"))) - ); - - Map requestBody = new HashMap<>(); - requestBody.put("model", "gpt-4o-mini"); - requestBody.put("messages", List.of( - Map.of("role", "system", "content", "You are a helpful assistant. Use the available tools to answer the user's question."), - Map.of("role", "user", "content", query) - )); - requestBody.put("tools", tools); - requestBody.put("tool_choice", "auto"); - - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create("https://api.openai.com/v1/chat/completions")) - .header("Content-Type", "application/json") - .header("Authorization", "Bearer " + OPENAI_API_KEY) - .POST(HttpRequest.BodyPublishers.ofString(objectMapper.writeValueAsString(requestBody))) - .timeout(Duration.ofSeconds(60)) - .build(); - - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - - if (response.statusCode() != 200) { - throw new IOException("OpenAI API error: " + response.statusCode() + " - " + response.body()); - } - - JsonNode json = objectMapper.readTree(response.body()); - JsonNode message = json.path("choices").path(0).path("message"); - - // Check if a tool was called - JsonNode toolCalls = message.path("tool_calls"); - if (toolCalls.isArray() && toolCalls.size() > 0) { - JsonNode toolCall = toolCalls.get(0); - String functionName = toolCall.path("function").path("name").asText(); - String argsJson = toolCall.path("function").path("arguments").asText(); - Map args = objectMapper.readValue(argsJson, Map.class); - - return Map.of( - "name", functionName, - "arguments", args, - "reasoning", "LLM selected " + functionName + " based on query analysis" - ); - } else { - // No tool called, return direct response - return Map.of( - "name", "direct_response", - "arguments", Map.of("query", query), - "reasoning", "LLM chose to respond directly without tools" - ); - } - } - - /** - * Call Anthropic Claude API for chat completion. - */ - private String callClaudeChat(String prompt, String model, String systemPrompt) throws IOException, InterruptedException { - Map requestBody = new HashMap<>(); - requestBody.put("model", model); - requestBody.put("max_tokens", 500); - requestBody.put("system", systemPrompt); - requestBody.put("messages", List.of( - Map.of("role", "user", "content", prompt) - )); - - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create("https://api.anthropic.com/v1/messages")) - .header("Content-Type", "application/json") - .header("x-api-key", ANTHROPIC_API_KEY) - .header("anthropic-version", "2023-06-01") - .POST(HttpRequest.BodyPublishers.ofString(objectMapper.writeValueAsString(requestBody))) - .timeout(Duration.ofSeconds(60)) - .build(); - - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - - if (response.statusCode() != 200) { - throw new IOException("Claude API error: " + response.statusCode() + " - " + response.body()); - } - - JsonNode json = objectMapper.readTree(response.body()); - return json.path("content").path(0).path("text").asText(); - } - - /** - * Call Claude with tool use for function selection. - */ - private Map callClaudeFunctionSelection(String query) throws IOException, InterruptedException { - List> tools = List.of( - Map.of( - "name", "get_weather", - "description", "Get the current weather for a location", - "input_schema", Map.of( - "type", "object", - "properties", Map.of( - "location", Map.of("type", "string", "description", "City name") - ), - "required", List.of("location") - ) - ), - Map.of( - "name", "search_web", - "description", "Search the web for information", - "input_schema", Map.of( - "type", "object", - "properties", Map.of( - "query", Map.of("type", "string", "description", "Search query") - ), - "required", List.of("query") - ) - ), - Map.of( - "name", "calculate", - "description", "Perform mathematical calculations", - "input_schema", Map.of( - "type", "object", - "properties", Map.of( - "expression", Map.of("type", "string", "description", "Math expression") - ), - "required", List.of("expression") - ) - ) - ); - - Map requestBody = new HashMap<>(); - requestBody.put("model", "claude-haiku-4-5"); - requestBody.put("max_tokens", 500); - requestBody.put("system", "You are a helpful assistant. Use the available tools to answer the user's question."); - requestBody.put("messages", List.of(Map.of("role", "user", "content", query))); - requestBody.put("tools", tools); - requestBody.put("tool_choice", Map.of("type", "auto")); - - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create("https://api.anthropic.com/v1/messages")) - .header("Content-Type", "application/json") - .header("x-api-key", ANTHROPIC_API_KEY) - .header("anthropic-version", "2023-06-01") - .POST(HttpRequest.BodyPublishers.ofString(objectMapper.writeValueAsString(requestBody))) - .timeout(Duration.ofSeconds(60)) - .build(); - - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - - if (response.statusCode() != 200) { - throw new IOException("Claude API error: " + response.statusCode() + " - " + response.body()); - } - - JsonNode json = objectMapper.readTree(response.body()); - JsonNode content = json.path("content"); - - // Check if a tool was called - for (JsonNode block : content) { - if ("tool_use".equals(block.path("type").asText())) { - String functionName = block.path("name").asText(); - JsonNode inputNode = block.path("input"); - Map args = objectMapper.convertValue(inputNode, Map.class); - - return Map.of( - "name", functionName, - "arguments", args, - "reasoning", "Claude selected " + functionName + " based on query analysis" - ); - } - } - - // No tool called, return direct response - return Map.of( - "name", "direct_response", - "arguments", Map.of("query", query), - "reasoning", "Claude chose to respond directly without tools" - ); - } - - private Map createToolDefinition(String name, String description, Map parameters) { - return Map.of( - "type", "function", - "function", Map.of( - "name", name, - "description", description, - "parameters", parameters - ) - ); - } - - // ═══════════════════════════════════════════════════════════════════ - // MULTI-AGENT CHAT WORKFLOW - // ═══════════════════════════════════════════════════════════════════ - - /** - * Multi-agent debate workflow: a moderator LLM routes turns between two LLM panelists. - * Mirrors the Python SDK multiagent_chat.py example. - */ - private void runMultiAgentChatWorkflow() { - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName("multiagent_chat_demo"); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - workflow.setDescription("Multi-agent debate: moderator routes between two LLM panelists"); - - // Init: set history variable - SetVariable init = new SetVariable("init_ref"); - init.input("history", List.of( - Map.of("role", "user", "message", "Discuss the following topic: ${workflow.input.topic}") - )); - init.input("last_speaker", ""); - - // Build moderator messages (worker prepends system prompt to history) - SimpleTask buildMessages = new SimpleTask("build_moderator_messages", "build_mod_msgs_ref"); - buildMessages.input("system_prompt", - "You are a discussion moderator. Two panelists are debating: " - + "${workflow.input.agent1_name} and ${workflow.input.agent2_name}.\n" - + "Summarize the latest exchange, then ask a follow-up question to " - + "one of them. Alternate fairly. The last speaker was: ${workflow.variables.last_speaker}.\n\n" - + "Respond ONLY with valid JSON:\n" - + "{\"result\": \"your moderator message\", \"user\": \"name_of_next_speaker\"}"); - buildMessages.input("history", "${workflow.variables.history}"); - - // Moderator LLM (produces JSON: {result, user}) - LlmChatComplete moderatorTask = new LlmChatComplete("moderator_llm", "moderator_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .messages("${build_mod_msgs_ref.output.result}") - .temperature(0.7) - .maxTokens(500) - .jsonOutput(true); - - // Agent 1 LLM - LlmChatComplete agent1Task = new LlmChatComplete("agent1_llm", "agent1_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .messages(List.of( - Map.of("role", "system", "message", - "You are ${workflow.input.agent1_name}. You reason and speak like this persona. " - + "You are in a panel discussion. Provide insightful analysis. " - + "Do not mention that you are an AI. Keep responses to 2-3 sentences.\n\n" - + "Topic: ${workflow.input.topic}"), - Map.of("role", "user", "message", "${moderator_ref.output.result.result}") - )) - .temperature(0.8) - .maxTokens(300); - - SimpleTask updateHistory1 = new SimpleTask("update_multiagent_history", "update_hist1_ref"); - updateHistory1.input("history", "${workflow.variables.history}"); - updateHistory1.input("moderator_message", "${moderator_ref.output.result.result}"); - updateHistory1.input("agent_name", "${workflow.input.agent1_name}"); - updateHistory1.input("agent_response", "${agent1_ref.output.result}"); - - SetVariable saveVar1 = new SetVariable("save_var1_ref"); - saveVar1.input("history", "${update_hist1_ref.output.result}"); - saveVar1.input("last_speaker", "${workflow.input.agent1_name}"); - - // Agent 2 LLM - LlmChatComplete agent2Task = new LlmChatComplete("agent2_llm", "agent2_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .messages(List.of( - Map.of("role", "system", "message", - "You are ${workflow.input.agent2_name}. You bring contrarian views and challenge assumptions. " - + "You are in a panel discussion. Be provocative but civil. " - + "Do not mention that you are an AI. Keep responses to 2-3 sentences.\n\n" - + "Topic: ${workflow.input.topic}"), - Map.of("role", "user", "message", "${moderator_ref.output.result.result}") - )) - .temperature(0.8) - .maxTokens(300); - - SimpleTask updateHistory2 = new SimpleTask("update_multiagent_history", "update_hist2_ref"); - updateHistory2.input("history", "${workflow.variables.history}"); - updateHistory2.input("moderator_message", "${moderator_ref.output.result.result}"); - updateHistory2.input("agent_name", "${workflow.input.agent2_name}"); - updateHistory2.input("agent_response", "${agent2_ref.output.result}"); - - SetVariable saveVar2 = new SetVariable("save_var2_ref"); - saveVar2.input("history", "${update_hist2_ref.output.result}"); - saveVar2.input("last_speaker", "${workflow.input.agent2_name}"); - - // Route to agent1 or agent2 based on moderator's pick - // Use a simplified routing: if moderator picks agent2, route there, else agent1 - Switch router = new Switch("route_ref", "${moderator_ref.output.result.user}"); - router.switchCase("${workflow.input.agent2_name}", agent2Task, updateHistory2, saveVar2); - router.defaultCase(agent1Task, updateHistory1, saveVar1); - - // Loop: build messages -> moderate -> route to agent - DoWhile loop = new DoWhile("loop_ref", 2, buildMessages, moderatorTask, router); - - workflow.add(init); - workflow.add(loop); - workflow.registerWorkflow(true, true); - pass("Multi-Agent Chat workflow registered"); - - Map input = new HashMap<>(); - input.put("topic", "The impact of artificial intelligence on employment"); - input.put("agent1_name", "optimistic technologist"); - input.put("agent2_name", "cautious economist"); - input.put("llmProvider", "openai"); - input.put("model", "gpt-4o-mini"); - - try { - var run = workflow.execute(input); - Workflow result = run.get(120, TimeUnit.SECONDS); - - String workflowId = result.getWorkflowId(); - String status = result.getStatus().toString(); - executedWorkflows.add(new WorkflowExecution("multiagent_chat_demo", workflowId, status)); - - if (result.getStatus() == Workflow.WorkflowStatus.COMPLETED) { - pass("Workflow executed: " + workflowId + " [" + status + "]"); - } else { - fail("Workflow failed: " + workflowId + " [" + status + "] - " + result.getReasonForIncompletion()); - } - } catch (Exception e) { - fail("Multi-agent chat error: " + (e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName())); - e.printStackTrace(); - } - } - - // ═══════════════════════════════════════════════════════════════════ - // HUMAN-IN-THE-LOOP CHAT WORKFLOW - // ═══════════════════════════════════════════════════════════════════ - - /** - * Human-in-the-loop interactive chat: workflow pauses at a WAIT task for user input. - * Mirrors the Python SDK llm_chat_human_in_loop.py example. - * In this automated test we simulate the user by updating the wait task externally. - */ - private void runHumanInLoopChatWorkflow() { - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName("llm_chat_human_in_loop"); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - workflow.setDescription("Human-in-the-loop chat using WAIT task for user input"); - - // Wait for user input - Wait userInput = new Wait("user_input_ref"); - - // Collect conversation history - SimpleTask collectHistoryTask = new SimpleTask("chat_collect_history", "collect_history_ref"); - collectHistoryTask.input("user_input", "${user_input_ref.output.question}"); - collectHistoryTask.input("history", "${chat_complete_ref.input.messages}"); - collectHistoryTask.input("assistant_response", "${chat_complete_ref.output.result}"); - collectHistoryTask.input("system_prompt", - "You are a helpful assistant that knows about science. " - + "Answer questions clearly and concisely."); - - // Chat completion - LlmChatComplete chatComplete = new LlmChatComplete("chat_llm", "chat_complete_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .messages("${collect_history_ref.output.result}") - .temperature(0.7) - .maxTokens(300); - - // Loop: wait -> collect -> respond (2 turns) - DoWhile chatLoop = new DoWhile("loop_ref", 2, userInput, collectHistoryTask, chatComplete); - - workflow.add(chatLoop); - workflow.registerWorkflow(true, true); - pass("Human-in-the-loop Chat workflow registered"); - - Map input = new HashMap<>(); - input.put("llmProvider", "openai"); - input.put("model", "gpt-4o-mini"); - - try { - // Start the workflow - it will pause at the first WAIT task - StartWorkflowRequest swReq = new StartWorkflowRequest(); - swReq.setName("llm_chat_human_in_loop"); - swReq.setVersion(1); - swReq.setInput(input); - String workflowId = workflowClient.startWorkflow(swReq); - pass("Workflow started: " + workflowId); - - // Simulate user responding to turn 1 - for (int turn = 1; turn <= 2; turn++) { - // Wait for the WAIT task to appear - // Inside a DoWhile loop the task ref gets suffixed with __1, __2, etc. - String taskRef = "user_input_ref__" + turn; - String question = (turn == 1) ? "What is photosynthesis?" : "How does it produce oxygen?"; - boolean resolved = waitAndUpdateWaitTask(workflowId, taskRef, question, 30); - if (!resolved) { - fail("Timed out waiting for WAIT task in turn " + turn); - break; - } - pass("Turn " + turn + ": submitted question: " + question); - Thread.sleep(3000); // give LLM time to respond - } - - // Wait for completion - long deadline = System.currentTimeMillis() + 90_000; - Workflow result = null; - while (System.currentTimeMillis() < deadline) { - result = workflowClient.getWorkflow(workflowId, false); - if (result.getStatus() != Workflow.WorkflowStatus.RUNNING) break; - Thread.sleep(2000); - } - - if (result != null) { - String status = result.getStatus().toString(); - executedWorkflows.add(new WorkflowExecution("llm_chat_human_in_loop", workflowId, status)); - if (result.getStatus() == Workflow.WorkflowStatus.COMPLETED) { - pass("Workflow completed: " + workflowId + " [" + status + "]"); - } else { - fail("Workflow did not complete: " + workflowId + " [" + status + "]"); - } - } - } catch (Exception e) { - fail("Human-in-loop chat error: " + (e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName())); - e.printStackTrace(); - } - } - - /** - * Wait for a WAIT task to be scheduled on a workflow, then complete it with user input. - */ - private boolean waitAndUpdateWaitTask(String workflowId, String taskRefName, String question, int timeoutSeconds) { - long deadline = System.currentTimeMillis() + (timeoutSeconds * 1000L); - while (System.currentTimeMillis() < deadline) { - try { - Workflow wf = workflowClient.getWorkflow(workflowId, true); - for (var task : wf.getTasks()) { - if (taskRefName.equals(task.getReferenceTaskName()) - && task.getStatus() == com.netflix.conductor.common.metadata.tasks.Task.Status.IN_PROGRESS) { - // Complete the WAIT task - com.netflix.conductor.common.metadata.tasks.TaskResult taskResult = - new com.netflix.conductor.common.metadata.tasks.TaskResult(task); - taskResult.setStatus(com.netflix.conductor.common.metadata.tasks.TaskResult.Status.COMPLETED); - taskResult.addOutputData("question", question); - taskClient.updateTask(taskResult); - return true; - } - } - Thread.sleep(1000); - } catch (Exception e) { - // retry - } - } - return false; - } - - // ═══════════════════════════════════════════════════════════════════ - // MCP WEATHER AGENT WORKFLOW - // ═══════════════════════════════════════════════════════════════════ - - /** - * MCP Weather Agent workflow: uses ListMcpTools + LLM planning + CallMcpTool. - * Mirrors the Python SDK mcp_weather_agent.py example. - */ - private void runMcpWeatherAgentWorkflow() { - String mcpServer = System.getenv().getOrDefault("MCP_SERVER_URL", "http://localhost:3001/mcp"); - - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName("mcp_ai_agent"); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - workflow.setDescription("AI agent using MCP tools for weather queries"); - - // Step 1: Discover available MCP tools (worker bridges to MCP server) - SimpleTask listTools = new SimpleTask("mcp_list_tools_worker", "discover_tools_ref"); - listTools.input("mcpServer", mcpServer); - - // Step 2: Ask LLM to plan which tool to use (returns JSON) - LlmChatComplete planTask = new LlmChatComplete("plan_action_llm", "plan_action_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .messages(List.of( - Map.of("role", "system", "message", - "You are an AI agent that can use tools to help users.\n\n" - + "Available tools:\n${discover_tools_ref.output.tools}\n\n" - + "User's request:\n${workflow.input.request}\n\n" - + "Decide which tool to use. Respond ONLY with this JSON:\n" - + "{\"method\": \"tool_name\", \"arguments\": {\"param\": \"value\"}, " - + "\"reasoning\": \"why you chose this tool\"}"), - Map.of("role", "user", "message", "What tool should I use?") - )) - .temperature(0.1) - .maxTokens(500) - .jsonOutput(true); - - // Step 3: Execute the selected tool via MCP (worker bridges to MCP server) - SimpleTask executeTool = new SimpleTask("mcp_call_tool_worker", "execute_tool_ref"); - executeTool.input("mcpServer", mcpServer); - executeTool.input("method", "${plan_action_ref.output.result.method}"); - executeTool.input("arguments", "${plan_action_ref.output.result.arguments}"); - - // Step 4: Summarize the result - LlmChatComplete summarizeTask = new LlmChatComplete("summarize_result_llm", "summarize_result_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .messages(List.of( - Map.of("role", "system", "message", - "You are a helpful assistant. Summarize the tool result.\n\n" - + "Original request: ${workflow.input.request}\n" - + "Tool used: ${plan_action_ref.output.result.method}\n" - + "Tool result: ${execute_tool_ref.output.content}\n\n" - + "Provide a natural, conversational response."), - Map.of("role", "user", "message", "Please summarize the result") - )) - .temperature(0.3) - .maxTokens(300); - - workflow.add(listTools); - workflow.add(planTask); - workflow.add(executeTool); - workflow.add(summarizeTask); - - workflow.setWorkflowOutput(Map.of( - "plan", "${plan_action_ref.output.result}", - "tool_result", "${execute_tool_ref.output.content}", - "summary", "${summarize_result_ref.output.result}" - )); - workflow.registerWorkflow(true, true); - pass("MCP Weather Agent workflow registered"); - - Map input = new HashMap<>(); - input.put("request", "What's the weather like in San Francisco?"); - input.put("llmProvider", "openai"); - input.put("model", "gpt-4o-mini"); - - try { - var run = workflow.execute(input); - Workflow result = run.get(120, TimeUnit.SECONDS); - - String workflowId = result.getWorkflowId(); - String status = result.getStatus().toString(); - executedWorkflows.add(new WorkflowExecution("mcp_ai_agent", workflowId, status)); - - if (result.getStatus() == Workflow.WorkflowStatus.COMPLETED) { - pass("Workflow executed: " + workflowId + " [" + status + "]"); - Object summary = result.getOutput().get("summary"); - if (summary != null) { - String summaryStr = summary.toString(); - if (summaryStr.length() > 120) summaryStr = summaryStr.substring(0, 120) + "..."; - pass("Agent response: " + summaryStr); - } - } else { - fail("Workflow failed: " + workflowId + " [" + status + "] - " + result.getReasonForIncompletion()); - } - } catch (Exception e) { - fail("MCP Weather Agent error: " + (e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName())); - e.printStackTrace(); - } - } - - // ═══════════════════════════════════════════════════════════════════ - // WORKER IMPLEMENTATIONS FOR NEW WORKFLOWS - // ═══════════════════════════════════════════════════════════════════ - - /** - * Collects conversation history for multi-turn chat. - * Appends assistant response and new user input to history list. - */ - @SuppressWarnings("unchecked") - private TaskResult executeChatCollectHistoryTask(Task task) { - TaskResult result = new TaskResult(task); - - String userInput = getStringOrNull(task.getInputData().get("user_input")); - String seedQuestion = getStringOrNull(task.getInputData().get("seed_question")); - String assistantResponse = getStringOrNull(task.getInputData().get("assistant_response")); - String systemPrompt = getStringOrNull(task.getInputData().get("system_prompt")); - Object historyObj = task.getInputData().get("history"); - - List> history = new ArrayList<>(); - - // Add system prompt as first message if provided and history is empty - if (historyObj instanceof List) { - for (Object item : (List) historyObj) { - if (item instanceof Map) { - Map msg = (Map) item; - if (msg.containsKey("role") && msg.containsKey("message")) { - history.add(Map.of("role", msg.get("role").toString(), "message", msg.get("message").toString())); - } - } - } - } - - // If history is empty and we have a system prompt, add it first - if (history.isEmpty() && systemPrompt != null && !systemPrompt.startsWith("$")) { - history.add(Map.of("role", "system", "message", systemPrompt)); - } - - if (assistantResponse != null && !assistantResponse.startsWith("$")) { - history.add(Map.of("role", "assistant", "message", assistantResponse)); - } - - if (userInput != null && !userInput.startsWith("$")) { - history.add(Map.of("role", "user", "message", userInput)); - } else if (seedQuestion != null && !seedQuestion.startsWith("$")) { - history.add(Map.of("role", "user", "message", seedQuestion)); - } - - result.setStatus(TaskResult.Status.COMPLETED); - result.addOutputData("result", history); - return result; - } - - /** - * Prepends a system prompt to conversation history for the moderator LLM. - */ - @SuppressWarnings("unchecked") - private TaskResult executeBuildModeratorMessagesTask(Task task) { - TaskResult result = new TaskResult(task); - - String systemPrompt = getStringOrNull(task.getInputData().get("system_prompt")); - Object historyObj = task.getInputData().get("history"); - - List> messages = new ArrayList<>(); - - if (systemPrompt != null && !systemPrompt.startsWith("$")) { - messages.add(Map.of("role", "system", "message", systemPrompt)); - } - - if (historyObj instanceof List) { - for (Object item : (List) historyObj) { - if (item instanceof Map) { - Map msg = (Map) item; - if (msg.containsKey("role") && msg.containsKey("message")) { - String msgText = msg.get("message").toString(); - if (!msgText.startsWith("$")) { - messages.add(Map.of("role", msg.get("role").toString(), "message", msgText)); - } - } - } - } - } - - result.setStatus(TaskResult.Status.COMPLETED); - result.addOutputData("result", messages); - return result; - } - - /** - * Appends moderator summary and agent response to the conversation history. - */ - @SuppressWarnings("unchecked") - private TaskResult executeUpdateMultiagentHistoryTask(Task task) { - TaskResult result = new TaskResult(task); - - Object historyObj = task.getInputData().get("history"); - String moderatorMessage = getStringOrNull(task.getInputData().get("moderator_message")); - String agentName = getStringOrNull(task.getInputData().get("agent_name")); - String agentResponse = getStringOrNull(task.getInputData().get("agent_response")); - - List> history = new ArrayList<>(); - - if (historyObj instanceof List) { - for (Object item : (List) historyObj) { - if (item instanceof Map) { - Map msg = (Map) item; - if (msg.containsKey("role") && msg.containsKey("message")) { - history.add(Map.of("role", msg.get("role").toString(), "message", msg.get("message").toString())); - } - } - } - } - - if (moderatorMessage != null && !moderatorMessage.startsWith("$")) { - history.add(Map.of("role", "assistant", "message", moderatorMessage)); - } - - if (agentResponse != null && !agentResponse.startsWith("$")) { - String prefix = (agentName != null && !agentName.startsWith("$")) ? "[" + agentName + "] " : ""; - history.add(Map.of("role", "user", "message", prefix + agentResponse)); - } - - result.setStatus(TaskResult.Status.COMPLETED); - result.addOutputData("result", history); - return result; - } - - /** Helper to safely get a String from a task input, returning null if not a String. */ - private String getStringOrNull(Object value) { - if (value instanceof String) return (String) value; - return null; - } - - // ═══════════════════════════════════════════════════════════════════ - // MCP WORKER IMPLEMENTATIONS - // ═══════════════════════════════════════════════════════════════════ - - /** - * MCP List Tools worker - calls the MCP server to discover available tools. - * Bridges to MCP server via HTTP for OSS Conductor (which lacks native MCP_LIST_TOOLS). - */ - private TaskResult executeMcpListToolsTask(Task task) { - TaskResult result = new TaskResult(task); - String mcpServer = (String) task.getInputData().getOrDefault("mcpServer", "http://localhost:3001/mcp"); - - try { - String responseBody = callMcpServer(mcpServer, "tools/list", Map.of()); - JsonNode json = parseSseResponse(responseBody); - JsonNode tools = json.path("result").path("tools"); - - // Convert tools to a list of simple maps for LLM consumption - List> toolList = new ArrayList<>(); - for (JsonNode tool : tools) { - Map t = new HashMap<>(); - t.put("name", tool.path("name").asText()); - t.put("description", tool.path("description").asText()); - JsonNode schema = tool.path("inputSchema"); - if (!schema.isMissingNode()) { - t.put("parameters", objectMapper.convertValue(schema, Map.class)); - } - toolList.add(t); - } - - result.setStatus(TaskResult.Status.COMPLETED); - result.addOutputData("tools", toolList); - result.addOutputData("toolCount", toolList.size()); - } catch (Exception e) { - result.setStatus(TaskResult.Status.FAILED); - result.setReasonForIncompletion("MCP list tools failed: " + e.getMessage()); - } - return result; - } - - /** - * MCP Call Tool worker - calls a specific tool on the MCP server. - * Bridges to MCP server via HTTP for OSS Conductor (which lacks native MCP_CALL_TOOL). - */ - @SuppressWarnings("unchecked") - private TaskResult executeMcpCallToolTask(Task task) { - TaskResult result = new TaskResult(task); - String mcpServer = (String) task.getInputData().getOrDefault("mcpServer", "http://localhost:3001/mcp"); - Object methodObj = task.getInputData().get("method"); - Object argsObj = task.getInputData().get("arguments"); - - String method = methodObj != null ? methodObj.toString() : ""; - Map arguments = Map.of(); - if (argsObj instanceof Map) { - arguments = (Map) argsObj; - } else if (argsObj instanceof String) { - try { - arguments = objectMapper.readValue((String) argsObj, Map.class); - } catch (Exception e) { - // use empty args - } - } - - if (method.isEmpty() || method.startsWith("$")) { - result.setStatus(TaskResult.Status.FAILED); - result.setReasonForIncompletion("No method specified for MCP call"); - return result; - } - - try { - Map params = new HashMap<>(); - params.put("name", method); - params.put("arguments", arguments); - - String responseBody = callMcpServer(mcpServer, "tools/call", params); - JsonNode json = parseSseResponse(responseBody); - JsonNode toolResult = json.path("result"); - - result.setStatus(TaskResult.Status.COMPLETED); - // Extract text content from the MCP response - JsonNode content = toolResult.path("content"); - if (content.isArray() && content.size() > 0) { - StringBuilder textContent = new StringBuilder(); - for (JsonNode item : content) { - if ("text".equals(item.path("type").asText())) { - textContent.append(item.path("text").asText()); - } - } - result.addOutputData("content", textContent.toString()); - } else { - result.addOutputData("content", objectMapper.writeValueAsString(toolResult)); - } - result.addOutputData("isError", toolResult.path("isError").asBoolean(false)); - result.addOutputData("raw", objectMapper.convertValue(toolResult, Map.class)); - } catch (Exception e) { - result.setStatus(TaskResult.Status.FAILED); - result.setReasonForIncompletion("MCP call tool failed: " + e.getMessage()); - } - return result; - } - - /** - * Make an HTTP call to the MCP server using JSON-RPC over SSE transport. - */ - private String callMcpServer(String mcpServer, String method, Map params) - throws IOException, InterruptedException { - Map requestBody = new HashMap<>(); - requestBody.put("jsonrpc", "2.0"); - requestBody.put("id", System.currentTimeMillis()); - requestBody.put("method", method); - requestBody.put("params", params); - - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(mcpServer)) - .header("Content-Type", "application/json") - .header("Accept", "application/json, text/event-stream") - .POST(HttpRequest.BodyPublishers.ofString(objectMapper.writeValueAsString(requestBody))) - .timeout(Duration.ofSeconds(30)) - .build(); - - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - - if (response.statusCode() >= 400) { - throw new IOException("MCP server error " + response.statusCode() + ": " + response.body()); - } - return response.body(); - } - - /** - * Parse SSE (Server-Sent Events) response from MCP server. - * MCP responses are formatted as: "event: message\ndata: {json}\n\n" - */ - private JsonNode parseSseResponse(String sseBody) throws IOException { - // Parse SSE format: lines starting with "data: " contain the JSON - for (String line : sseBody.split("\n")) { - if (line.startsWith("data: ")) { - String jsonData = line.substring(6).trim(); - return objectMapper.readTree(jsonData); - } - } - // Try to parse directly as JSON (non-SSE response) - return objectMapper.readTree(sseBody); - } -} diff --git a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/FunctionCallingExample.java b/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/FunctionCallingExample.java deleted file mode 100644 index c3dec3dd6..000000000 --- a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/FunctionCallingExample.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright 2024 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 io.orkes.conductor.sdk.examples.agentic; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.conductoross.conductor.sdk.ai.LlmChatComplete; -import org.conductoross.conductor.sdk.ai.ToolSpec; - -import com.netflix.conductor.client.http.ConductorClient; -import com.netflix.conductor.common.run.Workflow; -import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; -import com.netflix.conductor.sdk.workflow.def.tasks.SimpleTask; -import com.netflix.conductor.sdk.workflow.def.tasks.Switch; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -/** - * Example demonstrating LLM function calling with Conductor. - *

- * This example shows how an LLM can dynamically select which tool/function to call - * based on user queries. The workflow: - *

    - *
  • Receives a user query
  • - *
  • LLM analyzes the query and decides which function to call
  • - *
  • A SWITCH task routes to the appropriate worker based on LLM's decision
  • - *
  • The worker executes and returns results
  • - *
  • LLM formats the final response
  • - *
- * - *

This pattern is the foundation for building AI agents that can: - *

    - *
  • Call APIs dynamically
  • - *
  • Execute code
  • - *
  • Query databases
  • - *
  • Interact with external systems
  • - *
- * - *

Usage: - *

- * ./gradlew :examples:run -PmainClass=io.orkes.conductor.sdk.examples.agentic.FunctionCallingExample
- * 
- */ -public class FunctionCallingExample { - - private static final String WORKFLOW_NAME = "llm_function_calling"; - private static final String LLM_PROVIDER = "openai"; - private static final String MODEL = "gpt-4o-mini"; - - public static void main(String[] args) { - String query = args.length > 0 ? String.join(" ", args) : "What's the weather like in San Francisco?"; - - System.out.println("Starting LLM Function Calling Example"); - System.out.println("Query: " + query); - System.out.println(); - - // Initialize Conductor client - ConductorClient client = ClientUtil.getClient(); - WorkflowExecutor executor = new WorkflowExecutor(client, 10); - - try { - // Initialize workers for the functions - executor.initWorkers("io.orkes.conductor.sdk.examples.agentic.workers"); - - // Create and register the workflow - ConductorWorkflow> workflow = createFunctionCallingWorkflow(executor); - workflow.registerWorkflow(true, true); - System.out.println("Workflow registered: " + WORKFLOW_NAME); - - // Execute the workflow - Map input = new HashMap<>(); - input.put("query", query); - input.put("llmProvider", LLM_PROVIDER); - input.put("model", MODEL); - - var workflowRun = workflow.execute(input); - Workflow result = workflowRun.get(60, TimeUnit.SECONDS); - - System.out.println("\n=== Execution Complete ==="); - System.out.println("Status: " + result.getStatus()); - System.out.println("\nFinal Response:"); - System.out.println(result.getOutput().get("response")); - - } catch (Exception e) { - System.err.println("Error executing workflow: " + e.getMessage()); - e.printStackTrace(); - } finally { - executor.shutdown(); - } - } - - /** - * Creates a workflow that uses LLM to decide which function to call. - */ - private static ConductorWorkflow> createFunctionCallingWorkflow(WorkflowExecutor executor) { - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName(WORKFLOW_NAME); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - workflow.setDescription("LLM function calling with dynamic tool selection"); - - // Define available tools/functions using ToolSpec - List tools = new ArrayList<>(); - tools.add(new ToolSpec() - .name("get_weather") - .type("SIMPLE") - .description("Get the current weather for a location") - .inputSchema(Map.of( - "type", "object", - "properties", Map.of( - "location", Map.of("type", "string", "description", "City and state/country") - ), - "required", List.of("location") - ))); - tools.add(new ToolSpec() - .name("search_web") - .type("SIMPLE") - .description("Search the web for information") - .inputSchema(Map.of( - "type", "object", - "properties", Map.of( - "query", Map.of("type", "string", "description", "Search query") - ), - "required", List.of("query") - ))); - tools.add(new ToolSpec() - .name("calculate") - .type("SIMPLE") - .description("Perform mathematical calculations") - .inputSchema(Map.of( - "type", "object", - "properties", Map.of( - "expression", Map.of("type", "string", "description", "Math expression to evaluate") - ), - "required", List.of("expression") - ))); - - // Step 1: LLM decides which function to call - LlmChatComplete functionSelector = new LlmChatComplete("select_function", "selector_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .messages(List.of( - Map.of("role", "system", "content", - "You are a helpful assistant that selects the appropriate function to answer user queries. " + - "Analyze the user's request and call the most appropriate function."), - Map.of("role", "user", "content", "${workflow.input.query}") - )) - .tools(tools) - .temperature(0.0); - - workflow.add(functionSelector); - - // Step 2: Switch based on which function was selected - Switch functionRouter = new Switch("router_ref", - "${selector_ref.output.toolCalls[0].function.name}"); - - // Weather function worker - SimpleTask weatherTask = new SimpleTask("get_weather", "weather_ref"); - weatherTask.input("location", "${selector_ref.output.toolCalls[0].function.arguments.location}"); - functionRouter.switchCase("get_weather", weatherTask); - - // Web search function worker - SimpleTask searchTask = new SimpleTask("search_web", "search_ref"); - searchTask.input("query", "${selector_ref.output.toolCalls[0].function.arguments.query}"); - functionRouter.switchCase("search_web", searchTask); - - // Calculator function worker - SimpleTask calcTask = new SimpleTask("calculate", "calc_ref"); - calcTask.input("expression", "${selector_ref.output.toolCalls[0].function.arguments.expression}"); - functionRouter.switchCase("calculate", calcTask); - - // Default case - direct response without function call - SimpleTask defaultTask = new SimpleTask("direct_response", "default_ref"); - defaultTask.input("query", "${workflow.input.query}"); - functionRouter.defaultCase(defaultTask); - - workflow.add(functionRouter); - - // Step 3: LLM formats the final response - LlmChatComplete responseFormatter = new LlmChatComplete("format_response", "formatter_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .messages(List.of( - Map.of("role", "system", "content", - "Format the function result into a helpful, natural language response for the user."), - Map.of("role", "user", "content", "Original query: ${workflow.input.query}"), - Map.of("role", "assistant", "content", "I called a function to help answer your query."), - Map.of("role", "function", "name", "${selector_ref.output.toolCalls[0].function.name}", - "content", "${router_ref.output.result}") - )) - .temperature(0.7) - .maxTokens(300); - - workflow.add(responseFormatter); - - // Set output - Map outputParams = new HashMap<>(); - outputParams.put("response", "${formatter_ref.output.result}"); - outputParams.put("functionCalled", "${selector_ref.output.toolCalls[0].function.name}"); - outputParams.put("functionArgs", "${selector_ref.output.toolCalls[0].function.arguments}"); - workflow.setWorkflowOutput(outputParams); - - return workflow; - } - -} diff --git a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/HumanInLoopChatExample.java b/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/HumanInLoopChatExample.java deleted file mode 100644 index e423974c8..000000000 --- a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/HumanInLoopChatExample.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright 2024 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 io.orkes.conductor.sdk.examples.agentic; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Scanner; - -import org.conductoross.conductor.sdk.ai.LlmChatComplete; - -import com.netflix.conductor.client.http.ConductorClient; -import com.netflix.conductor.client.http.TaskClient; -import com.netflix.conductor.client.http.WorkflowClient; -import com.netflix.conductor.common.metadata.tasks.TaskResult; -import com.netflix.conductor.common.run.Workflow; -import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; -import com.netflix.conductor.sdk.workflow.def.tasks.DoWhile; -import com.netflix.conductor.sdk.workflow.def.tasks.SetVariable; -import com.netflix.conductor.sdk.workflow.def.tasks.Wait; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -import io.orkes.conductor.client.http.OrkesPromptClient; -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -/** - * Example demonstrating interactive human-in-the-loop chat with an LLM. - *

- * This example creates a workflow where: - *

    - *
  • A WAIT task pauses for human input
  • - *
  • The LLM processes the human's message and responds
  • - *
  • The conversation continues until the user types "quit"
  • - *
- * - *

The WAIT task allows external signals to provide input, making this - * perfect for interactive chatbot applications where human input is needed. - * - *

Prerequisites: - *

    - *
  • Conductor server running with AI/LLM integration configured
  • - *
  • OpenAI (or other LLM provider) integration set up in Conductor
  • - *
- * - *

Usage: - *

- * ./gradlew :examples:run -PmainClass=io.orkes.conductor.sdk.examples.agentic.HumanInLoopChatExample
- * 
- */ -public class HumanInLoopChatExample { - - private static final String WORKFLOW_NAME = "human_in_loop_chat"; - private static final String LLM_PROVIDER = "openai"; - private static final String MODEL = "gpt-4o-mini"; - private static final int MAX_TURNS = 10; - - public static void main(String[] args) { - System.out.println("Starting Human-in-the-Loop Chat Example"); - System.out.println("Type your messages and press Enter. Type 'quit' to exit.\n"); - - // Initialize Conductor client - ConductorClient client = ClientUtil.getClient(); - WorkflowExecutor executor = new WorkflowExecutor(client, 10); - WorkflowClient workflowClient = new WorkflowClient(client); - TaskClient taskClient = new TaskClient(client); - - try { - // Register prompt - registerPrompt(client); - - // Create and register the workflow - ConductorWorkflow> workflow = createChatWorkflow(executor); - workflow.registerWorkflow(true, true); - System.out.println("Workflow registered: " + WORKFLOW_NAME); - - // Start the workflow - Map input = new HashMap<>(); - input.put("llmProvider", LLM_PROVIDER); - input.put("model", MODEL); - input.put("systemPrompt", "You are a helpful, friendly AI assistant. Be concise in your responses."); - - String workflowId = workflow.startDynamic(input); - System.out.println("Started workflow: " + workflowId); - System.out.println("\n=== Chat Started ===\n"); - - // Interactive chat loop - Scanner scanner = new Scanner(System.in); - List> conversationHistory = new ArrayList<>(); - - for (int turn = 0; turn < MAX_TURNS; turn++) { - // Wait for the workflow to reach the WAIT task - Workflow wf = waitForWaitTask(workflowClient, workflowId); - - if (wf.getStatus() != Workflow.WorkflowStatus.RUNNING) { - System.out.println("Workflow ended with status: " + wf.getStatus()); - break; - } - - // Get user input - System.out.print("\nYou: "); - String userInput = scanner.nextLine().trim(); - - if ("quit".equalsIgnoreCase(userInput)) { - System.out.println("\nEnding conversation..."); - workflowClient.terminateWorkflow(workflowId, "User requested quit"); - break; - } - - // Add user message to history - Map userMessage = new HashMap<>(); - userMessage.put("role", "user"); - userMessage.put("content", userInput); - conversationHistory.add(userMessage); - - // Find the WAIT task and complete it with user input - completeWaitTask(taskClient, wf, userInput, conversationHistory); - - // Wait for LLM response - Thread.sleep(1000); // Give time for the LLM task to process - - wf = workflowClient.getWorkflow(workflowId, true); - - // Get the assistant's response from workflow variables or task output - String assistantResponse = getAssistantResponse(wf); - if (assistantResponse != null) { - System.out.println("\nAssistant: " + assistantResponse); - - Map assistantMessage = new HashMap<>(); - assistantMessage.put("role", "assistant"); - assistantMessage.put("content", assistantResponse); - conversationHistory.add(assistantMessage); - } - } - - System.out.println("\n=== Chat Ended ==="); - - } catch (Exception e) { - System.err.println("Error: " + e.getMessage()); - e.printStackTrace(); - } finally { - executor.shutdown(); - } - } - - /** - * Creates an interactive chat workflow with WAIT tasks for human input. - */ - private static ConductorWorkflow> createChatWorkflow(WorkflowExecutor executor) { - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName(WORKFLOW_NAME); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - workflow.setDescription("Interactive chat with human-in-the-loop using WAIT tasks"); - - // Initialize conversation state - Map initialVariables = new HashMap<>(); - initialVariables.put("conversationHistory", new ArrayList<>()); - initialVariables.put("turnCount", 0); - initialVariables.put("shouldContinue", true); - workflow.setVariables(initialVariables); - - // WAIT task for human input - Wait waitForInput = new Wait("wait_for_input_ref"); - waitForInput.input("waitType", "signal"); - - // Process user input and update state - SetVariable processInput = new SetVariable("process_input_ref"); - processInput.input("userMessage", "${wait_for_input_ref.output.userMessage}"); - processInput.input("turnCount", "${workflow.variables.turnCount + 1}"); - - // LLM chat task - LlmChatComplete chatTask = new LlmChatComplete("chat_llm", "chat_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .messages("${workflow.variables.conversationHistory}") - .temperature(0.7) - .maxTokens(500); - - // Update conversation history with response - SetVariable updateHistory = new SetVariable("update_history_ref"); - updateHistory.input("lastResponse", "${chat_ref.output.result}"); - - // DO_WHILE loop for conversation turns - DoWhile chatLoop = new DoWhile( - "chat_loop_ref", - MAX_TURNS, - waitForInput, processInput, chatTask, updateHistory - ); - - workflow.add(chatLoop); - - // Set output - Map outputParams = new HashMap<>(); - outputParams.put("conversationHistory", "${workflow.variables.conversationHistory}"); - outputParams.put("totalTurns", "${workflow.variables.turnCount}"); - workflow.setWorkflowOutput(outputParams); - - return workflow; - } - - /** - * Waits for the workflow to reach a WAIT task. - */ - private static Workflow waitForWaitTask(WorkflowClient workflowClient, String workflowId) throws InterruptedException { - while (true) { - Workflow wf = workflowClient.getWorkflow(workflowId, true); - - if (wf.getStatus() != Workflow.WorkflowStatus.RUNNING) { - return wf; - } - - // Check if there's a WAIT task in progress - boolean hasWaitTask = wf.getTasks().stream() - .anyMatch(t -> "WAIT".equals(t.getTaskType()) && - t.getStatus() == com.netflix.conductor.common.metadata.tasks.Task.Status.IN_PROGRESS); - - if (hasWaitTask) { - return wf; - } - - Thread.sleep(500); - } - } - - /** - * Completes the WAIT task with user input. - */ - private static void completeWaitTask(TaskClient taskClient, Workflow wf, - String userInput, List> history) { - wf.getTasks().stream() - .filter(t -> "WAIT".equals(t.getTaskType()) && - t.getStatus() == com.netflix.conductor.common.metadata.tasks.Task.Status.IN_PROGRESS) - .findFirst() - .ifPresent(task -> { - TaskResult result = new TaskResult(task); - result.setStatus(TaskResult.Status.COMPLETED); - result.addOutputData("userMessage", userInput); - result.addOutputData("conversationHistory", history); - taskClient.updateTask(result); - }); - } - - /** - * Extracts the assistant's response from the workflow. - */ - private static String getAssistantResponse(Workflow wf) { - // Try to get from the last completed LLM task - return wf.getTasks().stream() - .filter(t -> "LLM_CHAT_COMPLETE".equals(t.getTaskType()) && - t.getStatus() == com.netflix.conductor.common.metadata.tasks.Task.Status.COMPLETED) - .reduce((first, second) -> second) // Get last one - .map(t -> { - Object result = t.getOutputData().get("result"); - return result != null ? result.toString() : null; - }) - .orElse(null); - } - - /** - * Registers the prompt template. - */ - private static void registerPrompt(ConductorClient client) { - OrkesPromptClient promptClient = new OrkesPromptClient(client); - - String chatPrompt = "You are a helpful AI assistant.\n\n" + - "System: {{systemPrompt}}\n\n" + - "Conversation so far:\n{{conversationHistory}}\n\n" + - "Respond to the user's latest message thoughtfully and helpfully."; - - try { - promptClient.savePrompt("chat-assistant-prompt", - "Prompt for interactive chat assistant", chatPrompt); - System.out.println("Registered prompt: chat-assistant-prompt"); - } catch (Exception e) { - System.out.println("Prompt may already exist: " + e.getMessage()); - } - } -} diff --git a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/LlmChatExample.java b/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/LlmChatExample.java deleted file mode 100644 index 4b5cef14e..000000000 --- a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/LlmChatExample.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Copyright 2024 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 io.orkes.conductor.sdk.examples.agentic; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.conductoross.conductor.sdk.ai.LlmChatComplete; - -import com.netflix.conductor.client.http.ConductorClient; -import com.netflix.conductor.common.run.Workflow; -import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; -import com.netflix.conductor.sdk.workflow.def.tasks.DoWhile; -import com.netflix.conductor.sdk.workflow.def.tasks.SetVariable; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -import io.orkes.conductor.client.http.OrkesPromptClient; -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -/** - * Example demonstrating automated multi-turn Q&A between two LLMs. - *

- * This example creates a workflow where: - *

    - *
  • An "asker" LLM generates questions on a topic
  • - *
  • An "answerer" LLM provides responses
  • - *
  • The conversation continues for a specified number of turns
  • - *
- * - *

Prerequisites: - *

    - *
  • Conductor server running with AI/LLM integration configured
  • - *
  • OpenAI (or other LLM provider) integration set up in Conductor
  • - *
  • Prompt templates registered for asker and answerer roles
  • - *
- * - *

Environment variables: - *

    - *
  • CONDUCTOR_SERVER_URL - Conductor server URL (default: http://localhost:8080/api)
  • - *
  • CONDUCTOR_AUTH_KEY - Authentication key (for Orkes Conductor)
  • - *
  • CONDUCTOR_AUTH_SECRET - Authentication secret (for Orkes Conductor)
  • - *
- * - *

Usage: - *

- * # Run with default topic
- * ./gradlew :examples:run -PmainClass=io.orkes.conductor.sdk.examples.agentic.LlmChatExample
- * 
- * # Run with custom topic
- * ./gradlew :examples:run -PmainClass=io.orkes.conductor.sdk.examples.agentic.LlmChatExample --args="quantum computing"
- * 
- */ -public class LlmChatExample { - - private static final String WORKFLOW_NAME = "llm_multi_turn_chat"; - private static final String LLM_PROVIDER = "openai"; - private static final String MODEL = "gpt-4o-mini"; - private static final int MAX_TURNS = 3; - - public static void main(String[] args) { - String topic = args.length > 0 ? String.join(" ", args) : "artificial intelligence"; - - System.out.println("Starting LLM Multi-Turn Chat Example"); - System.out.println("Topic: " + topic); - System.out.println("Max turns: " + MAX_TURNS); - System.out.println(); - - // Initialize Conductor client - ConductorClient client = ClientUtil.getClient(); - WorkflowExecutor executor = new WorkflowExecutor(client, 10); - - try { - // Register prompts for the conversation - registerPrompts(client); - - // Create and register the workflow - ConductorWorkflow> workflow = createChatWorkflow(executor); - workflow.registerWorkflow(true, true); - System.out.println("Workflow registered: " + WORKFLOW_NAME); - - // Execute the workflow - Map input = new HashMap<>(); - input.put("topic", topic); - input.put("maxTurns", MAX_TURNS); - input.put("llmProvider", LLM_PROVIDER); - input.put("model", MODEL); - - var workflowRun = workflow.execute(input); - Workflow result = workflowRun.get(120, TimeUnit.SECONDS); - - System.out.println("\n=== Conversation Complete ==="); - System.out.println("Status: " + result.getStatus()); - - // Print the conversation history from output - Object historyObj = result.getOutput().get("conversationHistory"); - if (historyObj instanceof List) { - @SuppressWarnings("unchecked") - List> history = (List>) historyObj; - System.out.println("\n=== Conversation History ==="); - for (Map message : history) { - System.out.println("\n[" + message.get("role").toUpperCase() + "]"); - System.out.println(message.get("content")); - } - } - - } catch (Exception e) { - System.err.println("Error executing workflow: " + e.getMessage()); - e.printStackTrace(); - } finally { - executor.shutdown(); - } - } - - /** - * Creates a multi-turn chat workflow using LLM tasks. - *

- * The workflow uses a DO_WHILE loop to continue the conversation - * for the specified number of turns. - */ - private static ConductorWorkflow> createChatWorkflow(WorkflowExecutor executor) { - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName(WORKFLOW_NAME); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - workflow.setDescription("Multi-turn chat between two LLMs demonstrating agentic conversation patterns"); - - // Initialize conversation state using workflow variables - Map initialVariables = new HashMap<>(); - initialVariables.put("conversationHistory", new ArrayList<>()); - initialVariables.put("turnCount", 0); - workflow.setVariables(initialVariables); - - // Initialize state task - SetVariable initState = new SetVariable("init_state_ref"); - initState.input("topic", "${workflow.input.topic}"); - workflow.add(initState); - - // Create the asker LLM task - generates questions - LlmChatComplete askerTask = new LlmChatComplete("asker_llm", "asker_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .instructions("asker-prompt") - .promptVariables(Map.of( - "topic", "${workflow.variables.topic}", - "conversationHistory", "${workflow.variables.conversationHistory}" - )) - .temperature(0.8) - .maxTokens(200); - - // Update state with asker's question - SetVariable updateAfterAsker = new SetVariable("update_asker_ref"); - updateAfterAsker.input("lastQuestion", "${asker_ref.output.result}"); - - // Create the answerer LLM task - provides responses - LlmChatComplete answererTask = new LlmChatComplete("answerer_llm", "answerer_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .instructions("answerer-prompt") - .promptVariables(Map.of( - "question", "${workflow.variables.lastQuestion}", - "conversationHistory", "${workflow.variables.conversationHistory}" - )) - .temperature(0.7) - .maxTokens(500); - - // Update state with answerer's response and increment turn count - SetVariable updateAfterAnswerer = new SetVariable("update_answerer_ref"); - updateAfterAnswerer.input("turnCount", "${workflow.variables.turnCount + 1}"); - - // Create DO_WHILE loop for multi-turn conversation - DoWhile conversationLoop = new DoWhile( - "loop_ref", - "if ( $.loop_ref['iteration'] < " + MAX_TURNS + ") { true; } else { false; }", - askerTask, updateAfterAsker, answererTask, updateAfterAnswerer - ); - - workflow.add(conversationLoop); - - // Set final output - Map outputParams = new HashMap<>(); - outputParams.put("conversationHistory", "${workflow.variables.conversationHistory}"); - outputParams.put("totalTurns", "${workflow.variables.turnCount}"); - outputParams.put("topic", "${workflow.input.topic}"); - workflow.setWorkflowOutput(outputParams); - - return workflow; - } - - /** - * Registers prompt templates required for the chat workflow. - *

- * In a production environment, these would typically be managed - * separately and not registered during workflow execution. - */ - private static void registerPrompts(ConductorClient client) { - OrkesPromptClient promptClient = new OrkesPromptClient(client); - - // Asker prompt - generates questions on the topic - String askerPrompt = "You are a curious learner having a conversation about {{topic}}.\n" + - "Based on the conversation history so far, ask an insightful follow-up question.\n" + - "If this is the start of the conversation, ask an introductory question about the topic.\n\n" + - "Conversation history:\n{{conversationHistory}}\n\n" + - "Ask your next question (be concise, 1-2 sentences):"; - - try { - promptClient.savePrompt("asker-prompt", "Prompt for generating questions in multi-turn chat", askerPrompt); - System.out.println("Registered prompt: asker-prompt"); - } catch (Exception e) { - System.out.println("Prompt 'asker-prompt' may already exist: " + e.getMessage()); - } - - // Answerer prompt - provides knowledgeable responses - String answererPrompt = "You are a knowledgeable expert having a conversation.\n" + - "Answer the following question thoughtfully and informatively.\n" + - "Keep your response focused and under 3 paragraphs.\n\n" + - "Conversation history:\n{{conversationHistory}}\n\n" + - "Question: {{question}}\n\n" + - "Your response:"; - - try { - promptClient.savePrompt("answerer-prompt", "Prompt for generating answers in multi-turn chat", answererPrompt); - System.out.println("Registered prompt: answerer-prompt"); - } catch (Exception e) { - System.out.println("Prompt 'answerer-prompt' may already exist: " + e.getMessage()); - } - } -} diff --git a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/RagWorkflowExample.java b/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/RagWorkflowExample.java deleted file mode 100644 index 7efbe9460..000000000 --- a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/RagWorkflowExample.java +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Copyright 2024 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 io.orkes.conductor.sdk.examples.agentic; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.conductoross.conductor.sdk.ai.LlmChatComplete; -import org.conductoross.conductor.sdk.ai.LlmIndexText; -import org.conductoross.conductor.sdk.ai.LlmSearchIndex; - -import com.netflix.conductor.client.http.ConductorClient; -import com.netflix.conductor.common.run.Workflow; -import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -import io.orkes.conductor.client.http.OrkesPromptClient; -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -/** - * Example demonstrating a Retrieval-Augmented Generation (RAG) pipeline with Conductor. - *

- * RAG combines document retrieval with LLM generation to provide accurate, - * grounded responses. This example shows: - *

    - *
  • Document indexing - Converting documents to embeddings and storing in vector DB
  • - *
  • Semantic search - Finding relevant documents based on user queries
  • - *
  • Answer generation - Using retrieved context to generate accurate responses
  • - *
- * - *

Prerequisites: - *

    - *
  • Conductor server with AI/LLM integrations configured
  • - *
  • Vector database integration (Pinecone, Weaviate, pgvector, etc.)
  • - *
  • Embedding model integration (OpenAI, Cohere, etc.)
  • - *
  • LLM integration for answer generation
  • - *
- * - *

Usage: - *

- * # Index documents and answer questions
- * ./gradlew :examples:run -PmainClass=io.orkes.conductor.sdk.examples.agentic.RagWorkflowExample
- * 
- */ -public class RagWorkflowExample { - - private static final String INDEX_WORKFLOW = "rag_index_documents"; - private static final String QUERY_WORKFLOW = "rag_query"; - private static final String LLM_PROVIDER = "openai"; - private static final String EMBEDDING_MODEL = "text-embedding-ada-002"; - private static final String CHAT_MODEL = "gpt-4o-mini"; - private static final String VECTOR_DB = "pinecone"; - private static final String INDEX_NAME = "knowledge-base"; - private static final String NAMESPACE = "rag-demo"; - - public static void main(String[] args) { - System.out.println("Starting RAG Workflow Example"); - System.out.println(); - - // Initialize Conductor client - ConductorClient client = ClientUtil.getClient(); - WorkflowExecutor executor = new WorkflowExecutor(client, 10); - - try { - // Register prompts - registerPrompts(client); - - // Create and register workflows - ConductorWorkflow> indexWorkflow = createIndexingWorkflow(executor); - indexWorkflow.registerWorkflow(true, true); - System.out.println("Registered: " + INDEX_WORKFLOW); - - ConductorWorkflow> queryWorkflow = createQueryWorkflow(executor); - queryWorkflow.registerWorkflow(true, true); - System.out.println("Registered: " + QUERY_WORKFLOW); - - // Index some sample documents - System.out.println("\n=== Indexing Documents ==="); - indexSampleDocuments(indexWorkflow); - - // Query the knowledge base - System.out.println("\n=== Querying Knowledge Base ==="); - String question = args.length > 0 ? String.join(" ", args) : - "What are the key features of Conductor?"; - - Map queryInput = new HashMap<>(); - queryInput.put("question", question); - queryInput.put("llmProvider", LLM_PROVIDER); - queryInput.put("embeddingModel", EMBEDDING_MODEL); - queryInput.put("chatModel", CHAT_MODEL); - queryInput.put("vectorDb", VECTOR_DB); - queryInput.put("index", INDEX_NAME); - queryInput.put("namespace", NAMESPACE); - queryInput.put("topK", 3); - - System.out.println("Question: " + question); - - var queryRun = queryWorkflow.execute(queryInput); - Workflow result = queryRun.get(60, TimeUnit.SECONDS); - - System.out.println("\nStatus: " + result.getStatus()); - System.out.println("\n=== Answer ==="); - System.out.println(result.getOutput().get("answer")); - - System.out.println("\n=== Sources Used ==="); - @SuppressWarnings("unchecked") - List> sources = (List>) result.getOutput().get("sources"); - if (sources != null) { - for (int i = 0; i < sources.size(); i++) { - Map source = sources.get(i); - System.out.println((i + 1) + ". " + source.get("title")); - } - } - - } catch (Exception e) { - System.err.println("Error: " + e.getMessage()); - e.printStackTrace(); - } finally { - executor.shutdown(); - } - } - - /** - * Creates a workflow for indexing documents into the vector database. - */ - private static ConductorWorkflow> createIndexingWorkflow(WorkflowExecutor executor) { - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName(INDEX_WORKFLOW); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - workflow.setDescription("Index documents into vector database for RAG"); - - // Index document task - LlmIndexText indexTask = new LlmIndexText("index_document", "index_ref") - .vectorDb("${workflow.input.vectorDb}") - .namespace("${workflow.input.namespace}") - .index("${workflow.input.index}") - .embeddingModelProvider("${workflow.input.llmProvider}") - .embeddingModel("${workflow.input.embeddingModel}") - .text("${workflow.input.documentText}") - .docId("${workflow.input.documentId}") - .metadata("${workflow.input.metadata}") - .chunkSize(500) - .chunkOverlap(50); - - workflow.add(indexTask); - - // Set output - Map outputParams = new HashMap<>(); - outputParams.put("documentId", "${workflow.input.documentId}"); - outputParams.put("status", "indexed"); - outputParams.put("chunksCreated", "${index_ref.output.chunksCreated}"); - workflow.setWorkflowOutput(outputParams); - - return workflow; - } - - /** - * Creates a workflow for querying the knowledge base and generating answers. - */ - private static ConductorWorkflow> createQueryWorkflow(WorkflowExecutor executor) { - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName(QUERY_WORKFLOW); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - workflow.setDescription("Query knowledge base and generate RAG response"); - - // Step 1: Search vector database for relevant documents - LlmSearchIndex searchTask = new LlmSearchIndex("search_knowledge", "search_ref") - .vectorDb("${workflow.input.vectorDb}") - .namespace("${workflow.input.namespace}") - .index("${workflow.input.index}") - .embeddingModelProvider("${workflow.input.llmProvider}") - .embeddingModel("${workflow.input.embeddingModel}") - .query("${workflow.input.question}") - .maxResults(5); - - workflow.add(searchTask); - - // Step 2: Generate answer using retrieved context - LlmChatComplete generateAnswer = new LlmChatComplete("generate_answer", "answer_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.chatModel}") - .instructions("rag-answer-prompt") - .promptVariables(Map.of( - "question", "${workflow.input.question}", - "context", "${search_ref.output.results}" - )) - .temperature(0.3) - .maxTokens(500); - - workflow.add(generateAnswer); - - // Set output - Map outputParams = new HashMap<>(); - outputParams.put("answer", "${answer_ref.output.result}"); - outputParams.put("sources", "${search_ref.output.results}"); - outputParams.put("question", "${workflow.input.question}"); - workflow.setWorkflowOutput(outputParams); - - return workflow; - } - - /** - * Index sample documents about Conductor. - */ - private static void indexSampleDocuments(ConductorWorkflow> indexWorkflow) - throws Exception { - List> documents = List.of( - Map.of( - "id", "doc-1", - "title", "Conductor Overview", - "text", "Conductor is a platform for orchestrating microservices and managing workflows. " + - "It provides visibility and control over workflows, with features like automatic retries, " + - "rate limiting, and comprehensive monitoring. Conductor was originally developed at Netflix " + - "and is now an open-source project." - ), - Map.of( - "id", "doc-2", - "title", "Conductor Workers", - "text", "Workers in Conductor are responsible for executing tasks. They poll the Conductor " + - "server for tasks, execute them, and report results back. Workers can be written in any " + - "language and can run anywhere - in containers, VMs, or serverless functions. Workers " + - "are stateless and can be scaled horizontally." - ), - Map.of( - "id", "doc-3", - "title", "Conductor AI Features", - "text", "Conductor supports AI-native workflows including LLM integration, RAG pipelines, " + - "and agentic workflows. You can build AI agents where LLMs dynamically select tools, " + - "create multi-turn conversations, and implement retrieval-augmented generation for " + - "knowledge-grounded responses." - ) - ); - - for (Map doc : documents) { - Map input = new HashMap<>(); - input.put("documentId", doc.get("id")); - input.put("documentText", doc.get("text")); - input.put("metadata", Map.of("title", doc.get("title"))); - input.put("llmProvider", LLM_PROVIDER); - input.put("embeddingModel", EMBEDDING_MODEL); - input.put("vectorDb", VECTOR_DB); - input.put("index", INDEX_NAME); - input.put("namespace", NAMESPACE); - - try { - var run = indexWorkflow.execute(input); - Workflow result = run.get(30, TimeUnit.SECONDS); - System.out.println("Indexed: " + doc.get("title") + " - " + result.getStatus()); - } catch (Exception e) { - System.out.println("Failed to index " + doc.get("title") + ": " + e.getMessage()); - } - } - } - - /** - * Registers prompt templates. - */ - private static void registerPrompts(ConductorClient client) { - OrkesPromptClient promptClient = new OrkesPromptClient(client); - - String ragPrompt = "You are a helpful assistant that answers questions based on the provided context.\n\n" + - "Context from knowledge base:\n{{context}}\n\n" + - "Question: {{question}}\n\n" + - "Instructions:\n" + - "- Answer based ONLY on the provided context\n" + - "- If the context doesn't contain enough information, say so\n" + - "- Be concise and accurate\n" + - "- Cite which document(s) you used in your answer\n\n" + - "Answer:"; - - try { - promptClient.savePrompt("rag-answer-prompt", - "Prompt for RAG answer generation", ragPrompt); - System.out.println("Registered prompt: rag-answer-prompt"); - } catch (Exception e) { - System.out.println("Prompt may already exist: " + e.getMessage()); - } - } -} diff --git a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/VectorDbExample.java b/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/VectorDbExample.java deleted file mode 100644 index 81c56cfe1..000000000 --- a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/agentic/VectorDbExample.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright 2024 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 io.orkes.conductor.sdk.examples.agentic; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.conductoross.conductor.sdk.ai.LlmGenerateEmbeddings; -import org.conductoross.conductor.sdk.ai.LlmIndexText; -import org.conductoross.conductor.sdk.ai.LlmSearchIndex; - -import com.netflix.conductor.client.http.ConductorClient; -import com.netflix.conductor.common.run.Workflow; -import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -import io.orkes.conductor.sdk.examples.util.ClientUtil; - -/** - * Example demonstrating vector database operations with Conductor. - *

- * This example shows the fundamental vector database operations: - *

    - *
  • Text to embedding conversion
  • - *
  • Storing embeddings in a vector database
  • - *
  • Semantic similarity search
  • - *
- * - *

These operations are the building blocks for: - *

    - *
  • Retrieval-Augmented Generation (RAG)
  • - *
  • Semantic search applications
  • - *
  • Document clustering and classification
  • - *
  • Recommendation systems
  • - *
- * - *

Prerequisites: - *

    - *
  • Conductor server with vector database integration configured
  • - *
  • Embedding model integration (OpenAI, Cohere, etc.)
  • - *
- * - *

Usage: - *

- * ./gradlew :examples:run -PmainClass=io.orkes.conductor.sdk.examples.agentic.VectorDbExample
- * 
- */ -public class VectorDbExample { - - private static final String EMBEDDING_WORKFLOW = "generate_embeddings"; - private static final String INDEX_WORKFLOW = "vector_index"; - private static final String SEARCH_WORKFLOW = "vector_search"; - private static final String LLM_PROVIDER = "openai"; - private static final String EMBEDDING_MODEL = "text-embedding-ada-002"; - private static final String VECTOR_DB = "pinecone"; - private static final String INDEX_NAME = "demo-index"; - private static final String NAMESPACE = "vector-demo"; - - public static void main(String[] args) { - System.out.println("Starting Vector Database Example"); - System.out.println(); - - // Initialize Conductor client - ConductorClient client = ClientUtil.getClient(); - WorkflowExecutor executor = new WorkflowExecutor(client, 10); - - try { - // Create and register all workflows - ConductorWorkflow> embeddingWorkflow = createEmbeddingWorkflow(executor); - embeddingWorkflow.registerWorkflow(true, true); - System.out.println("Registered: " + EMBEDDING_WORKFLOW); - - ConductorWorkflow> indexWorkflow = createIndexWorkflow(executor); - indexWorkflow.registerWorkflow(true, true); - System.out.println("Registered: " + INDEX_WORKFLOW); - - ConductorWorkflow> searchWorkflow = createSearchWorkflow(executor); - searchWorkflow.registerWorkflow(true, true); - System.out.println("Registered: " + SEARCH_WORKFLOW); - - // Demo 1: Generate embeddings for a text - System.out.println("\n=== Demo 1: Generate Embeddings ==="); - String sampleText = "Conductor is an orchestration platform for microservices"; - - Map embeddingInput = new HashMap<>(); - embeddingInput.put("text", sampleText); - embeddingInput.put("llmProvider", LLM_PROVIDER); - embeddingInput.put("model", EMBEDDING_MODEL); - - System.out.println("Input text: " + sampleText); - - var embeddingRun = embeddingWorkflow.execute(embeddingInput); - Workflow embeddingResult = embeddingRun.get(30, TimeUnit.SECONDS); - - System.out.println("Status: " + embeddingResult.getStatus()); - @SuppressWarnings("unchecked") - List embeddings = (List) embeddingResult.getOutput().get("embeddings"); - if (embeddings != null) { - System.out.println("Embedding dimensions: " + embeddings.size()); - System.out.println("First 5 values: " + embeddings.subList(0, Math.min(5, embeddings.size()))); - } - - // Demo 2: Index documents - System.out.println("\n=== Demo 2: Index Documents ==="); - List> documents = List.of( - Map.of("id", "1", "text", "The quick brown fox jumps over the lazy dog"), - Map.of("id", "2", "text", "A fast auburn fox leaps above a sleepy canine"), - Map.of("id", "3", "text", "The weather today is sunny with clear skies"), - Map.of("id", "4", "text", "Machine learning is a subset of artificial intelligence"), - Map.of("id", "5", "text", "Deep learning uses neural networks with many layers") - ); - - for (Map doc : documents) { - Map indexInput = new HashMap<>(); - indexInput.put("documentId", doc.get("id")); - indexInput.put("text", doc.get("text")); - indexInput.put("llmProvider", LLM_PROVIDER); - indexInput.put("embeddingModel", EMBEDDING_MODEL); - indexInput.put("vectorDb", VECTOR_DB); - indexInput.put("index", INDEX_NAME); - indexInput.put("namespace", NAMESPACE); - indexInput.put("metadata", Map.of("source", "demo")); - - try { - var indexRun = indexWorkflow.execute(indexInput); - Workflow indexResult = indexRun.get(30, TimeUnit.SECONDS); - System.out.println("Indexed doc " + doc.get("id") + ": " + indexResult.getStatus()); - } catch (Exception e) { - System.out.println("Failed to index doc " + doc.get("id") + ": " + e.getMessage()); - } - } - - // Demo 3: Semantic search - System.out.println("\n=== Demo 3: Semantic Search ==="); - String searchQuery = "animals jumping"; - - Map searchInput = new HashMap<>(); - searchInput.put("query", searchQuery); - searchInput.put("llmProvider", LLM_PROVIDER); - searchInput.put("embeddingModel", EMBEDDING_MODEL); - searchInput.put("vectorDb", VECTOR_DB); - searchInput.put("index", INDEX_NAME); - searchInput.put("namespace", NAMESPACE); - searchInput.put("topK", 3); - - System.out.println("Search query: " + searchQuery); - - var searchRun = searchWorkflow.execute(searchInput); - Workflow searchResult = searchRun.get(30, TimeUnit.SECONDS); - - System.out.println("Status: " + searchResult.getStatus()); - System.out.println("\nSearch Results:"); - - @SuppressWarnings("unchecked") - List> results = (List>) searchResult.getOutput().get("results"); - if (results != null) { - for (int i = 0; i < results.size(); i++) { - Map result = results.get(i); - System.out.println((i + 1) + ". Score: " + result.get("score") + - " - " + result.get("text")); - } - } - - // Demo 4: Another semantic search - System.out.println("\n=== Demo 4: Another Semantic Search ==="); - searchQuery = "AI and machine learning"; - searchInput.put("query", searchQuery); - - System.out.println("Search query: " + searchQuery); - - searchRun = searchWorkflow.execute(searchInput); - searchResult = searchRun.get(30, TimeUnit.SECONDS); - - System.out.println("Status: " + searchResult.getStatus()); - System.out.println("\nSearch Results:"); - - @SuppressWarnings("unchecked") - List> results2 = (List>) searchResult.getOutput().get("results"); - if (results2 != null) { - for (int i = 0; i < results2.size(); i++) { - Map result = results2.get(i); - System.out.println((i + 1) + ". Score: " + result.get("score") + - " - " + result.get("text")); - } - } - - } catch (Exception e) { - System.err.println("Error: " + e.getMessage()); - e.printStackTrace(); - } finally { - executor.shutdown(); - } - } - - /** - * Creates a workflow for generating embeddings from text. - */ - private static ConductorWorkflow> createEmbeddingWorkflow(WorkflowExecutor executor) { - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName(EMBEDDING_WORKFLOW); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - workflow.setDescription("Generate embeddings from text"); - - LlmGenerateEmbeddings embedTask = new LlmGenerateEmbeddings("generate_embeddings", "embed_ref") - .llmProvider("${workflow.input.llmProvider}") - .model("${workflow.input.model}") - .text("${workflow.input.text}"); - - workflow.add(embedTask); - - Map outputParams = new HashMap<>(); - outputParams.put("embeddings", "${embed_ref.output.embeddings}"); - outputParams.put("model", "${workflow.input.model}"); - outputParams.put("inputText", "${workflow.input.text}"); - workflow.setWorkflowOutput(outputParams); - - return workflow; - } - - /** - * Creates a workflow for indexing text into a vector database. - */ - private static ConductorWorkflow> createIndexWorkflow(WorkflowExecutor executor) { - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName(INDEX_WORKFLOW); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - workflow.setDescription("Index text into vector database"); - - LlmIndexText indexTask = new LlmIndexText("index_text", "index_ref") - .vectorDb("${workflow.input.vectorDb}") - .namespace("${workflow.input.namespace}") - .index("${workflow.input.index}") - .embeddingModelProvider("${workflow.input.llmProvider}") - .embeddingModel("${workflow.input.embeddingModel}") - .text("${workflow.input.text}") - .docId("${workflow.input.documentId}") - .metadata("${workflow.input.metadata}"); - - workflow.add(indexTask); - - Map outputParams = new HashMap<>(); - outputParams.put("documentId", "${workflow.input.documentId}"); - outputParams.put("indexed", true); - workflow.setWorkflowOutput(outputParams); - - return workflow; - } - - /** - * Creates a workflow for semantic search in a vector database. - */ - private static ConductorWorkflow> createSearchWorkflow(WorkflowExecutor executor) { - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName(SEARCH_WORKFLOW); - workflow.setVersion(1); - workflow.setOwnerEmail("examples@conductor-oss.org"); - workflow.setDescription("Semantic search in vector database"); - - LlmSearchIndex searchTask = new LlmSearchIndex("search_vectors", "search_ref") - .vectorDb("${workflow.input.vectorDb}") - .namespace("${workflow.input.namespace}") - .index("${workflow.input.index}") - .embeddingModelProvider("${workflow.input.llmProvider}") - .embeddingModel("${workflow.input.embeddingModel}") - .query("${workflow.input.query}") - .maxResults(5); - - workflow.add(searchTask); - - Map outputParams = new HashMap<>(); - outputParams.put("results", "${search_ref.output.results}"); - outputParams.put("query", "${workflow.input.query}"); - workflow.setWorkflowOutput(outputParams); - - return workflow; - } -} diff --git a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/util/ClientUtil.java b/examples/old/src/main/java/io/orkes/conductor/sdk/examples/util/ClientUtil.java deleted file mode 100644 index 26dbb8bc1..000000000 --- a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/util/ClientUtil.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2022 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 io.orkes.conductor.sdk.examples.util; - -import com.netflix.conductor.client.http.ConductorClient; - -import io.orkes.conductor.client.ApiClient; -import io.orkes.conductor.client.OrkesClients; - -public class ClientUtil { - - private static final ConductorClient CLIENT = ApiClient.builder() - .useEnvVariables(true) - .readTimeout(10_000) - .connectTimeout(10_000) - .writeTimeout(10_000) - .build();; - - public static OrkesClients getOrkesClients() { - return new OrkesClients(CLIENT); - } - - public static ConductorClient getClient() { - return CLIENT; - } -} diff --git a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/validation/SdkValidationTest.java b/examples/old/src/main/java/io/orkes/conductor/sdk/examples/validation/SdkValidationTest.java deleted file mode 100644 index 6c0cd0f2b..000000000 --- a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/validation/SdkValidationTest.java +++ /dev/null @@ -1,396 +0,0 @@ -/* - * Copyright 2024 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 io.orkes.conductor.sdk.examples.validation; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.conductoross.conductor.sdk.ai.LlmChatComplete; -import org.conductoross.conductor.sdk.ai.LlmGenerateEmbeddings; -import org.conductoross.conductor.sdk.ai.LlmIndexText; -import org.conductoross.conductor.sdk.ai.LlmSearchIndex; -import org.conductoross.conductor.sdk.ai.LlmTextComplete; - -import com.netflix.conductor.client.automator.TaskRunnerConfigurer; -import com.netflix.conductor.client.http.ConductorClient; -import com.netflix.conductor.client.http.MetadataClient; -import com.netflix.conductor.client.http.TaskClient; -import com.netflix.conductor.client.http.WorkflowClient; -import com.netflix.conductor.client.worker.Worker; -import com.netflix.conductor.common.metadata.tasks.Task; -import com.netflix.conductor.common.metadata.tasks.TaskResult; -import com.netflix.conductor.common.metadata.workflow.StartWorkflowRequest; -import com.netflix.conductor.common.run.Workflow; -import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; -import com.netflix.conductor.sdk.workflow.def.tasks.DoWhile; -import com.netflix.conductor.sdk.workflow.def.tasks.ForkJoin; -import com.netflix.conductor.sdk.workflow.def.tasks.Http; -import com.netflix.conductor.sdk.workflow.def.tasks.SetVariable; -import com.netflix.conductor.sdk.workflow.def.tasks.SimpleTask; -import com.netflix.conductor.sdk.workflow.def.tasks.Switch; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -/** - * End-to-end validation script for the Conductor Java SDK. - *

- * This script validates: - *

    - *
  • SDK connectivity to Conductor server
  • - *
  • Workflow registration
  • - *
  • Worker task execution
  • - *
  • Workflow execution and completion
  • - *
  • LLM task class instantiation (compilation test)
  • - *
- * - *

Usage: - *

- * export CONDUCTOR_SERVER_URL=http://localhost:7001/api
- * ./gradlew :examples:run -PmainClass=io.orkes.conductor.sdk.examples.validation.SdkValidationTest
- * 
- */ -public class SdkValidationTest { - - private static final String VALIDATION_WORKFLOW = "sdk_validation_workflow"; - private static int passedTests = 0; - private static int failedTests = 0; - - public static void main(String[] args) { - String serverUrl = System.getenv().getOrDefault("CONDUCTOR_SERVER_URL", "http://localhost:7001/api"); - - System.out.println("╔══════════════════════════════════════════════════════════════╗"); - System.out.println("║ Conductor Java SDK End-to-End Validation ║"); - System.out.println("╚══════════════════════════════════════════════════════════════╝"); - System.out.println(); - System.out.println("Server URL: " + serverUrl); - System.out.println(); - - ConductorClient client = null; - WorkflowExecutor executor = null; - TaskRunnerConfigurer taskRunner = null; - - try { - // Test 1: Client connectivity - printTest("Test 1: Client Connectivity"); - client = ConductorClient.builder() - .basePath(serverUrl) - .build(); - - // Verify connectivity by getting server health - MetadataClient metadataClient = new MetadataClient(client); - try { - metadataClient.getAllWorkflowsWithLatestVersions(); - pass("Connected to Conductor server"); - } catch (Exception e) { - fail("Cannot connect to Conductor server: " + e.getMessage()); - throw e; - } - - // Test 2: LLM Task Classes Instantiation - printTest("Test 2: LLM Task Classes Instantiation"); - try { - // Test all new LLM task classes can be instantiated - LlmTextComplete textTask = new LlmTextComplete("test_text", "text_ref") - .llmProvider("openai") - .model("gpt-4") - .promptName("test-prompt") - .temperature(0.7); - pass("LlmTextComplete instantiated"); - - LlmChatComplete chatTask = new LlmChatComplete("test_chat", "chat_ref") - .llmProvider("openai") - .model("gpt-4") - .messages(List.of(Map.of("role", "user", "content", "test"))) - .temperature(0.7); - pass("LlmChatComplete instantiated"); - - LlmIndexText indexTask = new LlmIndexText("test_index", "index_ref") - .vectorDb("pinecone") - .namespace("test") - .index("test-index") - .embeddingModel("text-embedding-ada-002") - .text("test document"); - pass("LlmIndexText instantiated"); - - LlmSearchIndex searchTask = new LlmSearchIndex("test_search", "search_ref") - .vectorDb("pinecone") - .namespace("test") - .index("test-index") - .query("test query") - .maxResults(5); - pass("LlmSearchIndex instantiated"); - - LlmGenerateEmbeddings embedTask = new LlmGenerateEmbeddings("test_embed", "embed_ref") - .llmProvider("openai") - .model("text-embedding-ada-002") - .text("test text"); - pass("LlmGenerateEmbeddings instantiated"); - } catch (Exception e) { - fail("LLM task class instantiation failed: " + e.getMessage()); - } - - // Test 3: Workflow Definition - printTest("Test 3: Workflow Definition with SDK"); - executor = new WorkflowExecutor(client, 100); - ConductorWorkflow> workflow = createValidationWorkflow(executor); - pass("Workflow definition created with tasks: " + - workflow.toWorkflowDef().getTasks().size() + " tasks"); - - // Test 4: Workflow Registration - printTest("Test 4: Workflow Registration"); - try { - boolean registered = workflow.registerWorkflow(true, true); - if (registered) { - pass("Workflow registered: " + VALIDATION_WORKFLOW); - } else { - fail("Workflow registration returned false"); - } - } catch (Exception e) { - fail("Workflow registration failed: " + e.getMessage()); - } - - // Test 5: Start Workers - printTest("Test 5: Worker Initialization"); - TaskClient taskClient = new TaskClient(client); - List workers = List.of( - new ValidationWorker("validation_task_1"), - new ValidationWorker("validation_task_2"), - new ValidationWorker("validation_task_3") - ); - - taskRunner = new TaskRunnerConfigurer.Builder(taskClient, workers) - .withThreadCount(3) - .build(); - taskRunner.init(); - pass("Workers started for tasks: validation_task_1, validation_task_2, validation_task_3"); - - // Give workers time to start polling - Thread.sleep(2000); - - // Test 6: Workflow Execution - printTest("Test 6: Workflow Execution"); - Map input = new HashMap<>(); - input.put("name", "Conductor SDK Validation"); - input.put("testValue", 42); - - try { - var workflowRun = workflow.execute(input); - Workflow result = workflowRun.get(30, TimeUnit.SECONDS); - - if (result.getStatus() == Workflow.WorkflowStatus.COMPLETED) { - pass("Workflow completed successfully"); - pass("Workflow ID: " + result.getWorkflowId()); - pass("Output: " + result.getOutput()); - } else { - fail("Workflow ended with status: " + result.getStatus()); - if (result.getReasonForIncompletion() != null) { - fail("Reason: " + result.getReasonForIncompletion()); - } - } - } catch (Exception e) { - fail("Workflow execution failed: " + e.getMessage()); - } - - // Test 7: Workflow Client Operations - printTest("Test 7: Workflow Client Operations"); - WorkflowClient workflowClient = new WorkflowClient(client); - try { - // Start another workflow using StartWorkflowRequest - StartWorkflowRequest startRequest = new StartWorkflowRequest(); - startRequest.setName(VALIDATION_WORKFLOW); - startRequest.setVersion(1); - startRequest.setInput(input); - String workflowId = workflowClient.startWorkflow(startRequest); - pass("Started workflow via WorkflowClient: " + workflowId); - - // Wait a bit for it to start - Thread.sleep(1000); - - // Get workflow status - Workflow wf = workflowClient.getWorkflow(workflowId, true); - pass("Retrieved workflow status: " + wf.getStatus()); - - // Wait for completion - int attempts = 0; - while (wf.getStatus() == Workflow.WorkflowStatus.RUNNING && attempts < 30) { - Thread.sleep(1000); - wf = workflowClient.getWorkflow(workflowId, false); - attempts++; - } - - if (wf.getStatus() == Workflow.WorkflowStatus.COMPLETED) { - pass("Second workflow completed: " + workflowId); - } else { - fail("Second workflow status: " + wf.getStatus()); - } - } catch (Exception e) { - fail("Workflow client operations failed: " + e.getMessage()); - } - - // Test 8: Complex Task Types - printTest("Test 8: Complex Task Types (Switch, DoWhile, ForkJoin)"); - try { - // Test Switch task - Switch switchTask = new Switch("switch_ref", "${workflow.input.condition}"); - switchTask.switchCase("case1", new SimpleTask("task1", "task1_ref")); - switchTask.switchCase("case2", new SimpleTask("task2", "task2_ref")); - switchTask.defaultCase(new SimpleTask("default", "default_ref")); - pass("Switch task created with 2 cases + default"); - - // Test DoWhile task - DoWhile doWhile = new DoWhile("loop_ref", 3, - new SimpleTask("loop_task", "loop_task_ref")); - pass("DoWhile task created with 3 iterations"); - - // Test ForkJoin task - each array is a parallel branch - SimpleTask fork1 = new SimpleTask("fork1", "fork1_ref"); - SimpleTask fork2 = new SimpleTask("fork2", "fork2_ref"); - @SuppressWarnings("unchecked") - ForkJoin forkJoin = new ForkJoin("fork_ref", - new com.netflix.conductor.sdk.workflow.def.tasks.Task[]{fork1}, - new com.netflix.conductor.sdk.workflow.def.tasks.Task[]{fork2}); - pass("ForkJoin task created with 2 parallel branches"); - - // Test Http task - Http httpTask = new Http("http_ref"); - httpTask.url("https://httpbin.org/get") - .method(Http.Input.HttpMethod.GET); - pass("Http task created"); - - // Test SetVariable task - SetVariable setVar = new SetVariable("setvar_ref"); - setVar.input("myVar", "myValue"); - pass("SetVariable task created"); - } catch (Exception e) { - fail("Complex task types failed: " + e.getMessage()); - } - - } catch (Exception e) { - System.err.println("\n*** Fatal error: " + e.getMessage()); - e.printStackTrace(); - } finally { - // Cleanup - if (taskRunner != null) { - taskRunner.shutdown(); - } - if (executor != null) { - executor.shutdown(); - } - } - - // Print summary - System.out.println(); - System.out.println("╔══════════════════════════════════════════════════════════════╗"); - System.out.println("║ VALIDATION SUMMARY ║"); - System.out.println("╠══════════════════════════════════════════════════════════════╣"); - System.out.printf("║ Passed: %-4d ║%n", passedTests); - System.out.printf("║ Failed: %-4d ║%n", failedTests); - System.out.println("╠══════════════════════════════════════════════════════════════╣"); - if (failedTests == 0) { - System.out.println("║ Result: ALL TESTS PASSED ║"); - } else { - System.out.println("║ Result: SOME TESTS FAILED ║"); - } - System.out.println("╚══════════════════════════════════════════════════════════════╝"); - - System.exit(failedTests > 0 ? 1 : 0); - } - - /** - * Creates a simple validation workflow with multiple task types. - */ - private static ConductorWorkflow> createValidationWorkflow(WorkflowExecutor executor) { - ConductorWorkflow> workflow = new ConductorWorkflow<>(executor); - workflow.setName(VALIDATION_WORKFLOW); - workflow.setVersion(1); - workflow.setOwnerEmail("validation@conductor-oss.org"); - workflow.setDescription("SDK validation workflow"); - - // Task 1: Simple task - SimpleTask task1 = new SimpleTask("validation_task_1", "task1_ref"); - task1.input("input_name", "${workflow.input.name}"); - workflow.add(task1); - - // Task 2: Another simple task using output from task 1 - SimpleTask task2 = new SimpleTask("validation_task_2", "task2_ref"); - task2.input("previous_output", "${task1_ref.output.result}"); - task2.input("test_value", "${workflow.input.testValue}"); - workflow.add(task2); - - // Task 3: Final task - SimpleTask task3 = new SimpleTask("validation_task_3", "task3_ref"); - task3.input("all_results", Map.of( - "task1", "${task1_ref.output.result}", - "task2", "${task2_ref.output.result}" - )); - workflow.add(task3); - - // Set workflow output - Map output = new HashMap<>(); - output.put("finalResult", "${task3_ref.output.result}"); - output.put("task1Result", "${task1_ref.output.result}"); - output.put("task2Result", "${task2_ref.output.result}"); - workflow.setWorkflowOutput(output); - - return workflow; - } - - private static void printTest(String testName) { - System.out.println(); - System.out.println("─────────────────────────────────────────────────────────────────"); - System.out.println(testName); - System.out.println("─────────────────────────────────────────────────────────────────"); - } - - private static void pass(String message) { - System.out.println(" ✓ " + message); - passedTests++; - } - - private static void fail(String message) { - System.out.println(" ✗ " + message); - failedTests++; - } - - /** - * Simple worker for validation testing. - */ - static class ValidationWorker implements Worker { - private final String taskDefName; - - ValidationWorker(String taskDefName) { - this.taskDefName = taskDefName; - } - - @Override - public String getTaskDefName() { - return taskDefName; - } - - @Override - public TaskResult execute(Task task) { - TaskResult result = new TaskResult(task); - result.setStatus(TaskResult.Status.COMPLETED); - - // Echo input back as output with some processing - Map output = new HashMap<>(); - output.put("result", "Processed by " + taskDefName); - output.put("inputReceived", task.getInputData()); - output.put("timestamp", System.currentTimeMillis()); - result.setOutputData(output); - - return result; - } - } -} diff --git a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/workflowops/Main.java b/examples/old/src/main/java/io/orkes/conductor/sdk/examples/workflowops/Main.java deleted file mode 100644 index e811da045..000000000 --- a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/workflowops/Main.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2024 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 io.orkes.conductor.sdk.examples.workflowops; - -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -import io.orkes.conductor.client.http.OrkesWorkflowClient; -import io.orkes.conductor.sdk.examples.util.ClientUtil; -import io.orkes.conductor.sdk.examples.workflowops.workflowdef.GreetingsWorkflow; - -import lombok.Builder; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - - -public class Main { - - public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException { - //Initialise Conductor Client - var client = ClientUtil.getClient(); - var orkesWorkflowClient = new OrkesWorkflowClient(client); - - //Initialise WorkflowExecutor and Conductor Workers - var workflowExecutor = new WorkflowExecutor(client, 10); - workflowExecutor.initWorkers("com.netflix.conductor.sdk.examples.helloworld.workers"); - - //Create the workflow with input - var workflowCreator = new GreetingsWorkflow(workflowExecutor); - var simpleWorkflow = workflowCreator.create(); - var input = new GreetingsWorkflow.Input(); - input.setName("Orkes User"); - input.setPersons(List.of(Person.builder() - .id("1") - .name("John") - .last("Doe") - .email("john@orkes.io") - .build(), - Person.builder() - .id("2") - .name("Jane") - .last("Doe") - .email("jane@orkes.io") - .build())); - var workflowId = simpleWorkflow.startDynamic(input); - var summary = orkesWorkflowClient.getWorkflowStatusSummary(workflowId, false, false); - - //Workflow Execution Started - System.out.println("Your workflow started with id " + workflowId); - System.out.println("Workflow status is " + summary.getStatus()); - - var workflow = orkesWorkflowClient.getWorkflow(workflowId, true); - var lastTask = workflow.getTasks(); - var lastTaskId = lastTask.get(lastTask.size() - 1).getTaskDefName(); - System.out.println("Workflow status is " + workflow.getStatus() + " and current or last task is " + lastTaskId); - - //Test Termination - orkesWorkflowClient.terminateWorkflow(workflowId, "Testing Termination"); - workflow = orkesWorkflowClient.getWorkflow(workflowId, false); - System.out.println("Workflow status is " + workflow.getStatus()); - - var workflowIds = List.of(workflowId); - - //Restart Workflow - var bulkResponse = orkesWorkflowClient.restartWorkflow(workflowIds, false); - - workflow = orkesWorkflowClient.getWorkflow(workflowId, false); - System.out.println("Workflow status is " + workflow.getStatus()); - - //Pause Workflow - orkesWorkflowClient.pauseWorkflow(workflowId); - workflow = orkesWorkflowClient.getWorkflow(workflowId, true); - System.out.println("Workflow status is " + workflow.getStatus()); - - //Resume Workflow - orkesWorkflowClient.resumeWorkflow(workflowIds); - workflow = orkesWorkflowClient.getWorkflow(workflowId, true); - System.out.println("Workflow status is " + workflow.getStatus()); - - //Shutdown workflowClient and taskrunner - orkesWorkflowClient.close(); - System.exit(0); - } - - @Builder - @RequiredArgsConstructor - @Getter - public static class Person { - private final String id; - private final String name; - private final String last; - private final String email; - } -} diff --git a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/workflowops/workflowdef/GreetingsWorkflow.java b/examples/old/src/main/java/io/orkes/conductor/sdk/examples/workflowops/workflowdef/GreetingsWorkflow.java deleted file mode 100644 index 22b766fba..000000000 --- a/examples/old/src/main/java/io/orkes/conductor/sdk/examples/workflowops/workflowdef/GreetingsWorkflow.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2024 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 io.orkes.conductor.sdk.examples.workflowops.workflowdef; - -import java.time.Duration; -import java.util.List; - -import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow; -import com.netflix.conductor.sdk.workflow.def.tasks.Http; -import com.netflix.conductor.sdk.workflow.def.tasks.JQ; -import com.netflix.conductor.sdk.workflow.def.tasks.Javascript; -import com.netflix.conductor.sdk.workflow.def.tasks.SetVariable; -import com.netflix.conductor.sdk.workflow.def.tasks.SimpleTask; -import com.netflix.conductor.sdk.workflow.def.tasks.Switch; -import com.netflix.conductor.sdk.workflow.def.tasks.Wait; -import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; - -import io.orkes.conductor.sdk.examples.workflowops.Main; - -import lombok.Data; - -public class GreetingsWorkflow { - private final WorkflowExecutor executor; - - public GreetingsWorkflow(WorkflowExecutor executor) { - this.executor = executor; - } - - public ConductorWorkflow create() { - ConductorWorkflow workflow = new ConductorWorkflow<>(executor); - workflow.setName("greetings"); - workflow.setVersion(1); - //Simple Task - SimpleTask greetingsTask = new SimpleTask("greet", "greet_ref"); - greetingsTask.input("name", "IDXC" + "${workflow.input.name}"); - workflow.add(greetingsTask); - //JS Task - String script = "function greetings(name){return {\"text\": \"Your email is \" + name+\"@workflow.io\",\"url\": \"https://orkes-api-tester.orkesconductor.com/api\"}}greetings(\"'${workflow.input.name}'\");"; - Javascript jstask = new Javascript("hello_script", script); - workflow.add(jstask); - //Wait Task - Wait waitTask = new Wait("wait_for_1_sec", Duration.ofMillis(1000)); - workflow.add(waitTask);//workflow is an object of ConductorWorkflow - //Set Variable - SetVariable setVariable = new SetVariable("set_name"); - setVariable.input("Name", "${workflow.input.name}"); - workflow.add(setVariable); -// SubWorkflow -// SubWorkflow subWorkflow = new SubWorkflow("persist_inDB", "insertintodb", 1); -// subWorkflow.input("name", "{workflow.input.name}"); -// workflow.add(subWorkflow); - //Switch Case - Wait waitTask2 = new Wait("wait_for_2_sec", Duration.ofSeconds(2)); - Javascript jstask2 = new Javascript("hello_script2", script); - Switch switchTask = new Switch("Version_switch", "${workflow.input.name}").switchCase("Orkes", jstask2).switchCase("Others", waitTask2); - workflow.add(switchTask); - //JQ Task - JQ jqtask = new JQ("jq_task", ".persons | map({user:{email, name}})"); - jqtask.input("persons", "${workflow.input.persons}"); - workflow.add(jqtask); - //HTTP Task - Http httptask = new Http("HTTPtask"); - httptask.url("https://orkes-api-tester.orkesconductor.com/api"); - workflow.add(httptask); - Wait waitTask10 = new Wait("wait_for_10_sec", Duration.ofSeconds(10)); - workflow.add(waitTask10); - return workflow; - } - - @Data - public static class Input { - private String name; - private List persons; - } -} diff --git a/examples/old/src/main/resources/logback.xml b/examples/old/src/main/resources/logback.xml deleted file mode 100644 index 9df2403dd..000000000 --- a/examples/old/src/main/resources/logback.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{}): %msg%n%throwable - - - - - - - - - diff --git a/examples/old/src/main/resources/script.js b/examples/old/src/main/resources/script.js deleted file mode 100644 index af6d42c43..000000000 --- a/examples/old/src/main/resources/script.js +++ /dev/null @@ -1,11 +0,0 @@ -function e() { - if ($.value > 1){ - return { - "key": "value", - "key2": 42 - }; - } else { - return {}; - } -} -e(); \ No newline at end of file diff --git a/examples/old/src/main/resources/task_domain_wf.json b/examples/old/src/main/resources/task_domain_wf.json deleted file mode 100644 index f48ab5c27..000000000 --- a/examples/old/src/main/resources/task_domain_wf.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "createTime": 1688142904648, - "updateTime": 1688491115511, - "name": "task_domain_wf", - "description": "Workflow for workers with task domains", - "version": 1, - "tasks": [ - { - "name": "task-domain-annotated-simple-task", - "taskReferenceName": "task-domain-annotated-simple-task", - "inputParameters": {}, - "type": "SIMPLE", - "decisionCases": {}, - "defaultCase": [], - "forkTasks": [], - "startDelay": 0, - "joinOn": [], - "optional": false, - "defaultExclusiveJoinTask": [], - "asyncComplete": false, - "loopOver": [], - "onStateChange": {} - }, - { - "name": "task-domain-property-simple-task", - "taskReferenceName": "task-domain-property-simple-task", - "inputParameters": {}, - "type": "SIMPLE", - "decisionCases": {}, - "defaultCase": [], - "forkTasks": [], - "startDelay": 0, - "joinOn": [], - "optional": false, - "defaultExclusiveJoinTask": [], - "asyncComplete": false, - "loopOver": [], - "onStateChange": {} - }, - { - "name": "task-domain-all-simple-task", - "taskReferenceName": "task-domain-all-simple-task", - "inputParameters": {}, - "type": "SIMPLE", - "decisionCases": {}, - "defaultCase": [], - "forkTasks": [], - "startDelay": 0, - "joinOn": [], - "optional": false, - "defaultExclusiveJoinTask": [], - "asyncComplete": false, - "loopOver": [], - "onStateChange": {} - }, - { - "name": "task-domain-runner-simple-task", - "taskReferenceName": "task-domain-runner-simple-task", - "inputParameters": {}, - "type": "SIMPLE", - "decisionCases": {}, - "defaultCase": [], - "forkTasks": [], - "startDelay": 0, - "joinOn": [], - "optional": false, - "defaultExclusiveJoinTask": [], - "asyncComplete": false, - "loopOver": [], - "onStateChange": {} - } - ], - "inputParameters": [], - "outputParameters": {}, - "failureWorkflow": "", - "schemaVersion": 2, - "restartable": true, - "workflowStatusListenerEnabled": false, - "ownerEmail": "tester@email.com", - "timeoutPolicy": "ALERT_ONLY", - "timeoutSeconds": 0, - "variables": {}, - "inputTemplate": {}, - "onStateChange": {} -} \ No newline at end of file diff --git a/examples/old/src/main/resources/workflow.json b/examples/old/src/main/resources/workflow.json deleted file mode 100644 index 33f1625f0..000000000 --- a/examples/old/src/main/resources/workflow.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "hello", - "description": "hello workflow", - "version": 1, - "tasks": [ - { - "name": "greet", - "taskReferenceName": "greet_ref", - "type": "SIMPLE", - "inputParameters": { - "name": "${workflow.input.name}" - } - } - ], - "timeoutPolicy": "TIME_OUT_WF", - "timeoutSeconds": 60 - } \ No newline at end of file diff --git a/native-examples-spring/README.md b/native-examples-spring/README.md new file mode 100644 index 000000000..b05ba031e --- /dev/null +++ b/native-examples-spring/README.md @@ -0,0 +1,29 @@ +# 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` and `dev-mode`. Per workflow, as `conductor.worker..*` is per task: +`conductor.workflow..threadCount`, `pollingInterval`, `pollTimeout`, `paused` and +`continuationTimeout`, or `conductor.workflow.all.*` for every workflow. 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..1e4d8259c --- /dev/null +++ b/native-examples-spring/src/main/java/orders/OrderController.java @@ -0,0 +1,65 @@ +/* + * 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 com.netflix.conductor.common.run.Workflow.WorkflowStatus; + +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()); + WorkflowStatus status = run.status(); + view.put("status", status); + if (status == WorkflowStatus.COMPLETED) { + 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..35cefba21 --- /dev/null +++ b/native-examples/DURABILITY-BENCH.md @@ -0,0 +1,325 @@ +# 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 (`retryCount > 0` on its marker): a deferral, a failover or a re-run. A redelivery to a second worker after the first died runs the same offer and does not raise `retryCount`. Why a completion was deferred is the run's `reasonForIncompletion`, which `nondeterminism` reads | +| `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 when it could run to when it applied: from its task's `endTime` (the run's `createTime` for the first continuation) to its marker's `endTime`; 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-retry-count-fence`, `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/no-retry-count-fence.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 and the `lane` and `n` its entry names (`workflowTask.metadata`) 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/README.md b/native-examples/README.md new file mode 100644 index 000000000..e92afa305 --- /dev/null +++ b/native-examples/README.md @@ -0,0 +1,83 @@ +# Native workflow examples + +Workflows written as plain Java: a `@Workflow` method calls tasks, decides with `if` and `switch`, +loops with `for` and `while`, and Conductor runs it durably on the server. Read the examples in +order; each one is a single file with a `main` that hosts the workflow, starts it and prints the +result. + +| # | Example | What it shows | +|---|---|---| +| 01 | [Hello world](src/main/java/examples/ex01_hello_world/HelloWorld.java) | a workflow that calls two `@WorkerTask` methods, one after the other | +| 02 | [Conditionals](src/main/java/examples/ex02_conditionals/Conditionals.java) | decisions in plain Java (`if`, `switch`) and with `switchOn` | +| 03 | [Loops](src/main/java/examples/ex03_loops/Loops.java) | each loop twice: plain Java `for`, `while` and `do`-`while`, then `forEach`, `repeatUntil` and `doWhile` | +| 04 | [Parallel](src/main/java/examples/ex04_parallel/Parallel.java) | `async` and `join`; `fanOut`, a branch per item | +| 05 | [Sub workflows](src/main/java/examples/ex05_sub_workflows/SubWorkflows.java) | `child` to wait for a workflow's result, `startWorkflow` to start one and carry on | +| 06 | [Signals](src/main/java/examples/ex06_signals/Signals.java) | `@Signal`, `@Update`, `@Query`, `@Variable` and `awaitCondition`: a shopping cart | +| 07 | [Timers](src/main/java/examples/ex07_timers/Timers.java) | durable `sleep`, `now()`, and `@Schedule` | +| 08 | [Error handling](src/main/java/examples/ex08_error_handling/ErrorHandling.java) | retries, `NonRetryableException`, `catch (TaskFailure e)`, undoing with a saga, `WorkflowFailedException` | +| 09 | [HTTP](src/main/java/examples/ex09_http/HttpCalls.java) | `http(ref)`: GET and POST from the server, typed responses | +| 10 | [Human in the loop](src/main/java/examples/ex10_human_in_the_loop/HumanInTheLoop.java) | `human(ref)` for a person's decision, `external(ref)` for another system, with timeouts | +| 11 | [LLM](src/main/java/examples/ex11_llm/LlmCalls.java) | `llm(ref)`: text, and structured output read into a record | +| 12 | [MCP](src/main/java/examples/ex12_mcp/McpTools.java) | `mcp(ref)`: list an MCP server's tools and call them | +| 13 | [Agent](src/main/java/examples/ex13_agent/AgentCalls.java) | `agent(ref)`: a conversation with an A2A agent, and a long-running agent in `async` | +| 14 | [Agent harness](src/main/java/examples/ex14_agent_harness/AgentHarness.java) | a durable agent loop: a model plans each step, the workflow calls MCP tools, delegates to helper agents and asks a person | +| 15 | [Strict determinism](src/main/java/examples/ex15_strict_determinism/StrictDeterminism.java) | a workflow that calls `Math.random()`, `UUID.randomUUID()` and `Instant.now()` is refused when its workers start under `strictDeterminism`; the same workflow with `random()`, `once` and `now()` runs | + +Example 15 goes with [Determinism in native workflows](../design/native-workflows/determinism.md), +which explains why workflow code must take the same path each time it runs and how to write it so. + +Each example has an in-memory test next to it under `src/test/java/examples`. The test runs the +workflow without a server, with the answers of tasks, models, tools and agents given by the +test. Use them as a starting point for testing your own workflows. + +## Running + +You need a Conductor server. Examples 09 and 11 to 14 also need the stub in `stubs/ai_stub.py`, +which stands in for a web API, a chat model, an MCP server and an A2A agent: + +```shell +python3 native-examples/stubs/ai_stub.py 8765 & +``` + +Start the server with these settings: + +| Setting | Needed by | +|---|---| +| `conductor.workflow-message-queue.enabled=true` | 06, for its signal, update and query handlers | +| `conductor.ai.litellm.baseURL=http://localhost:8765` | 11 and 14, so that the server's LiteLLM provider reaches the stub's model | +| `conductor.a2a.callback.url=` | only for agents called with `pushNotifications(...)` (not used in 13) | + +Then run any example by its number and name, from the repository root: + +```shell +export CONDUCTOR_SERVER_URL=http://localhost:8080/api +./gradlew :native-examples:ex01_hello_world +./gradlew :native-examples:ex14_agent_harness +``` + +Each prints the execution's id: open it in the Conductor UI, at `/execution/`, to see the diagram. Set `STUB_URL` +when the stub is not on `http://localhost:8765`. + +Run the examples' tests: + +```shell +./gradlew :native-examples:test --tests 'examples.*' +``` + +## More examples + +- `agents.SupportTicket` and `agents.SupportDesk`: an agentic support desk. A model routes each + ticket, a `switchOn` hands it to that team's agent or to a person, and `fanOut` handles a whole + inbox at once. +- `reuse.Reuse`: a workflow that calls workers another team already runs, by name and through a + typed interface, with a task domain. + +## Everything else in this module + +The other packages are the SDK's own checks, not examples to learn from: +- `kitchensink`: what `./gradlew :native-examples:run` runs. +- `primitives`: one workflow per construct, with checks. +- `agents.Agents`, `conformance`, `branches`, `switches`, `loops`, `operator`, `failures`, + `retrythrow` and `hold`: checks against a server. +- `durability`: the durability bench and its chaos runs. +- `drawing`: the drawing checks. 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