fix(lambda): stream the body of a RESPONSE_STREAM function URL (#7885)

* fix(lambda): return the streamed body from a RESPONSE_STREAM function URL

A function URL in RESPONSE_STREAM mode parsed only the HttpResponseStream
prelude and dropped the body written after its eight NUL bytes, so callers got
the status and headers with an empty body. Split the stream at the delimiter
and return the rest as the body; a stream without a prelude is a 200
application/octet-stream, as on AWS. The stream is still buffered.

Closes #7837

* fix(lambda): stream the body of a RESPONSE_STREAM function URL as it is written

The runtime API now hands a streamed response to the invocation chunk by chunk,
ahead of the BodyHandler that buffers every other response, and completes the
invocation only when the stream ends, so the timeout, the concurrency permit
and the container stay held for the whole stream. The function URL answers as
soon as the head is known and writes each chunk as it arrives. The prelude is
read only when the stream's content type is
application/vnd.awslambda.http-integration-response; any other stream keeps
the content type the handler set.

* fix(lambda): check the streamed function URL response without timing it

The runtime API and controller tests pin chunk-by-chunk delivery, so the
end-to-end test only checks the status, content type and body.
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-11-10 11:54:40 -04:00
1 parent 8d95688eec
commit 65b09d0aac
11 files changed
+560 -16

No files matched your search

@@ -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();
}
}
@@ -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);
@@ -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<String> chunks = new CopyOnWriteArrayList<>();
AtomicReference<String> 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<String> 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<String> contentType,
List<String> 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