diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index 4435b55a17..2d9f886b93 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -86,6 +86,7 @@ import software.amazon.awssdk.services.kinesis.KinesisAsyncClient; import software.amazon.awssdk.services.kinesis.KinesisClient; import software.amazon.awssdk.services.kinesisanalyticsv2.KinesisAnalyticsV2Client; import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.awssdk.services.lambda.LambdaAsyncClient; import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest; import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest; @@ -949,6 +950,16 @@ public final class TestFixtures { .build(); } + public static LambdaAsyncClient lambdaAsyncClient() { + return LambdaAsyncClient.builder() + .endpointOverride(ENDPOINT) + .region(REGION) + .credentialsProvider(CREDENTIALS) + .httpClientBuilder(NettyNioAsyncHttpClient.builder() + .protocol(Protocol.HTTP1_1)) + .build(); + } + public static LambdaWebClient lambdaWebClient() { return LambdaWebClient.builder() .endpointOverride(ENDPOINT) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaInvokeWithResponseStreamTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaInvokeWithResponseStreamTest.java new file mode 100644 index 0000000000..c1ebc1e7aa --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaInvokeWithResponseStreamTest.java @@ -0,0 +1,86 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.services.lambda.LambdaAsyncClient; +import software.amazon.awssdk.services.lambda.LambdaClient; +import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest; +import software.amazon.awssdk.services.lambda.model.FunctionCode; +import software.amazon.awssdk.services.lambda.model.InvokeWithResponseStreamCompleteEvent; +import software.amazon.awssdk.services.lambda.model.InvokeWithResponseStreamRequest; +import software.amazon.awssdk.services.lambda.model.InvokeWithResponseStreamResponseHandler; +import software.amazon.awssdk.services.lambda.model.Runtime; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; + +@DisplayName("Lambda - InvokeWithResponseStream") +class LambdaInvokeWithResponseStreamTest { + + private static final String FN = "sdk-invoke-with-response-stream-fn"; + + private static LambdaClient lambda; + private static LambdaAsyncClient lambdaAsync; + + @BeforeAll + static void setup() { + lambda = TestFixtures.lambdaClient(); + lambdaAsync = TestFixtures.lambdaAsyncClient(); + lambda.createFunction(r -> r + .functionName(FN) + .runtime(Runtime.NODEJS22_X) + .role("arn:aws:iam::000000000000:role/lambda-role") + .handler("index.handler") + .timeout(30) + .code(FunctionCode.builder() + .zipFile(SdkBytes.fromByteArray(LambdaUtils.streamingZip())) + .build())); + } + + @AfterAll + static void cleanup() { + if (lambda != null) { + try { + lambda.deleteFunction(DeleteFunctionRequest.builder().functionName(FN).build()); + } catch (Exception ignored) { + // The function may already be gone. + } + lambda.close(); + } + if (lambdaAsync != null) { + lambdaAsync.close(); + } + } + + @Test + @DisplayName("streams the payload chunks and one InvokeComplete") + void streamsPayloadChunksAndOneInvokeComplete() throws Exception { + ByteArrayOutputStream payload = new ByteArrayOutputStream(); + List completes = new ArrayList<>(); + InvokeWithResponseStreamResponseHandler handler = InvokeWithResponseStreamResponseHandler.builder() + .onResponse(response -> { }) + .subscriber(InvokeWithResponseStreamResponseHandler.Visitor.builder() + .onPayloadChunk(chunk -> payload.writeBytes(chunk.payload().asByteArray())) + .onInvokeComplete(completes::add) + .build()) + .build(); + + lambdaAsync.invokeWithResponseStream(InvokeWithResponseStreamRequest.builder() + .functionName(FN) + .payload(SdkBytes.fromUtf8String("{}")) + .build(), handler) + .get(60, TimeUnit.SECONDS); + + assertThat(payload.toString(StandardCharsets.UTF_8)).isEqualTo("hello world"); + assertThat(completes).hasSize(1); + assertThat(completes.get(0).errorCode()).isNull(); + } +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaUtils.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaUtils.java index e15748e28b..93a73d65e3 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaUtils.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaUtils.java @@ -378,6 +378,18 @@ public final class LambdaUtils { return createZip("index.js", code); } + /** ZIP containing a Node.js handler that streams "hello " and "world" through the response stream. */ + public static byte[] streamingZip() { + String code = """ + exports.handler = awslambda.streamifyResponse(async (event, responseStream) => { + responseStream.write('hello '); + responseStream.write('world'); + responseStream.end(); + }); + """; + return createZip("index.js", code); + } + private static byte[] createZip(String filename, String content) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); diff --git a/docs/services/index.md b/docs/services/index.md index 503686d3ae..f28a4bb0e3 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -18,7 +18,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [S3 Tables](s3tables.md) | `/buckets`, `/namespaces/*`, `/tables/*` | REST JSON | 27 | | [DynamoDB](dynamodb.md) | `POST /` + `X-Amz-Target: DynamoDB_20120810.*` | JSON 1.1 | 53 | | [DynamoDB Streams](dynamodb.md#streams) | `POST /` + `X-Amz-Target: DynamoDBStreams_20120810.*` | JSON 1.1 | 4 | -| [Lambda](lambda.md) | `/2015-03-31/functions/...` + `/2025-12-01/durable-executions/...` | REST JSON | 68 | +| [Lambda](lambda.md) | `/2015-03-31/functions/...` + `/2025-12-01/durable-executions/...` | REST JSON | 69 | | [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 23 | | [Lambda Web Functions](lambda-web-functions.md) | `/2025-03-07/web-functions/...` | REST JSON | 20 | | [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 101 | diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 8e2ce4c1b0..d0b87226ea 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -17,6 +17,7 @@ Floci Lambda runs your function code locally inside real Docker containers - clo | `UpdateFunctionConfiguration` | Update runtime, handler, memory, timeout, environment, architectures, tracing, layers, and more | | `DeleteFunction` | Remove a function | | `Invoke` | Invoke a function synchronously or asynchronously. A durable function starts a durable execution | +| `InvokeWithResponseStream` | Invoke a function and stream its response as event stream frames (see Response streaming below) | | `CreateEventSourceMapping` | Connect SQS / Kinesis / DynamoDB Streams to a function | | `GetEventSourceMapping` | Get event source mapping details | | `ListEventSourceMappings` | List all event source mappings | @@ -315,6 +316,19 @@ Not emulated yet: - The `Deleting` state AWS shows for about a minute after `DeleteFunction` of a durable function. Floci removes it at once. +## Response streaming + +`InvokeWithResponseStream` answers with an `application/vnd.amazon.eventstream` body. It has one +`PayloadChunk` event for each chunk the function streams and one `InvokeComplete` event at the end. +A function that does not stream sends its whole response as one `PayloadChunk`. Every invocation +type runs the function, so `DryRun` and `Event` stream like `RequestResponse`. + +`X-Amz-Executed-Version`, `x-amzn-Remapped-Content-Type`, `Qualifier`, `X-Amz-Client-Context` and +`X-Amz-Log-Type: Tail` are supported. With a log tail, `InvokeComplete` carries `LogResult`. +`InvokeComplete` carries `ErrorCode` for a failed invocation. An error a streaming handler throws +also sets `ErrorDetails`, a timeout is `Sandbox.Timeout`, and a runtime that exits in the middle of +a stream is `Runtime.TruncatedResponse`. + ## Code signing configuration pagination `ListCodeSigningConfigs` accepts `MaxItems` from 1 to 10,000 and returns `NextMarker` @@ -494,7 +508,7 @@ Pagination uses Lambda's shared validation: out-of-range integers return marker returns `InvalidParameterValueException` with `Invalid pagination key.`. Missing or inaccessible function references return `ResourceNotFoundException`. -A function URL with `InvokeMode: RESPONSE_STREAM` streams the response: each chunk the handler writes reaches the caller as it is written. When the handler uses `awslambda.HttpResponseStream.from`, the status code, headers and cookies come from its prelude. Otherwise the response is a `200` with the content type the handler set, `application/octet-stream` by default. A function that fails before its stream starts, in its init or by timing out, answers `502`. An error the handler throws ends the body where it stopped, an empty `200` if it wrote nothing: the runtime reports it in HTTP trailers, which Floci's runtime API does not read. A handler that does not stream is answered as with `BUFFERED`. +A function URL with `InvokeMode: RESPONSE_STREAM` streams the response: each chunk the handler writes reaches the caller as it is written. When the handler uses `awslambda.HttpResponseStream.from`, the status code, headers and cookies come from its prelude. Otherwise the response is a `200` with the content type the handler set, `application/octet-stream` by default. A function that fails before its stream starts, in its init or by timing out, answers `502`. An error the handler throws ends the body where it stopped, an empty `200` if it wrote nothing: the runtime reports it in HTTP trailers, which Floci does not read for a function URL. A handler that does not stream is answered as with `BUFFERED`. Function URLs are not available in AWS GovCloud (US) or in the China Regions ([GovCloud guide](https://docs.aws.amazon.com/govcloud-us/latest/UserGuide/govcloud-lambda.html), @@ -659,7 +673,6 @@ For a longer drain, explicitly stop with the larger timeout and then start Floci These AWS Lambda operations have no handler in Floci. Calls will return `404` or an error: - Layer permissions (`AddLayerVersionPermission`, `RemoveLayerVersionPermission`, `GetLayerVersionPolicy`) -- `InvokeWithResponseStream` Code signing enforcement is not emulated: an attached configuration never gates a deployment. The attachment lifecycle is supported for `$LATEST`: `PutFunctionCodeSigningConfig` attaches or diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaController.java b/src/main/java/io/floci/aws/services/lambda/LambdaController.java index 3a44b93058..2fc8bbed62 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaController.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaController.java @@ -268,7 +268,7 @@ public class LambdaController { } String clientContext = type == InvocationType.RequestResponse - ? decodeClientContext(headers.getHeaderString("X-Amz-Client-Context")) : null; + ? decodeClientContext(objectMapper, headers.getHeaderString("X-Amz-Client-Context")) : null; String durableExecutionName = headers.getHeaderString("X-Amz-Durable-Execution-Name"); boolean logTail = type == InvocationType.RequestResponse @@ -310,7 +310,7 @@ public class LambdaController { return builder.build(); } - private String decodeClientContext(String encoded) { + static String decodeClientContext(ObjectMapper objectMapper, String encoded) { if (encoded == null || encoded.isEmpty()) { return null; } diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java b/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java index a5fd8e49df..84b514b78c 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java @@ -224,6 +224,13 @@ public class LambdaExecutorService implements Resettable { UUID.randomUUID().toString(), listener, null); } + /** As {@link #invokeStreaming}, for a request that carries a client context and may ask for a log tail. */ + InvokeResult invokeStreaming(LambdaFunction fn, byte[] payload, int chainDepth, String invokedQualifier, + String clientContext, boolean logTail, ResponseStreamListener listener) { + return invoke(fn, payload, InvocationType.RequestResponse, chainDepth, invokedQualifier, clientContext, + UUID.randomUUID().toString(), listener, null, logTail); + } + private InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth, String invokedQualifier, String clientContext, String requestId, ResponseStreamListener listener, String traceId) { @@ -472,6 +479,7 @@ public class LambdaExecutorService implements Resettable { InvokeResult result = new InvokeResult(200, "Unhandled", buildErrorPayload("Task timed out after " + fn.getTimeout() + " seconds", "Function.TimedOut"), null, requestId); + result.setTimedOut(true); includeLogTail(result, handle, logs); warmPool.destroyHandle(handle); return result; diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaInvokeResponseStream.java b/src/main/java/io/floci/aws/services/lambda/LambdaInvokeResponseStream.java new file mode 100644 index 0000000000..3052d7aea0 --- /dev/null +++ b/src/main/java/io/floci/aws/services/lambda/LambdaInvokeResponseStream.java @@ -0,0 +1,129 @@ +package io.floci.aws.services.lambda; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsEventStreamEncoder; +import io.floci.aws.services.lambda.model.InvokeResult; +import io.floci.aws.services.lambda.model.ResponseStreamListener; +import jakarta.ws.rs.core.GenericEntity; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.StreamingOutput; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.util.LinkedHashMap; +import java.util.concurrent.CompletableFuture; + +/** + * The response of {@code InvokeWithResponseStream}: {@code PayloadChunk} events as the function + * streams, then one {@code InvokeComplete}. A function that does not stream has its whole response + * sent as one chunk. + */ +final class LambdaInvokeResponseStream implements ResponseStreamListener { + + static final String EVENT_STREAM = "application/vnd.amazon.eventstream"; + private static final String JSON = MediaType.APPLICATION_JSON; + private static final String OCTET_STREAM = MediaType.APPLICATION_OCTET_STREAM; + + private final ObjectMapper objectMapper; + private final CompletableFuture started = new CompletableFuture<>(); + private final ResponseChunkQueue frames = new ResponseChunkQueue(); + private volatile Failure failure; + + private record Failure(String errorType, String errorBody) { + } + + LambdaInvokeResponseStream(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + @Override + public void onStart(String contentType) { + started.complete(contentType != null ? contentType : OCTET_STREAM); + } + + @Override + public void onChunk(byte[] chunk) { + if (chunk.length > 0) { + frames.add(frame("PayloadChunk", OCTET_STREAM, chunk)); + } + } + + @Override + public void onFailure(String errorType, String errorBody) { + failure = new Failure(errorType, errorBody); + } + + /** Completes with the content type of the stream once the runtime starts it. */ + CompletableFuture started() { + return started; + } + + /** The function has returned, whether or not it streamed anything. */ + void end() { + frames.end(); + } + + /** The content type AWS reports for the stream in {@code x-amzn-Remapped-Content-Type}. */ + String remappedContentType(CompletableFuture invocation) { + if (started.isDone()) { + return started.join(); + } + return invocation.join().isTimedOut() ? OCTET_STREAM : JSON; + } + + GenericEntity body(CompletableFuture invocation, boolean logTail) { + return new GenericEntity<>(output -> write(output, invocation, logTail), StreamingOutput.class); + } + + /** Writes the frames as they arrive until {@link #end()}, then the final {@code InvokeComplete}. */ + void write(OutputStream output, CompletableFuture invocation, boolean logTail) throws IOException { + frames.drainTo(output); + InvokeResult result = invocation.join(); + boolean streamed = started.isDone(); + boolean failed = result.getFunctionError() != null; + if (!streamed && !result.isTimedOut() && result.getPayload() != null && result.getPayload().length > 0) { + output.write(frame("PayloadChunk", OCTET_STREAM, result.getPayload())); + } + output.write(frame("InvokeComplete", JSON, complete(result, streamed, failed, logTail))); + output.flush(); + } + + private byte[] complete(InvokeResult result, boolean streamed, boolean failed, boolean logTail) { + ObjectNode payload = objectMapper.createObjectNode(); + if (logTail && result.getLogResult() != null) { + // AWS leaves ErrorCode out when it sends LogResult, also for a failed invocation. + payload.put("LogResult", result.getLogResult()); + } else if (streamed && result.isTimedOut()) { + payload.put("ErrorCode", "Sandbox.Timeout"); + } else if (failure != null) { + payload.put("ErrorCode", failure.errorType()); + if (failure.errorBody() != null) { + payload.put("ErrorDetails", failure.errorBody()); + } + } else if (!streamed && failed) { + payload.put("ErrorCode", "Unhandled"); + payload.put("ErrorDetails", ""); + } else if (streamed && failed) { + payload.put("ErrorCode", "Runtime.TruncatedResponse"); + } + try { + return objectMapper.writeValueAsBytes(payload); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static byte[] frame(String eventType, String contentType, byte[] payload) { + LinkedHashMap headers = new LinkedHashMap<>(); + headers.put(":event-type", eventType); + headers.put(":content-type", contentType); + headers.put(":message-type", "event"); + try { + return AwsEventStreamEncoder.encodeMessage(headers, payload); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaResponseStreamController.java b/src/main/java/io/floci/aws/services/lambda/LambdaResponseStreamController.java new file mode 100644 index 0000000000..f33e62d371 --- /dev/null +++ b/src/main/java/io/floci/aws/services/lambda/LambdaResponseStreamController.java @@ -0,0 +1,138 @@ +package io.floci.aws.services.lambda; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.SmithyValidationErrors; +import io.floci.aws.services.lambda.model.InvokeResult; +import io.smallrye.common.annotation.RunOnVirtualThread; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriInfo; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; + +/** + * InvokeWithResponseStream, under /2021-11-15. A separate class from {@link LambdaController} + * because it lives under a different API version prefix, and a class-level {@code @Path} can only + * be one literal prefix. + */ +@Path("/2021-11-15") +public class LambdaResponseStreamController { + + private static final int REQUEST_LIMIT = 6 * 1024 * 1024; + private static final List LOG_TYPES = List.of("Tail", "None"); + private static final List INVOCATION_TYPES = List.of("DryRun", "RequestResponse", "Event"); + + private final LambdaService lambdaService; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public LambdaResponseStreamController(LambdaService lambdaService, RegionResolver regionResolver, + ObjectMapper objectMapper) { + this.lambdaService = lambdaService; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @POST + @Path("/functions/{functionName}/response-streaming-invocations") + @Consumes(MediaType.WILDCARD) + @RunOnVirtualThread + public Response invokeWithResponseStream(@Context HttpHeaders headers, + @Context UriInfo uriInfo, + @PathParam("functionName") String functionName, + byte[] payload) { + String qualifier = uriInfo.getQueryParameters().getFirst("Qualifier"); + String region = regionResolver.resolveRegion(headers); + byte[] body = payload != null ? payload : new byte[0]; + + requireWithinLimit(body); + validate(headers.getHeaderString("X-Amz-Log-Type"), headers.getHeaderString("X-Amz-Invocation-Type"), + qualifier); + requireJson(body); + LambdaService.InvokeTarget target = lambdaService.resolveInvokeTarget(region, functionName, qualifier); + String clientContext = LambdaController.decodeClientContext(objectMapper, + headers.getHeaderString("X-Amz-Client-Context")); + boolean logTail = "Tail".equals(headers.getHeaderString("X-Amz-Log-Type")); + String traceHeader = headers.getHeaderString("X-Amzn-Trace-Id"); + + LambdaInvokeResponseStream stream = new LambdaInvokeResponseStream(objectMapper); + CompletableFuture invocation = new CompletableFuture<>(); + Thread.ofVirtual().name("lambda-invoke-stream").start(() -> { + try { + invocation.complete(lambdaService.invokeStreaming(target, region, body, clientContext, traceHeader, + logTail, stream)); + } catch (RuntimeException e) { + invocation.completeExceptionally(e); + } finally { + stream.end(); + } + }); + CompletableFuture.anyOf(stream.started(), invocation).handle((ignored, e) -> null).join(); + + String contentType; + try { + contentType = stream.remappedContentType(invocation); + } catch (CompletionException e) { + if (e.getCause() instanceof AwsException aws) { + throw aws; + } + throw e; + } + return Response.ok(stream.body(invocation, logTail)) + .type(LambdaInvokeResponseStream.EVENT_STREAM) + .header("X-Amz-Executed-Version", target.function().getVersion()) + .header("x-amzn-Remapped-Content-Type", contentType) + .build(); + } + + private static void requireWithinLimit(byte[] body) { + if (body.length > REQUEST_LIMIT) { + throw new AwsException("RequestEntityTooLargeException", body.length + + " byte payload is too large for the RequestResponse invocation type (limit " + + REQUEST_LIMIT + " bytes)", 413); + } + } + + private static void validate(String logType, String invocationType, String qualifier) { + List violations = new ArrayList<>(); + addEnumViolation(violations, logType, "logType", LOG_TYPES); + addEnumViolation(violations, invocationType, "invocationType", INVOCATION_TYPES); + violations.addAll(LambdaService.invokeQualifierViolations(qualifier)); + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); + } + } + + private static void addEnumViolation(List violations, String value, String field, List allowed) { + if (value != null && !allowed.contains(value)) { + violations.add(SmithyValidationErrors.notInEnum(value, field, allowed)); + } + } + + private void requireJson(byte[] body) { + if (body.length == 0) { + return; + } + try { + objectMapper.readTree(body); + } catch (IOException e) { + throw new AwsException("InvalidRequestContentException", + "Could not parse request body into json: Could not parse payload into json: " + e.getMessage(), + 400); + } + } +} diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaService.java b/src/main/java/io/floci/aws/services/lambda/LambdaService.java index 31b2adbd6c..b6783c9ea5 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaService.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaService.java @@ -1465,6 +1465,29 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { public InvokeResult invoke(String region, String functionName, String queryQualifier, byte[] payload, InvocationType type, String clientContext, String durableExecutionName, String traceHeader, boolean logTail) { + InvokeTarget target = resolveInvokeTarget(region, functionName, queryQualifier); + LambdaFunction fn = target.function(); + String qualifier = target.qualifier(); + reportCustomResourceLiveness(payload); + InvokeResult durable = invokeIfDurable(fn, region, qualifier, durableExecutionName, payload, type, + traceHeader, logTail); + if (durable != null) { + return durable; + } + InvokeResult result = logTail + ? executorService.invoke(fn, payload, type, + LambdaInvocationChain.currentDepth(), qualifier, clientContext, true) + : executorService.invoke(fn, payload, type, + LambdaInvocationChain.currentDepth(), qualifier, clientContext); + result.setExecutedVersion(fn.getVersion()); + return result; + } + + /** The function an Invoke runs, and the qualifier it was invoked through. */ + record InvokeTarget(LambdaFunction function, String qualifier) { + } + + InvokeTarget resolveInvokeTarget(String region, String functionName, String queryQualifier) { validateInvokeQualifier(queryQualifier); LambdaArnUtils.ResolvedFunctionRef ref = resolveWithRegion(region, functionName, queryQualifier); String name = ref.name(); @@ -1477,17 +1500,24 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { } else { fn = targetResolver.resolveInvokeTarget(region, name, qualifier); } + return new InvokeTarget(fn, qualifier); + } + + /** + * Runs a resolved target synchronously, handing a response the runtime streams to {@code listener} + * as it arrives. Every invocation type runs, as on {@code InvokeWithResponseStream}. + */ + InvokeResult invokeStreaming(InvokeTarget target, String region, byte[] payload, String clientContext, + String traceHeader, boolean logTail, ResponseStreamListener listener) { + LambdaFunction fn = target.function(); reportCustomResourceLiveness(payload); - InvokeResult durable = invokeIfDurable(fn, region, qualifier, durableExecutionName, payload, type, - traceHeader, logTail); + InvokeResult durable = invokeIfDurable(fn, region, target.qualifier(), null, payload, + InvocationType.RequestResponse, traceHeader, logTail); if (durable != null) { return durable; } - InvokeResult result = logTail - ? executorService.invoke(fn, payload, type, - LambdaInvocationChain.currentDepth(), qualifier, clientContext, true) - : executorService.invoke(fn, payload, type, - LambdaInvocationChain.currentDepth(), qualifier, clientContext); + InvokeResult result = executorService.invokeStreaming(fn, payload, LambdaInvocationChain.currentDepth(), + target.qualifier(), clientContext, logTail, listener); result.setExecutedVersion(fn.getVersion()); return result; } @@ -3509,9 +3539,26 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { /** Invoke's Qualifier, when supplied: 1-128 characters matching {@link #QUALIFIER}. */ private static void validateInvokeQualifier(String qualifier) { - validateNonEmpty(qualifier, "qualifier", false); - validateMaxLength(qualifier, "qualifier", 128); - validatePattern(qualifier, "qualifier", QUALIFIER); + List violations = invokeQualifierViolations(qualifier); + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); + } + } + + /** The violations of Invoke's Qualifier as AWS lists them, the pattern before the length. */ + static List invokeQualifierViolations(String qualifier) { + List violations = new ArrayList<>(); + if (qualifier == null) { + return violations; + } + if (!QUALIFIER.matcher(qualifier).matches()) { + violations.add(SmithyValidationErrors.pattern("qualifier", qualifier, QUALIFIER.pattern())); + } + String length = SmithyValidationErrors.lengthOutOfRange("qualifier", qualifier, 1, 128); + if (length != null) { + violations.add(length); + } + return violations; } public void deleteAlias(String region, String functionName, String aliasName) { diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaUrlResponseStream.java b/src/main/java/io/floci/aws/services/lambda/LambdaUrlResponseStream.java index ebfc9a218e..66333eb45d 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaUrlResponseStream.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaUrlResponseStream.java @@ -10,9 +10,7 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; -import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.LinkedBlockingQueue; /** * The response of a {@code RESPONSE_STREAM} function URL, as the function streams it. @@ -26,7 +24,6 @@ final class LambdaUrlResponseStream implements ResponseStreamListener { static final String HTTP_INTEGRATION_RESPONSE = "application/vnd.awslambda.http-integration-response"; private static final int PRELUDE_DELIMITER_LENGTH = 8; - private static final byte[] END = new byte[0]; /** The prelude, or null for a stream without one, and the content type the runtime sent. */ record Head(JsonNode prelude, String contentType) { @@ -34,7 +31,7 @@ final class LambdaUrlResponseStream implements ResponseStreamListener { private final ObjectMapper objectMapper; private final CompletableFuture head = new CompletableFuture<>(); - private final BlockingQueue body = new LinkedBlockingQueue<>(); + private final ResponseChunkQueue body = new ResponseChunkQueue(); private final ByteArrayOutputStream prelude = new ByteArrayOutputStream(); private String contentType; private boolean expectsPrelude; @@ -86,7 +83,7 @@ final class LambdaUrlResponseStream implements ResponseStreamListener { /** Ends the body; the function has returned, whether or not it streamed anything. */ void end() { - body.add(END); + body.end(); } CompletableFuture head() { @@ -102,13 +99,6 @@ final class LambdaUrlResponseStream implements ResponseStreamListener { } private void write(OutputStream output) throws IOException { - try { - for (byte[] chunk = body.take(); chunk != END; chunk = body.take()) { - output.write(chunk); - output.flush(); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } + body.drainTo(output); } } diff --git a/src/main/java/io/floci/aws/services/lambda/ResponseChunkQueue.java b/src/main/java/io/floci/aws/services/lambda/ResponseChunkQueue.java new file mode 100644 index 0000000000..4c78c35136 --- /dev/null +++ b/src/main/java/io/floci/aws/services/lambda/ResponseChunkQueue.java @@ -0,0 +1,42 @@ +package io.floci.aws.services.lambda; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +/** The chunks of a streamed response, handed from the runtime thread to the thread writing the body. */ +final class ResponseChunkQueue { + + private static final byte[] END = new byte[0]; + + private final BlockingQueue chunks = new LinkedBlockingQueue<>(); + private volatile boolean abandoned; + + void add(byte[] chunk) { + if (!abandoned) { + chunks.add(chunk); + } + } + + /** The function has returned, whether or not it streamed anything. */ + void end() { + chunks.add(END); + } + + /** Writes each chunk as it arrives, until {@link #end()}. Later chunks are dropped once a write fails. */ + void drainTo(OutputStream output) throws IOException { + try { + for (byte[] chunk = chunks.take(); chunk != END; chunk = chunks.take()) { + output.write(chunk); + output.flush(); + } + } catch (IOException e) { + abandoned = true; + chunks.clear(); + throw e; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} diff --git a/src/main/java/io/floci/aws/services/lambda/model/InvokeResult.java b/src/main/java/io/floci/aws/services/lambda/model/InvokeResult.java index b5567998a4..acaea9cd88 100644 --- a/src/main/java/io/floci/aws/services/lambda/model/InvokeResult.java +++ b/src/main/java/io/floci/aws/services/lambda/model/InvokeResult.java @@ -12,6 +12,7 @@ public class InvokeResult { private String requestId; private String executedVersion; private String durableExecutionArn; + private boolean timedOut; public InvokeResult() { } @@ -79,4 +80,12 @@ public class InvokeResult { public void setDurableExecutionArn(String durableExecutionArn) { this.durableExecutionArn = durableExecutionArn; } + + public boolean isTimedOut() { + return timedOut; + } + + public void setTimedOut(boolean timedOut) { + this.timedOut = timedOut; + } } diff --git a/src/main/java/io/floci/aws/services/lambda/model/ResponseStreamListener.java b/src/main/java/io/floci/aws/services/lambda/model/ResponseStreamListener.java index bb0fbcaeb0..8c10d570ad 100644 --- a/src/main/java/io/floci/aws/services/lambda/model/ResponseStreamListener.java +++ b/src/main/java/io/floci/aws/services/lambda/model/ResponseStreamListener.java @@ -10,4 +10,11 @@ public interface ResponseStreamListener { void onStart(String contentType); void onChunk(byte[] chunk); + + /** + * The stream ended in a failure: the function reported {@code errorType} in its trailers, or the + * runtime broke off ({@code Runtime.TruncatedResponse}). {@code errorBody} is the error JSON, or null. + */ + default void onFailure(String errorType, String errorBody) { + } } diff --git a/src/main/java/io/floci/aws/services/lambda/runtime/RequestTrailers.java b/src/main/java/io/floci/aws/services/lambda/runtime/RequestTrailers.java new file mode 100644 index 0000000000..bfd3a8a5e6 --- /dev/null +++ b/src/main/java/io/floci/aws/services/lambda/runtime/RequestTrailers.java @@ -0,0 +1,50 @@ +package io.floci.aws.services.lambda.runtime; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.handler.codec.http.HttpHeaders; +import io.netty.handler.codec.http.LastHttpContent; +import io.netty.util.AttributeKey; +import io.vertx.core.http.HttpConnection; +import io.vertx.core.net.impl.ConnectionBase; + +/** + * The HTTP trailers of a request. Vert.x exposes none on a server request, but Netty's decoder + * delivers them with the last content, so this reads them off the connection's pipeline. + * {@code ConnectionBase} is internal to Vert.x and is used only to reach that pipeline. + */ +final class RequestTrailers { + + private static final AttributeKey TRAILERS = AttributeKey.valueOf("floci.request-trailers"); + + private RequestTrailers() { + } + + /** Starts recording the trailers of every request that arrives on {@code connection}. */ + static void install(HttpConnection connection) { + if (connection instanceof ConnectionBase base) { + ChannelHandlerContext vertxHandler = base.channelHandlerContext(); + vertxHandler.pipeline().addBefore(vertxHandler.name(), "floci-request-trailers", new Recorder()); + } + } + + /** The trailers of the request that just ended on {@code connection}, or null when it had none. */ + static HttpHeaders take(HttpConnection connection) { + if (connection instanceof ConnectionBase base) { + return base.channel().attr(TRAILERS).getAndSet(null); + } + return null; + } + + private static final class Recorder extends ChannelInboundHandlerAdapter { + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + if (msg instanceof LastHttpContent last) { + HttpHeaders trailers = last.trailingHeaders(); + ctx.channel().attr(TRAILERS).set(trailers.isEmpty() ? null : trailers); + } + ctx.fireChannelRead(msg); + } + } +} diff --git a/src/main/java/io/floci/aws/services/lambda/runtime/RuntimeApiServer.java b/src/main/java/io/floci/aws/services/lambda/runtime/RuntimeApiServer.java index 757585d0ab..4e43422520 100644 --- a/src/main/java/io/floci/aws/services/lambda/runtime/RuntimeApiServer.java +++ b/src/main/java/io/floci/aws/services/lambda/runtime/RuntimeApiServer.java @@ -5,6 +5,7 @@ import io.floci.aws.services.lambda.model.InvokeResult; import io.floci.aws.services.lambda.model.PendingInvocation; import io.floci.aws.services.lambda.model.RegisteredExtension; import io.floci.aws.services.lambda.model.ResponseStreamListener; +import io.netty.handler.codec.http.HttpHeaders; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServer; @@ -19,6 +20,7 @@ import org.jboss.logging.Logger; import java.nio.charset.StandardCharsets; import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -84,6 +86,8 @@ public class RuntimeApiServer { private static final String INIT_ERROR_PATH = "/" + RUNTIME_API_VERSION + "/runtime/init/error"; private static final String RESPONSE_MODE_HEADER = "Lambda-Runtime-Function-Response-Mode"; + private static final String FUNCTION_ERROR_TYPE_TRAILER = "Lambda-Runtime-Function-Error-Type"; + private static final String FUNCTION_ERROR_BODY_TRAILER = "Lambda-Runtime-Function-Error-Body"; private static final String EXTENSIONS_API_VERSION = "2020-01-01"; private static final String EXTENSION_REGISTER_PATH = "/" + EXTENSIONS_API_VERSION + "/extension/register"; @@ -641,6 +645,7 @@ public class RuntimeApiServer { // automatically (no client-side change needed) and matches AWS's actual wire // protocol. .setHttp2ClearTextEnabled(false)); + httpServer.connectionHandler(RequestTrailers::install); httpServer.requestHandler(router).listen(port, "0.0.0.0", result -> { if (result.succeeded()) { LOG.infov("RuntimeApiServer started on port {0}", String.valueOf(port)); @@ -1027,14 +1032,32 @@ public class RuntimeApiServer { ctx.request().handler(chunk -> listener.onChunk(chunk.getBytes())); ctx.request().exceptionHandler(e -> { LOG.warnv("Streamed response of invocation {0} broke off: {1}", requestId, e.getMessage()); + listener.onFailure("Runtime.TruncatedResponse", null); completeStreamedResponse(requestId); }); ctx.request().endHandler(v -> { + HttpHeaders trailers = RequestTrailers.take(ctx.request().connection()); + if (trailers != null && trailers.contains(FUNCTION_ERROR_TYPE_TRAILER)) { + listener.onFailure(trailers.get(FUNCTION_ERROR_TYPE_TRAILER), + decodeErrorBody(requestId, trailers.get(FUNCTION_ERROR_BODY_TRAILER))); + } completeStreamedResponse(requestId); sendStatusOk(ctx); }); } + private String decodeErrorBody(String requestId, String encoded) { + if (encoded == null) { + return null; + } + try { + return new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + LOG.warnv("Error body trailer of invocation {0} is not base64: {1}", requestId, e.getMessage()); + return null; + } + } + private void completeStreamedResponse(String requestId) { PendingInvocation invocation = inFlight.remove(requestId); if (invocation != null) { diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaInvokeResponseStreamTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaInvokeResponseStreamTest.java new file mode 100644 index 0000000000..008f68ab70 --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambda/LambdaInvokeResponseStreamTest.java @@ -0,0 +1,300 @@ +package io.floci.aws.services.lambda; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.services.lambda.model.InvokeResult; +import io.floci.aws.testing.EventStreamMessages; +import io.floci.aws.testing.EventStreamMessages.Message; +import jakarta.ws.rs.core.StreamingOutput; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class LambdaInvokeResponseStreamTest { + + private LambdaInvokeResponseStream stream; + + @BeforeEach + void setUp() { + stream = new LambdaInvokeResponseStream(new ObjectMapper()); + } + + @Test + void streamedResponseSendsItsChunksThenAnEmptyInvokeComplete() throws IOException { + stream.onStart(null); + stream.onChunk("hello ".getBytes(StandardCharsets.UTF_8)); + stream.onChunk(new byte[0]); + stream.onChunk("world".getBytes(StandardCharsets.UTF_8)); + + List messages = write(new InvokeResult(200, null, new byte[0], null, "r"), false); + + assertEquals(List.of("PayloadChunk", "PayloadChunk", "InvokeComplete"), types(messages)); + assertEquals("hello ", messages.get(0).text()); + assertEquals("world", messages.get(1).text()); + assertEquals("{}", messages.get(2).text()); + assertEquals("application/octet-stream", stream.remappedContentType(done(new InvokeResult()))); + } + + @Test + void framesCarryTheirHeadersInOrder() throws IOException { + stream.onStart("text/plain"); + stream.onChunk(new byte[] {1}); + + List messages = write(new InvokeResult(200, null, new byte[0], null, "r"), false); + + assertEquals(List.of(":event-type", ":content-type", ":message-type"), + List.copyOf(messages.get(0).headers().keySet())); + assertEquals("application/octet-stream", messages.get(0).headers().get(":content-type")); + assertEquals("event", messages.get(0).headers().get(":message-type")); + assertEquals(List.of(":event-type", ":content-type", ":message-type"), + List.copyOf(messages.get(1).headers().keySet())); + assertEquals("application/json", messages.get(1).headers().get(":content-type")); + assertEquals("text/plain", stream.remappedContentType(done(new InvokeResult()))); + } + + @Test + void streamWithoutBytesSendsOnlyInvokeComplete() throws IOException { + stream.onStart(null); + + List messages = write(new InvokeResult(200, null, new byte[0], null, "r"), false); + + assertEquals(List.of("InvokeComplete"), types(messages)); + assertEquals("{}", messages.get(0).text()); + } + + @Test + void functionThatDoesNotStreamSendsItsPayloadAsOneChunk() throws IOException { + InvokeResult result = new InvokeResult(200, null, "{\"ok\":true}".getBytes(StandardCharsets.UTF_8), null, "r"); + + List messages = write(result, false); + + assertEquals(List.of("PayloadChunk", "InvokeComplete"), types(messages)); + assertEquals("{\"ok\":true}", messages.get(0).text()); + assertEquals("{}", messages.get(1).text()); + assertEquals("application/json", stream.remappedContentType(done(result))); + } + + @Test + void functionThatDoesNotStreamAndReturnsNothingSendsOnlyInvokeComplete() throws IOException { + List messages = write(new InvokeResult(200, null, new byte[0], null, "r"), false); + + assertEquals(List.of("InvokeComplete"), types(messages)); + } + + @Test + void functionErrorSendsTheErrorPayloadThenUnhandled() throws IOException { + InvokeResult result = new InvokeResult(200, "Unhandled", "{\"errorMessage\":\"x\"}".getBytes(StandardCharsets.UTF_8), + null, "r"); + + List messages = write(result, false); + + assertEquals(List.of("PayloadChunk", "InvokeComplete"), types(messages)); + assertEquals("{\"errorMessage\":\"x\"}", messages.get(0).text()); + assertEquals("{\"ErrorCode\":\"Unhandled\",\"ErrorDetails\":\"\"}", messages.get(1).text()); + assertEquals("application/json", stream.remappedContentType(done(result))); + } + + @Test + void timeoutWithoutStreamingSendsNoChunk() throws IOException { + InvokeResult result = new InvokeResult(200, "Unhandled", "{\"errorMessage\":\"timeout\"}".getBytes(StandardCharsets.UTF_8), + null, "r"); + result.setTimedOut(true); + + List messages = write(result, false); + + assertEquals(List.of("InvokeComplete"), types(messages)); + assertEquals("{\"ErrorCode\":\"Unhandled\",\"ErrorDetails\":\"\"}", messages.get(0).text()); + assertEquals("application/octet-stream", stream.remappedContentType(done(result))); + } + + @Test + void timeoutAfterStreamingReportsSandboxTimeout() throws IOException { + stream.onStart(null); + stream.onChunk("partial".getBytes(StandardCharsets.UTF_8)); + InvokeResult result = new InvokeResult(200, "Unhandled", "{}".getBytes(StandardCharsets.UTF_8), null, "r"); + result.setTimedOut(true); + + List messages = write(result, false); + + assertEquals(List.of("PayloadChunk", "InvokeComplete"), types(messages)); + assertEquals("{\"ErrorCode\":\"Sandbox.Timeout\"}", messages.get(1).text()); + } + + @Test + void failureAfterStreamingReportsTruncatedResponse() throws IOException { + stream.onStart(null); + stream.onChunk("partial".getBytes(StandardCharsets.UTF_8)); + InvokeResult result = new InvokeResult(200, "Unhandled", "{}".getBytes(StandardCharsets.UTF_8), null, "r"); + + List messages = write(result, false); + + assertEquals(List.of("PayloadChunk", "InvokeComplete"), types(messages)); + assertEquals("{\"ErrorCode\":\"Runtime.TruncatedResponse\"}", messages.get(1).text()); + } + + @Test + void logResultReplacesTheErrorFieldsAndKeepsTheChunkOfItsCase() throws IOException { + InvokeResult result = new InvokeResult(200, "Unhandled", "{\"errorMessage\":\"x\"}".getBytes(StandardCharsets.UTF_8), + "bG9ncw==", "r"); + + List messages = write(result, true); + + assertEquals(List.of("PayloadChunk", "InvokeComplete"), types(messages)); + assertEquals("{\"LogResult\":\"bG9ncw==\"}", messages.get(1).text()); + } + + @Test + void logResultOnATimeoutSendsNoChunk() throws IOException { + InvokeResult result = new InvokeResult(200, "Unhandled", "{}".getBytes(StandardCharsets.UTF_8), "bG9ncw==", "r"); + result.setTimedOut(true); + + List messages = write(result, true); + + assertEquals(List.of("InvokeComplete"), types(messages)); + assertEquals("{\"LogResult\":\"bG9ncw==\"}", messages.get(0).text()); + } + + @Test + void logResultIsLeftOutWhenNoTailWasAsked() throws IOException { + InvokeResult result = new InvokeResult(200, null, new byte[0], "bG9ncw==", "r"); + + List messages = write(result, false); + + assertEquals("{}", messages.get(0).text()); + } + + @Test + void failureReportsItsTypeAndBody() throws IOException { + stream.onStart(null); + stream.onChunk("hello ".getBytes(StandardCharsets.UTF_8)); + stream.onFailure("Error", "{\"errorMessage\":\"boom\"}"); + + List messages = write(new InvokeResult(200, null, new byte[0], null, "r"), false); + + assertEquals(List.of("PayloadChunk", "InvokeComplete"), types(messages)); + assertEquals("{\"ErrorCode\":\"Error\",\"ErrorDetails\":\"{\\\"errorMessage\\\":\\\"boom\\\"}\"}", + messages.get(1).text()); + } + + @Test + void failureWithoutABodyLeavesErrorDetailsOut() throws IOException { + stream.onStart(null); + stream.onFailure("Runtime.TruncatedResponse", null); + + List messages = write(new InvokeResult(200, null, new byte[0], null, "r"), false); + + assertEquals("{\"ErrorCode\":\"Runtime.TruncatedResponse\"}", messages.get(0).text()); + } + + @Test + void failureWithALogTailSendsOnlyLogResult() throws IOException { + stream.onStart(null); + stream.onFailure("Error", "{}"); + + List messages = write(new InvokeResult(200, null, new byte[0], "bG9ncw==", "r"), true); + + assertEquals("{\"LogResult\":\"bG9ncw==\"}", messages.get(0).text()); + } + + @Test + void timeoutWinsOverAFailure() throws IOException { + stream.onStart(null); + stream.onFailure("Error", "{}"); + InvokeResult result = new InvokeResult(200, "Unhandled", "{}".getBytes(StandardCharsets.UTF_8), null, "r"); + result.setTimedOut(true); + + List messages = write(result, false); + + assertEquals("{\"ErrorCode\":\"Sandbox.Timeout\"}", messages.get(0).text()); + } + + @Test + void startedCompletesOnlyForAStreamingFunction() { + assertFalse(stream.started().isDone()); + stream.onStart(null); + assertTrue(stream.started().isDone()); + } + + @Test + void chunksReachTheClientWhileTheFunctionIsStillRunning() throws Exception { + CompletableFuture invocation = new CompletableFuture<>(); + CountDownLatch firstWrite = new CountDownLatch(1); + ByteArrayOutputStream out = new ByteArrayOutputStream() { + @Override + public synchronized void write(byte[] bytes) throws IOException { + super.write(bytes); + firstWrite.countDown(); + } + }; + stream.onStart(null); + stream.onChunk("early".getBytes(StandardCharsets.UTF_8)); + StreamingOutput body = stream.body(invocation, false).getEntity(); + CompletableFuture writer = CompletableFuture.runAsync(() -> { + try { + body.write(out); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }); + + assertTrue(firstWrite.await(5, TimeUnit.SECONDS)); + assertFalse(writer.isDone()); + + invocation.complete(new InvokeResult(200, null, new byte[0], null, "r")); + stream.end(); + writer.get(5, TimeUnit.SECONDS); + assertEquals(List.of("PayloadChunk", "InvokeComplete"), types(decoded(out))); + } + + @Test + void chunksAreDroppedAfterTheClientIsGone() { + OutputStream closed = new OutputStream() { + @Override + public void write(int b) throws IOException { + throw new IOException("closed"); + } + }; + stream.onStart(null); + stream.onChunk(new byte[] {1}); + assertThrows(IOException.class, () -> stream.write(closed, new CompletableFuture<>(), false)); + + stream.onChunk(new byte[] {2}); + stream.end(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + assertDoesNotThrow(() -> stream.write(out, done(new InvokeResult(200, null, new byte[0], null, "r")), false)); + assertEquals(List.of("InvokeComplete"), types(decoded(out))); + } + + private static List decoded(ByteArrayOutputStream out) { + return EventStreamMessages.decode(out.toByteArray()); + } + + private List write(InvokeResult result, boolean logTail) throws IOException { + stream.end(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + stream.write(out, done(result), logTail); + return EventStreamMessages.decode(out.toByteArray()); + } + + private static List types(List messages) { + return messages.stream().map(Message::type).toList(); + } + + private static CompletableFuture done(InvokeResult result) { + return CompletableFuture.completedFuture(result); + } +} diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaInvokeWithResponseStreamIntegrationTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaInvokeWithResponseStreamIntegrationTest.java new file mode 100644 index 0000000000..c5344e567d --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambda/LambdaInvokeWithResponseStreamIntegrationTest.java @@ -0,0 +1,299 @@ +package io.floci.aws.services.lambda; + +import io.floci.aws.testing.EventStreamMessages; +import io.floci.aws.testing.EventStreamMessages.Message; +import io.floci.aws.testing.LambdaCodeFixtures; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class LambdaInvokeWithResponseStreamIntegrationTest { + + private static final String SUFFIX = UUID.randomUUID().toString().substring(0, 8); + private static final String STREAMING = "invoke-stream-" + SUFFIX; + private static final String PLAIN = "invoke-plain-" + SUFFIX; + private static final String EVENT_STREAM = "application/vnd.amazon.eventstream"; + + private static boolean created; + + @BeforeEach + void createFunctions() { + if (created) { + return; + } + created = true; + create(STREAMING, """ + exports.handler = awslambda.streamifyResponse(async (event, responseStream) => { + if (event.contentType) responseStream.setContentType(event.contentType); + if (event.mode === 'log') console.log('streamed log line'); + if (event.mode === 'throwBefore') throw new Error('boom before'); + if (event.mode === 'exit') { + await new Promise(() => responseStream.write('hello ', () => process.exit(3))); + } + responseStream.write('hello '); + if (event.mode === 'throwAfter') throw new Error('boom after'); + responseStream.write('world'); + responseStream.end(); + }); + """); + create(PLAIN, """ + exports.handler = async (event) => { + if (event.fail) throw new Error('boom'); + return {ok: true}; + }; + """); + } + + @Test + void streamingHandlerSendsItsChunksThenInvokeComplete() { + Response response = invoke(STREAMING, "{}", ""); + + response.then().statusCode(200) + .contentType(EVENT_STREAM) + .header("X-Amz-Executed-Version", "$LATEST") + .header("x-amzn-Remapped-Content-Type", "application/octet-stream"); + List messages = EventStreamMessages.decode(response.asByteArray()); + assertEquals("hello world", chunks(messages)); + assertEquals(1, messages.stream().filter(m -> "InvokeComplete".equals(m.type())).count()); + Message complete = messages.get(messages.size() - 1); + assertEquals("InvokeComplete", complete.type()); + assertEquals("{}", complete.text()); + assertEquals(List.of(":event-type", ":content-type", ":message-type"), + List.copyOf(complete.headers().keySet())); + assertEquals("application/json", complete.headers().get(":content-type")); + assertEquals("event", complete.headers().get(":message-type")); + assertEquals("application/octet-stream", messages.get(0).headers().get(":content-type")); + } + + @Test + void contentTypeTheHandlerSetsIsReported() { + Response response = invoke(STREAMING, "{\"contentType\":\"text/plain\"}", ""); + + response.then().statusCode(200).header("x-amzn-Remapped-Content-Type", "text/plain"); + assertEquals("hello world", chunks(EventStreamMessages.decode(response.asByteArray()))); + } + + @Test + void plainHandlerSendsItsResultAsOneChunk() { + Response response = invoke(PLAIN, "{}", ""); + + response.then().statusCode(200).header("x-amzn-Remapped-Content-Type", "application/json"); + List messages = EventStreamMessages.decode(response.asByteArray()); + assertEquals(2, messages.size()); + assertEquals("PayloadChunk", messages.get(0).type()); + assertEquals("{\"ok\":true}", messages.get(0).text()); + assertEquals("{}", messages.get(1).text()); + } + + @Test + void plainHandlerThatThrowsSendsTheErrorThenUnhandled() { + List messages = EventStreamMessages.decode(invoke(PLAIN, "{\"fail\":true}", "").asByteArray()); + + assertEquals(2, messages.size()); + assertEquals("PayloadChunk", messages.get(0).type()); + assertTrue(messages.get(0).text().contains("boom"), messages.get(0).text()); + assertEquals("{\"ErrorCode\":\"Unhandled\",\"ErrorDetails\":\"\"}", messages.get(1).text()); + } + + @Test + void errorBeforeAnyWriteIsReportedInInvokeComplete() { + List messages = EventStreamMessages.decode(invoke(STREAMING, "{\"mode\":\"throwBefore\"}", "").asByteArray()); + + assertEquals(1, messages.size()); + assertErrorComplete(messages.get(0), "boom before"); + } + + @Test + void errorAfterAWriteKeepsTheChunkAndIsReported() { + List messages = EventStreamMessages.decode(invoke(STREAMING, "{\"mode\":\"throwAfter\"}", "").asByteArray()); + + assertEquals(2, messages.size()); + assertEquals("hello ", messages.get(0).text()); + assertErrorComplete(messages.get(1), "boom after"); + } + + @Test + void runtimeExitInTheMiddleOfTheStreamIsATruncatedResponse() { + List messages = EventStreamMessages.decode(invoke(STREAMING, "{\"mode\":\"exit\"}", "").asByteArray()); + + assertEquals(2, messages.size()); + assertEquals("hello ", messages.get(0).text()); + assertEquals("{\"ErrorCode\":\"Runtime.TruncatedResponse\"}", messages.get(1).text()); + } + + private static void assertErrorComplete(Message complete, String message) { + assertEquals("InvokeComplete", complete.type()); + assertTrue(complete.text().startsWith("{\"ErrorCode\":\"Error\",\"ErrorDetails\":\""), complete.text()); + assertTrue(complete.text().contains(message), complete.text()); + } + + @Test + void logTailSendsOnlyLogResultInInvokeComplete() { + Response response = given().header("X-Amz-Log-Type", "Tail").body("{\"mode\":\"log\"}") + .when().post(path(STREAMING, "")); + + response.then().statusCode(200); + List messages = EventStreamMessages.decode(response.asByteArray()); + Message complete = messages.get(messages.size() - 1); + assertTrue(complete.text().startsWith("{\"LogResult\":\""), complete.text()); + String logs = new String(Base64.getDecoder().decode(complete.text().substring(14, complete.text().length() - 2))); + assertTrue(logs.contains("streamed log line"), logs); + } + + @Test + void dryRunStillStreams() { + Response response = given().header("X-Amz-Invocation-Type", "DryRun").body("{}") + .when().post(path(STREAMING, "")); + + response.then().statusCode(200); + assertEquals("hello world", chunks(EventStreamMessages.decode(response.asByteArray()))); + } + + @Test + void qualifierSelectsAPublishedVersion() { + given().contentType("application/json").body("{}") + .when().post("/2015-03-31/functions/" + STREAMING + "/versions") + .then().statusCode(201).body("Version", equalTo("1")); + + invoke(STREAMING, "{}", "?Qualifier=1").then().statusCode(200).header("X-Amz-Executed-Version", "1"); + } + + @Test + void bodyOverTheLimitIsRefused() { + byte[] body = new byte[6291457]; + Arrays.fill(body, (byte) 'x'); + + given().body(body).when().post(path(STREAMING, "")) + .then().statusCode(413) + .body("__type", equalTo("RequestEntityTooLargeException")) + .body("message", equalTo("6291457 byte payload is too large for the RequestResponse invocation type" + + " (limit 6291456 bytes)")); + } + + @Test + void invalidArgumentsAreAllReported() { + given().header("X-Amz-Log-Type", "Bogus").header("X-Amz-Invocation-Type", "Bogus").body("{}") + .when().post(path(STREAMING, "?Qualifier=a b")) + .then().statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("3 validation errors detected: " + + "Value 'Bogus' at 'logType' failed to satisfy constraint: " + + "Member must satisfy enum value set: [Tail, None]; " + + "Value 'Bogus' at 'invocationType' failed to satisfy constraint: " + + "Member must satisfy enum value set: [DryRun, RequestResponse, Event]; " + + "Value 'a b' at 'qualifier' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: \\$(LATEST(\\.PUBLISHED)?)|[a-zA-Z0-9-_$]+")); + } + + @Test + void emptyQualifierBreaksThePatternAndTheLength() { + given().body("{}").when().post(path(STREAMING, "?Qualifier=")) + .then().statusCode(400) + .body("message", equalTo("2 validation errors detected: " + + "Value '' at 'qualifier' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: \\$(LATEST(\\.PUBLISHED)?)|[a-zA-Z0-9-_$]+; " + + "Value '' at 'qualifier' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1")); + } + + @Test + void longQualifierWithABadCharacterBreaksThePatternAndTheLength() { + String qualifier = "a " + "a".repeat(127); + given().body("{}").when().post(path(STREAMING, "?Qualifier=" + qualifier)) + .then().statusCode(400) + .body("message", equalTo("2 validation errors detected: " + + "Value '" + qualifier + "' at 'qualifier' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: \\$(LATEST(\\.PUBLISHED)?)|[a-zA-Z0-9-_$]+; " + + "Value '" + qualifier + "' at 'qualifier' failed to satisfy constraint: " + + "Member must have length less than or equal to 128")); + } + + @Test + void plainInvokeReportsTheSameQualifierViolations() { + given().body("{}").when().post("/2015-03-31/functions/" + STREAMING + "/invocations?Qualifier=") + .then().statusCode(400) + .body("message", equalTo("2 validation errors detected: " + + "Value '' at 'qualifier' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: \\$(LATEST(\\.PUBLISHED)?)|[a-zA-Z0-9-_$]+; " + + "Value '' at 'qualifier' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1")); + } + + @Test + void bodyThatIsNotJsonIsRefused() { + given().body("not json").when().post(path(STREAMING, "")) + .then().statusCode(400) + .body("__type", equalTo("InvalidRequestContentException")) + .body("message", startsWith( + "Could not parse request body into json: Could not parse payload into json: ")); + } + + @Test + void functionThatDoesNotExistIsNotFound() { + given().body("{}").when().post(path("no-such-function-" + SUFFIX, "")) + .then().statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + void missingFunctionIsReportedBeforeABadClientContext() { + given().header("X-Amz-Client-Context", "%%%").body("{}") + .when().post(path("no-such-function-" + SUFFIX, "")) + .then().statusCode(404); + + given().header("X-Amz-Client-Context", "%%%").body("{}").when().post(path(STREAMING, "")) + .then().statusCode(400).body("__type", equalTo("InvalidRequestContentException")); + } + + @Test + void emptyBodyAndJsonScalarAreAccepted() { + invoke(STREAMING, "", "").then().statusCode(200); + invoke(STREAMING, "3", "").then().statusCode(200); + } + + private static Response invoke(String name, String body, String query) { + return given().body(body).when().post(path(name, query)); + } + + private static String path(String name, String query) { + return "/2021-11-15/functions/" + name + "/response-streaming-invocations" + query; + } + + private static String chunks(List messages) { + ByteArrayOutputStream joined = new ByteArrayOutputStream(); + messages.stream().filter(m -> "PayloadChunk".equals(m.type())) + .forEach(m -> joined.writeBytes(m.payload())); + return joined.toString(StandardCharsets.UTF_8); + } + + private static void create(String name, String code) { + given().contentType("application/json") + .body(""" + { + "FunctionName":"%s", + "Runtime":"nodejs22.x", + "Role":"arn:aws:iam::000000000000:role/lambda-role", + "Handler":"index.handler", + "Timeout":30, + "Code":{"ZipFile":"%s"} + } + """.formatted(name, Base64.getEncoder().encodeToString(LambdaCodeFixtures.nodeJsZip(code)))) + .when().post("/2015-03-31/functions") + .then().statusCode(201); + } +} diff --git a/src/test/java/io/floci/aws/services/lambda/runtime/RuntimeApiServerTest.java b/src/test/java/io/floci/aws/services/lambda/runtime/RuntimeApiServerTest.java index fb98a1563c..6884dd62c9 100644 --- a/src/test/java/io/floci/aws/services/lambda/runtime/RuntimeApiServerTest.java +++ b/src/test/java/io/floci/aws/services/lambda/runtime/RuntimeApiServerTest.java @@ -16,7 +16,9 @@ import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStreamReader; import java.io.OutputStream; import java.net.BindException; import java.net.InetSocketAddress; @@ -30,6 +32,7 @@ import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; +import java.util.Base64; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArrayList; @@ -386,6 +389,132 @@ class RuntimeApiServerTest { assertTrue(chunks.isEmpty()); } + @Test + @Timeout(10) + void errorTrailersOfAStreamedResponseReachTheListener() throws Exception { + List failures = new CopyOnWriteArrayList<>(); + PendingInvocation invocation = failureRecordingInvocation("req-trailers", failures); + server.enqueue(invocation); + pollNext(); + + try (Socket socket = new Socket("localhost", port)) { + sendStreamedResponse(socket, "req-trailers", chunk("partial") + + "0\r\nLambda-Runtime-Function-Error-Type: RangeError\r\n" + + "Lambda-Runtime-Function-Error-Body: " + base64("{\"errorType\":\"RangeError\"}") + + "\r\n\r\n"); + + InvokeResult result = invocation.getResultFuture().get(5, TimeUnit.SECONDS); + assertNull(result.getFunctionError()); + assertEquals(List.of("RangeError|{\"errorType\":\"RangeError\"}"), failures); + } + } + + @Test + @Timeout(10) + void streamedResponseWithoutTrailersIsNotAFailure() throws Exception { + List failures = new CopyOnWriteArrayList<>(); + PendingInvocation invocation = failureRecordingInvocation("req-no-trailers", failures); + server.enqueue(invocation); + pollNext(); + + try (Socket socket = new Socket("localhost", port)) { + sendStreamedResponse(socket, "req-no-trailers", chunk("data") + "0\r\n\r\n"); + + invocation.getResultFuture().get(5, TimeUnit.SECONDS); + assertTrue(failures.isEmpty()); + } + } + + @Test + @Timeout(10) + void trailersOfOneRequestAreNotSeenByTheNextOnTheSameConnection() throws Exception { + List firstFailures = new CopyOnWriteArrayList<>(); + List secondFailures = new CopyOnWriteArrayList<>(); + PendingInvocation first = failureRecordingInvocation("req-first", firstFailures); + server.enqueue(first); + pollNext(); + + try (Socket socket = new Socket("localhost", port)) { + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)); + sendStreamedResponse(socket, "req-first", chunk("a") + + "0\r\nLambda-Runtime-Function-Error-Type: Error\r\n\r\n"); + first.getResultFuture().get(5, TimeUnit.SECONDS); + readResponse(in); + + PendingInvocation second = failureRecordingInvocation("req-second", secondFailures); + server.enqueue(second); + pollNext(); + sendStreamedResponse(socket, "req-second", chunk("b") + "0\r\n\r\n"); + second.getResultFuture().get(5, TimeUnit.SECONDS); + readResponse(in); + } + assertEquals(List.of("Error|null"), firstFailures); + assertTrue(secondFailures.isEmpty()); + } + + @Test + @Timeout(10) + void connectionClosedInTheMiddleOfAStreamedResponseIsATruncatedResponse() throws Exception { + List failures = new CopyOnWriteArrayList<>(); + PendingInvocation invocation = failureRecordingInvocation("req-cut", failures); + server.enqueue(invocation); + pollNext(); + + try (Socket socket = new Socket("localhost", port)) { + sendStreamedResponse(socket, "req-cut", chunk("partial")); + } + + invocation.getResultFuture().get(5, TimeUnit.SECONDS); + assertEquals(List.of("Runtime.TruncatedResponse|null"), failures); + } + + private void sendStreamedResponse(Socket socket, String requestId, String body) throws IOException { + OutputStream out = socket.getOutputStream(); + out.write(("POST /2018-06-01/runtime/invocation/" + requestId + "/response HTTP/1.1\r\n" + + "Host: localhost\r\n" + + "Lambda-Runtime-Function-Response-Mode: streaming\r\n" + + "Trailer: Lambda-Runtime-Function-Error-Type, Lambda-Runtime-Function-Error-Body\r\n" + + "Transfer-Encoding: chunked\r\n\r\n" + + body).getBytes(StandardCharsets.UTF_8)); + out.flush(); + } + + private static void readResponse(BufferedReader in) throws IOException { + int length = 0; + for (String line = in.readLine(); line != null && !line.isEmpty(); line = in.readLine()) { + if (line.toLowerCase().startsWith("content-length:")) { + length = Integer.parseInt(line.substring("content-length:".length()).trim()); + } + } + in.skip(length); + } + + private static String base64(String text) { + return Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8)); + } + + private PendingInvocation failureRecordingInvocation(String requestId, List failures) { + PendingInvocation invocation = streamingInvocation(requestId, new AtomicReference<>(), new ArrayList<>()); + ResponseStreamListener delegate = invocation.getResponseStreamListener(); + invocation.setResponseStreamListener(new ResponseStreamListener() { + @Override + public void onStart(String type) { + delegate.onStart(type); + } + + @Override + public void onChunk(byte[] chunk) { + delegate.onChunk(chunk); + } + + @Override + public void onFailure(String errorType, String errorBody) { + failures.add(errorType + "|" + errorBody); + } + }); + return invocation; + } + private PendingInvocation streamingInvocation(String requestId, AtomicReference contentType, List chunks) { PendingInvocation invocation = new PendingInvocation( diff --git a/src/test/java/io/floci/aws/services/s3/S3SelectIntegrationTest.java b/src/test/java/io/floci/aws/services/s3/S3SelectIntegrationTest.java index eaae89cae2..7eeb09c1c7 100644 --- a/src/test/java/io/floci/aws/services/s3/S3SelectIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/s3/S3SelectIntegrationTest.java @@ -1,6 +1,7 @@ package io.floci.aws.services.s3; -import io.floci.aws.services.s3.EventStreamMessages.Message; +import io.floci.aws.testing.EventStreamMessages; +import io.floci.aws.testing.EventStreamMessages.Message; import io.quarkus.test.junit.QuarkusTest; import io.restassured.response.ValidatableResponse; import org.junit.jupiter.api.Test; diff --git a/src/test/java/io/floci/aws/services/s3/S3SelectStreamingTest.java b/src/test/java/io/floci/aws/services/s3/S3SelectStreamingTest.java index 42eeeaf6c5..792906ad81 100644 --- a/src/test/java/io/floci/aws/services/s3/S3SelectStreamingTest.java +++ b/src/test/java/io/floci/aws/services/s3/S3SelectStreamingTest.java @@ -3,8 +3,9 @@ package io.floci.aws.services.s3; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsException; import io.floci.aws.services.floci.duck.FlociDuckClient; -import io.floci.aws.services.s3.EventStreamMessages.Message; import io.floci.aws.services.s3.model.S3Object; +import io.floci.aws.testing.EventStreamMessages; +import io.floci.aws.testing.EventStreamMessages.Message; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/io/floci/aws/services/s3/EventStreamMessages.java b/src/test/java/io/floci/aws/testing/EventStreamMessages.java similarity index 91% rename from src/test/java/io/floci/aws/services/s3/EventStreamMessages.java rename to src/test/java/io/floci/aws/testing/EventStreamMessages.java index fe5e951c8f..f563026cea 100644 --- a/src/test/java/io/floci/aws/services/s3/EventStreamMessages.java +++ b/src/test/java/io/floci/aws/testing/EventStreamMessages.java @@ -1,4 +1,4 @@ -package io.floci.aws.services.s3; +package io.floci.aws.testing; import java.io.ByteArrayInputStream; import java.io.DataInputStream; @@ -13,24 +13,24 @@ import java.util.Map; import java.util.zip.CRC32; /** Splits an AWS event stream into its messages, checking the prelude and message CRCs of each. */ -final class EventStreamMessages { +public final class EventStreamMessages { private EventStreamMessages() { } - record Message(Map headers, byte[] payload) { + public record Message(Map headers, byte[] payload) { /** The event type of an event message, or the message type of any other. */ - String type() { + public String type() { return headers.getOrDefault(":event-type", headers.get(":message-type")); } - String text() { + public String text() { return new String(payload, StandardCharsets.UTF_8); } } - static List decode(byte[] stream) { + public static List decode(byte[] stream) { List messages = new ArrayList<>(); int offset = 0; try { diff --git a/tools/docs/service_matrix.yaml b/tools/docs/service_matrix.yaml index 41f131263f..545cec1a36 100644 --- a/tools/docs/service_matrix.yaml +++ b/tools/docs/service_matrix.yaml @@ -285,6 +285,7 @@ action_count_sources: - { path: services/lambda/LambdaAccountSettingsController.java, mode: rest } - { path: services/lambda/LambdaCodeSigningController.java, mode: rest } - { path: services/lambda/LambdaCodeSigningConfigFunctionsController.java, mode: rest } + - { path: services/lambda/LambdaResponseStreamController.java, mode: rest } - { path: services/lambda/LambdaConcurrencyController.java, mode: rest } - { path: services/lambda/LambdaProvisionedConcurrencyController.java, mode: rest } - { path: services/lambda/LambdaEventInvokeController.java, mode: rest }