mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 14:30:28 -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
@@ -1083,6 +1083,22 @@ public interface EmulatorConfig {
|
||||
interface FirehoseServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
/**
|
||||
* How often the buffer flusher checks for streams whose buffering
|
||||
* interval (BufferingHints.IntervalInSeconds) has elapsed.
|
||||
*/
|
||||
@WithDefault("10")
|
||||
long tickIntervalSeconds();
|
||||
|
||||
/**
|
||||
* Emulator-only volume trigger: number of buffered records that forces
|
||||
* an immediate flush, complementing the stream's BufferingHints.
|
||||
* Disabled by default (0) so out-of-the-box delivery matches real AWS;
|
||||
* set to 1 for LocalStack-style record-at-a-time delivery in local dev.
|
||||
*/
|
||||
@WithDefault("0")
|
||||
int flushRecordCount();
|
||||
}
|
||||
|
||||
interface KmsServiceConfig {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.firehose;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -11,37 +12,114 @@ import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescript
|
||||
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.s3.S3Service;
|
||||
import io.quarkus.runtime.ShutdownDelayInitiatedEvent;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@ApplicationScoped
|
||||
public class FirehoseService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(FirehoseService.class);
|
||||
private static final String DEFAULT_BUCKET = "floci-firehose-results";
|
||||
private static final int DEFAULT_FLUSH_COUNT = 5;
|
||||
private static final int DEFAULT_BUFFERING_INTERVAL_SECONDS = 300;
|
||||
private static final int DEFAULT_BUFFERING_SIZE_MBS = 5;
|
||||
|
||||
private final StorageBackend<String, DeliveryStreamDescription> streamStore;
|
||||
private final Map<String, List<byte[]>> buffers = new ConcurrentHashMap<>();
|
||||
private final Map<String, Instant> bufferSince = new ConcurrentHashMap<>();
|
||||
private final S3Service s3Service;
|
||||
private final RegionResolver regionResolver;
|
||||
private final Clock clock;
|
||||
private final long tickIntervalSeconds;
|
||||
private final int flushRecordCount;
|
||||
private final boolean flusherEnabled;
|
||||
private final ScheduledExecutorService flushExecutor;
|
||||
|
||||
@Inject
|
||||
public FirehoseService(StorageFactory storageFactory, S3Service s3Service, RegionResolver regionResolver,
|
||||
Clock clock) {
|
||||
Clock clock, EmulatorConfig config) {
|
||||
this.streamStore = storageFactory.create("firehose", "streams.json",
|
||||
new TypeReference<Map<String, DeliveryStreamDescription>>() {});
|
||||
this.s3Service = s3Service;
|
||||
this.regionResolver = regionResolver;
|
||||
this.clock = clock;
|
||||
this.tickIntervalSeconds = Math.max(1, config.services().firehose().tickIntervalSeconds());
|
||||
this.flushRecordCount = Math.max(0, config.services().firehose().flushRecordCount());
|
||||
this.flusherEnabled = config.services().firehose().enabled();
|
||||
this.flushExecutor = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "firehose-buffer-flusher");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
}
|
||||
|
||||
void onStart(@Observes StartupEvent ignored) {
|
||||
if (!flusherEnabled) {
|
||||
LOG.info("Firehose buffer flusher disabled by configuration");
|
||||
return;
|
||||
}
|
||||
flushExecutor.scheduleAtFixedRate(this::tickSafely, tickIntervalSeconds, tickIntervalSeconds, TimeUnit.SECONDS);
|
||||
LOG.infov("Firehose buffer flusher started (tick every {0}s)", tickIntervalSeconds);
|
||||
}
|
||||
|
||||
// ShutdownDelayInitiatedEvent fires before every ShutdownEvent observer, so this
|
||||
// drain lands the pending records in S3 while EmulatorLifecycle.onStop can still
|
||||
// persist them to disk via storageFactory.flushAll().
|
||||
void onPreShutdown(@Observes ShutdownDelayInitiatedEvent ignored) {
|
||||
flushExecutor.shutdownNow();
|
||||
buffers.keySet().forEach(this::flush);
|
||||
}
|
||||
|
||||
void tickSafely() {
|
||||
try {
|
||||
flushDueBuffers(clock.instant());
|
||||
} catch (Throwable t) {
|
||||
LOG.warnv("Firehose buffer flush tick failed: {0}", t.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
void flushDueBuffers(Instant now) {
|
||||
for (Map.Entry<String, List<byte[]>> entry : buffers.entrySet()) {
|
||||
if (entry.getValue().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
String streamName = entry.getKey();
|
||||
try {
|
||||
DeliveryStreamDescription stream = describeDeliveryStream(streamName);
|
||||
Instant since = bufferSince.putIfAbsent(streamName, now);
|
||||
if (since == null) {
|
||||
since = now;
|
||||
}
|
||||
if (!now.isBefore(since.plusSeconds(bufferingIntervalSeconds(stream)))) {
|
||||
flush(streamName, stream);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Firehose buffer flush failed for stream {0}: {1}", streamName, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int bufferingIntervalSeconds(DeliveryStreamDescription stream) {
|
||||
S3Destination s3 = stream.s3Destination();
|
||||
// describeDeliveryStream already applied defaults, so hints only miss
|
||||
// when the stream has no S3 destination at all (default-bucket delivery).
|
||||
if (s3 == null || s3.getBufferingHints() == null || s3.getBufferingHints().getIntervalInSeconds() == null) {
|
||||
return DEFAULT_BUFFERING_INTERVAL_SECONDS;
|
||||
}
|
||||
return s3.getBufferingHints().getIntervalInSeconds();
|
||||
}
|
||||
|
||||
public String createDeliveryStream(String name, S3Destination s3Config) {
|
||||
@@ -219,7 +297,11 @@ public class FirehoseService {
|
||||
public void deleteDeliveryStream(String name) {
|
||||
describeDeliveryStream(name);
|
||||
streamStore.delete(name);
|
||||
// Pending records are discarded, not flushed: verified against real AWS
|
||||
// (2026-07-13, eu-west-1) — 3 records buffered under a 300s/5MB hint never
|
||||
// reached the bucket after DeleteDeliveryStream completed.
|
||||
buffers.remove(name);
|
||||
bufferSince.remove(name);
|
||||
LOG.infov("Deleted Firehose delivery stream: {0}", name);
|
||||
}
|
||||
|
||||
@@ -229,27 +311,41 @@ public class FirehoseService {
|
||||
}
|
||||
|
||||
public void putRecord(String streamName, Record record) {
|
||||
DeliveryStreamDescription stream = describeDeliveryStream(streamName);
|
||||
buffers.computeIfAbsent(streamName, k -> Collections.synchronizedList(new ArrayList<>()))
|
||||
.add(record.getData());
|
||||
|
||||
if (buffers.get(streamName).size() >= DEFAULT_FLUSH_COUNT) {
|
||||
flush(streamName, stream);
|
||||
}
|
||||
putRecordBatch(streamName, List.of(record));
|
||||
}
|
||||
|
||||
public void putRecordBatch(String streamName, List<Record> records) {
|
||||
DeliveryStreamDescription stream = describeDeliveryStream(streamName);
|
||||
List<byte[]> buffer = buffers.computeIfAbsent(
|
||||
streamName, k -> Collections.synchronizedList(new ArrayList<>()));
|
||||
for (Record r : records) {
|
||||
buffer.add(r.getData());
|
||||
long bufferedBytes = 0;
|
||||
int bufferedCount;
|
||||
// Records and their buffering-start timestamp move together under the
|
||||
// buffer lock so the flusher never sees one without the other.
|
||||
synchronized (buffer) {
|
||||
for (Record r : records) {
|
||||
buffer.add(r.getData());
|
||||
}
|
||||
bufferSince.putIfAbsent(streamName, clock.instant());
|
||||
bufferedCount = buffer.size();
|
||||
for (byte[] data : buffer) {
|
||||
bufferedBytes += data.length;
|
||||
}
|
||||
}
|
||||
if (buffer.size() >= DEFAULT_FLUSH_COUNT) {
|
||||
if ((flushRecordCount > 0 && bufferedCount >= flushRecordCount)
|
||||
|| bufferedBytes >= bufferingSizeLimitBytes(stream)) {
|
||||
flush(streamName, stream);
|
||||
}
|
||||
}
|
||||
|
||||
private static long bufferingSizeLimitBytes(DeliveryStreamDescription stream) {
|
||||
S3Destination s3 = stream.s3Destination();
|
||||
int sizeInMBs = (s3 == null || s3.getBufferingHints() == null || s3.getBufferingHints().getSizeInMBs() == null)
|
||||
? DEFAULT_BUFFERING_SIZE_MBS
|
||||
: s3.getBufferingHints().getSizeInMBs();
|
||||
return sizeInMBs * 1024L * 1024L;
|
||||
}
|
||||
|
||||
public void flush(String streamName) {
|
||||
streamStore.get(streamName).ifPresent(stream -> flush(streamName, stream));
|
||||
}
|
||||
@@ -264,6 +360,11 @@ public class FirehoseService {
|
||||
synchronized (buffer) {
|
||||
toFlush = new ArrayList<>(buffer);
|
||||
buffer.clear();
|
||||
bufferSince.remove(streamName);
|
||||
}
|
||||
if (toFlush.isEmpty()) {
|
||||
// Lost the race against a concurrent flush; nothing left to deliver.
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
Reference in new issue
Block a user