fix(stepfunctions): return the HTTP task result on the native image (#7543)

This commit is contained in:
syedali032-creator authored and GitHub committed 2026-11-04 17:17:54 -04:00
1 parent 87c7a9ce7d
commit 68271ef6b8
5 files changed
+284 -14

No files matched your search

+3
View File
@@ -362,6 +362,8 @@ jobs:
- name: Start floci
run: |
DOCKER_GID=$(stat -c '%g' /var/run/docker.sock)
# sdk-test-java's HTTP Task regression calls a MOCK API on http://floci:4566; every
# other leg keeps the default rejection of plaintext http:invoke endpoints.
docker run -d --name floci --network compat-net \
-p 4566:4566 \
-v /var/run/docker.sock:/var/run/docker.sock \
@@ -372,6 +374,7 @@ jobs:
-e FLOCI_SERVICES_IOT_MQTT_ENABLED=true \
-e FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED=true \
-e FLOCI_TLS_ENABLED=true \
-e FLOCI_SERVICES_STEPFUNCTIONS_ALLOW_PLAINTEXT_HTTP=${{ matrix.test == 'sdk-test-java' }} \
-e FLOCI_SERVICES_EC2_MOCK=true \
-e FLOCI_SERVICES_REDSHIFT_ENDPOINT_HOST=floci \
-e FLOCI_SERVICES_RDS_ENDPOINT_HOST=floci \
@@ -156,6 +156,8 @@ import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityRequest;
import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityResponse;
import software.amazon.awssdk.services.sesv2.model.GetEmailIdentityRequest;
import software.amazon.awssdk.services.sfn.SfnClient;
import software.amazon.awssdk.services.sfn.model.DescribeExecutionResponse;
import software.amazon.awssdk.services.sfn.model.ExecutionStatus;
import software.amazon.awssdk.services.signin.SigninClient;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sqs.SqsClient;
@@ -1042,6 +1044,28 @@ public final class TestFixtures {
}
}
/**
* The execution's description once it is no longer {@code RUNNING}, or its last description at the
* timeout. It checks every 50 ms against Floci and every 500 ms against real AWS, like
* {@link #awaitStackTerminal}.
*/
public static DescribeExecutionResponse awaitExecutionTerminal(SfnClient sfn, String executionArn, Duration timeout)
throws InterruptedException {
long pollMillis = isRealAws() ? 500 : 50;
long deadline = System.nanoTime() + timeout.toNanos();
while (true) {
DescribeExecutionResponse execution = sfn.describeExecution(request -> request.executionArn(executionArn));
if (execution.status() != ExecutionStatus.RUNNING) {
return execution;
}
long remainingNanos = deadline - System.nanoTime();
if (remainingNanos <= 0) {
return execution;
}
Thread.sleep(Math.min(pollMillis, Math.max(1, Duration.ofNanos(remainingNanos).toMillis())));
}
}
public static GlueClient glueClient() {
return GlueClient.builder()
.endpointOverride(ENDPOINT)
@@ -0,0 +1,216 @@
package com.floci.test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.apigateway.ApiGatewayClient;
import software.amazon.awssdk.services.apigateway.model.IntegrationType;
import software.amazon.awssdk.services.apigateway.model.Resource;
import software.amazon.awssdk.services.eventbridge.EventBridgeClient;
import software.amazon.awssdk.services.eventbridge.model.ConnectionAuthorizationType;
import software.amazon.awssdk.services.sfn.SfnClient;
import software.amazon.awssdk.services.sfn.model.DescribeExecutionResponse;
import software.amazon.awssdk.services.sfn.model.ExecutionStatus;
import java.time.Duration;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("Step Functions HTTP Task")
class StepFunctionsHttpInvokeNativeTest {
private static final String ROLE_ARN = System.getenv("SFN_ROLE_ARN") != null
? System.getenv("SFN_ROLE_ARN")
: "arn:aws:iam::000000000000:role/service-role/test-role";
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
@DisplayName("HTTP Task output reaches ResultSelector in the native image")
void httpTaskResultIsSelectableInNativeImage() throws Exception {
Assumptions.assumeFalse(TestFixtures.isRealAws(), "Floci native-image regression test");
try (ApiGatewayClient apiGateway = TestFixtures.apiGatewayClient();
EventBridgeClient eventBridge = TestFixtures.eventBridgeClient();
SfnClient sfn = TestFixtures.sfnClient()) {
// Each delete is registered as soon as its resource exists and runs in reverse order.
Deque<Runnable> cleanup = new ArrayDeque<>();
Throwable failure = null;
try {
String apiId = apiGateway.createRestApi(request -> request
.name(TestFixtures.uniqueName("sfn-http-fixture"))).id();
cleanup.push(() -> apiGateway.deleteRestApi(request -> request.restApiId(apiId)));
String rootId = apiGateway.getResources(request -> request.restApiId(apiId)).items().stream()
.filter(resource -> "/".equals(resource.path()))
.findFirst()
.map(Resource::id)
.orElseThrow();
mockGet(apiGateway, apiId, rootId, "json", "{\"ok\": true, \"n\": 7}", Map.of("X-Probe", "'one'"));
mockGet(apiGateway, apiId, rootId, "empty", "", Map.of());
String deploymentId = apiGateway.createDeployment(request -> request.restApiId(apiId)).id();
apiGateway.createStage(request -> request.restApiId(apiId).stageName("test").deploymentId(deploymentId));
String connectionName = TestFixtures.uniqueName("sfn-http-connection");
String connectionArn = eventBridge.createConnection(request -> request
.name(connectionName)
.authorizationType(ConnectionAuthorizationType.API_KEY)
.authParameters(auth -> auth.apiKeyAuthParameters(key -> key
.apiKeyName("x-api-key")
.apiKeyValue("fixture")))).connectionArn();
cleanup.push(() -> eventBridge.deleteConnection(request -> request.name(connectionName)));
String stateMachineArn = sfn.createStateMachine(request -> request
.name(TestFixtures.uniqueName("sfn-http-native"))
.definition(definition(TestFixtures.endpoint() + "/execute-api/" + apiId + "/test", connectionArn))
.roleArn(ROLE_ARN)).stateMachineArn();
cleanup.push(() -> sfn.deleteStateMachine(request -> request.stateMachineArn(stateMachineArn)));
String executionArn = sfn.startExecution(request -> request
.stateMachineArn(stateMachineArn)
.input("{}")).executionArn();
DescribeExecutionResponse execution =
TestFixtures.awaitExecutionTerminal(sfn, executionArn, Duration.ofSeconds(60));
assertThat(execution.status())
.as("%s: %s", execution.error(), execution.cause())
.isEqualTo(ExecutionStatus.SUCCEEDED);
JsonNode output = MAPPER.readTree(execution.output());
JsonNode json = output.path("json");
assertThat(json.path("status").asInt()).isEqualTo(200);
assertThat(json.path("body").path("ok").asBoolean()).isTrue();
assertThat(json.path("body").path("n").asInt()).isEqualTo(7);
JsonNode probe = header(json.path("headers"), "X-Probe");
assertThat(probe.isArray()).as("X-Probe header %s", probe).isTrue();
assertThat(probe).hasSize(1);
assertThat(probe.get(0).asText()).isEqualTo("one");
JsonNode empty = output.path("empty");
assertThat(empty.path("status").asInt()).isEqualTo(200);
assertThat(empty.has("body")).isTrue();
assertThat(empty.get("body").isNull()).as("empty body %s", empty.get("body")).isTrue();
} catch (Throwable t) {
failure = t;
throw t;
} finally {
runCleanup(cleanup, failure);
}
}
}
private static String definition(String base, String connectionArn) {
return """
{
"StartAt": "Json",
"States": {
"Json": {
"Type": "Task",
"Resource": "arn:aws:states:::http:invoke",
"Parameters": {
"ApiEndpoint": "%1$s/json",
"Method": "GET",
"InvocationConfig": { "ConnectionArn": "%2$s" }
},
"ResultSelector": {
"status.$": "$.StatusCode",
"headers.$": "$.Headers",
"body.$": "$.ResponseBody"
},
"ResultPath": "$.json",
"Next": "Empty"
},
"Empty": {
"Type": "Task",
"Resource": "arn:aws:states:::http:invoke",
"Parameters": {
"ApiEndpoint": "%1$s/empty",
"Method": "GET",
"InvocationConfig": { "ConnectionArn": "%2$s" }
},
"ResultSelector": {
"status.$": "$.StatusCode",
"body.$": "$.ResponseBody"
},
"ResultPath": "$.empty",
"End": true
}
}
}
""".formatted(base, connectionArn);
}
// Attempts every registered delete. Failures join the test's own failure, or fail the test when
// it otherwise passed.
private static void runCleanup(Deque<Runnable> cleanup, Throwable failure) {
List<RuntimeException> errors = new ArrayList<>();
while (!cleanup.isEmpty()) {
try {
cleanup.pop().run();
} catch (RuntimeException e) {
errors.add(e);
}
}
if (errors.isEmpty()) {
return;
}
if (failure != null) {
errors.forEach(failure::addSuppressed);
return;
}
RuntimeException aggregate = new RuntimeException("HTTP Task fixture cleanup failed");
errors.forEach(aggregate::addSuppressed);
throw aggregate;
}
private static void mockGet(ApiGatewayClient apiGateway, String apiId, String rootId, String path,
String responseTemplate, Map<String, String> headers) {
String resourceId = apiGateway.createResource(request -> request
.restApiId(apiId)
.parentId(rootId)
.pathPart(path)).id();
apiGateway.putMethod(request -> request
.restApiId(apiId)
.resourceId(resourceId)
.httpMethod("GET")
.authorizationType("NONE"));
apiGateway.putIntegration(request -> request
.restApiId(apiId)
.resourceId(resourceId)
.httpMethod("GET")
.type(IntegrationType.MOCK)
.requestTemplates(Map.of("application/json", "{\"statusCode\": 200}")));
apiGateway.putMethodResponse(request -> request
.restApiId(apiId)
.resourceId(resourceId)
.httpMethod("GET")
.statusCode("200")
.responseParameters(headers.keySet().stream()
.collect(Collectors.toMap(name -> "method.response.header." + name, name -> true))));
apiGateway.putIntegrationResponse(request -> request
.restApiId(apiId)
.resourceId(resourceId)
.httpMethod("GET")
.statusCode("200")
.responseParameters(headers.entrySet().stream()
.collect(Collectors.toMap(entry -> "method.response.header." + entry.getKey(), Map.Entry::getValue)))
.responseTemplates(Map.of("application/json", responseTemplate)));
}
// Header names keep the fixture's case on Floci; HTTP makes them case-insensitive.
private static JsonNode header(JsonNode headers, String name) {
for (Iterator<String> names = headers.fieldNames(); names.hasNext(); ) {
String candidate = names.next();
if (candidate.equalsIgnoreCase(name)) {
return headers.get(candidate);
}
}
return MAPPER.missingNode();
}
}
@@ -1,6 +1,5 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -5230,13 +5229,15 @@ public class AslExecutor {
}
}
// Built field by field: binding a record through Jackson needs reflection metadata, and the native
// image has none for a private record, so valueToTree returned {} there.
private JsonNode httpResultJson(HttpResponse<Buffer> response) {
HttpTaskResponse stepHttpResponse = new HttpTaskResponse(
response.statusCode(),
response.statusMessage(),
httpResponseHeaders(response),
httpResponseBody(response));
return objectMapper.valueToTree(stepHttpResponse);
ObjectNode result = objectMapper.createObjectNode();
result.put("StatusCode", response.statusCode());
result.put("StatusText", response.statusMessage());
result.set("Headers", objectMapper.valueToTree(httpResponseHeaders(response)));
result.set("ResponseBody", httpResponseBody(response));
return result;
}
private Map<String, List<String>> httpResponseHeaders(HttpResponse<Buffer> response) {
@@ -5317,13 +5318,6 @@ public class AslExecutor {
private record HttpRequestPayload(Buffer body, String contentType) {
}
private record HttpTaskResponse(
@JsonProperty("StatusCode") int statusCode,
@JsonProperty("StatusText") String statusText,
@JsonProperty("Headers") Map<String, List<String>> headers,
@JsonProperty("ResponseBody") JsonNode responseBody) {
}
private void validateHttpMethod(String method) {
if (method == null || method.isBlank()) {
throw new FailStateException("States.Runtime", "Method is required for HTTP task");
@@ -300,6 +300,39 @@ class AslExecutorHttpInvokeTest {
assertTrue(body.path("active").asBoolean());
}
@Test
void emptyResponseBodyStillReturnsEveryResultField() throws Exception {
Execution execution = run("""
{
"StartAt": "CallHttp",
"States": {
"CallHttp": {
"Type": "Task",
"Resource": "arn:aws:states:::http:invoke",
"Parameters": {
"ApiEndpoint": "%s/text",
"Method": "POST",
"InvocationConfig": {
"ConnectionArn": "%s"
}
},
"End": true
}
}
}
""".formatted(baseUrl, connectionArn), "{}");
assertEquals("SUCCEEDED", execution.getStatus());
JsonNode output = objectMapper.readTree(execution.getOutput());
List<String> fields = new ArrayList<>();
output.fieldNames().forEachRemaining(fields::add);
assertEquals(List.of("StatusCode", "StatusText", "Headers", "ResponseBody"), fields);
assertEquals(201, output.path("StatusCode").asInt());
assertEquals("Created", output.path("StatusText").asText());
assertTrue(output.path("Headers").path("Content-Type").isArray());
assertTrue(output.path("ResponseBody").isNull());
}
@Test
void jsonataArgumentsSendAnExplicitNull() throws Exception {
// AWS keeps the null in the arguments a Task is invoked with: TestState TRACE reports