mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
d7e46525eb
commit
f094103b31
23 files changed
+1332
-36
No files matched your search
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String> 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<String> 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<InvokeResult> invocation) {
|
||||
if (started.isDone()) {
|
||||
return started.join();
|
||||
}
|
||||
return invocation.join().isTimedOut() ? OCTET_STREAM : JSON;
|
||||
}
|
||||
|
||||
GenericEntity<StreamingOutput> body(CompletableFuture<InvokeResult> 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<InvokeResult> 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<String, String> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String> LOG_TYPES = List.of("Tail", "None");
|
||||
private static final List<String> 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<InvokeResult> 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<String> 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<String> violations, String value, String field, List<String> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<String> invokeQualifierViolations(String qualifier) {
|
||||
List<String> 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) {
|
||||
|
||||
@@ -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> head = new CompletableFuture<>();
|
||||
private final BlockingQueue<byte[]> 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> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<byte[]> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
}
|
||||
@@ -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<HttpHeaders> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
Reference in new issue
Block a user