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/entities.py ADDED
@@ -0,0 +1,351 @@
1
+ """Stable-UUID, Store-bound entity handles with detached editable snapshots."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator, Mapping
6
+ from copy import deepcopy
7
+ from typing import Any
8
+
9
+ from .errors import DepositError
10
+ from .values import decode_value
11
+
12
+
13
+ class DNode(Mapping):
14
+ """Base stable identity handle; it never stores Neo4j internal IDs."""
15
+
16
+ _kind = ""
17
+
18
+ def __init__(self, store, data: Mapping[str, Any], schema: Mapping[str, str] | None = None,
19
+ *, snapshot_revision: int | None = None):
20
+ if isinstance(data, str):
21
+ if not data:
22
+ raise ValueError("Entity UUID must be a nonempty string")
23
+ data, schema, snapshot_revision = store._checked_entity_snapshot(self._kind, {"id": data})
24
+ if not isinstance(data, Mapping) or data.get("kind") != self._kind:
25
+ raise TypeError(f"Expected portable {self._kind} data")
26
+ identity = data.get("id")
27
+ namespace_id = data.get("namespaceId")
28
+ if not isinstance(identity, str) or not identity or namespace_id != store.namespace_id:
29
+ raise DepositError("SCOPE_MISMATCH", "Entity does not belong to this Store Namespace")
30
+ self._store = store
31
+ self._id = identity
32
+ self._namespace_id = namespace_id
33
+ self._snapshot = deepcopy(dict(data))
34
+ self._schema = dict(schema or {})
35
+ self._baseline_revision = snapshot_revision
36
+ self._pending: dict[str, Any] = {}
37
+ self._stale = False
38
+ register = getattr(store, "_register_handle", None)
39
+ if register is not None:
40
+ register(self)
41
+
42
+ @property
43
+ def id(self) -> str:
44
+ return self._id
45
+
46
+ @property
47
+ def namespace_id(self) -> str:
48
+ return self._namespace_id
49
+
50
+ @property
51
+ def uuid(self) -> str:
52
+ """Read-only compatibility alias for the stable public ID."""
53
+ return self._id
54
+
55
+ @property
56
+ def kind(self) -> str:
57
+ return self._kind
58
+
59
+ @property
60
+ def stale(self) -> bool:
61
+ return self._stale
62
+
63
+ @property
64
+ def pending(self) -> Mapping[str, Any]:
65
+ return deepcopy(self._pending)
66
+
67
+ @property
68
+ def name(self):
69
+ self._ensure_current()
70
+ return self._snapshot.get("name")
71
+
72
+ @property
73
+ def position(self) -> tuple[float, float]:
74
+ self._ensure_current()
75
+ value = self._snapshot.get("position", (0.0, 0.0))
76
+ if not isinstance(value, (list, tuple)) or len(value) < 2:
77
+ raise DepositError("INVALID_RESPONSE", "Entity position is invalid")
78
+ return float(value[0]), float(value[1])
79
+
80
+ @position.setter
81
+ def position(self, value) -> None:
82
+ if not isinstance(value, (list, tuple)) or len(value) != 2:
83
+ raise TypeError("position must contain exactly two coordinates")
84
+ self._store.set_position(self, value[0], value[1])
85
+
86
+ @property
87
+ def order(self) -> int:
88
+ self._ensure_current()
89
+ if self._kind != "Class":
90
+ raise AttributeError("Only Class handles have an order")
91
+ return self._snapshot.get("order", 0)
92
+
93
+ @order.setter
94
+ def order(self, value: int) -> None:
95
+ self._store.set_class_properties(self, order=value)
96
+
97
+ @property
98
+ def comment(self) -> str:
99
+ self._ensure_current()
100
+ if self._kind != "Class":
101
+ raise AttributeError("Only Class handles have a comment")
102
+ return self._snapshot.get("comment", "")
103
+
104
+ @comment.setter
105
+ def comment(self, value: str) -> None:
106
+ self._store.set_class_properties(self, comment=value)
107
+
108
+ def __getitem__(self, key: str) -> Any:
109
+ # Stable identity and scope do not depend on the cached data revision.
110
+ # Keep those fields available to callers using a handle as a selector.
111
+ if key == "id":
112
+ return self._id
113
+ if key == "namespaceId":
114
+ return self._namespace_id
115
+ if key == "kind":
116
+ return self._kind
117
+ self._ensure_current()
118
+ if key == "descriptors" and self._kind == "Object":
119
+ return self._decoded_descriptors()
120
+ if key in self._snapshot:
121
+ return deepcopy(self._snapshot[key])
122
+ if self._kind in {"Class", "Object"}:
123
+ return self._descriptor(key)
124
+ raise KeyError(key)
125
+
126
+ def __iter__(self) -> Iterator[str]:
127
+ self._ensure_current()
128
+ names = set(self._snapshot)
129
+ if self._kind == "Object":
130
+ names.update(self._snapshot.get("descriptors", {}))
131
+ elif self._kind == "Class":
132
+ names.update(self.declarations)
133
+ return iter(sorted(names))
134
+
135
+ def __len__(self) -> int:
136
+ return sum(1 for _ in self.__iter__())
137
+
138
+ def __eq__(self, other):
139
+ if isinstance(other, DNode):
140
+ return self._kind == other._kind and self._id == other._id and self._namespace_id == other._namespace_id
141
+ if isinstance(other, Mapping):
142
+ try:
143
+ return {key: self[key] for key in self} == dict(other)
144
+ except (KeyError, RuntimeError):
145
+ return False
146
+ return NotImplemented
147
+
148
+ def __hash__(self):
149
+ return hash((self._namespace_id, self._kind, self._id))
150
+
151
+ def _ensure_current(self):
152
+ if self._stale or self._snapshot is None:
153
+ raise RuntimeError("Entity snapshot is stale; call refresh() before reading or editing")
154
+
155
+ def _descriptor(self, name: str):
156
+ self._ensure_current()
157
+ if self._kind == "Class":
158
+ declaration = self.declarations.get(name)
159
+ if declaration is None:
160
+ raise KeyError(name)
161
+ return deepcopy(declaration)
162
+ values = self._snapshot.get("descriptors", {})
163
+ if name not in values:
164
+ raise KeyError(name)
165
+ return deepcopy(values[name])
166
+
167
+ def get(self, name: str, default=None):
168
+ try:
169
+ return self._descriptor(name)
170
+ except KeyError:
171
+ return default
172
+
173
+ def __setitem__(self, name: str, value: Any) -> None:
174
+ if self._kind != "Object":
175
+ raise TypeError("Only Object handles assign Descriptor values")
176
+ self._ensure_current()
177
+ if not isinstance(name, str) or not name:
178
+ raise ValueError("Descriptor name must be a nonempty string")
179
+ # Prepare (including Server-owned DGeometry resolution) before retaining
180
+ # this as a pending edit. A type/value error is not unresolved intent.
181
+ prepare = getattr(self._store, "_prepare_descriptor_payload", None)
182
+ submit = getattr(self._store, "_submit_descriptor_payload", None)
183
+ if prepare is None or submit is None:
184
+ from .store import _descriptor_payload
185
+ _descriptor_payload(value, self._schema.get(name))
186
+ payload = None
187
+ else:
188
+ payload = prepare(value, self._schema.get(name))
189
+ self._pending[name] = deepcopy(value)
190
+ if payload is None:
191
+ self._store.set_descriptor(self, name, value)
192
+ else:
193
+ submit(self, name, payload)
194
+ self._pending.pop(name, None)
195
+
196
+ def __delitem__(self, name: str) -> None:
197
+ if self._kind not in {"Object", "Class"}:
198
+ raise TypeError("Only Class or Object Descriptor values can be deleted")
199
+ self._ensure_current()
200
+ self._store._delete_descriptor(self, name)
201
+
202
+ def exists(self) -> bool:
203
+ self._ensure_current()
204
+ try:
205
+ if self._kind == "Class":
206
+ self._store.get_class({"id": self._id})
207
+ else:
208
+ self._store.get_object({"id": self._id})
209
+ except DepositError as exc:
210
+ if exc.code == "NOT_FOUND":
211
+ return False
212
+ raise
213
+ return True
214
+
215
+ def get_descriptor_comment(self, name: str) -> str:
216
+ if self._kind != "Class":
217
+ raise AttributeError("Only Class handles have Descriptor comments")
218
+ declaration = self.declarations.get(name)
219
+ if declaration is None:
220
+ raise KeyError(name)
221
+ return declaration.get("comment", "")
222
+
223
+ def set_descriptor_comment(self, name: str, comment: str) -> None:
224
+ if self._kind != "Class":
225
+ raise AttributeError("Only Class handles have Descriptor comments")
226
+ declaration = self.declarations.get(name)
227
+ if declaration is None:
228
+ raise KeyError(name)
229
+ self._store.set_class_descriptor({"id": declaration["id"]}, {"comment": comment}, dclass=self)
230
+
231
+ def _decoded_descriptors(self):
232
+ values = self._snapshot.get("descriptors", {})
233
+ return {name: deepcopy(value) for name, value in values.items()}
234
+
235
+ def _mark_stale(self):
236
+ self._snapshot = None
237
+ self._schema = {}
238
+ self._stale = True
239
+
240
+ def refresh(self):
241
+ pending = deepcopy(self._pending)
242
+ self._store.refresh()
243
+ data, schema, revision = self._store._checked_entity_snapshot(self._kind, {"id": self._id})
244
+ self._snapshot = deepcopy(data)
245
+ self._schema = dict(schema)
246
+ self._baseline_revision = revision
247
+ self._stale = False
248
+ self._pending = pending
249
+ return self
250
+
251
+ def reapply(self):
252
+ self._ensure_current()
253
+ for name, value in tuple(self._pending.items()):
254
+ self._store.set_descriptor(self, name, value)
255
+ self._pending.pop(name, None)
256
+ return self
257
+
258
+ def as_dict(self) -> dict[str, Any]:
259
+ self._ensure_current()
260
+ return deepcopy(self._snapshot)
261
+
262
+ def __repr__(self):
263
+ return f"<{self._kind} id={self._id!r} namespace_id={self._namespace_id!r}>"
264
+
265
+
266
+ class DClass(DNode):
267
+ _kind = "Class"
268
+
269
+ @property
270
+ def declarations(self) -> dict[str, dict[str, Any]]:
271
+ self._ensure_current()
272
+ raw = self._snapshot.get("descriptors", [])
273
+ if isinstance(raw, list):
274
+ return {item["name"]: deepcopy(item) for item in raw if isinstance(item, dict) and isinstance(item.get("name"), str)}
275
+ return {name: {"name": name, "type": kind} for name, kind in self._schema.items()}
276
+
277
+ def __setitem__(self, name: str, type_name: str) -> None:
278
+ self._ensure_current()
279
+ if not isinstance(name, str) or not name or not isinstance(type_name, str) or not type_name:
280
+ raise TypeError("Class Descriptor assignment requires a name and type name")
281
+ declaration = self.declarations.get(name)
282
+ if declaration is not None:
283
+ if declaration.get("type") != type_name:
284
+ raise ValueError("Changing an existing Descriptor type requires an explicit conversion")
285
+ return
286
+ self._store.create_class_descriptor(self, name, type_name)
287
+
288
+ def switch_descriptor_order(self, name1: str, name2: str):
289
+ return self._store.switch_descriptor_order(self, name1, name2)
290
+
291
+
292
+ class DObject(DNode):
293
+ _kind = "Object"
294
+
295
+ @property
296
+ def class_id(self) -> str:
297
+ self._ensure_current()
298
+ return self._snapshot["classId"]
299
+
300
+ def get_class(self) -> DClass:
301
+ return self._store.object_class(self)
302
+
303
+ def set_class(self, dclass: DClass | str | Mapping[str, Any]):
304
+ return self._store.set_membership(self, dclass)
305
+
306
+ def has_class(self, dclass: DClass | str | Mapping[str, Any]) -> bool:
307
+ if isinstance(dclass, DClass):
308
+ self._store._validate_handle(dclass, "Class")
309
+ class_id = dclass.id
310
+ else:
311
+ class_id = self._store.get_class_handle(dclass).id
312
+ return self.class_id == class_id
313
+
314
+ def get_descriptor_type(self, name: str) -> str:
315
+ self._ensure_current()
316
+ if name not in self._snapshot.get("descriptors", {}):
317
+ raise KeyError(name)
318
+ try:
319
+ return self._schema[name]
320
+ except KeyError as exc:
321
+ raise DepositError("INVALID_RESPONSE", "Descriptor has no declaration in its checked schema") from exc
322
+
323
+
324
+ def decode_snapshot(data: Mapping[str, Any], schema_data: Mapping[str, Any], namespace_id: str, store,
325
+ *, snapshot_revision: int | None = None):
326
+ """Decode Object Descriptor payloads against declarations from the same read transaction."""
327
+ if not isinstance(data, Mapping) or data.get("namespaceId") != namespace_id:
328
+ raise DepositError("SCOPE_MISMATCH", "Snapshot belongs to another Store Namespace")
329
+ raw_declarations = schema_data.get("descriptors", []) if isinstance(schema_data, Mapping) else []
330
+ declarations = {}
331
+ for item in raw_declarations:
332
+ if not isinstance(item, Mapping) or not isinstance(item.get("name"), str) or not isinstance(item.get("type"), str):
333
+ raise DepositError("INVALID_RESPONSE", "Class snapshot returned invalid declarations")
334
+ declarations[item["name"]] = item["type"]
335
+ copied = deepcopy(dict(data))
336
+ descriptors = copied.get("descriptors", {})
337
+ if not isinstance(descriptors, Mapping):
338
+ raise DepositError("INVALID_RESPONSE", "Object snapshot returned invalid Descriptors")
339
+ decoded = {}
340
+ for name, payload in descriptors.items():
341
+ kind = declarations.get(name)
342
+ if kind is None:
343
+ raise DepositError("INVALID_RESPONSE", "Object Descriptor has no declaration in the checked snapshot")
344
+ try:
345
+ decoded[name] = decode_value(kind, payload)
346
+ except (TypeError, ValueError, OverflowError) as exc:
347
+ raise DepositError("INVALID_RESPONSE", "Object Descriptor payload does not match its checked declaration") from exc
348
+ copied["descriptors"] = decoded
349
+ schema = declarations
350
+ handle_type = DObject if copied.get("kind") == "Object" else DClass
351
+ return handle_type(store, copied, schema, snapshot_revision=snapshot_revision)
deposit/errors.py ADDED
@@ -0,0 +1,61 @@
1
+ """Stable, safe error types exposed by the Deposit client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ class DepositError(Exception):
9
+ """A server-reported Deposit failure with a sanitized public envelope."""
10
+
11
+ def __init__(self, code: str, message: str, details: Any = None, request_id: str | None = None):
12
+ self.code = code
13
+ self.message = message
14
+ self.details = details
15
+ self.request_id = request_id
16
+ # Only the validated driver error mapper sets these fields. Local
17
+ # validation errors carry no claim about a server transaction outcome.
18
+ self.retryable: bool | None = None
19
+ self._server_reported = False
20
+ super().__init__(f"{code}: {message}")
21
+
22
+
23
+ class CompatibilityError(DepositError):
24
+ """The connected server is outside the package's tested support matrix."""
25
+
26
+ def __init__(self, version: str, supported: str, component: str = "Deposit Server"):
27
+ self.version = version
28
+ self.supported = supported
29
+ self.component = component
30
+ super().__init__("UNSUPPORTED_VERSION", f"{component} {version!r} is unsupported; this package supports {supported}.")
31
+
32
+
33
+ class TransportError(Exception):
34
+ """A Neo4j driver or transport failure, kept distinct from server errors."""
35
+
36
+
37
+ class DepositCancelled(DepositError):
38
+ """The Server established cancelled rollback."""
39
+
40
+ def __init__(self, operation_id: str, scope: str):
41
+ self.operation_id = operation_id
42
+ self.scope = scope
43
+ super().__init__("CANCELLED_ROLLED_BACK", "The operation was cancelled and rolled back")
44
+
45
+
46
+ class OperationCommittedAfterCancel(DepositError):
47
+ """The Server recorded completion before cancellation took effect."""
48
+
49
+ def __init__(self, operation_id: str, scope: str, status: dict):
50
+ self.operation_id = operation_id
51
+ self.scope = scope
52
+ super().__init__("OPERATION_COMMITTED", "The operation completed before cancellation", status)
53
+
54
+
55
+ class OutcomeUnknown(DepositError):
56
+ """The original attempt requires further inspection."""
57
+
58
+ def __init__(self, operation_id: str, scope: str):
59
+ self.operation_id = operation_id
60
+ self.scope = scope
61
+ super().__init__("OUTCOME_UNKNOWN", "Inspect the original operation before starting a new attempt")
deposit/exchange.py ADDED
@@ -0,0 +1,5 @@
1
+ """Public handle for an immutable Server-owned Exchange ZIP."""
2
+
3
+ from ._exchange import ExchangeBundle
4
+
5
+ __all__ = ["ExchangeBundle"]