open-standards/wai/wai-quantum-py/python/wai_quantum/service.py
Transaction Science fd3b7c60d4
All checks were successful
wai-quantum contract / does this change touch it (pull_request) Successful in 20s
wai-quantum dataflow member / does this change touch it (pull_request) Successful in 23s
WAI breaking changes and the conformance runner / WAI breaking · does this change touch WAI (pull_request) Successful in 24s
WAI examples / WAI examples · does this change touch them (pull_request) Successful in 24s
wai-quantum command line / does this change touch it (pull_request) Successful in 23s
wai-quantum CUDA member / does this change touch it (pull_request) Successful in 23s
WAI operation catalogue / does this change touch it (pull_request) Successful in 23s
WAI conformance / does this change touch it (pull_request) Successful in 26s
wai-audit collector and player integration / does this change touch it (pull_request) Successful in 27s
standards workspaces build + test / which workspaces this change touches (pull_request) Successful in 30s
wai-quantum editors / does this change touch it (pull_request) Successful in 6s
wai-quantum docs, course and locales / does this change touch it (pull_request) Successful in 9s
wai-quantum resource estimation / does this change touch it (pull_request) Successful in 11s
wai-quantum signal processor / does this change touch it (pull_request) Successful in 12s
wai-quantum HIP member / does this change touch it (pull_request) Successful in 11s
wai-quantum other formats / does this change touch it (pull_request) Successful in 12s
wai-quantum FPGA member / does this change touch it (pull_request) Successful in 13s
wai-quantum npu-cores member / does this change touch it (pull_request) Successful in 7s
wai-quantum OpenCL member / does this change touch it (pull_request) Successful in 10s
wai-quantum for JavaScript / does this change touch it (pull_request) Successful in 24s
wai-quantum Metal member / does this change touch it (pull_request) Successful in 22s
wai-quantum OpenQASM reader / does this change touch it (pull_request) Successful in 23s
wai-quantum neural-processor member / does this change touch it (pull_request) Successful in 13s
wai-quantum dataflow member / member · dataflow device absent (macos) (pull_request) Successful in 27s
WAI conformance / cross-arch byte-equality · macos (pull_request) Successful in 31s
wai-quantum pulse and dynamics / does this change touch it (pull_request) Successful in 8s
wai-quantum for Python / does this change touch it (pull_request) Successful in 7s
WAI energy receipts / does this change touch it (pull_request) Successful in 1m20s
wai-quantum error correction and mitigation / does this change touch it (pull_request) Successful in 7s
wai-quantum-qpu / does this change touch it (pull_request) Successful in 5s
wai-quantum extension points / does this change touch it (pull_request) Successful in 7s
wai-quantum service / does this change touch it (pull_request) Successful in 5s
wai-quantum matrix-extension member / does this change touch it (pull_request) Successful in 9s
wai-quantum studio and desktop / does this change touch it (pull_request) Successful in 5s
wai-quantum portable tensor program / does this change touch it (pull_request) Successful in 6s
wai-quantum tensor-engine member / does this change touch it (pull_request) Successful in 10s
wai-quantum on every processor / emulated · aarch64-unknown-linux-gnu (pull_request) Successful in 1m11s
wai-quantum variational and algorithm library / does this change touch it (pull_request) Successful in 6s
wai-quantum CPU vector units / does this change touch it (pull_request) Successful in 7s
wai-quantum verdicts and repairs / does this change touch it (pull_request) Successful in 7s
wai-quantum views in agent hosts / does this change touch it (pull_request) Successful in 5s
wai-quantum CUDA member / member · CUDA (jetson-hub) (pull_request) Successful in 1m32s
wai-quantum WebGPU member / does this change touch it (pull_request) Successful in 8s
wai-sink-swift native sink package / does this change touch it (pull_request) Successful in 6s
wai-sink-android native sink library / does this change touch it (pull_request) Successful in 9s
wai-web reach builds / wai-web reach · does this change touch it (pull_request) Successful in 5s
WAI Studio / does this change touch it (pull_request) Successful in 9s
wai-web wasm32 / does this change touch it (pull_request) Successful in 8s
wai-quantum on every processor / emulated · loongarch64-unknown-linux-gnu (pull_request) Successful in 1m39s
wai-quantum OpenCL member / member · OpenCL GPU and CPU (jetson-hub) (pull_request) Successful in 35s
WAI conformance / codec wrappers · fuzz smoke, text decode limits, C entry points, provenance, the semantic path (pull_request) Successful in 1m57s
wai-quantum CUDA member / member · CUDA (thor) (pull_request) Successful in 2m24s
wai-quantum on every processor / emulated · powerpc64-unknown-linux-gnu (pull_request) Successful in 2m18s
WAI conformance / fast integer kernels, every x86_64 kernel set (AVX-512 silicon) (pull_request) Successful in 2m56s
wai-quantum OpenCL member / member · OpenCL GPU and CPU (thor) (pull_request) Successful in 54s
wai-quantum HIP member / member · HIP (framework-128gb) (pull_request) Successful in 57s
wai-quantum on every processor / emulated · powerpc64le-unknown-linux-gnu (pull_request) Successful in 3m46s
wai-quantum command line / command line · macos (pull_request) Successful in 1m35s
wai-quantum on every processor / emulated · armv7-unknown-linux-gnueabihf (pull_request) Successful in 4m35s
wai-quantum npu-cores member / member · npu-cores, neural processor (framework-128gb silicon) (pull_request) Successful in 1m15s
wai-quantum on every processor / emulated · riscv64gc-unknown-linux-gnu (pull_request) Successful in 5m4s
wai-quantum OpenCL member / member · OpenCL GPU (framework-128gb) (pull_request) Successful in 22s
wai-audit collector and player integration / collector, player integration and the browser end to end · macos (pull_request) Successful in 1m46s
wai-quantum portable tensor program / tensor program · integrated GPU (framework-128gb) (pull_request) Successful in 12s
wai-quantum CPU vector units / member · vector units, avx2 and avx512 (framework-128gb silicon) (pull_request) Successful in 16s
wai-quantum on every processor / emulated · sparc64-unknown-linux-gnu (pull_request) Successful in 6m24s
wai-quantum contract / the policy is linked, and the deprecations page reads (pull_request) Successful in 10s
wai-quantum service / service energy · linux packages (pull_request) Successful in 1m36s
wai-quantum editors / editors · macos (pull_request) Successful in 1m53s
wai-quantum OpenCL member / member · OpenCL GPU (macos) (pull_request) Successful in 35s
wai-quantum portable tensor program / tensor program · GPUs (jetson-hub) (pull_request) Successful in 36s
wai-quantum FPGA member / member · FPGA datapath, simulated (macos) (pull_request) Successful in 1m47s
wai-quantum dataflow member / member · dataflow device, simulated (pci 1e52:401e) (pull_request) Successful in 1m28s
WAI breaking changes and the conformance runner / WAI breaking · wire, record and API against main · linux (pull_request) Successful in 1m49s
wai-quantum Metal member / member · Metal (macos) (pull_request) Successful in 40s
WAI breaking changes and the conformance runner / WAI breaking and conform · their tests, and the independent verifiers through wai conform · linux (pull_request) Successful in 2m29s
wai-quantum contract / API compatibility · linux (pull_request) Successful in 4m26s
wai-quantum pulse and dynamics / the same bits · macos (pull_request) Successful in 1m7s
WAI conformance / cross-arch byte-equality · linux (pull_request) Successful in 31s
WAI conformance / faces from keypoints under wasm32-wasip2 (wasmtime) (pull_request) Successful in 1m31s
wai-quantum contract / schemas and the committed tool lists · linux (pull_request) Successful in 5m53s
wai-quantum CUDA member / member · CUDA absent (linux) (pull_request) Successful in 1m38s
WAI conformance / quantum core and corpus under wasm32-wasip2 (wasmtime) (pull_request) Successful in 3m21s
wai-audit collector and player integration / collector · linux (pull_request) Successful in 1m23s
wai-quantum docs, course and locales / the Studio's words in every locale · linux (pull_request) Successful in 10s
wai-quantum command line / command line · linux (pull_request) Successful in 2m41s
standards workspaces build + test / macOS energy backends (pull_request) Successful in 10m34s
WAI examples / WAI examples · the archive, the readiness check, the browser and Apple · macos (pull_request) Successful in 13m9s
wai-quantum WebGPU member / member · integrated GPU, Vulkan (framework-128gb) (pull_request) Successful in 8m2s
wai-quantum neural-processor member / member · neural processor (macos) (pull_request) Successful in 6m13s
wai-quantum editors / editors · linux (pull_request) Successful in 3m1s
wai-quantum on every processor / emulated · s390x-unknown-linux-gnu (pull_request) Successful in 14m39s
wai-quantum resource estimation / estimation and calibration · linux, release (pull_request) Successful in 1m45s
wai-quantum-qpu / credentials in the keychain (macos) (pull_request) Successful in 35s
wai-quantum docs, course and locales / the course and the command line's languages · linux (pull_request) Successful in 2m38s
wai-quantum FPGA member / member · FPGA simulation absent (linux) (pull_request) Successful in 25s
wai-quantum dataflow member / member · dataflow device, simulated (pci 1e52:b140) (pull_request) Successful in 8m34s
wai-quantum OpenCL member / member · OpenCL absent (linux) (pull_request) Successful in 46s
WAI operation catalogue / the catalogue and every door · linux (pull_request) Successful in 4m42s
wai-quantum OpenQASM reader / corpus under wasm32-wasip2 (wasmtime) (pull_request) Successful in 50s
wai-quantum for Python / python · macos (pull_request) Successful in 3m42s
wai-quantum neural-processor member / member · neural processor absent (linux) (pull_request) Successful in 22s
wai-quantum on every processor / emulated · i686-unknown-linux-gnu (pull_request) Successful in 17m26s
wai-quantum matrix-extension member / member · matrix extension absent (macos) (pull_request) Successful in 26s
wai-quantum Metal member / member · Metal absent (linux) (pull_request) Successful in 2m4s
WAI conformance / cargo-class corpora · macos (pull_request) Successful in 18m22s
wai-quantum OpenQASM reader / reader and corpus · linux (pull_request) Successful in 2m25s
wai-quantum portable tensor program / tensor program · Metal and the arm64 CPU (macos) (pull_request) Successful in 41s
wai-quantum CPU vector units / member · vector unit absent (macos) (pull_request) Successful in 27s
wai-quantum for JavaScript / javascript · linux (pull_request) Successful in 3m17s
wai-quantum pulse and dynamics / reader, simulator and pulse jobs · linux, release (pull_request) Successful in 1m31s
wai-quantum other formats / readers, writers and the set · linux (pull_request) Successful in 4m29s
wai-quantum service / service · macos (pull_request) Successful in 5m28s
wai-quantum pulse and dynamics / reader, simulator and pulse jobs under wasm32-wasip2 (wasmtime) (pull_request) Successful in 2m38s
wai-quantum other formats / the set under wasm32-wasip2 (wasmtime) (pull_request) Successful in 5m39s
wai-quantum WebGPU member / member · browser WebGPU (macos) (pull_request) Successful in 2m53s
WAI energy receipts / energy receipts · macos (pull_request) Successful in 8m23s
wai-quantum WebGPU member / member · Metal (macos) (pull_request) Successful in 3m43s
WAI examples / WAI examples · portable · linux (pull_request) Successful in 11m35s
wai-quantum studio and desktop / desktop app · macos (pull_request) Successful in 7m13s
WAI conformance / cargo-class corpora · linux (pull_request) Successful in 19m0s
wai-quantum WebGPU member / member · GPU, Vulkan (thor) (pull_request) Successful in 24m44s
wai-quantum signal processor / processor and member · signal processor, emulated (pull_request) Successful in 14m44s
wai-quantum matrix-extension member / member · matrix extension, emulated (aarch64 Linux) (pull_request) Successful in 11s
wai-quantum extension points / the registry under wasm32-wasip2 (wasmtime) (pull_request) Successful in 1m1s
wai-quantum for Python / python · linux (pull_request) Successful in 2m50s
wai-quantum-qpu / clients against their contracts (linux) (pull_request) Successful in 1m28s
wai-sink-android native sink library / every ABI, the AAR, and the instrumented tests in a headless emulator · macos (pull_request) Successful in 7m46s
wai-quantum portable tensor program / tensor program · CPU, mutants, GPU builds (pull_request) Successful in 21s
wai-quantum error correction and mitigation / codes, decoders, texts and mitigation · linux, release (pull_request) Successful in 2m59s
wai-quantum CPU vector units / member · vector unit, rvv 1024-bit (riscv64, emulated) (pull_request) Successful in 10s
wai-quantum CPU vector units / member · vector unit, sve 128-bit (aarch64, emulated) (pull_request) Successful in 14s
wai-quantum extension points / the registry and the example · linux (pull_request) Successful in 3m12s
wai-quantum CPU vector units / member · vector unit, rvv 128-bit (riscv64, emulated) (pull_request) Successful in 12s
wai-quantum variational and algorithm library / parameters, gradients, optimisers, VQE, QAOA and builders · linux, release (pull_request) Successful in 1m42s
wai-quantum CPU vector units / member · vector unit, sve 2048-bit (aarch64, emulated) (pull_request) Successful in 18s
wai-quantum CPU vector units / member · vector unit, avx2 (x86_64 silicon) (pull_request) Successful in 8s
wai-quantum CPU vector units / member · vector unit, sve 512-bit (aarch64, emulated) (pull_request) Successful in 18s
wai-quantum WebGPU member / member · GPU, Vulkan (jetson-hub) (pull_request) Successful in 23m29s
wai-quantum studio and desktop / studio · browser (pull_request) Successful in 4m13s
wai-quantum verdicts and repairs / the intent set and the verdict under wasm32-wasip2 (wasmtime) (pull_request) Successful in 1m27s
wai-quantum docs, course and locales / every command and snippet in the docs · linux (pull_request) Successful in 20m30s
wai-quantum verdicts and repairs / verdicts, repairs and the intent set · linux (pull_request) Successful in 1m59s
WAI Studio / Studio in Chromium and Firefox · macos (pull_request) Successful in 11m56s
WAI Studio / the catalogue's actions, the unit tests and the core · linux (pull_request) Successful in 1m19s
wai-quantum views in agent hosts / views · the page and its engine (pull_request) Successful in 3m10s
wai-quantum service / service · linux (pull_request) Successful in 6m47s
wai-quantum studio and desktop / desktop app · linux (pull_request) Successful in 6m3s
wai-quantum WebGPU member / member · software Vulkan (linux) (pull_request) Successful in 2m22s
wai-quantum views in agent hosts / views · a scripted host (pull_request) Successful in 4m2s
wai-quantum WebGPU member / shader checks · browser build · wasip2 inertness · MSRV (pull_request) Successful in 4m20s
wai-web reach builds / wai-web reach builds · the package of record, every output as recorded (pull_request) Successful in 2m36s
wai-web wasm32 / wai-web wasm32 build · corpus, menu and writers (pull_request) Successful in 5m47s
wai-sink-swift native sink package / libwai slices, desktop tests, simulator tests · macos (pull_request) Successful in 21m18s
wai-web reach builds / wai-web reach builds · this tree's wai-web, every rung on its engine line (pull_request) Successful in 6m41s
WAI energy receipts / energy receipts · linux (pull_request) Successful in 15m13s
wai-quantum tensor-engine member / member · tensor engine, the kernel toolchain's simulator (linux) (pull_request) Successful in 14m43s
repository checks / lockfiles, advisories, tests in CI, workflow hygiene, spec and section references, public text (pull_request) Successful in 1m13s
WAI Studio / Studio in WebKit · linux (pull_request) Successful in 14m19s
WAI conformance / v2 vocabulary · manifests validate as stated (pull_request) Successful in 16s
WAI conformance / delivery telemetry · CMCD and CMSD against an independent library (pull_request) Successful in 21s
WAI conformance / cross-arch byte-equality · linux-arm64 (pull_request) Successful in 53s
WAI conformance / C2PA manifest emission · signed, read back, validated (pull_request) Successful in 2m56s
WAI examples / WAI examples · android-app · linux-arm64 (pull_request) Successful in 8m7s
standards workspaces build + test / joule-code-rs (joule-code/joule-code-rs, joule-code-rs, linux-arm64, true) (pull_request) Successful in 8m30s
wai-quantum HIP member / member · HIP absent (linux-arm64) (pull_request) Successful in 1m29s
WAI conformance / cargo-class corpora · linux-arm64 (pull_request) Successful in 18m57s
wai-quantum npu-cores member / member · npu-cores absent (linux-arm64) (pull_request) Successful in 29s
wai-quantum pulse and dynamics / the same bits · linux-arm64 (pull_request) Successful in 2m13s
WAI conformance / each feature of the independent verifiers' steps compiles alone (pull_request) Successful in 18m46s
wai-quantum tensor-engine member / member · tensor engine absent (linux-arm64) (pull_request) Successful in 35s
wai-quantum extension points / the registry and the example · linux-arm64 (pull_request) Successful in 2m27s
wai-quantum variational and algorithm library / parameters, gradients, optimisers, VQE, QAOA and builders · linux-arm64, release (pull_request) Successful in 2m38s
wai-sink-android native sink library / the JNI layer and the platform-free half on the host JVM · linux-arm64 (pull_request) Successful in 2m36s
WAI energy receipts / energy receipts · linux-arm64 (pull_request) Successful in 29m24s
WAI conformance / independent verifiers · claims, JWP, key discovery and integer payloads (Python) (pull_request) Successful in 1h3m13s
wai-quantum WebGPU member / member · DX12 and Vulkan (cbio-windows) (pull_request) Successful in 12m51s
wai-quantum studio and desktop / desktop app · windows (pull_request) Successful in 10m40s
wai-quantum-service: a job sent again under its key is the same job
A client that lost an answer could not ask again safely: a second
submission was a second job, counted against its limits. And the three MCP
tools that run declared idempotentHint: true, which was not so.

POST /v1/jobs and POST /v1/run take an Idempotency-Key, and the three tools
an idempotency_key. Sent again with the same key and request, a job is
answered with the key's job, before any limit, counting as no submission;
with another request the key is refused (J034), naming no job. A key names
its job while the job is kept, but for a job the service interrupted, which
the key runs again. Records keep the key's digest with the client's name;
one lock makes concurrent sends of one key one job. The tools' hint is now
false: a call without a key is a new job. Calls without a key are not
matched by their request, since a client is an address and that would give
one person's job id to anyone at the address sending the same program.

The command line and the Python client send each job under a fresh key, and
send it again under it where no answer came back, only to a service that
says it keeps keys. The Python client's wait also ends on an interrupted
job, where it ran to its deadline before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 17:46:09 -05:00

185 lines
8.4 KiB
Python

"""A client for the WAI quantum job service, in the standard library alone.
The public instance is at ``https://wai.transaction.science/quantum-jobs/v1``;
no account and no key. Every result the service returns carries a receipt
sealed with the service's key, and :meth:`Service.verify` checks it here,
offline, with the engine in this package: the network is needed to run a
job, never to trust its answer.
Routes (``/v1/openapi.json`` describes them): ``GET /v1`` the service,
``GET /v1/methods``, ``POST /v1/jobs`` submit, ``GET /v1/jobs/{id}`` a job's
status and result, ``DELETE /v1/jobs/{id}`` cancel, ``POST /v1/run`` submit
and wait.
A job goes under an ``Idempotency-Key``. Where no answer comes back, the
client sends it again under that key, twice at most, if the service says it
keeps keys: a job the service took is then answered, not taken again.
"""
from __future__ import annotations
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from typing import Any, Dict, Mapping, Optional, Tuple, Union
from . import _engine
from ._api import Program, job_request, verify
from ._job import Job, Verification
from .errors import ServiceError
__all__ = ["Service", "DEFAULT_SERVICE", "USER_AGENT"]
#: The public instance. ``$WAI_QUANTUM_SERVICE`` overrides it.
DEFAULT_SERVICE = "https://wai.transaction.science/quantum-jobs"
#: How the client names itself. The service's edge refuses requests that
#: name no client or a generic library's default; this names the package
#: and its version.
USER_AGENT = f"wai-quantum-python/{_engine.__version__}"
_FINISHED = ("done", "failed", "cancelled", "interrupted")
class Service:
"""The job service at ``base`` (``…/quantum-jobs`` or ``…/quantum-jobs/v1``;
by default ``$WAI_QUANTUM_SERVICE`` or the public instance).
``timeout`` bounds each HTTP request, in seconds; waiting for a job is
bounded separately (``wait=`` on :meth:`result` and :meth:`run`).
"""
def __init__(self, base: Optional[str] = None, *, timeout: float = 60.0, user_agent: Optional[str] = None) -> None:
base = (base or os.environ.get("WAI_QUANTUM_SERVICE") or DEFAULT_SERVICE).rstrip("/")
if base.endswith("/v1"):
base = base[: -len("/v1")]
self.base = base
self.timeout = timeout
self.user_agent = user_agent or USER_AGENT
def __repr__(self) -> str:
return f"Service({self.base!r})"
# -- HTTP ---------------------------------------------------------------
def _call(self, method: str, path: str, body: Any = None, extra: Optional[Mapping[str, str]] = None) -> Tuple[int, Any]:
url = f"{self.base}/v1{path}"
data = None if body is None else json.dumps(body, allow_nan=False).encode()
headers = {"User-Agent": self.user_agent, "Accept": "application/json"}
if data is not None:
headers["Content-Type"] = "application/json"
headers.update(extra or {})
req = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(req, timeout=self.timeout) as r:
status, raw = r.status, r.read()
except urllib.error.HTTPError as e:
status, raw = e.code, e.read()
except (urllib.error.URLError, OSError) as e:
reason = getattr(e, "reason", e)
raise ServiceError(f"{url}: {reason}") from e
try:
answer = json.loads(raw) if raw else None
except ValueError:
raise ServiceError(f"{url}: the answer is not JSON", status, raw[:200].decode("utf-8", "replace")) from None
if status >= 400:
why = answer.get("error") if isinstance(answer, dict) else None
raise ServiceError(why or f"{method} {url} failed", status, answer)
return status, answer
# -- the service ----------------------------------------------------------
def describe(self) -> Dict[str, Any]:
"""The service: its methods, its limits and the key it seals with."""
return self._call("GET", "")[1]
def health(self) -> bool:
try:
return self._call("GET", "/health")[1].get("ok") is True
except ServiceError:
return False
def methods(self) -> Any:
return self._call("GET", "/methods")[1]
# -- jobs -------------------------------------------------------------
def submit(self, program: Union[Program, Mapping[str, Any]], *, idempotency_key: Optional[str] = None, **job: Any) -> Dict[str, Any]:
"""Submit a job and return at once: its record, with its ``id`` and
``status`` (``queued`` or ``running``). The other keywords are
:func:`wai_quantum.job_request`'s.
``idempotency_key`` names the submission (1 to 255 visible ASCII
characters, no quote or backslash; make it unguessable): the same
key with the same job is answered with the same job, and with
another job refused (``J034``). Without one, a fresh key is made."""
return self._post("/jobs", job_request(program, **job), idempotency_key)
def status(self, job_id: str) -> Dict[str, Any]:
"""A job's record as it stands: its status, its plan, the request as
submitted, and once it is done its result with the receipt."""
return self._call("GET", f"/jobs/{urllib.parse.quote(job_id, safe='')}")[1]
def cancel(self, job_id: str) -> Dict[str, Any]:
"""Cancel a queued or running job; its record afterwards. A job that
has already finished is refused (``ServiceError``, status 409)."""
return self._call("DELETE", f"/jobs/{urllib.parse.quote(job_id, safe='')}")[1]
def result(self, job_id: str, *, wait: float = 600.0, poll: float = 1.0) -> Job:
"""The job's result, waiting up to ``wait`` seconds for it to finish.
A job that failed or was cancelled raises ``ServiceError`` with the
service's reason; one still running after ``wait`` raises too."""
return self._finish(self.status(job_id), wait, poll)
def run(self, program: Union[Program, Mapping[str, Any]], *, wait: float = 600.0, poll: float = 1.0, idempotency_key: Optional[str] = None, **job: Any) -> Job:
"""Run a job on the service and wait for its result (``POST /v1/run``,
then the job's record while it is still running). ``idempotency_key``
is :meth:`submit`'s."""
return self._finish(self._post("/run", job_request(program, **job), idempotency_key), wait, poll)
def _post(self, path: str, request: Dict[str, Any], key: Optional[str]) -> Dict[str, Any]:
"""A job sent under its key, and sent again under it where no answer
came back and the service keeps keys."""
key = key or uuid.uuid4().hex
sent = 0
while True:
sent += 1
try:
return self._call("POST", path, request, {"Idempotency-Key": key})[1]
except ServiceError as e:
if e.status is not None or sent == 3 or not self._keeps_keys():
raise
time.sleep(sent)
def _keeps_keys(self) -> bool:
"""Whether the service keeps the key a job is sent under."""
try:
return "POST /v1/jobs" in ((self.describe() or {}).get("idempotency") or {}).get("on", [])
except ServiceError:
return False
def _finish(self, record: Dict[str, Any], wait: float, poll: float) -> Job:
deadline = time.monotonic() + wait
while record.get("status") not in _FINISHED:
job_id = record.get("id")
if not job_id:
raise ServiceError("the service answered with no job id", None, record)
if time.monotonic() >= deadline:
raise ServiceError(f"job {job_id} is still {record.get('status')} after {wait:g} s", None, record)
time.sleep(poll)
record = self.status(job_id)
if record["status"] != "done":
raise ServiceError(f"job {record.get('id')} {record['status']}: {record.get('error') or 'no reason given'}", None, record)
return Job(record)
# -- receipts ---------------------------------------------------------
def verify(self, job: Any) -> Verification:
"""Whether a job's receipt seals its request and its result, checked
here, offline (no request is made). Compare its ``key`` with the
service's (``describe()["receipt_key"]``) to know who sealed it."""
return verify(job)