deposit-python 2.0.1__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.
deposit/_exchange.py ADDED
@@ -0,0 +1,524 @@
1
+ """Opaque Exchange intake, relay and leased reads."""
2
+
3
+ from base64 import b64decode, b64encode
4
+ from collections.abc import Mapping, Sequence
5
+ from contextlib import contextmanager, suppress
6
+ from hashlib import sha256
7
+ from io import BytesIO, RawIOBase
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+ import re
12
+ import tempfile
13
+ from threading import RLock
14
+ from weakref import WeakSet
15
+
16
+ from .errors import DepositError, OperationCommittedAfterCancel, OutcomeUnknown, TransportError
17
+ from .networkx import from_networkx
18
+
19
+
20
+ CHUNK_BYTES = 1024 * 1024
21
+ _RESOURCE = re.compile(r"resources/[a-f0-9]{64}")
22
+ _DIGEST = re.compile(r"[a-f0-9]{64}")
23
+
24
+
25
+ def _invalid(message):
26
+ return DepositError("INVALID_RESPONSE", message)
27
+
28
+
29
+ class ExchangeBundle:
30
+ """An immutable package reference with one fixed Server reader lease."""
31
+
32
+ def __init__(self, endpoint, reference, *, on_close=None):
33
+ self._endpoint = endpoint
34
+ self._reference = dict(reference)
35
+ self._closed = False
36
+ self._inspection = None
37
+ self._on_close = on_close
38
+ self._lock = RLock()
39
+ self._readers = WeakSet()
40
+ if (not all(isinstance(reference.get(key), str) for key in ("packageId", "grant", "sha256"))
41
+ or not _DIGEST.fullmatch(reference["sha256"])
42
+ or type(reference.get("bytes")) is not int or reference["bytes"] < 0):
43
+ raise _invalid("Invalid Exchange package reference")
44
+
45
+ @property
46
+ def source(self):
47
+ return {name: self._reference[name] for name in ("packageId", "grant")}
48
+
49
+ def _request(self, method, *arguments):
50
+ with self._lock:
51
+ if self._closed:
52
+ raise ValueError("Exchange bundle is closed")
53
+ return self._endpoint.call(f"deposit.exchange.{method}", *self.source.values(), *arguments)
54
+
55
+ def _inspect(self):
56
+ with self._lock:
57
+ if self._closed:
58
+ raise ValueError("Exchange bundle is closed")
59
+ if self._inspection is None:
60
+ envelope = self._request("inspect")
61
+ if (not isinstance(envelope.get("leaseId"), str) or not isinstance(envelope.get("manifest"), dict)
62
+ or not isinstance(envelope.get("collections"), dict)):
63
+ raise _invalid("Invalid Exchange inspection envelope")
64
+ self._inspection = envelope
65
+ return self._inspection
66
+
67
+ def _live_identity(self):
68
+ with self._lock:
69
+ if self._closed:
70
+ raise ValueError("Exchange bundle is closed")
71
+ return self._endpoint.live_identity()
72
+
73
+ @property
74
+ def manifest(self):
75
+ fields = self._inspect()["manifest"]
76
+ return {name: self._value({"type": value["kind"], **value}) if isinstance(value, dict) else value
77
+ for name, value in fields.items()}
78
+
79
+ @property
80
+ def graph(self):
81
+ envelope = self._inspect()
82
+ manifest = envelope["manifest"]
83
+ return {name: self._value({"type": descriptor["kind"], "collection": name, **descriptor})
84
+ for name, descriptor in envelope["collections"].items() if name not in manifest}
85
+
86
+ def _pages(self, collection):
87
+ lease = self._inspect()["leaseId"]
88
+ method = "memberPage" if collection == "files" else "graphPage"
89
+ arguments = (lease,) if collection == "files" else (lease, collection)
90
+ cursor = None
91
+ while True:
92
+ page = self._request(method, *arguments, cursor, 256)
93
+ entries = page.get("entries")
94
+ if (page.get("packageId") != self._reference["packageId"] or page.get("collection") != collection
95
+ or not isinstance(entries, list) or len(entries) > 256):
96
+ raise _invalid("Invalid Exchange collection page")
97
+ yield from entries
98
+ following = page.get("nextCursor")
99
+ if following is None:
100
+ return
101
+ if not isinstance(following, dict) or not entries or following == cursor:
102
+ raise _invalid("Invalid Exchange collection cursor")
103
+ cursor = following
104
+
105
+ def _value(self, record):
106
+ kind = record.get("type")
107
+ if kind == "scalar":
108
+ return record["value"]
109
+ name = record.get("collection")
110
+ if not isinstance(name, str):
111
+ raise _invalid("Invalid Exchange collection descriptor")
112
+ if kind == "text":
113
+ return _Text(self, name)
114
+ count = record.get("count")
115
+ if type(count) is not int or count < 0:
116
+ raise _invalid("Invalid Exchange collection count")
117
+ if kind == "mapping":
118
+ return _Mapping(self, name, count)
119
+ if kind == "sequence":
120
+ return _Sequence(self, name, count)
121
+ raise _invalid("Unknown Exchange value type")
122
+
123
+ def open_resource(self, entry):
124
+ if not isinstance(entry, str) or not _RESOURCE.fullmatch(entry):
125
+ raise ValueError("Invalid Exchange resource member")
126
+ metadata = self.manifest["files"][entry]
127
+ return self._reader(entry, metadata["bytes"], metadata["sha256"])
128
+
129
+ def open_package_stream(self):
130
+ self._inspect()
131
+ return self._reader("package", self._reference["bytes"], self._reference["sha256"])
132
+
133
+ def _reader(self, member, size, checksum):
134
+ with self._lock:
135
+ if self._closed:
136
+ raise ValueError("Exchange bundle is closed")
137
+ reader = _Reader(self, member, size, checksum)
138
+ self._readers.add(reader)
139
+ return reader
140
+
141
+ def save(self, path):
142
+ target = Path(path)
143
+ temporary = None
144
+ try:
145
+ with self.open_package_stream() as source, tempfile.NamedTemporaryFile(
146
+ mode="wb", dir=target.parent, prefix=".deposit-", suffix=".tmp", delete=False
147
+ ) as output:
148
+ temporary = Path(output.name)
149
+ while block := source.read(CHUNK_BYTES):
150
+ output.write(block)
151
+ output.flush()
152
+ os.fsync(output.fileno())
153
+ os.replace(temporary, target)
154
+ temporary = None
155
+ finally:
156
+ if temporary is not None:
157
+ temporary.unlink(missing_ok=True)
158
+
159
+ def close(self):
160
+ with self._lock:
161
+ if not self._closed:
162
+ try:
163
+ discard_package(self._endpoint, self.source, control=True)
164
+ finally:
165
+ self._detach()
166
+
167
+ def _detach(self):
168
+ with self._lock:
169
+ if not self._closed:
170
+ self._closed = True
171
+ for reader in tuple(self._readers):
172
+ reader.close()
173
+ try:
174
+ self._endpoint.close()
175
+ finally:
176
+ if self._on_close is not None:
177
+ self._on_close(self)
178
+
179
+ def __enter__(self):
180
+ return self
181
+
182
+ def __exit__(self, error_type, *_):
183
+ if error_type is None:
184
+ self.close()
185
+ else:
186
+ with suppress(Exception):
187
+ self.close()
188
+
189
+
190
+ class _Mapping(Mapping):
191
+ def __init__(self, bundle, collection, count):
192
+ self._bundle, self._collection, self._count = bundle, collection, count
193
+
194
+ def __len__(self):
195
+ return self._count
196
+
197
+ def items(self):
198
+ return self._items()
199
+
200
+ def _items(self):
201
+ for entry in self._bundle._pages(self._collection):
202
+ if self._collection == "files":
203
+ yield entry["member"], {"bytes": entry["bytes"], "sha256": entry["sha256"]}
204
+ else:
205
+ key = self._bundle._value(entry["key"])
206
+ yield str(key) if isinstance(key, _Text) else key, self._bundle._value(entry["value"])
207
+
208
+ def __iter__(self):
209
+ for key, _ in self._items():
210
+ yield key
211
+
212
+ def __getitem__(self, key):
213
+ for current, value in self._items():
214
+ if current == key:
215
+ return value
216
+ raise KeyError(key)
217
+
218
+
219
+ class _Sequence(Sequence):
220
+ def __init__(self, bundle, collection, count):
221
+ self._bundle, self._collection, self._count = bundle, collection, count
222
+
223
+ def __len__(self):
224
+ return self._count
225
+
226
+ def __iter__(self):
227
+ for entry in self._bundle._pages(self._collection):
228
+ yield self._bundle._value(entry)
229
+
230
+ def __getitem__(self, index):
231
+ if isinstance(index, slice):
232
+ return [self[position] for position in range(*index.indices(len(self)))]
233
+ wanted = index if index >= 0 else len(self) + index
234
+ if not 0 <= wanted < len(self):
235
+ raise IndexError(index)
236
+ for position, entry in enumerate(self):
237
+ if position == wanted:
238
+ return entry
239
+ raise _invalid("Exchange collection ended before its declared count")
240
+
241
+
242
+ class _Text:
243
+ def __init__(self, bundle, collection):
244
+ self._bundle, self._collection = bundle, collection
245
+
246
+ def chunks(self):
247
+ for entry in self._bundle._pages(self._collection):
248
+ yield entry["value"]
249
+
250
+ def __str__(self):
251
+ return "".join(self.chunks())
252
+
253
+
254
+ class _Reader(RawIOBase):
255
+ def __init__(self, bundle, member, size, checksum):
256
+ if type(size) is not int or size < 0 or not isinstance(checksum, str) or not _DIGEST.fullmatch(checksum):
257
+ raise _invalid("Invalid Exchange member metadata")
258
+ self._bundle, self._member, self._size, self._checksum = bundle, member, size, checksum
259
+ self._offset = 0
260
+ self._digest = sha256()
261
+ self._verified = False
262
+
263
+ def readable(self):
264
+ return True
265
+
266
+ def readinto(self, target):
267
+ if self.closed:
268
+ raise ValueError("Exchange stream is closed")
269
+ if self._verified or not target:
270
+ return 0
271
+ lease = self._bundle._inspect()["leaseId"]
272
+ limit = min(len(target), CHUNK_BYTES)
273
+ result = self._bundle._request("readChunk", lease, self._member, self._offset, limit)
274
+ encoded = result.get("bytesBase64")
275
+ if not isinstance(encoded, str) or len(encoded) > 4 * ((limit + 2) // 3):
276
+ raise _invalid("Invalid Exchange chunk")
277
+ try:
278
+ block = b64decode(encoded, validate=True)
279
+ except ValueError as exc:
280
+ raise _invalid("Invalid Exchange chunk encoding") from exc
281
+ if (result.get("offset") != self._offset or result.get("length") != len(block)
282
+ or len(block) != min(limit, self._size - self._offset)):
283
+ raise _invalid("Invalid Exchange chunk position or length")
284
+ self._digest.update(block)
285
+ self._offset += len(block)
286
+ if self._offset == self._size:
287
+ if self._digest.hexdigest() != self._checksum:
288
+ raise DepositError("RESOURCE_CORRUPT", "Exchange stream checksum differs")
289
+ self._verified = True
290
+ target[:len(block)] = block
291
+ return len(block)
292
+
293
+
294
+ @contextmanager
295
+ def _provider(source):
296
+ if isinstance(source, bytes):
297
+ with BytesIO(source) as stream:
298
+ yield stream
299
+ elif isinstance(source, (str, os.PathLike)):
300
+ with Path(source).open("rb") as stream:
301
+ yield stream
302
+ elif callable(getattr(source, "read", None)):
303
+ yield source
304
+ elif callable(source):
305
+ with source() as stream:
306
+ if not callable(getattr(stream, "read", None)):
307
+ raise TypeError("Exchange provider must return a binary stream")
308
+ yield stream
309
+ else:
310
+ raise TypeError("Exchange provider must be bytes, a path, or a binary stream")
311
+
312
+
313
+ def _stream_blocks(stream):
314
+ while True:
315
+ block = stream.read(CHUNK_BYTES)
316
+ if not isinstance(block, bytes) or len(block) > CHUNK_BYTES:
317
+ raise TypeError("Exchange provider must return bounded bytes")
318
+ if not block:
319
+ return
320
+ yield block
321
+
322
+
323
+ def _upload(execution, upload, member, blocks):
324
+ offset = 0
325
+ for block in blocks:
326
+ _chunk(execution, upload, member, offset, block)
327
+ offset += len(block)
328
+ if offset == 0 and member.startswith("resources/"):
329
+ _chunk(execution, upload, member, 0, b"")
330
+
331
+
332
+ def _chunk(execution, upload, member, offset, block):
333
+ result = execution.run("deposit.exchange.uploadChunk", upload, member, offset, b64encode(block).decode("ascii"))
334
+ if (result.get("uploadId"), result.get("member"), result.get("nextOffset")) != (upload, member, offset + len(block)):
335
+ raise _invalid("Exchange upload acknowledgement differs")
336
+
337
+
338
+ def stage_zip(endpoint, source):
339
+ """Send original package bytes from the current stream position."""
340
+ with _provider(source) as stream, _intake(endpoint, "zip", {}) as (execution, upload):
341
+ _upload(execution, upload, "package", _stream_blocks(stream))
342
+ return execution.run("deposit.exchange.finishUpload", upload)
343
+
344
+
345
+ def discard_package(endpoint, reference, *, control=False):
346
+ """Release any owned package that is no longer needed by a plan or reader."""
347
+ if not isinstance(reference, dict):
348
+ return
349
+ package_id, grant = reference.get("packageId"), reference.get("grant")
350
+ if isinstance(package_id, str) and isinstance(grant, str):
351
+ request = endpoint.control if control else endpoint.call
352
+ with suppress(DepositError, TransportError):
353
+ request("deposit.exchange.discard", package_id, grant)
354
+
355
+
356
+ @contextmanager
357
+ def _intake(endpoint, kind, metadata):
358
+ try:
359
+ with endpoint.execution() as execution:
360
+ reference = execution.run("deposit.exchange.beginUpload", endpoint.scope, kind, metadata)
361
+ upload = reference.get("uploadId")
362
+ if not isinstance(upload, str):
363
+ raise _invalid("Exchange upload acknowledgement has no identity")
364
+ try:
365
+ yield execution, upload
366
+ except OutcomeUnknown:
367
+ raise
368
+ except OperationCommittedAfterCancel as exc:
369
+ result = exc.details.get("result")
370
+ discard_package(endpoint, result, control=True)
371
+ with suppress(Exception):
372
+ execution.run("deposit.exchange.abortUpload", upload, cleanup=True)
373
+ raise
374
+ except BaseException:
375
+ with suppress(Exception):
376
+ execution.run("deposit.exchange.abortUpload", upload, cleanup=True)
377
+ raise
378
+ except BaseException:
379
+ # If the abort reply or upload identity was lost, an abandoned writer
380
+ # still becomes collectible as soon as its connection closes.
381
+ with suppress(Exception):
382
+ endpoint.interrupt_upload()
383
+ raise
384
+
385
+
386
+ def _json_fragments(value):
387
+ if isinstance(value, str):
388
+ yield b'"'
389
+ for start in range(0, len(value), 8192):
390
+ text = json.dumps(value[start:start + 8192], ensure_ascii=True)
391
+ yield text[1:-1].encode("ascii")
392
+ yield b'"'
393
+ elif isinstance(value, Mapping):
394
+ yield b"{"
395
+ for index, (key, child) in enumerate(value.items()):
396
+ if not isinstance(key, str):
397
+ raise TypeError("Exchange JSON keys must be strings")
398
+ if index:
399
+ yield b","
400
+ yield from _json_fragments(key)
401
+ yield b":"
402
+ yield from _json_fragments(child)
403
+ yield b"}"
404
+ elif isinstance(value, (list, tuple, _Sequence)):
405
+ yield b"["
406
+ for index, child in enumerate(value):
407
+ if index:
408
+ yield b","
409
+ yield from _json_fragments(child)
410
+ yield b"]"
411
+ elif isinstance(value, _Text):
412
+ yield b'"'
413
+ for chunk in value.chunks():
414
+ yield json.dumps(chunk, ensure_ascii=True)[1:-1].encode("ascii")
415
+ yield b'"'
416
+ else:
417
+ yield json.dumps(value, allow_nan=False).encode("ascii")
418
+
419
+
420
+ def _json_blocks(value):
421
+ buffer = bytearray()
422
+ for fragment in _json_fragments(value):
423
+ if len(buffer) + len(fragment) > CHUNK_BYTES:
424
+ yield bytes(buffer)
425
+ buffer.clear()
426
+ buffer.extend(fragment)
427
+ if buffer:
428
+ yield bytes(buffer)
429
+
430
+
431
+ def stage_snapshot(endpoint, snapshot, *, resources=None, resource_source=None):
432
+ """Encode structured input and send its resource providers without creating a ZIP."""
433
+ if not isinstance(snapshot, Mapping):
434
+ snapshot = from_networkx(snapshot)
435
+ manifest, graph, history = snapshot["manifest"], snapshot["graph"], snapshot.get("history")
436
+ if not isinstance(manifest, Mapping) or not isinstance(graph, Mapping):
437
+ raise TypeError("Exchange manifest and graph must be mappings")
438
+ manifest = {key: value for key, value in manifest.items() if key not in {"files", "packageId", "depositVersion"}}
439
+ if resources is not None and not isinstance(resources, Mapping):
440
+ raise TypeError("Exchange resources must map member names to providers")
441
+ explicit = resources if resources is not None else {}
442
+ if resource_source is not None:
443
+ if isinstance(resource_source, ExchangeBundle):
444
+ namespace = resource_source.manifest.get("sourceNamespaceId")
445
+ else:
446
+ from .store import Store
447
+ if not isinstance(resource_source, Store):
448
+ raise TypeError("Exchange resource source must be an authenticated Store or bundle")
449
+ namespace = resource_source.namespace_id
450
+ if namespace != manifest.get("sourceNamespaceId"):
451
+ raise ValueError("Resource source belongs to another Namespace")
452
+ with _intake(endpoint, "snapshot", {"includeHistory": history is not None}) as (execution, upload):
453
+ _upload(execution, upload, "manifest", _json_blocks(manifest))
454
+ _upload(execution, upload, "graph", _json_blocks(graph))
455
+ if history is not None:
456
+ _upload(execution, upload, "history", _json_blocks(history))
457
+ for entry, source in explicit.items():
458
+ if not isinstance(entry, str) or not _RESOURCE.fullmatch(entry):
459
+ raise ValueError("Resource providers must use content-addressed member names")
460
+ with _provider(source) as stream:
461
+ _upload(execution, upload, entry, _stream_blocks(stream))
462
+ staged = set(explicit)
463
+ for record in graph.get("resources", ()):
464
+ if not isinstance(record, Mapping) or not isinstance(record.get("entry"), str):
465
+ raise TypeError("Exchange resource records must identify a member")
466
+ entry = record["entry"]
467
+ if entry in explicit:
468
+ continue
469
+ if isinstance(resource_source, ExchangeBundle):
470
+ if entry in staged:
471
+ continue
472
+ provider = lambda: resource_source.open_resource(entry)
473
+ elif resource_source is not None:
474
+ reader = resource_source._open_import_resource(record, read=entry not in staged)
475
+ if reader is None:
476
+ continue
477
+ provider = lambda: reader
478
+ else:
479
+ raise ValueError(f"No content provider for Exchange resource {entry!r}")
480
+ with _provider(provider) as stream:
481
+ _upload(execution, upload, entry, _stream_blocks(stream))
482
+ staged.add(entry)
483
+ return execution.run("deposit.exchange.finishUpload", upload)
484
+
485
+
486
+ def package_for_target(bundle, endpoint):
487
+ """Hand off a still-authorized local grant, or verify an opaque relay."""
488
+ try:
489
+ same_actor_and_server = bundle._live_identity() == endpoint.live_identity()
490
+ except (DepositError, TransportError):
491
+ same_actor_and_server = False
492
+ if same_actor_and_server:
493
+ try:
494
+ inspection = endpoint.call("deposit.exchange.inspect", *bundle.source.values())
495
+ if not isinstance(inspection, dict) or not isinstance(inspection.get("leaseId"), str):
496
+ raise _invalid("Invalid Exchange grant inspection response")
497
+ except (DepositError, TransportError):
498
+ # No destination action has been submitted. Relay still requires
499
+ # every byte to be authorized by the independent source endpoint.
500
+ pass
501
+ else:
502
+ return bundle.source
503
+ with bundle.open_package_stream() as reader:
504
+ verified = stage_zip(endpoint, reader)
505
+ if (verified.get("bytes"), verified.get("sha256")) != (
506
+ bundle._reference["bytes"], bundle._reference["sha256"]):
507
+ with suppress(Exception):
508
+ endpoint.call("deposit.exchange.discard", verified["packageId"], verified["grant"])
509
+ raise DepositError("RESOURCE_CORRUPT", "Receiving package digest differs from the source")
510
+ return {name: verified[name] for name in ("packageId", "grant")}
511
+
512
+
513
+ def materialize_snapshot(bundle):
514
+ """Materialize the public current-graph dictionary from a leased export."""
515
+ def portable(value):
516
+ if isinstance(value, Mapping):
517
+ return {key: portable(child) for key, child in value.items()}
518
+ if isinstance(value, Sequence) and not isinstance(value, str):
519
+ return [portable(child) for child in value]
520
+ if isinstance(value, _Text):
521
+ return str(value)
522
+ return value
523
+
524
+ return {"manifest": portable(bundle.manifest), "graph": portable(bundle.graph)}