From 0af44192b62ea8bee1272c1a0086861f2a72ae85 Mon Sep 17 00:00:00 2001 From: Stephan Ewen Date: Tue, 17 Nov 2026 15:24:12 +0100 Subject: [PATCH] Add protocol tests for the V7 AwaitingOn message Restate Server will use AwaitingOnMessage to suspend idle invocations early, so the SDK must flush it before it parks waiting for input. Only the native (FFM) state machine implements protocol V7 and sends it. ProtocolConversation drives one invocation step by step, like the runtime: it withholds input until an expected message is decoded, so a message that is buffered instead of flushed makes the test time out. The V7 messages that the vendored V6 protocol.proto lacks are defined in a test-only proto, in a separate package. The tests cover: - a single await: flushed before blocking, and sent once - DurableFuture.all/any and Kotlin awaitAll/select: the reported tree, and the tree shrinking after partial progress - none while a ctx.run executes, then one while waiting for the ProposeRunCompletionAck - closing the input after AwaitingOn suspends with the same tree - none with protocol V6, on both the legacy and the native state machine The V7 tests are skipped when the native state machine is unavailable (JDK < 23, or no native library for the platform). --- .../dev/restate/sdk/core/AwaitingOnTest.java | 234 +++++++++++++++ .../sdk/core/ProtocolConversation.java | 271 ++++++++++++++++++ .../sdk/core/kotlinapi/AwaitingOnTest.kt | 114 ++++++++ .../restate/service/protocol_v7_test.proto | 52 ++++ 4 files changed, 671 insertions(+) create mode 100644 sdk-core/src/test/java/dev/restate/sdk/core/AwaitingOnTest.java create mode 100644 sdk-core/src/test/java/dev/restate/sdk/core/ProtocolConversation.java create mode 100644 sdk-core/src/test/kotlin/dev/restate/sdk/core/kotlinapi/AwaitingOnTest.kt create mode 100644 sdk-core/src/test/proto/dev/restate/service/protocol_v7_test.proto diff --git a/sdk-core/src/test/java/dev/restate/sdk/core/AwaitingOnTest.java b/sdk-core/src/test/java/dev/restate/sdk/core/AwaitingOnTest.java new file mode 100644 index 00000000..6757f5d2 --- /dev/null +++ b/sdk-core/src/test/java/dev/restate/sdk/core/AwaitingOnTest.java @@ -0,0 +1,234 @@ +// Copyright (c) 2023 - Restate Software, Inc., Restate GmbH +// +// This file is part of the Restate Java SDK, +// which is released under the MIT license. +// +// You can find a copy of the license in file LICENSE in the root +// directory of this repository or package, or at +// https://github.com/restatedev/sdk-java/blob/main/LICENSE +package dev.restate.sdk.core; + +import static dev.restate.sdk.core.ProtocolConversation.combinatorTypes; +import static dev.restate.sdk.core.ProtocolConversation.completionIds; +import static dev.restate.sdk.core.ProtocolConversation.proposeRunCompletionAck; +import static dev.restate.sdk.core.ProtocolConversation.sleepCompletion; +import static dev.restate.sdk.core.legacy.ProtoUtils.inputCmd; +import static dev.restate.sdk.core.legacy.ProtoUtils.outputCmd; +import static dev.restate.sdk.core.legacy.ProtoUtils.startMessage; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import dev.restate.common.function.ThrowingBiFunction; +import dev.restate.sdk.Context; +import dev.restate.sdk.DurableFuture; +import dev.restate.sdk.HandlerRunner; +import dev.restate.sdk.core.generated.protocol.Protocol; +import dev.restate.sdk.core.generated.protocolv7.ProtocolV7; +import dev.restate.sdk.core.generated.protocolv7.ProtocolV7.CombinatorType; +import dev.restate.sdk.endpoint.definition.HandlerDefinition; +import dev.restate.sdk.endpoint.definition.HandlerType; +import dev.restate.sdk.endpoint.definition.ServiceDefinition; +import dev.restate.sdk.endpoint.definition.ServiceType; +import dev.restate.serde.Serde; +import dev.restate.serde.jackson.JacksonSerdeFactory; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Protocol V7 {@code AwaitingOnMessage}: when user code blocks on futures that need input from the + * runtime, the SDK reports what it's awaiting, so the runtime can suspend the invocation early. It + * must be flushed before the SDK parks, otherwise the runtime never sees it. Only the native (FFM) + * state machine implements V7; those tests are skipped when it's unavailable. + */ +class AwaitingOnTest { + + private static ServiceDefinition service(ThrowingBiFunction body) { + return ServiceDefinition.of( + "AwaitingOn", + ServiceType.SERVICE, + List.of( + HandlerDefinition.of( + "run", + HandlerType.SHARED, + Serde.VOID, + TestSerdes.STRING, + HandlerRunner.of(body, new JacksonSerdeFactory(), null)))); + } + + private static ProtocolConversation v7(ThrowingBiFunction body) + throws Exception { + return ProtocolConversation.v7(service(body), "run"); + } + + @Test + void flushedBeforeBlockingOnSingleAwait() throws Exception { + try (var conv = + v7( + (ctx, in) -> { + ctx.sleep(Duration.ofSeconds(1)); + return "done"; + })) { + conv.send(startMessage(1), inputCmd()); + conv.expect(Protocol.SleepCommandMessage.class); + + // No more input until AwaitingOn is on the wire: if the SDK parks without flushing it, + // expect() times out. + var awaitingOn = conv.expect(ProtocolV7.AwaitingOnMessage.class); + assertThat(completionIds(awaitingOn.getAwaitingOn())).containsExactly(1); + assertThat(awaitingOn.getExecutingSideEffects()).isFalse(); + // Sent once per await point, not repeated while idle. + conv.expectNoOutputUntilIdle(); + + conv.send(sleepCompletion(1)); + assertThat(conv.expect(Protocol.OutputCommandMessage.class)).isEqualTo(outputCmd("done")); + conv.expect(Protocol.EndMessage.class); + conv.expectOutputClosed(); + } + } + + @Test + void allReportsTreeAndShrinksAfterPartialProgress() throws Exception { + try (var conv = + v7( + (ctx, in) -> { + DurableFuture.all(ctx.timer(Duration.ofSeconds(1)), ctx.timer(Duration.ofSeconds(2))) + .await(); + return "done"; + })) { + conv.send(startMessage(1), inputCmd()); + conv.expect(Protocol.SleepCommandMessage.class); + conv.expect(Protocol.SleepCommandMessage.class); + + var first = conv.expect(ProtocolV7.AwaitingOnMessage.class).getAwaitingOn(); + assertThat(completionIds(first)).containsExactlyInAnyOrder(1, 2); + assertThat(combinatorTypes(first)).contains(CombinatorType.ALL_SUCCEEDED_OR_FIRST_FAILED); + + // Still blocked after one completion: a new AwaitingOn with what's left. + conv.send(sleepCompletion(1)); + var second = conv.expect(ProtocolV7.AwaitingOnMessage.class).getAwaitingOn(); + assertThat(completionIds(second)).containsExactly(2); + + conv.send(sleepCompletion(2)); + assertThat(conv.expect(Protocol.OutputCommandMessage.class)).isEqualTo(outputCmd("done")); + conv.expect(Protocol.EndMessage.class); + } + } + + @Test + void anyReportsFirstCompletedTree() throws Exception { + try (var conv = + v7( + (ctx, in) -> + "winner-" + + DurableFuture.any( + ctx.timer(Duration.ofSeconds(1)), ctx.timer(Duration.ofSeconds(2))) + .await())) { + conv.send(startMessage(1), inputCmd()); + conv.expect(Protocol.SleepCommandMessage.class); + conv.expect(Protocol.SleepCommandMessage.class); + + var tree = conv.expect(ProtocolV7.AwaitingOnMessage.class).getAwaitingOn(); + assertThat(completionIds(tree)).containsExactlyInAnyOrder(1, 2); + assertThat(combinatorTypes(tree)) + .contains(CombinatorType.FIRST_COMPLETED) + .doesNotContain(CombinatorType.ALL_SUCCEEDED_OR_FIRST_FAILED); + + conv.send(sleepCompletion(2)); + assertThat(conv.expect(Protocol.OutputCommandMessage.class)).isEqualTo(outputCmd("winner-1")); + conv.expect(Protocol.EndMessage.class); + } + } + + @Test + void notSentWhileRunExecutesThenSentWhileWaitingForAck() throws Exception { + var runStarted = new CountDownLatch(1); + var releaseRun = new CountDownLatch(1); + try (var conv = + v7( + (ctx, in) -> + ctx.run( + "side-effect", + String.class, + () -> { + runStarted.countDown(); + releaseRun.await(); + return "ran"; + }))) { + conv.send(startMessage(1), inputCmd()); + conv.expect(Protocol.RunCommandMessage.class); + + assertThat(runStarted.await(10, TimeUnit.SECONDS)).isTrue(); + // The handler awaits the run, but the run is still executing: no AwaitingOn. + conv.expectNoOutputUntilIdle(); + + releaseRun.countDown(); + conv.expect(Protocol.ProposeRunCompletionMessage.class); + // Now it's waiting for the runtime to ack the proposal. + var awaitingOn = conv.expect(ProtocolV7.AwaitingOnMessage.class); + assertThat(completionIds(awaitingOn.getAwaitingOn())).containsExactly(1); + assertThat(awaitingOn.getExecutingSideEffects()).isFalse(); + + conv.send(proposeRunCompletionAck(1)); + assertThat(conv.expect(Protocol.OutputCommandMessage.class)).isEqualTo(outputCmd("ran")); + conv.expect(Protocol.EndMessage.class); + } finally { + releaseRun.countDown(); + } + } + + @Test + void inputCloseAfterAwaitingOnSuspendsOnSameTree() throws Exception { + try (var conv = + v7( + (ctx, in) -> { + ctx.sleep(Duration.ofSeconds(1)); + return "done"; + })) { + conv.send(startMessage(1), inputCmd()); + conv.expect(Protocol.SleepCommandMessage.class); + var awaitingOn = conv.expect(ProtocolV7.AwaitingOnMessage.class); + + conv.closeInput(); + var suspension = conv.expect(ProtocolV7.SuspensionMessage.class); + assertThat(suspension.getAwaitingOn()).isEqualTo(awaitingOn.getAwaitingOn()); + conv.expectOutputClosed(); + } + } + + static Stream stateMachines() { + return Stream.of( + Arguments.of("Legacy", StateMachineFactory.Loader.LEGACY_FACTORY), + Arguments.of("FFM", StateMachineFactory.Loader.FFM_FACTORY)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("stateMachines") + void notSentBelowV7(String name, StateMachineFactory stateMachineFactory) throws Exception { + assumeTrue(stateMachineFactory != null, name + " state machine unavailable"); + try (var conv = + new ProtocolConversation( + service( + (ctx, in) -> { + ctx.sleep(Duration.ofSeconds(1)); + return "done"; + }), + "run", + stateMachineFactory, + ProtocolConversation.V6)) { + conv.send(startMessage(1), inputCmd()); + conv.expect(Protocol.SleepCommandMessage.class); + conv.expectNoOutputUntilIdle(); + + conv.closeInput(); + conv.expect(Protocol.SuspensionMessage.class); + conv.expectOutputClosed(); + } + } +} diff --git a/sdk-core/src/test/java/dev/restate/sdk/core/ProtocolConversation.java b/sdk-core/src/test/java/dev/restate/sdk/core/ProtocolConversation.java new file mode 100644 index 00000000..b7bd48b5 --- /dev/null +++ b/sdk-core/src/test/java/dev/restate/sdk/core/ProtocolConversation.java @@ -0,0 +1,271 @@ +// Copyright (c) 2023 - Restate Software, Inc., Restate GmbH +// +// This file is part of the Restate Java SDK, +// which is released under the MIT license. +// +// You can find a copy of the license in file LICENSE in the root +// directory of this repository or package, or at +// https://github.com/restatedev/sdk-java/blob/main/LICENSE +package dev.restate.sdk.core; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.MessageLite; +import com.google.protobuf.MessageLiteOrBuilder; +import com.google.protobuf.Parser; +import dev.restate.common.Slice; +import dev.restate.sdk.core.generated.protocol.Protocol; +import dev.restate.sdk.core.generated.protocolv7.ProtocolV7; +import dev.restate.sdk.core.legacy.MessageType; +import dev.restate.sdk.core.legacy.ProtoUtils; +import dev.restate.sdk.endpoint.Endpoint; +import dev.restate.sdk.endpoint.HeadersAccessor; +import dev.restate.sdk.endpoint.definition.ServiceDefinition; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Flow; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +/** + * Drives one invocation over the raw service protocol step by step, like the runtime would: the + * test decides what to send next after looking at what the SDK wrote. Unlike {@link + * MockBidiStream}, which feeds a fixed input list and asserts on the final output, this lets a test + * withhold input until a message arrives, so a message the SDK buffers instead of flushing makes + * the test time out. + * + *

Besides the V6 messages known to {@link MessageType}, it encodes and decodes the V7 control + * messages defined in {@code src/test/proto/dev/restate/service/protocol_v7_test.proto}. + */ +public final class ProtocolConversation implements AutoCloseable { + + static final String V6 = "application/vnd.restate.invocation.v6"; + static final String V7 = "application/vnd.restate.invocation.v7"; + + private static final short AWAITING_ON_MESSAGE_TYPE = 0x0006; + private static final short PROPOSE_RUN_COMPLETION_ACK_MESSAGE_TYPE = 0x0007; + private static final long TIMEOUT_SECONDS = 10; + private static final Object OUTPUT_CLOSED = new Object(); + + private final ExecutorService coreExecutor = Executors.newSingleThreadExecutor(); + // Decoded messages, then OUTPUT_CLOSED or a Throwable. Written on the core thread. + private final BlockingQueue output = new LinkedBlockingQueue<>(); + private final boolean v7; + private final RequestProcessor processor; + // Bytes of an output frame split across chunks. Only accessed on the core thread. + private ByteBuffer partialFrame = ByteBuffer.allocate(0); + + /** + * Starts a V7 conversation with the native (FFM) state machine, the only one implementing V7. + * Aborts the calling test if it isn't available (JDK < 23, or no native library for this + * platform). + */ + public static ProtocolConversation v7(ServiceDefinition service, String handler) + throws Exception { + assumeTrue( + StateMachineFactory.Loader.FFM_FACTORY != null, + "the native state machine is unavailable (needs JDK 23+ and the native library)"); + return new ProtocolConversation(service, handler, StateMachineFactory.Loader.FFM_FACTORY, V7); + } + + ProtocolConversation( + ServiceDefinition service, + String handler, + StateMachineFactory stateMachineFactory, + String contentType) + throws Exception { + this.v7 = V7.equals(contentType); + EndpointRequestHandler server = + new EndpointRequestHandler( + null, Endpoint.builder().bind(service).build(), stateMachineFactory); + // Same wiring as MockBidiStream: create the processor and attach the output before any input, + // all on the single core thread. + this.processor = + coreExecutor + .submit( + () -> { + RequestProcessor p = + server.processorForRequest( + "/" + service.getServiceName() + "/" + handler, + HeadersAccessor.wrap(Map.of("content-type", contentType)), + EndpointRequestHandler.LoggingContextSetter.THREAD_LOCAL_INSTANCE, + coreExecutor, + true); + p.subscribe(new OutputSubscriber()); + p.onSubscribe( + new Flow.Subscription() { + @Override + public void request(long n) {} + + @Override + public void cancel() {} + }); + return p; + }) + .get(); + } + + // --- Input + + /** Sends the given messages and waits until the core thread has consumed them. */ + public void send(MessageLiteOrBuilder... messages) throws Exception { + List frames = new ArrayList<>(); + for (MessageLiteOrBuilder message : messages) { + frames.add(Slice.wrap(encode(ProtoUtils.build(message)))); + } + coreExecutor.submit(() -> frames.forEach(processor::onNext)).get(); + } + + /** Closes the input stream, as the runtime does to make the SDK suspend. */ + public void closeInput() throws Exception { + coreExecutor.submit(processor::onComplete).get(); + } + + // --- Output + + /** Returns the next output message; fails if none arrives in time or the output was closed. */ + public MessageLite next() throws InterruptedException { + Object o = output.poll(TIMEOUT_SECONDS, TimeUnit.SECONDS); + if (o == null) { + return fail("No output within %ss (was it buffered and never flushed?)", TIMEOUT_SECONDS); + } + if (o == OUTPUT_CLOSED) { + return fail("Output stream closed, expected another message"); + } + if (o instanceof Throwable t) { + return fail("Output stream failed", t); + } + return (MessageLite) o; + } + + /** Returns the next output message, asserting it is of the given type. */ + public T expect(Class type) throws InterruptedException { + MessageLite message = next(); + assertThat(message).isInstanceOf(type); + return type.cast(message); + } + + /** + * Waits until the core thread has run everything queued so far, then asserts the SDK wrote + * nothing more. The SDK writes output only from the core thread. + */ + public void expectNoOutputUntilIdle() throws Exception { + coreExecutor.submit(() -> {}).get(); + assertThat(output).isEmpty(); + } + + public void expectOutputClosed() throws InterruptedException { + assertThat(output.poll(TIMEOUT_SECONDS, TimeUnit.SECONDS)) + .as("output stream completion") + .isSameAs(OUTPUT_CLOSED); + } + + @Override + public void close() throws Exception { + coreExecutor.shutdown(); + assertThat(coreExecutor.awaitTermination(TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue(); + } + + // --- Message builders and AwaitingOn tree accessors + + public static Protocol.SleepCompletionNotificationMessage sleepCompletion(int completionId) { + return Protocol.SleepCompletionNotificationMessage.newBuilder() + .setCompletionId(completionId) + .setVoid(Protocol.Void.getDefaultInstance()) + .build(); + } + + public static ProtocolV7.ProposeRunCompletionAckMessage proposeRunCompletionAck( + int completionId) { + return ProtocolV7.ProposeRunCompletionAckMessage.newBuilder() + .setCompletionId(completionId) + .build(); + } + + /** Every completion id in the tree. */ + public static List completionIds(ProtocolV7.Future future) { + List ids = new ArrayList<>(future.getWaitingCompletionsList()); + future.getNestedFuturesList().forEach(nested -> ids.addAll(completionIds(nested))); + return ids; + } + + /** Every combinator type in the tree, root first. */ + public static List combinatorTypes(ProtocolV7.Future future) { + List types = new ArrayList<>(List.of(future.getCombinatorType())); + future.getNestedFuturesList().forEach(nested -> types.addAll(combinatorTypes(nested))); + return types; + } + + // --- Framing: 8-byte header (u16 type, u16 flags, u32 length), then the message + + private static ByteBuffer encode(MessageLite message) { + short type = + message instanceof ProtocolV7.ProposeRunCompletionAckMessage + ? PROPOSE_RUN_COMPLETION_ACK_MESSAGE_TYPE + : MessageType.fromMessage(message).encode(); + byte[] body = message.toByteArray(); + ByteBuffer frame = ByteBuffer.allocate(8 + body.length).order(ByteOrder.BIG_ENDIAN); + frame.putLong(((long) type << 48) | body.length); + frame.put(body); + return frame.flip(); + } + + private Parser parserFor(short type) { + if (type == AWAITING_ON_MESSAGE_TYPE) { + return ProtocolV7.AwaitingOnMessage.parser(); + } + if (type == MessageType.SuspensionMessage_TYPE && v7) { + return ProtocolV7.SuspensionMessage.parser(); + } + return MessageType.decode(type).messageParser(); + } + + private final class OutputSubscriber implements Flow.Subscriber { + @Override + public void onSubscribe(Flow.Subscription subscription) { + subscription.request(Long.MAX_VALUE); + } + + @Override + public void onNext(Slice chunk) { + ByteBuffer in = chunk.asReadOnlyByteBuffer(); + ByteBuffer buf = ByteBuffer.allocate(partialFrame.remaining() + in.remaining()); + buf.put(partialFrame).put(in).flip(); + try { + while (buf.remaining() >= 8) { + long header = buf.getLong(buf.position()); + int length = (int) header; + if (buf.remaining() < 8 + length) { + break; + } + buf.position(buf.position() + 8); + byte[] body = new byte[length]; + buf.get(body); + output.add(parserFor((short) (header >>> 48)).parseFrom(body)); + } + } catch (InvalidProtocolBufferException | RuntimeException e) { + output.add(e); + } + partialFrame = buf.slice(); + } + + @Override + public void onError(Throwable throwable) { + output.add(throwable); + } + + @Override + public void onComplete() { + output.add(OUTPUT_CLOSED); + } + } +} diff --git a/sdk-core/src/test/kotlin/dev/restate/sdk/core/kotlinapi/AwaitingOnTest.kt b/sdk-core/src/test/kotlin/dev/restate/sdk/core/kotlinapi/AwaitingOnTest.kt new file mode 100644 index 00000000..74237789 --- /dev/null +++ b/sdk-core/src/test/kotlin/dev/restate/sdk/core/kotlinapi/AwaitingOnTest.kt @@ -0,0 +1,114 @@ +// Copyright (c) 2023 - Restate Software, Inc., Restate GmbH +// +// This file is part of the Restate Java SDK, +// which is released under the MIT license. +// +// You can find a copy of the license in file LICENSE in the root +// directory of this repository or package, or at +// https://github.com/restatedev/sdk-java/blob/main/LICENSE +package dev.restate.sdk.core.kotlinapi + +import dev.restate.sdk.core.ProtocolConversation +import dev.restate.sdk.core.ProtocolConversation.combinatorTypes +import dev.restate.sdk.core.ProtocolConversation.completionIds +import dev.restate.sdk.core.ProtocolConversation.sleepCompletion +import dev.restate.sdk.core.generated.protocol.Protocol +import dev.restate.sdk.core.generated.protocolv7.ProtocolV7 +import dev.restate.sdk.core.generated.protocolv7.ProtocolV7.CombinatorType +import dev.restate.sdk.core.legacy.ProtoUtils.inputCmd +import dev.restate.sdk.core.legacy.ProtoUtils.outputCmd +import dev.restate.sdk.core.legacy.ProtoUtils.startMessage +import dev.restate.sdk.endpoint.definition.HandlerDefinition +import dev.restate.sdk.endpoint.definition.HandlerType +import dev.restate.sdk.endpoint.definition.ServiceDefinition +import dev.restate.sdk.endpoint.definition.ServiceType +import dev.restate.sdk.kotlin.* +import dev.restate.serde.kotlinx.* +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.Dispatchers +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +/** + * The Kotlin combinators report the same AwaitingOn trees as the Java ones, see + * [dev.restate.sdk.core.AwaitingOnTest]. + */ +class AwaitingOnTest { + + private fun v7(body: suspend (Context, Unit) -> String): ProtocolConversation = + ProtocolConversation.v7( + ServiceDefinition.of( + "AwaitingOn", + ServiceType.SERVICE, + listOf( + HandlerDefinition.of( + "run", + HandlerType.SHARED, + jsonSerde(), + jsonSerde(), + HandlerRunner.of( + KotlinSerializationSerdeFactory(), + HandlerRunner.Options(Dispatchers.Unconfined), + body, + ), + ) + ), + ), + "run", + ) + + @Test + fun awaitAllReportsTreeAndShrinksAfterPartialProgress() { + v7 { ctx, _ -> + listOf(ctx.timer(1.seconds), ctx.timer(2.seconds)).awaitAll() + "done" + } + .use { conv -> + conv.send(startMessage(1), inputCmd()) + conv.expect(Protocol.SleepCommandMessage::class.java) + conv.expect(Protocol.SleepCommandMessage::class.java) + + val first = conv.expect(ProtocolV7.AwaitingOnMessage::class.java).awaitingOn + assertThat(completionIds(first)).containsExactlyInAnyOrder(1, 2) + assertThat(combinatorTypes(first)).contains(CombinatorType.ALL_SUCCEEDED_OR_FIRST_FAILED) + + conv.send(sleepCompletion(1)) + val second = conv.expect(ProtocolV7.AwaitingOnMessage::class.java).awaitingOn + assertThat(completionIds(second)).containsExactly(2) + + conv.send(sleepCompletion(2)) + assertThat(conv.expect(Protocol.OutputCommandMessage::class.java)) + .isEqualTo(outputCmd("done")) + conv.expect(Protocol.EndMessage::class.java) + } + } + + @Test + fun selectReportsFirstCompletedTree() { + v7 { ctx, _ -> + val first = ctx.timer(1.seconds) + val second = ctx.timer(2.seconds) + select { + first.onAwait { "first" } + second.onAwait { "second" } + } + .await() + } + .use { conv -> + conv.send(startMessage(1), inputCmd()) + conv.expect(Protocol.SleepCommandMessage::class.java) + conv.expect(Protocol.SleepCommandMessage::class.java) + + val tree = conv.expect(ProtocolV7.AwaitingOnMessage::class.java).awaitingOn + assertThat(completionIds(tree)).containsExactlyInAnyOrder(1, 2) + assertThat(combinatorTypes(tree)) + .contains(CombinatorType.FIRST_COMPLETED) + .doesNotContain(CombinatorType.ALL_SUCCEEDED_OR_FIRST_FAILED) + + conv.send(sleepCompletion(2)) + assertThat(conv.expect(Protocol.OutputCommandMessage::class.java)) + .isEqualTo(outputCmd("second")) + conv.expect(Protocol.EndMessage::class.java) + } + } +} diff --git a/sdk-core/src/test/proto/dev/restate/service/protocol_v7_test.proto b/sdk-core/src/test/proto/dev/restate/service/protocol_v7_test.proto new file mode 100644 index 00000000..90b74c8c --- /dev/null +++ b/sdk-core/src/test/proto/dev/restate/service/protocol_v7_test.proto @@ -0,0 +1,52 @@ +// Copyright (c) 2023 - Restate Software, Inc., Restate GmbH +// +// This file is part of the Restate Java SDK, +// which is released under the MIT license. +// +// You can find a copy of the license in file LICENSE in the root +// directory of this repository or package, or at +// https://github.com/restatedev/sdk-java/blob/main/LICENSE + +// Test-only subset of service protocol V7: the messages the vendored V6 protocol.proto +// (src/main/service-protocol) lacks or defines differently. Field numbers match +// restatedev/service-protocol; the proto and Java packages differ on purpose, so these don't clash +// with the main generated classes. Drop this file if the vendored protocol.proto moves to V7. +syntax = "proto3"; + +package dev.restate.service.protocol.v7test; + +option java_package = "dev.restate.sdk.core.generated.protocolv7"; +option java_outer_classname = "ProtocolV7"; + +enum CombinatorType { + COMBINATOR_TYPE_UNKNOWN = 0; + FIRST_COMPLETED = 1; + ALL_COMPLETED = 2; + FIRST_SUCCEEDED_OR_ALL_FAILED = 3; + ALL_SUCCEEDED_OR_FIRST_FAILED = 4; +} + +message Future { + repeated uint32 waiting_completions = 1; + repeated uint32 waiting_signals = 2; + repeated string waiting_named_signals = 3; + repeated Future nested_futures = 4; + CombinatorType combinator_type = 5; +} + +// Type: 0x0001. In V7 the V6 waiting_* fields are replaced by awaiting_on. +message SuspensionMessage { + reserved 1, 2, 3; + Future awaiting_on = 4; +} + +// Type: 0x0006 +message AwaitingOnMessage { + Future awaiting_on = 1; + bool executing_side_effects = 2; +} + +// Type: 0x0007 +message ProposeRunCompletionAckMessage { + uint32 completion_id = 1; +}