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(iot): publish presence and subscription lifecycle events (#2002)
iot-rocket31ed9e2a3f09
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ed0cfdf2..997c8e1e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **IoT — a `#` region no longer widens topic filters** — a WebSocket session whose credential names `#` as its region received every message published under that region, whatever its filter, because filters were matched with the account and region prefix in front of them. Contributed by @iot-rocket.- **Cognito — app client secret hashes** — clients created with `GenerateSecret=true` require a valid `SecretHash` on signup, confirmation and password recovery, and `SECRET_HASH` on authentication and challenge responses. Missing or incorrect hashes return `NotAuthorizedException` before user changes, email delivery or Lambda triggers. Clients without a secret reject a supplied hash on self-service and initial authentication calls, while refresh and challenge responses ignore it, as on AWS. Refresh authentication verifies the token owner's username, or `sub` when the pool uses `UsernameAttributes`, and custom challenge sessions cannot be answered through a different client. The checks apply in both `AUTH` modes.### Added@@ -34,6 +35,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **RDS — a MySQL master user started in the background keeps its admin grant** — an instance whose engine image was not cached yet, or one respawned on restore, started on a background path that skipped the master-user grant the inline path gives, so the master user held only its own database and `SET PERSIST` failed for lack of `SYSTEM_VARIABLES_ADMIN`. Both paths now grant it. Contributed by @skialpine.### Added+- **IoT — lifecycle events** — the broker publishes `$aws/events/presence/connected|disconnected/{clientId}` and `$aws/events/subscriptions/subscribed|unsubscribed/{clientId}` with the AWS payload (`sessionIdentifier` kept by a resumed session, `principalIdentifier` the client certificate id, `versionNumber` advancing on every connect and disconnect, `disconnectReason` and `clientInitiatedDisconnect`), and as on AWS a subscription or topic rule whose filter starts with `#` or `+` does not receive `$aws/events` messages; client ids containing `#` or `+` get no lifecycle events. Contributed by @iot-rocket.- **Cognito — `SetUICustomization` and `GetUICustomization`** — store and return the classic hosted UI branding (CSS) for a user pool (`ClientId` `ALL`) or one app client, with the client falling back to the pool default, so SDK calls and Terraform's `aws_cognito_user_pool_ui_customization` work. As on AWS the pool needs a domain first. A logo `ImageFile` is accepted but not stored, as ministack does not serve hosted UI assets.- **OpenSearch Serverless — collections, security and access policies, and a proxied data plane** — `CreateCollection`, `BatchGetCollection`, `ListCollections`, `UpdateCollection`, `DeleteCollection`, `Create`/`Get`/`Update`/`Delete`/`ListSecurityPolicy` (`encryption`, `network`), `Create`/`Get`/`Update`/`Delete`/`ListAccessPolicy` (`data`), `GetPoliciesStats` and `TagResource` / `UntagResource` / `ListTagsForResource`, enough for Terraform's `aws_opensearchserverless_collection`, `_security_policy` and `_access_policy` to apply, plan clean and destroy. A collection needs a matching encryption policy (exact name or `prefix*`, most specific wins) unless `encryptionConfig` is given, and answers `kmsKeyArn: auto` for an AWS-owned key; policy documents are validated, a resource pattern may sit in only one encryption policy, a data policy refuses empty or wildcard principals, and an update must name the current `policyVersion` (`base64("<lastModifiedDate>_<n>")`). Its `collectionEndpoint`, `http://<id>.<region>.aoss.<host>:<port>`, is served through the gateway and requests must be SigV4-signed for `aoss` and carry `x-amz-content-sha256` (403 otherwise); with `OPENSEARCH_DATAPLANE=1` it is backed by its own `opensearchproject/opensearch` container, persisted on a named Docker volume across a restart under `PERSIST_STATE` and removed on `DeleteCollection`, otherwise it answers 503. APIs AOSS does not support answer 404, as `_refresh`, `_cluster/*` and scroll do on AWS, and `TIMESERIES` collections refuse custom document ids and updates. Data access and network policies are stored, not enforced. Checked against the botocore model and the OpenSearch Serverless developer guide and API reference.diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex 82048df5..e1f99c24 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -5296,6 +5296,8 @@ _persistent_sessions: dict[tuple[str, str, str], "_PersistentSessionState"] = {}# the broker's own session registry, so the two can never disagree and a# restart cannot leave a thing stuck reporting itself online._connectivity: dict[tuple[str, str, str], dict] = {}+# Next lifecycle-event ``versionNumber`` per (account, region, client id).+_presence_versions: dict[tuple[str, str, str], int] = {}_broker_lock = asyncio.Lock()_SESSION_EXPIRY_SECONDS: int = int(os.environ.get("IOT_SESSION_EXPIRY_SECONDS", "3600"))@@ -5305,13 +5307,17 @@ _MAX_QUEUED_MESSAGES = 1000class _PersistentSessionState:- __slots__ = ("subscriptions", "queued_messages", "created_at", "expiry_interval")+ __slots__ = (+ "subscriptions", "queued_messages", "created_at", "expiry_interval",+ "session_identifier",+ )def __init__(self,subscriptions: list[str],created_at: float,expiry_interval: int | None = None,+ session_identifier: str | None = None,):self.subscriptions: list[str] = subscriptionsself.queued_messages: list[tuple[str, bytes, int]] = []@@ -5321,6 +5327,8 @@ class _PersistentSessionState:# named no interval (every 3.1.1 client, and a v5 client that omitted# the property), so the module-wide default applies.self.expiry_interval: int | None = expiry_interval+ # Reported as ``sessionIdentifier`` by every connection that resumes it.+ self.session_identifier: str = session_identifier or str(uuid.uuid4())def _is_session_expired(session_state: _PersistentSessionState) -> bool:@@ -5453,6 +5461,13 @@ def _topic_matches(filter_: str, topic: str) -> bool:return ti == len(t_parts)+def _subscription_matches(filter_: str, topic: str) -> bool:+ """Whether a subscription's or rule's filter matches; ``$aws/events`` skips filters that start with a wildcard."""+ if topic.startswith("$aws/events/") and filter_[:1] in ("#", "+"):+ return False+ return _topic_matches(filter_, topic)++# ---------------------------------------------------------------------------# Topic validation# ---------------------------------------------------------------------------@@ -5509,6 +5524,7 @@ async def broker_stop() -> None:_connected_clients.clear()_persistent_sessions.clear()_connectivity.clear()+ _presence_versions.clear()_BASIC_INGEST_PREFIX = "$aws/rules/"@@ -5929,7 +5945,7 @@ async def _evaluate_topic_rules() -> None:for rule in _rules_for_account(account_id, region):filter_ = _rule_topic_filter(rule.get("sql", ""))- if filter_ and _topic_matches(filter_, topic):+ if filter_ and _subscription_matches(filter_, topic):await _run_rule_actions(account_id, region, rule, payload, topic, client_id)@@ -6443,7 +6459,9 @@ async def broker_publish(continueif sub.no_local and client_id is not None and sub.client_id == client_id:continue- if _topic_matches(sub.filter_prefixed, scoped):+ if _subscription_matches(+ _unscope_topic(sub.account_id, sub.region, sub.filter_prefixed), topic+ ):# Retain As Published forwards the publisher's flag; without# it the flag is cleared, so a subscriber can tell a live# message from a retained one (§3.3.1.3).@@ -6475,8 +6493,7 @@ async def broker_publish(if _is_session_expired(ps):continuefor filt in ps.subscriptions:- scoped_filter = _scoped_topic(ps_account_id, ps_region, filt)- if _topic_matches(scoped_filter, scoped):+ if _subscription_matches(filt, topic):ps.queued_messages.append((topic, payload, qos))if len(ps.queued_messages) > _MAX_QUEUED_MESSAGES:ps.queued_messages = ps.queued_messages[-_MAX_QUEUED_MESSAGES:]@@ -6490,9 +6507,9 @@ async def broker_publish(# recursive `accepted`/`delta`/`documents` publishes then flow back# through this function to drive their own subscribers and rules. The# response suffixes parse as None, so the bridge never re-triggers itself.- # NOTE known divergence: `_topic_matches` lets a bare `#` subscription- # match `$aws/...` topics, unlike real AWS where `#` excludes the- # reserved topic space.+ # As on AWS, a `#` subscription or rule also gets these `$aws/things`+ # topics; only `$aws/events` is kept from a leading wildcard+ # (`_subscription_matches`).shadow = _parse_shadow_topic(topic)if shadow is not None:try:@@ -6564,7 +6581,7 @@ async def broker_subscribe(rfor k, r in _retained.items()if k.startswith(scope_prefix)- and _topic_matches(filter_prefixed, k)+ and _subscription_matches(topic_filter, k[len(scope_prefix):])]else:retained_to_send = []@@ -6605,6 +6622,7 @@ def broker_reset() -> None:_connected_clients.clear()_persistent_sessions.clear()_connectivity.clear()+ _presence_versions.clear()# ---------------------------------------------------------------------------@@ -6643,7 +6661,7 @@ def _register_client(def _deregister_client(account_id: str, region: str, client_id: str, session: "_WSSession | None" = None-) -> None:+) -> bool:"""Drop a session from the registry and record its disconnect.``session`` identifies the caller so a session that has already been@@ -6652,10 +6670,11 @@ def _deregister_client(its socket close then drives its own handler through cleanup a second time.Without this guard that late second pass would evict the live session fromthe registry and backdate its connectivity to the moment the loser died.+ Returns whether this call recorded the disconnect."""key = (account_id, region, client_id)if session is not None and _connected_clients.get(key) is not session:- return+ return False_connected_clients.pop(key, None)_connectivity[key] = {"timestamp": _now_epoch_millis(),@@ -6663,6 +6682,15 @@ def _deregister_client(session.disconnect_reason() if session is not None else "CONNECTION_LOST"),}+ return True+++def _next_presence_version(account_id: str, region: str, client_id: str) -> int:+ """Take the client id's next lifecycle-event version; connects and disconnects each take one."""+ key = (account_id, region, client_id)+ version = _presence_versions.get(key, 0)+ _presence_versions[key] = version + 1+ return versionasync def _force_disconnect_duplicate(@@ -7086,10 +7114,16 @@ def _max_frame_buffer_bytes() -> int:class _WSSession:- def __init__(self, send_coro, account_id: str, region: str):+ def __init__(+ self, send_coro, account_id: str, region: str, principal: str | None = None+ ):self._send = send_coroself.account_id = account_idself.region = region+ # Lifecycle-event principal: the client certificate id, else the account.+ self._principal = principal or account_id+ self._session_identifier = ""+ self._presence_version = 0self._sub_ids: list[str] = []self._sub_filters: dict[str, str] = {}self._sub_granted_qos: dict[str, int] = {}@@ -7136,6 +7170,36 @@ class _WSSession:else "CONNECTION_LOST")+ async def _publish_lifecycle(self, event_type: str, **fields) -> None:+ """Publish this session's ``$aws/events`` presence or subscription event.++ AWS documents that client ids containing ``#`` or ``+`` receive no+ lifecycle events, so none is published for them."""+ if "#" in self._client_id or "+" in self._client_id:+ return+ group ="presence" if event_type.endswith("connected") else "subscriptions"+ await _publish_event(+ self.account_id,+ self.region,+ f"$aws/events/{group}/{event_type}/{self._client_id}",+ {+ "clientId": self._client_id,+ "timestamp": _now_epoch_millis(),+ "eventType": event_type,+ "sessionIdentifier": self._session_identifier,+ "principalIdentifier": self._principal,+ **fields,+ },+ )++ async def _publish_connected(self) -> None:+ """Publish this session's ``connected`` event."""+ await self._publish_lifecycle(+ "connected",+ ipAddress=_publish_source_ip.get(),+ versionNumber=self._presence_version,+ )+def _alloc_packet_id(self) -> int:pid = self._next_pidself._next_pid = (self._next_pid % 65535) + 1@@ -7409,6 +7473,11 @@ class _WSSession:self._graceful_disconnect = Falseself._forced_disconnect_reason = None+ self._session_identifier = str(uuid.uuid4())+ # Taken before the takeover, so the evicted session's disconnect follows it.+ self._presence_version = _next_presence_version(+ self.account_id, self.region, self._client_id+ )takeover_reason = await _force_disconnect_duplicate(self.account_id, self.region, self._client_id)@@ -7425,6 +7494,7 @@ class _WSSession:existing_ps = _persistent_sessions.get(session_key)if existing_ps is not None and not _is_session_expired(existing_ps):session_present = True+ self._session_identifier = existing_ps.session_identifierfor topic_filter in existing_ps.subscriptions:# A stored session keeps its topic filters, not the# subscription options they were made with: those live@@ -7448,17 +7518,20 @@ class _WSSession:existing_ps.queued_messages.clear()for q_topic, q_payload, q_qos in queued:await self.deliver_to_client(q_topic, q_payload, q_qos)+ await self._publish_connected()return Trueelse:_persistent_sessions[session_key] = _PersistentSessionState(subscriptions=[],created_at=time.time(),expiry_interval=self._session_expiry_interval,+ session_identifier=self._session_identifier,)await self._send_connack(session_present=session_present, assigned_client_id=assigned_client_id)+ await self._publish_connected()return Trueif pkt_type == PKT_PUBLISH:@@ -7514,8 +7587,10 @@ class _WSSession:# as unavailable in CONNACK and ignores it if sent anyway._subscribe_props, off = _decode_properties(body, off)granted = []+ topics = []while off < len(body):topic, off = _read_string(body, off)+ topics.append(topic)# MQTT 5 replaces 3.1.1's bare QoS byte with a subscription# options byte: the low two bits are the QoS, the rest are No# Local, Retain As Published and Retain Handling. In 3.1.1 the@@ -7550,6 +7625,7 @@ class _WSSession:await self.send_bytes(_make_suback(packet_id, granted, protocol_version=self.protocol_version))+ await self._publish_lifecycle("subscribed", topics=topics)return Trueif pkt_type == PKT_PUBACK:@@ -7614,6 +7690,7 @@ class _WSSession:else:# 3.1.1's UNSUBACK is the packet identifier and nothing else.await self.send_bytes(_make_unsuback(packet_id))+ await self._publish_lifecycle("unsubscribed", topics=filters)return Trueif pkt_type == PKT_PINGREQ:@@ -7668,9 +7745,16 @@ class _WSSession:self._sub_ids.clear()self._sub_filters.clear()self._sub_granted_qos.clear()- if self._client_id:- _deregister_client(- self.account_id, self.region, self._client_id, self+ if self._client_id and _deregister_client(+ self.account_id, self.region, self._client_id, self+ ):+ _next_presence_version(self.account_id, self.region, self._client_id)+ reason = self.disconnect_reason()+ await self._publish_lifecycle(+ "disconnected",+ clientInitiatedDisconnect=reason == "CLIENT_INITIATED_DISCONNECT",+ disconnectReason=reason,+ versionNumber=self._presence_version,)def _preserve_session(self) -> None:@@ -7686,6 +7770,7 @@ class _WSSession:subscriptions=unprefixed_filters,created_at=time.time(),expiry_interval=self._session_expiry_interval,+ session_identifier=self._session_identifier,)@@ -8421,7 +8506,9 @@ async def _mtls_serve_conn(reader: asyncio.StreamReader, writer: asyncio.StreamWaccount_token = _request_account_id.set(account_id)region_token = _request_region.set(region)- session = _WSSession(_tcp_send, account_id, region)+ session = _WSSession(+ _tcp_send, account_id, region, hashlib.sha256(der).hexdigest() if der else None+ )max_buffer = _max_frame_buffer_bytes()_mtls_logger.info("IoT mTLS: connection from %s serving %s/%s (%s)",diff --git a/tests/test_iot.py b/tests/test_iot.pyindex 89fc022a..f97eabb5 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -2086,6 +2086,115 @@ def test_iot_broker_region_wildcards_cannot_bypass_isolation(reset()+def test_iot_broker_wildcard_region_does_not_widen_its_own_filters():+ """A ``#`` region in the scope prefix must not turn a filter into ``#``."""+ reset()++ async def _run():+ account_id = "123456789012"+ received = []++ async def callback(topic, payload, qos):+ received.append(topic)++ await broker_subscribe(account_id, "#", "sensors/temp", callback)+ await broker_publish(account_id, "#", "other/topic", b"x")+ await broker_publish(account_id, "#", "sensors/temp", b"x")+ assert received == ["sensors/temp"]++ asyncio.run(_run())+ reset()+++def test_iot_broker_leading_wildcard_does_not_match_aws_events():+ """``#`` and ``+/...`` get ``$aws/things`` but not ``$aws/events``, live and queued."""+ reset()++ async def _run():+ send, _sent = _mock_send()+ offline = _WSSession(send, "123456789012")+ await offline.handle_packet(+ PKT_CONNECT, 0, _build_connect_body("offline-hash", clean_session=False)+ )+ await offline.handle_packet(+ PKT_SUBSCRIBE, 0x02, _build_subscribe_body(1, [("#", 1)])+ )+ await offline.cleanup()++ received = {}+ for topic_filter in ("#", "+/#", "$aws/events/#"):+ async def callback(topic, payload, qos, key=topic_filter):+ received.setdefault(key, []).append(topic)++ await subscribe("123456789012", topic_filter, callback)++ await publish("123456789012", "$aws/events/presence/connected/dev", b"{}", qos=1)+ await publish("123456789012", "$aws/things/dev/shadow/get/rejected", b"{}", qos=1)++ assert received == {+ "#": ["$aws/things/dev/shadow/get/rejected"],+ "+/#": ["$aws/things/dev/shadow/get/rejected"],+ "$aws/events/#": ["$aws/events/presence/connected/dev"],+ }+ queued = _persistent_sessions[("123456789012", _TEST_REGION, "offline-hash")]+ assert [m[0] for m in queued.queued_messages] == [+ "$aws/things/dev/shadow/get/rejected"+ ]++ asyncio.run(_run())+ reset()+++def test_iot_topic_rule_leading_wildcard_does_not_match_aws_events(monkeypatch):+ """A ``#`` rule fires on ``$aws/things`` but, as on AWS, not on ``$aws/events``."""+ from ministack.services import iot as iot_module++ reset()+ iot_module._topic_rules.clear()+ account_id = "123456789012"+ filters = (+ "#",+ "+/events/presence/#",+ "$aws/events/presence/connected/+",+ "$aws/things/+/shadow/update/accepted",+ )+ for i, topic_filter in enumerate(filters):+ iot_module._topic_rules.set_scoped(account_id, _TEST_REGION, f"r{i}", {+ "ruleName": f"r{i}",+ "sql": f"SELECT * FROM '{topic_filter}'",+ "ruleDisabled": False,+ "actions": [],+ })+ fired = []++ async def _capture_rule_action(+ dispatched_account_id, dispatched_region, rule, payload, topic="", client_id=None+ ):+ fired.append((rule["ruleName"], topic))++ monkeypatch.setattr(iot_module, "_run_rule_actions", _capture_rule_action)++ async def _run():+ for topic in (+ "sensors/temp",+ "$aws/events/presence/connected/dev",+ "$aws/things/dev/shadow/update/accepted",+ ):+ await broker_publish(account_id, _TEST_REGION, topic, b"{}")++ try:+ asyncio.run(_run())+ finally:+ iot_module._topic_rules.clear()+ reset()+ assert sorted(fired) == [+ ("r0", "$aws/things/dev/shadow/update/accepted"),+ ("r0", "sensors/temp"),+ ("r2", "$aws/events/presence/connected/dev"),+ ("r3", "$aws/things/dev/shadow/update/accepted"),+ ]++def test_iot_broker_persistent_sessions_are_region_isolated():reset()@@ -5235,6 +5344,175 @@ def test_connectivity_reconnect_clears_the_previous_disconnect_reason():reset()+async def _watch_lifecycle_events():+ """Subscribe to ``$aws/events/#`` and return the list the events land in."""+ events = []++ async def callback(topic, payload, qos):+ events.append((topic, json.loads(payload)))++ await subscribe(_ACCT, "$aws/events/#", callback)+ return events+++def test_lifecycle_events_for_connect_subscribe_unsubscribe_disconnect():+ """Payload keys and topics as AWS publishes them for one session."""+ reset()++ async def _run():+ events = await _watch_lifecycle_events()+ send, _sent = _mock_send()+ session = _IoTWSSession(send, _ACCT, _TEST_REGION, principal="c0ffee")+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("dev-life"))+ await session.handle_packet(+ PKT_SUBSCRIBE, 0x02, _build_subscribe_body(1, [("a", 0), ("b/#", 1)])+ )+ await session.handle_packet(+ PKT_UNSUBSCRIBE, 0x02, _build_unsubscribe_body(2, ["a", "never"])+ )+ await session.handle_packet(PKT_DISCONNECT, 0, b"")+ await session.cleanup()++ assert [topic for topic, _event in events] == [+ "$aws/events/presence/connected/dev-life",+ "$aws/events/subscriptions/subscribed/dev-life",+ "$aws/events/subscriptions/unsubscribed/dev-life",+ "$aws/events/presence/disconnected/dev-life",+ ]+ connected, subscribed, unsubscribed, disconnected = [e for _t, e in events]+ common = {+ "clientId": "dev-life",+ "principalIdentifier": "c0ffee",+ "sessionIdentifier": connected["sessionIdentifier"],+ }+ for event in (connected, subscribed, unsubscribed, disconnected):+ assert isinstance(event.pop("timestamp"), int)+ assert connected == {+ **common, "eventType": "connected", "ipAddress": "127.0.0.1",+ "versionNumber": 0,+ }+ assert subscribed == {**common, "eventType": "subscribed", "topics": ["a", "b/#"]}+ assert unsubscribed == {+ **common, "eventType": "unsubscribed", "topics": ["a", "never"],+ }+ assert disconnected == {+ **common, "eventType": "disconnected", "clientInitiatedDisconnect": True,+ "disconnectReason": "CLIENT_INITIATED_DISCONNECT", "versionNumber": 0,+ }++ asyncio.run(_run())+ reset()+++def test_lifecycle_events_skip_client_ids_with_wildcards():+ """AWS documents that client ids containing # or + receive no lifecycle events."""+ reset()++ async def _run():+ events = await _watch_lifecycle_events()+ for client_id in ("dev#hash", "dev+plus", "dev-plain"):+ send, _sent = _mock_send()+ session = _IoTWSSession(send, _ACCT, _TEST_REGION, principal="c0ffee")+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body(client_id))+ await session.handle_packet(+ PKT_SUBSCRIBE, 0x02, _build_subscribe_body(1, [("a", 0)])+ )+ await session.handle_packet(PKT_DISCONNECT, 0, b"")+ await session.cleanup()++ assert [topic for topic, _event in events] == [+ "$aws/events/presence/connected/dev-plain",+ "$aws/events/subscriptions/subscribed/dev-plain",+ "$aws/events/presence/disconnected/dev-plain",+ ]++ asyncio.run(_run())+ reset()+++def test_lifecycle_version_numbers_and_disconnect_reasons():+ """Connects and disconnects each advance versionNumber; a takeover allocates first."""+ reset()++ async def _run():+ events = await _watch_lifecycle_events()++ async def connect():+ send, _sent = _mock_send()+ session = _WSSession(send, _ACCT)+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("dev-ver"))+ return session++ first = await connect()+ await first.handle_packet(PKT_DISCONNECT, 0, b"")+ await first.cleanup()+ dropped = await connect()+ await dropped.cleanup()+ evicted = await connect()+ taker = await connect()+ await evicted.cleanup()+ await taker.handle_packet(PKT_DISCONNECT, 0, b"")+ await taker.cleanup()++ assert [+ (+ e["eventType"], e["versionNumber"], e.get("disconnectReason"),+ e.get("clientInitiatedDisconnect"), e["principalIdentifier"],+ )+ for _t, e in events+ ] == [+ ("connected", 0, None, None, _ACCT),+ ("disconnected", 0, "CLIENT_INITIATED_DISCONNECT", True, _ACCT),+ ("connected", 2, None, None, _ACCT),+ ("disconnected", 2, "CONNECTION_LOST", False, _ACCT),+ ("connected", 4, None, None, _ACCT),+ ("disconnected", 4, "DUPLICATE_CLIENTID", False, _ACCT),+ ("connected", 5, None, None, _ACCT),+ ("disconnected", 5, "CLIENT_INITIATED_DISCONNECT", True, _ACCT),+ ]++ asyncio.run(_run())+ reset()+++def test_lifecycle_resumed_session_keeps_its_session_identifier():+ """A resumed persistent session reuses sessionIdentifier and raises no subscribed event."""+ reset()++ async def _run():+ events = await _watch_lifecycle_events()++ async def connect(clean_session):+ send, _sent = _mock_send()+ session = _WSSession(send, _ACCT)+ await session.handle_packet(+ PKT_CONNECT, 0,+ _build_connect_body("dev-resume", clean_session=clean_session),+ )+ return session++ first = await connect(False)+ await first.handle_packet(PKT_SUBSCRIBE, 0x02, _build_subscribe_body(1, [("p", 1)]))+ await first.handle_packet(PKT_DISCONNECT, 0, b"")+ await first.cleanup()+ resumed = await connect(False)+ await resumed.handle_packet(PKT_DISCONNECT, 0, b"")+ await resumed.cleanup()+ fresh = await connect(True)+ await fresh.cleanup()++ kinds = [(e["eventType"], e["sessionIdentifier"]) for _t, e in events]+ original = kinds[0][1]+ assert [k for k, _s in kinds] == [+ "connected", "subscribed", "disconnected",+ "connected", "disconnected", "connected", "disconnected",+ ]+ assert [s == original for _k, s in kinds] == [True] * 5 + [False] * 2++ asyncio.run(_run())+ reset()++def test_connectivity_is_not_persisted_and_cannot_restore_as_connected():"""A snapshot must not be able to claim a thing is online after a restart.