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): connectivity.* terms in the fleet index (#1399)
iot-rocket3a29991aa9d1
diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex ccf126e1..f3cb5fee 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -21,7 +21,7 @@ Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:``DetachPolicy``, etc.- Fleet indexing: ``UpdateIndexingConfiguration`` /``GetIndexingConfiguration`` / ``DescribeIndex`` / ``ListIndices``, and- ``SearchIndex`` over the live registry + shadows+ ``SearchIndex`` over the live registry, shadows and MQTT connectivity- ``DescribeEndpoint`` returning a per-account hostnameThis is the control plane — pure HTTP/JSON, no MQTT broker@@ -150,6 +150,9 @@ class _RetainedMessage:def _broker_get_state() -> dict:+ # Retained messages only. Connectivity is deliberately not persisted: no+ # session survives a restart, so restoring a thing as connected would put a+ # claim in the fleet index that the broker cannot back with a live session.retained_list = []for topic, msg in _retained.items():retained_list.append({@@ -1815,6 +1818,10 @@ _SEARCH_TOP_FIELDS = ("thingName", "thingTypeName", "thingGroupNames")# addressable: shadow.metadata / shadow.version / shadow.name.<name> (named# shadows) are AWS fields this emulator does not project._SEARCH_SHADOW_HALVES = ("desired", "reported")+# Unlike attributes.* and shadow.*, the connectivity group is closed — AWS+# defines exactly these three — so an unknown leaf is a typo worth reporting+# rather than a field that happens to be absent from this thing.+_SEARCH_CONNECTIVITY_FIELDS = ("connected", "timestamp", "disconnectReason")# AWS names the single thing index ``AWS_Things``; it exists only while thing# indexing is enabled, which is why every fleet stack starts with an@@ -1851,6 +1858,12 @@ def _thing_indexing_mode() -> str:)+def _thing_connectivity_indexing_mode(config: dict) -> str:+ return config.get("thingIndexingConfiguration", {}).get(+ "thingConnectivityIndexingMode", "OFF"+ )++def _update_indexing_configuration(payload: dict) -> tuple:"""``POST /indexing/config`` — enable or disable fleet indexing.@@ -1861,10 +1874,11 @@ def _update_indexing_configuration(payload: dict) -> tuple:Only the modes this emulator can honor are interpreted —``thingIndexingMode`` gates ``SearchIndex`` and whether shadow fields are- queryable. ``deviceDefenderIndexingMode``, ``namedShadowIndexingMode``,- ``customFields`` and ``filter`` are stored and echoed back by- ``GetIndexingConfiguration`` so IaC round-trips cleanly, but nothing here- projects those fields; querying one is an out-of-grammar+ queryable, and ``thingConnectivityIndexingMode`` gates the+ ``connectivity`` group. ``deviceDefenderIndexingMode``,+ ``namedShadowIndexingMode``, ``customFields`` and ``filter`` are stored and+ echoed back by ``GetIndexingConfiguration`` so IaC round-trips cleanly, but+ nothing here projects those fields; querying one is an out-of-grammar``InvalidQueryException`` rather than a silent miss."""config = _indexing_configuration()@@ -1941,11 +1955,14 @@ def _get_indexing_configuration() -> tuple:def _index_schema(config: dict) -> str:"""``DescribeIndex``'s schema string for the configuration in force."""thing_cfg = config.get("thingIndexingConfiguration", {})- return (+ schema = ("REGISTRY_AND_SHADOW"if thing_cfg.get("thingIndexingMode") == "REGISTRY_AND_SHADOW"else "REGISTRY")+ if _thing_connectivity_indexing_mode(config) == "STATUS":+ schema += "_AND_CONNECTIVITY_STATUS"+ return schemadef _describe_index(path: str) -> tuple:@@ -2015,7 +2032,42 @@ def _classic_shadow_state(thing_name: str) -> dict | None:return rec.get("state") or {}-def _search_field_error(field: str, thing_mode: str) -> str | None:+def _thing_connectivity(account_id: str, region: str, thing_name: str) -> dict:+ """The ``connectivity`` group for a thing, as fleet indexing reports it.++ A thing counts as connected when a live MQTT session's *client id* equals+ the thing name. That is the association AWS makes, and it is the only one+ available: the broker knows client ids, and a device that connects under+ some other client id is legitimately not this thing's connectivity, even+ if the same hardware is behind it.++ ``connected`` is read from the session registry on every call rather than+ stored, so it cannot drift; only the transition timestamp and the reason+ the last session ended are remembered. A thing that has never connected+ reports ``connected: false`` with no timestamp — the honest answer, rather+ than an epoch that implies a disconnect that never happened.++ ``disconnectReason`` is reported whenever one is on record, including+ while the thing is connected: after a takeover that reason is+ DUPLICATE_CLIENTID, and the takeover is precisely the transition that+ produced the session now reporting itself online. An ordinary reconnect+ clears it (see ``_register_client``), so a reason that is present always+ describes how the *current* state came about.+ """+ key = (account_id, region, thing_name)+ doc: dict = {"connected": key in _connected_clients}+ record = _connectivity.get(key)+ if record is None:+ return doc+ doc["timestamp"] = record["timestamp"]+ if record.get("disconnectReason"):+ doc["disconnectReason"] = record["disconnectReason"]+ return doc+++def _search_field_error(+ field: str, thing_mode: str, connectivity_mode: str+) -> str | None:"""Why ``field`` is not queryable, or None when it is.Every rejection is a 400 rather than a query that matches nothing: a@@ -2026,6 +2078,16 @@ def _search_field_error(field: str, thing_mode: str) -> str | None:return Noneif field.startswith("attributes.") and field != "attributes.":return None+ if field.startswith("connectivity."):+ leaf = field.split(".", 1)[1]+ if leaf not in _SEARCH_CONNECTIVITY_FIELDS:+ return f"Unsupported query field: {field!r}"+ if connectivity_mode != "STATUS":+ return (+ f"Connectivity field {field!r} is not indexed: "+ "thingConnectivityIndexingMode is OFF"+ )+ return Noneif field.startswith("shadow."):parts = field.split(".")if len(parts) < 3 or parts[1] not in _SEARCH_SHADOW_HALVES or not parts[-1]:@@ -2043,13 +2105,19 @@ def _search_field_error(field: str, thing_mode: str) -> str | None:return f"Unsupported query field: {field!r}"-def _search_field_value(thing: dict, field: str, shadow_state: dict | None):+def _search_field_value(+ thing: dict, field: str, shadow_state: dict | None, connectivity: dict+):if field == "thingName":return thing.get("thingName")if field == "thingTypeName":return thing.get("thingTypeName")if field == "thingGroupNames":return thing.get("thingGroupNames") or None+ if field.startswith("connectivity."):+ # A missing key answers None, which never matches — so a thing that is+ # currently connected does not match connectivity.disconnectReason:*.+ return connectivity.get(field.split(".", 1)[1])if field.startswith("attributes."):return (thing.get("attributes") or {}).get(field.split(".", 1)[1])if field.startswith("shadow.") and shadow_state is not None:@@ -2138,11 +2206,12 @@ def _search_index(payload: dict) -> tuple:Supported grammar (the subset device fleets actually use):``AND``-separated ``field:value`` terms over ``thingName``,- ``thingTypeName``, ``thingGroupNames``, ``attributes.<name>`` and — once- ``thingIndexingMode`` is REGISTRY_AND_SHADOW —- ``shadow.desired|reported.<path>``, compared case-insensitively, with- ``*`` / ``?`` wildcards in the value. Anything outside that grammar is- rejected with ``InvalidQueryException``.+ ``thingTypeName``, ``thingGroupNames`` and ``attributes.<name>``; over+ ``shadow.desired|reported.<path>`` once ``thingIndexingMode`` is+ REGISTRY_AND_SHADOW; and over ``connectivity.connected`` / ``.timestamp``+ / ``.disconnectReason`` once ``thingConnectivityIndexingMode`` is STATUS.+ Values compare case-insensitively, with ``*`` / ``?`` wildcards.+ Anything outside that grammar is rejected with ``InvalidQueryException``.Results page through ``maxResults`` + ``nextToken``; the token is anoffset into the live match list, so a thing created between pages can@@ -2168,8 +2237,9 @@ def _search_index(payload: dict) -> tuple:f"Unsupported query syntax: {query!r}",400,)+ connectivity_mode = _thing_connectivity_indexing_mode(config)for field, _ in terms:- problem = _search_field_error(field, thing_mode)+ problem = _search_field_error(field, thing_mode, connectivity_mode)if problem is not None:return error_response_json("InvalidQueryException", problem, 400)@@ -2192,11 +2262,20 @@ def _search_index(payload: dict) -> tuple:)shadows_indexed = thing_mode == "REGISTRY_AND_SHADOW"+ connectivity_indexed = connectivity_mode == "STATUS"+ account_id, region = get_account_id(), get_region()matched = []for name, thing in _things.items():shadow_state = _classic_shadow_state(name) if shadows_indexed else None+ connectivity = (+ _thing_connectivity(account_id, region, name)+ if connectivity_indexed+ else {}+ )if not all(- _search_value_matches(_search_field_value(thing, f, shadow_state), v)+ _search_value_matches(+ _search_field_value(thing, f, shadow_state, connectivity), v+ )for f, v in terms):continue@@ -2206,6 +2285,8 @@ def _search_index(payload: dict) -> tuple:"attributes": thing.get("attributes") or {},"thingGroupNames": list(thing.get("thingGroupNames") or []),}+ if connectivity_indexed:+ entry["connectivity"] = connectivityif thing.get("thingTypeName"):entry["thingTypeName"] = thing["thingTypeName"]if shadow_state:@@ -3440,6 +3521,12 @@ _broker_logger = logging.getLogger("iot_broker")_subscriptions: dict[str, set["_Subscription"]] = {}_connected_clients: dict[tuple[str, str, str], "_WSSession"] = {}_persistent_sessions: dict[tuple[str, str, str], "_PersistentSessionState"] = {}+# Last connect/disconnect transition per (account, region, client id), as+# ``{"timestamp": <epoch ms>, "disconnectReason": <str|None>}``. Deliberately+# NOT a connected flag: liveness is read from ``_connected_clients``, which is+# 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] = {}_broker_lock = asyncio.Lock()_SESSION_EXPIRY_SECONDS: int = int(os.environ.get("IOT_SESSION_EXPIRY_SECONDS", "3600"))@@ -3633,6 +3720,7 @@ async def broker_stop() -> None:_retained.clear()_connected_clients.clear()_persistent_sessions.clear()+ _connectivity.clear()_BASIC_INGEST_PREFIX = "$aws/rules/"@@ -4393,6 +4481,7 @@ def broker_reset() -> None:_retained.clear()_connected_clients.clear()_persistent_sessions.clear()+ _connectivity.clear()# ---------------------------------------------------------------------------@@ -4400,36 +4489,87 @@ def broker_reset() -> None:# ---------------------------------------------------------------------------+def _now_epoch_millis() -> int:+ return int(time.time() * 1000)++def _register_client(- account_id: str, region: str, client_id: str, session: "_WSSession"+ account_id: str,+ region: str,+ client_id: str,+ session: "_WSSession",+ superseded_reason: str | None = None,) -> None:- _connected_clients[(account_id, region, client_id)] = session+ """Record a live session, and with it the transition that started it.++ ``superseded_reason`` is the reason the connect itself ended a previous+ session — only a takeover can do that, and only DUPLICATE_CLIENTID names+ it. Carrying it onto the new record is what makes the reason observable+ at all: the eviction and this registration are the same transition, so+ overwriting it here (as this did) left a value no caller could ever read.+ An ordinary reconnect passes None and clears the older reason, because+ that disconnect was a transition of its own that this connect supersedes.+ """+ key = (account_id, region, client_id)+ _connected_clients[key] = session+ _connectivity[key] = {+ "timestamp": _now_epoch_millis(),+ "disconnectReason": superseded_reason,+ }-def _deregister_client(account_id: str, region: str, client_id: str) -> None:- _connected_clients.pop((account_id, region, client_id), None)+def _deregister_client(+ account_id: str, region: str, client_id: str, session: "_WSSession | None" = None+) -> None:+ """Drop a session from the registry and record its disconnect.++ ``session`` identifies the caller so a session that has already been+ replaced cannot deregister its successor. A client that reconnects under+ the same client id is taken over: the old session is cleaned up first, and+ 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 from+ the registry and backdate its connectivity to the moment the loser died.+ """+ key = (account_id, region, client_id)+ if session is not None and _connected_clients.get(key) is not session:+ return+ _connected_clients.pop(key, None)+ _connectivity[key] = {+ "timestamp": _now_epoch_millis(),+ "disconnectReason": (+ session.disconnect_reason() if session is not None else "CONNECTION_LOST"+ ),+ }async def _force_disconnect_duplicate(account_id: str, region: str, client_id: str-) -> None:+) -> str | None:+ """Evict a session that the incoming one is taking over.++ Returns DUPLICATE_CLIENTID when there was one to evict, so the caller can+ carry that reason onto the record it is about to write; otherwise None.+ """key = (account_id, region, client_id)existing = _connected_clients.get(key)- if existing is not None:- _broker_logger.info("IoT broker: duplicate client_id=%s, forcing old connection closed", client_id)- if existing.protocol_version == MQTT_5:- # An MQTT 5 client is told why it lost the connection; 3.1.1 has- # no server-initiated DISCONNECT, so it just sees the close.- try:- await existing.send_bytes(_make_disconnect(RC5_SESSION_TAKEN_OVER))- except Exception:- pass+ if existing is None:+ return None+ _broker_logger.info("IoT broker: duplicate client_id=%s, forcing old connection closed", client_id)+ existing._forced_disconnect_reason = "DUPLICATE_CLIENTID"+ if existing.protocol_version == MQTT_5:+ # An MQTT 5 client is told why it lost the connection; 3.1.1 has+ # no server-initiated DISCONNECT, so it just sees the close.try:- await existing._send({"type": "websocket.close", "code": 1000})+ await existing.send_bytes(_make_disconnect(RC5_SESSION_TAKEN_OVER))except Exception:pass- await existing.cleanup()- _connected_clients.pop(key, None)+ try:+ await existing._send({"type": "websocket.close", "code": 1000})+ except Exception:+ pass+ await existing.cleanup()+ _connected_clients.pop(key, None)+ return "DUPLICATE_CLIENTID"# ---------------------------------------------------------------------------@@ -4840,6 +4980,28 @@ class _WSSession:self._will_retain: bool = Falseself._will_properties: bytes = b""self._graceful_disconnect: bool = False+ # Set when the broker itself ends the session, overriding whatever the+ # socket then looks like from the client's side.+ self._forced_disconnect_reason: str | None = None++ def disconnect_reason(self) -> str:+ """Why this session ended, in AWS's disconnect-reason vocabulary.++ Only the three the broker can actually tell apart are ever reported: a+ DISCONNECT packet (``CLIENT_INITIATED_DISCONNECT``), a takeover by a+ second connection using the same client id (``DUPLICATE_CLIENTID``),+ and everything else — a transport that went away (``CONNECTION_LOST``).+ AWS's remaining reasons name machinery this broker does not have+ (throttling, credential expiry, keep-alive enforcement), so reporting+ one would be a guess dressed up as a fact.+ """+ if self._forced_disconnect_reason:+ return self._forced_disconnect_reason+ return (+ "CLIENT_INITIATED_DISCONNECT"+ if self._graceful_disconnect+ else "CONNECTION_LOST"+ )def _alloc_packet_id(self) -> int:pid = self._next_pid@@ -5113,11 +5275,12 @@ class _WSSession:self._will_properties = b""self._graceful_disconnect = False- await _force_disconnect_duplicate(+ self._forced_disconnect_reason = None+ takeover_reason = await _force_disconnect_duplicate(self.account_id, self.region, self._client_id)_register_client(- self.account_id, self.region, self._client_id, self+ self.account_id, self.region, self._client_id, self, takeover_reason)session_key = (self.account_id, self.region, self._client_id)@@ -5366,7 +5529,9 @@ class _WSSession:self._sub_filters.clear()self._sub_granted_qos.clear()if self._client_id:- _deregister_client(self.account_id, self.region, self._client_id)+ _deregister_client(+ self.account_id, self.region, self._client_id, self+ )def _preserve_session(self) -> None:session_key = (self.account_id, self.region, self._client_id)diff --git a/tests/test_iot.py b/tests/test_iot.pyindex 087c00a5..e498b36e 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -597,11 +597,14 @@ def test_iot_legacy_principal_policy_unknown_policy_404(iot_client):# ----------------------------------------------------------------------------def _enable_fleet_indexing(client, mode: str = "REGISTRY_AND_SHADOW") -> None:+def _enable_fleet_indexing(+ client, mode: str = "REGISTRY_AND_SHADOW", connectivity: str = "STATUS"+) -> None:"""Turn the AWS_Things index on, as every fleet stack has to on AWS."""- client.update_indexing_configuration(- thingIndexingConfiguration={"thingIndexingMode": mode}- )+ thing_cfg = {"thingIndexingMode": mode}+ if mode != "OFF":+ thing_cfg["thingConnectivityIndexingMode"] = connectivity+ client.update_indexing_configuration(thingIndexingConfiguration=thing_cfg)def _iot_client_for_fresh_account():@@ -647,9 +650,16 @@ def test_iot_indexing_configuration_round_trip():assert index["schema"] == "REGISTRY_AND_SHADOW"# Registry-only indexing narrows the schema back.- _enable_fleet_indexing(client, "REGISTRY")+ _enable_fleet_indexing(client, "REGISTRY", connectivity="OFF")assert client.describe_index(indexName="AWS_Things")["schema"] == "REGISTRY"+ # Connectivity status widens it again, the way AWS's schema strings do.+ _enable_fleet_indexing(client, "REGISTRY")+ assert (+ client.describe_index(indexName="AWS_Things")["schema"]+ == "REGISTRY_AND_CONNECTIVITY_STATUS"+ )+# ...and turning it off retires the index._enable_fleet_indexing(client, "OFF")assert client.list_indices()["indexNames"] == []@@ -712,6 +722,36 @@ def test_iot_search_index_shadow_terms_need_shadow_indexing():client.search_index(queryString="thingName:whatever")+def test_iot_search_index_connectivity_needs_connectivity_indexing():+ """The connectivity group appears only under THING_CONNECTIVITY_INDEXING.++ That is the switch AWS puts it behind, so a fleet dashboard that forgets+ it has to find out here rather than in the cloud.+ """+ client = _iot_client_for_fresh_account()+ _enable_fleet_indexing(client, connectivity="OFF")+ name = _unique("connoff")+ client.create_thing(thingName=name)+ try:+ hit = client.search_index(queryString=f"thingName:{name}")["things"][0]+ assert "connectivity" not in hit+ with pytest.raises(ClientError) as ei:+ client.search_index(queryString="connectivity.connected:true")+ assert ei.value.response["Error"]["Code"] == "InvalidQueryException"++ _enable_fleet_indexing(client)+ hit = client.search_index(queryString=f"thingName:{name}")["things"][0]+ assert hit["connectivity"] == {"connected": False}+ assert [+ t["thingName"]+ for t in client.search_index(+ queryString=f"thingName:{name} AND connectivity.connected:false"+ )["things"]+ ] == [name]+ finally:+ client.delete_thing(thingName=name)++def test_iot_search_index_registry_and_shadow(iot_client, iot_data_client):_enable_fleet_indexing(iot_client)suffix = uuid.uuid4().hex[:8]@@ -847,7 +887,7 @@ def test_iot_search_index_returns_desired_and_reported_shadow(def test_iot_search_index_unsupported_query_rejected(iot_client):_enable_fleet_indexing(iot_client)for query in (- "connectivity.connected:true",+ "connectivity.online:true", # the group is closed; this leaf is a typo"NOT thingName:foo","thingName:foo AND", # a dangling AND is an error on AWS, not a no-op"AND thingName:foo",@@ -1014,6 +1054,30 @@ def test_iot_search_index_numeric_shadow_values(iot_client, iot_data_client):iot_client.delete_thing(thingName=name)+def test_iot_search_index_thing_that_never_connected_is_disconnected(iot_client):+ _enable_fleet_indexing(iot_client)+ name = f"searchthing-{uuid.uuid4().hex[:8]}-offline"+ iot_client.create_thing(thingName=name)+ try:+ doc = iot_client.search_index(queryString=f"thingName:{name}")["things"][0]+ assert doc["connectivity"] == {"connected": False}++ found = iot_client.search_index(+ queryString=f"thingName:{name} AND connectivity.connected:false"+ )["things"]+ assert [t["thingName"] for t in found] == [name]++ # It has never disconnected either, so it matches no reason at all.+ assert (+ iot_client.search_index(+ queryString=f"thingName:{name} AND connectivity.disconnectReason:*"+ )["things"]+ == []+ )+ finally:+ iot_client.delete_thing(thingName=name)++# ---------------------------------------------------------------------------# Topic rules# ---------------------------------------------------------------------------@@ -4593,6 +4657,175 @@ def test_ddb_attribute_value_mapping():assert _ddb_attribute_value({"a": 1}) == {"S": '{"a": 1}'}assert _ddb_attribute_value([1, 2]) == {"S": "[1, 2]"}assert _ddb_attribute_value("x") == {"S": "x"}+# Fleet-index connectivity (white-box: transitions and persistence)+# ----------------------------------------------------------------------++from ministack.services.iot import ( # noqa: E402+ _thing_connectivity,+)+from ministack.services.iot import ( # noqa: E402+ get_state as _iot_get_state,+)+from ministack.services.iot import ( # noqa: E402+ restore_state as _iot_restore_state,+)++_ACCT = "123456789012"+++def _connectivity_of(client_id):+ return _thing_connectivity(_ACCT, _TEST_REGION, client_id)+++def test_connectivity_reports_connected_while_session_is_live():+ reset()++ async def _run():+ send, _sent = _mock_send()+ session = _WSSession(send, _ACCT)+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("dev-live"))+ doc = _connectivity_of("dev-live")+ assert doc["connected"] is True+ assert doc["timestamp"] > 0+ # A live session has no disconnect reason to report.+ assert "disconnectReason" not in doc+ await session.cleanup()++ asyncio.run(_run())+ reset()+++def test_connectivity_disconnect_reason_distinguishes_clean_from_dropped():+ reset()++ async def _run():+ send, _sent = _mock_send()+ clean = _WSSession(send, _ACCT)+ await clean.handle_packet(PKT_CONNECT, 0, _build_connect_body("dev-clean"))+ await clean.handle_packet(PKT_DISCONNECT, 0, b"")+ await clean.cleanup()+ doc = _connectivity_of("dev-clean")+ assert doc["connected"] is False+ assert doc["disconnectReason"] == "CLIENT_INITIATED_DISCONNECT"++ send2, _sent2 = _mock_send()+ dropped = _WSSession(send2, _ACCT)+ await dropped.handle_packet(PKT_CONNECT, 0, _build_connect_body("dev-dropped"))+ # No DISCONNECT packet: the transport simply went away.+ await dropped.cleanup()+ assert _connectivity_of("dev-dropped")["disconnectReason"] == "CONNECTION_LOST"++ asyncio.run(_run())+ reset()+++def test_connectivity_timestamp_advances_across_transitions():+ reset()++ async def _run():+ send, _sent = _mock_send()+ session = _WSSession(send, _ACCT)+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("dev-clock"))+ connected_at = _connectivity_of("dev-clock")["timestamp"]+ time.sleep(0.01)+ await session.cleanup()+ assert _connectivity_of("dev-clock")["timestamp"] > connected_at++ asyncio.run(_run())+ reset()+++def test_connectivity_survives_takeover_by_a_duplicate_client_id():+ """The loser's late second cleanup must not disconnect the live session.++ Taking over a client id cleans the old session up once from the CONNECT+ path; its socket close then drives the same session through cleanup again.+ That second pass has to be a no-op, or the thing reads as offline while a+ session is sitting there connected.+ """+ reset()++ async def _run():+ send1, _s1 = _mock_send()+ first = _WSSession(send1, _ACCT)+ await first.handle_packet(PKT_CONNECT, 0, _build_connect_body("dev-dup"))++ send2, _s2 = _mock_send()+ second = _WSSession(send2, _ACCT)+ await second.handle_packet(PKT_CONNECT, 0, _build_connect_body("dev-dup"))+ assert _connectivity_of("dev-dup")["connected"] is True++ # The evicted session's own handler finally notices and cleans up.+ await first.cleanup()+ doc = _connectivity_of("dev-dup")+ assert doc["connected"] is True+ # The takeover is the transition that produced this live session, so+ # the reason it ended the previous one survives the registration.+ assert doc["disconnectReason"] == "DUPLICATE_CLIENTID"++ await second.cleanup()+ assert _connectivity_of("dev-dup")["connected"] is False++ asyncio.run(_run())+ reset()+++def test_connectivity_reconnect_clears_the_previous_disconnect_reason():+ """An ordinary reconnect is a transition of its own, so nothing lingers.++ Only a takeover carries a reason onto the new session, because there the+ eviction *is* the connect. A device that dropped and dialled back in gets+ a clean record, not the ghost of how the last session died.+ """+ reset()++ async def _run():+ send1, _s1 = _mock_send()+ first = _WSSession(send1, _ACCT)+ await first.handle_packet(PKT_CONNECT, 0, _build_connect_body("dev-again"))+ await first.cleanup() # dropped: CONNECTION_LOST+ assert _connectivity_of("dev-again")["disconnectReason"] == "CONNECTION_LOST"++ send2, _s2 = _mock_send()+ second = _WSSession(send2, _ACCT)+ await second.handle_packet(PKT_CONNECT, 0, _build_connect_body("dev-again"))+ doc = _connectivity_of("dev-again")+ assert doc["connected"] is True+ assert "disconnectReason" not in doc+ await second.cleanup()++ 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.++ Nothing reconnects when the process comes back, so a restored ``connected:+ true`` would be a claim with no session behind it.+ """+ reset()++ async def _run():+ send, _sent = _mock_send()+ session = _WSSession(send, _ACCT)+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("dev-snap"))+ assert _connectivity_of("dev-snap")["connected"] is True++ snapshot = _iot_get_state()+ assert "connectivity" not in json.dumps(snapshot["mqtt_broker"])++ # Restart: state comes back, sessions do not.+ await session.cleanup()+ reset()+ _iot_restore_state(snapshot)+ doc = _connectivity_of("dev-snap")+ assert doc["connected"] is False+ # And nothing was invented to fill the gap.+ assert "timestamp" not in doc++ asyncio.run(_run())+ reset()# ---------------------------------------------------------------------------# CA-certificate registry + JITR (registration code, RegisterCACertificate# and friends, and the $aws/events/certificates/registered/{caId} event)diff --git a/tests/test_iot_data.py b/tests/test_iot_data.pyindex b19d8093..0833b448 100644--- a/tests/test_iot_data.py+++ b/tests/test_iot_data.py@@ -1098,6 +1098,264 @@ def test_iot_rule_sns_action_publishes_to_topic(iot_client, iot_data_client, snsiot_client.delete_topic_rule(ruleName=rule)+# ---------------------------------------------------------------------------+# Fleet-index connectivity (a live MQTT session drives connectivity.*)+# ---------------------------------------------------------------------------+++def _broker_ws_url() -> str:+ parsed = urlparse(ENDPOINT)+ return (+ f"ws://prefix-ats.iot.us-east-1.{parsed.hostname or 'localhost'}"+ f":{parsed.port or 4566}/mqtt"+ )+++def _broker_ws_url_for(account: str, region: str = "us-east-1") -> str:+ """A broker URL whose SigV4 credential scope picks account and region."""+ parsed = urlparse(ENDPOINT)+ cred = quote(f"{account}/20240101/{region}/iotdevicegateway/aws4_request")+ return (+ f"ws://prefix-ats.iot.{region}.{parsed.hostname or 'localhost'}"+ f":{parsed.port or 4566}/mqtt"+ f"?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={cred}"+ )+++async def _mqtt_connect(client_id: str, url: str | None = None):+ """Open an MQTT session and hold it. The caller closes the socket."""+ ws = await websockets.connect(url or _broker_ws_url(), subprotocols=["mqtt"])+ await ws.send(_make_connect(client_id))+ await asyncio.wait_for(ws.recv(), timeout=2.0) # CONNACK+ return ws+++async def _mqtt_disconnect(ws, graceful: bool = True):+ if graceful:+ await ws.send(bytes([0xE0, 0x00])) # DISCONNECT+ await ws.close()+++def _enable_fleet_indexing(client) -> None:+ """Fleet indexing with connectivity status on — the dashboard's config."""+ client.update_indexing_configuration(+ thingIndexingConfiguration={+ "thingIndexingMode": "REGISTRY_AND_SHADOW",+ "thingConnectivityIndexingMode": "STATUS",+ }+ )+++def _connectivity_for(iot_client, thing: str) -> dict:+ hits = iot_client.search_index(queryString=f"thingName:{thing}")["things"]+ assert len(hits) == 1, hits+ return hits[0]["connectivity"]+++def _await_connected(iot_client, thing: str, want: bool, timeout: float = 5.0):+ """Wait for the index to report the wanted state, then return the group."""+ deadline = time.time() + timeout+ doc = _connectivity_for(iot_client, thing)+ while doc["connected"] is not want and time.time() < deadline:+ time.sleep(0.05)+ doc = _connectivity_for(iot_client, thing)+ assert doc["connected"] is want, doc+ return doc+++def test_search_index_finds_connected_thing_and_loses_it_on_disconnect(iot_client):+ """`connectivity.connected:true` is the "which of my things are online" query."""+ _enable_fleet_indexing(iot_client)+ thing = _unique("conn").replace("-", "")+ iot_client.create_thing(thingName=thing)++ async def _run():+ ws = await _mqtt_connect(thing)+ try:+ connected = _await_connected(iot_client, thing, True)+ assert connected["timestamp"] > 0+ online = iot_client.search_index(+ queryString=f"thingName:{thing} AND connectivity.connected:true"+ )["things"]+ assert [t["thingName"] for t in online] == [thing]+ finally:+ await _mqtt_disconnect(ws)++ offline = _await_connected(iot_client, thing, False)+ assert offline["disconnectReason"] == "CLIENT_INITIATED_DISCONNECT"+ assert (+ iot_client.search_index(+ queryString=f"thingName:{thing} AND connectivity.connected:true"+ )["things"]+ == []+ )++ try:+ asyncio.run(_run())+ finally:+ iot_client.delete_thing(thingName=thing)+++def test_search_index_connectivity_timestamp_moves_on_disconnect(iot_client):+ _enable_fleet_indexing(iot_client)+ thing = _unique("clock").replace("-", "")+ iot_client.create_thing(thingName=thing)++ async def _run():+ ws = await _mqtt_connect(thing)+ connected_at = _await_connected(iot_client, thing, True)["timestamp"]+ time.sleep(0.05)+ await _mqtt_disconnect(ws)+ assert _await_connected(iot_client, thing, False)["timestamp"] > connected_at++ try:+ asyncio.run(_run())+ finally:+ iot_client.delete_thing(thingName=thing)+++def test_search_index_connectivity_is_tied_to_the_client_id(iot_client):+ """A session under another client id is not this thing's connectivity.++ AWS keys connectivity on the MQTT client id, so a device that connects as+ something other than the thing name leaves the thing offline — which is the+ honest answer, since nothing links the two.+ """+ _enable_fleet_indexing(iot_client)+ thing = _unique("assoc").replace("-", "")+ iot_client.create_thing(thingName=thing)++ async def _run():+ ws = await _mqtt_connect(thing + "other")+ try:+ assert _connectivity_for(iot_client, thing)["connected"] is False+ finally:+ await _mqtt_disconnect(ws)++ try:+ asyncio.run(_run())+ finally:+ iot_client.delete_thing(thingName=thing)+++def test_search_index_connectivity_reports_a_dropped_transport(iot_client):+ _enable_fleet_indexing(iot_client)+ thing = _unique("drop").replace("-", "")+ iot_client.create_thing(thingName=thing)++ async def _run():+ ws = await _mqtt_connect(thing)+ _await_connected(iot_client, thing, True)+ # Close without sending DISCONNECT: the broker only sees the socket go.+ await _mqtt_disconnect(ws, graceful=False)+ assert _await_connected(iot_client, thing, False)[+ "disconnectReason"+ ] == "CONNECTION_LOST"++ try:+ asyncio.run(_run())+ finally:+ iot_client.delete_thing(thingName=thing)+++def test_search_index_reports_duplicate_client_id_after_a_takeover(iot_client):+ """A takeover is visible in the index: the thing stays online, with the+ reason the session it replaced was evicted.++ This is the only surface DUPLICATE_CLIENTID has here, and it is the whole+ point of recording it: the eviction and the winning session's connect are+ one transition, so the reason describes how the current state came about.+ """+ _enable_fleet_indexing(iot_client)+ thing = _unique("takeover").replace("-", "")+ iot_client.create_thing(thingName=thing)++ async def _run():+ first = await _mqtt_connect(thing)+ _await_connected(iot_client, thing, True)+ second = await _mqtt_connect(thing) # same client id: a takeover+ try:+ deadline = time.time() + 5+ doc = _connectivity_for(iot_client, thing)+ while doc.get("disconnectReason") is None and time.time() < deadline:+ time.sleep(0.05)+ doc = _connectivity_for(iot_client, thing)+ assert doc["connected"] is True, doc+ assert doc["disconnectReason"] == "DUPLICATE_CLIENTID", doc++ found = iot_client.search_index(+ queryString=(+ f"thingName:{thing} AND "+ "connectivity.disconnectReason:DUPLICATE_CLIENTID"+ )+ )["things"]+ assert [t["thingName"] for t in found] == [thing]+ finally:+ try:+ await first.close() # the broker already closed it+ except Exception:+ pass+ await _mqtt_disconnect(second)++ try:+ asyncio.run(_run())+ finally:+ iot_client.delete_thing(thingName=thing)+++def test_search_index_connectivity_is_isolated_across_accounts_and_regions():+ """A session in another account or region is not this thing's connectivity.++ The broker keys sessions by (account, region, client id); the index has to+ read the same key, or a device connecting in eu-west-1 would light up a+ same-named thing in us-east-1.+ """+ import boto3+ from botocore.config import Config++ account = f"{uuid.uuid4().int % 10**12:012d}"+ other_account = f"{uuid.uuid4().int % 10**12:012d}"++ def _client(account_id, region="us-east-1"):+ return boto3.client(+ "iot",+ endpoint_url=ENDPOINT,+ aws_access_key_id=account_id,+ aws_secret_access_key="test",+ region_name=region,+ config=Config(retries={"mode": "standard"}),+ )++ owner = _client(account)+ owner_eu = _client(account, "eu-west-1")+ for client in (owner, owner_eu):+ _enable_fleet_indexing(client)++ thing = _unique("iso").replace("-", "")+ owner.create_thing(thingName=thing)+ owner_eu.create_thing(thingName=thing)++ async def _run():+ # Same client id, different account: the owner's thing stays offline.+ ws = await _mqtt_connect(thing, _broker_ws_url_for(other_account))+ try:+ assert _connectivity_for(owner, thing)["connected"] is False+ finally:+ await _mqtt_disconnect(ws)++ # Same account, different region: still not this thing.+ ws = await _mqtt_connect(thing, _broker_ws_url_for(account, "eu-west-1"))+ try:+ assert _await_connected(owner_eu, thing, True)["connected"] is True+ assert _connectivity_for(owner, thing)["connected"] is False+ finally:+ await _mqtt_disconnect(ws)++ try:+ asyncio.run(_run())+ finally:+ owner.delete_thing(thingName=thing)+ owner_eu.delete_thing(thingName=thing)def test_iot_jitr_registration_event_drives_a_topic_rule(iot_client, lam, sqs):"""The JITR lifecycle event is a real broker publish, so a topic rule on``$aws/events/certificates/registered/{caId}`` hands it to a Lambda — the