Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(firehose): fanout s3 (#746)

Nahuel Nucera7512af82d2e6
diff --git a/ministack/services/firehose.py b/ministack/services/firehose.py
index d8b4aa1a..b99b94d9 100644
--- a/ministack/services/firehose.py
+++ b/ministack/services/firehose.py
@@ -239,6 +239,58 @@ def _record_id() -> str:
return f"{ts:020d}{uid}"
+# ─── Kinesis-source ingestion ────────────────────────────────────────────────
+# Public hook called by kinesis.py whenever PutRecord / PutRecords lands a
+# record. For any ACTIVE delivery stream whose Source is configured to the
+# Kinesis stream ARN, the record is forwarded to the configured destination
+# (currently S3 / ExtendedS3 — others buffer in-memory the same way the
+# direct PutRecord path does).
+#
+# AWS parity notes:
+# - AWS only forwards records that arrived at or after the delivery stream's
+# DeliveryStartTimestamp. Records older than that are skipped, matching
+# how the AWS shard iterator opens at that timestamp.
+# - Delivery is best-effort (any S3 / runtime error is logged and swallowed)
+# so a Firehose problem can never break the Kinesis write path.
+# - The `records` argument is a list of `(partition_key, raw_bytes)` tuples;
+# `raw_bytes` is the already-decoded record payload (matches what AWS would
+# read off the Kinesis shard).
+def ingest_from_kinesis_source(stream_arn: str, records: list) -> None:
+ if not stream_arn or not records:
+ return
+ now_ts = now_epoch()
+ with _lock:
+ targets = [
+ s for s in _streams.values()
+ if s.get("type") == "KinesisStreamAsSource"
+ and s.get("status") == "ACTIVE"
+ and (s.get("kinesis_source") or {}).get("KinesisStreamARN") == stream_arn
+ ]
+ # Snapshot delivery targets so the lock can be released before we
+ # schedule S3 writes (which dispatch on the event loop and should
+ # never run under this lock).
+ plan = []
+ for stream in targets:
+ start_ts = (stream.get("kinesis_source") or {}).get("DeliveryStartTimestamp") or 0
+ if now_ts < start_ts:
+ continue
+ for dest in stream.get("destinations", []):
+ if dest.get("type") not in ("ExtendedS3", "S3"):
+ continue
+ for _pkey, raw in records:
+ rid = _record_id()
+ dest["records"].append({"id": rid, "data": raw, "ts": now_ts})
+ plan.append((stream, dest, raw))
+ for stream, dest, raw in plan:
+ try:
+ _deliver_to_s3(stream, dest, raw)
+ except Exception as exc:
+ logger.warning(
+ "Firehose Kinesis-source delivery to %s failed: %s",
+ stream.get("name"), exc,
+ )
+
+
# ─── operations ──────────────────────────────────────────────────────────────
def _create_delivery_stream(data: dict):
diff --git a/ministack/services/kinesis.py b/ministack/services/kinesis.py
index dddbb641..a2f5aba5 100644
--- a/ministack/services/kinesis.py
+++ b/ministack/services/kinesis.py
@@ -444,6 +444,7 @@ def _put_record(data):
return error_response_json("ValidationException",
"1 validation error detected: Value at 'partitionKey' failed to satisfy constraint: "
"Member must have length less than or equal to 256", 400)
+ raw = b""
if record_data:
try:
raw = base64.b64decode(record_data)
@@ -464,6 +465,17 @@ def _put_record(data):
"Data": record_data,
"PartitionKey": partition_key,
})
+
+ # Fan out to any Firehose delivery stream configured with this Kinesis
+ # stream as its source. Best-effort, must not break this PutRecord.
+ try:
+ from ministack.services import firehose as _firehose
+ _firehose.ingest_from_kinesis_source(
+ stream["StreamARN"], [(partition_key, raw)],
+ )
+ except Exception:
+ logger.exception("Firehose fan-out from Kinesis PutRecord failed")
+
return json_response({
"ShardId": shard_id,
"SequenceNumber": seq,
@@ -508,6 +520,7 @@ def _put_records(data):
"Records total payload size exceeds 5 MB limit", 400)
results = []
+ fanout_pairs = []
for rec in records:
pk = rec.get("PartitionKey", "")
rd = rec.get("Data", "")
@@ -526,6 +539,20 @@ def _put_records(data):
"ShardId": sid,
"EncryptionType": stream.get("EncryptionType", "NONE"),
})
+ try:
+ raw = base64.b64decode(rd) if rd else b""
+ except Exception:
+ raw = rd.encode() if isinstance(rd, str) else rd
+ fanout_pairs.append((pk, raw))
+
+ # Fan out the whole batch to any Firehose delivery stream configured with
+ # this Kinesis stream as its source. Best-effort, must not break PutRecords.
+ try:
+ from ministack.services import firehose as _firehose
+ _firehose.ingest_from_kinesis_source(stream["StreamARN"], fanout_pairs)
+ except Exception:
+ logger.exception("Firehose fan-out from Kinesis PutRecords failed")
+
return json_response({
"FailedRecordCount": 0,
"Records": results,
diff --git a/tests/test_firehose.py b/tests/test_firehose.py
index 640774f7..5a322da7 100644
--- a/tests/test_firehose.py
+++ b/tests/test_firehose.py
@@ -332,3 +332,56 @@ def test_firehose_describe_nonexistent_carries_errortype(fh):
fh.describe_delivery_stream(DeliveryStreamName="missing-fh")
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
assert exc.value.response["ResponseMetadata"]["HTTPHeaders"].get("x-amzn-errortype") == "ResourceNotFoundException"
+
+
+def test_firehose_kinesis_stream_as_source_fans_out_to_s3(fh, kin, s3):
+ """KinesisStreamAsSource: records put into the source Kinesis stream
+ must reach the configured S3 destination. Issue #744."""
+ import base64 as _b64, time as _time, uuid as _uuid
+ stream_name = f"src-stream-{_uuid.uuid4().hex[:8]}"
+ delivery_name = f"fh-{_uuid.uuid4().hex[:8]}"
+ bucket = f"fh-src-bucket-{_uuid.uuid4().hex[:8]}"
+ s3.create_bucket(Bucket=bucket)
+ try:
+ kin.create_stream(StreamName=stream_name, ShardCount=1)
+ stream_arn = kin.describe_stream(
+ StreamName=stream_name)["StreamDescription"]["StreamARN"]
+ fh.create_delivery_stream(
+ DeliveryStreamName=delivery_name,
+ DeliveryStreamType="KinesisStreamAsSource",
+ KinesisStreamSourceConfiguration={
+ "KinesisStreamARN": stream_arn,
+ "RoleARN": "arn:aws:iam::000000000000:role/test",
+ },
+ ExtendedS3DestinationConfiguration={
+ "RoleARN": "arn:aws:iam::000000000000:role/test",
+ "BucketARN": f"arn:aws:s3:::{bucket}",
+ "Prefix": "out/",
+ "CompressionFormat": "UNCOMPRESSED",
+ },
+ )
+ # Single PutRecord.
+ kin.put_record(
+ StreamName=stream_name, PartitionKey="pk", Data=b'{"a":1}')
+ # Batch PutRecords.
+ kin.put_records(StreamName=stream_name, Records=[
+ {"PartitionKey": "pk1", "Data": b'{"a":2}'},
+ {"PartitionKey": "pk2", "Data": b'{"a":3}'},
+ ])
+ for _ in range(20):
+ objs = s3.list_objects_v2(Bucket=bucket, Prefix="out/").get("Contents", [])
+ if len(objs) >= 3:
+ break
+ _time.sleep(0.1)
+ objs = s3.list_objects_v2(Bucket=bucket, Prefix="out/").get("Contents", [])
+ assert len(objs) >= 3, f"expected 3 records delivered to S3, got {len(objs)}"
+ bodies = sorted(
+ s3.get_object(Bucket=bucket, Key=o["Key"])["Body"].read()
+ for o in objs
+ )
+ assert bodies == [b'{"a":1}', b'{"a":2}', b'{"a":3}']
+ finally:
+ try: fh.delete_delivery_stream(DeliveryStreamName=delivery_name)
+ except Exception: pass
+ try: kin.delete_stream(StreamName=stream_name)
+ except Exception: pass