openswx-collab-protocol 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.
@@ -0,0 +1,6 @@
1
+ """Wire protocol shared by the openswx collaboration server and the openswx client."""
2
+ from .messages import PROTOCOL_VERSION
3
+ from .ops import OpError, apply, diff, fingerprint, targets
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["PROTOCOL_VERSION", "OpError", "apply", "diff", "fingerprint", "targets", "__version__"]
@@ -0,0 +1,248 @@
1
+ """Messages on the document WebSocket (JSON text frames, one message per frame, `type` says which).
2
+
3
+ The first frame from the client must be `hello`; the server answers `welcome` or `error` and closes.
4
+ See docs/protocol.md for the flow.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from typing import Annotated, Any, Literal, Union
9
+
10
+ from pydantic import BaseModel, ConfigDict, Field, TypeAdapter
11
+
12
+ PROTOCOL_VERSION = 1
13
+
14
+
15
+ class _M(BaseModel):
16
+ model_config = ConfigDict(extra="ignore")
17
+
18
+
19
+ # ------------------------------------------------------------------ client -> server
20
+ class Hello(_M):
21
+ type: Literal["hello"] = "hello"
22
+ protocol: int = PROTOCOL_VERSION
23
+ token: str
24
+ client_id: str = Field(min_length=8, max_length=64) # one per running app; kept across reconnects
25
+ format_version: int | None = None # openswx file-format version of this client
26
+ last_seq: int | None = None # the last change this client has applied (reconnect); None: send the document
27
+ app: str | None = None
28
+
29
+
30
+ class Change(_M):
31
+ type: Literal["change"] = "change"
32
+ change_id: str = Field(min_length=1, max_length=64) # client-chosen; resending the same id is harmless
33
+ base_seq: int # the change was made on top of this sequence number
34
+ ops: list[dict[str, Any]]
35
+ command: str = "" # what the user did, for the history ("extrude", "edit_feature")
36
+ args: dict[str, Any] | None = None
37
+
38
+
39
+ class LockAcquire(_M):
40
+ type: Literal["lock.acquire"] = "lock.acquire"
41
+ request_id: str = ""
42
+ targets: list[str] # "f:<feature id>", "k:<top-level key>" or "structure"
43
+
44
+
45
+ class LockRelease(_M):
46
+ type: Literal["lock.release"] = "lock.release"
47
+ targets: list[str]
48
+
49
+
50
+ class Reserve(_M):
51
+ type: Literal["ids.reserve"] = "ids.reserve"
52
+ request_id: str = ""
53
+ features: int = Field(default=0, ge=0, le=64) # how many feature ids
54
+ names: list[str] = Field(default_factory=list, max_length=64) # name prefixes: "Sketch", "Boss-Extrude"
55
+
56
+
57
+ class Revert(_M):
58
+ type: Literal["change.revert"] = "change.revert"
59
+ request_id: str = ""
60
+ seq: int
61
+ mode: Literal["undo", "revert"] = "undo" # undo: only your own change; revert: anyone's (editors)
62
+
63
+
64
+ class Presence(_M):
65
+ type: Literal["presence"] = "presence"
66
+ data: dict[str, Any] # pointer, selection, tool, camera: relayed as is, never stored
67
+
68
+
69
+ class Draft(_M):
70
+ type: Literal["draft"] = "draft"
71
+ data: dict[str, Any] | None = None # unfinished work to preview on other screens; None clears it
72
+
73
+
74
+ class RebuildReport(_M):
75
+ type: Literal["rebuild.report"] = "rebuild.report"
76
+ seq: int # the document state the report is about
77
+ errors: dict[str, str] # feature id -> rebuild error
78
+
79
+
80
+ class Ping(_M):
81
+ type: Literal["ping"] = "ping"
82
+
83
+
84
+ ClientMessage = Annotated[
85
+ Union[Hello, Change, LockAcquire, LockRelease, Reserve, Revert, Presence, Draft, RebuildReport, Ping],
86
+ Field(discriminator="type"),
87
+ ]
88
+ client_message = TypeAdapter(ClientMessage)
89
+
90
+
91
+ # ------------------------------------------------------------------ server -> client
92
+ class Peer(_M):
93
+ client_id: str
94
+ user_id: str
95
+ name: str
96
+ colour: str
97
+ read_only: bool = False
98
+ presence: dict[str, Any] | None = None
99
+ draft: dict[str, Any] | None = None
100
+
101
+
102
+ class LockHolder(_M):
103
+ client_id: str
104
+ user_id: str
105
+ name: str
106
+ detached: bool = False # the holder is disconnected and the lock is in its grace period
107
+
108
+
109
+ class ChangeEvent(_M):
110
+ type: Literal["change"] = "change"
111
+ seq: int
112
+ author: str # user id
113
+ author_name: str = ""
114
+ client_id: str | None = None
115
+ change_id: str | None = None # lets a reconnecting client recognise its own changes in the catch-up
116
+ time: float = 0.0
117
+ ops: list[dict[str, Any]]
118
+ command: str = ""
119
+ reverts: int | None = None
120
+
121
+
122
+ class Welcome(_M):
123
+ type: Literal["welcome"] = "welcome"
124
+ protocol: int = PROTOCOL_VERSION
125
+ document_id: str
126
+ seq: int
127
+ format_version: int | None = None
128
+ you: Peer
129
+ role: str
130
+ read_only_reason: str | None = None
131
+ peers: list[Peer] = Field(default_factory=list)
132
+ locks: dict[str, LockHolder] = Field(default_factory=dict)
133
+ broken: dict[str, dict[str, Any]] = Field(default_factory=dict)
134
+ project_id: str | None = None # (blobs in the content are fetched through the project)
135
+ reserved: dict[str, list[str]] = Field(default_factory=dict) # {ids, names} this client still holds
136
+ content: dict[str, Any] | None = None # the whole document at `seq` ...
137
+ changes: list[ChangeEvent] | None = None # ... or the changes since the client's last_seq
138
+
139
+
140
+ class ChangeAccepted(_M):
141
+ type: Literal["change.accepted"] = "change.accepted"
142
+ change_id: str
143
+ seq: int
144
+
145
+
146
+ class ChangeRejected(_M):
147
+ type: Literal["change.rejected"] = "change.rejected"
148
+ change_id: str
149
+ # stale: someone changed the same thing since base_seq. locked: someone else holds a lock.
150
+ # invalid: cannot be applied. read_only. id_taken. missing_blob. too_large.
151
+ code: str
152
+ message: str = ""
153
+ conflicts: dict[str, Any] = Field(default_factory=dict) # target -> who / which change
154
+
155
+
156
+ class LockResult(_M):
157
+ type: Literal["lock.result"] = "lock.result"
158
+ request_id: str = ""
159
+ granted: list[str] = Field(default_factory=list)
160
+ denied: dict[str, LockHolder] = Field(default_factory=dict)
161
+
162
+
163
+ class LockChanged(_M):
164
+ type: Literal["lock.changed"] = "lock.changed"
165
+ acquired: dict[str, LockHolder] = Field(default_factory=dict)
166
+ released: list[str] = Field(default_factory=list)
167
+
168
+
169
+ class Reserved(_M):
170
+ type: Literal["ids.reserved"] = "ids.reserved"
171
+ request_id: str = ""
172
+ ids: list[str] = Field(default_factory=list)
173
+ names: list[str] = Field(default_factory=list)
174
+
175
+
176
+ class RevertResult(_M):
177
+ type: Literal["change.revert.result"] = "change.revert.result"
178
+ request_id: str = ""
179
+ ok: bool
180
+ seq: int | None = None # the new change that undid it
181
+ ops: list[dict[str, Any]] | None = None # what to apply locally (the sender gets no `change` event for it)
182
+ code: str | None = None
183
+ message: str = ""
184
+ conflicts: dict[str, Any] = Field(default_factory=dict)
185
+
186
+
187
+ class PeerJoined(_M):
188
+ type: Literal["peer.joined"] = "peer.joined"
189
+ peer: Peer
190
+
191
+
192
+ class PeerLeft(_M):
193
+ type: Literal["peer.left"] = "peer.left"
194
+ client_id: str
195
+
196
+
197
+ class PresenceEvent(_M):
198
+ type: Literal["presence"] = "presence"
199
+ client_id: str
200
+ data: dict[str, Any]
201
+
202
+
203
+ class DraftEvent(_M):
204
+ type: Literal["draft"] = "draft"
205
+ client_id: str
206
+ data: dict[str, Any] | None = None
207
+
208
+
209
+ class RebuildStatus(_M):
210
+ type: Literal["rebuild.status"] = "rebuild.status"
211
+ seq: int
212
+ broken: dict[str, dict[str, Any]] # feature id -> {error, by_seq, by_user, by_name, command}
213
+
214
+
215
+ class VersionEvent(_M):
216
+ type: Literal["version.created"] = "version.created"
217
+ id: str
218
+ seq: int
219
+ name: str
220
+ author: str
221
+
222
+
223
+ class ReferenceEvent(_M):
224
+ """Sent to everyone in an assembly when a part it uses gets a new named version. Nothing about the part
225
+ beyond its id: ask GET /documents/{assembly}/references, which tells each person what they may know."""
226
+ type: Literal["reference.update"] = "reference.update"
227
+ document: str # the part
228
+ components: list[str] # ids of the components that are pinned to something older
229
+
230
+
231
+ class Pong(_M):
232
+ type: Literal["pong"] = "pong"
233
+ seq: int = 0
234
+
235
+
236
+ class Error(_M):
237
+ type: Literal["error"] = "error"
238
+ code: str
239
+ message: str = ""
240
+ request_id: str | None = None # set when it answers a request that carried one (ids.reserve)
241
+
242
+
243
+ ServerMessage = Annotated[
244
+ Union[Welcome, ChangeEvent, ChangeAccepted, ChangeRejected, LockResult, LockChanged, Reserved, RevertResult,
245
+ PeerJoined, PeerLeft, PresenceEvent, DraftEvent, RebuildStatus, VersionEvent, ReferenceEvent, Pong, Error],
246
+ Field(discriminator="type"),
247
+ ]
248
+ server_message = TypeAdapter(ServerMessage)
@@ -0,0 +1,439 @@
1
+ """Document operations: how a change to an openswx document is described, compared and applied.
2
+
3
+ A document is the JSON dict openswx saves (`PartDocument.to_dict()`): top-level keys plus an ordered
4
+ `features` list of `{"id", "name", "type", "params", "suppressed"}`. A change is a list of operations
5
+ that address features by id, never by position, so two changes to different features commute.
6
+
7
+ {"op": "feature.add", "feature": {...}, "after": "<id>" | None}
8
+ {"op": "feature.remove", "id": "<id>"}
9
+ {"op": "feature.update", "id": "<id>", "set": [[path, value], ...], "unset": [path, ...]}
10
+ {"op": "feature.order", "ids": ["<id>", ...]} # the complete new order
11
+ {"op": "doc.patch", "set": [[path, value], ...], "unset": [path, ...]}
12
+
13
+ A path is a list of dict keys. Dicts are compared key by key; lists and scalars are replaced whole.
14
+
15
+ Assemblies have two more id-keyed lists, `components` and `mates`. They work exactly like features, with
16
+ the list named in the operation:
17
+
18
+ {"op": "item.add", "in": "components", "item": {"id": ...}, "after": "<id>" | None}
19
+ {"op": "item.remove", "in": "mates", "id": "<id>"}
20
+ {"op": "item.update", "in": "components", "id": "<id>", "set": [...], "unset": [...]}
21
+ {"op": "item.order", "in": "components", "ids": [...]}
22
+
23
+ Used by both the server (which has no geometry kernel) and the openswx client.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import hashlib
28
+ import json
29
+ import math
30
+ from typing import Any, Callable
31
+
32
+ # Per-user view state: stays on each machine, never sent.
33
+ LOCAL_ONLY = frozenset({"rollback", "active_config", "display_state", "journal", "name"})
34
+ # Owned by the server (it hands out feature ids and names): clients never send changes to these.
35
+ SERVER_OWNED = frozenset({"next_id", "counters"})
36
+ UNSYNCED = LOCAL_ONLY | SERVER_OWNED
37
+
38
+ STRUCTURE = "structure" # lock target for changes to the shape of the feature tree
39
+ ORDER = "order" # change target of feature.order
40
+ ITEM_LISTS = ("components", "mates") # id-keyed lists besides features (assemblies)
41
+ LISTS = ("features",) + ITEM_LISTS
42
+
43
+
44
+ def target_of(coll: str, item_id: Any) -> str:
45
+ """'f:<id>' for a feature, 'i:<list>:<id>' for a component or mate."""
46
+ return f"f:{item_id}" if coll == "features" else f"i:{coll}:{item_id}"
47
+
48
+
49
+ def order_target(coll: str) -> str:
50
+ return ORDER if coll == "features" else f"{ORDER}:{coll}"
51
+
52
+
53
+ class OpError(ValueError):
54
+ """An operation that cannot be applied to the document it was sent for."""
55
+
56
+
57
+ MAX_DEPTH = 64 # how deeply nested a document may be (real openswx documents stay far below)
58
+ MAX_NAME = 200 # longest feature id, name or type
59
+
60
+
61
+ def same(a: Any, b: Any) -> bool:
62
+ """Equal as JSON. Python calls 1, 1.0 and True equal; a document that changes one into another has
63
+ changed (its fingerprint has), so the change must travel."""
64
+ if a is b: # (the server shares untouched features between versions: most comparisons end here)
65
+ return True
66
+ if a != b:
67
+ return False
68
+ if isinstance(a, (dict, list)):
69
+ return json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True)
70
+ if isinstance(a, float) and isinstance(b, float):
71
+ return math.copysign(1.0, a) == math.copysign(1.0, b) # (0.0 and -0.0 are written differently)
72
+ return type(a) is type(b)
73
+
74
+
75
+ def check_value(v: Any, room: int = MAX_DEPTH) -> None:
76
+ """Refuse what cannot live in a document: nesting deeper than `room` levels, and numbers that are not
77
+ JSON (NaN, Infinity: every reader of the document would choke on them)."""
78
+ if room < 0:
79
+ raise OpError("the value is nested too deeply")
80
+ if isinstance(v, float):
81
+ if not math.isfinite(v):
82
+ raise OpError("NaN and Infinity cannot be stored in a document")
83
+ elif isinstance(v, dict):
84
+ for k, x in v.items():
85
+ if not isinstance(k, str):
86
+ raise OpError("object keys must be text")
87
+ check_value(x, room - 1)
88
+ elif isinstance(v, list):
89
+ for x in v:
90
+ check_value(x, room - 1)
91
+
92
+
93
+ # ------------------------------------------------------------------ dict diff / patch
94
+ def dict_diff(a: dict, b: dict) -> tuple[list, list]:
95
+ """What turns dict `a` into dict `b`: ([[path, value], ...], [path, ...])."""
96
+ sets: list = []
97
+ unsets: list = []
98
+
99
+ def walk(x: dict, y: dict, path: list) -> None:
100
+ for k in x:
101
+ if k not in y:
102
+ unsets.append(path + [k])
103
+ for k, v in y.items():
104
+ if k not in x:
105
+ sets.append([path + [k], v])
106
+ elif not same(x[k], v):
107
+ if isinstance(x[k], dict) and isinstance(v, dict):
108
+ walk(x[k], v, path + [k])
109
+ else:
110
+ sets.append([path + [k], v])
111
+
112
+ walk(a, b, [])
113
+ return sets, unsets
114
+
115
+
116
+ def _parent(d: dict, path: list) -> dict:
117
+ if not isinstance(path, list) or not path or len(path) > MAX_DEPTH or not all(isinstance(k, str) for k in path):
118
+ raise OpError("bad path")
119
+ cur: Any = d
120
+ for k in path[:-1]:
121
+ cur = cur.get(k) if isinstance(cur, dict) else None
122
+ if not isinstance(cur, dict):
123
+ raise OpError(f"nothing to change at {'/'.join(path)}")
124
+ return cur
125
+
126
+
127
+ def dict_patch(d: dict, sets: list, unsets: list) -> None:
128
+ """Apply a dict_diff result to `d`, in place."""
129
+ for path in unsets or []:
130
+ _parent(d, path).pop(path[-1], None)
131
+ for item in sets or []:
132
+ if not isinstance(item, (list, tuple)) or len(item) != 2:
133
+ raise OpError("bad set entry")
134
+ path, value = item
135
+ parent = _parent(d, path)
136
+ check_value(value, MAX_DEPTH - len(path))
137
+ parent[path[-1]] = _copy(value)
138
+
139
+
140
+ def _copy(v: Any) -> Any:
141
+ return json.loads(json.dumps(v)) if isinstance(v, (dict, list)) else v
142
+
143
+
144
+ # ------------------------------------------------------------------ diff
145
+ def _shared_top(doc: dict) -> dict:
146
+ return {k: v for k, v in doc.items() if k not in LISTS and k not in UNSYNCED}
147
+
148
+
149
+ def _items(doc: dict, coll: str) -> list[dict]:
150
+ items = doc.get(coll)
151
+ if items is None:
152
+ return []
153
+ if not isinstance(items, list) or not all(isinstance(x, dict) and isinstance(x.get("id"), str) for x in items):
154
+ raise OpError(f"{coll} must be a list of objects that each have an id")
155
+ return items
156
+
157
+
158
+ def _op(coll: str, action: str, **kw) -> dict:
159
+ if coll == "features":
160
+ if "item" in kw:
161
+ kw["feature"] = kw.pop("item")
162
+ return {"op": f"feature.{action}", **kw}
163
+ return {"op": f"item.{action}", "in": coll, **kw}
164
+
165
+
166
+ def diff(before: dict, after: dict) -> list[dict]:
167
+ """The operations that turn document `before` into `after` (local-only and server-owned keys ignored)."""
168
+ ops: list[dict] = []
169
+ for coll in LISTS:
170
+ b_list, a_list = _items(before, coll), _items(after, coll)
171
+ b = {f["id"]: f for f in b_list}
172
+ a = {f["id"]: f for f in a_list}
173
+ a_ids = [f["id"] for f in a_list]
174
+ for fid in b:
175
+ if fid not in a:
176
+ ops.append(_op(coll, "remove", id=fid))
177
+ for n, fid in enumerate(a_ids):
178
+ if fid not in b:
179
+ ops.append(_op(coll, "add", item=_copy(a[fid]), after=a_ids[n - 1] if n else None))
180
+ elif not same(a[fid], b[fid]):
181
+ sets, unsets = dict_diff(b[fid], a[fid])
182
+ ops.append(_op(coll, "update", id=fid, set=_copy(sets), unset=unsets))
183
+ # removes and adds alone reproduce the order unless items that stayed changed places
184
+ if [f["id"] for f in b_list if f["id"] in a] != [i for i in a_ids if i in b]:
185
+ ops.append(_op(coll, "order", ids=a_ids))
186
+ sets, unsets = dict_diff(_shared_top(before), _shared_top(after))
187
+ if sets or unsets:
188
+ ops.append({"op": "doc.patch", "set": _copy(sets), "unset": unsets})
189
+ return ops
190
+
191
+
192
+ # ------------------------------------------------------------------ apply
193
+ def _check_doc_path(path: Any) -> None:
194
+ if not isinstance(path, list) or not path or path[0] in LISTS or path[0] in UNSYNCED:
195
+ raise OpError(f"doc.patch may not change {path[0] if isinstance(path, list) and path else path!r}")
196
+
197
+
198
+ _ACTION_KEYS = {"add": ("after",), "remove": ("id",), "update": ("id", "set", "unset"), "order": ("ids",)}
199
+
200
+
201
+ def parse(op: Any) -> tuple[str, str]:
202
+ """(action, list) of an operation: ('update', 'features'), ('add', 'components'), ('patch', '')."""
203
+ if not isinstance(op, dict) or not isinstance(op.get("op"), str):
204
+ raise OpError("an operation must be an object with an op")
205
+ kind = op["op"]
206
+ if kind == "doc.patch":
207
+ return "patch", ""
208
+ family, _, action = kind.partition(".")
209
+ if action in _ACTION_KEYS:
210
+ if family == "feature":
211
+ return action, "features"
212
+ if family == "item" and op.get("in") in ITEM_LISTS:
213
+ return action, op["in"]
214
+ raise OpError(f"unknown operation {kind!r}")
215
+
216
+
217
+ def _payload(op: dict, coll: str) -> Any:
218
+ return op.get("feature") if coll == "features" else op.get("item")
219
+
220
+
221
+ def clean(ops: Any) -> list[dict]:
222
+ """The operations with nothing in them but what an operation is made of: anything else a sender put
223
+ there (and everything that is not valid JSON data, like NaN) is refused or dropped before the change is
224
+ stored and sent on to others."""
225
+ if not isinstance(ops, list):
226
+ raise OpError("a change is a list of operations")
227
+ out = []
228
+ for op in ops:
229
+ action, coll = parse(op)
230
+ if action == "patch":
231
+ keys: tuple = ("set", "unset")
232
+ else:
233
+ keys = _ACTION_KEYS[action] + ((("feature",) if coll == "features" else ("item",)) if action == "add" else ())
234
+ kept = {"op": op["op"], **({"in": coll} if coll in ITEM_LISTS else {}), **{k: op[k] for k in keys if k in op}}
235
+ check_value(kept, MAX_DEPTH + 4)
236
+ if "after" in kept and kept["after"] is not None and not isinstance(kept["after"], str):
237
+ raise OpError("after must be an id")
238
+ if "id" in kept and not isinstance(kept["id"], str):
239
+ raise OpError("id must be text")
240
+ out.append(kept)
241
+ return out
242
+
243
+
244
+ def check_feature(f: Any) -> None:
245
+ """A feature must keep a usable id, name and type whatever an operation did to it."""
246
+ if not isinstance(f, dict):
247
+ raise OpError("a feature must be an object")
248
+ for k in ("id", "name", "type"):
249
+ v = f.get(k)
250
+ if not isinstance(v, str) or not v or len(v) > MAX_NAME:
251
+ raise OpError(f"a feature needs a {k} (text, at most {MAX_NAME} characters)")
252
+ check_value(f, MAX_DEPTH - 2)
253
+
254
+
255
+ def check_item(coll: str, x: Any) -> None:
256
+ if coll == "features":
257
+ return check_feature(x)
258
+ if not isinstance(x, dict) or not isinstance(x.get("id"), str) or not 0 < len(x["id"]) <= MAX_NAME:
259
+ raise OpError(f"every entry of {coll} needs an id (text, at most {MAX_NAME} characters)")
260
+ check_value(x, MAX_DEPTH - 2)
261
+
262
+
263
+ def apply(doc: dict, ops: list[dict]) -> dict:
264
+ """Apply operations to `doc` in place and return it. Raises OpError and may leave `doc` half-changed:
265
+ apply to a copy when the result must be all-or-nothing.
266
+
267
+ Feature names must be unique when the whole change has been applied, not after each operation: a
268
+ change may swap two names, or delete a feature and give its name to another."""
269
+ renamed = False
270
+ for op in ops:
271
+ action, coll = parse(op)
272
+ if action == "patch":
273
+ for path in list(op.get("unset") or []):
274
+ _check_doc_path(path)
275
+ for s in op.get("set") or []:
276
+ _check_doc_path(s[0] if isinstance(s, list) and s else None)
277
+ dict_patch(doc, op.get("set") or [], op.get("unset") or [])
278
+ continue
279
+ items = doc.setdefault(coll, [])
280
+ if not isinstance(items, list):
281
+ raise OpError(f"{coll} is not a list")
282
+ renamed = renamed or (coll == "features" and action in ("add", "update"))
283
+ if action == "add":
284
+ x = _payload(op, coll)
285
+ check_item(coll, x)
286
+ if any(i["id"] == x["id"] for i in items):
287
+ raise OpError(f"an entry with id {x['id']} already exists in {coll}")
288
+ after = op.get("after")
289
+ if after is None:
290
+ at = 0
291
+ else:
292
+ at = next((n for n, i in enumerate(items) if i["id"] == after), -1) + 1
293
+ if at == 0:
294
+ raise OpError(f"{after} (to insert after) no longer exists in {coll}")
295
+ items.insert(at, _copy(x))
296
+ elif action == "remove":
297
+ del items[_index(items, op.get("id"), coll)]
298
+ elif action == "update":
299
+ n = _index(items, op.get("id"), coll)
300
+ dict_patch(items[n], op.get("set") or [], op.get("unset") or [])
301
+ check_item(coll, items[n]) # (checked as it ends up: whatever the patch did to it)
302
+ if items[n]["id"] != op.get("id"):
303
+ raise OpError("an id cannot change")
304
+ else: # order
305
+ ids = op.get("ids")
306
+ cur = [i["id"] for i in items]
307
+ if not isinstance(ids, list) or len(ids) != len(cur) or not all(isinstance(i, str) for i in ids) \
308
+ or set(ids) != set(cur):
309
+ raise OpError(f"an order must list every entry of {coll} exactly once")
310
+ rank = {i: n for n, i in enumerate(ids)}
311
+ items.sort(key=lambda i: rank[i["id"]])
312
+ if renamed:
313
+ seen: set[str] = set()
314
+ for x in doc.get("features") or []:
315
+ if x["name"] in seen:
316
+ raise OpError(f"a feature named {x['name']} already exists")
317
+ seen.add(x["name"])
318
+ return doc
319
+
320
+
321
+ def _index(items: list[dict], item_id: Any, coll: str = "features") -> int:
322
+ for n, x in enumerate(items):
323
+ if x["id"] == item_id:
324
+ return n
325
+ raise OpError(f"{'feature' if coll == 'features' else coll[:-1]} {item_id} no longer exists")
326
+
327
+
328
+ # ------------------------------------------------------------------ what a change touches
329
+ def targets(ops: list[dict]) -> set[str]:
330
+ """What a change touches, as strings two changes can be compared by: 'f:<feature id>',
331
+ 'i:<list>:<id>', 'k:<top-level key>', 'order', 'order:<list>'. Two changes with no target in common
332
+ do not conflict."""
333
+ out: set[str] = set()
334
+ for op in ops:
335
+ action, coll = parse(op)
336
+ if action == "patch":
337
+ for path in list(op.get("unset") or []) + [s[0] for s in op.get("set") or []]:
338
+ out.add(f"k:{path[0]}")
339
+ elif action == "add":
340
+ out.add(target_of(coll, _payload(op, coll)["id"]))
341
+ elif action == "order":
342
+ out.add(order_target(coll))
343
+ else:
344
+ out.add(target_of(coll, op.get("id")))
345
+ return out
346
+
347
+
348
+ def added_targets(ops: list[dict]) -> set[str]:
349
+ """The targets of everything a change adds."""
350
+ return {target_of(coll, _payload(op, coll)["id"]) for op in ops for action, coll in [parse(op)] if action == "add"}
351
+
352
+
353
+ def added_ids(ops: list[dict]) -> set[str]:
354
+ """Ids of the features a change adds."""
355
+ return {op["feature"]["id"] for op in ops if op.get("op") == "feature.add"}
356
+
357
+
358
+ def is_structural(ops: list[dict]) -> bool:
359
+ """Does the change alter the shape of a tree (so the structure lock applies)?"""
360
+ return any(parse(op)[0] in ("remove", "order") for op in ops)
361
+
362
+
363
+ def fingerprint(doc: dict) -> str:
364
+ """A hash of the shared part of a document: equal on every client that is in sync."""
365
+ shared = {k: v for k, v in doc.items() if k not in UNSYNCED}
366
+ return hashlib.sha256(json.dumps(shared, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
367
+
368
+
369
+ # ------------------------------------------------------------------ ids and names
370
+ def split_number(text: str) -> tuple[str, int] | None:
371
+ """'Boss-Extrude12' -> ('Boss-Extrude', 12); None when there is no trailing number (of at most 9 digits)."""
372
+ stem = text.rstrip("0123456789")
373
+ digits = text[len(stem):]
374
+ return (stem, int(digits)) if 0 < len(digits) <= 9 else None
375
+
376
+
377
+ def absorb_ids(state: dict, feats: list[dict] | None = None) -> None:
378
+ """Move `next_id` and `counters` past every feature id and name in use (all features, or just `feats`).
379
+ The server does this for every accepted change; a client does it after applying changes from others, so
380
+ that what it creates next does not reuse an id it has just been sent."""
381
+ try:
382
+ nid = int(state.get("next_id") or 1)
383
+ except (TypeError, ValueError):
384
+ nid = 1
385
+ counters = state.get("counters")
386
+ if not isinstance(counters, dict):
387
+ counters = state["counters"] = {}
388
+ for f in (state.get("features") or []) if feats is None else feats:
389
+ got = split_number(str(f.get("id", "")))
390
+ if got and got[0] == "f":
391
+ nid = max(nid, got[1] + 1)
392
+ got = split_number(str(f.get("name", "")))
393
+ if got and got[0]:
394
+ have = counters.get(got[0], 0)
395
+ counters[got[0]] = max(have if isinstance(have, int) else 0, got[1])
396
+ state["next_id"] = nid
397
+
398
+
399
+ # ------------------------------------------------------------------ large strings (imported bodies)
400
+ BLOB_MIN = 16384 # strings at least this long travel as separately uploaded blobs
401
+
402
+
403
+ def externalize(obj: Any, sink: dict[str, bytes], min_len: int = BLOB_MIN) -> Any:
404
+ """A copy of `obj` with every long string replaced by {"$blob": sha256, "len": n}; the bytes go to `sink`."""
405
+ if isinstance(obj, str) and len(obj) >= min_len:
406
+ data = obj.encode("utf-8")
407
+ sha = hashlib.sha256(data).hexdigest()
408
+ sink[sha] = data
409
+ return {"$blob": sha, "len": len(obj)}
410
+ if isinstance(obj, dict):
411
+ return {k: externalize(v, sink, min_len) for k, v in obj.items()}
412
+ if isinstance(obj, list):
413
+ return [externalize(v, sink, min_len) for v in obj]
414
+ return obj
415
+
416
+
417
+ def blob_refs(obj: Any) -> set[str]:
418
+ out: set[str] = set()
419
+ if isinstance(obj, dict):
420
+ if isinstance(obj.get("$blob"), str) and set(obj) <= {"$blob", "len"}:
421
+ out.add(obj["$blob"])
422
+ else:
423
+ for v in obj.values():
424
+ out |= blob_refs(v)
425
+ elif isinstance(obj, list):
426
+ for v in obj:
427
+ out |= blob_refs(v)
428
+ return out
429
+
430
+
431
+ def internalize(obj: Any, fetch: Callable[[str], bytes]) -> Any:
432
+ """The reverse of externalize: `fetch(sha256)` returns the bytes of a blob."""
433
+ if isinstance(obj, dict):
434
+ if isinstance(obj.get("$blob"), str) and set(obj) <= {"$blob", "len"}:
435
+ return fetch(obj["$blob"]).decode("utf-8")
436
+ return {k: internalize(v, fetch) for k, v in obj.items()}
437
+ if isinstance(obj, list):
438
+ return [internalize(v, fetch) for v in obj]
439
+ return obj
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.4
2
+ Name: openswx-collab-protocol
3
+ Version: 0.1.0
4
+ Summary: Wire protocol and document operations shared by the openswx collaboration server and client
5
+ Author: the openswx authors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/DukeOfCheese/openswx-collab
8
+ Project-URL: Documentation, https://github.com/DukeOfCheese/openswx-collab/tree/main/docs
9
+ Project-URL: Issues, https://github.com/DukeOfCheese/openswx-collab/issues
10
+ Keywords: cad,collaboration,real-time,openswx
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering
14
+ Requires-Python: >=3.11
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: pydantic>=2.6
18
+ Dynamic: license-file
19
+
20
+ # openswx-collab-protocol
21
+
22
+ The wire protocol shared by the [openswx](https://github.com/DukeOfCheese/openswx) collaboration server and
23
+ client: id-keyed operations on a CAD document (`diff`, `apply`, `targets`) and the WebSocket messages.
24
+ Depends on pydantic only.
25
+
26
+ Documentation, self-hosting guide and the protocol reference: https://github.com/DukeOfCheese/openswx-collab
27
+
28
+ Apache-2.0. openswx-collab is an independent open-source project, not affiliated with Dassault Systemes.
@@ -0,0 +1,8 @@
1
+ openswx_collab_protocol/__init__.py,sha256=G8bsrO5tkDWfpWzrhs5DmKSzNTtdeHx1kEvdH6HCmsg,309
2
+ openswx_collab_protocol/messages.py,sha256=mWsGeq_EsQqA2Y3hTZPpKGLE4W5XvJthPVS0nQqm4H8,7863
3
+ openswx_collab_protocol/ops.py,sha256=LQOStTOT-tGeza0Wi1A2M5rpcpHurTVjoztMqhLPS9o,18786
4
+ openswx_collab_protocol-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
5
+ openswx_collab_protocol-0.1.0.dist-info/METADATA,sha256=NMcg6_w9Pd8HvxANMKAMGenK9tckUTv5wHCry5UXSB4,1262
6
+ openswx_collab_protocol-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ openswx_collab_protocol-0.1.0.dist-info/top_level.txt,sha256=DWrdl6SyC9SFcNS1iHt8FsIDhF4TxtfE6zxhhTBHYd4,24
8
+ openswx_collab_protocol-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ openswx_collab_protocol