diff --git a/docs/services/lambda.md b/docs/services/lambda.md index c2a99e6976..06bad19c2e 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -429,6 +429,8 @@ disabled fails with Lambda's error as the resource status reason. Function URLs are also reachable directly on `/{proxy:.*}` under the Lambda URL controller, which routes the request into the normal `Invoke` path. +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`. + 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), [China guide](https://docs.amazonaws.cn/en_us/aws/latest/userguide/lambda.html)), so 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 c611bc4ca4..7826884fcf 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java @@ -12,6 +12,7 @@ import io.floci.aws.services.lambda.model.InvocationType; import io.floci.aws.services.lambda.model.InvokeResult; import io.floci.aws.services.lambda.model.LambdaFunction; import io.floci.aws.services.lambda.model.PendingInvocation; +import io.floci.aws.services.lambda.model.ResponseStreamListener; import io.floci.aws.services.lambda.runtime.RuntimeApiServer; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; @@ -166,7 +167,7 @@ public class LambdaExecutorService implements Resettable { } public InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, String requestId) { - return invoke(fn, payload, type, 0, null, null, requestId); + return invoke(fn, payload, type, 0, null, null, requestId, null); } /** @@ -190,11 +191,23 @@ public class LambdaExecutorService implements Resettable { InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth, String invokedQualifier, String clientContext) { - return invoke(fn, payload, type, chainDepth, invokedQualifier, clientContext, UUID.randomUUID().toString()); + return invoke(fn, payload, type, chainDepth, invokedQualifier, clientContext, UUID.randomUUID().toString(), + null); + } + + /** + * A synchronous invocation whose response, if the runtime streams it, goes to {@code listener} + * as it arrives rather than into the returned result. + */ + public InvokeResult invokeStreaming(LambdaFunction fn, byte[] payload, int chainDepth, String invokedQualifier, + ResponseStreamListener listener) { + return invoke(fn, payload, InvocationType.RequestResponse, chainDepth, invokedQualifier, null, + UUID.randomUUID().toString(), listener); } private InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth, - String invokedQualifier, String clientContext, String requestId) { + String invokedQualifier, String clientContext, String requestId, + ResponseStreamListener listener) { if (type == InvocationType.DryRun) { return new InvokeResult(204, null, new byte[0], null, requestId); } @@ -246,7 +259,7 @@ public class LambdaExecutorService implements Resettable { } try { - return executeSync(fn, payload, requestId, clientContext, invokedQualifier); + return executeSync(fn, payload, requestId, clientContext, invokedQualifier, listener); } finally { permit.close(); } @@ -302,7 +315,7 @@ public class LambdaExecutorService implements Resettable { } InvokeResult result; try (permit) { - result = executeSync(event.fn(), event.payload(), event.requestId(), null, event.invokedQualifier()); + result = executeSync(event.fn(), event.payload(), event.requestId(), null, event.invokedQualifier(), null); } catch (RuntimeException e) { LOG.warnv("Error in async Lambda execution for {0}: {1}", event.fn().getFunctionName(), e.getMessage()); // Stops retrying, as upstream did: routes the previous attempt's result, or UnknownError when @@ -360,7 +373,8 @@ public class LambdaExecutorService implements Resettable { } private InvokeResult executeSync(LambdaFunction fn, byte[] payload, String requestId, - String clientContext, String invokedQualifier) { + String clientContext, String invokedQualifier, + ResponseStreamListener listener) { ContainerHandle handle; try { handle = warmPool.acquireProvisioned(fn, invokedQualifier); @@ -378,6 +392,7 @@ public class LambdaExecutorService implements Resettable { requestId, payload, deadlineMs, fn.getFunctionArn(), new CompletableFuture<>()); invocation.setClientContext(clientContext); + invocation.setResponseStreamListener(listener); RuntimeApiServer runtimeApiServer = handle.getRuntimeApiServer(); boolean initializing = !runtimeApiServer.hasRuntimePolled(); long dispatchWaitMs = dispatchWaitMs(fn.getTimeout(), initializing, 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 8c2cb890d3..bc7910e617 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaService.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaService.java @@ -38,6 +38,7 @@ import io.floci.aws.services.lambda.model.LambdaAlias; import io.floci.aws.services.lambda.model.LambdaFileSystemConfig; import io.floci.aws.services.lambda.model.LambdaFunction; import io.floci.aws.services.lambda.model.LambdaUrlConfig; +import io.floci.aws.services.lambda.model.ResponseStreamListener; import io.floci.aws.services.lambda.model.ScalingConfig; import io.floci.aws.services.lambda.zip.CodeStore; import io.floci.aws.services.lambda.zip.DeploymentPackage; @@ -1560,7 +1561,21 @@ public class LambdaService implements ResourceProvider { return invokeArn(functionArn, payload, InvocationType.Event, chainDepth); } + /** + * Invokes a Lambda target ARN synchronously, handing a response the runtime streams to + * {@code listener} as it arrives. + */ + public InvokeResult invokeArnStreaming(String functionArn, byte[] payload, ResponseStreamListener listener) { + return invokeArn(functionArn, payload, InvocationType.RequestResponse, + LambdaInvocationChain.currentDepth(), listener); + } + private InvokeResult invokeArn(String functionArn, byte[] payload, InvocationType type, int chainDepth) { + return invokeArn(functionArn, payload, type, chainDepth, null); + } + + private InvokeResult invokeArn(String functionArn, byte[] payload, InvocationType type, int chainDepth, + ResponseStreamListener listener) { AwsArnUtils.Arn arn = AwsArnUtils.parse(functionArn); LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(functionArn); LambdaFunction fn = targetResolver.resolveInvokeTargetForAccount( @@ -1569,7 +1584,9 @@ public class LambdaService implements ResourceProvider { if (durable != null) { return durable; } - InvokeResult result = executorService.invoke(fn, payload, type, chainDepth, ref.qualifier()); + InvokeResult result = listener == null + ? executorService.invoke(fn, payload, type, chainDepth, ref.qualifier()) + : executorService.invokeStreaming(fn, payload, chainDepth, ref.qualifier(), listener); result.setExecutedVersion(fn.getVersion()); return result; } diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaUrlInvocationController.java b/src/main/java/io/floci/aws/services/lambda/LambdaUrlInvocationController.java index f84d7e0f72..0edb043885 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaUrlInvocationController.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaUrlInvocationController.java @@ -13,6 +13,7 @@ import io.floci.aws.services.lambda.model.InvocationType; import io.floci.aws.services.lambda.model.InvokeResult; import io.floci.aws.services.lambda.model.LambdaAlias; import io.floci.aws.services.lambda.model.LambdaFunction; +import io.floci.aws.services.lambda.model.LambdaUrlConfig; import io.smallrye.common.annotation.RunOnVirtualThread; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; @@ -39,6 +40,8 @@ import java.util.Base64; import java.util.List; import java.util.Locale; import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; /** * Handles Lambda Function URL invocations. @@ -114,6 +117,7 @@ public class LambdaUrlInvocationController { String functionArn; String region; String accountId; + LambdaUrlConfig urlConfig; if (target instanceof LambdaAlias alias) { functionName = alias.getFunctionName(); @@ -121,12 +125,14 @@ public class LambdaUrlInvocationController { AwsArnUtils.Arn arn = AwsArnUtils.parse(functionArn); region = arn.region(); accountId = arn.accountId(); + urlConfig = alias.getUrlConfig(); } else if (target instanceof LambdaFunction fn) { functionName = fn.getFunctionName(); functionArn = fn.getFunctionArn(); AwsArnUtils.Arn arn = AwsArnUtils.parse(functionArn); region = arn.region(); accountId = fn.getAccountId() != null ? fn.getAccountId() : arn.accountId(); + urlConfig = fn.getUrlConfig(); } else { return Response.status(404).entity(jsonMessage("Function URL not found")).type(MediaType.APPLICATION_JSON).build(); } @@ -139,15 +145,72 @@ public class LambdaUrlInvocationController { LOG.infov("Lambda URL invocation: {0} {1} -> {2} (region: {3})", method, urlId, functionName, region); + boolean streamed = urlConfig != null && "RESPONSE_STREAM".equals(urlConfig.getInvokeMode()); try { - InvokeResult result = lambdaService.invokeArn( - functionArn, event.getBytes(), InvocationType.RequestResponse); - return buildResponse(result); + if (streamed) { + return invokeStreamed(functionArn, event.getBytes()); + } + return buildResponse(lambdaService.invokeArn( + functionArn, event.getBytes(), InvocationType.RequestResponse)); } catch (AwsException e) { return Response.status(e.getHttpStatus()).entity(e.getMessage()).build(); } } + /** + * Runs the invocation on its own thread and answers as soon as the head of the streamed response + * is known, so the body reaches the caller as the function writes it. A function that fails or + * returns before it streams anything is answered as a buffered response. + */ + private Response invokeStreamed(String functionArn, byte[] event) { + LambdaUrlResponseStream stream = new LambdaUrlResponseStream(objectMapper); + CompletableFuture invocation = new CompletableFuture<>(); + Thread.ofVirtual().name("lambda-url-stream").start(() -> { + try { + invocation.complete(lambdaService.invokeArnStreaming(functionArn, event, stream)); + } catch (RuntimeException e) { + invocation.completeExceptionally(e); + } finally { + stream.end(); + } + }); + CompletableFuture.anyOf(stream.head(), invocation).handle((ignored, e) -> null).join(); + + if (!stream.head().isDone()) { + try { + return buildResponse(invocation.join()); + } catch (CompletionException e) { + if (e.getCause() instanceof AwsException aws) { + throw aws; + } + throw e; + } + } + LambdaUrlResponseStream.Head head; + try { + head = stream.head().join(); + } catch (CompletionException e) { + LOG.warnv("Streamed response of {0} has an unreadable prelude: {1}", functionArn, e.getMessage()); + return Response.status(FUNCTION_ERROR_STATUS).build(); + } + Response.ResponseBuilder builder; + if (head.prelude() == null) { + builder = Response.ok().type(head.contentType() != null ? head.contentType() : MediaType.APPLICATION_OCTET_STREAM); + } else { + builder = Response.status(head.prelude().path("statusCode").asInt(200)); + applyHeadersAndCookies(builder, head.prelude()); + } + return builder.entity(stream.body()).build(); + } + + private static void applyHeadersAndCookies(Response.ResponseBuilder builder, JsonNode response) { + response.path("headers").fields().forEachRemaining(e -> builder.header(e.getKey(), e.getValue().asText())); + JsonNode cookies = response.path("cookies"); + if (cookies.isArray()) { + cookies.forEach(cookie -> builder.header("Set-Cookie", cookie.asText())); + } + } + private String buildEvent(String method, String urlId, String proxy, HttpHeaders headers, UriInfo uriInfo, byte[] body, String requestId, String region) { ObjectNode root = objectMapper.createObjectNode(); root.put("version", "2.0"); @@ -228,12 +291,7 @@ public class LambdaUrlInvocationController { if (node.isObject() && node.has("statusCode")) { int status = node.get("statusCode").asInt(); Response.ResponseBuilder builder = Response.status(status); - if (node.has("headers")) { - node.get("headers").fields().forEachRemaining(e -> builder.header(e.getKey(), e.getValue().asText())); - } - if (node.has("cookies") && node.get("cookies").isArray()) { - node.get("cookies").forEach(cookie -> builder.header("Set-Cookie", cookie.asText())); - } + applyHeadersAndCookies(builder, node); if (node.has("body")) { String body = node.get("body").asText(); boolean isBase64 = node.path("isBase64Encoded").asBoolean(false); diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaUrlResponseStream.java b/src/main/java/io/floci/aws/services/lambda/LambdaUrlResponseStream.java new file mode 100644 index 0000000000..ebfc9a218e --- /dev/null +++ b/src/main/java/io/floci/aws/services/lambda/LambdaUrlResponseStream.java @@ -0,0 +1,114 @@ +package io.floci.aws.services.lambda; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.services.lambda.model.ResponseStreamListener; +import jakarta.ws.rs.core.GenericEntity; +import jakarta.ws.rs.core.StreamingOutput; + +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. + * + *

A stream with the {@code application/vnd.awslambda.http-integration-response} content type, + * which {@code awslambda.HttpResponseStream.from} sets, starts with a JSON prelude (statusCode, + * headers, cookies) ended by eight NUL bytes. The head of the response is known once that prelude + * has arrived, or, for any other stream, once the first bytes have. + */ +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) { + } + + private final ObjectMapper objectMapper; + private final CompletableFuture head = new CompletableFuture<>(); + private final BlockingQueue body = new LinkedBlockingQueue<>(); + private final ByteArrayOutputStream prelude = new ByteArrayOutputStream(); + private String contentType; + private boolean expectsPrelude; + private int delimiterBytes; + + LambdaUrlResponseStream(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + @Override + public void onStart(String contentType) { + this.contentType = contentType; + this.expectsPrelude = contentType != null && contentType.startsWith(HTTP_INTEGRATION_RESPONSE); + } + + @Override + public void onChunk(byte[] chunk) { + if (chunk.length == 0) { + return; + } + if (head.isDone()) { + body.add(chunk); + } else if (!expectsPrelude) { + body.add(chunk); + head.complete(new Head(null, contentType)); + } else { + readPrelude(chunk); + } + } + + private void readPrelude(byte[] chunk) { + for (int i = 0; i < chunk.length; i++) { + prelude.write(chunk[i]); + delimiterBytes = chunk[i] == 0 ? delimiterBytes + 1 : 0; + if (delimiterBytes == PRELUDE_DELIMITER_LENGTH) { + byte[] json = Arrays.copyOf(prelude.toByteArray(), prelude.size() - PRELUDE_DELIMITER_LENGTH); + if (i + 1 < chunk.length) { + body.add(Arrays.copyOfRange(chunk, i + 1, chunk.length)); + } + try { + head.complete(new Head(objectMapper.readTree(json), contentType)); + } catch (IOException e) { + head.completeExceptionally(e); + } + return; + } + } + } + + /** Ends the body; the function has returned, whether or not it streamed anything. */ + void end() { + body.add(END); + } + + CompletableFuture head() { + return head; + } + + /** + * Writes the body as it arrives, until the function returns. The {@code GenericEntity} keeps + * {@code StreamingOutput} as the entity type, as the Bedrock controllers do. + */ + GenericEntity body() { + return new GenericEntity<>(this::write, StreamingOutput.class); + } + + 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(); + } + } +} diff --git a/src/main/java/io/floci/aws/services/lambda/model/PendingInvocation.java b/src/main/java/io/floci/aws/services/lambda/model/PendingInvocation.java index 41e5825c93..d3e2dcd246 100644 --- a/src/main/java/io/floci/aws/services/lambda/model/PendingInvocation.java +++ b/src/main/java/io/floci/aws/services/lambda/model/PendingInvocation.java @@ -13,6 +13,7 @@ public class PendingInvocation { private final CompletableFuture resultFuture; private final CompletableFuture dispatchedFuture = new CompletableFuture<>(); private volatile String clientContext; + private volatile ResponseStreamListener responseStreamListener; public PendingInvocation(String requestId, byte[] payload, long deadlineMs, String functionArn, CompletableFuture resultFuture) { @@ -39,6 +40,8 @@ public class PendingInvocation { public String getFunctionArn() { return functionArn; } public String getClientContext() { return clientContext; } public void setClientContext(String clientContext) { this.clientContext = clientContext; } + public ResponseStreamListener getResponseStreamListener() { return responseStreamListener; } + public void setResponseStreamListener(ResponseStreamListener listener) { this.responseStreamListener = listener; } public CompletableFuture getResultFuture() { return resultFuture; } public CompletableFuture getDispatchedFuture() { return dispatchedFuture; } } 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 new file mode 100644 index 0000000000..bb0fbcaeb0 --- /dev/null +++ b/src/main/java/io/floci/aws/services/lambda/model/ResponseStreamListener.java @@ -0,0 +1,13 @@ +package io.floci.aws.services.lambda.model; + +/** + * Receives a response that the function streams, as the runtime sends it. Only an invocation that + * carries a listener is streamed; every other response is buffered into its {@link InvokeResult}. + */ +public interface ResponseStreamListener { + + /** The runtime started the stream; {@code contentType} is the one it sent, or null. */ + void onStart(String contentType); + + void onChunk(byte[] chunk); +} 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 965dbb815f..273eb9e212 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 @@ -4,6 +4,7 @@ import io.floci.aws.services.lambda.model.ExtensionEvent; 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.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServer; @@ -82,6 +83,8 @@ public class RuntimeApiServer { private static final String ERROR_PATH = "/" + RUNTIME_API_VERSION + "/runtime/invocation/:requestId/error"; 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 EXTENSIONS_API_VERSION = "2020-01-01"; private static final String EXTENSION_REGISTER_PATH = "/" + EXTENSIONS_API_VERSION + "/extension/register"; private static final String EXTENSION_NEXT_PATH = "/" + EXTENSIONS_API_VERSION + "/extension/event/next"; @@ -406,6 +409,8 @@ public class RuntimeApiServer { CompletableFuture started = new CompletableFuture<>(); Router router = Router.router(vertx); + // Registered ahead of the BodyHandler so that a streamed response is read as it arrives. + router.post(RESPONSE_PATH).handler(this::handleStreamedResponse); router.route().handler(BodyHandler.create()); // GET /runtime/invocation/next — AWS Runtime API contract: blocks until an invocation @@ -1004,6 +1009,39 @@ public class RuntimeApiServer { sendStatusOk(ctx); } + /** + * Hands a streamed response to the invocation's {@link ResponseStreamListener} chunk by chunk and + * completes the invocation only when the stream ends, so the function's timeout and its + * container stay held for the whole stream. A response that is not streamed, or one for an + * invocation without a listener, goes on to the buffered handler. + */ + private void handleStreamedResponse(RoutingContext ctx) { + String requestId = ctx.pathParam("requestId"); + PendingInvocation invocation = inFlight.get(requestId); + ResponseStreamListener listener = invocation == null ? null : invocation.getResponseStreamListener(); + if (listener == null || !"streaming".equalsIgnoreCase(ctx.request().getHeader(RESPONSE_MODE_HEADER))) { + ctx.next(); + return; + } + listener.onStart(ctx.request().getHeader("Content-Type")); + 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()); + completeStreamedResponse(requestId); + }); + ctx.request().endHandler(v -> { + completeStreamedResponse(requestId); + sendStatusOk(ctx); + }); + } + + private void completeStreamedResponse(String requestId) { + PendingInvocation invocation = inFlight.remove(requestId); + if (invocation != null) { + invocation.getResultFuture().complete(new InvokeResult(200, null, new byte[0], null, requestId)); + } + } + private void sendStatusOk(RoutingContext ctx) { ctx.response() .setStatusCode(202) diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaFunctionUrlResponseStreamTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaFunctionUrlResponseStreamTest.java new file mode 100644 index 0000000000..e8c1bc2669 --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambda/LambdaFunctionUrlResponseStreamTest.java @@ -0,0 +1,78 @@ +package io.floci.aws.services.lambda; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class LambdaFunctionUrlResponseStreamTest { + + private static final String FUNCTION_NAME = "function-url-response-stream"; + + @Test + void responseStreamUrlAnswersWithThePreludeAndTheStreamedBody() throws Exception { + String urlId = createStreamingFunctionUrl(); + + given() + .when().get("/lambda-url/" + urlId + "/") + .then() + .statusCode(201) + .header("content-type", "text/event-stream") + .body(equalTo("data: first\n\ndata: last\n\n")); + } + + private String createStreamingFunctionUrl() throws Exception { + given() + .contentType("application/json") + .body(""" + { + "FunctionName":"%s", + "Runtime":"nodejs22.x", + "Role":"arn:aws:iam::000000000000:role/lambda-role", + "Handler":"index.handler", + "Code":{"ZipFile":"%s"} + } + """.formatted(FUNCTION_NAME, Base64.getEncoder().encodeToString(lambdaZip()))) + .when().post("/2015-03-31/functions") + .then() + .statusCode(201); + + String functionUrl = given() + .contentType("application/json") + .body(""" + {"AuthType":"NONE","InvokeMode":"RESPONSE_STREAM"} + """) + .when().post("/2021-10-31/functions/" + FUNCTION_NAME + "/url") + .then() + .statusCode(201) + .extract().path("FunctionUrl"); + int scheme = functionUrl.indexOf("://"); + return functionUrl.substring(scheme + 3, functionUrl.indexOf('.', scheme + 3)); + } + + private byte[] lambdaZip() throws Exception { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (ZipOutputStream zip = new ZipOutputStream(bytes)) { + zip.putNextEntry(new ZipEntry("index.js")); + zip.write(""" + exports.handler = awslambda.streamifyResponse(async (event, responseStream) => { + responseStream = awslambda.HttpResponseStream.from(responseStream, { + statusCode: 201, headers: { "content-type": "text/event-stream" } }); + responseStream.write("data: first\\n\\n"); + responseStream.write("data: last\\n\\n"); + responseStream.end(); + }); + """.getBytes(StandardCharsets.UTF_8)); + zip.closeEntry(); + } + return bytes.toByteArray(); + } +} diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaUrlInvocationControllerTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaUrlInvocationControllerTest.java index 08d6d4425f..305dd16de9 100644 --- a/src/test/java/io/floci/aws/services/lambda/LambdaUrlInvocationControllerTest.java +++ b/src/test/java/io/floci/aws/services/lambda/LambdaUrlInvocationControllerTest.java @@ -8,18 +8,25 @@ import io.floci.aws.services.lambda.model.InvocationType; import io.floci.aws.services.lambda.model.InvokeResult; import io.floci.aws.services.lambda.model.LambdaAlias; import io.floci.aws.services.lambda.model.LambdaFunction; +import io.floci.aws.services.lambda.model.LambdaUrlConfig; +import io.floci.aws.services.lambda.model.ResponseStreamListener; +import jakarta.ws.rs.core.GenericEntity; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MultivaluedHashMap; import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.StreamingOutput; import jakarta.ws.rs.core.UriInfo; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.List; import java.util.Locale; +import java.util.concurrent.CountDownLatch; import java.util.function.Function; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -368,6 +375,116 @@ class LambdaUrlInvocationControllerTest { assertFalse(eventNode.has("cookies")); } + @Test + void responseStreamUrlAnswersWithThePreludeAndStreamsTheBodyAfterIt() throws Exception { + Response response = invokeResponseStreamUrl(listener -> { + listener.onStart("application/vnd.awslambda.http-integration-response"); + listener.onChunk(bytes("{\"statusCode\":201,\"headers\":{\"content-type\":\"text/event-stream\"}," + + "\"cookies\":[\"a=1\"]}\0\0\0\0")); + listener.onChunk(bytes("\0\0\0\0data: 1\n\n")); + listener.onChunk(bytes("data: [DONE]\n\n")); + return streamedResult(); + }); + + assertEquals(201, response.getStatus()); + assertEquals("text/event-stream", response.getHeaderString("content-type")); + assertEquals("a=1", response.getHeaderString("Set-Cookie")); + assertEquals("data: 1\n\ndata: [DONE]\n\n", body(response)); + } + + @Test + void responseStreamUrlAnswersBeforeTheFunctionFinishes() throws Exception { + CountDownLatch finish = new CountDownLatch(1); + Response response = invokeResponseStreamUrl(listener -> { + listener.onStart("text/plain"); + listener.onChunk(bytes("first ")); + finish.await(); + listener.onChunk(bytes("last")); + return streamedResult(); + }); + + assertEquals(200, response.getStatus()); + finish.countDown(); + assertEquals("first last", body(response)); + } + + @Test + void responseStreamUrlWithoutAPreludeKeepsTheStreamsContentType() throws Exception { + Response response = invokeResponseStreamUrl(listener -> { + listener.onStart("text/plain"); + listener.onChunk(bytes("{\"statusCode\":418}\0\0\0\0\0\0\0\0hello")); + return streamedResult(); + }); + + assertEquals(200, response.getStatus()); + assertEquals("text/plain", response.getHeaderString("content-type")); + assertEquals("{\"statusCode\":418}\0\0\0\0\0\0\0\0hello", body(response)); + } + + @Test + void responseStreamUrlAnswers502WhenTheFunctionFailsBeforeStreaming() throws Exception { + Response response = invokeResponseStreamUrl(listener -> { + InvokeResult failed = streamedResult(); + failed.setFunctionError("Unhandled"); + return failed; + }); + + assertEquals(502, response.getStatus()); + } + + @Test + void responseStreamUrlAnswers502ForAnUnreadablePrelude() throws Exception { + Response response = invokeResponseStreamUrl(listener -> { + listener.onStart("application/vnd.awslambda.http-integration-response"); + listener.onChunk(bytes("not json\0\0\0\0\0\0\0\0body")); + return streamedResult(); + }); + + assertEquals(502, response.getStatus()); + } + + private interface StreamingFunction { + InvokeResult run(ResponseStreamListener listener) throws Exception; + } + + private Response invokeResponseStreamUrl(StreamingFunction function) { + LambdaUrlConfig urlConfig = new LambdaUrlConfig(); + urlConfig.setInvokeMode("RESPONSE_STREAM"); + LambdaFunction fn = new LambdaFunction(); + fn.setFunctionName("my-function"); + fn.setFunctionArn(FUNCTION_ARN); + fn.setAccountId("100000000012"); + fn.setUrlConfig(urlConfig); + + LambdaService lambdaService = mock(LambdaService.class); + when(lambdaService.getTargetByUrlId("url-id")).thenReturn(fn); + when(lambdaService.invokeArnStreaming(eq(FUNCTION_ARN), any(byte[].class), any(ResponseStreamListener.class))) + .thenAnswer(invocation -> function.run(invocation.getArgument(2))); + + return newController(lambdaService).handleGet("url-id", "", headersWith(null), + uriInfoFor("http://localhost/lambda-url/url-id/")); + } + + private static InvokeResult streamedResult() { + InvokeResult result = new InvokeResult(); + result.setStatusCode(200); + result.setPayload(new byte[0]); + return result; + } + + private static byte[] bytes(String text) { + return text.getBytes(StandardCharsets.UTF_8); + } + + private static String body(Response response) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Object entity = response.getEntity(); + StreamingOutput stream = entity instanceof GenericEntity generic + ? (StreamingOutput) generic.getEntity() : (StreamingOutput) entity; + stream.write(out); + return out.toString(StandardCharsets.UTF_8); + } + private JsonNode readTree(byte[] json) { try { return new ObjectMapper().readTree(json); 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 4ab6fe481c..22abcfb7b2 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 @@ -2,6 +2,7 @@ package io.floci.aws.services.lambda.runtime; import io.floci.aws.services.lambda.model.InvokeResult; import io.floci.aws.services.lambda.model.PendingInvocation; +import io.floci.aws.services.lambda.model.ResponseStreamListener; import io.vertx.core.Context; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; @@ -16,18 +17,22 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; +import java.io.OutputStream; import java.net.BindException; import java.net.InetSocketAddress; import java.net.ServerSocket; +import java.net.Socket; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; @@ -303,6 +308,90 @@ class RuntimeApiServerTest { assertEquals("OK", new JsonObject(response.body()).getString("status")); } + @Test + @Timeout(10) + void streamedResponseReachesTheListenerChunkByChunkAndCompletesAtTheEnd() throws Exception { + List chunks = new CopyOnWriteArrayList<>(); + AtomicReference contentType = new AtomicReference<>(); + PendingInvocation invocation = streamingInvocation("req-stream", contentType, chunks); + server.enqueue(invocation); + pollNext(); + + try (Socket socket = new Socket("localhost", port)) { + OutputStream out = socket.getOutputStream(); + out.write(("POST /2018-06-01/runtime/invocation/req-stream/response HTTP/1.1\r\n" + + "Host: localhost\r\n" + + "Lambda-Runtime-Function-Response-Mode: streaming\r\n" + + "Content-Type: text/event-stream\r\n" + + "Transfer-Encoding: chunked\r\n\r\n" + + chunk("data: 1\n\n")).getBytes(StandardCharsets.UTF_8)); + out.flush(); + + await().atMost(Duration.ofSeconds(5)).until(() -> chunks.size() == 1); + assertEquals("text/event-stream", contentType.get()); + assertEquals("data: 1\n\n", chunks.get(0)); + assertFalse(invocation.getResultFuture().isDone()); + + out.write((chunk("data: 2\n\n") + "0\r\n\r\n").getBytes(StandardCharsets.UTF_8)); + out.flush(); + + InvokeResult result = invocation.getResultFuture().get(5, TimeUnit.SECONDS); + assertNull(result.getFunctionError()); + assertEquals("data: 1\n\ndata: 2\n\n", String.join("", chunks)); + } + } + + @Test + @Timeout(10) + void bufferedResponseOfAnInvocationWithAListenerStaysInTheResult() throws Exception { + List chunks = new CopyOnWriteArrayList<>(); + PendingInvocation invocation = streamingInvocation("req-buffered", new AtomicReference<>(), chunks); + server.enqueue(invocation); + pollNext(); + + httpClient.send(HttpRequest.newBuilder() + .uri(URI.create("http://localhost:" + port + + "/2018-06-01/runtime/invocation/req-buffered/response")) + .POST(HttpRequest.BodyPublishers.ofString("\"result\"")) + .build(), + HttpResponse.BodyHandlers.ofString()); + + InvokeResult result = invocation.getResultFuture().get(5, TimeUnit.SECONDS); + assertEquals("\"result\"", new String(result.getPayload(), StandardCharsets.UTF_8)); + assertTrue(chunks.isEmpty()); + } + + private PendingInvocation streamingInvocation(String requestId, AtomicReference contentType, + List chunks) { + PendingInvocation invocation = new PendingInvocation( + requestId, "{}".getBytes(), System.currentTimeMillis() + 60_000, + "arn:aws:lambda:us-east-1:000000000000:function:test", + new CompletableFuture<>()); + invocation.setResponseStreamListener(new ResponseStreamListener() { + @Override + public void onStart(String type) { + contentType.set(type); + } + + @Override + public void onChunk(byte[] chunk) { + chunks.add(new String(chunk, StandardCharsets.UTF_8)); + } + }); + return invocation; + } + + private void pollNext() throws Exception { + httpClient.send(HttpRequest.newBuilder() + .uri(URI.create("http://localhost:" + port + "/2018-06-01/runtime/invocation/next")) + .GET().build(), + HttpResponse.BodyHandlers.ofString()); + } + + private static String chunk(String data) { + return Integer.toHexString(data.getBytes(StandardCharsets.UTF_8).length) + "\r\n" + data + "\r\n"; + } + /** * Regression for #3314: the Python and Node.js runtime interface clients never send * {@code Lambda-Runtime-Function-Error-Type} on {@code /invocation/{id}/error} at all, so