Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

perf: keep long polls, Invoke and function URL calls off the shared workers (#6576)

Jackson Price4ab43eeeab9e
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java
index a914b9d156..a5d0a9f19c 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.marketplace.MarketplaceEntitlementCon
import io.github.hectorvent.floci.services.sns.SnsJsonHandler;
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandler;
+import io.smallrye.common.annotation.RunOnVirtualThread;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
@@ -39,6 +40,9 @@ import java.util.zip.GZIPInputStream;
* <p>
* Currently supported services: DynamoDB (incl. Streams), SQS, SNS, Kinesis,
* Step Functions, and CloudWatch Metrics.
+ * <p>
+ * Requests run on virtual threads, as in {@link AwsJsonController}, so a ReceiveMessage or
+ * GetActivityTask long poll does not hold one of the shared request workers while it waits.
*/
@Path("/")
public class AwsJsonCborController {
@@ -292,6 +296,7 @@ public class AwsJsonCborController {
@Path("service/{serviceId}/operation/{operation}")
@Consumes({GENERIC_CBOR_MEDIA_TYPE, AWS_CBOR_1_1_MEDIA_TYPE})
@Produces({GENERIC_CBOR_MEDIA_TYPE, AWS_CBOR_1_1_MEDIA_TYPE})
+ @RunOnVirtualThread
public Response handleSmithyRpcV2Cbor(
@PathParam(RPC_V2_SERVICE_PARAMETER) String serviceId,
@PathParam(RPC_V2_OPERATION_PARAMETER) String operation,
@@ -384,6 +389,7 @@ public class AwsJsonCborController {
@POST
@Consumes({GENERIC_CBOR_MEDIA_TYPE, AWS_CBOR_1_1_MEDIA_TYPE})
@Produces({GENERIC_CBOR_MEDIA_TYPE, AWS_CBOR_1_1_MEDIA_TYPE})
+ @RunOnVirtualThread
public Response handleCborRequest(
@HeaderParam("X-Amz-Target") String target,
@Context HttpHeaders httpHeaders,
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java
index 03822340de..7445604edb 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java
@@ -20,6 +20,7 @@ import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandle
import io.github.hectorvent.floci.services.swf.SwfJsonHandler;
import io.github.hectorvent.floci.services.timestreaminfluxdb.TimestreamInfluxDbJsonHandler;
import io.github.hectorvent.floci.services.verifiedpermissions.VerifiedPermissionsJsonHandler;
+import io.smallrye.common.annotation.RunOnVirtualThread;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
@@ -34,6 +35,9 @@ import org.jboss.logging.Logger;
* Currently supported services:
* - DynamoDB (DynamoDB_20120810.*)
* - SQS (AmazonSQS.*)
+ * <p>
+ * Requests run on virtual threads: SQS ReceiveMessage and Step Functions GetActivityTask wait up
+ * to 20 and 60 seconds for work, and that wait must not hold one of the shared request workers.
*/
@Path("/")
public class AwsJsonController {
@@ -100,6 +104,7 @@ public class AwsJsonController {
@POST
@Consumes("application/json")
@Produces("application/json")
+ @RunOnVirtualThread
public Response handlePlainJsonRequest(
@HeaderParam("X-Amz-Target") String target,
@Context HttpHeaders httpHeaders,
@@ -118,6 +123,7 @@ public class AwsJsonController {
@POST
@Consumes(CONTENT_TYPE_AWS_JSON_1_0)
@Produces(CONTENT_TYPE_AWS_JSON_1_0)
+ @RunOnVirtualThread
public Response handleJsonRequest(
@HeaderParam("X-Amz-Target") String target,
@Context HttpHeaders httpHeaders,
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
index 2277b73355..f63fc90c4a 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
@@ -21,6 +21,7 @@ import io.github.hectorvent.floci.services.redshift.RedshiftQueryHandler;
import io.github.hectorvent.floci.services.ses.SesQueryHandler;
import io.github.hectorvent.floci.services.sns.SnsQueryHandler;
import io.github.hectorvent.floci.services.sqs.SqsQueryHandler;
+import io.smallrye.common.annotation.RunOnVirtualThread;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
@@ -49,6 +50,9 @@ import java.util.stream.Stream;
* Authorization header's credential scope. When there is no such header, or its scope names no
* service that speaks the Query protocol, the action name and the {@code Version} the request
* declares decide instead, as {@link #inferServiceFromAction} describes.
+ * <p>
+ * Requests run on virtual threads, so an SQS ReceiveMessage long poll, which waits up to 20 seconds,
+ * does not hold one of the shared request workers while it waits.
*
* @see AwsJsonController
*/
@@ -135,6 +139,7 @@ public class AwsQueryController {
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_XML)
+ @RunOnVirtualThread
public Response dispatch(
@HeaderParam("Authorization") String authorization,
@Context UriInfo uriInfo,
@@ -387,6 +392,7 @@ public class AwsQueryController {
@GET
@Path(QUERY_GET_PATH)
@Produces({MediaType.APPLICATION_XML, MediaType.TEXT_HTML})
+ @RunOnVirtualThread
public Response dispatchQueryGet(@HeaderParam("Authorization") String authorization,
@Context UriInfo uriInfo,
@Context ContainerRequestContext request) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
index f471b4e693..4b662d4c13 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.lambda.model.LambdaAlias;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.s3.PreSignedUrlGenerator;
+import io.smallrye.common.annotation.RunOnVirtualThread;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
@@ -239,9 +240,12 @@ public class LambdaController {
private static final int ASYNC_REQUEST_LIMIT = 1 * 1024 * 1024;
private static final int SYNC_RESPONSE_LIMIT = 6 * 1024 * 1024;
+ // A synchronous invocation waits for its function to finish; on a virtual thread that wait does
+ // not hold one of the shared request workers.
@POST
@Path("/functions/{functionName}/invocations")
@Consumes(MediaType.WILDCARD)
+ @RunOnVirtualThread
public Response invoke(@Context HttpHeaders headers,
@Context UriInfo uriInfo,
@PathParam("functionName") String functionName,
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaUrlInvocationController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaUrlInvocationController.java
index 68966a17c1..69986e2056 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaUrlInvocationController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaUrlInvocationController.java
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.lambda.model.LambdaAlias;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
+import io.smallrye.common.annotation.RunOnVirtualThread;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
@@ -44,10 +45,14 @@ import java.util.UUID;
*
* Supports host-based routing if possible, but also path-based routing:
* /lambda-url/{urlId}/{proxy: .*}
+ *
+ * Requests run on virtual threads: an invocation waits for its function to finish, and that wait
+ * must not hold one of the shared request workers.
*/
@Path("/lambda-url/{urlId}")
@Produces(MediaType.WILDCARD)
@Consumes(MediaType.WILDCARD)
+@RunOnVirtualThread
public class LambdaUrlInvocationController {
private static final Logger LOG = Logger.getLogger(LambdaUrlInvocationController.class);
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 91639a0c38..b20001e314 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -43,6 +43,12 @@ quarkus:
# Enables the pre-shutdown phase so stop hooks run before the HTTP server stops.
# No 'delay' value is set - observers run synchronously, no artificial sleep is introduced.
delay-enabled: true
+ virtual-threads:
+ # AWS JSON 1.0, CBOR, Query, Invoke and function URL requests run on virtual threads (see
+ # AwsJsonController), long polls among them. At shutdown, interrupt any still running after
+ # 10 s, the interval Quarkus uses for worker threads, instead of its default minute.
+ # Fixed at build time.
+ shutdown-timeout: 10s
index-dependency:
swagger-models-v2:
group-id: io.swagger
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AwsProtocolLongPollIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AwsProtocolLongPollIntegrationTest.java
new file mode 100644
index 0000000000..0e9d3a53fe
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/AwsProtocolLongPollIntegrationTest.java
@@ -0,0 +1,226 @@
+package io.github.hectorvent.floci.core.common;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
+import io.github.hectorvent.floci.services.sqs.SqsService;
+import io.github.hectorvent.floci.testing.FourWorkerThreadsProfile;
+import io.github.hectorvent.floci.testing.HeldWorkerProbes;
+import io.github.hectorvent.floci.testing.HeldWorkerProbes.Probe;
+import io.github.hectorvent.floci.testing.HeldWorkerProbes.Scope;
+import io.quarkus.test.common.http.TestHTTPResource;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import io.quarkus.test.junit.mockito.InjectSpy;
+import io.restassured.path.xml.XmlPath;
+import jakarta.inject.Inject;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.net.URI;
+import java.net.URLEncoder;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static io.github.hectorvent.floci.testing.HeldWorkerProbes.SCOPES;
+import static io.github.hectorvent.floci.testing.HeldWorkerProbes.served;
+import static io.github.hectorvent.floci.testing.HeldWorkerProbes.signed;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Mockito.doAnswer;
+
+/**
+ * A ReceiveMessage long poll waits without holding one of the shared request workers, on each of
+ * the five entry points SQS is served through: AWS JSON 1.0, Query POST and GET, and CBOR by
+ * X-Amz-Target and by Smithy RPC v2 path. The profile leaves four workers, and four receives that
+ * wait twenty seconds would otherwise queue every other request behind them, including the health
+ * check and SSM, which still run on the worker pool.
+ */
+@QuarkusTest
+@TestProfile(FourWorkerThreadsProfile.class)
+class AwsProtocolLongPollIntegrationTest {
+
+ private static final String JSON_1_0 = "application/x-amz-json-1.0";
+ private static final String CBOR_1_1 = "application/x-amz-cbor-1.1";
+ private static final ObjectMapper CBOR = new ObjectMapper(new CBORFactory());
+
+ @TestHTTPResource("/")
+ URI endpoint;
+
+ @InjectSpy
+ SqsService sqsService;
+
+ @Inject
+ RequestContext context;
+
+ @Inject
+ ObjectMapper mapper;
+
+ @ParameterizedTest
+ @ValueSource(strings = {"json", "query-post", "query-get", "cbor-target", "cbor-rpc"})
+ void waitingReceivesLeaveOtherRequestsServed(String protocol) throws Exception {
+ String prefix = "long-poll-" + UUID.randomUUID();
+ Map<Scope, String> queues = new LinkedHashMap<>();
+ Map<String, Scope> receiveScopes = new ConcurrentHashMap<>();
+ CountDownLatch receiving = new CountDownLatch(SCOPES.size());
+ try (HttpClient client = HttpClient.newHttpClient()) {
+ try {
+ for (Scope scope : SCOPES) {
+ HttpResponse<byte[]> created = served(sqs(client, scope, "query-post", "CreateQueue",
+ Map.of("QueueName", prefix + "-" + scope.identity())));
+ assertEquals(200, created.statusCode());
+ queues.put(scope, xml(created).getString("CreateQueueResponse.CreateQueueResult.QueueUrl"));
+ }
+ doAnswer(call -> {
+ Scope current = new Scope(context.getAccountId(), context.getRegion());
+ if (receiveScopes.putIfAbsent(call.getArgument(0), current) == null) {
+ receiving.countDown();
+ }
+ return call.callRealMethod();
+ }).when(sqsService).receiveMessage(anyString(), anyInt(), anyInt(), nullable(Integer.class),
+ anyString());
+
+ List<CompletableFuture<HttpResponse<byte[]>>> receives = new ArrayList<>();
+ for (Scope scope : SCOPES) {
+ receives.add(sqs(client, scope, protocol, "ReceiveMessage",
+ Map.of("QueueUrl", queues.get(scope), "WaitTimeSeconds", HeldWorkerProbes.HOLD_SECONDS)));
+ }
+ assertTrue(receiving.await(HeldWorkerProbes.ARRIVAL_SECONDS, TimeUnit.SECONDS),
+ "every receive reaches SqsService");
+ for (Scope scope : SCOPES) {
+ assertEquals(scope, receiveScopes.get(queues.get(scope)),
+ "a receive runs in the account and Region it was signed for");
+ }
+
+ List<Probe> probes = new ArrayList<>(HeldWorkerProbes.sharedProbes(client, endpoint));
+ for (Scope scope : SCOPES) {
+ probes.add(new Probe("ListQueues as " + scope.identity(), sqs(client, scope, protocol,
+ "ListQueues", Map.of("QueueNamePrefix", prefix)), listed -> {
+ assertEquals(200, listed.statusCode());
+ assertEquals(List.of(queues.get(scope)), queueUrls(listed, protocol));
+ assertProtocolHeaders(listed, protocol);
+ }));
+ }
+ probes.add(new Probe("ReceiveMessage with WaitTimeSeconds 21", sqs(client, SCOPES.getFirst(), protocol,
+ "ReceiveMessage", Map.of("QueueUrl", queues.get(SCOPES.getFirst()), "WaitTimeSeconds", 21)),
+ invalid -> {
+ assertEquals(400, invalid.statusCode());
+ assertEquals("InvalidParameterValue", errorCode(invalid, protocol));
+ }));
+ HeldWorkerProbes.assertServed(probes);
+ for (CompletableFuture<HttpResponse<byte[]>> receive : receives) {
+ assertFalse(receive.isDone(), "the receives are still waiting for a message");
+ }
+
+ for (int i = 0; i < SCOPES.size(); i++) {
+ Scope scope = SCOPES.get(i);
+ RequestScopes.runAs(scope.account(), scope.region(),
+ () -> sqsService.sendMessage(queues.get(scope), scope.identity(), 0, scope.region()));
+ HttpResponse<byte[]> delivered = receives.get(i).get(10, TimeUnit.SECONDS);
+ assertEquals(200, delivered.statusCode());
+ assertEquals(List.of(scope.identity()), messageBodies(delivered, protocol));
+ }
+ } finally {
+ // Deleting a queue also ends a receive still waiting on it.
+ for (Map.Entry<Scope, String> queue : queues.entrySet()) {
+ Scope scope = queue.getKey();
+ RequestScopes.runAs(scope.account(), scope.region(),
+ () -> sqsService.deleteQueue(queue.getValue(), scope.region()));
+ }
+ }
+ }
+ }
+
+ private CompletableFuture<HttpResponse<byte[]>> sqs(HttpClient client, Scope scope, String protocol,
+ String action, Map<String, Object> parameters)
+ throws Exception {
+ if (protocol.startsWith("query")) {
+ Map<String, Object> query = new LinkedHashMap<>(parameters);
+ query.put("Action", action);
+ query.put("Version", "2012-11-05");
+ List<String> pairs = new ArrayList<>();
+ query.forEach((key, value) -> pairs.add(URLEncoder.encode(key, StandardCharsets.UTF_8)
+ + "=" + URLEncoder.encode(value.toString(), StandardCharsets.UTF_8)));
+ String encoded = String.join("&", pairs);
+ HttpRequest.Builder request = "query-get".equals(protocol)
+ ? signed(URI.create(endpoint + "?" + encoded), scope, "sqs").GET()
+ : signed(endpoint, scope, "sqs")
+ .header("Content-Type", "application/x-www-form-urlencoded")
+ .POST(HttpRequest.BodyPublishers.ofString(encoded));
+ return client.sendAsync(request.build(), HttpResponse.BodyHandlers.ofByteArray());
+ }
+ if ("json".equals(protocol)) {
+ return client.sendAsync(signed(endpoint, scope, "sqs")
+ .header("Content-Type", JSON_1_0)
+ .header("X-Amz-Target", "AmazonSQS." + action)
+ .POST(HttpRequest.BodyPublishers.ofByteArray(mapper.writeValueAsBytes(parameters)))
+ .build(), HttpResponse.BodyHandlers.ofByteArray());
+ }
+ HttpRequest.Builder request = "cbor-rpc".equals(protocol)
+ ? signed(endpoint.resolve("service/SQS/operation/" + action), scope, "sqs")
+ .header("smithy-protocol", "rpc-v2-cbor")
+ : signed(endpoint, scope, "sqs").header("X-Amz-Target", "AmazonSQS." + action);
+ return client.sendAsync(request
+ .header("Content-Type", CBOR_1_1)
+ .POST(HttpRequest.BodyPublishers.ofByteArray(CBOR.writeValueAsBytes(parameters)))
+ .build(), HttpResponse.BodyHandlers.ofByteArray());
+ }
+
+ private List<String> queueUrls(HttpResponse<byte[]> response, String protocol) throws Exception {
+ if (protocol.startsWith("query")) {
+ return xml(response).getList("ListQueuesResponse.ListQueuesResult.QueueUrl", String.class);
+ }
+ List<String> urls = new ArrayList<>();
+ tree(response, protocol).path("QueueUrls").forEach(url -> urls.add(url.asText()));
+ return urls;
+ }
+
+ private List<String> messageBodies(HttpResponse<byte[]> response, String protocol) throws Exception {
+ if (protocol.startsWith("query")) {
+ return xml(response).getList("ReceiveMessageResponse.ReceiveMessageResult.Message.Body", String.class);
+ }
+ List<String> bodies = new ArrayList<>();
+ tree(response, protocol).path("Messages").forEach(message -> bodies.add(message.path("Body").asText()));
+ return bodies;
+ }
+
+ private String errorCode(HttpResponse<byte[]> response, String protocol) throws Exception {
+ if (protocol.startsWith("query")) {
+ return xml(response).getString("ErrorResponse.Error.Code");
+ }
+ return tree(response, protocol).path("__type").asText();
+ }
+
+ private static void assertProtocolHeaders(HttpResponse<byte[]> response, String protocol) {
+ if (protocol.startsWith("query")) {
+ assertTrue(response.headers().firstValue("Content-Type").orElseThrow().startsWith("application/xml"));
+ } else if (protocol.startsWith("cbor")) {
+ assertEquals("rpc-v2-cbor", response.headers().firstValue("smithy-protocol").orElseThrow());
+ } else {
+ assertTrue(response.headers().firstValue("Content-Type").orElseThrow().startsWith(JSON_1_0));
+ }
+ }
+
+ private JsonNode tree(HttpResponse<byte[]> response, String protocol) throws Exception {
+ return ("json".equals(protocol) ? mapper : CBOR).readTree(response.body());
+ }
+
+ private static XmlPath xml(HttpResponse<byte[]> response) {
+ return new XmlPath(new String(response.body(), StandardCharsets.UTF_8));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaSynchronousInvokeDispatchIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaSynchronousInvokeDispatchIntegrationTest.java
new file mode 100644
index 0000000000..546ab78e83
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaSynchronousInvokeDispatchIntegrationTest.java
@@ -0,0 +1,196 @@
+package io.github.hectorvent.floci.services.lambda;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.RequestContext;
+import io.github.hectorvent.floci.services.lambda.model.InvocationType;
+import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
+import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
+import io.github.hectorvent.floci.testing.FourWorkerThreadsProfile;
+import io.github.hectorvent.floci.testing.HeldWorkerProbes;
+import io.github.hectorvent.floci.testing.HeldWorkerProbes.Probe;
+import io.github.hectorvent.floci.testing.HeldWorkerProbes.Scope;
+import io.quarkus.test.InjectMock;
+import io.quarkus.test.common.http.TestHTTPResource;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import jakarta.inject.Inject;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+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.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static io.github.hectorvent.floci.testing.HeldWorkerProbes.SCOPES;
+import static io.github.hectorvent.floci.testing.HeldWorkerProbes.signed;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.when;
+
+/**
+ * A synchronous Invoke or function URL request waits for its function without holding one of the
+ * shared request workers. The profile leaves four workers, and four invocations held at the service
+ * boundary would otherwise queue every request that still needs a worker, such as the health check
+ * and SSM, behind them. The service is mocked, so the test exercises the REST dispatch and its
+ * request scope, not a runtime.
+ */
+@QuarkusTest
+@TestProfile(FourWorkerThreadsProfile.class)
+class LambdaSynchronousInvokeDispatchIntegrationTest {
+
+ @TestHTTPResource("/")
+ URI endpoint;
+
+ @InjectMock
+ LambdaService lambdaService;
+
+ @Inject
+ RequestContext context;
+
+ @Inject
+ ObjectMapper mapper;
+
+ @ParameterizedTest
+ @ValueSource(strings = {"Invoke", "GET", "POST", "PUT", "DELETE", "PATCH"})
+ void heldInvocationsLeaveOtherRequestsServed(String route) throws Exception {
+ boolean invoke = "Invoke".equals(route);
+ CountDownLatch invoking = new CountDownLatch(SCOPES.size());
+ Map<String, Held> held = new ConcurrentHashMap<>();
+ Map<String, CompletableFuture<InvokeResult>> releases = new ConcurrentHashMap<>();
+ for (Scope scope : SCOPES) {
+ releases.put(target(scope, invoke), new CompletableFuture<>());
+ }
+ // An unknown URL id gets null, which the controller answers with a 404 the await below reports.
+ when(lambdaService.getTargetByUrlId(anyString())).thenAnswer(call -> SCOPES.stream()
+ .filter(candidate -> candidate.identity().equals(call.getArgument(0)))
+ .findFirst()
+ .map(LambdaSynchronousInvokeDispatchIntegrationTest::function)
+ .orElse(null));
+ // Each answer only records what it saw and waits for its own release; the checks run on the
+ // test thread, so a mismatch fails there with its own message instead of a 500 to the client.
+ doAnswer(call -> hold(call.getArgument(1), call.getArgument(4), held, invoking, releases))
+ .when(lambdaService).invoke(anyString(), anyString(), any(), any(), any(), any(), any());
+ doAnswer(call -> hold(call.getArgument(0), call.getArgument(2), held, invoking, releases))
+ .when(lambdaService).invokeArn(anyString(), any(), any());
+
+ List<CompletableFuture<HttpResponse<String>>> invocations = new ArrayList<>();
+ try (HttpClient client = HttpClient.newHttpClient()) {
+ try {
+ for (Scope scope : SCOPES) {
+ String path = invoke
+ ? "2015-03-31/functions/" + functionName(scope) + "/invocations"
+ : "lambda-url/" + scope.identity() + "/check";
+ invocations.add(client.sendAsync(signed(endpoint.resolve(path), scope, "lambda")
+ .header("Content-Type", "application/json")
+ .method(invoke ? "POST" : route, HttpRequest.BodyPublishers.ofString("{}"))
+ .build(), HttpResponse.BodyHandlers.ofString()));
+ }
+ assertTrue(invoking.await(HeldWorkerProbes.ARRIVAL_SECONDS, TimeUnit.SECONDS),
+ () -> "every invocation reaches LambdaService; answered without it: " + answered(invocations));
+ assertEquals(releases.keySet(), held.keySet(), "each function is invoked once, by its own target");
+ for (Scope scope : SCOPES) {
+ Held invocation = held.get(target(scope, invoke));
+ assertEquals(InvocationType.RequestResponse, invocation.type());
+ assertEquals(scope, invocation.scope(), "an invocation runs in the account and Region of its function");
+ }
+
+ // The health check and SSM need a worker; DynamoDB and EC2 run on virtual threads.
+ List<Probe> probes = new ArrayList<>(HeldWorkerProbes.sharedProbes(client, endpoint));
+ probes.add(HeldWorkerProbes.probe("DynamoDB ListTables", client,
+ signed(endpoint, SCOPES.getFirst(), "dynamodb")
+ .header("Content-Type", "application/x-amz-json-1.0")
+ .header("X-Amz-Target", "DynamoDB_20120810.ListTables")
+ .POST(HttpRequest.BodyPublishers.ofString("{}"))
+ .build(), tables -> {
+ assertEquals(200, tables.statusCode());
+ assertTrue(mapper.readTree(tables.body()).path("TableNames").isArray());
+ }));
+ HeldWorkerProbes.assertServed(probes);
+ for (CompletableFuture<HttpResponse<String>> invocation : invocations) {
+ assertFalse(invocation.isDone(), "the invocations are still waiting for their functions");
+ }
+
+ for (int i = 0; i < SCOPES.size(); i++) {
+ Scope scope = SCOPES.get(i);
+ InvokeResult result = new InvokeResult(200, null, ("{\"statusCode\":201,\"body\":\""
+ + scope.identity() + "\"}").getBytes(StandardCharsets.UTF_8), null, "req-" + i);
+ result.setExecutedVersion("1");
+ releases.get(target(scope, invoke)).complete(result);
+ HttpResponse<String> response = invocations.get(i).get(10, TimeUnit.SECONDS);
+ if (invoke) {
+ assertEquals(200, response.statusCode());
+ assertEquals("1", response.headers().firstValue("X-Amz-Executed-Version").orElseThrow());
+ assertEquals(scope.identity(), mapper.readTree(response.body()).path("body").asText());
+ } else {
+ assertEquals(201, response.statusCode());
+ assertEquals(scope.identity(), response.body());
+ }
+ }
+ } finally {
+ for (CompletableFuture<InvokeResult> release : releases.values()) {
+ release.complete(new InvokeResult(200, null, null, null, "released"));
+ }
+ }
+ }
+ }
+
+ private InvokeResult hold(String target, InvocationType type, Map<String, Held> held,
+ CountDownLatch invoking, Map<String, CompletableFuture<InvokeResult>> releases)
+ throws Exception {
+ held.put(target, new Held(type, new Scope(context.getAccountId(), context.getRegion())));
+ invoking.countDown();
+ CompletableFuture<InvokeResult> release = releases.get(target);
+ return release == null ? new InvokeResult(200, null, null, null, "unexpected")
+ : release.get(HeldWorkerProbes.HOLD_SECONDS, TimeUnit.SECONDS);
+ }
+
+ private static LambdaFunction function(Scope scope) {
+ LambdaFunction function = new LambdaFunction();
+ function.setFunctionName(functionName(scope));
+ function.setFunctionArn(functionArn(scope));
+ function.setAccountId(scope.account());
+ return function;
+ }
+
+ /** The status and body of each request that was answered while it should have been waiting. */
+ private static List<String> answered(List<CompletableFuture<HttpResponse<String>>> invocations) {
+ List<String> answers = new ArrayList<>();
+ for (CompletableFuture<HttpResponse<String>> invocation : invocations) {
+ HttpResponse<String> response = invocation.getNow(null);
+ if (response != null) {
+ answers.add(response.statusCode() + " " + response.body());
+ }
+ }
+ return answers;
+ }
+
+ /** What a held invocation saw: how it was invoked and the account and Region it ran in. */
+ private record Held(InvocationType type, Scope scope) {
+ }
+
+ private static String functionName(Scope scope) {
+ return "held-" + scope.identity();
+ }
+
+ private static String functionArn(Scope scope) {
+ return "arn:aws:lambda:" + scope.region() + ":" + scope.account() + ":function:" + functionName(scope);
+ }
+
+ /** What LambdaService receives: the name from Invoke, the ARN from a function URL. */
+ private static String target(Scope scope, boolean invoke) {
+ return invoke ? functionName(scope) : functionArn(scope);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/testing/FourWorkerThreadsProfile.java b/src/test/java/io/github/hectorvent/floci/testing/FourWorkerThreadsProfile.java
new file mode 100644
index 0000000000..dd816b28a1
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/testing/FourWorkerThreadsProfile.java
@@ -0,0 +1,23 @@
+package io.github.hectorvent.floci.testing;
+
+import io.quarkus.test.junit.QuarkusTestProfile;
+
+import java.util.Map;
+
+/**
+ * Shrinks the shared request worker pool to four threads, and changes nothing else, so a test can
+ * occupy every worker with four held requests and check what else is still served. Quarkus builds
+ * the application once per distinct profile class, so the classes that need only this override
+ * share this one rather than each declaring an identical nested profile.
+ */
+public class FourWorkerThreadsProfile implements QuarkusTestProfile {
+
+ /** The worker pool size this profile configures. */
+ public static final int WORKER_THREADS = 4;
+
+ @Override
+ public Map<String, String> getConfigOverrides() {
+ return Map.of("quarkus.thread-pool.core-threads", String.valueOf(WORKER_THREADS),
+ "quarkus.thread-pool.max-threads", String.valueOf(WORKER_THREADS));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/testing/HeldWorkerProbes.java b/src/test/java/io/github/hectorvent/floci/testing/HeldWorkerProbes.java
new file mode 100644
index 0000000000..a8f43de35f
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/testing/HeldWorkerProbes.java
@@ -0,0 +1,157 @@
+package io.github.hectorvent.floci.testing;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+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.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * The shared part of the tests that hold one request per worker of {@link FourWorkerThreadsProfile}
+ * and check what is still served: the account and Region of each held request, the signing, and
+ * the probes sent while the requests are held.
+ *
+ * <p>Probes are sent together and share one deadline, {@link #PROBE_DEADLINE_SECONDS}. A held
+ * request waits {@link #HOLD_SECONDS} and the tests allow {@link #ARRIVAL_SECONDS} for all of them to
+ * reach the service, so {@link #assertServed} fails before any held request is released.
+ */
+public final class HeldWorkerProbes {
+
+ /** One held request per worker, each in its own account and Region. */
+ public static final List<Scope> SCOPES = List.of(
+ new Scope("111122223333", "us-east-1"),
+ new Scope("111122223333", "us-west-2"),
+ new Scope("444455556666", "us-east-1"),
+ new Scope("444455556666", "us-west-2"));
+
+ /** How long a held request waits before it is answered on its own. */
+ public static final int HOLD_SECONDS = 20;
+
+ /** How long the tests wait for every held request to reach the service. */
+ public static final long ARRIVAL_SECONDS = 10;
+
+ /** How long all probes together may take, which is what a held worker pool would exceed. */
+ public static final long PROBE_DEADLINE_SECONDS = 5;
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ static {
+ if (SCOPES.size() != FourWorkerThreadsProfile.WORKER_THREADS) {
+ throw new IllegalStateException("one scope per worker thread: " + SCOPES.size() + " scopes, "
+ + FourWorkerThreadsProfile.WORKER_THREADS + " workers");
+ }
+ if (ARRIVAL_SECONDS + PROBE_DEADLINE_SECONDS >= HOLD_SECONDS) {
+ throw new IllegalStateException("the probes must finish before a held request is released");
+ }
+ }
+
+ private HeldWorkerProbes() {}
+
+ /** The account and Region a held request is signed for. */
+ public record Scope(String account, String region) {
+ public String identity() {
+ return account + "-" + region;
+ }
+ }
+
+ /** Checks a probe's response once it has been answered. */
+ @FunctionalInterface
+ public interface ResponseCheck {
+ void check(HttpResponse<byte[]> response) throws Exception;
+ }
+
+ /** A request sent while the held requests wait, and what its answer must look like. */
+ public record Probe(String name, CompletableFuture<HttpResponse<byte[]>> response, ResponseCheck check) {
+ }
+
+ /** A request builder carrying a placeholder SigV4 header for {@code scope} and {@code service}. */
+ public static HttpRequest.Builder signed(URI uri, Scope scope, String service) {
+ return HttpRequest.newBuilder(uri)
+ .header("Authorization", EnforcementFixtures.auth(scope.account(), scope.region(), service));
+ }
+
+ /** Sends {@code request} now; its answer is checked by {@link #assertServed}. */
+ public static Probe probe(String name, HttpClient client, HttpRequest request, ResponseCheck check) {
+ return new Probe(name, client.sendAsync(request, HttpResponse.BodyHandlers.ofByteArray()), check);
+ }
+
+ /**
+ * Sends the probes every held-worker test shares, answered here only while a worker is free or
+ * the request runs on a virtual thread: the health check and SSM, which still need a worker, and
+ * EC2 DescribeRegions on the Query entry point.
+ */
+ public static List<Probe> sharedProbes(HttpClient client, URI endpoint) {
+ Scope scope = SCOPES.getFirst();
+ return List.of(
+ probe("GET /health", client, HttpRequest.newBuilder(endpoint.resolve("health")).GET().build(),
+ response -> {
+ assertEquals(200, response.statusCode());
+ assertEquals("community", MAPPER.readTree(response.body()).path("edition").asText());
+ }),
+ probe("SSM DescribeParameters", client, signed(endpoint, scope, "ssm")
+ .header("Content-Type", "application/x-amz-json-1.1")
+ .header("X-Amz-Target", "AmazonSSM.DescribeParameters")
+ .POST(HttpRequest.BodyPublishers.ofString("{}"))
+ .build(), response -> {
+ assertEquals(200, response.statusCode());
+ assertTrue(MAPPER.readTree(response.body()).path("Parameters").isArray());
+ }),
+ probe("EC2 DescribeRegions", client, signed(endpoint, scope, "ec2")
+ .header("Content-Type", "application/x-www-form-urlencoded")
+ .POST(HttpRequest.BodyPublishers.ofString("Action=DescribeRegions&Version=2016-11-15"))
+ .build(), response -> {
+ assertEquals(200, response.statusCode());
+ assertTrue(new String(response.body(), StandardCharsets.UTF_8)
+ .contains("<DescribeRegionsResponse"));
+ }));
+ }
+
+ /**
+ * Fails unless every probe is answered within {@link #PROBE_DEADLINE_SECONDS} of this call, then
+ * runs each probe's check. The probes are already in flight, so they wait concurrently.
+ */
+ public static void assertServed(List<Probe> probes) throws Exception {
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(PROBE_DEADLINE_SECONDS);
+ List<String> unanswered = new ArrayList<>();
+ for (Probe probe : probes) {
+ try {
+ probe.response().get(Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS);
+ } catch (TimeoutException e) {
+ unanswered.add(probe.name());
+ } catch (ExecutionException e) {
+ fail(probe.name() + " failed: " + e.getCause(), e.getCause());
+ }
+ }
+ if (!unanswered.isEmpty()) {
+ fail("not answered within " + PROBE_DEADLINE_SECONDS + " s while the requests are held: " + unanswered);
+ }
+ for (Probe probe : probes) {
+ try {
+ probe.check().check(probe.response().join());
+ } catch (AssertionError e) {
+ throw new AssertionError(probe.name() + ": " + e.getMessage(), e);
+ } catch (Exception e) {
+ fail(probe.name() + ": " + e, e);
+ }
+ }
+ }
+
+ /** Waits for one request outside the held phase, failing when it is not answered in time. */
+ public static <T> HttpResponse<T> served(CompletableFuture<HttpResponse<T>> request) {
+ return assertDoesNotThrow(() -> request.get(PROBE_DEADLINE_SECONDS, TimeUnit.SECONDS),
+ "a request is answered within " + PROBE_DEADLINE_SECONDS + " s");
+ }
+}