Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(lambda): event source mappings pick up new work at once (#2082)
Antonie Popovicc95ba3d26ff5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0b602fba..4d43e4e9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -27,6 +27,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **Lambda — event source mappings pick up new work at once** — a new SQS message, Kinesis record or DynamoDB stream record now wakes the poller instead of waiting for its idle tick, cutting the delay from send to invocation from 0.75 s to about 4 ms.- **TLS — the generated certificate works with rustls** — it was a CA certificate, which rustls refuses as a server's (`CaUsedAsEndEntity`). It is now a server certificate (`CA:FALSE`, `serverAuth`), and a cached CA certificate is regenerated.- **Lambda — preserve invocation aliases in runtime context** — `Invoke` retains the requested alias or version in `invoked_function_arn`, while `function_version` remains the resolved published version. Warm workers receive invocation identity per request. Contributed by @jayjanssen.- **IoT — `DescribeCertificate` reports `certificateMode`** — the field was missing from the description. It is now `SNI_ONLY` for a certificate registered with `RegisterCertificateWithoutCA` and `DEFAULT` for the others, as AWS reports it. Contributed by @iot-rocket.diff --git a/ministack/core/concurrency.py b/ministack/core/concurrency.pyindex 46a79550..d8bbeac8 100644--- a/ministack/core/concurrency.py+++ b/ministack/core/concurrency.py@@ -190,6 +190,12 @@ async def run_reentrant(fn, *args, thread_name: str = "ministack-reentrant"):raise cancellation+# Set by every producer of event-source work (an SQS message, a Kinesis record, a+# DynamoDB stream record), so the Lambda ESM poller picks it up at once instead of+# on its idle tick.+esm_wake = threading.Event()++def spawn_background(fn, *args, thread_name: str = "ministack-background", **kwargs):"""Start named fire-and-forget work with its exceptions logged.diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.pyindex a376a8da..cac844c7 100644--- a/ministack/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -32,7 +32,7 @@ from collections import defaultdictfrom decimal import Decimal, InvalidOperationfrom ministack.core.arn import ArnParseError, parse_arn-from ministack.core.concurrency import spawn_background+from ministack.core.concurrency import esm_wake, spawn_backgroundfrom ministack.core.responses import (AccountRegionScopedDict,AccountScopedDict,@@ -736,6 +736,7 @@ def _emit_stream_event(table_name: str, event_name: str, old_item: dict | None,if table_name not in _stream_records:_stream_records[table_name] = []_stream_records[table_name].append(record)+ esm_wake.set()_trim_stream_records(table_name)if has_kinesis:diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.pyindex deba4c36..53012b5a 100644--- a/ministack/services/eventbridge.py+++ b/ministack/services/eventbridge.py@@ -40,6 +40,7 @@ import urllib.requestfrom datetime import datetime, timedelta, timezonefrom ministack.core.arn import ArnParseError, parse_arn+from ministack.core.concurrency import esm_wakefrom ministack.core.responses import (AccountRegionScopedDict,AccountScopedDict,@@ -2497,6 +2498,7 @@ def _dispatch_to_sqs(spec, payload, sqs_parameters=None):queue["messages"].append(msg)if hasattr(_sqs, "_ensure_msg_fields"):_sqs._ensure_msg_fields(queue["messages"][-1])+ esm_wake.set()logger.info("EventBridge → SQS %s", queue_name)diff --git a/ministack/services/kinesis.py b/ministack/services/kinesis.pyindex cbf4d238..d87b05f8 100644--- a/ministack/services/kinesis.py+++ b/ministack/services/kinesis.py@@ -25,6 +25,7 @@ import timeimport zlibfrom ministack.core.arn import ArnParseError, parse_arn+from ministack.core.concurrency import esm_wakefrom ministack.core.responses import (AccountRegionScopedDict,AccountScopedDict,@@ -337,6 +338,7 @@ def put_record_internal(stream_arn: str, partition_key: str, data: bytes) -> boo"Data": base64.b64encode(data).decode("ascii"),"PartitionKey": partition_key,})+ esm_wake.set()return True@@ -635,6 +637,7 @@ def _put_record(data):"Data": record_data,"PartitionKey": partition_key,})+ esm_wake.set()# Fan out to any Firehose delivery stream configured with this Kinesis# stream as its source. Best-effort, must not break this PutRecord.@@ -714,6 +717,7 @@ def _put_records(data):except Exception:raw = rd.encode() if isinstance(rd, str) else rdfanout_pairs.append((pk, raw))+ esm_wake.set()# Fan out the whole batch to any Firehose delivery stream configured with# this Kinesis stream as its source. Best-effort, must not break PutRecords.diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 9bcb6ba7..a0587aaf 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -51,7 +51,7 @@ from urllib.parse import quote, unquotefrom ministack.core import container_reaperfrom ministack.core.arn import ArnParseError, parse_arn-from ministack.core.concurrency import run_reentrant, spawn_background+from ministack.core.concurrency import esm_wake, run_reentrant, spawn_backgroundfrom ministack.core.lambda_runtime import (DURABLE_ENV_VARS,INVOKE_DEPTH_BOOTSTRAP,@@ -3772,6 +3772,7 @@ def _route_async_failure(target_arn: str, func_name: str, event: dict, result: d"group_id": None, "dedup_id": None,"dedup_cache_key": None, "seq": None,})+ esm_wake.set()returnelif spec.service == "sns":import ministack.services.sns as _sns@@ -7198,8 +7199,8 @@ _ESM_SQS_DEFAULT_CONCURRENCY = 5# esm_uuid -> dispatched batches not yet finished._esm_inflight: dict[str, int] = {}_esm_inflight_lock = threading.Lock()-# Set when a dispatched batch finishes, so _poll_loop refills the slot at once.-_esm_wake = threading.Event()+# Set when a dispatched batch finishes or a source gains work, so _poll_loop acts at once.+_esm_wake = esm_wakedef _sqs_esm_concurrency(esm: dict, func_rec: dict, config: dict, queue: dict | None = None) -> int:@@ -7266,8 +7267,13 @@ def _ensure_poller():_poller_started = True+# A wake that found nothing (another tenant's traffic, an unmapped source) delays the next wake by this much.+_ESM_IDLE_WAKE_GAP_SECONDS = 0.05++def _poll_loop():"""Background thread: polls SQS/Kinesis/DynamoDB for active ESMs and invokes Lambda."""+ idle_wake = Falsewhile True:processed = False_esm_wake.clear()@@ -7287,7 +7293,11 @@ def _poll_loop():# immediately rather than waiting out the idle cadence below, so# throughput isn't throttled to batch_size-per-tick.if not processed:- _esm_wake.wait(1 if _esms.has_any() else 5)+ if idle_wake:+ time.sleep(_ESM_IDLE_WAKE_GAP_SECONDS)+ idle_wake = bool(_esm_wake.wait(1 if _esms.has_any() else 5))+ else:+ idle_wake = Falsedef _iter_all_esms():@@ -7684,6 +7694,7 @@ def _send_ddb_stream_failure_record(esm, func_rec, batch, stream_arn, result, co"sys": {"SenderId": get_account_id(), "SentTimestamp": str(int(now * 1000))},"group_id": None, "dedup_id": None, "dedup_cache_key": None, "seq": None,})+ esm_wake.set()elif spec.service == "sns":import ministack.services.sns as _snsif dest in _sns._topics:diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex ead12378..55081899 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -55,6 +55,7 @@ from xml.sax.saxutils import escape as _escfrom defusedxml.ElementTree import fromstringfrom ministack.core.arn import ArnParseError, parse_arn+from ministack.core.concurrency import esm_wakefrom ministack.core.iam_evaluator import (AmbiguousAccessKeyError,CredentialResolutionError,@@ -3638,6 +3639,7 @@ def _deliver_event_to_sqs(arn: str, event_payload: dict, bucket_region: str,}_sqs._ensure_msg_fields(msg)queue["messages"].append(msg)+ esm_wake.set()logger.info("S3 notification → SQS %s", queue_name)diff --git a/ministack/services/sns.py b/ministack/services/sns.pyindex 2bd32a5d..3f638fa7 100644--- a/ministack/services/sns.py+++ b/ministack/services/sns.py@@ -35,6 +35,7 @@ _PORT = os.environ.get("GATEWAY_PORT", "4566")import ministack.services.lambda_svc as _lambda_svcfrom ministack.core.arn import ArnParseError, parse_arn+from ministack.core.concurrency import esm_wakefrom ministack.core.responses import AccountRegionScopedDict, get_account_id, get_region, new_uuid, request_scopefrom ministack.services import sqs as _sqs@@ -1298,6 +1299,7 @@ def _deliver_to_sqs(endpoint: str, envelope: str, raw: bool, raw_message: str,msg["dedup_id"] = message_dedup_id_sqs._ensure_msg_fields(msg)queue["messages"].append(msg)+ esm_wake.set()logger.info("SNS fanout → SQS %s", queue_name)diff --git a/ministack/services/sqs.py b/ministack/services/sqs.pyindex 969f7294..de00622f 100644--- a/ministack/services/sqs.py+++ b/ministack/services/sqs.py@@ -39,6 +39,7 @@ from urllib.parse import parse_qs, urlparsefrom xml.sax.saxutils import escape as _escfrom ministack.core.arn import ArnParseError, parse_arn+from ministack.core.concurrency import esm_wakefrom ministack.core.responses import AccountRegionScopedDict, get_account_id, get_region, new_uuidfrom ministack.core.tls import use_ssl_enabled@@ -706,6 +707,7 @@ def _act_send_message(data: dict, qurl: str) -> dict:"seq": seq,}q["messages"].append(msg)+ esm_wake.set()if q["is_fifo"] and dedup_id:q["dedup_cache"][dedup_cache_key] = {@@ -818,6 +820,8 @@ def _act_change_visibility(data: dict, qurl: str) -> dict:breakif not found:raise _Err("ReceiptHandleIsInvalid", "The input receipt handle is invalid.")+ if vt == 0:+ esm_wake.set()return {}@@ -881,6 +885,8 @@ def _act_change_visibility_batch(data: dict, qurl: str) -> dict:breakif found:ok.append({"Id": eid})+ if vt == 0:+ esm_wake.set()else:fail.append({"Id": eid,@@ -1334,6 +1340,7 @@ def _dlq_sweep(q: dict) -> None:moved["receipt_handle"] = Nonemoved["visible_at"] = nowdlq["messages"].append(moved)+ esm_wake.set()else:keep.append(m)q["messages"] = keepdiff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex c7f2773a..df8348da 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -14284,6 +14284,53 @@ while True:assert result["result"] == arn[email protected]("source", ["sqs", "sqs-visibility", "dynamodb", "kinesis"])+def test_new_event_source_work_wakes_poll_loop(esm_poll_state, source):+ """New work for an event source is picked up at once, not on the poller's idle tick."""+ _lsvc, _sqs, _kin, _ddb = esm_poll_state+ if source == "sqs":+ _sqs._queues[_sqs._queue_url("wake-q")] = {"name": "wake-q", "messages": [], "attributes": {}, "is_fifo": False,+ "dedup_cache": {}, "fifo_seq": 0}+ produce = lambda: _sqs._act_send_message({"MessageBody": "x"}, _sqs._queue_url("wake-q")) # noqa: E731+ elif source == "sqs-visibility":+ url = _sqs_esm_fixture(_lsvc, _sqs, "wake-v")+ _sqs._queues[url]["messages"][0]["receipt_handle"] = "rh"+ produce = lambda: _sqs._act_change_visibility({"ReceiptHandle": "rh", "VisibilityTimeout": "0"}, url) # noqa: E731+ elif source == "dynamodb":+ _ddb._create_table({"TableName": "wake-t", "BillingMode": "PAY_PER_REQUEST",+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],+ "StreamSpecification": {"StreamEnabled": True, "StreamViewType": "NEW_IMAGE"}})+ produce = lambda: _ddb._put_item({"TableName": "wake-t", "Item": {"pk": {"S": "1"}}}) # noqa: E731+ else:+ _kin._create_stream({"StreamName": "wake-s", "ShardCount": 1})+ _kin._streams["wake-s"]["StreamStatus"] = "ACTIVE"+ produce = lambda: _kin._put_record({"StreamName": "wake-s", "PartitionKey": "k", "Data": "eA=="}) # noqa: E731+ _lsvc._esm_wake.clear()+ produce()+ assert _lsvc._esm_wake.is_set()+++def test_poll_loop_paces_wakes_that_find_nothing(esm_poll_state, monkeypatch):+ """Traffic the poller has no mapping for must not keep it scanning back to back."""+ waits, sleeps = [], []++ def fake_wait(secs):+ waits.append(secs)+ if len(waits) > 2:+ raise _StopPollLoop()+ return True++ monkeypatch.setattr(lsvc, "_poll_sqs", lambda: False)+ monkeypatch.setattr(lsvc, "_poll_kinesis", lambda: False)+ monkeypatch.setattr(lsvc, "_poll_dynamodb_streams", lambda: False)+ monkeypatch.setattr(lsvc._esm_wake, "wait", fake_wait)+ monkeypatch.setattr(lsvc.time, "sleep", sleeps.append)+ with pytest.raises(_StopPollLoop):+ lsvc._poll_loop()+ assert sleeps == [lsvc._ESM_IDLE_WAKE_GAP_SECONDS] * 2++@pytest.mark.parametrize("runtime", ["python3.12", "nodejs20.x"])@pytest.mark.parametrize("asynchronous", [False, True])def test_invocation_retains_alias_without_mutating_version(monkeypatch, asynchronous, runtime):