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/__init__.py +15 -0
- deposit/_batch.py +307 -0
- deposit/_exchange.py +524 -0
- deposit/_exchange_transport.py +411 -0
- deposit/_gateway.py +612 -0
- deposit/_meta.py +2 -0
- deposit/_paging.py +645 -0
- deposit/_procedure_manifest.json +3799 -0
- deposit/_resource_buffer.py +211 -0
- deposit/_resources.py +187 -0
- deposit/_version.py +24 -0
- deposit/client.py +535 -0
- deposit/entities.py +351 -0
- deposit/errors.py +61 -0
- deposit/exchange.py +5 -0
- deposit/networkx.py +325 -0
- deposit/store.py +2142 -0
- deposit/values.py +510 -0
- deposit_python-2.0.1.dist-info/METADATA +81 -0
- deposit_python-2.0.1.dist-info/RECORD +23 -0
- deposit_python-2.0.1.dist-info/WHEEL +5 -0
- deposit_python-2.0.1.dist-info/licenses/LICENSE +21 -0
- deposit_python-2.0.1.dist-info/top_level.txt +1 -0
deposit/networkx.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"""Lossless NetworkX adapter for Deposit Exchange graph snapshots."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from collections.abc import Mapping
|
|
5
|
+
from copy import deepcopy
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
import json
|
|
8
|
+
import uuid
|
|
9
|
+
import math
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import networkx as nx
|
|
13
|
+
|
|
14
|
+
GRAPH_CATEGORIES= (
|
|
15
|
+
"classes", "objects", "descriptors", "geometries", "memberships",
|
|
16
|
+
"relationships", "classRelationships", "patterns", "userTools", "resources",
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
_NODE_KINDS = {"Class", "Object"}
|
|
20
|
+
_EDGE_KINDS = {"Membership", "Relationship", "ClassRelationship"}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def to_networkx(snapshot: Mapping[str, Any]):
|
|
24
|
+
value = _portable_snapshot(snapshot)
|
|
25
|
+
manifest, records = value["manifest"], value["graph"]
|
|
26
|
+
namespace_id = manifest["sourceNamespaceId"]
|
|
27
|
+
revision = manifest["exportedRevision"]
|
|
28
|
+
graph = nx.MultiDiGraph()
|
|
29
|
+
graph.graph.update(
|
|
30
|
+
namespaceId=namespace_id,
|
|
31
|
+
revision=revision,
|
|
32
|
+
depositVersion=manifest.get("depositVersion"),
|
|
33
|
+
patterns=deepcopy(records["patterns"]),
|
|
34
|
+
resources=deepcopy(records["resources"]),
|
|
35
|
+
geometries=deepcopy(records["geometries"]),
|
|
36
|
+
userTools=deepcopy(records["userTools"]),
|
|
37
|
+
scope=manifest["scope"],
|
|
38
|
+
rootIds=deepcopy(manifest["rootIds"]),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
classes = {record["id"]: record for record in records["classes"]}
|
|
42
|
+
objects = {record["id"]: record for record in records["objects"]}
|
|
43
|
+
if len(classes) != len(records["classes"]) or len(objects) != len(records["objects"]):
|
|
44
|
+
raise ValueError("Snapshot contains duplicate node identities")
|
|
45
|
+
descriptor_values: dict[str, dict[str, Any]] = {}
|
|
46
|
+
for descriptor in records["descriptors"]:
|
|
47
|
+
owner = descriptor.get("objectId")
|
|
48
|
+
if not isinstance(owner, str) or owner not in objects:
|
|
49
|
+
raise ValueError("Descriptor has a missing or invalid Object endpoint")
|
|
50
|
+
if descriptor.get("name") in descriptor_values.setdefault(owner, {}):
|
|
51
|
+
raise ValueError("Snapshot contains duplicate Object Descriptor names")
|
|
52
|
+
# Descriptor identity and provenance are visible graph data. Keeping
|
|
53
|
+
# the complete current record here avoids a hidden snapshot sidecar.
|
|
54
|
+
visible = deepcopy(descriptor)
|
|
55
|
+
visible.update(kind="Descriptor", namespaceId=namespace_id, objectId=owner)
|
|
56
|
+
descriptor_values[owner][descriptor["name"]] = visible
|
|
57
|
+
|
|
58
|
+
for record in records["classes"]:
|
|
59
|
+
node = _node_record(record, namespace_id, "Class")
|
|
60
|
+
graph.add_node((namespace_id, "Class", record["id"]), **node)
|
|
61
|
+
for record in records["objects"]:
|
|
62
|
+
node = _node_record(record, namespace_id, "Object")
|
|
63
|
+
node["descriptors"] = descriptor_values.get(record["id"], {})
|
|
64
|
+
graph.add_node((namespace_id, "Object", record["id"]), **node)
|
|
65
|
+
|
|
66
|
+
edge_ids = set()
|
|
67
|
+
for membership in records["memberships"]:
|
|
68
|
+
object_id, class_id = membership.get("objectId"), membership.get("classId")
|
|
69
|
+
if object_id not in objects or class_id not in classes:
|
|
70
|
+
raise ValueError("Membership has a missing or invalid endpoint")
|
|
71
|
+
_add_edge(graph, namespace_id, "Membership", object_id, class_id, membership, edge_ids)
|
|
72
|
+
for kind, category, endpoint_kind in (
|
|
73
|
+
("Relationship", "relationships", "Object"),
|
|
74
|
+
("ClassRelationship", "classRelationships", "Class"),
|
|
75
|
+
):
|
|
76
|
+
known = objects if endpoint_kind == "Object" else classes
|
|
77
|
+
for record in records[category]:
|
|
78
|
+
source, target = record.get("sourceId"), record.get("targetId")
|
|
79
|
+
if source not in known or target not in known:
|
|
80
|
+
raise ValueError(f"{kind} has a missing or invalid endpoint")
|
|
81
|
+
_add_edge(graph, namespace_id, kind, source, target, record, edge_ids)
|
|
82
|
+
return graph
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def from_networkx(graph) -> dict[str, Any]:
|
|
86
|
+
if not isinstance(graph, nx.MultiDiGraph):
|
|
87
|
+
raise TypeError("from_networkx requires a networkx.MultiDiGraph")
|
|
88
|
+
frozen_nodes, frozen_edges, metadata = _freeze_graph(graph)
|
|
89
|
+
namespace_id = metadata.get("namespaceId")
|
|
90
|
+
revision = metadata.get("revision")
|
|
91
|
+
if not isinstance(namespace_id, str) or not namespace_id:
|
|
92
|
+
raise ValueError("Graph metadata requires a source namespaceId")
|
|
93
|
+
if type(revision) is not int or revision < 0:
|
|
94
|
+
raise ValueError("Graph metadata requires a nonnegative source revision")
|
|
95
|
+
return _snapshot_from_graph(frozen_nodes, frozen_edges, metadata, namespace_id, revision)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _portable_snapshot(snapshot: Mapping[str, Any]) -> dict[str, Any]:
|
|
99
|
+
if not isinstance(snapshot, Mapping) or set(snapshot) - {"manifest", "graph", "history"}:
|
|
100
|
+
raise TypeError("Deposit graph snapshot must contain manifest, graph and optional history")
|
|
101
|
+
if not isinstance(snapshot.get("manifest"), Mapping) or not isinstance(snapshot.get("graph"), Mapping):
|
|
102
|
+
raise TypeError("Deposit graph snapshot requires manifest and graph mappings")
|
|
103
|
+
try:
|
|
104
|
+
_ensure_json_portable(snapshot)
|
|
105
|
+
except (TypeError, ValueError, OverflowError) as exc:
|
|
106
|
+
raise TypeError("Deposit graph snapshot must contain only finite JSON-portable values") from exc
|
|
107
|
+
value = {"manifest": snapshot["manifest"], "graph": snapshot["graph"]}
|
|
108
|
+
if "history" in snapshot:
|
|
109
|
+
value["history"] = snapshot["history"]
|
|
110
|
+
manifest, records = value["manifest"], value["graph"]
|
|
111
|
+
if any(not isinstance(records.get(name), list) for name in GRAPH_CATEGORIES):
|
|
112
|
+
raise ValueError("Deposit graph snapshot categories are incomplete")
|
|
113
|
+
source_ns = manifest.get("sourceNamespaceId")
|
|
114
|
+
revision = manifest.get("exportedRevision")
|
|
115
|
+
if not isinstance(source_ns, str) or not source_ns or type(revision) is not int or revision < 0:
|
|
116
|
+
raise ValueError("Deposit graph snapshot has invalid source identity or revision")
|
|
117
|
+
return value
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _ensure_json_portable(root: Any) -> None:
|
|
121
|
+
"""Validate finite JSON data iteratively without cloning the full snapshot."""
|
|
122
|
+
active: set[int] = set()
|
|
123
|
+
pending = [iter((root,))]
|
|
124
|
+
owners = []
|
|
125
|
+
while pending:
|
|
126
|
+
try:
|
|
127
|
+
value = next(pending[-1])
|
|
128
|
+
except StopIteration:
|
|
129
|
+
pending.pop()
|
|
130
|
+
if owners:
|
|
131
|
+
active.remove(owners.pop())
|
|
132
|
+
continue
|
|
133
|
+
if value is None or type(value) in (str, bool, int):
|
|
134
|
+
if isinstance(value, str):
|
|
135
|
+
for start in range(0, len(value), 64 * 1024):
|
|
136
|
+
value[start:start + 64 * 1024].encode("utf-8")
|
|
137
|
+
continue
|
|
138
|
+
if type(value) is float:
|
|
139
|
+
if not math.isfinite(value):
|
|
140
|
+
raise ValueError("non-finite number")
|
|
141
|
+
continue
|
|
142
|
+
if type(value) not in (dict, list):
|
|
143
|
+
raise TypeError(f"unsupported JSON value: {type(value).__name__}")
|
|
144
|
+
identity = id(value)
|
|
145
|
+
if identity in active:
|
|
146
|
+
raise ValueError("cyclic JSON value")
|
|
147
|
+
active.add(identity)
|
|
148
|
+
owners.append(identity)
|
|
149
|
+
if type(value) is dict:
|
|
150
|
+
def items(mapping):
|
|
151
|
+
for key, item in mapping.items():
|
|
152
|
+
if not isinstance(key, str):
|
|
153
|
+
raise TypeError("JSON object keys must be strings")
|
|
154
|
+
for start in range(0, len(key), 64 * 1024):
|
|
155
|
+
key[start:start + 64 * 1024].encode("utf-8")
|
|
156
|
+
yield item
|
|
157
|
+
pending.append(iter(items(value)))
|
|
158
|
+
else:
|
|
159
|
+
pending.append(iter(value))
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _node_record(record: dict[str, Any], namespace_id: str, kind: str) -> dict[str, Any]:
|
|
163
|
+
identity = record.get("id")
|
|
164
|
+
if not isinstance(identity, str) or not identity:
|
|
165
|
+
raise ValueError(f"{kind} record requires a stable id")
|
|
166
|
+
if record.get("namespaceId", namespace_id) != namespace_id:
|
|
167
|
+
raise ValueError(f"{kind} record Namespace contradicts the graph snapshot")
|
|
168
|
+
if record.get("kind", kind) != kind:
|
|
169
|
+
raise ValueError(f"{kind} record kind contradicts its containing graph category")
|
|
170
|
+
attrs = deepcopy(record)
|
|
171
|
+
attrs.update(id=identity, namespaceId=namespace_id, kind=kind)
|
|
172
|
+
return attrs
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _add_edge(graph, namespace_id: str, kind: str, source_id: str, target_id: str, record: dict[str, Any], edge_ids: set):
|
|
176
|
+
identity = record.get("id")
|
|
177
|
+
if not isinstance(identity, str) or not identity:
|
|
178
|
+
raise ValueError(f"{kind} edge requires a stable id")
|
|
179
|
+
if record.get("namespaceId", namespace_id) != namespace_id or record.get("kind", kind) != kind:
|
|
180
|
+
raise ValueError(f"{kind} record metadata contradicts its containing graph category")
|
|
181
|
+
if identity in edge_ids:
|
|
182
|
+
raise ValueError("Snapshot contains duplicate edge identities")
|
|
183
|
+
edge_ids.add(identity)
|
|
184
|
+
expected_endpoints = {
|
|
185
|
+
"Membership": (record.get("objectId", source_id), record.get("classId", target_id)),
|
|
186
|
+
"Relationship": (record.get("sourceId", source_id), record.get("targetId", target_id)),
|
|
187
|
+
"ClassRelationship": (record.get("sourceId", source_id), record.get("targetId", target_id)),
|
|
188
|
+
}[kind]
|
|
189
|
+
if expected_endpoints != (source_id, target_id):
|
|
190
|
+
raise ValueError(f"{kind} record endpoints contradict graph endpoints")
|
|
191
|
+
source_kind, target_kind = {
|
|
192
|
+
"Membership": ("Object", "Class"),
|
|
193
|
+
"Relationship": ("Object", "Object"),
|
|
194
|
+
"ClassRelationship": ("Class", "Class"),
|
|
195
|
+
}[kind]
|
|
196
|
+
attrs = deepcopy(record)
|
|
197
|
+
attrs.update(id=identity, kind=kind)
|
|
198
|
+
graph.add_edge((namespace_id, source_kind, source_id), (namespace_id, target_kind, target_id), key=identity, **attrs)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _freeze_graph(graph):
|
|
202
|
+
try:
|
|
203
|
+
nodes = tuple((deepcopy(key), _json_freeze(dict(attrs))) for key, attrs in graph.nodes(data=True))
|
|
204
|
+
edges = tuple((deepcopy(source), deepcopy(target), deepcopy(key), _json_freeze(dict(attrs)))
|
|
205
|
+
for source, target, key, attrs in graph.edges(keys=True, data=True))
|
|
206
|
+
metadata = _json_freeze(dict(graph.graph))
|
|
207
|
+
return nodes, edges, metadata
|
|
208
|
+
except (TypeError, ValueError, OverflowError) as exc:
|
|
209
|
+
raise TypeError("NetworkX graph data must contain only finite JSON-portable values") from exc
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _json_freeze(value):
|
|
213
|
+
_ensure_json_portable(value)
|
|
214
|
+
return json.loads(json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")))
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _snapshot_from_graph(nodes, edges, metadata, namespace_id, revision):
|
|
218
|
+
record_lists = {name: [] for name in GRAPH_CATEGORIES}
|
|
219
|
+
by_key = {}
|
|
220
|
+
for key, attrs in nodes:
|
|
221
|
+
if not isinstance(key, (list, tuple)) or len(key) != 3:
|
|
222
|
+
raise ValueError("Node keys must be (namespace_id, kind, id) tuples")
|
|
223
|
+
ns, kind, identity = key
|
|
224
|
+
if ns != namespace_id or kind not in _NODE_KINDS or not isinstance(identity, str) or not identity:
|
|
225
|
+
raise ValueError("Node key has an invalid Namespace, kind or id")
|
|
226
|
+
if attrs.get("id") != identity or attrs.get("kind") != kind:
|
|
227
|
+
raise ValueError("Node key and required id/kind attributes must agree")
|
|
228
|
+
if key in by_key:
|
|
229
|
+
raise ValueError("Graph contains duplicate node keys")
|
|
230
|
+
by_key[tuple(key)] = attrs
|
|
231
|
+
record = {name: deepcopy(value) for name, value in attrs.items() if name != "kind"}
|
|
232
|
+
record["kind"] = kind
|
|
233
|
+
if kind == "Class":
|
|
234
|
+
record_lists["classes"].append(record)
|
|
235
|
+
else:
|
|
236
|
+
record_lists["objects"].append(record)
|
|
237
|
+
object_descriptor_values = {
|
|
238
|
+
record["id"]: deepcopy(record.get("descriptors", {}))
|
|
239
|
+
for record in record_lists["objects"]
|
|
240
|
+
}
|
|
241
|
+
for record in record_lists["objects"]:
|
|
242
|
+
record.pop("descriptors", None)
|
|
243
|
+
seen_edges = set()
|
|
244
|
+
seen_edge_ids = set()
|
|
245
|
+
for source, target, key, attrs in edges:
|
|
246
|
+
source, target = tuple(source), tuple(target)
|
|
247
|
+
if source not in by_key or target not in by_key:
|
|
248
|
+
raise ValueError("Edge endpoint is missing from graph nodes")
|
|
249
|
+
kind, identity = attrs.get("kind"), attrs.get("id")
|
|
250
|
+
if kind not in _EDGE_KINDS or not isinstance(identity, str) or key != identity:
|
|
251
|
+
raise ValueError("Edge key, id and kind must agree")
|
|
252
|
+
if (source, target, key) in seen_edges or identity in seen_edge_ids:
|
|
253
|
+
raise ValueError("Graph contains duplicate edge identities")
|
|
254
|
+
seen_edges.add((source, target, key))
|
|
255
|
+
seen_edge_ids.add(identity)
|
|
256
|
+
expected_kinds = {"Membership": ("Object", "Class"), "Relationship": ("Object", "Object"), "ClassRelationship": ("Class", "Class")}[kind]
|
|
257
|
+
if (source[1], target[1]) != expected_kinds:
|
|
258
|
+
raise ValueError(f"{kind} has invalid endpoint kinds")
|
|
259
|
+
record = {name: deepcopy(value) for name, value in attrs.items() if name != "kind"}
|
|
260
|
+
record["kind"] = kind
|
|
261
|
+
if kind == "Membership":
|
|
262
|
+
if record.get("objectId", source[2]) != source[2] or record.get("classId", target[2]) != target[2]:
|
|
263
|
+
raise ValueError("Membership attributes contradict graph endpoints")
|
|
264
|
+
record.update(objectId=source[2], classId=target[2])
|
|
265
|
+
record_lists["memberships"].append(record)
|
|
266
|
+
else:
|
|
267
|
+
if record.get("sourceId", source[2]) != source[2] or record.get("targetId", target[2]) != target[2]:
|
|
268
|
+
raise ValueError(f"{kind} attributes contradict graph endpoints")
|
|
269
|
+
record.update(sourceId=source[2], targetId=target[2])
|
|
270
|
+
record_lists["relationships" if kind == "Relationship" else "classRelationships"].append(record)
|
|
271
|
+
patterns = metadata.get("patterns", [])
|
|
272
|
+
if not isinstance(patterns, list):
|
|
273
|
+
raise TypeError("Graph patterns metadata must be a list")
|
|
274
|
+
record_lists["patterns"] = deepcopy(patterns)
|
|
275
|
+
for category in ("resources", "geometries", "userTools"):
|
|
276
|
+
values = metadata.get(category, [])
|
|
277
|
+
if not isinstance(values, list):
|
|
278
|
+
raise TypeError(f"Graph {category} metadata must be a list")
|
|
279
|
+
record_lists[category] = deepcopy(values)
|
|
280
|
+
descriptor_ids = set()
|
|
281
|
+
for record in record_lists["objects"]:
|
|
282
|
+
object_id = record["id"]
|
|
283
|
+
values = object_descriptor_values.get(object_id, {})
|
|
284
|
+
if not isinstance(values, dict):
|
|
285
|
+
raise TypeError("Object descriptors must be a mapping")
|
|
286
|
+
for name, value in values.items():
|
|
287
|
+
if _is_visible_descriptor_record(value):
|
|
288
|
+
descriptor = deepcopy(dict(value))
|
|
289
|
+
else:
|
|
290
|
+
# Accept direct value replacement as a convenient graph edit;
|
|
291
|
+
# new scalar values receive one identity at freeze time.
|
|
292
|
+
descriptor = {"id": str(uuid.uuid4()), "name": name, "value": deepcopy(value),
|
|
293
|
+
"kind": "Descriptor", "namespaceId": namespace_id, "objectId": object_id}
|
|
294
|
+
if not isinstance(descriptor.get("id"), str) or not descriptor["id"]:
|
|
295
|
+
raise ValueError("Visible Descriptor records require a stable ID")
|
|
296
|
+
if descriptor["id"] in descriptor_ids:
|
|
297
|
+
raise ValueError("Graph contains duplicate Descriptor identities")
|
|
298
|
+
descriptor_ids.add(descriptor["id"])
|
|
299
|
+
descriptor["name"] = name
|
|
300
|
+
record_lists["descriptors"].append(descriptor)
|
|
301
|
+
scope = metadata.get("scope", "namespace")
|
|
302
|
+
root_ids = metadata.get("rootIds", [])
|
|
303
|
+
manifest = {
|
|
304
|
+
"sourceNamespaceId": namespace_id,
|
|
305
|
+
"name": "NetworkX graph", "description": "", "depositVersion": metadata.get("depositVersion"),
|
|
306
|
+
"historyMode": "disabled", "exportedRevision": revision,
|
|
307
|
+
"createdAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
|
308
|
+
"rootIds": deepcopy(root_ids),
|
|
309
|
+
"scope": scope, "includeHistory": False,
|
|
310
|
+
"files": {},
|
|
311
|
+
}
|
|
312
|
+
return {"manifest": manifest, "graph": record_lists}
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _is_visible_descriptor_record(value):
|
|
316
|
+
"""Recognize only the complete visible-record shape, not a scientific map."""
|
|
317
|
+
return (
|
|
318
|
+
isinstance(value, Mapping)
|
|
319
|
+
and value.get("kind") == "Descriptor"
|
|
320
|
+
and isinstance(value.get("id"), str) and bool(value.get("id"))
|
|
321
|
+
and isinstance(value.get("namespaceId"), str) and bool(value.get("namespaceId"))
|
|
322
|
+
and isinstance(value.get("objectId"), str) and bool(value.get("objectId"))
|
|
323
|
+
and isinstance(value.get("name"), str) and bool(value.get("name"))
|
|
324
|
+
and "value" in value
|
|
325
|
+
)
|