feat(lambda): add InvokeWithResponseStream (#8964)

* feat(lambda): add InvokeWithResponseStream
* feat(lambda): report a streaming handler's error in InvokeComplete
* fix(lambda): send response stream chunks while the function runs
* fix(lambda): build Invoke qualifier violations with the shared helpers
* test(lambda): exit the streaming handler from the write callback
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-19 11:10:09 -04:00
1 parent d7e46525eb
commit f094103b31
23 files changed
+1332 -36

No files matched your search

@@ -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<Message> 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<Message> 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<Message> 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<Message> 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<Message> 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<Message> 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<Message> 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<Message> 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<Message> 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<Message> 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<Message> 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<Message> 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<Message> 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<Message> 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<Message> 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<Message> 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<InvokeResult> 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<Void> 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<Message> decoded(ByteArrayOutputStream out) {
return EventStreamMessages.decode(out.toByteArray());
}
private List<Message> 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<String> types(List<Message> messages) {
return messages.stream().map(Message::type).toList();
}
private static CompletableFuture<InvokeResult> done(InvokeResult result) {
return CompletableFuture.completedFuture(result);
}
}
@@ -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<Message> 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<Message> 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<Message> 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<Message> messages = EventStreamMessages.decode(invoke(STREAMING, "{\"mode\":\"throwBefore\"}", "").asByteArray());
assertEquals(1, messages.size());
assertErrorComplete(messages.get(0), "boom before");
}
@Test
void errorAfterAWriteKeepsTheChunkAndIsReported() {
List<Message> 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<Message> 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<Message> 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<Message> 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);
}
}
@@ -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<String> 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<String> 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<String> firstFailures = new CopyOnWriteArrayList<>();
List<String> 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<String> 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<String> 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<String> contentType,
List<String> chunks) {
PendingInvocation invocation = new PendingInvocation(
@@ -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;
@@ -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;
@@ -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<String, String> headers, byte[] payload) {
public record Message(Map<String, String> 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<Message> decode(byte[] stream) {
public static List<Message> decode(byte[] stream) {
List<Message> messages = new ArrayList<>();
int offset = 0;
try {