From 65439e4fd7c440f6349170635510f8e248a25e58 Mon Sep 17 00:00:00 2001 From: Joie Wu Date: Wed, 18 Nov 2026 16:36:47 -0800 Subject: [PATCH] Support direct synchronous returns from Temporal operations --- CHANGELOG.md | 3 + .../nexus/TemporalOperationProcessor.java | 35 ++-- .../temporal/nexus/TemporalNexusClient.java | 9 +- .../io/temporal/nexus/TemporalOperation.java | 14 +- .../nexus/TemporalOperationProcessorTest.java | 154 +++++++++++++++++- .../TemporalOperationAnnotationTest.java | 95 ++++++++++- 6 files changed, 281 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b1a84aaf47..806390cfae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,9 @@ to docs, or any other relevant information. - Experimental Event Groups associate related workflow commands so their history events can be viewed together. Create a group with `Workflow.newEventGroup` and attach it by calling `addEventGroups` on the command's options. +- `@TemporalOperation` methods can return their output directly for synchronous completion. + Existing methods returning `TemporalOperationResult`, including asynchronous results, remain + supported. ### Changed - Updated Cloud API bindings to v0.27.0, including opt-in user group memberships, projects, diff --git a/temporal-sdk/src/main/java/io/temporal/internal/nexus/TemporalOperationProcessor.java b/temporal-sdk/src/main/java/io/temporal/internal/nexus/TemporalOperationProcessor.java index 8f13a67a37..d5197c8abd 100644 --- a/temporal-sdk/src/main/java/io/temporal/internal/nexus/TemporalOperationProcessor.java +++ b/temporal-sdk/src/main/java/io/temporal/internal/nexus/TemporalOperationProcessor.java @@ -84,14 +84,6 @@ private static void validateSignature(Method method) { + " must accept (TemporalNexusClient, I); got " + describeSignature(method)); } - if (!TemporalOperationResult.class.equals(method.getReturnType())) { - throw new IllegalArgumentException( - "@TemporalOperation method " - + method.getName() - + " must return TemporalOperationResult; got " - + method.getGenericReturnType().getTypeName() - + ". Use @OperationImpl for custom handler shapes."); - } for (Class declared : method.getExceptionTypes()) { if (!RuntimeException.class.isAssignableFrom(declared) && !Error.class.isAssignableFrom(declared) @@ -119,22 +111,24 @@ private static void validateTypes(Method method, OperationDefinition operationDe + " but got " + declaredInputType.getTypeName()); } - Type returnType = method.getGenericReturnType(); - if (!(returnType instanceof ParameterizedType)) { - throw new IllegalArgumentException( - "@TemporalOperation method " - + method.getName() - + " must use parameterized TemporalOperationResult, not the raw type."); + Type resultType = method.getGenericReturnType(); + if (method.getReturnType() == TemporalOperationResult.class) { + if (!(resultType instanceof ParameterizedType)) { + throw new IllegalArgumentException( + "@TemporalOperation method " + + method.getName() + + " must use parameterized TemporalOperationResult, not the raw type."); + } + resultType = ((ParameterizedType) resultType).getActualTypeArguments()[0]; } - Type resultTypeArg = ((ParameterizedType) returnType).getActualTypeArguments()[0]; - if (!typesMatch(resultTypeArg, operationDefinition.getOutputType())) { + if (!typesMatch(resultType, operationDefinition.getOutputType())) { throw new IllegalArgumentException( "@TemporalOperation method " + method.getName() + " output type mismatch: expected " + operationDefinition.getOutputType().getTypeName() + " but got " - + resultTypeArg.getTypeName()); + + resultType.getTypeName()); } } @@ -143,7 +137,12 @@ private static void validateTypes(Method method, OperationDefinition operationDe static TemporalOperationResult invokeStartHandler( MethodHandle handle, TemporalNexusClient client, Object input) throws OperationException { try { - return (TemporalOperationResult) handle.invoke(client, input); + Object result = handle.invoke(client, input); + // Use the declared return type so null direct results are wrapped, while existing wrapped + // handlers retain their behavior (including asynchronous results). + return TemporalOperationResult.class.equals(handle.type().returnType()) + ? (TemporalOperationResult) result + : TemporalOperationResult.sync(result); } catch (RuntimeException | Error | OperationException e) { // HandlerException is a RuntimeException and falls into the RuntimeException arm. throw e; diff --git a/temporal-sdk/src/main/java/io/temporal/nexus/TemporalNexusClient.java b/temporal-sdk/src/main/java/io/temporal/nexus/TemporalNexusClient.java index 37d7bf7c53..d9dca1be2a 100644 --- a/temporal-sdk/src/main/java/io/temporal/nexus/TemporalNexusClient.java +++ b/temporal-sdk/src/main/java/io/temporal/nexus/TemporalNexusClient.java @@ -35,17 +35,16 @@ * } * } * - *

For synchronous operations, use {@link #getWorkflowClient()} directly and return a {@link - * TemporalOperationResult#sync} result. For example, to send a signal: + *

For synchronous {@link TemporalOperation} methods, use {@link #getWorkflowClient()} directly + * and return the output value, or use {@code void} when there is no output. Explicit {@link + * TemporalOperationResult#sync} results are also supported. For example, to send a signal: * *

{@code
  * @TemporalOperation
- * public TemporalOperationResult cancelOrder(
- *     TemporalNexusClient client, CancelOrderInput input) {
+ * public void cancelOrder(TemporalNexusClient client, CancelOrderInput input) {
  *   client.getWorkflowClient()
  *       .newUntypedWorkflowStub("order-" + input.getOrderId())
  *       .signal("requestCancellation", input);
- *   return TemporalOperationResult.sync(null);
  * }
  * }
* diff --git a/temporal-sdk/src/main/java/io/temporal/nexus/TemporalOperation.java b/temporal-sdk/src/main/java/io/temporal/nexus/TemporalOperation.java index 70ffa34571..9c0b2968dc 100644 --- a/temporal-sdk/src/main/java/io/temporal/nexus/TemporalOperation.java +++ b/temporal-sdk/src/main/java/io/temporal/nexus/TemporalOperation.java @@ -19,7 +19,8 @@ *
    *
  • be {@code public}, *
  • accept exactly two parameters: {@link TemporalNexusClient} and the operation input type, - *
  • return {@link TemporalOperationResult}. + *
  • return the operation output type directly for synchronous completion, or {@link + * TemporalOperationResult} for explicit synchronous or asynchronous completion. *
* *

Workflow-run example: @@ -41,6 +42,17 @@ * } * } * + *

A synchronous operation can return its output directly. The SDK wraps the returned value in + * {@link TemporalOperationResult#sync(Object)} internally. The returned value may be null. A {@code + * void} method is supported for an operation with no output. + * + *

{@code
+ * @TemporalOperation
+ * public Greeting greet(TemporalNexusClient client, GreetingInput input) {
+ *   return new Greeting("Hello, " + input.getName());
+ * }
+ * }
+ * *

Access information about the current invocation through {@link NexusOperationContext#getInfo() * Nexus.getOperationContext().getInfo()}, including its cancellation token and {@linkplain * NexusOperationInfo#getRequestId() start request ID}. diff --git a/temporal-sdk/src/test/java/io/temporal/internal/nexus/TemporalOperationProcessorTest.java b/temporal-sdk/src/test/java/io/temporal/internal/nexus/TemporalOperationProcessorTest.java index e2eb07c84d..185665b843 100644 --- a/temporal-sdk/src/test/java/io/temporal/internal/nexus/TemporalOperationProcessorTest.java +++ b/temporal-sdk/src/test/java/io/temporal/internal/nexus/TemporalOperationProcessorTest.java @@ -52,6 +52,68 @@ public void happyPath_voidInputAndOutput() { TemporalOperationProcessor.process(new VoidIo()); } + @Test + public void directReturns_registerAndWrapResults() throws Exception { + DirectReturn handler = new DirectReturn(); + TemporalOperationProcessor.process(handler); + TemporalOperationResult result = invoke(handler, String.class, "direct"); + Assert.assertTrue(result.isSync()); + Assert.assertEquals("direct", result.getSyncResult()); + } + + @Test + public void directReturns_wrapNullAsSuccessfulSyncResult() throws Exception { + TemporalOperationResult result = invoke(new DirectReturn(), String.class, null); + Assert.assertNotNull(result); + Assert.assertTrue(result.isSync()); + Assert.assertNull(result.getSyncResult()); + } + + @Test + public void directReturns_preserveCompositeGenericValidation() { + TemporalOperationProcessor.process(new DirectComposite()); + IllegalArgumentException e = + assertInvalid(() -> TemporalOperationProcessor.process(new DirectCompositeBadOutput())); + Assert.assertTrue(e.getMessage(), e.getMessage().contains("output type mismatch")); + } + + @Test + public void directReturns_supportPrimitiveAndVoidResults() throws Exception { + DirectPrimitive primitive = new DirectPrimitive(); + TemporalOperationProcessor.process(primitive); + Assert.assertEquals(42, invoke(primitive, Integer.class, 42).getSyncResult()); + + DirectVoid noOutput = new DirectVoid(); + TemporalOperationProcessor.process(noOutput); + TemporalOperationResult result = invoke(noOutput, Void.class, null); + Assert.assertTrue(result.isSync()); + Assert.assertNull(result.getSyncResult()); + Assert.assertTrue(noOutput.invoked); + } + + @Test + public void directReturns_propagateOperationExceptionUnwrapped() throws Exception { + DirectFailure handler = new DirectFailure(); + TemporalOperationProcessor.process(handler); + io.nexusrpc.OperationException thrown = + Assert.assertThrows( + io.nexusrpc.OperationException.class, () -> invoke(handler, String.class, "input")); + Assert.assertSame(handler.failure, thrown); + } + + @Test + public void wrappedReturns_preserveSyncAndAsyncResults() throws Exception { + for (TemporalOperationResult expected : + java.util.Arrays.asList( + TemporalOperationResult.sync("wrapped"), + TemporalOperationResult.sync(null), + TemporalOperationResult.async("token"))) { + WrappedReturn handler = new WrappedReturn(expected); + TemporalOperationProcessor.process(handler); + Assert.assertSame(expected, invoke(handler, String.class, "input")); + } + } + @Test public void rejects_compositeGenericInputMismatch() { IllegalArgumentException e = @@ -116,6 +178,7 @@ public void invokeStartHandler_propagatesRuntimeExceptionUnwrapped() throws Exce Assert.assertThrows( IllegalStateException.class, () -> TemporalOperationProcessor.invokeStartHandler(handle, null, "in")); + Assert.assertSame(instance.failure, thrown); Assert.assertEquals("user-thrown", thrown.getMessage()); // First user frame is at the top — no reflective wrapper class in between. Assert.assertEquals(ThrowingHandler.class.getName(), thrown.getStackTrace()[0].getClassName()); @@ -125,8 +188,7 @@ public void invokeStartHandler_propagatesRuntimeExceptionUnwrapped() throws Exce public void rejects_badReturnType() { IllegalArgumentException e = assertInvalid(() -> TemporalOperationProcessor.process(new BadReturnType())); - Assert.assertTrue( - e.getMessage(), e.getMessage().contains("must return TemporalOperationResult")); + Assert.assertTrue(e.getMessage(), e.getMessage().contains("output type mismatch")); } @Test @@ -173,6 +235,14 @@ private static IllegalArgumentException assertInvalid(Runnable action) { return (IllegalArgumentException) wrapper.getCause(); } + private static TemporalOperationResult invoke( + Object instance, Class inputType, Object input) throws Exception { + java.lang.reflect.Method method = + instance.getClass().getMethod("op", TemporalNexusClient.class, inputType); + return TemporalOperationProcessor.invokeStartHandler( + java.lang.invoke.MethodHandles.lookup().unreflect(method).bindTo(instance), null, input); + } + // ----- Fixtures ----- @ServiceImpl(service = SingleOpService.class) @@ -185,12 +255,88 @@ public TemporalOperationResult op(TemporalNexusClient client, String inp @ServiceImpl(service = SingleOpService.class) public static class BadReturnType { + @TemporalOperation + public Integer op(TemporalNexusClient client, String input) { + return 42; + } + } + + @ServiceImpl(service = SingleOpService.class) + public static class DirectReturn { @TemporalOperation public String op(TemporalNexusClient client, String input) { return input; } } + @ServiceImpl(service = CompositeGenericService.class) + public static class DirectComposite { + @TemporalOperation + public java.util.List compose( + TemporalNexusClient client, java.util.Map input) { + return java.util.Collections.emptyList(); + } + } + + @ServiceImpl(service = CompositeGenericService.class) + public static class DirectCompositeBadOutput { + @TemporalOperation + public java.util.List compose( + TemporalNexusClient client, java.util.Map input) { + return java.util.Collections.emptyList(); + } + } + + @Service + public interface PrimitiveService { + @Operation + Integer op(Integer input); + } + + @ServiceImpl(service = PrimitiveService.class) + public static class DirectPrimitive { + @TemporalOperation + public int op(TemporalNexusClient client, Integer input) { + return input; + } + } + + @ServiceImpl(service = VoidIoService.class) + public static class DirectVoid { + boolean invoked; + + @TemporalOperation + public void op(TemporalNexusClient client, Void input) { + invoked = true; + } + } + + @ServiceImpl(service = SingleOpService.class) + public static class WrappedReturn { + private final TemporalOperationResult result; + + WrappedReturn(TemporalOperationResult result) { + this.result = result; + } + + @TemporalOperation + public TemporalOperationResult op(TemporalNexusClient client, String input) { + return result; + } + } + + @ServiceImpl(service = SingleOpService.class) + public static class DirectFailure { + final io.nexusrpc.OperationException failure = + io.nexusrpc.OperationException.failed(new IllegalArgumentException("direct failure")); + + @TemporalOperation + public String op(TemporalNexusClient client, String input) + throws io.nexusrpc.OperationException { + throw failure; + } + } + @ServiceImpl(service = SingleOpService.class) public static class BadArity { @TemporalOperation @@ -269,9 +415,11 @@ public TemporalOperationResult op(TemporalNexusClient client, String inp @ServiceImpl(service = SingleOpService.class) public static class ThrowingHandler { + final IllegalStateException failure = new IllegalStateException("user-thrown"); + @TemporalOperation public TemporalOperationResult op(TemporalNexusClient client, String input) { - throw new IllegalStateException("user-thrown"); + throw failure; } } diff --git a/temporal-sdk/src/test/java/io/temporal/workflow/nexus/TemporalOperationAnnotationTest.java b/temporal-sdk/src/test/java/io/temporal/workflow/nexus/TemporalOperationAnnotationTest.java index 6aa9700bae..84311c6ba0 100644 --- a/temporal-sdk/src/test/java/io/temporal/workflow/nexus/TemporalOperationAnnotationTest.java +++ b/temporal-sdk/src/test/java/io/temporal/workflow/nexus/TemporalOperationAnnotationTest.java @@ -1,11 +1,15 @@ package io.temporal.workflow.nexus; import io.nexusrpc.Operation; +import io.nexusrpc.OperationException; import io.nexusrpc.Service; import io.nexusrpc.handler.OperationHandler; import io.nexusrpc.handler.OperationImpl; import io.nexusrpc.handler.ServiceImpl; +import io.temporal.client.WorkflowFailedException; import io.temporal.client.WorkflowOptions; +import io.temporal.failure.ApplicationFailure; +import io.temporal.failure.NexusOperationFailure; import io.temporal.nexus.Nexus; import io.temporal.nexus.TemporalNexusClient; import io.temporal.nexus.TemporalOperation; @@ -17,6 +21,8 @@ import io.temporal.workflow.*; import io.temporal.workflow.shared.TestWorkflows; import java.time.Duration; +import java.util.Collections; +import java.util.List; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; @@ -30,9 +36,16 @@ public class TemporalOperationAnnotationTest { @Rule public SDKTestWorkflowRule testWorkflowRule = SDKTestWorkflowRule.newBuilder() - .setWorkflowTypes(SugarCaller.class, MixedCaller.class, SugarTargetWorkflowImpl.class) + .setWorkflowTypes( + SugarCaller.class, + MixedCaller.class, + SugarTargetWorkflowImpl.class, + DirectCaller.class) .setNexusServiceImplementation( - new SugarServiceImpl(), new SyncSugarServiceImpl(), new MixedServiceImpl()) + new SugarServiceImpl(), + new SyncSugarServiceImpl(), + new MixedServiceImpl(), + new DirectServiceImpl()) .build(); @Test @@ -56,8 +69,65 @@ public void mixedClass_bothOperationsReachable() { Assert.assertEquals("workflow:mixed-input|legacy:legacy-input", stub.execute("mixed-input")); } + @Test + public void directReturn_serializesDeclaredOutput() { + DirectCallerWorkflow stub = + testWorkflowRule.newWorkflowStubTimeoutOptions(DirectCallerWorkflow.class); + List result = stub.execute("hi"); + Assert.assertEquals(1, result.size()); + Assert.assertEquals("direct:hi", result.get(0).message); + } + + @Test + public void directReturn_nullOutputReachesCaller() { + DirectCallerWorkflow stub = + testWorkflowRule.newWorkflowStubTimeoutOptions(DirectCallerWorkflow.class); + Assert.assertNull(stub.execute("null-output")); + } + + @Test + public void directReturn_propagatesOperationFailure() { + DirectCallerWorkflow stub = + testWorkflowRule.newWorkflowStubTimeoutOptions(DirectCallerWorkflow.class); + WorkflowFailedException failure = + Assert.assertThrows(WorkflowFailedException.class, () -> stub.execute("fail")); + Assert.assertTrue(failure.getCause() instanceof NexusOperationFailure); + Throwable operationError = failure.getCause().getCause(); + Assert.assertTrue(operationError instanceof ApplicationFailure); + Assert.assertEquals("OperationError", ((ApplicationFailure) operationError).getType()); + Throwable cause = operationError.getCause(); + Assert.assertTrue(cause instanceof ApplicationFailure); + Assert.assertEquals( + IllegalArgumentException.class.getName(), ((ApplicationFailure) cause).getType()); + Assert.assertEquals("direct failure", ((ApplicationFailure) cause).getOriginalMessage()); + } + // ----- Caller workflows ----- + @WorkflowInterface + public interface DirectCallerWorkflow { + @WorkflowMethod + List execute(String input); + } + + public static class DirectCaller implements DirectCallerWorkflow { + @Override + public List execute(String input) { + return Workflow.newNexusServiceStub(DirectService.class, defaultServiceOptions()) + .greet(input); + } + } + + public static class Greeting { + public String message; + + public Greeting() {} + + public Greeting(String message) { + this.message = message; + } + } + @WorkflowInterface public interface SyncCallerWorkflow { @WorkflowMethod @@ -116,6 +186,27 @@ private static NexusServiceOptions defaultServiceOptions() { // ----- Nexus services ----- + @Service + public interface DirectService { + @Operation + List greet(String input); + } + + @ServiceImpl(service = DirectService.class) + public static class DirectServiceImpl { + @TemporalOperation + public List greet(TemporalNexusClient client, String input) + throws OperationException { + if ("fail".equals(input)) { + throw OperationException.failed(new IllegalArgumentException("direct failure")); + } + if ("null-output".equals(input)) { + return null; + } + return Collections.singletonList(new Greeting("direct:" + input)); + } + } + @Service public interface SugarService { @Operation