Skip to content

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

Prerelease/v1.5.23b (#2092)

Nahuel Nucera9f780a255f8f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 31c130d3..a18679d6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,11 +9,18 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
+- **DynamoDB — multi-attribute GSI keys** — a GSI whose `KeySchema` has several `HASH` or `RANGE` attributes now indexes items by all of them. `Query` needs equality on every partition-key attribute and takes sort-key attributes left to right, only the last with a range condition (`ValidationException` "Query key condition not supported" otherwise); `LastEvaluatedKey` carries every key attribute. Reported by @jun-ut.
+- **SES v2 — dedicated IP pools** — `CreateDedicatedIpPool`, `GetDedicatedIpPool`, `ListDedicatedIpPools` and `DeleteDedicatedIpPool`, with pool tags on `arn:aws:ses:<region>:<account>:dedicated-ip-pool/<name>`. Reported by @wparad.
- **API Gateway v1 — `AWS` integrations targeting SQS** — non-proxy integrations whose URI names `sqs:path/{account}/{queue}` now reach the queue: the matching `requestTemplates` entry is rendered with the `$input.body`, `$input.json('<json-path>')`, `$input.params('<name>')` and `$util.urlEncode(...)` subset (a request with no matching template passes its body through as the form-encoded Query call), the rendered `Action` dispatch runs against the queue's own account and region, and the backend reply or error flows through `integrationResponses` — `selectionPattern` matched against the backend status code, else the default response, else 500 `Internal server error` — including `responseTemplates` and `method.response.header.*` parameters. A `SendMessage` reply reaches the response template as SQS's JSON envelope (`SendMessageResponse.SendMessageResult`). Other `AWS` service URIs still take the Lambda path. Contributed by @pingedbrain.
- **AppConfig — gradual rollout and alarm rollback** — deployments used to complete as soon as they started. They now move through `DEPLOYING`, `BAKING` and `COMPLETE` on the strategy's schedule, and `PercentageComplete`, `EventLog` and the environment `State` follow along. A CloudWatch alarm in the environment's `Monitors` that goes to `ALARM` before the bake ends rolls the deployment back. Starting a deployment while another is in progress, or with a stale `LatestDeploymentNumber`, returns `ConflictException`. Each configuration session switches to the new version once the rollout reaches it, so a fleet of AppConfig Agent sidecars picks it up gradually. Strategy minutes are real minutes, as on AWS; a strategy with no duration and no bake completes as it starts. Contributed by @Jolley71717.
### Fixed
+- **SES — `SendEmail` checks addresses and the configuration set** — an address without a domain returns `InvalidParameterValue` "Missing final '@domain'", and an unknown `ConfigurationSetName` returns `ConfigurationSetDoesNotExist` carrying the `ConfigurationSetName` field. Contributed by @DimQ1.
+- **S3 — re-creating a bucket you own** — outside us-east-1 it returns `BucketAlreadyOwnedByYou` (409) "The bucket you tried to create already exists, and you own it."; in us-east-1 it returns 200 and resets the bucket ACL. Contributed by @DimQ1.
+- **SNS — published messages are no longer kept** — every publish was stored on its topic and persisted, growing without bound; SNS has no API that reads them back. Contributed by @DimQ1.
+- **SQS — queue `DelaySeconds` applies to messages from other services** — deliveries from SNS, EventBridge, S3 notifications and Lambda destinations and DLQs were visible at once. Contributed by @DimQ1.
+- **S3 — truncated uploads return `IncompleteBody`** — a body shorter than its `Content-Length` or a malformed `aws-chunked` upload was stored as a partial object; it now returns `IncompleteBody` (400) "You did not provide the number of bytes specified by the Content-Length HTTP header." `/_ministack/sqs/messages?queue_url=` matches the queue by account and name, so any form of the URL works. Contributed by @DimQ1.
- **Step Functions — retry `StopExecution` after an abort** — an already-aborted execution now returns its original stop date instead of `ValidationException`. A retry preserves the first error/cause and emits no duplicate abort event.
- **Gateway**: reject malformed request-body and aws-chunked framing; preserve account-isolated SQS diagnostic aliases and tombstone-aware peeking.
@@ -35,11 +42,17 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Fixed
+- **DynamoDB — index Query and write cost no longer grow with table size** — a `Query` on a GSI or LSI read every item in the table, and every write recounted the table. Index partitions and `ItemCount` are now maintained per write. Contributed by @DimQ1.
+- **DynamoDB — `ClientRequestToken` expires after 10 minutes** — `TransactWriteItems` and `ExecuteTransaction` tokens were kept forever; after 10 minutes a reused token is now a new request, and expired tokens are released. Contributed by @DimQ1.
+- **DynamoDB Streams — no record for a write that changes nothing** — a `PutItem` or `UpdateItem` leaving the item unchanged wrote a `MODIFY` record. Contributed by @DimQ1.
+- **DynamoDB Streams — closed streams stay readable for 24 hours** — disabling a stream or deleting its table made it vanish, and re-enabling handed the new stream the old records. The closed stream now describes as `DISABLED` with an `EndingSequenceNumber`, its records stay readable, and `GetRecords` omits `NextShardIterator` once the shard is drained. `GetRecords` records no longer carry `eventSourceARN`. Contributed by @DimQ1.
+- **CloudWatch — `Values`/`Counts` and `StatisticValues` aggregate correctly** — `Values` were stored once per count and a statistic set as its average, so `SampleCount`, `Sum`, `Minimum` and `Maximum` were wrong; the Query protocol dropped both. Percentiles are no longer returned for a period with a negative value or with a statistic set that is not one repeated value, and `GetMetricStatistics` now honours `ExtendedStatistics`. Contributed by @DimQ1.
+- **SQS — FIFO delays and `MaxNumberOfMessages`** — FIFO queues ignored their `DelaySeconds` and accepted any per-message delay. A FIFO message now waits the queue delay, and a nonzero per-message `DelaySeconds` returns `InvalidParameterValue` "Value N for parameter DelaySeconds is invalid. Reason: The request include parameter that is not valid for this queue type." An explicit `DelaySeconds=0` on a standard queue now overrides the queue delay. `ReceiveMessage` with `MaxNumberOfMessages` outside 1-10 returns `InvalidParameterValue` "Value N for parameter MaxNumberOfMessages is invalid. Reason: Must be between 1 and 10, if provided." instead of clamping. Contributed by @DimQ1.
- **Lambda — invocation IDs and Docker logs** — one request ID is propagated to Docker RIE, warm/local Python and Node.js, and provided runtimes. RIE output is identified by executor metadata and saved without a second START / END / REPORT sequence. Other executors and empty RIE output retain synthetic platform logs.
- **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.
-- **Cognito — `RESET_REQUIRED` users cannot sign in with a password** — after `AdminResetUserPassword`, `InitiateAuth` `USER_PASSWORD_AUTH`, `AdminInitiateAuth` `ADMIN_USER_PASSWORD_AUTH` / `ADMIN_NO_SRP_AUTH` and `USER_SRP_AUTH` still accepted the old password. They now return `PasswordResetRequiredException`, checked next to `UserNotConfirmedException`. Contributed by @prandogabriel.
+- **Cognito — `RESET_REQUIRED` users cannot sign in with a password** — after `AdminResetUserPassword`, password and SRP sign-in with the correct password return `PasswordResetRequiredException`; a wrong password is still `NotAuthorizedException`. Contributed by @prandogabriel.
- **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.
### Fixed
diff --git a/ministack/app.py b/ministack/app.py
index 05f2c123..969d34f4 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -568,6 +568,8 @@ def _get_reset_lock() -> asyncio.Lock:
class _IncompleteRequestBody(Exception):
"""The request body ended before its declared framing was complete."""
+ body = b""
+
class _RequestBodyDisconnected(Exception):
"""The client disconnected before the request body was complete."""
@@ -722,19 +724,25 @@ async def _read_request_body(receive, method: str, headers: dict) -> bytes:
if content_length is not None:
content_length = content_length.strip()
if not re.fullmatch(r"[0-9]+", content_length) or len(body) != int(content_length):
- raise _IncompleteRequestBody("Content-Length does not match request body")
- return _decode_aws_chunked_body(body, headers)
+ exc = _IncompleteRequestBody("Content-Length does not match request body")
+ exc.body = body
+ raise exc
+ try:
+ return _decode_aws_chunked_body(body, headers)
+ except _IncompleteRequestBody as exc:
+ exc.body = body
+ raise
def _incomplete_request_body_response(method: str, path: str, headers: dict, query_params: dict):
- """Use the routed protocol's existing error envelope for an incomplete body."""
- message = "You did not provide the number of bytes specified by the Content-Length HTTP header"
- service = detect_service(method, path, headers, query_params)
- if service == "s3":
- return _get_module("s3")._error("IncompleteBody", message, 400)
- from ministack.core.responses import error_response_json
-
- return error_response_json("IncompleteBody", message, 400)
+ """S3's IncompleteBody; None for other services, which have no such error."""
+ if detect_service(method, path, headers, query_params) != "s3":
+ return None
+ return _get_module("s3")._error(
+ "IncompleteBody",
+ "You did not provide the number of bytes specified by the Content-Length HTTP header.",
+ 400,
+ )
def _encode_header_value(v: str) -> bytes:
@@ -1146,8 +1154,6 @@ async def _handle_sqs_messages_request(method: str, path: str, headers: dict, qu
msgs = queue.get("messages") or []
rendered = []
for m in msgs:
- if m is None:
- continue
rendered.append(
{
"MessageId": m.get("id"),
@@ -2883,10 +2889,12 @@ async def app(scope, receive, send):
body = await _read_request_body(receive, method, headers)
except _RequestBodyDisconnected:
return
- except _IncompleteRequestBody:
+ except _IncompleteRequestBody as exc:
response = _incomplete_request_body_response(method, path, headers, query_params)
- await _send_if_handled(send, response, receive)
- return
+ if response is not None:
+ await _send_if_handled(send, response, receive)
+ return
+ body = exc.body
if await _send_if_handled(
send, await _handle_post_body_shortcuts(method, path, headers, body, query_params, request_id), receive
diff --git a/ministack/services/appsync.py b/ministack/services/appsync.py
index 665a7bcb..dcb9ed50 100644
--- a/ministack/services/appsync.py
+++ b/ministack/services/appsync.py
@@ -2433,21 +2433,21 @@ def _ddb_put_item(table, table_name, args):
if not isinstance(table["items"], defaultdict):
table["items"] = defaultdict(dict, table["items"])
- table["items"][pk_val][sk_val] = ddb_item
- table["ItemCount"] = sum(len(v) for v in table["items"].values())
+ _ddb._set_item(table, pk_val, sk_val, ddb_item)
return _strip_ddb_types(ddb_item, [])
def _ddb_update_item(table, table_name, args):
"""Update an existing item — merge input fields."""
+ import ministack.services.dynamodb as _ddb
input_data = args.get("input", args)
pk_name = table["pk_name"]
pk_val = str(input_data.get("id") or input_data.get(pk_name, ""))
if pk_val in table["items"]:
sk = next(iter(table["items"][pk_val]), "")
- existing = table["items"][pk_val].get(sk, {})
+ existing = dict(table["items"][pk_val].get(sk, {}))
for k, v in input_data.items():
if isinstance(v, str):
existing[k] = {"S": v}
@@ -2455,21 +2455,22 @@ def _ddb_update_item(table, table_name, args):
existing[k] = {"N": str(v)}
elif isinstance(v, bool):
existing[k] = {"BOOL": v}
+ if sk in table["items"][pk_val]:
+ _ddb._set_item(table, pk_val, sk, existing)
return _strip_ddb_types(existing, [])
return None
def _ddb_delete_item(table, table_name, args):
"""Delete an item and return it."""
+ import ministack.services.dynamodb as _ddb
input_data = args.get("input", args)
pk_name = table["pk_name"]
pk_val = str(input_data.get("id") or input_data.get(pk_name, ""))
if pk_val in table["items"]:
sk = next(iter(table["items"][pk_val]), "")
- item = table["items"][pk_val].pop(sk, None)
- if not table["items"][pk_val]:
- table["items"].pop(pk_val, None)
+ item = _ddb._remove_item(table, pk_val, sk)
if item:
return _strip_ddb_types(item, [])
return None
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 81dd1e2c..bb84d605 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -1663,7 +1663,6 @@ def _sns_create(logical_id, props, stack_name):
}),
},
"subscriptions": [],
- "messages": [],
"tags": _tag_map(props.get("Tags")),
}
@@ -1936,8 +1935,7 @@ def _ddb_create(logical_id, props, stack_name):
def _ddb_delete(physical_id, props):
- _dynamodb._tables.pop(physical_id, None)
- _dynamodb.drop_stream_records(physical_id)
+ _dynamodb.drop_stream_records(physical_id, _dynamodb._tables.pop(physical_id, None))
def _ddb_update_call(data):
diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.py
index 8c817d51..40e1acb3 100644
--- a/ministack/services/cloudwatch.py
+++ b/ministack/services/cloudwatch.py
@@ -194,57 +194,87 @@ def _evict_old_metrics():
# ---------------------------------------------------------------------------
-def _calc_stats(values):
- if not values:
+def _point_stats(pt):
+ """(SampleCount, Sum, Minimum, Maximum) of one stored point: a value seen
+ ``Count`` times, or a published statistic set."""
+ sv = pt.get("_stat")
+ if sv is not None:
+ return (float(sv.get("SampleCount", 0)), float(sv.get("Sum", 0)),
+ float(sv.get("Minimum", 0)), float(sv.get("Maximum", 0)))
+ count = float(pt.get("Count", 1.0))
+ return count, pt["Value"] * count, pt["Value"], pt["Value"]
+
+
+def _calc_stats(points):
+ parts = [_point_stats(p) for p in points]
+ parts = [p for p in parts if p[0] > 0]
+ if not parts:
return {}
+ count = sum(p[0] for p in parts)
+ total = sum(p[1] for p in parts)
return {
- "SampleCount": float(len(values)),
- "Sum": sum(values),
- "Average": sum(values) / len(values),
- "Minimum": min(values),
- "Maximum": max(values),
+ "SampleCount": count,
+ "Sum": total,
+ "Average": total / count,
+ "Minimum": min(p[2] for p in parts),
+ "Maximum": max(p[3] for p in parts),
}
-def _percentile(values, pct):
- """Extended-statistic percentile of values (0-100), computes the way
- that CloudWatch documents it: sort ascending and linearly interpolate
- between the two nearest ranks.
+def _percentile_samples(points):
+ """(value, weight) samples for percentiles, or None when CloudWatch has
+ none: any negative value, or a statistic set that is not a single
+ repeated value ("Min and Max are equal, and Sum is equal to Min
+ multiplied by SampleCount", or SampleCount 1 with Min, Max, Sum equal)."""
+ samples = []
+ for pt in points:
+ count, total, low, high = _point_stats(pt)
+ if count <= 0:
+ continue
+ if pt.get("_stat") is not None and not (low == high and total == low * count):
+ return None
+ if low < 0:
+ return None
+ samples.append((low, count))
+ return samples or None
+
+
+def _percentile(samples, pct):
+ """Extended-statistic percentile (0-100) of weighted samples: sort
+ ascending and linearly interpolate between the two nearest ranks, as if
+ each value appeared ``weight`` times (numpy's default "linear" method)."""
+ ordered = sorted(samples)
+ total = sum(w for _, w in ordered)
+ rank = (pct / 100.0) * (total - 1) if total > 1 else 0.0
+
+ def at(index):
+ seen = 0.0
+ for value, weight in ordered:
+ seen += weight
+ if index < seen:
+ return value
+ return ordered[-1][0]
- Matches e.g. numpy's default ("linear") interpolation method."""
- if not values:
- return 0
- ordered = sorted(values)
- n = len(ordered)
- if n == 1:
- return ordered[0]
- rank = (pct / 100.0) * (n - 1)
lower = int(rank)
- upper = min(lower + 1, n - 1)
frac = rank - lower
- return ordered[lower] + frac * (ordered[upper] - ordered[lower])
+ low = at(lower)
+ return low + frac * (at(lower + 1) - low) if frac else low
def _is_percentile_stat(stat_name):
return bool(stat_name) and stat_name[0] in ("p", "P") and stat_name[1:].replace(".", "", 1).isdigit()
-def _stat_value(stats, stat_name, values=None):
+def _stat_value(stats, stat_name, points=None):
"""Extract a single statistic. stat_name is either a basic statistic name
already present in stats (Average/Sum/Minimum/Maximum/SampleCount) or an
- extended-statistic percentile (e.g. "p95", "p99.9"), computed from the raw
- sample values for this period via _percentile.
-
- Falls back to Average if values are not available (e.g. callers that only
- have pre-aggregated stats, not the raw samples) so behavior degrades
- gracefully rather than raising.
- """
+ extended-statistic percentile (e.g. "p95", "p99.9") computed from the
+ period's points; None when the percentile is not available for them."""
if stat_name in stats:
return stats[stat_name]
if _is_percentile_stat(stat_name):
- if values:
- return _percentile(values, float(stat_name[1:]))
- return stats.get("Average", 0)
+ samples = _percentile_samples(points or [])
+ return _percentile(samples, float(stat_name[1:])) if samples else None
return stats.get("Average", 0)
@@ -273,12 +303,13 @@ def _evaluate_alarm(alarm):
if not recent:
return
- recent_values = [p["Value"] for p in recent]
- stats = _calc_stats(recent_values)
+ stats = _calc_stats(recent)
# an alarm is configured with either Statistic (basic) or ExtendedStatistic (percentile),
# never both thus prefer whichever is set.
stat_name = alarm.get("ExtendedStatistic") or alarm.get("Statistic", "Average")
- val = _stat_value(stats, stat_name, recent_values)
+ val = _stat_value(stats, stat_name, recent)
+ if val is None:
+ return
threshold = alarm.get("Threshold", 0)
op = alarm.get("ComparisonOperator", "")
@@ -531,6 +562,30 @@ async def handle_request(method, path, headers, body, query_params):
# ---------------------------------------------------------------------------
+def _p_list(params, prefix):
+ out = []
+ while _p(params, f"{prefix}.member.{len(out) + 1}"):
+ out.append(float(_p(params, f"{prefix}.member.{len(out) + 1}")))
+ return out
+
+
+def _store_datum(namespace, name, dims, ts, unit, value, values, counts, stat_values):
+ """Store one MetricDatum: each of ``Values`` once per its ``Counts`` entry
+ (default 1), a statistic set as published, or a single ``Value``."""
+ bucket = _metric_bucket((namespace, name, _dims_key(dims)))
+ base = {"Timestamp": ts, "Unit": unit, "Dimensions": dims}
+ if values is not None:
+ counts = counts or [1.0] * len(values)
+ for v, c in zip(values, counts):
+ bucket.append({**base, "Value": float(v), "Count": float(c)})
+ elif stat_values is not None:
+ count = float(stat_values.get("SampleCount", 0))
+ bucket.append({**base, "Value": float(stat_values.get("Sum", 0)) / count if count else 0.0,
+ "_stat": stat_values})
+ else:
+ bucket.append({**base, "Value": float(value or 0)})
+
+
def _put_metric_data(params, cbor_data, is_cbor, is_json=False):
if is_cbor or is_json:
namespace = cbor_data.get("Namespace", "")
@@ -538,40 +593,11 @@ def _put_metric_data(params, cbor_data, is_cbor, is_json=False):
mn = md.get("MetricName", "")
dims = {d["Name"]: d["Value"] for d in md.get("Dimensions", [])}
- if "Values" in md:
- values = md["Values"]
- counts = md.get("Counts", [1.0] * len(values))
- for v, c in zip(values, counts):
- for _ in range(int(c)):
- _metric_bucket((namespace, mn, _dims_key(dims))).append(
- {
- "Timestamp": _parse_ts(md.get("Timestamp"))
- or time.time(),
- "Value": float(v),
- "Unit": md.get("Unit", "None"),
- "Dimensions": dims,
- }
- )
- elif "StatisticValues" in md:
- sv = md["StatisticValues"]
- _metric_bucket((namespace, mn, _dims_key(dims))).append(
- {
- "Timestamp": _parse_ts(md.get("Timestamp")) or time.time(),
- "Value": sv.get("Sum", 0) / max(sv.get("SampleCount", 1), 1),
- "Unit": md.get("Unit", "None"),
- "Dimensions": dims,
- "_stat": sv,
- }
- )
- else:
- _metric_bucket((namespace, mn, _dims_key(dims))).append(
- {
- "Timestamp": _parse_ts(md.get("Timestamp")) or time.time(),
- "Value": float(md.get("Value", 0)),
- "Unit": md.get("Unit", "None"),
- "Dimensions": dims,
- }
- )
+ _store_datum(
+ namespace, mn, dims, _parse_ts(md.get("Timestamp")) or time.time(),
+ md.get("Unit", "None"), md.get("Value"), md.get("Values"),
+ md.get("Counts"), md.get("StatisticValues"),
+ )
else:
namespace = _p(params, "Namespace")
i = 1
@@ -588,14 +614,15 @@ def _put_metric_data(params, cbor_data, is_cbor, is_json=False):
_p(params, f"MetricData.member.{i}.Dimensions.member.{j}.Name")
] = _p(params, f"MetricData.member.{i}.Dimensions.member.{j}.Value")
j += 1
- _metric_bucket((namespace, mn, _dims_key(dims))).append(
- {
- "Timestamp": ts,
- "Value": value,
- "Unit": unit,
- "Dimensions": dims,
- }
- )
+ values = _p_list(params, f"MetricData.member.{i}.Values")
+ counts = _p_list(params, f"MetricData.member.{i}.Counts")
+ sv = {
+ k: float(_p(params, f"MetricData.member.{i}.StatisticValues.{k}"))
+ for k in ("SampleCount", "Sum", "Minimum", "Maximum")
+ if _p(params, f"MetricData.member.{i}.StatisticValues.{k}")
+ }
+ _store_datum(namespace, mn, dims, ts, unit, value, values or None,
+ counts or None, sv or None)
i += 1
_evaluate_all_alarms()
@@ -688,6 +715,7 @@ def _get_metric_statistics(params, cbor_data, is_cbor, is_json=False):
start_time = _parse_ts(cbor_data.get("StartTime"))
end_time = _parse_ts(cbor_data.get("EndTime"))
req_stats = cbor_data.get("Statistics", [])
+ req_extended = cbor_data.get("ExtendedStatistics", [])
req_dims = _dims_from_list(cbor_data.get("Dimensions") or [])
else:
namespace = _p(params, "Namespace")
@@ -707,8 +735,11 @@ def _get_metric_statistics(params, cbor_data, is_cbor, is_json=False):
while _p(params, f"Statistics.member.{si}"):
req_stats.append(_p(params, f"Statistics.member.{si}"))
si += 1
+ req_extended = []
+ while _p(params, f"ExtendedStatistics.member.{len(req_extended) + 1}"):
+ req_extended.append(_p(params, f"ExtendedStatistics.member.{len(req_extended) + 1}"))
- if not req_stats:
+ if not req_stats and not req_extended:
req_stats = ["SampleCount", "Sum", "Average", "Minimum", "Maximum"]
all_points = []
@@ -727,12 +758,12 @@ def _get_metric_statistics(params, cbor_data, is_cbor, is_json=False):
buckets = defaultdict(list)
for pt in all_points:
bucket_ts = int(pt["Timestamp"] // period) * period
- buckets[bucket_ts].append(pt["Value"])
+ buckets[bucket_ts].append(pt)
datapoints = []
for ts in sorted(buckets):
- vals = buckets[ts]
- stats = _calc_stats(vals)
+ pts = buckets[ts]
+ stats = _calc_stats(pts)
dp = {
"Timestamp": _ts_iso(ts),
"Unit": all_points[0]["Unit"] if all_points else "None",
@@ -740,6 +771,13 @@ def _get_metric_statistics(params, cbor_data, is_cbor, is_json=False):
for s in req_stats:
if s in stats:
dp[s] = stats[s]
+ extended = {}
+ for s in req_extended:
+ v = _stat_value(stats, s, pts) if _is_percentile_stat(s) else None
+ if v is not None:
+ extended[s] = v
+ if extended:
+ dp["ExtendedStatistics"] = extended
datapoints.append(dp)
if is_cbor:
@@ -877,15 +915,17 @@ def _get_metric_data(params, cbor_data, is_cbor, is_json=False):
buckets = defaultdict(list)
for pt in all_pts:
- buckets[int(pt["Timestamp"] // period) * period].append(pt["Value"])
+ buckets[int(pt["Timestamp"] // period) * period].append(pt)
timestamps = []
values = []
for ts in sorted(buckets):
- bucket_values = buckets[ts]
- stats = _calc_stats(bucket_values)
+ bucket_pts = buckets[ts]
+ value = _stat_value(_calc_stats(bucket_pts), stat_name, bucket_pts)
+ if value is None:
+ continue
timestamps.append(_ts_iso(ts))
- values.append(_stat_value(stats, stat_name, bucket_values))
+ values.append(value)
if return_data:
results.append(
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index d8667400..9f842b37 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -3808,9 +3808,6 @@ def _initiate_user_srp_auth(pool: dict, pid: str, cid: str, auth_params: dict):
return error_response_json("NotAuthorizedException", "User is disabled.", 400)
if user.get("UserStatus") == "UNCONFIRMED":
return error_response_json("UserNotConfirmedException", "User is not confirmed.", 400)
- if user.get("UserStatus") == "RESET_REQUIRED":
- return error_response_json("PasswordResetRequiredException",
- "Password reset required for the user", 400)
user_id = user["Username"]
token, session = _create_challenge_session(pid, cid, user_id)
session["auth_flow"] = "USER_SRP_AUTH"
@@ -3850,6 +3847,8 @@ def _respond_to_password_verifier(data: dict, cid: str):
refused = _password_signin_refused(user)
if refused:
return refused
+ if user.get("UserStatus") == "RESET_REQUIRED":
+ return _password_reset_required()
client_metadata = data.get("ClientMetadata", {})
if not custom:
return _password_auth_result(pool, session["pool_id"], cid, user, user["Username"],
@@ -3892,14 +3891,14 @@ def _admin_initiate_auth(data):
# user is refused as disabled first (measured).
if user.get("UserStatus") == "UNCONFIRMED":
return error_response_json("UserNotConfirmedException", "User is not confirmed.", 400)
- if user.get("UserStatus") == "RESET_REQUIRED":
- return error_response_json("PasswordResetRequiredException",
- "Password reset required for the user", 400)
refused = _password_signin_refused(user)
if refused:
return refused
if user.get("_password") and user["_password"] != password:
return error_response_json("NotAuthorizedException", "Incorrect username or password.", 400)
+ # Only a correct password learns that a reset is required.
+ if user.get("UserStatus") == "RESET_REQUIRED":
+ return _password_reset_required()
return _password_auth_result(pool, pid, cid, user, username)
if auth_flow == "USER_SRP_AUTH":
@@ -4200,14 +4199,14 @@ def _initiate_auth(data):
# user is refused as disabled first (measured).
if user.get("UserStatus") == "UNCONFIRMED":
return error_response_json("UserNotConfirmedException", "User is not confirmed.", 400)
- if user.get("UserStatus") == "RESET_REQUIRED":
- return error_response_json("PasswordResetRequiredException",
- "Password reset required for the user", 400)
refused = _password_signin_refused(user)
if refused:
return refused
if user.get("_password") and user["_password"] != password:
return error_response_json("NotAuthorizedException", "Incorrect username or password.", 400)
+ # Only a correct password learns that a reset is required.
+ if user.get("UserStatus") == "RESET_REQUIRED":
+ return _password_reset_required()
return _password_auth_result(pool, pid, cid, user, username)
if auth_flow in ("REFRESH_TOKEN_AUTH", "REFRESH_TOKEN"):
@@ -5207,6 +5206,10 @@ def _admin_link_provider_for_user(data):
return json_response({})
+def _password_reset_required():
+ return error_response_json("PasswordResetRequiredException", "Password reset required for the user", 400)
+
+
def _password_signin_refused(user):
"""The refusal a password sign-in draws for a provider-deactivated local user.
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index cac844c7..d347655e 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -116,8 +116,12 @@ _lock = threading.Lock()
# ── Persistence ────────────────────────────────────────────
def get_state():
+ tables = AccountRegionScopedDict()
+ for (account_id, region, table_name), table in _tables.all_items():
+ tables.set_scoped(account_id, region, table_name, copy.deepcopy(
+ {k: v for k, v in table.items() if k != _INDEX_MEMBERS}))
return {
- "tables": copy.deepcopy(_tables),
+ "tables": tables,
"tags": copy.deepcopy(_tags),
"ttl_settings": copy.deepcopy(_ttl_settings),
"pitr_settings": copy.deepcopy(_pitr_settings),
@@ -662,9 +666,55 @@ def stream_live_records(table_name: str, *, account_id=None, region=None) -> lis
return _live_stream_records(table_name, account_id, region)
-def drop_stream_records(table_name: str) -> None:
- _stream_records.pop(table_name, None)
- _stream_trimmed.pop(table_name, None)
+# Streams closed by disabling them or deleting their table, by stream ARN.
+# "If you disable a stream on a table, the data in the stream continues to be
+# readable for 24 hours."
+_closed_streams = AccountRegionScopedDict()
+
+
+def _sweep_closed_streams() -> None:
+ cutoff = time.time() - _STREAM_RETENTION_SECONDS
+ for (account_id, region, arn), closed in _closed_streams.all_items():
+ if closed["ClosedAt"] < cutoff:
+ _closed_streams.pop_scoped(account_id, region, arn, None)
+
+
+def closed_stream(stream_arn: str) -> dict | None:
+ """The closed stream ``stream_arn`` with its unexpired records, or None."""
+ _sweep_closed_streams()
+ closed = _closed_streams.get(stream_arn)
+ if closed is None:
+ return None
+ records = closed["records"]
+ cutoff = time.time() - _STREAM_RETENTION_SECONDS
+ expired = 0
+ while expired < len(records) and _record_age_cutoff(records[expired], cutoff):
+ expired += 1
+ if expired:
+ del records[:expired]
+ closed["trimmed"] += expired
+ return closed
+
+
+def drop_stream_records(table_name: str, table: dict | None = None) -> None:
+ """Detach the table's current stream; an enabled one stays readable as closed."""
+ records = _stream_records.pop(table_name, None) or []
+ trimmed = _stream_trimmed.pop(table_name, 0)
+ spec = (table or {}).get("StreamSpecification") or {}
+ arn = (table or {}).get("LatestStreamArn")
+ if not spec.get("StreamEnabled") or not arn:
+ return
+ _sweep_closed_streams()
+ _closed_streams[arn] = {
+ "TableName": table_name,
+ "StreamLabel": table.get("LatestStreamLabel", ""),
+ "StreamViewType": spec.get("StreamViewType", "NEW_AND_OLD_IMAGES"),
+ "KeySchema": copy.deepcopy(table.get("KeySchema", [])),
+ "CreationRequestDateTime": table.get("CreationDateTime", 0),
+ "ClosedAt": time.time(),
+ "records": records,
+ "trimmed": trimmed,
+ }
def _next_stream_seq():
@@ -690,7 +740,7 @@ def _build_change_record(table: dict, event_name: str, old_item: dict | None, ne
"SizeBytes": 0,
"StreamViewType": view_type,
},
- "eventSourceARN": f"{table['TableArn']}/stream/{_stream_label()}",
+ "eventSourceARN": table.get("LatestStreamArn") or f"{table['TableArn']}/stream/{_stream_label()}",
}
ref_item = new_item or old_item or {}
@@ -730,7 +780,8 @@ def _emit_stream_event(table_name: str, event_name: str, old_item: dict | None,
if not streams_enabled and not has_kinesis:
return
- if streams_enabled:
+ # A PutItem/UpdateItem that changes no data writes no stream record.
+ if streams_enabled and not (event_name == "MODIFY" and old_item == new_item):
view_type = spec.get("StreamViewType", "NEW_AND_OLD_IMAGES")
record = _build_change_record(table, event_name, old_item, new_item, view_type)
if table_name not in _stream_records:
@@ -801,13 +852,10 @@ def _ttl_reaper():
ttl_val = _extract_key_val(ttl_attr)
try:
if float(ttl_val) <= now:
- del sk_map[sk_val]
+ _remove_item(table, pk_val, sk_val)
logger.debug("TTL expired item %s/%s from %s", pk_val, sk_val, table_name)
except (ValueError, TypeError):
pass
- if not sk_map:
- del table["items"][pk_val]
- _update_counts(table)
except Exception as exc:
logger.error("TTL reaper error: %s", exc)
@@ -1273,14 +1321,14 @@ def _delete_table(data):
desc = _table_description(name)
desc["TableStatus"] = "DELETING"
remaining = [r for r in _replica_group(_tables[name]) if r != get_region()]
- del _tables[name]
+ deleted = _tables.pop(name)
if remaining:
_set_replica_group(name, remaining)
_tags.pop(desc.get("TableArn", ""), None)
_ttl_settings.pop(name, None)
_pitr_settings.pop(name, None)
_kinesis_destinations.pop(name, None)
- drop_stream_records(name)
+ drop_stream_records(name, deleted)
return json_response({"TableDescription": desc})
@@ -1323,7 +1371,7 @@ def _set_replica_group(name, regions):
def _create_replica(name, table, region):
"""Copy ``table`` into ``region`` as a replica, with its items."""
account = get_account_id()
- replica = copy.deepcopy({k: v for k, v in table.items() if k != "items"})
+ replica = copy.deepcopy({k: v for k, v in table.items() if k not in ("items", _INDEX_MEMBERS)})
replica["items"] = defaultdict(dict, copy.deepcopy(dict(table["items"])))
arn = f"arn:aws:dynamodb:{region}:{account}:table/{name}"
replica.update({
@@ -1370,11 +1418,11 @@ def _apply_replica_updates(name, table, updates):
return error_response_json("ValidationException",
"Replica specified in the Replica Update or Replica Delete action of the request was not found.", 400)
if action == "Delete":
- _tables.pop_scoped(account, region, name, None)
+ deleted = _tables.pop_scoped(account, region, name, None)
_ttl_settings.pop_scoped(account, region, name, None)
_pitr_settings.pop_scoped(account, region, name, None)
with request_scope(account, region):
- drop_stream_records(name)
+ drop_stream_records(name, deleted)
regions.discard(region)
_set_replica_group(name, regions)
if len(regions) <= 1:
@@ -1400,12 +1448,9 @@ def _replicate_write(table, event_name, old_item, new_item):
sk_val = _extract_key_val(item.get(replica["sk_name"])) if replica["sk_name"] else "__no_sort__"
previous = replica["items"].get(pk_val, {}).get(sk_val)
if new_item is None:
- replica["items"].get(pk_val, {}).pop(sk_val, None)
- if pk_val in replica["items"] and not replica["items"][pk_val]:
- del replica["items"][pk_val]
+ _remove_item(replica, pk_val, sk_val)
else:
- replica["items"][pk_val][sk_val] = copy.deepcopy(new_item)
- _update_counts(replica)
+ _set_item(replica, pk_val, sk_val, copy.deepcopy(new_item))
if new_item is None and previous is None:
continue
replica_event = "REMOVE" if new_item is None else ("MODIFY" if previous else "INSERT")
@@ -1478,6 +1523,8 @@ def _update_table(data):
if "StreamSpecification" in data:
stream_spec = data["StreamSpecification"]
stream_was_enabled = bool((table.get("StreamSpecification") or {}).get("StreamEnabled"))
+ if stream_was_enabled and not stream_spec.get("StreamEnabled"):
+ drop_stream_records(name, table)
table["StreamSpecification"] = stream_spec
if stream_spec.get("StreamEnabled") and not stream_was_enabled:
stream_label = _stream_label()
@@ -1511,6 +1558,8 @@ def _update_table(data):
# AttributeDefinitions — stored definitions do not satisfy the check
# (measured eu-west-2, 2026-07-12, paritysuite).
defined_attrs = {a["AttributeName"] for a in data.get("AttributeDefinitions", [])}
+ if data.get("GlobalSecondaryIndexUpdates"):
+ table.pop(_INDEX_MEMBERS, None)
for update in data.get("GlobalSecondaryIndexUpdates", []):
if "Create" in update:
gsi_def = copy.deepcopy(update["Create"])
@@ -1819,8 +1868,7 @@ def _put_item(data):
if not _evaluate_expected(old_item or {}, expected, data.get("ConditionalOperator", "AND")):
return _conditional_check_failed(data, old_item)
- table["items"][pk_val][sk_val] = item
- _update_counts(table)
+ _set_item(table, pk_val, sk_val, item)
event_name = "MODIFY" if old_item else "INSERT"
_emit_stream_event(name, event_name, old_item, item)
@@ -1911,9 +1959,8 @@ def _delete_item(data):
return _conditional_check_failed(data, old_item)
if old_item is not None:
- table["items"].get(pk_val, {}).pop(sk_val, None)
+ _remove_item(table, pk_val, sk_val)
_emit_stream_event(name, "REMOVE", old_item, None)
- _update_counts(table)
result = {}
if data.get("ReturnValues") == "ALL_OLD" and old_item:
@@ -2045,8 +2092,7 @@ def _update_item(data):
if err:
return err
- table["items"][pk_val][sk_val] = item
- _update_counts(table)
+ _set_item(table, pk_val, sk_val, item)
event_name = "MODIFY" if old_item else "INSERT"
_emit_stream_event(name, event_name, old_item, item)
@@ -2179,6 +2225,11 @@ def _query(data):
"1 validation error detected: Must specify either a ProjectionExpression or non-empty AttributesToGet when Select is SPECIFIC_ATTRIBUTES", 400)
pk_name, sk_name, is_gsi = _resolve_index_keys(table, index_name)
+ index = _index_def(table, index_name) if index_name else None
+ hash_names, range_names = _index_key_lists(index) if index else ([pk_name], [sk_name] if sk_name else [])
+ multi_key = len(hash_names) > 1 or len(range_names) > 1
+ if multi_key:
+ pk_name, sk_name = hash_names[0], (range_names[0] if range_names else None)
# ConsistentRead on a GSI is invalid (only LSIs support strongly-consistent reads).
if data.get("ConsistentRead") and is_gsi:
return error_response_json("ValidationException",
@@ -2193,24 +2244,28 @@ def _query(data):
if table.get("sk_name"):
required.add(table["sk_name"])
if index_name:
- required.add(pk_name)
- if sk_name:
- required.add(sk_name)
+ required.update(hash_names + range_names)
if not required.issubset(esk.keys()):
return error_response_json("ValidationException",
"The provided starting key is invalid", 400)
- if key_conditions:
- pk_val = _extract_pk_from_key_conditions(key_conditions, pk_name)
- else:
- pk_val = _extract_pk_from_condition(key_cond, eav, ean, pk_name)
- if pk_val is None:
- return error_response_json("ValidationException",
- f"Query condition missed key schema element: {pk_name}", 400)
+ # Every partition-key attribute needs an equality condition; a
+ # multi-attribute partition is the tuple of their values.
+ pk_vals = []
+ for _hn in hash_names:
+ if key_conditions:
+ _hv = _extract_pk_from_key_conditions(key_conditions, _hn)
+ else:
+ _hv = _extract_pk_from_condition(key_cond, eav, ean, _hn)
+ if _hv is None:
+ return error_response_json("ValidationException",
+ f"Query condition missed key schema element: {_hn}", 400)
+ pk_vals.append(_hv)
+ pk_val = pk_vals[0] if len(pk_vals) == 1 else tuple(pk_vals)
# A key-condition value whose type does not match the key's schema type is
# rejected, as on real AWS ("Condition parameter type does not match schema
# type") — MiniStack used to accept N for an S key and return the row.
- for _kn in (pk_name, sk_name):
+ for _kn in hash_names + range_names:
if not _kn:
continue
_av = _key_condition_av(key_cond, key_conditions, eav, ean, _kn)
@@ -2228,9 +2283,7 @@ def _query(data):
kce_tokens = _tokenize(key_cond)
except Exception:
kce_tokens = []
- allowed = {pk_name}
- if sk_name:
- allowed.add(sk_name)
+ allowed = set(hash_names + range_names)
# A document path on a key attribute is rejected up front (AWS).
if any(tok[0] == "DOT" for tok in kce_tokens):
return error_response_json("ValidationException",
@@ -2250,6 +2303,11 @@ def _query(data):
if resolved and resolved not in allowed:
return error_response_json("ValidationException",
f"Query condition missed key schema element: {resolved}", 400)
+ # Multi-attribute sort keys are queried left to right without gaps,
+ # and only the last one queried may use a range condition.
+ if len(range_names) > 1 and not _multi_sort_condition_ok(kce_tokens, ean, range_names):
+ return error_response_json("ValidationException",
+ "Query key condition not supported", 400)
# Key-condition operands are validated like key values themselves:
# an empty string/binary operand is rejected with the same error AWS
# raises for empty key attribute values.
@@ -2286,13 +2344,16 @@ def _query(data):
return error_response_json("ValidationException",
"The provided starting key does not match the range key predicate", 400)
- if is_gsi or index_name:
+ members = _index_members(table).get(index_name) if index_name else None
+ if members is not None:
+ # Only this index partition; sparse items are never members.
+ bucket = table["items"]
+ candidates = [bucket[pk][sk] for pk, sk in members.get(pk_val, ()) if sk in bucket.get(pk, ())]
+ elif is_gsi or index_name:
candidates = []
for pk_bucket in table["items"].values():
for it in pk_bucket.values():
if pk_name in it and _extract_key_val(it[pk_name]) == pk_val:
- # Sparse index: for composite GSIs/LSIs, items that have the index
- # hash key but are missing the index range key are excluded.
if sk_name and sk_name not in it:
continue
candidates.append(it)
@@ -2303,7 +2364,7 @@ def _query(data):
# GSI/LSI: order by (INDEX_SORT, BASE_PK, BASE_SK). The base-table keys
# tiebreak rows with equal INDEX_SORT (or hash-only GSIs), matching
# real DynamoDB's hidden ordering and making pagination cursors stable.
- sort_keys = _index_order_keys(table, sk_name)
+ sort_keys = _index_order_keys(table, range_names)
candidates.sort(
key=lambda it: tuple(_index_order_value(it, n, t) for n, t in sort_keys),
reverse=not scan_forward,
@@ -2321,7 +2382,8 @@ def _query(data):
return error_response_json("ValidationException", str(exc), 400)
if esk:
- candidates = _apply_exclusive_start_key(candidates, esk, pk_name, sk_name, scan_forward, table=table)
+ candidates = _apply_exclusive_start_key(
+ candidates, esk, pk_name, range_names if multi_key else sk_name, scan_forward, table=table)
# AWS returns a LastEvaluatedKey whenever it stopped *because of* the
# limit — including when the results end exactly at the limit, since it
@@ -2364,9 +2426,9 @@ def _query(data):
if has_more and candidates:
lek = _build_key(candidates[-1], table["pk_name"], table["sk_name"])
if index_name:
- ik = _build_key(candidates[-1], pk_name, sk_name)
- for k, v in ik.items():
- lek.setdefault(k, v)
+ for k in hash_names + range_names:
+ if k in candidates[-1]:
+ lek.setdefault(k, candidates[-1][k])
result["LastEvaluatedKey"] = lek
_add_consumed_capacity(result, data, name, index_name=data.get("IndexName"))
@@ -2497,16 +2559,17 @@ def _scan(data):
if index_name:
pk_name_idx, sk_name_idx, is_gsi = _resolve_index_keys(table, index_name)
+ idx_hashes, idx_ranges = _index_key_lists(_index_def(table, index_name) or {})
if is_gsi:
# Sparse GSI semantics: items lacking ANY of the index's key
# attributes (hash, or range on a composite GSI) don't appear.
- all_items = [it for it in all_items if pk_name_idx in it and (not sk_name_idx or sk_name_idx in it)]
+ all_items = [it for it in all_items if all(n in it for n in idx_hashes + idx_ranges)]
else:
# LSI: items lacking the index's RANGE attribute don't appear.
if sk_name_idx:
all_items = [it for it in all_items if sk_name_idx in it]
# Sort by index key ordering so ESK/LEK pagination is consistent.
- sort_keys = _index_order_keys(table, sk_name_idx)
+ sort_keys = _index_order_keys(table, idx_ranges or sk_name_idx)
all_items.sort(key=lambda it: tuple(_index_order_value(it, n, t) for n, t in sort_keys))
# Parallel scan: partition items deterministically across segments by
@@ -2533,16 +2596,15 @@ def _scan(data):
if table.get("sk_name"):
required.add(table["sk_name"])
if index_name:
- required.add(pk_name_idx)
- if sk_name_idx:
- required.add(sk_name_idx)
+ required.update(idx_hashes + idx_ranges)
if not required.issubset(esk.keys()):
return error_response_json("ValidationException",
"The provided starting key is invalid: The provided key element does not match the schema", 400)
if index_name:
# For index scans, use index-aware ordering (same as Query pagination).
all_items = _apply_exclusive_start_key(
- all_items, esk, pk_name_idx, sk_name_idx, scan_forward=True, table=table
+ all_items, esk, pk_name_idx, idx_ranges if len(idx_ranges) > 1 else sk_name_idx,
+ scan_forward=True, table=table
)
else:
all_items = _apply_exclusive_start_key_scan(all_items, esk, table)
@@ -2585,9 +2647,9 @@ def _scan(data):
if has_more and all_items:
lek = _build_key(all_items[-1], table["pk_name"], table["sk_name"])
if index_name:
- ik = _build_key(all_items[-1], pk_name_idx, sk_name_idx)
- for k, v in ik.items():
- lek.setdefault(k, v)
+ for k in idx_hashes + idx_ranges:
+ if k in all_items[-1]:
+ lek.setdefault(k, all_items[-1][k])
result["LastEvaluatedKey"] = lek
_add_consumed_capacity(result, data, name, index_name=data.get("IndexName"))
@@ -2827,8 +2889,7 @@ def _partiql_insert(table, parsed):
if pk_val in table["items"] and sk_val in table["items"][pk_val]:
return error_response_json("DuplicateItemException",
"Duplicate primary key exists in table", 400)
- table["items"][pk_val][sk_val] = item
- _update_counts(table)
+ _set_item(table, pk_val, sk_val, item)
return json_response({})
@@ -3128,9 +3189,8 @@ def _partiql_update(table, parsed):
_partiql_remove_path(work, parts)
applied_paths.append(parts)
# Nothing failed — commit the working copy.
- item.clear()
- item.update(work)
- item_after = item
+ _set_item(table, pk_key, sk_key, work)
+ item_after = work
if returning:
r = returning.upper().strip()
@@ -3176,10 +3236,7 @@ def _partiql_delete(table, parsed):
return _conditional_check_failed({}, item)
item_before = copy.deepcopy(item) if returning else None
- del table["items"][pk_key][sk_key]
- if not table["items"][pk_key]:
- del table["items"][pk_key]
- _update_counts(table)
+ _remove_item(table, pk_key, sk_key)
if returning and returning.upper().strip() == "ALL OLD *":
return json_response({"Items": [item_before] if item_before else []})
@@ -3317,7 +3374,7 @@ def _execute_transaction(data):
crt = data.get("ClientRequestToken")
signature = None
if crt:
- prior = _txn_idempotency.get(crt)
+ prior = _txn_token_lookup(crt)
signature = {k: v for k, v in data.items() if k != "ClientRequestToken"}
if prior is not None:
if prior.get("signature") == signature:
@@ -3403,6 +3460,7 @@ def _execute_transaction(data):
tbl = _tables.get(tname)
if tbl is not None:
tbl["items"] = defaultdict(dict, items)
+ _items_replaced(tbl)
idx, code, msg = failure
reasons = [{"Code": "None"} for _ in statements]
reasons[idx] = {"Code": code.split("#")[-1], "Message": msg}
@@ -3439,7 +3497,7 @@ def _execute_transaction(data):
"WriteCapacityUnits": write_units})
result["ConsumedCapacity"] = consumed
if crt:
- _txn_idempotency[crt] = {"signature": signature, "response": result, "sizes": txn_sizes}
+ _txn_token_store(crt, {"signature": signature, "response": result, "sizes": txn_sizes})
return json_response(result)
@@ -4041,7 +4099,7 @@ def _batch_write_item(data):
if key_err:
return key_err
old_item = table["items"].get(pk_val, {}).get(sk_val)
- table["items"][pk_val][sk_val] = item
+ _set_item(table, pk_val, sk_val, item)
_emit_stream_event(_normalize_table_name(table_name), "MODIFY" if old_item else "INSERT", old_item, item)
_accumulate_write_capacity(cap, table, old_item, item)
elif "DeleteRequest" in req:
@@ -4050,11 +4108,10 @@ def _batch_write_item(data):
if key_err:
return key_err
old_item = table["items"].get(pk_val, {}).get(sk_val)
- table["items"].get(pk_val, {}).pop(sk_val, None)
+ _remove_item(table, pk_val, sk_val)
if old_item:
_emit_stream_event(_normalize_table_name(table_name), "REMOVE", old_item, None)
_accumulate_write_capacity(cap, table, old_item, None)
- _update_counts(table)
result = {"UnprocessedItems": unprocessed}
rc = data.get("ReturnConsumedCapacity", "NONE")
if rc != "NONE":
@@ -4161,7 +4218,7 @@ def _transact_write_items(data):
# raises IdempotentParameterMismatchException.
crt = data.get("ClientRequestToken")
if crt:
- prior = _txn_idempotency.get(crt)
+ prior = _txn_token_lookup(crt)
# Drop the ClientRequestToken from the payload signature so equality
# is on the actual transaction body.
signature = {k: v for k, v in data.items() if k != "ClientRequestToken"}
@@ -4330,7 +4387,7 @@ def _transact_write_items(data):
pk_val = _extract_key_val(item.get(tbl["pk_name"]))
sk_val = _extract_key_val(item.get(tbl["sk_name"])) if tbl["sk_name"] else "__no_sort__"
old_item = tbl["items"].get(pk_val, {}).get(sk_val)
- tbl["items"][pk_val][sk_val] = item
+ _set_item(tbl, pk_val, sk_val, item)
_emit_stream_event(table_name, "MODIFY" if old_item else "INSERT", old_item, item)
_txn_write_effects.setdefault(table_name, []).append((old_item, item))
elif op_type == "Delete":
@@ -4338,7 +4395,7 @@ def _transact_write_items(data):
pk_val = _extract_key_val(key.get(tbl["pk_name"]))
sk_val = _extract_key_val(key.get(tbl["sk_name"])) if tbl["sk_name"] else "__no_sort__"
old_item = tbl["items"].get(pk_val, {}).get(sk_val)
- tbl["items"].get(pk_val, {}).pop(sk_val, None)
+ _remove_item(tbl, pk_val, sk_val)
if old_item:
_emit_stream_event(table_name, "REMOVE", old_item, None)
_txn_write_effects.setdefault(table_name, []).append((old_item, None))
@@ -4351,10 +4408,9 @@ def _transact_write_items(data):
ue = op.get("UpdateExpression", "")
if ue:
item, _ = _apply_update_expression(item, ue, op.get("ExpressionAttributeValues", {}), op.get("ExpressionAttributeNames", {}))
- tbl["items"][pk_val][sk_val] = item
+ _set_item(tbl, pk_val, sk_val, item)
_emit_stream_event(table_name, "MODIFY" if old_item else "INSERT", old_item, item)
_txn_write_effects.setdefault(table_name, []).append((old_item, item))
- _update_counts(tbl)
# ConsumedCapacity: a transactional write costs 2 x ceil(size/1KB) WCU per
# item on the table (measured against real DynamoDB, eu-west-2, by
@@ -4393,11 +4449,33 @@ def _transact_write_items(data):
if rc != "NONE" and consumed:
result["ConsumedCapacity"] = consumed
if crt:
- _txn_idempotency[crt] = {"signature": signature, "response": result, "sizes": txn_sizes}
+ _txn_token_store(crt, {"signature": signature, "response": result, "sizes": txn_sizes})
return json_response(result)
_txn_idempotency = AccountRegionScopedDict()
+_TXN_TOKEN_TTL = 600 # "valid for 10 minutes after the first request that uses it is completed"
+_txn_token_sweep_at = 0.0
+
+
+def _txn_token_lookup(crt):
+ prior = _txn_idempotency.get(crt)
+ if prior is not None and time.time() - prior["completed_at"] >= _TXN_TOKEN_TTL:
+ _txn_idempotency.pop(crt, None)
+ return None
+ return prior
+
+
+def _txn_token_store(crt, entry):
+ global _txn_token_sweep_at
+ now = time.time()
+ entry["completed_at"] = now
+ _txn_idempotency[crt] = entry
+ if now >= _txn_token_sweep_at:
+ _txn_token_sweep_at = now + 60
+ for (account_id, region, token), prior in _txn_idempotency.all_items():
+ if now - prior["completed_at"] >= _TXN_TOKEN_TTL:
+ _txn_idempotency.pop_scoped(account_id, region, token, None)
def _transact_get_items(data):
@@ -5854,7 +5932,7 @@ def _restore_table_from_backup(data):
# Restore items.
snap = desc.get("_items_snapshot") or {}
_tables[target]["items"] = defaultdict(dict, copy.deepcopy(snap))
- _update_counts(_tables[target])
+ _items_replaced(_tables[target])
# AWS attaches a RestoreSummary to the response — clients (Terraform, the
# AWS SDK) read SourceBackupArn / RestoreInProgress to track the restore.
_tables[target]["RestoreSummary"] = {
@@ -5893,7 +5971,7 @@ def _restore_table_to_point_in_time(data):
if status != 200:
return status, {"Content-Type": "application/x-amz-json-1.0"}, body
_tables[target]["items"] = defaultdict(dict, copy.deepcopy(dict(src.get("items", {}))))
- _update_counts(_tables[target])
+ _items_replaced(_tables[target])
return json_response({"TableDescription": _table_description(target)})
@@ -7158,6 +7236,30 @@ def _index_order_value(item, name, type_hint):
return _sort_key_value(item.get(name), type_hint)
+def _multi_sort_condition_ok(tokens, ean, range_names):
+ """Sort-key attributes of a multi-attribute key must be queried left to
+ right without skipping any, with equality on all but the last."""
+ ops = {}
+ i = 0
+ while i < len(tokens):
+ kind, val = tokens[i]
+ if kind == "IDENT" and val.lower() == "begins_with" and i + 2 < len(tokens):
+ arg = tokens[i + 2]
+ name = ean.get(arg[1]) if arg[0] == "NAME_REF" else arg[1]
+ ops.setdefault(name, []).append("range")
+ i += 3
+ continue
+ name = ean.get(val) if kind == "NAME_REF" else (val if kind == "IDENT" else None)
+ if name in range_names and i + 1 < len(tokens):
+ eq = tokens[i + 1][0] == "EQ" or (i >= 2 and tokens[i - 1][0] == "EQ" and tokens[i - 2][0] == "VALUE_REF")
+ ops.setdefault(name, []).append("eq" if eq else "range")
+ i += 1
+ used = [n for n in range_names if n in ops]
+ if used != range_names[:len(used)] or any(len(ops[n]) != 1 for n in used):
+ return False
+ return all(ops[n] == ["eq"] for n in used[:-1])
+
+
def _index_order_keys(table, sk_name):
"""Ordered list of (attr_name, attr_type) used to sort a GSI/LSI Query
result deterministically: (INDEX_SORT, BASE_PK, BASE_SK). Real DynamoDB
@@ -7167,7 +7269,8 @@ def _index_order_keys(table, sk_name):
hash-only)."""
seen = set()
keys = []
- for n in (sk_name, table.get("pk_name"), table.get("sk_name")):
+ index_sorts = list(sk_name) if isinstance(sk_name, (list, tuple)) else [sk_name]
+ for n in (*index_sorts, table.get("pk_name"), table.get("sk_name")):
if n and n not in seen:
seen.add(n)
keys.append((n, _get_attr_type(table, n)))
@@ -7504,6 +7607,111 @@ def _compact_projection(value):
# Misc helpers
# ---------------------------------------------------------------------------
+# Derived per table, never persisted: {index_name: {index hash value:
+# {(base_pk, base_sk): None}}} (insertion-ordered), so a GSI/LSI Query reads its own partition
+# instead of every item. Built on first use; dropped whenever items are
+# replaced wholesale or the index set changes.
+_INDEX_MEMBERS = "_index_members"
+
+
+def _index_key_lists(index):
+ """(HASH names, RANGE names) of an index KeySchema, in order; a GSI may
+ have up to four of each (multi-attribute keys)."""
+ schema = index.get("KeySchema", [])
+ return ([k.get("AttributeName") for k in schema if k.get("KeyType") == "HASH"],
+ [k.get("AttributeName") for k in schema if k.get("KeyType") == "RANGE"])
+
+
+def _index_def(table, index_name):
+ for index in table.get("GlobalSecondaryIndexes", []) + table.get("LocalSecondaryIndexes", []):
+ if index.get("IndexName") == index_name:
+ return index
+ return None
+
+
+def _index_key_schemas(table):
+ for index in table.get("GlobalSecondaryIndexes", []) + table.get("LocalSecondaryIndexes", []):
+ hashes, ranges = _index_key_lists(index)
+ yield index.get("IndexName"), hashes, ranges
+
+
+def _index_partition(item, hashes, ranges):
+ """The index partition of an item: its HASH value, or the tuple of them
+ for a multi-attribute key; None when any key attribute is missing."""
+ if not hashes or any(n not in item for n in hashes + ranges):
+ return None
+ if len(hashes) == 1:
+ return _extract_key_val(item[hashes[0]])
+ return tuple(_extract_key_val(item[n]) for n in hashes)
+
+
+def _index_members(table):
+ members = table.get(_INDEX_MEMBERS)
+ if members is None:
+ members = {}
+ for name, hash_key, range_key in _index_key_schemas(table):
+ partitions = members.setdefault(name, {})
+ for base_pk, sk_map in table["items"].items():
+ for base_sk, item in sk_map.items():
+ partition = _index_partition(item, hash_key, range_key)
+ if partition is not None:
+ partitions.setdefault(partition, {})[(base_pk, base_sk)] = None
+ table[_INDEX_MEMBERS] = members
+ return members
+
+
+def _index_item(table, base_pk, base_sk, item, add):
+ members = table.get(_INDEX_MEMBERS)
+ if members is None:
+ return
+ for name, hash_key, range_key in _index_key_schemas(table):
+ if name not in members:
+ table.pop(_INDEX_MEMBERS, None)
+ return
+ partition = _index_partition(item, hash_key, range_key)
+ if partition is None:
+ continue
+ partitions = members[name]
+ if add:
+ partitions.setdefault(partition, {})[(base_pk, base_sk)] = None
+ elif partition in partitions:
+ partitions[partition].pop((base_pk, base_sk), None)
+ if not partitions[partition]:
+ del partitions[partition]
+
+
+def _set_item(table, pk_val, sk_val, item):
+ """Store an item, keeping ItemCount and index membership current."""
+ old_item = table["items"].get(pk_val, {}).get(sk_val)
+ if old_item is not None:
+ _index_item(table, pk_val, sk_val, old_item, add=False)
+ else:
+ table["ItemCount"] = table.get("ItemCount", 0) + 1
+ table["TableSizeBytes"] = table["ItemCount"] * 200
+ table["items"].setdefault(pk_val, {})[sk_val] = item
+ _index_item(table, pk_val, sk_val, item, add=True)
+ return old_item
+
+
+def _remove_item(table, pk_val, sk_val):
+ """Delete an item, keeping ItemCount and index membership current."""
+ sk_map = table["items"].get(pk_val)
+ old_item = sk_map.pop(sk_val, None) if sk_map is not None else None
+ if sk_map is not None and not sk_map:
+ del table["items"][pk_val]
+ if old_item is not None:
+ _index_item(table, pk_val, sk_val, old_item, add=False)
+ table["ItemCount"] = max(0, table.get("ItemCount", 0) - 1)
+ table["TableSizeBytes"] = table["ItemCount"] * 200
+ return old_item
+
+
+def _items_replaced(table):
+ """After table["items"] is swapped wholesale: recount and rebuild lazily."""
+ table.pop(_INDEX_MEMBERS, None)
+ _update_counts(table)
+
+
def _update_counts(table):
count = sum(len(v) for v in table["items"].values())
table["ItemCount"] = count
@@ -7890,6 +8098,7 @@ def reset():
_pitr_settings.clear()
_stream_records.clear()
_stream_trimmed.clear()
+ _closed_streams.clear()
_kinesis_destinations.clear()
_backups.clear()
_contributor_insights.clear()
diff --git a/ministack/services/dynamodb_streams.py b/ministack/services/dynamodb_streams.py
index e51603b5..c9e64197 100644
--- a/ministack/services/dynamodb_streams.py
+++ b/ministack/services/dynamodb_streams.py
@@ -236,12 +236,16 @@ def _describe_stream(data):
spec, table_name = source
info = _enabled_stream_info(table_name, account_id=spec.account_id, region=spec.region)
+ closed = None
if info is None or info["StreamArn"] != stream_arn:
- return error_response_json(
- "ResourceNotFoundException", f"Stream not found: {stream_arn}", 400
- )
+ closed = _ddb.closed_stream(stream_arn)
+ if closed is None:
+ return error_response_json(
+ "ResourceNotFoundException", f"Stream not found: {stream_arn}", 400
+ )
+ info = closed
- records = _records_for(spec.account_id, spec.region, table_name)
+ records = closed["records"] if closed else _records_for(spec.account_id, spec.region, table_name)
starting_seq = records[0]["dynamodb"]["SequenceNumber"] if records else None
shard: dict = {
@@ -250,9 +254,16 @@ def _describe_stream(data):
}
if starting_seq:
shard["SequenceNumberRange"]["StartingSequenceNumber"] = starting_seq
+ if closed:
+ shard["SequenceNumberRange"]["EndingSequenceNumber"] = records[-1]["dynamodb"]["SequenceNumber"]
- table = _ddb._tables.get_scoped(spec.account_id, spec.region, table_name, {})
- key_schema = table.get("KeySchema", [])
+ if closed:
+ key_schema = closed["KeySchema"]
+ created = closed["CreationRequestDateTime"]
+ else:
+ table = _ddb._tables.get_scoped(spec.account_id, spec.region, table_name, {})
+ key_schema = table.get("KeySchema", [])
+ created = table.get("CreationDateTime", 0)
# AWS shard pagination: Limit caps the number of Shards returned (max 100),
# ExclusiveStartShardId skips past a previously-returned shard. We expose
@@ -269,9 +280,9 @@ def _describe_stream(data):
description = {
"StreamArn": stream_arn,
"StreamLabel": info["StreamLabel"],
- "StreamStatus": "ENABLED",
+ "StreamStatus": "DISABLED" if closed else "ENABLED",
"StreamViewType": info["StreamViewType"],
- "CreationRequestDateTime": table.get("CreationDateTime", 0),
+ "CreationRequestDateTime": created,
"TableName": table_name,
"KeySchema": key_schema,
"Shards": page,
@@ -305,12 +316,15 @@ def _get_shard_iterator(data):
info = _enabled_stream_info(table_name, account_id=spec.account_id, region=spec.region)
if info is None or info["StreamArn"] != stream_arn:
- return error_response_json(
- "ResourceNotFoundException", f"Stream not found: {stream_arn}", 400
- )
-
- records = _records_for(spec.account_id, spec.region, table_name)
- horizon = _horizon(spec.account_id, spec.region, table_name)
+ closed = _ddb.closed_stream(stream_arn)
+ if closed is None:
+ return error_response_json(
+ "ResourceNotFoundException", f"Stream not found: {stream_arn}", 400
+ )
+ records, horizon = closed["records"], closed["trimmed"]
+ else:
+ records = _records_for(spec.account_id, spec.region, table_name)
+ horizon = _horizon(spec.account_id, spec.region, table_name)
position = horizon
if iterator_type == "TRIM_HORIZON":
position = horizon
@@ -376,21 +390,35 @@ def _get_records(data):
)
info = _enabled_stream_info(table_name, account_id=account_id, region=region)
+ closed = None
if info is None or (stream_arn and info["StreamArn"] != stream_arn):
- return error_response_json(
- "ExpiredIteratorException",
- "Iterator references a stream that is no longer enabled",
- 400,
- )
+ closed = _ddb.closed_stream(stream_arn) if stream_arn else None
+ if closed is None:
+ return error_response_json(
+ "ExpiredIteratorException",
+ "Iterator references a stream that is no longer enabled",
+ 400,
+ )
# ``position`` is absolute, so an iterator minted before records expired
# still lands correctly; one that now points behind the trim horizon
# resumes at the horizon rather than skipping live records.
- position = max(position, _horizon(account_id, region, table_name))
- page = _ddb.stream_records_since(
- table_name, position, limit, account_id=account_id, region=region
- )
+ if closed:
+ position = max(position, closed["trimmed"])
+ offset = position - closed["trimmed"]
+ page = closed["records"][offset:offset + limit]
+ else:
+ position = max(position, _horizon(account_id, region, table_name))
+ page = _ddb.stream_records_since(
+ table_name, position, limit, account_id=account_id, region=region
+ )
next_position = position + len(page)
+ # The Streams Record shape carries no eventSourceARN (Lambda events do).
+ page = [{k: v for k, v in r.items() if k != "eventSourceARN"} for r in page]
+ if closed and next_position >= closed["trimmed"] + len(closed["records"]):
+ # "If set to null, the shard has been closed and the requested
+ # iterator will not return any more data."
+ return json_response({"Records": page})
next_iterator = _encode_iterator(
table_name,
shard_id,
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index 53012b5a..c2e4937f 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -2469,7 +2469,7 @@ def _dispatch_to_sqs(spec, payload, sqs_parameters=None):
"md5_body": md5,
"receipt_handle": None,
"sent_at": now,
- "visible_at": now,
+ "visible_at": now + _sqs.queue_delay(queue),
"receive_count": 0,
"attributes": {},
"message_attributes": {},
@@ -2511,12 +2511,6 @@ def _dispatch_to_sns(arn, payload):
return
msg_id = new_uuid()
- topic["messages"].append({
- "id": msg_id,
- "message": payload,
- "subject": "EventBridge Notification",
- "timestamp": int(time.time()),
- })
_sns._fanout(arn, msg_id, payload, "EventBridge Notification")
logger.info("EventBridge → SNS %s", arn)
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index b1dc212a..82107bba 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -3761,7 +3761,7 @@ def _route_async_failure(target_arn: str, func_name: str, event: dict, result: d
"md5_attrs": "",
"receipt_handle": None,
"sent_at": now,
- "visible_at": now,
+ "visible_at": now + _sqs.queue_delay(target_q),
"receive_count": 0,
"first_receive_at": None,
"message_attributes": {},
@@ -4921,19 +4921,25 @@ def _emit_lambda_logs(func: dict, request_id: str, log_text: str,
}
stream = group["streams"][stream_name]
+ start = f"START RequestId: {request_id} Version: {qualifier}"
+ end = f"END RequestId: {request_id}"
+
+ def _report():
+ return (f"REPORT RequestId: {request_id}\tDuration: {duration_ms} ms\t"
+ f"Billed Duration: {duration_ms} ms\tMemory Size: "
+ f"{config.get('MemorySize', 128)} MB\tMax Memory Used: {_probe_peak_memory_mb(func)} MB")
+
if log_source == "rie" and log_text:
lines = log_text.splitlines()
+ # RIE prints START on every invoke but no END/REPORT when init or the invoke fails (502).
+ if not any(line.startswith(f"START RequestId: {request_id}") for line in lines):
+ lines.insert(0, start)
+ if not any(line.startswith(end) for line in lines):
+ lines.append(end)
+ if not any(line.startswith(f"REPORT RequestId: {request_id}") for line in lines):
+ lines.append(_report())
else:
- lines = [f"START RequestId: {request_id} Version: {qualifier}"]
- if log_text:
- lines.extend(log_text.splitlines())
- lines.append(f"END RequestId: {request_id}")
- peak_mb = _probe_peak_memory_mb(func)
- lines.append(
- f"REPORT RequestId: {request_id}\tDuration: {duration_ms} ms\t"
- f"Billed Duration: {duration_ms} ms\tMemory Size: "
- f"{config.get('MemorySize', 128)} MB\tMax Memory Used: {peak_mb} MB"
- )
+ lines = [start, *(log_text.splitlines() if log_text else []), end, _report()]
for line in lines:
stream["events"].append({"timestamp": now_ms, "message": line, "ingestionTime": now_ms})
if stream["firstEventTimestamp"] is None:
@@ -7699,7 +7705,7 @@ def _send_ddb_stream_failure_record(esm, func_rec, batch, stream_arn, result, co
target_q["messages"].append({
"id": new_uuid(), "body": body,
"md5_body": hashlib.md5(body.encode()).hexdigest(), "md5_attrs": "",
- "receipt_handle": None, "sent_at": now, "visible_at": now,
+ "receipt_handle": None, "sent_at": now, "visible_at": now + _sqs.queue_delay(target_q),
"receive_count": 0, "first_receive_at": None, "message_attributes": {},
"sys": {"SenderId": get_account_id(), "SentTimestamp": str(int(now * 1000))},
"group_id": None, "dedup_id": None, "dedup_cache_key": None, "seq": None,
diff --git a/ministack/services/pipes.py b/ministack/services/pipes.py
index d5f4eb6e..5985bbc5 100644
--- a/ministack/services/pipes.py
+++ b/ministack/services/pipes.py
@@ -306,14 +306,6 @@ def _publish_record_to_sns(topic_arn: str, pipe: dict, record: dict):
message = json.dumps(record)
subject = f"Pipes {pipe.get('Name', '')}"
- topic["messages"].append({
- "id": msg_id,
- "message": message,
- "subject": subject,
- "message_structure": "",
- "message_attributes": {},
- "timestamp": int(time.time()),
- })
_sns._fanout(topic_arn, msg_id, message, subject, "", {})
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index 55081899..b8ca2106 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -2147,7 +2147,15 @@ def _create_bucket(name: str, body: bytes, headers: dict = None):
if canned_acl and canned_acl not in _CANNED_BUCKET_ACLS:
return _error("InvalidArgument", f"Invalid x-amz-acl value: {canned_acl}", 400)
if name in _buckets:
- # Idempotent: same account already owns it — return 200 like real AWS
+ # Outside us-east-1 AWS returns BucketAlreadyOwnedByYou; in us-east-1,
+ # "returns 200 OK and resets the bucket access control lists (ACLs)".
+ if _buckets[name].get("region", "us-east-1") != "us-east-1":
+ return _error("BucketAlreadyOwnedByYou",
+ "The bucket you tried to create already exists, and you own it.",
+ 409, f"/{name}")
+ _bucket_acl.pop(name, None)
+ if canned_acl:
+ _bucket_acl[name] = _canned_acl_policy_xml(canned_acl, _canonical_owner_id())
return 200, {"Location": f"/{name}"}, b""
if _bucket_owner_account(name) is not None:
# "After creating a general purpose bucket in the shared global
@@ -3634,7 +3642,7 @@ def _deliver_event_to_sqs(arn: str, event_payload: dict, bucket_region: str,
"md5": hashlib.md5(body.encode()).hexdigest(),
"receipt_handle": None,
"sent_at": now,
- "visible_at": now,
+ "visible_at": now + _sqs.queue_delay(queue),
"receive_count": 0,
}
_sqs._ensure_msg_fields(msg)
diff --git a/ministack/services/ses.py b/ministack/services/ses.py
index 815e51bb..83acee4a 100644
--- a/ministack/services/ses.py
+++ b/ministack/services/ses.py
@@ -479,16 +479,10 @@ def _send_email(params):
cc_addrs = _collect_list(params, "Destination.CcAddresses.member")
bcc_addrs = _collect_list(params, "Destination.BccAddresses.member")
recipients = to_addrs + cc_addrs + bcc_addrs
- if not source or not _valid_email_address(source):
- return _error("InvalidParameterValue", "The address specified is not valid.", 400)
- if not recipients or any(not _valid_email_address(address) for address in recipients):
- return _error("InvalidParameterValue", "The destination address is not valid.", 400)
- if "Message.Subject.Data" not in params:
- return _error("InvalidParameterValue", "The Subject field is required.", 400)
- if "Message.Body.Text.Data" not in params and "Message.Body.Html.Data" not in params:
- return _error("InvalidParameterValue", "The message body must contain Text or Html content.", 400)
+ if any(_missing_domain(address) for address in [source, *recipients] if address):
+ return _error("InvalidParameterValue", "Missing final '@domain'", 400)
if config_set and config_set not in _configuration_sets:
- return _error("ConfigurationSetDoesNotExist", f"Configuration set {config_set} does not exist.", 400)
+ return _config_set_missing(config_set)
rejected = _message_rejection(source, recipients)
if rejected:
return _error("MessageRejected", rejected, 400)
@@ -508,15 +502,14 @@ def _send_email(params):
f"<SendEmailResult><MessageId>{msg_id}</MessageId></SendEmailResult>")
-def _valid_email_address(value: str) -> bool:
- if not value.isascii():
- return False
- address = parseaddr(value)[1]
- if not address or len(address) > 320:
- return False
- local, separator, domain = address.rpartition("@")
- return bool(separator and local and domain and "." in domain
- and not any(character.isspace() for character in address))
+def _missing_domain(value: str) -> bool:
+ _, separator, domain = parseaddr(value)[1].rpartition("@")
+ return not separator or not domain
+
+
+def _config_set_missing(name):
+ return _error("ConfigurationSetDoesNotExist", f"Configuration set {name} does not exist", 400,
+ "Sender", fields={"ConfigurationSetName": name})
def _record_send(source, to_addrs, cc_addrs=None, bcc_addrs=None,
@@ -959,8 +952,7 @@ def _delete_configuration_set(params):
if blocked:
return blocked
if name not in _configuration_sets:
- return _error("ConfigurationSetDoesNotExist",
- f"Configuration set {name} does not exist", 400)
+ return _config_set_missing(name)
del _configuration_sets[name]
return _xml(200, "DeleteConfigurationSetResponse", "<DeleteConfigurationSetResult/>")
@@ -969,8 +961,7 @@ def _describe_configuration_set(params):
name = _p(params, "ConfigurationSetName")
cs = _configuration_sets.get(name)
if not cs:
- return _error("ConfigurationSetDoesNotExist",
- f"Configuration set {name} does not exist", 400)
+ return _config_set_missing(name)
return _xml(200, "DescribeConfigurationSetResponse",
f"<DescribeConfigurationSetResult>"
f"<ConfigurationSet><Name>{cs['Name']}</Name></ConfigurationSet>"
@@ -1416,9 +1407,10 @@ def _xml(status, root_tag, inner):
return status, {"Content-Type": "application/xml"}, body
-def _error(code, message, status, error_type=""):
+def _error(code, message, status, error_type="", fields=None):
type_xml = f"<Type>{error_type}</Type>" if error_type else ""
message_xml = f"<Message>{_esc(message)}</Message>" if message is not None else ""
+ message_xml += "".join(f"<{k}>{_esc(v)}</{k}>" for k, v in (fields or {}).items())
body = (f'<?xml version="1.0" encoding="UTF-8"?>'
f'<ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">'
f'<Error>{type_xml}<Code>{code}</Code>{message_xml}</Error>'
diff --git a/ministack/services/ses_v2.py b/ministack/services/ses_v2.py
index 30681aa7..3a4983a5 100644
--- a/ministack/services/ses_v2.py
+++ b/ministack/services/ses_v2.py
@@ -11,7 +11,9 @@ Supports: SendEmail, CreateEmailIdentity, GetEmailIdentity, DeleteEmailIdentity,
PutAccountSuppressionAttributes, TagResource, UntagResource,
ListTagsForResource, CreateTenant, GetTenant, ListTenants, DeleteTenant,
CreateTenantResourceAssociation, DeleteTenantResourceAssociation,
- ListTenantResources, ListResourceTenants, PutTenantSuppressionAttributes.
+ ListTenantResources, ListResourceTenants, PutTenantSuppressionAttributes,
+ CreateDedicatedIpPool, GetDedicatedIpPool, ListDedicatedIpPools,
+ DeleteDedicatedIpPool.
Email templates live in the v1 store, so either API version sees the other's.
"""
@@ -62,6 +64,7 @@ _config_sets = AccountRegionScopedDict() # name -> dict
_ses_tags = AccountRegionScopedDict() # resource_arn -> [tags]
_tenants = AccountRegionScopedDict()
_tenant_resources = AccountRegionScopedDict() # tenant name -> {ARN: timestamp}
+_dedicated_ip_pools = AccountRegionScopedDict() # pool name -> {PoolName, ScalingMode}
def get_state() -> dict:
@@ -71,6 +74,7 @@ def get_state() -> dict:
"_ses_tags": _ses_tags,
"_tenants": _tenants,
"_tenant_resources": _tenant_resources,
+ "_dedicated_ip_pools": _dedicated_ip_pools,
})
@@ -84,6 +88,7 @@ def _restore_state(data: dict):
_restore_tag_store(data.get("_ses_tags", {}))
_restore_regional_store(_tenants, data.get("_tenants", {}))
_restore_regional_store(_tenant_resources, data.get("_tenant_resources", {}))
+ _restore_regional_store(_dedicated_ip_pools, data.get("_dedicated_ip_pools", {}))
def _restore_tag_store(restored):
@@ -312,6 +317,9 @@ def _local_ses_v2_resource_arn(arn):
elif kind == "configuration-set":
if name not in _config_sets:
return None, _not_found_resource_arn(arn)
+ elif kind == "dedicated-ip-pool":
+ if name not in _dedicated_ip_pools:
+ return None, _not_found_resource_arn(arn)
elif kind == "tenant":
parts = name.split("/")
if len(parts) == 1:
@@ -871,6 +879,38 @@ async def handle_request(method, path, headers, body, query_params):
_identities.pop(identity, None)
return json_response({})
+ # /v2/email/dedicated-ip-pools (Create/Get/List/DeleteDedicatedIpPool)
+ if sub == "/dedicated-ip-pools" and method == "POST":
+ name = data.get("PoolName", "")
+ if not name:
+ return _json_err("BadRequestException", "PoolName is required")
+ if name in _dedicated_ip_pools:
+ return _json_err("AlreadyExistsException", f"Pool {name} already exists")
+ _dedicated_ip_pools[name] = {"PoolName": name, "ScalingMode": data.get("ScalingMode") or "STANDARD"}
+ _ses_tags[_resource_arn("dedicated-ip-pool", name)] = list(data.get("Tags", []))
+ return json_response({})
+
+ if sub == "/dedicated-ip-pools" and method == "GET":
+ page, next_token, err = _paginate(list(_dedicated_ip_pools.keys()), query_params, 100, maximum=1000)
+ if err:
+ return err
+ out = {"DedicatedIpPools": page}
+ if next_token:
+ out["NextToken"] = next_token
+ return json_response(out)
+
+ m = re.match(r"^/dedicated-ip-pools/([^/]+)$", sub)
+ if m and method in ("GET", "DELETE"):
+ name = m.group(1)
+ pool = _dedicated_ip_pools.get(name)
+ if pool is None:
+ return _json_err("NotFoundException", f"Pool {name} does not exist", 404)
+ if method == "GET":
+ return json_response({"DedicatedIpPool": dict(pool)})
+ _dedicated_ip_pools.pop(name, None)
+ _ses_tags.pop(_resource_arn("dedicated-ip-pool", name), None)
+ return json_response({})
+
# POST /v2/email/configuration-sets (CreateConfigurationSet)
if sub == "/configuration-sets" and method == "POST":
name = data.get("ConfigurationSetName", "")
@@ -1016,3 +1056,4 @@ def reset():
_ses_tags.clear()
_tenants.clear()
_tenant_resources.clear()
+ _dedicated_ip_pools.clear()
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index 3f638fa7..c06762d3 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -290,6 +290,8 @@ def load_persisted_state(data):
def _restore_state(data):
if data:
_topics.update(data.get("topics", {}))
+ for topic in _topics.all_values():
+ topic.pop("messages", None) # publish history is no longer kept
_sub_arn_to_topic.update(data.get("sub_arn_to_topic", {}))
_sms_messages.update(data.get("sms_messages", {}))
_platform_applications.update(data.get("platform_applications", {}))
@@ -421,7 +423,6 @@ def _create_topic(params):
}),
},
"subscriptions": [],
- "messages": [],
"tags": {},
}
@@ -943,14 +944,6 @@ def publish_internal(
else:
msg_id = new_uuid()
- topic["messages"].append({
- "id": msg_id,
- "message": message,
- "subject": subject,
- "message_structure": message_structure,
- "message_attributes": msg_attrs,
- "timestamp": int(time.time()),
- })
_fanout(topic_arn, msg_id, message, subject, message_structure, msg_attrs,
message_group_id=message_group_id, message_dedup_id=dedup_id)
logger.info(
@@ -1128,15 +1121,6 @@ def _publish_batch(params):
"sequence_number": seq_number,
}
- topic["messages"].append({
- "id": msg_id,
- "message": message,
- "subject": subject,
- "message_structure": message_structure,
- "message_attributes": msg_attrs,
- "timestamp": int(time.time()),
- })
-
_fanout(topic_arn, msg_id, message, subject, message_structure, msg_attrs,
message_group_id=group_id, message_dedup_id=dedup_id)
@@ -1150,14 +1134,6 @@ def _publish_batch(params):
else:
# ── Standard (non-FIFO) batch entry ──
msg_id = new_uuid()
- topic["messages"].append({
- "id": msg_id,
- "message": message,
- "subject": subject,
- "message_structure": message_structure,
- "message_attributes": msg_attrs,
- "timestamp": int(time.time()),
- })
_fanout(topic_arn, msg_id, message, subject, message_structure, msg_attrs)
successful += (
@@ -1290,7 +1266,7 @@ def _deliver_to_sqs(endpoint: str, envelope: str, raw: bool, raw_message: str,
"md5_attrs": _sqs._md5_msg_attrs(sqs_attrs),
"receipt_handle": None,
"sent_at": now,
- "visible_at": now,
+ "visible_at": now + _sqs.queue_delay(queue),
"receive_count": 0,
}
if message_group_id:
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index de00622f..b48c76a5 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -612,6 +612,14 @@ def _act_get_queue_url(data: dict, _u: str) -> dict:
return {"QueueUrl": url}
+def queue_delay(q: dict) -> int:
+ """The queue's DelaySeconds; internal producers' messages wait it too."""
+ try:
+ return int(q["attributes"].get("DelaySeconds", "0"))
+ except (TypeError, ValueError):
+ return 0
+
+
# ── SendMessage ─────────────────────────────────────────────
def _act_send_message(data: dict, qurl: str) -> dict:
@@ -642,8 +650,16 @@ def _act_send_message(data: dict, qurl: str) -> dict:
f"One or more parameters are invalid. Reason: Message must be shorter than {max_size} bytes.",
)
- delay = int(data.get("DelaySeconds")
- or q["attributes"].get("DelaySeconds", "0"))
+ # A per-message DelaySeconds overrides the queue's; FIFO queues accept
+ # only 0 and keep the queue-level delay (real AWS, ap-south-1).
+ _delay = data.get("DelaySeconds")
+ if q["is_fifo"] and _delay is not None and int(_delay) != 0:
+ raise _Err("InvalidParameterValue",
+ f"Value {int(_delay)} for parameter DelaySeconds is invalid. "
+ "Reason: The request include parameter that is not valid for this queue type.")
+ if _delay is None or q["is_fifo"]:
+ _delay = q["attributes"].get("DelaySeconds", "0")
+ delay = int(_delay)
msg_attrs = data.get("MessageAttributes") or {}
sys_attrs = data.get("MessageSystemAttributes") or {}
group_id = data.get("MessageGroupId")
@@ -682,7 +698,6 @@ def _act_send_message(data: dict, qurl: str) -> dict:
return r
q["fifo_seq"] += 1
seq = str(q["fifo_seq"]).zfill(20)
- delay = 0
now = time.time()
mid = new_uuid()
@@ -729,7 +744,11 @@ async def _act_receive_message(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
q = _get_q(url, "sqs:ReceiveMessage")
- max_n = min(int(data.get("MaxNumberOfMessages", 1)), 10)
+ max_n = int(data.get("MaxNumberOfMessages", 1))
+ if not 1 <= max_n <= 10:
+ raise _Err("InvalidParameterValue",
+ f"Value {max_n} for parameter MaxNumberOfMessages is invalid. "
+ "Reason: Must be between 1 and 10, if provided.")
# An explicit request value wins even when it is 0 — a supplied
# VisibilityTimeout=0 / WaitTimeSeconds=0 must NOT fall back to the queue
# attribute (0 is falsy in Python; keying on presence is required).
diff --git a/tests/test_cloudwatch.py b/tests/test_cloudwatch.py
index 67e9f0cc..ecc4b613 100644
--- a/tests/test_cloudwatch.py
+++ b/tests/test_cloudwatch.py
@@ -990,3 +990,74 @@ def test_cloudwatch_json_timestamps_are_epoch_numbers(cw):
for dp in datapoints:
assert isinstance(dp["Timestamp"], int), (
f"Timestamp must be int epoch over JSON, got {type(dp['Timestamp']).__name__}: {dp['Timestamp']}")
+
+
+def _cw_period_start():
+ return (int(time.time()) // 3600 - 1) * 3600
+
+
+def test_cloudwatch_values_counts_and_statistic_sets_aggregate_weighted(cw):
+ ns = f"Test/Weighted{_uuid_mod.uuid4().hex[:8]}"
+ ts = _cw_period_start() + 60
+ cw.put_metric_data(Namespace=ns, MetricData=[
+ {"MetricName": "Counted", "Timestamp": ts, "Values": [1.0, 2.0], "Counts": [3.0, 1.0]},
+ {"MetricName": "Set", "Timestamp": ts,
+ "StatisticValues": {"SampleCount": 4, "Sum": 10, "Minimum": 1, "Maximum": 4}},
+ {"MetricName": "Repeated", "Timestamp": ts,
+ "StatisticValues": {"SampleCount": 3, "Sum": 6, "Minimum": 2, "Maximum": 2}},
+ {"MetricName": "Negative", "Timestamp": ts, "Values": [-1.0, 5.0]},
+ ])
+
+ def stats(name, **kw):
+ return cw.get_metric_statistics(Namespace=ns, MetricName=name, StartTime=ts - 60,
+ EndTime=ts + 3000, Period=3600, **kw)["Datapoints"][0]
+
+ dp = stats("Counted", Statistics=["SampleCount", "Sum", "Average", "Minimum", "Maximum"])
+ assert (dp["SampleCount"], dp["Sum"], dp["Average"], dp["Minimum"], dp["Maximum"]) == (4, 5, 1.25, 1, 2)
+ assert stats("Counted", ExtendedStatistics=["p50", "p100"])["ExtendedStatistics"] == {"p50": 1, "p100": 2}
+
+ dp = stats("Set", Statistics=["SampleCount", "Sum", "Average", "Minimum", "Maximum"])
+ assert (dp["SampleCount"], dp["Sum"], dp["Average"], dp["Minimum"], dp["Maximum"]) == (4, 10, 2.5, 1, 4)
+ assert "ExtendedStatistics" not in stats("Set", ExtendedStatistics=["p50"])
+ assert stats("Repeated", ExtendedStatistics=["p50"])["ExtendedStatistics"] == {"p50": 2}
+ assert "ExtendedStatistics" not in stats("Negative", ExtendedStatistics=["p50"])
+
+ resp = cw.get_metric_data(StartTime=ts - 60, EndTime=ts + 3000, MetricDataQueries=[
+ {"Id": "neg", "MetricStat": {"Metric": {"Namespace": ns, "MetricName": "Negative"},
+ "Period": 3600, "Stat": "p50"}},
+ {"Id": "avg", "MetricStat": {"Metric": {"Namespace": ns, "MetricName": "Negative"},
+ "Period": 3600, "Stat": "Average"}}])
+ by_id = {r["Id"]: r["Values"] for r in resp["MetricDataResults"]}
+ assert by_id == {"neg": [], "avg": [2.0]}
+
+
+def test_cloudwatch_query_protocol_put_metric_data_values_and_statistic_values():
+ import urllib.parse
+ import urllib.request
+
+ from conftest import ENDPOINT
+ ns = f"Test/QueryWeighted{_uuid_mod.uuid4().hex[:8]}"
+ ts = _cw_period_start() + 60
+ stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(ts))
+ form = {
+ "Action": "PutMetricData", "Version": "2010-08-01", "Namespace": ns,
+ "MetricData.member.1.MetricName": "Counted", "MetricData.member.1.Timestamp": stamp,
+ "MetricData.member.1.Values.member.1": "1", "MetricData.member.1.Values.member.2": "2",
+ "MetricData.member.1.Counts.member.1": "3", "MetricData.member.1.Counts.member.2": "1",
+ "MetricData.member.2.MetricName": "Set", "MetricData.member.2.Timestamp": stamp,
+ "MetricData.member.2.StatisticValues.SampleCount": "4",
+ "MetricData.member.2.StatisticValues.Sum": "10",
+ "MetricData.member.2.StatisticValues.Minimum": "1",
+ "MetricData.member.2.StatisticValues.Maximum": "4",
+ }
+ req = urllib.request.Request(
+ ENDPOINT, data=urllib.parse.urlencode(form).encode(),
+ headers={"Content-Type": "application/x-www-form-urlencoded",
+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/monitoring/aws4_request, "
+ "SignedHeaders=host, Signature=x"})
+ assert urllib.request.urlopen(req).status == 200
+ cw = __import__("conftest").make_client("cloudwatch")
+ for name, expected in (("Counted", (4, 5)), ("Set", (4, 10))):
+ dp = cw.get_metric_statistics(Namespace=ns, MetricName=name, StartTime=ts - 60, EndTime=ts + 3000,
+ Period=3600, Statistics=["SampleCount", "Sum"])["Datapoints"][0]
+ assert (dp["SampleCount"], dp["Sum"]) == expected
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index 7fec1a58..203e9e08 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -403,6 +403,10 @@ def test_cognito_password_auth_reset_required_user_is_refused_until_reset(cognit
AuthParameters=params)
return cognito_idp.initiate_auth(ClientId=cid, AuthFlow="USER_PASSWORD_AUTH", AuthParameters=params)
+ # A wrong password is refused as wrong; only the right one learns a reset is required.
+ with pytest.raises(ClientError) as exc:
+ sign_in("Wrong1!")
+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"
with pytest.raises(ClientError) as exc:
sign_in("IvyPass1!")
assert exc.value.response["Error"]["Code"] == "PasswordResetRequiredException"
@@ -9007,9 +9011,7 @@ def test_cognito_srp_empty_challenge_responses(cognito_idp):
("sub as username", "UserNotFoundException", "User does not exist."),
("disabled", "NotAuthorizedException", "User is disabled."),
("unconfirmed", "UserNotConfirmedException", "User is not confirmed."),
- ("reset required", "PasswordResetRequiredException", "Password reset required for the user"),
-], ids=["missing-srp-a", "non-hex-srp-a", "client-without-srp", "unknown-user", "sub-as-username", "disabled", "unconfirmed",
- "reset-required"])
+], ids=["missing-srp-a", "non-hex-srp-a", "client-without-srp", "unknown-user", "sub-as-username", "disabled", "unconfirmed"])
def test_cognito_srp_initiate_refusals(cognito_idp, case, code, message):
flows = ["ALLOW_USER_PASSWORD_AUTH"] if case == "client without SRP" else ["ALLOW_USER_SRP_AUTH"]
pid, cid = _srp_pool(cognito_idp, flows)
@@ -9028,8 +9030,6 @@ def test_cognito_srp_initiate_refusals(cognito_idp, case, code, message):
elif case == "unconfirmed":
username = "srp-unconfirmed"
cognito_idp.sign_up(ClientId=cid, Username=username, Password="Correct1!")
- elif case == "reset required":
- cognito_idp.admin_reset_user_password(UserPoolId=pid, Username=username)
auth_params = {"USERNAME": username, **({"SRP_A": srp_a} if srp_a else {})}
with pytest.raises(ClientError) as exc:
cognito_idp.initiate_auth(ClientId=cid, AuthFlow="USER_SRP_AUTH", AuthParameters=auth_params)
@@ -9037,6 +9037,19 @@ def test_cognito_srp_initiate_refusals(cognito_idp, case, code, message):
assert exc.value.response["Error"]["Message"] == message
[email protected]("admin", [False, True])
+def test_cognito_srp_reset_required_is_answered_after_the_proof(cognito_idp, admin):
+ pid, cid = _srp_pool(cognito_idp)
+ cognito_idp.admin_reset_user_password(UserPoolId=pid, Username="srp-user")
+ with pytest.raises(ClientError) as exc:
+ _srp_sign_in(cognito_idp, pid, cid, "srp-user", "Wrong1!", admin=admin)
+ assert exc.value.response["Error"]["Code"] == "NotAuthorizedException"
+ with pytest.raises(ClientError) as exc:
+ _srp_sign_in(cognito_idp, pid, cid, "srp-user", "Correct1!", admin=admin)
+ assert exc.value.response["Error"]["Code"] == "PasswordResetRequiredException"
+ assert exc.value.response["Error"]["Message"] == "Password reset required for the user"
+
+
def test_cognito_srp_challenge_answers_repeated_proofs(cognito_idp):
"""A wrong proof does not use up the challenge, and a correct one can be sent twice."""
pid, cid = _srp_pool(cognito_idp)
diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.py
index ff7364e9..cfa8002e 100644
--- a/tests/test_dynamodb.py
+++ b/tests/test_dynamodb.py
@@ -7420,3 +7420,178 @@ def test_dynamodb_global_table_replica_update_errors():
for client in (other, home):
with contextlib.suppress(ClientError):
client.delete_table(TableName=name)
+
+
+def test_dynamodb_gsi_query_tracks_every_write_path(ddb):
+ name = f"gsi-track-{_uuid_mod.uuid4().hex[:8]}"
+ ddb.create_table(
+ TableName=name, BillingMode="PAY_PER_REQUEST",
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"},
+ {"AttributeName": "g", "AttributeType": "S"},
+ {"AttributeName": "r", "AttributeType": "N"}],
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ GlobalSecondaryIndexes=[{"IndexName": "byG",
+ "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"},
+ {"AttributeName": "r", "KeyType": "RANGE"}],
+ "Projection": {"ProjectionType": "ALL"}}])
+
+ def gsi(g):
+ resp = ddb.query(TableName=name, IndexName="byG", KeyConditionExpression="g = :g",
+ ExpressionAttributeValues={":g": {"S": g}})
+ return [it["pk"]["S"] for it in resp["Items"]]
+
+ try:
+ ddb.put_item(TableName=name, Item={"pk": {"S": "a"}, "g": {"S": "x"}, "r": {"N": "2"}})
+ ddb.put_item(TableName=name, Item={"pk": {"S": "b"}, "g": {"S": "x"}, "r": {"N": "1"}})
+ ddb.put_item(TableName=name, Item={"pk": {"S": "sparse"}, "g": {"S": "x"}})
+ assert gsi("x") == ["b", "a"]
+
+ ddb.update_item(TableName=name, Key={"pk": {"S": "a"}}, UpdateExpression="SET g = :y",
+ ExpressionAttributeValues={":y": {"S": "y"}})
+ assert gsi("x") == ["b"] and gsi("y") == ["a"]
+
+ ddb.batch_write_item(RequestItems={name: [
+ {"PutRequest": {"Item": {"pk": {"S": "c"}, "g": {"S": "y"}, "r": {"N": "0"}}}},
+ {"DeleteRequest": {"Key": {"pk": {"S": "b"}}}}]})
+ assert gsi("x") == [] and gsi("y") == ["c", "a"]
+
+ ddb.transact_write_items(TransactItems=[
+ {"Update": {"TableName": name, "Key": {"pk": {"S": "c"}}, "UpdateExpression": "SET g = :z",
+ "ExpressionAttributeValues": {":z": {"S": "z"}}}},
+ {"Delete": {"TableName": name, "Key": {"pk": {"S": "a"}}}}])
+ assert gsi("y") == [] and gsi("z") == ["c"]
+
+ ddb.execute_statement(Statement=f"UPDATE \"{name}\" SET g = 'w' WHERE pk = 'c'")
+ assert gsi("z") == [] and gsi("w") == ["c"]
+ ddb.execute_statement(Statement=f"INSERT INTO \"{name}\" VALUE {{'pk': 'd', 'g': 'w', 'r': 9}}")
+ assert gsi("w") == ["c", "d"]
+ ddb.execute_statement(Statement=f"DELETE FROM \"{name}\" WHERE pk = 'c'")
+ assert gsi("w") == ["d"]
+
+ ddb.delete_item(TableName=name, Key={"pk": {"S": "d"}})
+ assert gsi("w") == []
+ assert ddb.describe_table(TableName=name)["Table"]["ItemCount"] == 1
+ finally:
+ ddb.delete_table(TableName=name)
+
+
+def test_dynamodb_index_membership_not_persisted():
+ from ministack.services import dynamodb as _d
+ table = {"pk_name": "pk", "sk_name": None, "items": _d.defaultdict(dict),
+ "GlobalSecondaryIndexes": [{"IndexName": "byG",
+ "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}]}]}
+ _d._set_item(table, "a", "__no_sort__", {"pk": {"S": "a"}, "g": {"S": "x"}})
+ assert _d._index_members(table) == {"byG": {"x": {("a", "__no_sort__"): None}}}
+ _d._set_item(table, "a", "__no_sort__", {"pk": {"S": "a"}, "g": {"S": "y"}})
+ _d._set_item(table, "b", "__no_sort__", {"pk": {"S": "b"}})
+ assert _d._index_members(table) == {"byG": {"y": {("a", "__no_sort__"): None}}}
+ assert table["ItemCount"] == 2
+ _d._remove_item(table, "a", "__no_sort__")
+ assert _d._index_members(table) == {"byG": {}} and table["ItemCount"] == 1
+ assert "a" not in table["items"]
+ _d._tables.set_scoped("000000000000", "us-east-1", "persist-probe", table)
+ try:
+ state = _d.get_state()["tables"].get_scoped("000000000000", "us-east-1", "persist-probe")
+ assert _d._INDEX_MEMBERS not in state and _d._INDEX_MEMBERS in table
+ finally:
+ _d._tables.pop_scoped("000000000000", "us-east-1", "persist-probe", None)
+
+
+def test_dynamodb_client_request_token_expires_after_ten_minutes(monkeypatch):
+ from ministack.services import dynamodb as _d
+ now = [1_000_000.0]
+ monkeypatch.setattr(_d.time, "time", lambda: now[0])
+ monkeypatch.setattr(_d, "_txn_token_sweep_at", 0.0)
+ token, stale = f"crt-{_uuid_mod.uuid4().hex}", f"crt-{_uuid_mod.uuid4().hex}"
+ try:
+ _d._txn_token_store(stale, {"signature": {}, "response": {}})
+ now[0] += 300
+ _d._txn_token_store(token, {"signature": {}, "response": {}})
+ now[0] += 299
+ assert _d._txn_token_lookup(stale) is not None
+ now[0] += 1
+ assert _d._txn_token_lookup(stale) is None
+ assert _d._txn_token_lookup(token) is not None
+ now[0] += 300
+ assert _d._txn_token_lookup(token) is None
+ _d._txn_token_store(f"crt-{_uuid_mod.uuid4().hex}", {"signature": {}, "response": {}})
+ assert all(t not in (token, stale) for _, _, t in (k for k, _ in _d._txn_idempotency.all_items()))
+ finally:
+ _d._txn_idempotency.pop(token, None)
+ _d._txn_idempotency.pop(stale, None)
+
+
+def test_dynamodb_stream_skips_writes_that_change_nothing(ddb, ddb_streams):
+ name = f"noop-stream-{_uuid_mod.uuid4().hex[:8]}"
+ arn = ddb.create_table(
+ TableName=name, BillingMode="PAY_PER_REQUEST",
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ StreamSpecification={"StreamEnabled": True, "StreamViewType": "NEW_AND_OLD_IMAGES"},
+ )["TableDescription"]["LatestStreamArn"]
+ try:
+ item = {"pk": {"S": "a"}, "v": {"N": "1"}}
+ ddb.put_item(TableName=name, Item=item)
+ ddb.put_item(TableName=name, Item=item)
+ ddb.update_item(TableName=name, Key={"pk": {"S": "a"}}, UpdateExpression="SET v = :v",
+ ExpressionAttributeValues={":v": {"N": "1"}})
+ ddb.update_item(TableName=name, Key={"pk": {"S": "a"}}, UpdateExpression="SET v = :v",
+ ExpressionAttributeValues={":v": {"N": "2"}})
+ shard = ddb_streams.describe_stream(StreamArn=arn)["StreamDescription"]["Shards"][0]["ShardId"]
+ it = ddb_streams.get_shard_iterator(StreamArn=arn, ShardId=shard,
+ ShardIteratorType="TRIM_HORIZON")["ShardIterator"]
+ events = [r["eventName"] for r in ddb_streams.get_records(ShardIterator=it)["Records"]]
+ assert events == ["INSERT", "MODIFY"]
+ finally:
+ ddb.delete_table(TableName=name)
+
+
+def test_dynamodb_gsi_multi_attribute_keys(ddb):
+ name = f"multi-key-{_uuid_mod.uuid4().hex[:8]}"
+ ddb.create_table(
+ TableName=name, BillingMode="PAY_PER_REQUEST",
+ AttributeDefinitions=[{"AttributeName": n, "AttributeType": "S"} for n in ("pk", "a", "b", "s1", "s2")],
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ GlobalSecondaryIndexes=[{
+ "IndexName": "Idx", "Projection": {"ProjectionType": "ALL"},
+ "KeySchema": [{"AttributeName": "a", "KeyType": "HASH"}, {"AttributeName": "b", "KeyType": "HASH"},
+ {"AttributeName": "s1", "KeyType": "RANGE"}, {"AttributeName": "s2", "KeyType": "RANGE"}],
+ }])
+
+ def query(cond, **vals):
+ return ddb.query(TableName=name, IndexName="Idx", KeyConditionExpression=cond,
+ ExpressionAttributeValues={f":{k}": {"S": v} for k, v in vals.items()})
+
+ try:
+ rows = [("1", "x", "y", "p", "2"), ("2", "x", "y", "p", "1"), ("3", "x", "y", "q", "1"),
+ ("4", "x", "z", "p", "1"), ("5", "x", "y", "p", None)]
+ for pk, a, b, s1, s2 in rows:
+ item = {"pk": {"S": pk}, "a": {"S": a}, "b": {"S": b}, "s1": {"S": s1}}
+ if s2:
+ item["s2"] = {"S": s2}
+ ddb.put_item(TableName=name, Item=item)
+
+ def pks(resp):
+ return [it["pk"]["S"] for it in resp["Items"]]
+
+ assert pks(query("a = :a AND b = :b", a="x", b="y")) == ["2", "1", "3"]
+ assert pks(query("a = :a AND b = :b AND s1 = :s1 AND s2 >= :s2", a="x", b="y", s1="p", s2="2")) == ["1"]
+ assert pks(query("a = :a AND b = :b AND begins_with(s1, :s1)", a="x", b="y", s1="q")) == ["3"]
+ page = ddb.query(TableName=name, IndexName="Idx", Limit=1, KeyConditionExpression="a = :a AND b = :b",
+ ExpressionAttributeValues={":a": {"S": "x"}, ":b": {"S": "y"}})
+ assert set(page["LastEvaluatedKey"]) == {"pk", "a", "b", "s1", "s2"}
+ rest = ddb.query(TableName=name, IndexName="Idx", ExclusiveStartKey=page["LastEvaluatedKey"],
+ KeyConditionExpression="a = :a AND b = :b",
+ ExpressionAttributeValues={":a": {"S": "x"}, ":b": {"S": "y"}})
+ assert pks(rest) == ["1", "3"]
+
+ with pytest.raises(ClientError) as exc:
+ query("a = :a", a="x")
+ assert exc.value.response["Error"]["Message"] == "Query condition missed key schema element: b"
+ for cond, vals in (("a = :a AND b = :b AND s2 = :s2", {"s2": "1"}),
+ ("a = :a AND b = :b AND s1 > :s1 AND s2 = :s2", {"s1": "a", "s2": "1"})):
+ with pytest.raises(ClientError) as exc:
+ query(cond, a="x", b="y", **vals)
+ assert exc.value.response["Error"]["Message"] == "Query key condition not supported"
+ finally:
+ ddb.delete_table(TableName=name)
diff --git a/tests/test_dynamodb_streams.py b/tests/test_dynamodb_streams.py
index f574cab6..126048ec 100644
--- a/tests/test_dynamodb_streams.py
+++ b/tests/test_dynamodb_streams.py
@@ -7,6 +7,10 @@ visible through the public Streams API used by boto3.client("dynamodbstreams")
and by Lambda event-source mappings.
"""
+import contextlib
+import time
+import uuid
+
import pytest
from botocore.exceptions import ClientError
@@ -544,3 +548,39 @@ def test_records_expire_on_read_without_further_writes(streams_state):
assert _seqs(_json(streams_service._get_records({
"ShardIterator": _iterator(streams_service, arn, "TRIM_HORIZON"),
}))) == ["1"]
+
+
+def test_closed_stream_stays_readable_and_new_stream_starts_empty(ddb, ddb_streams):
+ name = f"closed-stream-{uuid.uuid4().hex[:8]}"
+ _make_table(ddb, name)
+ old_arn = _stream_arn(ddb, name)
+ try:
+ ddb.put_item(TableName=name, Item={"pk": {"S": "a"}})
+ ddb.update_table(TableName=name, StreamSpecification={"StreamEnabled": False})
+ desc = ddb_streams.describe_stream(StreamArn=old_arn)["StreamDescription"]
+ assert desc["StreamStatus"] == "DISABLED"
+ seq = desc["Shards"][0]["SequenceNumberRange"]
+ assert seq["EndingSequenceNumber"] == seq["StartingSequenceNumber"]
+ it = ddb_streams.get_shard_iterator(StreamArn=old_arn, ShardId=desc["Shards"][0]["ShardId"],
+ ShardIteratorType="TRIM_HORIZON")["ShardIterator"]
+ resp = ddb_streams.get_records(ShardIterator=it)
+ assert [r["eventName"] for r in resp["Records"]] == ["INSERT"]
+ assert "eventSourceARN" not in resp["Records"][0]
+ assert "NextShardIterator" not in resp
+
+ time.sleep(0.01)
+ ddb.update_table(TableName=name, StreamSpecification={"StreamEnabled": True,
+ "StreamViewType": "NEW_IMAGE"})
+ new_arn = _stream_arn(ddb, name)
+ assert new_arn != old_arn
+ shard = ddb_streams.describe_stream(StreamArn=new_arn)["StreamDescription"]["Shards"][0]["ShardId"]
+ it = ddb_streams.get_shard_iterator(StreamArn=new_arn, ShardId=shard,
+ ShardIteratorType="TRIM_HORIZON")["ShardIterator"]
+ assert ddb_streams.get_records(ShardIterator=it)["Records"] == []
+
+ ddb.delete_table(TableName=name)
+ assert ddb_streams.describe_stream(StreamArn=new_arn)["StreamDescription"]["StreamStatus"] == "DISABLED"
+ assert ddb_streams.describe_stream(StreamArn=old_arn)["StreamDescription"]["StreamStatus"] == "DISABLED"
+ finally:
+ with contextlib.suppress(ClientError):
+ ddb.delete_table(TableName=name)
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index b8e94fb7..3de3d7d5 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -14375,3 +14375,337 @@ def test_invocation_retains_alias_without_mutating_version(monkeypatch, asynchro
assert function == original
finally:
invalidate_worker(name)
+
+
+# ---------------------------------------------------------------------------
+# Invocation IDs and platform logs (one RequestId; RIE's own START/END/REPORT kept)
+# ---------------------------------------------------------------------------
+
+import asyncio
+import base64
+import io
+import json
+import re
+import shutil
+import time
+import urllib.error
+import uuid
+import zipfile
+from unittest.mock import Mock
+
+import pytest
+
+from ministack.core import lambda_runtime
+from ministack.core.responses import AccountRegionScopedDict
+from ministack.services import cloudwatch_logs as cwl
+from ministack.services import lambda_svc as _svc
+
+
+def log_state(monkeypatch):
+ monkeypatch.setattr(cwl, "_log_groups", AccountRegionScopedDict())
+ monkeypatch.setattr(cwl, "_fanout_to_subscription_filters", Mock())
+ monkeypatch.setattr(_svc, "_probe_peak_memory_mb", lambda func: 12)
+ monkeypatch.setattr(_svc, "_ensure_reaper_thread", lambda: None)
+ monkeypatch.setattr(_svc, "_proxy_url_for", lambda config: None)
+ monkeypatch.setattr(_svc, "LAMBDA_STRICT", False)
+ monkeypatch.setattr(_svc, "LAMBDA_EXECUTOR", "local")
+
+
+def _function(runtime="python3.12", code_zip=None):
+ name = "invocation-logs-" + uuid.uuid4().hex
+ return {"config": {
+ "FunctionName": name,
+ "FunctionArn": _svc._func_arn(name),
+ "Runtime": runtime, "Handler": "index.handler", "Version": "$LATEST",
+ "MemorySize": 128, "Timeout": 10, "PackageType": "Zip",
+ }, "code_zip": code_zip}
+
+
+def _messages(func):
+ group = cwl._log_groups["/aws/lambda/" + func["config"]["FunctionName"]]
+ return [e["message"] for s in group["streams"].values() for e in s["events"]]
+
+
+def _assert_platform_lines(messages, request_id):
+ for kind in ("START", "END", "REPORT"):
+ ids = [m.group(1) for line in messages
+ if (m := re.match(rf"^{kind} RequestId: (\S+)", line))]
+ assert ids == [request_id]
+
+
[email protected]("mode,target", [
+ ("python", "_execute_function_warm"), ("node", "_execute_function_warm"),
+ ("docker", "_execute_function_docker"), ("strict", "_execute_function_docker"),
+ ("image", "_execute_function_docker"), ("other", "_execute_function_docker"),
+ ("provided", "_execute_function_provided_warm"),
+ ("durable", "_execute_function_provided"), ("proxy", "_execute_function_proxy"),
+])
+def test_execute_function_generates_one_request_id(monkeypatch, log_state, mode, target):
+ func = _function()
+ if mode == "node":
+ func["config"]["Runtime"] = "nodejs22.x"
+ elif mode == "other":
+ func["config"]["Runtime"] = "ruby3.3"
+ elif mode in ("provided", "durable"):
+ func["config"]["Runtime"] = "provided.al2023"
+ elif mode == "image":
+ func["config"].update(PackageType="Image", ImageUri="example:latest")
+ monkeypatch.setattr(_svc, "LAMBDA_EXECUTOR", "docker" if mode == "docker" else "local")
+ monkeypatch.setattr(_svc, "LAMBDA_STRICT", mode == "strict")
+ if mode == "proxy":
+ monkeypatch.setattr(_svc, "_proxy_url_for", lambda config: "http://proxy")
+ generated = Mock(return_value="invocation-id")
+ executor = Mock(return_value={"body": {"ok": True}, "log": "user output"})
+ emit = Mock()
+ monkeypatch.setattr(_svc, "new_uuid", generated)
+ monkeypatch.setattr(_svc, target, executor)
+ monkeypatch.setattr(_svc, "_emit_lambda_logs", emit)
+ token = _svc._durable_ctx.set({"arn": "execution"} if mode == "durable" else None)
+ try:
+ _svc._execute_function(func, {"input": 1})
+ finally:
+ _svc._durable_ctx.reset(token)
+ generated.assert_called_once_with()
+ args = (func, {"input": 1}, "http://proxy", "invocation-id") if mode == "proxy" else (
+ func, {"input": 1}, "invocation-id")
+ executor.assert_called_once_with(*args)
+ assert emit.call_args.args[1] == "invocation-id"
+
+
[email protected]("unavailable", ["sdk", "daemon"])
[email protected]("runtime,target", [
+ ("python3.12", "_execute_function_warm"),
+ ("nodejs22.x", "_execute_function_warm"),
+ ("ruby3.3", "_execute_function_local"),
+])
+def test_docker_fallback_preserves_id_and_synthetic_logs(
+ monkeypatch, log_state, unavailable, runtime, target):
+ func = _function(runtime, b"zip")
+ monkeypatch.setattr(_svc, "_docker_available", unavailable != "sdk")
+ monkeypatch.setattr(_svc, "_get_docker_client", lambda: None)
+ executor = Mock(return_value={"body": {}, "log": "USER_PRINT fallback"})
+ monkeypatch.setattr(_svc, target, executor)
+ monkeypatch.setattr(_svc, "LAMBDA_EXECUTOR", "docker")
+ _svc._execute_function_dispatch(func, func["config"], {}, "same-id", time.time())
+ executor.assert_called_once_with(func, {}, "same-id")
+ _assert_platform_lines(_messages(func), "same-id")
+
+
[email protected]("log_source,error", [(None, False), ("rie", False), ("rie", True)])
+def test_invoke_preserves_log_provenance_and_tail(monkeypatch, log_state, log_source, error):
+ func = _function()
+ raw = "START RequestId: same-id Version: $LATEST\nUSER_PRINT once\nEND RequestId: same-id\nREPORT RequestId: same-id\tDuration: 1.25 ms"
+ monkeypatch.setitem(_svc._functions, func["config"]["FunctionName"], func)
+ monkeypatch.setattr(_svc, "LAMBDA_EXECUTOR", "docker")
+ monkeypatch.setattr(_svc, "_execute_function_docker", Mock(return_value={
+ "body": {}, "log": raw, "log_source": log_source, "error": error}))
+ monkeypatch.setattr(_svc, "_emit_lambda_metrics", lambda *args, **kwargs: None)
+ monkeypatch.setattr(_svc, "new_uuid", lambda: "same-id")
+ status, headers, _ = asyncio.run(_svc._invoke(func["config"]["FunctionName"], {}, {"x-amz-log-type": "Tail"}))
+ assert status == 200
+ assert ("X-Amz-Function-Error" in headers) == error
+ tail = base64.b64decode(headers["X-Amz-Log-Result"]).decode().splitlines()
+ assert tail == raw.splitlines()
+ messages = _messages(func)
+ # User-written platform-looking lines remain user logs without RIE metadata.
+ assert (messages if log_source == "rie" else messages[1:-2]) == tail
+ if log_source == "rie":
+ _assert_platform_lines(messages, "same-id")
+ else:
+ _assert_platform_lines([messages[0], *messages[-2:]], "same-id")
+ assert len(messages) == len(tail) + 3
+ forwarded = cwl._fanout_to_subscription_filters.call_args.args[2]
+ assert [e["message"] for e in forwarded] == messages
+
+
[email protected]("raw", ["", "partial runtime output"])
+def test_rie_empty_and_partial_logs_get_one_platform_sequence(log_state, raw):
+ func = _function()
+ _svc._emit_lambda_logs(func, "same-id", raw, True, 1, log_source="rie")
+ messages = _messages(func)
+ _assert_platform_lines(messages, "same-id")
+ if raw:
+ assert messages[1:-2] == [raw]
+
+
+def test_rie_failure_output_gets_its_missing_end_and_report(log_state):
+ """RIE prints START but no END/REPORT when init or the invoke fails (502)."""
+ func = _function()
+ raw = "START RequestId: same-id Version: $LATEST\nRuntime.ImportModuleError: no module"
+ _svc._emit_lambda_logs(func, "same-id", raw, True, 1, log_source="rie")
+ messages = _messages(func)
+ _assert_platform_lines(messages, "same-id")
+ assert messages[:2] == raw.splitlines()
+
+
[email protected]("outcome", ["ok", "handler-error", "init-error", "read-timeout", "not-running"])
+def test_invoke_rie_passes_request_id_and_marks_actual_rie_output(monkeypatch, outcome):
+ container = Mock()
+ container.status = "exited" if outcome == "not-running" else "running"
+ container.attrs = {"NetworkSettings": {"Networks": {}}}
+ container.ports = {"8080/tcp": [{"HostPort": "12345"}]}
+ container.logs.return_value = b"opaque output"
+ monkeypatch.setattr(_svc, "_running_in_container", lambda: False)
+ monkeypatch.setattr(_svc, "LAMBDA_DOCKER_NETWORK", "")
+ response = Mock(headers={})
+ response.read.return_value = json.dumps(
+ {"errorType": "ValueError", "errorMessage": "failed"} if outcome == "handler-error" else {"ok": True}
+ ).encode()
+ seen = []
+
+ def post(req, timeout):
+ seen.append(req)
+ if outcome == "init-error":
+ raise urllib.error.HTTPError(req.full_url, 502, "Bad Gateway", {}, io.BytesIO(b"{}"))
+ if outcome == "read-timeout":
+ raise TimeoutError("timed out")
+ return response
+
+ monkeypatch.setattr(_svc.urllib.request, "urlopen", post)
+ result = _svc._invoke_rie(container, {"input": 1}, 3, "same-id")
+ assert result["log"] == "opaque output"
+ if outcome == "not-running":
+ assert not seen
+ assert "log_source" not in result
+ else:
+ assert len(seen) == 1
+ assert dict(seen[0].header_items())["X-amzn-requestid"] == "same-id"
+ assert json.loads(seen[0].data) == {"input": 1}
+ assert result["log_source"] == "rie"
+
+
+_PYTHON_HANDLER = """import logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger()
+logger.setLevel(logging.INFO)
+def handler(event, context):
+ print('USER_PRINT ' + event['marker'], flush=True)
+ logger.info('USER_INFO %s', event['marker'])
+ return {'request_id': context.aws_request_id, 'stream': context.log_stream_name}
+"""
+_NODE_HANDLER = """exports.handler = async (event, context) => {
+ return {request_id: context.awsRequestId, stream: context.logStreamName};
+};
+"""
+_PROVIDED_BOOTSTRAP = """#!/usr/bin/env python3
+import json, os, urllib.request
+base = 'http://' + os.environ['AWS_LAMBDA_RUNTIME_API'] + '/2018-06-01/runtime/'
+while True:
+ response = urllib.request.urlopen(base + 'invocation/next')
+ request_id = response.headers['Lambda-Runtime-Aws-Request-Id']
+ response.read()
+ payload = json.dumps({'request_id': request_id}).encode()
+ urllib.request.urlopen(urllib.request.Request(base + 'invocation/' + request_id + '/response', data=payload)).read()
+ if os.environ.get('PROBE_ONE_SHOT'):
+ break
+"""
+
+
+def _code_zip():
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w") as archive:
+ archive.writestr("index.py", _PYTHON_HANDLER)
+ archive.writestr("index.js", _NODE_HANDLER)
+ bootstrap = zipfile.ZipInfo("bootstrap")
+ bootstrap.external_attr = 0o100755 << 16
+ archive.writestr(bootstrap, _PROVIDED_BOOTSTRAP)
+ return output.getvalue()
+
+
+def _assert_two_invocations(func, *, rie=False):
+ previous_id = None
+ for seq in range(2):
+ marker = str(seq)
+ before = len(_messages(func)) if seq else 0
+ result = _svc._execute_function(func, {"marker": marker})
+ assert not result.get("error"), result
+ request_id = result["body"]["request_id"]
+ assert request_id != previous_id
+ if func["config"]["Runtime"].startswith(("python", "nodejs")):
+ assert request_id != result["body"]["stream"]
+ messages = _messages(func)[before:]
+ _assert_platform_lines(messages, request_id)
+ if rie:
+ assert result["log_source"] == "rie"
+ assert messages == result["log"].splitlines()
+ if func["config"]["Runtime"].startswith("python"):
+ for kind in ("USER_PRINT", "USER_INFO"):
+ assert sum(kind + " " + marker in line for line in messages) == 1
+ previous_id = request_id
+
+
[email protected]("runtime", ["python3.12", "nodejs22.x"])
[email protected]("executor", ["warm", "local"])
+def test_real_python_and_node_invocations_share_platform_request_id(monkeypatch, log_state, runtime, executor):
+ if runtime.startswith("nodejs") and not shutil.which("node"):
+ pytest.skip("Node.js is required")
+ if executor == "local" and runtime.startswith("python") and not shutil.which("python3"):
+ pytest.skip("local executor requires python3")
+ if executor == "local":
+ monkeypatch.setattr(_svc, "_execute_function_warm", _svc._execute_function_local)
+ func = _function(runtime, _code_zip())
+ try:
+ _assert_two_invocations(func)
+ finally:
+ lambda_runtime.invalidate_worker(func["config"]["FunctionName"])
+
+
[email protected]("one_shot", [False, True])
+def test_real_provided_runtime_receives_platform_request_id(monkeypatch, log_state, one_shot):
+ if not shutil.which("python3"):
+ pytest.skip("provided bootstrap requires /usr/bin/env python3")
+ func = _function("provided.al2023", _code_zip())
+ if one_shot:
+ func["config"]["Environment"] = {"Variables": {"PROBE_ONE_SHOT": "1"}}
+ token = _svc._durable_ctx.set({"arn": "execution"} if one_shot else None)
+ try:
+ _assert_two_invocations(func)
+ finally:
+ _svc._durable_ctx.reset(token)
+ lambda_runtime.invalidate_worker(func["config"]["FunctionName"])
+
+
[email protected](scope="module")
+def python_lambda_image(tmp_path_factory):
+ docker = pytest.importorskip("docker")
+ try:
+ client = docker.from_env()
+ client.ping()
+ except docker.errors.DockerException as exc:
+ pytest.skip(f"Docker daemon unavailable: {exc}")
+ base = "public.ecr.aws/lambda/python:3.12"
+ try:
+ client.images.get(base)
+ except docker.errors.ImageNotFound:
+ client.images.pull(base)
+ tag = "ministack-log-test:" + uuid.uuid4().hex
+ build_dir = tmp_path_factory.mktemp("lambda-image")
+ (build_dir / "Dockerfile").write_text(
+ 'FROM ' + base + '\nCOPY index.py /var/task/index.py\nCMD ["index.handler"]\n', encoding="utf-8")
+ (build_dir / "index.py").write_text(_PYTHON_HANDLER, encoding="utf-8")
+ client.images.build(path=str(build_dir), tag=tag, rm=True)
+ try:
+ yield tag
+ finally:
+ client.images.remove(tag)
+ client.close()
+
+
[email protected]("package_type", ["Zip", "Image"])
+def test_real_docker_invocations_have_one_platform_log_sequence(monkeypatch, log_state, request, package_type):
+ if _svc._get_docker_client() is None:
+ pytest.skip("Docker daemon unavailable")
+ monkeypatch.setattr(_svc, "LAMBDA_EXECUTOR", "docker")
+ monkeypatch.setattr(_svc, "_KEEPALIVE_KILL_ON_RELEASE", False)
+ spawn = Mock(wraps=_svc._spawn_lambda_container)
+ monkeypatch.setattr(_svc, "_spawn_lambda_container", spawn)
+ func = _function(code_zip=_code_zip())
+ if package_type == "Image":
+ func["config"].update(PackageType="Image", ImageUri=request.getfixturevalue("python_lambda_image"))
+ try:
+ _assert_two_invocations(func, rie=True)
+ spawn.assert_called_once() # The second invocation must reuse the environment.
+ finally:
+ _svc._pool_kill_function("000000000000", func["config"]["FunctionName"])
diff --git a/tests/test_lambda_invocation_logs.py b/tests/test_lambda_invocation_logs.py
deleted file mode 100644
index 2a7def91..00000000
--- a/tests/test_lambda_invocation_logs.py
+++ /dev/null
@@ -1,322 +0,0 @@
-"""Invocation IDs and platform logs: AWS docs and local RIE observations.
-
-Docker tests use real RIE containers; no live AWS account validation is claimed.
-"""
-import asyncio
-import base64
-import io
-import json
-import re
-import shutil
-import time
-import urllib.error
-import uuid
-import zipfile
-from unittest.mock import Mock
-
-import pytest
-
-from ministack.core import lambda_runtime
-from ministack.core.responses import AccountRegionScopedDict
-from ministack.services import cloudwatch_logs as cwl
-from ministack.services import lambda_svc as svc
-
-
-def log_state(monkeypatch):
- monkeypatch.setattr(cwl, "_log_groups", AccountRegionScopedDict())
- monkeypatch.setattr(cwl, "_fanout_to_subscription_filters", Mock())
- monkeypatch.setattr(svc, "_probe_peak_memory_mb", lambda func: 12)
- monkeypatch.setattr(svc, "_ensure_reaper_thread", lambda: None)
- monkeypatch.setattr(svc, "_proxy_url_for", lambda config: None)
- monkeypatch.setattr(svc, "LAMBDA_STRICT", False)
- monkeypatch.setattr(svc, "LAMBDA_EXECUTOR", "local")
-
-
-def _function(runtime="python3.12", code_zip=None):
- name = "invocation-logs-" + uuid.uuid4().hex
- return {"config": {
- "FunctionName": name,
- "FunctionArn": svc._func_arn(name),
- "Runtime": runtime, "Handler": "index.handler", "Version": "$LATEST",
- "MemorySize": 128, "Timeout": 10, "PackageType": "Zip",
- }, "code_zip": code_zip}
-
-
-def _messages(func):
- group = cwl._log_groups["/aws/lambda/" + func["config"]["FunctionName"]]
- return [e["message"] for s in group["streams"].values() for e in s["events"]]
-
-
-def _assert_platform_lines(messages, request_id):
- for kind in ("START", "END", "REPORT"):
- ids = [m.group(1) for line in messages
- if (m := re.match(rf"^{kind} RequestId: (\S+)", line))]
- assert ids == [request_id]
-
-
[email protected]("mode,target", [
- ("python", "_execute_function_warm"), ("node", "_execute_function_warm"),
- ("docker", "_execute_function_docker"), ("strict", "_execute_function_docker"),
- ("image", "_execute_function_docker"), ("other", "_execute_function_docker"),
- ("provided", "_execute_function_provided_warm"),
- ("durable", "_execute_function_provided"), ("proxy", "_execute_function_proxy"),
-])
-def test_execute_function_generates_one_request_id(monkeypatch, log_state, mode, target):
- func = _function()
- if mode == "node":
- func["config"]["Runtime"] = "nodejs22.x"
- elif mode == "other":
- func["config"]["Runtime"] = "ruby3.3"
- elif mode in ("provided", "durable"):
- func["config"]["Runtime"] = "provided.al2023"
- elif mode == "image":
- func["config"].update(PackageType="Image", ImageUri="example:latest")
- monkeypatch.setattr(svc, "LAMBDA_EXECUTOR", "docker" if mode == "docker" else "local")
- monkeypatch.setattr(svc, "LAMBDA_STRICT", mode == "strict")
- if mode == "proxy":
- monkeypatch.setattr(svc, "_proxy_url_for", lambda config: "http://proxy")
- generated = Mock(return_value="invocation-id")
- executor = Mock(return_value={"body": {"ok": True}, "log": "user output"})
- emit = Mock()
- monkeypatch.setattr(svc, "new_uuid", generated)
- monkeypatch.setattr(svc, target, executor)
- monkeypatch.setattr(svc, "_emit_lambda_logs", emit)
- token = svc._durable_ctx.set({"arn": "execution"} if mode == "durable" else None)
- try:
- svc._execute_function(func, {"input": 1})
- finally:
- svc._durable_ctx.reset(token)
- generated.assert_called_once_with()
- args = (func, {"input": 1}, "http://proxy", "invocation-id") if mode == "proxy" else (
- func, {"input": 1}, "invocation-id")
- executor.assert_called_once_with(*args)
- assert emit.call_args.args[1] == "invocation-id"
-
-
[email protected]("unavailable", ["sdk", "daemon"])
[email protected]("runtime,target", [
- ("python3.12", "_execute_function_warm"),
- ("nodejs22.x", "_execute_function_warm"),
- ("ruby3.3", "_execute_function_local"),
-])
-def test_docker_fallback_preserves_id_and_synthetic_logs(
- monkeypatch, log_state, unavailable, runtime, target):
- func = _function(runtime, b"zip")
- monkeypatch.setattr(svc, "_docker_available", unavailable != "sdk")
- monkeypatch.setattr(svc, "_get_docker_client", lambda: None)
- executor = Mock(return_value={"body": {}, "log": "USER_PRINT fallback"})
- monkeypatch.setattr(svc, target, executor)
- monkeypatch.setattr(svc, "LAMBDA_EXECUTOR", "docker")
- svc._execute_function_dispatch(func, func["config"], {}, "same-id", time.time())
- executor.assert_called_once_with(func, {}, "same-id")
- _assert_platform_lines(_messages(func), "same-id")
-
-
[email protected]("log_source,error", [(None, False), ("rie", False), ("rie", True)])
-def test_invoke_preserves_log_provenance_and_tail(monkeypatch, log_state, log_source, error):
- func = _function()
- raw = "START RequestId: same-id Version: $LATEST\nUSER_PRINT once\nEND RequestId: same-id\nREPORT RequestId: same-id\tDuration: 1.25 ms"
- monkeypatch.setitem(svc._functions, func["config"]["FunctionName"], func)
- monkeypatch.setattr(svc, "LAMBDA_EXECUTOR", "docker")
- monkeypatch.setattr(svc, "_execute_function_docker", Mock(return_value={
- "body": {}, "log": raw, "log_source": log_source, "error": error}))
- monkeypatch.setattr(svc, "_emit_lambda_metrics", lambda *args, **kwargs: None)
- monkeypatch.setattr(svc, "new_uuid", lambda: "same-id")
- status, headers, _ = asyncio.run(svc._invoke(func["config"]["FunctionName"], {}, {"x-amz-log-type": "Tail"}))
- assert status == 200
- assert ("X-Amz-Function-Error" in headers) == error
- tail = base64.b64decode(headers["X-Amz-Log-Result"]).decode().splitlines()
- assert tail == raw.splitlines()
- messages = _messages(func)
- # User-written platform-looking lines remain user logs without RIE metadata.
- assert (messages if log_source == "rie" else messages[1:-2]) == tail
- if log_source == "rie":
- _assert_platform_lines(messages, "same-id")
- else:
- _assert_platform_lines([messages[0], *messages[-2:]], "same-id")
- assert len(messages) == len(tail) + 3
- forwarded = cwl._fanout_to_subscription_filters.call_args.args[2]
- assert [e["message"] for e in forwarded] == messages
-
-
[email protected]("raw", ["", "partial runtime output"])
-def test_rie_empty_and_partial_logs_are_handled_without_text_parsing(log_state, raw):
- func = _function()
- svc._emit_lambda_logs(func, "same-id", raw, True, 1, log_source="rie")
- if raw:
- assert _messages(func) == [raw]
- else:
- _assert_platform_lines(_messages(func), "same-id")
-
-
[email protected]("outcome", ["ok", "handler-error", "init-error", "read-timeout", "not-running"])
-def test_invoke_rie_passes_request_id_and_marks_actual_rie_output(monkeypatch, outcome):
- container = Mock()
- container.status = "exited" if outcome == "not-running" else "running"
- container.attrs = {"NetworkSettings": {"Networks": {}}}
- container.ports = {"8080/tcp": [{"HostPort": "12345"}]}
- container.logs.return_value = b"opaque output"
- monkeypatch.setattr(svc, "_running_in_container", lambda: False)
- monkeypatch.setattr(svc, "LAMBDA_DOCKER_NETWORK", "")
- response = Mock(headers={})
- response.read.return_value = json.dumps(
- {"errorType": "ValueError", "errorMessage": "failed"} if outcome == "handler-error" else {"ok": True}
- ).encode()
- seen = []
-
- def post(req, timeout):
- seen.append(req)
- if outcome == "init-error":
- raise urllib.error.HTTPError(req.full_url, 502, "Bad Gateway", {}, io.BytesIO(b"{}"))
- if outcome == "read-timeout":
- raise TimeoutError("timed out")
- return response
-
- monkeypatch.setattr(svc.urllib.request, "urlopen", post)
- result = svc._invoke_rie(container, {"input": 1}, 3, "same-id")
- assert result["log"] == "opaque output"
- if outcome == "not-running":
- assert not seen
- assert "log_source" not in result
- else:
- assert len(seen) == 1
- assert dict(seen[0].header_items())["X-amzn-requestid"] == "same-id"
- assert json.loads(seen[0].data) == {"input": 1}
- assert result["log_source"] == "rie"
-
-
-_PYTHON_HANDLER = """import logging
-logging.basicConfig(level=logging.INFO)
-logger = logging.getLogger()
-logger.setLevel(logging.INFO)
-def handler(event, context):
- print('USER_PRINT ' + event['marker'], flush=True)
- logger.info('USER_INFO %s', event['marker'])
- return {'request_id': context.aws_request_id, 'stream': context.log_stream_name}
-"""
-_NODE_HANDLER = """exports.handler = async (event, context) => {
- return {request_id: context.awsRequestId, stream: context.logStreamName};
-};
-"""
-_PROVIDED_BOOTSTRAP = """#!/usr/bin/env python3
-import json, os, urllib.request
-base = 'http://' + os.environ['AWS_LAMBDA_RUNTIME_API'] + '/2018-06-01/runtime/'
-while True:
- response = urllib.request.urlopen(base + 'invocation/next')
- request_id = response.headers['Lambda-Runtime-Aws-Request-Id']
- response.read()
- payload = json.dumps({'request_id': request_id}).encode()
- urllib.request.urlopen(urllib.request.Request(base + 'invocation/' + request_id + '/response', data=payload)).read()
- if os.environ.get('PROBE_ONE_SHOT'):
- break
-"""
-
-
-def _code_zip():
- output = io.BytesIO()
- with zipfile.ZipFile(output, "w") as archive:
- archive.writestr("index.py", _PYTHON_HANDLER)
- archive.writestr("index.js", _NODE_HANDLER)
- bootstrap = zipfile.ZipInfo("bootstrap")
- bootstrap.external_attr = 0o100755 << 16
- archive.writestr(bootstrap, _PROVIDED_BOOTSTRAP)
- return output.getvalue()
-
-
-def _assert_two_invocations(func, *, rie=False):
- previous_id = None
- for seq in range(2):
- marker = str(seq)
- before = len(_messages(func)) if seq else 0
- result = svc._execute_function(func, {"marker": marker})
- assert not result.get("error"), result
- request_id = result["body"]["request_id"]
- assert request_id != previous_id
- if func["config"]["Runtime"].startswith(("python", "nodejs")):
- assert request_id != result["body"]["stream"]
- messages = _messages(func)[before:]
- _assert_platform_lines(messages, request_id)
- if rie:
- assert result["log_source"] == "rie"
- assert messages == result["log"].splitlines()
- if func["config"]["Runtime"].startswith("python"):
- for kind in ("USER_PRINT", "USER_INFO"):
- assert sum(kind + " " + marker in line for line in messages) == 1
- previous_id = request_id
-
-
[email protected]("runtime", ["python3.12", "nodejs22.x"])
[email protected]("executor", ["warm", "local"])
-def test_real_python_and_node_invocations_share_platform_request_id(monkeypatch, log_state, runtime, executor):
- if runtime.startswith("nodejs") and not shutil.which("node"):
- pytest.skip("Node.js is required")
- if executor == "local" and runtime.startswith("python") and not shutil.which("python3"):
- pytest.skip("local executor requires python3")
- if executor == "local":
- monkeypatch.setattr(svc, "_execute_function_warm", svc._execute_function_local)
- func = _function(runtime, _code_zip())
- try:
- _assert_two_invocations(func)
- finally:
- lambda_runtime.invalidate_worker(func["config"]["FunctionName"])
-
-
[email protected]("one_shot", [False, True])
-def test_real_provided_runtime_receives_platform_request_id(monkeypatch, log_state, one_shot):
- if not shutil.which("python3"):
- pytest.skip("provided bootstrap requires /usr/bin/env python3")
- func = _function("provided.al2023", _code_zip())
- if one_shot:
- func["config"]["Environment"] = {"Variables": {"PROBE_ONE_SHOT": "1"}}
- token = svc._durable_ctx.set({"arn": "execution"} if one_shot else None)
- try:
- _assert_two_invocations(func)
- finally:
- svc._durable_ctx.reset(token)
- lambda_runtime.invalidate_worker(func["config"]["FunctionName"])
-
-
[email protected](scope="module")
-def python_lambda_image(tmp_path_factory):
- docker = pytest.importorskip("docker")
- try:
- client = docker.from_env()
- client.ping()
- except docker.errors.DockerException as exc:
- pytest.skip(f"Docker daemon unavailable: {exc}")
- base = "public.ecr.aws/lambda/python:3.12"
- try:
- client.images.get(base)
- except docker.errors.ImageNotFound:
- client.images.pull(base)
- tag = "ministack-log-test:" + uuid.uuid4().hex
- build_dir = tmp_path_factory.mktemp("lambda-image")
- (build_dir / "Dockerfile").write_text(
- 'FROM ' + base + '\nCOPY index.py /var/task/index.py\nCMD ["index.handler"]\n', encoding="utf-8")
- (build_dir / "index.py").write_text(_PYTHON_HANDLER, encoding="utf-8")
- client.images.build(path=str(build_dir), tag=tag, rm=True)
- try:
- yield tag
- finally:
- client.images.remove(tag)
- client.close()
-
-
[email protected]("package_type", ["Zip", "Image"])
-def test_real_docker_invocations_have_one_platform_log_sequence(monkeypatch, log_state, request, package_type):
- if svc._get_docker_client() is None:
- pytest.skip("Docker daemon unavailable")
- monkeypatch.setattr(svc, "LAMBDA_EXECUTOR", "docker")
- monkeypatch.setattr(svc, "_KEEPALIVE_KILL_ON_RELEASE", False)
- spawn = Mock(wraps=svc._spawn_lambda_container)
- monkeypatch.setattr(svc, "_spawn_lambda_container", spawn)
- func = _function(code_zip=_code_zip())
- if package_type == "Image":
- func["config"].update(PackageType="Image", ImageUri=request.getfixturevalue("python_lambda_image"))
- try:
- _assert_two_invocations(func, rie=True)
- spawn.assert_called_once() # The second invocation must reuse the environment.
- finally:
- svc._pool_kill_function("000000000000", func["config"]["FunctionName"])
diff --git a/tests/test_ministack.py b/tests/test_ministack.py
index a131bc42..45b9cbe7 100644
--- a/tests/test_ministack.py
+++ b/tests/test_ministack.py
@@ -1,11 +1,15 @@
"""Ministack admin/core tests — health, config, persistence, hypercorn compat."""
+import asyncio
import json
import os
+import xml.etree.ElementTree as ET
from urllib.parse import urlparse
import pytest
+from ministack import app as app_module
+
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
# ========== from test_ministack.py ==========
@@ -890,3 +894,136 @@ def test_a_failed_service_module_reports_no_state():
from ministack.app import _ErrorModule
assert _ErrorModule("appsync", "No module named 'graphql'").get_state() is None
+
+
+# Request-body framing (aws-chunked, Content-Length)
+
+ ("body", "headers"),
+ [
+ (b"3", {"content-encoding": "aws-chunked"}),
+ (b"x\r\n", {"content-encoding": "aws-chunked"}),
+ (b"3\r\nab", {"content-encoding": "aws-chunked"}),
+ (b"3\r\nabc\r\n", {"content-encoding": "aws-chunked"}),
+ (b"3\r\nabc\r\n0\r\n", {"content-encoding": "aws-chunked"}),
+ (
+ b"1\r\na\r\n0\r\n\r\n",
+ {"content-encoding": "aws-chunked", "x-amz-decoded-content-length": "2"},
+ ),
+ (
+ b"1\r\na\r\n0\r\n\r\n",
+ {"content-encoding": "aws-chunked", "x-amz-trailer": "x-amz-checksum-crc32"},
+ ),
+ ],
+)
+def test_decode_aws_chunked_rejects_incomplete_or_inconsistent_body(body, headers):
+ with pytest.raises(app_module._IncompleteRequestBody):
+ app_module._decode_aws_chunked_body(body, headers)
+
+
+def test_decode_aws_chunked_accepts_complete_body_and_announced_trailer():
+ body = (
+ b"3;chunk-signature=ignored\r\nabc\r\n"
+ b"0;chunk-signature=ignored\r\n"
+ b"x-amz-checksum-crc32: value\r\n\r\n"
+ )
+ headers = {
+ "content-encoding": "aws-chunked",
+ "x-amz-decoded-content-length": "3",
+ "x-amz-trailer": "x-amz-checksum-crc32",
+ }
+
+ assert app_module._decode_aws_chunked_body(body, headers) == b"abc"
+ assert headers["x-amz-checksum-crc32"] == "value"
+
+
+def _run_asgi_request(monkeypatch, headers, body_message):
+ messages = []
+ received = iter([body_message])
+
+ async def receive():
+ return next(received)
+
+ async def send(message):
+ messages.append(message)
+
+ async def unexpected_dispatch(*_args):
+ pytest.fail("incomplete request body reached service dispatch")
+
+ monkeypatch.setattr(app_module, "_dispatch_service_request", unexpected_dispatch)
+ scope = {
+ "type": "http",
+ "asgi": {"version": "3.0", "spec_version": "2.3"},
+ "http_version": "1.1",
+ "method": "PUT",
+ "scheme": "http",
+ "path": "/bucket/key",
+ "raw_path": b"/bucket/key",
+ "root_path": "",
+ "query_string": b"",
+ "headers": [(b"host", b"localhost:4566"), *headers],
+ "client": ("127.0.0.1", 55555),
+ "server": ("127.0.0.1", 4566),
+ }
+
+ asyncio.run(app_module.app(scope, receive, send))
+ return messages
+
+
+ ("headers", "body"),
+ [
+ ([(b"content-length", b"5")], b"abc"),
+ ([(b"content-encoding", b"aws-chunked")], b"3\r\nab"),
+ ],
+)
+def test_incomplete_s3_body_returns_incomplete_body_before_dispatch(monkeypatch, headers, body):
+ messages = _run_asgi_request(
+ monkeypatch,
+ headers,
+ {"type": "http.request", "body": body, "more_body": False},
+ )
+ response = next(message for message in messages if message["type"] == "http.response.start")
+ response_body = next(message["body"] for message in messages if message["type"] == "http.response.body")
+
+ assert response["status"] == 400
+ assert ET.fromstring(response_body).findtext("Code") == "IncompleteBody"
+ assert ET.fromstring(response_body).findtext("Message") == (
+ "You did not provide the number of bytes specified by the Content-Length HTTP header.")
+
+
+def test_s3_body_disconnect_stops_before_dispatch(monkeypatch):
+ messages = _run_asgi_request(monkeypatch, [], {"type": "http.disconnect"})
+
+ assert messages == []
+
+
+def test_incomplete_non_s3_body_is_dispatched_without_s3_error(monkeypatch):
+ dispatched = []
+
+ async def record_dispatch(*args):
+ dispatched.append(args)
+ return 200, {}, b""
+
+ monkeypatch.setattr(app_module, "_dispatch_service_request", record_dispatch)
+ sent = []
+
+ async def receive():
+ return {"type": "http.request", "body": b"Action=ListQueues", "more_body": False}
+
+ async def send(message):
+ sent.append(message)
+
+ scope = {
+ "type": "http", "asgi": {"version": "3.0", "spec_version": "2.3"}, "http_version": "1.1",
+ "method": "POST", "scheme": "http", "path": "/", "raw_path": b"/", "root_path": "",
+ "query_string": b"",
+ "headers": [(b"host", b"localhost:4566"), (b"content-length", b"99"),
+ (b"content-type", b"application/x-www-form-urlencoded"),
+ (b"authorization", b"AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/sqs/aws4_request, "
+ b"SignedHeaders=host, Signature=x")],
+ "client": ("127.0.0.1", 55555), "server": ("127.0.0.1", 4566),
+ }
+ asyncio.run(app_module.app(scope, receive, send))
+ assert all(b"IncompleteBody" not in m.get("body", b"") for m in sent)
+ assert len(dispatched) == 1 and dispatched[0][3] == b"Action=ListQueues"
diff --git a/tests/test_request_body.py b/tests/test_request_body.py
deleted file mode 100644
index fd1a42b0..00000000
--- a/tests/test_request_body.py
+++ /dev/null
@@ -1,104 +0,0 @@
-import asyncio
-import xml.etree.ElementTree as ET
-
-import pytest
-
-from ministack import app as app_module
-
-
- ("body", "headers"),
- [
- (b"3", {"content-encoding": "aws-chunked"}),
- (b"x\r\n", {"content-encoding": "aws-chunked"}),
- (b"3\r\nab", {"content-encoding": "aws-chunked"}),
- (b"3\r\nabc\r\n", {"content-encoding": "aws-chunked"}),
- (b"3\r\nabc\r\n0\r\n", {"content-encoding": "aws-chunked"}),
- (
- b"1\r\na\r\n0\r\n\r\n",
- {"content-encoding": "aws-chunked", "x-amz-decoded-content-length": "2"},
- ),
- (
- b"1\r\na\r\n0\r\n\r\n",
- {"content-encoding": "aws-chunked", "x-amz-trailer": "x-amz-checksum-crc32"},
- ),
- ],
-)
-def test_decode_aws_chunked_rejects_incomplete_or_inconsistent_body(body, headers):
- with pytest.raises(app_module._IncompleteRequestBody):
- app_module._decode_aws_chunked_body(body, headers)
-
-
-def test_decode_aws_chunked_accepts_complete_body_and_announced_trailer():
- body = (
- b"3;chunk-signature=ignored\r\nabc\r\n"
- b"0;chunk-signature=ignored\r\n"
- b"x-amz-checksum-crc32: value\r\n\r\n"
- )
- headers = {
- "content-encoding": "aws-chunked",
- "x-amz-decoded-content-length": "3",
- "x-amz-trailer": "x-amz-checksum-crc32",
- }
-
- assert app_module._decode_aws_chunked_body(body, headers) == b"abc"
- assert headers["x-amz-checksum-crc32"] == "value"
-
-
-def _run_asgi_request(monkeypatch, headers, body_message):
- messages = []
- received = iter([body_message])
-
- async def receive():
- return next(received)
-
- async def send(message):
- messages.append(message)
-
- async def unexpected_dispatch(*_args):
- pytest.fail("incomplete request body reached service dispatch")
-
- monkeypatch.setattr(app_module, "_dispatch_service_request", unexpected_dispatch)
- scope = {
- "type": "http",
- "asgi": {"version": "3.0", "spec_version": "2.3"},
- "http_version": "1.1",
- "method": "PUT",
- "scheme": "http",
- "path": "/bucket/key",
- "raw_path": b"/bucket/key",
- "root_path": "",
- "query_string": b"",
- "headers": [(b"host", b"localhost:4566"), *headers],
- "client": ("127.0.0.1", 55555),
- "server": ("127.0.0.1", 4566),
- }
-
- asyncio.run(app_module.app(scope, receive, send))
- return messages
-
-
- ("headers", "body"),
- [
- ([(b"content-length", b"5")], b"abc"),
- ([(b"content-encoding", b"aws-chunked")], b"3\r\nab"),
- ],
-)
-def test_incomplete_s3_body_returns_incomplete_body_before_dispatch(monkeypatch, headers, body):
- messages = _run_asgi_request(
- monkeypatch,
- headers,
- {"type": "http.request", "body": body, "more_body": False},
- )
- response = next(message for message in messages if message["type"] == "http.response.start")
- response_body = next(message["body"] for message in messages if message["type"] == "http.response.body")
-
- assert response["status"] == 400
- assert ET.fromstring(response_body).findtext("Code") == "IncompleteBody"
-
-
-def test_s3_body_disconnect_stops_before_dispatch(monkeypatch):
- messages = _run_asgi_request(monkeypatch, [], {"type": "http.disconnect"})
-
- assert messages == []
\ No newline at end of file
diff --git a/tests/test_s3.py b/tests/test_s3.py
index d59cbab6..297e70f2 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -7960,3 +7960,22 @@ def test_delete_objects_in_an_unversioned_bucket(s3, sqs, notified):
s3.delete_objects(Bucket=bucket, Delete={"Objects": [{"Key": "u.txt"}, {"Key": "never-there.txt"}]})
[record] = _event_records(sqs, url, 1)
assert (record["s3"]["object"]["key"], record["eventName"]) == ("u.txt", "ObjectRemoved:Delete")
+
+
+def test_s3_create_owned_bucket_again(s3):
+ east = f"owned-east-{_uuid_mod.uuid4().hex[:8]}"
+ west = f"owned-west-{_uuid_mod.uuid4().hex[:8]}"
+ s3.create_bucket(Bucket=east, ACL="public-read")
+ s3.create_bucket(Bucket=west, CreateBucketConfiguration={"LocationConstraint": "us-west-2"})
+ try:
+ s3.create_bucket(Bucket=east)
+ grants = s3.get_bucket_acl(Bucket=east)["Grants"]
+ assert [g["Permission"] for g in grants] == ["FULL_CONTROL"]
+ with pytest.raises(ClientError) as exc:
+ s3.create_bucket(Bucket=west, CreateBucketConfiguration={"LocationConstraint": "us-west-2"})
+ assert exc.value.response["Error"]["Code"] == "BucketAlreadyOwnedByYou"
+ assert exc.value.response["Error"]["Message"] == "The bucket you tried to create already exists, and you own it."
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409
+ finally:
+ s3.delete_bucket(Bucket=east)
+ s3.delete_bucket(Bucket=west)
diff --git a/tests/test_ses.py b/tests/test_ses.py
index 0c3e4f39..47286879 100644
--- a/tests/test_ses.py
+++ b/tests/test_ses.py
@@ -75,19 +75,6 @@ def test_ses_send_email_accepts_present_empty_content(monkeypatch, subject):
"Message.Body.Text.Data": [""],
}
assert ses_service._send_email(params)[0] == 200
- del params["Message.Subject.Data"]
- assert ses_service._send_email(params)[0] == 400
- params["Message.Subject.Data"] = [subject]
- del params["Message.Body.Text.Data"]
- assert ses_service._send_email(params)[0] == 400
-
-
-def test_ses_email_address_requires_ascii():
- from ministack.services.ses import _valid_email_address
-
- assert not _valid_email_address("user\[email protected]")
- assert not _valid_email_address("user@\u00e9xample.com")
- assert _valid_email_address("[email protected]")
def test_ses_send_email_rejects_invalid_address(ses):
@@ -102,6 +89,7 @@ def test_ses_send_email_rejects_invalid_address(ses):
},
)
assert exc.value.response["Error"]["Code"] == "InvalidParameterValue"
+ assert exc.value.response["Error"]["Message"] == "Missing final '@domain'"
def test_ses_send_email_rejects_missing_configuration_set(ses):
@@ -117,6 +105,9 @@ def test_ses_send_email_rejects_missing_configuration_set(ses):
ConfigurationSetName="missing-set",
)
assert exc.value.response["Error"]["Code"] == "ConfigurationSetDoesNotExist"
+ assert exc.value.response["Error"]["Message"] == "Configuration set missing-set does not exist"
+ assert exc.value.response["ConfigurationSetName"] == "missing-set"
+
def test_ses_list_identities(ses):
ses.verify_email_identity(EmailAddress="[email protected]")
diff --git a/tests/test_ses_v2.py b/tests/test_ses_v2.py
index e4bebb0c..52f53014 100644
--- a/tests/test_ses_v2.py
+++ b/tests/test_ses_v2.py
@@ -1272,3 +1272,23 @@ def test_tenant_association_normalizes_foreign_partitions(sesv2):
sesv2.tag_resource(ResourceArn=cn_arn, Tags=[{"Key": "ck", "Value": "v"}])
sesv2.delete_tenant(TenantName=name)
sesv2.delete_configuration_set(ConfigurationSetName=cs)
+
+
+def test_dedicated_ip_pool_lifecycle(sesv2):
+ name = f"pool-{uuid.uuid4().hex[:8]}"
+ sesv2.create_dedicated_ip_pool(PoolName=name, ScalingMode="MANAGED", Tags=[{"Key": "k", "Value": "v"}])
+ try:
+ assert sesv2.get_dedicated_ip_pool(PoolName=name)["DedicatedIpPool"] == {
+ "PoolName": name, "ScalingMode": "MANAGED"}
+ assert name in sesv2.list_dedicated_ip_pools()["DedicatedIpPools"]
+ arn = f"arn:aws:ses:us-east-1:000000000000:dedicated-ip-pool/{name}"
+ assert sesv2.list_tags_for_resource(ResourceArn=arn)["Tags"] == [{"Key": "k", "Value": "v"}]
+ with pytest.raises(ClientError) as exc:
+ sesv2.create_dedicated_ip_pool(PoolName=name)
+ assert exc.value.response["Error"]["Code"] == "AlreadyExistsException"
+ finally:
+ sesv2.delete_dedicated_ip_pool(PoolName=name)
+ with pytest.raises(ClientError) as exc:
+ sesv2.get_dedicated_ip_pool(PoolName=name)
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
diff --git a/tests/test_sns.py b/tests/test_sns.py
index b6d13571..657ffec3 100644
--- a/tests/test_sns.py
+++ b/tests/test_sns.py
@@ -1990,7 +1990,6 @@ def _seed_internal_topic(_sns, name, *, attributes=None, subscriptions=()):
_sns._topics[arn] = {
"name": name,
"arn": arn,
- "messages": [],
"subscriptions": list(subscriptions),
"attributes": attributes or {},
}
@@ -2000,10 +1999,9 @@ def _seed_internal_topic(_sns, name, *, attributes=None, subscriptions=()):
def test_sns_publish_internal_stores_the_record_and_fans_out(sns_internal, monkeypatch):
"""A publish through the seam gets everything an HTTP one gets.
- The message_structure and message_attributes here are the two fields the
- hand-rolled `topic["messages"].append(...)` this replaced used to drop, and
- both are load-bearing: the first picks the per-protocol body, the second is
- what a subscription filter policy reads.
+ The message_structure and message_attributes here are both load-bearing:
+ the first picks the per-protocol body, the second is what a subscription
+ filter policy reads.
"""
delivered = []
monkeypatch.setattr(
@@ -2036,12 +2034,7 @@ def test_sns_publish_internal_stores_the_record_and_fans_out(sns_internal, monke
assert result["sequence_number"] is None
assert result["message_id"]
- stored = sns_internal._topics[arn]["messages"]
- assert len(stored) == 1
- assert stored[0]["id"] == result["message_id"]
- assert stored[0]["subject"] == "a subject"
- assert stored[0]["message_structure"] == "json"
- assert stored[0]["message_attributes"] == attrs
+ assert "messages" not in sns_internal._topics[arn]
# message_structure picked the sqs body rather than the default one.
assert delivered == ["for-sqs"]
@@ -2121,8 +2114,7 @@ def test_sns_publish_internal_fifo_replays_a_duplicate_without_redelivering(
assert second["duplicate"] is True
assert second["message_id"] == first["message_id"]
assert second["sequence_number"] == first["sequence_number"]
- # ...and neither the store nor the subscriber saw it twice.
- assert len(sns_internal._topics[arn]["messages"]) == 1
+ # ...and the subscriber did not see it twice.
assert delivered == ["once"]
# A different dedup id inside the same group is a new message.
@@ -2131,7 +2123,7 @@ def test_sns_publish_internal_fifo_replays_a_duplicate_without_redelivering(
)
assert third["duplicate"] is False
assert third["sequence_number"] == "2".zfill(20)
- assert len(sns_internal._topics[arn]["messages"]) == 2
+ assert delivered == ["once", "twice"]
def test_sns_publish_internal_rejections(sns_internal):
@@ -2319,3 +2311,21 @@ def test_sns_topic_publish_is_not_in_the_sms_log(sns):
assert _sms_log(phoneNumber=phone)["sms_messages"] == {phone: []}
sns.delete_topic(TopicArn=topic_arn)
+
+
+def test_sns_to_sqs_delivery_waits_for_queue_delay(sns, sqs):
+ name = f"delayed-{_uuid_mod.uuid4().hex[:8]}"
+ topic = sns.create_topic(Name=name)["TopicArn"]
+ url = sqs.create_queue(QueueName=name, Attributes={"DelaySeconds": "2"})["QueueUrl"]
+ qarn = sqs.get_queue_attributes(QueueUrl=url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ sqs.set_queue_attributes(QueueUrl=url, Attributes={"Policy": json.dumps(sqs_policy_allow_sns(qarn, topic))})
+ try:
+ sns.subscribe(TopicArn=topic, Protocol="sqs", Endpoint=qarn,
+ Attributes={"RawMessageDelivery": "true"})
+ sns.publish(TopicArn=topic, Message="later")
+ assert "Messages" not in sqs.receive_message(QueueUrl=url)
+ time.sleep(2.2)
+ assert [m["Body"] for m in sqs.receive_message(QueueUrl=url)["Messages"]] == ["later"]
+ finally:
+ sns.delete_topic(TopicArn=topic)
+ sqs.delete_queue(QueueUrl=url)
diff --git a/tests/test_sqs.py b/tests/test_sqs.py
index 7179ca21..460370cc 100644
--- a/tests/test_sqs.py
+++ b/tests/test_sqs.py
@@ -777,14 +777,6 @@ def test_sqs_change_message_visibility_invalid_receipt_handle(sqs):
assert exc_info.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
-def test_sqs_receive_max_10(sqs):
- """ReceiveMessage with MaxNumberOfMessages > 10 is capped at 10."""
- url = sqs.create_queue(QueueName="qa-sqs-max10")["QueueUrl"]
- for i in range(15):
- sqs.send_message(QueueUrl=url, MessageBody=f"msg{i}")
- msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=15)
- assert len(msgs.get("Messages", [])) <= 10
-
def test_sqs_visibility_timeout_zero_makes_visible(sqs):
"""ChangeMessageVisibility to 0 makes message immediately visible again."""
url = sqs.create_queue(QueueName="qa-sqs-vis0")["QueueUrl"]
@@ -1938,8 +1930,6 @@ class TestCrossAccountSns:
arn, ACCT_B, "sns:Publish"))
assert _resp_code(_as(ACCT_B, sns_svc._publish, {
"TopicArn": arn, "Message": "granted"})) == (200, "")
- topic = sns_svc._topic_by_arn_any_scope(arn)
- assert [m["message"] for m in topic["messages"]] == ["granted"]
def test_explicit_deny_blocks_same_account(self, auth):
name = _uniq("xpol-t")
@@ -2290,3 +2280,40 @@ def test_queue_url_scheme_http_without_tls(monkeypatch):
name = _uniq("plain-scheme")
created = _as(ACCT_A, sqs_svc._act_create_queue, {"QueueName": name}, "")["QueueUrl"]
assert created.startswith("http://"), created
+
+
+def test_sqs_fifo_queue_delay_and_per_message_delay(sqs):
+ name = f"delay-{_uuid_mod.uuid4().hex[:8]}"
+ fifo = sqs.create_queue(QueueName=f"{name}.fifo", Attributes={
+ "FifoQueue": "true", "ContentBasedDeduplication": "true", "DelaySeconds": "2"})["QueueUrl"]
+ std = sqs.create_queue(QueueName=name, Attributes={"DelaySeconds": "2"})["QueueUrl"]
+ try:
+ with pytest.raises(ClientError) as exc:
+ sqs.send_message(QueueUrl=fifo, MessageBody="n", MessageGroupId="g", DelaySeconds=1)
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterValue"
+ assert exc.value.response["Error"]["Message"] == (
+ "Value 1 for parameter DelaySeconds is invalid. "
+ "Reason: The request include parameter that is not valid for this queue type.")
+ sqs.send_message(QueueUrl=fifo, MessageBody="m", MessageGroupId="g", DelaySeconds=0)
+ sqs.send_message(QueueUrl=std, MessageBody="now", DelaySeconds=0)
+ assert "Messages" not in sqs.receive_message(QueueUrl=fifo)
+ assert [m["Body"] for m in sqs.receive_message(QueueUrl=std)["Messages"]] == ["now"]
+ time.sleep(2.2)
+ assert [m["Body"] for m in sqs.receive_message(QueueUrl=fifo)["Messages"]] == ["m"]
+ finally:
+ sqs.delete_queue(QueueUrl=fifo)
+ sqs.delete_queue(QueueUrl=std)
+
+
[email protected]("value", [0, 11])
+def test_sqs_receive_max_number_of_messages_out_of_range(sqs, value):
+ url = sqs.create_queue(QueueName=f"maxn-{_uuid_mod.uuid4().hex[:8]}")["QueueUrl"]
+ try:
+ with pytest.raises(ClientError) as exc:
+ sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=value)
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterValue"
+ assert exc.value.response["Error"]["Message"] == (
+ f"Value {value} for parameter MaxNumberOfMessages is invalid. "
+ "Reason: Must be between 1 and 10, if provided.")
+ finally:
+ sqs.delete_queue(QueueUrl=url)