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): cancel a job once a criterion of its abortConfig is met (#2184)
iot-rocket837b11919600
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fcb3c55c..1ab11cda 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -27,6 +27,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added+- **IoT — job abort criteria** — a job's `abortConfig` was stored but never acted on; once a device report, a `CancelJobExecution`, a `DeleteJobExecution` or a timeout meets one of its criteria, the job is now canceled with reasonCode `ABORT_CANCEL` and AWS's comment, together with its `QUEUED` executions. `CreateJob` and `CreateJobTemplate` stored any `abortConfig`; they now refuse what `UpdateJob` refuses, and all three refuse a missing criterion member, a threshold of 0 or less or with more than two decimals, and a failure type given twice. A `CancelJob` without `force` now reports `forceCanceled` as false. Contributed by @iot-rocket.- **CloudFormation — SES configuration set updates** — `AWS::SES::ConfigurationSet` and `AWS::SES::ConfigurationSetEventDestination` stored none of their options, tags or destinations, and a change re-ran the create; both now provision through the SES v2 calls and update in place, a removed option goes back to its default as on AWS, and only a `Name` or `ConfigurationSetName` change replaces them. Contributed by @iot-rocket.- **SES v2 — configuration set options and event destinations** — `GetConfigurationSet` returned only the name and the tags given at creation; it now returns the tracking, delivery, reputation, sending, suppression, VDM and archiving options that `CreateConfigurationSet` and the seven `PutConfigurationSet*Options` calls set, and a call clears the members it leaves out, as on AWS. `CreateConfigurationSetEventDestination`, `GetConfigurationSetEventDestinations`, `UpdateConfigurationSetEventDestination` and `DeleteConfigurationSetEventDestination` are new. `CreateConfigurationSet` with a name already in use is refused with `AlreadyExistsException` instead of replacing the set. Contributed by @iot-rocket.- **IoT — MQTT publish, subscribe and receive evaluate IoT policies under `AUTH=true`** — after the CONNECT a certificate session could publish, subscribe and receive on any topic; it now needs `iot:Publish` on the topic (and `iot:RetainPublish` for a retained message or will), `iot:Subscribe` per topic filter and `iot:Receive` per delivered message. A refused PUBLISH or SUBSCRIBE closes an MQTT 3.1.1 connection (disconnect reason `CLIENT_ERROR`), MQTT 5 answers PUBACK 0x87, DISCONNECT 0x87 at QoS 0 (`AUTH_ERROR`) or 0x87 for the refused filter, which the `subscribed` event leaves out (no event when none is granted), a refused will refuses the CONNECT, and a message the subscriber may not receive is dropped. Contributed by @iot-rocket.diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex c13eadf5..54c65f44 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -6250,6 +6250,8 @@ def _jobs_apply_timeout(execution: dict) -> dict:execution["versionNumber"] += 1_job_execution_event(execution)_jobs_maybe_complete(execution["jobId"])+ # A read sends no jobs/notify, so the things an abort cancels here are not notified.+ _jobs_abort(execution["jobId"])return execution@@ -6277,6 +6279,43 @@ def _jobs_maybe_complete(job_id: str) -> None:_job_event(job, "completed")+# The execution statuses each abortConfig failureType counts.+_JOB_ABORT_FAILURE_STATUSES = {+ "FAILED": ("FAILED",), "REJECTED": ("REJECTED",), "TIMED_OUT": ("TIMED_OUT",),+ "ALL": ("FAILED", "REJECTED", "TIMED_OUT"),+}+++def _jobs_abort(job_id: str) -> dict:+ """Cancel an IN_PROGRESS job once a criterion of its abortConfig is met; returns _jobs_cancel's mapping."""+ job = _jobs.get(job_id)+ criteria = ((job or {}).get("abortConfig") or {}).get("criteriaList") or []+ if not criteria or job.get("status") != "IN_PROGRESS":+ return {}+ counts = _jobs_status_counts(job_id)+ # Every terminal execution counts as completed, CANCELED and REMOVED ones included.+ completed = sum(counts[status] for status in _JOB_EXECUTION_TERMINAL)+ for criterion in criteria:+ failure_type = criterion.get("failureType")+ threshold = criterion.get("thresholdPercentage")+ minimum = criterion.get("minNumberOfExecutedThings")+ if (+ criterion.get("action") != "CANCEL"+ or failure_type not in _JOB_ABORT_FAILURE_STATUSES+ or not isinstance(threshold, (int, float))+ or not isinstance(minimum, int)+ ):+ continue+ failed = sum(counts[status] for status in _JOB_ABORT_FAILURE_STATUSES[failure_type])+ if completed >= max(minimum, 1) and failed * 100 >= threshold * completed:+ comment = (+ f"Abort criteria for failure type {failure_type} with threshold {threshold:.2f}% met. "+ f"Total completed executions: {completed}, total {failure_type} executions: {failed}"+ )+ return _jobs_cancel(job_id, {"comment": comment, "reasonCode": "ABORT_CANCEL"}, False)+ return {}++def _jobs_check_expected_version(execution: dict, expected, conflict_code: str) -> tuple | None:@@ -6457,6 +6496,16 @@ async def _create_job(job_id: str, payload: dict) -> tuple:"Invalid jobId: must match [a-zA-Z0-9_-]{1,64}",400,)+ abort = payload.get("abortConfig")+ if violations := _job_update_violations(job_id, {"abortConfig": abort}):+ return _job_validation_error(violations)+ timeout_cfg = payload.get("timeoutConfig") or {}+ if timeout_cfg:+ err = _job_timeout_error(timeout_cfg.get("inProgressTimeoutInMinutes"))+ if err:+ return err+ if err := _job_abort_criteria_error(abort):+ return errif job_id in _jobs:return error_response_json("ResourceAlreadyExistsException", f"Job {job_id} already exists", 409@@ -6501,11 +6550,6 @@ async def _create_job(job_id: str, payload: dict) -> tuple:"follow the format YYYY-MM-DDThh:mm.",400,)- timeout_cfg = payload.get("timeoutConfig") or {}- if timeout_cfg:- err = _job_timeout_error(timeout_cfg.get("inProgressTimeoutInMinutes"))- if err:- return errtargets = payload.get("targets")if not targets:return error_response_json(@@ -6574,7 +6618,7 @@ async def _create_job(job_id: str, payload: dict) -> tuple:"presignedUrlConfig": payload.get("presignedUrlConfig") or {},"jobExecutionsRolloutConfig": payload.get("jobExecutionsRolloutConfig")or {},- # Stored so DescribeJob echoes them. timeoutConfig is acted on; nothing aborts.+ # Stored so DescribeJob echoes them. abortConfig and timeoutConfig are acted on."abortConfig": payload.get("abortConfig"),"timeoutConfig": payload.get("timeoutConfig"),"jobExecutionsRetryConfig": payload.get("jobExecutionsRetryConfig"),@@ -6613,10 +6657,12 @@ _JOB_ROLE_ARN_RE = re.compile(r"^arn:aws[a-z-]*:iam::\d{12}:role/.+$")def _job_update_violations(job_id: str, payload: dict) -> list[str]:- """Model constraint failures of an UpdateJob request."""+ """Model constraint failures of an UpdateJob request; CreateJob and CreateJobTemplate check abortConfig with it."""found: list[str] = []- def bound(value, member, low=None, high=None, double=False):+ def bound(value, member, low=None, high=None, double=False, required=False):+ if value is None and required:+ found.append(_job_validation_clause(None, member, "Member must not be null"))if not isinstance(value, (int, float)) or isinstance(value, bool):returnshown = float(value) if double else value@@ -6627,7 +6673,9 @@ def _job_update_violations(job_id: str, payload: dict) -> list[str]:found.append(_job_validation_clause(shown, member, f"Member must have value less than or equal to {high}"))- def enum(value, member, allowed):+ def enum(value, member, allowed, required=False):+ if value is None and required:+ found.append(_job_validation_clause(None, member, "Member must not be null"))if value is not None and value not in allowed:found.append(_job_validation_clause(value, member, f"Member must satisfy enum value set: {allowed}"))@@ -6689,17 +6737,45 @@ def _job_update_violations(job_id: str, payload: dict) -> list[str]:at = f"jobExecutionsRetryConfig.criteriaList.{i}.member"bound(c.get("numberOfRetries"), f"{at}.numberOfRetries", low=0, high=10)enum(c.get("failureType"), f"{at}.failureType", "[ALL, TIMED_OUT, FAILED]")- for i, c in enumerate(criteria_list(payload.get("abortConfig"),- "abortConfig.criteriaList"), 1):+ abort = payload.get("abortConfig")+ if isinstance(abort, dict) and abort.get("criteriaList") is None:+ found.append(_job_validation_clause(+ None, "abortConfig.criteriaList", "Member must not be null"))+ for i, c in enumerate(criteria_list(abort, "abortConfig.criteriaList"), 1):at = f"abortConfig.criteriaList.{i}.member"- bound(c.get("minNumberOfExecutedThings"), f"{at}.minNumberOfExecutedThings", low=1)- enum(c.get("failureType"), f"{at}.failureType", "[ALL, TIMED_OUT, FAILED, REJECTED]")- enum(c.get("action"), f"{at}.action", "[CANCEL]")+ bound(c.get("minNumberOfExecutedThings"), f"{at}.minNumberOfExecutedThings", low=1,+ required=True)+ enum(c.get("failureType"), f"{at}.failureType", "[ALL, TIMED_OUT, FAILED, REJECTED]",+ required=True)+ enum(c.get("action"), f"{at}.action", "[CANCEL]", required=True)bound(c.get("thresholdPercentage"), f"{at}.thresholdPercentage", high=100,- double=True)+ double=True, required=True)return found+def _job_abort_criteria_error(abort) -> tuple | None:+ """The abortConfig checks that follow the model constraints, criterion by criterion."""+ criteria = abort.get("criteriaList") if isinstance(abort, dict) else None+ seen = set()+ for c in criteria if isinstance(criteria, list) else []:+ if not isinstance(c, dict):+ continue+ threshold = c.get("thresholdPercentage")+ numeric = isinstance(threshold, (int, float)) and not isinstance(threshold, bool)+ message = None+ if c.get("failureType") in seen:+ message = "Multiple AbortCriteria cannot have the same failure type"+ elif numeric and threshold <= 0:+ message = (f"ThresholdPercentage value {float(threshold)} for AbortCriteria "+ "must have value greater than 0")+ elif numeric and round(threshold, 2) != threshold:+ message = "Abort thresholdPercentage must have two or less decimal digits"+ if message:+ return error_response_json("InvalidRequestException", message, 400)+ seen.add(c.get("failureType"))+ return None++def _job_update_request_error(job_id: str, payload: dict) -> tuple | None:"""Checks that need no job: they answer even for an unknown job id."""violations = _job_update_violations(job_id, payload)@@ -6715,6 +6791,8 @@ def _job_update_request_error(job_id: str, payload: dict) -> tuple | None:(payload["timeoutConfig"] or {}).get("inProgressTimeoutInMinutes"))if err:return err+ if err := _job_abort_criteria_error(payload.get("abortConfig")):+ return errrollout = payload.get("jobExecutionsRolloutConfig")if isinstance(rollout, dict):maximum, rate = rollout.get("maximumPerMinute"), rollout.get("exponentialRate")@@ -7045,10 +7123,12 @@ def _handle_job_template(method: str, path: str, body: bytes) -> tuple:def _create_job_template(template_id: str, payload: dict) -> tuple:+ abort = payload.get("abortConfig")+ violations = _job_update_violations(template_id, {"abortConfig": abort})if payload.get("description") is None:- return _job_template_validation_error(- None, "description", "Member must not be null"- )+ violations.insert(0, _job_validation_clause(None, "description", "Member must not be null"))+ if violations:+ return _job_validation_error(violations)document = payload.get("document")if isinstance(document, str) and len(document) > 32768:return _job_template_validation_error(@@ -7057,6 +7137,8 @@ def _create_job_template(template_id: str, payload: dict) -> tuple:minutes = (payload.get("timeoutConfig") or {}).get("inProgressTimeoutInMinutes")if minutes is not None and (err := _job_timeout_error(minutes)):return err+ if err := _job_abort_criteria_error(abort):+ return errsource = payload.get("documentSource")if document and source:return error_response_json(@@ -7259,21 +7341,12 @@ def _job_payload_from_template(payload: dict) -> tuple[dict | None, tuple | Nonereturn merged, None-async def _cancel_job(job_id: str, payload: dict, qp: dict) -> tuple:- job = _jobs.get(job_id)- if job is None:- return _error_not_found("Job", job_id)- if job["status"] != "IN_PROGRESS":- return error_response_json(- "InvalidRequestException",- f"Job {job_id} is in status {job['status']} and cannot be canceled",- 400,- )- force = _qp_bool(qp, "force")+def _jobs_cancel(job_id: str, payload: dict, force: bool) -> dict:+ """CancelJob's state change; maps each thing whose execution it canceled to its earlier queue front."""+ job = _jobs[job_id]now = _jobs_now_ms()job["status"] = "CANCELED"- if force:- job["forceCanceled"] = True+ job["forceCanceled"] = forcejob["lastUpdatedAt"] = nowjob["completedAt"] = nowif payload.get("comment") is not None:@@ -7304,9 +7377,23 @@ async def _cancel_job(job_id: str, payload: dict, qp: dict) -> tuple:_job_execution_event(execution, force_canceled=force)canceled_things.add(execution["thingName"])_job_event(job, "canceled")+ return {thing_name: prev_next[thing_name] for thing_name in canceled_things}+++async def _cancel_job(job_id: str, payload: dict, qp: dict) -> tuple:+ job = _jobs.get(job_id)+ if job is None:+ return _error_not_found("Job", job_id)+ if job["status"] != "IN_PROGRESS":+ return error_response_json(+ "InvalidRequestException",+ f"Job {job_id} is in status {job['status']} and cannot be canceled",+ 400,+ )+ canceled = _jobs_cancel(job_id, payload, _qp_bool(qp, "force"))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])+ for thing_name in sorted(canceled):+ await jobs_notify_thing(account_id, region, thing_name, canceled[thing_name])response = {"jobArn": job["jobArn"], "jobId": job_id}if job.get("description") is not None:response["description"] = job["description"]@@ -7499,6 +7586,7 @@ async def _cancel_job_execution(_job_execution_event(execution, force_canceled=force)_jobs_maybe_complete(job_id)await jobs_notify_thing(get_account_id(), get_region(), thing, prev_next)+ await jobs_abort_if_met(get_account_id(), get_region(), job_id)return json_response({})@@ -7558,6 +7646,7 @@ async def _delete_job_execution(thing: str, job_id: str, number: str, qp: dict)_jobs_maybe_complete(job_id)if pending:await jobs_notify_thing(get_account_id(), get_region(), thing, prev_next)+ await jobs_abort_if_met(get_account_id(), get_region(), job_id)return 200, {}, b""@@ -7877,6 +7966,14 @@ def jobs_update_execution(return dict(execution), None+async def jobs_abort_if_met(account_id: str, region: str, job_id: str) -> None:+ """Apply the job's abortConfig after an execution finished, notifying the things whose execution it canceled."""+ with request_scope(account_id, region):+ canceled = _jobs_abort(job_id)+ for thing_name in sorted(canceled):+ await jobs_notify_thing(account_id, region, thing_name, canceled[thing_name])++def jobs_execution_view(execution: dict, document: str | dict | None) -> dict:"""Device-plane JobExecution — whole-second ``long`` timestamps (the APIreference words every stamp as "the time, in seconds since the epoch"),@@ -9238,6 +9335,7 @@ async def _handle_jobs_publish(# publishes update/accepted first, then notify + notify-next# (live-captured order) — which the _respond above just preserved.await jobs_notify_thing(account_id, region, thing, prev_next)+ await jobs_abort_if_met(account_id, region, job_id)def _shadow_rejected(status: int, message: str, client_token: str | None = None) -> dict:diff --git a/ministack/services/iot_jobs_data.py b/ministack/services/iot_jobs_data.pyindex b1e9ea0d..4a769dd1 100644--- a/ministack/services/iot_jobs_data.py+++ b/ministack/services/iot_jobs_data.py@@ -254,4 +254,5 @@ async def _update_execution(thing: str, job_id: str, payload: dict) -> tuple:await _iot_module.jobs_notify_thing(get_account_id(), get_region(), thing, prev_next)+ await _iot_module.jobs_abort_if_met(get_account_id(), get_region(), job_id)return json_response(response)diff --git a/tests/test_iot.py b/tests/test_iot.pyindex 300d8e2a..7686aee8 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -9286,6 +9286,63 @@ def test_iot_job_cancel_events():assert "forceCanceled" not in events[10][1]+def test_iot_job_abort_events():+ async def calls(call):+ from ministack.services import iot as iot_module++ for thing in ("ev-t1", "ev-t2", "ev-t3"):+ await call("POST", f"/things/{thing}")+ failed = {"failureType": "FAILED", "action": "CANCEL",+ "thresholdPercentage": 50.0, "minNumberOfExecutedThings": 2}+ await _create_job(call, "ev-abort", ["ev-t1", "ev-t2", "ev-t3"],+ abortConfig={"criteriaList": [failed]})+ await call("POST", "/things/ev-t1/jobs/ev-abort", {"status": "SUCCEEDED"}, device=True)+ await iot_module.broker_publish(+ _EVENTS_ACCOUNT, _TEST_REGION, "$aws/things/ev-t2/jobs/ev-abort/update",+ json.dumps({"status": "FAILED"}).encode(),+ )+ timed_out = {**failed, "failureType": "TIMED_OUT", "minNumberOfExecutedThings": 1}+ await _create_job(call, "ev-timeout", ["ev-t1", "ev-t2"],+ abortConfig={"criteriaList": [timed_out]},+ timeoutConfig={"inProgressTimeoutInMinutes": 1})+ await call("POST", "/things/ev-t1/jobs/ev-timeout", {"status": "IN_PROGRESS"}, device=True)+ iot_module._job_executions[("ev-t1", "ev-timeout")]["startedAt"] -= 61_000+ await call("GET", "/things/ev-t1/jobs/ev-timeout", device=True)++ events = _registry_events(calls, enable=("JOB", "JOB_EXECUTION"))+ assert [t for t, _e in events] == [+ "$aws/events/jobExecution/ev-abort/succeeded",+ "$aws/events/jobExecution/ev-abort/failed",+ "$aws/events/job/ev-abort/cancellation_in_progress",+ "$aws/events/jobExecution/ev-abort/canceled",+ "$aws/events/job/ev-abort/canceled",+ "$aws/events/jobExecution/ev-timeout/timed_out",+ "$aws/events/job/ev-timeout/cancellation_in_progress",+ "$aws/events/jobExecution/ev-timeout/canceled",+ "$aws/events/job/ev-timeout/canceled",+ ]+ for _t, e in events:+ e.pop("eventId")+ _job_stamps(e)+ abort = {+ "eventType": "JOB", "jobId": "ev-abort", "targetSelection": "SNAPSHOT",+ "targets": [f"{_JOB_ARN}:thing/ev-t1", f"{_JOB_ARN}:thing/ev-t2", f"{_JOB_ARN}:thing/ev-t3"],+ "forceCanceled": False, "reasonCode": "ABORT_CANCEL",+ "comment": "Abort criteria for failure type FAILED with threshold 50.00% met. "+ "Total completed executions: 2, total FAILED executions: 1",+ }+ assert events[2][1] == {**abort, "operation": "cancellation_in_progress",+ "status": "CANCELLATION_IN_PROGRESS"}+ assert events[3][1]["thingArn"] == f"{_JOB_ARN}:thing/ev-t3"+ assert events[4][1] == {**abort, "operation": "canceled", "status": "CANCELED",+ "jobProcessDetails": _job_counts(Canceled=1, Failed=1, Succeeded=1)}+ assert events[8][1]["comment"] == (+ "Abort criteria for failure type TIMED_OUT with threshold 50.00% met. "+ "Total completed executions: 1, total TIMED_OUT executions: 1"+ )+ assert events[8][1]["jobProcessDetails"] == _job_counts(Canceled=1, TimedOut=1)++def test_iot_job_removed_timed_out_and_deleted_events():async def calls(call):from ministack.services import iot as iot_modulediff --git a/tests/test_iot_jobs_data.py b/tests/test_iot_jobs_data.pyindex 78f5ff13..2527662a 100644--- a/tests/test_iot_jobs_data.py+++ b/tests/test_iot_jobs_data.py@@ -1266,6 +1266,272 @@ def test_iot_jobs_fleet_completes_only_when_every_execution_is_terminal(_cleanup(iot_client, jobs=[job_id], things=[first, second])+def _abort_config(*criteria):+ return {"criteriaList": [+ {"failureType": failure_type, "action": "CANCEL",+ "thresholdPercentage": threshold, "minNumberOfExecutedThings": minimum}+ for failure_type, threshold, minimum in criteria+ ]}+++def _abort_comment(failure_type, threshold, completed, failed):+ return (+ f"Abort criteria for failure type {failure_type} with threshold {threshold} met. "+ f"Total completed executions: {completed}, total {failure_type} executions: {failed}"+ )+++def test_iot_jobs_abort_config_cancels_the_job_and_its_queued_executions(+ iot_client, iot_jobs_data+):+ """FAILED 30 % after 2: the second FAILED cancels the job and its QUEUED executions; IN_PROGRESS runs on."""+ things = [_unique("jobs-thing") for _ in range(5)]+ job_id = _unique("job")+ try:+ arns = [_create_thing(iot_client, thing) for thing in things]+ iot_client.create_job(jobId=job_id, targets=arns, document=_DOCUMENT,+ abortConfig=_abort_config(("FAILED", 30, 2)))+ iot_jobs_data.update_job_execution(jobId=job_id, thingName=things[0], status="IN_PROGRESS")+ iot_jobs_data.update_job_execution(jobId=job_id, thingName=things[1], status="FAILED")+ assert iot_client.describe_job(jobId=job_id)["job"]["status"] == "IN_PROGRESS"++ iot_jobs_data.update_job_execution(jobId=job_id, thingName=things[2], status="FAILED")+ job = iot_client.describe_job(jobId=job_id)["job"]+ assert job["status"] == "CANCELED"+ assert job["reasonCode"] == "ABORT_CANCEL"+ assert job["comment"] == _abort_comment("FAILED", "30.00%", 2, 2)+ assert job["forceCanceled"] is False+ assert [+ iot_client.describe_job_execution(jobId=job_id, thingName=thing)["execution"]["status"]+ for thing in things+ ] == ["IN_PROGRESS", "FAILED", "FAILED", "CANCELED", "CANCELED"]++ iot_jobs_data.update_job_execution(jobId=job_id, thingName=things[0], status="SUCCEEDED")+ job = iot_client.describe_job(jobId=job_id)["job"]+ assert job["status"] == "CANCELED"+ assert job["jobProcessDetails"]["numberOfSucceededThings"] == 1+ finally:+ _cleanup(iot_client, jobs=[job_id], things=things)++[email protected]("criteria, reports, comment", [+ # A SUCCEEDED counts as completed, and its report runs the check.+ ([("FAILED", 50, 3)], ["FAILED", "FAILED", "SUCCEEDED"], ("FAILED", "50.00%", 3, 2)),+ # The threshold is a minimum.+ ([("FAILED", 50, 2)], ["SUCCEEDED", "FAILED"], ("FAILED", "50.00%", 2, 1)),+ # REJECTED counts REJECTED executions only.+ ([("REJECTED", 33.33, 2)], ["FAILED", "SUCCEEDED", "REJECTED"], ("REJECTED", "33.33%", 3, 1)),+ # ALL counts FAILED and REJECTED alike.+ ([("ALL", 60, 3)], ["FAILED", "REJECTED", "SUCCEEDED"], ("ALL", "60.00%", 3, 2)),+ # Of two criteria met at once, the first in the list cancels.+ ([("ALL", 40, 1), ("FAILED", 50, 1)], ["FAILED"], ("ALL", "40.00%", 1, 1)),+ ([("FAILED", 50, 1), ("ALL", 40, 1)], ["FAILED"], ("FAILED", "50.00%", 1, 1)),+ # A canceled execution counts as completed, and CancelJobExecution runs the check.+ ([("FAILED", 40, 2)], ["FAILED", "CANCEL"], ("FAILED", "40.00%", 2, 1)),+])+def test_iot_jobs_abort_config_counts_completed_executions(+ iot_client, iot_jobs_data, criteria, reports, comment+):+ """Each report completes one more of four executions; only the last one meets a criterion."""+ things = [_unique("jobs-thing") for _ in range(4)]+ job_id = _unique("job")+ try:+ arns = [_create_thing(iot_client, thing) for thing in things]+ iot_client.create_job(jobId=job_id, targets=arns, document=_DOCUMENT,+ abortConfig=_abort_config(*criteria))+ for thing, report in zip(things, reports):+ assert iot_client.describe_job(jobId=job_id)["job"]["status"] == "IN_PROGRESS"+ if report == "CANCEL":+ iot_client.cancel_job_execution(jobId=job_id, thingName=thing)+ else:+ iot_jobs_data.update_job_execution(jobId=job_id, thingName=thing, status=report)+ job = iot_client.describe_job(jobId=job_id)["job"]+ assert job["status"] == "CANCELED"+ assert job["comment"] == _abort_comment(*comment)+ execution = iot_client.describe_job_execution(jobId=job_id, thingName=things[-1])+ assert execution["execution"]["status"] == "CANCELED"+ finally:+ _cleanup(iot_client, jobs=[job_id], things=things)+++def test_iot_jobs_abort_config_counts_removed_executions(iot_client, iot_jobs_data):+ """A thing leaving a CONTINUOUS job's group completes its execution as REMOVED."""+ things = [_unique("jobs-thing") for _ in range(3)]+ group = _unique("jobs-group")+ job_id = _unique("job")+ try:+ group_arn = iot_client.create_thing_group(thingGroupName=group)["thingGroupArn"]+ for thing in things:+ _create_thing(iot_client, thing)+ iot_client.add_thing_to_thing_group(thingGroupName=group, thingName=thing)+ iot_client.create_job(jobId=job_id, targets=[group_arn], document=_DOCUMENT,+ targetSelection="CONTINUOUS",+ abortConfig=_abort_config(("FAILED", 40, 2)))+ iot_client.remove_thing_from_thing_group(thingGroupName=group, thingName=things[0])+ iot_jobs_data.update_job_execution(jobId=job_id, thingName=things[1], status="FAILED")+ job = iot_client.describe_job(jobId=job_id)["job"]+ assert job["status"] == "CANCELED"+ assert job["comment"] == _abort_comment("FAILED", "40.00%", 2, 1)+ assert job["jobProcessDetails"]["numberOfRemovedThings"] == 1+ finally:+ _cleanup(iot_client, jobs=[job_id], things=things, groups=[group])+++def test_iot_jobs_abort_config_last_execution_completes_the_job(iot_client, iot_jobs_data):+ """A report that finishes the job's last open execution completes the job, whatever the criteria."""+ things = [_unique("jobs-thing") for _ in range(2)]+ job_id = _unique("job")+ try:+ arns = [_create_thing(iot_client, thing) for thing in things]+ iot_client.create_job(jobId=job_id, targets=arns, document=_DOCUMENT,+ abortConfig=_abort_config(("FAILED", 50, 2)))+ for thing in things:+ iot_jobs_data.update_job_execution(jobId=job_id, thingName=thing, status="FAILED")+ job = iot_client.describe_job(jobId=job_id)["job"]+ assert job["status"] == "COMPLETED"+ assert "reasonCode" not in job+ finally:+ _cleanup(iot_client, jobs=[job_id], things=things)+++def test_iot_jobs_abort_config_ignores_deleted_executions(iot_client, iot_jobs_data):+ """A deleted execution no longer counts, and DeleteJobExecution runs the check."""+ things = [_unique("jobs-thing") for _ in range(4)]+ kept, deleted = _unique("job"), _unique("job")+ try:+ arns = [_create_thing(iot_client, thing) for thing in things]+ iot_client.create_job(jobId=kept, targets=arns[:3], document=_DOCUMENT,+ abortConfig=_abort_config(("FAILED", 50, 2)))+ iot_jobs_data.update_job_execution(jobId=kept, thingName=things[0], status="FAILED")+ iot_client.delete_job_execution(jobId=kept, thingName=things[0], executionNumber=1)+ iot_jobs_data.update_job_execution(jobId=kept, thingName=things[1], status="SUCCEEDED")+ assert iot_client.describe_job(jobId=kept)["job"]["status"] == "IN_PROGRESS"++ iot_client.create_job(jobId=deleted, targets=arns, document=_DOCUMENT,+ abortConfig=_abort_config(("FAILED", 40, 2)))+ for thing, status in zip(things, ["SUCCEEDED", "SUCCEEDED", "FAILED"]):+ iot_jobs_data.update_job_execution(jobId=deleted, thingName=thing, status=status)+ assert iot_client.describe_job(jobId=deleted)["job"]["status"] == "IN_PROGRESS"+ iot_client.delete_job_execution(jobId=deleted, thingName=things[0], executionNumber=1)+ job = iot_client.describe_job(jobId=deleted)["job"]+ assert job["status"] == "CANCELED"+ assert job["comment"] == _abort_comment("FAILED", "40.00%", 2, 1)+ execution = iot_client.describe_job_execution(jobId=deleted, thingName=things[3])+ assert execution["execution"]["status"] == "CANCELED"+ finally:+ _cleanup(iot_client, jobs=[kept, deleted], things=things)+++_TIMEOUT_0 = "Provide valid timeout value, inProgressTimeoutInMinutes cannot be 0."+++def test_iot_jobs_abort_config_rejects_what_aws_rejects(iot_client):+ """CreateJob, CreateJobTemplate and UpdateJob refuse the same abortConfig values."""+ from conftest import make_client++ raw = make_client("iot", {"parameter_validation": False})+ thing = _unique("jobs-thing")+ job_id, other = _unique("job"), _unique("job")+ template_id = _unique("tmpl")++ def criterion(failure_type="FAILED", threshold=50, **over):+ return {"failureType": failure_type, "action": "CANCEL",+ "thresholdPercentage": threshold, "minNumberOfExecutedThings": 1, **over}++ def without(member):+ return {"criteriaList": [{k: v for k, v in criterion().items() if k != member}]}++ def constraint(value, member, rule):+ shown = "null" if value is None else f"'{value}'"+ return (f"1 validation error detected: Value {shown} at "+ f"'abortConfig.criteriaList{member}' failed to satisfy constraint: Member must {rule}")++ duplicate = "Multiple AbortCriteria cannot have the same failure type"+ decimals = "Abort thresholdPercentage must have two or less decimal digits"+ positive = "ThresholdPercentage value 0.0 for AbortCriteria must have value greater than 0"+ cases = [+ *[(without(member), constraint(None, f".1.member.{member}", "not be null"))+ for member in ("failureType", "action", "thresholdPercentage",+ "minNumberOfExecutedThings")],+ ({}, constraint(None, "", "not be null")),+ ({"criteriaList": [criterion(threshold=100.01)]},+ constraint(100.01, ".1.member.thresholdPercentage", "have value less than or equal to 100")),+ ({"criteriaList": [criterion(), criterion("ALL", action="BAD")]},+ constraint("BAD", ".2.member.action", "satisfy enum value set: [CANCEL]")),+ # The model constraints come first.+ ({"criteriaList": [criterion("BAD", 0)]},+ constraint("BAD", ".1.member.failureType",+ "satisfy enum value set: [ALL, TIMED_OUT, FAILED, REJECTED]")),+ ({"criteriaList": [criterion(threshold=0)]}, positive),+ ({"criteriaList": [criterion(threshold=-0.001)]},+ "ThresholdPercentage value -0.001 for AbortCriteria must have value greater than 0"),+ ({"criteriaList": [criterion(threshold=10.999)]}, decimals),+ ({"criteriaList": [criterion(), criterion(threshold=20)]}, duplicate),+ # Criterion by criterion: a duplicate is refused before its own threshold.+ ({"criteriaList": [criterion(threshold=10.999), criterion("ALL", 0)]}, decimals),+ ({"criteriaList": [criterion(), criterion(threshold=0)]}, duplicate),+ ({"criteriaList": [criterion(threshold=10.999), criterion(threshold=20)]}, decimals),+ ]+ try:+ thing_arn = _create_thing(iot_client, thing)+ iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)+ for abort, message in cases:+ for call in (+ lambda: raw.create_job(jobId=other, targets=[thing_arn], document=_DOCUMENT,+ abortConfig=abort),+ lambda: raw.create_job_template(jobTemplateId=template_id, description="d",+ document=_DOCUMENT, abortConfig=abort),+ lambda: raw.update_job(jobId=job_id, abortConfig=abort),+ ):+ with pytest.raises(ClientError) as ei:+ call()+ assert _error(ei) == (400, "InvalidRequestException", message), abort+ assert "abortConfig" not in iot_client.describe_job(jobId=job_id)["job"]++ # A bad timeout answers before the criteria checks, both before the id is looked up.+ iot_client.create_job_template(jobTemplateId=template_id, description="d",+ document=_DOCUMENT)+ zero = {"criteriaList": [criterion(threshold=0)]}+ timeout = {"timeoutConfig": {"inProgressTimeoutInMinutes": 0}}+ for call, message in [+ (lambda: raw.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT,+ abortConfig=zero), positive),+ (lambda: raw.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT,+ **timeout), _TIMEOUT_0),+ (lambda: raw.create_job(jobId=other, targets=[thing_arn], document=_DOCUMENT,+ abortConfig=zero, **timeout), _TIMEOUT_0),+ (lambda: raw.create_job_template(jobTemplateId=template_id, description="d",+ document=_DOCUMENT, abortConfig=zero), positive),+ (lambda: raw.create_job_template(jobTemplateId=other, description="d",+ document=_DOCUMENT, abortConfig=zero, **timeout),+ _TIMEOUT_0),+ (lambda: raw.create_job_template(jobTemplateId=other, document=_DOCUMENT,+ abortConfig={"criteriaList": [criterion("BAD")]}),+ "2 validation errors detected: Value null at 'description' failed to satisfy "+ "constraint: Member must not be null; Value 'BAD' at "+ "'abortConfig.criteriaList.1.member.failureType' failed to satisfy constraint: "+ "Member must satisfy enum value set: [ALL, TIMED_OUT, FAILED, REJECTED]"),+ (lambda: raw.update_job(jobId=other, abortConfig=zero), positive),+ (lambda: raw.update_job(jobId=job_id, abortConfig=zero, **timeout), _TIMEOUT_0),+ ]:+ with pytest.raises(ClientError) as ei:+ call()+ assert _error(ei) == (400, "InvalidRequestException", message)++ # Two decimals, and one criterion per failure type, are accepted.+ accepted = {"criteriaList": [criterion(t, 10.99) for t in+ ("FAILED", "REJECTED", "TIMED_OUT", "ALL")]}+ iot_client.create_job(jobId=other, targets=[thing_arn], document=_DOCUMENT,+ abortConfig=accepted)+ assert iot_client.describe_job(jobId=other)["job"]["abortConfig"] == accepted+ finally:+ try:+ iot_client.delete_job_template(jobTemplateId=template_id)+ except ClientError:+ pass+ _cleanup(iot_client, jobs=[job_id, other], things=[thing])++# ---------------------------------------------------------------------------# Routing: the jobs routes must not shadow thing CRUD# ---------------------------------------------------------------------------@@ -2496,6 +2762,7 @@ def test_iot_jobs_cancel_job_without_force_leaves_in_progress(job = iot_client.describe_job(jobId=job_id)["job"]assert job["status"] == "CANCELED"+ assert job["forceCanceled"] is Falseexecution = iot_client.describe_job_execution(jobId=job_id, thingName=thing)["execution"]@@ -3254,6 +3521,30 @@ def test_jobs_mqtt_start_next_of_first_job_is_silent(iot_client, iot_data_client_assert_epoch_seconds(execution["startedAt"])+def test_jobs_mqtt_abort_config_notifies_the_things_it_cancels(iot_client, iot_data_client):+ """A FAILED over MQTT that meets abortConfig notifies the thing whose QUEUED execution it canceled."""+ reporter, waiting = _unique("jobs-mqtt-ab"), _unique("jobs-mqtt-ab")+ job_id = _unique("job")+ arns = [_create_thing(iot_client, thing) for thing in (reporter, waiting)]+ iot_client.create_job(jobId=job_id, targets=arns, document=_DOCUMENT,+ abortConfig=_abort_config(("FAILED", 50, 1)))+ base = f"$aws/things/{waiting}/jobs"+ received = _collect_shadow_frames(+ f"{base}/#",+ lambda: _mqtt_publish(+ topic=f"$aws/things/{reporter}/jobs/{job_id}/update",+ payload=json.dumps({"status": "FAILED"}).encode(),+ ),+ want=2,+ )+ frames = _frames_by_topic(received)+ assert frames[f"{base}/notify"]["jobs"] == {}+ assert set(frames[f"{base}/notify-next"]) == {"timestamp"}+ job = iot_client.describe_job(jobId=job_id)["job"]+ assert job["status"] == "CANCELED"+ assert job["comment"] == _abort_comment("FAILED", "50.00%", 1, 1)++def test_jobs_mqtt_update_include_flags_and_terminal_notify(iot_client, iot_data_client):