Skip to content

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

feat(iot): publish registry events; fix removeThingType in UpdateThing and DeleteThingGroup with child groups (#1903)

iot-rocket51f8a80a32d8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a0c000e2..f68feabd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
+- **IoT — registry events** — with a type enabled through `UpdateEventConfigurations`, the thing, thing type, thing type association, thing group, thing group hierarchy and thing group membership operations publish the AWS payload to `$aws/events/...`, where MQTT subscribers and topic rules receive it.
- **CloudFormation — `AWS::Lambda::Version` updates `FunctionScalingConfig` in place** — a stack update re-ran the create, which published a new version for every change; a `FunctionScalingConfig` change now keeps the version, also when the update rolls back. Contributed by @iot-rocket.
### Fixed
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index db40ede9..8ff360eb 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -11278,7 +11278,9 @@ def _iot_thing_group_update(physical_id, old_props, new_props, stack_name, logic
def _iot_thing_group_delete(physical_id, props):
rec = _iot_thing_group_record(physical_id)
if rec is not None:
- _iot._delete_thing_group(rec["thingGroupName"])
+ resp = _iot._delete_thing_group(rec["thingGroupName"])
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::IoT::ThingGroup delete failed: {resp[2]!r}")
def _iot_policy_document(props):
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 447f9c2b..7410c240 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -461,6 +461,21 @@ def _qp_bool(qp: dict, name: str, default: bool = False) -> bool:
async def handle_request(
method: str, path: str, headers: dict, body: bytes, query_params: dict
+) -> tuple:
+ """Route an IoT control-plane request, then publish the registry events it raised."""
+ events: list = []
+ token = _pending_events.set(events)
+ try:
+ response = await _route_request(method, path, headers, body, query_params)
+ finally:
+ _pending_events.reset(token)
+ for account_id, region, topic, event in events:
+ await _publish_event(account_id, region, topic, event)
+ return response
+
+
+async def _route_request(
+ method: str, path: str, headers: dict, body: bytes, query_params: dict
) -> tuple:
"""Route an IoT control-plane request to the appropriate handler.
@@ -739,6 +754,7 @@ def _create_thing(name: str, payload: dict) -> tuple:
"thingGroupNames": [],
}
_things[name] = record
+ _thing_events("CREATED", record, None)
logger.info("IoT Thing created: %s", name)
return json_response({
"thingName": name,
@@ -804,10 +820,11 @@ def _update_thing(name: str, payload: dict) -> tuple:
else:
merged[k] = v
thing["attributes"] = merged
- else:
+ elif "attributePayload" in payload:
thing["attributes"] = dict(new_attrs)
- new_type = payload.get("thingTypeName")
+ old_type = thing.get("thingTypeName")
+ new_type = "" if payload.get("removeThingType") else payload.get("thingTypeName")
if new_type is not None:
if new_type and new_type not in _thing_types:
return _error_not_found("ThingType", new_type)
@@ -815,6 +832,7 @@ def _update_thing(name: str, payload: dict) -> tuple:
thing["version"] = thing.get("version", 1) + 1
_things[name] = thing
+ _thing_events("UPDATED", thing, old_type)
return json_response({})
@@ -828,12 +846,14 @@ def _delete_thing(name: str) -> tuple:
if thing_arn in cert.get("attachedThings", []):
cert["attachedThings"].remove(thing_arn)
_certificates[cert_id] = cert
+ _thing_events("DELETED", thing, thing.get("thingTypeName"))
# Remove from groups
for gname in list(thing.get("thingGroupNames", [])):
group = _thing_groups.get(gname)
if group and name in group.get("things", []):
group["things"].remove(name)
_thing_groups[gname] = group
+ _membership_event("REMOVED", group, thing)
# Drop the thing's job executions with it. Left behind, a live execution
# for a thing that no longer exists holds its job out of COMPLETED forever,
# and a later thing of the same name would inherit that stale history.
@@ -937,6 +957,7 @@ def _create_thing_type(name: str, payload: dict) -> tuple:
},
}
_thing_types[name] = record
+ _thing_type_event("CREATED", record)
logger.info("IoT Thing Type created: %s", name)
return json_response({
"thingTypeName": name,
@@ -964,6 +985,7 @@ def _deprecate_thing_type(name: str, payload: dict) -> tuple:
t["thingTypeMetadata"]["deprecated"] = not undo
t["thingTypeMetadata"]["deprecationDate"] = None if undo else _now_epoch()
_thing_types[name] = t
+ _thing_type_event("UPDATED", t)
return json_response({})
@@ -978,6 +1000,7 @@ def _delete_thing_type(name: str) -> tuple:
400,
)
del _thing_types[name]
+ _thing_type_event("DELETED", t)
return json_response({})
@@ -1041,6 +1064,9 @@ def _create_thing_group(name: str, payload: dict) -> tuple:
"creationDate": record["creationDate"],
}
_thing_groups[name] = record
+ _thing_group_event("CREATED", record)
+ if parent:
+ _hierarchy_event("ADDED", _thing_groups[parent], record)
return json_response({
"thingGroupName": name,
"thingGroupArn": record["thingGroupArn"],
@@ -1119,6 +1145,7 @@ def _update_thing_group(name: str, payload: dict) -> tuple:
}
g["version"] = g.get("version", 1) + 1
_thing_groups[name] = g
+ _thing_group_event("UPDATED", g)
return json_response({"version": g["version"]})
@@ -1126,12 +1153,22 @@ def _delete_thing_group(name: str) -> tuple:
g = _thing_groups.get(name)
if g is None:
return _error_not_found("ThingGroup", name)
+ if any((c.get("thingGroupMetadata") or {}).get("parentGroupName") == name for c in _thing_groups.values()):
+ return error_response_json(
+ "InvalidRequestException",
+ f"Cannot delete thing group : {name} when there are still child groups attached to it", 400,
+ )
# Remove group from any Things that referenced it
for tname in list(g.get("things", [])):
thing = _things.get(tname)
if thing and name in thing.get("thingGroupNames", []):
thing["thingGroupNames"].remove(name)
_things[tname] = thing
+ _membership_event("REMOVED", g, thing)
+ _thing_group_event("DELETED", g)
+ parent = _thing_groups.get((g.get("thingGroupMetadata") or {}).get("parentGroupName") or "")
+ if parent:
+ _hierarchy_event("REMOVED", parent, g)
del _thing_groups[name]
return json_response({})
@@ -1152,6 +1189,7 @@ def _add_thing_to_group(payload: dict) -> tuple:
if tname not in group.get("things", []):
group.setdefault("things", []).append(tname)
_thing_groups[gname] = group
+ _membership_event("ADDED", group, thing)
if gname not in thing.get("thingGroupNames", []):
thing.setdefault("thingGroupNames", []).append(gname)
_things[tname] = thing
@@ -1170,6 +1208,7 @@ def _remove_thing_from_group(payload: dict) -> tuple:
if tname in group.get("things", []):
group["things"].remove(tname)
_thing_groups[gname] = group
+ _membership_event("REMOVED", group, thing)
if gname in thing.get("thingGroupNames", []):
thing["thingGroupNames"].remove(gname)
_things[tname] = thing
@@ -1414,21 +1453,9 @@ async def _publish_certificate_registered(
"certificateRegistrationTimestamp": registration_timestamp,
"sourceIp": source_ip,
}
- try:
- await broker_publish(
- account_id,
- region,
- f"$aws/events/certificates/registered/{ca_id}",
- json.dumps(event).encode("utf-8"),
- qos=0,
- )
- except Exception:
- # The certificate is already registered at this point, so a broker
- # failure must not undo it; the iot-data publish path guards the same
- # call the same way.
- logger.warning(
- "JITR registered-event publish failed for CA %s", ca_id, exc_info=True
- )
+ await _publish_event(
+ account_id, region, f"$aws/events/certificates/registered/{ca_id}", event
+ )
def _create_keys_and_certificate(qp: dict) -> tuple:
@@ -2862,6 +2889,135 @@ def _update_event_configurations(payload: dict) -> tuple:
return json_response({})
+# Registry events raised while handling a request, published once the handler returns.
+_pending_events: contextvars.ContextVar[list | None] = contextvars.ContextVar(
+ "iot_pending_events", default=None
+)
+
+
+async def _publish_event(account_id: str, region: str, topic: str, event: dict) -> None:
+ """Publish an ``$aws/events`` message; a broker failure never undoes the operation behind it."""
+ try:
+ await broker_publish(
+ account_id, region, topic, json.dumps(event).encode("utf-8"), qos=0
+ )
+ except Exception:
+ logger.warning("IoT event publish failed on %s", topic, exc_info=True)
+
+
+def _registry_event(
+ config_type: str, topic: str, event_type: str, operation: str, fields: dict,
+ event_id: str | None = None,
+) -> None:
+ """Queue ``$aws/events/{topic}`` when ``config_type`` is enabled for the request's account and region."""
+ pending = _pending_events.get()
+ enabled = (_event_config.get(_EVENT_CONFIG_KEY) or {}).get("enabled", ())
+ if pending is None or config_type not in enabled:
+ return
+ pending.append((get_account_id(), get_region(), f"$aws/events/{topic}", {
+ "eventType": event_type,
+ "eventId": event_id or uuid.uuid4().hex,
+ "timestamp": int(time.time() * 1000),
+ "operation": operation,
+ "accountId": get_account_id(),
+ **fields,
+ }))
+
+
+def _thing_events(operation: str, thing: dict, old_type: str | None) -> None:
+ """THING event plus the type association changes, which share its eventId."""
+ event_id = uuid.uuid4().hex
+ name = thing["thingName"]
+ _registry_event("THING", f"thing/{name}/{operation.lower()}", "THING_EVENT", operation, {
+ "thingId": thing["thingId"],
+ "thingName": name,
+ "versionNumber": thing.get("version", 1),
+ "thingTypeName": thing.get("thingTypeName"),
+ "billinGroupName": None,
+ "attributes": dict(thing.get("attributes") or {}),
+ }, event_id)
+ new_type = None if operation == "DELETED" else thing.get("thingTypeName")
+ if old_type == new_type:
+ return
+ for type_name, change in ((new_type, "ADDED"), (old_type, "REMOVED")):
+ if type_name:
+ _registry_event(
+ "THING_TYPE_ASSOCIATION",
+ f"thingTypeAssociation/thing/{name}/thingType/{type_name}/{change.lower()}",
+ "THING_TYPE_ASSOCIATION_EVENT", change,
+ {"thingId": thing["thingId"], "thingName": name, "thingTypeName": type_name},
+ event_id,
+ )
+
+
+def _thing_type_event(operation: str, thing_type: dict) -> None:
+ props = thing_type.get("thingTypeProperties") or {}
+ meta = thing_type.get("thingTypeMetadata") or {}
+ deprecated_at = meta.get("deprecationDate")
+ name = thing_type["thingTypeName"]
+ _registry_event("THING_TYPE", f"thingType/{name}/{operation.lower()}", "THING_TYPE_EVENT", operation, {
+ "thingTypeId": thing_type["thingTypeId"],
+ "thingTypeName": name,
+ "isDeprecated": bool(meta.get("deprecated")),
+ "deprecationDate": int(deprecated_at * 1000) if deprecated_at else None,
+ "searchableAttributes": props.get("searchableAttributes") or None,
+ "propagatingAttributes": (props.get("mqtt5Configuration") or {}).get("propagatingAttributes") or None,
+ "description": props.get("thingTypeDescription"),
+ })
+
+
+def _thing_group_event(operation: str, group: dict) -> None:
+ props = group.get("thingGroupProperties") or {}
+ parent_name = (group.get("thingGroupMetadata") or {}).get("parentGroupName")
+ ancestors = []
+ ancestor = _thing_groups.get(parent_name) if parent_name else None
+ while ancestor:
+ ancestors.insert(0, {"groupArn": ancestor["thingGroupArn"], "groupId": ancestor["thingGroupId"]})
+ up = (ancestor.get("thingGroupMetadata") or {}).get("parentGroupName")
+ ancestor = _thing_groups.get(up) if up else None
+ name = group["thingGroupName"]
+ _registry_event("THING_GROUP", f"thingGroup/{name}/{operation.lower()}", "THING_GROUP_EVENT", operation, {
+ "thingGroupId": group["thingGroupId"],
+ "thingGroupName": name,
+ "versionNumber": group.get("version", 1),
+ "parentGroupName": parent_name,
+ "parentGroupId": ancestors[-1]["groupId"] if ancestors else None,
+ "description": props.get("thingGroupDescription"),
+ "rootToParentThingGroups": ancestors or None,
+ "attributes": (props.get("attributePayload") or {}).get("attributes") or None,
+ "dynamicGroupMappingId": None,
+ })
+
+
+def _hierarchy_event(operation: str, parent: dict, child: dict) -> None:
+ _registry_event(
+ "THING_GROUP_HIERARCHY",
+ f"thingGroupHierarchy/thingGroup/{parent['thingGroupName']}"
+ f"/childThingGroup/{child['thingGroupName']}/{operation.lower()}",
+ "THING_GROUP_HIERARCHY_EVENT", operation, {
+ "thingGroupId": parent["thingGroupId"],
+ "thingGroupName": parent["thingGroupName"],
+ "childGroupId": child["thingGroupId"],
+ "childGroupName": child["thingGroupName"],
+ },
+ )
+
+
+def _membership_event(operation: str, group: dict, thing: dict) -> None:
+ _registry_event(
+ "THING_GROUP_MEMBERSHIP",
+ f"thingGroupMembership/thingGroup/{group['thingGroupName']}"
+ f"/thing/{thing['thingName']}/{operation.lower()}",
+ "THING_GROUP_MEMBERSHIP_EVENT", operation, {
+ "groupArn": group["thingGroupArn"],
+ "groupId": group["thingGroupId"],
+ "thingArn": thing["thingArn"],
+ "thingId": thing["thingId"],
+ "membershipId": str(uuid.uuid5(uuid.NAMESPACE_URL, f"{group['thingGroupId']}/{thing['thingId']}")),
+ },
+ )
+
+
# ---------------------------------------------------------------------------
# Topic rules
# ---------------------------------------------------------------------------
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index c6f4fe5b..879678bd 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -23868,6 +23868,40 @@ def test_cfn_iot_thing_group_rename_replaces_and_parent_change_is_refused(cfn, i
_delete_cfn_test_stack(cfn, stack_name)
+def test_cfn_iot_thing_group_delete_with_child_group_fails(cfn, iot_client):
+ """A stack whose thing group still has a child group created outside the
+ stack lands in DELETE_FAILED with the service message and keeps the group;
+ once the child is gone a retried delete removes it."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-tg-held-{uid}"
+ parent, child = f"cfn-tg-held-p-{uid}", f"cfn-tg-held-c-{uid}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps({"Resources": {
+ "Parent": {"Type": "AWS::IoT::ThingGroup", "Properties": {"ThingGroupName": parent}}}}))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ iot_client.create_thing_group(thingGroupName=child, parentGroupName=parent)
+ cfn.delete_stack(StackName=stack_name)
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "DELETE_FAILED"
+ assert stack["StackStatusReason"] == "The following resource(s) failed to delete: [Parent]."
+ assert (f"Cannot delete thing group : {parent} when there are still child groups attached to it"
+ in _stack_event_reasons(cfn, stack_name))
+ iot_client.describe_thing_group(thingGroupName=parent)
+
+ iot_client.delete_thing_group(thingGroupName=child)
+ cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
+ with pytest.raises(ClientError) as exc:
+ iot_client.describe_thing_group(thingGroupName=parent)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ finally:
+ try:
+ iot_client.delete_thing_group(thingGroupName=child)
+ except ClientError:
+ pass
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
def test_cfn_apigateway_authorizer_update_in_place_and_replacement(cfn, apigw_v1):
"""An authorizer property change updates the authorizer under the same id
(Ref and AuthorizerId keep their value), a property the template drops
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 929999f6..f77211ca 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -8,6 +8,7 @@ iot-data Publish) is covered separately in ``test_iot_data.py``.
import base64
import json
import logging
+import re
import time
import uuid
@@ -140,6 +141,24 @@ def test_iot_update_thing_increments_version(iot_client):
iot_client.delete_thing(thingName=name)
+def test_iot_update_thing_remove_thing_type_keeps_attributes(iot_client):
+ type_name = _unique("type")
+ name = _unique("thing")
+ iot_client.create_thing_type(thingTypeName=type_name)
+ iot_client.create_thing(
+ thingName=name, thingTypeName=type_name,
+ attributePayload={"attributes": {"k": "v"}},
+ )
+ iot_client.update_thing(thingName=name, removeThingType=True)
+ desc = iot_client.describe_thing(thingName=name)
+ assert desc.get("thingTypeName") is None
+ assert desc["attributes"] == {"k": "v"}
+ assert desc["version"] == 2
+ iot_client.delete_thing(thingName=name)
+ iot_client.deprecate_thing_type(thingTypeName=type_name)
+ iot_client.delete_thing_type(thingTypeName=type_name)
+
+
def test_iot_list_things_filter_by_attribute(iot_client):
a = _unique("thing")
b = _unique("thing")
@@ -286,6 +305,22 @@ def test_iot_delete_thing_type_active_rejected(iot_client):
# ---------------------------------------------------------------------------
+def test_iot_delete_thing_group_with_child_groups_is_refused(iot_client):
+ parent, child = _unique("parent"), _unique("child")
+ iot_client.create_thing_group(thingGroupName=parent)
+ iot_client.create_thing_group(thingGroupName=child, parentGroupName=parent)
+ with pytest.raises(ClientError) as ei:
+ iot_client.delete_thing_group(thingGroupName=parent)
+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"
+ assert ei.value.response["Error"]["Message"] == (
+ f"Cannot delete thing group : {parent} when there are still child groups attached to it"
+ )
+ assert iot_client.describe_thing_group(thingGroupName=child)["thingGroupMetadata"][
+ "parentGroupName"] == parent
+ iot_client.delete_thing_group(thingGroupName=child)
+ iot_client.delete_thing_group(thingGroupName=parent)
+
+
def test_iot_thing_group_membership(iot_client):
gname = _unique("group")
tname = _unique("thing")
@@ -5612,6 +5647,245 @@ def test_iot_jitr_auto_registration_on_connect(monkeypatch):
assert second["certificateRegistrationTimestamp"] == str(int(record["creationDate"] * 1000))
+# ----------------------------------------------------------------------
+# Registry events ($aws/events/...) gated by UpdateEventConfigurations
+# ----------------------------------------------------------------------
+
+_EVENTS_ACCOUNT = "123456789012"
+
+
+def _registry_events(calls, enable=_EVENT_TYPES) -> list:
+ """Run ``calls`` in-process with ``enable`` on and return the ``$aws/events`` messages."""
+ from ministack.core.responses import set_request_account_id, set_request_region
+ from ministack.services import iot as iot_module
+
+ received: list = []
+
+ async def _collect(topic, payload, qos):
+ received.append((topic, json.loads(payload)))
+
+ async def _call(method, path, body=None):
+ status, _, resp = await iot_module.handle_request(
+ method, path, {}, json.dumps(body or {}).encode(), {}
+ )
+ assert status == 200, resp
+ return json.loads(resp or b"{}")
+
+ async def _run():
+ set_request_account_id(_EVENTS_ACCOUNT)
+ set_request_region(_TEST_REGION)
+ await iot_module.broker_subscribe(
+ _EVENTS_ACCOUNT, _TEST_REGION, "$aws/events/#", _collect
+ )
+ await _call("PATCH", "/event-configurations", {
+ "eventConfigurations": {t: {"Enabled": True} for t in enable}
+ })
+ await calls(_call)
+
+ try:
+ asyncio.run(_run())
+ finally:
+ iot_module.reset()
+ iot_module.broker_reset()
+ for _topic, event in received:
+ assert re.fullmatch(r"[0-9a-f]{32}", event["eventId"])
+ assert isinstance(event.pop("timestamp"), int)
+ assert event.pop("accountId") == _EVENTS_ACCOUNT
+ return received
+
+
+def test_iot_registry_events_follow_the_event_configuration():
+ async def calls(call):
+ await call("POST", "/things/ev-thing")
+ await call("POST", "/thing-groups/ev-group")
+ await call("PUT", "/thing-groups/addThingToThingGroup",
+ {"thingGroupName": "ev-group", "thingName": "ev-thing"})
+
+ assert _registry_events(calls, enable=()) == []
+ assert [t for t, _e in _registry_events(calls, enable=("THING_GROUP",))] == [
+ "$aws/events/thingGroup/ev-group/created",
+ ]
+
+
+def test_iot_thing_events_and_type_associations():
+ ids = {}
+
+ async def calls(call):
+ for type_name in ("ev-type-a", "ev-type-b"):
+ await call("POST", f"/thing-types/{type_name}")
+ ids["thing"] = (await call("POST", "/things/ev-thing", {
+ "thingTypeName": "ev-type-a", "attributePayload": {"attributes": {"a": "1"}},
+ }))["thingId"]
+ await call("PATCH", "/things/ev-thing", {
+ "thingTypeName": "ev-type-b",
+ "attributePayload": {"attributes": {"b": "2"}, "merge": True},
+ })
+ await call("PATCH", "/things/ev-thing", {"removeThingType": True})
+ await call("DELETE", "/things/ev-thing")
+
+ events = _registry_events(calls, enable=("THING", "THING_TYPE_ASSOCIATION"))
+ base = "$aws/events/thing/ev-thing"
+ assoc = "$aws/events/thingTypeAssociation/thing/ev-thing/thingType"
+ assert [t for t, _e in events] == [
+ f"{base}/created", f"{assoc}/ev-type-a/added",
+ f"{base}/updated", f"{assoc}/ev-type-b/added", f"{assoc}/ev-type-a/removed",
+ f"{base}/updated", f"{assoc}/ev-type-b/removed",
+ f"{base}/deleted",
+ ]
+ # One operation's thing and association events share an eventId.
+ assert len({e.pop("eventId") for _t, e in events[:2]}) == 1
+ assert len({e.pop("eventId") for _t, e in events[2:5]}) == 1
+ assert len({e.pop("eventId") for _t, e in events[5:7]}) == 1
+ thing = {"eventType": "THING_EVENT", "thingId": ids["thing"],
+ "thingName": "ev-thing", "billinGroupName": None}
+ assert events[0][1] == {**thing, "operation": "CREATED", "versionNumber": 1,
+ "thingTypeName": "ev-type-a", "attributes": {"a": "1"}}
+ assert events[2][1] == {**thing, "operation": "UPDATED", "versionNumber": 2,
+ "thingTypeName": "ev-type-b",
+ "attributes": {"a": "1", "b": "2"}}
+ assert events[5][1] == {**thing, "operation": "UPDATED", "versionNumber": 3,
+ "thingTypeName": None,
+ "attributes": {"a": "1", "b": "2"}}
+ events[7][1].pop("eventId")
+ assert events[7][1] == {**thing, "operation": "DELETED", "versionNumber": 3,
+ "thingTypeName": None,
+ "attributes": {"a": "1", "b": "2"}}
+ assert events[4][1] == {
+ "eventType": "THING_TYPE_ASSOCIATION_EVENT", "operation": "REMOVED",
+ "thingId": ids["thing"], "thingName": "ev-thing", "thingTypeName": "ev-type-a",
+ }
+
+
+def test_iot_thing_type_events():
+ ids = {}
+
+ async def calls(call):
+ ids["type"] = (await call("POST", "/thing-types/ev-type", {"thingTypeProperties": {
+ "thingTypeDescription": "d1", "searchableAttributes": ["a"],
+ }}))["thingTypeId"]
+ await call("POST", "/thing-types/ev-type/deprecate", {})
+ await call("POST", "/thing-types/ev-type/deprecate", {"undoDeprecate": True})
+ await call("POST", "/thing-types/ev-type/deprecate", {})
+ await call("DELETE", "/thing-types/ev-type")
+ await call("POST", "/thing-types/ev-bare")
+
+ events = _registry_events(calls, enable=("THING_TYPE",))
+ base = "$aws/events/thingType"
+ assert [t for t, _e in events] == [
+ f"{base}/ev-type/created", f"{base}/ev-type/updated", f"{base}/ev-type/updated",
+ f"{base}/ev-type/updated", f"{base}/ev-type/deleted", f"{base}/ev-bare/created",
+ ]
+ for _t, e in events:
+ e.pop("eventId")
+ deprecated_at = events[1][1].pop("deprecationDate")
+ assert isinstance(deprecated_at, int)
+ thing_type = {"eventType": "THING_TYPE_EVENT", "thingTypeId": ids["type"],
+ "thingTypeName": "ev-type", "searchableAttributes": ["a"],
+ "propagatingAttributes": None, "description": "d1"}
+ assert events[0][1] == {**thing_type, "operation": "CREATED",
+ "isDeprecated": False, "deprecationDate": None}
+ assert events[1][1] == {**thing_type, "operation": "UPDATED", "isDeprecated": True}
+ assert events[2][1] == {**thing_type, "operation": "UPDATED",
+ "isDeprecated": False, "deprecationDate": None}
+ assert events[4][1]["operation"] == "DELETED"
+ assert events[4][1]["isDeprecated"] is True
+ bare = events[5][1]
+ assert (bare["searchableAttributes"], bare["description"]) == (None, None)
+
+
+def test_iot_thing_group_hierarchy_and_membership_events():
+ ids = {}
+
+ async def calls(call):
+ ids["parent"] = (await call("POST", "/thing-groups/ev-parent", {"thingGroupProperties": {
+ "thingGroupDescription": "gd", "attributePayload": {"attributes": {"k": "v"}},
+ }}))["thingGroupId"]
+ ids["child"] = (await call("POST", "/thing-groups/ev-child",
+ {"parentGroupName": "ev-parent"}))["thingGroupId"]
+ ids["thing"] = (await call("POST", "/things/ev-thing"))["thingId"]
+ for _ in range(2):
+ await call("PUT", "/thing-groups/addThingToThingGroup",
+ {"thingGroupName": "ev-child", "thingName": "ev-thing"})
+ await call("PUT", "/thing-groups/removeThingFromThingGroup",
+ {"thingGroupName": "ev-child", "thingName": "ev-thing"})
+ await call("PATCH", "/thing-groups/ev-parent",
+ {"thingGroupProperties": {"thingGroupDescription": "gd2"}})
+ await call("DELETE", "/thing-groups/ev-child")
+ await call("PUT", "/thing-groups/addThingToThingGroup",
+ {"thingGroupName": "ev-parent", "thingName": "ev-thing"})
+ await call("DELETE", "/thing-groups/ev-parent")
+
+ events = _registry_events(
+ calls, enable=("THING_GROUP", "THING_GROUP_HIERARCHY", "THING_GROUP_MEMBERSHIP")
+ )
+ group = "$aws/events/thingGroup"
+ hierarchy = "$aws/events/thingGroupHierarchy/thingGroup/ev-parent/childThingGroup/ev-child"
+ member = "$aws/events/thingGroupMembership/thingGroup"
+ assert [t for t, _e in events] == [
+ f"{group}/ev-parent/created",
+ f"{group}/ev-child/created", f"{hierarchy}/added",
+ f"{member}/ev-child/thing/ev-thing/added",
+ f"{member}/ev-child/thing/ev-thing/removed",
+ f"{group}/ev-parent/updated",
+ f"{group}/ev-child/deleted", f"{hierarchy}/removed",
+ f"{member}/ev-parent/thing/ev-thing/added",
+ f"{member}/ev-parent/thing/ev-thing/removed",
+ f"{group}/ev-parent/deleted",
+ ]
+ for _t, e in events:
+ e.pop("eventId")
+ arn = f"arn:aws:iot:{_TEST_REGION}:{_EVENTS_ACCOUNT}"
+ parent = {"eventType": "THING_GROUP_EVENT", "thingGroupId": ids["parent"],
+ "thingGroupName": "ev-parent", "parentGroupName": None,
+ "parentGroupId": None, "rootToParentThingGroups": None,
+ "attributes": {"k": "v"}, "dynamicGroupMappingId": None}
+ assert events[0][1] == {**parent, "operation": "CREATED", "versionNumber": 1,
+ "description": "gd"}
+ assert events[5][1] == {**parent, "operation": "UPDATED", "versionNumber": 2,
+ "description": "gd2"}
+ assert events[1][1] == {
+ "eventType": "THING_GROUP_EVENT", "operation": "CREATED",
+ "thingGroupId": ids["child"], "thingGroupName": "ev-child", "versionNumber": 1,
+ "parentGroupName": "ev-parent", "parentGroupId": ids["parent"],
+ "description": None,
+ "rootToParentThingGroups": [
+ {"groupArn": f"{arn}:thinggroup/ev-parent", "groupId": ids["parent"]},
+ ],
+ "attributes": None, "dynamicGroupMappingId": None,
+ }
+ assert events[2][1] == {
+ "eventType": "THING_GROUP_HIERARCHY_EVENT", "operation": "ADDED",
+ "thingGroupId": ids["parent"], "thingGroupName": "ev-parent",
+ "childGroupId": ids["child"], "childGroupName": "ev-child",
+ }
+ added, removed = events[3][1], events[4][1]
+ assert added == {
+ "eventType": "THING_GROUP_MEMBERSHIP_EVENT", "operation": "ADDED",
+ "groupArn": f"{arn}:thinggroup/ev-child", "groupId": ids["child"],
+ "thingArn": f"{arn}:thing/ev-thing", "thingId": ids["thing"],
+ "membershipId": removed["membershipId"],
+ }
+ assert removed["operation"] == "REMOVED"
+ assert events[9][1]["membershipId"] != added["membershipId"]
+
+
+def test_iot_deleting_a_thing_announces_its_group_memberships():
+ async def calls(call):
+ await call("POST", "/things/ev-thing")
+ await call("POST", "/thing-groups/ev-group")
+ await call("PUT", "/thing-groups/addThingToThingGroup",
+ {"thingGroupName": "ev-group", "thingName": "ev-thing"})
+ await call("DELETE", "/things/ev-thing")
+
+ events = _registry_events(calls, enable=("THING", "THING_GROUP_MEMBERSHIP"))
+ assert [t for t, _e in events] == [
+ "$aws/events/thing/ev-thing/created",
+ "$aws/events/thingGroupMembership/thingGroup/ev-group/thing/ev-thing/added",
+ "$aws/events/thing/ev-thing/deleted",
+ "$aws/events/thingGroupMembership/thingGroup/ev-group/thing/ev-thing/removed",
+ ]
+
+
# ----------------------------------------------------------------------
# Shadow-over-MQTT bridge (white-box).
# ----------------------------------------------------------------------