mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(firehose): honor BufferingHints with time and size based flush (#2314)
* feat(firehose): honor BufferingHints with time and size based flush Buffers now flush when the stream's BufferingHints.SizeInMBs is reached or when IntervalInSeconds has elapsed since the first buffered record, replacing the hardcoded 5-record count trigger that matched neither AWS nor LocalStack. A single-thread daemon flusher ticks every floci.services.firehose.tick-interval-seconds (default 10). Buffers are drained on ShutdownDelayInitiatedEvent so pending records reach S3 before EmulatorLifecycle persists storage to disk. DeleteDeliveryStream keeps discarding pending records, matching real AWS (verified empirically: 3 records buffered under a 300s/5MB hint never reached the bucket after deletion). Fixes #1886 * feat(firehose): add opt-in flush-record-count trigger Emulator-only volume trigger complementing BufferingHints: setting floci.services.firehose.flush-record-count to N flushes a stream's buffer as soon as it holds N records. Disabled by default (0) so out-of-the-box delivery matches real AWS; 1 gives LocalStack-style record-at-a-time delivery for interactive local dev, where stream definitions mirror production intervals and waiting for IntervalInSeconds is impractical. Covers the use case of #1852. Co-Authored-By: yoshinori-aono-om <yoshinori.aono@omiai.inc> * test(firehose): cover size and interval flush triggers at the wire level The size trigger delivers inline on the writing request, and the interval trigger runs through the real background flusher started on StartupEvent — previously only verified manually. The test-scope Clock is the frozen MutableClock alternative, so the interval test advances it explicitly instead of sleeping through real time. * fix(firehose): clamp the flush tick interval and mirror config keys in application.yml A zero or negative floci.services.firehose.tick-interval-seconds reached scheduleAtFixedRate unchanged, which throws IllegalArgumentException from the StartupEvent observer and aborts startup. Clamp it to a 1s minimum, the same guard RdsDataService applies to its cleanup interval. Also list tick-interval-seconds and flush-record-count under the firehose service in the main and test application.yml, matching how other tunable service settings are surfaced there. * test(firehose): wait for buffered delivery in DataLake and SES compatibility tests DataLakeTest relied on the removed 5-record flush: with buffered delivery its Athena query ran before anything reached S3, failing with NoSuchBucket on floci-firehose-results (caught by the compatibility CI job). Both tests now set explicit BufferingHints and poll for the delivered object first. A 5s interval keeps the wait short — floci does not enforce AWS's 60s server-side minimum and the SDK does no client-side range validation. --------- Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
This commit is contained in:
1 parent
c745f821af
commit
bfda938f72
13 files changed
+650
-50
No files matched your search
+17
-8
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.firehose;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
@@ -20,6 +21,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class FirehoseExtendedS3IntegrationTest {
|
||||
|
||||
@Inject
|
||||
FirehoseService firehoseService;
|
||||
|
||||
private static final String STREAM_NAME = "test-extended-s3-stream";
|
||||
private static final String LEGACY_STREAM_NAME = "test-legacy-s3-stream";
|
||||
private static final String MINIMAL_STREAM_NAME = "test-minimal-extended-s3-stream";
|
||||
@@ -339,7 +343,7 @@ class FirehoseExtendedS3IntegrationTest {
|
||||
String stream = "delivery-default-stream";
|
||||
String bucket = "extended-s3-delivery-default";
|
||||
createDeliveryStream(stream, bucket, "");
|
||||
putFiveRecords(stream);
|
||||
putFiveRecordsAndFlush(stream);
|
||||
|
||||
String key = firstDeliveredKey(bucket, "");
|
||||
assertTrue(key.matches(TIME_PREFIX_REGEX + stream + SUFFIX_REGEX), key);
|
||||
@@ -351,7 +355,7 @@ class FirehoseExtendedS3IntegrationTest {
|
||||
String stream = "delivery-static-stream";
|
||||
String bucket = "extended-s3-delivery-static";
|
||||
createDeliveryStream(stream, bucket, ", \"Prefix\": \"events/data/\"");
|
||||
putFiveRecords(stream);
|
||||
putFiveRecordsAndFlush(stream);
|
||||
|
||||
String key = firstDeliveredKey(bucket, "events/data/");
|
||||
assertTrue(key.matches("events/data/" + TIME_PREFIX_REGEX + stream + SUFFIX_REGEX), key);
|
||||
@@ -363,7 +367,7 @@ class FirehoseExtendedS3IntegrationTest {
|
||||
String stream = "delivery-noslash-stream";
|
||||
String bucket = "extended-s3-delivery-noslash";
|
||||
createDeliveryStream(stream, bucket, ", \"Prefix\": \"legacy\"");
|
||||
putFiveRecords(stream);
|
||||
putFiveRecordsAndFlush(stream);
|
||||
|
||||
String key = firstDeliveredKey(bucket, "legacy");
|
||||
assertTrue(key.matches("legacy" + TIME_PREFIX_REGEX + stream + SUFFIX_REGEX), key);
|
||||
@@ -375,7 +379,7 @@ class FirehoseExtendedS3IntegrationTest {
|
||||
String stream = "delivery-expr-stream";
|
||||
String bucket = "extended-s3-delivery-expr";
|
||||
createDeliveryStream(stream, bucket, ", \"Prefix\": \"data/!{timestamp:yyyy/MM/dd}/\"");
|
||||
putFiveRecords(stream);
|
||||
putFiveRecordsAndFlush(stream);
|
||||
|
||||
String key = firstDeliveredKey(bucket, "data/");
|
||||
assertTrue(key.matches("data/\\d{4}/\\d{2}/\\d{2}/" + stream + SUFFIX_REGEX), key);
|
||||
@@ -387,7 +391,7 @@ class FirehoseExtendedS3IntegrationTest {
|
||||
String stream = "delivery-rand-stream";
|
||||
String bucket = "extended-s3-delivery-rand";
|
||||
createDeliveryStream(stream, bucket, ", \"Prefix\": \"rand/!{firehose:random-string}/\"");
|
||||
putFiveRecords(stream);
|
||||
putFiveRecordsAndFlush(stream);
|
||||
|
||||
String key = firstDeliveredKey(bucket, "rand/");
|
||||
assertTrue(key.matches("rand/[A-Za-z0-9]{11}/" + stream + SUFFIX_REGEX), key);
|
||||
@@ -412,7 +416,7 @@ class FirehoseExtendedS3IntegrationTest {
|
||||
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.CustomTimeZone",
|
||||
equalTo("Europe/Madrid"));
|
||||
|
||||
putFiveRecords(stream);
|
||||
putFiveRecordsAndFlush(stream);
|
||||
String key = firstDeliveredKey(bucket, "events/");
|
||||
assertTrue(key.matches("events/" + TIME_PREFIX_REGEX + stream + SUFFIX_REGEX), key);
|
||||
}
|
||||
@@ -436,8 +440,12 @@ class FirehoseExtendedS3IntegrationTest {
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
/** Five records reach DEFAULT_FLUSH_COUNT, so the batch triggers the automatic flush. */
|
||||
private void putFiveRecords(String streamName) {
|
||||
/**
|
||||
* Small records stay buffered until the size (SizeInMBs) or interval
|
||||
* (IntervalInSeconds) trigger fires; force the flush so the delivery
|
||||
* assertions are deterministic (same mechanism the scheduled flusher uses).
|
||||
*/
|
||||
private void putFiveRecordsAndFlush(String streamName) {
|
||||
String data = Base64.getEncoder().encodeToString("{\"id\": 1}".getBytes(StandardCharsets.UTF_8));
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
@@ -455,6 +463,7 @@ class FirehoseExtendedS3IntegrationTest {
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("FailedPutCount", equalTo(0));
|
||||
firehoseService.flush(streamName);
|
||||
}
|
||||
|
||||
private String firstDeliveredKey(String bucket, String listPrefix) {
|
||||
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
package io.github.hectorvent.floci.services.firehose;
|
||||
|
||||
import io.github.hectorvent.floci.testing.MutableClock;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Wire-level coverage of the AWS-faithful BufferingHints flush triggers:
|
||||
* volume ({@code SizeInMBs}) and time ({@code IntervalInSeconds}), delivered
|
||||
* by the background flusher without any explicit flush call.
|
||||
*
|
||||
* The emulator-only record-count trigger is covered by
|
||||
* {@link FirehoseFlushRecordCountIntegrationTest}: it needs a different
|
||||
* config override, and a Quarkus test profile applies to the whole class.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(FirehoseFlushIntegrationTest.FastTickProfile.class)
|
||||
class FirehoseFlushIntegrationTest {
|
||||
|
||||
public static class FastTickProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
// 1s flush tick so the interval test waits seconds, not the 10s default.
|
||||
return Map.of("floci.services.firehose.tick-interval-seconds", "1");
|
||||
}
|
||||
}
|
||||
|
||||
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String TARGET_PREFIX = "Firehose_20150804.";
|
||||
private static final Pattern KEY_PATTERN = Pattern.compile("<Key>([^<]+)</Key>");
|
||||
|
||||
/** The global test-scope Clock alternative, frozen at 2026-01-01 unless advanced. */
|
||||
@Inject
|
||||
MutableClock clock;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void sizeTriggerDeliversWhenBufferedBytesReachSizeInMBs() {
|
||||
String stream = "flush-size-stream";
|
||||
String bucket = "flush-size-archive";
|
||||
createDeliveryStream(stream, bucket, 1, 300);
|
||||
|
||||
String halfMiB = Base64.getEncoder()
|
||||
.encodeToString("A".repeat(512 * 1024).getBytes(StandardCharsets.UTF_8));
|
||||
putRecord(stream, halfMiB);
|
||||
putRecord(stream, halfMiB); // crosses the 1 MiB threshold: flushes inline, no waiting
|
||||
|
||||
String body = given()
|
||||
.when()
|
||||
.get("/" + bucket + "/" + firstDeliveredKey(bucket))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
// Both records, each followed by the newline the flush appends.
|
||||
assertEquals(2 * 512 * 1024 + 2, body.length());
|
||||
assertTrue(body.startsWith("A"), "delivered body should contain the record payload");
|
||||
}
|
||||
|
||||
@Test
|
||||
void intervalTriggerDeliversAfterIntervalInSecondsElapses() {
|
||||
String stream = "flush-interval-stream";
|
||||
String bucket = "flush-interval-archive";
|
||||
createDeliveryStream(stream, bucket, 5, 60);
|
||||
|
||||
putRecord(stream, Base64.getEncoder()
|
||||
.encodeToString("{\"n\":42}".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
// The test-scope Clock is frozen, so the interval can only elapse by
|
||||
// advancing it; the real 1s tick then finds the buffer due.
|
||||
clock.advance(Duration.ofSeconds(61));
|
||||
|
||||
await().atMost(Duration.ofSeconds(15)).untilAsserted(() ->
|
||||
given()
|
||||
.when()
|
||||
.get("/" + bucket + "/" + firstDeliveredKey(bucket))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(equalTo("{\"n\":42}\n")));
|
||||
}
|
||||
|
||||
private void createDeliveryStream(String streamName, String bucket, int sizeInMBs, int intervalInSeconds) {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_PREFIX + "CreateDeliveryStream")
|
||||
.body("""
|
||||
{
|
||||
"DeliveryStreamName": "%s",
|
||||
"DeliveryStreamType": "DirectPut",
|
||||
"ExtendedS3DestinationConfiguration": {
|
||||
"RoleARN": "arn:aws:iam::000000000000:role/firehose-delivery-role",
|
||||
"BucketARN": "arn:aws:s3:::%s",
|
||||
"BufferingHints": {"SizeInMBs": %d, "IntervalInSeconds": %d}
|
||||
}
|
||||
}
|
||||
""".formatted(streamName, bucket, sizeInMBs, intervalInSeconds))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DeliveryStreamARN", notNullValue());
|
||||
}
|
||||
|
||||
private void putRecord(String streamName, String base64Data) {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_PREFIX + "PutRecord")
|
||||
.body("{ \"DeliveryStreamName\": \"" + streamName + "\", \"Record\": {\"Data\": \"" + base64Data + "\"} }")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("RecordId", notNullValue());
|
||||
}
|
||||
|
||||
private String firstDeliveredKey(String bucket) {
|
||||
String listing = given()
|
||||
.when()
|
||||
.get("/" + bucket)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
Matcher key = KEY_PATTERN.matcher(listing);
|
||||
assertTrue(key.find(), "expected a delivered object in " + bucket + ", got: " + listing);
|
||||
return key.group(1);
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package io.github.hectorvent.floci.services.firehose;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Verifies {@code floci.services.firehose.flush-record-count=1} delivers
|
||||
* every record to the S3 destination immediately.
|
||||
*
|
||||
* Kept separate from {@link FirehoseFlushIntegrationTest} (size and interval
|
||||
* triggers) because this class needs a different config override and a
|
||||
* Quarkus test profile applies to the whole class.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(FirehoseFlushRecordCountIntegrationTest.FlushEveryRecordProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class FirehoseFlushRecordCountIntegrationTest {
|
||||
|
||||
public static class FlushEveryRecordProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.services.firehose.flush-record-count", "1");
|
||||
}
|
||||
}
|
||||
|
||||
private static final String STREAM_NAME = "test-flush-count-stream";
|
||||
private static final String BUCKET = "flush-count-archive";
|
||||
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String TARGET_PREFIX = "Firehose_20150804.";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createDeliveryStream() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_PREFIX + "CreateDeliveryStream")
|
||||
.body("""
|
||||
{
|
||||
"DeliveryStreamName": "%s",
|
||||
"DeliveryStreamType": "DirectPut",
|
||||
"ExtendedS3DestinationConfiguration": {
|
||||
"RoleARN": "arn:aws:iam::000000000000:role/firehose-delivery-role",
|
||||
"BucketARN": "arn:aws:s3:::%s",
|
||||
"Prefix": "single/"
|
||||
}
|
||||
}
|
||||
""".formatted(STREAM_NAME, BUCKET))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DeliveryStreamARN", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void singleRecordIsDeliveredImmediately() {
|
||||
// {"n":1} — base64: eyJuIjoxfQ==
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_PREFIX + "PutRecord")
|
||||
.body("{ \"DeliveryStreamName\": \"" + STREAM_NAME + "\", \"Record\": {\"Data\": \"eyJuIjoxfQ==\"} }")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("RecordId", notNullValue());
|
||||
|
||||
// The record must be visible in the destination bucket without any
|
||||
// further puts (path-style S3 ListObjects on the same edge port).
|
||||
String listing = given()
|
||||
.when()
|
||||
.get("/" + BUCKET)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
|
||||
Matcher key = Pattern.compile("<Key>(single/[^<]+)</Key>").matcher(listing);
|
||||
assertTrue(key.find(), "expected a delivered object under single/, got: " + listing);
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/" + BUCKET + "/" + key.group(1))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(equalTo("{\"n\":1}\n"));
|
||||
}
|
||||
}
|
||||
+158
-12
@@ -1,7 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.firehose;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;
|
||||
@@ -15,12 +15,16 @@ import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -29,25 +33,46 @@ class FirehoseServiceTest {
|
||||
private static final String UUID_REGEX = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
||||
|
||||
private FirehoseService firehoseService;
|
||||
private StorageFactory storageFactory;
|
||||
private S3Service s3Service;
|
||||
private MutableClock clock;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
|
||||
storageFactory = Mockito.mock(StorageFactory.class);
|
||||
when(storageFactory.create(anyString(), anyString(), any()))
|
||||
.thenReturn(AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
s3Service = Mockito.mock(S3Service.class);
|
||||
firehoseService = new FirehoseService(storageFactory, s3Service,
|
||||
new RegionResolver("us-east-1", "000000000000"), new MutableClock());
|
||||
clock = new MutableClock();
|
||||
firehoseService = newService(0);
|
||||
}
|
||||
|
||||
private void putRecordsUntilFlush(String streamName) {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
Record record = new Record(("{\"n\":" + i + "}").getBytes(StandardCharsets.UTF_8));
|
||||
firehoseService.putRecord(streamName, record);
|
||||
private FirehoseService newService(int flushRecordCount) {
|
||||
EmulatorConfig.FirehoseServiceConfig firehoseCfg = mock(EmulatorConfig.FirehoseServiceConfig.class);
|
||||
when(firehoseCfg.enabled()).thenReturn(true);
|
||||
when(firehoseCfg.tickIntervalSeconds()).thenReturn(10L);
|
||||
when(firehoseCfg.flushRecordCount()).thenReturn(flushRecordCount);
|
||||
EmulatorConfig.ServicesConfig servicesCfg = mock(EmulatorConfig.ServicesConfig.class);
|
||||
when(servicesCfg.firehose()).thenReturn(firehoseCfg);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.services()).thenReturn(servicesCfg);
|
||||
|
||||
return new FirehoseService(storageFactory, s3Service,
|
||||
new RegionResolver("us-east-1", "000000000000"), clock, config);
|
||||
}
|
||||
|
||||
private void putRecords(String streamName, int count) {
|
||||
for (int i = 0; i < count; i++) {
|
||||
firehoseService.putRecord(streamName, new Record(("{\"n\":" + i + "}").getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
}
|
||||
|
||||
/** Puts a few small records and forces delivery, the way the interval trigger eventually would. */
|
||||
private void putRecordsAndFlush(String streamName) {
|
||||
putRecords(streamName, 5);
|
||||
firehoseService.flush(streamName);
|
||||
}
|
||||
|
||||
private String deliveredKey(String expectedBucket) {
|
||||
ArgumentCaptor<String> bucket = ArgumentCaptor.forClass(String.class);
|
||||
ArgumentCaptor<String> key = ArgumentCaptor.forClass(String.class);
|
||||
@@ -59,7 +84,7 @@ class FirehoseServiceTest {
|
||||
@Test
|
||||
void deliversToDefaultBucketWithAwsShapedKey() {
|
||||
firehoseService.createDeliveryStream("my-stream", null);
|
||||
putRecordsUntilFlush("my-stream");
|
||||
putRecordsAndFlush("my-stream");
|
||||
|
||||
String key = deliveredKey("floci-firehose-results");
|
||||
assertTrue(key.matches("2026/01/01/00/my-stream-1-2026-01-01-00-00-00-" + UUID_REGEX), key);
|
||||
@@ -71,7 +96,7 @@ class FirehoseServiceTest {
|
||||
s3.setBucketArn("arn:aws:s3:::custom-bucket");
|
||||
s3.setPrefix("events/data/");
|
||||
firehoseService.createDeliveryStream("my-stream", s3);
|
||||
putRecordsUntilFlush("my-stream");
|
||||
putRecordsAndFlush("my-stream");
|
||||
|
||||
String key = deliveredKey("custom-bucket");
|
||||
assertTrue(key.matches("events/data/2026/01/01/00/my-stream-1-2026-01-01-00-00-00-" + UUID_REGEX), key);
|
||||
@@ -83,7 +108,7 @@ class FirehoseServiceTest {
|
||||
s3.setBucketArn("arn:aws:s3:::custom-bucket");
|
||||
s3.setCustomTimeZone("Europe/Madrid");
|
||||
firehoseService.createDeliveryStream("my-stream", s3);
|
||||
putRecordsUntilFlush("my-stream");
|
||||
putRecordsAndFlush("my-stream");
|
||||
|
||||
String key = deliveredKey("custom-bucket");
|
||||
assertTrue(key.matches("2026/01/01/01/my-stream-1-2026-01-01-01-00-00-" + UUID_REGEX), key);
|
||||
@@ -110,8 +135,129 @@ class FirehoseServiceTest {
|
||||
assertEquals("Asia/Tokyo",
|
||||
firehoseService.describeDeliveryStream("my-stream").s3Destination().getCustomTimeZone());
|
||||
|
||||
putRecordsUntilFlush("my-stream");
|
||||
putRecordsAndFlush("my-stream");
|
||||
String key = deliveredKey("custom-bucket");
|
||||
assertTrue(key.matches("events/2026/01/01/09/my-stream-3-2026-01-01-09-00-00-" + UUID_REGEX), key);
|
||||
}
|
||||
|
||||
@Test
|
||||
void timeBasedFlushKeepsBufferWhileDefaultIntervalHasNotElapsed() {
|
||||
firehoseService.createDeliveryStream("idle-stream", null);
|
||||
putRecords("idle-stream", 2);
|
||||
|
||||
firehoseService.flushDueBuffers(clock.instant().plusSeconds(299));
|
||||
|
||||
verify(s3Service, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), anyMap());
|
||||
}
|
||||
|
||||
@Test
|
||||
void timeBasedFlushDeliversBufferedRecordsAfterDefaultInterval() {
|
||||
firehoseService.createDeliveryStream("idle-stream", null);
|
||||
putRecords("idle-stream", 2);
|
||||
|
||||
firehoseService.flushDueBuffers(clock.instant().plusSeconds(300));
|
||||
|
||||
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(s3Service).putObject(eq("floci-firehose-results"), anyString(), body.capture(), anyString(), anyMap());
|
||||
assertEquals("{\"n\":0}\n{\"n\":1}\n", new String(body.getValue(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void timeBasedFlushHonorsStreamBufferingIntervalHint() {
|
||||
S3Destination s3 = new S3Destination();
|
||||
s3.setBucketArn("arn:aws:s3:::custom-bucket");
|
||||
DeliveryStreamDescription.BufferingHints hints = new DeliveryStreamDescription.BufferingHints();
|
||||
hints.setSizeInMBs(5);
|
||||
hints.setIntervalInSeconds(60);
|
||||
s3.setBufferingHints(hints);
|
||||
firehoseService.createDeliveryStream("hinted-stream", s3);
|
||||
putRecords("hinted-stream", 1);
|
||||
|
||||
firehoseService.flushDueBuffers(clock.instant().plusSeconds(59));
|
||||
verify(s3Service, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), anyMap());
|
||||
|
||||
firehoseService.flushDueBuffers(clock.instant().plusSeconds(60));
|
||||
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(s3Service).putObject(eq("custom-bucket"), anyString(), body.capture(), anyString(), anyMap());
|
||||
assertEquals("{\"n\":0}\n", new String(body.getValue(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/** Matches real AWS: the volume trigger is bytes vs SizeInMBs, never a record count. */
|
||||
@Test
|
||||
void smallRecordsDoNotTriggerSizeBasedFlushRegardlessOfCount() {
|
||||
firehoseService.createDeliveryStream("trickle-stream", null);
|
||||
putRecords("trickle-stream", 20);
|
||||
|
||||
verify(s3Service, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), anyMap());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sizeBasedFlushDeliversWhenBufferedBytesReachSizeHint() {
|
||||
S3Destination s3 = new S3Destination();
|
||||
s3.setBucketArn("arn:aws:s3:::custom-bucket");
|
||||
DeliveryStreamDescription.BufferingHints hints = new DeliveryStreamDescription.BufferingHints();
|
||||
hints.setSizeInMBs(1);
|
||||
hints.setIntervalInSeconds(300);
|
||||
s3.setBufferingHints(hints);
|
||||
firehoseService.createDeliveryStream("bulky-stream", s3);
|
||||
|
||||
firehoseService.putRecord("bulky-stream", new Record(new byte[512 * 1024]));
|
||||
verify(s3Service, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), anyMap());
|
||||
|
||||
firehoseService.putRecord("bulky-stream", new Record(new byte[512 * 1024]));
|
||||
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(s3Service).putObject(eq("custom-bucket"), anyString(), body.capture(), anyString(), anyMap());
|
||||
// Both 512 KiB records, each followed by the newline the flush appends.
|
||||
assertEquals(2 * 512 * 1024 + 2, body.getValue().length);
|
||||
}
|
||||
|
||||
/** Emulator-only opt-in: flush-record-count=1 restores LocalStack-style record-at-a-time delivery. */
|
||||
@Test
|
||||
void flushRecordCountOfOneDeliversEachRecordImmediately() {
|
||||
firehoseService = newService(1);
|
||||
firehoseService.createDeliveryStream("eager-stream", null);
|
||||
firehoseService.putRecord("eager-stream", new Record("{\"n\":0}".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(s3Service).putObject(eq("floci-firehose-results"), anyString(), body.capture(), anyString(), anyMap());
|
||||
assertEquals("{\"n\":0}\n", new String(body.getValue(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void flushRecordCountThresholdDeliversTheWholeBuffer() {
|
||||
firehoseService = newService(3);
|
||||
firehoseService.createDeliveryStream("counted-stream", null);
|
||||
putRecords("counted-stream", 2);
|
||||
verify(s3Service, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), anyMap());
|
||||
|
||||
firehoseService.putRecord("counted-stream", new Record("{\"n\":2}".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(s3Service).putObject(eq("floci-firehose-results"), anyString(), body.capture(), anyString(), anyMap());
|
||||
assertEquals("{\"n\":0}\n{\"n\":1}\n{\"n\":2}\n", new String(body.getValue(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/** Matches real AWS: DeleteDeliveryStream discards undelivered records instead of flushing them. */
|
||||
@Test
|
||||
void deleteDeliveryStreamDiscardsBufferedRecords() {
|
||||
firehoseService.createDeliveryStream("doomed-stream", null);
|
||||
putRecords("doomed-stream", 2);
|
||||
|
||||
firehoseService.deleteDeliveryStream("doomed-stream");
|
||||
firehoseService.flushDueBuffers(clock.instant().plusSeconds(301));
|
||||
|
||||
verify(s3Service, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), anyMap());
|
||||
}
|
||||
|
||||
@Test
|
||||
void timeBasedFlushDeliversEachBatchOnlyOnce() {
|
||||
firehoseService.createDeliveryStream("idle-stream", null);
|
||||
putRecords("idle-stream", 2);
|
||||
|
||||
Instant afterInterval = clock.instant().plusSeconds(301);
|
||||
firehoseService.flushDueBuffers(afterInterval);
|
||||
firehoseService.flushDueBuffers(afterInterval.plusSeconds(301));
|
||||
|
||||
verify(s3Service).putObject(anyString(), anyString(), any(byte[].class), anyString(), anyMap());
|
||||
}
|
||||
}
|
||||
+16
-8
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService.MetricIdentity;
|
||||
import io.github.hectorvent.floci.services.firehose.FirehoseService;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
@@ -83,6 +84,9 @@ class SesEventPublishingV2IntegrationTest {
|
||||
@Inject
|
||||
CloudWatchMetricsService metricsService;
|
||||
|
||||
@Inject
|
||||
FirehoseService firehoseService;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
@@ -639,22 +643,26 @@ class SesEventPublishingV2IntegrationTest {
|
||||
|
||||
@Test
|
||||
@Order(15)
|
||||
void firehose_fiveSends_triggerAutoFlushAndWriteNdjsonToS3() throws Exception {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
sendEmailToConfigSet(CS_FIREHOSE, "recipient" + i + "@example.com", "fh-evt-" + i);
|
||||
}
|
||||
void firehose_sendEventsAreDeliveredAsNdjsonToS3() throws Exception {
|
||||
sendEmailToConfigSet(CS_FIREHOSE, "recipient0@example.com", "fh-evt-0");
|
||||
sendEmailToConfigSet(CS_FIREHOSE, "recipient1@example.com", "fh-evt-1");
|
||||
|
||||
// Small events stay buffered until the stream's size (SizeInMBs) or
|
||||
// interval (IntervalInSeconds) trigger fires; force the flush so the
|
||||
// assertion is deterministic (same mechanism the scheduled flusher uses).
|
||||
firehoseService.flush(FIREHOSE_STREAM);
|
||||
|
||||
List<S3Object> objects = s3Service.listObjects(FIREHOSE_BUCKET, FIREHOSE_STREAM + "/", null, 100);
|
||||
assertEquals(1, objects.size(),
|
||||
"expected exactly one flushed S3 object after 5 putRecord calls (DEFAULT_FLUSH_COUNT)");
|
||||
"expected exactly one flushed S3 object containing the buffered events");
|
||||
|
||||
S3Object obj = s3Service.getObject(FIREHOSE_BUCKET, objects.get(0).getKey());
|
||||
String body = new String(obj.getData(), StandardCharsets.UTF_8);
|
||||
String[] lines = body.split("\\R");
|
||||
assertEquals(5, lines.length, "flushed object should contain 5 NDJSON records");
|
||||
assertEquals(2, lines.length, "flushed object should contain one NDJSON record per send");
|
||||
|
||||
for (int i = 0; i < 5; i++) {
|
||||
JsonNode event = MAPPER.readTree(lines[i]);
|
||||
for (String line : lines) {
|
||||
JsonNode event = MAPPER.readTree(line);
|
||||
assertEquals("Send", event.path("eventType").asText());
|
||||
assertEquals(SENDER, event.path("mail").path("source").asText());
|
||||
assertEquals(CS_FIREHOSE,
|
||||
|
||||
Reference in new issue
Block a user