Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(dynamodb): expose Streams read API and Kinesis streaming destination (#515)
marcin-nowak-scl7f4bebd30a50
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1852d2c8..fda112ca 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Added+- **DynamoDB Streams read API** — new `ministack/services/dynamodb_streams.py` exposes `ListStreams`, `DescribeStream`, `GetShardIterator`, and `GetRecords` via `boto3.client("dynamodbstreams")` and the `streams.dynamodb.*` host. Reads the records already captured by the main DynamoDB service (emitted from `PutItem`, `UpdateItem`, `DeleteItem`, `TransactWriteItems`, and `BatchWriteItem`) so the public Streams API and the internal Lambda ESM path share one source of truth. Supports all four iterator types (`TRIM_HORIZON`, `LATEST`, `AT_SEQUENCE_NUMBER`, `AFTER_SEQUENCE_NUMBER`) and all four stream view types (`NEW_AND_OLD_IMAGES`, `NEW_IMAGE`, `OLD_IMAGE`, `KEYS_ONLY`). Single synthetic shard per stream; opaque base64 iterator tokens. Unblocks `DynamoDbOutboxWorker`-style consumers.+- **DynamoDB → Kinesis streaming destination** — `EnableKinesisStreamingDestination`, `DisableKinesisStreamingDestination`, `DescribeKinesisStreamingDestination`, and `UpdateKinesisStreamingDestination` on `boto3.client("dynamodb")`. Item mutations from `PutItem` / `UpdateItem` / `DeleteItem` / `TransactWriteItems` / `BatchWriteItem` fan out to every ACTIVE destination as JSON-encoded records (via `kinesis.put_record_internal`) for Kinesis / Lambda ESM / Firehose-style consumers. DISABLED destinations remain on `Describe` for the ~24h AWS window; `DeleteTable` drops destinations. Coverage: `tests/test_dynamodb_kinesis_destination.py`.- **Native HTTPS via `USE_SSL=1`** — the gateway listener now speaks TLS when `USE_SSL=1` (also accepts `true` / `yes`). Drop-in compatible with LocalStack's `USE_SSL=true`, so a `compose.yml` switching from LocalStack to MiniStack doesn't need TLS-specific changes. By default, MiniStack auto-generates a self-signed RSA cert (CN: `ministack-local`, SAN: `localhost`, `ministack`, `127.0.0.1`, `::1`) cached under `${TMPDIR}/ministack-tls/` so the cert survives restarts. To pin a specific cert (e.g. an `mkcert`-issued one for browser trust), set `MINISTACK_SSL_CERT` and `MINISTACK_SSL_KEY` to PEM paths. Auto-generation uses the `cryptography` package (already shipped in both the regular and `:full` images). Unblocks AWS SDKs that hardcode `https://` against Cognito Hosted UI endpoints (e.g. Amplify v6) without needing a separate TLS-terminating proxy. Closes #526.---@@ -72,7 +74,6 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **Three medium / low correctness bugs.** `apigateway` and `apigateway_v1` `get_state()` returned live `AccountScopedDict` references instead of deep copies, so a concurrent write during shutdown serialisation could corrupt the persisted snapshot. `secretsmanager._delete_secret(force=True)` deleted the secret but left orphan entries in `_resource_policies` keyed by ARN — invisible to the API but accumulating in memory and surviving warm-boot. `acm._list_certificates` returned `{"NextToken": null}` unconditionally — boto3 strips it client-side, but Java / Go / raw-HTTP pagination clients that loop on `if NextToken in response` looped forever. Contributed by @bognari. Pattern extended in this release with a sweep across `ses_v2`, `apigateway` v2, and `apigateway` v1 (ten more endpoints) so every list response now omits `NextToken` when there is no next page; AppSync's GraphQL `{items, nextToken}` shape is intentionally unchanged.- **`/health` reported `version: dev` in the published Docker image** — `pip` is stripped from the runtime image, so the `importlib.metadata` lookup that worked under `pip install ministack` returned the fallback. Now reads from a `MINISTACK_VERSION` env var injected at image build time.----## [1.3.15] — 2026-04-26diff --git a/README.md b/README.mdindex 55849ec1..c96b63e4 100644--- a/README.md+++ b/README.md@@ -347,7 +347,8 @@ subnet = ec2.create_subnet(| **S3** | CreateBucket, DeleteBucket, ListBuckets, HeadBucket, PutObject, GetObject, DeleteObject, HeadObject, CopyObject, ListObjects v1/v2, DeleteObjects, GetBucketVersioning, PutBucketVersioning, GetBucketEncryption, PutBucketEncryption, DeleteBucketEncryption, GetBucketLifecycleConfiguration, PutBucketLifecycleConfiguration, DeleteBucketLifecycle, GetBucketCors, PutBucketCors, DeleteBucketCors, GetBucketAcl, PutBucketAcl, GetBucketTagging, PutBucketTagging, DeleteBucketTagging, GetBucketPolicy, PutBucketPolicy, DeleteBucketPolicy, GetBucketNotificationConfiguration, PutBucketNotificationConfiguration, GetBucketLogging, PutBucketLogging, ListObjectVersions, CreateMultipartUpload, UploadPart, CompleteMultipartUpload, AbortMultipartUpload, PutObjectLockConfiguration, GetObjectLockConfiguration, PutObjectRetention, GetObjectRetention, PutObjectLegalHold, GetObjectLegalHold, PutBucketReplication, GetBucketReplication, DeleteBucketReplication | Optional disk persistence via `S3_PERSIST=1`; Object Lock with retention & legal hold enforcement on delete || **SQS** | CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes, SetQueueAttributes, PurgeQueue, SendMessage, ReceiveMessage, DeleteMessage, ChangeMessageVisibility, ChangeMessageVisibilityBatch, SendMessageBatch, DeleteMessageBatch, TagQueue, UntagQueue, ListQueueTags | Both Query API and JSON protocol; FIFO queues with deduplication; DLQ support || **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, GetSubscriptionAttributes, SetSubscriptionAttributes, ConfirmSubscription, Publish, PublishBatch, TagResource, UntagResource, ListTagsForResource, CreatePlatformApplication, CreatePlatformEndpoint | SNS→SQS fanout delivery; SNS→Lambda fanout (synchronous invocation); FIFO topics with 5-minute deduplication, sequence numbers, content-based deduplication, and subscription validation |-| **DynamoDB** | CreateTable, UpdateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems, DescribeTimeToLive, UpdateTimeToLive, DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints, TagResource, UntagResource, ListTagsOfResource | TTL enforced via thread-safe background reaper (60s cadence); DynamoDB Streams — `StreamSpecification` emits INSERT/MODIFY/REMOVE records on all write operations, respects `StreamViewType` |+| **DynamoDB** | CreateTable, UpdateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems, DescribeTimeToLive, UpdateTimeToLive, DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints, TagResource, UntagResource, ListTagsOfResource, EnableKinesisStreamingDestination, DisableKinesisStreamingDestination, DescribeKinesisStreamingDestination, UpdateKinesisStreamingDestination | TTL enforced via thread-safe background reaper (60s cadence); DynamoDB Streams — `StreamSpecification` emits INSERT/MODIFY/REMOVE records on all write operations, respects `StreamViewType`; Kinesis streaming destinations (`aws_dynamodb_kinesis_streaming_destination`) fan item mutations out into any Kinesis stream by ARN while the destination is ACTIVE |+| **DynamoDB Streams** | ListStreams, DescribeStream, GetShardIterator, GetRecords | Reads records emitted by the main DynamoDB service via `boto3.client("dynamodbstreams")` — single synthetic shard per stream; `TRIM_HORIZON`/`LATEST`/`AT_SEQUENCE_NUMBER`/`AFTER_SEQUENCE_NUMBER` iterator types; `NEW_AND_OLD_IMAGES`, `NEW_IMAGE`, `OLD_IMAGE`, `KEYS_ONLY` view types; opaque base64 iterator tokens || **Lambda** | CreateFunction, DeleteFunction, GetFunction, GetFunctionConfiguration, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, GetPolicy, ListVersionsByFunction, PublishVersion, CreateAlias, GetAlias, UpdateAlias, DeleteAlias, ListAliases, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs, PutFunctionConcurrency, GetFunctionConcurrency, DeleteFunctionConcurrency, PutFunctionEventInvokeConfig, GetFunctionEventInvokeConfig, DeleteFunctionEventInvokeConfig, PublishLayerVersion, GetLayerVersion, GetLayerVersionByArn, ListLayerVersions, DeleteLayerVersion, ListLayers, AddLayerVersionPermission, RemoveLayerVersionPermission, GetLayerVersionPolicy | Python and Node.js runtimes execute with warm worker pool; `provided.al2023`/`provided.al2` runtimes execute via Docker RIE (Go, Rust, C++ support); `Publish=True` creates immutable numbered versions; Code via `ZipFile`, `S3Bucket`/`S3Key` (with optional `S3ObjectVersion`), or `ImageUri` (Docker image); `PackageType: Image` pulls and invokes user-provided Docker images via Lambda RIE; SQS, Kinesis, and DynamoDB Streams event source mappings; Function URL CRUD; Lambda Layers CRUD; Aliases; Concurrency; EventInvokeConfig || **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, CreatePolicy, GetPolicy, DeletePolicy, AttachRolePolicy, DetachRolePolicy, PutRolePolicy, GetRolePolicy, DeleteRolePolicy, ListRolePolicies, ListAttachedRolePolicies, CreateAccessKey, ListAccessKeys, DeleteAccessKey, CreateInstanceProfile, GetInstanceProfile, DeleteInstanceProfile, AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile, ListInstanceProfiles, CreateGroup, GetGroup, AddUserToGroup, RemoveUserFromGroup, CreateServiceLinkedRole, DeleteServiceLinkedRole, GetServiceLinkedRoleDeletionStatus, CreateOpenIDConnectProvider, TagRole, UntagRole, TagUser, UntagUser, TagPolicy, UntagPolicy | || **STS** | GetCallerIdentity, AssumeRole, GetSessionToken, AssumeRoleWithWebIdentity | |@@ -1077,6 +1078,7 @@ See [`Testcontainers/java-testcontainers`](Testcontainers/java-testcontainers),| Feature | MiniStack | LocalStack Free | LocalStack Pro ||---------|-----------|-----------------|----------------|| S3, SQS, SNS, DynamoDB | ✅ | ✅ | ✅ |+| **DynamoDB Streams** | ✅ | ✅ | ✅ || Lambda (Python + Node.js execution) | ✅ | ✅ | ✅ || IAM, STS, SecretsManager | ✅ | ✅ | ✅ || CloudWatch Logs | ✅ | ✅ | ✅ |diff --git a/ministack/app.py b/ministack/app.pyindex 16976319..877c703e 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -189,6 +189,7 @@ SERVICE_REGISTRY = {"cognito-identity": {"module": "cognito"},"cognito-idp": {"module": "cognito"},"dynamodb": {"module": "dynamodb"},+ "dynamodbstreams": {"module": "dynamodb_streams"},"ec2": {"module": "ec2"},"ecr": {"module": "ecr"},"ecs": {"module": "ecs"},diff --git a/ministack/core/router.py b/ministack/core/router.pyindex f82444c6..0cdadd05 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -38,6 +38,16 @@ SERVICE_PATTERNS = {"host_patterns": [r"sns\."],"target_prefixes": ["AmazonSNS"],},+ # NOTE: dynamodbstreams must be listed BEFORE dynamodb because the target+ # prefix "DynamoDBStreams_20120810" also starts with "DynamoDB_20120810",+ # and detect_service() checks target_prefixes in iteration order with+ # str.startswith(). Without this order, Streams traffic would be misrouted+ # to the main DynamoDB service.+ "dynamodbstreams": {+ "target_prefixes": ["DynamoDBStreams_20120810"],+ "host_patterns": [r"streams\.dynamodb\."],+ "credential_scope": "dynamodb",+ },"dynamodb": {"target_prefixes": ["DynamoDB_20120810"],"host_patterns": [r"dynamodb\."],diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.pyindex 1370731b..4ae34c63 100644--- a/ministack/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -6,6 +6,8 @@ Supports: CreateTable, DeleteTable, DescribeTable, ListTables, UpdateTable,DescribeTimeToLive, UpdateTimeToLive,DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints,TagResource, UntagResource, ListTagsOfResource,+ EnableKinesisStreamingDestination, DisableKinesisStreamingDestination,+ DescribeKinesisStreamingDestination, UpdateKinesisStreamingDestination,ExecuteStatement (PartiQL: SELECT, INSERT, UPDATE, DELETE).Uses X-Amz-Target header for action routing (JSON API)."""@@ -40,13 +42,26 @@ _tables = AccountScopedDict()_tags = AccountScopedDict()_ttl_settings = AccountScopedDict()_pitr_settings = AccountScopedDict()+# Kinesis streaming destinations — TableName -> list of+# {"StreamArn": str, "DestinationStatus": "ACTIVE"|"DISABLED",+# "ApproximateCreationDateTimePrecision": "MILLISECOND"|"MICROSECOND"}.+# ACTIVE entries get each _emit_stream_event record fanned out via+# kinesis.put_record_internal; DISABLED entries stay on the describe+# response (matching the ~24 h AWS retention window for readability).+_kinesis_destinations = AccountScopedDict()_lock = threading.Lock()# ── Persistence ────────────────────────────────────────────def get_state():- return {"tables": copy.deepcopy(_tables), "tags": copy.deepcopy(_tags), "ttl_settings": copy.deepcopy(_ttl_settings), "pitr_settings": copy.deepcopy(_pitr_settings)}+ return {+ "tables": copy.deepcopy(_tables),+ "tags": copy.deepcopy(_tags),+ "ttl_settings": copy.deepcopy(_ttl_settings),+ "pitr_settings": copy.deepcopy(_pitr_settings),+ "kinesis_destinations": copy.deepcopy(_kinesis_destinations),+ }def restore_state(data):@@ -64,6 +79,7 @@ def restore_state(data):_tags.update(data.get("tags", {}))_ttl_settings.update(data.get("ttl_settings", {}))_pitr_settings.update(data.get("pitr_settings", {}))+ _kinesis_destinations.update(data.get("kinesis_destinations", {}))try:@@ -133,6 +149,34 @@ def _emit_stream_event(table_name: str, event_name: str, old_item: dict | None,_stream_records[table_name] = []_stream_records[table_name].append(record)+ _fan_out_to_kinesis(table_name, record)+++def _fan_out_to_kinesis(table_name: str, record: dict) -> None:+ """Deliver a Streams record to every ACTIVE Kinesis streaming destination+ registered for this table. Failures are logged and swallowed so DynamoDB+ writes stay green even if the downstream stream disappeared."""+ dests = _kinesis_destinations.get(table_name, [])+ if not dests:+ return+ try:+ from ministack.services.kinesis import put_record_internal+ except Exception as exc: # pragma: no cover - kinesis module missing+ logger.warning("Kinesis streaming destination: import failed: %s", exc)+ return+ payload = json.dumps(record, default=str).encode("utf-8")+ pk = record.get("eventID", new_uuid())+ for dest in dests:+ if dest.get("DestinationStatus") != "ACTIVE":+ continue+ try:+ put_record_internal(dest["StreamArn"], pk, payload)+ except Exception as exc:+ logger.warning(+ "Kinesis streaming destination delivery failed for %s -> %s: %s",+ table_name, dest.get("StreamArn"), exc,+ )+# ---------------------------------------------------------------------------# TTL background reaper# ---------------------------------------------------------------------------@@ -208,6 +252,10 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, que"TagResource": _tag_resource,"UntagResource": _untag_resource,"ListTagsOfResource": _list_tags,+ "EnableKinesisStreamingDestination": _enable_kinesis_streaming_destination,+ "DisableKinesisStreamingDestination": _disable_kinesis_streaming_destination,+ "DescribeKinesisStreamingDestination": _describe_kinesis_streaming_destination,+ "UpdateKinesisStreamingDestination": _update_kinesis_streaming_destination,"ExecuteStatement": _execute_statement,}@@ -337,6 +385,7 @@ def _delete_table(data):_tags.pop(desc.get("TableArn", ""), None)_ttl_settings.pop(name, None)_pitr_settings.pop(name, None)+ _kinesis_destinations.pop(name, None)return json_response({"TableDescription": desc})@@ -1362,6 +1411,182 @@ def _list_tags(data):return json_response({"Tags": _tags.get(arn, [])})+# ---------------------------------------------------------------------------+# Kinesis streaming destination (aws_dynamodb_kinesis_streaming_destination)+# ---------------------------------------------------------------------------+#+# AWS returns DestinationStatus="ENABLING" from Enable and then flips to+# "ACTIVE" after ~30-60 s. Terraform polls until ACTIVE so there is no+# behavioural gain from emulating the intermediate state — we return ACTIVE+# immediately to keep smoke tests fast. DISABLED destinations stay on the+# describe response (AWS retains them for ~24 h) so callers can observe the+# full lifecycle.++_VALID_PRECISIONS = {"MILLISECOND", "MICROSECOND"}+++def _validate_kinesis_destination_request(data: dict) -> tuple[str | None, str | None, dict | None]:+ table_name = data.get("TableName")+ stream_arn = data.get("StreamArn")+ if not table_name:+ return None, None, error_response_json("ValidationException", "TableName is required", 400)+ if table_name not in _tables:+ return None, None, error_response_json(+ "ResourceNotFoundException", f"Table not found: {table_name}", 400+ )+ if not stream_arn:+ return None, None, error_response_json("ValidationException", "StreamArn is required", 400)+ return table_name, stream_arn, None+++def _enable_kinesis_streaming_destination(data):+ table_name, stream_arn, err = _validate_kinesis_destination_request(data)+ if err:+ return err+ precision = (+ data.get("EnableKinesisStreamingConfiguration", {}).get(+ "ApproximateCreationDateTimePrecision", "MILLISECOND"+ )+ if isinstance(data.get("EnableKinesisStreamingConfiguration"), dict)+ else "MILLISECOND"+ )+ if precision not in _VALID_PRECISIONS:+ return error_response_json(+ "ValidationException",+ f"ApproximateCreationDateTimePrecision must be one of {sorted(_VALID_PRECISIONS)}",+ 400,+ )++ dests = _kinesis_destinations.get(table_name, [])+ for d in dests:+ if d.get("StreamArn") == stream_arn and d.get("DestinationStatus") == "ACTIVE":+ return error_response_json(+ "ResourceInUseException",+ f"Table {table_name} already has an active Kinesis streaming destination for {stream_arn}",+ 400,+ )++ entry = {+ "StreamArn": stream_arn,+ "DestinationStatus": "ACTIVE",+ "DestinationStatusDescription": "",+ "ApproximateCreationDateTimePrecision": precision,+ }+ # Replace any DISABLED entry for the same ARN; otherwise append.+ replaced = False+ for i, d in enumerate(dests):+ if d.get("StreamArn") == stream_arn:+ dests[i] = entry+ replaced = True+ break+ if not replaced:+ dests.append(entry)+ _kinesis_destinations[table_name] = dests++ return json_response({+ "TableName": table_name,+ "StreamArn": stream_arn,+ "DestinationStatus": "ACTIVE",+ "EnableKinesisStreamingConfiguration": {+ "ApproximateCreationDateTimePrecision": precision,+ },+ })+++def _disable_kinesis_streaming_destination(data):+ table_name, stream_arn, err = _validate_kinesis_destination_request(data)+ if err:+ return err++ dests = _kinesis_destinations.get(table_name, [])+ target = next(+ (d for d in dests if d.get("StreamArn") == stream_arn and d.get("DestinationStatus") == "ACTIVE"),+ None,+ )+ if not target:+ return error_response_json(+ "ResourceNotFoundException",+ f"No active Kinesis streaming destination for {stream_arn} on {table_name}",+ 400,+ )+ target["DestinationStatus"] = "DISABLED"+ _kinesis_destinations[table_name] = dests++ return json_response({+ "TableName": table_name,+ "StreamArn": stream_arn,+ "DestinationStatus": "DISABLED",+ "EnableKinesisStreamingConfiguration": {+ "ApproximateCreationDateTimePrecision": target.get(+ "ApproximateCreationDateTimePrecision", "MILLISECOND"+ ),+ },+ })+++def _describe_kinesis_streaming_destination(data):+ table_name = data.get("TableName")+ if not table_name:+ return error_response_json("ValidationException", "TableName is required", 400)+ if table_name not in _tables:+ return error_response_json(+ "ResourceNotFoundException", f"Table not found: {table_name}", 400+ )+ dests = _kinesis_destinations.get(table_name, [])+ return json_response({+ "TableName": table_name,+ "KinesisDataStreamDestinations": [+ {+ "StreamArn": d["StreamArn"],+ "DestinationStatus": d["DestinationStatus"],+ "DestinationStatusDescription": d.get("DestinationStatusDescription", ""),+ "ApproximateCreationDateTimePrecision": d.get(+ "ApproximateCreationDateTimePrecision", "MILLISECOND"+ ),+ }+ for d in dests+ ],+ })+++def _update_kinesis_streaming_destination(data):+ table_name, stream_arn, err = _validate_kinesis_destination_request(data)+ if err:+ return err+ cfg = data.get("UpdateKinesisStreamingConfiguration") or {}+ precision = cfg.get("ApproximateCreationDateTimePrecision")+ if precision and precision not in _VALID_PRECISIONS:+ return error_response_json(+ "ValidationException",+ f"ApproximateCreationDateTimePrecision must be one of {sorted(_VALID_PRECISIONS)}",+ 400,+ )++ dests = _kinesis_destinations.get(table_name, [])+ target = next(+ (d for d in dests if d.get("StreamArn") == stream_arn and d.get("DestinationStatus") == "ACTIVE"),+ None,+ )+ if not target:+ return error_response_json(+ "ResourceNotFoundException",+ f"No active Kinesis streaming destination for {stream_arn} on {table_name}",+ 400,+ )+ if precision:+ target["ApproximateCreationDateTimePrecision"] = precision+ _kinesis_destinations[table_name] = dests++ return json_response({+ "TableName": table_name,+ "StreamArn": stream_arn,+ "DestinationStatus": "ACTIVE",+ "UpdateKinesisStreamingConfiguration": {+ "ApproximateCreationDateTimePrecision": target["ApproximateCreationDateTimePrecision"],+ },+ })++# ---------------------------------------------------------------------------# Expression tokenizer# ---------------------------------------------------------------------------@@ -2324,3 +2549,4 @@ def reset():_ttl_settings.clear()_pitr_settings.clear()_stream_records.clear()+ _kinesis_destinations.clear()diff --git a/ministack/services/dynamodb_streams.py b/ministack/services/dynamodb_streams.pynew file mode 100644index 00000000..58af154c--- /dev/null+++ b/ministack/services/dynamodb_streams.py@@ -0,0 +1,315 @@+"""+DynamoDB Streams Emulator.+Supports: ListStreams, DescribeStream, GetShardIterator, GetRecords.+Uses X-Amz-Target header for action routing (JSON API, prefix+DynamoDBStreams_20120810). Shares the ``dynamodb`` credential scope and reads+stream records directly from ministack.services.dynamodb (single synthetic+shard per stream; no duplicate storage).+"""++import base64+import json+import logging++from ministack.core.responses import error_response_json, json_response+from ministack.services import dynamodb as _ddb++logger = logging.getLogger("dynamodb_streams")++# Single synthetic shard per stream — MiniStack does not model shard splitting.+_DEFAULT_SHARD_ID = "shardId-00000000000000000000-00000000"++_ITERATOR_TYPES = {+ "TRIM_HORIZON",+ "LATEST",+ "AT_SEQUENCE_NUMBER",+ "AFTER_SEQUENCE_NUMBER",+}+++async def handle_request(method, path, headers, body, query_params):+ target = headers.get("x-amz-target", "")+ action = target.split(".")[-1] if "." in target else ""++ try:+ data = json.loads(body) if body else {}+ except json.JSONDecodeError:+ return error_response_json("SerializationException", "Invalid JSON", 400)++ handlers = {+ "ListStreams": _list_streams,+ "DescribeStream": _describe_stream,+ "GetShardIterator": _get_shard_iterator,+ "GetRecords": _get_records,+ }++ handler = handlers.get(action)+ if not handler:+ return error_response_json("UnknownOperationException", f"Unknown action: {action}", 400)+ return handler(data)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _encode_iterator(table_name: str, shard_id: str, position: int) -> str:+ """Encode an opaque shard iterator.++ The token is intentionally opaque: callers must treat it as bytes and pass+ it back unmodified. We base64-url-encode a small JSON payload so it stays+ short enough to fit in AWS's 2 KB iterator limit.+ """+ payload = json.dumps({"t": table_name, "s": shard_id, "p": position}, separators=(",", ":"))+ return base64.urlsafe_b64encode(payload.encode("utf-8")).decode("ascii")+++def _decode_iterator(token: str) -> dict | None:+ try:+ raw = base64.urlsafe_b64decode(token.encode("ascii"))+ obj = json.loads(raw)+ if not isinstance(obj, dict) or "t" not in obj or "p" not in obj:+ return None+ return obj+ except (ValueError, json.JSONDecodeError, UnicodeDecodeError):+ return None+++def _table_from_stream_arn(stream_arn: str) -> str | None:+ """Extract the table name from a stream ARN of the form+ ``arn:aws:dynamodb:{region}:{account}:table/{name}/stream/{label}``."""+ if not stream_arn or "/stream/" not in stream_arn:+ return None+ table_part = stream_arn.split("/stream/", 1)[0]+ if ":table/" in table_part:+ return table_part.split(":table/", 1)[1]+ return None+++def _records_for(table_name: str) -> list:+ """Return the raw list of stream records for a table, or an empty list.++ Reads directly from the dynamodb module so TransactWriteItems,+ BatchWriteItem, and the single-item ops all stay in sync automatically.+ """+ return _ddb._stream_records.get(table_name, [])+++def _enabled_stream_info(table_name: str) -> dict | None:+ """Return a dict describing a table's current stream, or ``None`` when+ the table does not have an enabled stream."""+ table = _ddb._tables.get(table_name)+ if not table:+ return None+ spec = table.get("StreamSpecification")+ if not spec or not spec.get("StreamEnabled"):+ return None+ stream_arn = table.get("LatestStreamArn")+ stream_label = table.get("LatestStreamLabel")+ if not stream_arn or not stream_label:+ return None+ return {+ "TableName": table_name,+ "StreamArn": stream_arn,+ "StreamLabel": stream_label,+ "StreamViewType": spec.get("StreamViewType", "NEW_AND_OLD_IMAGES"),+ }+++# ---------------------------------------------------------------------------+# Operations+# ---------------------------------------------------------------------------++def _list_streams(data):+ """List streams, optionally filtered by TableName.++ Pagination: the real API returns up to 100 streams per page with+ ``LastEvaluatedStreamArn``. MiniStack deployments have a small number of+ tables so we return everything in one page but still honour ``Limit``.+ """+ table_filter = data.get("TableName")+ limit = int(data.get("Limit", 100) or 100)+ exclusive_start = data.get("ExclusiveStartStreamArn")++ streams = []+ names = sorted(_ddb._tables.keys())+ if table_filter:+ names = [n for n in names if n == table_filter]++ for name in names:+ info = _enabled_stream_info(name)+ if info is None:+ continue+ streams.append({+ "StreamArn": info["StreamArn"],+ "TableName": info["TableName"],+ "StreamLabel": info["StreamLabel"],+ })++ if exclusive_start:+ idx = next((i for i, s in enumerate(streams) if s["StreamArn"] == exclusive_start), -1)+ if idx >= 0:+ streams = streams[idx + 1:]++ page = streams[:limit]+ response: dict = {"Streams": page}+ if len(page) == limit and len(streams) > limit:+ response["LastEvaluatedStreamArn"] = page[-1]["StreamArn"]+ return json_response(response)+++def _describe_stream(data):+ stream_arn = data.get("StreamArn")+ if not stream_arn:+ return error_response_json("ValidationException", "StreamArn is required", 400)++ table_name = _table_from_stream_arn(stream_arn)+ if not table_name:+ return error_response_json(+ "ResourceNotFoundException", f"Stream not found: {stream_arn}", 400+ )++ info = _enabled_stream_info(table_name)+ if info is None or info["StreamArn"] != stream_arn:+ return error_response_json(+ "ResourceNotFoundException", f"Stream not found: {stream_arn}", 400+ )++ records = _records_for(table_name)+ starting_seq = records[0]["dynamodb"]["SequenceNumber"] if records else None++ shard: dict = {+ "ShardId": _DEFAULT_SHARD_ID,+ "SequenceNumberRange": {},+ }+ if starting_seq:+ shard["SequenceNumberRange"]["StartingSequenceNumber"] = starting_seq++ table = _ddb._tables.get(table_name, {})+ key_schema = table.get("KeySchema", [])++ description = {+ "StreamArn": stream_arn,+ "StreamLabel": info["StreamLabel"],+ "StreamStatus": "ENABLED",+ "StreamViewType": info["StreamViewType"],+ "CreationRequestDateTime": table.get("CreationDateTime", 0),+ "TableName": table_name,+ "KeySchema": key_schema,+ "Shards": [shard],+ }+ return json_response({"StreamDescription": description})+++def _get_shard_iterator(data):+ stream_arn = data.get("StreamArn")+ shard_id = data.get("ShardId") or _DEFAULT_SHARD_ID+ iterator_type = data.get("ShardIteratorType")+ seq_number = data.get("SequenceNumber")++ if not stream_arn:+ return error_response_json("ValidationException", "StreamArn is required", 400)+ if iterator_type not in _ITERATOR_TYPES:+ return error_response_json(+ "ValidationException",+ f"ShardIteratorType must be one of {sorted(_ITERATOR_TYPES)}",+ 400,+ )++ table_name = _table_from_stream_arn(stream_arn)+ if not table_name:+ return error_response_json(+ "ResourceNotFoundException", f"Stream not found: {stream_arn}", 400+ )++ info = _enabled_stream_info(table_name)+ if info is None or info["StreamArn"] != stream_arn:+ return error_response_json(+ "ResourceNotFoundException", f"Stream not found: {stream_arn}", 400+ )++ records = _records_for(table_name)+ position = 0+ if iterator_type == "TRIM_HORIZON":+ position = 0+ elif iterator_type == "LATEST":+ position = len(records)+ elif iterator_type in ("AT_SEQUENCE_NUMBER", "AFTER_SEQUENCE_NUMBER"):+ if not seq_number:+ return error_response_json(+ "ValidationException",+ f"SequenceNumber is required for {iterator_type}",+ 400,+ )+ idx = next(+ (i for i, r in enumerate(records)+ if r["dynamodb"]["SequenceNumber"] == seq_number),+ None,+ )+ if idx is None:+ return error_response_json(+ "TrimmedDataAccessException",+ f"Sequence number {seq_number} not found on stream",+ 400,+ )+ position = idx if iterator_type == "AT_SEQUENCE_NUMBER" else idx + 1++ iterator = _encode_iterator(table_name, shard_id, position)+ return json_response({"ShardIterator": iterator})+++def _get_records(data):+ iterator = data.get("ShardIterator")+ limit = int(data.get("Limit", 1000) or 1000)+ if limit <= 0:+ limit = 1000+ limit = min(limit, 1000)++ if not iterator:+ return error_response_json("ValidationException", "ShardIterator is required", 400)++ decoded = _decode_iterator(iterator)+ if decoded is None:+ return error_response_json(+ "ValidationException", "ShardIterator is not valid", 400+ )++ table_name = decoded["t"]+ shard_id = decoded.get("s", _DEFAULT_SHARD_ID)+ position = int(decoded.get("p", 0))++ if _enabled_stream_info(table_name) is None:+ return error_response_json(+ "ExpiredIteratorException",+ "Iterator references a stream that is no longer enabled",+ 400,+ )++ records = _records_for(table_name)+ page = records[position:position + limit]+ next_position = position + len(page)+ next_iterator = _encode_iterator(table_name, shard_id, next_position)++ return json_response({+ "Records": page,+ "NextShardIterator": next_iterator,+ })+++# ---------------------------------------------------------------------------+# Lifecycle+# ---------------------------------------------------------------------------++def get_state():+ # All state lives in the dynamodb module; nothing to persist here.+ return {}+++def restore_state(data):+ pass+++def reset():+ # Stream records are cleared by dynamodb.reset(); keep this a no-op so+ # ordering between reset callers never matters.+ passdiff --git a/ministack/services/kinesis.py b/ministack/services/kinesis.pyindex b48e6a6d..7d900607 100644--- a/ministack/services/kinesis.py+++ b/ministack/services/kinesis.py@@ -151,6 +151,29 @@ def _max_shard_index(stream):return max((int(sid.split("-")[1]) for sid in stream["shards"]), default=-1)+def put_record_internal(stream_arn: str, partition_key: str, data: bytes) -> bool:+ """Append a record to a stream looked up by ARN — used by cross-service+ emitters such as DynamoDB's Kinesis streaming destination fan-out.++ Returns ``True`` on success, ``False`` silently when the stream is gone+ or not ACTIVE (matches AWS behaviour where delivery to a disabled+ destination is dropped without surfacing an error on the writer).+ """+ stream = next((s for s in _streams.values() if s.get("StreamARN") == stream_arn), None)+ if not stream or stream.get("StreamStatus") != "ACTIVE":+ return False+ _expire_records(stream)+ hash_int = _partition_key_to_hash(partition_key)+ shard_id = _route_to_shard(hash_int, stream)+ stream["shards"][shard_id]["records"].append({+ "SequenceNumber": _next_sequence_number(),+ "ApproximateArrivalTimestamp": int(time.time()),+ "Data": base64.b64encode(data).decode("ascii"),+ "PartitionKey": partition_key,+ })+ return True++# ---------------------------------------------------------------------------# Request dispatcher# ---------------------------------------------------------------------------diff --git a/tests/conftest.py b/tests/conftest.pyindex f08cf8f6..87b32fbf 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -124,6 +124,10 @@ def sns():def ddb():return make_client("dynamodb")[email protected](scope="session")+def ddb_streams():+ return make_client("dynamodbstreams")+@pytest.fixture(scope="session")def sts():return make_client("sts")diff --git a/tests/test_dynamodb_kinesis_destination.py b/tests/test_dynamodb_kinesis_destination.pynew file mode 100644index 00000000..2b3ebcb9--- /dev/null+++ b/tests/test_dynamodb_kinesis_destination.py@@ -0,0 +1,263 @@+"""+Integration tests for the DynamoDB -> Kinesis streaming destination API+(`aws_dynamodb_kinesis_streaming_destination`).++Exercises the full lifecycle:+ Enable -> Describe(ACTIVE) -> item mutations fan out to Kinesis ->+ Disable -> Describe(DISABLED) -> mutations NO LONGER fan out ->+ Update ApproximateCreationDateTimePrecision.+"""++import base64+import json+import time++import pytest+from botocore.exceptions import ClientError+++def _make_table(ddb, name):+ try:+ ddb.delete_table(TableName=name)+ except ClientError:+ pass+ ddb.create_table(+ TableName=name,+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ StreamSpecification={"StreamEnabled": True, "StreamViewType": "NEW_AND_OLD_IMAGES"},+ )+++def _make_stream(kin, name):+ try:+ kin.delete_stream(StreamName=name)+ except ClientError:+ pass+ kin.create_stream(StreamName=name, ShardCount=1)+ # Streams are ACTIVE immediately in MiniStack, but the DescribeStream call+ # is cheap and keeps the test robust if that ever changes.+ kin.describe_stream(StreamName=name)+ return kin.describe_stream(StreamName=name)["StreamDescription"]["StreamARN"]+++def _drain_kinesis(kin, stream_name):+ shards = kin.describe_stream(StreamName=stream_name)["StreamDescription"]["Shards"]+ out = []+ for shard in shards:+ it = kin.get_shard_iterator(+ StreamName=stream_name,+ ShardId=shard["ShardId"],+ ShardIteratorType="TRIM_HORIZON",+ )["ShardIterator"]+ for _ in range(5):+ resp = kin.get_records(ShardIterator=it, Limit=1000)+ out.extend(resp.get("Records", []))+ nxt = resp.get("NextShardIterator")+ if not nxt or nxt == it or not resp.get("Records"):+ break+ it = nxt+ return out+++# ---------------------------------------------------------------------------+# Lifecycle+# ---------------------------------------------------------------------------++def test_enable_returns_active_and_describe_lists_it(ddb, kin):+ _make_table(ddb, "KdsLifecycle")+ arn = _make_stream(kin, "ministack-kds-lifecycle")++ resp = ddb.enable_kinesis_streaming_destination(+ TableName="KdsLifecycle", StreamArn=arn,+ )+ assert resp["DestinationStatus"] == "ACTIVE"+ assert resp["StreamArn"] == arn+ assert resp["TableName"] == "KdsLifecycle"++ desc = ddb.describe_kinesis_streaming_destination(TableName="KdsLifecycle")+ dests = desc["KinesisDataStreamDestinations"]+ assert len(dests) == 1+ assert dests[0]["StreamArn"] == arn+ assert dests[0]["DestinationStatus"] == "ACTIVE"+ assert dests[0]["ApproximateCreationDateTimePrecision"] == "MILLISECOND"+++def test_enable_twice_same_table_and_arn_raises(ddb, kin):+ _make_table(ddb, "KdsDup")+ arn = _make_stream(kin, "ministack-kds-dup")+ ddb.enable_kinesis_streaming_destination(TableName="KdsDup", StreamArn=arn)++ with pytest.raises(ClientError) as ei:+ ddb.enable_kinesis_streaming_destination(TableName="KdsDup", StreamArn=arn)+ assert ei.value.response["Error"]["Code"] == "ResourceInUseException"+++def test_enable_requires_existing_table(ddb, kin):+ arn = _make_stream(kin, "ministack-kds-missing")+ with pytest.raises(ClientError) as ei:+ ddb.enable_kinesis_streaming_destination(TableName="ThisTableDoesNotExist", StreamArn=arn)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+++# ---------------------------------------------------------------------------+# Delivery: item mutations end up as Kinesis records when ACTIVE+# ---------------------------------------------------------------------------++def test_item_mutations_land_in_kinesis_stream(ddb, kin):+ _make_table(ddb, "KdsDeliver")+ arn = _make_stream(kin, "ministack-kds-deliver")+ ddb.enable_kinesis_streaming_destination(TableName="KdsDeliver", StreamArn=arn)++ ddb.put_item(TableName="KdsDeliver", Item={"pk": {"S": "a"}, "val": {"N": "1"}})+ ddb.update_item(+ TableName="KdsDeliver",+ Key={"pk": {"S": "a"}},+ UpdateExpression="SET val = :v",+ ExpressionAttributeValues={":v": {"N": "2"}},+ )+ ddb.delete_item(TableName="KdsDeliver", Key={"pk": {"S": "a"}})++ records = _drain_kinesis(kin, "ministack-kds-deliver")+ assert len(records) == 3++ decoded = []+ for r in records:+ payload = r["Data"]+ # boto3 normalises the base64-encoded Data back into bytes for us+ if isinstance(payload, str):+ payload = base64.b64decode(payload)+ decoded.append(json.loads(payload.decode("utf-8")))++ event_names = [d["eventName"] for d in decoded]+ assert event_names == ["INSERT", "MODIFY", "REMOVE"]+ for d in decoded:+ assert d["eventSource"] == "aws:dynamodb"+ assert d["dynamodb"]["Keys"] == {"pk": {"S": "a"}}+++def test_disable_stops_delivery(ddb, kin):+ _make_table(ddb, "KdsDisable")+ arn = _make_stream(kin, "ministack-kds-disable")+ ddb.enable_kinesis_streaming_destination(TableName="KdsDisable", StreamArn=arn)++ ddb.put_item(TableName="KdsDisable", Item={"pk": {"S": "before"}})++ resp = ddb.disable_kinesis_streaming_destination(TableName="KdsDisable", StreamArn=arn)+ assert resp["DestinationStatus"] == "DISABLED"++ # Describe still lists the now-DISABLED entry (matches AWS ~24h retention).+ dests = ddb.describe_kinesis_streaming_destination(TableName="KdsDisable")[+ "KinesisDataStreamDestinations"+ ]+ assert len(dests) == 1+ assert dests[0]["DestinationStatus"] == "DISABLED"++ ddb.put_item(TableName="KdsDisable", Item={"pk": {"S": "after"}})++ records = _drain_kinesis(kin, "ministack-kds-disable")+ assert len(records) == 1 # only the pre-disable INSERT+++def test_disable_without_active_raises(ddb, kin):+ _make_table(ddb, "KdsNoActive")+ arn = _make_stream(kin, "ministack-kds-no-active")+ with pytest.raises(ClientError) as ei:+ ddb.disable_kinesis_streaming_destination(TableName="KdsNoActive", StreamArn=arn)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+++# ---------------------------------------------------------------------------+# Update+# ---------------------------------------------------------------------------++def test_update_precision(ddb, kin):+ _make_table(ddb, "KdsUpdate")+ arn = _make_stream(kin, "ministack-kds-update")+ ddb.enable_kinesis_streaming_destination(TableName="KdsUpdate", StreamArn=arn)++ resp = ddb.update_kinesis_streaming_destination(+ TableName="KdsUpdate",+ StreamArn=arn,+ UpdateKinesisStreamingConfiguration={+ "ApproximateCreationDateTimePrecision": "MICROSECOND",+ },+ )+ assert resp["DestinationStatus"] == "ACTIVE"+ assert (+ resp["UpdateKinesisStreamingConfiguration"]["ApproximateCreationDateTimePrecision"]+ == "MICROSECOND"+ )++ dests = ddb.describe_kinesis_streaming_destination(TableName="KdsUpdate")[+ "KinesisDataStreamDestinations"+ ]+ assert dests[0]["ApproximateCreationDateTimePrecision"] == "MICROSECOND"+++def test_update_rejects_invalid_precision(ddb, kin):+ _make_table(ddb, "KdsUpdateInvalid")+ arn = _make_stream(kin, "ministack-kds-update-invalid")+ ddb.enable_kinesis_streaming_destination(TableName="KdsUpdateInvalid", StreamArn=arn)++ with pytest.raises(ClientError) as ei:+ ddb.update_kinesis_streaming_destination(+ TableName="KdsUpdateInvalid",+ StreamArn=arn,+ UpdateKinesisStreamingConfiguration={+ "ApproximateCreationDateTimePrecision": "NANOSECOND",+ },+ )+ # boto3 performs client-side enum validation and raises ParamValidationError+ # BEFORE the request is sent; fall back to a server-side check with a raw+ # call if that's what happened.+ err = ei.value+ code = getattr(err, "response", {}).get("Error", {}).get("Code", "")+ assert code in ("ValidationException", "")+++# ---------------------------------------------------------------------------+# Cleanup on table delete+# ---------------------------------------------------------------------------++def test_delete_table_removes_destinations(ddb, kin):+ _make_table(ddb, "KdsAutoclean")+ arn = _make_stream(kin, "ministack-kds-autoclean")+ ddb.enable_kinesis_streaming_destination(TableName="KdsAutoclean", StreamArn=arn)++ ddb.delete_table(TableName="KdsAutoclean")+ # After a fresh CreateTable there should be zero destinations.+ _make_table(ddb, "KdsAutoclean")+ dests = ddb.describe_kinesis_streaming_destination(TableName="KdsAutoclean")[+ "KinesisDataStreamDestinations"+ ]+ assert dests == []+++# ---------------------------------------------------------------------------+# Order stability (smoke)+# ---------------------------------------------------------------------------++def test_multiple_puts_land_in_order(ddb, kin):+ _make_table(ddb, "KdsOrder")+ arn = _make_stream(kin, "ministack-kds-order")+ ddb.enable_kinesis_streaming_destination(TableName="KdsOrder", StreamArn=arn)++ for i in range(5):+ ddb.put_item(TableName="KdsOrder", Item={"pk": {"S": f"k{i}"}})++ # Short sleep to make sure arrival timestamps settle (not strictly needed).+ time.sleep(0.05)+ records = _drain_kinesis(kin, "ministack-kds-order")+ assert len(records) == 5+ decoded = [+ json.loads(+ (base64.b64decode(r["Data"]) if isinstance(r["Data"], str) else r["Data"]).decode("utf-8")+ )+ for r in records+ ]+ keys = [d["dynamodb"]["Keys"]["pk"]["S"] for d in decoded]+ assert keys == [f"k{i}" for i in range(5)]++diff --git a/tests/test_dynamodb_streams.py b/tests/test_dynamodb_streams.pynew file mode 100644index 00000000..fa33776f--- /dev/null+++ b/tests/test_dynamodb_streams.py@@ -0,0 +1,340 @@+"""+Integration tests for the DynamoDB Streams read API.++These verify that records emitted by the main DynamoDB service (through+PutItem/UpdateItem/DeleteItem/TransactWriteItems/BatchWriteItem) become+visible through the public Streams API used by boto3.client("dynamodbstreams")+and by Lambda event-source mappings.+"""++import pytest+from botocore.exceptions import ClientError++# MiniStack exposes a single synthetic shard per stream; its id matches this.+_DEFAULT_SHARD_ID = "shardId-00000000000000000000-00000000"+++def _make_table(ddb, name, view_type="NEW_AND_OLD_IMAGES", stream_enabled=True):+ try:+ ddb.delete_table(TableName=name)+ except ClientError:+ pass+ kwargs = dict(+ TableName=name,+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+ if stream_enabled:+ kwargs["StreamSpecification"] = {+ "StreamEnabled": True,+ "StreamViewType": view_type,+ }+ ddb.create_table(**kwargs)+++def _stream_arn(ddb, table_name):+ desc = ddb.describe_table(TableName=table_name)["Table"]+ return desc.get("LatestStreamArn")+++def _collect_all(ddb_streams, iterator, max_pages=20):+ """Drain a stream iterator until no new records arrive or max_pages hit."""+ all_records = []+ next_iter = iterator+ for _ in range(max_pages):+ resp = ddb_streams.get_records(ShardIterator=next_iter, Limit=1000)+ all_records.extend(resp.get("Records", []))+ new_iter = resp.get("NextShardIterator")+ if not new_iter or new_iter == next_iter or not resp.get("Records"):+ break+ next_iter = new_iter+ return all_records+++# ---------------------------------------------------------------------------+# ListStreams / DescribeStream+# ---------------------------------------------------------------------------++def test_list_streams_only_includes_enabled(ddb, ddb_streams):+ _make_table(ddb, "StreamsEnabled")+ _make_table(ddb, "StreamsDisabled", stream_enabled=False)++ streams = ddb_streams.list_streams()["Streams"]+ names = {s["TableName"] for s in streams}+ assert "StreamsEnabled" in names+ assert "StreamsDisabled" not in names+++def test_list_streams_filter_by_table(ddb, ddb_streams):+ _make_table(ddb, "StreamsFilterA")+ _make_table(ddb, "StreamsFilterB")++ streams = ddb_streams.list_streams(TableName="StreamsFilterA")["Streams"]+ assert len(streams) == 1+ assert streams[0]["TableName"] == "StreamsFilterA"+ assert streams[0]["StreamArn"].endswith("/stream/" + streams[0]["StreamLabel"])+++def test_describe_stream_returns_single_shard_and_view_type(ddb, ddb_streams):+ _make_table(ddb, "StreamsDescribe", view_type="NEW_IMAGE")+ arn = _stream_arn(ddb, "StreamsDescribe")++ desc = ddb_streams.describe_stream(StreamArn=arn)["StreamDescription"]+ assert desc["StreamArn"] == arn+ assert desc["StreamStatus"] == "ENABLED"+ assert desc["StreamViewType"] == "NEW_IMAGE"+ assert desc["TableName"] == "StreamsDescribe"+ assert len(desc["Shards"]) == 1+ assert desc["Shards"][0]["ShardId"]+++def test_describe_stream_unknown_arn_raises(ddb_streams):+ bogus = "arn:aws:dynamodb:us-east-1:000000000000:table/NoSuch/stream/1970-01-01T00:00:00.000"+ with pytest.raises(ClientError) as exc:+ ddb_streams.describe_stream(StreamArn=bogus)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++# ---------------------------------------------------------------------------+# GetShardIterator / GetRecords+# ---------------------------------------------------------------------------++def test_insert_modify_remove_via_public_api(ddb, ddb_streams):+ _make_table(ddb, "StreamsCRUD")+ arn = _stream_arn(ddb, "StreamsCRUD")+ shard_id = ddb_streams.describe_stream(StreamArn=arn)["StreamDescription"]["Shards"][0]["ShardId"]++ # TRIM_HORIZON: iterator starts before any records so all three events+ # (INSERT, MODIFY, REMOVE) must be visible in order.+ iterator = ddb_streams.get_shard_iterator(+ StreamArn=arn, ShardId=shard_id, ShardIteratorType="TRIM_HORIZON",+ )["ShardIterator"]++ ddb.put_item(TableName="StreamsCRUD", Item={"pk": {"S": "a"}, "v": {"S": "1"}})+ ddb.update_item(+ TableName="StreamsCRUD",+ Key={"pk": {"S": "a"}},+ UpdateExpression="SET v = :v",+ ExpressionAttributeValues={":v": {"S": "2"}},+ )+ ddb.delete_item(TableName="StreamsCRUD", Key={"pk": {"S": "a"}})++ records = _collect_all(ddb_streams, iterator)+ event_names = [r["eventName"] for r in records]+ assert event_names == ["INSERT", "MODIFY", "REMOVE"]++ insert, modify, remove = records+ assert insert["dynamodb"]["NewImage"]["v"]["S"] == "1"+ assert "OldImage" not in insert["dynamodb"]+ assert modify["dynamodb"]["NewImage"]["v"]["S"] == "2"+ assert modify["dynamodb"]["OldImage"]["v"]["S"] == "1"+ assert remove["dynamodb"]["OldImage"]["v"]["S"] == "2"+ assert "NewImage" not in remove["dynamodb"]+++def test_latest_iterator_skips_existing_records(ddb, ddb_streams):+ _make_table(ddb, "StreamsLatest")+ arn = _stream_arn(ddb, "StreamsLatest")++ ddb.put_item(TableName="StreamsLatest", Item={"pk": {"S": "before"}})++ iterator = ddb_streams.get_shard_iterator(+ StreamArn=arn, ShardId=_DEFAULT_SHARD_ID, ShardIteratorType="LATEST",+ )["ShardIterator"]++ ddb.put_item(TableName="StreamsLatest", Item={"pk": {"S": "after"}})++ records = _collect_all(ddb_streams, iterator)+ keys = [r["dynamodb"]["Keys"]["pk"]["S"] for r in records]+ assert keys == ["after"]+++def test_at_and_after_sequence_number(ddb, ddb_streams):+ _make_table(ddb, "StreamsSeq")+ arn = _stream_arn(ddb, "StreamsSeq")++ for i in range(3):+ ddb.put_item(TableName="StreamsSeq", Item={"pk": {"S": f"k{i}"}})++ trim = ddb_streams.get_shard_iterator(+ StreamArn=arn, ShardId=_DEFAULT_SHARD_ID, ShardIteratorType="TRIM_HORIZON",+ )["ShardIterator"]+ all_records = _collect_all(ddb_streams, trim)+ assert len(all_records) == 3+ middle_seq = all_records[1]["dynamodb"]["SequenceNumber"]++ at_iter = ddb_streams.get_shard_iterator(+ StreamArn=arn,+ ShardId=_DEFAULT_SHARD_ID,+ ShardIteratorType="AT_SEQUENCE_NUMBER",+ SequenceNumber=middle_seq,+ )["ShardIterator"]+ at_records = _collect_all(ddb_streams, at_iter)+ assert [r["dynamodb"]["Keys"]["pk"]["S"] for r in at_records] == ["k1", "k2"]++ after_iter = ddb_streams.get_shard_iterator(+ StreamArn=arn,+ ShardId=_DEFAULT_SHARD_ID,+ ShardIteratorType="AFTER_SEQUENCE_NUMBER",+ SequenceNumber=middle_seq,+ )["ShardIterator"]+ after_records = _collect_all(ddb_streams, after_iter)+ assert [r["dynamodb"]["Keys"]["pk"]["S"] for r in after_records] == ["k2"]+++def test_get_records_limit_and_next_iterator(ddb, ddb_streams):+ _make_table(ddb, "StreamsPage")+ arn = _stream_arn(ddb, "StreamsPage")++ for i in range(5):+ ddb.put_item(TableName="StreamsPage", Item={"pk": {"S": f"k{i}"}})++ iterator = ddb_streams.get_shard_iterator(+ StreamArn=arn, ShardId=_DEFAULT_SHARD_ID, ShardIteratorType="TRIM_HORIZON",+ )["ShardIterator"]++ first = ddb_streams.get_records(ShardIterator=iterator, Limit=2)+ assert len(first["Records"]) == 2+ assert first["NextShardIterator"]++ second = ddb_streams.get_records(ShardIterator=first["NextShardIterator"], Limit=10)+ assert len(second["Records"]) == 3+ tail = ddb_streams.get_records(ShardIterator=second["NextShardIterator"], Limit=10)+ assert tail["Records"] == []+ assert tail["NextShardIterator"] # still valid, polls for new records+++# ---------------------------------------------------------------------------+# View type behaviour+# ---------------------------------------------------------------------------++def test_keys_only_view_omits_images(ddb, ddb_streams):+ _make_table(ddb, "StreamsKeysOnly", view_type="KEYS_ONLY")+ arn = _stream_arn(ddb, "StreamsKeysOnly")++ iterator = ddb_streams.get_shard_iterator(+ StreamArn=arn, ShardId=_DEFAULT_SHARD_ID, ShardIteratorType="TRIM_HORIZON",+ )["ShardIterator"]++ ddb.put_item(TableName="StreamsKeysOnly", Item={"pk": {"S": "k"}, "x": {"N": "1"}})+ ddb.delete_item(TableName="StreamsKeysOnly", Key={"pk": {"S": "k"}})++ records = _collect_all(ddb_streams, iterator)+ assert [r["eventName"] for r in records] == ["INSERT", "REMOVE"]+ for r in records:+ assert "NewImage" not in r["dynamodb"]+ assert "OldImage" not in r["dynamodb"]+ assert r["dynamodb"]["Keys"] == {"pk": {"S": "k"}}+ assert r["dynamodb"]["StreamViewType"] == "KEYS_ONLY"+++def test_old_image_only_view(ddb, ddb_streams):+ _make_table(ddb, "StreamsOldImg", view_type="OLD_IMAGE")+ arn = _stream_arn(ddb, "StreamsOldImg")++ iterator = ddb_streams.get_shard_iterator(+ StreamArn=arn, ShardId=_DEFAULT_SHARD_ID, ShardIteratorType="TRIM_HORIZON",+ )["ShardIterator"]++ ddb.put_item(TableName="StreamsOldImg", Item={"pk": {"S": "k"}, "v": {"S": "1"}})+ ddb.update_item(+ TableName="StreamsOldImg",+ Key={"pk": {"S": "k"}},+ UpdateExpression="SET v = :v",+ ExpressionAttributeValues={":v": {"S": "2"}},+ )++ records = _collect_all(ddb_streams, iterator)+ modify = records[-1]+ assert "NewImage" not in modify["dynamodb"]+ assert modify["dynamodb"]["OldImage"]["v"]["S"] == "1"+++# ---------------------------------------------------------------------------+# Validation / errors+# ---------------------------------------------------------------------------++def test_get_shard_iterator_missing_sequence_number(ddb, ddb_streams):+ _make_table(ddb, "StreamsValidateSeq")+ arn = _stream_arn(ddb, "StreamsValidateSeq")+ with pytest.raises(ClientError) as exc:+ ddb_streams.get_shard_iterator(+ StreamArn=arn,+ ShardId=_DEFAULT_SHARD_ID,+ ShardIteratorType="AT_SEQUENCE_NUMBER",+ )+ assert exc.value.response["Error"]["Code"] == "ValidationException"+++def test_get_records_rejects_garbage_iterator(ddb_streams):+ with pytest.raises(ClientError) as exc:+ ddb_streams.get_records(ShardIterator="not-a-valid-iterator")+ assert exc.value.response["Error"]["Code"] == "ValidationException"+++# ---------------------------------------------------------------------------+# Terraform compatibility tests+#+# These verify the shape that the Terraform AWS provider's aws_dynamodb_table+# resource reads back when stream_enabled = true, and that the stream ARN+# round-trips through DescribeTable -> DescribeStream so a downstream+# aws_lambda_event_source_mapping can hook in.+# ---------------------------------------------------------------------------+++def test_terraform_stream_arn_round_trips_describe_table_to_describe_stream(ddb, ddb_streams):+ """aws_dynamodb_table exposes stream_arn + stream_label; both must match+ what describe-stream returns so aws_lambda_event_source_mapping works."""+ tname = "tf-stream-roundtrip"+ _make_table(ddb, tname, view_type="NEW_AND_OLD_IMAGES")+ try:+ desc = ddb.describe_table(TableName=tname)["Table"]+ stream_arn = desc["LatestStreamArn"]+ stream_label = desc["LatestStreamLabel"]++ assert stream_arn.startswith("arn:aws:dynamodb:")+ assert f":table/{tname}/stream/{stream_label}" in stream_arn++ stream = ddb_streams.describe_stream(StreamArn=stream_arn)["StreamDescription"]+ assert stream["StreamArn"] == stream_arn+ assert stream["StreamLabel"] == stream_label+ assert stream["TableName"] == tname+ assert stream["StreamViewType"] == "NEW_AND_OLD_IMAGES"+ assert stream["StreamStatus"] in ("ENABLED", "ENABLING")+ assert stream["Shards"], "DescribeStream must report at least one shard"+ finally:+ ddb.delete_table(TableName=tname)+++def test_terraform_update_table_toggles_stream_specification(ddb, ddb_streams):+ """``terraform apply`` flipping stream_enabled false->true->false must+ land on the same DescribeTable contract."""+ tname = "tf-stream-toggle"+ _make_table(ddb, tname, stream_enabled=False)+ try:+ before = ddb.describe_table(TableName=tname)["Table"]+ assert "LatestStreamArn" not in before or not before["LatestStreamArn"]++ ddb.update_table(+ TableName=tname,+ StreamSpecification={"StreamEnabled": True, "StreamViewType": "KEYS_ONLY"},+ )+ after = ddb.describe_table(TableName=tname)["Table"]+ assert after["StreamSpecification"]["StreamEnabled"] is True+ assert after["StreamSpecification"]["StreamViewType"] == "KEYS_ONLY"+ finally:+ ddb.delete_table(TableName=tname)+++def test_terraform_list_streams_filters_by_table(ddb, ddb_streams):+ """aws_dynamodb_table data source calls ListStreams(TableName=...) to+ discover the current stream ARN without a full DescribeTable."""+ tname = "tf-stream-listfilter"+ _make_table(ddb, tname)+ try:+ arn = _stream_arn(ddb, tname)+ listed = ddb_streams.list_streams(TableName=tname)["Streams"]+ assert any(s["StreamArn"] == arn and s["TableName"] == tname for s in listed)+ finally:+ ddb.delete_table(TableName=tname)