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
feat(lambda): support ScalingConfig on SQS event source mappings (#1029)
Liam Mizrahi3ec7b634f478
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fa65dd72..514d7f55 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Added+- **Lambda — event source mappings accept and persist `ScalingConfig` (`MaximumConcurrency`)** — `CreateEventSourceMapping` and `UpdateEventSourceMapping` now accept a `ScalingConfig` block and echo it back on create, `GetEventSourceMapping`, and `ListEventSourceMappings`, so the SQS-trigger `scaling_config { maximum_concurrency = N }` on the Terraform `aws_lambda_event_source_mapping` resource round-trips instead of being silently dropped (which surfaced as a perpetual plan diff). `MaximumConcurrency` outside the AWS-valid 2–1000 range is rejected with `ValidationException`. `BatchSize` and `MaximumBatchingWindowInSeconds` were already supported. Contributed by @liammizrahi.- **Organizations — `ListParents` + tag ops for the OU Terraform round-trip** — adds `ListParents(ChildId)` (returns the single parent AWS reports — `{"Parents": [{"Id", "Type"}]}`, `Type=ROOT` for the org root else `ORGANIZATIONAL_UNIT` — from the `_ParentId` already stored on every OU and account; unknown `ChildId` → `ChildNotFoundException`) **and** `TagResource` / `UntagResource` / `ListTagsForResource` for taggable org resources. The Terraform/OpenTofu `aws_organizations_organizational_unit` Read calls **both** `ListParents` (to populate `parent_id`, which `DescribeOrganizationalUnit` omits) and `ListTagsForResource` on every create + refresh — even for an untagged OU. With either missing, `apply` hard-stops on the read-back (`InvalidAction: Operation '<op>' not implemented`), so a multi-OU hierarchy never finished creating and was never idempotent; with both, it applies cleanly and re-applies as a no-op. No new state. Closes #990.### Fixed- **CloudTrail — `CreateTrail` persists `KmsKeyId`** — `CreateTrail` accepted `KmsKeyId` but dropped it (only `UpdateTrail` stored it), so `DescribeTrails`/`GetTrail` read it back empty and Terraform's `aws_cloudtrail` did not converge in a single apply: the first `plan` after `apply` showed a `kms_key_id` diff that only cleared on a second apply (via `UpdateTrail`). `CreateTrail` now stores and returns `KmsKeyId`, normalized to a full key ARN as real AWS echoes it (a bare key id is expanded; an ARN or `alias/...` is kept), and omits the field when no CMK is set so an unset trail shows no diff. `UpdateTrail` normalizes it the same way and likewise omits it from its response when unset. Contributed by @b-rajesh.diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 3adb034c..45fbc0c3 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -4544,7 +4544,34 @@ def _esm_response(esm: dict) -> dict:return {k: v for k, v in esm.items() if k not in ("FunctionName", "Enabled")}+def _validate_scaling_config(data: dict):+ scaling = data.get("ScalingConfig")+ if not scaling:+ return None+ max_conc = scaling.get("MaximumConcurrency")+ if max_conc is None:+ return None+ if max_conc < 2:+ return error_response_json(+ "ValidationException",+ f"1 validation error detected: Value '{max_conc}' at 'scalingConfig.maximumConcurrency' "+ "failed to satisfy constraint: Member must have value greater than or equal to 2",+ 400,+ )+ if max_conc > 1000:+ return error_response_json(+ "ValidationException",+ f"1 validation error detected: Value '{max_conc}' at 'scalingConfig.maximumConcurrency' "+ "failed to satisfy constraint: Member must have value less than or equal to 1000",+ 400,+ )+ return None++def _create_esm(data: dict):+ err = _validate_scaling_config(data)+ if err:+ return erresm_id = new_uuid()# Preserve the alias/version qualifier if the caller supplied one so# poller invocations route to the correct target (#407).@@ -4574,6 +4601,8 @@ def _create_esm(data: dict):_init_stream_position(esm_id, event_source_arn, esm["StartingPosition"])if data.get("FilterCriteria"):esm["FilterCriteria"] = data.get("FilterCriteria")+ if data.get("ScalingConfig"):+ esm["ScalingConfig"] = data["ScalingConfig"]# #442: Tags are accepted on CreateEventSourceMapping. Stored inline on# the ESM record; surfaced via _list_tags for the ESM ARN.tags = data.get("Tags") or {}@@ -4629,6 +4658,9 @@ def _update_esm(esm_id: str, data: dict):f"Event source mapping not found: {esm_id}",404,)+ err = _validate_scaling_config(data)+ if err:+ return errfor key in ("BatchSize","MaximumBatchingWindowInSeconds",@@ -4639,6 +4671,7 @@ def _update_esm(esm_id: str, data: dict):"ParallelizationFactor","DestinationConfig","FilterCriteria",+ "ScalingConfig",):if key in data:esm[key] = data[key]diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex bddb52e3..9ed8c66e 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -413,6 +413,119 @@ def test_lambda_esm_sqs_comprehensive(lam, sqs):lam.delete_event_source_mapping(UUID=esm_uuid)+def test_lambda_esm_scaling_config_round_trip(lam, sqs):+ try:+ lam.delete_function(FunctionName="esm-scaling-func")+ except ClientError:+ pass++ lam.create_function(+ FunctionName="esm-scaling-func",+ Runtime="python3.12",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip("def handler(event, context):\n return {}\n")},+ )+ q_url = sqs.create_queue(QueueName="esm-scaling-queue")["QueueUrl"]+ q_arn = sqs.get_queue_attributes(+ QueueUrl=q_url, AttributeNames=["QueueArn"],+ )["Attributes"]["QueueArn"]++ resp = lam.create_event_source_mapping(+ EventSourceArn=q_arn,+ FunctionName="esm-scaling-func",+ BatchSize=5,+ MaximumBatchingWindowInSeconds=20,+ ScalingConfig={"MaximumConcurrency": 7},+ Enabled=True,+ )+ esm_uuid = resp["UUID"]+ assert resp["ScalingConfig"] == {"MaximumConcurrency": 7}+ assert resp["MaximumBatchingWindowInSeconds"] == 20++ got = lam.get_event_source_mapping(UUID=esm_uuid)+ assert got["ScalingConfig"] == {"MaximumConcurrency": 7}++ listed = lam.list_event_source_mappings(FunctionName="esm-scaling-func")+ entry = next(e for e in listed["EventSourceMappings"] if e["UUID"] == esm_uuid)+ assert entry["ScalingConfig"] == {"MaximumConcurrency": 7}++ updated = lam.update_event_source_mapping(+ UUID=esm_uuid, ScalingConfig={"MaximumConcurrency": 50},+ )+ assert updated["ScalingConfig"] == {"MaximumConcurrency": 50}++ lam.delete_event_source_mapping(UUID=esm_uuid)++def test_lambda_esm_no_scaling_config_omits_field(lam, sqs):+ try:+ lam.delete_function(FunctionName="esm-noscaling-func")+ except ClientError:+ pass++ lam.create_function(+ FunctionName="esm-noscaling-func",+ Runtime="python3.12",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip("def handler(event, context):\n return {}\n")},+ )+ q_url = sqs.create_queue(QueueName="esm-noscaling-queue")["QueueUrl"]+ q_arn = sqs.get_queue_attributes(+ QueueUrl=q_url, AttributeNames=["QueueArn"],+ )["Attributes"]["QueueArn"]++ resp = lam.create_event_source_mapping(+ EventSourceArn=q_arn, FunctionName="esm-noscaling-func", BatchSize=5,+ )+ assert "ScalingConfig" not in resp++ lam.delete_event_source_mapping(UUID=resp["UUID"])+[email protected]("bad_value", [1, 1001])+def test_lambda_esm_scaling_config_out_of_range_rejected(lam, sqs, bad_value):+ import urllib.error+ import urllib.request++ try:+ lam.delete_function(FunctionName="esm-badscaling-func")+ except ClientError:+ pass++ lam.create_function(+ FunctionName="esm-badscaling-func",+ Runtime="python3.12",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip("def handler(event, context):\n return {}\n")},+ )+ q_url = sqs.create_queue(QueueName="esm-badscaling-queue")["QueueUrl"]+ q_arn = sqs.get_queue_attributes(+ QueueUrl=q_url, AttributeNames=["QueueArn"],+ )["Attributes"]["QueueArn"]++ payload = json.dumps({+ "EventSourceArn": q_arn,+ "FunctionName": "esm-badscaling-func",+ "ScalingConfig": {"MaximumConcurrency": bad_value},+ }).encode()+ req = urllib.request.Request(+ f"{_endpoint}/2015-03-31/event-source-mappings",+ data=payload,+ headers={+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/lambda/aws4_request",+ "Content-Type": "application/json",+ },+ method="POST",+ )+ try:+ urllib.request.urlopen(req)+ assert False, "Expected a ValidationException error response"+ except urllib.error.HTTPError as e:+ assert e.code == 400+ body = json.loads(e.read())+ assert body.get("__type") == "ValidationException", body+def test_lambda_esm_filter_criteria_stored_on_create(lam, sqs):"""FilterCriteria specified at CreateEventSourceMapping must be echoedback by GetEventSourceMapping — it was silently dropped before this fix."""