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/store.py
ADDED
|
@@ -0,0 +1,2142 @@
|
|
|
1
|
+
"""Synchronous operations on an authenticated, Namespace-bound Store."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from contextlib import contextmanager, nullcontext, suppress
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
import threading
|
|
10
|
+
import weakref
|
|
11
|
+
from typing import Any, Iterator
|
|
12
|
+
import uuid
|
|
13
|
+
|
|
14
|
+
from ._exchange import ExchangeBundle, discard_package, package_for_target, stage_snapshot, stage_zip
|
|
15
|
+
from ._exchange_transport import OperationEndpoint, _IMPORT_RESULTS
|
|
16
|
+
from ._paging import ImportResult, _valid_plan_observation, valid_import_plan_wrapper
|
|
17
|
+
from ._resources import ResourceReader, upload_resource
|
|
18
|
+
from ._gateway import (
|
|
19
|
+
StoreResult,
|
|
20
|
+
bind_arguments,
|
|
21
|
+
build_query,
|
|
22
|
+
detached_result,
|
|
23
|
+
domain_arguments,
|
|
24
|
+
immutable_request,
|
|
25
|
+
map_driver_error,
|
|
26
|
+
store_procedure,
|
|
27
|
+
store_control_procedure,
|
|
28
|
+
)
|
|
29
|
+
from .errors import DepositError, OperationCommittedAfterCancel, OutcomeUnknown, TransportError
|
|
30
|
+
from .entities import DClass, DObject, DNode
|
|
31
|
+
from .networkx import from_networkx, to_networkx
|
|
32
|
+
from .values import DResource
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
_STORE_FACTORY_TOKEN = object()
|
|
36
|
+
_DOMAIN_VALUE_TYPES = {
|
|
37
|
+
"String", "Integer", "Float", "Boolean", "Date", "Time", "LocalTime", "DateTime",
|
|
38
|
+
"LocalDateTime", "Duration", "Point", "List", "DDict", "DGeometry", "DResource",
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Store:
|
|
43
|
+
"""An independently authenticated session bound to one immutable Namespace UUID."""
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
client,
|
|
48
|
+
*,
|
|
49
|
+
token: str,
|
|
50
|
+
actor_id: str,
|
|
51
|
+
namespace_id: str,
|
|
52
|
+
observed: Any,
|
|
53
|
+
_factory_token: object | None = None,
|
|
54
|
+
):
|
|
55
|
+
if _factory_token is not _STORE_FACTORY_TOKEN:
|
|
56
|
+
raise TypeError("Store instances are created by Client.open_store()")
|
|
57
|
+
self._client = client
|
|
58
|
+
self._token = token
|
|
59
|
+
self._actor_id = actor_id
|
|
60
|
+
self._namespace_id = namespace_id
|
|
61
|
+
self._operation_lock = threading.Lock()
|
|
62
|
+
self._close_lock = threading.Lock()
|
|
63
|
+
self._state_lock = threading.Lock()
|
|
64
|
+
self._control_condition = threading.Condition(self._state_lock)
|
|
65
|
+
self._inflight_controls = 0
|
|
66
|
+
self._closed = False
|
|
67
|
+
self._closing = False
|
|
68
|
+
self._active = False
|
|
69
|
+
self._active_result: StoreResult | None = None
|
|
70
|
+
self._active_endpoint = None
|
|
71
|
+
self._bundles = set()
|
|
72
|
+
self._readers = weakref.WeakValueDictionary()
|
|
73
|
+
self._ready_plans = set()
|
|
74
|
+
self._plan_packages = {}
|
|
75
|
+
self._result_packages = []
|
|
76
|
+
self._batch_collection: Any = None
|
|
77
|
+
# DNode equality intentionally follows stable domain identity. A
|
|
78
|
+
# WeakSet would therefore collapse separate snapshots of the same
|
|
79
|
+
# entity; key by Python object identity so each cached snapshot is
|
|
80
|
+
# invalidated independently.
|
|
81
|
+
self._handles = weakref.WeakValueDictionary()
|
|
82
|
+
self._endpoint = OperationEndpoint(client, token, namespace_id, actor=actor_id)
|
|
83
|
+
try:
|
|
84
|
+
if self._get_revision(observed) is None:
|
|
85
|
+
self.refresh()
|
|
86
|
+
except BaseException:
|
|
87
|
+
self._endpoint.close()
|
|
88
|
+
raise
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def namespace_id(self) -> str:
|
|
92
|
+
return self._namespace_id
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def closed(self) -> bool:
|
|
96
|
+
with self._state_lock:
|
|
97
|
+
return self._closed
|
|
98
|
+
|
|
99
|
+
def create_class(self, name: str, properties: dict[str, Any] | None = None, *,
|
|
100
|
+
descriptors=None, position=None, order=None, comment=None) -> DClass:
|
|
101
|
+
if not isinstance(name, str) or not name:
|
|
102
|
+
raise ValueError("Class name must be a nonempty string")
|
|
103
|
+
if properties is not None and not isinstance(properties, dict):
|
|
104
|
+
raise TypeError("Class properties must be a dictionary")
|
|
105
|
+
props = dict(properties or {})
|
|
106
|
+
if descriptors is not None:
|
|
107
|
+
props["descriptors"] = _class_declarations(descriptors)
|
|
108
|
+
if position is not None:
|
|
109
|
+
props["position"] = list(_position_value(position))
|
|
110
|
+
if order is not None:
|
|
111
|
+
if type(order) is not int or order < 0:
|
|
112
|
+
raise ValueError("Class order must be a nonnegative integer")
|
|
113
|
+
props["order"] = order
|
|
114
|
+
if comment is not None:
|
|
115
|
+
if not isinstance(comment, str):
|
|
116
|
+
raise TypeError("Class comment must be a string")
|
|
117
|
+
props["comment"] = comment
|
|
118
|
+
_, (data, schema, revision) = self._run_action(
|
|
119
|
+
"deposit.create.class", [name, props], post_snapshot=True
|
|
120
|
+
)
|
|
121
|
+
return DClass(self, data, schema, snapshot_revision=revision)
|
|
122
|
+
|
|
123
|
+
def create_object(self, class_selector: str | dict[str, Any] | DClass, properties: dict[str, Any] | None = None, *,
|
|
124
|
+
descriptors: Mapping[str, Any] | None = None, position=None) -> DObject:
|
|
125
|
+
selector = self._handle_id_or_selector(class_selector, "Class")
|
|
126
|
+
class_handle = class_selector if isinstance(class_selector, DClass) else None
|
|
127
|
+
if properties is not None and not isinstance(properties, dict):
|
|
128
|
+
raise TypeError("Object properties must be a dictionary")
|
|
129
|
+
object_properties = dict(properties or {})
|
|
130
|
+
if descriptors is not None:
|
|
131
|
+
if not isinstance(descriptors, Mapping):
|
|
132
|
+
raise TypeError("Object descriptors must be a mapping")
|
|
133
|
+
if "descriptors" in object_properties:
|
|
134
|
+
raise ValueError("Supply descriptors either in properties or as a keyword")
|
|
135
|
+
object_properties["descriptors"] = dict(descriptors)
|
|
136
|
+
if position is not None:
|
|
137
|
+
object_properties["position"] = list(_position_value(position))
|
|
138
|
+
class_schema, class_revision = {}, None
|
|
139
|
+
if class_handle is not None and not class_handle.stale:
|
|
140
|
+
class_schema, class_revision = class_handle._schema, class_handle._baseline_revision
|
|
141
|
+
elif class_handle is not None or isinstance(selector, str) or object_properties.get("descriptors"):
|
|
142
|
+
# A name can implicitly create a Class on the Server. This convenience
|
|
143
|
+
# requires an existing Class. Descriptors also need the current schema:
|
|
144
|
+
# declared values and new declarations have different wire shapes.
|
|
145
|
+
data, class_schema, class_revision = self._checked_entity_snapshot("Class", selector)
|
|
146
|
+
selector = {"id": data["id"]}
|
|
147
|
+
props = _encode_object_properties(
|
|
148
|
+
object_properties, class_schema, geometry_encoder=self._geometry_write_value,
|
|
149
|
+
resource_encoder=self._resource_write_value,
|
|
150
|
+
)
|
|
151
|
+
_, (data, schema, revision) = self._run_action(
|
|
152
|
+
"deposit.create.object", [selector, props], pinned_revision=class_revision,
|
|
153
|
+
stale_handle=class_handle, post_snapshot=True,
|
|
154
|
+
)
|
|
155
|
+
return DObject(self, data, schema, snapshot_revision=revision)
|
|
156
|
+
|
|
157
|
+
def delete_class(self, dclass: DClass | str | dict[str, Any]):
|
|
158
|
+
selector = self._handle_id_or_selector(dclass, "Class")
|
|
159
|
+
if isinstance(dclass, DClass):
|
|
160
|
+
return self._run_handle_action(dclass, "deposit.delete.class", [selector])
|
|
161
|
+
return self._run_action("deposit.delete.class", [selector])
|
|
162
|
+
|
|
163
|
+
def delete_object(self, dobject: DObject | str | dict[str, Any]):
|
|
164
|
+
selector = self._handle_id_or_selector(dobject, "Object")
|
|
165
|
+
identity = selector["id"] if isinstance(selector, dict) else selector
|
|
166
|
+
if isinstance(dobject, DObject):
|
|
167
|
+
return self._run_handle_action(dobject, "deposit.delete.object", [identity])
|
|
168
|
+
return self._run_action("deposit.delete.object", [identity])
|
|
169
|
+
|
|
170
|
+
def create_descriptor(self, dobject: DObject, name: str, value: Any):
|
|
171
|
+
self._validate_handle(dobject, "Object")
|
|
172
|
+
if not isinstance(name, str) or not name:
|
|
173
|
+
raise ValueError("Descriptor name must be a nonempty string")
|
|
174
|
+
payload = self._prepare_descriptor_payload(value, dobject._schema.get(name))
|
|
175
|
+
return self._run_handle_action(dobject, "deposit.create.descriptor", [dobject.id, name, payload],
|
|
176
|
+
refresh=True)
|
|
177
|
+
|
|
178
|
+
def delete_descriptor(self, dobject: DObject, name: str):
|
|
179
|
+
self._validate_handle(dobject, "Object")
|
|
180
|
+
return self._delete_descriptor(dobject, name)
|
|
181
|
+
|
|
182
|
+
def delete_class_descriptor(self, dclass: DClass, name: str):
|
|
183
|
+
self._validate_handle(dclass, "Class")
|
|
184
|
+
return self._delete_descriptor(dclass, name)
|
|
185
|
+
|
|
186
|
+
def get_class(self, selection: str | dict[str, Any]) -> dict[str, Any]:
|
|
187
|
+
if isinstance(selection, DNode):
|
|
188
|
+
self._validate_handle(selection, "Class")
|
|
189
|
+
return self._read_entity("deposit.get.class", _selector(selection, "Class"))
|
|
190
|
+
|
|
191
|
+
def get_object(self, selection: str | dict[str, Any]) -> dict[str, Any]:
|
|
192
|
+
if isinstance(selection, DNode):
|
|
193
|
+
self._validate_handle(selection, "Object")
|
|
194
|
+
return self._read_entity("deposit.get.object", _selector(selection, "Object"))
|
|
195
|
+
|
|
196
|
+
def get_class_handle(self, selection: str | dict[str, Any] | DClass) -> DClass:
|
|
197
|
+
identity = self._handle_id_or_selector(selection, "Class")
|
|
198
|
+
data, schema, revision = self._checked_entity_snapshot("Class", identity)
|
|
199
|
+
return DClass(self, data, schema, snapshot_revision=revision)
|
|
200
|
+
|
|
201
|
+
def get_object_handle(self, selection: str | dict[str, Any] | DObject) -> DObject:
|
|
202
|
+
identity = self._handle_id_or_selector(selection, "Object")
|
|
203
|
+
data, schema, revision = self._checked_entity_snapshot("Object", identity)
|
|
204
|
+
return DObject(self, data, schema, snapshot_revision=revision)
|
|
205
|
+
|
|
206
|
+
def _handle_id_or_selector(self, selection, kind: str):
|
|
207
|
+
if isinstance(selection, DNode):
|
|
208
|
+
self._validate_handle(selection, kind)
|
|
209
|
+
return {"id": selection.id}
|
|
210
|
+
if kind == "Class":
|
|
211
|
+
return _selector(selection, kind)
|
|
212
|
+
if isinstance(selection, str) and selection:
|
|
213
|
+
return selection
|
|
214
|
+
if isinstance(selection, dict) and set(selection) == {"id"} and isinstance(selection["id"], str):
|
|
215
|
+
return selection
|
|
216
|
+
raise TypeError("Object selector must be a stable UUID or an Object handle")
|
|
217
|
+
|
|
218
|
+
def _validate_handle(self, handle, kind: str | None = None) -> None:
|
|
219
|
+
if not isinstance(handle, DNode) or handle._store is not self:
|
|
220
|
+
raise ValueError("Entity handle belongs to another Store")
|
|
221
|
+
if handle.namespace_id != self._namespace_id or (kind is not None and handle.kind != kind):
|
|
222
|
+
raise ValueError("Entity handle has the wrong Store Namespace or kind")
|
|
223
|
+
|
|
224
|
+
def _register_handle(self, handle) -> None:
|
|
225
|
+
self._handles[id(handle)] = handle
|
|
226
|
+
|
|
227
|
+
def _invalidate_handles(self, *, except_handle=None) -> None:
|
|
228
|
+
for handle in tuple(self._handles.values()):
|
|
229
|
+
if handle is not except_handle:
|
|
230
|
+
handle._mark_stale()
|
|
231
|
+
|
|
232
|
+
def _checked_entity_snapshot(self, kind: str, selection, *, _already_serialized: bool = False,
|
|
233
|
+
expected_revision: int | None = None):
|
|
234
|
+
if kind == "Class":
|
|
235
|
+
calls = (
|
|
236
|
+
"CALL deposit.get.classPage($selection, {pageSize: 1}, $token) YIELD data AS page "
|
|
237
|
+
"WITH page.items[0] AS entity "
|
|
238
|
+
)
|
|
239
|
+
projection = "{entity: entity, schema: entity}"
|
|
240
|
+
elif kind == "Object":
|
|
241
|
+
calls = (
|
|
242
|
+
"CALL deposit.get.objectPage($selection, {pageSize: 1}, $token) YIELD data AS page "
|
|
243
|
+
"WITH page.items[0] AS entity "
|
|
244
|
+
"CALL deposit.get.classPage({id: entity.classId}, {pageSize: 1}, $token) YIELD data AS classPage "
|
|
245
|
+
)
|
|
246
|
+
projection = "{entity: entity, schema: classPage.items[0]}"
|
|
247
|
+
else:
|
|
248
|
+
raise ValueError("Only Class and Object snapshots are supported")
|
|
249
|
+
rows, revision = self._checked_read(
|
|
250
|
+
calls, projection, {"selection": selection}, expected_revision=expected_revision,
|
|
251
|
+
_already_serialized=_already_serialized,
|
|
252
|
+
)
|
|
253
|
+
if len(rows) != 1 or not isinstance(rows[0], dict):
|
|
254
|
+
raise DepositError("INVALID_RESPONSE", "Checked entity snapshot returned no single record")
|
|
255
|
+
entity, schema = rows[0].get("entity"), rows[0].get("schema")
|
|
256
|
+
if not isinstance(entity, dict) or not isinstance(schema, dict):
|
|
257
|
+
raise DepositError("INVALID_RESPONSE", "Checked entity snapshot returned invalid data")
|
|
258
|
+
if entity.get("namespaceId") != self._namespace_id or schema.get("namespaceId") != self._namespace_id:
|
|
259
|
+
raise DepositError("SCOPE_MISMATCH", "Snapshot belongs to another Store Namespace")
|
|
260
|
+
if (entity.get("kind") != kind or schema.get("kind") != "Class"
|
|
261
|
+
or (isinstance(selection, dict) and "id" in selection and _item_id(entity) != selection["id"])):
|
|
262
|
+
raise DepositError("INVALID_RESPONSE", "Checked snapshot returned another entity")
|
|
263
|
+
if kind == "Class":
|
|
264
|
+
return entity, _schema_from_class_data(entity), revision
|
|
265
|
+
if schema.get("id") != entity.get("classId"):
|
|
266
|
+
raise DepositError("INVALID_RESPONSE", "Object snapshot returned another Class schema")
|
|
267
|
+
from .entities import decode_snapshot
|
|
268
|
+
decoded = decode_snapshot(entity, schema, self._namespace_id, self, snapshot_revision=revision)
|
|
269
|
+
return decoded._snapshot, decoded._schema, revision
|
|
270
|
+
|
|
271
|
+
@staticmethod
|
|
272
|
+
def _require_revision(revision: int, expected_revision: int | None) -> None:
|
|
273
|
+
if expected_revision is not None and revision != expected_revision:
|
|
274
|
+
raise DepositError("REVISION_CONFLICT", "Namespace changed during checked iteration or snapshot read")
|
|
275
|
+
|
|
276
|
+
def _checked_read(self, calls: str, projection: str, parameters, *, expected_revision=None,
|
|
277
|
+
_already_serialized=False):
|
|
278
|
+
if not _already_serialized:
|
|
279
|
+
self._assert_not_collecting_batch()
|
|
280
|
+
# The ungrouped collect consumes all portable results before the end
|
|
281
|
+
# revision call and emits one row even when the subquery has no results.
|
|
282
|
+
query = (
|
|
283
|
+
"CYPHER 25 CALL deposit.get.revision($token) YIELD data AS start "
|
|
284
|
+
"CALL (start) { WITH start WHERE $expected IS NULL OR start.sequence = $expected "
|
|
285
|
+
f"{calls} RETURN collect({projection}) AS rows }} "
|
|
286
|
+
"CALL deposit.get.revision($token) YIELD data AS end "
|
|
287
|
+
"RETURN start, rows, end"
|
|
288
|
+
)
|
|
289
|
+
parameters = {**parameters, "token": self._token, "expected": expected_revision}
|
|
290
|
+
with (nullcontext() if _already_serialized else self._serialized()):
|
|
291
|
+
session = None
|
|
292
|
+
transaction = None
|
|
293
|
+
try:
|
|
294
|
+
session = self._client._session()
|
|
295
|
+
transaction = session.begin_transaction()
|
|
296
|
+
result = transaction.run(query, parameters)
|
|
297
|
+
if tuple(result.keys()) != ("start", "rows", "end"):
|
|
298
|
+
raise DepositError("INVALID_RESPONSE", "Checked read returned unexpected columns")
|
|
299
|
+
record = result.single(strict=True)
|
|
300
|
+
result.consume()
|
|
301
|
+
if record is None or not isinstance(record.get("rows"), list):
|
|
302
|
+
raise DepositError("INVALID_RESPONSE", "Checked read returned an invalid result")
|
|
303
|
+
start, end = record.get("start"), record.get("end")
|
|
304
|
+
first = start.get("sequence") if isinstance(start, dict) else None
|
|
305
|
+
last = end.get("sequence") if isinstance(end, dict) else None
|
|
306
|
+
if type(first) is not int or first < 0 or type(last) is not int or last < 0:
|
|
307
|
+
raise DepositError("INVALID_RESPONSE", "Read returned no checked Namespace revision")
|
|
308
|
+
self._require_revision(first, expected_revision)
|
|
309
|
+
self._require_revision(last, first)
|
|
310
|
+
rows = _portable_input(record["rows"])
|
|
311
|
+
transaction.commit()
|
|
312
|
+
return rows, first
|
|
313
|
+
except BaseException as exc:
|
|
314
|
+
if transaction is not None:
|
|
315
|
+
try: transaction.rollback()
|
|
316
|
+
except Exception: pass
|
|
317
|
+
if isinstance(exc, DepositError) or not isinstance(exc, Exception):
|
|
318
|
+
raise
|
|
319
|
+
raise map_driver_error(exc) from exc
|
|
320
|
+
finally:
|
|
321
|
+
if session is not None:
|
|
322
|
+
try: session.close()
|
|
323
|
+
except Exception: pass
|
|
324
|
+
|
|
325
|
+
def _checked_entity_page(self, procedure: str, selection, options, *, expected_revision=None):
|
|
326
|
+
entry = store_procedure(procedure)
|
|
327
|
+
if entry["action"] or tuple(entry["columns"]) != ("data",) or not procedure.endswith("Page"):
|
|
328
|
+
raise ValueError("Checked pages require a read-only Domain Page procedure")
|
|
329
|
+
bound = bind_arguments(entry, (selection, options), namespace_id=self._namespace_id)
|
|
330
|
+
query, parameters = build_query(entry, bound, self._token)
|
|
331
|
+
call = query.removeprefix("CYPHER 25 ").removesuffix(" RETURN data")
|
|
332
|
+
rows, revision = self._checked_read(call, "data", parameters, expected_revision=expected_revision)
|
|
333
|
+
if len(rows) != 1:
|
|
334
|
+
raise DepositError("INVALID_RESPONSE", f"{procedure} returned no single page")
|
|
335
|
+
page = rows[0]
|
|
336
|
+
items = page.get("items") if isinstance(page, dict) else None
|
|
337
|
+
if isinstance(items, list) and any(
|
|
338
|
+
isinstance(item, dict) and "namespaceId" in item and item["namespaceId"] != self.namespace_id
|
|
339
|
+
for item in items
|
|
340
|
+
):
|
|
341
|
+
raise DepositError("SCOPE_MISMATCH", "Page item belongs to another Store Namespace")
|
|
342
|
+
return page, revision
|
|
343
|
+
|
|
344
|
+
def _checked_page_entities(self, kind: str, identities, revision: int | None, *, _already_serialized=False):
|
|
345
|
+
if not identities:
|
|
346
|
+
return {}, revision
|
|
347
|
+
procedure = "deposit.get.classPage" if kind == "Class" else "deposit.get.objectPage"
|
|
348
|
+
calls = (
|
|
349
|
+
"UNWIND $ids AS id "
|
|
350
|
+
f"CALL {procedure}({{id: id}}, {{pageSize: 1}}, $token) YIELD data AS page "
|
|
351
|
+
)
|
|
352
|
+
rows, checked_revision = self._checked_read(
|
|
353
|
+
calls, "page.items[0]", {"ids": list(identities)}, expected_revision=revision,
|
|
354
|
+
_already_serialized=_already_serialized,
|
|
355
|
+
)
|
|
356
|
+
entities = {}
|
|
357
|
+
for row in rows:
|
|
358
|
+
if not isinstance(row, dict) or row.get("kind") != kind:
|
|
359
|
+
raise DepositError("INVALID_RESPONSE", f"Expected portable {kind} data")
|
|
360
|
+
if row.get("namespaceId") != self._namespace_id:
|
|
361
|
+
raise DepositError("SCOPE_MISMATCH", "Page entity belongs to another Store Namespace")
|
|
362
|
+
entities[_item_id(row)] = row
|
|
363
|
+
if len(rows) != len(identities) or entities.keys() != set(identities):
|
|
364
|
+
raise DepositError("INVALID_RESPONSE", "Checked read returned unexpected entity identities")
|
|
365
|
+
return entities, checked_revision
|
|
366
|
+
|
|
367
|
+
def _class_page_handles(self, items, revision):
|
|
368
|
+
handles = []
|
|
369
|
+
for item in items:
|
|
370
|
+
_item_id(item)
|
|
371
|
+
handles.append(DClass(self, item, _schema_from_class_data(item), snapshot_revision=revision))
|
|
372
|
+
return handles
|
|
373
|
+
|
|
374
|
+
def _object_page_handles(self, items, revision, schemas, known_class=None):
|
|
375
|
+
from .entities import decode_snapshot
|
|
376
|
+
class_ids = {}
|
|
377
|
+
for item in items:
|
|
378
|
+
_item_id(item)
|
|
379
|
+
class_id = item.get("classId")
|
|
380
|
+
if item.get("kind") != "Object" or not isinstance(class_id, str) or not class_id:
|
|
381
|
+
raise DepositError("INVALID_RESPONSE", "Object page omitted Class identity")
|
|
382
|
+
if item.get("namespaceId") != self._namespace_id:
|
|
383
|
+
raise DepositError("SCOPE_MISMATCH", "Page entity belongs to another Store Namespace")
|
|
384
|
+
class_ids[class_id] = None
|
|
385
|
+
if known_class is not None:
|
|
386
|
+
snapshot = known_class._snapshot
|
|
387
|
+
if (snapshot is not None and not known_class.stale and known_class._baseline_revision == revision
|
|
388
|
+
and snapshot is known_class._snapshot):
|
|
389
|
+
schemas[known_class.id] = snapshot
|
|
390
|
+
missing = [class_id for class_id in class_ids if class_id not in schemas]
|
|
391
|
+
fetched, _ = self._checked_page_entities("Class", missing, revision)
|
|
392
|
+
schemas.update(fetched)
|
|
393
|
+
handles = [decode_snapshot(item, schemas[item["classId"]], self._namespace_id, self,
|
|
394
|
+
snapshot_revision=revision) for item in items]
|
|
395
|
+
# Only retain schemas used by the latest page. A single iterator pins its revision.
|
|
396
|
+
used = {class_id: schemas[class_id] for class_id in class_ids}
|
|
397
|
+
schemas.clear()
|
|
398
|
+
schemas.update(used)
|
|
399
|
+
return handles
|
|
400
|
+
|
|
401
|
+
def set_descriptor(self, dobject: DObject, name: str, value: Any) -> dict[str, Any]:
|
|
402
|
+
self._validate_handle(dobject, "Object")
|
|
403
|
+
if not isinstance(name, str) or not name:
|
|
404
|
+
raise ValueError("Descriptor name must be a nonempty string")
|
|
405
|
+
payload = self._prepare_descriptor_payload(value, dobject._schema.get(name))
|
|
406
|
+
return self._submit_descriptor_payload(dobject, name, payload)
|
|
407
|
+
|
|
408
|
+
def _prepare_descriptor_payload(self, value: Any, declared: str | None) -> Any:
|
|
409
|
+
return _descriptor_payload(
|
|
410
|
+
value, declared, geometry_encoder=self._geometry_write_value,
|
|
411
|
+
resource_encoder=self._resource_write_value,
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
def _submit_descriptor_payload(self, dobject: DObject, name: str, payload: Any) -> dict[str, Any]:
|
|
415
|
+
return self._run_handle_action(dobject, "deposit.set.descriptor", [dobject.id, name, payload], refresh=True)
|
|
416
|
+
|
|
417
|
+
def _geometry_write_value(self, value: Any) -> dict[str, Any]:
|
|
418
|
+
from .values import DGeometry, TypedValue
|
|
419
|
+
if isinstance(value, TypedValue):
|
|
420
|
+
value = value.value
|
|
421
|
+
if not isinstance(value, DGeometry):
|
|
422
|
+
if isinstance(value, Mapping) and value.get("type") == "DGeometry":
|
|
423
|
+
value = DGeometry(from_dict=value)
|
|
424
|
+
elif isinstance(value, Mapping):
|
|
425
|
+
value = DGeometry(from_dict={"type": "DGeometry", "value": dict(value)})
|
|
426
|
+
else:
|
|
427
|
+
raise TypeError("DGeometry assignments require a DGeometry value")
|
|
428
|
+
value.resolve(self)
|
|
429
|
+
# Identity and cached coordinates remain local. Server owns and updates
|
|
430
|
+
# the geometry attached to the destination Descriptor.
|
|
431
|
+
return {key: value._value[key] for key in
|
|
432
|
+
("wkt", "srid", "verticalSrid", "axisOrder", "dimensions")}
|
|
433
|
+
|
|
434
|
+
@staticmethod
|
|
435
|
+
def _resource_write_value(value: Any) -> dict[str, str]:
|
|
436
|
+
from .values import DResource, TypedValue
|
|
437
|
+
if isinstance(value, TypedValue):
|
|
438
|
+
value = value.value
|
|
439
|
+
if isinstance(value, DResource):
|
|
440
|
+
value = value._value
|
|
441
|
+
if isinstance(value, Mapping) and value.get("type") == "DResource":
|
|
442
|
+
value = value.get("value")
|
|
443
|
+
if not isinstance(value, Mapping):
|
|
444
|
+
raise TypeError("DResource assignments require a ready resource reference")
|
|
445
|
+
resource_id = value.get("resourceId")
|
|
446
|
+
if not isinstance(resource_id, str) or not resource_id:
|
|
447
|
+
raise ValueError("Upload the resource before assigning it to a Descriptor")
|
|
448
|
+
# Filename and image metadata are local/display fields. The Server
|
|
449
|
+
# accepts only the resource identity for Descriptor assignment.
|
|
450
|
+
return {"resourceId": resource_id}
|
|
451
|
+
|
|
452
|
+
def _delete_descriptor(self, owner: DNode, name: str) -> dict[str, Any]:
|
|
453
|
+
if owner.kind == "Object":
|
|
454
|
+
procedure = "deposit.delete.descriptor"
|
|
455
|
+
selector = {"objectId": owner.id, "name": name}
|
|
456
|
+
else:
|
|
457
|
+
procedure = "deposit.delete.classDescriptor"
|
|
458
|
+
declaration = owner.declarations.get(name)
|
|
459
|
+
if declaration is None:
|
|
460
|
+
raise KeyError(name)
|
|
461
|
+
selector = {"id": _item_id(declaration)}
|
|
462
|
+
return self._run_handle_action(owner, procedure, [selector], refresh=True)
|
|
463
|
+
|
|
464
|
+
def create_class_descriptor(self, dclass: DClass, name: str, type_name: str, comment: str = "") -> dict[str, Any]:
|
|
465
|
+
self._validate_handle(dclass, "Class")
|
|
466
|
+
if not isinstance(name, str) or not name or not isinstance(type_name, str) or not type_name:
|
|
467
|
+
raise ValueError("Descriptor name and type must be nonempty strings")
|
|
468
|
+
return self._run_handle_action(dclass, "deposit.create.classDescriptor",
|
|
469
|
+
[{"id": dclass.id}, name, type_name, {"comment": comment}], refresh=True)
|
|
470
|
+
|
|
471
|
+
def set_class_descriptor(self, selector: dict[str, Any], patch: dict[str, Any], *,
|
|
472
|
+
dclass: DClass | None = None) -> dict[str, Any]:
|
|
473
|
+
selector_dclass = selector if isinstance(selector, DClass) else None
|
|
474
|
+
owner = dclass or selector_dclass
|
|
475
|
+
if selector_dclass is not None:
|
|
476
|
+
self._validate_handle(selector_dclass, "Class")
|
|
477
|
+
name = patch.get("name") if isinstance(patch, dict) else None
|
|
478
|
+
declaration = selector_dclass.declarations.get(name) if isinstance(name, str) else None
|
|
479
|
+
if declaration is None:
|
|
480
|
+
raise KeyError(name)
|
|
481
|
+
selector = {"id": declaration["id"]}
|
|
482
|
+
patch = {key: value for key, value in patch.items() if key != "name"}
|
|
483
|
+
if owner is not None:
|
|
484
|
+
self._validate_handle(owner, "Class")
|
|
485
|
+
descriptor_id = selector.get("id") if isinstance(selector, Mapping) else None
|
|
486
|
+
if descriptor_id is not None and descriptor_id not in {
|
|
487
|
+
item.get("id") for item in owner.declarations.values()
|
|
488
|
+
}:
|
|
489
|
+
raise ValueError("Class Descriptor selector does not belong to the supplied Class handle")
|
|
490
|
+
if not isinstance(selector, dict) or not isinstance(patch, dict):
|
|
491
|
+
raise TypeError("selector and patch must be dictionaries")
|
|
492
|
+
if owner is not None:
|
|
493
|
+
return self._run_handle_action(owner, "deposit.set.classDescriptor", [selector, patch], refresh=True)
|
|
494
|
+
return self._run_action("deposit.set.classDescriptor", [selector, patch])
|
|
495
|
+
|
|
496
|
+
def set_class_properties(self, dclass: DClass, **patch) -> dict[str, Any]:
|
|
497
|
+
self._validate_handle(dclass, "Class")
|
|
498
|
+
allowed = {"name", "position", "order", "comment"}
|
|
499
|
+
if not patch or set(patch) - allowed:
|
|
500
|
+
raise ValueError("Class patch must contain supported fields")
|
|
501
|
+
if "name" in patch and (not isinstance(patch["name"], str) or not patch["name"]):
|
|
502
|
+
raise ValueError("Class name must be a nonempty string")
|
|
503
|
+
if "comment" in patch and not isinstance(patch["comment"], str):
|
|
504
|
+
raise TypeError("Class comment must be a string")
|
|
505
|
+
if "order" in patch and (type(patch["order"]) is not int or patch["order"] < 0):
|
|
506
|
+
raise ValueError("Class order must be a nonnegative integer")
|
|
507
|
+
if "position" in patch:
|
|
508
|
+
patch["position"] = list(_position_value(patch["position"]))
|
|
509
|
+
return self._run_handle_action(dclass, "deposit.set.class", [{"id": dclass.id}, patch], refresh=True)
|
|
510
|
+
|
|
511
|
+
def set_position(self, node: DNode, x: float, y: float) -> dict[str, Any]:
|
|
512
|
+
self._validate_handle(node)
|
|
513
|
+
position = _position_value((x, y))
|
|
514
|
+
if node.kind == "Class":
|
|
515
|
+
procedure, selector = "deposit.set.class", {"id": node.id}
|
|
516
|
+
elif node.kind == "Object":
|
|
517
|
+
procedure, selector = "deposit.set.object", node.id
|
|
518
|
+
else:
|
|
519
|
+
raise TypeError("Only Class and Object handles have a position")
|
|
520
|
+
return self._run_handle_action(node, procedure, [selector, {"position": list(position)}], refresh=True)
|
|
521
|
+
|
|
522
|
+
def change_class_descriptor_type(self, dclass: DClass, name: str, type_name: str, *, conversion: str):
|
|
523
|
+
self._validate_handle(dclass, "Class")
|
|
524
|
+
declaration = dclass.declarations.get(name)
|
|
525
|
+
if declaration is None:
|
|
526
|
+
raise KeyError(name)
|
|
527
|
+
if not isinstance(type_name, str) or not type_name:
|
|
528
|
+
raise ValueError("type_name must be a nonempty string")
|
|
529
|
+
if conversion not in {"identity", "integerToFloat", "floatToIntegerExact"}:
|
|
530
|
+
raise ValueError("Unsupported class Descriptor conversion")
|
|
531
|
+
return self._run_handle_action(dclass, "deposit.set.classDescriptor", [
|
|
532
|
+
{"id": declaration["id"]}, {"type": type_name, "conversion": conversion},
|
|
533
|
+
], refresh=True)
|
|
534
|
+
|
|
535
|
+
def switch_descriptor_order(self, dclass: DClass, name1: str, name2: str):
|
|
536
|
+
self._validate_handle(dclass, "Class")
|
|
537
|
+
first, second = dclass.declarations.get(name1), dclass.declarations.get(name2)
|
|
538
|
+
if first is None or second is None:
|
|
539
|
+
raise KeyError(name1 if first is None else name2)
|
|
540
|
+
if first["id"] == second["id"]:
|
|
541
|
+
return {"changed": False}
|
|
542
|
+
with self.transaction() as batch:
|
|
543
|
+
batch._pin_handle(dclass, "Class")
|
|
544
|
+
batch.call("deposit.set.classDescriptor", {"id": first["id"]}, {"order": second.get("order", 0)})
|
|
545
|
+
batch.call("deposit.set.classDescriptor", {"id": second["id"]}, {"order": first.get("order", 0)})
|
|
546
|
+
batch._refresh_handles = (dclass,)
|
|
547
|
+
return {"changed": True}
|
|
548
|
+
|
|
549
|
+
def switch_class_order(self, first: DClass, second: DClass):
|
|
550
|
+
self._validate_handle(first, "Class")
|
|
551
|
+
self._validate_handle(second, "Class")
|
|
552
|
+
if first.id == second.id:
|
|
553
|
+
return {"changed": False}
|
|
554
|
+
if first._baseline_revision != second._baseline_revision:
|
|
555
|
+
raise ValueError("Class handles have conflicting checked snapshot revisions")
|
|
556
|
+
with self.transaction() as batch:
|
|
557
|
+
batch._pin_handle(first, "Class")
|
|
558
|
+
batch._pin_handle(second, "Class")
|
|
559
|
+
batch.call("deposit.set.class", {"id": first.id}, {"order": second.order})
|
|
560
|
+
batch.call("deposit.set.class", {"id": second.id}, {"order": first.order})
|
|
561
|
+
batch._refresh_handles = (first, second)
|
|
562
|
+
return {"changed": True}
|
|
563
|
+
|
|
564
|
+
def set_membership(self, dobject: DObject, dclass: DClass | str | dict[str, Any]):
|
|
565
|
+
self._validate_handle(dobject, "Object")
|
|
566
|
+
selector = self._handle_id_or_selector(dclass, "Class")
|
|
567
|
+
handles = (dobject, dclass) if isinstance(dclass, DClass) else (dobject,)
|
|
568
|
+
revision = _matching_handle_revision(*handles)
|
|
569
|
+
try:
|
|
570
|
+
return self._run_action("deposit.set.membership", [dobject.id, selector],
|
|
571
|
+
pinned_revision=revision, refresh_handles=(dobject,))
|
|
572
|
+
except DepositError as exc:
|
|
573
|
+
if exc.code == "REVISION_CONFLICT":
|
|
574
|
+
for handle in handles:
|
|
575
|
+
handle._mark_stale()
|
|
576
|
+
raise
|
|
577
|
+
|
|
578
|
+
def object_class(self, dobject: DObject) -> DClass:
|
|
579
|
+
self._validate_handle(dobject, "Object")
|
|
580
|
+
rows, revision = self._checked_read(
|
|
581
|
+
"CALL deposit.get.objectClass($object, $token) YIELD node "
|
|
582
|
+
"CALL deposit.utils.toData(node, $token) YIELD data ",
|
|
583
|
+
"data", {"object": dobject.id},
|
|
584
|
+
)
|
|
585
|
+
if len(rows) != 1 or not isinstance(rows[0], dict) or rows[0].get("kind") != "Class":
|
|
586
|
+
raise DepositError("INVALID_RESPONSE", "Object class lookup returned no Class snapshot")
|
|
587
|
+
return DClass(self, rows[0], _schema_from_class_data(rows[0]), snapshot_revision=revision)
|
|
588
|
+
|
|
589
|
+
def create_relationship(self, src_object: DObject, tgt_object: DObject, label: str, weight=None):
|
|
590
|
+
self._validate_handle(src_object, "Object")
|
|
591
|
+
self._validate_handle(tgt_object, "Object")
|
|
592
|
+
if not isinstance(label, str) or not label:
|
|
593
|
+
raise ValueError("Relationship label must be a nonempty string")
|
|
594
|
+
revision = _matching_handle_revision(src_object, tgt_object)
|
|
595
|
+
properties = {} if weight is None else {"weight": weight}
|
|
596
|
+
return self._run_multi_handle_action("deposit.create.relationship",
|
|
597
|
+
[src_object.id, tgt_object.id, label, properties],
|
|
598
|
+
revision, (src_object, tgt_object))
|
|
599
|
+
|
|
600
|
+
def create_class_relationship(self, src_class: DClass, tgt_class: DClass, label: str, comment=""):
|
|
601
|
+
self._validate_handle(src_class, "Class")
|
|
602
|
+
self._validate_handle(tgt_class, "Class")
|
|
603
|
+
if not isinstance(label, str) or not label or not isinstance(comment, str):
|
|
604
|
+
raise ValueError("Class relationship label and comment must be strings")
|
|
605
|
+
revision = _matching_handle_revision(src_class, tgt_class)
|
|
606
|
+
return self._run_multi_handle_action(
|
|
607
|
+
"deposit.create.classRelationship", [
|
|
608
|
+
{"id": src_class.id}, {"id": tgt_class.id}, label, {"comment": comment},
|
|
609
|
+
], revision, (src_class, tgt_class),
|
|
610
|
+
)
|
|
611
|
+
|
|
612
|
+
def set_relationship(self, relationship_id: str, **patch):
|
|
613
|
+
if not isinstance(relationship_id, str) or not relationship_id:
|
|
614
|
+
raise ValueError("relationship_id must be a nonempty stable ID")
|
|
615
|
+
if not patch:
|
|
616
|
+
raise ValueError("Relationship patch must not be empty")
|
|
617
|
+
return self._run_action("deposit.set.relationship", [relationship_id, patch])
|
|
618
|
+
|
|
619
|
+
def set_class_relationship(self, relationship_id: str, **patch):
|
|
620
|
+
if not isinstance(relationship_id, str) or not relationship_id:
|
|
621
|
+
raise ValueError("relationship_id must be a nonempty stable ID")
|
|
622
|
+
if not patch:
|
|
623
|
+
raise ValueError("Class relationship patch must not be empty")
|
|
624
|
+
return self._run_action("deposit.set.classRelationship", [relationship_id, patch])
|
|
625
|
+
|
|
626
|
+
def delete_relationship(self, relationship_id: str):
|
|
627
|
+
return self._run_action("deposit.delete.relationship", [_stable_id(relationship_id)])
|
|
628
|
+
|
|
629
|
+
def delete_class_relationship(self, relationship_id: str):
|
|
630
|
+
return self._run_action("deposit.delete.classRelationship", [_stable_id(relationship_id)])
|
|
631
|
+
|
|
632
|
+
def delete_all(self, confirm_namespace_name: str):
|
|
633
|
+
if not isinstance(confirm_namespace_name, str) or not confirm_namespace_name:
|
|
634
|
+
raise ValueError("Namespace name confirmation must be a nonempty string")
|
|
635
|
+
return self._run_action("deposit.delete.all", [confirm_namespace_name])
|
|
636
|
+
|
|
637
|
+
def get_relationship(self, selection: str | dict[str, Any]):
|
|
638
|
+
return self._call_one("deposit.get.relationship", selection)
|
|
639
|
+
|
|
640
|
+
def get_class_relationship(self, selection: str | dict[str, Any]):
|
|
641
|
+
return self._call_one("deposit.get.classRelationship", selection)
|
|
642
|
+
|
|
643
|
+
def create_user_tool(self, name: str, data: str, comment: str = ""):
|
|
644
|
+
if not isinstance(name, str) or not name or not isinstance(data, str) or not isinstance(comment, str):
|
|
645
|
+
raise ValueError("User Tool name, data, and comment must be strings")
|
|
646
|
+
return self._run_action("deposit.create.userTool", [name, {"data": data, "comment": comment}])
|
|
647
|
+
|
|
648
|
+
def set_user_tool(self, user_tool_id: str, **patch):
|
|
649
|
+
return self._run_action("deposit.set.userTool", [{"id": _stable_id(user_tool_id)}, patch])
|
|
650
|
+
|
|
651
|
+
def delete_user_tool(self, user_tool_id: str):
|
|
652
|
+
return self._run_action("deposit.delete.userTool", [{"id": _stable_id(user_tool_id)}])
|
|
653
|
+
|
|
654
|
+
def upload_resource(self, resource: DResource) -> DResource:
|
|
655
|
+
"""Upload a local resource once, consuming a borrowed stream from its current position."""
|
|
656
|
+
self._assert_not_collecting_batch()
|
|
657
|
+
if not isinstance(resource, DResource):
|
|
658
|
+
raise TypeError("resource must be a DResource")
|
|
659
|
+
if resource.resource_id is not None and resource._path is None and resource._stream is None:
|
|
660
|
+
if resource._value.get("namespaceId") not in (None, self.namespace_id):
|
|
661
|
+
raise DepositError("SCOPE_MISMATCH", "Resource belongs to another Namespace")
|
|
662
|
+
return resource
|
|
663
|
+
with self._serialized(), self._using_endpoint() as endpoint:
|
|
664
|
+
return upload_resource(endpoint, resource)
|
|
665
|
+
|
|
666
|
+
def _open_resource(self, resource: DResource):
|
|
667
|
+
self._assert_not_collecting_batch()
|
|
668
|
+
if not isinstance(resource, DResource) or not resource.resource_id:
|
|
669
|
+
raise ValueError("resource must be a stored DResource reference")
|
|
670
|
+
if resource._value.get("namespaceId") not in (None, self._namespace_id):
|
|
671
|
+
raise DepositError("SCOPE_MISMATCH", "Resource belongs to another Namespace")
|
|
672
|
+
with self._serialized():
|
|
673
|
+
metadata = self._endpoint.call("deposit.resource.info", resource.resource_id)
|
|
674
|
+
if not isinstance(metadata, dict) or metadata.get("resourceId") != resource.resource_id:
|
|
675
|
+
raise DepositError("INVALID_RESPONSE", "Resource metadata did not match the selected resource")
|
|
676
|
+
resource._value.update(metadata)
|
|
677
|
+
reader = ResourceReader(self._read_resource_chunk, resource.resource_id, metadata)
|
|
678
|
+
self._readers[id(reader)] = reader
|
|
679
|
+
return reader
|
|
680
|
+
|
|
681
|
+
def _read_resource_chunk(self, procedure, *arguments):
|
|
682
|
+
self._check_result_reader()
|
|
683
|
+
return self._endpoint.control(procedure, *arguments)
|
|
684
|
+
|
|
685
|
+
def _open_import_resource(self, record, *, read):
|
|
686
|
+
"""Check the exact source resource even when another ID shares its bytes."""
|
|
687
|
+
self._check_result_reader()
|
|
688
|
+
resource_id = _stable_id(record.get("id"))
|
|
689
|
+
metadata = self._endpoint.control("deposit.resource.info", resource_id)
|
|
690
|
+
if (not isinstance(metadata, dict) or metadata.get("resourceId") != resource_id
|
|
691
|
+
or metadata.get("bytes") != record.get("bytes")
|
|
692
|
+
or record.get("entry") != f"resources/{metadata.get('checksum')}"):
|
|
693
|
+
raise DepositError("RESOURCE_CORRUPT", "Source resource differs from the snapshot")
|
|
694
|
+
if not read:
|
|
695
|
+
return None
|
|
696
|
+
return ResourceReader(self._read_resource_chunk, resource_id, metadata)
|
|
697
|
+
|
|
698
|
+
def create_pattern(self, name: str, definition: Mapping[str, Any],
|
|
699
|
+
properties: Mapping[str, Any] | None = None) -> dict[str, Any]:
|
|
700
|
+
"""Create a Pattern and return the server-authored portable entity."""
|
|
701
|
+
if not isinstance(name, str) or not name:
|
|
702
|
+
raise ValueError("Pattern name must be a nonempty string")
|
|
703
|
+
if not isinstance(definition, Mapping):
|
|
704
|
+
raise TypeError("Pattern definition must be a mapping")
|
|
705
|
+
if properties is not None and not isinstance(properties, Mapping):
|
|
706
|
+
raise TypeError("Pattern properties must be a mapping")
|
|
707
|
+
outcome = self._run_action(
|
|
708
|
+
"deposit.create.pattern",
|
|
709
|
+
[name, dict(definition), dict(properties or {})],
|
|
710
|
+
)
|
|
711
|
+
if not isinstance(outcome, dict):
|
|
712
|
+
raise DepositError("INVALID_RESPONSE", "Pattern creation returned no portable entity")
|
|
713
|
+
return outcome
|
|
714
|
+
|
|
715
|
+
def get_pattern(self, selection: str | Mapping[str, Any]) -> dict[str, Any]:
|
|
716
|
+
"""Read one Pattern using a server-supported name or ID selector."""
|
|
717
|
+
return self._read_entity("deposit.get.pattern", _pattern_selector(selection))
|
|
718
|
+
|
|
719
|
+
def set_pattern(self, pattern: str | Mapping[str, Any], **patch: Any) -> dict[str, Any]:
|
|
720
|
+
"""Apply a Pattern patch and preserve the server's returned definition."""
|
|
721
|
+
if not patch:
|
|
722
|
+
raise ValueError("Pattern patch cannot be empty")
|
|
723
|
+
return self._run_action(
|
|
724
|
+
"deposit.set.pattern", [_pattern_selector(pattern), patch]
|
|
725
|
+
)
|
|
726
|
+
|
|
727
|
+
def delete_pattern(self, pattern: str | Mapping[str, Any]) -> Any:
|
|
728
|
+
"""Delete one Pattern through the namespace-scoped server procedure."""
|
|
729
|
+
return self._run_action("deposit.delete.pattern", [_pattern_selector(pattern)])
|
|
730
|
+
|
|
731
|
+
def patterns(self, name: str | None = None, *, page_size: int = 200):
|
|
732
|
+
"""Iterate server-paged Pattern records without interpreting definitions."""
|
|
733
|
+
if name is not None and (not isinstance(name, str) or not name):
|
|
734
|
+
raise ValueError("Pattern name filter must be a nonempty string")
|
|
735
|
+
return self._entity_page(
|
|
736
|
+
"deposit.get.patternPage", name, page_size=page_size,
|
|
737
|
+
transform=lambda item, _revision: item,
|
|
738
|
+
)
|
|
739
|
+
|
|
740
|
+
def objects_by_pattern(
|
|
741
|
+
self,
|
|
742
|
+
pattern: Mapping[str, Any],
|
|
743
|
+
values: Mapping[str, Any] | None = None,
|
|
744
|
+
rules: Mapping[str, Any] | None = None,
|
|
745
|
+
*,
|
|
746
|
+
page_size: int = 200,
|
|
747
|
+
cursor: str | None = None,
|
|
748
|
+
) -> dict[str, Any]:
|
|
749
|
+
"""Request one server-matched Pattern page using an ID-only selector."""
|
|
750
|
+
if not isinstance(pattern, Mapping):
|
|
751
|
+
raise TypeError("Pattern search requires an {id: UUID} selector mapping")
|
|
752
|
+
if values is not None and not isinstance(values, Mapping):
|
|
753
|
+
raise TypeError("Pattern values must be a mapping")
|
|
754
|
+
if rules is not None and not isinstance(rules, Mapping):
|
|
755
|
+
raise TypeError("Pattern rules must be a mapping")
|
|
756
|
+
if type(page_size) is not int or not 1 <= page_size <= 1000:
|
|
757
|
+
raise ValueError("page_size must be an integer from 1 through 1000")
|
|
758
|
+
if cursor is not None and (not isinstance(cursor, str) or not cursor):
|
|
759
|
+
raise ValueError("cursor must be a nonempty string")
|
|
760
|
+
page = {"pageSize": page_size}
|
|
761
|
+
if cursor is not None:
|
|
762
|
+
page["cursor"] = cursor
|
|
763
|
+
result = self._call_one(
|
|
764
|
+
"deposit.get.objectsByPatternPage",
|
|
765
|
+
_pattern_id_selector(pattern),
|
|
766
|
+
_portable_input(dict(values or {})),
|
|
767
|
+
_portable_input(dict(rules or {})),
|
|
768
|
+
page,
|
|
769
|
+
)
|
|
770
|
+
if not isinstance(result, dict):
|
|
771
|
+
raise DepositError("INVALID_RESPONSE", "Pattern search returned no portable page")
|
|
772
|
+
return result
|
|
773
|
+
|
|
774
|
+
def import_data_by_pattern(
|
|
775
|
+
self,
|
|
776
|
+
pattern: Mapping[str, Any],
|
|
777
|
+
values: Mapping[str, Any],
|
|
778
|
+
rules: Mapping[str, Any] | None = None,
|
|
779
|
+
*, operation_id=None,
|
|
780
|
+
):
|
|
781
|
+
"""Analyze form data for an ID-selected Pattern with an optional analysis ID."""
|
|
782
|
+
if not isinstance(pattern, Mapping) or not isinstance(values, Mapping):
|
|
783
|
+
raise TypeError("Pattern must be an {id: UUID} selector and form values must be a mapping")
|
|
784
|
+
if rules is not None and not isinstance(rules, Mapping):
|
|
785
|
+
raise TypeError("Pattern rules must be a mapping")
|
|
786
|
+
return self._analyze("deposit.import.dataByPattern", [
|
|
787
|
+
_portable_input(dict(pattern)), _portable_input(dict(values)), _import_rules(rules),
|
|
788
|
+
], operation_id=operation_id)
|
|
789
|
+
|
|
790
|
+
def get_layout(
|
|
791
|
+
self, selection: Mapping[str, Any], options: Mapping[str, Any] | None = None
|
|
792
|
+
) -> dict[str, Any]:
|
|
793
|
+
"""Return the server-computed graph layout for the selected entities."""
|
|
794
|
+
if not isinstance(selection, Mapping):
|
|
795
|
+
raise TypeError("Layout selection must be a mapping")
|
|
796
|
+
if options is not None and not isinstance(options, Mapping):
|
|
797
|
+
raise TypeError("Layout options must be a mapping")
|
|
798
|
+
result = self._call_one(
|
|
799
|
+
"deposit.get.layout",
|
|
800
|
+
_portable_input(dict(selection)),
|
|
801
|
+
_portable_input(dict(options or {})),
|
|
802
|
+
)
|
|
803
|
+
if not isinstance(result, dict):
|
|
804
|
+
raise DepositError("INVALID_RESPONSE", "Server returned no layout result")
|
|
805
|
+
positions = result.get("positions")
|
|
806
|
+
if not isinstance(positions, dict):
|
|
807
|
+
raise DepositError("INVALID_RESPONSE", "Server returned an invalid layout result")
|
|
808
|
+
return positions
|
|
809
|
+
|
|
810
|
+
def get_subtree(
|
|
811
|
+
self, roots=None, *, max_hops: int | None = None, root_class_boundary: bool = True
|
|
812
|
+
) -> dict[str, Any]:
|
|
813
|
+
"""Return a revision-pinned snapshot of the current scientific graph."""
|
|
814
|
+
self._assert_not_collecting_batch()
|
|
815
|
+
if roots is not None and not isinstance(roots, (str, bytes)):
|
|
816
|
+
roots = list(roots)
|
|
817
|
+
roots, options = self._export_arguments(roots, max_hops, root_class_boundary)
|
|
818
|
+
options["includeHistory"] = False
|
|
819
|
+
with self._serialized(), self._using_endpoint() as endpoint:
|
|
820
|
+
with endpoint.execution() as execution:
|
|
821
|
+
data = execution.run("deposit.get.data", roots, options)
|
|
822
|
+
if isinstance(data, dict) and "manifest" in data and "graph" in data:
|
|
823
|
+
return {"manifest": data["manifest"], "graph": data["graph"]}
|
|
824
|
+
from ._exchange import materialize_snapshot
|
|
825
|
+
try:
|
|
826
|
+
return materialize_snapshot(ExchangeBundle(endpoint, data))
|
|
827
|
+
finally:
|
|
828
|
+
discard_package(endpoint, data)
|
|
829
|
+
|
|
830
|
+
def to_networkx(
|
|
831
|
+
self, roots=None, *, max_hops: int | None = None, root_class_boundary: bool = True
|
|
832
|
+
):
|
|
833
|
+
"""Export the selected snapshot as a NetworkX MultiDiGraph."""
|
|
834
|
+
return to_networkx(self.get_subtree(
|
|
835
|
+
roots, max_hops=max_hops, root_class_boundary=root_class_boundary,
|
|
836
|
+
))
|
|
837
|
+
|
|
838
|
+
def from_networkx(self, graph, *, resources=None, resource_source=None, rules=None, operation_id=None):
|
|
839
|
+
"""Analyze a Deposit MultiDiGraph with an optional analysis ID."""
|
|
840
|
+
return self.from_dict(from_networkx(graph), resources=resources, resource_source=resource_source,
|
|
841
|
+
rules=rules, operation_id=operation_id)
|
|
842
|
+
|
|
843
|
+
def import_rows(self, rows, relationships=None, *, targets=None, rules=None, operation_id=None):
|
|
844
|
+
"""Analyze tabular input on the Server with an optional analysis ID."""
|
|
845
|
+
frozen_rows = _freeze_import_rows(rows)
|
|
846
|
+
if relationships is None:
|
|
847
|
+
frozen_relationships = []
|
|
848
|
+
else:
|
|
849
|
+
if not isinstance(relationships, (list, tuple)):
|
|
850
|
+
raise TypeError("relationships must be a list of relationship records")
|
|
851
|
+
frozen_relationships = []
|
|
852
|
+
for relationship in relationships:
|
|
853
|
+
if not isinstance(relationship, Mapping):
|
|
854
|
+
raise TypeError("relationships must contain mapping records")
|
|
855
|
+
frozen_relationships.append(dict(relationship))
|
|
856
|
+
if targets is not None and not isinstance(targets, Mapping):
|
|
857
|
+
raise TypeError("targets must be a mapping")
|
|
858
|
+
return self._analyze("deposit.import.rows", [
|
|
859
|
+
_portable_input({"rows": frozen_rows}), _portable_input(dict(targets or {})),
|
|
860
|
+
_portable_input(frozen_relationships), _import_rules(rules),
|
|
861
|
+
], operation_id=operation_id)
|
|
862
|
+
|
|
863
|
+
def import_subtree(self, subtree, *, resources=None, resource_source=None, rules=None, operation_id=None):
|
|
864
|
+
"""Analyze a public subgraph with optional resources and an optional analysis ID."""
|
|
865
|
+
return self.from_dict(subtree, resources=resources, resource_source=resource_source,
|
|
866
|
+
rules=rules, operation_id=operation_id)
|
|
867
|
+
|
|
868
|
+
def from_dict(self, data, *, resources=None, resource_source=None, rules=None, operation_id=None):
|
|
869
|
+
"""Analyze a public graph and its resources with an optional analysis ID."""
|
|
870
|
+
if not isinstance(data, Mapping):
|
|
871
|
+
raise TypeError("Import snapshot must be a manifest/graph mapping")
|
|
872
|
+
return self._analyze_package(
|
|
873
|
+
lambda endpoint: stage_snapshot(endpoint, data, resources=resources, resource_source=resource_source),
|
|
874
|
+
rules, operation_id=operation_id,
|
|
875
|
+
)
|
|
876
|
+
|
|
877
|
+
def _export_arguments(self, roots, max_hops, root_class_boundary):
|
|
878
|
+
selection = None
|
|
879
|
+
if roots is not None:
|
|
880
|
+
if not isinstance(roots, (list, tuple)):
|
|
881
|
+
raise TypeError("roots must be a list or tuple of Object UUIDs")
|
|
882
|
+
if len(roots) > (1_048_576 - 1024) // 39:
|
|
883
|
+
raise DepositError("LIMIT_EXCEEDED", "Explicit export selector exceeds request budget")
|
|
884
|
+
selection = []
|
|
885
|
+
for root in roots:
|
|
886
|
+
if isinstance(root, DObject):
|
|
887
|
+
self._validate_handle(root, "Object")
|
|
888
|
+
root = root.id
|
|
889
|
+
if isinstance(root, Mapping) and set(root) == {"id"}:
|
|
890
|
+
root = root["id"]
|
|
891
|
+
root = _stable_id(root)
|
|
892
|
+
if len(root) != 36 or str(uuid.UUID(root)) != root.lower():
|
|
893
|
+
raise ValueError("Explicit export roots must be Object UUIDs")
|
|
894
|
+
selection.append(root)
|
|
895
|
+
options = {"rootClassBoundary": root_class_boundary}
|
|
896
|
+
if max_hops is not None:
|
|
897
|
+
options["maxHops"] = max_hops
|
|
898
|
+
return selection, options
|
|
899
|
+
|
|
900
|
+
def export_exchange(self, *, roots=None, max_hops=None, root_class_boundary=True, operation_id=None):
|
|
901
|
+
"""Export a Server package with an optional export ID and return its owning bundle."""
|
|
902
|
+
self._assert_not_collecting_batch()
|
|
903
|
+
selection, options = self._export_arguments(roots, max_hops, root_class_boundary)
|
|
904
|
+
with self._serialized():
|
|
905
|
+
endpoint = OperationEndpoint(self._client, self._token, self.namespace_id,
|
|
906
|
+
expected=self._endpoint.binding, actor=self._actor_id)
|
|
907
|
+
try:
|
|
908
|
+
with self._using_endpoint(endpoint), endpoint.execution() as execution:
|
|
909
|
+
endpoint.require_exchange()
|
|
910
|
+
reference = execution.run("deposit.exchange.export", selection, options, operation_id=operation_id)
|
|
911
|
+
bundle = ExchangeBundle(endpoint, reference, on_close=self._bundles.discard)
|
|
912
|
+
self._bundles.add(bundle)
|
|
913
|
+
return bundle
|
|
914
|
+
except BaseException:
|
|
915
|
+
endpoint.close()
|
|
916
|
+
raise
|
|
917
|
+
|
|
918
|
+
def import_exchange(self, source, *, rules=None, operation_id=None):
|
|
919
|
+
"""Analyze ZIP bytes or an authorized Exchange bundle with an optional analysis ID."""
|
|
920
|
+
if isinstance(source, ExchangeBundle):
|
|
921
|
+
return self._analyze_package(lambda endpoint: package_for_target(source, endpoint),
|
|
922
|
+
rules, operation_id=operation_id, source=source)
|
|
923
|
+
return self._analyze_package(lambda endpoint: stage_zip(endpoint, source),
|
|
924
|
+
rules, operation_id=operation_id)
|
|
925
|
+
|
|
926
|
+
def import_from(self, source_store, *, roots=None, max_hops=None,
|
|
927
|
+
root_class_boundary=True, rules=None, operation_id=None):
|
|
928
|
+
"""Analyze an independently authenticated Store's export.
|
|
929
|
+
|
|
930
|
+
operation_id identifies analysis in the receiving Store."""
|
|
931
|
+
if not isinstance(source_store, Store):
|
|
932
|
+
raise TypeError("source_store must be an authenticated Store")
|
|
933
|
+
_import_rules(rules)
|
|
934
|
+
with source_store.export_exchange(roots=roots, max_hops=max_hops,
|
|
935
|
+
root_class_boundary=root_class_boundary) as source:
|
|
936
|
+
return self._analyze_package(lambda endpoint: package_for_target(source, endpoint),
|
|
937
|
+
rules, operation_id=operation_id, source=source, own_source=True)
|
|
938
|
+
|
|
939
|
+
def _analyze_package(self, stage, rules, *, operation_id, source=None, own_source=False):
|
|
940
|
+
self._assert_not_collecting_batch()
|
|
941
|
+
rules = _import_rules(rules)
|
|
942
|
+
self._endpoint._require_capabilities("pagedImportResults")
|
|
943
|
+
with self._serialized(), self._using_endpoint() as endpoint:
|
|
944
|
+
endpoint.require_exchange()
|
|
945
|
+
reference = stage(endpoint)
|
|
946
|
+
direct = source is not None and reference == source.source
|
|
947
|
+
owned = not direct
|
|
948
|
+
retained = False
|
|
949
|
+
try:
|
|
950
|
+
with endpoint.execution() as execution:
|
|
951
|
+
envelope = execution.run("deposit.import.analyze", {
|
|
952
|
+
name: reference[name] for name in ("packageId", "grant")
|
|
953
|
+
}, rules, operation_id=operation_id)
|
|
954
|
+
result = self._import_result(envelope)
|
|
955
|
+
if result.plan_id:
|
|
956
|
+
with self._state_lock:
|
|
957
|
+
self._ready_plans.add(result.plan_id)
|
|
958
|
+
if owned or own_source:
|
|
959
|
+
self._plan_packages[result.plan_id] = (reference, direct)
|
|
960
|
+
retained = True
|
|
961
|
+
elif direct and own_source:
|
|
962
|
+
# The conflict diagnostic itself still checks source authorization.
|
|
963
|
+
self._result_packages.append(reference)
|
|
964
|
+
retained = True
|
|
965
|
+
if direct and own_source and retained:
|
|
966
|
+
source._detach()
|
|
967
|
+
if result.state == "IMPORT_CONFLICT":
|
|
968
|
+
self._raise_import_diagnostic(result)
|
|
969
|
+
return result
|
|
970
|
+
except OperationCommittedAfterCancel as exc:
|
|
971
|
+
self._discard_cancelled_analysis(exc)
|
|
972
|
+
raise
|
|
973
|
+
except OutcomeUnknown:
|
|
974
|
+
# Admission may still be using the package. Expiry owns cleanup.
|
|
975
|
+
retained = True
|
|
976
|
+
if direct and own_source:
|
|
977
|
+
source._detach()
|
|
978
|
+
raise
|
|
979
|
+
finally:
|
|
980
|
+
if owned and not retained:
|
|
981
|
+
discard_package(endpoint, reference)
|
|
982
|
+
|
|
983
|
+
def _analyze(self, procedure, arguments, *, operation_id=None):
|
|
984
|
+
self._assert_not_collecting_batch()
|
|
985
|
+
self._endpoint._require_capabilities("pagedImportResults")
|
|
986
|
+
with self._serialized():
|
|
987
|
+
try:
|
|
988
|
+
result = self._import_result(self._run_action(
|
|
989
|
+
procedure, arguments, operation_id=operation_id, _already_serialized=True,
|
|
990
|
+
))
|
|
991
|
+
except OperationCommittedAfterCancel as exc:
|
|
992
|
+
self._discard_cancelled_analysis(exc)
|
|
993
|
+
raise
|
|
994
|
+
if result.plan_id:
|
|
995
|
+
with self._state_lock:
|
|
996
|
+
self._ready_plans.add(result.plan_id)
|
|
997
|
+
if result.state == "IMPORT_CONFLICT":
|
|
998
|
+
self._raise_import_diagnostic(result)
|
|
999
|
+
return result
|
|
1000
|
+
|
|
1001
|
+
def _discard_cancelled_analysis(self, error):
|
|
1002
|
+
summary = error.details.get("result")
|
|
1003
|
+
if isinstance(summary, dict) and isinstance(summary.get("planId"), str):
|
|
1004
|
+
with suppress(DepositError, TransportError):
|
|
1005
|
+
self._discard_plan(summary["planId"])
|
|
1006
|
+
|
|
1007
|
+
@staticmethod
|
|
1008
|
+
def _raise_import_diagnostic(result):
|
|
1009
|
+
try:
|
|
1010
|
+
conflicts = result["conflicts"]
|
|
1011
|
+
except KeyError as exc:
|
|
1012
|
+
result.close()
|
|
1013
|
+
raise DepositError("INVALID_RESPONSE", "Import diagnostic result has no conflicts") from exc
|
|
1014
|
+
failure = DepositError(
|
|
1015
|
+
"IMPORT_CONFLICT", "Import analysis found conflicts",
|
|
1016
|
+
{"conflicts": conflicts}, result.operation_id,
|
|
1017
|
+
)
|
|
1018
|
+
# Keep the lazy detail reader alive for as long as the exception is
|
|
1019
|
+
# retained; callers can close it explicitly after inspecting details.
|
|
1020
|
+
failure.import_result = result
|
|
1021
|
+
raise failure
|
|
1022
|
+
|
|
1023
|
+
def import_apply(self, plan_id: str, *, operation_id=None):
|
|
1024
|
+
"""Apply a ready plan in one Server transaction with an optional apply ID."""
|
|
1025
|
+
_stable_id(plan_id)
|
|
1026
|
+
self._endpoint._require_capabilities("pagedImportResults")
|
|
1027
|
+
with self._serialized():
|
|
1028
|
+
try:
|
|
1029
|
+
envelope = self._run_action("deposit.import.apply", [plan_id],
|
|
1030
|
+
operation_id=operation_id, _already_serialized=True)
|
|
1031
|
+
except OutcomeUnknown:
|
|
1032
|
+
with self._state_lock:
|
|
1033
|
+
self._ready_plans.discard(plan_id)
|
|
1034
|
+
self._plan_packages.pop(plan_id, None)
|
|
1035
|
+
raise
|
|
1036
|
+
except OperationCommittedAfterCancel:
|
|
1037
|
+
self._finish_plan(plan_id, keep_source=True)
|
|
1038
|
+
raise
|
|
1039
|
+
except DepositError as exc:
|
|
1040
|
+
if isinstance(exc.details, dict) and exc.details.get("state") == "COMMITTED":
|
|
1041
|
+
self._finish_plan(plan_id, keep_source=True)
|
|
1042
|
+
elif exc.code != "OPERATION_MISMATCH":
|
|
1043
|
+
with suppress(DepositError, TransportError):
|
|
1044
|
+
self._discard_plan(plan_id)
|
|
1045
|
+
raise
|
|
1046
|
+
self._finish_plan(plan_id, keep_source=True)
|
|
1047
|
+
return self._import_result(envelope)
|
|
1048
|
+
|
|
1049
|
+
def discard_import_plan(self, plan_id: str):
|
|
1050
|
+
"""Discard an unused plan and report the Server's plan state."""
|
|
1051
|
+
self._assert_not_collecting_batch()
|
|
1052
|
+
_stable_id(plan_id)
|
|
1053
|
+
# Independent of the ordinary lock, so a concurrent apply and discard
|
|
1054
|
+
# are ordered by the Server rather than by this Store.
|
|
1055
|
+
if not self._begin_parallel_control():
|
|
1056
|
+
raise RuntimeError("Store is closed")
|
|
1057
|
+
try:
|
|
1058
|
+
return self._discard_plan(plan_id)
|
|
1059
|
+
finally:
|
|
1060
|
+
self._end_parallel_control()
|
|
1061
|
+
|
|
1062
|
+
def _discard_plan(self, plan_id):
|
|
1063
|
+
result = self._endpoint.control("deposit.import.discardPlan", plan_id)
|
|
1064
|
+
if (not _valid_plan_observation(result) or result["planId"] != plan_id
|
|
1065
|
+
or result["namespaceId"] != self.namespace_id):
|
|
1066
|
+
raise DepositError("INVALID_RESPONSE", "Plan discard returned an invalid observation")
|
|
1067
|
+
self._finish_plan(plan_id, keep_source=result["state"] == "applied")
|
|
1068
|
+
return result
|
|
1069
|
+
|
|
1070
|
+
def _finish_plan(self, plan_id, *, keep_source):
|
|
1071
|
+
with self._state_lock:
|
|
1072
|
+
self._ready_plans.discard(plan_id)
|
|
1073
|
+
owned = self._plan_packages.pop(plan_id, None)
|
|
1074
|
+
if owned is None:
|
|
1075
|
+
return
|
|
1076
|
+
reference, direct = owned
|
|
1077
|
+
if direct and keep_source:
|
|
1078
|
+
self._result_packages.append(reference)
|
|
1079
|
+
return
|
|
1080
|
+
discard_package(self._endpoint, reference, control=True)
|
|
1081
|
+
|
|
1082
|
+
def import_inspect(self, plan_id: str):
|
|
1083
|
+
"""Read a plan's immutable analysis result without applying it."""
|
|
1084
|
+
_stable_id(plan_id)
|
|
1085
|
+
self._assert_not_collecting_batch()
|
|
1086
|
+
with self._serialized():
|
|
1087
|
+
self._endpoint._require_capabilities("pagedImportResults")
|
|
1088
|
+
wrapper = self._endpoint.call("deposit.get.importPlan", plan_id)
|
|
1089
|
+
if not valid_import_plan_wrapper(wrapper, plan_id=plan_id, namespace_id=self._namespace_id):
|
|
1090
|
+
raise DepositError("INVALID_RESPONSE", "Import plan inspection returned an invalid wrapper")
|
|
1091
|
+
return self._import_result(wrapper["analysisResult"], plan_observation=wrapper["plan"])
|
|
1092
|
+
|
|
1093
|
+
def _import_result(self, envelope: Any, *, plan_observation=None):
|
|
1094
|
+
if not isinstance(envelope, dict) or envelope.get("namespaceId") != self._namespace_id:
|
|
1095
|
+
raise DepositError("INVALID_RESPONSE", "Import action returned an invalid result envelope")
|
|
1096
|
+
result = self._client._result_view(self._token, envelope, ImportResult,
|
|
1097
|
+
plan_observation=plan_observation, check_open=self._check_result_reader,
|
|
1098
|
+
requester=self._endpoint.control)
|
|
1099
|
+
self._readers[id(result)] = result
|
|
1100
|
+
return result
|
|
1101
|
+
|
|
1102
|
+
def _check_result_reader(self):
|
|
1103
|
+
if self._closed or self._closing:
|
|
1104
|
+
raise RuntimeError("Store is closed")
|
|
1105
|
+
|
|
1106
|
+
def call(self, procedure: str, *arguments: Any, operation_id=None):
|
|
1107
|
+
"""Call an allowlisted Store procedure using its domain arguments.
|
|
1108
|
+
|
|
1109
|
+
For a tracked procedure, supply a fresh UUIDv7 as operation_id to
|
|
1110
|
+
identify the attempt before submission. The wrapper otherwise
|
|
1111
|
+
generates and registers an ID. For import analysis and apply, the ID
|
|
1112
|
+
identifies that individual step."""
|
|
1113
|
+
self._assert_not_collecting_batch()
|
|
1114
|
+
entry = store_procedure(procedure)
|
|
1115
|
+
tracked = entry.get("tracked") == "always"
|
|
1116
|
+
if operation_id is not None and not tracked:
|
|
1117
|
+
raise ValueError("Procedure does not accept a tracked operation")
|
|
1118
|
+
if procedure == "deposit.import.apply":
|
|
1119
|
+
return self.import_apply(*arguments, operation_id=operation_id)
|
|
1120
|
+
if procedure == "deposit.import.discardPlan":
|
|
1121
|
+
return self.discard_import_plan(*arguments)
|
|
1122
|
+
if tracked:
|
|
1123
|
+
if procedure in _IMPORT_RESULTS:
|
|
1124
|
+
return self._analyze(procedure, arguments, operation_id=operation_id)
|
|
1125
|
+
outcome = self._run_action(procedure, arguments, operation_id=operation_id)
|
|
1126
|
+
columns = entry["columns"]
|
|
1127
|
+
row = {columns[0]: outcome} if len(columns) == 1 else outcome
|
|
1128
|
+
return detached_result(entry, row, self._token)
|
|
1129
|
+
bound = bind_arguments(entry, arguments, namespace_id=self._namespace_id)
|
|
1130
|
+
return self._open_result(entry, bound)
|
|
1131
|
+
|
|
1132
|
+
def get_requests(self) -> tuple[Mapping[str, Any], ...]:
|
|
1133
|
+
"""List requests visible to this Store's authenticated actor.
|
|
1134
|
+
|
|
1135
|
+
This control query uses a fresh session and does not wait for the
|
|
1136
|
+
Store's ordinary operation lock, so it remains usable while a request
|
|
1137
|
+
is running on the Store session.
|
|
1138
|
+
"""
|
|
1139
|
+
self._assert_not_collecting_batch()
|
|
1140
|
+
if not self._begin_parallel_control():
|
|
1141
|
+
raise RuntimeError("Store is closed")
|
|
1142
|
+
try:
|
|
1143
|
+
entry = store_control_procedure("deposit.get.requests")
|
|
1144
|
+
bound = bind_arguments(entry, ())
|
|
1145
|
+
query, parameters = build_query(entry, bound, self._token)
|
|
1146
|
+
session = None
|
|
1147
|
+
try:
|
|
1148
|
+
session = self._client._session()
|
|
1149
|
+
result = session.run(query, parameters)
|
|
1150
|
+
columns = tuple(result.keys())
|
|
1151
|
+
expected = tuple(entry["columns"])
|
|
1152
|
+
if columns != expected:
|
|
1153
|
+
raise DepositError("INVALID_RESPONSE", "Request listing returned unexpected columns")
|
|
1154
|
+
requests = tuple(immutable_request(record.get("data")) for record in result)
|
|
1155
|
+
result.consume()
|
|
1156
|
+
return requests
|
|
1157
|
+
except DepositError:
|
|
1158
|
+
raise
|
|
1159
|
+
except Exception as exc:
|
|
1160
|
+
raise map_driver_error(exc) from exc
|
|
1161
|
+
finally:
|
|
1162
|
+
if session is not None:
|
|
1163
|
+
try:
|
|
1164
|
+
session.close()
|
|
1165
|
+
except Exception:
|
|
1166
|
+
pass
|
|
1167
|
+
finally:
|
|
1168
|
+
self._end_parallel_control()
|
|
1169
|
+
|
|
1170
|
+
def cancel_request(self, request_id: str) -> bool:
|
|
1171
|
+
"""Request cancellation of one server-authorized active request."""
|
|
1172
|
+
self._assert_not_collecting_batch()
|
|
1173
|
+
if not isinstance(request_id, str) or not request_id:
|
|
1174
|
+
raise ValueError("request_id must be a nonempty string")
|
|
1175
|
+
if not self._begin_parallel_control():
|
|
1176
|
+
return False
|
|
1177
|
+
try:
|
|
1178
|
+
entry = store_control_procedure("deposit.utils.cancelRequest")
|
|
1179
|
+
bound = bind_arguments(entry, (request_id,))
|
|
1180
|
+
query, parameters = build_query(entry, bound, self._token)
|
|
1181
|
+
row = self._client._single(query, parameters)
|
|
1182
|
+
value = row.get("value")
|
|
1183
|
+
if not isinstance(value, bool):
|
|
1184
|
+
raise DepositError("INVALID_RESPONSE", "Request cancellation returned no boolean result")
|
|
1185
|
+
return value
|
|
1186
|
+
finally:
|
|
1187
|
+
self._end_parallel_control()
|
|
1188
|
+
|
|
1189
|
+
def get_administrative_mode(self) -> bool:
|
|
1190
|
+
"""Read this Store session's administrative-mode state."""
|
|
1191
|
+
self._assert_not_collecting_batch()
|
|
1192
|
+
with self._serialized():
|
|
1193
|
+
value = self._client.get_administrative_mode(self._token)
|
|
1194
|
+
if not isinstance(value, bool):
|
|
1195
|
+
raise DepositError("INVALID_RESPONSE", "Administrative-mode lookup returned no boolean result")
|
|
1196
|
+
return value
|
|
1197
|
+
|
|
1198
|
+
def get_operation(self, operation_id: str) -> Any:
|
|
1199
|
+
"""Inspect an exact operation on the independent control connection."""
|
|
1200
|
+
return self._operation_status(operation_id, cancel=False)
|
|
1201
|
+
|
|
1202
|
+
def cancel_operation(self, operation_id: str) -> Any:
|
|
1203
|
+
"""Request cancellation and return the reported state in this Store's Namespace."""
|
|
1204
|
+
return self._operation_status(operation_id, cancel=True)
|
|
1205
|
+
|
|
1206
|
+
def _operation_status(self, operation_id, *, cancel):
|
|
1207
|
+
_stable_id(operation_id)
|
|
1208
|
+
if not self._begin_parallel_control():
|
|
1209
|
+
raise RuntimeError("Store is closed")
|
|
1210
|
+
try:
|
|
1211
|
+
if cancel:
|
|
1212
|
+
with self._state_lock:
|
|
1213
|
+
endpoint = self._active_endpoint
|
|
1214
|
+
if endpoint is not None:
|
|
1215
|
+
endpoint.note_cancel(operation_id)
|
|
1216
|
+
return self._endpoint._operation_status(operation_id, cancel)
|
|
1217
|
+
finally:
|
|
1218
|
+
self._end_parallel_control()
|
|
1219
|
+
|
|
1220
|
+
def get_last_operation(self) -> Any:
|
|
1221
|
+
"""Return the last operation observed by this Store session."""
|
|
1222
|
+
self._assert_not_collecting_batch()
|
|
1223
|
+
with self._serialized():
|
|
1224
|
+
return self._client.get_last_operation(self._token)
|
|
1225
|
+
|
|
1226
|
+
def set_administrative_mode(self, enabled: bool) -> bool:
|
|
1227
|
+
"""Explicitly set this Store session's administrative-mode state."""
|
|
1228
|
+
self._assert_not_collecting_batch()
|
|
1229
|
+
if not isinstance(enabled, bool):
|
|
1230
|
+
raise TypeError("enabled must be a bool")
|
|
1231
|
+
with self._serialized():
|
|
1232
|
+
value = self._client.set_administrative_mode(self._token, enabled)
|
|
1233
|
+
if not isinstance(value, bool):
|
|
1234
|
+
raise DepositError("INVALID_RESPONSE", "Administrative-mode update returned no boolean result")
|
|
1235
|
+
return value
|
|
1236
|
+
|
|
1237
|
+
def refresh(self) -> None:
|
|
1238
|
+
"""Explicitly refresh this session's Namespace revision baseline."""
|
|
1239
|
+
self._assert_not_collecting_batch()
|
|
1240
|
+
with self._serialized(allow_closing=True):
|
|
1241
|
+
self._client._single(
|
|
1242
|
+
"CYPHER 25 CALL deposit.utils.refresh($scope, $token) YIELD data RETURN data",
|
|
1243
|
+
{"scope": "namespace", "token": self._token},
|
|
1244
|
+
)
|
|
1245
|
+
profile = self._endpoint.call("deposit.get.session")
|
|
1246
|
+
self._endpoint._check_profile(profile)
|
|
1247
|
+
self._session_revision(profile)
|
|
1248
|
+
self._invalidate_handles()
|
|
1249
|
+
|
|
1250
|
+
def transaction(self):
|
|
1251
|
+
"""Collect one bounded atomic ``deposit.apply.batch`` action."""
|
|
1252
|
+
from ._batch import Batch
|
|
1253
|
+
if self._batch_collection is not None:
|
|
1254
|
+
raise RuntimeError("Nested batches are not supported")
|
|
1255
|
+
return Batch(self)
|
|
1256
|
+
|
|
1257
|
+
def get_query_page(self, querystr: str, *, parameters: dict[str, Any] | None = None,
|
|
1258
|
+
page_size: int | None = None, cursor: str | None = None) -> dict[str, Any]:
|
|
1259
|
+
"""Return one typed, revision-bound page from the server query engine."""
|
|
1260
|
+
from .values import decode_value
|
|
1261
|
+
if not isinstance(querystr, str) or not querystr:
|
|
1262
|
+
raise ValueError("querystr must be a nonempty string")
|
|
1263
|
+
if parameters is None:
|
|
1264
|
+
parameters = {}
|
|
1265
|
+
if not isinstance(parameters, dict) or any(not isinstance(k, str) for k in parameters):
|
|
1266
|
+
raise TypeError("parameters must be a string-keyed dictionary")
|
|
1267
|
+
if page_size is not None and (type(page_size) is not int or not 1 <= page_size <= 1000):
|
|
1268
|
+
raise ValueError("page_size must be an integer from 1 through 1000")
|
|
1269
|
+
if cursor is not None and (not isinstance(cursor, str) or not cursor):
|
|
1270
|
+
raise ValueError("cursor must be a nonempty string")
|
|
1271
|
+
options = {}
|
|
1272
|
+
if page_size is not None:
|
|
1273
|
+
options["pageSize"] = page_size
|
|
1274
|
+
if cursor is not None:
|
|
1275
|
+
options["cursor"] = cursor
|
|
1276
|
+
bound_parameters = _query_parameters(parameters)
|
|
1277
|
+
with self.call("deposit.get.queryPage", querystr, bound_parameters, options) as result:
|
|
1278
|
+
first = next(result, None)
|
|
1279
|
+
if first is None:
|
|
1280
|
+
raise DepositError("INVALID_RESPONSE", "Query page returned no page record")
|
|
1281
|
+
if next(result, None) is not None:
|
|
1282
|
+
raise DepositError("INVALID_RESPONSE", "Query page returned multiple page records")
|
|
1283
|
+
data = first.get("data")
|
|
1284
|
+
if not isinstance(data, dict) or set(data) != {"columns", "rows", "nextCursor"}:
|
|
1285
|
+
raise DepositError("INVALID_RESPONSE", "Query page returned an invalid page")
|
|
1286
|
+
columns = data["columns"]
|
|
1287
|
+
rows = data["rows"]
|
|
1288
|
+
next_cursor = data["nextCursor"]
|
|
1289
|
+
if (not isinstance(columns, list) or not isinstance(rows, list)
|
|
1290
|
+
or (next_cursor is not None and not isinstance(next_cursor, str))):
|
|
1291
|
+
raise DepositError("INVALID_RESPONSE", "Query page returned invalid columns, rows, or cursor")
|
|
1292
|
+
names = []
|
|
1293
|
+
for column in columns:
|
|
1294
|
+
if not isinstance(column, dict) or set(column) != {"name", "type"}:
|
|
1295
|
+
raise DepositError("INVALID_RESPONSE", "Query page returned invalid column metadata")
|
|
1296
|
+
if not isinstance(column["name"], str) or not isinstance(column["type"], str) or column["name"] in names:
|
|
1297
|
+
raise DepositError("INVALID_RESPONSE", "Query page returned duplicate or invalid columns")
|
|
1298
|
+
names.append(column["name"])
|
|
1299
|
+
detached_rows = []
|
|
1300
|
+
for row in rows:
|
|
1301
|
+
if not isinstance(row, dict) or set(row) != {"values", "presence"}:
|
|
1302
|
+
raise DepositError("INVALID_RESPONSE", "Query page returned an invalid row")
|
|
1303
|
+
values, presence = row["values"], row["presence"]
|
|
1304
|
+
if not isinstance(values, dict) or not isinstance(presence, dict) or set(values) != set(names) or set(presence) != set(names):
|
|
1305
|
+
raise DepositError("INVALID_RESPONSE", "Query page row does not match its columns")
|
|
1306
|
+
if any(type(flag) is not bool for flag in presence.values()):
|
|
1307
|
+
raise DepositError("INVALID_RESPONSE", "Query page presence flags must be booleans")
|
|
1308
|
+
decoded = {}
|
|
1309
|
+
for column in columns:
|
|
1310
|
+
name, kind = column["name"], column["type"]
|
|
1311
|
+
try:
|
|
1312
|
+
decoded[name] = decode_value(kind, values[name]) if kind in _DOMAIN_VALUE_TYPES else values[name]
|
|
1313
|
+
except (TypeError, ValueError, OverflowError) as exc:
|
|
1314
|
+
raise DepositError("INVALID_RESPONSE", "Query page contains an invalid typed value") from exc
|
|
1315
|
+
detached_rows.append({"values": decoded, "presence": dict(presence)})
|
|
1316
|
+
from ._paging import QueryPage
|
|
1317
|
+
return QueryPage({"columns": [dict(column) for column in columns], "rows": detached_rows,
|
|
1318
|
+
"nextCursor": next_cursor})
|
|
1319
|
+
|
|
1320
|
+
def iter_query(self, querystr: str, *, parameters: dict[str, Any] | None = None,
|
|
1321
|
+
page_size: int = 200):
|
|
1322
|
+
"""Create a lazy row iterator over cursor-bound query pages."""
|
|
1323
|
+
from ._paging import QueryIterator
|
|
1324
|
+
if not isinstance(querystr, str) or not querystr:
|
|
1325
|
+
raise ValueError("querystr must be a nonempty string")
|
|
1326
|
+
if parameters is None:
|
|
1327
|
+
parameters = {}
|
|
1328
|
+
if not isinstance(parameters, dict):
|
|
1329
|
+
raise TypeError("parameters must be a dictionary")
|
|
1330
|
+
if type(page_size) is not int or not 1 <= page_size <= 1000:
|
|
1331
|
+
raise ValueError("page_size must be an integer from 1 through 1000")
|
|
1332
|
+
if self._batch_collection is not None:
|
|
1333
|
+
raise RuntimeError("Store operations are unavailable while collecting a batch")
|
|
1334
|
+
return QueryIterator(self, querystr, _query_parameters(parameters), page_size)
|
|
1335
|
+
|
|
1336
|
+
def query_from(self, queries):
|
|
1337
|
+
"""Yield one first page for each independent ``(query, parameters)`` pair."""
|
|
1338
|
+
for item in queries:
|
|
1339
|
+
if not isinstance(item, (tuple, list)) or len(item) != 2:
|
|
1340
|
+
raise TypeError("queries must yield (querystr, parameters) pairs")
|
|
1341
|
+
querystr, parameters = item
|
|
1342
|
+
yield self.get_query_page(querystr, parameters=parameters)
|
|
1343
|
+
|
|
1344
|
+
def _entity_page(self, procedure: str, selection, *, page_size=200, transform=None, prepare=None,
|
|
1345
|
+
expected_revision=None):
|
|
1346
|
+
from ._paging import EntityPageIterator
|
|
1347
|
+
return EntityPageIterator(self, procedure, selection, page_size=page_size, transform=transform,
|
|
1348
|
+
prepare=prepare, expected_revision=expected_revision)
|
|
1349
|
+
|
|
1350
|
+
def classes(self, name: str | None = None, *, page_size=200):
|
|
1351
|
+
return self._entity_page("deposit.get.classPage", name, page_size=page_size,
|
|
1352
|
+
prepare=self._class_page_handles)
|
|
1353
|
+
|
|
1354
|
+
def objects(self, *, class_name: str | None = None, descriptors: Mapping[str, Any] | None = None,
|
|
1355
|
+
object_id: str | None = None, page_size=200):
|
|
1356
|
+
from .values import DType, TypedValue
|
|
1357
|
+
if object_id is not None:
|
|
1358
|
+
if class_name is not None or descriptors:
|
|
1359
|
+
raise ValueError("object_id is exclusive with Class and Descriptor filters")
|
|
1360
|
+
return iter((self.get_object_handle({"id": _stable_id(object_id)}),))
|
|
1361
|
+
selection = {}
|
|
1362
|
+
schema = None
|
|
1363
|
+
schema_revision = None
|
|
1364
|
+
dclass = None
|
|
1365
|
+
if class_name is not None:
|
|
1366
|
+
dclass = self.get_class_handle(class_name)
|
|
1367
|
+
selection["classId"] = dclass.id
|
|
1368
|
+
schema = dclass._schema
|
|
1369
|
+
schema_revision = dclass._baseline_revision
|
|
1370
|
+
if descriptors is not None:
|
|
1371
|
+
if not isinstance(descriptors, Mapping) or any(not isinstance(k, str) for k in descriptors):
|
|
1372
|
+
raise TypeError("descriptors must be a string-keyed mapping")
|
|
1373
|
+
encoded = {}
|
|
1374
|
+
for name, value in descriptors.items():
|
|
1375
|
+
if isinstance(value, (TypedValue, DType)):
|
|
1376
|
+
if schema is None:
|
|
1377
|
+
raise TypeError("Typed Descriptor filters require class_name schema context")
|
|
1378
|
+
kind = schema.get(name)
|
|
1379
|
+
if kind is None:
|
|
1380
|
+
raise KeyError(name)
|
|
1381
|
+
encoded[name] = _descriptor_payload(
|
|
1382
|
+
value, kind, geometry_encoder=self._geometry_write_value,
|
|
1383
|
+
resource_encoder=self._resource_write_value,
|
|
1384
|
+
)
|
|
1385
|
+
else:
|
|
1386
|
+
encoded[name] = value
|
|
1387
|
+
selection["descriptors"] = encoded
|
|
1388
|
+
schemas = {}
|
|
1389
|
+
return self._entity_page("deposit.get.objectPage", selection or None, page_size=page_size,
|
|
1390
|
+
expected_revision=schema_revision,
|
|
1391
|
+
prepare=lambda items, revision: self._object_page_handles(items, revision, schemas, dclass))
|
|
1392
|
+
|
|
1393
|
+
def members(self, dclass: DClass | str | dict[str, Any], *, page_size=200):
|
|
1394
|
+
handle = dclass if isinstance(dclass, DClass) else self.get_class_handle(dclass)
|
|
1395
|
+
self._validate_handle(handle, "Class")
|
|
1396
|
+
schemas = {}
|
|
1397
|
+
return self._entity_page(
|
|
1398
|
+
"deposit.get.classMembersPage", {"id": handle.id}, page_size=page_size,
|
|
1399
|
+
prepare=lambda items, revision: self._object_page_handles(items, revision, schemas, handle),
|
|
1400
|
+
)
|
|
1401
|
+
|
|
1402
|
+
def is_member(self, dobject: DObject, dclass: DClass | str | dict[str, Any]) -> bool:
|
|
1403
|
+
self._validate_handle(dobject, "Object")
|
|
1404
|
+
return dobject.has_class(dclass)
|
|
1405
|
+
|
|
1406
|
+
def descriptors(self, dobject: DObject, name: str | None = None, *, page_size=200):
|
|
1407
|
+
self._validate_handle(dobject, "Object")
|
|
1408
|
+
self._ensure_handle_current(dobject)
|
|
1409
|
+
revision = _matching_handle_revision(dobject)
|
|
1410
|
+
schema = dict(dobject._schema)
|
|
1411
|
+
selection = {"objectId": dobject.id}
|
|
1412
|
+
if name is not None:
|
|
1413
|
+
if not isinstance(name, str) or not name:
|
|
1414
|
+
raise ValueError("Descriptor name must be a nonempty string")
|
|
1415
|
+
selection["name"] = name
|
|
1416
|
+
|
|
1417
|
+
def decode(item, page_revision):
|
|
1418
|
+
descriptor_name = item.get("name")
|
|
1419
|
+
if not isinstance(descriptor_name, str):
|
|
1420
|
+
raise DepositError("INVALID_RESPONSE", "Descriptor page item has no name")
|
|
1421
|
+
kind = schema.get(descriptor_name)
|
|
1422
|
+
if kind is None:
|
|
1423
|
+
raise DepositError("INVALID_RESPONSE", "Descriptor page item has no checked declaration")
|
|
1424
|
+
from .values import decode_value
|
|
1425
|
+
try:
|
|
1426
|
+
value = decode_value(kind, item.get("value"))
|
|
1427
|
+
except (TypeError, ValueError, OverflowError) as exc:
|
|
1428
|
+
raise DepositError("INVALID_RESPONSE", "Descriptor page value does not match its declaration") from exc
|
|
1429
|
+
return descriptor_name, value, kind
|
|
1430
|
+
|
|
1431
|
+
return self._entity_page("deposit.get.descriptorPage", selection, page_size=page_size, transform=decode,
|
|
1432
|
+
expected_revision=revision)
|
|
1433
|
+
|
|
1434
|
+
def class_descriptors(self, dclass: DClass, name: str | None = None, *, page_size=200):
|
|
1435
|
+
self._validate_handle(dclass, "Class")
|
|
1436
|
+
selection = {"classId": dclass.id}
|
|
1437
|
+
if name is not None:
|
|
1438
|
+
if not isinstance(name, str) or not name:
|
|
1439
|
+
raise ValueError("Descriptor name must be a nonempty string")
|
|
1440
|
+
selection["name"] = name
|
|
1441
|
+
return self._entity_page(
|
|
1442
|
+
"deposit.get.classDescriptorPage", selection, page_size=page_size,
|
|
1443
|
+
transform=lambda item, revision: (item.get("name"), item.get("type"), item.get("comment", "")),
|
|
1444
|
+
)
|
|
1445
|
+
|
|
1446
|
+
def relationships(self, src_object: DObject | None = None, tgt_object: DObject | None = None,
|
|
1447
|
+
label: str | None = None, *, page_size=200):
|
|
1448
|
+
selection = {}
|
|
1449
|
+
if src_object is not None:
|
|
1450
|
+
self._validate_handle(src_object, "Object")
|
|
1451
|
+
selection["sourceId"] = src_object.id
|
|
1452
|
+
if tgt_object is not None:
|
|
1453
|
+
self._validate_handle(tgt_object, "Object")
|
|
1454
|
+
selection["targetId"] = tgt_object.id
|
|
1455
|
+
if label is not None:
|
|
1456
|
+
if not isinstance(label, str) or not label:
|
|
1457
|
+
raise ValueError("Relationship label must be a nonempty string")
|
|
1458
|
+
selection["label"] = label
|
|
1459
|
+
return self._entity_page("deposit.get.relationshipPage", selection or None, page_size=page_size)
|
|
1460
|
+
|
|
1461
|
+
def class_relationships(self, src_class: DClass | None = None, tgt_class: DClass | None = None,
|
|
1462
|
+
label: str | None = None, *, page_size=200):
|
|
1463
|
+
selection = {}
|
|
1464
|
+
if src_class is not None:
|
|
1465
|
+
self._validate_handle(src_class, "Class")
|
|
1466
|
+
selection["sourceId"] = src_class.id
|
|
1467
|
+
if tgt_class is not None:
|
|
1468
|
+
self._validate_handle(tgt_class, "Class")
|
|
1469
|
+
selection["targetId"] = tgt_class.id
|
|
1470
|
+
if label is not None:
|
|
1471
|
+
if not isinstance(label, str) or not label:
|
|
1472
|
+
raise ValueError("Relationship label must be a nonempty string")
|
|
1473
|
+
selection["label"] = label
|
|
1474
|
+
return self._entity_page("deposit.get.classRelationshipPage", selection or None, page_size=page_size)
|
|
1475
|
+
|
|
1476
|
+
def neighbors(self, dobject: DObject, *, direction="both", page_size=200):
|
|
1477
|
+
return self._neighbors(dobject, direction=direction, page_size=page_size, class_relationship=False)
|
|
1478
|
+
|
|
1479
|
+
def class_neighbors(self, dclass: DClass, *, direction="both", page_size=200):
|
|
1480
|
+
return self._neighbors(dclass, direction=direction, page_size=page_size, class_relationship=True)
|
|
1481
|
+
|
|
1482
|
+
def _neighbors(self, source: DNode, *, direction, page_size, class_relationship):
|
|
1483
|
+
kind = "Class" if class_relationship else "Object"
|
|
1484
|
+
self._validate_handle(source, kind)
|
|
1485
|
+
if direction not in {"outgoing", "incoming", "both"}:
|
|
1486
|
+
raise ValueError("direction must be 'outgoing', 'incoming', or 'both'")
|
|
1487
|
+
procedure = "deposit.get.classRelationshipPage" if class_relationship else "deposit.get.relationshipPage"
|
|
1488
|
+
seen = set()
|
|
1489
|
+
selections = []
|
|
1490
|
+
if direction in {"outgoing", "both"}:
|
|
1491
|
+
selections.append(("sourceId", "targetId"))
|
|
1492
|
+
if direction in {"incoming", "both"}:
|
|
1493
|
+
selections.append(("targetId", "sourceId"))
|
|
1494
|
+
revision = None
|
|
1495
|
+
schemas = {}
|
|
1496
|
+
for filter_key, other_key in selections:
|
|
1497
|
+
def prepare(relationships, checked_revision):
|
|
1498
|
+
selected = []
|
|
1499
|
+
identities = {}
|
|
1500
|
+
for relationship in relationships:
|
|
1501
|
+
identity, other_id = relationship.get("id"), relationship.get(other_key)
|
|
1502
|
+
if not isinstance(identity, str) or not isinstance(other_id, str):
|
|
1503
|
+
raise DepositError("INVALID_RESPONSE", "Relationship page omitted stable endpoint identity")
|
|
1504
|
+
if identity in seen:
|
|
1505
|
+
continue
|
|
1506
|
+
seen.add(identity)
|
|
1507
|
+
selected.append((other_id, relationship))
|
|
1508
|
+
identities[other_id] = None
|
|
1509
|
+
entities, _ = self._checked_page_entities(kind, identities, checked_revision)
|
|
1510
|
+
items = [entities[other_id] for other_id, _ in selected]
|
|
1511
|
+
if kind == "Class":
|
|
1512
|
+
handles = self._class_page_handles(items, checked_revision)
|
|
1513
|
+
else:
|
|
1514
|
+
handles = self._object_page_handles(items, checked_revision, schemas)
|
|
1515
|
+
return [(handle, relationship) for handle, (_, relationship) in zip(handles, selected, strict=True)]
|
|
1516
|
+
|
|
1517
|
+
iterator = self._entity_page(procedure, {filter_key: source.id}, page_size=page_size,
|
|
1518
|
+
expected_revision=revision, prepare=prepare)
|
|
1519
|
+
try:
|
|
1520
|
+
yield from iterator
|
|
1521
|
+
finally:
|
|
1522
|
+
revision = iterator.revision
|
|
1523
|
+
iterator.close()
|
|
1524
|
+
|
|
1525
|
+
def get_user_tool(self, selection: str | dict[str, Any]):
|
|
1526
|
+
return self._call_one("deposit.get.userTool", selection)
|
|
1527
|
+
|
|
1528
|
+
def user_tools(self, name: str | None = None, *, page_size=200):
|
|
1529
|
+
if name is not None and (not isinstance(name, str) or not name):
|
|
1530
|
+
raise ValueError("User Tool name filter must be a nonempty string")
|
|
1531
|
+
selection = name
|
|
1532
|
+
return self._entity_page("deposit.get.userToolPage", selection, page_size=page_size)
|
|
1533
|
+
|
|
1534
|
+
def _begin_batch_collection(self, batch) -> None:
|
|
1535
|
+
with self._state_lock:
|
|
1536
|
+
if self._closed or self._closing:
|
|
1537
|
+
raise RuntimeError("Store is closed")
|
|
1538
|
+
if self._batch_collection is not None:
|
|
1539
|
+
raise RuntimeError("Nested batches are not supported")
|
|
1540
|
+
self._batch_collection = batch
|
|
1541
|
+
|
|
1542
|
+
def _end_batch_collection(self, batch) -> None:
|
|
1543
|
+
with self._state_lock:
|
|
1544
|
+
if self._batch_collection is batch:
|
|
1545
|
+
self._batch_collection = None
|
|
1546
|
+
|
|
1547
|
+
def _submit_batch(self, commands: list[dict[str, Any]], *, pinned_revision: int | None = None,
|
|
1548
|
+
refresh_handles=()) -> dict[str, Any]:
|
|
1549
|
+
if not commands:
|
|
1550
|
+
return {}
|
|
1551
|
+
result = self._run_action("deposit.apply.batch", [commands], pinned_revision=pinned_revision,
|
|
1552
|
+
refresh_handles=refresh_handles)
|
|
1553
|
+
if not isinstance(result, dict) or not isinstance(result.get("results"), dict):
|
|
1554
|
+
raise DepositError("INVALID_RESPONSE", "Batch action returned no portable command results")
|
|
1555
|
+
return result["results"]
|
|
1556
|
+
|
|
1557
|
+
def cancel(self) -> bool:
|
|
1558
|
+
"""Request cancellation of this Store's current operation or read."""
|
|
1559
|
+
return self._cancel(allow_closing=False)
|
|
1560
|
+
|
|
1561
|
+
def _cancel(self, *, allow_closing: bool) -> bool:
|
|
1562
|
+
if not self._begin_parallel_control(allow_closing=allow_closing):
|
|
1563
|
+
return False
|
|
1564
|
+
try:
|
|
1565
|
+
with self._state_lock:
|
|
1566
|
+
endpoint = self._active_endpoint
|
|
1567
|
+
if endpoint is not None:
|
|
1568
|
+
endpoint.cancel_current()
|
|
1569
|
+
return True
|
|
1570
|
+
entry = store_control_procedure("deposit.utils.cancel")
|
|
1571
|
+
query, parameters = build_query(entry, (), self._token)
|
|
1572
|
+
row = self._client._single(query, parameters)
|
|
1573
|
+
value = row.get("value")
|
|
1574
|
+
if not isinstance(value, bool):
|
|
1575
|
+
raise DepositError("INVALID_RESPONSE", "Cancellation returned no boolean result")
|
|
1576
|
+
return value
|
|
1577
|
+
finally:
|
|
1578
|
+
self._end_parallel_control()
|
|
1579
|
+
|
|
1580
|
+
def _begin_parallel_control(self, *, allow_closing: bool = False) -> bool:
|
|
1581
|
+
with self._control_condition:
|
|
1582
|
+
if self._closed or (self._closing and not allow_closing):
|
|
1583
|
+
return False
|
|
1584
|
+
self._inflight_controls += 1
|
|
1585
|
+
return True
|
|
1586
|
+
|
|
1587
|
+
def _end_parallel_control(self) -> None:
|
|
1588
|
+
with self._control_condition:
|
|
1589
|
+
self._inflight_controls -= 1
|
|
1590
|
+
self._control_condition.notify_all()
|
|
1591
|
+
|
|
1592
|
+
def close(self) -> None:
|
|
1593
|
+
with self._close_lock:
|
|
1594
|
+
with self._state_lock:
|
|
1595
|
+
if self._closed:
|
|
1596
|
+
return
|
|
1597
|
+
self._closing = True
|
|
1598
|
+
active = self._active
|
|
1599
|
+
active_result = self._active_result
|
|
1600
|
+
if active:
|
|
1601
|
+
try:
|
|
1602
|
+
self._cancel(allow_closing=True)
|
|
1603
|
+
except Exception:
|
|
1604
|
+
# Release local readers and the session even when cancellation fails.
|
|
1605
|
+
pass
|
|
1606
|
+
failure: Exception | None = None
|
|
1607
|
+
if active_result is not None:
|
|
1608
|
+
try:
|
|
1609
|
+
active_result.close()
|
|
1610
|
+
except Exception as exc:
|
|
1611
|
+
failure = exc
|
|
1612
|
+
with self._control_condition:
|
|
1613
|
+
while self._inflight_controls:
|
|
1614
|
+
self._control_condition.wait()
|
|
1615
|
+
with self._operation_lock:
|
|
1616
|
+
for reader in tuple(self._readers.values()):
|
|
1617
|
+
with suppress(Exception):
|
|
1618
|
+
reader.close()
|
|
1619
|
+
for plan_id in tuple(self._ready_plans):
|
|
1620
|
+
with suppress(DepositError, TransportError):
|
|
1621
|
+
self._discard_plan(plan_id)
|
|
1622
|
+
for reference in self._result_packages:
|
|
1623
|
+
discard_package(self._endpoint, reference, control=True)
|
|
1624
|
+
self._ready_plans.clear()
|
|
1625
|
+
self._plan_packages.clear()
|
|
1626
|
+
self._result_packages.clear()
|
|
1627
|
+
for bundle in tuple(self._bundles):
|
|
1628
|
+
with suppress(Exception):
|
|
1629
|
+
bundle.close()
|
|
1630
|
+
try:
|
|
1631
|
+
self._endpoint.close()
|
|
1632
|
+
except Exception as exc:
|
|
1633
|
+
failure = failure or exc
|
|
1634
|
+
try:
|
|
1635
|
+
self._client.logout(self._token)
|
|
1636
|
+
except Exception as exc:
|
|
1637
|
+
if failure is None and not _session_already_unavailable(exc):
|
|
1638
|
+
failure = exc
|
|
1639
|
+
with self._state_lock:
|
|
1640
|
+
self._closed = True
|
|
1641
|
+
self._closing = False
|
|
1642
|
+
self._client._store_closed(self)
|
|
1643
|
+
if failure is not None:
|
|
1644
|
+
raise failure
|
|
1645
|
+
|
|
1646
|
+
def __enter__(self) -> "Store":
|
|
1647
|
+
with self._state_lock:
|
|
1648
|
+
if self._closed or self._closing:
|
|
1649
|
+
raise RuntimeError("Store is closed")
|
|
1650
|
+
return self
|
|
1651
|
+
|
|
1652
|
+
def __exit__(self, exc_type, exc, traceback) -> None:
|
|
1653
|
+
self.close()
|
|
1654
|
+
|
|
1655
|
+
@contextmanager
|
|
1656
|
+
def _serialized(self, *, allow_closing: bool = False) -> Iterator[None]:
|
|
1657
|
+
self._operation_lock.acquire()
|
|
1658
|
+
try:
|
|
1659
|
+
with self._state_lock:
|
|
1660
|
+
if self._closed or (self._closing and not allow_closing):
|
|
1661
|
+
raise RuntimeError("Store is closed")
|
|
1662
|
+
self._active = True
|
|
1663
|
+
yield
|
|
1664
|
+
finally:
|
|
1665
|
+
with self._state_lock:
|
|
1666
|
+
self._active = False
|
|
1667
|
+
self._operation_lock.release()
|
|
1668
|
+
|
|
1669
|
+
def _read_entity(self, procedure: str, selection: dict[str, Any] | str) -> dict[str, Any]:
|
|
1670
|
+
self._assert_not_collecting_batch()
|
|
1671
|
+
with self._serialized():
|
|
1672
|
+
query = (
|
|
1673
|
+
f"CYPHER 25 CALL {procedure}Page($selection, {{pageSize: 1}}, $token) YIELD data "
|
|
1674
|
+
"RETURN data.items[0] AS data"
|
|
1675
|
+
)
|
|
1676
|
+
row = self._client._single(query, {"selection": selection, "token": self._token})
|
|
1677
|
+
data = row.get("data")
|
|
1678
|
+
if not isinstance(data, dict):
|
|
1679
|
+
raise DepositError("INVALID_RESPONSE", f"{procedure} returned no portable entity")
|
|
1680
|
+
if data.get("namespaceId") != self._namespace_id:
|
|
1681
|
+
raise DepositError("SCOPE_MISMATCH", "Entity belongs to another Namespace")
|
|
1682
|
+
return data
|
|
1683
|
+
|
|
1684
|
+
def _call_one(self, procedure: str, *arguments: Any, _already_serialized: bool = False) -> Any:
|
|
1685
|
+
entry = store_procedure(procedure)
|
|
1686
|
+
if _already_serialized:
|
|
1687
|
+
bound = bind_arguments(entry, arguments, namespace_id=self._namespace_id)
|
|
1688
|
+
result = self._open_result(entry, bound, _already_serialized=True)
|
|
1689
|
+
else:
|
|
1690
|
+
result = self.call(procedure, *arguments)
|
|
1691
|
+
with result:
|
|
1692
|
+
row = next(result, None)
|
|
1693
|
+
if row is None:
|
|
1694
|
+
raise DepositError("INVALID_RESPONSE", f"{procedure} returned no row")
|
|
1695
|
+
if len(entry["columns"]) == 1:
|
|
1696
|
+
column = entry["columns"][0]
|
|
1697
|
+
value = row.get(column)
|
|
1698
|
+
if not entry["action"] and column in {"node", "rel"}:
|
|
1699
|
+
value = result.to_data(value)
|
|
1700
|
+
else:
|
|
1701
|
+
value = dict(row)
|
|
1702
|
+
if next(result, None) is not None:
|
|
1703
|
+
raise DepositError("INVALID_RESPONSE", f"{procedure} returned multiple rows")
|
|
1704
|
+
return _portable_input(value)
|
|
1705
|
+
|
|
1706
|
+
def _refresh_handle_snapshots(self, handles) -> None:
|
|
1707
|
+
if len(handles) == 1:
|
|
1708
|
+
handle = handles[0]
|
|
1709
|
+
data, schema, revision = self._checked_entity_snapshot(
|
|
1710
|
+
handle.kind, {"id": handle.id}, _already_serialized=True,
|
|
1711
|
+
)
|
|
1712
|
+
snapshots = [(data, schema)]
|
|
1713
|
+
else:
|
|
1714
|
+
entities, revision = self._checked_page_entities(
|
|
1715
|
+
"Class", [handle.id for handle in handles], None, _already_serialized=True,
|
|
1716
|
+
)
|
|
1717
|
+
snapshots = [(entities[handle.id], _schema_from_class_data(entities[handle.id])) for handle in handles]
|
|
1718
|
+
for handle, (data, schema) in zip(handles, snapshots, strict=True):
|
|
1719
|
+
handle._snapshot = data
|
|
1720
|
+
handle._schema = schema
|
|
1721
|
+
handle._baseline_revision = revision
|
|
1722
|
+
handle._stale = False
|
|
1723
|
+
|
|
1724
|
+
@staticmethod
|
|
1725
|
+
def _ensure_handle_current(handle: DNode) -> None:
|
|
1726
|
+
if handle.stale:
|
|
1727
|
+
raise RuntimeError("Entity snapshot is stale; call refresh() before reading or editing")
|
|
1728
|
+
|
|
1729
|
+
def _run_multi_handle_action(self, procedure: str, arguments: list[Any], revision: int,
|
|
1730
|
+
handles: tuple[DNode, ...]):
|
|
1731
|
+
try:
|
|
1732
|
+
return self._run_action(procedure, arguments, pinned_revision=revision)
|
|
1733
|
+
except DepositError as exc:
|
|
1734
|
+
if exc.code == "REVISION_CONFLICT":
|
|
1735
|
+
for handle in handles:
|
|
1736
|
+
handle._mark_stale()
|
|
1737
|
+
raise
|
|
1738
|
+
|
|
1739
|
+
def _open_result(self, entry: dict[str, Any], arguments: tuple[Any, ...], *, _already_serialized: bool = False) -> StoreResult:
|
|
1740
|
+
# Convenience calls may already hold the operation lock.
|
|
1741
|
+
guard = nullcontext() if _already_serialized else self._serialized()
|
|
1742
|
+
guard.__enter__()
|
|
1743
|
+
session = None
|
|
1744
|
+
transaction = None
|
|
1745
|
+
store_result = None
|
|
1746
|
+
closing_error = False
|
|
1747
|
+
try:
|
|
1748
|
+
with self._state_lock:
|
|
1749
|
+
if self._closed or (self._closing and not _already_serialized):
|
|
1750
|
+
closing_error = True
|
|
1751
|
+
raise RuntimeError("Store is closed")
|
|
1752
|
+
session = self._client._session()
|
|
1753
|
+
transaction = session.begin_transaction()
|
|
1754
|
+
query, parameters = build_query(entry, arguments, self._token)
|
|
1755
|
+
result = transaction.run(query, parameters)
|
|
1756
|
+
columns = tuple(result.keys())
|
|
1757
|
+
expected = tuple(entry["columns"])
|
|
1758
|
+
if columns != expected:
|
|
1759
|
+
raise DepositError("INVALID_RESPONSE", f"{entry['name']} returned unexpected columns")
|
|
1760
|
+
|
|
1761
|
+
def finish_result(closed_result: StoreResult) -> None:
|
|
1762
|
+
with self._state_lock:
|
|
1763
|
+
if self._active_result is closed_result:
|
|
1764
|
+
self._active_result = None
|
|
1765
|
+
guard.__exit__(None, None, None)
|
|
1766
|
+
|
|
1767
|
+
store_result = StoreResult(
|
|
1768
|
+
columns,
|
|
1769
|
+
result=result,
|
|
1770
|
+
transaction=transaction,
|
|
1771
|
+
session=session,
|
|
1772
|
+
on_close=finish_result,
|
|
1773
|
+
token=self._token,
|
|
1774
|
+
)
|
|
1775
|
+
with self._state_lock:
|
|
1776
|
+
closing_error = self._closed or (self._closing and not _already_serialized)
|
|
1777
|
+
if not closing_error:
|
|
1778
|
+
self._active_result = store_result
|
|
1779
|
+
if closing_error:
|
|
1780
|
+
store_result.close()
|
|
1781
|
+
raise RuntimeError("Store is closed")
|
|
1782
|
+
return store_result
|
|
1783
|
+
except BaseException as exc:
|
|
1784
|
+
if store_result is None or not store_result.closed:
|
|
1785
|
+
if transaction is not None:
|
|
1786
|
+
try:
|
|
1787
|
+
transaction.rollback()
|
|
1788
|
+
except Exception:
|
|
1789
|
+
pass
|
|
1790
|
+
if session is not None:
|
|
1791
|
+
try:
|
|
1792
|
+
session.close()
|
|
1793
|
+
except Exception:
|
|
1794
|
+
pass
|
|
1795
|
+
guard.__exit__(None, None, None)
|
|
1796
|
+
if isinstance(exc, (DepositError, TransportError)) or closing_error:
|
|
1797
|
+
raise
|
|
1798
|
+
if isinstance(exc, Exception):
|
|
1799
|
+
raise map_driver_error(exc) from exc
|
|
1800
|
+
raise
|
|
1801
|
+
|
|
1802
|
+
def _run_handle_action(self, handle: DNode, procedure: str, arguments: list[Any], *, refresh=False) -> dict[str, Any]:
|
|
1803
|
+
self._ensure_handle_current(handle)
|
|
1804
|
+
return self._run_action(procedure, arguments, pinned_revision=handle._baseline_revision,
|
|
1805
|
+
stale_handle=handle, refresh_handles=(handle,) if refresh else ())
|
|
1806
|
+
|
|
1807
|
+
@contextmanager
|
|
1808
|
+
def _using_endpoint(self, endpoint=None):
|
|
1809
|
+
endpoint = self._endpoint if endpoint is None else endpoint
|
|
1810
|
+
with self._state_lock:
|
|
1811
|
+
if self._closing or self._closed:
|
|
1812
|
+
raise RuntimeError("Store is closed")
|
|
1813
|
+
endpoint.reset_cancellation()
|
|
1814
|
+
self._active_endpoint = endpoint
|
|
1815
|
+
try:
|
|
1816
|
+
yield endpoint
|
|
1817
|
+
finally:
|
|
1818
|
+
with self._state_lock:
|
|
1819
|
+
self._active_endpoint = None
|
|
1820
|
+
|
|
1821
|
+
def _run_action(self, procedure: str, arguments, *, pinned_revision: int | None = None,
|
|
1822
|
+
stale_handle: DNode | None = None, post_snapshot: bool = False,
|
|
1823
|
+
refresh_handles=(), operation_id=None, _already_serialized: bool = False):
|
|
1824
|
+
if self._batch_collection is not None and procedure != "deposit.apply.batch":
|
|
1825
|
+
raise RuntimeError("Store mutations are unavailable while collecting a batch")
|
|
1826
|
+
entry = store_procedure(procedure)
|
|
1827
|
+
if entry.get("tracked") != "always":
|
|
1828
|
+
raise ValueError("Procedure does not accept a tracked operation")
|
|
1829
|
+
bound = bind_arguments(domain_arguments(entry), tuple(arguments), namespace_id=self.namespace_id)
|
|
1830
|
+
frozen = _portable_input(list(bound))
|
|
1831
|
+
operation_id = self._client.new_operation_id() if operation_id is None else operation_id
|
|
1832
|
+
|
|
1833
|
+
def observe(profile):
|
|
1834
|
+
revision = self._session_revision(profile)
|
|
1835
|
+
if pinned_revision is not None and pinned_revision != revision:
|
|
1836
|
+
if stale_handle is not None:
|
|
1837
|
+
stale_handle._mark_stale()
|
|
1838
|
+
raise DepositError("REVISION_CONFLICT", "Entity handle baseline is stale; refresh and reapply explicitly")
|
|
1839
|
+
|
|
1840
|
+
with nullcontext() if _already_serialized else self._serialized():
|
|
1841
|
+
try:
|
|
1842
|
+
with self._using_endpoint() as endpoint, endpoint.execution() as execution:
|
|
1843
|
+
outcome = execution.run(procedure, *frozen, operation_id=operation_id, observe=observe)
|
|
1844
|
+
except DepositError as exc:
|
|
1845
|
+
if exc.code == "REVISION_CONFLICT" and stale_handle is not None:
|
|
1846
|
+
stale_handle._mark_stale()
|
|
1847
|
+
if isinstance(exc, (OutcomeUnknown, OperationCommittedAfterCancel)) or (
|
|
1848
|
+
isinstance(exc.details, dict) and exc.details.get("state") == "COMMITTED"):
|
|
1849
|
+
self._invalidate_handles()
|
|
1850
|
+
raise
|
|
1851
|
+
if entry["scope"] == "namespace" or procedure == "deposit.import.apply":
|
|
1852
|
+
self._invalidate_handles()
|
|
1853
|
+
if entry["columns"] in (["node"], ["rel"]) and (
|
|
1854
|
+
not isinstance(outcome, dict) or outcome.get("namespaceId") != self.namespace_id):
|
|
1855
|
+
raise DepositError("SCOPE_MISMATCH", "Mutation result belongs to another Namespace",
|
|
1856
|
+
{"operationId": operation_id, "scope": self.namespace_id, "state": "COMMITTED"})
|
|
1857
|
+
if post_snapshot or refresh_handles:
|
|
1858
|
+
try:
|
|
1859
|
+
if post_snapshot:
|
|
1860
|
+
kind = "Class" if procedure == "deposit.create.class" else "Object"
|
|
1861
|
+
identity = _item_id(outcome)
|
|
1862
|
+
snapshot = self._checked_entity_snapshot(kind, {"id": identity}, _already_serialized=True)
|
|
1863
|
+
return outcome, snapshot
|
|
1864
|
+
self._refresh_handle_snapshots(refresh_handles)
|
|
1865
|
+
except (DepositError, TransportError, KeyError, TypeError, ValueError) as exc:
|
|
1866
|
+
raise DepositError("RESULT_UNAVAILABLE", "The mutation committed. Inspect its Server receipt.",
|
|
1867
|
+
{"operationId": operation_id, "scope": self.namespace_id, "state": "COMMITTED"}) from exc
|
|
1868
|
+
return _portable_input(outcome)
|
|
1869
|
+
|
|
1870
|
+
def _assert_not_collecting_batch(self) -> None:
|
|
1871
|
+
if self._batch_collection is not None:
|
|
1872
|
+
raise RuntimeError("Store operations are unavailable while collecting a batch")
|
|
1873
|
+
|
|
1874
|
+
def _session_revision(self, profile: dict[str, Any]) -> int:
|
|
1875
|
+
revision = self._get_revision(profile.get("observed"))
|
|
1876
|
+
if revision is None:
|
|
1877
|
+
raise DepositError("REVISION_UNAVAILABLE", "Server returned no Namespace revision baseline")
|
|
1878
|
+
return revision
|
|
1879
|
+
|
|
1880
|
+
def _get_revision(self, observed: Any) -> int | None:
|
|
1881
|
+
if not isinstance(observed, dict):
|
|
1882
|
+
return None
|
|
1883
|
+
revision = observed.get(self._namespace_id)
|
|
1884
|
+
return revision if isinstance(revision, int) and not isinstance(revision, bool) and revision >= 0 else None
|
|
1885
|
+
|
|
1886
|
+
|
|
1887
|
+
def _selector(value: str | dict[str, Any], kind: str) -> str | dict[str, Any]:
|
|
1888
|
+
if isinstance(value, DNode):
|
|
1889
|
+
if value.kind != kind:
|
|
1890
|
+
raise TypeError(f"{kind} selector has the wrong handle kind")
|
|
1891
|
+
return {"id": value.id}
|
|
1892
|
+
if isinstance(value, str) and value:
|
|
1893
|
+
return value
|
|
1894
|
+
if isinstance(value, dict):
|
|
1895
|
+
if set(value) == {"id"} and isinstance(value["id"], str) and value["id"]:
|
|
1896
|
+
return {"id": value["id"]}
|
|
1897
|
+
if value.get("kind") == kind and isinstance(value.get("id"), str):
|
|
1898
|
+
return {"id": value["id"]}
|
|
1899
|
+
raise TypeError(f"{kind} selector must be a name or a stable-ID record")
|
|
1900
|
+
|
|
1901
|
+
|
|
1902
|
+
def _pattern_selector(value: str | Mapping[str, Any]) -> str | dict[str, Any]:
|
|
1903
|
+
if isinstance(value, str) and value:
|
|
1904
|
+
return value
|
|
1905
|
+
if isinstance(value, Mapping):
|
|
1906
|
+
selector = dict(value)
|
|
1907
|
+
if set(selector) == {"id"} and isinstance(selector["id"], str) and selector["id"]:
|
|
1908
|
+
return selector
|
|
1909
|
+
if set(selector) == {"name"} and isinstance(selector["name"], str) and selector["name"]:
|
|
1910
|
+
return selector["name"]
|
|
1911
|
+
raise TypeError("Pattern selector must be a nonempty name or an {id: UUID} mapping")
|
|
1912
|
+
|
|
1913
|
+
|
|
1914
|
+
def _pattern_id_selector(value: Mapping[str, Any]) -> dict[str, str]:
|
|
1915
|
+
selector = dict(value)
|
|
1916
|
+
if set(selector) != {"id"} or not isinstance(selector["id"], str) or not selector["id"]:
|
|
1917
|
+
raise TypeError("Pattern selector must contain only a nonempty 'id' string")
|
|
1918
|
+
return {"id": selector["id"]}
|
|
1919
|
+
|
|
1920
|
+
|
|
1921
|
+
def _import_rules(rules):
|
|
1922
|
+
if rules is not None and not isinstance(rules, Mapping):
|
|
1923
|
+
raise TypeError("rules must be a mapping")
|
|
1924
|
+
return _portable_input(dict(rules or {}))
|
|
1925
|
+
|
|
1926
|
+
|
|
1927
|
+
def _freeze_import_rows(rows: Any) -> list[dict[str, Any]]:
|
|
1928
|
+
if not isinstance(rows, (list, tuple)):
|
|
1929
|
+
raise TypeError("rows must be a list or tuple of row records")
|
|
1930
|
+
frozen = []
|
|
1931
|
+
for row in rows:
|
|
1932
|
+
if not isinstance(row, Mapping):
|
|
1933
|
+
raise TypeError("rows must contain mapping records")
|
|
1934
|
+
record = dict(row)
|
|
1935
|
+
if isinstance(record.get("values"), Mapping):
|
|
1936
|
+
record["values"] = dict(record["values"])
|
|
1937
|
+
frozen.append(record)
|
|
1938
|
+
return frozen
|
|
1939
|
+
|
|
1940
|
+
|
|
1941
|
+
def _schema_from_class_data(data: Any) -> dict[str, str]:
|
|
1942
|
+
if not isinstance(data, Mapping):
|
|
1943
|
+
return {}
|
|
1944
|
+
declarations = data.get("descriptors", [])
|
|
1945
|
+
if not isinstance(declarations, list):
|
|
1946
|
+
return {}
|
|
1947
|
+
schema = {}
|
|
1948
|
+
for declaration in declarations:
|
|
1949
|
+
if not isinstance(declaration, Mapping):
|
|
1950
|
+
continue
|
|
1951
|
+
name, type_name = declaration.get("name"), declaration.get("type")
|
|
1952
|
+
if isinstance(name, str) and isinstance(type_name, str):
|
|
1953
|
+
schema[name] = type_name
|
|
1954
|
+
return schema
|
|
1955
|
+
|
|
1956
|
+
|
|
1957
|
+
def _stable_id(value: Any) -> str:
|
|
1958
|
+
if not isinstance(value, str) or not value:
|
|
1959
|
+
raise TypeError("Entity selector must be a nonempty stable ID")
|
|
1960
|
+
return value
|
|
1961
|
+
|
|
1962
|
+
|
|
1963
|
+
def _item_id(item: Mapping[str, Any]) -> str:
|
|
1964
|
+
"""Extract a stable public entity ID from a portable page item."""
|
|
1965
|
+
identity = item.get("id")
|
|
1966
|
+
if not isinstance(identity, str) or not identity:
|
|
1967
|
+
raise DepositError("INVALID_RESPONSE", "Entity page item has no stable public ID")
|
|
1968
|
+
return identity
|
|
1969
|
+
|
|
1970
|
+
|
|
1971
|
+
def _position_value(value: Any) -> tuple[int | float, int | float]:
|
|
1972
|
+
if not isinstance(value, (tuple, list)) or len(value) != 2:
|
|
1973
|
+
raise TypeError("position must contain exactly two numeric coordinates")
|
|
1974
|
+
if any(type(item) not in {int, float} or not math.isfinite(item) for item in value):
|
|
1975
|
+
raise TypeError("position coordinates must be finite numbers")
|
|
1976
|
+
return value[0], value[1]
|
|
1977
|
+
|
|
1978
|
+
|
|
1979
|
+
def _matching_handle_revision(*handles: DNode) -> int:
|
|
1980
|
+
if not handles:
|
|
1981
|
+
raise ValueError("At least one entity handle is required")
|
|
1982
|
+
revisions = []
|
|
1983
|
+
for handle in handles:
|
|
1984
|
+
if handle.stale:
|
|
1985
|
+
raise RuntimeError("Entity snapshot is stale; call refresh() before editing")
|
|
1986
|
+
revision = handle._baseline_revision
|
|
1987
|
+
if type(revision) is not int or revision < 0:
|
|
1988
|
+
raise ValueError("Entity handle has no checked snapshot revision")
|
|
1989
|
+
revisions.append(revision)
|
|
1990
|
+
if len(set(revisions)) != 1:
|
|
1991
|
+
raise ValueError("Entity handles have conflicting checked snapshot revisions")
|
|
1992
|
+
return revisions[0]
|
|
1993
|
+
|
|
1994
|
+
|
|
1995
|
+
def _class_declarations(values: Any) -> list[dict[str, Any]]:
|
|
1996
|
+
if isinstance(values, Mapping):
|
|
1997
|
+
source = []
|
|
1998
|
+
for name, item in values.items():
|
|
1999
|
+
if isinstance(item, str):
|
|
2000
|
+
source.append((name, item))
|
|
2001
|
+
elif isinstance(item, (tuple, list)):
|
|
2002
|
+
source.append((name, *item))
|
|
2003
|
+
elif isinstance(item, Mapping):
|
|
2004
|
+
source.append({"name": name, **item})
|
|
2005
|
+
else:
|
|
2006
|
+
raise TypeError("Class declaration values must be type names or declaration records")
|
|
2007
|
+
elif isinstance(values, (tuple, list)):
|
|
2008
|
+
source = list(values)
|
|
2009
|
+
else:
|
|
2010
|
+
raise TypeError("descriptors must be a mapping or sequence")
|
|
2011
|
+
declarations = []
|
|
2012
|
+
names = set()
|
|
2013
|
+
for order, item in enumerate(source):
|
|
2014
|
+
if isinstance(item, Mapping):
|
|
2015
|
+
declaration = dict(item)
|
|
2016
|
+
name, type_name = declaration.get("name"), declaration.get("type")
|
|
2017
|
+
comment = declaration.get("comment", "")
|
|
2018
|
+
order_value = declaration.get("order", order)
|
|
2019
|
+
elif isinstance(item, (tuple, list)) and len(item) in {2, 3}:
|
|
2020
|
+
name, type_name = item[:2]
|
|
2021
|
+
comment = item[2] if len(item) == 3 else ""
|
|
2022
|
+
order_value = order
|
|
2023
|
+
declaration = {}
|
|
2024
|
+
else:
|
|
2025
|
+
raise TypeError("Each Class declaration must be (name, type[, comment]) or a mapping")
|
|
2026
|
+
if not isinstance(name, str) or not name or not isinstance(type_name, str) or not type_name:
|
|
2027
|
+
raise ValueError("Class declaration name and type must be nonempty strings")
|
|
2028
|
+
if name in names:
|
|
2029
|
+
raise ValueError(f"Duplicate Class declaration {name!r}")
|
|
2030
|
+
if not isinstance(comment, str) or type(order_value) is not int or order_value < 0:
|
|
2031
|
+
raise ValueError("Class declaration comment/order is invalid")
|
|
2032
|
+
names.add(name)
|
|
2033
|
+
declarations.append({"name": name, "type": type_name, "order": order_value, "comment": comment})
|
|
2034
|
+
return declarations
|
|
2035
|
+
|
|
2036
|
+
|
|
2037
|
+
def _descriptor_payload(value: Any, declared: str | None, *, geometry_encoder=None, resource_encoder=None) -> Any:
|
|
2038
|
+
from .values import DType, TypedValue, _infer_type, encode_value
|
|
2039
|
+
if declared is not None:
|
|
2040
|
+
if isinstance(value, TypedValue):
|
|
2041
|
+
if value.type != declared:
|
|
2042
|
+
raise TypeError(f"Descriptor is declared as {declared}")
|
|
2043
|
+
value = value.value
|
|
2044
|
+
elif isinstance(value, DType):
|
|
2045
|
+
if value._type != declared:
|
|
2046
|
+
raise TypeError(f"Descriptor is declared as {declared}")
|
|
2047
|
+
value = value.value
|
|
2048
|
+
if declared == "DGeometry" and geometry_encoder is not None:
|
|
2049
|
+
value = geometry_encoder(value)
|
|
2050
|
+
elif declared == "DResource" and resource_encoder is not None:
|
|
2051
|
+
value = resource_encoder(value)
|
|
2052
|
+
return encode_value(declared, value)
|
|
2053
|
+
if isinstance(value, TypedValue):
|
|
2054
|
+
kind, raw = value.type, value.value
|
|
2055
|
+
if kind == "DGeometry" and geometry_encoder is not None:
|
|
2056
|
+
raw = geometry_encoder(raw)
|
|
2057
|
+
elif kind == "DResource" and resource_encoder is not None:
|
|
2058
|
+
raw = resource_encoder(raw)
|
|
2059
|
+
return {"type": kind, "value": encode_value(kind, raw)}
|
|
2060
|
+
if isinstance(value, DType):
|
|
2061
|
+
if value._type == "DGeometry" and geometry_encoder is not None:
|
|
2062
|
+
raw = geometry_encoder(value)
|
|
2063
|
+
return {"type": value._type, "value": encode_value(value._type, raw)}
|
|
2064
|
+
if value._type == "DResource" and resource_encoder is not None:
|
|
2065
|
+
raw = resource_encoder(value)
|
|
2066
|
+
return {"type": value._type, "value": encode_value(value._type, raw)}
|
|
2067
|
+
return value.to_dict()
|
|
2068
|
+
kind = _infer_type(value)
|
|
2069
|
+
if kind == "DGeometry" and geometry_encoder is not None:
|
|
2070
|
+
raw = geometry_encoder(value)
|
|
2071
|
+
elif kind == "DResource" and resource_encoder is not None:
|
|
2072
|
+
raw = resource_encoder(value)
|
|
2073
|
+
else:
|
|
2074
|
+
raw = value
|
|
2075
|
+
return {"type": kind, "value": encode_value(kind, raw)}
|
|
2076
|
+
|
|
2077
|
+
|
|
2078
|
+
def _encode_object_properties(properties: dict[str, Any], schema: Mapping[str, str], *,
|
|
2079
|
+
geometry_encoder=None, resource_encoder=None) -> dict[str, Any]:
|
|
2080
|
+
result = dict(properties)
|
|
2081
|
+
if "descriptors" in result:
|
|
2082
|
+
descriptors = result["descriptors"]
|
|
2083
|
+
if not isinstance(descriptors, Mapping) or any(not isinstance(name, str) for name in descriptors):
|
|
2084
|
+
raise TypeError("Object descriptors must be a string-keyed mapping")
|
|
2085
|
+
result["descriptors"] = {
|
|
2086
|
+
name: _descriptor_payload(value, schema.get(name), geometry_encoder=geometry_encoder,
|
|
2087
|
+
resource_encoder=resource_encoder)
|
|
2088
|
+
for name, value in descriptors.items()
|
|
2089
|
+
}
|
|
2090
|
+
return result
|
|
2091
|
+
|
|
2092
|
+
|
|
2093
|
+
def _query_parameters(values: dict[str, Any]) -> dict[str, Any]:
|
|
2094
|
+
from .values import DType, TypedValue
|
|
2095
|
+
result = {}
|
|
2096
|
+
for key, value in values.items():
|
|
2097
|
+
if isinstance(value, (TypedValue, DType)):
|
|
2098
|
+
result[key] = value.to_dict()["value"]
|
|
2099
|
+
elif isinstance(value, dict):
|
|
2100
|
+
result[key] = _query_parameters(value)
|
|
2101
|
+
elif isinstance(value, list):
|
|
2102
|
+
result[key] = [_query_parameters(item) if isinstance(item, dict) else item.to_dict()["value"]
|
|
2103
|
+
if isinstance(item, (TypedValue, DType)) else item for item in value]
|
|
2104
|
+
else:
|
|
2105
|
+
result[key] = value
|
|
2106
|
+
return result
|
|
2107
|
+
|
|
2108
|
+
|
|
2109
|
+
def _portable_input(value: Any) -> Any:
|
|
2110
|
+
_validate_portable_value(value)
|
|
2111
|
+
try:
|
|
2112
|
+
encoded = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
|
|
2113
|
+
return json.loads(encoded)
|
|
2114
|
+
except (TypeError, ValueError, OverflowError) as exc:
|
|
2115
|
+
raise TypeError("Procedure arguments must be losslessly JSON-portable") from exc
|
|
2116
|
+
|
|
2117
|
+
|
|
2118
|
+
def _validate_portable_value(value: Any) -> None:
|
|
2119
|
+
"""Reject values JSON would coerce or silently alter before sending them."""
|
|
2120
|
+
if value is None or type(value) in {bool, int, str}:
|
|
2121
|
+
return
|
|
2122
|
+
if type(value) is float:
|
|
2123
|
+
if not math.isfinite(value):
|
|
2124
|
+
raise TypeError("Procedure arguments must be losslessly JSON-portable")
|
|
2125
|
+
return
|
|
2126
|
+
if isinstance(value, Mapping):
|
|
2127
|
+
if type(value) is not dict:
|
|
2128
|
+
raise TypeError("Procedure arguments require built-in JSON mappings")
|
|
2129
|
+
for key, item in value.items():
|
|
2130
|
+
if not isinstance(key, str):
|
|
2131
|
+
raise TypeError("Procedure arguments require string mapping keys")
|
|
2132
|
+
_validate_portable_value(item)
|
|
2133
|
+
return
|
|
2134
|
+
if type(value) is list:
|
|
2135
|
+
for item in value:
|
|
2136
|
+
_validate_portable_value(item)
|
|
2137
|
+
return
|
|
2138
|
+
raise TypeError("Procedure arguments must be losslessly JSON-portable")
|
|
2139
|
+
|
|
2140
|
+
|
|
2141
|
+
def _session_already_unavailable(exc: Exception) -> bool:
|
|
2142
|
+
return isinstance(exc, DepositError) and exc.code in {"AUTH_FAILED", "AUTH_REQUIRED", "SESSION_EXPIRED", "NOT_FOUND"}
|