mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(firehose): deliver records from a Kinesis stream source (#2528)
* feat(firehose): deliver records from a Kinesis stream source A delivery stream created with DeliveryStreamType=KinesisStreamAsSource recorded its KinesisStreamSourceConfiguration and then ignored it. Nothing read the source stream, so the only way records reached S3 was PutRecord on the delivery stream itself -- which real AWS rejects for a sourced stream. CreateDeliveryStream succeeded, DescribeDeliveryStream reported ACTIVE, and the stream silently delivered nothing. Found by terraform-aws-messaging's own TestKinesisFirehose, which puts one record into the source stream and polls the destination bucket: every API call succeeded and the test failed with "no objects found in the bucket" after six 60s retries. The flusher tick now polls each sourced delivery stream through the ordinary shard-iterator API, so what it ingests is exactly what a GetRecords consumer would see, and the iterator doubles as the checkpoint. The first iterator starts at DeliveryStartTimestamp rather than TRIM_HORIZON: attaching Firehose to a stream that already holds records does not backfill them on AWS. Records are handed to putRecordBatch, so they buffer and trigger flushes on the same terms as records delivered by PutRecord. A source stream that does not exist is logged at debug and skipped, so one broken delivery stream cannot stall polling for the others. * fix(firehose): persist Kinesis source shard checkpoints across a restart The shard iterator each source shard had been consumed to lived only in an in-memory map, while the delivery stream itself and the source stream's records both sit in persisted storage. On restart the checkpoint was the one piece that did not come back, so polling rebuilt every iterator from DeliveryStartTimestamp and delivered the source stream's entire retained history to S3 a second time -- silently, and again on every subsequent restart. The checkpoint moves into a firehose/source-iterators.json store alongside streams.json. A Kinesis shard iterator is safe to persist because it is a self-describing token (streamName|shardId|type|sequenceNumber|index|timestamp, base64) with no JVM-lifetime component, and KinesisService never trims a shard's record list, so an index recorded before a restart still resolves to the same position after one. The checkpoint is written after the polled records are buffered, so a crash between the two re-reads them rather than dropping them, and a graceful shutdown loses nothing at all: onPreShutdown already drains the buffers to S3 before storage is flushed to disk. buffers and bufferSince stay in memory -- losing those loses only what was in flight, which is bounded, where losing the checkpoint replays an unbounded history. * fix(firehose): commit source checkpoints on delivery, not on buffering Persisting the advanced shard iterator inside pollKinesisSource fixed an unbounded replay on restart but introduced a worse failure in its place. Polled records do not go to S3 from the poller; they go through putRecordBatch into the in-memory buffer and reach S3 only when a flush trips. Writing the checkpoint immediately after buffering let the durable checkpoint outrun durable delivery: terminate in that window and the buffer is gone while the persisted checkpoint already says those records were consumed, so the restored poller resumes past them and they are never delivered. Real Firehose is at-least-once, so a duplicate is correct-if-untidy; a silent permanent skip is not. The checkpoint now has two halves. pendingSourceIterators holds the advanced position in memory, and only a flush whose S3 write actually succeeded promotes it into the persisted source-iterators store. The poller reads from pending-or-committed, so a second poll still does not re-read what the first buffered, and the restart case the previous commit fixed still holds: polling resumes from the last committed position, never from DeliveryStartTimestamp. Ordering and failure detail: - The advance runs inside putRecordBatch under the buffer lock, alongside the records it covers, so no flush can observe one without the other, and a throw before buffering leaves the checkpoint alone. - flush takes the pending checkpoint out under that same lock, and flush drains the whole buffer, so a successful write makes every record the checkpoint covers durable. - A failed write neither commits nor restores the checkpoint: the durable position stays put and the next poll reads those records again, which repairs the failed delivery instead of silently dropping it. - Each advance rebases on the current pending-or-committed map instead of one carried across the shard loop, so a discarded pending rolls the other shards back with it. Commits merge per shard, so two flushes completing out of order cost a duplicate rather than dropping a shard's progress. - onPreShutdown is unchanged and now correct by construction: its drain commits each checkpoint it makes durable, before storage is written out. The comment claiming a crash between the two "re-reads them rather than dropping them" was simply wrong -- buffering is not durability -- and is replaced. Records arriving through PutRecord share the buffer and are unaffected: they carry no checkpoint advance, and a flush that mixes them with sourced records still delivers both before anything is committed. * fix(firehose): stamp DeliveryStartTimestamp at creation for a Kinesis source CreateDeliveryStream's KinesisStreamSourceConfiguration carries only the ARN and role -- DeliveryStartTimestamp exists only on the Description shape, which AWS fills in at creation. FirehoseJsonHandler mapped the source straight off the request, so through the API the field was always null and the poller fell back to TRIM_HORIZON, backfilling a pre-populated source stream's whole history into S3. createDeliveryStream now stamps the field itself when a KinesisStreamAsSource request omits it, matching how AWS behaves: attaching Firehose to a stream that already holds records does not replay them. Adds a wire-level regression test that pre-loads a Kinesis stream, creates the delivery stream through the real CreateDeliveryStream API call, and asserts the pre-existing record is never delivered while one added afterward is -- closing the gap where the existing unit test covered this by calling FirehoseService.createDeliveryStream directly and hand-setting the timestamp, stepping around the API path entirely.
This commit is contained in:
1 parent
054508df87
commit
009ac0b4a6
3 files changed
+476
-9
No files matched your search
+96
@@ -101,6 +101,102 @@ class FirehoseFlushIntegrationTest {
|
||||
.body(equalTo("{\"n\":42}\n")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire-level coverage of the gap in {@code kinesisSourceDoesNotBackfillRecordsFromBeforeDeliveryStart}
|
||||
* (FirehoseServiceTest): that test calls {@code FirehoseService.createDeliveryStream}
|
||||
* directly and hand-sets {@code DeliveryStartTimestamp} on the source, stepping around
|
||||
* the actual API path. CreateDeliveryStream's wire request
|
||||
* (KinesisStreamSourceConfiguration) never carries that field -- AWS fills it in on the
|
||||
* Description shape at creation -- so this drives creation through the real
|
||||
* X-Amz-Target: Firehose_20150804.CreateDeliveryStream call against a Kinesis stream
|
||||
* that already holds a record, and asserts that record is never delivered while one
|
||||
* added afterward is.
|
||||
*/
|
||||
@Test
|
||||
void kinesisSourceCreatedThroughTheApiDoesNotBackfillPreExistingRecords() throws InterruptedException {
|
||||
String sourceStream = "flush-kinesis-source-stream";
|
||||
String deliveryStream = "flush-kinesis-source-delivery";
|
||||
String bucket = "flush-kinesis-source-archive";
|
||||
String sourceArn = "arn:aws:kinesis:us-east-1:000000000000:stream/" + sourceStream;
|
||||
|
||||
createKinesisStream(sourceStream);
|
||||
putKinesisRecord(sourceStream, "old");
|
||||
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_PREFIX + "CreateDeliveryStream")
|
||||
.body("""
|
||||
{
|
||||
"DeliveryStreamName": "%s",
|
||||
"DeliveryStreamType": "KinesisStreamAsSource",
|
||||
"KinesisStreamSourceConfiguration": {
|
||||
"KinesisStreamARN": "%s",
|
||||
"RoleARN": "arn:aws:iam::000000000000:role/firehose-source-role"
|
||||
},
|
||||
"ExtendedS3DestinationConfiguration": {
|
||||
"RoleARN": "arn:aws:iam::000000000000:role/firehose-delivery-role",
|
||||
"BucketARN": "arn:aws:s3:::%s",
|
||||
"BufferingHints": {"SizeInMBs": 5, "IntervalInSeconds": 60}
|
||||
}
|
||||
}
|
||||
""".formatted(deliveryStream, sourceArn, bucket))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DeliveryStreamARN", notNullValue());
|
||||
|
||||
// Give the 1s poller a couple of real ticks to run against the pre-loaded stream
|
||||
// before adding a record it is meant to pick up. A backfill bug would buffer
|
||||
// "old" here already; the buffering interval below (60s of the frozen test clock)
|
||||
// is what lets this test tell "polled and buffered" apart from "never polled".
|
||||
Thread.sleep(2500);
|
||||
|
||||
putKinesisRecord(sourceStream, "new");
|
||||
|
||||
// Let a poll tick actually buffer "new" before the clock moves: bufferSince is
|
||||
// stamped from this same frozen Clock, so advancing first would stamp it already
|
||||
// in the future and the interval trigger below would never fire.
|
||||
Thread.sleep(2500);
|
||||
|
||||
// The frozen test-scope Clock only elapses when advanced; the real 1s tick then
|
||||
// finds the buffer due, same as intervalTriggerDeliversAfterIntervalInSecondsElapses.
|
||||
clock.advance(Duration.ofSeconds(61));
|
||||
|
||||
await().atMost(Duration.ofSeconds(15)).untilAsserted(() ->
|
||||
given()
|
||||
.when()
|
||||
.get("/" + bucket + "/" + firstDeliveredKey(bucket))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(equalTo("new\n")));
|
||||
}
|
||||
|
||||
private void createKinesisStream(String streamName) {
|
||||
given()
|
||||
.header("X-Amz-Target", "Kinesis_20131202.CreateStream")
|
||||
.contentType(CONTENT_TYPE)
|
||||
.body("{\"StreamName\": \"" + streamName + "\", \"ShardCount\": 1}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private void putKinesisRecord(String streamName, String data) {
|
||||
given()
|
||||
.header("X-Amz-Target", "Kinesis_20131202.PutRecord")
|
||||
.contentType(CONTENT_TYPE)
|
||||
.body("{\"StreamName\": \"" + streamName + "\", \"Data\": \""
|
||||
+ Base64.getEncoder().encodeToString(data.getBytes(StandardCharsets.UTF_8))
|
||||
+ "\", \"PartitionKey\": \"pk\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("SequenceNumber", notNullValue());
|
||||
}
|
||||
|
||||
private void createDeliveryStream(String streamName, String bucket, int sizeInMBs, int intervalInSeconds) {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
|
||||
+183
-3
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
|
||||
import io.github.hectorvent.floci.services.firehose.model.Record;
|
||||
import io.github.hectorvent.floci.services.kinesis.KinesisService;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.PutObjectOptions;
|
||||
import io.github.hectorvent.floci.testing.MutableClock;
|
||||
@@ -21,6 +22,8 @@ import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -43,6 +46,7 @@ class FirehoseServiceTest {
|
||||
private static final String FIVE_RECORDS = "{\"n\":0}\n{\"n\":1}\n{\"n\":2}\n{\"n\":3}\n{\"n\":4}\n";
|
||||
|
||||
private FirehoseService firehoseService;
|
||||
private KinesisService kinesisService;
|
||||
private StorageFactory storageFactory;
|
||||
private S3Service s3Service;
|
||||
private MutableClock clock;
|
||||
@@ -50,8 +54,16 @@ class FirehoseServiceTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
storageFactory = Mockito.mock(StorageFactory.class);
|
||||
// A backend per store, keyed by file name, exactly as the real StorageFactory
|
||||
// reuses backends by path. One shared instance would put KinesisStream values in
|
||||
// the map FirehoseService.scan() reads as delivery streams; a fresh instance per
|
||||
// create() call would make a second service over "the same storage" impossible
|
||||
// to build, which is what the restart test needs.
|
||||
Map<String, AccountAwareStorageBackend<?>> backends = new HashMap<>();
|
||||
when(storageFactory.create(anyString(), anyString(), any()))
|
||||
.thenReturn(AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
.thenAnswer(invocation -> backends.computeIfAbsent(
|
||||
invocation.getArgument(0) + "/" + invocation.getArgument(1),
|
||||
k -> AccountAwareStorageBackend.inMemory("000000000000")));
|
||||
s3Service = Mockito.mock(S3Service.class);
|
||||
clock = new MutableClock();
|
||||
firehoseService = newService(0);
|
||||
@@ -67,8 +79,12 @@ class FirehoseServiceTest {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.services()).thenReturn(servicesCfg);
|
||||
|
||||
return new FirehoseService(storageFactory, s3Service,
|
||||
new RegionResolver("us-east-1", "000000000000"), clock, config);
|
||||
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
|
||||
// A real KinesisService, not a mock: the point of the source poller is that it
|
||||
// sees what a GetRecords consumer sees, and a stubbed one could not show that.
|
||||
kinesisService = new KinesisService(storageFactory, regionResolver);
|
||||
return new FirehoseService(storageFactory, s3Service, kinesisService,
|
||||
regionResolver, clock, config);
|
||||
}
|
||||
|
||||
private static S3Destination destination(String bucketArn, String compressionFormat) {
|
||||
@@ -419,4 +435,168 @@ class FirehoseServiceTest {
|
||||
delivered("floci-firehose-results").body());
|
||||
}
|
||||
|
||||
|
||||
// --- Kinesis stream as source -------------------------------------------------
|
||||
//
|
||||
// A KinesisStreamAsSource delivery stream is never given records by PutRecord: on
|
||||
// real AWS the API rejects that, and everything it delivers comes from Firehose
|
||||
// reading the source stream. Recording the source and not reading it makes such a
|
||||
// stream a silent black hole -- create succeeds, describe looks healthy, nothing is
|
||||
// ever delivered.
|
||||
|
||||
private static DeliveryStreamDescription.KinesisStreamSource kinesisSource(String streamName) {
|
||||
DeliveryStreamDescription.KinesisStreamSource source =
|
||||
new DeliveryStreamDescription.KinesisStreamSource();
|
||||
source.setKinesisStreamArn("arn:aws:kinesis:us-east-1:000000000000:stream/" + streamName);
|
||||
source.setRoleArn("arn:aws:iam::000000000000:role/firehose");
|
||||
return source;
|
||||
}
|
||||
|
||||
private void createSourcedDeliveryStream(String deliveryStream, String sourceStream) {
|
||||
kinesisService.createStream(sourceStream, 1, "us-east-1");
|
||||
firehoseService.createDeliveryStream(deliveryStream, destination("arn:aws:s3:::sink", null),
|
||||
java.util.List.of(), "KinesisStreamAsSource", kinesisSource(sourceStream));
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisSourceRecordsAreDelivered() {
|
||||
createSourcedDeliveryStream("sourced-stream", "src-stream");
|
||||
kinesisService.putRecord("src-stream", "hello".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
|
||||
|
||||
firehoseService.pollKinesisSources();
|
||||
firehoseService.flush("sourced-stream");
|
||||
|
||||
assertEquals("hello\n", delivered("sink").text());
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisSourceRecordsAreDeliveredExactlyOnce() {
|
||||
createSourcedDeliveryStream("sourced-stream", "src-stream");
|
||||
kinesisService.putRecord("src-stream", "hello".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
|
||||
|
||||
// The iterator is the checkpoint, so a second poll before the flush must not
|
||||
// re-read what the first one already buffered.
|
||||
firehoseService.pollKinesisSources();
|
||||
firehoseService.pollKinesisSources();
|
||||
firehoseService.flush("sourced-stream");
|
||||
|
||||
assertEquals("hello\n", delivered("sink").text());
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisSourcePollingResumesAfterAFlush() {
|
||||
createSourcedDeliveryStream("sourced-stream", "src-stream");
|
||||
kinesisService.putRecord("src-stream", "first".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
|
||||
firehoseService.pollKinesisSources();
|
||||
firehoseService.flush("sourced-stream");
|
||||
|
||||
kinesisService.putRecord("src-stream", "second".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
|
||||
firehoseService.pollKinesisSources();
|
||||
firehoseService.flush("sourced-stream");
|
||||
|
||||
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(s3Service, Mockito.times(2)).putObject(anyString(), anyString(), body.capture(), anyString(),
|
||||
anyMap(), any(PutObjectOptions.class));
|
||||
assertEquals(java.util.List.of("first\n", "second\n"),
|
||||
body.getAllValues().stream().map(b -> new String(b, StandardCharsets.UTF_8)).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisSourceDoesNotBackfillRecordsFromBeforeDeliveryStart() {
|
||||
kinesisService.createStream("src-stream", 1, "us-east-1");
|
||||
kinesisService.putRecord("src-stream", "old".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
|
||||
DeliveryStreamDescription.KinesisStreamSource source = kinesisSource("src-stream");
|
||||
// Attaching Firehose to a stream that already holds records does not replay them;
|
||||
// delivery starts at DeliveryStartTimestamp.
|
||||
source.setDeliveryStartTimestamp(Instant.now().plusSeconds(3600));
|
||||
firehoseService.createDeliveryStream("sourced-stream", destination("arn:aws:s3:::sink", null),
|
||||
java.util.List.of(), "KinesisStreamAsSource", source);
|
||||
|
||||
firehoseService.pollKinesisSources();
|
||||
firehoseService.flush("sourced-stream");
|
||||
|
||||
verifyNothingDelivered();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deliveryStreamWithNoKinesisSourceIsUnaffectedByPolling() {
|
||||
firehoseService.createDeliveryStream("plain-stream", destination("arn:aws:s3:::sink", null));
|
||||
|
||||
firehoseService.pollKinesisSources();
|
||||
firehoseService.flush("plain-stream");
|
||||
|
||||
verifyNothingDelivered();
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisSourceCheckpointSurvivesARestart() {
|
||||
createSourcedDeliveryStream("sourced-stream", "src-stream");
|
||||
kinesisService.putRecord("src-stream", "hello".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
|
||||
firehoseService.pollKinesisSources();
|
||||
firehoseService.flush("sourced-stream");
|
||||
|
||||
// Restart: a fresh service over the same storage, the way the emulator comes back
|
||||
// up against its persisted state. The delivery stream and the source stream's
|
||||
// records both survive, so an in-memory-only checkpoint would rebuild the iterator
|
||||
// from DeliveryStartTimestamp and deliver "hello" to S3 a second time.
|
||||
firehoseService = newService(0);
|
||||
firehoseService.pollKinesisSources();
|
||||
firehoseService.flush("sourced-stream");
|
||||
|
||||
assertEquals("hello\n", delivered("sink").text());
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisSourceRecordsBufferedButNeverFlushedSurviveARestart() {
|
||||
createSourcedDeliveryStream("sourced-stream", "src-stream");
|
||||
kinesisService.putRecord("src-stream", "hello".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
|
||||
|
||||
// Poll, then crash. The record is in the in-memory buffer and no flush has run,
|
||||
// so nothing reached S3 and nothing in memory survives.
|
||||
firehoseService.pollKinesisSources();
|
||||
verifyNothingDelivered();
|
||||
|
||||
// Restart. A checkpoint persisted at poll time would already have recorded the
|
||||
// record as consumed, and the restored poller would skip past it forever --
|
||||
// silent, permanent loss. Committing the checkpoint only on a successful flush
|
||||
// means the restored poller reads it again and delivers it.
|
||||
firehoseService = newService(0);
|
||||
firehoseService.pollKinesisSources();
|
||||
firehoseService.flush("sourced-stream");
|
||||
|
||||
assertEquals("hello\n", delivered("sink").text());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedDeliveryLeavesTheSourceCheckpointUncommitted() {
|
||||
createSourcedDeliveryStream("sourced-stream", "src-stream");
|
||||
kinesisService.putRecord("src-stream", "hello".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
|
||||
when(s3Service.putObject(anyString(), anyString(), any(byte[].class), anyString(),
|
||||
anyMap(), any(PutObjectOptions.class))).thenThrow(new RuntimeException("s3 unavailable"));
|
||||
|
||||
firehoseService.pollKinesisSources();
|
||||
firehoseService.flush("sourced-stream");
|
||||
|
||||
// The write failed, so the record is not durable and the checkpoint must not have
|
||||
// moved: once S3 is back, the next poll has to read it again.
|
||||
Mockito.reset(s3Service);
|
||||
firehoseService.pollKinesisSources();
|
||||
firehoseService.flush("sourced-stream");
|
||||
|
||||
assertEquals("hello\n", delivered("sink").text());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMissingSourceStreamDoesNotStopOtherStreamsFromPolling() {
|
||||
// No createStream for "gone-stream": describeStream throws ResourceNotFound.
|
||||
firehoseService.createDeliveryStream("broken-stream", destination("arn:aws:s3:::sink", null),
|
||||
java.util.List.of(), "KinesisStreamAsSource", kinesisSource("gone-stream"));
|
||||
createSourcedDeliveryStream("sourced-stream", "src-stream");
|
||||
kinesisService.putRecord("src-stream", "hello".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
|
||||
|
||||
firehoseService.pollKinesisSources();
|
||||
firehoseService.flush("sourced-stream");
|
||||
|
||||
assertEquals("hello\n", delivered("sink").text());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user