mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(firehose): keep buffered records when S3 delivery fails (#3471)
* fix(firehose): keep buffered records when S3 delivery fails A failed S3 write dropped the batch it was delivering. Records that came in through PutRecord were lost; records polled from a Kinesis source were only recovered by re-reading from the committed checkpoint. A failed delivery now restores the batch at the front of the buffer, ahead of records that arrived while the write was in flight, keeps the buffer's original start time so the next scheduled tick retries it, and re-pends the source checkpoint so a later successful delivery commits it. Successful delivery, compression and the scheduled flush are unchanged. * fix(firehose): serialize delivery per stream so a later flush cannot commit past an unresolved batch The buffer monitor only made the snapshot atomic. A poll that had read past a first flush's checkpoint could buffer its records after that flush took the pending position, and a second flush would then deliver them and commit a position past the first batch while its S3 write was still in flight. If that write failed, the durable checkpoint already sat past records that were only buffered for retry, and a restart before the retry skipped them. One delivery at a time per stream, from taking the buffer to committing or restoring its checkpoint, closes that window; the poller keeps buffering under the buffer lock alone, so a slow write never stalls a poll. * docs(firehose): a failed S3 write now keeps its batch buffered * docs(firehose): drop the stale no-retry note in the Parquet converter
This commit is contained in:
1 parent
c18c80e557
commit
6507f32aea
4 files changed
+269
-38
No files matched your search
+201
-3
@@ -21,11 +21,22 @@ import org.mockito.Mockito;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -38,6 +49,7 @@ import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
@@ -77,6 +89,14 @@ class FirehoseServiceTest {
|
||||
}
|
||||
|
||||
private FirehoseService newService(int flushRecordCount) {
|
||||
return newService(flushRecordCount, UnaryOperator.identity());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param kinesisDecorator applied to the source service before the poller sees it,
|
||||
* e.g. {@code Mockito::spy} to park a poll mid-way.
|
||||
*/
|
||||
private FirehoseService newService(int flushRecordCount, UnaryOperator<KinesisService> kinesisDecorator) {
|
||||
EmulatorConfig.FirehoseServiceConfig firehoseCfg = mock(EmulatorConfig.FirehoseServiceConfig.class);
|
||||
when(firehoseCfg.enabled()).thenReturn(true);
|
||||
when(firehoseCfg.tickIntervalSeconds()).thenReturn(10L);
|
||||
@@ -89,12 +109,37 @@ class FirehoseServiceTest {
|
||||
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);
|
||||
kinesisService = kinesisDecorator.apply(new KinesisService(storageFactory, regionResolver));
|
||||
return new FirehoseService(storageFactory, s3Service, kinesisService,
|
||||
regionResolver, clock, config, mock(FirehoseParquetConverter.class),
|
||||
mock(FirehoseLambdaTransformer.class));
|
||||
}
|
||||
|
||||
/** The committed source checkpoint, as a restarted service would read it back. */
|
||||
@SuppressWarnings("unchecked")
|
||||
private Optional<Map<String, String>> durableCheckpoint(String deliveryStream) {
|
||||
AccountAwareStorageBackend<Map<String, String>> store =
|
||||
(AccountAwareStorageBackend<Map<String, String>>) backends.get("firehose/source-iterators.json");
|
||||
return store.getForAccount("000000000000", "us-east-1/" + deliveryStream);
|
||||
}
|
||||
|
||||
/**
|
||||
* Spin until {@code thread} is parked entering a monitor or {@code task} has finished,
|
||||
* whichever comes first, so the assertions that follow see a settled state rather than
|
||||
* a thread that was merely never scheduled.
|
||||
*/
|
||||
private static void awaitParkedOrDone(AtomicReference<Thread> thread, Future<?> task)
|
||||
throws InterruptedException {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
|
||||
while (System.nanoTime() < deadline && !task.isDone()) {
|
||||
Thread th = thread.get();
|
||||
if (th != null && th.getState() == Thread.State.BLOCKED) {
|
||||
return;
|
||||
}
|
||||
Thread.sleep(5);
|
||||
}
|
||||
}
|
||||
|
||||
private static S3Destination destination(String bucketArn, String compressionFormat) {
|
||||
S3Destination s3 = new S3Destination();
|
||||
s3.setBucketArn(bucketArn);
|
||||
@@ -125,13 +170,18 @@ class FirehoseServiceTest {
|
||||
}
|
||||
|
||||
private Delivered delivered(String expectedBucket) {
|
||||
return delivered(expectedBucket, 1);
|
||||
}
|
||||
|
||||
/** The most recent of exactly {@code attempts} S3 writes. */
|
||||
private Delivered delivered(String expectedBucket, int attempts) {
|
||||
ArgumentCaptor<String> bucket = ArgumentCaptor.forClass(String.class);
|
||||
ArgumentCaptor<String> key = ArgumentCaptor.forClass(String.class);
|
||||
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
|
||||
ArgumentCaptor<String> contentType = ArgumentCaptor.forClass(String.class);
|
||||
ArgumentCaptor<PutObjectOptions> options = ArgumentCaptor.forClass(PutObjectOptions.class);
|
||||
verify(s3Service).putObject(bucket.capture(), key.capture(), body.capture(), contentType.capture(),
|
||||
anyMap(), options.capture());
|
||||
verify(s3Service, times(attempts)).putObject(bucket.capture(), key.capture(), body.capture(),
|
||||
contentType.capture(), anyMap(), options.capture());
|
||||
assertEquals(expectedBucket, bucket.getValue());
|
||||
return new Delivered(key.getValue(), body.getValue(), contentType.getValue(),
|
||||
options.getValue().getContentEncoding());
|
||||
@@ -673,6 +723,154 @@ class FirehoseServiceTest {
|
||||
assertEquals("hello\n", delivered("sink").text());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedDeliveryRestoresTheBatchAheadOfRecordsAddedDuringDelivery() {
|
||||
firehoseService.createDeliveryStream("retry-stream", destination("arn:aws:s3:::sink", null));
|
||||
firehoseService.putRecord("retry-stream", new Record("first".getBytes(StandardCharsets.UTF_8)));
|
||||
firehoseService.putRecord("retry-stream", new Record("second".getBytes(StandardCharsets.UTF_8)));
|
||||
AtomicBoolean s3Down = new AtomicBoolean(true);
|
||||
when(s3Service.putObject(anyString(), anyString(), any(byte[].class), anyString(),
|
||||
anyMap(), any(PutObjectOptions.class))).thenAnswer(invocation -> {
|
||||
if (s3Down.getAndSet(false)) {
|
||||
firehoseService.putRecord("retry-stream", new Record("third".getBytes(StandardCharsets.UTF_8)));
|
||||
throw new RuntimeException("s3 unavailable");
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
firehoseService.flush("retry-stream");
|
||||
firehoseService.flush("retry-stream");
|
||||
|
||||
assertEquals("first\nsecond\nthird\n", delivered("sink", 2).text());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestoredBatchIsRetriedOnTheNextScheduledFlush() {
|
||||
firehoseService.createDeliveryStream("retry-stream", destination("arn:aws:s3:::sink", null));
|
||||
firehoseService.putRecord("retry-stream", new Record("first".getBytes(StandardCharsets.UTF_8)));
|
||||
AtomicBoolean s3Down = new AtomicBoolean(true);
|
||||
when(s3Service.putObject(anyString(), anyString(), any(byte[].class), anyString(),
|
||||
anyMap(), any(PutObjectOptions.class))).thenAnswer(invocation -> {
|
||||
if (s3Down.getAndSet(false)) {
|
||||
// A record arrives while the write is in flight; it must not push the
|
||||
// restored batch's buffering start forward.
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
firehoseService.putRecord("retry-stream", new Record("second".getBytes(StandardCharsets.UTF_8)));
|
||||
throw new RuntimeException("s3 unavailable");
|
||||
}
|
||||
return null;
|
||||
});
|
||||
clock.advance(Duration.ofSeconds(300));
|
||||
firehoseService.flushDueBuffers(clock.instant());
|
||||
verify(s3Service, times(1)).putObject(anyString(), anyString(), any(byte[].class), anyString(),
|
||||
anyMap(), any(PutObjectOptions.class));
|
||||
|
||||
clock.advance(Duration.ofSeconds(10));
|
||||
firehoseService.flushDueBuffers(clock.instant());
|
||||
|
||||
assertEquals("first\nsecond\n", delivered("sink", 2).text());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSuccessfulDeliveryClearsOnlyTheRecordsItWrote() {
|
||||
firehoseService.createDeliveryStream("keep-stream", destination("arn:aws:s3:::sink", null));
|
||||
firehoseService.putRecord("keep-stream", new Record("first".getBytes(StandardCharsets.UTF_8)));
|
||||
AtomicBoolean firstWrite = new AtomicBoolean(true);
|
||||
when(s3Service.putObject(anyString(), anyString(), any(byte[].class), anyString(),
|
||||
anyMap(), any(PutObjectOptions.class))).thenAnswer(invocation -> {
|
||||
if (firstWrite.getAndSet(false)) {
|
||||
firehoseService.putRecord("keep-stream", new Record("second".getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
firehoseService.flush("keep-stream");
|
||||
assertEquals("first\n", delivered("sink").text());
|
||||
|
||||
firehoseService.flush("keep-stream");
|
||||
assertEquals("second\n", delivered("sink", 2).text());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLaterFlushCannotCommitItsCheckpointWhileAnEarlierBatchIsUnresolved() throws Exception {
|
||||
// A spy, so one poll can be parked between reading its page and buffering it.
|
||||
firehoseService = newService(0, Mockito::spy);
|
||||
createSourcedDeliveryStream("sourced-stream", "src-stream");
|
||||
kinesisService.putRecord("src-stream", "first".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
|
||||
firehoseService.pollKinesisSources();
|
||||
|
||||
// The first S3 write parks until released and then fails, like a slow S3 that
|
||||
// eventually answers with an error. Later writes succeed.
|
||||
CountDownLatch firstWriteStarted = new CountDownLatch(1);
|
||||
CountDownLatch releaseFirstWrite = new CountDownLatch(1);
|
||||
AtomicBoolean firstWrite = new AtomicBoolean(true);
|
||||
when(s3Service.putObject(anyString(), anyString(), any(byte[].class), anyString(),
|
||||
anyMap(), any(PutObjectOptions.class))).thenAnswer(invocation -> {
|
||||
if (firstWrite.getAndSet(false)) {
|
||||
firstWriteStarted.countDown();
|
||||
releaseFirstWrite.await();
|
||||
throw new RuntimeException("s3 unavailable");
|
||||
}
|
||||
return null;
|
||||
});
|
||||
// The next poll parks once it has read its page, before it buffers the records
|
||||
// and advances the pending checkpoint past them.
|
||||
kinesisService.putRecord("src-stream", "second".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
|
||||
CountDownLatch pollRead = new CountDownLatch(1);
|
||||
CountDownLatch resumePoll = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
Object page = invocation.callRealMethod();
|
||||
pollRead.countDown();
|
||||
resumePoll.await();
|
||||
return page;
|
||||
}).when(kinesisService).getRecordsForAccount(anyString(), anyString(), any(), anyString());
|
||||
|
||||
ExecutorService pool = Executors.newFixedThreadPool(3);
|
||||
try {
|
||||
// P reads "second" from the position "first" was polled to, then parks.
|
||||
Future<?> poll = pool.submit(firehoseService::pollKinesisSources);
|
||||
assertTrue(pollRead.await(2, TimeUnit.SECONDS), "the poll must read its page");
|
||||
// A takes "first" with its checkpoint and parks inside the S3 write.
|
||||
Future<?> flushA = pool.submit(() -> firehoseService.flush("sourced-stream"));
|
||||
assertTrue(firstWriteStarted.await(2, TimeUnit.SECONDS), "flush A must reach its S3 write");
|
||||
// P buffers "second" and leaves a checkpoint past both records pending.
|
||||
resumePoll.countDown();
|
||||
poll.get(2, TimeUnit.SECONDS);
|
||||
// B finds "second" buffered while A still owes "first" to S3.
|
||||
AtomicReference<Thread> bThread = new AtomicReference<>();
|
||||
Future<?> flushB = pool.submit(() -> {
|
||||
bThread.set(Thread.currentThread());
|
||||
firehoseService.flush("sourced-stream");
|
||||
});
|
||||
awaitParkedOrDone(bThread, flushB);
|
||||
|
||||
// Committing B's checkpoint now would persist a position past "first" while
|
||||
// "first" is not durable: a restart before A's retry would skip it forever.
|
||||
assertTrue(durableCheckpoint("sourced-stream").isEmpty(),
|
||||
"no checkpoint may be committed while an earlier batch is unresolved");
|
||||
verify(s3Service, times(1)).putObject(anyString(), anyString(), any(byte[].class), anyString(),
|
||||
anyMap(), any(PutObjectOptions.class));
|
||||
assertThrows(TimeoutException.class, () -> flushB.get(500, TimeUnit.MILLISECONDS),
|
||||
"a later flush must wait for the earlier batch to resolve");
|
||||
|
||||
releaseFirstWrite.countDown();
|
||||
flushA.get(2, TimeUnit.SECONDS);
|
||||
flushB.get(2, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
// A's failure hands "first" back ahead of "second"; B then delivers both.
|
||||
assertEquals("first\nsecond\n", delivered("sink", 2).text());
|
||||
|
||||
// Restart: the committed checkpoint covers exactly what reached S3, so nothing
|
||||
// is re-read and nothing is skipped.
|
||||
firehoseService = newService(0);
|
||||
firehoseService.pollKinesisSources();
|
||||
firehoseService.flush("sourced-stream");
|
||||
verify(s3Service, times(2)).putObject(anyString(), anyString(), any(byte[].class), anyString(),
|
||||
anyMap(), any(PutObjectOptions.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMissingSourceStreamDoesNotStopOtherStreamsFromPolling() {
|
||||
// No createStream for "gone-stream": describeStream throws ResourceNotFound.
|
||||
|
||||
Reference in new issue
Block a user