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(kinesis): add SubscribeToShard (#1888)
Nahuel Nucerad193edcc0d97
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0aab1f49..90333a8c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added+- **Kinesis — `SubscribeToShard`** — enhanced fan-out: a registered consumer receives the shard's records as `SubscribeToShardEvent`s over an event stream (HTTP/1.1 or HTTP/2) for up to 5 minutes, from any `StartingPosition`, with `ContinuationSequenceNumber` for resuming and `ChildShards` when the shard is split or merged. A second call for the same consumer and shard within 5 seconds is a `ResourceInUseException`; a later one takes the subscription over.- **CloudWatch Logs — resource policies** — `PutResourcePolicy`, `DescribeResourcePolicies` and `DeleteResourcePolicy`, account-scoped (up to 10) or scoped to one log group through `resourceArn`, with `expectedRevisionId` checks. `AWS::Logs::ResourcePolicy` stacks now create real policies. Contributed by @fabio-andre-rodrigues.- **CloudFormation — `RollbackStack`** — rolls a stack left `CREATE_FAILED` or `UPDATE_FAILED` with rollback disabled back to its last stable state: a failed create ends `ROLLBACK_COMPLETE`, a failed update reverts its changes, deletes what it added and ends `UPDATE_ROLLBACK_COMPLETE`. `RetainExceptOnCreate` is honoured. Contributed by @fabio-andre-rodrigues.- **CloudFormation — stack drift detection** — `DetectStackDrift`, `DescribeStackDriftDetectionStatus`, `DetectStackResourceDrift` and `DescribeStackResourceDrifts` compare the properties a template sets, plus stack-level tags, with the service's current record (`IN_SYNC`, `MODIFIED` with `PropertyDifferences`, `DELETED`); stacks and resources report `DriftInformation`. Contributed by @fabio-andre-rodrigues.diff --git a/README.md b/README.mdindex 1c093b63..1f7b5ec7 100644--- a/README.md+++ b/README.md@@ -422,7 +422,7 @@ subnet = ec2.create_subnet(|---------|-----------|-------|| **SSM Parameter Store** | PutParameter, GetParameter, GetParameters, GetParametersByPath, DeleteParameter, DeleteParameters, DescribeParameters, GetParameterHistory, LabelParameterVersion, AddTagsToResource, RemoveTagsFromResource, ListTagsForResource | Supports String, SecureString, StringList; `name:version` and `name:label` selectors on `GetParameter` / `GetParameters` || **EventBridge** | CreateEventBus, UpdateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus, PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule, PutTargets, RemoveTargets, ListTargetsByRule, ListRuleNamesByTarget, PutEvents, TestEventPattern, TagResource, UntagResource, ListTagsForResource, CreateArchive, DeleteArchive, DescribeArchive, UpdateArchive, ListArchives, PutPermission, RemovePermission, CreateConnection, DescribeConnection, DeleteConnection, UpdateConnection, DeauthorizeConnection, ListConnections, CreateApiDestination, DescribeApiDestination, DeleteApiDestination, UpdateApiDestination, ListApiDestinations, StartReplay, DescribeReplay, ListReplays, CancelReplay, CreateEndpoint, DeleteEndpoint, DescribeEndpoint, ListEndpoints, UpdateEndpoint, ActivateEventSource, DeactivateEventSource, DescribeEventSource, CreatePartnerEventSource, DeletePartnerEventSource, DescribePartnerEventSource, ListPartnerEventSources, ListPartnerEventSourceAccounts, ListEventSources, PutPartnerEvents | Lambda target dispatch on PutEvents; S3 EventBridge notifications; archives capture matching events and `StartReplay` re-dispatches them to the destination bus in a background thread; API destination targets are **invoked over HTTP** on PutEvents — connection auth (Basic, API Key, OAuth client-credentials with token caching and 401/407 refresh), connection/target header/query/body parameter merging with connection precedence, `*` path parameters, dynamic JSON-path parameter values resolved from the untransformed event, and the AWS default headers (`User-Agent: Amazon/EventBridge/ApiDestinations`, default `Content-Type: application/json; charset=utf-8`), which connection and target parameters cannot override; redirects are not followed (a `3xx` is a non-retryable delivery failure), only `http(s)` invocation and OAuth authorization endpoints are accepted, `HttpMethod` and `AuthorizationType` are validated against their enums, and a connection that is not `AUTHORIZED` is not invoked (`DeauthorizeConnection` clears its stored credentials) — the 24h retry pipeline, rate limiting, and DLQs are not modeled; SaaS/partner APIs are otherwise control-plane stubs. Event patterns are **validated** — `PutRule`, `TestEventPattern`, `CreateArchive` and `UpdateArchive` reject a malformed pattern with `InvalidEventPatternException` carrying AWS's own reason text — and evaluate `prefix`/`suffix` (plain or case-insensitive via a nested `equals-ignore-case`), `wildcard` (AWS semantics — only `*` is special, `\` escapes — with catastrophic backtracking ruled out), `equals-ignore-case` (AWS's per-character case alternation), `exactly`, `cidr` (IPv4/IPv6, host bits floored, `/32` and `/128` refused as AWS refuses them), `numeric` (as the grammar it is: one comparison or a lower-then-upper bound), `exists` (leaf nodes only, so an object or an empty array does not exist), `anything-but` (a literal, a list, or a nested `prefix`/`suffix`/`wildcard`/`equals-ignore-case`, singly or as a list), and `$or` at any field position — expanded into flat alternatives at rule creation, so AWS's per-leaf last-write-wins collision rule and its 1000-combination cap both hold. All ten envelope fields are filterable, an unmodelled key is a path the event lacks rather than an error, `resources` is an intersection, array values are matched per element (with AWS's array-consistency rule), and values compare as JSON so a string never equals a number. An operand or key the matcher cannot evaluate never matches, rather than raising or matching everything. Not modeled: the 4096-character pattern limit, the wildcard-complexity refusal, and the 256-leaf rule-size cap |-| **Kinesis** | CreateStream, DeleteStream, DescribeStream, DescribeStreamSummary, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords, IncreaseStreamRetentionPeriod, DecreaseStreamRetentionPeriod, MergeShards, SplitShard, UpdateShardCount, StartStreamEncryption, StopStreamEncryption, EnableEnhancedMonitoring, DisableEnhancedMonitoring, RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers, DescribeStreamConsumer, AddTagsToStream, RemoveTagsFromStream, ListTagsForStream | Partition key → shard routing; AWS limits enforced (1 MB/record, 500 records/batch, 5 MB payload, 256-char partition key) |+| **Kinesis** | CreateStream, DeleteStream, DescribeStream, DescribeStreamSummary, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords, IncreaseStreamRetentionPeriod, DecreaseStreamRetentionPeriod, MergeShards, SplitShard, UpdateShardCount, StartStreamEncryption, StopStreamEncryption, EnableEnhancedMonitoring, DisableEnhancedMonitoring, RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers, DescribeStreamConsumer, SubscribeToShard, AddTagsToStream, RemoveTagsFromStream, ListTagsForStream | Partition key → shard routing; AWS limits enforced (1 MB/record, 500 records/batch, 5 MB payload, 256-char partition key); SubscribeToShard pushes `SubscribeToShardEvent`s over HTTP/1.1 or HTTP/2 (h2c) for up to 5 minutes, JSON or CBOR || **CloudWatch Metrics** | PutMetricData, GetMetricStatistics, GetMetricData, ListMetrics, PutMetricAlarm, PutCompositeAlarm, DescribeAlarms, DescribeAlarmsForMetric, DescribeAlarmHistory, DeleteAlarms, SetAlarmState, EnableAlarmActions, DisableAlarmActions, TagResource, UntagResource, ListTagsForResource, PutDashboard, GetDashboard, DeleteDashboards, ListDashboards | CBOR and JSON protocol || **SES** | SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail, VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity, VerifyDomainDkim, ListIdentities, ListVerifiedEmailAddresses, GetIdentityVerificationAttributes, GetIdentityDkimAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics, SetIdentityNotificationTopic, SetIdentityFeedbackForwardingEnabled, CreateConfigurationSet, DeleteConfigurationSet, DescribeConfigurationSet, ListConfigurationSets, CreateTemplate, GetTemplate, UpdateTemplate, DeleteTemplate, ListTemplates | Emails stored in-memory, not sent || **SES v2** | SendEmail, CreateEmailIdentity, GetEmailIdentity, DeleteEmailIdentity, ListEmailIdentities, CreateConfigurationSet, GetConfigurationSet, DeleteConfigurationSet, ListConfigurationSets, CreateEmailTemplate, GetEmailTemplate, UpdateEmailTemplate, DeleteEmailTemplate, ListEmailTemplates, GetAccount, PutAccountSuppressionAttributes, ListSuppressedDestinations, TagResource, UntagResource, ListTagsForResource | REST API (`/v2/email/`); identities auto-verified; emails stored in-memory, not sent; email templates share the v1 store, so `SendEmail` with `Content.Template` renders a template created through either API version |diff --git a/ministack/services/kinesis.py b/ministack/services/kinesis.pyindex 3454ae78..0b079095 100644--- a/ministack/services/kinesis.py+++ b/ministack/services/kinesis.py@@ -9,7 +9,7 @@ Supports: CreateStream, DeleteStream, DescribeStream, DescribeStreamSummary,IncreaseStreamRetentionPeriod, DecreaseStreamRetentionPeriod,AddTagsToStream, RemoveTagsFromStream, ListTagsForStream,RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers,- DescribeStreamConsumer,+ DescribeStreamConsumer, SubscribeToShard,StartStreamEncryption, StopStreamEncryption,EnableEnhancedMonitoring, DisableEnhancedMonitoring."""@@ -22,11 +22,13 @@ import loggingimport osimport threadingimport time+import zlibfrom ministack.core.arn import ArnParseError, parse_arnfrom ministack.core.responses import (AccountRegionScopedDict,AccountScopedDict,+ StreamingResponse,error_response_json,get_account_id,get_region,@@ -44,6 +46,11 @@ ITERATOR_EXPIRY_SECONDS = 300_streams = AccountRegionScopedDict()_shard_iterators = AccountRegionScopedDict()_consumers = AccountRegionScopedDict()+# (ConsumerARN, ShardId) -> {"id", "started"} of the live SubscribeToShard+_subscriptions = {}+SUBSCRIPTION_SECONDS = 300+_SUBSCRIPTION_TAKEOVER_SECONDS = 5+_SUBSCRIPTION_IDLE_SECONDS = 5_sequence_counter = 0_sequence_lock = threading.Lock()@@ -387,6 +394,7 @@ async def handle_request(method, path, headers, body, query_params):"DeregisterStreamConsumer": _deregister_consumer,"ListStreamConsumers": _list_consumers,"DescribeStreamConsumer": _describe_stream_consumer,+ "SubscribeToShard": lambda d: _subscribe_to_shard(d, is_cbor),"StartStreamEncryption": _start_stream_encryption,"StopStreamEncryption": _stop_stream_encryption,"EnableEnhancedMonitoring": _enable_enhanced_monitoring,@@ -400,6 +408,8 @@ async def handle_request(method, path, headers, body, query_params):return error_response_json("InvalidAction", f"Unknown action: {action}", 400)status, resp_headers, resp_body = handler(data)+ if isinstance(resp_body, StreamingResponse):+ return status, resp_headers, resp_bodyif is_cbor:import cbor2# Re-encode JSON response body as CBOR@@ -740,20 +750,10 @@ def _get_shard_iterator(data):seq = data.get("StartingSequenceNumber", "")at_ts = data.get("Timestamp")- if it_type == "TRIM_HORIZON":- position = 0- elif it_type == "LATEST":- position = len(records)- elif it_type == "AT_SEQUENCE_NUMBER":- position = next((i for i, r in enumerate(records) if r["SequenceNumber"] >= seq), len(records))- elif it_type == "AFTER_SEQUENCE_NUMBER":- position = next((i for i, r in enumerate(records) if r["SequenceNumber"] > seq), len(records))- elif it_type == "AT_TIMESTAMP":- if at_ts is None:- return error_response_json("ValidationException", "Timestamp required for AT_TIMESTAMP", 400)- ts_val = float(at_ts)- position = next((i for i, r in enumerate(records) if r["ApproximateArrivalTimestamp"] >= ts_val), len(records))- else:+ if it_type == "AT_TIMESTAMP" and at_ts is None:+ return error_response_json("ValidationException", "Timestamp required for AT_TIMESTAMP", 400)+ position = _start_position(records, it_type, seq, at_ts)+ if position is None:return error_response_json("ValidationException", f"Invalid ShardIteratorType: {it_type}", 400)resolved_name = name if name else next((n for n, s in _streams.items() if s is stream), "")@@ -768,6 +768,23 @@ def _get_shard_iterator(data):return json_response({"ShardIterator": token})+def _start_position(records, it_type, seq, at_ts):+ """Index into ``records`` where an iterator type starts; None for an unknown type."""+ if it_type == "TRIM_HORIZON":+ return 0+ if it_type == "LATEST":+ return len(records)+ if it_type == "AT_SEQUENCE_NUMBER":+ return next((i for i, r in enumerate(records) if r["SequenceNumber"] >= seq), len(records))+ if it_type == "AFTER_SEQUENCE_NUMBER":+ return next((i for i, r in enumerate(records) if r["SequenceNumber"] > seq), len(records))+ if it_type == "AT_TIMESTAMP":+ ts_val = float(at_ts)+ return next((i for i, r in enumerate(records)+ if r["ApproximateArrivalTimestamp"] >= ts_val), len(records))+ return None++def _ensure_base64(value):"""Return a base64-encoded string regardless of input format."""if isinstance(value, bytes):@@ -1123,6 +1140,156 @@ def _describe_stream_consumer(data):# Stream encryption# ---------------------------------------------------------------------------+# ---------------------------------------------------------------------------+# SubscribeToShard (enhanced fan-out eventstream)+# ---------------------------------------------------------------------------++def _eventstream_message(headers, payload):+ """One ``application/vnd.amazon.eventstream`` message with string headers."""+ raw = bytearray()+ for name, value in headers.items():+ name_b, value_b = name.encode(), value.encode()+ raw += bytes([len(name_b)]) + name_b + b"\x07" + len(value_b).to_bytes(2, "big") + value_b+ prelude = (12 + len(raw) + len(payload) + 4).to_bytes(4, "big") + len(raw).to_bytes(4, "big")+ head = prelude + zlib.crc32(prelude).to_bytes(4, "big") + bytes(raw) + payload+ return head + zlib.crc32(head).to_bytes(4, "big")+++def _subscribe_to_shard(data, is_cbor):+ consumer_arn = data.get("ConsumerARN")+ shard_id = data.get("ShardId")+ starting = data.get("StartingPosition") or {}+ it_type = starting.get("Type")+ if not consumer_arn or not shard_id or not it_type:+ return error_response_json("InvalidArgumentException",+ "ConsumerARN, ShardId and StartingPosition.Type are required", 400)+ consumer = _consumer_from_arn(consumer_arn)+ if not consumer:+ return error_response_json("ResourceNotFoundException",+ f"Consumer {consumer_arn} not found", 400)+ if consumer.get("ConsumerStatus") != "ACTIVE":+ return error_response_json("ResourceInUseException",+ f"Consumer {consumer_arn} is not ACTIVE", 400)+ stream = _resolve_stream_by_arn(consumer["StreamARN"])+ if not stream or shard_id not in stream["shards"]:+ return error_response_json("ResourceNotFoundException",+ f"Shard {shard_id} in stream {consumer['StreamARN']} not found", 400)+ if it_type in ("AT_SEQUENCE_NUMBER", "AFTER_SEQUENCE_NUMBER") and not starting.get("SequenceNumber"):+ return error_response_json("InvalidArgumentException",+ f"SequenceNumber is required for {it_type}", 400)+ if it_type == "AT_TIMESTAMP" and starting.get("Timestamp") is None:+ return error_response_json("InvalidArgumentException",+ "Timestamp is required for AT_TIMESTAMP", 400)+ _expire_records(stream)+ position = _start_position(stream["shards"][shard_id]["records"], it_type,+ starting.get("SequenceNumber", ""), starting.get("Timestamp"))+ if position is None:+ return error_response_json("InvalidArgumentException",+ f"Invalid StartingPosition.Type: {it_type}", 400)++ # A second call within 5 seconds is refused; later, it takes the subscription over.+ key = (consumer_arn, shard_id)+ now = time.time()+ live = _subscriptions.get(key)+ if live and now - live["started"] < _SUBSCRIPTION_TAKEOVER_SECONDS:+ return error_response_json("ResourceInUseException",+ f"Another active subscription exists for consumer {consumer_arn} "+ f"and shard {shard_id}", 400)+ subscription_id = new_uuid()+ _subscriptions[key] = {"id": subscription_id, "started": now}+ content_type = "application/x-amz-cbor-1.1" if is_cbor else "application/json"+ account_id, region = get_account_id(), get_region()+ stream_name = stream["StreamName"]++ def encode(payload):+ if is_cbor:+ import cbor2+ return cbor2.dumps(payload)+ return json.dumps(payload).encode()++ def event(event_type, payload):+ return _eventstream_message({":message-type": "event", ":event-type": event_type,+ ":content-type": content_type}, encode(payload))++ def exception(error_type, message):+ return _eventstream_message({":message-type": "exception", ":exception-type": error_type,+ ":content-type": content_type}, encode({"message": message}))++ def record_out(r, encryption):+ raw = base64.b64decode(_ensure_base64(r["Data"]))+ return {"SequenceNumber": r["SequenceNumber"],+ "ApproximateArrivalTimestamp": r["ApproximateArrivalTimestamp"],+ "Data": raw if is_cbor else base64.b64encode(raw).decode("ascii"),+ "PartitionKey": r["PartitionKey"],+ "EncryptionType": encryption}++ async def run(send, receive):+ import asyncio++ async def chunk(body, more=True):+ await send({"type": "http.response.body", "body": body, "more_body": more})++ async def disconnected():+ while (await receive()).get("type") != "http.disconnect":+ pass++ pos = position+ records = stream["shards"][shard_id]["records"]+ continuation = (records[pos - 1]["SequenceNumber"] if 0 < pos <= len(records)+ else stream["shards"][shard_id]["starting_sequence_number"])+ deadline = now + SUBSCRIPTION_SECONDS+ last_sent = 0.0+ watcher = asyncio.create_task(disconnected())+ try:+ await chunk(_eventstream_message({":message-type": "event", ":event-type": "initial-response",+ ":content-type": content_type}, encode({})))+ while not watcher.done() and time.time() < deadline:+ if (_subscriptions.get(key) or {}).get("id") != subscription_id:+ await chunk(exception("ResourceInUseException",+ f"Subscription to shard {shard_id} was taken over"))+ return+ current = _streams.get_scoped(account_id, region, stream_name)+ if current is not stream or _consumers.get_scoped(account_id, region, consumer_arn) is None:+ await chunk(exception("ResourceNotFoundException",+ f"Stream {stream_name} or consumer {consumer_arn} not found"))+ return+ shard = stream["shards"].get(shard_id)+ if shard is None:+ children = [{"ShardId": sid, "ParentShards": [p for p in (s.get("parent_shard_id"),+ s.get("adjacent_parent_shard_id")) if p],+ "HashKeyRange": {"StartingHashKey": s["starting_hash_key"],+ "EndingHashKey": s["ending_hash_key"]}}+ for sid, s in sorted(stream["shards"].items())+ if shard_id in (s.get("parent_shard_id"), s.get("adjacent_parent_shard_id"))]+ await chunk(event("SubscribeToShardEvent", {+ "Records": [], "ContinuationSequenceNumber": continuation,+ "MillisBehindLatest": 0, "ChildShards": children}))+ return+ records = shard["records"]+ batch = records[min(pos, len(records)):]+ if batch or not last_sent or time.time() - last_sent >= _SUBSCRIPTION_IDLE_SECONDS:+ encryption = stream.get("EncryptionType", "NONE")+ if batch:+ pos += len(batch)+ continuation = batch[-1]["SequenceNumber"]+ await chunk(event("SubscribeToShardEvent", {+ "Records": [record_out(r, encryption) for r in batch],+ "ContinuationSequenceNumber": continuation,+ "MillisBehindLatest": 0}))+ last_sent = time.time()+ await asyncio.wait({watcher}, timeout=0.2)+ finally:+ if (_subscriptions.get(key) or {}).get("id") == subscription_id:+ _subscriptions.pop(key, None)+ watcher.cancel()+ try:+ await chunk(b"", more=False)+ except Exception:+ pass++ return 200, {"Content-Type": "application/vnd.amazon.eventstream"}, StreamingResponse(run)++def _start_stream_encryption(data):name, stream = _resolve_stream(data)if not stream:@@ -1232,3 +1399,4 @@ def reset():_streams.clear()_shard_iterators.clear()_consumers.clear()+ _subscriptions.clear()diff --git a/tests/test_kinesis.py b/tests/test_kinesis.pyindex 2babeca7..5b4f2781 100644--- a/tests/test_kinesis.py+++ b/tests/test_kinesis.py@@ -286,6 +286,128 @@ def test_kinesis_register_deregister_consumer(kin):kin.delete_stream(StreamName=sname)+def _subscribe_setup(kin, shards=1):+ sname = f"intg-sub-{_uuid_mod.uuid4().hex[:8]}"+ kin.create_stream(StreamName=sname, ShardCount=shards)+ stream_arn = kin.describe_stream(StreamName=sname)["StreamDescription"]["StreamARN"]+ consumer_arn = kin.register_stream_consumer(+ StreamARN=stream_arn, ConsumerName="efo")["Consumer"]["ConsumerARN"]+ return sname, consumer_arn+++def test_kinesis_subscribe_to_shard_pushes_backlog_then_new_records(kin):+ sname, consumer_arn = _subscribe_setup(kin)+ first = [kin.put_record(StreamName=sname, Data=f"r{i}".encode(), PartitionKey="k")["SequenceNumber"]+ for i in range(2)]+ resp = kin.subscribe_to_shard(ConsumerARN=consumer_arn, ShardId="shardId-000000000000",+ StartingPosition={"Type": "TRIM_HORIZON"})+ events = iter(resp["EventStream"])+ event = next(events)["SubscribeToShardEvent"]+ assert [r["Data"] for r in event["Records"]] == [b"r0", b"r1"]+ assert [r["SequenceNumber"] for r in event["Records"]] == first+ assert event["ContinuationSequenceNumber"] == first[-1]+ assert event["MillisBehindLatest"] == 0++ third = kin.put_record(StreamName=sname, Data=b"r2", PartitionKey="k")["SequenceNumber"]+ event = next(events)["SubscribeToShardEvent"]+ assert [(r["Data"], r["PartitionKey"]) for r in event["Records"]] == [(b"r2", "k")]+ assert event["ContinuationSequenceNumber"] == third+ resp["EventStream"].close()++ resumed = kin.subscribe_to_shard(+ ConsumerARN=consumer_arn, ShardId="shardId-000000000000",+ StartingPosition={"Type": "AFTER_SEQUENCE_NUMBER", "SequenceNumber": first[0]})+ with pytest.raises(ClientError) as exc: # refused within 5 s of the first call+ kin.subscribe_to_shard(ConsumerARN=consumer_arn, ShardId="shardId-000000000000",+ StartingPosition={"Type": "LATEST"})+ assert exc.value.response["Error"]["Code"] == "ResourceInUseException"+ event = next(iter(resumed["EventStream"]))["SubscribeToShardEvent"]+ assert [r["SequenceNumber"] for r in event["Records"]] == [first[1], third]+ resumed["EventStream"].close()+ kin.delete_stream(StreamName=sname)+++def test_kinesis_subscribe_to_shard_latest_starts_empty_and_takeover_ends_the_old_stream(kin):+ sname, consumer_arn = _subscribe_setup(kin)+ kin.put_record(StreamName=sname, Data=b"old", PartitionKey="k")+ old = kin.subscribe_to_shard(ConsumerARN=consumer_arn, ShardId="shardId-000000000000",+ StartingPosition={"Type": "LATEST"})+ old_events = iter(old["EventStream"])+ event = next(old_events)["SubscribeToShardEvent"]+ assert event["Records"] == [] and event["ContinuationSequenceNumber"]++ time.sleep(5.2)+ new = kin.subscribe_to_shard(ConsumerARN=consumer_arn, ShardId="shardId-000000000000",+ StartingPosition={"Type": "LATEST"})+ with pytest.raises(ClientError) as exc:+ for _ in old_events:+ pass+ assert exc.value.response["Error"]["Code"] == "ResourceInUseException"+ assert next(iter(new["EventStream"]))["SubscribeToShardEvent"]["Records"] == []+ new["EventStream"].close()+ kin.delete_stream(StreamName=sname)+++def test_kinesis_subscribe_to_shard_ends_with_child_shards_after_a_split(kin):+ sname, consumer_arn = _subscribe_setup(kin)+ resp = kin.subscribe_to_shard(ConsumerARN=consumer_arn, ShardId="shardId-000000000000",+ StartingPosition={"Type": "TRIM_HORIZON"})+ events = iter(resp["EventStream"])+ assert "ChildShards" not in next(events)["SubscribeToShardEvent"]+ kin.split_shard(StreamName=sname, ShardToSplit="shardId-000000000000",+ NewStartingHashKey=str(2**127))+ last = [e["SubscribeToShardEvent"] for e in events][-1]+ assert sorted(c["ShardId"] for c in last["ChildShards"]) == [+ "shardId-000000000001", "shardId-000000000002"]+ assert all(c["ParentShards"] == ["shardId-000000000000"] for c in last["ChildShards"])+ kin.delete_stream(StreamName=sname)+++def test_kinesis_subscribe_to_shard_errors(kin):+ sname, consumer_arn = _subscribe_setup(kin)+ cases = [+ (dict(ConsumerARN=consumer_arn + "0", ShardId="shardId-000000000000",+ StartingPosition={"Type": "LATEST"}), "ResourceNotFoundException"),+ (dict(ConsumerARN=consumer_arn, ShardId="shardId-000000000009",+ StartingPosition={"Type": "LATEST"}), "ResourceNotFoundException"),+ (dict(ConsumerARN=consumer_arn, ShardId="shardId-000000000000",+ StartingPosition={"Type": "AT_SEQUENCE_NUMBER"}), "InvalidArgumentException"),+ ]+ for kwargs, code in cases:+ with pytest.raises(ClientError) as exc:+ kin.subscribe_to_shard(**kwargs)+ assert exc.value.response["Error"]["Code"] == code+ kin.delete_stream(StreamName=sname)+++def test_kinesis_subscribe_to_shard_cbor_events(kin):+ import urllib.request++ import cbor2+ from botocore.eventstream import EventStreamBuffer++ sname, consumer_arn = _subscribe_setup(kin)+ kin.put_record(StreamName=sname, Data=b"\x00\x01", PartitionKey="k")+ request = urllib.request.Request(+ kin.meta.endpoint_url, method="POST",+ data=cbor2.dumps({"ConsumerARN": consumer_arn, "ShardId": "shardId-000000000000",+ "StartingPosition": {"Type": "TRIM_HORIZON"}}),+ headers={"Content-Type": "application/x-amz-cbor-1.1",+ "X-Amz-Target": "Kinesis_20131202.SubscribeToShard",+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/kinesis/aws4_request"})+ buffer, messages = EventStreamBuffer(), []+ with urllib.request.urlopen(request, timeout=10) as response:+ while len(messages) < 2:+ buffer.add_data(response.read1(65536))+ messages.extend(buffer)+ assert messages[0].headers[":event-type"] == "initial-response"+ event = messages[1]+ assert event.headers[":content-type"] == "application/x-amz-cbor-1.1"+ record = cbor2.loads(event.payload)["Records"][0]+ assert record["Data"] == b"\x00\x01"+ kin.delete_stream(StreamName=sname)++def test_kinesis_consumer_arns_reject_foreign_region_without_exact_key_fallback(kin):"""ConsumerARN paths must not resolve a consumer owned by another request region."""west = _regional_kin("us-west-2")