diff --git a/temporal-sdk/src/main/java/io/temporal/internal/nexus/system/SystemNexusConverterContext.java b/temporal-sdk/src/main/java/io/temporal/internal/nexus/system/SystemNexusConverterContext.java new file mode 100644 index 0000000000..0f85629c1d --- /dev/null +++ b/temporal-sdk/src/main/java/io/temporal/internal/nexus/system/SystemNexusConverterContext.java @@ -0,0 +1,37 @@ +package io.temporal.internal.nexus.system; + +import io.temporal.common.converter.DataConverter; +import java.util.Objects; +import java.util.function.Supplier; + +/** Scopes user-value conversion independently of generated bindings and system envelopes. */ +public final class SystemNexusConverterContext { + private static final ThreadLocal USER_CONVERTER = new ThreadLocal<>(); + + private SystemNexusConverterContext() {} + + /** Returns the user converter active in the current synchronous transfer conversion scope. */ + public static DataConverter currentDataConverter() { + DataConverter converter = USER_CONVERTER.get(); + if (converter == null) { + throw new IllegalStateException("System Nexus user converter context is not active"); + } + return converter; + } + + /** Runs a synchronous conversion with the user converter and restores any enclosing scope. */ + public static T withDataConverter(DataConverter converter, Supplier action) { + Objects.requireNonNull(converter, "converter"); + DataConverter previous = USER_CONVERTER.get(); + USER_CONVERTER.set(converter); + try { + return action.get(); + } finally { + if (previous == null) { + USER_CONVERTER.remove(); + } else { + USER_CONVERTER.set(previous); + } + } + } +} diff --git a/temporal-sdk/src/main/java/io/temporal/internal/sync/ExternalWorkflowInvocationHandler.java b/temporal-sdk/src/main/java/io/temporal/internal/sync/ExternalWorkflowInvocationHandler.java index 0f7def87ea..ea2249a6c6 100644 --- a/temporal-sdk/src/main/java/io/temporal/internal/sync/ExternalWorkflowInvocationHandler.java +++ b/temporal-sdk/src/main/java/io/temporal/internal/sync/ExternalWorkflowInvocationHandler.java @@ -4,13 +4,76 @@ import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor; import io.temporal.common.metadata.POJOWorkflowInterfaceMetadata; import io.temporal.common.metadata.POJOWorkflowMethodMetadata; +import io.temporal.common.metadata.WorkflowMethodType; +import io.temporal.internal.common.InternalUtils; import io.temporal.workflow.ExternalWorkflowStub; import io.temporal.workflow.Functions; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; +import java.util.Objects; -/** Dynamic implementation of a strongly typed child workflow interface. */ -class ExternalWorkflowInvocationHandler implements InvocationHandler { +/** Dynamic implementation of a strongly typed external workflow interface. */ +public class ExternalWorkflowInvocationHandler implements InvocationHandler { + + private static final ThreadLocal probeContext = new ThreadLocal<>(); + private static final ThreadLocal probeResult = new ThreadLocal<>(); + + /** Probes one invocation without starting a workflow or sending a signal. */ + public static ProbeResult probe(Functions.Proc invocation, WorkflowMethodType expected) { + Objects.requireNonNull(invocation, "invocation"); + if (probeContext.get() != null) { + throw new IllegalStateException("Already probing an external workflow invocation"); + } + ProbeContext context = new ProbeContext(expected); + probeContext.set(context); + try { + invocation.apply(); + ProbeResult result = probeResult.get(); + if (context.invocations != 1 || result == null) { + throw new IllegalArgumentException( + "Expected exactly one external workflow " + expected + " invocation"); + } + return result; + } finally { + probeResult.remove(); + probeContext.remove(); + } + } + + private static final class ProbeContext { + private final WorkflowMethodType expected; + private int invocations; + + private ProbeContext(WorkflowMethodType expected) { + this.expected = Objects.requireNonNull(expected, "expected"); + } + } + + /** Metadata captured from a bound external workflow method. */ + public static final class ProbeResult { + private final ExternalWorkflowStub stub; + private final Object[] arguments; + private final POJOWorkflowMethodMetadata metadata; + + private ProbeResult( + ExternalWorkflowStub stub, POJOWorkflowMethodMetadata metadata, Object[] args) { + this.stub = stub; + this.arguments = args == null ? new Object[0] : args.clone(); + this.metadata = metadata; + } + + public ExternalWorkflowStub getStub() { + return stub; + } + + public Object[] getArguments() { + return arguments.clone(); + } + + public POJOWorkflowMethodMetadata getMetadata() { + return metadata; + } + } private final ExternalWorkflowStub stub; private final POJOWorkflowInterfaceMetadata workflowMetadata; @@ -40,6 +103,15 @@ public Object invoke(Object proxy, Method method, Object[] args) { return stub; } POJOWorkflowMethodMetadata methodMetadata = workflowMetadata.getMethodMetadata(method); + ProbeContext context = probeContext.get(); + if (context != null) { + if (++context.invocations != 1 || methodMetadata.getType() != context.expected) { + throw new IllegalArgumentException( + "Expected exactly one external workflow " + context.expected + " invocation"); + } + probeResult.set(new ProbeResult(stub, methodMetadata, args)); + return InternalUtils.getValueOrDefault(null, method.getReturnType()); + } switch (methodMetadata.getType()) { case QUERY: throw new UnsupportedOperationException( diff --git a/temporal-sdk/src/test/java/io/temporal/internal/nexus/system/SystemNexusConverterContextTest.java b/temporal-sdk/src/test/java/io/temporal/internal/nexus/system/SystemNexusConverterContextTest.java new file mode 100644 index 0000000000..f9f598fe40 --- /dev/null +++ b/temporal-sdk/src/test/java/io/temporal/internal/nexus/system/SystemNexusConverterContextTest.java @@ -0,0 +1,76 @@ +package io.temporal.internal.nexus.system; + +import static org.junit.Assert.*; + +import io.temporal.common.converter.CodecDataConverter; +import io.temporal.common.converter.DataConverter; +import io.temporal.common.converter.DefaultDataConverter; +import java.util.Collections; +import java.util.concurrent.*; +import org.junit.Test; + +public class SystemNexusConverterContextTest { + @Test + public void restoresNestedScopesAfterSuccessAndFailure() { + DataConverter outer = DefaultDataConverter.STANDARD_INSTANCE; + DataConverter inner = new CodecDataConverter(outer, Collections.emptyList()); + SystemNexusConverterContext.withDataConverter( + outer, + () -> { + assertSame(outer, SystemNexusConverterContext.currentDataConverter()); + assertSame( + inner, + SystemNexusConverterContext.withDataConverter( + inner, SystemNexusConverterContext::currentDataConverter)); + assertSame(outer, SystemNexusConverterContext.currentDataConverter()); + assertThrows( + IllegalArgumentException.class, + () -> + SystemNexusConverterContext.withDataConverter( + inner, + () -> { + throw new IllegalArgumentException("failure"); + })); + assertSame(outer, SystemNexusConverterContext.currentDataConverter()); + return null; + }); + assertThrows(IllegalStateException.class, SystemNexusConverterContext::currentDataConverter); + assertThrows( + NullPointerException.class, + () -> SystemNexusConverterContext.withDataConverter(null, () -> null)); + assertThrows(IllegalStateException.class, SystemNexusConverterContext::currentDataConverter); + } + + @Test + public void isolatesConcurrentConversionScopes() throws Exception { + DataConverter first = DefaultDataConverter.STANDARD_INSTANCE; + DataConverter second = new CodecDataConverter(first, Collections.emptyList()); + CyclicBarrier barrier = new CyclicBarrier(2); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future a = executor.submit(() -> scopedConverter(first, barrier)); + Future b = executor.submit(() -> scopedConverter(second, barrier)); + assertSame(first, a.get(10, TimeUnit.SECONDS)); + assertSame(second, b.get(10, TimeUnit.SECONDS)); + } finally { + executor.shutdownNow(); + } + assertThrows(IllegalStateException.class, SystemNexusConverterContext::currentDataConverter); + } + + private DataConverter scopedConverter(DataConverter converter, CyclicBarrier barrier) { + DataConverter result = + SystemNexusConverterContext.withDataConverter( + converter, + () -> { + try { + barrier.await(5, TimeUnit.SECONDS); + } catch (Exception e) { + throw new RuntimeException(e); + } + return SystemNexusConverterContext.currentDataConverter(); + }); + assertThrows(IllegalStateException.class, SystemNexusConverterContext::currentDataConverter); + return result; + } +} diff --git a/temporal-sdk/src/test/java/io/temporal/workflow/TypedWorkflowMethodCaptureTest.java b/temporal-sdk/src/test/java/io/temporal/workflow/TypedWorkflowMethodCaptureTest.java new file mode 100644 index 0000000000..b0dd0eb354 --- /dev/null +++ b/temporal-sdk/src/test/java/io/temporal/workflow/TypedWorkflowMethodCaptureTest.java @@ -0,0 +1,238 @@ +package io.temporal.workflow; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import io.temporal.api.common.v1.WorkflowExecution; +import io.temporal.common.CronSchedule; +import io.temporal.common.MethodRetry; +import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor; +import io.temporal.common.metadata.WorkflowMethodType; +import io.temporal.internal.sync.ExternalWorkflowInvocationHandler; +import io.temporal.internal.sync.ExternalWorkflowInvocationHandler.ProbeResult; +import io.temporal.internal.sync.StubMarker; +import java.lang.reflect.Proxy; +import java.util.List; +import java.util.concurrent.*; +import org.junit.Test; + +public class TypedWorkflowMethodCaptureTest { + public interface Base { + @SignalMethod(name = "custom-signal") + void signal(String value, int number); + } + + @WorkflowInterface + public interface Target extends Base { + @WorkflowMethod(name = "custom-workflow") + @MethodRetry( + initialIntervalSeconds = 7, + maximumAttempts = 3, + backoffCoefficient = 3, + maximumIntervalSeconds = 100, + doNotRetry = {"NoRetry"}) + @CronSchedule("0 * * * *") + int start(String value); + + @QueryMethod + String query(); + + @UpdateMethod + String update(); + } + + @WorkflowInterface + public interface GenericTarget { + @WorkflowMethod + List start(); + } + + private final WorkflowOutboundCallsInterceptor outbound = + mock(WorkflowOutboundCallsInterceptor.class); + private final RuntimeException normalSignal = new IllegalStateException("normal signal path"); + + private T stub(Class type, String id) { + return type.cast( + Proxy.newProxyInstance( + type.getClassLoader(), + new Class[] {type, StubMarker.class}, + new ExternalWorkflowInvocationHandler( + type, + WorkflowExecution.newBuilder().setWorkflowId(id).build(), + outbound, + ignored -> { + throw normalSignal; + }))); + } + + @Test + public void probesNamesArgumentsAnnotationsAndReturnTypesWithoutCommands() { + Target target = stub(Target.class, "target"); + Functions.Func1 method = target::start; + ProbeResult call = + ExternalWorkflowInvocationHandler.probe( + () -> assertEquals(0, (int) method.apply("input")), WorkflowMethodType.WORKFLOW); + assertEquals("custom-workflow", call.getMetadata().getName()); + assertEquals(WorkflowMethodType.WORKFLOW, call.getMetadata().getType()); + assertEquals(Target.class, call.getMetadata().getWorkflowInterface()); + assertArrayEquals(new Object[] {"input"}, call.getArguments()); + assertEquals(int.class, call.getMetadata().getWorkflowMethod().getReturnType()); + assertEquals(int.class, call.getMetadata().getWorkflowMethod().getGenericReturnType()); + assertEquals("target", call.getStub().getExecution().getWorkflowId()); + assertEquals( + 3, + call.getMetadata().getWorkflowMethod().getAnnotation(MethodRetry.class).maximumAttempts()); + assertEquals( + "0 * * * *", + call.getMetadata().getWorkflowMethod().getAnnotation(CronSchedule.class).value()); + assertSame(ExternalWorkflowStub.fromTyped(target), call.getStub()); + call.getArguments()[0] = "changed"; + assertEquals("input", call.getArguments()[0]); + + Functions.Proc2 signal = target::signal; + ProbeResult signalCall = + ExternalWorkflowInvocationHandler.probe( + () -> signal.apply("value", 42), WorkflowMethodType.SIGNAL); + assertEquals("custom-signal", signalCall.getMetadata().getName()); + assertEquals(WorkflowMethodType.SIGNAL, signalCall.getMetadata().getType()); + assertArrayEquals(new Object[] {"value", 42}, signalCall.getArguments()); + GenericTarget generic = stub(GenericTarget.class, "generic"); + Functions.Func> start = generic::start; + ProbeResult genericCall = + ExternalWorkflowInvocationHandler.probe(() -> start.apply(), WorkflowMethodType.WORKFLOW); + assertEquals( + "java.util.List", + genericCall.getMetadata().getWorkflowMethod().getGenericReturnType().getTypeName()); + verifyNoInteractions(outbound); + assertThrows(IllegalStateException.class, () -> target.start("outside probe")); + assertSame( + normalSignal, assertThrows(RuntimeException.class, () -> target.signal("outside", 1))); + } + + @Test + public void rejectsMissingRepeatedAndWrongKindInvocations() { + Target target = stub(Target.class, "target"); + Functions.Func1 start = target::start; + assertThrows( + IllegalArgumentException.class, + () -> ExternalWorkflowInvocationHandler.probe(() -> {}, WorkflowMethodType.WORKFLOW)); + assertThrows( + IllegalArgumentException.class, + () -> + ExternalWorkflowInvocationHandler.probe( + () -> { + start.apply("first"); + start.apply("second"); + }, + WorkflowMethodType.WORKFLOW)); + assertThrows( + IllegalArgumentException.class, + () -> + ExternalWorkflowInvocationHandler.probe( + () -> start.apply("input"), WorkflowMethodType.SIGNAL)); + Functions.Proc2 signal = target::signal; + assertThrows( + IllegalArgumentException.class, + () -> + ExternalWorkflowInvocationHandler.probe( + () -> signal.apply("value", 1), WorkflowMethodType.WORKFLOW)); + Functions.Func query = target::query; + Functions.Func update = target::update; + assertThrows( + IllegalArgumentException.class, + () -> + ExternalWorkflowInvocationHandler.probe( + () -> query.apply(), WorkflowMethodType.SIGNAL)); + assertThrows( + IllegalArgumentException.class, + () -> + ExternalWorkflowInvocationHandler.probe( + () -> update.apply(), WorkflowMethodType.SIGNAL)); + verifyNoInteractions(outbound); + } + + @Test + public void capturesInvocationsWithoutInspectingTheirLambdaRepresentation() { + Target target = stub(Target.class, "target"); + Functions.Proc invocation = + new Functions.Proc() { + @Override + public void apply() { + target.start("input"); + } + }; + ProbeResult call = + ExternalWorkflowInvocationHandler.probe(invocation, WorkflowMethodType.WORKFLOW); + assertEquals("custom-workflow", call.getMetadata().getName()); + assertArrayEquals(new Object[] {"input"}, call.getArguments()); + ProbeResult lambda = + ExternalWorkflowInvocationHandler.probe( + () -> target.start("lambda"), WorkflowMethodType.WORKFLOW); + assertArrayEquals(new Object[] {"lambda"}, lambda.getArguments()); + verifyNoInteractions(outbound); + } + + @Test + public void restoresProbeStateAfterFailureAndRejectsNesting() { + Target target = stub(Target.class, "target"); + Functions.Func1 method = target::start; + RuntimeException failure = new RuntimeException("failed"); + assertSame( + failure, + assertThrows( + RuntimeException.class, + () -> + ExternalWorkflowInvocationHandler.probe( + () -> { + throw failure; + }, + WorkflowMethodType.WORKFLOW))); + ProbeResult result = + ExternalWorkflowInvocationHandler.probe( + () -> { + assertThrows( + IllegalStateException.class, + () -> + ExternalWorkflowInvocationHandler.probe( + () -> method.apply("nested"), WorkflowMethodType.WORKFLOW)); + method.apply("outer"); + }, + WorkflowMethodType.WORKFLOW); + assertArrayEquals(new Object[] {"outer"}, result.getArguments()); + assertThrows(IllegalStateException.class, () -> target.start("outside probe")); + verifyNoInteractions(outbound); + } + + @Test + public void isolatesProbeResultsAcrossThreads() throws Exception { + Target first = stub(Target.class, "first"); + Target second = stub(Target.class, "second"); + CyclicBarrier barrier = new CyclicBarrier(2); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future a = executor.submit(() -> parallelProbe(first::start, "a", barrier)); + Future b = executor.submit(() -> parallelProbe(second::start, "b", barrier)); + assertEquals("first:a", a.get(10, TimeUnit.SECONDS)); + assertEquals("second:b", b.get(10, TimeUnit.SECONDS)); + } finally { + executor.shutdownNow(); + } + verifyNoInteractions(outbound); + } + + private String parallelProbe( + Functions.Func1 method, String value, CyclicBarrier barrier) { + ProbeResult result = + ExternalWorkflowInvocationHandler.probe( + () -> { + try { + barrier.await(5, TimeUnit.SECONDS); + } catch (Exception e) { + throw new RuntimeException(e); + } + method.apply(value); + }, + WorkflowMethodType.WORKFLOW); + return result.getStub().getExecution().getWorkflowId() + ":" + result.getArguments()[0]; + } +}