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/client.py
ADDED
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
"""Client-side discovery and Deposit authentication smoke path."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import uuid
|
|
7
|
+
from contextlib import contextmanager, suppress
|
|
8
|
+
from functools import cache
|
|
9
|
+
from importlib.metadata import version as distribution_version
|
|
10
|
+
from importlib.resources import files
|
|
11
|
+
from threading import Condition, Lock
|
|
12
|
+
from typing import Any
|
|
13
|
+
from weakref import WeakValueDictionary
|
|
14
|
+
|
|
15
|
+
from neo4j import Driver
|
|
16
|
+
from neo4j.exceptions import Neo4jError
|
|
17
|
+
|
|
18
|
+
from ._gateway import (
|
|
19
|
+
bind_client_arguments,
|
|
20
|
+
build_query,
|
|
21
|
+
client_procedure,
|
|
22
|
+
domain_arguments,
|
|
23
|
+
map_driver_error,
|
|
24
|
+
store_control_procedure,
|
|
25
|
+
tracked_procedure,
|
|
26
|
+
)
|
|
27
|
+
from .errors import CompatibilityError, DepositError, OutcomeUnknown, TransportError
|
|
28
|
+
from ._exchange_transport import OperationEndpoint
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _manifest() -> dict[str, Any]:
|
|
32
|
+
return json.loads(files("deposit").joinpath("_procedure_manifest.json").read_text(encoding="utf-8"))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Client:
|
|
36
|
+
"""A synchronous connection facade.
|
|
37
|
+
|
|
38
|
+
The caller owns a driver unless ``owns_driver=True`` is supplied. Client
|
|
39
|
+
authentication is intentionally separate from Store construction.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(self, driver: Driver, *, owns_driver: bool = False, database: str | None = None):
|
|
43
|
+
self._driver = driver
|
|
44
|
+
self._owns_driver = owns_driver
|
|
45
|
+
self._database = database
|
|
46
|
+
self._closed = False
|
|
47
|
+
self._version: str | None = None
|
|
48
|
+
self._stores = set()
|
|
49
|
+
self._tokens = set()
|
|
50
|
+
self._readers = WeakValueDictionary()
|
|
51
|
+
self._active_endpoints = set()
|
|
52
|
+
self._state = Condition()
|
|
53
|
+
self._close_lock = Lock()
|
|
54
|
+
self._closing = False
|
|
55
|
+
|
|
56
|
+
def _session(self):
|
|
57
|
+
if self._closed:
|
|
58
|
+
raise RuntimeError("Client is closed")
|
|
59
|
+
options = {"database": self._database} if self._database else {}
|
|
60
|
+
return self._driver.session(**options)
|
|
61
|
+
|
|
62
|
+
def _single(self, query: str, parameters: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
63
|
+
return self._single_with_summary(query, parameters)[0]
|
|
64
|
+
|
|
65
|
+
def _single_with_summary(self, query: str, parameters: dict[str, Any] | None = None):
|
|
66
|
+
try:
|
|
67
|
+
with self._session() as session:
|
|
68
|
+
result = session.run(query, parameters or {})
|
|
69
|
+
record = result.single(strict=True)
|
|
70
|
+
consume = getattr(result, "consume", None)
|
|
71
|
+
summary = consume() if consume is not None else None
|
|
72
|
+
return dict(record), summary
|
|
73
|
+
except Neo4jError as exc:
|
|
74
|
+
raise map_driver_error(exc) from exc
|
|
75
|
+
except DepositError:
|
|
76
|
+
raise
|
|
77
|
+
except Exception as exc:
|
|
78
|
+
raise TransportError("Neo4j request failed") from exc
|
|
79
|
+
|
|
80
|
+
@staticmethod
|
|
81
|
+
@cache
|
|
82
|
+
def _check_driver_support() -> None:
|
|
83
|
+
support = _manifest()["support"]
|
|
84
|
+
driver_version = distribution_version("neo4j")
|
|
85
|
+
try:
|
|
86
|
+
driver_components = driver_version.split(".")
|
|
87
|
+
driver_major, driver_minor = int(driver_components[0]), int(driver_components[1])
|
|
88
|
+
except (IndexError, TypeError, ValueError) as exc:
|
|
89
|
+
raise CompatibilityError(driver_version, support["neo4j_driver"], "Neo4j Python driver") from exc
|
|
90
|
+
if driver_major != 6 or driver_minor < 1:
|
|
91
|
+
raise CompatibilityError(driver_version, support["neo4j_driver"], "Neo4j Python driver")
|
|
92
|
+
|
|
93
|
+
def discover(self) -> dict[str, Any]:
|
|
94
|
+
"""Return discovery after checking the installed Neo4j Python driver."""
|
|
95
|
+
self._check_driver_support()
|
|
96
|
+
record = self._single("CYPHER 25 CALL deposit.get.info() YIELD data RETURN data")
|
|
97
|
+
data = record.get("data")
|
|
98
|
+
if not isinstance(data, dict) or not isinstance(data.get("version"), str):
|
|
99
|
+
raise DepositError("INVALID_RESPONSE", "Server discovery returned no version")
|
|
100
|
+
version = data["version"]
|
|
101
|
+
self._version = version
|
|
102
|
+
return dict(data)
|
|
103
|
+
|
|
104
|
+
def require_paged_import_results(self) -> dict[str, Any]:
|
|
105
|
+
"""Require the final paged-result contract before import operations."""
|
|
106
|
+
data = self.discover()
|
|
107
|
+
capabilities = data.get("capabilities")
|
|
108
|
+
if (not isinstance(capabilities, list) or any(not isinstance(item, str) for item in capabilities)
|
|
109
|
+
or "pagedImportResults" not in capabilities):
|
|
110
|
+
raise CompatibilityError(str(capabilities if capabilities is not None else "missing"),
|
|
111
|
+
"pagedImportResults", "Deposit import result capability")
|
|
112
|
+
return data
|
|
113
|
+
|
|
114
|
+
def require_clone_capabilities(self) -> dict[str, Any]:
|
|
115
|
+
"""Require full Namespace clone and paged result support from the Server."""
|
|
116
|
+
data = self.discover()
|
|
117
|
+
capabilities = data.get("capabilities")
|
|
118
|
+
required = {"fullNamespaceClone", "pagedImportResults"}
|
|
119
|
+
malformed = not isinstance(capabilities, list) or any(not isinstance(item, str) for item in capabilities)
|
|
120
|
+
normalized = [item for item in capabilities if isinstance(item, str)] if isinstance(capabilities, list) else []
|
|
121
|
+
if malformed or not required.issubset(normalized):
|
|
122
|
+
missing = sorted(required.difference(normalized))
|
|
123
|
+
detail = "malformed" if malformed else ", ".join(missing)
|
|
124
|
+
raise CompatibilityError(detail, ", ".join(sorted(required)), "Deposit Namespace clone capability")
|
|
125
|
+
return data
|
|
126
|
+
|
|
127
|
+
def login(self, username: str, password: str) -> str:
|
|
128
|
+
"""Authenticate and return the session token; credentials are never logged."""
|
|
129
|
+
self.discover()
|
|
130
|
+
record = self._single(
|
|
131
|
+
"CYPHER 25 CALL deposit.utils.login($username, $password) YIELD value RETURN value",
|
|
132
|
+
{"username": username, "password": password},
|
|
133
|
+
)
|
|
134
|
+
token = record.get("value")
|
|
135
|
+
if not isinstance(token, str) or not token:
|
|
136
|
+
raise DepositError("INVALID_RESPONSE", "Login returned no session token")
|
|
137
|
+
with self._state:
|
|
138
|
+
if self._closing or self._closed:
|
|
139
|
+
with suppress(Exception):
|
|
140
|
+
self.logout(token)
|
|
141
|
+
raise RuntimeError("Client is closed")
|
|
142
|
+
self._tokens.add(token)
|
|
143
|
+
return token
|
|
144
|
+
|
|
145
|
+
def bootstrap(self, username: str, password: str) -> dict[str, Any]:
|
|
146
|
+
"""Create the initial Deposit administrator on a fresh server only."""
|
|
147
|
+
self.discover()
|
|
148
|
+
record = self._single(
|
|
149
|
+
"CYPHER 25 CALL deposit.utils.bootstrap($username, $password) YIELD data RETURN data",
|
|
150
|
+
{"username": username, "password": password},
|
|
151
|
+
)
|
|
152
|
+
data = record.get("data")
|
|
153
|
+
if not isinstance(data, dict):
|
|
154
|
+
raise DepositError("INVALID_RESPONSE", "Bootstrap returned no profile")
|
|
155
|
+
return dict(data)
|
|
156
|
+
|
|
157
|
+
def get_session(self, token: str) -> dict[str, Any]:
|
|
158
|
+
"""Return the sanitized profile for this authenticated session."""
|
|
159
|
+
self.discover()
|
|
160
|
+
record = self._single(
|
|
161
|
+
"CYPHER 25 CALL deposit.get.session($token) YIELD data RETURN data", {"token": token}
|
|
162
|
+
)
|
|
163
|
+
data = record.get("data")
|
|
164
|
+
if not isinstance(data, dict):
|
|
165
|
+
raise DepositError("INVALID_RESPONSE", "Session inspection returned no profile")
|
|
166
|
+
return dict(data)
|
|
167
|
+
|
|
168
|
+
def logout(self, token: str) -> None:
|
|
169
|
+
"""Revoke a Deposit session without closing a caller-owned driver."""
|
|
170
|
+
self.discover()
|
|
171
|
+
self._single("CYPHER 25 CALL deposit.utils.logout($token) YIELD value RETURN value", {"token": token})
|
|
172
|
+
with self._state:
|
|
173
|
+
self._tokens.discard(token)
|
|
174
|
+
|
|
175
|
+
@contextmanager
|
|
176
|
+
def _operation_endpoint(self, token, scope):
|
|
177
|
+
with self._state:
|
|
178
|
+
if self._closed or self._closing:
|
|
179
|
+
raise RuntimeError("Client is closed")
|
|
180
|
+
endpoint = OperationEndpoint(self, token, scope)
|
|
181
|
+
self._active_endpoints.add(endpoint)
|
|
182
|
+
try:
|
|
183
|
+
yield endpoint
|
|
184
|
+
finally:
|
|
185
|
+
try:
|
|
186
|
+
endpoint.close()
|
|
187
|
+
finally:
|
|
188
|
+
with self._state:
|
|
189
|
+
self._active_endpoints.remove(endpoint)
|
|
190
|
+
self._state.notify_all()
|
|
191
|
+
|
|
192
|
+
def _result_request(self, token, procedure, *arguments):
|
|
193
|
+
entry = client_procedure(procedure)
|
|
194
|
+
bound = bind_client_arguments(entry, arguments)
|
|
195
|
+
query, parameters = build_query(entry, bound, token)
|
|
196
|
+
return self._single(query, parameters).get("data")
|
|
197
|
+
|
|
198
|
+
def _result_view(self, token, envelope, result_type, *, plan_observation=None, check_open=None, requester=None):
|
|
199
|
+
from ._paging import valid_import_result_envelope
|
|
200
|
+
|
|
201
|
+
def request(procedure, *arguments):
|
|
202
|
+
if self._closed or self._closing:
|
|
203
|
+
raise RuntimeError("Client is closed")
|
|
204
|
+
if check_open is not None:
|
|
205
|
+
check_open()
|
|
206
|
+
try:
|
|
207
|
+
if requester is not None:
|
|
208
|
+
return requester(procedure, *arguments)
|
|
209
|
+
return self._result_request(token, procedure, *arguments)
|
|
210
|
+
except TransportError as exc:
|
|
211
|
+
raise DepositError("RESULT_UNAVAILABLE", "Could not reach the Server for the result",
|
|
212
|
+
{"operationId": envelope["operationId"], "resultId": envelope["resultId"]}) from exc
|
|
213
|
+
|
|
214
|
+
if valid_import_result_envelope(envelope, leased=False):
|
|
215
|
+
acquired = request("deposit.get.importResult", envelope["resultId"])
|
|
216
|
+
if (not valid_import_result_envelope(acquired)
|
|
217
|
+
or any(acquired[key] != value for key, value in envelope.items())):
|
|
218
|
+
raise DepositError("INVALID_RESPONSE", "Result lease does not match its immutable envelope")
|
|
219
|
+
envelope = acquired
|
|
220
|
+
return result_type(request, envelope, plan_observation=plan_observation)
|
|
221
|
+
|
|
222
|
+
def _invoke_client_procedure(self, procedure: str, token: str, *arguments: Any) -> Any:
|
|
223
|
+
entry = client_procedure(procedure)
|
|
224
|
+
bound = bind_client_arguments(entry, arguments)
|
|
225
|
+
query, parameters = build_query(entry, bound, token, portable=True)
|
|
226
|
+
self.discover()
|
|
227
|
+
record = self._single(query, parameters)
|
|
228
|
+
column = entry["columns"][0]
|
|
229
|
+
if column not in record:
|
|
230
|
+
raise DepositError("INVALID_RESPONSE", f"{procedure} returned no {column} result")
|
|
231
|
+
value = record[column]
|
|
232
|
+
if column in {"node", "rel"} and not isinstance(value, dict):
|
|
233
|
+
raise DepositError("INVALID_RESPONSE", f"{procedure} returned no portable entity")
|
|
234
|
+
return value
|
|
235
|
+
|
|
236
|
+
def _invoke_client_rows(self, procedure: str, token: str, *arguments: Any) -> tuple[dict[str, Any], ...]:
|
|
237
|
+
"""Read portable entity rows, preserving zero/one/many cardinality."""
|
|
238
|
+
entry = client_procedure(procedure)
|
|
239
|
+
bound = bind_client_arguments(entry, arguments)
|
|
240
|
+
query, parameters = build_query(entry, bound, token, portable=True)
|
|
241
|
+
self.discover()
|
|
242
|
+
try:
|
|
243
|
+
with self._session() as session:
|
|
244
|
+
result = session.run(query, parameters)
|
|
245
|
+
column = entry["columns"][0]
|
|
246
|
+
rows = []
|
|
247
|
+
for record in result:
|
|
248
|
+
if column not in record.keys():
|
|
249
|
+
raise DepositError("INVALID_RESPONSE", f"{procedure} returned no {column} result")
|
|
250
|
+
value = record[column]
|
|
251
|
+
if not isinstance(value, dict):
|
|
252
|
+
raise DepositError("INVALID_RESPONSE", f"{procedure} returned no portable entity")
|
|
253
|
+
rows.append(dict(value))
|
|
254
|
+
consume = getattr(result, "consume", None)
|
|
255
|
+
if consume is not None:
|
|
256
|
+
consume()
|
|
257
|
+
return tuple(rows)
|
|
258
|
+
except Neo4jError as exc:
|
|
259
|
+
raise map_driver_error(exc) from exc
|
|
260
|
+
except DepositError:
|
|
261
|
+
raise
|
|
262
|
+
except Exception as exc:
|
|
263
|
+
raise TransportError("Neo4j request failed") from exc
|
|
264
|
+
|
|
265
|
+
@staticmethod
|
|
266
|
+
def new_operation_id() -> str:
|
|
267
|
+
"""Create a fresh UUIDv7 for explicit tracking."""
|
|
268
|
+
return str(uuid.uuid7())
|
|
269
|
+
|
|
270
|
+
def get_operation(self, token: str, operation_id: str, *, scope: str = "server") -> Any:
|
|
271
|
+
"""Inspect an operation under its original explicit scope."""
|
|
272
|
+
return self._invoke_client_procedure("deposit.get.operation", token, operation_id, scope)
|
|
273
|
+
|
|
274
|
+
def cancel_operation(self, token: str, operation_id: str, *, scope: str = "server") -> Any:
|
|
275
|
+
"""Request cancellation and return the Server's authoritative state."""
|
|
276
|
+
with self._state:
|
|
277
|
+
endpoints = tuple(self._active_endpoints)
|
|
278
|
+
for endpoint in endpoints:
|
|
279
|
+
if endpoint.scope == scope and endpoint.token == token and endpoint.note_cancel(operation_id):
|
|
280
|
+
return endpoint._operation_status(operation_id, True)
|
|
281
|
+
return self._invoke_client_procedure("deposit.action.cancel", token, operation_id, scope)
|
|
282
|
+
|
|
283
|
+
def get_last_operation(self, token: str) -> Any:
|
|
284
|
+
"""Return the last operation observed by this authenticated session."""
|
|
285
|
+
entry = store_control_procedure("deposit.get.lastOperation")
|
|
286
|
+
query, parameters = build_query(entry, (), token)
|
|
287
|
+
return self._single(query, parameters).get("data")
|
|
288
|
+
|
|
289
|
+
def get_active_namespace(self, token: str) -> dict[str, Any] | None:
|
|
290
|
+
"""Return the active Namespace as portable data, or None if unselected."""
|
|
291
|
+
self.discover()
|
|
292
|
+
query = (
|
|
293
|
+
"CYPHER 25 CALL deposit.get.activeNamespace($token) YIELD node "
|
|
294
|
+
"CALL { WITH node WITH node WHERE node IS NOT NULL "
|
|
295
|
+
"CALL deposit.utils.toData(node, $token) YIELD data RETURN data "
|
|
296
|
+
"UNION ALL WITH node WITH node WHERE node IS NULL RETURN null AS data } "
|
|
297
|
+
"RETURN data"
|
|
298
|
+
)
|
|
299
|
+
data = self._single(query, {"token": token}).get("data")
|
|
300
|
+
if data is not None and not isinstance(data, dict):
|
|
301
|
+
raise DepositError("INVALID_RESPONSE", "Active Namespace lookup returned invalid data")
|
|
302
|
+
return dict(data) if isinstance(data, dict) else None
|
|
303
|
+
|
|
304
|
+
def set_active_namespace(self, token: str, namespace: Any = None) -> dict[str, Any]:
|
|
305
|
+
"""Set and return the active Namespace as portable data."""
|
|
306
|
+
return self._invoke_client_procedure("deposit.set.activeNamespace", token, namespace)
|
|
307
|
+
|
|
308
|
+
def get_administrative_mode(self, token: str) -> Any:
|
|
309
|
+
"""Return the authenticated session's administrative mode value."""
|
|
310
|
+
return self._invoke_client_procedure("deposit.get.administrativeMode", token)
|
|
311
|
+
|
|
312
|
+
def set_administrative_mode(self, token: str, enabled: bool) -> Any:
|
|
313
|
+
"""Set and return the authenticated session's administrative mode value."""
|
|
314
|
+
return self._invoke_client_procedure("deposit.set.administrativeMode", token, enabled)
|
|
315
|
+
|
|
316
|
+
def get_user(self, token: str, selection: Any) -> Any:
|
|
317
|
+
"""Read a user record using an explicit manifest-defined selector."""
|
|
318
|
+
if selection is None or (isinstance(selection, dict) and not selection):
|
|
319
|
+
raise ValueError("selection must identify one user; use get_users for unfiltered results")
|
|
320
|
+
return self._invoke_client_procedure("deposit.get.user", token, selection)
|
|
321
|
+
|
|
322
|
+
def get_users(self, token: str, selection: Any = None) -> tuple[dict[str, Any], ...]:
|
|
323
|
+
"""Read zero or more selected users as detached portable dictionaries."""
|
|
324
|
+
return self._invoke_client_rows("deposit.get.user", token, selection)
|
|
325
|
+
|
|
326
|
+
def get_user_page(self, token: str, selection: Any = None, page: dict[str, Any] | None = None) -> Any:
|
|
327
|
+
"""Read a page of user records."""
|
|
328
|
+
return self._invoke_client_procedure(
|
|
329
|
+
"deposit.get.userPage", token, selection, {} if page is None else page
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
def get_namespace(self, token: str, selection: Any) -> dict[str, Any]:
|
|
333
|
+
"""Read a Namespace using an explicit selector as portable data."""
|
|
334
|
+
if selection is None or (isinstance(selection, dict) and not selection):
|
|
335
|
+
raise ValueError("selection must identify one Namespace; use get_namespaces for unfiltered results")
|
|
336
|
+
return self._invoke_client_procedure("deposit.get.namespace", token, selection)
|
|
337
|
+
|
|
338
|
+
def get_namespaces(self, token: str, selection: Any = None) -> tuple[dict[str, Any], ...]:
|
|
339
|
+
"""Read zero or more selected Namespaces as detached portable dictionaries."""
|
|
340
|
+
return self._invoke_client_rows("deposit.get.namespace", token, selection)
|
|
341
|
+
|
|
342
|
+
def get_namespace_page(
|
|
343
|
+
self, token: str, selection: Any = None, page: dict[str, Any] | None = None
|
|
344
|
+
) -> Any:
|
|
345
|
+
"""Read a page of Namespace records."""
|
|
346
|
+
return self._invoke_client_procedure(
|
|
347
|
+
"deposit.get.namespacePage", token, selection, {} if page is None else page
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
def prune_resources_status(self, token: str, prune_id: str) -> Any:
|
|
351
|
+
"""Read status for an existing resource-pruning operation."""
|
|
352
|
+
return self._invoke_client_procedure("deposit.admin.pruneResourcesStatus", token, prune_id)
|
|
353
|
+
|
|
354
|
+
def prune_resources(self, token: str, options: dict[str, Any], *, operation_id=None) -> Any:
|
|
355
|
+
"""Preview resource collection or start a tracked prune with an optional ID."""
|
|
356
|
+
if not isinstance(options, dict):
|
|
357
|
+
raise TypeError("prune_resources options must be a dictionary")
|
|
358
|
+
route = "deposit.admin.pruneResources"
|
|
359
|
+
entry = tracked_procedure(route)
|
|
360
|
+
(options,) = bind_client_arguments(domain_arguments(entry), (options,))
|
|
361
|
+
if options.get("dryRun") is not False:
|
|
362
|
+
if operation_id is not None:
|
|
363
|
+
raise ValueError("Dry-run pruning does not accept an operation ID")
|
|
364
|
+
query, parameters = build_query(entry, (options,), token)
|
|
365
|
+
self.discover()
|
|
366
|
+
return self._single(query, parameters)["data"]
|
|
367
|
+
scope = "server"
|
|
368
|
+
if options.get("scope", "namespace") != "all":
|
|
369
|
+
scope = self.get_session(token).get("namespaceId")
|
|
370
|
+
if not isinstance(scope, str):
|
|
371
|
+
raise DepositError("NO_ACTIVE_NAMESPACE", "Select a Namespace first")
|
|
372
|
+
with self._operation_endpoint(token, scope) as endpoint, endpoint.execution() as execution:
|
|
373
|
+
return execution.run(route, options, operation_id=operation_id)
|
|
374
|
+
|
|
375
|
+
def coordinates_to_wkt(
|
|
376
|
+
self,
|
|
377
|
+
token: str,
|
|
378
|
+
geometry_type: str,
|
|
379
|
+
coordinates: Any,
|
|
380
|
+
options: dict[str, Any] | None = None,
|
|
381
|
+
) -> Any:
|
|
382
|
+
"""Convert coordinates to WKT using the server's geometry rules."""
|
|
383
|
+
return self._invoke_client_procedure(
|
|
384
|
+
"deposit.utils.coordinatesToWKT", token, geometry_type, coordinates,
|
|
385
|
+
{} if options is None else options,
|
|
386
|
+
)
|
|
387
|
+
|
|
388
|
+
def wkt_to_coordinates(
|
|
389
|
+
self, token: str, wkt: str, options: dict[str, Any] | None = None
|
|
390
|
+
) -> Any:
|
|
391
|
+
"""Convert WKT to coordinates using the server's geometry rules."""
|
|
392
|
+
return self._invoke_client_procedure(
|
|
393
|
+
"deposit.utils.wktToCoordinates", token, wkt, {} if options is None else options
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
def open_store(
|
|
397
|
+
self,
|
|
398
|
+
namespace: str | dict[str, Any],
|
|
399
|
+
*,
|
|
400
|
+
username: str,
|
|
401
|
+
password: str,
|
|
402
|
+
):
|
|
403
|
+
"""Open an independently authenticated Store bound to one Namespace UUID."""
|
|
404
|
+
if not isinstance(namespace, (str, dict)) or (isinstance(namespace, dict) and not namespace):
|
|
405
|
+
raise TypeError("namespace must be a name or an explicit {id: UUID} selector")
|
|
406
|
+
if isinstance(namespace, dict) and (set(namespace) != {"id"} or not isinstance(namespace["id"], str)):
|
|
407
|
+
raise ValueError("Explicit Namespace selectors must contain only a string id")
|
|
408
|
+
token = self.login(username, password)
|
|
409
|
+
try:
|
|
410
|
+
session = self.get_session(token)
|
|
411
|
+
user = session.get("user")
|
|
412
|
+
actor_id = user.get("id") if isinstance(user, dict) else None
|
|
413
|
+
if not isinstance(actor_id, str) or not actor_id:
|
|
414
|
+
raise DepositError("INVALID_RESPONSE", "Session inspection returned no actor identity")
|
|
415
|
+
selector = namespace if isinstance(namespace, str) else {"id": namespace["id"]}
|
|
416
|
+
query = (
|
|
417
|
+
"CYPHER 25 CALL deposit.get.namespace($selection, $token) YIELD node "
|
|
418
|
+
"CALL deposit.utils.toData(node, $token) YIELD data RETURN data"
|
|
419
|
+
)
|
|
420
|
+
row = self._single(query, {"selection": selector, "token": token})
|
|
421
|
+
data = row.get("data")
|
|
422
|
+
namespace_id = data.get("id") if isinstance(data, dict) else None
|
|
423
|
+
if not isinstance(namespace_id, str) or not namespace_id:
|
|
424
|
+
raise DepositError("INVALID_RESPONSE", "Namespace selection returned no UUID")
|
|
425
|
+
self._single(
|
|
426
|
+
"CYPHER 25 CALL deposit.set.activeNamespace($namespace, $token) YIELD node RETURN node",
|
|
427
|
+
{"namespace": {"id": namespace_id}, "token": token},
|
|
428
|
+
)
|
|
429
|
+
active_query = (
|
|
430
|
+
"CYPHER 25 CALL deposit.get.activeNamespace($token) YIELD node "
|
|
431
|
+
"CALL deposit.utils.toData(node, $token) YIELD data RETURN data"
|
|
432
|
+
)
|
|
433
|
+
active = self._single(active_query, {"token": token}).get("data")
|
|
434
|
+
if not isinstance(active, dict) or active.get("id") != namespace_id:
|
|
435
|
+
raise DepositError("SCOPE_MISMATCH", "Store session selected a different Namespace")
|
|
436
|
+
session = self.get_session(token)
|
|
437
|
+
from .store import Store, _STORE_FACTORY_TOKEN
|
|
438
|
+
|
|
439
|
+
store = Store(
|
|
440
|
+
self, token=token, actor_id=actor_id, namespace_id=namespace_id,
|
|
441
|
+
observed=session.get("observed"), _factory_token=_STORE_FACTORY_TOKEN,
|
|
442
|
+
)
|
|
443
|
+
with self._state:
|
|
444
|
+
if not self._closing and not self._closed:
|
|
445
|
+
self._stores.add(store)
|
|
446
|
+
return store
|
|
447
|
+
store.close()
|
|
448
|
+
raise RuntimeError("Client is closed")
|
|
449
|
+
except Exception:
|
|
450
|
+
try:
|
|
451
|
+
self.logout(token)
|
|
452
|
+
except Exception:
|
|
453
|
+
pass
|
|
454
|
+
raise
|
|
455
|
+
|
|
456
|
+
def clone_namespace(self, token: str, source, *, operation_id=None):
|
|
457
|
+
"""Create a Namespace atomically from a complete Exchange package.
|
|
458
|
+
|
|
459
|
+
operation_id identifies the clone attempt. Upload steps use their own IDs."""
|
|
460
|
+
from ._exchange import ExchangeBundle, discard_package, package_for_target, stage_zip
|
|
461
|
+
from ._paging import CloneResult
|
|
462
|
+
|
|
463
|
+
with self._operation_endpoint(token, "server") as endpoint:
|
|
464
|
+
endpoint._require_capabilities("fullNamespaceClone", "pagedImportResults")
|
|
465
|
+
endpoint.require_exchange()
|
|
466
|
+
endpoint.call("deposit.utils.refresh", "server")
|
|
467
|
+
if isinstance(source, ExchangeBundle):
|
|
468
|
+
reference = package_for_target(source, endpoint)
|
|
469
|
+
owned = reference != source.source
|
|
470
|
+
else:
|
|
471
|
+
reference = stage_zip(endpoint, source)
|
|
472
|
+
owned = True
|
|
473
|
+
try:
|
|
474
|
+
with endpoint.execution() as execution:
|
|
475
|
+
envelope = execution.run("deposit.import.cloneNamespace", {
|
|
476
|
+
name: reference[name] for name in ("packageId", "grant")
|
|
477
|
+
}, operation_id=operation_id)
|
|
478
|
+
result = self._result_view(token, envelope, CloneResult)
|
|
479
|
+
self._readers[id(result)] = result
|
|
480
|
+
return result
|
|
481
|
+
except OutcomeUnknown:
|
|
482
|
+
owned = False
|
|
483
|
+
raise
|
|
484
|
+
finally:
|
|
485
|
+
if owned:
|
|
486
|
+
discard_package(endpoint, reference)
|
|
487
|
+
|
|
488
|
+
def close(self) -> None:
|
|
489
|
+
with self._close_lock:
|
|
490
|
+
with self._state:
|
|
491
|
+
if self._closed:
|
|
492
|
+
return
|
|
493
|
+
self._closing = True
|
|
494
|
+
endpoints = tuple(self._active_endpoints)
|
|
495
|
+
for endpoint in endpoints:
|
|
496
|
+
with suppress(Exception):
|
|
497
|
+
endpoint.cancel_current()
|
|
498
|
+
failure = None
|
|
499
|
+
for store in tuple(self._stores):
|
|
500
|
+
try:
|
|
501
|
+
store.close()
|
|
502
|
+
except Exception as exc:
|
|
503
|
+
if failure is None:
|
|
504
|
+
failure = exc
|
|
505
|
+
with self._state:
|
|
506
|
+
self._state.wait_for(lambda: not self._active_endpoints)
|
|
507
|
+
for result in tuple(self._readers.values()):
|
|
508
|
+
result.close()
|
|
509
|
+
for token in tuple(self._tokens):
|
|
510
|
+
try:
|
|
511
|
+
self.logout(token)
|
|
512
|
+
except DepositError as exc:
|
|
513
|
+
if exc.code not in {"AUTH_FAILED", "AUTH_REQUIRED", "SESSION_EXPIRED", "NOT_FOUND"} and failure is None:
|
|
514
|
+
failure = exc
|
|
515
|
+
except Exception as exc:
|
|
516
|
+
if failure is None:
|
|
517
|
+
failure = exc
|
|
518
|
+
self._tokens.clear()
|
|
519
|
+
self._closed = True
|
|
520
|
+
if self._owns_driver:
|
|
521
|
+
self._driver.close()
|
|
522
|
+
if failure is not None:
|
|
523
|
+
raise failure
|
|
524
|
+
|
|
525
|
+
def _store_closed(self, store: Any) -> None:
|
|
526
|
+
with self._state:
|
|
527
|
+
self._stores.discard(store)
|
|
528
|
+
|
|
529
|
+
def __enter__(self) -> "Client":
|
|
530
|
+
if self._closed:
|
|
531
|
+
raise RuntimeError("Client is closed")
|
|
532
|
+
return self
|
|
533
|
+
|
|
534
|
+
def __exit__(self, exc_type, exc, traceback) -> None:
|
|
535
|
+
self.close()
|