cap-sdk-python 2.16.1__py3-none-any.whl → 2.18.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cap/__init__.py CHANGED
@@ -10,6 +10,7 @@ from .bus import connect_nats
10
10
  from .runtime import Agent, Context, BlobStore, RedisBlobStore, InMemoryBlobStore
11
11
  from .middleware import Middleware, NextFn, logging_middleware
12
12
  from .metrics import MetricsHook, NoopMetrics
13
+ from .outcome import JobFailure
13
14
  from .heartbeat import (
14
15
  heartbeat_payload,
15
16
  heartbeat_payload_with_memory,
@@ -62,6 +63,41 @@ from .production_resource import (
62
63
  validate_resource_ref,
63
64
  validate_resource_ref_compatibility,
64
65
  )
66
+ from .resource_registry import (
67
+ InMemoryResourceBackend,
68
+ InvalidResourceRefError,
69
+ InvalidResourceRegistryError,
70
+ InvalidTrustedResourceContextError,
71
+ ResolvedResource,
72
+ ResourceBackendRegistration,
73
+ ResourceBackendUnavailableError,
74
+ ResourceDigestMismatchError,
75
+ ResourceExpiredError,
76
+ ResourceExternalizeRequest,
77
+ ResourceExternalizerBackend,
78
+ ResourceExternalizerUnavailableError,
79
+ ResourceMediaTypeMismatchError,
80
+ ResourceMetadataMismatchError,
81
+ ResourceRegistry,
82
+ ResourceRegistryError,
83
+ ResourceResolveRequest,
84
+ ResourceResolveResult,
85
+ ResourceResolverBackend,
86
+ ResourceResolverUnavailableError,
87
+ ResourceSizeMismatchError,
88
+ ResourceTooLargeError,
89
+ TrustedResourceContext,
90
+ )
91
+ from .resource_nats_kv import (
92
+ NATS_KV_RESOLVER_ID,
93
+ InvalidNatsKvBucketError,
94
+ InvalidNatsKvURIError,
95
+ NatsKvEntryNotFoundError,
96
+ NatsKvResourceBackend,
97
+ NatsKvResourceError,
98
+ NatsKvStorageError,
99
+ NatsKvTenantMismatchError,
100
+ )
65
101
  from .production_events import (
66
102
  ProductionEventAuthority,
67
103
  ProductionEventConflictError,
@@ -134,6 +170,7 @@ __all__ = [
134
170
  "logging_middleware",
135
171
  "MetricsHook",
136
172
  "NoopMetrics",
173
+ "JobFailure",
137
174
  "heartbeat_payload",
138
175
  "heartbeat_payload_with_memory",
139
176
  "heartbeat_payload_with_progress",
@@ -175,6 +212,37 @@ __all__ = [
175
212
  "canonical_legacy_redis_key",
176
213
  "validate_resource_ref",
177
214
  "validate_resource_ref_compatibility",
215
+ "InMemoryResourceBackend",
216
+ "InvalidResourceRefError",
217
+ "InvalidResourceRegistryError",
218
+ "InvalidTrustedResourceContextError",
219
+ "ResolvedResource",
220
+ "ResourceBackendRegistration",
221
+ "ResourceBackendUnavailableError",
222
+ "ResourceDigestMismatchError",
223
+ "ResourceExpiredError",
224
+ "ResourceExternalizeRequest",
225
+ "ResourceExternalizerBackend",
226
+ "ResourceExternalizerUnavailableError",
227
+ "ResourceMediaTypeMismatchError",
228
+ "ResourceMetadataMismatchError",
229
+ "ResourceRegistry",
230
+ "ResourceRegistryError",
231
+ "ResourceResolveRequest",
232
+ "ResourceResolveResult",
233
+ "ResourceResolverBackend",
234
+ "ResourceResolverUnavailableError",
235
+ "ResourceSizeMismatchError",
236
+ "ResourceTooLargeError",
237
+ "TrustedResourceContext",
238
+ "InvalidNatsKvBucketError",
239
+ "InvalidNatsKvURIError",
240
+ "NATS_KV_RESOLVER_ID",
241
+ "NatsKvEntryNotFoundError",
242
+ "NatsKvResourceBackend",
243
+ "NatsKvResourceError",
244
+ "NatsKvStorageError",
245
+ "NatsKvTenantMismatchError",
178
246
  "ValidationError",
179
247
  "validate_alert",
180
248
  "validate_job_request",
cap/cancel.py ADDED
@@ -0,0 +1,102 @@
1
+ """Internal attempt-local cancellation, after normal packet admission.
2
+
3
+ The entire admitted dispatch must match, including an empty dispatch. Attempts
4
+ sharing a job id remain independent. The unverified peek is routing, not trust.
5
+ Synchronous handlers cannot be pre-empted on the event loop; their result wins.
6
+ Threaded work finishes independently after its terminal result. A handler that
7
+ suppresses cancellation keeps its slot until it returns; its outcome is discarded.
8
+ Closing drains cancel subscriptions. cap.worker.run_worker is unchanged.
9
+ """
10
+ import asyncio
11
+ import math
12
+ import threading
13
+ from copy import deepcopy
14
+ from dataclasses import dataclass, field
15
+ from typing import Dict, List, Optional, Protocol
16
+
17
+ from cap.errors import MalformedPacketError
18
+ from cap.outcome import _Outcome, _enum_number, _error_code
19
+ from cap.packet_boundary import parse_packet
20
+
21
+ _JOB_TIMEOUT = _Outcome(_enum_number("JobStatus", "JOB_STATUS_FAILED"),
22
+ _error_code("JOB_TIMEOUT"), "TIMEOUT", "job deadline exceeded")
23
+ _JOB_CANCELLED = _Outcome(_enum_number("JobStatus", "JOB_STATUS_CANCELLED"),
24
+ _error_code("UNSPECIFIED"), "", "job cancelled")
25
+
26
+
27
+ class _Dispatch(Protocol):
28
+ def SerializeToString(self, *, deterministic: bool = False) -> bytes: ...
29
+
30
+
31
+ class _Cancel(Protocol):
32
+ # Generated protobuf messages have no stubs. Describe only the read surface.
33
+ @property
34
+ def job_id(self) -> str: ...
35
+
36
+ @property
37
+ def dispatch(self) -> _Dispatch: ...
38
+
39
+
40
+ @dataclass(eq=False)
41
+ class RunningAttempt:
42
+ job_id: str
43
+ dispatch: _Dispatch
44
+ stopped: threading.Event = field(default_factory=threading.Event)
45
+ requested: asyncio.Event = field(default_factory=asyncio.Event)
46
+
47
+
48
+ class CancelRegistry:
49
+ def __init__(self) -> None:
50
+ self._running: Dict[str, List[RunningAttempt]] = {}
51
+
52
+ def register(self, job_id: str, dispatch: _Dispatch) -> RunningAttempt:
53
+ snapshot = deepcopy(dispatch)
54
+ attempt = RunningAttempt(job_id, snapshot) # Called inside the running loop.
55
+ self._running.setdefault(job_id, []).append(attempt)
56
+ return attempt
57
+
58
+ def unregister(self, attempt: RunningAttempt) -> None:
59
+ attempts = self._running[attempt.job_id]
60
+ attempts.remove(attempt)
61
+ if not attempts:
62
+ del self._running[attempt.job_id]
63
+
64
+ def is_running(self, job_id: str) -> bool:
65
+ return job_id in self._running
66
+
67
+ def apply(self, cancel: _Cancel) -> int:
68
+ matched = 0
69
+ for attempt in self._running.get(cancel.job_id, ()):
70
+ if attempt.dispatch == cancel.dispatch:
71
+ attempt.requested.set()
72
+ matched += 1
73
+ return matched
74
+
75
+
76
+ def peek_cancel_job_id(payload: bytes) -> str:
77
+ try:
78
+ packet = parse_packet(payload)
79
+ except MalformedPacketError:
80
+ return ""
81
+ return str(packet.job_cancel.job_id) if packet.HasField("job_cancel") else ""
82
+
83
+
84
+ def validate_max_deadline(value: Optional[float]) -> Optional[float]:
85
+ if value is None:
86
+ return None
87
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or value <= 0:
88
+ raise ValueError("max_deadline must be positive and finite, or None")
89
+ try:
90
+ value = float(value)
91
+ except OverflowError as exc:
92
+ raise ValueError("max_deadline must be positive and finite, or None") from exc
93
+ if not math.isfinite(value):
94
+ raise ValueError("max_deadline must be positive and finite, or None")
95
+ return value
96
+
97
+
98
+ def handler_deadline(start: float, deadline_ms: int, maximum: Optional[float]) -> Optional[float]:
99
+ seconds = deadline_ms / 1000 if deadline_ms > 0 else maximum
100
+ if seconds is None:
101
+ return None
102
+ return start + (min(seconds, maximum) if maximum is not None else seconds)
cap/client.py CHANGED
@@ -1,12 +1,22 @@
1
1
  from google.protobuf import timestamp_pb2
2
2
  from cap.pb.cordum.agent.v1 import buspacket_pb2, job_pb2
3
3
  from cryptography.hazmat.primitives.asymmetric import ec
4
- from typing import Optional
4
+ from typing import TYPE_CHECKING, Dict, Optional, Protocol, cast
5
5
 
6
6
 
7
7
  from cap.constants import DEFAULT_PROTOCOL_VERSION
8
8
  from cap.packet_boundary import Publisher, finalize_packet
9
9
  from cap.subjects import SUBJECT_SUBMIT
10
+ from cap.telemetry import ErrorType, Publish, TelemetryConfig, inject_headers, start_publish
11
+
12
+ if TYPE_CHECKING:
13
+ from opentelemetry.context import Context as OtelContext
14
+
15
+
16
+ class _HeaderPublisher(Protocol):
17
+ async def publish(
18
+ self, subject: str, payload: bytes, headers: Optional[Dict[str, str]] = None
19
+ ) -> None: ...
10
20
 
11
21
 
12
22
  async def submit_job(
@@ -17,6 +27,8 @@ async def submit_job(
17
27
  private_key: Optional[ec.EllipticCurvePrivateKey] = None,
18
28
  *,
19
29
  session_token: Optional[str] = None,
30
+ telemetry: Optional[TelemetryConfig] = None,
31
+ context: "Optional[OtelContext]" = None,
20
32
  ) -> None:
21
33
  """Publish a JobRequest onto the CAP submit subject.
22
34
 
@@ -27,6 +39,13 @@ async def submit_job(
27
39
  sender_id: Identity of the sender (used in the BusPacket envelope).
28
40
  private_key: Optional ECDSA private key for signing the packet.
29
41
  session_token: Optional trusted runtime token for the outer envelope.
42
+ telemetry: Optional trace-context configuration. ``None`` sends no
43
+ headers and starts no span. When set, a ``publish sys.job.submit``
44
+ span is started and its W3C trace context is sent in the
45
+ ``traceparent`` and ``tracestate`` headers, so ``nc.publish`` must
46
+ accept a ``headers=`` keyword.
47
+ context: The OpenTelemetry parent context of the publish span; ``None``
48
+ means the current context. Used only when ``telemetry`` is set.
30
49
  """
31
50
  ts = timestamp_pb2.Timestamp()
32
51
  ts.GetCurrentTime()
@@ -40,6 +59,18 @@ async def submit_job(
40
59
  outgoing = finalize_packet(
41
60
  packet, private_key, session_token=session_token
42
61
  )
43
- await nc.publish(
44
- SUBJECT_SUBMIT, outgoing.SerializeToString(deterministic=True)
62
+ data = outgoing.SerializeToString(deterministic=True)
63
+ if telemetry is None:
64
+ await nc.publish(SUBJECT_SUBMIT, data)
65
+ return
66
+ span_context, span = start_publish(
67
+ telemetry, Publish(subject=SUBJECT_SUBMIT, conversation_id=trace_id), context
45
68
  )
69
+ headers = inject_headers(telemetry, None, span_context)
70
+ try:
71
+ await cast(_HeaderPublisher, nc).publish(SUBJECT_SUBMIT, data, headers=headers)
72
+ except Exception:
73
+ span.fail(ErrorType.TRANSPORT_PUBLISH_FAILED)
74
+ raise
75
+ finally:
76
+ span.end()
cap/dispatch_fence.py ADDED
@@ -0,0 +1,121 @@
1
+ """Internal, synchronous dispatch fence for admitted requests with a dispatch.
2
+
3
+ The trust mode determines who can steer this fence; it authenticates nothing.
4
+ Validate the worker and bounded ids before comparing dispatch and request digest.
5
+ An unknown job runs. Exact RUNNING drops; exact DONE replays a recorded result
6
+ or runs again without one. A conflicting digest or stale attempt drops. While
7
+ RUNNING only active+1 may replace it; once DONE any newer attempt may replace it.
8
+ Record bound result bytes and trace id before publishing, only for the matching
9
+ RUNNING entry. finish closes only its own attempt. Replays never record or run.
10
+ The runtime logs fixed reasons and bounded job ids, never request content.
11
+
12
+ This store is in memory, per process, and used only on the event-loop thread.
13
+ Age since the last write and oldest-write-first size eviction make jobs unknown;
14
+ restart or eviction loses deduplication. This is not a durable exactly-once store.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import math
19
+ import time
20
+ from collections import OrderedDict
21
+ from dataclasses import dataclass
22
+ from enum import Enum
23
+ from typing import Callable, Optional, Tuple
24
+
25
+ from cap.resource_registry import MAX_TRUSTED_JOB_ID_BYTES
26
+
27
+ MAX_DISPATCH_ID_BYTES = 128
28
+ DEFAULT_MAX_JOBS, DEFAULT_MAX_AGE = 1024, 3600.0
29
+ Dispatch = Tuple[str, int, str]
30
+ RecordedResult = Tuple[str, bytes]
31
+
32
+
33
+ class FenceDecision(Enum):
34
+ RUN = "run"
35
+ REPLAY = "replay"
36
+ DROP = "drop"
37
+
38
+
39
+ @dataclass
40
+ class _Entry:
41
+ dispatch: Dispatch
42
+ digest: bytes
43
+ written_at: float
44
+ running: bool = True
45
+ result: Optional[RecordedResult] = None
46
+
47
+
48
+ class DispatchFence:
49
+ def __init__(self, max_jobs: int = DEFAULT_MAX_JOBS, max_age: float = DEFAULT_MAX_AGE,
50
+ clock: Callable[[], float] = time.monotonic) -> None:
51
+ if type(max_jobs) is not int or not 1 <= max_jobs <= 1_000_000:
52
+ raise ValueError("dispatch_fence_max_jobs must be an int from 1 to 1000000")
53
+ message = "dispatch_fence_max_age must be positive and finite"
54
+ if isinstance(max_age, bool) or not isinstance(max_age, (int, float)) or max_age <= 0:
55
+ raise ValueError(message)
56
+ try:
57
+ age = float(max_age)
58
+ except OverflowError as exc:
59
+ raise ValueError(message) from exc
60
+ if not math.isfinite(age):
61
+ raise ValueError(message)
62
+ self.max_jobs, self.max_age, self._clock = max_jobs, age, clock
63
+ self._entries: OrderedDict[str, _Entry] = OrderedDict()
64
+
65
+ def admit(self, job_id: str, dispatch: Dispatch, request_digest: bytes, worker_id: str,
66
+ *, replay_only: bool = False) -> Tuple[FenceDecision, str, Optional[RecordedResult]]:
67
+ self._evict()
68
+ reason = ""
69
+ dispatch_id, attempt, assigned_worker_id = dispatch
70
+ if (not 0 < len(dispatch_id.encode("utf-8")) <= MAX_DISPATCH_ID_BYTES
71
+ or attempt < 1 or len(job_id.encode("utf-8")) > MAX_TRUSTED_JOB_ID_BYTES):
72
+ reason = "malformed dispatch"
73
+ elif assigned_worker_id != worker_id:
74
+ reason = "wrong worker"
75
+ entry = self._entries.get(job_id)
76
+ if not reason and entry is not None:
77
+ if dispatch == entry.dispatch:
78
+ if request_digest != entry.digest:
79
+ reason = "conflicting dispatch"
80
+ elif entry.running:
81
+ reason = "in flight"
82
+ elif entry.result is not None:
83
+ return FenceDecision.REPLAY, "recorded result", entry.result
84
+ elif attempt <= entry.dispatch[1]:
85
+ reason = "stale attempt"
86
+ elif entry.running and attempt != entry.dispatch[1] + 1:
87
+ reason = "future attempt"
88
+ if reason or replay_only:
89
+ return FenceDecision.DROP, reason or "unrecorded duplicate", None
90
+ self._write(job_id, _Entry(dispatch, request_digest, self._clock()))
91
+ return FenceDecision.RUN, "new dispatch", None
92
+
93
+ def record(self, job_id: str, dispatch: Dispatch, trace_id: str, result_bytes: bytes) -> bool:
94
+ self._evict()
95
+ entry = self._entries.get(job_id)
96
+ if entry is None or not entry.running or entry.dispatch != dispatch:
97
+ return False
98
+ entry.running, entry.result = False, (trace_id, result_bytes)
99
+ self._write(job_id, entry)
100
+ return True
101
+
102
+ def finish(self, job_id: str, dispatch: Dispatch) -> None:
103
+ self._evict()
104
+ entry = self._entries.get(job_id)
105
+ if entry is not None and entry.running and entry.dispatch == dispatch:
106
+ entry.running = False
107
+ self._write(job_id, entry)
108
+
109
+ def _write(self, job_id: str, entry: _Entry) -> None:
110
+ entry.written_at = self._clock()
111
+ self._entries[job_id] = entry
112
+ self._entries.move_to_end(job_id)
113
+ self._evict()
114
+
115
+ def _evict(self) -> None:
116
+ now = self._clock()
117
+ while self._entries:
118
+ first = next(iter(self._entries.values()))
119
+ if now - first.written_at <= self.max_age and len(self._entries) <= self.max_jobs:
120
+ break
121
+ self._entries.popitem(last=False)
cap/job_events.py ADDED
@@ -0,0 +1,101 @@
1
+ """Internal, event-loop-only hooks for async Agent handlers (not run_worker).
2
+
3
+ Progress awaits its ordered publish. Artifacts require the operator registry;
4
+ slots reserve call order and bounds latch the first fixed failure, even if caught.
5
+ Retries clear slots, not the latch. Hooks close at invocation exit (in the same
6
+ coroutine as the retry loop), terminal publish entry, and request cleanup.
7
+ Closed or unbound Context hooks still validate, but do no I/O. Sync handlers
8
+ cannot await these hooks; callers must await them before the final attempt ends.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from typing import Awaitable, Callable, List, NoReturn, Optional
14
+
15
+ from cap.outcome import JobFailure, _Outcome, _RESOURCE_EXHAUSTED, _failed
16
+ from cap.production_resource import MAX_RESOURCE_MEDIA_TYPE_BYTES, _MEDIA_PATTERN
17
+ from cap.resource_registry import ResourceTooLargeError
18
+
19
+ ARTIFACT_PURPOSE_PREFIX = "job-artifact:"
20
+ MAX_MARKER_BYTES = 256
21
+ _NAME_PATTERN = re.compile(r"[a-z0-9][a-z0-9._-]{0,63}")
22
+ _ARTIFACT_COUNT_EXCEEDED = _failed(_RESOURCE_EXHAUSTED, "artifact count exceeds max")
23
+ _ARTIFACT_TOO_LARGE = _failed(_RESOURCE_EXHAUSTED, "artifact exceeds max size")
24
+ _ARTIFACT_WRITE_FAILED = _failed(_RESOURCE_EXHAUSTED, "artifact write failed")
25
+
26
+
27
+ def check_marker(marker: str) -> None:
28
+ if type(marker) is not str:
29
+ raise TypeError("marker must be a str")
30
+ if not marker.isprintable() or not 1 <= len(marker.encode("utf-8")) <= MAX_MARKER_BYTES:
31
+ raise ValueError("marker must be printable and 1-256 UTF-8 bytes")
32
+
33
+
34
+ def check_artifact(name: str, media_type: str, content: bytes) -> None:
35
+ if type(name) is not str or type(media_type) is not str or type(content) is not bytes:
36
+ raise TypeError("artifact requires str name, str media type and bytes content")
37
+ if _NAME_PATTERN.fullmatch(name) is None:
38
+ raise ValueError("artifact name must match [a-z0-9][a-z0-9._-]{0,63}")
39
+ if (_MEDIA_PATTERN.fullmatch(media_type) is None
40
+ or len(media_type.encode("utf-8")) > MAX_RESOURCE_MEDIA_TYPE_BYTES):
41
+ raise ValueError("artifact media type must be canonical and at most 127 bytes")
42
+ if not content:
43
+ raise ValueError("artifact content must not be empty")
44
+
45
+
46
+ class _JobEvents:
47
+ def __init__(self, publish: Callable[[str], Awaitable[None]],
48
+ externalize: Optional[Callable[[str, str, bytes], Awaitable[object]]],
49
+ max_artifacts: int, max_artifact_bytes: int) -> None:
50
+ self._publish = publish
51
+ self._externalize = externalize
52
+ self._max_artifacts = max_artifacts
53
+ self._max_artifact_bytes = max_artifact_bytes
54
+ self._slots: List[Optional[object]] = []
55
+ self.closed = False
56
+ self.failure: Optional[_Outcome] = None
57
+
58
+ def close(self) -> None:
59
+ self.closed = True
60
+
61
+ def begin_attempt(self) -> None:
62
+ self._slots = []
63
+
64
+ def refs(self) -> List[object]:
65
+ return [ref for ref in self._slots if ref is not None]
66
+
67
+ async def progress(self, marker: str) -> None:
68
+ if self.closed:
69
+ return
70
+ await self._publish(marker)
71
+
72
+ def _latch(self, failure: _Outcome) -> NoReturn:
73
+ if self.failure is None:
74
+ self.failure = failure
75
+ raise JobFailure(_RESOURCE_EXHAUSTED)
76
+
77
+ async def artifact(self, name: str, media_type: str, content: bytes) -> None:
78
+ if self.closed:
79
+ return
80
+ if len(self._slots) >= self._max_artifacts:
81
+ self._latch(_ARTIFACT_COUNT_EXCEEDED)
82
+ if len(content) > self._max_artifact_bytes:
83
+ self._latch(_ARTIFACT_TOO_LARGE)
84
+ slots = self._slots # a late completion cannot fill a subsequent attempt's slots
85
+ index = len(slots)
86
+ slots.append(None)
87
+ failure, ref = None, None
88
+ try:
89
+ if self._externalize is None:
90
+ failure = _ARTIFACT_WRITE_FAILED
91
+ else:
92
+ ref = await self._externalize(name, media_type, content)
93
+ except ResourceTooLargeError:
94
+ failure = _ARTIFACT_TOO_LARGE
95
+ except Exception:
96
+ failure = _ARTIFACT_WRITE_FAILED
97
+ if self.closed:
98
+ return
99
+ if failure is not None:
100
+ self._latch(failure)
101
+ slots[index] = ref
cap/outcome.py ADDED
@@ -0,0 +1,160 @@
1
+ """Typed job outcomes with spec/13 error codes.
2
+
3
+ Handlers raise :class:`JobFailure` to publish a structured failure instead of
4
+ an opaque ``"handler failed"``. The runtime publishes only fixed text from the
5
+ table below, so exception text, input bytes and pointer text never reach a
6
+ published :class:`JobResult` field.
7
+ """
8
+
9
+ import re
10
+ from dataclasses import dataclass
11
+ from functools import partial
12
+ from typing import Callable, Dict, FrozenSet, Mapping, Optional, Tuple, Union
13
+
14
+ from cap.pb.cordum.agent.v1 import job_pb2
15
+
16
+
17
+ def _enum_number(enum_name: str, value_name: str) -> int:
18
+ # The generated module has no stubs; its descriptor is the typed way in.
19
+ number: int = job_pb2.DESCRIPTOR.enum_types_by_name[enum_name].values_by_name[value_name].number
20
+ return number
21
+
22
+
23
+ def _error_code(name: str) -> int:
24
+ return _enum_number("ErrorCode", "ERROR_CODE_" + name)
25
+
26
+
27
+ _STATUS_FAILED = _enum_number("JobStatus", "JOB_STATUS_FAILED")
28
+ _STATUS_RETRYABLE = _enum_number("JobStatus", "JOB_STATUS_FAILED_RETRYABLE")
29
+ _STATUS_FATAL = _enum_number("JobStatus", "JOB_STATUS_FAILED_FATAL")
30
+ _UNSPECIFIED = _error_code("UNSPECIFIED")
31
+ _INVALID_INPUT = _error_code("JOB_INVALID_INPUT")
32
+ _NOT_FOUND = _error_code("JOB_NOT_FOUND")
33
+ _RESOURCE_EXHAUSTED = _error_code("JOB_RESOURCE_EXHAUSTED")
34
+
35
+ _DEFINED_ERROR_CODES: FrozenSet[int] = frozenset(
36
+ value.number for value in job_pb2.DESCRIPTOR.enum_types_by_name["ErrorCode"].values
37
+ ) - {_UNSPECIFIED}
38
+ _APPLICATION_CODES = range(1000, 10000)
39
+ _STRING_CODE = re.compile(r"[A-Z][A-Z0-9_]{0,63}")
40
+
41
+ # spec/13 "Legacy String Mapping": the error_code string older consumers read.
42
+ _LEGACY_ERROR_STRINGS: Mapping[int, str] = {
43
+ _error_code("JOB_TIMEOUT"): "TIMEOUT",
44
+ _error_code("SAFETY_DENIED"): "DENIED",
45
+ _error_code("JOB_PERMISSION_DENIED"): "PERMISSION_DENIED",
46
+ }
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class _Outcome:
51
+ """The spec/13 fields of one published failure. Every field is fixed text."""
52
+
53
+ status: int
54
+ error_code_enum: int
55
+ error_code: str
56
+ error_message: str
57
+
58
+
59
+ def _failed(error_code_enum: int, error_message: str) -> _Outcome:
60
+ return _Outcome(_STATUS_FAILED, error_code_enum, "", error_message)
61
+
62
+
63
+ # The SDK failure table (task-013d478b, comment-e33d348f).
64
+ _CONTEXT_POINTER_INVALID = _failed(_INVALID_INPUT, "context pointer invalid")
65
+ # With a ResourceRegistry the input is JobRequest.context_ref (task-d35bf16f).
66
+ _CONTEXT_REF_REQUIRED = _failed(_INVALID_INPUT, "context ref required")
67
+ _CONTEXT_REF_REFUSED = _failed(_INVALID_INPUT, "context ref refused")
68
+ _CONTEXT_FETCH_FAILED = _failed(_UNSPECIFIED, "context fetch failed")
69
+ _CONTEXT_NOT_FOUND = _failed(_NOT_FOUND, "context not found")
70
+ _CONTEXT_TOO_LARGE = _failed(_RESOURCE_EXHAUSTED, "context exceeds max size")
71
+ _CONTEXT_DECODE_FAILED = _failed(_INVALID_INPUT, "context decode failed")
72
+ _INPUT_INVALID = _failed(_INVALID_INPUT, "input validation failed")
73
+ _HANDLER_FAILED = _failed(_UNSPECIFIED, "handler failed")
74
+ _RESULT_ENCODE_FAILED = _failed(_UNSPECIFIED, "result encode failed")
75
+ _RESULT_TOO_LARGE = _failed(_RESOURCE_EXHAUSTED, "result exceeds max size")
76
+ _RESULT_WRITE_FAILED = _failed(_UNSPECIFIED, "result write failed")
77
+
78
+ _REPORTED_MESSAGE = "handler reported failure"
79
+
80
+
81
+ def _normalize_code(code: Union[int, str]) -> Union[int, str]:
82
+ # Exact-type copies: a subclass cannot carry its own __str__ or enum name.
83
+ if isinstance(code, bool) or not isinstance(code, (int, str)):
84
+ raise TypeError("JobFailure code must be an int or a str")
85
+ if isinstance(code, int):
86
+ value = int.__int__(code)
87
+ if value not in _DEFINED_ERROR_CODES and value not in _APPLICATION_CODES:
88
+ raise ValueError(
89
+ "JobFailure int code must be a defined ErrorCode other than "
90
+ "UNSPECIFIED, or an application code in 1000-9999"
91
+ )
92
+ return value
93
+ text = str.__str__(code)
94
+ if _STRING_CODE.fullmatch(text) is None:
95
+ raise ValueError("JobFailure str code must match [A-Z][A-Z0-9_]{0,63}")
96
+ return text
97
+
98
+
99
+ class JobFailure(Exception):
100
+ """Raise from a handler or middleware to publish a typed spec/13 failure.
101
+
102
+ ``code`` is an ``ErrorCode`` value (or an application code in 1000-9999),
103
+ which sets ``error_code_enum``, or an upper-snake string, which sets
104
+ ``error_code``. ``retryable`` selects the status: ``None`` publishes
105
+ ``JOB_STATUS_FAILED``, ``True`` ``JOB_STATUS_FAILED_RETRYABLE`` and
106
+ ``False`` ``JOB_STATUS_FAILED_FATAL``. The SDK never retries a
107
+ ``JobFailure``, and its ``error_message`` is always the fixed
108
+ ``"handler reported failure"``.
109
+ """
110
+
111
+ def __init__(self, code: Union[int, str], *, retryable: Optional[bool] = None) -> None:
112
+ normalized = _normalize_code(code)
113
+ if retryable is not None and not isinstance(retryable, bool):
114
+ raise TypeError("JobFailure retryable must be None or a bool")
115
+ super().__init__("job failure: %s" % normalized)
116
+ self._code = normalized
117
+ self._retryable = retryable
118
+ # Name-mangled so a subclass attribute cannot replace what is published.
119
+ self.__outcome = _Outcome(
120
+ _status_for(retryable),
121
+ normalized if isinstance(normalized, int) else _UNSPECIFIED,
122
+ normalized if isinstance(normalized, str) else _LEGACY_ERROR_STRINGS.get(normalized, ""),
123
+ _REPORTED_MESSAGE,
124
+ )
125
+
126
+ def __reduce__(self) -> Tuple[Callable[..., "JobFailure"], Tuple[Union[int, str]], Dict[str, object]]:
127
+ # The default rebuilds from args (the fixed text), which is not a valid code.
128
+ return partial(type(self), retryable=self._retryable), (self._code,), dict(vars(self))
129
+
130
+ @property
131
+ def code(self) -> Union[int, str]:
132
+ return self._code
133
+
134
+ @property
135
+ def retryable(self) -> Optional[bool]:
136
+ return self._retryable
137
+
138
+ @property
139
+ def status(self) -> int:
140
+ return self.__outcome.status
141
+
142
+ @property
143
+ def error_code_enum(self) -> int:
144
+ return self.__outcome.error_code_enum
145
+
146
+ @property
147
+ def error_code(self) -> str:
148
+ return self.__outcome.error_code
149
+
150
+
151
+ def _status_for(retryable: Optional[bool]) -> int:
152
+ if retryable is None:
153
+ return _STATUS_FAILED
154
+ return _STATUS_RETRYABLE if retryable else _STATUS_FATAL
155
+
156
+
157
+ def _failure_outcome(failure: JobFailure) -> _Outcome:
158
+ """The validated outcome; a JobFailure that skipped __init__ fails closed."""
159
+ outcome = vars(failure).get("_JobFailure__outcome")
160
+ return outcome if isinstance(outcome, _Outcome) else _HANDLER_FAILED
@@ -17,6 +17,13 @@ MAX_RESOURCE_PURPOSE_BYTES = 128
17
17
  MAX_RESOURCE_SIZE_BYTES = 1 << 30
18
18
  MAX_LEGACY_REDIS_KEY_BYTES = 1024
19
19
 
20
+ _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
21
+ # google.protobuf.Timestamp range: 0001-01-01T00:00:00Z through
22
+ # 9999-12-31T23:59:59.999999999Z, exactly Go timestamppb.CheckValid.
23
+ _MIN_TIMESTAMP_SECONDS = -62_135_596_800
24
+ _MAX_TIMESTAMP_SECONDS = 253_402_300_799
25
+ _NANOS_PER_SECOND = 1_000_000_000
26
+
20
27
  _ID_PATTERN = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
21
28
  _PURPOSE_PATTERN = re.compile(r"^[a-z0-9][a-z0-9._:-]*$")
22
29
  _MEDIA_PATTERN = re.compile(r"^[a-z0-9][a-z0-9!#$&^_.+-]*/[a-z0-9][a-z0-9!#$&^_.+-]*$")
@@ -107,13 +114,15 @@ def _validate_expiry(ref: ResourceRef, now: datetime) -> None:
107
114
  raise ResourceRefValidationError("validation time must be timezone-aware")
108
115
  if not ref.HasField("expires_at"):
109
116
  raise ResourceRefValidationError("resource expiry is required")
110
- if ref.expires_at.nanos < 0 or ref.expires_at.nanos >= 1_000_000_000:
117
+ seconds, nanos = ref.expires_at.seconds, ref.expires_at.nanos
118
+ if not (_MIN_TIMESTAMP_SECONDS <= seconds <= _MAX_TIMESTAMP_SECONDS
119
+ and 0 <= nanos < _NANOS_PER_SECOND):
111
120
  raise ResourceRefValidationError("resource expiry timestamp is invalid")
112
- try:
113
- expiry = ref.expires_at.ToDatetime(tzinfo=timezone.utc)
114
- except (OverflowError, ValueError) as exc:
115
- raise ResourceRefValidationError("resource expiry timestamp is invalid") from exc
116
- if expiry <= now.astimezone(timezone.utc):
121
+ # ToDatetime truncates nanoseconds; aware subtraction avoids astimezone's
122
+ # overflow at datetime.min/max. timedelta normalizes to floor seconds with
123
+ # non-negative subseconds, so this is exact like Go AsTime().After(now).
124
+ elapsed = now - _EPOCH
125
+ if (seconds, nanos) <= (elapsed.days * 86_400 + elapsed.seconds, elapsed.microseconds * 1_000):
117
126
  raise ResourceRefValidationError("resource expiry is not in the future")
118
127
 
119
128