minigraph-book 0.1.0__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.
minigraph/__init__.py ADDED
@@ -0,0 +1,53 @@
1
+ """minigraph: a small property-graph database, built one subsystem at a time in the accompanying book."""
2
+
3
+ from minigraph.arguments import ArgumentGraph
4
+ from minigraph.database import Database
5
+ from minigraph.errors import ConstraintError
6
+ from minigraph.errors import EdgeNotFoundError
7
+ from minigraph.errors import FormatError
8
+ from minigraph.errors import GraphError
9
+ from minigraph.errors import IndexExistsError
10
+ from minigraph.errors import LogCorruptionError
11
+ from minigraph.errors import MissingPropertyError
12
+ from minigraph.errors import NodeInUseError
13
+ from minigraph.errors import NodeNotFoundError
14
+ from minigraph.errors import NoSuchIndexError
15
+ from minigraph.errors import QueryError
16
+ from minigraph.errors import QuerySyntaxError
17
+ from minigraph.errors import UniquenessError
18
+ from minigraph.errors import ValidationError
19
+ from minigraph.execute import Result
20
+ from minigraph.execute import run
21
+ from minigraph.graph import Graph
22
+ from minigraph.model import Edge
23
+ from minigraph.model import Node
24
+ from minigraph.storage import load
25
+ from minigraph.storage import save
26
+ from minigraph.vocabulary import Dimension
27
+
28
+ __all__ = [
29
+ "ArgumentGraph",
30
+ "ConstraintError",
31
+ "Database",
32
+ "Dimension",
33
+ "Edge",
34
+ "EdgeNotFoundError",
35
+ "FormatError",
36
+ "Graph",
37
+ "GraphError",
38
+ "IndexExistsError",
39
+ "LogCorruptionError",
40
+ "MissingPropertyError",
41
+ "NoSuchIndexError",
42
+ "Node",
43
+ "NodeInUseError",
44
+ "NodeNotFoundError",
45
+ "QueryError",
46
+ "QuerySyntaxError",
47
+ "Result",
48
+ "UniquenessError",
49
+ "ValidationError",
50
+ "load",
51
+ "run",
52
+ "save",
53
+ ]
minigraph/arguments.py ADDED
@@ -0,0 +1,160 @@
1
+ """Model a debate as a graph: statements, and the attacks and supports between them.
2
+
3
+ Everything is stored in an ordinary :class:`~minigraph.graph.Graph`, in the layout that
4
+ :mod:`minigraph.vocabulary` describes.
5
+ """
6
+
7
+ from typing import TYPE_CHECKING
8
+
9
+ from minigraph.errors import ArgumentError
10
+ from minigraph.errors import UnknownAlgorithmError
11
+ from minigraph.framework import Options
12
+ from minigraph.framework import project
13
+ from minigraph.graph import Graph
14
+ from minigraph.semantics import Gradual
15
+ from minigraph.semantics import Grounded
16
+ from minigraph.semantics import Preferred
17
+ from minigraph.vocabulary import ATTACK
18
+ from minigraph.vocabulary import DIMENSIONS
19
+ from minigraph.vocabulary import SOURCE_OF
20
+ from minigraph.vocabulary import STATEMENT
21
+ from minigraph.vocabulary import SUPPORT
22
+ from minigraph.vocabulary import TARGETS
23
+ from minigraph.vocabulary import Dimension
24
+
25
+ if TYPE_CHECKING:
26
+ from collections.abc import Sequence
27
+
28
+ from minigraph.model import NodeId
29
+ from minigraph.semantics import Algorithm
30
+ from minigraph.semantics import Outcome
31
+
32
+
33
+ class ArgumentGraph:
34
+ """A graph of statements with attacks and supports, built with the vocabulary of a debate.
35
+
36
+ >>> debate = ArgumentGraph()
37
+ >>> rain = debate.state("It will rain")
38
+ >>> sun = debate.state("It will be sunny")
39
+ >>> debate.attack_with(sun, rain, authority=1)
40
+ 3
41
+ >>> debate.graph.node_count(), debate.graph.edge_count()
42
+ (3, 2)
43
+
44
+ :param graph: the graph to keep the debate in; ``None`` means a new, empty one.
45
+ """
46
+
47
+ def __init__(self, graph: Graph | None = None) -> None:
48
+ self.graph = Graph() if graph is None else graph
49
+ self._algorithms: dict[str, Algorithm] = {
50
+ "grounded": Grounded(),
51
+ "preferred": Preferred(),
52
+ "gradual": Gradual(),
53
+ }
54
+
55
+ def state(self, text: str, base: float | None = None) -> NodeId:
56
+ """Add a statement.
57
+
58
+ :param text: what the statement says.
59
+ :param base: how believable it is before anyone argues about it, from 0 to 1; ``None`` leaves it unset.
60
+ :return: the id of the new statement.
61
+ :raises ArgumentError: if ``base`` is not between 0 and 1.
62
+ :raises ValidationError: if the text is not a legal property value.
63
+ """
64
+ props: dict[str, object] = {"text": text}
65
+ if base is not None:
66
+ if not 0.0 <= base <= 1.0:
67
+ message = f"base must be between 0 and 1, not {base}"
68
+ raise ArgumentError(message)
69
+ props["base"] = float(base)
70
+ return self.graph.create_node(STATEMENT, props).id
71
+
72
+ def attack_with(
73
+ self,
74
+ source: NodeId,
75
+ target: NodeId,
76
+ *,
77
+ authority: int | None = None,
78
+ specificity: int | None = None,
79
+ recency: int | None = None,
80
+ ) -> NodeId:
81
+ """Make a statement attack a statement, or another attack or support.
82
+
83
+ :param source: the statement that attacks.
84
+ :param target: what it attacks: a statement, or an attack or a support.
85
+ :param authority: how authoritative the attack's source is; lower wins; ``None`` ranks last.
86
+ :param specificity: how specific it is; lower wins; ``None`` ranks last.
87
+ :param recency: how recent it is; lower wins; ``None`` ranks last.
88
+ :return: the id of the new attack.
89
+ :raises ArgumentError: if ``source`` is not a statement, or ``target`` is not part of the debate.
90
+ """
91
+ ranks = {Dimension.AUTHORITY: authority, Dimension.SPECIFICITY: specificity, Dimension.RECENCY: recency}
92
+ return self._relate(ATTACK, source, target, ranks)
93
+
94
+ def support_with(
95
+ self,
96
+ source: NodeId,
97
+ target: NodeId,
98
+ *,
99
+ authority: int | None = None,
100
+ specificity: int | None = None,
101
+ recency: int | None = None,
102
+ ) -> NodeId:
103
+ """Make a statement support a statement, or another attack or support.
104
+
105
+ The arguments are those of :meth:`attack_with`.
106
+
107
+ :return: the id of the new support.
108
+ :raises ArgumentError: if ``source`` is not a statement, or ``target`` is not part of the debate.
109
+ """
110
+ ranks = {Dimension.AUTHORITY: authority, Dimension.SPECIFICITY: specificity, Dimension.RECENCY: recency}
111
+ return self._relate(SUPPORT, source, target, ranks)
112
+
113
+ def _relate(self, kind: str, source: NodeId, target: NodeId, ranks: dict[Dimension, int | None]) -> NodeId:
114
+ """Create the relation node and its two edges, all or nothing."""
115
+ if STATEMENT not in self.graph.node(source).labels:
116
+ message = f"node {source} is not a statement, so it cannot be the source of a relation"
117
+ raise ArgumentError(message)
118
+ if not self.graph.node(target).labels & {STATEMENT, ATTACK, SUPPORT}:
119
+ message = f"node {target} is not a statement, an attack or a support"
120
+ raise ArgumentError(message)
121
+ props = {dimension.value: rank for dimension, rank in ranks.items() if rank is not None}
122
+ with self.graph.begin() as unit:
123
+ relation = unit.create_node(kind, props)
124
+ unit.create_edge(source, relation.id, SOURCE_OF)
125
+ unit.create_edge(relation.id, target, TARGETS)
126
+ return relation.id
127
+
128
+ def register(self, name: str, algorithm: Algorithm) -> None:
129
+ """Make an algorithm available under a name.
130
+
131
+ :param name: the name to run it by.
132
+ :param algorithm: any object with a ``solve`` method that takes a framework and returns an outcome.
133
+ :raises ArgumentError: if the name is already taken.
134
+ """
135
+ if name in self._algorithms:
136
+ message = f"an algorithm called {name!r} is already registered"
137
+ raise ArgumentError(message)
138
+ self._algorithms[name] = algorithm
139
+
140
+ def solve(
141
+ self,
142
+ name: str,
143
+ *,
144
+ supports: bool = True,
145
+ higher_order: bool = True,
146
+ precedence: Sequence[Dimension] = DIMENSIONS,
147
+ ) -> Outcome:
148
+ """Run a registered algorithm on the debate.
149
+
150
+ :param name: the algorithm to run.
151
+ :param supports: if ``False``, reason on attacks only.
152
+ :param higher_order: if ``False``, ignore the attacks and supports that aim at other attacks and supports.
153
+ :param precedence: the dimensions on which attacks can outrank one another, most important first; empty means none.
154
+ :return: what the algorithm found.
155
+ :raises UnknownAlgorithmError: if no algorithm has that name.
156
+ """
157
+ algorithm = self._algorithms.get(name)
158
+ if algorithm is None:
159
+ raise UnknownAlgorithmError(name, sorted(self._algorithms))
160
+ return algorithm.solve(project(self.graph, Options(supports, higher_order, tuple(precedence))))
minigraph/binary.py ADDED
@@ -0,0 +1,394 @@
1
+ """Encode snapshots in a compact binary format with a checksum."""
2
+
3
+ import struct
4
+ import zlib
5
+ from typing import TYPE_CHECKING
6
+
7
+ from minigraph.changes import Change
8
+ from minigraph.constraints import ConstraintSpec
9
+ from minigraph.errors import FormatError
10
+ from minigraph.errors import ValidationError
11
+ from minigraph.index import IndexSpec
12
+ from minigraph.model import Edge
13
+ from minigraph.model import Node
14
+ from minigraph.snapshot import Snapshot
15
+
16
+ if TYPE_CHECKING:
17
+ from collections.abc import Callable
18
+ from collections.abc import Iterable
19
+ from collections.abc import Mapping
20
+ from collections.abc import Sequence
21
+
22
+ from minigraph.changes import AnyChange
23
+ from minigraph.constraints import ConstraintKind
24
+ from minigraph.index import IndexKind
25
+ from minigraph.index import Target
26
+ from minigraph.values import Scalar
27
+ from minigraph.values import Value
28
+
29
+ _MAGIC = b"MGRF"
30
+ _VERSION = 1
31
+ _FALSE, _TRUE, _INT, _FLOAT, _STR, _LIST = range(6)
32
+ _TARGETS: tuple[Target, ...] = ("node", "edge")
33
+ _INDEX_KINDS: tuple[IndexKind, ...] = ("hash", "sorted")
34
+ _CONSTRAINT_KINDS: tuple[ConstraintKind, ...] = ("unique", "exists")
35
+
36
+
37
+ def _put_uvarint(out: bytearray, number: int) -> None:
38
+ """Append a non-negative integer, seven bits at a time, least significant first."""
39
+ while number >= 0x80:
40
+ out.append((number & 0x7F) | 0x80)
41
+ number >>= 7
42
+ out.append(number)
43
+
44
+
45
+ def _put_int(out: bytearray, number: int) -> None:
46
+ """Append a signed integer, zigzag-mapped to a non-negative one."""
47
+ _put_uvarint(out, number * 2 if number >= 0 else -number * 2 - 1)
48
+
49
+
50
+ def _put_str(out: bytearray, text: str) -> None:
51
+ """Append a string: its length in bytes, then its UTF-8 encoding."""
52
+ raw = text.encode("utf-8")
53
+ _put_uvarint(out, len(raw))
54
+ out += raw
55
+
56
+
57
+ def _put_scalar(out: bytearray, value: Scalar) -> None:
58
+ """Append a scalar: a tag, then its content."""
59
+ match value:
60
+ case bool():
61
+ out.append(_TRUE if value else _FALSE)
62
+ case int():
63
+ out.append(_INT)
64
+ _put_int(out, value)
65
+ case float():
66
+ out.append(_FLOAT)
67
+ out += struct.pack(">d", value)
68
+ case str():
69
+ out.append(_STR)
70
+ _put_str(out, value)
71
+
72
+
73
+ def _put_value(out: bytearray, value: Value) -> None:
74
+ """Append a property value: a scalar, or a list tag, a count and the scalars."""
75
+ if isinstance(value, tuple):
76
+ out.append(_LIST)
77
+ _put_uvarint(out, len(value))
78
+ for item in value:
79
+ _put_scalar(out, item)
80
+ else:
81
+ _put_scalar(out, value)
82
+
83
+
84
+ def _put_props(out: bytearray, props: Mapping[str, Value]) -> None:
85
+ """Append a number of properties, each a name and a value."""
86
+ _put_uvarint(out, len(props))
87
+ for name, value in props.items():
88
+ _put_str(out, name)
89
+ _put_value(out, value)
90
+
91
+
92
+ def _put_names(out: bytearray, names: Iterable[str]) -> None:
93
+ """Append a count of names and the sorted names."""
94
+ ordered = sorted(names)
95
+ _put_uvarint(out, len(ordered))
96
+ for name in ordered:
97
+ _put_str(out, name)
98
+
99
+
100
+ def _put_each[T](out: bytearray, items: Sequence[T], put: Callable[[bytearray, T], None]) -> None:
101
+ """Append a count of items, then each item."""
102
+ _put_uvarint(out, len(items))
103
+ for item in items:
104
+ put(out, item)
105
+
106
+
107
+ def _put_node(out: bytearray, node: Node) -> None:
108
+ _put_uvarint(out, node.id)
109
+ _put_names(out, node.labels)
110
+ _put_props(out, node.props)
111
+
112
+
113
+ def _put_edge(out: bytearray, edge: Edge) -> None:
114
+ _put_uvarint(out, edge.id)
115
+ _put_uvarint(out, edge.src)
116
+ _put_uvarint(out, edge.dst)
117
+ _put_names(out, edge.types)
118
+ _put_props(out, edge.props)
119
+
120
+
121
+ def _put_index(out: bytearray, spec: IndexSpec) -> None:
122
+ out.append(_TARGETS.index(spec.target))
123
+ _put_str(out, spec.token)
124
+ _put_str(out, spec.prop)
125
+ out.append(_INDEX_KINDS.index(spec.kind))
126
+
127
+
128
+ def _put_constraint(out: bytearray, spec: ConstraintSpec) -> None:
129
+ out.append(_CONSTRAINT_KINDS.index(spec.kind))
130
+ out.append(_TARGETS.index(spec.target))
131
+ _put_str(out, spec.token)
132
+ _put_str(out, spec.prop)
133
+
134
+
135
+ class _Reader:
136
+ """Read values from bytes, one after the other."""
137
+
138
+ def __init__(self, data: bytes) -> None:
139
+ self._data = data
140
+ self._position = 0
141
+
142
+ def at_end(self) -> bool:
143
+ return self._position == len(self._data)
144
+
145
+ def take(self, count: int) -> bytes:
146
+ end = self._position + count
147
+ if end > len(self._data):
148
+ raise FormatError("unexpected end of data")
149
+ chunk = self._data[self._position : end]
150
+ self._position = end
151
+ return chunk
152
+
153
+ def byte(self) -> int:
154
+ return self.take(1)[0]
155
+
156
+ def uvarint(self) -> int:
157
+ number = shift = 0
158
+ while True:
159
+ byte = self.byte()
160
+ number |= (byte & 0x7F) << shift
161
+ if byte < 0x80:
162
+ return number
163
+ shift += 7
164
+
165
+ def integer(self) -> int:
166
+ mapped = self.uvarint()
167
+ return mapped >> 1 if mapped % 2 == 0 else -((mapped + 1) >> 1)
168
+
169
+ def text(self) -> str:
170
+ return self.take(self.uvarint()).decode("utf-8")
171
+
172
+ def scalar(self, tag: int) -> Scalar:
173
+ match tag:
174
+ case 0 | 1:
175
+ return tag == 1
176
+ case 2:
177
+ return self.integer()
178
+ case 3:
179
+ return float(struct.unpack(">d", self.take(8))[0])
180
+ case 4:
181
+ return self.text()
182
+ raise FormatError(f"unknown value tag {tag}")
183
+
184
+ def value(self) -> Value:
185
+ tag = self.byte()
186
+ if tag == _LIST:
187
+ return tuple(self.scalar(self.byte()) for _ in range(self.uvarint()))
188
+ return self.scalar(tag)
189
+
190
+ def props(self) -> dict[str, Value]:
191
+ return {self.text(): self.value() for _ in range(self.uvarint())}
192
+
193
+ def names(self) -> list[str]:
194
+ return [self.text() for _ in range(self.uvarint())]
195
+
196
+ def each[T](self, get: Callable[[_Reader], T]) -> tuple[T, ...]:
197
+ return tuple(get(self) for _ in range(self.uvarint()))
198
+
199
+
200
+ def _pick[T](options: tuple[T, ...], index: int) -> T:
201
+ """Return the option at an index read from the data, or raise if there is none."""
202
+ if index >= len(options):
203
+ raise FormatError(f"unknown option {index}")
204
+ return options[index]
205
+
206
+
207
+ def _get_node(reader: _Reader) -> Node:
208
+ return Node.make(reader.uvarint(), reader.names(), reader.props())
209
+
210
+
211
+ def _get_edge(reader: _Reader) -> Edge:
212
+ return Edge.make(reader.uvarint(), reader.uvarint(), reader.uvarint(), reader.names(), reader.props())
213
+
214
+
215
+ def _get_index(reader: _Reader) -> IndexSpec:
216
+ target = _pick(_TARGETS, reader.byte())
217
+ return IndexSpec(target, reader.text(), reader.text(), _pick(_INDEX_KINDS, reader.byte()))
218
+
219
+
220
+ def _get_constraint(reader: _Reader) -> ConstraintSpec:
221
+ kind = _pick(_CONSTRAINT_KINDS, reader.byte())
222
+ return ConstraintSpec(kind, _pick(_TARGETS, reader.byte()), reader.text(), reader.text())
223
+
224
+
225
+ class BinaryFormat:
226
+ """Encode snapshots in a compact binary format, protected by a CRC-32.
227
+
228
+ >>> snapshot = Snapshot(nodes=(Node.make(1, "Person", {"age": -3}),), next_node=2)
229
+ >>> BinaryFormat().loads(BinaryFormat().dumps(snapshot)) == snapshot
230
+ True
231
+ """
232
+
233
+ def dumps(self, snapshot: Snapshot) -> bytes:
234
+ """Return the snapshot as bytes, ending with a checksum."""
235
+ out = bytearray(_MAGIC)
236
+ out.append(_VERSION)
237
+ for number in (snapshot.next_node, snapshot.next_edge, snapshot.last_tx):
238
+ _put_uvarint(out, number)
239
+ _put_each(out, snapshot.nodes, _put_node)
240
+ _put_each(out, snapshot.edges, _put_edge)
241
+ _put_each(out, snapshot.indexes, _put_index)
242
+ _put_each(out, snapshot.constraints, _put_constraint)
243
+ out += zlib.crc32(out).to_bytes(4, "big")
244
+ return bytes(out)
245
+
246
+ def loads(self, data: bytes) -> Snapshot:
247
+ """Return the snapshot in ``data``.
248
+
249
+ :raises FormatError: if the magic, version or checksum is wrong, the data is truncated
250
+ or has bytes left over, or it holds anything that a graph could not hold.
251
+ """
252
+ reader = _Reader(_verified(data))
253
+ reader.take(len(_MAGIC) + 1)
254
+ try:
255
+ next_node, next_edge, last_tx = reader.uvarint(), reader.uvarint(), reader.uvarint()
256
+ nodes = reader.each(_get_node)
257
+ edges = reader.each(_get_edge)
258
+ indexes = reader.each(_get_index)
259
+ constraints = reader.each(_get_constraint)
260
+ except (ValueError, ValidationError) as error:
261
+ raise FormatError(f"invalid binary snapshot: {error}") from error
262
+ if not reader.at_end():
263
+ raise FormatError("unexpected data after the snapshot")
264
+ return Snapshot(nodes, edges, next_node, next_edge, indexes, constraints, last_tx)
265
+
266
+
267
+ def _verified(data: bytes) -> bytes:
268
+ """Return the data without its checksum, after checking the magic, the version and the checksum."""
269
+ if len(data) < len(_MAGIC) + 5 or data[: len(_MAGIC)] != _MAGIC:
270
+ raise FormatError("not a minigraph binary snapshot")
271
+ if data[len(_MAGIC)] != _VERSION:
272
+ raise FormatError(f"unsupported binary version {data[len(_MAGIC)]}")
273
+ body, stored = data[:-4], int.from_bytes(data[-4:], "big")
274
+ if zlib.crc32(body) != stored:
275
+ raise FormatError("checksum mismatch: the data is damaged")
276
+ return body
277
+
278
+
279
+ def _put_change(out: bytearray, change: AnyChange) -> None:
280
+ """Append a change: a flags byte, then its before and its after, when they exist."""
281
+ flags = (1 if change.before is not None else 0) | (2 if change.after is not None else 0)
282
+ out.append(flags | (4 if isinstance(change.entity, Edge) else 0))
283
+ for entity in (change.before, change.after):
284
+ if isinstance(entity, Node):
285
+ _put_node(out, entity)
286
+ elif isinstance(entity, Edge):
287
+ _put_edge(out, entity)
288
+
289
+
290
+ def _get_change(reader: _Reader) -> AnyChange:
291
+ """Read a change written by :func:`_put_change`."""
292
+ flags = reader.byte()
293
+ if flags & 4:
294
+ before_edge = _get_edge(reader) if flags & 1 else None
295
+ after_edge = _get_edge(reader) if flags & 2 else None
296
+ return Change(before_edge, after_edge)
297
+ before_node = _get_node(reader) if flags & 1 else None
298
+ after_node = _get_node(reader) if flags & 2 else None
299
+ return Change(before_node, after_node)
300
+
301
+
302
+ def encode_commit(tx: int, changes: Sequence[AnyChange]) -> bytes:
303
+ """Encode a commit: its transaction number and its changes.
304
+
305
+ >>> from minigraph.model import Node
306
+ >>> record = encode_commit(7, [Change(None, Node.make(1, "Person"))])
307
+ >>> number, changes = decode_commit(record)
308
+ >>> number, changes[0].kind
309
+ (7, 'create')
310
+
311
+ :param tx: the transaction number.
312
+ :param changes: the changes of the commit, in order.
313
+ """
314
+ out = bytearray()
315
+ _put_uvarint(out, tx)
316
+ _put_each(out, changes, _put_change)
317
+ return bytes(out)
318
+
319
+
320
+ def decode_commit(data: bytes) -> tuple[int, list[AnyChange]]:
321
+ """Decode a commit written by :func:`encode_commit`.
322
+
323
+ :param data: the encoded commit.
324
+ :return: the transaction number and the changes.
325
+ :raises FormatError: if the data is not a valid commit.
326
+ """
327
+ reader = _Reader(data)
328
+ try:
329
+ tx = reader.uvarint()
330
+ changes = reader.each(_get_change)
331
+ except (ValueError, ValidationError) as error:
332
+ raise FormatError(f"invalid commit record: {error}") from error
333
+ if not reader.at_end():
334
+ raise FormatError("unexpected data after the commit")
335
+ return tx, list(changes)
336
+
337
+
338
+ def encode_ints(numbers: Sequence[int]) -> bytes:
339
+ """Encode non-negative integers one after the other.
340
+
341
+ >>> decode_ints(encode_ints([1, 300, 70000]), 3)
342
+ [1, 300, 70000]
343
+ """
344
+ out = bytearray()
345
+ for number in numbers:
346
+ _put_uvarint(out, number)
347
+ return bytes(out)
348
+
349
+
350
+ def decode_ints(data: bytes, count: int) -> list[int]:
351
+ """Decode the first ``count`` integers of ``data``, ignoring whatever follows.
352
+
353
+ :raises FormatError: if ``data`` ends before ``count`` integers.
354
+ """
355
+ reader = _Reader(data)
356
+ return [reader.uvarint() for _ in range(count)]
357
+
358
+
359
+ def encode_node(node: Node) -> bytes:
360
+ """Encode a node: its id first, then its labels and properties."""
361
+ out = bytearray()
362
+ _put_node(out, node)
363
+ return bytes(out)
364
+
365
+
366
+ def decode_node(data: bytes) -> Node:
367
+ """Decode a node written by :func:`encode_node`.
368
+
369
+ :raises FormatError: if the data is not a valid node.
370
+ """
371
+ reader = _Reader(data)
372
+ try:
373
+ return _get_node(reader)
374
+ except (ValueError, ValidationError) as error:
375
+ raise FormatError(f"invalid node record: {error}") from error
376
+
377
+
378
+ def encode_edge(edge: Edge) -> bytes:
379
+ """Encode an edge: its id and its two endpoints first, then its types and properties."""
380
+ out = bytearray()
381
+ _put_edge(out, edge)
382
+ return bytes(out)
383
+
384
+
385
+ def decode_edge(data: bytes) -> Edge:
386
+ """Decode an edge written by :func:`encode_edge`.
387
+
388
+ :raises FormatError: if the data is not a valid edge.
389
+ """
390
+ reader = _Reader(data)
391
+ try:
392
+ return _get_edge(reader)
393
+ except (ValueError, ValidationError) as error:
394
+ raise FormatError(f"invalid edge record: {error}") from error
minigraph/changes.py ADDED
@@ -0,0 +1,64 @@
1
+ """Describe writes as data: the change of one node or edge from a before to an after."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Literal
5
+
6
+ from minigraph.errors import ValidationError
7
+ from minigraph.model import Edge
8
+ from minigraph.model import Node
9
+
10
+ type ChangeKind = Literal["create", "update", "delete"]
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class Change[E: (Node, Edge)]:
15
+ """Describe how one node or edge goes from one state to another.
16
+
17
+ >>> change = Change(None, Node.make(1, "Person"))
18
+ >>> change.kind, change.id, change.inverse().kind
19
+ ('create', 1, 'delete')
20
+
21
+ :param before: the entity as it must be before the change; ``None`` for a creation.
22
+ :param after: the entity as it is after the change; ``None`` for a deletion.
23
+ :raises ValidationError: if both are ``None``, or they have different ids.
24
+ """
25
+
26
+ before: E | None
27
+ after: E | None
28
+
29
+ def __post_init__(self) -> None:
30
+ if self.before is None and self.after is None:
31
+ raise ValidationError("a change needs a before or an after")
32
+ if self.before is not None and self.after is not None and self.before.id != self.after.id:
33
+ raise ValidationError("a change cannot turn one entity into another")
34
+
35
+ @property
36
+ def entity(self) -> E:
37
+ """Return the entity the change is about: its new state, or the old one for a deletion."""
38
+ current = self.after if self.after is not None else self.before
39
+ assert current is not None
40
+ return current
41
+
42
+ @property
43
+ def id(self) -> int:
44
+ """Return the id of the node or edge."""
45
+ return self.entity.id
46
+
47
+ @property
48
+ def kind(self) -> ChangeKind:
49
+ """Return whether the change creates, updates or deletes."""
50
+ if self.before is None:
51
+ return "create"
52
+ return "delete" if self.after is None else "update"
53
+
54
+ def inverse(self) -> Change[E]:
55
+ """Return the change that undoes this one."""
56
+ return Change(self.after, self.before)
57
+
58
+ def describe(self) -> str:
59
+ """Return a short description, for error messages."""
60
+ what = "node" if isinstance(self.entity, Node) else "edge"
61
+ return f"{self.kind} of {what} {self.id}"
62
+
63
+
64
+ type AnyChange = Change[Node] | Change[Edge]