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): add UpdateJob (#2115)
iot-rocket461ee7470215
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a075ff39..a7c00604 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Added+- **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- **Error envelope Content-Types now match AWS per protocol** — real AWS picks an error's `Content-Type` from the service's protocol, and services disagree: `application/x-amz-json-1.1` for jsonVersion-1.1 services (Kinesis, KMS, Secrets Manager, Athena, Cognito, EventBridge, WAFv2, CloudWatch Logs) vs `1.0` (DynamoDB, Step Functions, SQS); `text/xml` for query services (IAM, SNS, RDS, CloudFormation) and `text/xml;charset=UTF-8` for EC2; `application/json` for rest-json (Lambda, AppSync, API Gateway) vs `application/x-amz-json-1.1` for SESv2; `text/xml` for rest-xml except S3's `application/xml`. Errors are now normalized at dispatch using the botocore service model plus wire-captured quirks. Evidence: real AWS wire captures diffed per probe (7/28 → 23/28 probes conforming).diff --git a/README.md b/README.mdindex 98f34cae..c07ac234 100644--- a/README.md+++ b/README.md@@ -643,7 +643,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i| **CodeBuild** | CreateProject, BatchGetProjects, ListProjects, UpdateProject, DeleteProject, StartBuild, BatchGetBuilds, StopBuild, ListBuilds, ListBuildsForProject, BatchDeleteBuilds | 11 actions; project and build metadata stored in-memory; builds complete immediately with SUCCEEDED status by default. Set `MINISTACK_CODEBUILD_EXECUTE=1` and mount the Docker socket to **really run them**: the project's inline buildspec goes to the official AWS CodeBuild local agent, which runs the phases in `environment.image`, and `BatchGetBuilds` reports live `phases` with a real `SUCCEEDED`/`FAILED` outcome. Execution needs the workspace shared with the host at the **same path** (`-v /tmp/ministack-codebuild:/tmp/ministack-codebuild`), because the agent bind-mounts it into the build container; a build gets `AWS_ENDPOINT_URL` pointing back at MiniStack, honours `timeoutInMinutes`, and is stopped by `StopBuild`. An executed build streams the agent output into its `logs.groupName` / `logs.streamName`, so `aws logs tail` reads the build log back || **AppConfig** | CreateApplication, GetApplication, ListApplications, UpdateApplication, DeleteApplication, CreateEnvironment, GetEnvironment, ListEnvironments, UpdateEnvironment, DeleteEnvironment, CreateConfigurationProfile, GetConfigurationProfile, ListConfigurationProfiles, UpdateConfigurationProfile, DeleteConfigurationProfile, CreateHostedConfigurationVersion, GetHostedConfigurationVersion, ListHostedConfigurationVersions, DeleteHostedConfigurationVersion, CreateDeploymentStrategy, GetDeploymentStrategy, ListDeploymentStrategies, UpdateDeploymentStrategy, DeleteDeploymentStrategy, StartDeployment, GetDeployment, ListDeployments, StopDeployment, TagResource, UntagResource, ListTagsForResource, StartConfigurationSession, GetLatestConfiguration | 33 operations; control plane + data plane; hosted configuration versions; the AWS-predefined deployment strategies (4) are listed and immutable; deployments move through `DEPLOYING`, `BAKING` and `COMPLETE` on the strategy's schedule (`LINEAR` or `EXPONENTIAL` steps, then the bake time), with `PercentageComplete`, the event log and the environment `State` reported along the way; a `Monitors` alarm that goes to `ALARM` before the bake ends rolls the deployment back; one deployment per environment at a time (`ConflictException`, also for a stale `LatestDeploymentNumber`); `StopDeployment` rolls back a `DEPLOYING` deployment, and with `AllowRevert` also a `BAKING` one, or reverts a completed one within 72 hours; during a rollout a session gets the new version once the rollout reaches its fixed slot (MiniStack's choice, since AWS does not document how it picks targets); `GetLatestConfiguration` returns an empty body when the session already has the latest version, plus `Version-Label`, and uses `RequiredMinimumPollIntervalInSeconds` as the poll interval || **Transfer Family** | CreateServer, DescribeServer, DeleteServer, ListServers, StartServer, StopServer, CreateUser, DescribeUser, DeleteUser, ListUsers, ImportSshPublicKey, DeleteSshPublicKey | 12 operations; **real SFTP listener** on `:2222` (override with `SFTP_PORT`) backed by S3 — `ls`, `put`, `get`, `mkdir`, `rename` work end-to-end against the local S3 emulator; `SFTP_PORT_PER_SERVER=1` allocates one port per `CreateServer` from `SFTP_BASE_PORT` (default 2300); SSH key auth scans every user across every server and account; `LOGICAL` and `PATH` home-directory mappings; host key persists across restarts when `PERSIST_STATE=1` |-| **IoT Jobs** | Control plane (`iot`): CreateJob, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, DescribeJobExecution, CancelJobExecution, CreateJobTemplate, DescribeJobTemplate, ListJobTemplates, DeleteJobTemplate; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 13 control-plane + 4 device data-plane operations sharing one store. A job created with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a request member replaces the template's. Executions walk `QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED, TIMED_OUT}`; an execution past its `timeoutConfig.inProgressTimeoutInMinutes`, or past the `stepTimeoutInMinutes` the device reported, becomes `TIMED_OUT`, and the device plane reports `approximateSecondsBeforeTimedOut` while it runs. `REMOVED` is modeled and counted in `jobProcessDetails` but nothing sets it: deleting a thing DELETES its executions (freeing a job that was only waiting on that thing) rather than marking them `REMOVED`. `versionNumber` gives optimistic concurrency: every transition bumps it and a stale `expectedVersion` is rejected with a 409 whose message carries the current version — coded `VersionConflictException` on the control plane and `InvalidStateTransitionException` on the device plane, each as its own service model declares. `executionNumber` is write-once (always 1: an execution is never re-queued). Devices may only report `IN_PROGRESS` / `SUCCEEDED` / `FAILED` / `REJECTED` via `UpdateJobExecution`; targets are thing or thing-group ARNs — `SNAPSHOT` jobs resolve group membership once at creation, `CONTINUOUS` jobs also pick up things added to a target group later, and a target must name a thing or thing group in the caller's own account and region (anything else is `ResourceNotFoundException`, since it would resolve to no devices at all); a non-continuous job auto-`COMPLETED`s (with `jobProcessDetails` counts) once every execution is terminal. **`documentSource` is not fetched**: a job created with an S3 `documentSource` serves a `{"documentSource": "<url>"}` placeholder as its document rather than the object's content, so the lifecycle still runs — pass `document` when the content matters; a job template with a `documentSource` stores the same placeholder. **Timestamps are epoch seconds on every plane, as AWS documents**: control-plane responses use `timestamp` shapes (boto3 parses them to datetimes) while `iot-jobs-data` responses carry whole-second integer `long`s. **Jobs over MQTT**: the reserved `$aws/things/<thing>/jobs/#` request topics (`get`, `start-next`, `<jobId>/get` incl. `$next`, `<jobId>/update`) answer on their `accepted`/`rejected` topics from the same store as the HTTP plane (`jobDocument` as a JSON object over MQTT, a string over HTTP, as on AWS; rejections carry the string `ErrorCode` values and the execution's state on version and state-transition conflicts); `notify` fires when the pending set changes and `notify-next` when the queue front changes; `stepTimeoutInMinutes` and `executionNumber` are accepted but ignored. Job state persists with the IoT store when `PERSIST_STATE=1` |+| **IoT Jobs** | Control plane (`iot`): CreateJob, UpdateJob, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, DescribeJobExecution, CancelJobExecution, CreateJobTemplate, DescribeJobTemplate, ListJobTemplates, DeleteJobTemplate; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 14 control-plane + 4 device data-plane operations sharing one store. A job created with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a request member replaces the template's. Executions walk `QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED, TIMED_OUT}`; an execution past its `timeoutConfig.inProgressTimeoutInMinutes`, or past the `stepTimeoutInMinutes` the device reported, becomes `TIMED_OUT`, and the device plane reports `approximateSecondsBeforeTimedOut` while it runs. `REMOVED` is modeled and counted in `jobProcessDetails` but nothing sets it: deleting a thing DELETES its executions (freeing a job that was only waiting on that thing) rather than marking them `REMOVED`. `versionNumber` gives optimistic concurrency: every transition bumps it and a stale `expectedVersion` is rejected with a 409 whose message carries the current version — coded `VersionConflictException` on the control plane and `InvalidStateTransitionException` on the device plane, each as its own service model declares. `executionNumber` is write-once (always 1: an execution is never re-queued). Devices may only report `IN_PROGRESS` / `SUCCEEDED` / `FAILED` / `REJECTED` via `UpdateJobExecution`; targets are thing or thing-group ARNs — `SNAPSHOT` jobs resolve group membership once at creation, `CONTINUOUS` jobs also pick up things added to a target group later, and a target must name a thing or thing group in the caller's own account and region (anything else is `ResourceNotFoundException`, since it would resolve to no devices at all); a non-continuous job auto-`COMPLETED`s (with `jobProcessDetails` counts) once every execution is terminal. **`documentSource` is not fetched**: a job created with an S3 `documentSource` serves a `{"documentSource": "<url>"}` placeholder as its document rather than the object's content, so the lifecycle still runs — pass `document` when the content matters; a job template with a `documentSource` stores the same placeholder. **Timestamps are epoch seconds on every plane, as AWS documents**: control-plane responses use `timestamp` shapes (boto3 parses them to datetimes) while `iot-jobs-data` responses carry whole-second integer `long`s. **Jobs over MQTT**: the reserved `$aws/things/<thing>/jobs/#` request topics (`get`, `start-next`, `<jobId>/get` incl. `$next`, `<jobId>/update`) answer on their `accepted`/`rejected` topics from the same store as the HTTP plane (`jobDocument` as a JSON object over MQTT, a string over HTTP, as on AWS; rejections carry the string `ErrorCode` values and the execution's state on version and state-transition conflicts); `notify` fires when the pending set changes and `notify-next` when the queue front changes; `stepTimeoutInMinutes` and `executionNumber` are accepted but ignored. Job state persists with the IoT store when `PERSIST_STATE=1` || **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, ListThingGroupsForThing, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, CreateCertificateFromCsr, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, ListCertificatesByCA, CreateProvisioningTemplate, DescribeProvisioningTemplate, ListProvisioningTemplates, UpdateProvisioningTemplate, DeleteProvisioningTemplate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), MQTT-over-WebSocket pub/sub, DescribeEventConfigurations, UpdateEventConfigurations, CreateDomainConfiguration, DescribeDomainConfiguration, ListDomainConfigurations, UpdateDomainConfiguration, DeleteDomainConfiguration | 63 operations + **MQTT 3.1.1 and 5.0 over WebSocket** (negotiated per connection) on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection), but a **native mTLS MQTT listener on 8883** serves device SDK binaries by default — the client certificate is optional (no certificate means the default account, like an unsigned WebSocket upgrade) and, when presented, must be registered `ACTIVE` in exactly one account, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK (see `IOT_MTLS_PORT` in the environment table); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane; **fleet indexing** works the way it does on AWS — `UpdateIndexingConfiguration` turns the `AWS_Things` index on (Terraform `aws_iot_indexing_configuration`), and searching while `thingIndexingMode` is `OFF` answers `ResourceNotFoundException`; `SearchIndex` then queries the live registry + classic shadows with `AND`-separated `thingName` / `thingTypeName` / `thingGroupNames` / `attributes.*` / `shadow.reported.*` / `shadow.desired.*` terms (`*` / `?` wildcards, `maxResults` / `nextToken` paging) — there is no projection to build, so hits are always current; the deprecated principal-policy family (`AttachPrincipalPolicy` / `DetachPrincipalPolicy` / `ListPrincipalPolicies` / `ListPolicyPrincipals`) maps 1:1 onto the modern policy-target store; **topic rules fire on matching publishes** (incl. Basic Ingest `$aws/rules/<name>`) with SQL SELECT projection (`topic()`, `timestamp()`, `encode()`, `newuuid()`, `replace()`, `clientid()`, `isUndefined()`), **WHERE-clause evaluation** (comparisons, `IN`, `LIKE`, `BETWEEN`, `IS NULL`, `regexp_matches`, bare boolean attributes, composed with `AND` / `OR` and parenthesised grouping; missing attributes fail closed as on AWS; unparseable SQL → `SqlParseException`), and `lambda` / `republish` / `dynamoDBv2` / `sns` / `sqs` actions dispatched in-process with the rule's `errorAction` on failure; **device shadows over MQTT** — the `$aws/things/<thing>/shadow[/name/<name>]/{get,update,delete}` reserved topics drive the shadow store and reply on `accepted` / `rejected` (with `delta` and `documents` on update); a **CA-certificate registry** (`RegisterCACertificate` and friends) with the just-in-time-registration `registered` event on `$aws/events/certificates/registered/{caCertificateId}`; a **provisioning-template registry** (`CreateProvisioningTemplate` and friends) — storage + CRUD only, so `provisioningRoleArn` is presence-checked but not resolved and the fleet-provisioning MQTT workflow (`$aws/provisioning-templates/...`) is not implemented; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry; the broker publishes the presence and subscription lifecycle events (`$aws/events/presence/connected\|disconnected/{clientId}`, `$aws/events/subscriptions/subscribed\|unsubscribed/{clientId}`) || **IoT Wireless** | GetPositionEstimate | Single operation (`POST /position-estimate`, SigV4 scope `iotwireless`, endpoint prefix `api.iotwireless`). **The response is the raw GeoJSON blob** — the output shape's `payload` trait — so boto3 hands back a `StreamingBody` under `GeoJsonPayload`, not a JSON envelope. Resolves from `Ip` only: `WiFiAccessPoints` / `CellTowers` / `Gnss` are accepted and ignored, `Timestamp` and `AdvancedConfiguration` only reach `properties`, and the estimate is synthetic + deterministic — the canonical IP (an IPv4-mapped IPv6 address counts as its IPv4 form) hashes onto lon [-180, 180) / lat [-60, 60), 4 decimals — so the same address always answers the same estimate and consumer tests can assert on it. `properties` carry `horizontalAccuracy` 1000000 (the value of one live call) and `horizontalConfidenceLevel` 0.68 (the default the AWS IoT Core Device Location guide documents — `AdvancedConfiguration.WiFiCellular.ConfidencePercent` overrides it, divided by 100, within the 50 to 99 the model allows) plus `timestamp`, which is always there: AWS documents the request's `Timestamp` as the resolve time and the receive time as its substitute when the caller sends none, so send a `Timestamp` and the whole blob is byte-identical. The real payload's `country` and city/state/postal properties are omitted for that determinism. An input with no resolver hint and an `IpAddress` that `ipaddress.ip_address()` refuses answer `ValidationException` (those two wordings are recorded from the live service; every other message in this service is MiniStack's own, since none is documented); a `Timestamp` that is not a Unix timestamp, and a `ConfidencePercent` outside the model's range, are `ValidationException` too; a valid address that is **not globally routable or is multicast** (private, loopback, TEST-NET, multicast groups, ...) answers `ResourceNotFoundException` `Cannot find position for the IP address <ip>`, mirroring the real service's refusal when its geo database has no entry. A well-formed request whose only measurements are WLAN/cell/GNSS is `ResourceNotFoundException` too — the developer guide documents 404 for exactly that ("no location information was found or solved ... The MAC address or cellular tower information is not sufficient ... The GNSS payload is not sufficient"), and 400 for measurement data formatted incorrectly. Stateless — nothing persists || **EventBridge Scheduler** | CreateSchedule, GetSchedule, UpdateSchedule, DeleteSchedule, ListSchedules, CreateScheduleGroup, GetScheduleGroup, DeleteScheduleGroup, ListScheduleGroups, TagResource, UntagResource, ListTagsForResource | 12 actions; schedules **fire their targets** — a background sweep invokes each enabled schedule's target (Lambda, SQS, SNS, Step Functions) when due, honoring `State`, `StartDate`/`EndDate`, and `ActionAfterCompletion: DELETE`; schedule groups with cascading deletes; `rate()`, `cron()`, `at()` expressions; group/prefix/state filters on list; default group auto-created; CFN `AWS::Scheduler::Schedule` and `AWS::Scheduler::ScheduleGroup` supported |diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex 631ac79b..b55f7514 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -35,8 +35,8 @@ Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:``SearchIndex`` over the live registry, shadows and MQTT connectivity- Registry events: ``DescribeEventConfigurations`` /``UpdateEventConfigurations``- - Jobs (control plane): ``CreateJob``, ``DescribeJob``, ``ListJobs``,- ``GetJobDocument``, ``CancelJob``, ``DeleteJob``,+ - Jobs (control plane): ``CreateJob``, ``UpdateJob``, ``DescribeJob``,+ ``ListJobs``, ``GetJobDocument``, ``CancelJob``, ``DeleteJob``,``ListJobExecutionsForThing``, ``DescribeJobExecution``,``CancelJobExecution`` — execution state shared with the``iot-jobs-data`` device data plane (``iot_jobs_data.py``)@@ -76,6 +76,7 @@ import reimport sslimport structimport time+import unicodedataimport uuidimport weakreffrom datetime import datetime, timezone@@ -5052,13 +5053,17 @@ def _jobs_timeout_minutes(execution: dict, job: dict | None) -> int | None:``stepTimeoutInMinutes`` from the device's own UpdateJobExecution wins overthe job's ``timeoutConfig.inProgressTimeoutInMinutes``, which the reference- describes as applying to every execution of the job.+ describes as applying to every execution of the job. An execution that was+ running when UpdateJob changed the job's timeout keeps the earlier value."""step = execution.get("stepTimeoutInMinutes")if step is not None:return step- cfg = (job or {}).get("timeoutConfig") or {}- minutes = cfg.get("inProgressTimeoutInMinutes")+ if "jobTimeoutInMinutes" in execution:+ minutes = execution["jobTimeoutInMinutes"]+ else:+ cfg = (job or {}).get("timeoutConfig") or {}+ minutes = cfg.get("inProgressTimeoutInMinutes")return minutes if isinstance(minutes, int) else None@@ -5194,6 +5199,8 @@ async def _handle_job(method: str, path: str, body: bytes, qp: dict) -> tuple:return await _create_job(job_id, _parse_body(body))if method == "GET":return _describe_job(job_id)+ if method == "PATCH":+ return _update_job(job_id, _parse_body(body))if method == "DELETE":return await _delete_job(job_id, qp)return error_response_json(@@ -5245,17 +5252,9 @@ async def _create_job(job_id: str, payload: dict) -> tuple:)timeout_cfg = payload.get("timeoutConfig") or {}if timeout_cfg:- minutes = timeout_cfg.get("inProgressTimeoutInMinutes")- try:- minutes = int(minutes)- except (TypeError, ValueError):- minutes = None- if minutes is None or not 1 <= minutes <= 10080:- return error_response_json(- "InvalidRequestException",- "inProgressTimeoutInMinutes must be between 1 and 10080",- 400,- )+ err = _job_timeout_error(timeout_cfg.get("inProgressTimeoutInMinutes"))+ if err:+ return errtargets = payload.get("targets")if not targets:return error_response_json(@@ -5354,6 +5353,218 @@ async def _create_job(job_id: str, payload: dict) -> tuple:return json_response(response)+# The members UpdateJob takes; each one given replaces the stored one whole.+_JOB_UPDATE_MEMBERS = (+ "description", "presignedUrlConfig", "jobExecutionsRolloutConfig",+ "abortConfig", "timeoutConfig", "jobExecutionsRetryConfig",+)+_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."""+ found: list[str] = []++ def bound(value, member, low=None, high=None, double=False):+ if not isinstance(value, (int, float)) or isinstance(value, bool):+ return+ shown = float(value) if double else value+ if low is not None and value < low:+ found.append(_job_validation_clause(+ shown, member, f"Member must have value greater than or equal to {low}"))+ elif high is not None and value > high:+ found.append(_job_validation_clause(+ shown, member, f"Member must have value less than or equal to {high}"))++ def enum(value, member, allowed):+ 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}"))++ def criteria_list(cfg, member, high=None):+ items = cfg.get("criteriaList") if isinstance(cfg, dict) else None+ if not isinstance(items, list):+ return []+ if not items:+ found.append(_job_validation_clause(+ "[]", member, "Member must have length greater than or equal to 1"))+ elif high is not None and len(items) > high:+ shown = "[" + ", ".join(+ f"RetryCriteria(failureType={c.get('failureType')}, "+ f"numberOfRetries={c.get('numberOfRetries')})" for c in items+ ) + "]"+ found.append(_job_validation_clause(+ shown, member, f"Member must have length less than or equal to {high}"))+ return [c for c in items if isinstance(c, dict)]++ # Fixed order, independent of the request's member order.+ if len(job_id) > 64:+ found.append(_job_validation_clause(+ job_id, "jobId", "Member must have length less than or equal to 64"))+ elif not _JOB_ID_RE.match(job_id):+ found.append(_job_validation_clause(+ job_id, "jobId", "Member must satisfy regular expression pattern: [a-zA-Z0-9_-]+"))+ rollout = payload.get("jobExecutionsRolloutConfig") or {}+ if isinstance(rollout, dict):+ at = "jobExecutionsRolloutConfig"+ bound(rollout.get("maximumPerMinute"), f"{at}.maximumPerMinute", low=1, high=1000)+ rate = rollout.get("exponentialRate") or {}+ if isinstance(rate, dict):+ bound(rate.get("baseRatePerMinute"), f"{at}.exponentialRate.baseRatePerMinute",+ low=1, high=1000)+ bound(rate.get("incrementFactor"), f"{at}.exponentialRate.incrementFactor",+ low=1.1, high=5, double=True)+ criteria = rate.get("rateIncreaseCriteria") or {}+ if isinstance(criteria, dict):+ for name in ("numberOfNotifiedThings", "numberOfSucceededThings"):+ bound(criteria.get(name),+ f"{at}.exponentialRate.rateIncreaseCriteria.{name}", low=1)+ description = payload.get("description")+ if isinstance(description, str):+ if len(description) > 2028:+ found.append(_job_validation_clause(+ description, "description",+ "Member must have length less than or equal to 2028"))+ elif any(unicodedata.category(ch).startswith("C") for ch in description):+ found.append(_job_validation_clause(+ description, "description",+ r"Member must satisfy regular expression pattern: [^\p{C}]+"))+ presign = payload.get("presignedUrlConfig") or {}+ if isinstance(presign, dict):+ bound(presign.get("expiresInSec"), "presignedUrlConfig.expiresInSec",+ low=60, high=3600)+ for i, c in enumerate(criteria_list(payload.get("jobExecutionsRetryConfig"),+ "jobExecutionsRetryConfig.criteriaList", 2), 1):+ 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):+ 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("thresholdPercentage"), f"{at}.thresholdPercentage", high=100,+ double=True)+ return found+++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)+ if violations:+ return _job_validation_error(violations)+ if all(payload.get(member) is None for member in _JOB_UPDATE_MEMBERS):+ return error_response_json(+ "InvalidRequestException",+ f"Update Job request for job {job_id} cannot be empty.", 400,+ )+ if payload.get("timeoutConfig") is not None:+ err = _job_timeout_error(+ (payload["timeoutConfig"] or {}).get("inProgressTimeoutInMinutes"))+ if err:+ return err+ rollout = payload.get("jobExecutionsRolloutConfig")+ if isinstance(rollout, dict):+ maximum, rate = rollout.get("maximumPerMinute"), rollout.get("exponentialRate")+ message = None+ if maximum is None:+ message = (+ "Provide MaximumPerMinute value when ExponentialRate is defined"+ if rate is not None else+ "Provide MaximumPerMinute value or provide ExponentialRate and "+ "MaximumPerMinute"+ )+ elif isinstance(rate, dict):+ criteria = rate.get("rateIncreaseCriteria") or {}+ given = sum(criteria.get(name) is not None for name in (+ "numberOfNotifiedThings", "numberOfSucceededThings"))+ if given != 1:+ message = (+ f"Provide {'either' if not given else 'only one of'} "+ "NumberOfNotifiedThings or NumberOfSucceededThings when "+ "RateIncreaseCriteria is defined"+ )+ elif (rate.get("baseRatePerMinute") or 0) > maximum:+ message = (+ "Exponential rollout baseRatePerMinute should be less than "+ "maximumPerMinute."+ )+ if message:+ return error_response_json("InvalidRequestException", message, 400)+ role = (payload.get("presignedUrlConfig") or {}).get("roleArn")+ if role is not None and not _JOB_ROLE_ARN_RE.match(str(role)):+ return error_response_json(+ "InvalidRequestException", f"Given role {role} is invalid.", 400+ )+ return None+++def _job_retry_update_error(job: dict, retry: dict) -> tuple | None:+ """A retry config can only set the retries of its creation-time failure types to 0."""+ criteria = [c for c in retry.get("criteriaList") or [] if isinstance(c, dict)]+ message = None+ if any(c.get("numberOfRetries") != 0 for c in criteria):+ message = "The number of retries cannot be updated to any number other than 0."+ elif len(criteria) > 1 and any(c.get("failureType") == "ALL" for c in criteria):+ message = "A retryCriteria with failure type ALL must be used by itself."+ elif not job.get("jobExecutionsRetryConfig"):+ message = (+ "RetryConfig cannot be updated if the job has no RetryConfig defined "+ "during creation."+ )+ else:+ existing = {+ c.get("failureType")+ for c in job["jobExecutionsRetryConfig"].get("criteriaList") or []+ }+ if {c.get("failureType") for c in criteria} != existing:+ message = "FailureTypes must match existing FailureTypes defined in RetryConfig."+ if message:+ return error_response_json("InvalidRequestException", message, 400)+ return None+++def _update_job(job_id: str, payload: dict) -> tuple:+ err = _job_update_request_error(job_id, payload)+ if err:+ return err+ job = _jobs.get(job_id)+ if job is None:+ return error_response_json(+ "ResourceNotFoundException", f"Job {job_id} cannot be found.", 404+ )+ if job["status"] != "IN_PROGRESS":+ return error_response_json(+ "InvalidRequestException",+ f"Job {job_id} in status {job['status']} cannot be updated.", 400,+ )+ if payload.get("jobExecutionsRetryConfig") is not None:+ err = _job_retry_update_error(job, payload["jobExecutionsRetryConfig"])+ if err:+ return err+ if payload.get("timeoutConfig") is not None:+ # A running execution keeps the in-progress timeout it started with.+ _jobs_materialize_executions(job_id)+ minutes = (job.get("timeoutConfig") or {}).get("inProgressTimeoutInMinutes")+ for execution in _job_executions.values():+ if (+ execution["jobId"] == job_id+ and execution["status"] == "IN_PROGRESS"+ and "jobTimeoutInMinutes" not in execution+ ):+ execution["jobTimeoutInMinutes"] = minutes+ changes = {+ member: copy.deepcopy(payload[member])+ for member in _JOB_UPDATE_MEMBERS+ if payload.get(member) is not None+ }+ _job_config_floats(changes)+ job.update(changes)+ job["lastUpdatedAt"] = _jobs_now_ms()+ return 200, {}, b""++def _job_summary(job: dict) -> dict:summary = {"jobArn": job["jobArn"],@@ -5502,16 +5713,45 @@ def _job_template_arn(template_id: str) -> str:return f"arn:aws:iot:{get_region()}:{get_account_id()}:jobtemplate/{template_id}"-def _job_template_validation_error(value, member: str, constraint: str) -> tuple:+def _job_validation_clause(value, member: str, constraint: str) -> str:shown = "null" if value is None else f"'{value}'"+ return f"Value {shown} at '{member}' failed to satisfy constraint: {constraint}"+++def _job_validation_error(clauses: list[str]) -> tuple:+ noun = "error" if len(clauses) == 1 else "errors"+ return error_response_json(+ "InvalidRequestException",+ f"{len(clauses)} validation {noun} detected: " + "; ".join(clauses),+ 400,+ )+++def _job_template_validation_error(value, member: str, constraint: str) -> tuple:+ return _job_validation_error([_job_validation_clause(value, member, constraint)])+++def _job_timeout_error(minutes) -> tuple | None:+ if isinstance(minutes, int) and not isinstance(minutes, bool) and 1 <= minutes <= 10080:+ return Nonereturn error_response_json("InvalidRequestException",- f"1 validation error detected: Value {shown} at '{member}' failed to "- f"satisfy constraint: {constraint}",+ "Provide valid timeout value, inProgressTimeoutInMinutes cannot be "+ f"{'null' if minutes is None else minutes}.",400,)+def _job_config_floats(record: dict) -> None:+ """The two `double` members read back as floats (25 comes back as 25.0)."""+ for criteria in (record.get("abortConfig") or {}).get("criteriaList") or []:+ if isinstance(criteria.get("thresholdPercentage"), int):+ criteria["thresholdPercentage"] = float(criteria["thresholdPercentage"])+ rate = (record.get("jobExecutionsRolloutConfig") or {}).get("exponentialRate") or {}+ if isinstance(rate.get("incrementFactor"), int):+ rate["incrementFactor"] = float(rate["incrementFactor"])++def _job_template_id_error(template_id: str) -> tuple | None:if len(template_id) > 64:return _job_template_validation_error(@@ -5563,13 +5803,8 @@ def _create_job_template(template_id: str, payload: dict) -> tuple:document, "document", "Member must have length less than or equal to 32768")minutes = (payload.get("timeoutConfig") or {}).get("inProgressTimeoutInMinutes")- if minutes is not None and not (isinstance(minutes, int) and 1 <= minutes <= 10080):- return error_response_json(- "InvalidRequestException",- "Provide valid timeout value, inProgressTimeoutInMinutes cannot be "- f"{minutes}.",- 400,- )+ if minutes is not None and (err := _job_timeout_error(minutes)):+ return errsource = payload.get("documentSource")if document and source:return error_response_json(@@ -5616,13 +5851,7 @@ def _create_job_template(template_id: str, payload: dict) -> tuple:):if payload.get(member) is not None:record[member] = copy.deepcopy(payload[member])- # The two `double` members read back as floats (25 comes back as 25.0).- for criteria in (record.get("abortConfig") or {}).get("criteriaList") or []:- if isinstance(criteria.get("thresholdPercentage"), int):- criteria["thresholdPercentage"] = float(criteria["thresholdPercentage"])- rate = (record.get("jobExecutionsRolloutConfig") or {}).get("exponentialRate") or {}- if isinstance(rate.get("incrementFactor"), int):- rate["incrementFactor"] = float(rate["incrementFactor"])+ _job_config_floats(record)_job_templates[template_id] = recordreturn json_response({"jobTemplateArn": record["jobTemplateArn"], "jobTemplateId": template_id,diff --git a/tests/test_iot_jobs_data.py b/tests/test_iot_jobs_data.pyindex b7c7299c..99fe2b2f 100644--- a/tests/test_iot_jobs_data.py+++ b/tests/test_iot_jobs_data.py@@ -1401,6 +1401,399 @@ def test_iot_jobs_cancel_job_and_delete(iot_client, iot_jobs_data):_cleanup(iot_client, things=[thing])+# ---------------------------------------------------------------------------+# UpdateJob+# ---------------------------------------------------------------------------+++def _patch_job(job_id, payload):+ """Raw UpdateJob, so botocore's own validation does not get in the way."""+ return _raw(_IOT_AUTH, "PATCH", f"/jobs/{job_id}", payload)+++def test_iot_jobs_update_job_replaces_each_member(iot_client, iot_jobs_data):+ """UpdateJob replaces each given member whole and answers with an empty body."""+ thing = _unique("jobs-thing")+ job_id = _unique("job")+ try:+ thing_arn = _create_thing(iot_client, thing)+ iot_client.create_job(+ jobId=job_id, targets=[thing_arn], document=_DOCUMENT,+ description="before", timeoutConfig={"inProgressTimeoutInMinutes": 60},+ )+ iot_jobs_data.start_next_pending_job_execution(thingName=thing)+ before = iot_client.describe_job(jobId=job_id)["job"]+ time.sleep(1.1)+ req = urllib.request.Request(+ f"{ENDPOINT}/jobs/{job_id}", data=b'{"description": "after"}',+ method="PATCH",+ headers={"Authorization": _IOT_AUTH, "content-type": "application/json"},+ )+ with urllib.request.urlopen(req, timeout=5) as resp:+ assert (resp.status, resp.read()) == (200, b"")+ after = iot_client.describe_job(jobId=job_id)["job"]+ assert after["description"] == "after"+ assert after["lastUpdatedAt"] > before["lastUpdatedAt"]+ assert after["jobProcessDetails"] == before["jobProcessDetails"]+ assert after["timeoutConfig"] == {"inProgressTimeoutInMinutes": 60}++ role = "arn:aws:iam::000000000000:role/presign"+ rate = {"baseRatePerMinute": 5, "incrementFactor": 2,+ "rateIncreaseCriteria": {"numberOfNotifiedThings": 10}}+ abort = {"criteriaList": [{"failureType": "FAILED", "action": "CANCEL",+ "thresholdPercentage": 50,+ "minNumberOfExecutedThings": 3}]}+ for member, value, stored in (+ ("presignedUrlConfig", {"roleArn": role, "expiresInSec": 600}, None),+ ("jobExecutionsRolloutConfig",+ {"maximumPerMinute": 20, "exponentialRate": rate},+ {"maximumPerMinute": 20,+ "exponentialRate": {**rate, "incrementFactor": 2.0}}),+ # A member given replaces the stored one: the exponentialRate goes.+ ("jobExecutionsRolloutConfig", {"maximumPerMinute": 30}, None),+ ("abortConfig", abort, None),+ ("timeoutConfig", {"inProgressTimeoutInMinutes": 120}, None),+ ):+ iot_client.update_job(jobId=job_id, **{member: value})+ status, body = _raw(_IOT_AUTH, "GET", f"/jobs/{job_id}")+ assert body["job"][member] == (stored or value), member+ threshold = body["job"]["abortConfig"]["criteriaList"][0]["thresholdPercentage"]+ assert isinstance(threshold, float)+ assert body["job"]["jobProcessDetails"]["numberOfInProgressThings"] == 1+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_jobs_update_job_rejects_invalid_values(iot_client):+ thing = _unique("jobs-thing")+ job_id = _unique("job")+ role = "arn:aws:iam::000000000000:role/presign"+ rate = {"maximumPerMinute": 20, "exponentialRate": {+ "baseRatePerMinute": 5, "incrementFactor": 2,+ "rateIncreaseCriteria": {"numberOfNotifiedThings": 10}}}++ def with_rate(**over):+ return {"jobExecutionsRolloutConfig": {+ **rate, "exponentialRate": {**rate["exponentialRate"], **over}}}++ def clause(value, member, rule):+ return f"Value '{value}' at '{member}' failed to satisfy constraint: Member must {rule}"++ def constraint(value, member, rule):+ return f"1 validation error detected: {clause(value, member, rule)}"++ abort = "abortConfig.criteriaList.1.member"+ retry = "jobExecutionsRetryConfig.criteriaList.1.member"+ cases = [+ ({}, f"Update Job request for job {job_id} cannot be empty."),+ ({"timeoutConfig": {"inProgressTimeoutInMinutes": 0}},+ "Provide valid timeout value, inProgressTimeoutInMinutes cannot be 0."),+ ({"timeoutConfig": {"inProgressTimeoutInMinutes": 10081}},+ "Provide valid timeout value, inProgressTimeoutInMinutes cannot be 10081."),+ ({"timeoutConfig": {}},+ "Provide valid timeout value, inProgressTimeoutInMinutes cannot be null."),+ ({"jobExecutionsRolloutConfig": {"maximumPerMinute": 0}},+ constraint(0, "jobExecutionsRolloutConfig.maximumPerMinute",+ "have value greater than or equal to 1")),+ ({"jobExecutionsRolloutConfig": {"maximumPerMinute": 1001}},+ constraint(1001, "jobExecutionsRolloutConfig.maximumPerMinute",+ "have value less than or equal to 1000")),+ ({"jobExecutionsRolloutConfig": {}},+ "Provide MaximumPerMinute value or provide ExponentialRate and "+ "MaximumPerMinute"),+ ({"jobExecutionsRolloutConfig": {"exponentialRate": rate["exponentialRate"]}},+ "Provide MaximumPerMinute value when ExponentialRate is defined"),+ (with_rate(baseRatePerMinute=50),+ "Exponential rollout baseRatePerMinute should be less than maximumPerMinute."),+ (with_rate(incrementFactor=5.1),+ constraint(5.1, "jobExecutionsRolloutConfig.exponentialRate.incrementFactor",+ "have value less than or equal to 5")),+ (with_rate(rateIncreaseCriteria={}),+ "Provide either NumberOfNotifiedThings or NumberOfSucceededThings when "+ "RateIncreaseCriteria is defined"),+ (with_rate(rateIncreaseCriteria={"numberOfNotifiedThings": 10,+ "numberOfSucceededThings": 5}),+ "Provide only one of NumberOfNotifiedThings or NumberOfSucceededThings when "+ "RateIncreaseCriteria is defined"),+ ({"abortConfig": {"criteriaList": [{"failureType": "BAD", "action": "CANCEL",+ "thresholdPercentage": 50,+ "minNumberOfExecutedThings": 3}]}},+ constraint("BAD", f"{abort}.failureType",+ "satisfy enum value set: [ALL, TIMED_OUT, FAILED, REJECTED]")),+ ({"abortConfig": {"criteriaList": [{"failureType": "FAILED", "action": "CANCEL",+ "thresholdPercentage": 101,+ "minNumberOfExecutedThings": 3}]}},+ constraint(101.0, f"{abort}.thresholdPercentage",+ "have value less than or equal to 100")),+ ({"abortConfig": {"criteriaList": []}},+ constraint("[]", "abortConfig.criteriaList",+ "have length greater than or equal to 1")),+ ({"jobExecutionsRetryConfig": {"criteriaList": [+ {"failureType": "REJECTED", "numberOfRetries": 0}]}},+ constraint("REJECTED", f"{retry}.failureType",+ "satisfy enum value set: [ALL, TIMED_OUT, FAILED]")),+ ({"jobExecutionsRetryConfig": {"criteriaList": [+ {"failureType": "FAILED", "numberOfRetries": 11}]}},+ constraint(11, f"{retry}.numberOfRetries", "have value less than or equal to 10")),+ ({"jobExecutionsRetryConfig": {"criteriaList": [+ {"failureType": t, "numberOfRetries": 1} for t in ("FAILED", "TIMED_OUT", "ALL")+ ]}},+ constraint("[RetryCriteria(failureType=FAILED, numberOfRetries=1), "+ "RetryCriteria(failureType=TIMED_OUT, numberOfRetries=1), "+ "RetryCriteria(failureType=ALL, numberOfRetries=1)]",+ "jobExecutionsRetryConfig.criteriaList",+ "have length less than or equal to 2")),+ ({"presignedUrlConfig": {"roleArn": role, "expiresInSec": 59}},+ constraint(59, "presignedUrlConfig.expiresInSec",+ "have value greater than or equal to 60")),+ ({"presignedUrlConfig": {"roleArn": "short", "expiresInSec": 600}},+ "Given role short is invalid."),+ ({"description": "x" * 2029},+ constraint("x" * 2029, "description", "have length less than or equal to 2028")),+ ({"description": "a\u0001b"},+ constraint("a\u0001b", "description",+ r"satisfy regular expression pattern: [^\p{C}]+")),+ ({"jobExecutionsRolloutConfig": {"maximumPerMinute": 0},+ "presignedUrlConfig": {"roleArn": role, "expiresInSec": 59}},+ "2 validation errors detected: Value '0' at "+ "'jobExecutionsRolloutConfig.maximumPerMinute' failed to satisfy constraint: "+ "Member must have value greater than or equal to 1; Value '59' at "+ "'presignedUrlConfig.expiresInSec' failed to satisfy constraint: Member must "+ "have value greater than or equal to 60"),+ # The same order whatever order the request sends the members in.+ ({"abortConfig": {"criteriaList": [{"minNumberOfExecutedThings": 3,+ "thresholdPercentage": 50,+ "failureType": "BAD", "action": "CANCEL"}]},+ "presignedUrlConfig": {"roleArn": role, "expiresInSec": 59},+ "jobExecutionsRetryConfig": {"criteriaList": [+ {"failureType": "FAILED", "numberOfRetries": 11}]},+ "jobExecutionsRolloutConfig": {"maximumPerMinute": 0}},+ "4 validation errors detected: " + "; ".join([+ clause(0, "jobExecutionsRolloutConfig.maximumPerMinute",+ "have value greater than or equal to 1"),+ clause(59, "presignedUrlConfig.expiresInSec",+ "have value greater than or equal to 60"),+ clause(11, f"{retry}.numberOfRetries", "have value less than or equal to 10"),+ clause("BAD", f"{abort}.failureType",+ "satisfy enum value set: [ALL, TIMED_OUT, FAILED, REJECTED]"),+ ])),+ ({"abortConfig": {"criteriaList": [{"failureType": "BAD", "action": "BAD",+ "thresholdPercentage": 101,+ "minNumberOfExecutedThings": 0}]}},+ "4 validation errors detected: " + "; ".join([+ clause(0, f"{abort}.minNumberOfExecutedThings",+ "have value greater than or equal to 1"),+ clause("BAD", f"{abort}.failureType",+ "satisfy enum value set: [ALL, TIMED_OUT, FAILED, REJECTED]"),+ clause("BAD", f"{abort}.action", "satisfy enum value set: [CANCEL]"),+ clause(101.0, f"{abort}.thresholdPercentage",+ "have value less than or equal to 100"),+ ])),+ ]+ try:+ thing_arn = _create_thing(iot_client, thing)+ iot_client.create_job(jobId=job_id, targets=[thing_arn], document=_DOCUMENT)+ before = iot_client.describe_job(jobId=job_id)["job"]+ for payload, message in cases:+ status, body = _patch_job(job_id, payload)+ assert (status, body["message"]) == (400, message), payload+ assert iot_client.describe_job(jobId=job_id)["job"] == before++ # The request checks answer before the job is looked up.+ assert _patch_job("bad.id", {"description": "x"})[1]["message"] == constraint(+ "bad.id", "jobId", "satisfy regular expression pattern: [a-zA-Z0-9_-]+")+ missing = _unique("job")+ assert _patch_job(missing, {})[1]["message"] == (+ f"Update Job request for job {missing} cannot be empty.")+ status, body = _patch_job(missing, {"description": "x"})+ assert (status, body["message"]) == (404, f"Job {missing} cannot be found.")++ # CreateJob refuses a bad timeout with the same message.+ status, body = _raw(_IOT_AUTH, "PUT", f"/jobs/{missing}", {+ "targets": [thing_arn], "document": _DOCUMENT,+ "timeoutConfig": {"inProgressTimeoutInMinutes": 0}})+ assert (status, body["message"]) == (+ 400, "Provide valid timeout value, inProgressTimeoutInMinutes cannot be 0.")+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[thing])+++def test_iot_jobs_update_job_only_while_in_progress(iot_client, iot_jobs_data):+ """A CANCELED or COMPLETED job, or one in another account, is not updated."""+ thing = _unique("jobs-thing")+ canceled, done = _unique("job"), _unique("job")+ try:+ thing_arn = _create_thing(iot_client, thing)+ iot_client.create_job(jobId=canceled, targets=[thing_arn], document=_DOCUMENT)+ iot_client.cancel_job(jobId=canceled)+ iot_client.create_job(jobId=done, targets=[thing_arn], document=_DOCUMENT)+ iot_jobs_data.start_next_pending_job_execution(thingName=thing)+ iot_jobs_data.update_job_execution(thingName=thing, jobId=done, status="SUCCEEDED")+ for job_id, status in ((canceled, "CANCELED"), (done, "COMPLETED")):+ assert iot_client.describe_job(jobId=job_id)["job"]["status"] == status+ for payload in ({"description": "late"},+ {"timeoutConfig": {"inProgressTimeoutInMinutes": 5}}):+ with pytest.raises(ClientError) as ei:+ iot_client.update_job(jobId=job_id, **payload)+ assert _error(ei) == (+ 400, "InvalidRequestException",+ f"Job {job_id} in status {status} cannot be updated.",+ )+ with pytest.raises(ClientError) as ei:+ _account_client("iot", "222222222222").update_job(+ jobId=done, description="x")+ assert _error(ei) == (+ 404, "ResourceNotFoundException", f"Job {done} cannot be found.")+ finally:+ _cleanup(iot_client, jobs=[canceled, done], things=[thing])+++def test_iot_jobs_update_job_retry_config_only_drops_to_zero(iot_client):+ thing = _unique("jobs-thing")+ plain, single, with_retry = _unique("job"), _unique("job"), _unique("job")++ def retry(*criteria):+ return {"criteriaList": [+ {"failureType": failure, "numberOfRetries": number}+ for failure, number in criteria]}++ try:+ thing_arn = _create_thing(iot_client, thing)+ iot_client.create_job(jobId=plain, targets=[thing_arn], document=_DOCUMENT)+ iot_client.create_job(jobId=single, targets=[thing_arn], document=_DOCUMENT,+ jobExecutionsRetryConfig=retry(("FAILED", 2)))+ iot_client.create_job(+ jobId=with_retry, targets=[thing_arn], document=_DOCUMENT,+ timeoutConfig={"inProgressTimeoutInMinutes": 10},+ jobExecutionsRetryConfig=retry(("FAILED", 2), ("TIMED_OUT", 3)),+ )+ for job_id, config, message in (+ (plain, retry(("FAILED", 2)),+ "The number of retries cannot be updated to any number other than 0."),+ (plain, retry(("FAILED", 0)),+ "RetryConfig cannot be updated if the job has no RetryConfig defined "+ "during creation."),+ (with_retry, retry(("FAILED", 1)),+ "The number of retries cannot be updated to any number other than 0."),+ (single, retry(("TIMED_OUT", 0)),+ "FailureTypes must match existing FailureTypes defined in RetryConfig."),+ (single, retry(("FAILED", 0), ("TIMED_OUT", 0)),+ "FailureTypes must match existing FailureTypes defined in RetryConfig."),+ (with_retry, retry(("FAILED", 0)),+ "FailureTypes must match existing FailureTypes defined in RetryConfig."),+ (with_retry, retry(("FAILED", 0), ("ALL", 0)),+ "A retryCriteria with failure type ALL must be used by itself."),+ ):+ with pytest.raises(ClientError) as ei:+ iot_client.update_job(jobId=job_id, jobExecutionsRetryConfig=config)+ assert _error(ei) == (400, "InvalidRequestException", message), config++ # The same failure types in any order; stored as sent.+ both = retry(("TIMED_OUT", 0), ("FAILED", 0))+ iot_client.update_job(jobId=with_retry, jobExecutionsRetryConfig=both)+ job = iot_client.describe_job(jobId=with_retry)["job"]+ assert job["jobExecutionsRetryConfig"] == both+ finally:+ _cleanup(iot_client, jobs=[plain, single, with_retry], things=[thing])+++def test_iot_jobs_update_job_timeout_reaches_executions_that_start_later(+ iot_client, iot_jobs_data+):+ """A new timeout reaches later starts; a running execution keeps its own."""+ things = [_unique("jobs-thing") for _ in range(2)]+ job_id = _unique("job")++ def seconds_left(thing):+ execution = iot_jobs_data.describe_job_execution(+ thingName=thing, jobId=job_id)["execution"]+ return execution.get("approximateSecondsBeforeTimedOut")++ try:+ arns = [_create_thing(iot_client, thing) for thing in things]+ iot_client.create_job(jobId=job_id, targets=arns, document=_DOCUMENT,+ timeoutConfig={"inProgressTimeoutInMinutes": 60})+ iot_jobs_data.start_next_pending_job_execution(thingName=things[0])+ iot_client.update_job(jobId=job_id,+ timeoutConfig={"inProgressTimeoutInMinutes": 120})+ iot_jobs_data.start_next_pending_job_execution(thingName=things[1])+ assert 3500 < seconds_left(things[0]) <= 3600+ assert 7100 < seconds_left(things[1]) <= 7200+ iot_client.update_job(jobId=job_id,+ timeoutConfig={"inProgressTimeoutInMinutes": 30})+ assert 3500 < seconds_left(things[0]) <= 3600+ assert 7100 < seconds_left(things[1]) <= 7200+ finally:+ _cleanup(iot_client, jobs=[job_id], things=things)+++def test_iot_jobs_update_job_timeout_on_a_continuous_job(iot_client, iot_jobs_data):+ """A running execution stays without a timeout; a later joiner gets the new one."""+ group = _unique("jobs-group")+ early, late = _unique("jobs-thing"), _unique("jobs-thing")+ job_id = _unique("job")++ def seconds_left(thing):+ execution = iot_jobs_data.describe_job_execution(+ thingName=thing, jobId=job_id)["execution"]+ return execution.get("approximateSecondsBeforeTimedOut")++ try:+ group_arn = iot_client.create_thing_group(thingGroupName=group)["thingGroupArn"]+ for thing in (early, late):+ _create_thing(iot_client, thing)+ iot_client.add_thing_to_thing_group(thingGroupName=group, thingName=early)+ iot_client.create_job(jobId=job_id, targets=[group_arn], document=_DOCUMENT,+ targetSelection="CONTINUOUS")+ iot_jobs_data.start_next_pending_job_execution(thingName=early)+ iot_client.update_job(jobId=job_id,+ timeoutConfig={"inProgressTimeoutInMinutes": 20})+ assert seconds_left(early) is None+ iot_client.add_thing_to_thing_group(thingGroupName=group, thingName=late)+ iot_jobs_data.start_next_pending_job_execution(thingName=late)+ assert 1100 < seconds_left(late) <= 1200+ iot_client.update_job(jobId=job_id,+ timeoutConfig={"inProgressTimeoutInMinutes": 40})+ assert seconds_left(early) is None+ assert 1100 < seconds_left(late) <= 1200+ finally:+ _cleanup(iot_client, jobs=[job_id], things=[early, late], groups=[group])+++def test_iot_jobs_update_job_survives_persistence():+ """Updated members and a kept timeout survive get_state / load_persisted_state."""+ from ministack.core.responses import request_scope+ from ministack.services import iot as iot_module++ iot_module.reset()+ try:+ with request_scope("123456789012", "us-east-1"):+ now = iot_module._jobs_now_ms()+ iot_module._jobs["j1"] = {+ "jobId": "j1", "targets": [], "targetSelection": "SNAPSHOT",+ "status": "IN_PROGRESS", "document": "{}", "snapshotted": True,+ "timeoutConfig": {"inProgressTimeoutInMinutes": 1},+ }+ iot_module._job_executions[("t1", "j1")] = {+ "jobId": "j1", "thingName": "t1", "status": "IN_PROGRESS",+ "statusDetails": {}, "queuedAt": now, "startedAt": now,+ "lastUpdatedAt": now, "executionNumber": 1, "versionNumber": 2,+ }+ status, _, body = iot_module._update_job("j1", {+ "description": "d", "timeoutConfig": {"inProgressTimeoutInMinutes": 9}})+ assert (status, body) == (200, b"")+ state = iot_module.get_state()+ iot_module.reset()+ iot_module.load_persisted_state(state)+ job = iot_module._jobs["j1"]+ assert job["description"] == "d"+ assert job["timeoutConfig"] == {"inProgressTimeoutInMinutes": 9}+ execution = iot_module._job_executions[("t1", "j1")]+ assert iot_module._jobs_seconds_before_timeout(execution) == 60+ finally:+ iot_module.reset()++# ---------------------------------------------------------------------------# CancelJob with in-flight executions + control-plane version conflicts# ---------------------------------------------------------------------------