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 +68 -0
- cap/cancel.py +102 -0
- cap/client.py +34 -3
- cap/dispatch_fence.py +121 -0
- cap/job_events.py +101 -0
- cap/outcome.py +160 -0
- cap/production_resource.py +15 -6
- cap/resource_nats_kv.py +196 -0
- cap/resource_registry.py +360 -0
- cap/runtime.py +662 -120
- cap/telemetry.py +366 -0
- cap/testing.py +36 -2
- cap_sdk_python-2.18.0.dist-info/METADATA +700 -0
- {cap_sdk_python-2.16.1.dist-info → cap_sdk_python-2.18.0.dist-info}/RECORD +17 -10
- cap_sdk_python-2.16.1.dist-info/METADATA +0 -414
- {cap_sdk_python-2.16.1.dist-info → cap_sdk_python-2.18.0.dist-info}/WHEEL +0 -0
- {cap_sdk_python-2.16.1.dist-info → cap_sdk_python-2.18.0.dist-info}/licenses/LICENSE +0 -0
- {cap_sdk_python-2.16.1.dist-info → cap_sdk_python-2.18.0.dist-info}/top_level.txt +0 -0
cap/resource_nats_kv.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""Content-addressed JetStream KV ResourceRef backend ("nats-kv").
|
|
2
|
+
|
|
3
|
+
The URI is ``nats-kv://<bucket>/<tenant>/<sha256hex>``, with the trusted tenant
|
|
4
|
+
verbatim and a 64-character lowercase hexadecimal SHA-256 digest. The KV key is
|
|
5
|
+
``hex(tenant) + "." + sha256hex + "." + hex(media_type)``, in lowercase
|
|
6
|
+
hexadecimal of the bytes; the value is the raw content, with no header or
|
|
7
|
+
envelope. Media types have separate keys, so the same bytes stored with two
|
|
8
|
+
media types never overwrite each other. This is the storage format of the Go
|
|
9
|
+
backend ``internal/resourcekv``, byte for byte, and
|
|
10
|
+
``internal/resourcekv/testdata/golden-entry.json`` is the shared parity fixture.
|
|
11
|
+
|
|
12
|
+
Operators provision the bucket (history 1 suffices) with ``max_value_size``
|
|
13
|
+
between 1 byte and 1 GiB; it becomes the registration's ``max_bytes``, and an
|
|
14
|
+
unbounded bucket is refused. Set ``max_age`` to at least the longest reference
|
|
15
|
+
lifetime and keep the server's max_payload at or above ``max_value_size``.
|
|
16
|
+
Entries have no per-entry TTL. The connection, credentials and bucket come from
|
|
17
|
+
the operator; no ResourceRef chooses them. The registry still runs every
|
|
18
|
+
generic check before and after each call.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import hashlib
|
|
23
|
+
import hmac
|
|
24
|
+
import re
|
|
25
|
+
from typing import TYPE_CHECKING
|
|
26
|
+
|
|
27
|
+
from nats.js.errors import KeyDeletedError, KeyNotFoundError
|
|
28
|
+
|
|
29
|
+
from .pb.cordum.agent.v1.job_pb2 import ResourceRef
|
|
30
|
+
from .production_resource import MAX_RESOURCE_AUTHORITY_BYTES, MAX_RESOURCE_SIZE_BYTES
|
|
31
|
+
from .resource_registry import (
|
|
32
|
+
ResourceBackendRegistration,
|
|
33
|
+
ResourceDigestMismatchError,
|
|
34
|
+
ResourceExternalizeRequest,
|
|
35
|
+
ResourceResolveRequest,
|
|
36
|
+
ResourceResolveResult,
|
|
37
|
+
ResourceSizeMismatchError,
|
|
38
|
+
ResourceTooLargeError,
|
|
39
|
+
_timestamp,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
if TYPE_CHECKING:
|
|
43
|
+
from nats.js.kv import KeyValue
|
|
44
|
+
|
|
45
|
+
NATS_KV_RESOLVER_ID = "nats-kv"
|
|
46
|
+
_URI_PREFIX = "nats-kv://"
|
|
47
|
+
_BUCKET_PATTERN = re.compile(r"[A-Za-z0-9_-]+")
|
|
48
|
+
_DIGEST_PATTERN = re.compile(r"[0-9a-f]{64}")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class NatsKvResourceError(Exception):
|
|
52
|
+
message = "cap: nats-kv resource error"
|
|
53
|
+
|
|
54
|
+
def __init__(self) -> None:
|
|
55
|
+
super().__init__(self.message)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class InvalidNatsKvBucketError(NatsKvResourceError):
|
|
59
|
+
message = "cap: invalid or unbounded nats-kv bucket"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class InvalidNatsKvURIError(NatsKvResourceError):
|
|
63
|
+
message = "cap: invalid nats-kv URI"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class NatsKvTenantMismatchError(NatsKvResourceError):
|
|
67
|
+
message = "cap: nats-kv tenant mismatch"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class NatsKvEntryNotFoundError(NatsKvResourceError):
|
|
71
|
+
message = "cap: nats-kv entry not found"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class NatsKvStorageError(NatsKvResourceError):
|
|
75
|
+
"""A storage failure. The message never carries backend error text."""
|
|
76
|
+
|
|
77
|
+
message = "cap: nats-kv storage unavailable"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _entry_key(tenant: str, digest: str, media_type: str) -> str:
|
|
81
|
+
return tenant.encode("utf-8").hex() + "." + digest + "." + media_type.encode("utf-8").hex()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class NatsKvResourceBackend:
|
|
85
|
+
"""Resolver and externalizer over one operator-provisioned JetStream KV bucket.
|
|
86
|
+
|
|
87
|
+
Build it with :meth:`open`. It is immutable afterwards, and the KV handle
|
|
88
|
+
must be usable from the event loop that calls the registry.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
__slots__ = ("_kv", "_bucket", "_max_bytes")
|
|
92
|
+
|
|
93
|
+
def __init__(self, kv: KeyValue, bucket: str, max_bytes: int) -> None:
|
|
94
|
+
if (kv is None or not isinstance(bucket, str)
|
|
95
|
+
or len(bucket) > MAX_RESOURCE_AUTHORITY_BYTES
|
|
96
|
+
or _BUCKET_PATTERN.fullmatch(bucket) is None
|
|
97
|
+
or type(max_bytes) is not int
|
|
98
|
+
or not 0 < max_bytes <= MAX_RESOURCE_SIZE_BYTES):
|
|
99
|
+
raise InvalidNatsKvBucketError()
|
|
100
|
+
self._kv = kv
|
|
101
|
+
self._bucket = bucket
|
|
102
|
+
self._max_bytes = max_bytes
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
async def open(cls, kv: KeyValue) -> NatsKvResourceBackend:
|
|
106
|
+
"""Validate the bucket and snapshot its ``max_value_size`` as the bound."""
|
|
107
|
+
if kv is None:
|
|
108
|
+
raise InvalidNatsKvBucketError()
|
|
109
|
+
try:
|
|
110
|
+
status = await kv.status()
|
|
111
|
+
except Exception as exc:
|
|
112
|
+
raise NatsKvStorageError() from exc
|
|
113
|
+
bucket = getattr(status, "bucket", None)
|
|
114
|
+
config = getattr(getattr(status, "stream_info", None), "config", None)
|
|
115
|
+
bound = getattr(config, "max_msg_size", None)
|
|
116
|
+
if not isinstance(bucket, str) or not isinstance(bound, int):
|
|
117
|
+
raise InvalidNatsKvBucketError()
|
|
118
|
+
return cls(kv, bucket, bound)
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def bucket(self) -> str:
|
|
122
|
+
return self._bucket
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def max_bytes(self) -> int:
|
|
126
|
+
return self._max_bytes
|
|
127
|
+
|
|
128
|
+
def registration(self) -> ResourceBackendRegistration:
|
|
129
|
+
"""The paired resolver and externalizer for ``ResourceRegistry``."""
|
|
130
|
+
return ResourceBackendRegistration(NATS_KV_RESOLVER_ID, self._max_bytes, self, self)
|
|
131
|
+
|
|
132
|
+
async def resolve(self, request: ResourceResolveRequest) -> ResourceResolveResult:
|
|
133
|
+
"""Fetch only from this bucket and the trusted tenant's key."""
|
|
134
|
+
tenant = request.trusted_context.tenant_id
|
|
135
|
+
digest = self._uri_digest(request.uri, tenant)
|
|
136
|
+
try:
|
|
137
|
+
entry = await self._kv.get(_entry_key(tenant, digest, request.media_type))
|
|
138
|
+
except (KeyNotFoundError, KeyDeletedError):
|
|
139
|
+
raise NatsKvEntryNotFoundError() from None
|
|
140
|
+
except Exception as exc:
|
|
141
|
+
raise NatsKvStorageError() from exc
|
|
142
|
+
value = getattr(entry, "value", None)
|
|
143
|
+
if not isinstance(value, (bytes, bytearray)):
|
|
144
|
+
raise NatsKvStorageError()
|
|
145
|
+
return ResourceResolveResult(bytes(value), request.media_type)
|
|
146
|
+
|
|
147
|
+
def _uri_digest(self, uri: str, tenant: str) -> str:
|
|
148
|
+
if not isinstance(uri, str) or not uri.startswith(_URI_PREFIX):
|
|
149
|
+
raise InvalidNatsKvURIError()
|
|
150
|
+
parts = uri[len(_URI_PREFIX):].split("/")
|
|
151
|
+
if len(parts) != 3 or parts[0] != self._bucket or not parts[1]:
|
|
152
|
+
raise InvalidNatsKvURIError()
|
|
153
|
+
if parts[1] != tenant:
|
|
154
|
+
raise NatsKvTenantMismatchError()
|
|
155
|
+
if _DIGEST_PATTERN.fullmatch(parts[2]) is None:
|
|
156
|
+
raise InvalidNatsKvURIError()
|
|
157
|
+
return parts[2]
|
|
158
|
+
|
|
159
|
+
async def externalize(self, request: ResourceExternalizeRequest) -> ResourceRef:
|
|
160
|
+
"""Write content-addressed raw bytes and return the reference."""
|
|
161
|
+
content = bytes(request.content)
|
|
162
|
+
if len(content) != request.size_bytes:
|
|
163
|
+
raise ResourceSizeMismatchError()
|
|
164
|
+
if not hmac.compare_digest(hashlib.sha256(content).digest(), request.sha256):
|
|
165
|
+
raise ResourceDigestMismatchError()
|
|
166
|
+
if request.size_bytes > self._max_bytes:
|
|
167
|
+
raise ResourceTooLargeError()
|
|
168
|
+
tenant = request.trusted_context.tenant_id
|
|
169
|
+
if ".." in tenant:
|
|
170
|
+
raise InvalidNatsKvURIError()
|
|
171
|
+
digest = request.sha256.hex()
|
|
172
|
+
try:
|
|
173
|
+
await self._kv.put(_entry_key(tenant, digest, request.media_type), content)
|
|
174
|
+
except Exception as exc:
|
|
175
|
+
raise NatsKvStorageError() from exc
|
|
176
|
+
return ResourceRef(
|
|
177
|
+
resolver_id=NATS_KV_RESOLVER_ID,
|
|
178
|
+
uri=_URI_PREFIX + self._bucket + "/" + tenant + "/" + digest,
|
|
179
|
+
sha256=request.sha256,
|
|
180
|
+
media_type=request.media_type,
|
|
181
|
+
size_bytes=request.size_bytes,
|
|
182
|
+
expires_at=_timestamp(request.expires_at),
|
|
183
|
+
purpose=request.purpose,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
__all__ = [
|
|
188
|
+
"InvalidNatsKvBucketError",
|
|
189
|
+
"InvalidNatsKvURIError",
|
|
190
|
+
"NATS_KV_RESOLVER_ID",
|
|
191
|
+
"NatsKvEntryNotFoundError",
|
|
192
|
+
"NatsKvResourceBackend",
|
|
193
|
+
"NatsKvResourceError",
|
|
194
|
+
"NatsKvStorageError",
|
|
195
|
+
"NatsKvTenantMismatchError",
|
|
196
|
+
]
|
cap/resource_registry.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
"""Fail-closed ResourceRef operations through operator-installed backends."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import hmac
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from types import MappingProxyType
|
|
10
|
+
from typing import Callable, Dict, Mapping, Optional, Protocol, Sequence, Tuple
|
|
11
|
+
|
|
12
|
+
from google.protobuf.timestamp_pb2 import Timestamp
|
|
13
|
+
|
|
14
|
+
from .pb.cordum.agent.v1.job_pb2 import ResourceRef
|
|
15
|
+
from .production_resource import (
|
|
16
|
+
MAX_RESOURCE_IDENTIFIER_BYTES, MAX_RESOURCE_MEDIA_TYPE_BYTES,
|
|
17
|
+
MAX_RESOURCE_PURPOSE_BYTES, MAX_RESOURCE_SIZE_BYTES, ResourceRefValidationError,
|
|
18
|
+
_ID_PATTERN, _MEDIA_PATTERN, _PURPOSE_PATTERN, validate_resource_ref,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
MAX_TRUSTED_TENANT_ID_BYTES = 128
|
|
22
|
+
MAX_TRUSTED_JOB_ID_BYTES = 256
|
|
23
|
+
_TENANT_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")
|
|
24
|
+
_JOB_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:@\-\[\]]*")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ResourceRegistryError(Exception):
|
|
28
|
+
message = "cap: resource registry error"
|
|
29
|
+
|
|
30
|
+
def __init__(self) -> None:
|
|
31
|
+
super().__init__(self.message)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class InvalidResourceRegistryError(ResourceRegistryError):
|
|
35
|
+
message = "cap: invalid resource registry"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class InvalidTrustedResourceContextError(ResourceRegistryError):
|
|
39
|
+
message = "cap: invalid trusted resource context"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class InvalidResourceRefError(ResourceRegistryError):
|
|
43
|
+
message = "cap: invalid production resource reference"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class ResourceResolverUnavailableError(ResourceRegistryError):
|
|
47
|
+
message = "cap: resource resolver unavailable"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ResourceExternalizerUnavailableError(ResourceRegistryError):
|
|
51
|
+
message = "cap: resource externalizer unavailable"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ResourceBackendUnavailableError(ResourceRegistryError):
|
|
55
|
+
message = "cap: resource backend unavailable"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class ResourceExpiredError(ResourceRegistryError):
|
|
59
|
+
message = "cap: resource expired"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class ResourceTooLargeError(ResourceRegistryError):
|
|
63
|
+
message = "cap: resource exceeds installed limit"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class ResourceSizeMismatchError(ResourceRegistryError):
|
|
67
|
+
message = "cap: resource size mismatch"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ResourceMediaTypeMismatchError(ResourceRegistryError):
|
|
71
|
+
message = "cap: resource media type mismatch"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class ResourceDigestMismatchError(ResourceRegistryError):
|
|
75
|
+
message = "cap: resource digest mismatch"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class ResourceMetadataMismatchError(ResourceRegistryError):
|
|
79
|
+
message = "cap: externalized resource metadata mismatch"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True)
|
|
83
|
+
class TrustedResourceContext:
|
|
84
|
+
tenant_id: str
|
|
85
|
+
job_id: str
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True)
|
|
89
|
+
class ResourceResolveRequest:
|
|
90
|
+
trusted_context: TrustedResourceContext
|
|
91
|
+
uri: str
|
|
92
|
+
media_type: str
|
|
93
|
+
purpose: str
|
|
94
|
+
declared_size_bytes: int
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass(frozen=True)
|
|
98
|
+
class ResourceResolveResult:
|
|
99
|
+
content: bytes
|
|
100
|
+
media_type: str
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True)
|
|
104
|
+
class ResolvedResource:
|
|
105
|
+
content: bytes
|
|
106
|
+
media_type: str
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass(frozen=True)
|
|
110
|
+
class ResourceExternalizeRequest:
|
|
111
|
+
trusted_context: TrustedResourceContext
|
|
112
|
+
content: bytes
|
|
113
|
+
media_type: str
|
|
114
|
+
purpose: str
|
|
115
|
+
expires_at: datetime
|
|
116
|
+
size_bytes: int
|
|
117
|
+
sha256: bytes
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class ResourceResolverBackend(Protocol):
|
|
121
|
+
async def resolve(self, request: ResourceResolveRequest) -> ResourceResolveResult: ...
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class ResourceExternalizerBackend(Protocol):
|
|
125
|
+
async def externalize(self, request: ResourceExternalizeRequest) -> ResourceRef: ...
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@dataclass(frozen=True)
|
|
129
|
+
class ResourceBackendRegistration:
|
|
130
|
+
id: str
|
|
131
|
+
max_bytes: int
|
|
132
|
+
resolver: ResourceResolverBackend
|
|
133
|
+
externalizer: ResourceExternalizerBackend
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _matches(value: str, limit: int, pattern: re.Pattern[str]) -> bool:
|
|
137
|
+
return isinstance(value, str) and len(value) <= limit and pattern.fullmatch(value) is not None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _validate_trusted(trusted: TrustedResourceContext) -> None:
|
|
141
|
+
if (not isinstance(trusted, TrustedResourceContext)
|
|
142
|
+
or not _matches(trusted.tenant_id, MAX_TRUSTED_TENANT_ID_BYTES, _TENANT_PATTERN)
|
|
143
|
+
or not _matches(trusted.job_id, MAX_TRUSTED_JOB_ID_BYTES, _JOB_PATTERN)):
|
|
144
|
+
raise InvalidTrustedResourceContextError()
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _snapshot(ref: ResourceRef) -> ResourceRef:
|
|
148
|
+
if not isinstance(ref, ResourceRef):
|
|
149
|
+
raise InvalidResourceRefError()
|
|
150
|
+
snapshot = ResourceRef()
|
|
151
|
+
snapshot.CopyFrom(ref)
|
|
152
|
+
original = snapshot.SerializeToString(deterministic=True)
|
|
153
|
+
snapshot.DiscardUnknownFields()
|
|
154
|
+
if original != snapshot.SerializeToString(deterministic=True):
|
|
155
|
+
raise InvalidResourceRefError()
|
|
156
|
+
return snapshot
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _utc(value: datetime) -> Optional[datetime]:
|
|
160
|
+
try:
|
|
161
|
+
if isinstance(value, datetime) and value.utcoffset() is not None:
|
|
162
|
+
return value.astimezone(timezone.utc)
|
|
163
|
+
except (OverflowError, ValueError):
|
|
164
|
+
pass
|
|
165
|
+
return None
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _timestamp(value: datetime) -> Timestamp:
|
|
169
|
+
result = Timestamp()
|
|
170
|
+
result.FromDatetime(value.astimezone(timezone.utc))
|
|
171
|
+
return result
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _expired(ref: ResourceRef, now: datetime) -> bool:
|
|
175
|
+
if not ref.HasField("expires_at") or not 0 <= ref.expires_at.nanos < 10**9:
|
|
176
|
+
return False
|
|
177
|
+
try:
|
|
178
|
+
ref.expires_at.ToDatetime(tzinfo=timezone.utc)
|
|
179
|
+
except (OverflowError, ValueError):
|
|
180
|
+
return False
|
|
181
|
+
stamp = _timestamp(now)
|
|
182
|
+
return (ref.expires_at.seconds, ref.expires_at.nanos) <= (stamp.seconds, stamp.nanos)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _generic_valid(ref: ResourceRef, ids: Sequence[str], now: datetime) -> bool:
|
|
186
|
+
try:
|
|
187
|
+
validate_resource_ref(ref, ids, now=now)
|
|
188
|
+
except ResourceRefValidationError:
|
|
189
|
+
return False
|
|
190
|
+
return True
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _externalized_snapshot(ref: ResourceRef, backend_id: str,
|
|
194
|
+
request: ResourceExternalizeRequest, stamp: Timestamp) -> ResourceRef:
|
|
195
|
+
if not isinstance(ref, ResourceRef):
|
|
196
|
+
raise ResourceMetadataMismatchError()
|
|
197
|
+
snapshot = _snapshot(ref)
|
|
198
|
+
if (snapshot.resolver_id != backend_id or snapshot.media_type != request.media_type
|
|
199
|
+
or snapshot.purpose != request.purpose or snapshot.size_bytes != request.size_bytes
|
|
200
|
+
or not hmac.compare_digest(snapshot.sha256, request.sha256)
|
|
201
|
+
or not snapshot.HasField("expires_at")
|
|
202
|
+
or snapshot.expires_at.seconds != stamp.seconds or snapshot.expires_at.nanos != stamp.nanos):
|
|
203
|
+
raise ResourceMetadataMismatchError()
|
|
204
|
+
return snapshot
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class ResourceRegistry:
|
|
208
|
+
"""Snapshot of installed backends; backend reads must honor declared_size_bytes."""
|
|
209
|
+
__slots__ = ("_backends", "_now")
|
|
210
|
+
|
|
211
|
+
def __init__(self, registrations: Sequence[ResourceBackendRegistration], *,
|
|
212
|
+
now: Optional[Callable[[], datetime]] = None) -> None:
|
|
213
|
+
backends: Dict[str, ResourceBackendRegistration] = {}
|
|
214
|
+
for item in registrations:
|
|
215
|
+
if (not isinstance(item, ResourceBackendRegistration)
|
|
216
|
+
or not _matches(item.id, MAX_RESOURCE_IDENTIFIER_BYTES, _ID_PATTERN)
|
|
217
|
+
or type(item.max_bytes) is not int
|
|
218
|
+
or not 0 < item.max_bytes <= MAX_RESOURCE_SIZE_BYTES
|
|
219
|
+
or not callable(getattr(item.resolver, "resolve", None))
|
|
220
|
+
or not callable(getattr(item.externalizer, "externalize", None))
|
|
221
|
+
or item.id in backends):
|
|
222
|
+
raise InvalidResourceRegistryError()
|
|
223
|
+
backends[item.id] = item
|
|
224
|
+
if not backends:
|
|
225
|
+
raise InvalidResourceRegistryError()
|
|
226
|
+
self._backends: Mapping[str, ResourceBackendRegistration] = MappingProxyType(backends)
|
|
227
|
+
self._now = now if now is not None else lambda: datetime.now(timezone.utc)
|
|
228
|
+
|
|
229
|
+
@property
|
|
230
|
+
def backend_ids(self) -> Tuple[str, ...]:
|
|
231
|
+
return tuple(self._backends)
|
|
232
|
+
|
|
233
|
+
def _current_time(self) -> datetime:
|
|
234
|
+
now = _utc(self._now())
|
|
235
|
+
if now is None:
|
|
236
|
+
raise InvalidResourceRegistryError()
|
|
237
|
+
return now
|
|
238
|
+
|
|
239
|
+
async def resolve(self, ref: ResourceRef, trusted: TrustedResourceContext) -> ResolvedResource:
|
|
240
|
+
_validate_trusted(trusted)
|
|
241
|
+
snapshot = _snapshot(ref)
|
|
242
|
+
now = self._current_time()
|
|
243
|
+
if not _generic_valid(snapshot, [snapshot.resolver_id], now):
|
|
244
|
+
if _expired(snapshot, now):
|
|
245
|
+
raise ResourceExpiredError()
|
|
246
|
+
raise InvalidResourceRefError()
|
|
247
|
+
backend = self._backends.get(snapshot.resolver_id)
|
|
248
|
+
if backend is None:
|
|
249
|
+
raise ResourceResolverUnavailableError()
|
|
250
|
+
if snapshot.size_bytes > backend.max_bytes:
|
|
251
|
+
raise ResourceTooLargeError()
|
|
252
|
+
request = ResourceResolveRequest(trusted, snapshot.uri, snapshot.media_type,
|
|
253
|
+
snapshot.purpose, snapshot.size_bytes)
|
|
254
|
+
result = None
|
|
255
|
+
try:
|
|
256
|
+
result = await backend.resolver.resolve(request)
|
|
257
|
+
except Exception:
|
|
258
|
+
pass
|
|
259
|
+
if not isinstance(result, ResourceResolveResult) or type(result.content) is not bytes:
|
|
260
|
+
raise ResourceBackendUnavailableError()
|
|
261
|
+
if len(result.content) > snapshot.size_bytes:
|
|
262
|
+
raise ResourceTooLargeError()
|
|
263
|
+
if _expired(snapshot, self._current_time()):
|
|
264
|
+
raise ResourceExpiredError()
|
|
265
|
+
if result.media_type != snapshot.media_type:
|
|
266
|
+
raise ResourceMediaTypeMismatchError()
|
|
267
|
+
if len(result.content) != snapshot.size_bytes:
|
|
268
|
+
raise ResourceSizeMismatchError()
|
|
269
|
+
if not hmac.compare_digest(hashlib.sha256(result.content).digest(), snapshot.sha256):
|
|
270
|
+
raise ResourceDigestMismatchError()
|
|
271
|
+
return ResolvedResource(result.content, result.media_type)
|
|
272
|
+
|
|
273
|
+
async def externalize(self, backend_id: str, content: bytes, *, media_type: str,
|
|
274
|
+
purpose: str, expires_at: datetime,
|
|
275
|
+
trusted: TrustedResourceContext) -> ResourceRef:
|
|
276
|
+
_validate_trusted(trusted)
|
|
277
|
+
backend = self._backends.get(backend_id) if isinstance(backend_id, str) else None
|
|
278
|
+
if backend is None:
|
|
279
|
+
raise ResourceExternalizerUnavailableError()
|
|
280
|
+
if (not _matches(media_type, MAX_RESOURCE_MEDIA_TYPE_BYTES, _MEDIA_PATTERN)
|
|
281
|
+
or not _matches(purpose, MAX_RESOURCE_PURPOSE_BYTES, _PURPOSE_PATTERN)):
|
|
282
|
+
raise InvalidResourceRefError()
|
|
283
|
+
expiry = _utc(expires_at)
|
|
284
|
+
if expiry is None:
|
|
285
|
+
raise InvalidResourceRefError()
|
|
286
|
+
stamp = _timestamp(expiry)
|
|
287
|
+
validated_at = self._current_time()
|
|
288
|
+
if expiry <= validated_at:
|
|
289
|
+
raise ResourceExpiredError()
|
|
290
|
+
if type(content) is not bytes:
|
|
291
|
+
raise ResourceBackendUnavailableError()
|
|
292
|
+
if len(content) > backend.max_bytes:
|
|
293
|
+
raise ResourceTooLargeError()
|
|
294
|
+
if not content:
|
|
295
|
+
raise ResourceSizeMismatchError()
|
|
296
|
+
request = ResourceExternalizeRequest(trusted, content, media_type, purpose,
|
|
297
|
+
expiry, len(content), hashlib.sha256(content).digest())
|
|
298
|
+
failed = False
|
|
299
|
+
ref = None
|
|
300
|
+
try:
|
|
301
|
+
ref = await backend.externalizer.externalize(request)
|
|
302
|
+
except Exception:
|
|
303
|
+
failed = True
|
|
304
|
+
if failed:
|
|
305
|
+
raise ResourceBackendUnavailableError()
|
|
306
|
+
if expiry <= self._current_time():
|
|
307
|
+
raise ResourceExpiredError()
|
|
308
|
+
snapshot = _externalized_snapshot(ref, backend_id, request, stamp)
|
|
309
|
+
if not _generic_valid(snapshot, self.backend_ids, validated_at):
|
|
310
|
+
raise InvalidResourceRefError()
|
|
311
|
+
return snapshot
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
class InMemoryResourceBackend:
|
|
315
|
+
"""Test-only, non-durable process storage. Not thread-safe or for production."""
|
|
316
|
+
|
|
317
|
+
def __init__(self, resolver_id: str = "memory") -> None:
|
|
318
|
+
self.resolver_id = resolver_id
|
|
319
|
+
self._entries: Dict[Tuple[str, str], Tuple[bytes, str]] = {}
|
|
320
|
+
|
|
321
|
+
async def resolve(self, request: ResourceResolveRequest) -> ResourceResolveResult:
|
|
322
|
+
content, media_type = self._entries[(request.trusted_context.tenant_id, request.uri)]
|
|
323
|
+
return ResourceResolveResult(content, media_type)
|
|
324
|
+
|
|
325
|
+
async def externalize(self, request: ResourceExternalizeRequest) -> ResourceRef:
|
|
326
|
+
tenant = request.trusted_context.tenant_id
|
|
327
|
+
uri = f"memory://{tenant}/{request.sha256.hex()}"
|
|
328
|
+
self._entries[(tenant, uri)] = (request.content, request.media_type)
|
|
329
|
+
return ResourceRef(resolver_id=self.resolver_id, uri=uri, sha256=request.sha256,
|
|
330
|
+
size_bytes=request.size_bytes, media_type=request.media_type,
|
|
331
|
+
purpose=request.purpose, expires_at=_timestamp(request.expires_at))
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
__all__ = [
|
|
335
|
+
"InMemoryResourceBackend",
|
|
336
|
+
"InvalidResourceRefError",
|
|
337
|
+
"InvalidResourceRegistryError",
|
|
338
|
+
"InvalidTrustedResourceContextError",
|
|
339
|
+
"MAX_TRUSTED_JOB_ID_BYTES",
|
|
340
|
+
"MAX_TRUSTED_TENANT_ID_BYTES",
|
|
341
|
+
"ResolvedResource",
|
|
342
|
+
"ResourceBackendRegistration",
|
|
343
|
+
"ResourceBackendUnavailableError",
|
|
344
|
+
"ResourceDigestMismatchError",
|
|
345
|
+
"ResourceExpiredError",
|
|
346
|
+
"ResourceExternalizeRequest",
|
|
347
|
+
"ResourceExternalizerBackend",
|
|
348
|
+
"ResourceExternalizerUnavailableError",
|
|
349
|
+
"ResourceMediaTypeMismatchError",
|
|
350
|
+
"ResourceMetadataMismatchError",
|
|
351
|
+
"ResourceRegistry",
|
|
352
|
+
"ResourceRegistryError",
|
|
353
|
+
"ResourceResolveRequest",
|
|
354
|
+
"ResourceResolveResult",
|
|
355
|
+
"ResourceResolverBackend",
|
|
356
|
+
"ResourceResolverUnavailableError",
|
|
357
|
+
"ResourceSizeMismatchError",
|
|
358
|
+
"ResourceTooLargeError",
|
|
359
|
+
"TrustedResourceContext",
|
|
360
|
+
]
|