mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(lambda): share the stream OnFailure delivery and send it in the destination's account (#6224)
* fix(lambda): share the stream OnFailure delivery and send it in the destination's account * fix(lambda): log the cause when an OnFailure send fails * fix(lambda): write the stream record arrival times in the source's precision * refactor(lambda): reuse the invocation record timestamp formatter
This commit is contained in:
1 parent
05a0639e29
commit
b0a4d5064b
7 files changed
+640
-241
No files matched your search
+11
-22
@@ -49,7 +49,6 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
@@ -145,7 +144,11 @@ class DynamoDbStreamsEventSourcePollerTest {
|
||||
private DynamoDbStreamsEventSourcePoller pollerOver(DynamoDbStreamReader streamReader, EsmStore store) {
|
||||
return new DynamoDbStreamsEventSourcePoller(
|
||||
mock(Vertx.class), streamReader, executorService, new LambdaTargetResolver(functionStore, aliasStore),
|
||||
store, OBJECT_MAPPER, config, filterMatcher, sqsService, snsService, s3Service, clock::get);
|
||||
store, OBJECT_MAPPER, config, filterMatcher, batchFailures(), clock::get);
|
||||
}
|
||||
|
||||
private StreamBatchFailures batchFailures() {
|
||||
return new StreamBatchFailures(sqsService, snsService, s3Service, OBJECT_MAPPER, config);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -243,7 +246,7 @@ class DynamoDbStreamsEventSourcePollerTest {
|
||||
Vertx vertx = mock(Vertx.class);
|
||||
DynamoDbStreamsEventSourcePoller p = new DynamoDbStreamsEventSourcePoller(
|
||||
vertx, reader, executorService, new LambdaTargetResolver(functionStore, aliasStore),
|
||||
esmStore, OBJECT_MAPPER, config, filterMatcher, sqsService, snsService, s3Service, clock::get);
|
||||
esmStore, OBJECT_MAPPER, config, filterMatcher, batchFailures(), clock::get);
|
||||
|
||||
p.startPersistedPollers();
|
||||
|
||||
@@ -988,17 +991,6 @@ class DynamoDbStreamsEventSourcePollerTest {
|
||||
S3Service s3Service, AccountAwareStorageBackend<S3Object> objects) {
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3OnFailureKeyUsesUtcLayout() {
|
||||
UUID randomId = UUID.fromString("12345678-1234-1234-1234-123456789abc");
|
||||
|
||||
String key = DynamoDbStreamsEventSourcePoller.buildS3OnFailureKey(
|
||||
"esm-1", "shard-1", Instant.parse("2026-09-14T23:07:08Z"), randomId);
|
||||
|
||||
assertEquals("aws/lambda/esm-1/shard-1/2026/09/14/"
|
||||
+ "2026-09-14T23.07.08-12345678-1234-1234-1234-123456789abc", key);
|
||||
}
|
||||
|
||||
@Test
|
||||
void onFailurePayloadUsesEpochSecondsNotMillisForArrivalTimestamps() throws Exception {
|
||||
// Chosen so the seconds/millis interpretations land 46+ years apart: a millis bug cannot
|
||||
@@ -1029,13 +1021,10 @@ class DynamoDbStreamsEventSourcePollerTest {
|
||||
ArgumentCaptor<String> bodyCaptor = ArgumentCaptor.forClass(String.class);
|
||||
verify(sqsService, timeout(2000)).sendMessage(anyString(), bodyCaptor.capture(), anyInt(), anyString());
|
||||
|
||||
JsonNode dlqPayload = OBJECT_MAPPER.readTree(bodyCaptor.getValue());
|
||||
Instant first = Instant.parse(
|
||||
dlqPayload.path("DDBStreamBatchInfo").path("approximateArrivalOfFirstRecord").asText());
|
||||
Instant last = Instant.parse(
|
||||
dlqPayload.path("DDBStreamBatchInfo").path("approximateArrivalOfLastRecord").asText());
|
||||
assertEquals(knownEpochSeconds, first.getEpochSecond());
|
||||
assertEquals(knownEpochSeconds, last.getEpochSecond());
|
||||
// 1_700_000_000 epoch seconds, written in whole seconds as in the AWS DynamoDB Streams example.
|
||||
JsonNode batchInfo = OBJECT_MAPPER.readTree(bodyCaptor.getValue()).path("DDBStreamBatchInfo");
|
||||
assertEquals("2023-11-14T22:13:20Z", batchInfo.path("approximateArrivalOfFirstRecord").asText());
|
||||
assertEquals("2023-11-14T22:13:20Z", batchInfo.path("approximateArrivalOfLastRecord").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1323,7 +1312,7 @@ class DynamoDbStreamsEventSourcePollerTest {
|
||||
void retryBackoffDoublesFromThePollIntervalAndCapsOut() {
|
||||
assertEquals(2_000, poller.retryBackoffMs(1));
|
||||
assertEquals(4_000, poller.retryBackoffMs(2));
|
||||
assertEquals(DynamoDbStreamsEventSourcePoller.MAX_RETRY_BACKOFF_MS, poller.retryBackoffMs(20));
|
||||
assertEquals(StreamBatchFailures.MAX_RETRY_BACKOFF_MS, poller.retryBackoffMs(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+11
-44
@@ -1,12 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.sqs.model.Message;
|
||||
import io.github.hectorvent.floci.services.sqs.model.Queue;
|
||||
import io.github.hectorvent.floci.testing.SqsTestQueue;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
@@ -17,8 +14,6 @@ import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
@@ -26,7 +21,6 @@ import java.util.zip.ZipOutputStream;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* Runs a real failing function to prove the asynchronous retries wait as they do on AWS (scaled down by
|
||||
@@ -41,7 +35,6 @@ class LambdaAsyncRetryDockerIntegrationTest {
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String ROLE = "arn:aws:iam::" + ACCOUNT + ":role/lambda-role";
|
||||
private static final Duration RECEIVE_DEADLINE = Duration.ofSeconds(60);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
@@ -68,7 +61,7 @@ class LambdaAsyncRetryDockerIntegrationTest {
|
||||
.then()
|
||||
.statusCode(202);
|
||||
|
||||
JsonNode record = awaitRecord(fixture.aliasQueueUrl());
|
||||
JsonNode record = fixture.aliasQueue().awaitJson(RECEIVE_DEADLINE);
|
||||
long elapsedMillis = Duration.ofNanos(System.nanoTime() - started).toMillis();
|
||||
|
||||
assertTrue(elapsedMillis >= 3000,
|
||||
@@ -79,7 +72,7 @@ class LambdaAsyncRetryDockerIntegrationTest {
|
||||
assertTrue(functionArn.endsWith(":1"), "functionArn should name the executed version: " + functionArn);
|
||||
assertEquals("1", record.path("responseContext").path("executedVersion").asText());
|
||||
assertEquals("alias", record.path("requestPayload").path("probe").asText());
|
||||
assertTrue(receiveOnce(fixture.latestQueueUrl()).isEmpty(),
|
||||
assertTrue(fixture.latestQueue().receive().isEmpty(),
|
||||
"the unqualified OnFailure destination should receive nothing");
|
||||
} finally {
|
||||
deleteFunction(fixture.functionName());
|
||||
@@ -98,12 +91,12 @@ class LambdaAsyncRetryDockerIntegrationTest {
|
||||
.then()
|
||||
.statusCode(202);
|
||||
|
||||
JsonNode record = awaitRecord(fixture.latestQueueUrl());
|
||||
JsonNode record = fixture.latestQueue().awaitJson(RECEIVE_DEADLINE);
|
||||
|
||||
assertEquals("RetriesExhausted", record.path("requestContext").path("condition").asText());
|
||||
assertEquals(1, record.path("requestContext").path("approximateInvokeCount").asInt());
|
||||
assertEquals("latest", record.path("requestPayload").path("probe").asText());
|
||||
assertTrue(receiveOnce(fixture.aliasQueueUrl()).isEmpty(),
|
||||
assertTrue(fixture.aliasQueue().receive().isEmpty(),
|
||||
"the alias OnFailure destination should receive nothing");
|
||||
} finally {
|
||||
deleteFunction(fixture.functionName());
|
||||
@@ -113,8 +106,8 @@ class LambdaAsyncRetryDockerIntegrationTest {
|
||||
private Fixture setUp() throws Exception {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String functionName = "async-retry-" + suffix;
|
||||
String latestQueueUrl = createQueue("async-retry-latest-" + suffix);
|
||||
String aliasQueueUrl = createQueue("async-retry-alias-" + suffix);
|
||||
SqsTestQueue latestQueue = SqsTestQueue.create(sqsService, ACCOUNT, REGION, "async-retry-latest-");
|
||||
SqsTestQueue aliasQueue = SqsTestQueue.create(sqsService, ACCOUNT, REGION, "async-retry-alias-");
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
@@ -152,7 +145,7 @@ class LambdaAsyncRetryDockerIntegrationTest {
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("{\"MaximumRetryAttempts\":0,\"DestinationConfig\":{\"OnFailure\":{\"Destination\":\"%s\"}}}"
|
||||
.formatted(queueArn(latestQueueUrl)))
|
||||
.formatted(latestQueue.arn()))
|
||||
.when()
|
||||
.put(CONFIG_PATH + "/functions/" + functionName + "/event-invoke-config")
|
||||
.then()
|
||||
@@ -161,39 +154,13 @@ class LambdaAsyncRetryDockerIntegrationTest {
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("{\"MaximumRetryAttempts\":2,\"DestinationConfig\":{\"OnFailure\":{\"Destination\":\"%s\"}}}"
|
||||
.formatted(queueArn(aliasQueueUrl)))
|
||||
.formatted(aliasQueue.arn()))
|
||||
.when()
|
||||
.put(CONFIG_PATH + "/functions/" + functionName + "/event-invoke-config?Qualifier=live")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
return new Fixture(functionName, latestQueueUrl, aliasQueueUrl);
|
||||
}
|
||||
|
||||
private String createQueue(String queueName) {
|
||||
Queue queue = RequestScopes.callAs(ACCOUNT, () -> sqsService.createQueue(queueName, Map.of(), REGION));
|
||||
return queue.getQueueUrl();
|
||||
}
|
||||
|
||||
private String queueArn(String queueUrl) {
|
||||
return RequestScopes.callAs(ACCOUNT, () ->
|
||||
sqsService.getQueueAttributes(queueUrl, List.of("QueueArn"), REGION).get("QueueArn"));
|
||||
}
|
||||
|
||||
private List<Message> receiveOnce(String queueUrl) {
|
||||
return RequestScopes.callAs(ACCOUNT, () -> sqsService.receiveMessage(queueUrl, 1, 30, 0, REGION));
|
||||
}
|
||||
|
||||
private JsonNode awaitRecord(String queueUrl) throws Exception {
|
||||
long deadline = System.nanoTime() + RECEIVE_DEADLINE.toNanos();
|
||||
while (System.nanoTime() < deadline) {
|
||||
List<Message> messages = receiveOnce(queueUrl);
|
||||
if (!messages.isEmpty()) {
|
||||
return MAPPER.readTree(messages.get(0).getBody());
|
||||
}
|
||||
Thread.sleep(250);
|
||||
}
|
||||
return fail("no OnFailure record reached " + queueUrl + " within " + RECEIVE_DEADLINE.toSeconds() + " s");
|
||||
return new Fixture(functionName, latestQueue, aliasQueue);
|
||||
}
|
||||
|
||||
private static void deleteFunction(String functionName) {
|
||||
@@ -221,6 +188,6 @@ class LambdaAsyncRetryDockerIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
private record Fixture(String functionName, String latestQueueUrl, String aliasQueueUrl) {
|
||||
private record Fixture(String functionName, SqsTestQueue latestQueue, SqsTestQueue aliasQueue) {
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.testing.SqsTestQueue;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* A poller thread carries no request context, so account-aware stores fall back to the default
|
||||
* account. A mapping outside it must still reach its SQS and SNS destinations, as the poller sends
|
||||
* from such a thread. The test thread has no request context either.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class StreamBatchFailuresAccountIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "111122223333";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final Duration DELIVERY_TIMEOUT = Duration.ofSeconds(5);
|
||||
private static final StreamBatchFailures.DiscardedBatch BATCH = new StreamBatchFailures.DiscardedBatch(
|
||||
"DDBStreamBatchInfo", "shardId-000000000000", "s1", "s1",
|
||||
"2026-10-20T12:07:26Z", "2026-10-20T12:07:26Z", 1,
|
||||
"arn:aws:dynamodb:us-east-1:111122223333:table/t/stream/2026-08-01T00:00:00.000", () -> "{\"Records\":[]}");
|
||||
|
||||
@Inject
|
||||
StreamBatchFailures failures;
|
||||
|
||||
@Inject
|
||||
SqsService sqsService;
|
||||
|
||||
@Inject
|
||||
SnsService snsService;
|
||||
|
||||
@Test
|
||||
void sqsDestinationOutsideTheDefaultAccountGetsTheRecord() throws Exception {
|
||||
SqsTestQueue queue = SqsTestQueue.create(sqsService, ACCOUNT, REGION, "esm-failures-");
|
||||
|
||||
failures.sendToOnFailureDestination(mappingTo(queue.arn()), BATCH, new InvokeResult(), 1,
|
||||
StreamBatchFailures.RETRY_ATTEMPTS_EXHAUSTED);
|
||||
|
||||
assertEquals("RetryAttemptsExhausted",
|
||||
queue.awaitJson(DELIVERY_TIMEOUT).at("/requestContext/condition").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void snsDestinationOutsideTheDefaultAccountGetsTheRecord() throws Exception {
|
||||
SqsTestQueue queue = SqsTestQueue.create(sqsService, ACCOUNT, REGION, "esm-failures-");
|
||||
String topicArn = RequestScopes.callAs(ACCOUNT, () -> snsService.createTopic(
|
||||
"esm-failures-" + UUID.randomUUID().toString().substring(0, 8), Map.of(), null, REGION).getTopicArn());
|
||||
RequestScopes.runAs(ACCOUNT, () -> snsService.subscribe(topicArn, "sqs", queue.arn(), REGION,
|
||||
Map.of("RawMessageDelivery", "true")));
|
||||
|
||||
failures.sendToOnFailureDestination(mappingTo(topicArn), BATCH, new InvokeResult(), 1,
|
||||
StreamBatchFailures.RETRY_ATTEMPTS_EXHAUSTED);
|
||||
|
||||
assertEquals("RetryAttemptsExhausted",
|
||||
queue.awaitJson(DELIVERY_TIMEOUT).at("/requestContext/condition").asText());
|
||||
}
|
||||
|
||||
private static EventSourceMapping mappingTo(String destinationArn) {
|
||||
EventSourceMapping esm = new EventSourceMapping();
|
||||
esm.setUuid("esm-1");
|
||||
esm.setAccountId(ACCOUNT);
|
||||
esm.setRegion(REGION);
|
||||
esm.setEventSourceArn(BATCH.streamArn());
|
||||
EventSourceMapping.OnFailure onFailure = new EventSourceMapping.OnFailure();
|
||||
onFailure.setDestination(destinationArn);
|
||||
EventSourceMapping.DestinationConfig destinationConfig = new EventSourceMapping.DestinationConfig();
|
||||
destinationConfig.setOnFailure(onFailure);
|
||||
esm.setDestinationConfig(destinationConfig);
|
||||
return esm;
|
||||
}
|
||||
}
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.testutil.LogCapture;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.LogRecord;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
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.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class StreamBatchFailuresTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String STREAM_ARN = "arn:aws:dynamodb:us-east-1:000000000000:table/t/stream/2026-08-01T00:00:00.000";
|
||||
private static final String EVENT = "{\"Records\":[{\"eventSource\":\"aws:dynamodb\"}]}";
|
||||
/** Whole seconds: {@code ISO_INSTANT} would drop the fraction that AWS always writes. */
|
||||
private static final StreamBatchFailures.DiscardedBatch BATCH = batch(() -> EVENT);
|
||||
|
||||
private SqsService sqsService;
|
||||
private SnsService snsService;
|
||||
private S3Service s3Service;
|
||||
private StreamBatchFailures failures;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
|
||||
sqsService = mock(SqsService.class);
|
||||
snsService = mock(SnsService.class);
|
||||
s3Service = mock(S3Service.class);
|
||||
failures = new StreamBatchFailures(sqsService, snsService, s3Service, MAPPER, config);
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3KeyUsesTheUtcLayout() {
|
||||
UUID randomId = UUID.fromString("12345678-1234-1234-1234-123456789abc");
|
||||
|
||||
String key = StreamBatchFailures.s3Key("esm-1", "shard-1", Instant.parse("2026-09-14T23:07:08Z"), randomId);
|
||||
|
||||
assertEquals("aws/lambda/esm-1/shard-1/2026/09/14/"
|
||||
+ "2026-09-14T23.07.08-12345678-1234-1234-1234-123456789abc", key);
|
||||
}
|
||||
|
||||
@Test
|
||||
void retryBackoffDoublesFromThePollIntervalAndCapsAtOneMinute() {
|
||||
assertEquals(1_000, StreamBatchFailures.retryBackoffMs(500, 1));
|
||||
assertEquals(2_000, StreamBatchFailures.retryBackoffMs(500, 2));
|
||||
assertEquals(32_000, StreamBatchFailures.retryBackoffMs(500, 6));
|
||||
assertEquals(60_000, StreamBatchFailures.retryBackoffMs(500, 7));
|
||||
assertEquals(60_000, StreamBatchFailures.retryBackoffMs(500, 10_000), "a large retry count must not overflow");
|
||||
}
|
||||
|
||||
@Test
|
||||
void retryAttemptsRunOutAfterOnePlusTheMaximumInvocations() {
|
||||
assertFalse(StreamBatchFailures.retryAttemptsExhausted(esm(null, null), 10_001), "unset means no limit");
|
||||
assertFalse(StreamBatchFailures.retryAttemptsExhausted(esm(-1, null), 10_001), "-1 means no limit");
|
||||
assertTrue(StreamBatchFailures.retryAttemptsExhausted(esm(0, null), 1));
|
||||
assertFalse(StreamBatchFailures.retryAttemptsExhausted(esm(10, null), 10));
|
||||
assertTrue(StreamBatchFailures.retryAttemptsExhausted(esm(10, null), 11));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maximumRecordAgeIsExceededOnlyForAFiniteLimit() {
|
||||
Instant arrival = Instant.parse("2026-10-20T12:07:26.012Z");
|
||||
long weekLater = arrival.plusSeconds(604_801).toEpochMilli();
|
||||
long almostAMinute = arrival.toEpochMilli() + 59_999;
|
||||
long aMinute = arrival.toEpochMilli() + 60_000;
|
||||
|
||||
assertFalse(StreamBatchFailures.maximumRecordAgeExceeded(esm(null, null), arrival, weekLater), "unset");
|
||||
assertFalse(StreamBatchFailures.maximumRecordAgeExceeded(esm(null, -1), arrival, weekLater), "-1");
|
||||
assertFalse(StreamBatchFailures.maximumRecordAgeExceeded(esm(null, 60), arrival, almostAMinute));
|
||||
assertTrue(StreamBatchFailures.maximumRecordAgeExceeded(esm(null, 60), arrival, aMinute));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqsRecordFillsDefaultsWritesTheTimestampInMillisecondsAndDoesNotBuildTheEvent() throws Exception {
|
||||
EventSourceMapping esm = esm(0, null);
|
||||
esm.setDestinationConfig(destination("arn:aws:sqs:us-east-1:000000000000:dlq"));
|
||||
StreamBatchFailures.DiscardedBatch batch = batch(() -> {
|
||||
throw new AssertionError("only an S3 destination may build the event");
|
||||
});
|
||||
|
||||
failures.sendToOnFailureDestination(esm, batch, new InvokeResult(), 1,
|
||||
StreamBatchFailures.RETRY_ATTEMPTS_EXHAUSTED);
|
||||
|
||||
ArgumentCaptor<String> body = ArgumentCaptor.forClass(String.class);
|
||||
verify(sqsService, times(1)).sendMessage(eq("http://localhost:4566/000000000000/dlq"), body.capture(),
|
||||
eq(0), eq("us-east-1"));
|
||||
JsonNode record = MAPPER.readTree(body.getValue());
|
||||
assertEquals("", record.at("/requestContext/requestId").asText(), record.toString());
|
||||
assertEquals("", record.at("/requestContext/functionArn").asText());
|
||||
assertEquals(List.of("statusCode", "executedVersion"), fieldNames(record.path("responseContext")),
|
||||
"no functionError without a function error: " + record);
|
||||
assertEquals(200, record.at("/responseContext/statusCode").asInt());
|
||||
assertEquals("$LATEST", record.at("/responseContext/executedVersion").asText());
|
||||
assertEquals("2023-11-14T22:13:20Z", record.at("/DDBStreamBatchInfo/approximateArrivalOfFirstRecord").asText(),
|
||||
"the arrival times are written as the source gives them");
|
||||
assertEquals("2023-11-14T22:13:21Z", record.at("/DDBStreamBatchInfo/approximateArrivalOfLastRecord").asText());
|
||||
assertTrue(record.path("timestamp").asText().matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z"),
|
||||
"timestamp must be ISO-8601 with exactly three fraction digits: " + record.path("timestamp"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void destinationInAnotherRegionIsReachedInItsOwnRegion() {
|
||||
EventSourceMapping esm = esm(0, null);
|
||||
esm.setDestinationConfig(destination("arn:aws:sqs:eu-west-2:000000000000:dlq"));
|
||||
|
||||
failures.sendToOnFailureDestination(esm, BATCH, new InvokeResult(), 1,
|
||||
StreamBatchFailures.RETRY_ATTEMPTS_EXHAUSTED);
|
||||
|
||||
verify(sqsService, times(1)).sendMessage(eq("http://localhost:4566/000000000000/dlq"), anyString(),
|
||||
eq(0), eq("eu-west-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3RecordCarriesTheEventAsAPayloadString() throws Exception {
|
||||
EventSourceMapping esm = esm(0, null);
|
||||
esm.setDestinationConfig(destination("arn:aws:s3:::failures"));
|
||||
InvokeResult error = new InvokeResult(200, "Unhandled", new byte[0], null, "req-1");
|
||||
|
||||
failures.sendToOnFailureDestination(esm, BATCH, error, 1, StreamBatchFailures.MAXIMUM_RECORD_AGE_EXCEEDED);
|
||||
|
||||
ArgumentCaptor<String> key = ArgumentCaptor.forClass(String.class);
|
||||
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(s3Service, times(1)).putObject(eq("failures"), key.capture(), body.capture(),
|
||||
eq("application/json"), eq(Map.of()));
|
||||
assertTrue(key.getValue().startsWith("aws/lambda/esm-1/shardId-000000000000/"), key.getValue());
|
||||
JsonNode record = MAPPER.readTree(new String(body.getValue(), StandardCharsets.UTF_8));
|
||||
assertEquals(List.of("requestContext", "responseContext", "version", "payload", "timestamp", "DDBStreamBatchInfo"),
|
||||
fieldNames(record));
|
||||
assertEquals(EVENT, record.path("payload").asText());
|
||||
assertEquals("MaximumRecordAgeExceeded", record.at("/requestContext/condition").asText());
|
||||
assertEquals("Unhandled", record.at("/responseContext/functionError").asText());
|
||||
verifyNoInteractions(sqsService, snsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusedSendIsLoggedWithItsCauseNotThrown() {
|
||||
EventSourceMapping esm = esm(0, null);
|
||||
esm.setDestinationConfig(destination("arn:aws:sqs:us-east-1:000000000000:gone"));
|
||||
AwsException refusal = new AwsException("AWS.SimpleQueueService.NonExistentQueue",
|
||||
"The specified queue does not exist.", 400);
|
||||
when(sqsService.sendMessage(anyString(), anyString(), anyInt(), anyString())).thenThrow(refusal);
|
||||
|
||||
List<LogRecord> records = LogCapture.capture(StreamBatchFailures.class, () ->
|
||||
failures.sendToOnFailureDestination(esm, BATCH, new InvokeResult(), 1,
|
||||
StreamBatchFailures.RETRY_ATTEMPTS_EXHAUSTED));
|
||||
|
||||
LogRecord error = records.stream()
|
||||
.filter(record -> record.getLevel().intValue() >= Level.SEVERE.intValue())
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AssertionError("no error was logged: " + records));
|
||||
assertSame(refusal, error.getThrown(), "the error log must keep the cause and its stack trace");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", "arn:aws:lambda:us-east-1:000000000000:function:other", "arn:aws:s3:::"})
|
||||
void unusableDestinationSendsNothing(String destinationArn) {
|
||||
EventSourceMapping esm = esm(0, null);
|
||||
esm.setDestinationConfig(destination(destinationArn));
|
||||
|
||||
failures.sendToOnFailureDestination(esm, BATCH, new InvokeResult(), 1,
|
||||
StreamBatchFailures.RETRY_ATTEMPTS_EXHAUSTED);
|
||||
|
||||
verifyNoInteractions(sqsService, snsService, s3Service);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingWithoutDestinationSendsNothing() {
|
||||
failures.sendToOnFailureDestination(esm(0, null), BATCH, new InvokeResult(), 1,
|
||||
StreamBatchFailures.RETRY_ATTEMPTS_EXHAUSTED);
|
||||
|
||||
verifyNoInteractions(sqsService, snsService, s3Service);
|
||||
}
|
||||
|
||||
private static StreamBatchFailures.DiscardedBatch batch(Supplier<String> event) {
|
||||
return new StreamBatchFailures.DiscardedBatch("DDBStreamBatchInfo", "shardId-000000000000", "s1", "s2",
|
||||
"2023-11-14T22:13:20Z", "2023-11-14T22:13:21Z", 2, STREAM_ARN, event);
|
||||
}
|
||||
|
||||
private static EventSourceMapping esm(Integer maximumRetryAttempts, Integer maximumRecordAgeInSeconds) {
|
||||
EventSourceMapping esm = new EventSourceMapping();
|
||||
esm.setUuid("esm-1");
|
||||
esm.setAccountId("000000000000");
|
||||
esm.setRegion("us-east-1");
|
||||
esm.setEventSourceArn(STREAM_ARN);
|
||||
esm.setMaximumRetryAttempts(maximumRetryAttempts);
|
||||
esm.setMaximumRecordAgeInSeconds(maximumRecordAgeInSeconds);
|
||||
return esm;
|
||||
}
|
||||
|
||||
private static EventSourceMapping.DestinationConfig destination(String arn) {
|
||||
EventSourceMapping.OnFailure onFailure = new EventSourceMapping.OnFailure();
|
||||
onFailure.setDestination(arn);
|
||||
EventSourceMapping.DestinationConfig destinationConfig = new EventSourceMapping.DestinationConfig();
|
||||
destinationConfig.setOnFailure(onFailure);
|
||||
return destinationConfig;
|
||||
}
|
||||
|
||||
private static List<String> fieldNames(JsonNode node) {
|
||||
List<String> names = new ArrayList<>();
|
||||
node.fieldNames().forEachRemaining(names::add);
|
||||
return names;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package io.github.hectorvent.floci.testing;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.sqs.model.Message;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
|
||||
/**
|
||||
* An SQS queue a test creates in one account and Region, typically as a destination, and then waits
|
||||
* on for one JSON message. Every call runs in that account, so it works from a thread without a
|
||||
* request context.
|
||||
*/
|
||||
public final class SqsTestQueue {
|
||||
|
||||
/** Longer than any test, so a received message never comes back and fails a later check. */
|
||||
private static final int VISIBILITY_TIMEOUT_SECONDS = 300;
|
||||
private static final Duration POLL_INTERVAL = Duration.ofMillis(250);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private final SqsService sqsService;
|
||||
private final String account;
|
||||
private final String region;
|
||||
private final String url;
|
||||
|
||||
private SqsTestQueue(SqsService sqsService, String account, String region, String url) {
|
||||
this.sqsService = sqsService;
|
||||
this.account = account;
|
||||
this.region = region;
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
/** Creates a queue named {@code namePrefix} plus a random suffix. */
|
||||
public static SqsTestQueue create(SqsService sqsService, String account, String region, String namePrefix) {
|
||||
String name = namePrefix + UUID.randomUUID().toString().substring(0, 8);
|
||||
String url = RequestScopes.callAs(account, () -> sqsService.createQueue(name, Map.of(), region).getQueueUrl());
|
||||
return new SqsTestQueue(sqsService, account, region, url);
|
||||
}
|
||||
|
||||
public String url() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public String arn() {
|
||||
return RequestScopes.callAs(account, () ->
|
||||
sqsService.getQueueAttributes(url, List.of("QueueArn"), region).get("QueueArn"));
|
||||
}
|
||||
|
||||
/** At most one message, received without waiting. */
|
||||
public List<Message> receive() {
|
||||
return RequestScopes.callAs(account, () ->
|
||||
sqsService.receiveMessage(url, 1, VISIBILITY_TIMEOUT_SECONDS, 0, region));
|
||||
}
|
||||
|
||||
/** Polls until a message arrives, and returns its body parsed as JSON. */
|
||||
public JsonNode awaitJson(Duration timeout) throws Exception {
|
||||
List<Message> messages = await("a message in " + url)
|
||||
.atMost(timeout)
|
||||
.pollInterval(POLL_INTERVAL)
|
||||
.until(this::receive, received -> !received.isEmpty());
|
||||
return MAPPER.readTree(messages.get(0).getBody());
|
||||
}
|
||||
|
||||
public void delete() {
|
||||
RequestScopes.runAs(account, () -> sqsService.deleteQueue(url, region));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user