Skip to content

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

feat(iot): publish job and job execution events (#2116)

iot-rocket88e15fc336e9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a7c00604..b4d38c59 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added
+- **IoT — job and job execution events** — completed, canceled and deleted jobs and finished, removed or deleted executions publish to `$aws/events/job/...` and `$aws/events/jobExecution/...` when `UpdateEventConfigurations` enables them. Contributed by @iot-rocket.
- **IoT — `UpdateJob`** — `PATCH /jobs/{jobId}` updates an `IN_PROGRESS` job's description, presigned URL, rollout, abort, timeout and retry configuration with AWS's checks; running executions keep their timeout. `CreateJob` refuses a bad timeout with the same message. Contributed by @iot-rocket.
- **Signer — real signatures on the IoT platform** — when ACM holds the key of the profile's certificate, `StartSigningJob` on `AWSIoTDeviceManagement-SHA256-ECDSA` writes AWS's signed document instead of a JSON receipt, and an RSA key fails the job. Without a key the receipt stays and a warning is logged. Contributed by @iot-rocket.
### Fixed
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index b55f7514..f8b02a2e 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -66,6 +66,7 @@ from __future__ import annotations
import asyncio
import base64
+import contextlib
import contextvars
import copy
import hashlib
@@ -484,15 +485,8 @@ 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 with publishing_events():
+ return await _route_request(method, path, headers, body, query_params)
async def _route_request(
@@ -3685,16 +3679,33 @@ async def _publish_event(account_id: str, region: str, topic: str, event: dict)
logger.warning("IoT event publish failed on %s", topic, exc_info=True)
+async def publishing_events():
+ """Collect the ``$aws/events`` messages raised inside the block and publish them after it."""
+ events: list = []
+ token = _pending_events.set(events)
+ try:
+ yield
+ finally:
+ _pending_events.reset(token)
+ for account_id, region, topic, event in events:
+ await _publish_event(account_id, region, topic, event)
+
+
+def _event_wanted(config_type: str) -> bool:
+ """Whether events are being collected and ``config_type`` is enabled for the account and region."""
+ enabled = (_event_config.get(_EVENT_CONFIG_KEY) or {}).get("enabled", ())
+ return _pending_events.get() is not None and config_type in enabled
+
+
def _registry_event(
config_type: str, topic: str, event_type: str, operation: str, fields: dict,
event_id: str | None = None, with_account: bool = True,
) -> 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:
+ if not _event_wanted(config_type):
return
- pending.append((get_account_id(), get_region(), f"$aws/events/{topic}", {
+ _pending_events.get().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),
@@ -5034,6 +5045,7 @@ def _jobs_thing_left_group(thing: str) -> bool:
continue
execution["status"] = "REMOVED"
execution["lastUpdatedAt"] = now
+ _job_execution_event(execution)
removed = True
return removed
@@ -5043,6 +5055,75 @@ def _jobs_with_history(execution: dict) -> list[dict]:
return [execution, *execution.get("history", [])]
+def _jobs_status_counts(job_id: str) -> dict:
+ """Executions of a job per status, a rejoined thing's earlier ones included."""
+ counts = {status: 0 for status in _JOB_EXECUTION_STATUSES}
+ for latest in _job_executions.values():
+ if latest["jobId"] == job_id:
+ for execution in _jobs_with_history(latest):
+ counts[execution["status"]] += 1
+ return counts
+
+
+def _job_event(job: dict, operation: str) -> None:
+ """Queue ``$aws/events/job/{jobId}/{operation}``; completed and canceled carry the execution counts."""
+ if not _event_wanted("JOB"):
+ return
+ fields = {
+ "jobId": job["jobId"],
+ "status": operation.upper(),
+ "targetSelection": job["targetSelection"],
+ "targets": list(job.get("targets") or []),
+ "createdAt": job["createdAt"],
+ "lastUpdatedAt": job["lastUpdatedAt"],
+ "timestamp": int(time.time()),
+ }
+ if job.get("description") is not None:
+ fields["description"] = job["description"]
+ if operation == "completed":
+ fields["completedAt"] = job["completedAt"]
+ if operation in ("cancellation_in_progress", "canceled"):
+ fields["forceCanceled"] = bool(job.get("forceCanceled"))
+ for member in ("comment", "reasonCode"):
+ if job.get(member) is not None:
+ fields[member] = job[member]
+ if operation in ("completed", "canceled"):
+ counts = _jobs_status_counts(job["jobId"])
+ fields["jobProcessDetails"] = {
+ f"numberOf{name}Things": counts[status]
+ for name, status in (
+ ("Canceled", "CANCELED"), ("Rejected", "REJECTED"), ("Failed", "FAILED"),
+ ("Removed", "REMOVED"), ("Succeeded", "SUCCEEDED"), ("TimedOut", "TIMED_OUT"),
+ )
+ }
+ _registry_event(
+ "JOB", f"job/{job['jobId']}/{operation}", "JOB", operation, fields,
+ str(uuid.uuid4()), with_account=False,
+ )
+
+
+def _job_execution_event(
+ execution: dict, status: str | None = None, force_canceled: bool | None = None
+) -> None:
+ """Queue ``$aws/events/jobExecution/{jobId}/{status}`` for an execution that reached ``status``."""
+ status = status or execution["status"]
+ fields = {
+ "jobId": execution["jobId"],
+ "thingArn": _thing_arn(execution["thingName"]),
+ "status": status,
+ "executionNumber": execution["executionNumber"],
+ "timestamp": int(time.time()),
+ }
+ if force_canceled is not None:
+ fields["forceCanceled"] = force_canceled
+ if execution.get("statusDetails"):
+ fields["statusDetails"] = dict(execution["statusDetails"])
+ _registry_event(
+ "JOB_EXECUTION", f"jobExecution/{execution['jobId']}/{status.lower()}",
+ "JOB_EXECUTION", status.lower(), fields, str(uuid.uuid4()), with_account=False,
+ )
+
+
def _jobs_materialize_all() -> None:
for job_id in list(_jobs.keys()):
_jobs_materialize_executions(job_id)
@@ -5107,6 +5188,7 @@ def _jobs_apply_timeout(execution: dict) -> dict:
execution["status"] = "TIMED_OUT"
execution["lastUpdatedAt"] = _jobs_now_ms()
execution["versionNumber"] += 1
+ _job_execution_event(execution)
_jobs_maybe_complete(execution["jobId"])
return execution
@@ -5132,6 +5214,7 @@ def _jobs_maybe_complete(job_id: str) -> None:
job["status"] = "COMPLETED"
job["completedAt"] = now
job["lastUpdatedAt"] = now
+ _job_event(job, "completed")
def _jobs_check_expected_version(
@@ -5586,11 +5669,7 @@ def _describe_job(job_id: str) -> tuple:
_jobs_materialize_executions(job_id)
# Every execution counts, a rejoined thing's earlier ones included
# (measured eu-central-1 2026-10-05).
- counts = {status: 0 for status in _JOB_EXECUTION_STATUSES}
- for latest in _job_executions.values():
- if latest["jobId"] == job_id:
- for execution in _jobs_with_history(latest):
- counts[execution["status"]] += 1
+ counts = _jobs_status_counts(job_id)
job_doc = {
**_job_summary(job),
"targets": list(job.get("targets") or []),
@@ -5660,9 +5739,13 @@ async def _delete_job(job_id: str, qp: dict) -> tuple:
and execution["status"] in ("QUEUED", "IN_PROGRESS")
})
prev_next = {t: jobs_first_pending_job_id(t) for t in affected}
+ job["lastUpdatedAt"] = _jobs_now_ms()
+ _job_event(job, "deletion_in_progress")
del _jobs[job_id]
for key in [k for k in _job_executions.keys() if k[1] == job_id]:
+ _job_execution_event(_job_executions[key], "DELETED")
del _job_executions[key]
+ _job_event(job, "deleted")
account_id, region = get_account_id(), get_region()
for thing_name in affected:
await jobs_notify_thing(account_id, region, thing_name, prev_next[thing_name])
@@ -6013,6 +6096,7 @@ async def _cancel_job(job_id: str, payload: dict, qp: dict) -> tuple:
job["comment"] = payload["comment"]
if payload.get("reasonCode") is not None:
job["reasonCode"] = payload["reasonCode"]
+ _job_event(job, "cancellation_in_progress")
# QUEUED executions are always canceled with the job; IN_PROGRESS ones
# only when force is set — as on AWS. Queue fronts are snapshotted before
# the sweep so notify-next fires only where the front actually changed.
@@ -6033,7 +6117,9 @@ async def _cancel_job(job_id: str, payload: dict, qp: dict) -> tuple:
execution["status"] = "CANCELED"
execution["lastUpdatedAt"] = now
execution["versionNumber"] += 1
+ _job_execution_event(execution, force_canceled=force)
canceled_things.add(execution["thingName"])
+ _job_event(job, "canceled")
account_id, region = get_account_id(), get_region()
for thing_name in sorted(canceled_things):
await jobs_notify_thing(account_id, region, thing_name, prev_next[thing_name])
@@ -6173,6 +6259,7 @@ async def _cancel_job_execution(
execution["statusDetails"] = dict(payload["statusDetails"])
execution["lastUpdatedAt"] = _jobs_now_ms()
execution["versionNumber"] += 1
+ _job_execution_event(execution, force_canceled=force)
_jobs_maybe_complete(job_id)
await jobs_notify_thing(get_account_id(), get_region(), thing, prev_next)
return json_response({})
@@ -6351,6 +6438,8 @@ def jobs_update_execution(
execution["timeoutStartedAt"] = now
execution["lastUpdatedAt"] = now
execution["versionNumber"] += 1
+ if status in _JOB_EXECUTION_TERMINAL:
+ _job_execution_event(execution)
_jobs_maybe_complete(job_id)
return dict(execution), None
@@ -7925,7 +8014,8 @@ async def broker_publish(
jobs = _parse_jobs_topic(topic)
if jobs is not None:
try:
- await _handle_jobs_publish(account_id, region, *jobs, payload)
+ async with publishing_events():
+ await _handle_jobs_publish(account_id, region, *jobs, payload)
except Exception:
# Same guard as the shadow bridge above.
_broker_logger.warning(
diff --git a/ministack/services/iot_jobs_data.py b/ministack/services/iot_jobs_data.py
index 72f2edb7..dcd3ef96 100644
--- a/ministack/services/iot_jobs_data.py
+++ b/ministack/services/iot_jobs_data.py
@@ -70,6 +70,12 @@ def reset() -> None:
async def handle_request(
method: str, path: str, headers: dict, body: bytes, query_params: dict
) -> tuple:
+ """Route a device-plane request, then publish the job events it raised."""
+ async with _iot_module.publishing_events():
+ return await _route_request(method, path, body, query_params)
+
+
+async def _route_request(method: str, path: str, body: bytes, query_params: dict) -> tuple:
qp = {k: (v[0] if isinstance(v, list) else v) for k, v in query_params.items()}
if not path.startswith("/things/"):
diff --git a/tests/test_iot.py b/tests/test_iot.py
index a873bdf3..a009b249 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -6558,15 +6558,17 @@ 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
+ from ministack.services import iot_jobs_data
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(), {}
+ async def _call(method, path, body=None, query=None, device=False):
+ plane = iot_jobs_data if device else iot_module
+ status, _, resp = await plane.handle_request(
+ method, path, {}, json.dumps(body or {}).encode(), query or {}
)
assert status == 200, resp
return json.loads(resp or b"{}")
@@ -6588,8 +6590,15 @@ def _registry_events(calls, enable=_EVENT_TYPES) -> list:
iot_module.reset()
iot_module.broker_reset()
for _topic, event in received:
+ timestamp = event.pop("timestamp")
+ assert isinstance(timestamp, int)
+ if event["eventType"] in ("JOB", "JOB_EXECUTION"):
+ # Job events carry a dashed UUID and epoch seconds, and no accountId.
+ assert str(uuid.UUID(event["eventId"])) == event["eventId"]
+ assert timestamp < 10**11
+ assert "accountId" not in event
+ continue
assert re.fullmatch(r"[0-9a-f]{32}", event["eventId"])
- assert isinstance(event.pop("timestamp"), int)
if event["eventType"] == "THING_TYPE_ASSOCIATION_EVENT":
assert "accountId" not in event
else:
@@ -6789,6 +6798,213 @@ def test_iot_deleting_a_thing_announces_its_group_memberships():
]
+_JOB_ARN = f"arn:aws:iot:{_TEST_REGION}:{_EVENTS_ACCOUNT}"
+
+
+async def _create_job(call, job_id, things, **extra):
+ await call("PUT", f"/jobs/{job_id}", {
+ "targets": [f"{_JOB_ARN}:thing/{t}" for t in things], "document": "{}", **extra,
+ })
+
+
+def _job_counts(**counts) -> dict:
+ return {f"numberOf{name}Things": counts.get(name, 0) for name in (
+ "Canceled", "Rejected", "Failed", "Removed", "Succeeded", "TimedOut",
+ )}
+
+
+def _job_stamps(event: dict) -> None:
+ """Drop the epoch-millisecond job stamps after checking their unit."""
+ for member in ("createdAt", "lastUpdatedAt", "completedAt"):
+ if member in event:
+ assert event.pop(member) > 10**12
+
+
+def test_iot_job_execution_events_for_device_reports():
+ async def calls(call):
+ from ministack.services import iot as iot_module
+
+ await call("POST", "/things/ev-t1")
+ await _create_job(call, "ev-ok", ["ev-t1"], description="jd")
+ await call("POST", "/things/ev-t1/jobs/ev-ok", {"status": "IN_PROGRESS"}, device=True)
+ await call("POST", "/things/ev-t1/jobs/ev-ok",
+ {"status": "SUCCEEDED", "statusDetails": {"s": "2"}}, device=True)
+ await _create_job(call, "ev-fail", ["ev-t1"])
+ await iot_module.broker_publish(
+ _EVENTS_ACCOUNT, _TEST_REGION, "$aws/things/ev-t1/jobs/ev-fail/update",
+ json.dumps({"status": "FAILED", "statusDetails": {"errorCode": "E43"}}).encode(),
+ )
+ await _create_job(call, "ev-rej", ["ev-t1"])
+ await call("POST", "/things/ev-t1/jobs/ev-rej", {"status": "REJECTED"}, device=True)
+
+ events = _registry_events(calls, enable=("JOB", "JOB_EXECUTION"))
+ assert [t for t, _e in events] == [
+ "$aws/events/jobExecution/ev-ok/succeeded", "$aws/events/job/ev-ok/completed",
+ "$aws/events/jobExecution/ev-fail/failed", "$aws/events/job/ev-fail/completed",
+ "$aws/events/jobExecution/ev-rej/rejected", "$aws/events/job/ev-rej/completed",
+ ]
+ for _t, e in events:
+ e.pop("eventId")
+ _job_stamps(e)
+ execution = {"eventType": "JOB_EXECUTION", "executionNumber": 1,
+ "thingArn": f"{_JOB_ARN}:thing/ev-t1"}
+ assert events[0][1] == {**execution, "operation": "succeeded", "jobId": "ev-ok",
+ "status": "SUCCEEDED", "statusDetails": {"s": "2"}}
+ assert events[1][1] == {
+ "eventType": "JOB", "operation": "completed", "jobId": "ev-ok",
+ "status": "COMPLETED", "targetSelection": "SNAPSHOT",
+ "targets": [f"{_JOB_ARN}:thing/ev-t1"], "description": "jd",
+ "jobProcessDetails": _job_counts(Succeeded=1),
+ }
+ assert events[2][1] == {**execution, "operation": "failed", "jobId": "ev-fail",
+ "status": "FAILED", "statusDetails": {"errorCode": "E43"}}
+ assert events[3][1]["jobProcessDetails"] == _job_counts(Failed=1)
+ assert events[4][1] == {**execution, "operation": "rejected", "jobId": "ev-rej",
+ "status": "REJECTED"}
+ assert events[5][1]["jobProcessDetails"] == _job_counts(Rejected=1)
+
+
+def test_iot_job_cancel_events():
+ async def calls(call):
+ for thing in ("ev-t1", "ev-t2"):
+ await call("POST", f"/things/{thing}")
+ await _create_job(call, "ev-cancel", ["ev-t1", "ev-t2"])
+ await call("POST", "/things/ev-t1/jobs/ev-cancel", {"status": "IN_PROGRESS"}, device=True)
+ await call("PUT", "/jobs/ev-cancel/cancel", {"comment": "c1", "reasonCode": "R1"})
+ await call("POST", "/things/ev-t1/jobs/ev-cancel", {"status": "SUCCEEDED"}, device=True)
+ await _create_job(call, "ev-force", ["ev-t1", "ev-t2"])
+ await call("POST", "/things/ev-t1/jobs/ev-force",
+ {"status": "IN_PROGRESS", "statusDetails": {"p": "1"}}, device=True)
+ await call("PUT", "/jobs/ev-force/cancel", {"comment": "c2"}, {"force": "true"})
+ await _create_job(call, "ev-exec", ["ev-t1", "ev-t2"])
+ await call("PUT", "/things/ev-t2/jobs/ev-exec/cancel")
+ await call("POST", "/things/ev-t1/jobs/ev-exec", {"status": "IN_PROGRESS"}, device=True)
+ await call("PUT", "/things/ev-t1/jobs/ev-exec/cancel",
+ {"statusDetails": {"why": "w"}}, {"force": "true"})
+
+ events = _registry_events(calls, enable=("JOB", "JOB_EXECUTION"))
+ topics = [t for t, _e in events]
+ assert topics == [
+ "$aws/events/job/ev-cancel/cancellation_in_progress",
+ "$aws/events/jobExecution/ev-cancel/canceled",
+ "$aws/events/job/ev-cancel/canceled",
+ "$aws/events/jobExecution/ev-cancel/succeeded",
+ "$aws/events/job/ev-force/cancellation_in_progress",
+ "$aws/events/jobExecution/ev-force/canceled",
+ "$aws/events/jobExecution/ev-force/canceled",
+ "$aws/events/job/ev-force/canceled",
+ "$aws/events/jobExecution/ev-exec/canceled",
+ "$aws/events/jobExecution/ev-exec/canceled",
+ "$aws/events/job/ev-exec/completed",
+ ]
+ for _t, e in events:
+ e.pop("eventId")
+ _job_stamps(e)
+ job = {"eventType": "JOB", "targetSelection": "SNAPSHOT",
+ "targets": [f"{_JOB_ARN}:thing/ev-t1", f"{_JOB_ARN}:thing/ev-t2"]}
+ assert events[0][1] == {**job, "operation": "cancellation_in_progress",
+ "jobId": "ev-cancel", "status": "CANCELLATION_IN_PROGRESS",
+ "forceCanceled": False, "comment": "c1", "reasonCode": "R1"}
+ assert events[1][1] == {
+ "eventType": "JOB_EXECUTION", "operation": "canceled", "jobId": "ev-cancel",
+ "thingArn": f"{_JOB_ARN}:thing/ev-t2", "status": "CANCELED",
+ "executionNumber": 1, "forceCanceled": False,
+ }
+ # The IN_PROGRESS execution a cancel without force leaves running is not counted.
+ assert events[2][1] == {**job, "operation": "canceled", "jobId": "ev-cancel",
+ "status": "CANCELED", "forceCanceled": False,
+ "comment": "c1", "reasonCode": "R1",
+ "jobProcessDetails": _job_counts(Canceled=1)}
+ forced = {e["thingArn"]: e for _t, e in events[5:7]}
+ assert forced[f"{_JOB_ARN}:thing/ev-t1"]["statusDetails"] == {"p": "1"}
+ assert {e["forceCanceled"] for e in forced.values()} == {True}
+ assert events[7][1]["forceCanceled"] is True
+ assert events[7][1]["jobProcessDetails"] == _job_counts(Canceled=2)
+ assert [e["forceCanceled"] for _t, e in events[8:10]] == [False, True]
+ assert events[9][1]["statusDetails"] == {"why": "w"}
+ assert events[10][1]["jobProcessDetails"] == _job_counts(Canceled=2)
+ assert "forceCanceled" not in events[10][1]
+
+
+def test_iot_job_removed_timed_out_and_deleted_events():
+ async def calls(call):
+ from ministack.services import iot as iot_module
+
+ for thing in ("ev-t3", "ev-t4"):
+ await call("POST", f"/things/{thing}")
+ await call("POST", "/thing-groups/ev-group")
+ await call("PUT", "/thing-groups/addThingToThingGroup",
+ {"thingGroupName": "ev-group", "thingName": "ev-t3"})
+ await call("PUT", "/jobs/ev-cont", {
+ "targets": [f"{_JOB_ARN}:thinggroup/ev-group"], "document": "{}",
+ "targetSelection": "CONTINUOUS",
+ })
+ await call("PUT", "/thing-groups/removeThingFromThingGroup",
+ {"thingGroupName": "ev-group", "thingName": "ev-t3"})
+ await _create_job(call, "ev-timeout", ["ev-t4"],
+ timeoutConfig={"inProgressTimeoutInMinutes": 1})
+ await call("POST", "/things/ev-t4/jobs/ev-timeout",
+ {"status": "IN_PROGRESS", "statusDetails": {"d": "1"}}, device=True)
+ iot_module._job_executions[("ev-t4", "ev-timeout")]["startedAt"] -= 61_000
+ await call("GET", "/things/ev-t4/jobs/ev-timeout", device=True)
+ await call("DELETE", "/jobs/ev-timeout")
+ await call("DELETE", "/jobs/ev-cont", query={"force": "true"})
+
+ events = _registry_events(calls, enable=("JOB", "JOB_EXECUTION"))
+ assert [t for t, _e in events] == [
+ "$aws/events/jobExecution/ev-cont/removed",
+ "$aws/events/jobExecution/ev-timeout/timed_out",
+ "$aws/events/job/ev-timeout/completed",
+ "$aws/events/job/ev-timeout/deletion_in_progress",
+ "$aws/events/jobExecution/ev-timeout/deleted",
+ "$aws/events/job/ev-timeout/deleted",
+ "$aws/events/job/ev-cont/deletion_in_progress",
+ "$aws/events/jobExecution/ev-cont/deleted",
+ "$aws/events/job/ev-cont/deleted",
+ ]
+ for _t, e in events:
+ e.pop("eventId")
+ _job_stamps(e)
+ assert events[0][1] == {
+ "eventType": "JOB_EXECUTION", "operation": "removed", "jobId": "ev-cont",
+ "thingArn": f"{_JOB_ARN}:thing/ev-t3", "status": "REMOVED", "executionNumber": 1,
+ }
+ assert events[1][1]["status"] == "TIMED_OUT"
+ assert events[2][1]["jobProcessDetails"] == _job_counts(TimedOut=1)
+ job = {"eventType": "JOB", "jobId": "ev-timeout", "targetSelection": "SNAPSHOT",
+ "targets": [f"{_JOB_ARN}:thing/ev-t4"]}
+ assert events[3][1] == {**job, "operation": "deletion_in_progress",
+ "status": "DELETION_IN_PROGRESS"}
+ assert events[4][1] == {
+ "eventType": "JOB_EXECUTION", "operation": "deleted", "jobId": "ev-timeout",
+ "thingArn": f"{_JOB_ARN}:thing/ev-t4", "status": "DELETED", "executionNumber": 1,
+ "statusDetails": {"d": "1"},
+ }
+ assert events[5][1] == {**job, "operation": "deleted", "status": "DELETED"}
+ assert events[8][1]["targetSelection"] == "CONTINUOUS"
+
+
[email protected]("enable", [("JOB",), ("JOB_EXECUTION",), ()])
+def test_iot_job_events_follow_the_event_configuration(enable):
+ async def calls(call):
+ await call("POST", "/things/ev-t1")
+ await _create_job(call, "ev-ok", ["ev-t1"])
+ await call("POST", "/things/ev-t1/jobs/ev-ok", {"status": "SUCCEEDED"}, device=True)
+ await _create_job(call, "ev-cancel", ["ev-t1"])
+ await call("PUT", "/jobs/ev-cancel/cancel")
+
+ events = _registry_events(calls, enable=enable)
+ expected = {
+ ("JOB",): ["$aws/events/job/ev-ok/completed",
+ "$aws/events/job/ev-cancel/cancellation_in_progress",
+ "$aws/events/job/ev-cancel/canceled"],
+ ("JOB_EXECUTION",): ["$aws/events/jobExecution/ev-ok/succeeded",
+ "$aws/events/jobExecution/ev-cancel/canceled"],
+ (): [],
+ }
+ assert [t for t, _e in events] == expected[enable]
+
+
# ----------------------------------------------------------------------
# Shadow-over-MQTT bridge (white-box).
# ----------------------------------------------------------------------