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.
@@ -0,0 +1,411 @@
1
+ """Connection-bound synchronous operation invocation."""
2
+
3
+ from contextlib import contextmanager, suppress
4
+ from threading import Lock
5
+ from time import sleep
6
+ from uuid import uuid7
7
+
8
+ from neo4j import GraphDatabase
9
+ from neo4j.exceptions import Neo4jError
10
+
11
+ from ._gateway import _manifest, build_query, map_driver_error, tracked_procedure
12
+ from .errors import (
13
+ CompatibilityError, DepositCancelled, DepositError, OperationCommittedAfterCancel,
14
+ OutcomeUnknown, TransportError,
15
+ )
16
+ from ._paging import valid_import_result_envelope
17
+
18
+
19
+ _INFO = "CYPHER 25 CALL deposit.get.info() YIELD data RETURN data"
20
+ _CONTROLS = {
21
+ "deposit.action.begin", "deposit.action.cancel", "deposit.get.operation", "deposit.get.session",
22
+ "deposit.get.importPlan", "deposit.get.importResult", "deposit.get.importResultPage", "deposit.get.importResultEntry",
23
+ "deposit.import.discardPlan",
24
+ "deposit.resource.info", "deposit.resource.downloadChunk", "deposit.utils.refresh",
25
+ *(f"deposit.exchange.{name}" for name in ("inspect", "memberPage", "graphPage", "readChunk", "discard")),
26
+ }
27
+ _IMPORT_RESULTS = {
28
+ "deposit.import.analyze": "analysis",
29
+ "deposit.import.rows": "analysis",
30
+ "deposit.import.dataByPattern": "analysis",
31
+ "deposit.import.apply": "apply",
32
+ "deposit.import.cloneNamespace": "clone",
33
+ }
34
+ _TRANSFER_RESULTS = {
35
+ "deposit.resource.beginUpload", "deposit.resource.uploadChunk", "deposit.resource.finishUpload",
36
+ "deposit.get.data", "deposit.get.namespaceData",
37
+ }
38
+
39
+
40
+ def _endpoint_address(address):
41
+ try:
42
+ host, port = address.host.lower().rstrip("."), address.port
43
+ if host and 0 < port <= 65535:
44
+ return f"[{host}]:{port}" if ":" in host and not host.startswith("[") else f"{host}:{port}"
45
+ except (AttributeError, TypeError):
46
+ pass
47
+ raise TransportError("Neo4j did not report the contacted server address")
48
+
49
+
50
+ def _call(session, procedure, arguments, token, *, prepare=None):
51
+ if procedure in _CONTROLS:
52
+ entry = next(item for item in _manifest()["procedures"] if item["name"] == procedure)
53
+ else:
54
+ entry = tracked_procedure(procedure)
55
+ query, parameters = build_query(entry, arguments, token, portable=True)
56
+ try:
57
+ with session.begin_transaction() as transaction:
58
+ if prepare is not None:
59
+ prepare(transaction)
60
+ result = transaction.run(query, parameters)
61
+ row = dict(result.single(strict=True))
62
+ result.consume()
63
+ if set(row) != set(entry["columns"]):
64
+ raise TransportError("Server returned unexpected procedure columns")
65
+ transaction.commit()
66
+ except Neo4jError as exc:
67
+ raise map_driver_error(exc) from exc
68
+ except (DepositError, TransportError):
69
+ raise
70
+ except Exception as exc:
71
+ raise TransportError("Neo4j procedure invocation failed") from exc
72
+ return next(iter(row.values())) if len(row) == 1 else row
73
+
74
+
75
+ class OperationEndpoint:
76
+ """Authenticated endpoint with separate one-connection execution and control pools."""
77
+
78
+ def __init__(self, client, token, scope, *, expected=None, actor=None):
79
+ self.token = token
80
+ self.scope = scope
81
+ self._actor = actor
82
+ self._lock = Lock()
83
+ self._control_lock = Lock()
84
+ self._active_id = None
85
+ self._stopped = False
86
+ self._closed = False
87
+ self._verified_connection = None
88
+ client._check_driver_support()
89
+ row, summary = client._single_with_summary(_INFO)
90
+ info = row.get("data")
91
+ if not isinstance(info, dict) or not isinstance(summary.database, str) or not summary.database:
92
+ raise TransportError("Operation discovery returned no verified database identity")
93
+ capabilities = info.get("capabilities")
94
+ if (not isinstance(info.get("incarnation"), str) or not isinstance(capabilities, list)
95
+ or any(not isinstance(item, str) for item in capabilities)
96
+ or "operationControl" not in capabilities):
97
+ raise CompatibilityError(str(info.get("version")), "operationControl")
98
+ self.endpoint = _endpoint_address(summary.server.address)
99
+ self.database = summary.database
100
+ self.incarnation = info["incarnation"]
101
+ self._capabilities = frozenset(capabilities)
102
+ if expected is not None and self.binding != expected:
103
+ raise DepositError("SCOPE_MISMATCH", "The Store endpoint changed")
104
+ # Keep the original auth provider, impersonation and TLS trust policy.
105
+ pool = client._driver._pool
106
+ self._config = dict(pool.pool_config)
107
+ self._config.update(max_connection_pool_size=1, max_connection_lifetime=float("inf"))
108
+ self._impersonated = pool.workspace_config.impersonated_user
109
+ self._execution = self._new_driver()
110
+ self._control = None
111
+ try:
112
+ self.live_identity()
113
+ except BaseException:
114
+ self.close()
115
+ raise
116
+
117
+ @property
118
+ def binding(self):
119
+ return self.endpoint, self.database, self.incarnation
120
+
121
+ def require_exchange(self):
122
+ self._require_capabilities("exchangeIntake")
123
+
124
+ def _require_capabilities(self, *required):
125
+ if not self._capabilities.issuperset(required):
126
+ raise CompatibilityError(str(sorted(self._capabilities)), ", ".join(required))
127
+
128
+ def _new_driver(self):
129
+ return GraphDatabase.driver(f"bolt://{self.endpoint}", **self._config)
130
+
131
+ def _session(self, driver):
132
+ return driver.session(database=self.database, impersonated_user=self._impersonated)
133
+
134
+ def _verify_session(self, transaction):
135
+ try:
136
+ result = transaction.run(_INFO)
137
+ info = result.single(strict=True)["data"]
138
+ summary = result.consume()
139
+ except Neo4jError as exc:
140
+ raise map_driver_error(exc) from exc
141
+ except Exception as exc:
142
+ raise TransportError("Could not verify the operation endpoint") from exc
143
+ if (not isinstance(info, dict)
144
+ or (_endpoint_address(summary.server.address), summary.database, info.get("incarnation")) != self.binding):
145
+ raise DepositError("SCOPE_MISMATCH", "The operation endpoint changed")
146
+ capabilities = info.get("capabilities")
147
+ if (not isinstance(capabilities, list) or any(not isinstance(item, str) for item in capabilities)
148
+ or frozenset(capabilities) != self._capabilities):
149
+ raise CompatibilityError(str(capabilities), str(sorted(self._capabilities)))
150
+
151
+ def _verify_execution(self, transaction):
152
+ # Session objects can acquire a different Bolt connection between transactions.
153
+ connection = getattr(transaction, "_connection", None)
154
+ if connection is None:
155
+ raise TransportError("Neo4j did not expose the execution connection")
156
+ if connection is not self._verified_connection:
157
+ self._verified_connection = None
158
+ self._verify_session(transaction)
159
+ self._verified_connection = connection
160
+ return connection
161
+
162
+ @contextmanager
163
+ def execution(self):
164
+ with self._session(self._execution) as session:
165
+ yield OperationExecution(self, session, verify=self._verify_execution)
166
+
167
+ def call(self, procedure, *arguments):
168
+ with self._session(self._execution) as session:
169
+ return _call(session, procedure, arguments, self.token, prepare=self._verify_execution)
170
+
171
+ def live_identity(self):
172
+ with self._session(self._execution) as session:
173
+ profile = _call(session, "deposit.get.session", (), self.token, prepare=self._verify_execution)
174
+ self._check_profile(profile)
175
+ return (*self.binding, self._actor)
176
+
177
+ def _check_profile(self, profile):
178
+ user = profile.get("user") if isinstance(profile, dict) else None
179
+ actor = user.get("id") if isinstance(user, dict) else None
180
+ if not isinstance(actor, str) or (self._actor is not None and actor != self._actor):
181
+ self._verified_connection = None
182
+ raise DepositError("IDENTITY_MISMATCH", "The authenticated operation actor changed")
183
+ if self.scope != "server" and profile.get("namespaceId") != self.scope:
184
+ self._verified_connection = None
185
+ raise DepositError("SCOPE_MISMATCH", "The authenticated operation Namespace changed")
186
+ self._actor = actor
187
+
188
+ def control(self, procedure, *arguments):
189
+ with self._control_lock:
190
+ if self._closed:
191
+ raise TransportError("The operation endpoint is closed")
192
+ if self._control is None:
193
+ self._control = self._new_driver()
194
+ with self._session(self._control) as session:
195
+ return _call(session, procedure, arguments, self.token, prepare=self._verify_session)
196
+
197
+ def _operation_status(self, operation_id, cancel):
198
+ procedure = "deposit.action.cancel" if cancel else "deposit.get.operation"
199
+ return self.control(procedure, operation_id, self.scope)
200
+
201
+ def interrupt_upload(self):
202
+ """Close the writer connection so a stopped upload cannot be continued."""
203
+ self._execution.close()
204
+ self._verified_connection = None
205
+ self._execution = self._new_driver()
206
+
207
+ def check_running(self):
208
+ with self._lock:
209
+ if self._stopped:
210
+ raise DepositError("TRANSFER_INTERRUPTED", "The workflow was stopped between Server operations")
211
+
212
+ def reset_cancellation(self):
213
+ with self._lock:
214
+ self._stopped = False
215
+
216
+ def cancel_current(self):
217
+ with self._lock:
218
+ self._stopped = True
219
+ operation_id = self._active_id
220
+ if operation_id is not None:
221
+ self._operation_status(operation_id, True)
222
+ return operation_id is not None
223
+
224
+ def note_cancel(self, operation_id):
225
+ with self._lock:
226
+ if self._active_id != operation_id:
227
+ return False
228
+ self._stopped = True
229
+ return True
230
+
231
+ def close(self):
232
+ with self._control_lock:
233
+ if self._closed:
234
+ return
235
+ self._closed = True
236
+ self._verified_connection = None
237
+ try:
238
+ self._execution.close()
239
+ finally:
240
+ if self._control is not None:
241
+ self._control.close()
242
+
243
+ def __enter__(self):
244
+ return self
245
+
246
+ def __exit__(self, *_):
247
+ self.close()
248
+
249
+
250
+ class OperationExecution:
251
+ def __init__(self, endpoint, session, *, verify=None):
252
+ self._endpoint = endpoint
253
+ self._session = session
254
+ self._verify = verify
255
+
256
+ def run(self, procedure, *arguments, operation_id=None, cleanup=False, observe=None):
257
+ entry = tracked_procedure(procedure)
258
+ operation_id = str(uuid7()) if operation_id is None else operation_id
259
+ endpoint = self._endpoint
260
+ connection = None
261
+ submitted = False
262
+
263
+ def prepare_registration(transaction):
264
+ nonlocal connection, submitted
265
+ if self._verify is not None:
266
+ connection = self._verify(transaction)
267
+ if observe is not None:
268
+ result = transaction.run(
269
+ "CYPHER 25 CALL deposit.get.session($token) YIELD data RETURN data",
270
+ {"token": endpoint.token},
271
+ )
272
+ profile = result.single(strict=True)["data"]
273
+ result.consume()
274
+ endpoint._check_profile(profile)
275
+ observe(profile)
276
+ submitted = True
277
+
278
+ def require_original_connection(transaction):
279
+ if self._verify is not None and transaction._connection is not connection:
280
+ raise TransportError("The registered operation lost its execution connection")
281
+
282
+ with endpoint._lock:
283
+ if endpoint._stopped and not cleanup:
284
+ raise DepositError("TRANSFER_INTERRUPTED", "The workflow was stopped between Server operations")
285
+ if endpoint._active_id is not None:
286
+ raise RuntimeError("The execution connection already has an active operation")
287
+ endpoint._active_id = operation_id
288
+ try:
289
+ try:
290
+ registration = (operation_id, endpoint.scope, procedure, list(arguments))
291
+ if self._verify is None and observe is None:
292
+ submitted = True
293
+ status = _call(self._session, "deposit.action.begin", registration, endpoint.token)
294
+ else:
295
+ status = _call(self._session, "deposit.action.begin", registration, endpoint.token,
296
+ prepare=prepare_registration)
297
+ if not self._matches(status, operation_id):
298
+ raise TransportError("Operation registration identity changed")
299
+ if status.get("state") == "CANCELLED_ROLLED_BACK":
300
+ raise DepositCancelled(operation_id, endpoint.scope)
301
+ if status.get("state") != "REGISTERED":
302
+ # An existing terminal attempt can be inspected by ID. It
303
+ # cannot authorize a second execution from this call.
304
+ return self._settled_result(procedure, operation_id, status)
305
+ checks = {"prepare": require_original_connection} if self._verify is not None else {}
306
+ result = _call(self._session, procedure, (*arguments, operation_id), endpoint.token, **checks)
307
+ if procedure in _IMPORT_RESULTS:
308
+ self._check_envelope(procedure, operation_id, result)
309
+ with endpoint._lock:
310
+ stopped = endpoint._stopped
311
+ if stopped and not cleanup:
312
+ self._completed_after_stop(entry, operation_id, result)
313
+ return result
314
+ except (TransportError, KeyboardInterrupt) as failure:
315
+ if not submitted:
316
+ raise
317
+ return self._settle(procedure, operation_id, failure, cancel=isinstance(failure, KeyboardInterrupt))
318
+ except DepositError as failure:
319
+ if type(failure) is DepositError and failure.code in {
320
+ "CANCELLED", "OPERATION_NOT_CLAIMABLE", "OUTCOME_UNKNOWN",
321
+ }:
322
+ return self._settle(procedure, operation_id, failure)
323
+ raise
324
+ finally:
325
+ with endpoint._lock:
326
+ endpoint._active_id = None
327
+
328
+ def _completed_after_stop(self, entry, operation_id, value):
329
+ endpoint = self._endpoint
330
+ procedure = entry["name"]
331
+ status = None
332
+ with suppress(DepositError, TransportError):
333
+ status = endpoint._operation_status(operation_id, False)
334
+ if (not self._matches(status, operation_id) or status.get("procedure") != procedure
335
+ or status.get("state") not in {"COMMITTED", "COMPLETED_NO_DOMAIN_WRITE"}):
336
+ # This invocation already received its COMMIT acknowledgement.
337
+ # An inaccessible status read cannot undo that evidence.
338
+ domain = (entry["scope"] not in {"operational", "exchangeUpload"}
339
+ or procedure == "deposit.import.apply")
340
+ result = None
341
+ if procedure.startswith("deposit.exchange."):
342
+ result = value
343
+ elif _IMPORT_RESULTS.get(procedure) == "analysis":
344
+ result = {"planId": value["planId"]}
345
+ status = {"operationId": operation_id, "scope": endpoint.scope, "procedure": procedure,
346
+ "state": "COMMITTED" if domain else "COMPLETED_NO_DOMAIN_WRITE", "result": result}
347
+ raise OperationCommittedAfterCancel(operation_id, endpoint.scope, status)
348
+
349
+ def _matches(self, status, operation_id):
350
+ return (isinstance(status, dict) and status.get("operationId") == operation_id
351
+ and status.get("scope") == self._endpoint.scope)
352
+
353
+ def _check_envelope(self, procedure, operation_id, envelope):
354
+ kind = _IMPORT_RESULTS[procedure]
355
+ if (not valid_import_result_envelope(envelope) or envelope["kind"] != kind
356
+ or envelope["operationId"] != operation_id
357
+ or (kind != "clone" and envelope["namespaceId"] != self._endpoint.scope)):
358
+ raise TransportError("Import result does not match the executed operation")
359
+
360
+ def _settle(self, procedure, operation_id, failure, *, cancel=False):
361
+ endpoint = self._endpoint
362
+ try:
363
+ try:
364
+ status = endpoint._operation_status(operation_id, cancel)
365
+ except (DepositError, TransportError):
366
+ if not cancel:
367
+ raise
368
+ status = endpoint._operation_status(operation_id, False)
369
+ if self._matches(status, operation_id) and status.get("state") in {"RUNNING", "REGISTERED"} and not cancel:
370
+ cancel = True
371
+ status = endpoint._operation_status(operation_id, True)
372
+ for _ in range(3):
373
+ if not self._matches(status, operation_id) or status.get("state") != "CANCEL_REQUESTED":
374
+ break
375
+ sleep(0.025)
376
+ status = endpoint._operation_status(operation_id, False)
377
+ except Exception:
378
+ raise OutcomeUnknown(operation_id, endpoint.scope) from failure
379
+ return self._settled_result(procedure, operation_id, status, failure, cancel=cancel)
380
+
381
+ def _settled_result(self, procedure, operation_id, status, failure=None, *, cancel=False):
382
+ endpoint = self._endpoint
383
+ if not self._matches(status, operation_id):
384
+ raise OutcomeUnknown(operation_id, endpoint.scope) from failure
385
+ state = status.get("state")
386
+ if state == "CANCELLED_ROLLED_BACK" and status.get("procedure") in {None, procedure}:
387
+ raise DepositCancelled(operation_id, endpoint.scope) from failure
388
+ if status.get("procedure") != procedure:
389
+ raise OutcomeUnknown(operation_id, endpoint.scope) from failure
390
+ if state == "FAILED_ROLLED_BACK":
391
+ raise DepositError(state, "The operation failed and rolled back", status) from failure
392
+ if state not in {"COMMITTED", "COMPLETED_NO_DOMAIN_WRITE"}:
393
+ raise OutcomeUnknown(operation_id, endpoint.scope) from failure
394
+ if cancel:
395
+ raise OperationCommittedAfterCancel(operation_id, endpoint.scope, status) from failure
396
+ summary = status.get("result")
397
+ code = status.get("code")
398
+ if code is None and isinstance(summary, dict):
399
+ if procedure.startswith("deposit.exchange.") or procedure in _TRANSFER_RESULTS:
400
+ return summary
401
+ if procedure in _IMPORT_RESULTS and isinstance(summary.get("resultId"), str):
402
+ try:
403
+ envelope = endpoint.call("deposit.get.importResult", summary["resultId"])
404
+ self._check_envelope(procedure, operation_id, envelope)
405
+ if envelope["resultId"] != summary["resultId"]:
406
+ raise TransportError("Result lease has another identity")
407
+ return envelope
408
+ except (DepositError, TransportError) as exc:
409
+ code = exc.code if isinstance(exc, DepositError) and exc.code == "RESULT_EXPIRED" else "RESULT_UNAVAILABLE"
410
+ failure = exc
411
+ raise DepositError(code or "RESULT_UNAVAILABLE", "The operation finished. Inspect its Server receipt.", status) from failure