diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StepFunctionsNestedSmTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StepFunctionsNestedSmTest.java index be8705a63e..846e86b1d2 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StepFunctionsNestedSmTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StepFunctionsNestedSmTest.java @@ -8,9 +8,9 @@ import static org.assertj.core.api.Assertions.*; /** * Compatibility tests for nested state machine execution via optimised integrations: - * arn:aws:states:::states:startExecution (fire-and-forget) - * arn:aws:states:::states:startExecution.sync (wait, return full execution envelope) - * arn:aws:states:::states:startExecution.sync:2 (wait, return only child output) + * arn:aws:states:::states:startExecution (fire-and-forget, return the StartExecution response) + * arn:aws:states:::states:startExecution.sync (wait, return the execution envelope, Output a JSON string) + * arn:aws:states:::states:startExecution.sync:2 (wait, return the execution envelope, Output a JSON value) * * Covers Issue #254. */ @@ -62,7 +62,7 @@ class StepFunctionsNestedSmTest { @Test @Order(1) - void sync2_parentReceivesChildOutputDirectly() throws InterruptedException { + void sync2_parentReceivesEnvelopeWithOutputAsJsonValue() throws InterruptedException { String parentDef = """ { "StartAt": "InvokeChild", @@ -93,11 +93,12 @@ class StepFunctionsNestedSmTest { DescribeExecutionResponse result = pollUntilDone(execArn); assertThat(result.status()).isEqualTo(ExecutionStatus.SUCCEEDED); - // Output must be the child's parsed output object, not an envelope + // Output must be the PascalCase envelope, with the child's output as a JSON value assertThat(result.output()) - .contains("\"computed\":true") - .contains("\"value\":42") - .doesNotContain("executionArn"); + .contains("\"ExecutionArn\"") + .contains("\"Status\":\"SUCCEEDED\"") + .contains("\"Input\":{\"trigger\":\"sync2\"}") + .contains("\"Output\":{\"computed\":true,\"value\":42}"); } finally { try { sfn.deleteStateMachine(b -> b.stateMachineArn(parentSmArn)); } catch (Exception ignored) {} } @@ -138,11 +139,12 @@ class StepFunctionsNestedSmTest { DescribeExecutionResponse result = pollUntilDone(execArn); assertThat(result.status()).isEqualTo(ExecutionStatus.SUCCEEDED); - // Output must be the full envelope: executionArn, status, output (as a string), etc. + // Output must be the PascalCase envelope, with the child's output as a JSON string assertThat(result.output()) - .contains("executionArn") - .contains("\"SUCCEEDED\"") - .contains("\"output\""); + .contains("\"ExecutionArn\"") + .contains("\"Status\":\"SUCCEEDED\"") + .contains("\"Input\":\"{\\\"trigger\\\":\\\"sync\\\"}\"") + .contains("\"Output\":\"{\\\"computed\\\":true,\\\"value\\\":42}\""); } finally { try { sfn.deleteStateMachine(b -> b.stateMachineArn(parentSmArn)); } catch (Exception ignored) {} } @@ -183,10 +185,10 @@ class StepFunctionsNestedSmTest { DescribeExecutionResponse result = pollUntilDone(execArn); assertThat(result.status()).isEqualTo(ExecutionStatus.SUCCEEDED); - // Output must be { executionArn, startDate } — no child output + // Output must be { ExecutionArn, StartDate } with no child output assertThat(result.output()) - .contains("executionArn") - .contains("startDate") + .contains("\"ExecutionArn\"") + .contains("\"StartDate\"") .doesNotContain("\"SUCCEEDED\""); } finally { try { sfn.deleteStateMachine(b -> b.stateMachineArn(parentSmArn)); } catch (Exception ignored) {} diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index 19c71319dc..3c41c5ec6b 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -433,14 +433,24 @@ more than syntax: | Resource | Child type | A child that fails | Result | | --- | --- | --- | --- | -| `arn:aws:states:::states:startExecution` | Standard | not awaited | `{executionArn, startDate}` | -| `arn:aws:states:::states:startExecution.sync` | Standard | fails the calling task | execution envelope, `output` as a JSON string | -| `arn:aws:states:::states:startExecution.sync:2` | Standard | fails the calling task | the child output, parsed | -| `arn:aws:states:::aws-sdk:sfn:startExecution` | Standard | not awaited | `{ExecutionArn, StartDate}` | +| `arn:aws:states:::states:startExecution` | Standard | not awaited | `{ExecutionArn, StartDate}`, `StartDate` in epoch milliseconds | +| `arn:aws:states:::states:startExecution.sync` | Standard | fails the calling task | execution envelope, `Input` and `Output` as JSON strings | +| `arn:aws:states:::states:startExecution.sync:2` | Standard | fails the calling task | execution envelope, `Input` and `Output` as JSON values | +| `arn:aws:states:::aws-sdk:sfn:startExecution` | Standard | not awaited | `{ExecutionArn, StartDate}`, `StartDate` as an ISO-8601 string | | `arn:aws:states:::aws-sdk:sfn:startSyncExecution` | Express | reported through `Status` | PascalCase envelope, `Output` as a JSON string | `states:startExecution` and `aws-sdk:sfn:startExecution` are the same API through two different -integrations, and only the casing of the result tells them apart. +integrations, and only the format of `StartDate` tells their results apart. AWS also adds +`SdkHttpMetadata` and `SdkResponseMetadata` to the `states:startExecution` result, which Floci +omits. + +The execution envelope of the two `.sync` modes is the child's `DescribeExecution` response, +PascalCase with its keys in alphabetical order and dates in epoch milliseconds: `ExecutionArn`, +`Input`, `InputDetails`, `Name`, `Output`, `OutputDetails`, `RedriveCount`, `RedriveStatus`, +`RedriveStatusReason`, `StartDate`, `StateMachineArn`, `Status` and `StopDate`. So the child's +output is at `$.Output` in both modes: a JSON string through `.sync`, to read with +`States.StringToJson`, and a JSON value through `.sync:2`, to read directly, for example with a +`ResultSelector` or `OutputPath` of `$.Output`. `startSyncExecution` is the only one that does not fail the calling task when the child fails: the SDK call itself succeeded, so the task result carries `Status`, `Error` and `Cause` and the parent diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java index cf745b619a..0d5adb38c0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java @@ -1448,10 +1448,10 @@ public class AslExecutor { } /** - * AWS SDK integration for {@code sfn:startExecution}. Unlike the optimized - * {@code states:startExecution}, which returns {@code executionArn} and {@code startDate} in - * the casing of the wire response, this one returns the SDK's own {@code ExecutionArn} and an - * ISO-8601 {@code StartDate}. Neither waits for the child. + * AWS SDK integration for {@code sfn:startExecution}. Both this and the optimized + * {@code states:startExecution} return {@code ExecutionArn} and {@code StartDate}; the + * optimized one carries {@code StartDate} in epoch milliseconds, this one as an ISO-8601 + * string. Neither waits for the child. */ private JsonNode invokeAwsSdkSfnStartExecution(JsonNode input, String region) throws Exception { String smArn = input.path("StateMachineArn").asText(null); @@ -1636,9 +1636,9 @@ public class AslExecutor { /** * AWS SDK integration for {@code sfn:startSyncExecution}, the way an EXPRESS child workflow is * called. It differs from the optimized {@code states:startExecution.sync} integration in three - * ways: the child must be EXPRESS, the response envelope uses PascalCase field names with - * {@code Output} as a JSON string, and a child execution that fails is reported through - * {@code Status} rather than failing the calling task. + * ways: the child must be EXPRESS, the response envelope is the SDK's StartSyncExecution + * response rather than the DescribeExecution one, and a child execution that fails is reported + * through {@code Status} rather than failing the calling task. */ private JsonNode invokeAwsSdkSfnStartSyncExecution(JsonNode input, String region) throws Exception { String smArn = input.path("StateMachineArn").asText(null); @@ -1719,19 +1719,16 @@ public class AslExecutor { } String execArn = exec.getExecutionArn(); - if ("".equals(mode)) { - // Fire-and-forget: return { executionArn, startDate } - ObjectNode result = objectMapper.createObjectNode(); - result.put("executionArn", execArn); - result.put("startDate", exec.getStartDate()); - return result; - } - - // The job is submitted: AWS records the StartExecution response here, before the wait - // (measured: PascalCase, StartDate in epoch milliseconds). + // The StartExecution response as this integration reports it (measured: PascalCase, + // StartDate in epoch milliseconds). Request-response returns it as the Task result. ObjectNode startResponse = objectMapper.createObjectNode(); startResponse.put("ExecutionArn", execArn); startResponse.put("StartDate", Math.round(exec.getStartDate() * 1000)); + if ("".equals(mode)) { + return startResponse; + } + + // The job is submitted: AWS records the same response here, before the wait. try { jobSubmitted.accept(startResponse); } catch (RuntimeException e) { @@ -1771,70 +1768,74 @@ public class AslExecutor { continue; } if ("SUCCEEDED".equals(status)) { - if (".sync:2".equals(mode)) { - String out = current.getOutput(); - return objectMapper.readTree(out != null ? out : "null"); - } - // .sync — full execution envelope; output field is a JSON string - ObjectNode envelope = objectMapper.createObjectNode(); - envelope.put("executionArn", current.getExecutionArn()); - envelope.put("stateMachineArn", current.getStateMachineArn()); - envelope.put("name", current.getName()); - envelope.put("status", current.getStatus()); - envelope.put("startDate", current.getStartDate()); - if (current.getStopDate() != null) { - envelope.put("stopDate", current.getStopDate()); - } - if (current.getInput() != null) { - envelope.put("input", current.getInput()); - } - if (current.getOutput() != null) { - envelope.put("output", current.getOutput()); - } - return envelope; + // Both modes return the envelope (measured); .sync:2 differs only in carrying + // Input and Output as JSON values where .sync carries them as JSON strings. + return nestedExecutionEnvelope(current, true, ".sync:2".equals(mode)); } // However the child ended, FAILED, TIMED_OUT or ABORTED, and whatever its own error, the // parent sees States.TaskFailed (measured), so a Catch on the child's error never fires. - throw new FailStateException("States.TaskFailed", nestedExecutionFailureCause(current)); + throw new FailStateException("States.TaskFailed", + nestedExecutionEnvelope(current, false, false).toString()); } } /** - * The cause of a {@code .sync} Task whose child ended other than SUCCEEDED, as measured on AWS - * for {@code .sync} and {@code .sync:2} alike: the child's DescribeExecution response in - * PascalCase with its keys in alphabetical order, {@code Cause} and {@code Error} only when the - * child has them, {@code StateMachineAliasArn} and {@code StateMachineVersionArn} only when it - * was started through an alias or a version (an alias carries both), dates in epoch - * milliseconds, and no {@code Output}. Floci does not implement - * redrive, so the two redrive fields carry what AWS reports for a child never redriven. + * The child's DescribeExecution response as a {@code .sync} or {@code .sync:2} Task reports it + * (measured on AWS): PascalCase with its keys in alphabetical order, dates in epoch + * milliseconds, {@code StateMachineAliasArn} and {@code StateMachineVersionArn} only when the + * child was started through an alias or a version (an alias carries both). + * + *

A child that SUCCEEDED is the Task result: it carries {@code Output}, {@code OutputDetails} + * and {@code RedriveStatusReason}, and {@code .sync:2} carries {@code Input} and {@code Output} + * as JSON values ({@code payloadsAsJson}) where {@code .sync} carries JSON strings. A child that + * ended any other way is the cause of the failed Task, the same for both modes: {@code Cause} + * and {@code Error} only when the child has them, and no {@code Output}. Floci does not + * implement redrive, so the redrive fields carry what AWS reports for a child never redriven. */ - private String nestedExecutionFailureCause(Execution child) { - ObjectNode cause = objectMapper.createObjectNode(); - if (child.getCause() != null) { - cause.put("Cause", child.getCause()); + private ObjectNode nestedExecutionEnvelope(Execution child, boolean succeeded, boolean payloadsAsJson) + throws JsonProcessingException { + ObjectNode envelope = objectMapper.createObjectNode(); + if (!succeeded && child.getCause() != null) { + envelope.put("Cause", child.getCause()); } - if (child.getError() != null) { - cause.put("Error", child.getError()); + if (!succeeded && child.getError() != null) { + envelope.put("Error", child.getError()); } - cause.put("ExecutionArn", child.getExecutionArn()); - cause.put("Input", child.getInput() != null ? child.getInput() : "{}"); - cause.putObject("InputDetails").put("Included", true); - cause.put("Name", child.getName()); - cause.put("RedriveCount", 0); - cause.put("RedriveStatus", "REDRIVABLE"); - cause.put("StartDate", Math.round(child.getStartDate() * 1000)); + envelope.put("ExecutionArn", child.getExecutionArn()); + String input = child.getInput() != null ? child.getInput() : "{}"; + if (payloadsAsJson) { + envelope.set("Input", objectMapper.readTree(input)); + } else { + envelope.put("Input", input); + } + envelope.putObject("InputDetails").put("Included", true); + envelope.put("Name", child.getName()); + if (succeeded && child.getOutput() != null) { + if (payloadsAsJson) { + envelope.set("Output", objectMapper.readTree(child.getOutput())); + } else { + envelope.put("Output", child.getOutput()); + } + envelope.putObject("OutputDetails").put("Included", true); + } + envelope.put("RedriveCount", 0); + envelope.put("RedriveStatus", succeeded ? "NOT_REDRIVABLE" : "REDRIVABLE"); + if (succeeded) { + envelope.put("RedriveStatusReason", "Execution is SUCCEEDED and cannot be redriven"); + } + envelope.put("StartDate", Math.round(child.getStartDate() * 1000)); if (child.getStateMachineAliasArn() != null) { - cause.put("StateMachineAliasArn", child.getStateMachineAliasArn()); + envelope.put("StateMachineAliasArn", child.getStateMachineAliasArn()); } - cause.put("StateMachineArn", child.getStateMachineArn()); + envelope.put("StateMachineArn", child.getStateMachineArn()); if (child.getStateMachineVersionArn() != null) { - cause.put("StateMachineVersionArn", child.getStateMachineVersionArn()); + envelope.put("StateMachineVersionArn", child.getStateMachineVersionArn()); } - cause.put("Status", child.getStatus()); + envelope.put("Status", child.getStatus()); if (child.getStopDate() != null) { - cause.put("StopDate", Math.round(child.getStopDate() * 1000)); + envelope.put("StopDate", Math.round(child.getStopDate() * 1000)); } - return cause.toString(); + return envelope; } /** diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedStartExecutionTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedStartExecutionTest.java index 1f14c130a7..89ccf189ea 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedStartExecutionTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedStartExecutionTest.java @@ -272,31 +272,72 @@ class AslExecutorNestedStartExecutionTest { assertEquals("StepFunctions.StateMachineDoesNotExistException", exec.getError()); } - @ParameterizedTest - @ValueSource(strings = {".sync", ".sync:2"}) - void syncChildSuccessIsUndisturbedByTheWrap(String mode) throws Exception { - // Regression guard: wrapping the start call in try/catch must not disturb the .sync/.sync:2 - // success branches. The child starts RUNNING (setUp) then the poll observes it SUCCEEDED. - Execution done = new Execution(); - done.setExecutionArn("arn:aws:states:us-east-1:000000000000:execution:child:e1"); - done.setStateMachineArn(CHILD_ARN); - done.setName("e1"); - done.setStatus("SUCCEEDED"); - done.setStartDate(1.0); - done.setStopDate(2.0); - done.setOutput("{\"ok\":true}"); - when(childSfn.describeExecution(any())).thenReturn(done); + /** + * Measured on AWS: .sync returns the child's DescribeExecution response in PascalCase, keys in + * alphabetical order, dates in epoch milliseconds, Input and Output as JSON strings. + */ + @Test + void syncReturnsTheExecutionEnvelopeWithPayloadsAsJsonStrings() { + childSucceeds(); - Execution exec = runParent(parentMode(mode), "{}"); - assertEquals("SUCCEEDED", exec.getStatus()); - var output = mapper.readTree(exec.getOutput()); - if (".sync:2".equals(mode)) { - assertTrue(output.path("ok").asBoolean(), "sync:2 returns the parsed child output"); - } else { - assertEquals("SUCCEEDED", output.path("status").asText(), "sync returns the execution envelope"); - assertEquals("{\"ok\":true}", output.path("output").asText(), "envelope output is the child output JSON string"); - } + Execution exec = runParent(parentMode(".sync"), "{}"); + + assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause()); + assertEquals("{\"ExecutionArn\":\"arn:aws:states:us-east-1:000000000000:execution:child:e1\"," + + "\"Input\":\"{\\\"k\\\":1}\",\"InputDetails\":{\"Included\":true},\"Name\":\"e1\"," + + "\"Output\":\"{\\\"ok\\\":true}\",\"OutputDetails\":{\"Included\":true}," + + "\"RedriveCount\":0,\"RedriveStatus\":\"NOT_REDRIVABLE\"," + + "\"RedriveStatusReason\":\"Execution is SUCCEEDED and cannot be redriven\"," + + "\"StartDate\":1000,\"StateMachineArn\":\"" + CHILD_ARN + "\"," + + "\"Status\":\"SUCCEEDED\",\"StopDate\":2000}", exec.getOutput()); } + + /** Measured on AWS: .sync:2 returns the same envelope with Input and Output as JSON values. */ + @Test + void sync2ReturnsTheExecutionEnvelopeWithPayloadsAsJsonValues() { + childSucceeds(); + + Execution exec = runParent(parentMode(".sync:2"), "{}"); + + assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause()); + assertEquals("{\"ExecutionArn\":\"arn:aws:states:us-east-1:000000000000:execution:child:e1\"," + + "\"Input\":{\"k\":1},\"InputDetails\":{\"Included\":true},\"Name\":\"e1\"," + + "\"Output\":{\"ok\":true},\"OutputDetails\":{\"Included\":true}," + + "\"RedriveCount\":0,\"RedriveStatus\":\"NOT_REDRIVABLE\"," + + "\"RedriveStatusReason\":\"Execution is SUCCEEDED and cannot be redriven\"," + + "\"StartDate\":1000,\"StateMachineArn\":\"" + CHILD_ARN + "\"," + + "\"Status\":\"SUCCEEDED\",\"StopDate\":2000}", exec.getOutput()); + } + + /** Measured on AWS: a child started through an alias carries the alias and its version. */ + @Test + void syncEnvelopeCarriesTheAliasAndVersionTheChildWasStartedThrough() throws Exception { + Execution done = childSucceeds(); + done.setStateMachineAliasArn(CHILD_ARN + ":live"); + done.setStateMachineVersionArn(CHILD_ARN + ":1"); + + Execution exec = runParent(parentMode(".sync:2"), "{}"); + + List keys = new ArrayList<>(); + mapper.readTree(exec.getOutput()).fieldNames().forEachRemaining(keys::add); + assertEquals(List.of("ExecutionArn", "Input", "InputDetails", "Name", "Output", "OutputDetails", + "RedriveCount", "RedriveStatus", "RedriveStatusReason", "StartDate", "StateMachineAliasArn", + "StateMachineArn", "StateMachineVersionArn", "Status", "StopDate"), keys); + } + + /** + * Measured on AWS: request-response returns the StartExecution response in PascalCase with + * StartDate in epoch milliseconds (and the SDK metadata, which Floci omits). + */ + @Test + void requestResponseReturnsTheStartExecutionResponseInPascalCase() { + Execution exec = runParent(parentMode(""), "{}"); + + assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause()); + assertEquals("{\"ExecutionArn\":\"arn:aws:states:us-east-1:000000000000:execution:child:e1\"," + + "\"StartDate\":1000}", exec.getOutput()); + } + /** * AWS records TaskSubmitted once StartExecution has returned and before it waits on the child * (measured: resourceType states, resource startExecution.sync:2, the response in PascalCase with @@ -360,7 +401,7 @@ class AslExecutorNestedStartExecutionTest { assertFalse(types().contains("TaskSubmitted"), types().toString()); } - private void childSucceeds() { + private Execution childSucceeds() { Execution done = new Execution(); done.setExecutionArn("arn:aws:states:us-east-1:000000000000:execution:child:e1"); done.setStateMachineArn(CHILD_ARN); @@ -368,8 +409,10 @@ class AslExecutorNestedStartExecutionTest { done.setStatus("SUCCEEDED"); done.setStartDate(1.0); done.setStopDate(2.0); + done.setInput("{\"k\":1}"); done.setOutput("{\"ok\":true}"); when(childSfn.describeExecution(any())).thenReturn(done); + return done; } private List types() { diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedSyncTimeoutTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedSyncTimeoutTest.java index 1dfffb9c5e..595c3452ac 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedSyncTimeoutTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedSyncTimeoutTest.java @@ -118,7 +118,7 @@ class AslExecutorNestedSyncTimeoutTest { assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause()); assertEquals(700, polls.get()); - assertTrue(objectMapper.readTree(execution.getOutput()).path("output").asText().contains("42")); + assertTrue(objectMapper.readTree(execution.getOutput()).path("Output").asText().contains("42")); verify(sfnService, never()).stopExecution(any(), any(), any()); } diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNestedStartExecutionResultIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNestedStartExecutionResultIntegrationTest.java new file mode 100644 index 0000000000..1fe598329b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNestedStartExecutionResultIntegrationTest.java @@ -0,0 +1,182 @@ +package io.github.hectorvent.floci.services.stepfunctions; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * The Task result of {@code states:startExecution} in its three modes, the way AWS returns it + * (measured in ap-northeast-1 on 2026-09-30): the StartExecution response for request-response and + * the child's DescribeExecution response for {@code .sync} and {@code .sync:2}, all PascalCase with + * dates in epoch milliseconds, {@code .sync:2} carrying {@code Input} and {@code Output} as JSON + * values where {@code .sync} carries JSON strings. + */ +@QuarkusTest +class StepFunctionsNestedStartExecutionResultIntegrationTest { + + private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0"; + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role"; + private static final List ENVELOPE_KEYS = List.of("ExecutionArn", "Input", "InputDetails", "Name", + "Output", "OutputDetails", "RedriveCount", "RedriveStatus", "RedriveStatusReason", "StartDate", + "StateMachineArn", "Status", "StopDate"); + private static final ObjectMapper mapper = new ObjectMapper(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void eachModeReturnsItsPascalCaseResult() throws Exception { + String childArn = createStateMachine("nested-result-child", """ + {"StartAt": "D", "States": {"D": {"Type": "Pass", "Result": {"ok": true}, "End": true}}} + """); + String parentArn = createStateMachine("nested-result-parent", """ + { + "StartAt": "RR", + "States": { + "RR": { + "Type": "Task", + "Resource": "arn:aws:states:::states:startExecution", + "Parameters": {"StateMachineArn": "%1$s", "Input": {"k": 1}}, + "ResultPath": "$.rr", + "Next": "Sync" + }, + "Sync": { + "Type": "Task", + "Resource": "arn:aws:states:::states:startExecution.sync", + "Parameters": {"StateMachineArn": "%1$s", "Input": {"k": 1}}, + "ResultPath": "$.sync", + "Next": "Sync2" + }, + "Sync2": { + "Type": "Task", + "Resource": "arn:aws:states:::states:startExecution.sync:2", + "Parameters": {"StateMachineArn": "%1$s", "Input": {"k": 1}}, + "ResultPath": "$.sync2", + "Next": "Unwrap" + }, + "Unwrap": { + "Type": "Pass", + "Parameters": {"ok.$": "$.sync2.Output.ok"}, + "ResultPath": "$.unwrapped", + "End": true + } + } + } + """.formatted(childArn)); + + Response done = waitForTerminalExecution(startExecution(parentArn, "{}")); + + assertEquals("SUCCEEDED", done.jsonPath().getString("status"), done.body().asString()); + JsonNode output = mapper.readTree(done.jsonPath().getString("output")); + + JsonNode requestResponse = output.path("rr"); + assertEquals(List.of("ExecutionArn", "StartDate"), fieldNames(requestResponse)); + assertTrue(requestResponse.path("ExecutionArn").asText().contains(":execution:nested-result-child"), + requestResponse.toString()); + assertTrue(requestResponse.path("StartDate").isIntegralNumber(), "epoch milliseconds: " + requestResponse); + + JsonNode sync = output.path("sync"); + assertEquals(ENVELOPE_KEYS, fieldNames(sync)); + assertEquals("{\"k\":1}", sync.path("Input").asText()); + assertEquals("{\"ok\":true}", sync.path("Output").asText()); + assertEquals(childArn, sync.path("StateMachineArn").asText()); + assertEquals("SUCCEEDED", sync.path("Status").asText()); + assertEquals("NOT_REDRIVABLE", sync.path("RedriveStatus").asText()); + assertEquals("Execution is SUCCEEDED and cannot be redriven", sync.path("RedriveStatusReason").asText()); + assertTrue(sync.path("InputDetails").path("Included").asBoolean(), sync.toString()); + assertTrue(sync.path("OutputDetails").path("Included").asBoolean(), sync.toString()); + assertTrue(sync.path("StartDate").isIntegralNumber(), "epoch milliseconds: " + sync); + assertTrue(sync.path("StopDate").isIntegralNumber(), "epoch milliseconds: " + sync); + + JsonNode sync2 = output.path("sync2"); + assertEquals(ENVELOPE_KEYS, fieldNames(sync2)); + assertEquals(mapper.readTree("{\"k\":1}"), sync2.path("Input")); + assertEquals(mapper.readTree("{\"ok\":true}"), sync2.path("Output")); + assertEquals("SUCCEEDED", sync2.path("Status").asText()); + + assertTrue(output.path("unwrapped").path("ok").asBoolean(), "$.Output of .sync:2 is addressable: " + output); + } + + private static List fieldNames(JsonNode node) { + List names = new ArrayList<>(); + Iterator it = node.fieldNames(); + while (it.hasNext()) { + names.add(it.next()); + } + return names; + } + + private static String createStateMachine(String name, String definition) { + Response resp = given() + .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine") + .contentType(SFN_CONTENT_TYPE) + .body(""" + {"name": "%s-%d", "definition": %s, "roleArn": "%s"} + """.formatted(name, System.currentTimeMillis(), quote(definition), ROLE_ARN)) + .when() + .post("/"); + resp.then().statusCode(200); + return resp.jsonPath().getString("stateMachineArn"); + } + + private static String startExecution(String smArn, String input) { + Response resp = given() + .header("X-Amz-Target", "AWSStepFunctions.StartExecution") + .contentType(SFN_CONTENT_TYPE) + .body(""" + {"stateMachineArn": "%s", "input": %s} + """.formatted(smArn, quote(input))) + .when() + .post("/"); + resp.then().statusCode(200); + return resp.jsonPath().getString("executionArn"); + } + + private static Response describeExecution(String execArn) { + return given() + .header("X-Amz-Target", "AWSStepFunctions.DescribeExecution") + .contentType(SFN_CONTENT_TYPE) + .body(""" + {"executionArn": "%s"} + """.formatted(execArn)) + .when() + .post("/"); + } + + private static Response waitForTerminalExecution(String execArn) throws InterruptedException { + for (int poll = 0; poll < 200; poll++) { + Response resp = describeExecution(execArn); + if (!"RUNNING".equals(resp.jsonPath().getString("status"))) { + return resp; + } + Thread.sleep(100); + } + fail("Execution " + execArn + " was still RUNNING after 20 seconds"); + return null; + } + + private static String quote(String raw) { + return "\"" + raw + .replace("\\", "\\\\") + .replace("\"", "\\\"") + .replace("\n", "\\n") + .replace("\r", "\\r") + .replace("\t", "\\t") + + "\""; + } +}