Compare commits

..
Author SHA1 Message Date
Dennis Kobert 24cbc5671e The metadata file is an append-only log of stamped facts folded on read, so a name, a label or a tag appends one line; the History panel names and tags interactions, with given labels shown in bold and tag chips 2026-09-29 19:58:55 +00:00
Dennis Kobert 9c1019796c Every mounted document retires on the frame tick, in a session or not, so solo steps enter history as they close; the History panel shows each closed transaction waiting for the retirer as a pending row of its own 2026-09-29 19:43:17 +00:00
Dennis Kobert 2dd91c0fcf History panel actions: go back to here, remove this step, bring back and following a branch from its stub; a shared head move to an ancestor as a HeadMove without copies, requested from the host by guests, and the retired undo generalised to dropping any step 2026-09-29 17:37:31 +00:00
Dennis Kobert 860ec5c465 History panel, read-only: the active document's history as interactions along the head's line, expandable to their deltas, with authors from the record, retirement times, derived labels, the head and undone rows, branch counts and the room's work in progress, refreshed each frame it moved; docked as a tab beside Layers from the Window menu 2026-09-29 15:50:58 +00:00
Dennis Kobert d90eacdee6 History phase one: retirements record their wall time as a delta attribute carried onto copies, and a per-document metadata record of users beside the history is persisted, carried in the sync and gossiped on change, so the editor names authors from the record before presence and colours by user id 2026-09-29 14:37:00 +00:00
Dennis Kobert f42a46c513 The cursor icon other peers see names the active shape for the Line, Rectangle and Ellipse tools instead of the Shape tool's polygon 2026-09-28 16:49:58 +00:00
Dennis Kobert fca4d4f9a8 Remote cursors show the tool their peer holds: the cursor packet carries the active tool's icon name, and both document and graph cursors are rendered by one Svelte component with the icon in the label, replacing the canvas overlay for document cursors so a remote move no longer redraws every overlay 2026-09-28 15:48:45 +00:00
Dennis Kobert 2c2926fd9c The native wasm shim proxies PanelType like the other editor types, so the desktop build compiles the focus_panel command 2026-09-28 13:09:53 +00:00
Dennis Kobert 2a2a92e627 Session tokens parse out of share links everywhere, so the CLI takes a pasted link; the panel gets a copy button for the bare token, the desktop app copies the session link natively, and the tab circle uses the editor's tooltip 2026-09-28 12:43:49 +00:00
Dennis Kobert f09a3855a8 The live viewer logs the resources it waits on before compiling and each one it receives, so a resource no peer holds is visible instead of a dark window 2026-09-26 11:41:03 +00:00
Dennis Kobert a476a156b4 The live viewer presents its background before the document is compiled, so the window is mapped on Wayland while it still waits for the sync, and logs when it synced and compiled 2026-09-26 11:25:42 +00:00
Dennis Kobert 3686641f5f The pointer position is recorded over the node graph too: the frontend sends a hover-only message that reaches no tool, so the cursor other peers see follows the mouse over the graph rather than jumping on clicks 2026-09-26 10:24:58 +00:00
Dennis Kobert 2d0c6fc6bc A guest joining by link takes the host's document id on any sync, not only a full one, so its own link names the shared room; the document name is a registry attribute staged on share, fork and rename and adopted by guests; a demo artwork opens with a fresh document id so everyone opening it does not share one room; the join field is a labelled row 2026-09-26 10:01:33 +00:00
Dennis Kobert 64b07445b7 Cursors carry the space they are in, the document or a network of the node graph by its path, so a peer with the graph open sends graph coordinates; receivers draw document cursors on the canvas overlay only while their graph is closed and graph cursors for the network they show through the Svelte graph as viewport points; the tab circle sits between the name and the close button 2026-09-26 09:50:20 +00:00
Dennis Kobert b5fa35aeff The user id is stored as a decimal string in the preferences, since a 64-bit number did not survive the browser's JSON store and the preferences failed to load, leaving every peer anonymous under user id 0 and dropping the name; the Session panel's not-shared state takes a pasted session link or token to join 2026-09-26 09:33:30 +00:00
Dennis Kobert 8b7bc2cd64 Session panel polish: no host or guest wording, the actions sit right under the state line in every state, anonymous peers are named Anonymous <animal> from the user id in italics, a Show cursors preference switch, the tab circle smaller and muted and red when the transport is lost, and a lost transport reconnects every three seconds until the room is back or sharing stops 2026-09-26 09:19:35 +00:00
Dennis Kobert 1b3a446d8a Session panel follow-ups: the File menu loses its share entry, a restored or newly added Session panel docks as a tab beside Properties instead of above it, a workspace saved before the panel existed gets it on load, and the panel refreshes once the working copy has mounted 2026-09-26 08:50:10 +00:00
Dennis Kobert c8be835772 Fork a session: leave the room, give the manifest a fresh document id and host the document as a new session with its own link; a transport drop keeps the document shared so the Session panel shows it disconnected and offers to reconnect, and the end of a connection the document already left or forked away from is ignored by generation 2026-09-26 08:33:26 +00:00
Dennis Kobert f820ed1ade The stored user id reaches the CRDT: the session carries a UserId next to its PeerId, the working copy persists it and follows the preferences on open, RegisterPeer records it and registration is a last-writer-wins write rather than a claim that errors on conflict, and undo of a retired step in a session names the person's latest step across the peer ids they accumulate 2026-09-26 08:20:45 +00:00
Dennis Kobert c9979f148a Presence: a profile packet carries the display name after each hello and on rename, a cursor packet carries the pointer in document space once a frame, both outside the causal broadcast; the name and a user id drawn once live in the preferences and the Session panel edits the name; other peers' cursors draw as overlays with a name label coloured by peer id 2026-09-26 07:59:04 +00:00
Dennis Kobert 9a7bf7a579 Session panel: sharing moves from a dialog to a panel docked next to Properties that shows the session state, the join link, the peers and the share and disconnect actions; a shared document's tab carries a circle that focuses the panel 2026-09-26 07:34:50 +00:00
Dennis Kobert db144ca217 Host handover: when the host leaves the lowest synced guest takes the role over, an unsynced guest steps aside and syncs from the new host, two hosts resolve by id, a returning host is a guest, the host merges a divergent line with a merge delta the room follows, and coarsening orders writes by stamp 2026-09-25 15:20:26 +00:00
Dennis Kobert 1a0b0741c4 Decode declarations the byte store already holds before applying remote changes: a second join in one browser requested nothing from the host and its rebuild found no declarations 2026-09-25 13:05:30 +00:00
Dennis Kobert ccdbc3ff80 Poll a room as packets arrive, not only per frame: the inbox wakes a future, so a host in a hidden tab answers a join at once instead of once a second 2026-09-25 12:49:05 +00:00
Dennis Kobert 48fbe6d2df One contextual session entry: share connects to the document's room and takes the host role only if none greets, disconnect leaves, and a shared document reconnects when reopened 2026-09-25 12:15:06 +00:00
Dennis Kobert cf75b0e99a Log the join handshake steps at info level to time where a guest waits 2026-09-25 11:57:34 +00:00
Dennis Kobert 4080405ef4 Derive the session token from the document id and let a copy rejoin its room with its own history, adopting the host's document id on a full sync 2026-09-25 11:55:50 +00:00
Dennis Kobert fe2f2c00a2 Fit the viewport to the document once a joining guest's interface follows the host's state and the graph has run 2026-09-25 11:41:14 +00:00
Dennis Kobert 435f33547a Coarsen a transaction at retirement to the newest write per field, keeping structural ops and the wires that stand for a referenced node 2026-09-25 11:22:20 +00:00
Dennis Kobert d59abb08e0 Keep the resource bytes a retracted step names alive across garbage collection, so its redo can still be served to peers 2026-09-25 11:15:43 +00:00
Dennis Kobert 4b4be2fffa Undo a retired step in a session by dropping it out of the shared line and moving every peer's head, with guests following the host's line instead of merging 2026-09-25 10:57:49 +00:00
Dennis Kobert 4d00dbae89 Follow the registry on the entities a hot undo or redo named instead of installing the legacy snapshot, send only the head's ancestry to peers, and keep a paused gesture in one transaction 2026-09-25 10:22:24 +00:00
Dennis Kobert e490c4fcc2 Take a hot transaction back on undo so it never becomes history, with placeholders replacing the last deferred write in the registry 2026-09-25 10:00:13 +00:00
Dennis Kobert d2bfda8178 Retire closed transactions per author on a policy instead of everything at the host's gesture, keeping open transactions hot 2026-09-25 08:55:07 +00:00
Dennis Kobert f18becb21b Keep removed resource sources as stamped tombstones under a chain floor, so source ops commute 2026-09-25 08:55:07 +00:00
Dennis Kobert 92cd31b607 Keep an attribute stamped at a map's floor when another map folds in, so a removal's snapshot no longer wipes what the addition wrote 2026-09-24 22:41:07 +00:00
Dennis Kobert b9ce700995 Make every registry op a timestamped write, presence and attribute deletion included, so merges apply once and the refold goes 2026-09-24 22:28:14 +00:00
Dennis Kobert 2893e6086b Retire a prefix of the hot log in the order it was applied 2026-09-24 21:23:15 +00:00
Dennis Kobert 09581fb86f Append retired deltas to the history file on a fast-forward merge instead of rewriting it 2026-09-24 21:17:23 +00:00
Dennis Kobert 75d0bee48d Stage recorded edits every frame in a session so each movement reaches peers 2026-09-24 21:17:23 +00:00
Dennis Kobert b12b692a2d Index history for tips, timestamps and resource hashes, fast-forward chained merges, and fold snapshots in place 2026-09-24 20:07:18 +00:00
Dennis Kobert 710487160c Broadcast the hot ops a recorded batch stages 2026-09-24 18:03:17 +00:00
Dennis Kobert e784ebfeb7 Reconcile remote changes into the interface instead of rebuilding it 2026-09-24 17:32:12 +00:00
Dennis Kobert 3c7bc125ea Record what remote ops touched on the Gdd sync target 2026-09-24 17:32:12 +00:00
Dennis Kobert 1c90c3732c Project single registry entities to the runtime and count refolds that change the working registry 2026-09-24 17:32:12 +00:00
Dennis Kobert 1ea5bf106a Keep a slot's ui attributes across an implementation swap 2026-09-24 17:32:12 +00:00
Dennis Kobert 7bf3452232 Name the seed and peer when a history cannot be replayed 2026-09-24 16:36:57 +00:00
Dennis Kobert 88c0d3a160 Guard that a seed fixes the run, since hashed iteration order once decided edits 2026-09-24 16:36:57 +00:00
Dennis Kobert c04cba26ad Make the simulation deterministic and check both registry zones 2026-09-24 16:36:57 +00:00
Dennis Kobert d34a7edf82 Propagate the refold error out of the sync target 2026-09-24 16:36:57 +00:00
Dennis Kobert 58ab6f0d99 Pin the working-registry divergence the retired-state checks never looked at 2026-09-24 16:36:57 +00:00
Dennis Kobert 650cd76f88 Keep unretired hot ops across a full resync instead of dropping them 2026-09-24 16:36:57 +00:00
Dennis Kobert 06ad3fa181 Pin the witness path that keeps an author's run contiguous 2026-09-24 16:36:57 +00:00
Dennis Kobert b21af5eec0 Follow the retired-beyond rename in the simulation dump 2026-09-24 16:36:57 +00:00
Dennis Kobert 7197cc1bd4 Layer the peer-transport work onto the hardened graph-storage API 2026-09-24 16:36:57 +00:00
Dennis Kobert 4b2a63d0f3 Resurrect from the replay position when folding a snapshot from history 2026-09-24 16:36:51 +00:00
Dennis Kobert 3b9474e346 Stamp a freshly created node's implementation at the origin timestamp 2026-09-24 13:56:16 +00:00
Dennis Kobert dc4fa94012 Make a peer's working registry agree with its own retired snapshot 2026-09-24 13:56:16 +00:00
Dennis Kobert 7b10164b72 Store retired ops past a prefix as runs so a permanent gap cannot grow them 2026-09-24 13:56:16 +00:00
Dennis Kobert c408e6ed69 Record what the retired-beyond set actually bounds 2026-09-24 13:56:16 +00:00
Dennis Kobert e1508acac5 Give hot-op sequence numbers their own type 2026-09-24 13:56:16 +00:00
Dennis Kobert a8d6bb73e7 Vary comment phrasing and cut the repeated constructions 2026-09-24 13:56:16 +00:00
Dennis Kobert ec057cea3b Retry an owed refold and keep the unguarded hot-op path crate-private 2026-09-24 13:56:16 +00:00
Dennis Kobert 1d9653d40f Address review findings 2026-09-24 13:56:16 +00:00
Dennis Kobert 1bbce952e2 Shorten the comments on the retired-state changes 2026-09-24 13:56:16 +00:00
Dennis Kobert 6ae05765d2 Make retired state a function of history alone 2026-09-24 13:56:16 +00:00
Keavon Chambers ddafaaa757 Add an "Output Type" parameter to the 'Math f(x)' and 'Math f(…)' nodes (#4591)
Add an 'Output Type' choice to the 'Math f(x)' and 'Math f(…)' nodes
2026-09-23 20:26:51 -07:00
Keavon Chambers 2c1cca7e99 Rename the TaggedValue I64/F64/F64Array variants to Integer/Number/Numbers (#4590)
Rename the TaggedValue F64/I64/F64Array variants to Number/Integer/Numbers
2026-09-23 18:02:06 -07:00
Keavon Chambers c91d0cd5a3 Update all node parameters with appropriate attributes of #[unit(...)], bounds, etc., deprecating the type alias units pattern (#4589)
Replace the node parameter typedefs with unit and widget attributes
2026-09-23 17:08:05 -07:00
Dennis Kobert 84ed60a404 Route every network interface write through a single-writer store (#4586)
* Route every network interface write through a single-writer store

* Keep the existing previewing behaviour and fix the review findings that remain

* Record what each store write changed and stage it into the working copy

* Fix the delta path's resource staging, batch liveness, and stale comparisons

* Keep batch resource liveness and load-time repairs consistent with what reaches storage

* Correct the delta documentation and stop persisting pinned nodes the network lost

* Swap a node's implementation in place instead of rebuilding the node

* Resolve network attributes through the same source as the IDs they name

* Resolve an implementation swap by timestamp and let an edit report whether it changed the value
2026-09-23 21:52:02 +00:00
Keavon Chambers 942d138fc1 Add #[multiline] and #[progression] node parameter attributes for choosing a type's preferred widget variant (#4587)
Add #[multiline] and #[progression] node parameter attributes for choosing a widget
2026-09-23 13:44:49 -07:00
Keavon Chambers dadc8717ff Narrow node parameters with an integer meaning from i32/f64 to i64 (#4584)
* Narrow node parameters with an integer meaning from i32/f64 to i64

* Update demo artwork
2026-09-23 03:18:41 -07:00
Keavon Chambers 9423dcada7 Replace all node usages of u32/u64 with i64 (#4582)
* Add TODO notes that the raster filters' lengths should scale through the footprint instead of counting whole source pixels

* Standardize the node catalog's integer parameters on i64, replacing u32 and u64 with hard-bounded i64

* Retire the 'As u32' and 'As u64' nodes into 'As Integer' and upgrade stored unsigned values to I64
2026-09-23 00:15:09 -07:00
Keavon Chambers 2941c74051 Replace all node usages of f32 with f64 (#4581)
Retire f32 from the node catalog so every Number is an f64, leaving only the Color and shader internals computing in f32
2026-09-22 21:47:49 -07:00
Keavon Chambers cd00af84f3 Make the node macro reject nodes with unmatched #[implementations] counts (#4580)
Make the node macro reject a node whose #[implementations] row counts differ across parameters instead of padding the shorter lists
2026-09-22 21:04:14 -07:00
Keavon Chambers 951339a6d6 Move the adjustment nodes to 64-bit precision number parameters (#4579)
Declare shader nodes in f64 and have the node macro emit the f32 variant that the shader build computes with
2026-09-22 19:38:19 -07:00
Keavon Chambers f5507c0959 Round half away from zero on every Number to Integer conversion instead of truncating (#4578)
* Add an I64 tagged value as the node graph's integer storage type, with a whole-number widget for it

* Round half away from zero on every Number to Integer conversion instead of truncating
2026-09-22 18:22:24 -07:00
Keavon Chambers 60bba681d3 Have the math expression nodes each use #[data] to cache its parsed expression input (#4577)
Parse each expression node's source once, reusing the tree across list items and frames
2026-09-22 17:44:18 -07:00
Keavon Chambers f868aadd8d Retire the 'Math' node and migrate its documents to 'Math f(x)' and 'Math f(…)' (#4576)
Retire the Math node and migrate its documents to Math f(x) and Math f(…)
2026-09-22 17:14:47 -07:00
Keavon Chambers b610d9bc23 Extend the math expression parser's combinatorics, statistics, roots, powers, and division past the reals (#4574) 2026-09-22 16:00:08 -07:00
Dennis Kobert 69398a6703 Make GDD based undo syncronous by caching protonode declarations (#4571)
* Make gdd based undo syncronous by caching protonode declarations

* Address review comments
2026-09-22 11:32:12 +00:00
225 changed files with 20251 additions and 4565 deletions

No files matched your search

Generated
+1706 -49
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -11,6 +11,8 @@ members = [
"document/format",
"document/graph-storage",
"document/container",
"document/peer-transport",
"document/live",
"editor",
"frontend/wrapper",
"libraries/dyn-any",
@@ -98,6 +100,8 @@ graph-craft = { path = "node-graph/graph-craft" }
document-format = { path = "document/format" }
document-graph-storage = { path = "document/graph-storage", default-features = false }
document-container = { path = "document/container" }
peer-transport = { path = "document/peer-transport" }
document-live = { path = "document/live" }
raster-nodes = { path = "node-graph/nodes/raster" }
graphene-std = { path = "node-graph/nodes/gstd" }
interpreted-executor = { path = "node-graph/interpreted-executor" }
+1
View File
@@ -18,6 +18,7 @@ accepted = [
"NCSA", # Keep this list in sync with those in `/deny.toml`
"bzip2-1.0.6", # Keep this list in sync with those in `/deny.toml`
"OFL-1.1", # Keep this list in sync with those in `/deny.toml`
"Unlicense", # Keep this list in sync with those in `/deny.toml`
]
workarounds = ["ring"]
ignore-build-dependencies = true
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":fLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":fLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"I64":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"I64":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_vaLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"outLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"outLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
+1
View File
@@ -82,6 +82,7 @@ allow = [
"NCSA", # Keep this list in sync with those in `/about.toml`
"bzip2-1.0.6", # Keep this list in sync with those in `/about.toml`
"OFL-1.1", # Keep this list in sync with those in `/about.toml`
"Unlicense", # Keep this list in sync with those in `/about.toml`
]
# The confidence threshold for detecting a license from license text.
# The higher the value, the more closely the license text must be to the
@@ -115,6 +115,13 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
FrontendMessage::TriggerClipboardWrite { content } => {
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite { content });
}
// The desktop app has no web origin to build the link from, so it points at the hosted editor; the token
// alone is offered separately.
FrontendMessage::TriggerSessionLinkCopy { token } => {
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite {
content: format!("https://editor.graphite.rs/?session={token}"),
});
}
FrontendMessage::WindowPointerLock => {
dispatcher.respond(DesktopFrontendMessage::PointerLock);
}
+1 -1
View File
@@ -47,7 +47,7 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
&& e != "No active document"
{
tracing::error!("Error poling node graph: {}", e);
tracing::error!("Error polling node graph: {}", e);
}
while let Some(message) = responses.pop_front() {
self.queue_editor_message(message);
+4 -1
View File
@@ -17,11 +17,14 @@ conversion = ["document-graph-storage/conversion", "dep:graph-craft", "dep:core-
# gates that format's `ExportFormat` arm and sink. The folder/memory codec-free core needs neither.
zip = ["document-container/zip"]
xz = ["document-container/xz"]
default = ["conversion", "zip", "xz"]
# Live collaboration: `Gdd` hosts or joins a `peer_transport` session and mirrors hot ops and retired history to peers.
network = ["dep:peer-transport"]
default = ["conversion", "zip", "xz", "network"]
[dependencies]
document-container = { workspace = true }
document-graph-storage = { workspace = true, default-features = false }
peer-transport = { workspace = true, optional = true }
graph-craft = { workspace = true, optional = true }
graphene-resource = { workspace = true }
core-types = { workspace = true, optional = true }
+4
View File
@@ -47,4 +47,8 @@ pub enum Error {
/// An export marked a resource for embedding but its bytes were absent from the byte store.
#[error("embedded resource {0} missing from the byte store")]
MissingResource(ResourceHash),
/// A packet for the collaboration session failed to encode.
#[cfg(feature = "network")]
#[error("network error: {0}")]
Network(#[from] peer_transport::PacketError),
}
+12 -1
View File
@@ -11,7 +11,7 @@ use graphene_resource::{LoadResource, Resource, ResourceHash};
use crate::error::Error;
use crate::layout::Layout;
use crate::session_state::SessionState;
use crate::{Gdd, MANIFEST_CODEC, io};
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, io};
/// Export wrapping. Payloads keep the working copy's recorded per-payload codecs (see
/// [`crate::manifest::PayloadCodecs`]); export does not re-encode.
@@ -146,14 +146,25 @@ impl<L: Layout> Gdd<L> {
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
let session_state = SessionState {
peer_id: self.session.peer(),
user_id: self.session.user(),
head_rev: self.session.head_rev(),
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
next_node_counter: self.session.next_node_counter(),
// An export is a copy taken out of the room; it does not reconnect on its own.
shared: false,
next_hot_sequence: self.session.next_hot_sequence(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
sink.write_entry(&io::path_for(self.layout.session_basename(), codecs.session), &codecs.session.write_single(&session_state)?)?;
if !self.metadata.is_empty() {
let mut facts = Vec::new();
for fact in self.metadata.facts() {
METADATA_CODEC.append(&mut facts, &fact)?;
}
sink.write_entry(&io::path_for(self.layout.metadata_basename(), METADATA_CODEC), &facts)?;
}
let working_copy_hashes: std::collections::HashSet<ResourceHash> = self.resource_hashes().await?.into_iter().collect();
+5
View File
@@ -12,6 +12,8 @@ pub trait Layout {
fn registry_basename(&self) -> &str;
fn history_basename(&self) -> &str;
fn hot_log_basename(&self) -> &str;
/// What people state about the history beside it: users and their names, later labels and tags.
fn metadata_basename(&self) -> &str;
fn resources_dir(&self) -> &str;
fn resource_path(&self, hash: &ResourceHash) -> String;
/// The embedded legacy `.graphite` document, stored verbatim during the dual-write soak so the
@@ -39,6 +41,9 @@ impl Layout for GddV1Layout {
fn hot_log_basename(&self) -> &str {
"hot-log"
}
fn metadata_basename(&self) -> &str {
"metadata"
}
fn resources_dir(&self) -> &str {
"resources"
}
+129 -27
View File
@@ -17,10 +17,10 @@ use document_container::backends::folder::FolderBackend;
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
#[cfg(feature = "conversion")]
use document_graph_storage::{CommitError, NodeMetadataSource};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session};
use document_graph_storage::{Delta, HistoryMetadata, HotOp, MetadataFact, PeerId, Registry, Session, UserId};
#[cfg(feature = "conversion")]
use graphene_resource::LoadResource;
use graphene_resource::ResourceHash;
use graphene_resource::{ResourceHash, ResourceStorage};
pub mod codec;
pub mod error;
@@ -28,6 +28,8 @@ pub mod export;
pub mod io;
pub mod layout;
pub mod manifest;
#[cfg(feature = "network")]
pub mod network;
pub mod persist;
pub mod resource;
pub mod session_state;
@@ -55,6 +57,8 @@ pub const MANIFEST_CODEC: Codec = Codec::Json;
/// users who want a diffable on-disk representation. Recorded in the manifest at create time and
/// read back on open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
/// The metadata file is a log of facts appended one per line and folded on read, so nothing is ever rewritten.
pub const METADATA_CODEC: Codec = Codec::JsonLines;
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::MessagePack;
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::MessagePackFrames;
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
@@ -68,8 +72,8 @@ pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
/// read.
/// `Clone` shares the working-copy container (`Arc<AnyContainer>`) so a cloned handle reads and writes
/// the *same* on-disk/OPFS working copy — including any writes still queued on the OPFS backend. The
/// `Session` is cloned (a snapshot copy); the container is shared.
#[derive(Clone)]
/// `Session` is cloned (a snapshot copy); the container is shared. A live collaboration session is
/// not carried over, so a clone is a read-only copy for asynchronous writes.
pub struct Gdd<L: Layout = GddV1Layout> {
pub(crate) session: Session,
pub(crate) working: Arc<AnyContainer>,
@@ -78,12 +82,77 @@ pub struct Gdd<L: Layout = GddV1Layout> {
/// per-payload codecs so the persist path never probes the filesystem, keeping it fully read-free
/// and synchronous.
pub(crate) manifest: Manifest,
/// What people state about the history: its users and their names, later labels and tags. Kept beside
/// the history in its own file, merged last-writer-wins with every copy met, never folded and never undone.
pub(crate) metadata: HistoryMetadata,
/// The wall clock as the editor last reported it, in milliseconds since the Unix epoch, so retirements can
/// record when they happened. `None` for a copy nothing ticks, the CLI or a test.
pub(crate) wall_clock_ms: Option<f64>,
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
pub(crate) view_settings: std::collections::BTreeMap<String, serde_json::Value>,
/// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer
/// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network.
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
/// Where this document's resource bytes live. `None` means the working copy's own content-addressed
/// store, which is what a standalone handle uses. The editor points this at its application-wide
/// cache, the single store resources are kept in there.
pub(crate) byte_store: Option<Arc<dyn ResourceStorage>>,
#[cfg(feature = "network")]
pub(crate) network: Option<peer_transport::Replica>,
#[cfg(feature = "network")]
pub(crate) pending_persist: PendingPersist,
/// What peers changed since the editor last took it, so it can bring its runtime mirror into line
/// with the registry without rebuilding it.
#[cfg(feature = "network")]
pub(crate) remote_changes: network::RemoteChanges,
/// When each closed transaction was first seen here, by its marker, so the retirement policy can age
/// it. Not persisted: after a reopen everything pending is old enough.
pub(crate) transactions_seen: std::collections::HashMap<document_graph_storage::HotOpId, f64>,
/// When this peer last staged an op, so an open transaction the editor never closed can be closed
/// once it has gone quiet.
pub(crate) own_last_staged_ms: Option<f64>,
/// Whether an op of this peer's own was staged since the last policy tick.
pub(crate) own_staged_since_tick: bool,
/// Whether the document is meant to be in its room: set by sharing, cleared by disconnecting, and
/// persisted so a reopened document reconnects on its own.
pub(crate) shared: bool,
}
/// Whole-file rewrites the sync path defers to the end of a poll, so one batch of remote packets costs
/// one rewrite of each file rather than one per packet.
#[cfg(feature = "network")]
#[derive(Debug, Default, Clone, Copy)]
pub(crate) struct PendingPersist {
pub(crate) history: bool,
pub(crate) hot_log: bool,
pub(crate) snapshot: bool,
}
impl<L: Layout + Clone> Clone for Gdd<L> {
fn clone(&self) -> Self {
Self {
session: self.session.clone(),
working: self.working.clone(),
layout: self.layout.clone(),
manifest: self.manifest.clone(),
view_settings: self.view_settings.clone(),
metadata: self.metadata.clone(),
wall_clock_ms: self.wall_clock_ms,
network_view_settings: self.network_view_settings.clone(),
byte_store: self.byte_store.clone(),
shared: self.shared,
#[cfg(feature = "network")]
network: None,
#[cfg(feature = "network")]
pending_persist: PendingPersist::default(),
#[cfg(feature = "network")]
remote_changes: network::RemoteChanges::default(),
transactions_seen: Default::default(),
own_last_staged_ms: None,
own_staged_since_tick: false,
}
}
}
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
@@ -101,10 +170,10 @@ impl<L: Layout + Default> Gdd<L> {
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
pub async fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub async fn create(path: &Path, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
let working = AnyContainer::Folder(FolderBackend::create(path)?);
let layout = L::default();
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version).await
Self::create_in(working, layout, peer, user, document_uuid, editor_version, stdlib_version).await
}
}
@@ -135,29 +204,40 @@ impl<L: Layout> Gdd<L> {
true => io::read_single(&working, layout.session_basename(), codecs.session).await?,
false => SessionState::default(),
};
let metadata = match io::exists(&working, layout.metadata_basename(), METADATA_CODEC).await {
true => HistoryMetadata::fold(io::iter::<MetadataFact>(&working, layout.metadata_basename(), METADATA_CODEC).await?),
false => HistoryMetadata::default(),
};
let has_registry = io::exists(&working, layout.registry_basename(), codecs.registry).await;
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
let peer = session_state.peer_id;
// A copy written before identities were stored has no user; the peer stands for itself until one is set.
let user = match session_state.user_id {
UserId(0) => UserId(peer.0),
user => user,
};
let mut session = match (has_registry, has_history) {
(true, true) => {
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
let history = load_history(&working, &layout, codecs.history).await?;
Session::load(peer, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
Session::load(peer, user, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
}
(true, false) => {
// Registry-only export: synthesize a history that reproduces this state.
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
Session::bootstrap_from_registry(peer, registry)?
Session::bootstrap_from_registry(peer, user, registry)?
}
(false, _) => Session::replay_from_history(peer, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
(false, _) => Session::replay_from_history(peer, user, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
};
// Restore the published frontier (silent/published undo boundary) regardless of which load arm ran.
if let Some(rev) = session_state.last_broadcast_rev {
session.publish_up_to(rev);
}
// Every arm must continue this peer's authored-op count too.
session.restore_hot_sequence(session_state.next_hot_sequence);
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
@@ -168,19 +248,36 @@ impl<L: Layout> Gdd<L> {
manifest,
view_settings: session_state.view_settings,
network_view_settings: session_state.network_view_settings,
shared: session_state.shared,
metadata,
wall_clock_ms: None,
byte_store: None,
#[cfg(feature = "network")]
network: None,
#[cfg(feature = "network")]
pending_persist: PendingPersist::default(),
#[cfg(feature = "network")]
remote_changes: network::RemoteChanges::default(),
transactions_seen: Default::default(),
own_last_staged_ms: None,
own_staged_since_tick: false,
})
}
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
/// the manifest and writes each payload with its recorded codec.
pub async fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub async fn create_in(working: AnyContainer, layout: L, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
let codecs = manifest.codecs;
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
let session_state = SessionState { peer_id: peer, ..Default::default() };
let session_state = SessionState {
peer_id: peer,
user_id: user,
..Default::default()
};
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
let session = Session::with_peer(peer);
let session = Session::with_identity(peer, user);
io::write_single(&working, layout.registry_basename(), codecs.registry, session.registry())?;
Ok(Self {
@@ -190,6 +287,19 @@ impl<L: Layout> Gdd<L> {
manifest,
view_settings: std::collections::BTreeMap::new(),
network_view_settings: std::collections::BTreeMap::new(),
metadata: HistoryMetadata::default(),
wall_clock_ms: None,
byte_store: None,
shared: false,
#[cfg(feature = "network")]
network: None,
#[cfg(feature = "network")]
pending_persist: PendingPersist::default(),
#[cfg(feature = "network")]
remote_changes: network::RemoteChanges::default(),
transactions_seen: Default::default(),
own_last_staged_ms: None,
own_staged_since_tick: false,
})
}
}
@@ -292,24 +402,16 @@ impl<L: Layout> Gdd<L> {
(working, self.layout)
}
/// Resolve the proto-node declarations referenced by the registry into a [`document_graph_storage::Declarations`]
/// map, loading each `ProtoNode`'s bytes from `byte_store` (the global cache in the editor, the
/// working-copy container for standalone). Only resources referenced by `Implementation::ProtoNode`
/// are visited, so image/font resources are skipped. Cold-path (open / `to_runtime`); async
/// because resource loads are.
/// Resolve every proto-node declaration referenced by the registry or its history into a
/// [`document_graph_storage::Declarations`] map, loading each `ProtoNode`'s bytes from `byte_store`
/// (the global cache in the editor, the working-copy container for standalone). Covers history so
/// the map can serve any undo/redo target. Cold-path (mount / open); async because resource loads are.
#[cfg(feature = "conversion")]
pub async fn declarations(&self, byte_store: &dyn LoadResource) -> document_graph_storage::Declarations {
use document_graph_storage::Implementation;
let registry = self.session.registry();
let mut declarations = document_graph_storage::Declarations::new();
for node in registry.node_instances.values() {
let Implementation::ProtoNode(id) = node.implementation() else { continue };
if declarations.contains_key(id) {
continue;
}
let Some(hash) = registry.resources.get(id).and_then(|entry| entry.hash) else {
for (id, hash) in self.session.all_declaration_resources() {
let Some(hash) = hash else {
log::error!("Declaration resource {id} has no resolved hash; cannot load ProtoNode");
continue;
};
@@ -319,7 +421,7 @@ impl<L: Layout> Gdd<L> {
};
match document_graph_storage::decode_declaration(resource.as_ref()) {
Ok(proto) => {
declarations.insert(*id, proto);
declarations.insert(id, proto);
}
Err(error) => log::error!("Failed to deserialize ProtoNode for {id}: {error}"),
}
+372
View File
@@ -0,0 +1,372 @@
//! Live collaboration on the [`Gdd`] handle. `share` / `join` attach a [`Replica`]; the persist path
//! then broadcasts staged hot ops and (as host) retired deltas, and `poll_peers` applies what peers
//! send through the [`SyncTarget`] impl below, which persists inbound state the same way local
//! edits are.
use std::collections::HashSet;
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, RegistryDelta, ResourceHash, RetiredHotOps, Rev, Session, Touched, UserId};
use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, Transport};
use crate::error::Error;
use crate::layout::Layout;
use crate::{Gdd, PendingPersist};
/// What peers changed in the working registry since the editor last asked. The editor keeps a runtime
/// mirror of the registry and brings just the touched entities back into line, unless the registry was
/// rederived wholesale, when the touched set no longer bounds what changed.
#[derive(Clone, Debug, Default)]
pub struct RemoteChanges {
pub touched: Touched,
/// The working registry was replaced wholesale by a full sync, so the mirror has to be rebuilt from it.
pub rebuilt: bool,
}
impl RemoteChanges {
pub fn is_empty(&self) -> bool {
self.touched.is_empty() && !self.rebuilt
}
pub fn extend(&mut self, other: RemoteChanges) {
self.touched.extend(other.touched);
self.rebuilt |= other.rebuilt;
}
}
impl<L: Layout> Gdd<L> {
/// Takes what peers changed since the last call. Empty when nothing did.
pub fn take_remote_changes(&mut self) -> RemoteChanges {
std::mem::take(&mut self.remote_changes)
}
}
impl<L: Layout> Gdd<L> {
pub fn share(&mut self, transport: impl Transport + 'static, user: UserId) {
self.network = Some(Replica::host(transport, self.session.peer(), user));
}
/// Connect to the room every copy of this document shares, host or guest as the room calls for, and
/// remember that the document is shared so a reopen reconnects on its own.
pub fn connect(&mut self, transport: impl Transport + 'static, user: UserId) -> Result<(), Error> {
self.network = Some(Replica::connect(transport, self.session.peer(), user));
self.shared = true;
self.persist_session_state()
}
/// Whether the document is meant to be in its room; see [`connect`](Self::connect).
pub fn is_shared(&self) -> bool {
self.shared
}
/// For a connection still undecided after the grace period: take the host role if no host is there. See
/// [`Replica::decide_role`].
pub fn decide_role(&mut self) -> Option<Role> {
self.network.as_mut().and_then(Replica::decide_role)
}
pub fn join(&mut self, transport: impl Transport + 'static, user: UserId) {
self.network = Some(Replica::guest(transport, self.session.peer(), user));
}
/// Leaves the room. A host retires every closed transaction first, so what peers finished is in
/// history before the retirer goes away.
pub fn leave(&mut self) {
self.shared = false;
if let Err(error) = self.persist_session_state() {
log::error!("Persisting the session state before leaving failed: {error}");
}
self.disconnect();
}
/// Drops the connection but keeps the document shared, for a transport that went down: a reopen
/// reconnects on its own, and the Session panel offers to reconnect now.
pub fn disconnect(&mut self) {
let closed = self.session.closed_transactions();
if let Err(error) = self.retire_transactions(&closed) {
log::error!("Retiring before leaving failed: {error}");
}
if let Some(mut replica) = self.network.take() {
replica.leave();
}
}
pub fn role(&self) -> Option<Role> {
self.network.as_ref().map(Replica::role)
}
pub fn is_synced(&self) -> bool {
self.network.as_ref().is_none_or(Replica::is_synced)
}
/// Announce this peer's display name to the room; a no-op when it has not changed or nobody is connected.
pub fn set_name(&mut self, name: &str) -> Result<(), Error> {
if let Some(replica) = &mut self.network {
replica.set_name(name)?;
}
Ok(())
}
/// Send this peer's pointer position, `None` when it left the viewport.
pub fn send_cursor(&mut self, position: Option<peer_transport::CursorPosition>) -> Result<(), Error> {
if let Some(replica) = &mut self.network {
replica.send_cursor(position)?;
}
Ok(())
}
/// The other peers in the room; empty when the document is not connected.
pub fn peers(&self) -> Vec<peer_transport::RemotePeer> {
self.network.as_ref().map(|replica| replica.peers().cloned().collect()).unwrap_or_default()
}
/// Record that the runtime was rebuilt from the registry, so the next staged diff is taken against it.
pub fn mark_runtime_current(&mut self) {
self.session.mark_runtime_current();
}
pub fn poll_peers(&mut self) -> Vec<Event> {
let Some(mut replica) = self.network.take() else { return Vec::new() };
let events = replica.poll(self);
self.network = Some(replica);
events
}
/// Answer an [`Event::ResourceRequested`].
pub fn send_resource(&mut self, to: peer_transport::TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), Error> {
if let Some(replica) = &mut self.network {
replica.send_resource(to, hash, bytes)?;
}
Ok(())
}
}
impl<L: Layout> SyncTarget for Gdd<L> {
fn peer(&self) -> PeerId {
self.session.peer()
}
fn document_id(&self) -> Option<u64> {
Some(self.manifest.document_id)
}
fn adopt_document_id(&mut self, document_id: u64) -> Result<(), TargetError> {
self.update_manifest(|manifest| manifest.document_id = document_id)?;
Ok(())
}
fn head(&self) -> Option<Rev> {
self.session.head_rev()
}
fn retired_registry(&self) -> Registry {
self.session.retired_registry().clone()
}
fn hot_log(&self) -> Vec<HotOp> {
self.session.hot_log().to_vec()
}
fn known_revs(&self) -> Vec<Rev> {
self.session.known_revs()
}
fn contains_rev(&self, rev: Rev) -> bool {
self.session.delta(rev).is_some()
}
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta> {
<Session as SyncTarget>::deltas_unknown_to(&self.session, known)
}
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
self.session.load(registry, history, head)?;
self.remote_changes.rebuilt = true;
self.pending_persist = PendingPersist {
history: true,
hot_log: true,
snapshot: true,
};
Ok(())
}
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
// An op naming an entity that has not arrived here yet is handed back for a later retry, so only
// what actually applied reaches the hot frame log.
let mut deferred = Vec::new();
for hot_op in ops {
// Recorded whether or not it applies: a failed apply can still have resurrected what it references.
self.remote_changes.touched.record(&hot_op.op);
if self.session.replay_hot_op(hot_op.clone()).is_err() {
deferred.push(hot_op);
continue;
}
self.append_hot_frame(&hot_op)?;
}
Ok(deferred)
}
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId], head: Option<Rev>) -> Result<(), TargetError> {
let incoming: HashSet<Rev> = deltas.iter().map(|delta| delta.id).collect();
let length_before = self.session.history_len();
for delta in &deltas {
self.remote_changes.touched.record(&delta.kind);
}
SyncTarget::merge_remote(&mut self.session, deltas, retires, head)?;
// Whatever a peer sent is shared by definition, so it sits behind the published frontier too: a
// guest must no more silently rewind the host's history than the host may rewind its own.
if let Some(head) = self.session.head_rev() {
self.session.publish_up_to(head);
}
// A batch that extended canonical history at the end, with any merge delta joining it there, extends
// the file the same way. One that sorted earlier deltas after it rewrites the file.
let tail: Vec<Rev> = self.session.history().skip(length_before).map(|delta| delta.id).collect();
let appended = tail
.iter()
.all(|&rev| incoming.contains(&rev) || self.session.delta(rev).is_some_and(|delta| matches!(delta.kind, RegistryDelta::Merge { .. })));
match appended {
true => self.append_history_deltas(&tail)?,
false => self.pending_persist.history = true,
}
self.pending_persist.hot_log |= !retires.is_empty();
self.pending_persist.snapshot = true;
Ok(())
}
fn merge_divergent(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<Vec<Delta>, TargetError> {
let length_before = self.session.history_len();
for delta in &deltas {
self.remote_changes.touched.record(&delta.kind);
}
let absorbed = SyncTarget::merge_divergent(&mut self.session, deltas, retires)?;
if let Some(head) = self.session.head_rev() {
self.session.publish_up_to(head);
}
// The absorbed deltas and the merge joining them are the batch; a sort that moved earlier deltas
// after them rewrites the file.
let absorbed_ids: HashSet<Rev> = absorbed.iter().map(|delta| delta.id).collect();
let tail: Vec<Rev> = self.session.history().skip(length_before).map(|delta| delta.id).collect();
match tail.iter().all(|rev| absorbed_ids.contains(rev)) {
true => self.append_history_deltas(&tail)?,
false => self.pending_persist.history = true,
}
self.pending_persist.hot_log |= !retires.is_empty();
self.pending_persist.snapshot = true;
Ok(absorbed)
}
fn retired_marks(&self) -> RetiredHotOps {
SyncTarget::retired_marks(&self.session)
}
fn absorb_retired_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError> {
SyncTarget::absorb_retired_marks(&mut self.session, remote)?;
self.pending_persist.hot_log = true;
Ok(())
}
fn retracted_marks(&self) -> RetiredHotOps {
SyncTarget::retracted_marks(&self.session)
}
fn absorb_retracted_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError> {
let touched = self.session.absorb_retracted_marks(remote);
if !touched.is_empty() {
self.remote_changes.touched.extend(touched);
self.pending_persist.hot_log = true;
self.pending_persist.snapshot = true;
}
Ok(())
}
fn metadata(&self) -> HistoryMetadata {
self.metadata.clone()
}
fn absorb_metadata(&mut self, remote: &HistoryMetadata) -> Result<bool, TargetError> {
let landed = self.metadata.merge(remote);
if landed.is_empty() {
return Ok(false);
}
self.append_facts(&landed)?;
Ok(true)
}
fn retract_hot_ops(&mut self, ops: &[HotOpId]) -> Result<(), TargetError> {
let touched = self.session.retract_hot_ops(ops);
self.remote_changes.touched.extend(touched);
self.pending_persist.hot_log = true;
self.pending_persist.snapshot = true;
Ok(())
}
fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
let (moved, touched) = self.session.drop_interaction(rev)?;
self.remote_changes.touched.extend(touched);
self.pending_persist.history = true;
self.pending_persist.hot_log = true;
self.pending_persist.snapshot = true;
Ok(moved)
}
fn restore_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, TargetError> {
let revs = self.session.restore_interaction(rev)?;
let deltas: Vec<Delta> = revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
for delta in &deltas {
self.remote_changes.touched.record(&delta.kind);
}
if let Some(&last) = revs.last() {
self.session.publish_up_to(last);
}
self.pending_persist.history = true;
self.pending_persist.snapshot = true;
Ok(deltas)
}
fn apply_head_move(&mut self, moved: &HeadMove) -> Result<(), TargetError> {
let touched = self.session.apply_head_move(moved)?;
self.remote_changes.touched.extend(touched);
if let Some(head) = self.session.head_rev() {
self.session.publish_up_to(head);
}
self.pending_persist.history = true;
self.pending_persist.hot_log = true;
self.pending_persist.snapshot = true;
Ok(())
}
fn move_head_to(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
let (moved, touched) = self.session.move_head_to(rev)?;
self.remote_changes.touched.extend(touched);
self.pending_persist.snapshot = true;
Ok(moved)
}
fn flush(&mut self) -> Result<(), TargetError> {
let pending = std::mem::take(&mut self.pending_persist);
if pending.history {
self.rewrite_history()?;
}
if pending.hot_log {
self.rewrite_hot_log()?;
}
if pending.snapshot {
self.persist_registry_snapshot()?;
self.persist_session_state()?;
}
Ok(())
}
fn missing_resources(&self) -> HashSet<ResourceHash> {
self.unstored_resources().into_iter().collect()
}
fn store_resource(&mut self, _hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
self.hold_resource(bytes)?;
Ok(())
}
}
+388 -63
View File
@@ -6,7 +6,7 @@
use document_container::AsyncContainer;
#[cfg(feature = "conversion")]
use document_graph_storage::NodeMetadataSource;
use document_graph_storage::{HotOp, Rev, TimeStamp};
use document_graph_storage::{Delta, HistoryMetadata, HotOp, MetadataFact, RegistryDelta, Rev, TimeStamp, UserId, WallStamp};
#[cfg(feature = "conversion")]
use graphene_resource::ResourceStorage;
@@ -14,7 +14,7 @@ use crate::error::Error;
use crate::layout::Layout;
use crate::manifest::Manifest;
use crate::session_state::SessionState;
use crate::{Gdd, MANIFEST_CODEC, io};
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, io};
impl<L: Layout> Gdd<L> {
/// Move the undo cursor back one commit (silent-zone reflog undo) and persist the new cursor. Returns
@@ -36,6 +36,16 @@ impl<L: Layout> Gdd<L> {
}
/// Edit the cached manifest and persist it. Always JSON, synchronous.
/// The person using this device, from the editor's preferences. A change registers the peer again on
/// its next staged batch, and the newer registration wins everywhere.
pub fn set_user(&mut self, user: UserId) -> Result<(), Error> {
if self.session.user() == user {
return Ok(());
}
self.session.set_user(user);
self.persist_session_state()
}
pub fn update_manifest(&mut self, edit: impl FnOnce(&mut Manifest)) -> Result<(), Error> {
edit(&mut self.manifest);
io::write_single(&self.working, self.layout.manifest_basename(), MANIFEST_CODEC, &self.manifest)?;
@@ -47,7 +57,7 @@ impl<L: Layout> Gdd<L> {
/// declaration bytes. The working registry reflects the edit immediately, but nothing enters durable
/// retired history until [`retire_pending_interaction`](Self::retire_pending_interaction). Staging on
/// every edit while retiring only at interaction boundaries lets several edits coalesce into one retired
/// interaction.
/// interaction. Returns the decoded declarations the snapshot references, for the caller's cache.
///
/// # Errors
/// [`Error::Commit`] if the runtime diff is rejected by the session. On an [`Error::Container`] /
@@ -60,54 +70,59 @@ impl<L: Layout> Gdd<L> {
metadata: &M,
resources: &graphene_resource::ResourceRegistry,
byte_store: &dyn ResourceStorage,
) -> Result<(), Error> {
let (hot_ops, declaration_bytes) = self.session.stage_from_runtime(network, metadata, resources)?;
for hot_op in &hot_ops {
self.append_hot_frame(hot_op)?;
}
) -> Result<document_graph_storage::Declarations, Error> {
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
self.persist_staged(&hot_ops)?;
// Persist proto-node declaration content to the byte store (the global cache in the editor,
// the working-copy container for standalone export). Content-addressed, so re-storing
// identical bytes on every commit is an idempotent no-op.
for bytes in declaration_bytes.values() {
for bytes in conversion.declaration_bytes.values() {
byte_store.store(bytes);
}
Ok(())
Ok(conversion.declarations)
}
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
/// the whole document and diffing it against the working registry.
///
/// Otherwise identical to [`stage_runtime_snapshot`](Self::stage_runtime_snapshot): each op becomes a
/// hot frame, and the proto-node declaration bytes go to the byte store.
/// hot frame, is broadcast to any session, and the proto-node declaration bytes go to the byte store.
#[cfg(feature = "conversion")]
pub fn stage_constructed_ops(
&mut self,
ops: Vec<document_graph_storage::RegistryDelta>,
declaration_bytes: &document_graph_storage::from_runtime::DeclarationBytes,
byte_store: &dyn ResourceStorage,
) -> Result<(), Error> {
let hot_ops = self.session.stage_computed_ops(ops)?;
for hot_op in &hot_ops {
self.append_hot_frame(hot_op)?;
}
) -> Result<Vec<HotOp>, Error> {
let hot_ops = self.stage_ops(ops)?;
for bytes in declaration_bytes.values() {
byte_store.store(bytes);
}
Ok(())
Ok(hot_ops)
}
/// Retire every pending hot op into durable history as a single interaction (marking the batch's last
/// delta as the interaction boundary), then re-snapshot the registry. One interaction is one undo unit,
/// so the caller invokes this at each undo-step boundary and before any undo/redo. A no-op when there
/// are no pending hot ops.
pub fn retire_pending_interaction(&mut self) -> Result<Vec<Rev>, Error> {
let Some(up_to) = self.session.hot_log().iter().map(|hot_op| hot_op.timestamp).max() else {
return Ok(Vec::new());
};
self.retire_inner(up_to, true)
/// Stage raw registry ops as hot ops, for callers that don't go through the runtime diff.
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, Error> {
let hot_ops = self.session.stage_ops(ops)?;
self.persist_staged(&hot_ops)?;
Ok(hot_ops)
}
/// Every staged hot op takes this path, whether it came from a recorded batch, a whole-document diff or
/// a raw op: the frame that survives a crash, then the broadcast that reaches the room.
fn persist_staged(&mut self, hot_ops: &[HotOp]) -> Result<(), Error> {
if hot_ops.iter().any(|hot_op| !matches!(hot_op.op, RegistryDelta::EndTransaction)) {
self.own_staged_since_tick = true;
}
for hot_op in hot_ops {
self.append_hot_frame(hot_op)?;
}
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
replica.broadcast_hot_ops(hot_ops)?;
}
Ok(())
}
/// Commit a runtime snapshot as one complete interaction: stage it, then immediately retire it into
@@ -139,24 +154,34 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
/// Persist freshly-staged hot ops and immediately retire them into durable history. Appends each
/// hot frame (so a crash before retirement still recovers the work), then retires up to the last
/// staged timestamp, which drains exactly these ops and re-snapshots the registry. Returns the
/// retired `Rev`s. A no-op when nothing was staged.
/// Persist freshly-staged hot ops and immediately retire exactly them into durable history as one unit.
/// Appends each hot frame first, so a crash before retirement still recovers the work. Returns the
/// retired `Rev`s. A no-op when nothing was staged, and the ops stay hot on a peer that does not retire.
pub(crate) fn append_and_retire(&mut self, hot_ops: &[HotOp], interaction_end: bool) -> Result<Vec<Rev>, Error> {
let Some(last) = hot_ops.last() else { return Ok(Vec::new()) };
if hot_ops.is_empty() {
return Ok(Vec::new());
}
for hot_op in hot_ops {
self.append_hot_frame(hot_op)?;
}
if !self.retires_locally() {
return Ok(Vec::new());
}
self.retire_inner(last.timestamp, interaction_end)
let ids: Vec<_> = hot_ops.iter().map(HotOp::id).collect();
let revs = self.session.retire_hot_ops(&ids)?;
// Marked before the history frames are written, so the boundary is on disk with them.
if interaction_end && let Some(&last) = revs.last() {
self.session.mark_interaction_end(last);
}
self.finish_retirement(&revs, &ids)?;
Ok(revs)
}
/// Encode the history deltas identified by `revs` and append them to the history file. `revs` comes
/// from `Session::retire` in append order, which is a valid replay order, so a direct per-rev lookup
/// preserves replay order without scanning the whole history.
fn append_history_deltas(&mut self, revs: &[Rev]) -> Result<(), Error> {
pub(crate) fn append_history_deltas(&mut self, revs: &[Rev]) -> Result<(), Error> {
let mut buffer = Vec::new();
for &rev in revs {
let Some(delta) = self.session.delta(rev) else {
@@ -171,7 +196,7 @@ impl<L: Layout> Gdd<L> {
/// Set a local annotation (e.g. a commit message) on an existing retired delta and re-persist it.
/// Unlike the per-interaction marker written inline at retire, this targets an already-written delta, so
/// the whole history file is rewritten in topological order. O(history) — fine for occasional user
/// the whole history file is rewritten in topological order. O(history), fine for occasional user
/// labeling, not for per-interaction marking (which uses the inline path). No-op if `rev` is unknown.
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> Result<(), Error> {
if self.session.annotate_delta(rev, key, value) {
@@ -182,7 +207,7 @@ impl<L: Layout> Gdd<L> {
/// Rewrite the entire history file from the in-memory session. `history()` yields deltas in
/// topological (append) order, which is a valid replay order, so no separate sort is needed.
fn rewrite_history(&mut self) -> Result<(), Error> {
pub(crate) fn rewrite_history(&mut self) -> Result<(), Error> {
let mut buffer = Vec::new();
for delta in self.session.history() {
self.manifest.codecs.history.append(&mut buffer, delta)?;
@@ -191,13 +216,67 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
fn persist_session_state(&mut self) -> Result<(), Error> {
/// What people state about the history: users and their names, later labels and tags.
pub fn metadata(&self) -> &HistoryMetadata {
&self.metadata
}
/// State a fact about a user, `wall_ms` being now on the wall clock: put on record, persisted, and told
/// to the room when it changed anything. Returns whether it did.
pub fn record_user_attribute(&mut self, user: UserId, key: &str, value: serde_json::Value, wall_ms: f64) -> Result<bool, Error> {
let stamp = WallStamp {
ms: wall_ms.max(0.) as u64,
peer: self.session.peer(),
};
let Some(fact) = self.metadata.set_user_attribute(user, key, value, stamp) else {
return Ok(false);
};
self.append_facts(&[fact])?;
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
replica.send_metadata(&self.metadata)?;
}
Ok(true)
}
/// State a fact about a rev, the interaction it closes in the History panel's terms: a label or a tag. Put on
/// record, appended to the file, and told to the room when it changed anything. Returns whether it did.
pub fn record_rev_attribute(&mut self, rev: Rev, key: &str, value: serde_json::Value, wall_ms: f64) -> Result<bool, Error> {
let stamp = WallStamp {
ms: wall_ms.max(0.) as u64,
peer: self.session.peer(),
};
let Some(fact) = self.metadata.set_rev_attribute(rev, key, value, stamp) else {
return Ok(false);
};
self.append_facts(&[fact])?;
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
replica.send_metadata(&self.metadata)?;
}
Ok(true)
}
/// Append facts to the metadata file, one line each; the file is never rewritten.
pub(crate) fn append_facts(&mut self, facts: &[MetadataFact]) -> Result<(), Error> {
let mut buffer = Vec::new();
for fact in facts {
METADATA_CODEC.append(&mut buffer, fact)?;
}
self.working.append_non_blocking(&io::path_for(self.layout.metadata_basename(), METADATA_CODEC), &buffer)?;
Ok(())
}
pub(crate) fn persist_session_state(&mut self) -> Result<(), Error> {
let state = SessionState {
peer_id: self.session.peer(),
user_id: self.session.user(),
head_rev: self.session.head_rev(),
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
next_node_counter: self.session.next_node_counter(),
next_hot_sequence: self.session.next_hot_sequence(),
shared: self.shared,
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
@@ -209,7 +288,7 @@ impl<L: Layout> Gdd<L> {
/// registry to match the persisted `head`, so any cursor move (undo/redo) that rewinds the working
/// registry without retiring must re-persist it or a reopen would read a registry inconsistent with
/// `head`. Synchronous and hot-path-safe (`write_non_blocking`).
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
pub(crate) fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.registry())?;
Ok(())
}
@@ -238,45 +317,291 @@ impl<L: Layout> Gdd<L> {
self.persist_session_state()
}
fn append_hot_frame(&mut self, op: &HotOp) -> Result<(), Error> {
pub(crate) fn append_hot_frame(&mut self, op: &HotOp) -> Result<(), Error> {
let mut buffer = Vec::new();
self.manifest.codecs.hot_log.append(&mut buffer, op)?;
self.working.append_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &buffer)?;
Ok(())
}
/// Working-copy checkpoint: promote hot ops with timestamp `≤ up_to` into retired deltas,
/// append them to the history file, rewrite the hot log with remaining (unretired) ops, and
/// re-snapshot the registry. Synchronous.
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, Error> {
self.retire_inner(up_to, false)
/// How many closed transactions have to be waiting before they retire. Later retirement fuses more
/// of a gesture's ops into one delta and keeps more of what an undo can still rewind silently.
pub const RETIRE_AFTER_TRANSACTIONS: usize = 10;
/// How long a closed transaction sits before it may retire, so every peer has seen all of it.
pub const RETIRE_MIN_AGE_MS: f64 = 2_000.0;
/// How long anything waits at most: a quiet session still retires, and a transaction with a gap in
/// its author's run retires with what arrived.
pub const RETIRE_MAX_AGE_MS: f64 = 60_000.0;
/// Closes this peer's open transaction, if it has one, with a marker that reaches the room like any
/// other hot op. The editor calls this at each undo-step boundary.
pub fn end_transaction(&mut self) -> Result<(), Error> {
let staged = self.session.end_transaction()?;
self.persist_staged(&staged)?;
Ok(())
}
/// `interaction_end`: mark the batch's last delta as an interaction boundary (one undo unit) before its
/// history frame is written, so the marker persists on reopen without a later frame rewrite.
fn retire_inner(&mut self, up_to: TimeStamp, interaction_end: bool) -> Result<Vec<Rev>, Error> {
let new_revs = self.session.retire(up_to)?;
/// Undo this peer's latest transaction while it is still hot: the ops leave the hot log here and, once
/// the retraction reaches them, on every peer, and they never retire. Returns whether there was a hot
/// transaction to take back; `false` means the step already retired and undo has to move the cursor.
/// What the ops named lands in the remote changes, so a mirror brings those entities into line with
/// whatever others wrote to them meanwhile.
pub fn retract_transaction(&mut self) -> Result<Option<Vec<RegistryDelta>>, Error> {
let Some(document_graph_storage::Retraction { ids, touched, ops }) = self.session.retract_transaction()? else {
return Ok(None);
};
self.own_last_staged_ms = None;
#[cfg(feature = "network")]
self.remote_changes.touched.extend(touched);
#[cfg(not(feature = "network"))]
let _ = touched;
self.rewrite_hot_log()?;
self.persist_registry_snapshot()?;
self.persist_session_state()?;
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
replica.broadcast_retraction(&ids)?;
}
#[cfg(not(feature = "network"))]
let _ = ids;
Ok(Some(ops))
}
// Mark before `append_history_deltas` so the on-disk frame carries the boundary.
if interaction_end && let Some(&last) = new_revs.last() {
self.session.mark_interaction_end(last);
/// Undo this peer's latest retired step in a session, the one [`Session::latest_own_interaction`]
/// names. The retirer drops it out of the shared line itself and tells the room, and what the step
/// named lands in the remote changes for the mirror to follow; anyone else asks the retirer, and the
/// head move comes back through the poll like any remote change. `None` when this peer has no retired
/// step of its own on the line.
#[cfg(feature = "network")]
pub fn undo_retired_step(&mut self) -> Result<Option<Rev>, Error> {
let Some(rev) = self.session.latest_own_interaction() else {
return Ok(None);
};
self.drop_step(rev)?;
Ok(Some(rev))
}
/// Drop any retired interaction out of the line, by the retirer directly or on request, the later steps minted
/// again on its parent; see [`Session::drop_interaction`]. What it named lands in the remote changes for the
/// mirror to follow. Works alone too, where this peer is its own retirer.
#[cfg(feature = "network")]
pub fn drop_step(&mut self, rev: Rev) -> Result<(), Error> {
if self.retires_locally() {
let (moved, touched) = self.session.drop_interaction(rev)?;
self.remote_changes.touched.extend(touched);
if let Some(head) = self.session.head_rev() {
self.session.publish_up_to(head);
}
self.rewrite_history()?;
self.rewrite_hot_log()?;
self.persist_registry_snapshot()?;
self.persist_session_state()?;
if let Some(replica) = &mut self.network {
replica.broadcast_head_move(moved)?;
}
} else if let Some(replica) = &mut self.network {
replica.request_undo(rev, false)?;
}
Ok(())
}
/// Move the head to an ancestor in a session, everything since staying as a branch; see
/// [`Session::move_head_to`]. The retirer does it and tells the room; anyone else asks the retirer.
#[cfg(feature = "network")]
pub fn move_head(&mut self, rev: Rev) -> Result<(), Error> {
if self.retires_locally() {
let (moved, touched) = self.session.move_head_to(rev)?;
self.remote_changes.touched.extend(touched);
if let Some(head) = self.session.head_rev() {
self.session.publish_up_to(head);
}
self.persist_registry_snapshot()?;
self.persist_session_state()?;
if let Some(replica) = &mut self.network {
replica.broadcast_head_move(moved)?;
}
} else if let Some(replica) = &mut self.network {
replica.request_move(rev)?;
}
Ok(())
}
/// Redo a step [`undo_retired_step`](Self::undo_retired_step) dropped: it comes back as a copy on top
/// of the line, by the retirer, directly or on request.
#[cfg(feature = "network")]
pub fn redo_retired_step(&mut self, rev: Rev) -> Result<(), Error> {
if self.retires_locally() {
let revs = self.session.restore_interaction(rev)?;
let deltas: Vec<Delta> = revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
for delta in &deltas {
self.remote_changes.touched.record(&delta.kind);
}
if let Some(&last) = revs.last() {
self.session.publish_up_to(last);
}
self.rewrite_history()?;
self.rewrite_hot_log()?;
self.persist_registry_snapshot()?;
self.persist_session_state()?;
if let Some(replica) = &mut self.network {
replica.broadcast_retired(&deltas, &[])?;
}
} else if let Some(replica) = &mut self.network {
replica.request_undo(rev, true)?;
}
Ok(())
}
/// Stage ops a retraction took back, as a fresh transaction, noting what they name as a change for the
/// mirror to follow: the redo of a step taken back is a new edit to everyone, this peer included.
pub fn restage_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<(), Error> {
#[cfg(feature = "network")]
for op in &ops {
self.remote_changes.touched.record(op);
}
self.stage_ops(ops)?;
Ok(())
}
/// Retire every transaction the policy says is due at `now_ms`, on any monotonic millisecond clock the
/// caller keeps: closed transactions that have waited [`RETIRE_MIN_AGE_MS`](Self::RETIRE_MIN_AGE_MS),
/// once [`RETIRE_AFTER_TRANSACTIONS`](Self::RETIRE_AFTER_TRANSACTIONS) of them are waiting or the oldest
/// has waited [`RETIRE_MAX_AGE_MS`](Self::RETIRE_MAX_AGE_MS). An open transaction never retires, whoever
/// its author is. Called once a frame by the editor with whether it is between steps; a peer that does
/// not retire only closes its own transaction here, once it has gone quiet for the minimum age.
pub fn retire_due(&mut self, now_ms: f64, idle: bool) -> Result<Vec<Rev>, Error> {
// The editor's clock is the wall clock; retirements record it as the time a step happened.
self.wall_clock_ms = Some(now_ms);
// A gesture the editor never closed, or one interrupted by a reopen, closes on its own once quiet,
// but only while the editor is between steps: a pause inside a gesture must not split it, since undo
// takes a whole transaction back.
if self.own_staged_since_tick {
self.own_staged_since_tick = false;
self.own_last_staged_ms = Some(now_ms);
} else if idle && self.own_last_staged_ms.is_some_and(|last| now_ms - last >= Self::RETIRE_MIN_AGE_MS) {
self.end_transaction()?;
self.own_last_staged_ms = None;
}
if !self.retires_locally() {
return Ok(Vec::new());
}
let closed = self.session.closed_transactions();
let mut seen = std::mem::take(&mut self.transactions_seen);
let mut due = Vec::new();
let mut oldest_age: f64 = 0.0;
for transaction in &closed {
let Some(&marker) = transaction.ops.last() else { continue };
let age = now_ms - *seen.entry(marker).or_insert(now_ms);
if age >= Self::RETIRE_MIN_AGE_MS && (transaction.contiguous || age >= Self::RETIRE_MAX_AGE_MS) {
due.push(transaction.clone());
oldest_age = oldest_age.max(age);
}
}
seen.retain(|marker, _| closed.iter().any(|transaction| transaction.ops.last() == Some(marker)));
self.transactions_seen = seen;
if due.len() >= Self::RETIRE_AFTER_TRANSACTIONS || oldest_age >= Self::RETIRE_MAX_AGE_MS {
self.retire_transactions(&due)
} else {
Ok(Vec::new())
}
}
/// Close this peer's open transaction and retire every closed transaction, whoever its author is,
/// leaving other authors' open ones hot. The undo path takes this before moving the cursor, so the
/// interaction being undone is in history; a peer that does not retire only closes its own.
pub fn retire_pending_interaction(&mut self) -> Result<Vec<Rev>, Error> {
self.end_transaction()?;
self.own_last_staged_ms = None;
let closed = self.session.closed_transactions();
self.retire_transactions(&closed)
}
/// Retire the given closed transactions, each as one interaction, in one history append and one
/// broadcast. A no-op for a peer that leaves retirement to the session host.
pub fn retire_transactions(&mut self, transactions: &[document_graph_storage::ClosedTransaction]) -> Result<Vec<Rev>, Error> {
if !self.retires_locally() || transactions.is_empty() {
return Ok(Vec::new());
}
let mut revs = Vec::new();
let mut retired_hot_ops = Vec::new();
for transaction in transactions {
revs.extend(self.session.retire_transaction(transaction)?);
retired_hot_ops.extend(transaction.ops.iter().copied());
}
self.finish_retirement(&revs, &retired_hot_ops)?;
Ok(revs)
}
/// Working-copy checkpoint over a timestamp: promote every hot op stamped at or before `up_to` into
/// retired deltas, whatever its author and whether or not its transaction is closed. For callers
/// that own the whole log; a session retires by [`retire_transactions`](Self::retire_transactions).
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, Error> {
if !self.retires_locally() {
return Ok(Vec::new());
}
let retired_hot_ops = self.session.hot_ops_up_to(up_to);
let revs = self.session.retire(up_to)?;
self.finish_retirement(&revs, &retired_hot_ops)?;
Ok(revs)
}
/// What every retirement ends with: the published frontier moves, the deltas reach the history file,
/// the hot log and snapshot are rewritten, and the room hears about it.
fn finish_retirement(&mut self, new_revs: &[Rev], retired_hot_ops: &[document_graph_storage::HotOpId]) -> Result<(), Error> {
// Stamped before the frames are written, so the time is on disk with them and goes out with the broadcast.
if let Some(wall_ms) = self.wall_clock_ms
&& !new_revs.is_empty()
{
self.session.stamp_retired_at(new_revs, wall_ms as u64);
}
// In a session these deltas are about to reach peers, so the published frontier moves with them.
// Rewinding a commit peers already hold would diverge from them for good, with nothing on the wire
// to tell them, so undo past this point has to go through forward inverse ops instead. Set before
// the persists below so the frontier survives a reopen.
#[cfg(feature = "network")]
if self.network.is_some()
&& let Some(&last) = new_revs.last()
{
self.session.publish_up_to(last);
}
if !new_revs.is_empty() {
self.append_history_deltas(&new_revs)?;
self.append_history_deltas(new_revs)?;
}
// Rewrite hot log with whatever survived retirement.
let mut hot_buffer = Vec::new();
for hot_op in self.session.hot_log() {
self.manifest.codecs.hot_log.append(&mut hot_buffer, hot_op)?;
}
self.working
.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &hot_buffer)?;
self.rewrite_hot_log()?;
self.persist_registry_snapshot()?;
self.persist_session_state()?;
Ok(new_revs)
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
let deltas: Vec<_> = new_revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
replica.broadcast_retired(&deltas, retired_hot_ops)?;
}
#[cfg(not(feature = "network"))]
let _ = retired_hot_ops;
Ok(())
}
/// Guests leave retirement to the session host and keep their hot ops until the host's retired
/// deltas arrive.
fn retires_locally(&self) -> bool {
#[cfg(feature = "network")]
{
self.network.as_ref().is_none_or(|replica| replica.role() == peer_transport::Role::Host)
}
#[cfg(not(feature = "network"))]
true
}
pub(crate) fn rewrite_hot_log(&mut self) -> Result<(), Error> {
let mut buffer = Vec::new();
for hot_op in self.session.hot_log() {
self.manifest.codecs.hot_log.append(&mut buffer, hot_op)?;
}
self.working.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &buffer)?;
Ok(())
}
}
+36
View File
@@ -91,6 +91,36 @@ impl<L: Layout> Gdd<L> {
{
ResourceProxy(self.working.clone(), self.layout.clone())
}
/// Point resource lookups at an external store instead of the working copy, for an embedder that
/// already keeps one cache for every open document.
pub fn set_byte_store(&mut self, byte_store: Arc<dyn ResourceStorage>) {
self.byte_store = Some(byte_store);
}
/// Whether this document's resource bytes are on hand, in whichever store backs it.
pub fn holds_resource(&self, hash: &ResourceHash) -> bool {
match &self.byte_store {
Some(byte_store) => byte_store.contains(hash),
None => self.working.exists_non_blocking(&self.layout.resource_path(hash)),
}
}
/// Put resource bytes into whichever store backs this document.
pub fn hold_resource(&self, bytes: &[u8]) -> Result<(), ContainerError> {
match &self.byte_store {
Some(byte_store) => {
byte_store.store(bytes);
Ok(())
}
None => self.working.write_non_blocking(&self.layout.resource_path(&ResourceHash::from(bytes)), bytes),
}
}
/// Resources the registry or its history names whose bytes are not on hand.
pub fn unstored_resources(&self) -> Vec<ResourceHash> {
self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.holds_resource(hash)).collect()
}
}
impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
@@ -104,6 +134,12 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
pub struct ResourceProxy<T: Layout>(Arc<AnyContainer>, T);
impl<T: Layout + Clone> Clone for ResourceProxy<T> {
fn clone(&self) -> Self {
Self(self.0.clone(), self.1.clone())
}
}
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
Box::pin(async move {
+13 -1
View File
@@ -4,7 +4,7 @@
//!
//! Lives in `session.json`. Rewritten on retirement.
use document_graph_storage::{NetworkId, PeerId, Rev};
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev, UserId};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
@@ -15,6 +15,10 @@ pub struct SessionState {
/// tiebreaking and minting peer-scoped IDs.
#[serde(default)]
pub peer_id: PeerId,
/// The person using this device, from the editor's preferences: what the peer registers as in the CRDT,
/// so undo and authorship follow the person across the peer ids they accumulate. `0` until one is known.
#[serde(default)]
pub user_id: UserId,
/// Local-chain cursor. Points at the most recently applied retired delta, or `None` on an empty
/// document (no commits yet).
#[serde(default)]
@@ -39,4 +43,12 @@ pub struct SessionState {
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, serde_json::Value>>,
/// How many hot ops this peer has authored, feeding [`document_graph_storage::HotOp::sequence`]. A
/// reopen continues the run instead of reusing a spent sequence. Appended last: a positional codec
/// decodes these fields in declaration order.
#[serde(default)]
pub next_hot_sequence: HotSequence,
/// Whether the document was in its room when it was last persisted, so a reopen reconnects by itself.
#[serde(default)]
pub shared: bool,
}
+114
View File
@@ -0,0 +1,114 @@
// The record kept beside the history: what people state about the document's users, persisted with the
// working copy and merged with every copy met. Needs the network feature for a session and the runtime
// conversion for staging ops.
#![cfg(all(feature = "conversion", feature = "network"))]
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::from_runtime::DeclarationBytes;
use document_graph_storage::{Network, NetworkId, PeerId, RegistryDelta, Rev, TimeStamp, UserId, rev_attr, user_attr};
use peer_transport::mock::MockNetwork;
const NOW_MS: f64 = 1_700_000_000_000.;
async fn document(peer: u64, user: u64) -> GddV1 {
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(user), 1, "editor".into(), "stdlib".into())
.await
.expect("create")
}
/// Let the room settle: greetings, the sync handshake and whatever was broadcast, however many rounds it takes.
fn settle(network: &mut MockNetwork, peers: &mut [&mut GddV1]) {
for _ in 0..16 {
for peer in peers.iter_mut() {
peer.poll_peers();
}
network.deliver_all();
}
for peer in peers.iter_mut() {
peer.poll_peers();
}
}
#[test]
fn a_recorded_name_survives_a_reopen() {
futures::executor::block_on(async {
let mut gdd = document(1, 10).await;
assert!(gdd.record_user_attribute(UserId(10), user_attr::NAME, "Ada".into(), NOW_MS).expect("record"));
assert!(
!gdd.record_user_attribute(UserId(10), user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"),
"the same name is no change"
);
let step = Rev::new(7).expect("non-zero");
assert!(gdd.record_rev_attribute(step, rev_attr::LABEL, "Fixed the eye".into(), NOW_MS).expect("record"));
assert!(gdd.record_rev_attribute(step, "tag:v1", true.into(), NOW_MS).expect("record"));
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.expect("open");
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
assert_eq!(reopened.metadata().rev_label(step), Some("Fixed the eye"), "a label appended after the name is folded back in");
assert_eq!(reopened.metadata().rev_tags(step), vec!["v1"]);
});
}
#[test]
fn names_reach_the_room_with_the_sync_and_as_they_change() {
futures::executor::block_on(async {
let mut host = document(1, 10).await;
let mut guest = document(2, 20).await;
host.record_user_attribute(UserId(10), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
// A name given before joining travels with the joiner and reaches the host.
guest.record_user_attribute(UserId(20), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
let mut network = MockNetwork::new(1);
let host_endpoint = network.endpoint();
let guest_endpoint = network.endpoint();
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
host.share(host_endpoint, UserId(10));
guest.join(guest_endpoint, UserId(20));
network.connect(host_id);
network.connect(guest_id);
settle(&mut network, &mut [&mut host, &mut guest]);
assert!(guest.is_synced());
assert_eq!(guest.metadata().user_name(UserId(10)), Some("Ada"), "the host's record came with the sync");
assert_eq!(host.metadata().user_name(UserId(20)), Some("Bea"), "the guest's record came back to the host");
// A rename while in the room goes round on its own.
assert!(guest.record_user_attribute(UserId(20), user_attr::NAME, "Beatrix".into(), NOW_MS + 5_000.).expect("record"));
settle(&mut network, &mut [&mut host, &mut guest]);
assert_eq!(host.metadata().user_name(UserId(20)), Some("Beatrix"));
assert_eq!(host.metadata(), guest.metadata(), "both copies hold the same record");
});
}
#[test]
fn a_retirement_records_when_it_happened() {
futures::executor::block_on(async {
let mut gdd = document(1, 10).await;
// The editor's per-frame tick is where the wall clock comes from.
gdd.retire_due(NOW_MS, true).expect("tick");
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
gdd.stage_constructed_ops(
vec![RegistryDelta::AddNetwork {
id: NetworkId(9),
network: Network::default(),
}],
&DeclarationBytes::default(),
&byte_store,
)
.expect("stage");
let everything = TimeStamp {
counter: u64::MAX,
peer: PeerId(u64::MAX),
};
let revs = gdd.retire(everything).expect("retire");
assert!(!revs.is_empty());
for rev in revs {
let delta = gdd.session().delta(rev).expect("retired delta");
assert_eq!(delta.retired_at(), Some(NOW_MS as u64));
}
});
}
+36 -23
View File
@@ -5,7 +5,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
use document_graph_storage::{HotOp, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp, UserId};
fn empty_container() -> AnyContainer {
AnyContainer::Memory(MemoryBackend::new())
@@ -44,7 +44,7 @@ fn create_in_round_trips_empty_document() {
futures::executor::block_on(async {
let container = empty_container();
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()).await {
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), UserId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()).await {
Ok(gdd) => gdd,
Err(error) => panic!("create_in failed: {error:?}"),
};
@@ -82,7 +82,7 @@ fn open_in_rejects_wrong_format_magic() {
#[test]
fn manifest_returns_what_create_in_wrote() {
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into())
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), UserId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -99,7 +99,7 @@ fn manifest_returns_what_create_in_wrote() {
#[test]
fn update_manifest_changes_visible_after_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -116,7 +116,7 @@ fn update_manifest_changes_visible_after_reopen() {
#[test]
fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -128,6 +128,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
@@ -143,7 +144,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
#[test]
fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -154,6 +155,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
let late = HotOp {
op: RegistryDelta::AddNetwork {
@@ -161,6 +163,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
sequence: HotSequence(2),
};
gdd.apply_hot_op(early).unwrap();
gdd.apply_hot_op(late).unwrap();
@@ -189,7 +192,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
#[test]
fn last_broadcast_rev_persists_across_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -200,6 +203,7 @@ fn last_broadcast_rev_persists_across_reopen() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
gdd.apply_hot_op(op).unwrap();
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
@@ -220,7 +224,7 @@ fn export_folder_round_trips_through_open() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into())
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -250,7 +254,7 @@ fn export_zip_round_trips_via_deserialize() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into())
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), UserId(4), 0xCD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -277,7 +281,7 @@ fn export_rejects_invalid_options() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into())
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xEF, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -302,7 +306,7 @@ fn resource_round_trip_add_read_remove() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), UserId(99), 0xCAFE, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -334,7 +338,7 @@ fn resource_survives_reopen() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), UserId(7), 0xC0DE, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -365,7 +369,7 @@ fn resource_from_path_uses_fs_copy_on_folder_backend() {
// Need a folder-backed working copy to exercise the fs::copy path.
let working_dir = tempfile::tempdir().unwrap();
let working = AnyContainer::Folder(FolderBackend::create(working_dir.path()).unwrap());
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -391,7 +395,7 @@ fn export_carries_resources() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), UserId(2), 0xBC, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -421,7 +425,7 @@ fn embed_all_resources_materializes_link_only_resource() {
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), UserId(8), 0xF00D, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -488,7 +492,7 @@ fn export_materializes_embedded_resource_from_byte_store() {
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(9), 0xBEEF, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -531,7 +535,7 @@ fn export_round_trips_unretired_hot_ops() {
use graphene_resource::{DataSource, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xF15E, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -586,7 +590,7 @@ fn open_in_rejects_future_format_version() {
#[test]
fn create_in_records_default_codecs_in_manifest() {
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -609,7 +613,7 @@ fn first_commit_registers_peer_and_survives_reopen() {
use graphene_resource::ResourceRegistry;
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), UserId(21), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -630,11 +634,19 @@ fn first_commit_registers_peer_and_survives_reopen() {
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
assert_eq!(gdd.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "first commit registers the peer");
assert_eq!(
gdd.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
Some(UserId(21)),
"first commit registers the peer"
);
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
assert_eq!(reopened.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "registration survives reopen");
assert_eq!(
reopened.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
Some(UserId(21)),
"registration survives reopen"
);
});
}
@@ -645,7 +657,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
futures::executor::block_on(async {
use document_container::AsyncContainer;
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -655,6 +667,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
@@ -698,7 +711,7 @@ fn declarations_round_trip_through_byte_store() {
..Default::default()
};
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -0,0 +1,48 @@
// Needs the runtime conversion for `stage_constructed_ops` and the network feature for a session.
#![cfg(all(feature = "conversion", feature = "network"))]
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::from_runtime::DeclarationBytes;
use document_graph_storage::{Network, NetworkId, PeerId, RegistryDelta, UserId};
use peer_transport::mock::MockNetwork;
/// Every staging path has to reach the room. The recorded-batch path once appended its hot frames and
/// stopped there, so an edit made through the interface was persisted and never sent.
#[test]
fn staging_a_constructed_batch_reaches_the_room() {
futures::executor::block_on(async {
let mut host = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 1, "editor".into(), "stdlib".into())
.await
.expect("create");
let mut network = MockNetwork::new(1);
let host_endpoint = network.endpoint();
let guest_endpoint = network.endpoint();
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
host.share(host_endpoint, UserId(1));
network.connect(host_id);
network.connect(guest_id);
// Greeting the guest is what lets the host send to it; the hello itself is then out of the way.
host.poll_peers();
network.deliver_all();
assert_eq!(network.pending(), 0);
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
let staged = host
.stage_constructed_ops(
vec![RegistryDelta::AddNetwork {
id: NetworkId(9),
network: Network::default(),
}],
&DeclarationBytes::default(),
&byte_store,
)
.expect("stage");
assert!(!staged.is_empty(), "the staged hot ops come back for the caller");
assert!(network.pending() > 0, "a staged batch must be broadcast to the room");
});
}
+25 -4
View File
@@ -8,21 +8,42 @@ use std::collections::BTreeMap;
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
pub mod attr;
/// A type-erased attribute value paired with the timestamp at which it was last set.
/// A type-erased attribute value paired with the timestamp at which it was last set. A deleted key
/// stays as a stamped tombstone, so a write older than the deletion is recognised as older whichever
/// order the two land in; readers see a tombstone as absent.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Value {
pub value: serde_json::Value,
pub timestamp: TimeStamp,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub deleted: bool,
}
impl Value {
pub fn new(value: serde_json::Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp }
Self { value, timestamp, deleted: false }
}
/// The tombstone of a key deleted at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
value: serde_json::Value::Null,
timestamp,
deleted: true,
}
}
}
/// Attribute maps. Each entity carries an `attributes_timestamp` next to its map: when the map was last
/// written whole, by an addition or a whole-list input write. A key absent from the map is deleted as of
/// that stamp, so a write older than it is dropped, and a tombstone older than it is redundant.
pub type Attributes = BTreeMap<String, Value>;
/// The live entries of an attribute map: every key that is not a tombstone.
pub fn live(attributes: &Attributes) -> impl Iterator<Item = (&String, &Value)> {
attributes.iter().filter(|(_, value)| !value.deleted)
}
/// Write helpers for `Attributes`.
pub trait AttributesWrite {
/// Inserts a JSON value under `key`.
@@ -44,7 +65,7 @@ pub trait AttributesWrite {
impl AttributesWrite for Attributes {
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp) {
self.insert(key.to_string(), Value { value, timestamp });
self.insert(key.to_string(), Value::new(value, timestamp));
}
}
@@ -66,6 +87,6 @@ pub trait AttributesRead {
impl AttributesRead for Attributes {
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
self.get(key).and_then(|v| serde_json::from_value(v.value.clone()).ok())
self.get(key).filter(|v| !v.deleted).and_then(|v| serde_json::from_value(v.value.clone()).ok())
}
}
@@ -31,6 +31,7 @@ pub mod node {
pub mod session {
pub mod network {
pub const PREVIEWING: &str = "ui::previewing";
// TODO: Remove these graph ui nav-specific attributes
pub const NAV_PTZ: &str = "ui::nav::ptz";
pub const NAV_TRANSFORM: &str = "ui::nav::transform";
@@ -68,4 +69,7 @@ pub mod network {
pub mod delta {
/// Marks the last delta of a user interaction, so the undo cursor steps per-interaction, not per-delta.
pub const INTERACTION_END: &str = "interaction_end";
/// When the delta entered history, in wall-clock milliseconds since the Unix epoch as its retirer saw them.
/// For showing when a step happened; order always comes from the graph, never from this.
pub const RETIRED_AT: &str = "retired_at";
}
+32 -20
View File
@@ -1,4 +1,6 @@
use crate::{Attributes, AttributesWrite, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
use crate::{
Attributes, AttributesWrite, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev,
};
use graphene_resource::ResourceHash;
use serde::{Deserialize, Serialize};
@@ -76,6 +78,11 @@ impl Delta {
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == serde_json::Value::Bool(true))
}
/// When the delta entered history in wall-clock milliseconds, if its retirer recorded it.
pub fn retired_at(&self) -> Option<u64> {
self.attributes.get(attr::delta::RETIRED_AT).and_then(|recorded| recorded.value.as_u64())
}
/// The content-addressed `Rev` this delta's identity fields hash to. Equals `id` for a delta built
/// via `new`/`merge`; differs only if `id` was tampered with or the hash derivation changed.
pub fn recomputed_id(&self) -> Rev {
@@ -119,6 +126,15 @@ pub enum RegistryDelta {
id: NodeId,
inputs: Vec<InputSlot>,
},
/// A node's implementation, for swapping what it computes without rebuilding the node.
///
/// Removing and re-adding the node would express the same change, but would also clear every
/// attribute it carries, so restating them would clobber whatever a concurrent peer wrote to the
/// node's name, lock or pin.
SetNodeImplementation {
id: NodeId,
implementation: Implementation,
},
ChangeNodeAttribute {
id: NodeId,
delta: AttributeDelta,
@@ -195,6 +211,9 @@ pub enum RegistryDelta {
Merge {
extra_parents: Vec<Rev>,
},
/// The last op of its author's transaction. Changes nothing; retirement takes an author's ops through
/// one of these as one unit and drops the marker itself. See [`Session::closed_transactions`](crate::Session::closed_transactions).
EndTransaction,
// Allow for future delta types without a model change
Other(serde_json::Value),
}
@@ -209,28 +228,21 @@ pub struct AttributeDelta {
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
AttributeDelta {
key: delta.key.clone(),
value: attributes.get(&delta.key).map(|previous| previous.value.clone()),
value: attributes.get(&delta.key).filter(|previous| !previous.deleted).map(|previous| previous.value.clone()),
}
}
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, force: bool, attributes: &mut Attributes) {
/// Lands a single-key write. `floor` is when the map was last written whole: a key the map does not
/// hold is deleted as of then, so a write older than it is dropped. A deletion leaves a tombstone.
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, force: bool, attributes: &mut Attributes, floor: TimeStamp) {
let AttributeDelta { key, value } = delta;
match value {
Some(value) => match attributes.entry(key) {
std::collections::btree_map::Entry::Occupied(mut entry) => {
if force || timestamp > entry.get().timestamp {
entry.insert(Value { value, timestamp });
}
}
std::collections::btree_map::Entry::Vacant(entry) => {
entry.insert(Value { value, timestamp });
}
},
None => {
let should_remove = force || attributes.get(&key).is_none_or(|existing| timestamp > existing.timestamp);
if should_remove {
attributes.remove(&key);
}
}
let decided = attributes.get(&key).map_or(floor, |existing| existing.timestamp);
if !force && timestamp <= decided {
return;
}
let entry = match value {
Some(value) => Value::new(value, timestamp),
None => Value::deleted(timestamp),
};
attributes.insert(key, entry);
}
+11 -6
View File
@@ -166,14 +166,14 @@ fn diff_resource_entry(id: ResourceId, from: &ResourceEntry, to: &ResourceEntry,
deltas.push(RegistryDelta::SetResourceHash { id, hash: to.hash });
}
for (key, _) in &from.sources {
for (key, _) in from.live_sources() {
if to.source(key).is_none() {
deltas.push(RegistryDelta::RemoveSource { id, key: *key });
}
}
// Compare source bodies only; the per-source timestamp is derived from the diff, not part of it.
for (key, to_source) in &to.sources {
for (key, to_source) in to.live_sources() {
if from.source(key).is_none_or(|from_source| from_source.source != to_source.source) {
deltas.push(RegistryDelta::AddSource {
id,
@@ -196,15 +196,16 @@ fn nodes_have_same_implementation(a: &Node, b: &Node) -> bool {
fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) -> Vec<AttributeDelta> {
let mut deltas = Vec::new();
for key in from.keys() {
if !to.contains_key(key) {
let held = |attributes: &crate::Attributes, key: &str| attributes.get(key).filter(|value| !value.deleted).map(|value| value.value.clone());
for (key, _) in crate::attributes::live(from) {
if held(to, key).is_none() {
deltas.push(AttributeDelta { key: key.clone(), value: None });
}
}
// Compare by `value` only; the per-entry `timestamp` is derived from the diff, not part of it.
for (key, to_value) in to {
if from.get(key).is_none_or(|from_value| from_value.value != to_value.value) {
for (key, to_value) in crate::attributes::live(to) {
if held(from, key).is_none_or(|from_value| from_value != to_value.value) {
deltas.push(AttributeDelta {
key: key.clone(),
value: Some(to_value.value.clone()),
@@ -287,6 +288,7 @@ mod tests {
input: NodeInput::Import { index: 0 },
timestamp: TimeStamp::ORIGIN,
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
});
let deltas = compute_deltas(&from, &to);
@@ -344,6 +346,7 @@ mod tests {
crate::Value {
value: serde_json::json!("old"),
timestamp: stamp(0),
deleted: false,
},
);
from.node_instances.insert(NodeId(42), node);
@@ -354,6 +357,7 @@ mod tests {
crate::Value {
value: serde_json::json!("new"),
timestamp: stamp(1),
deleted: false,
},
);
@@ -379,6 +383,7 @@ mod tests {
crate::Value {
value: serde_json::json!("value"),
timestamp: stamp(1),
deleted: false,
},
);
File diff suppressed because it is too large. Load diff
+50 -38
View File
@@ -117,33 +117,17 @@ impl TryFrom<&NodeNetwork> for Registry {
pub type DeclarationBytes = HashMap<ResourceHash, Vec<u8>>;
/// A `from_runtime` conversion result: the reference-only [`Registry`] plus the proto-node
/// declaration *bytes* it extracted, keyed by content hash. `document-graph-storage` doesn't own a byte
/// store, so the caller (the `Gdd`) persists these into its content store; the registry only holds
/// the `ResourceId`/`ResourceHash` references.
/// declarations it extracted, as bytes keyed by content hash (for the caller's byte store) and as
/// decoded [`ProtoNode`]s keyed by id (for the caller's declaration cache).
pub struct RuntimeConversion {
pub registry: Registry,
pub declaration_bytes: DeclarationBytes,
pub declarations: crate::Declarations,
/// Each network's runtime `metadata_path` mapped to its stable storage `NetworkId`, for associating
/// per-network, per-peer view state (`session.json`) without re-deriving ids.
pub network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
}
impl RuntimeConversion {
/// Rebuild the [`Declarations`](crate::Declarations) map (`ResourceId` → [`ProtoNode`]) from the
/// extracted bytes, for callers that keep the bytes in hand instead of routing them through a
/// byte store (tests, the round-trip CLI). Editor/`Gdd` paths persist the bytes and resolve via
/// their byte store instead.
pub fn declarations(&self) -> Result<crate::Declarations, ConversionError> {
self.declaration_bytes
.iter()
.map(|(hash, bytes)| {
let proto = decode_declaration(bytes).map_err(|error| ConversionError::SerializationError(format!("declaration {hash}: {error}")))?;
Ok((ResourceId::from_hash(hash), proto))
})
.collect()
}
}
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through a self-describing
/// `serde_json::Value` (so serde aliases keep working and the on-disk shape stays migratable), then
/// rmp-serialized (which encodes the intermediate `Value` compactly). Paired with [`decode_declaration`].
@@ -177,6 +161,7 @@ impl Registry {
let mut ctx = ConversionContext {
declaration_ids: HashMap::new(),
declaration_bytes: HashMap::new(),
declarations: HashMap::new(),
network_ids: HashMap::new(),
metadata,
peer,
@@ -195,6 +180,7 @@ impl Registry {
Ok(RuntimeConversion {
registry,
declaration_bytes: ctx.declaration_bytes,
declarations: ctx.declarations,
network_ids: ctx.network_ids,
})
}
@@ -232,11 +218,13 @@ pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, i
peer,
};
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
// Built rather than written: the chain is put in place as converted, floor and all at the origin.
entry.force_set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
);
}
@@ -289,6 +277,8 @@ struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
declaration_ids: HashMap<String, ResourceId>,
/// Extracted declaration content keyed by hash, handed back for the caller's byte store.
declaration_bytes: DeclarationBytes,
/// The same declarations decoded, keyed by id, handed back for the caller's declaration cache.
declarations: crate::Declarations,
/// Maps each network's runtime `metadata_path` to its stable storage `NetworkId`, so the caller can
/// associate per-network, per-peer view state (in `session.json`) with networks without re-deriving ids.
network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
@@ -345,10 +335,18 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
.collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new();
write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
write_ui_network_attributes(&mut attributes, node_network, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
registry.networks.insert(network_id, Network { exports, attributes });
registry.networks.insert(
network_id,
Network {
presence: TimeStamp::ORIGIN,
exports,
attributes,
attributes_timestamp: TimeStamp::ORIGIN,
},
);
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
Ok(())
@@ -426,6 +424,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
input: convert_input(input, parent_path, network_id, ctx.ids(metadata_path))?,
timestamp,
attributes: input_attrs,
attributes_timestamp: timestamp,
});
}
@@ -458,9 +457,14 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
write_ui_attributes(&mut attributes, ctx.metadata, metadata_path, runtime_node_id, timestamp)?;
Ok(Node {
presence: timestamp,
added: timestamp,
inputs_timestamp: timestamp,
implementation,
implementation_timestamp: timestamp,
inputs,
attributes,
attributes_timestamp: timestamp,
network: network_id,
})
}
@@ -554,20 +558,25 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
/// does it: a runtime ID is not stable across a round trip.
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
node_network: &NodeNetwork,
network_path: &[RuntimeNodeId],
parent_path: Option<&NodePath>,
network_id: NetworkId,
ids: NodeIds<'_, M>,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
// The same source the IDs resolve through, so a network's attributes and the nodes they name agree.
let Some(metadata) = ids.metadata else { return Ok(()) };
if let Some(reference) = metadata.reference(network_path) {
attributes.set(node::ui::REFERENCE, serde_json::Value::String(reference.to_string()), timestamp);
}
let to_storage_id = |runtime_id: RuntimeNodeId| ids.resolve(&child_path(parent_path, network_id, runtime_id), runtime_id);
let pinned_order = metadata.pinned_order(network_path);
// Only nodes the converted network still holds: the read side drops a stored ID it cannot find, so
// persisting one for a node deleted or reparented elsewhere would leave stored state disagreeing with
// what a peer converting the same input produces.
let pinned_order: Vec<_> = metadata.pinned_order(network_path).into_iter().filter(|pinned| node_network.nodes.contains_key(pinned)).collect();
if !pinned_order.is_empty() {
let stored: Vec<NodeId> = pinned_order.into_iter().map(to_storage_id).collect();
attributes
@@ -626,7 +635,7 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
}
/// The non-ui attributes a slot carries, derived from the input itself: the declared type of an
/// import, and a reflection node.s metadata. Public for staging paths that rebuild a node.s slots.
/// import, and a reflection node's metadata.
pub fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
let mut attributes = crate::Attributes::new();
let timestamp = TimeStamp::ORIGIN;
@@ -677,6 +686,7 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
register_declaration_resource(registry, id, hash, ctx.peer);
ctx.declaration_bytes.insert(hash, bytes);
ctx.declarations.insert(id, proto);
ctx.declaration_ids.insert(identifier_str, id);
Implementation::ProtoNode(id)
@@ -770,6 +780,7 @@ impl<'m> ScopedConversion<'m> {
ctx: ConversionContext {
declaration_ids: HashMap::new(),
declaration_bytes: HashMap::new(),
declarations: HashMap::new(),
network_ids: HashMap::new(),
metadata,
peer,
@@ -814,24 +825,25 @@ impl<'m> ScopedConversion<'m> {
.collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new();
write_ui_network_attributes(
&mut attributes,
self.ctx.metadata,
local_path,
owner_path.as_ref(),
network_id,
self.ctx.ids(local_path),
TimeStamp::ORIGIN,
)?;
write_ui_network_attributes(&mut attributes, node_network, local_path, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
registry.networks.insert(network_id, Network { exports, attributes });
registry.networks.insert(
network_id,
Network {
presence: TimeStamp::ORIGIN,
exports,
attributes,
attributes_timestamp: TimeStamp::ORIGIN,
},
);
Ok(())
}
/// The extracted proto-node declaration bytes, for the caller to persist into its byte store.
pub fn finish(self) -> DeclarationBytes {
self.ctx.declaration_bytes
/// The extracted proto-node declarations: the bytes for the caller's byte store, and the same
/// declarations decoded for its declaration cache.
pub fn finish(self) -> (DeclarationBytes, crate::Declarations) {
(self.ctx.declaration_bytes, self.ctx.declarations)
}
}
+123 -18
View File
@@ -8,16 +8,27 @@
//! construction. The only operation that introduces out-of-order deltas is [`merge`](History::merge),
//! which re-sorts the combined set into the canonical order to restore the invariant.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp};
use crate::{AttributesWrite, CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp};
/// The indexes are maintained by every mutator, so the questions the per-frame and per-interaction
/// paths ask (is this timestamp retired, what are the tips, which hashes does history name) are probes
/// rather than scans of a history that only ever grows.
#[derive(Clone, Debug, Default)]
pub struct History {
/// Deltas in topological order. Mutated only via [`push`](Self::push).
deltas: Vec<Delta>,
/// `Rev` to its position in `deltas`. Kept in sync with `deltas` by every mutator.
index: HashMap<Rev, usize>,
/// The timestamps the deltas were authored at.
timestamps: HashSet<TimeStamp>,
/// Every rev some delta names as a parent.
referenced: HashSet<Rev>,
/// Deltas no other delta names as a parent.
tips: HashSet<Rev>,
/// Content hashes the deltas name, from resource additions and removals.
resource_hashes: HashSet<ResourceHash>,
}
impl History {
@@ -27,8 +38,16 @@ impl History {
/// Build from deltas already in topological order (the on-disk load path), indexing them in place.
pub fn from_ordered(deltas: Vec<Delta>) -> Self {
let index = deltas.iter().enumerate().map(|(position, delta)| (delta.id, position)).collect();
Self { deltas, index }
let mut history = Self::default();
for delta in deltas {
history.push(delta);
}
history
}
/// Where `rev` sits in the file order, if it is here.
pub fn position(&self, rev: Rev) -> Option<usize> {
self.index.get(&rev).copied()
}
pub fn get(&self, rev: Rev) -> Option<&Delta> {
@@ -39,6 +58,35 @@ impl History {
self.index.contains_key(&rev)
}
/// Whether history holds a delta authored at `timestamp`.
pub fn contains_timestamp(&self, timestamp: TimeStamp) -> bool {
self.timestamps.contains(&timestamp)
}
/// The content hashes named by any resource addition or removal in history.
pub fn resource_hashes(&self) -> &HashSet<ResourceHash> {
&self.resource_hashes
}
/// Whether the deltas from `from` on extend the canonical order as they stand: a chain, each the
/// first's child in turn, hanging off the last delta before them. Such a tail is what every
/// retirement in a hosted session appends, and needs no re-sort.
///
/// The sort emits, among the deltas whose parents are all out, the lowest rev. A chain on the last
/// delta is alone in that set at every step, so it sorts where it was appended. A tail whose root
/// hangs off an earlier delta competes with that delta's later siblings and may sort before them.
pub fn extends_canonically(&self, from: usize) -> bool {
let Some(tail) = self.deltas.get(from..) else { return true };
let mut previous = from.checked_sub(1).map(|position| self.deltas[position].id);
for delta in tail {
if delta.parent != previous || matches!(delta.kind, RegistryDelta::Merge { .. }) {
return false;
}
previous = Some(delta.id);
}
true
}
pub fn len(&self) -> usize {
self.deltas.len()
}
@@ -51,10 +99,23 @@ impl History {
/// (idempotent re-apply) overwrites the existing entry in place rather than appending, so the
/// order and index are unchanged.
pub fn push(&mut self, delta: Delta) {
self.timestamps.insert(delta.timestamp);
match &delta.kind {
RegistryDelta::AddResource { entry, .. } => self.resource_hashes.extend(entry.hash),
RegistryDelta::RemoveResource { snapshot, .. } => self.resource_hashes.extend(snapshot.hash),
_ => {}
}
if let Some(&position) = self.index.get(&delta.id) {
self.deltas[position] = delta;
return;
}
for parent in delta.all_parents() {
self.referenced.insert(parent);
self.tips.remove(&parent);
}
if !self.referenced.contains(&delta.id) {
self.tips.insert(delta.id);
}
self.index.insert(delta.id, self.deltas.len());
self.deltas.push(delta);
}
@@ -64,22 +125,17 @@ impl History {
self.deltas.iter()
}
/// Absorb `incoming` (dedup by `Rev`) and canonically re-sort the whole combined history.
///
/// The sort is deterministic (topological, ties broken by `Rev`), so two peers that absorb the same
/// delta set produce byte-identical history, not merely two different valid orderings. This is the
/// history-convergence mechanism: arrival order is erased. Callers update the registry separately
/// (LWW apply is commutative, so the registry converges regardless of order).
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) {
for delta in incoming {
self.push(delta);
}
self.canonical_sort();
/// The delta at `position` in topological order.
pub fn at(&self, position: usize) -> Option<&Delta> {
self.deltas.get(position)
}
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
fn canonical_sort(&mut self) {
///
/// Deterministic: two peers that absorb the same delta set end up with byte-identical history, not two
/// different valid orderings. Arrival order is erased.
pub fn canonical_sort(&mut self) {
// Unsatisfied in-history parent count per delta, plus reverse edges to decrement as parents emit.
let mut pending_parents: HashMap<Rev, usize> = HashMap::with_capacity(self.deltas.len());
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
@@ -119,11 +175,60 @@ impl History {
}
}
/// `roots` and everything reachable from them through all parent links. Unknown roots are skipped.
pub fn ancestors(&self, roots: impl IntoIterator<Item = Rev>) -> HashSet<Rev> {
let mut seen = HashSet::new();
let mut stack: Vec<Rev> = roots.into_iter().filter(|rev| self.contains(*rev)).collect();
while let Some(rev) = stack.pop() {
if !seen.insert(rev) {
continue;
}
if let Some(delta) = self.get(rev) {
stack.extend(delta.all_parents());
}
}
seen
}
pub fn is_ancestor(&self, ancestor: Rev, descendant: Rev) -> bool {
self.ancestors([descendant]).contains(&ancestor)
}
/// `tip` plus the revs at first-parent distance 1, 2, 4, 8, ... behind it. Sent to a remote peer
/// so it can locate the divergence point within a factor of two of the true distance.
pub fn sample_chain(&self, tip: Rev) -> Vec<Rev> {
let mut samples = vec![tip];
let mut current = tip;
let mut distance = 0;
let mut next_sample_distance = 1;
while let Some(parent) = self.get(current).and_then(|delta| delta.parent) {
current = parent;
distance += 1;
if distance == next_sample_distance {
samples.push(current);
next_sample_distance *= 2;
}
}
// The root always: two copies of one document share it however far their lines have diverged, so
// a peer answering the sample can tell a divergent copy from a stranger and merge rather than replace.
if samples.last() != Some(&current) {
samples.push(current);
}
samples
}
/// Every delta not reachable from the `known` revs the remote peer reported, in topological order.
pub fn deltas_unknown_to(&self, known: impl IntoIterator<Item = Rev>) -> Vec<&Delta> {
let known = self.ancestors(known);
self.deltas.iter().filter(|delta| !known.contains(&delta.id)).collect()
}
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
pub fn tips(&self) -> Vec<Rev> {
let referenced: std::collections::HashSet<Rev> = self.deltas.iter().flat_map(|delta| delta.all_parents()).collect();
let mut tips: Vec<Rev> = self.deltas.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
let mut tips: Vec<Rev> = self.tips.iter().copied().collect();
tips.sort_unstable();
tips
}
@@ -0,0 +1,283 @@
//! What people say about a document's history, kept beside it rather than in it: who its users are, what
//! its steps are called and which are tagged. None of it is folded into the document, so moving the head
//! never changes it and stating it never rewrites a delta. Every statement is a [`MetadataFact`] with a
//! wall-clock stamp, the newer of two about the same thing winning, which makes the record a state that
//! merges the same in any order and any number of times. On disk the facts are appended one per line and
//! folded on read, so a rename appends one line and nothing is ever rewritten.
use crate::ids::{PeerId, Rev, UserId};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// When a fact was stated and by whom: milliseconds since the Unix epoch, the peer breaking ties.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct WallStamp {
pub ms: u64,
pub peer: PeerId,
}
/// What a fact is about.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum Subject {
User(UserId),
Rev(Rev),
}
/// One statement: an attribute of a user or of a rev, with its stamp. The unit of the file and of a merge.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataFact {
pub subject: Subject,
pub key: String,
pub value: serde_json::Value,
pub stamp: WallStamp,
}
/// One stated value with its stamp, as the folded record holds it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Fact {
pub value: serde_json::Value,
pub stamp: WallStamp,
}
/// Everything on record about one user.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UserRecord {
pub user: UserId,
pub attributes: BTreeMap<String, Fact>,
}
/// Everything on record about one rev: the interaction it closes, in the History panel's terms.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RevRecord {
pub rev: Rev,
pub attributes: BTreeMap<String, Fact>,
}
/// The attribute keys the editor writes for a user.
pub mod user_attr {
/// The display name the user chose. Absent or empty means unnamed.
pub const NAME: &str = "name";
}
/// The attribute keys the editor writes for a rev.
pub mod rev_attr {
/// The name a person gave the interaction the rev closes. Absent or empty means unnamed.
pub const LABEL: &str = "label";
/// A tag on the rev, one key per tag name after this prefix; `true` while it stands, `false` once removed.
pub const TAG_PREFIX: &str = "tag:";
}
/// The folded record. Users and revs are kept sorted so two copies holding the same facts serialize alike.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct HistoryMetadata {
#[serde(default)]
pub users: Vec<UserRecord>,
#[serde(default)]
pub revs: Vec<RevRecord>,
}
impl HistoryMetadata {
pub fn is_empty(&self) -> bool {
self.users.is_empty() && self.revs.is_empty()
}
/// The record folded from facts in file order: each fact lands unless a newer one about the same thing stands.
pub fn fold(facts: impl IntoIterator<Item = MetadataFact>) -> Self {
let mut record = Self::default();
for fact in facts {
record.absorb(fact);
}
record
}
/// Every fact the record holds, users first then revs, for writing it out whole.
pub fn facts(&self) -> Vec<MetadataFact> {
let users = self.users.iter().flat_map(|record| {
record.attributes.iter().map(|(key, fact)| MetadataFact {
subject: Subject::User(record.user),
key: key.clone(),
value: fact.value.clone(),
stamp: fact.stamp,
})
});
let revs = self.revs.iter().flat_map(|record| {
record.attributes.iter().map(|(key, fact)| MetadataFact {
subject: Subject::Rev(record.rev),
key: key.clone(),
value: fact.value.clone(),
stamp: fact.stamp,
})
});
users.chain(revs).collect()
}
pub fn user(&self, user: UserId) -> Option<&UserRecord> {
self.users.binary_search_by_key(&user, |record| record.user).ok().map(|index| &self.users[index])
}
pub fn user_attribute(&self, user: UserId, key: &str) -> Option<&Fact> {
self.user(user)?.attributes.get(key)
}
/// The user's display name, if one is on record and not empty.
pub fn user_name(&self, user: UserId) -> Option<&str> {
self.user_attribute(user, user_attr::NAME)?.value.as_str().filter(|name| !name.is_empty())
}
pub fn rev(&self, rev: Rev) -> Option<&RevRecord> {
self.revs.binary_search_by_key(&rev, |record| record.rev).ok().map(|index| &self.revs[index])
}
pub fn rev_attribute(&self, rev: Rev, key: &str) -> Option<&Fact> {
self.rev(rev)?.attributes.get(key)
}
/// The name a person gave the interaction `rev` closes, if any and not empty.
pub fn rev_label(&self, rev: Rev) -> Option<&str> {
self.rev_attribute(rev, rev_attr::LABEL)?.value.as_str().filter(|label| !label.is_empty())
}
/// The tags standing on `rev`, in name order.
pub fn rev_tags(&self, rev: Rev) -> Vec<&str> {
let Some(record) = self.rev(rev) else { return Vec::new() };
record
.attributes
.iter()
.filter(|(_, fact)| fact.value == serde_json::Value::Bool(true))
.filter_map(|(key, _)| key.strip_prefix(rev_attr::TAG_PREFIX))
.collect()
}
/// State a fact about a user. Nothing changes when the same value already stands, whatever its stamp;
/// otherwise the fact is stamped no earlier than the one it replaces, so a clock behind a peer's still
/// gets its say. Returns the fact as stated, for appending to the file and telling the room.
pub fn set_user_attribute(&mut self, user: UserId, key: &str, value: serde_json::Value, stamp: WallStamp) -> Option<MetadataFact> {
self.state(Subject::User(user), key, value, stamp)
}
/// State a fact about a rev; see [`set_user_attribute`](Self::set_user_attribute).
pub fn set_rev_attribute(&mut self, rev: Rev, key: &str, value: serde_json::Value, stamp: WallStamp) -> Option<MetadataFact> {
self.state(Subject::Rev(rev), key, value, stamp)
}
fn state(&mut self, subject: Subject, key: &str, value: serde_json::Value, mut stamp: WallStamp) -> Option<MetadataFact> {
let attributes = self.attributes_mut(subject);
if let Some(existing) = attributes.get(key) {
if existing.value == value {
return None;
}
if stamp <= existing.stamp {
stamp.ms = existing.stamp.ms + 1;
}
}
attributes.insert(key.to_string(), Fact { value: value.clone(), stamp });
Some(MetadataFact {
subject,
key: key.to_string(),
value,
stamp,
})
}
/// Take on one fact as stated elsewhere: it lands unless an equal or newer stamp stands for the same thing.
/// Returns whether it landed.
pub fn absorb(&mut self, fact: MetadataFact) -> bool {
let attributes = self.attributes_mut(fact.subject);
if attributes.get(&fact.key).is_some_and(|mine| fact.stamp <= mine.stamp) {
return false;
}
attributes.insert(fact.key, Fact { value: fact.value, stamp: fact.stamp });
true
}
/// Take on another copy's record: for every key, the newer stamp wins. Returns the facts that landed, for
/// appending to the file.
pub fn merge(&mut self, other: &Self) -> Vec<MetadataFact> {
other.facts().into_iter().filter(|fact| self.absorb(fact.clone())).collect()
}
fn attributes_mut(&mut self, subject: Subject) -> &mut BTreeMap<String, Fact> {
match subject {
Subject::User(user) => {
let index = match self.users.binary_search_by_key(&user, |record| record.user) {
Ok(index) => index,
Err(index) => {
self.users.insert(index, UserRecord { user, attributes: BTreeMap::new() });
index
}
};
&mut self.users[index].attributes
}
Subject::Rev(rev) => {
let index = match self.revs.binary_search_by_key(&rev, |record| record.rev) {
Ok(index) => index,
Err(index) => {
self.revs.insert(index, RevRecord { rev, attributes: BTreeMap::new() });
index
}
};
&mut self.revs[index].attributes
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn stamp(ms: u64, peer: u64) -> WallStamp {
WallStamp { ms, peer: PeerId(peer) }
}
fn rev(n: u128) -> Rev {
Rev::new(n).expect("non-zero")
}
#[test]
fn the_newer_fact_wins_whatever_order_the_copies_meet_in() {
let mut a = HistoryMetadata::default();
let mut b = HistoryMetadata::default();
assert!(a.set_user_attribute(UserId(1), user_attr::NAME, "Ada".into(), stamp(10, 1)).is_some());
assert!(b.set_user_attribute(UserId(1), user_attr::NAME, "Ada L.".into(), stamp(20, 2)).is_some());
let mut ab = a.clone();
assert_eq!(ab.merge(&b).len(), 1);
let mut ba = b.clone();
assert!(ba.merge(&a).is_empty());
assert_eq!(ab, ba);
assert_eq!(ab.user_name(UserId(1)), Some("Ada L."));
assert!(ab.merge(&b).is_empty(), "merging again changes nothing");
}
#[test]
fn a_clock_behind_a_peers_still_gets_its_say() {
let mut record = HistoryMetadata::default();
record.set_user_attribute(UserId(1), user_attr::NAME, "Ada".into(), stamp(100, 2));
let stated = record.set_user_attribute(UserId(1), user_attr::NAME, "Countess".into(), stamp(5, 1)).expect("a change");
assert_eq!(stated.stamp.ms, 101);
assert_eq!(record.user_name(UserId(1)), Some("Countess"));
assert!(
record.set_user_attribute(UserId(1), user_attr::NAME, "Countess".into(), stamp(500, 1)).is_none(),
"the same value is no change"
);
}
#[test]
fn the_fold_of_the_facts_is_the_record_and_back() {
let mut record = HistoryMetadata::default();
record.set_user_attribute(UserId(9), user_attr::NAME, "".into(), stamp(1, 1));
record.set_user_attribute(UserId(3), user_attr::NAME, "Bea".into(), stamp(1, 1));
record.set_rev_attribute(rev(7), rev_attr::LABEL, "Fixed the eye".into(), stamp(2, 1));
record.set_rev_attribute(rev(7), "tag:v1", true.into(), stamp(3, 1));
record.set_rev_attribute(rev(7), "tag:draft", false.into(), stamp(4, 1));
assert_eq!(record.user_name(UserId(9)), None);
assert_eq!(record.users.iter().map(|record| record.user).collect::<Vec<_>>(), vec![UserId(3), UserId(9)]);
assert_eq!(record.rev_label(rev(7)), Some("Fixed the eye"));
assert_eq!(record.rev_tags(rev(7)), vec!["v1"]);
let facts = record.facts();
assert_eq!(facts.len(), 5);
assert_eq!(HistoryMetadata::fold(facts), record);
}
}
+2
View File
@@ -56,6 +56,8 @@ pub const ROOT_NETWORK: NetworkId = NetworkId(0);
/// Upper bound on a network's export slot count, guarding `SetExport` against a malicious or corrupted
/// slot index forcing an unbounded `exports` allocation.
pub(crate) const MAX_EXPORT_SLOTS: usize = 1 << 16;
/// A per-slot write can bring a slot past the end of the list into being, so it is capped the same way.
pub(crate) const MAX_INPUT_SLOTS: usize = 1 << 16;
/// Per-device identity. Stable per `(device, document)`. Used for CRDT tiebreaking and `NodeId`
/// scoping. Globally unique across all peers ever in a document.
+7 -1
View File
@@ -5,11 +5,13 @@ pub mod crdt;
pub mod delta;
pub mod document;
pub mod history;
pub mod history_metadata;
pub mod ids;
pub mod model;
pub mod registry;
pub mod resources;
pub mod session;
pub mod touched;
#[cfg(any(feature = "conversion", test))]
pub mod from_runtime;
@@ -22,11 +24,13 @@ pub use attributes::*;
pub use crdt::*;
pub use document::*;
pub use history::History;
pub use history_metadata::{Fact, HistoryMetadata, MetadataFact, RevRecord, Subject, UserRecord, WallStamp, rev_attr, user_attr};
pub use ids::*;
pub use model::*;
pub use registry::*;
pub use resources::*;
pub use session::*;
pub use touched::Touched;
#[cfg(any(feature = "conversion", test))]
pub use from_runtime::{
@@ -36,10 +40,12 @@ pub use from_runtime::{
#[cfg(any(feature = "conversion", test))]
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
#[cfg(any(feature = "conversion", test))]
pub use to_runtime::Declarations;
pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProjection};
#[cfg(test)]
mod tests {
mod bookkeeping;
mod crdt;
mod projection;
mod round_trip;
}
@@ -38,10 +38,9 @@ pub struct NetworkMetadataEntry {
/// Stable storage id of this network. Lets the editor associate per-network, per-peer view state
/// (the node-graph nav, in `session.json`) with a network across reparenting.
pub network_id: crate::NetworkId,
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference` — definition lineage tag.
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference`: the definition lineage tag.
pub reference: Option<String>,
/// The display order of the network's pinned nodes. Shared for the same reason the pinned flag is:
/// a shared set with per-peer ordering could never reconcile.
/// The display order of the network's pinned nodes.
pub pinned_order: Vec<RuntimeNodeId>,
}
@@ -98,9 +97,12 @@ pub trait NodeMetadataSource {
fn storage_node_id(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<crate::NodeId> {
None
}
/// The definition the network was instantiated from, if it still names one.
fn reference(&self, _network_path: &[RuntimeNodeId]) -> Option<&str> {
None
}
/// The display order of the network's pinned nodes.
fn pinned_order(&self, _network_path: &[RuntimeNodeId]) -> Vec<RuntimeNodeId> {
Vec::new()
+89
View File
@@ -4,9 +4,29 @@ use std::borrow::Cow;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
/// When the node was last added, so a concurrent addition of the same id and a removal resolve by
/// last-writer-wins rather than by arrival order. See [`Registry::removed_nodes`](crate::Registry::removed_nodes).
#[serde(default)]
pub(crate) presence: TimeStamp,
/// When the node was last added, which is what decides its network between concurrent additions
/// of one id; every other field carries its own timestamp.
#[serde(default)]
pub(crate) added: TimeStamp,
/// When the input list last changed shape, so a whole-list write and a per-slot write resolve the
/// same whichever lands first: the list follows the newer of the two, and a slot the older list also
/// held keeps whichever of its values is newer.
#[serde(default)]
pub(crate) inputs_timestamp: TimeStamp,
pub(crate) implementation: Implementation,
/// When the implementation was last written, so a swap resolves by last-writer-wins rather than by
/// the order ops happen to arrive in. Absent from documents written before swaps were expressible.
#[serde(default)]
pub(crate) implementation_timestamp: TimeStamp,
pub(crate) inputs: Vec<InputSlot>,
pub(crate) attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub(crate) attributes_timestamp: TimeStamp,
pub(crate) network: NetworkId,
}
@@ -43,12 +63,42 @@ impl Node {
attributes_value_equal(&self.attributes, &other.attributes)
}
/// A node in `network` whose `inputs` slots are unset, for a caller that fills them in with
/// `ChangeNodeInput`. The slot count is fixed at creation, since changing an input addresses a
/// slot by position.
pub fn new(network: NetworkId, implementation: Implementation, inputs: usize) -> Self {
let slot = InputSlot::unset(TimeStamp::ORIGIN);
Self {
presence: TimeStamp::ORIGIN,
added: TimeStamp::ORIGIN,
inputs_timestamp: TimeStamp::ORIGIN,
implementation,
implementation_timestamp: TimeStamp::ORIGIN,
inputs: vec![slot; inputs],
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
network,
}
}
/// Dead content for a node nothing has added yet, so a write arriving ahead of the addition has
/// somewhere to land. Every field is at the origin, so the addition's values win when it comes.
pub(crate) fn placeholder() -> Self {
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(0)), 0)
}
#[cfg(test)]
pub(crate) fn dummy() -> Self {
Self {
presence: TimeStamp::ORIGIN,
added: TimeStamp::ORIGIN,
inputs_timestamp: TimeStamp::ORIGIN,
implementation: Implementation::ProtoNode(ResourceId::new()),
implementation_timestamp: TimeStamp::default(),
inputs: vec![],
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
network: crate::ROOT_NETWORK,
}
}
@@ -61,6 +111,26 @@ pub struct InputSlot {
pub input: NodeInput,
pub timestamp: TimeStamp,
pub attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub attributes_timestamp: TimeStamp,
}
impl InputSlot {
/// A slot holding nothing, stamped `at`.
pub fn unset(at: TimeStamp) -> Self {
// `to_runtime` reads this back as a `TaggedValue`, whose unit `None` variant encodes as this string.
// Pinned by `unset_input_slot_deserializes_as_tagged_value_none`.
Self {
input: NodeInput::Value {
value: serde_json::Value::String("None".to_string()),
exposed: false,
},
timestamp: at,
attributes: Attributes::new(),
attributes_timestamp: at,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -92,10 +162,16 @@ pub enum Implementation {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Network {
/// When the network was last added; see [`Node::presence`].
#[serde(default)]
pub presence: TimeStamp,
pub exports: Vec<ExportSlot>,
/// Per-network `ui::*` state (navigation, previewing). Separate from `Node.attributes` so
/// view-state edits LWW independently.
pub attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub attributes_timestamp: TimeStamp,
}
impl Network {
@@ -154,6 +230,19 @@ mod tests {
}
}
/// `to_runtime` has to read back what `Node::new` writes into an unset slot, so its literal must stay
/// in step with how `TaggedValue::None` serializes.
#[test]
fn unset_input_slot_deserializes_as_tagged_value_none() {
let node = Node::new(crate::ROOT_NETWORK, Implementation::Network(crate::ROOT_NETWORK), 1);
let NodeInput::Value { value, .. } = &node.inputs()[0].input else {
panic!("a fresh slot holds a value input");
};
let tagged: graph_craft::document::value::TaggedValue = serde_json::from_value(value.clone()).expect("the unset slot value must deserialize");
assert_eq!(tagged, graph_craft::document::value::TaggedValue::None);
}
/// A `SetExport(None)` truncation leaves a trailing empty slot. Such a network is value-equal to
/// the same network without that slot, so the soak oracle doesn't false-report drift.
#[test]
+63 -8
View File
@@ -1,7 +1,14 @@
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// The live document: what exists and what it holds.
///
/// Every field is last-writer-wins on a timestamp, including whether an entity exists, so the registry
/// is a function of the set of ops applied and not of their order. An entity that was removed keeps a
/// tombstone here with the removal's timestamp: an addition or a write stamped earlier is recognised as
/// older and dropped whichever order it arrives in, and a write stamped later revives the entity from
/// the tombstone. The live maps hold only what exists, so a reader never sees a tombstone.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Registry {
pub node_instances: HashMap<NodeId, Node>,
@@ -9,13 +16,61 @@ pub struct Registry {
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
/// by `ResourceId`. See [`ResourceStore`].
pub resources: ResourceStore,
/// Append-only mapping from per-device `PeerId` to per-human `UserId`.
/// Registered by each device's first contribution via `RegistryDelta::RegisterPeer`.
pub peer_users: HashMap<PeerId, UserId>,
/// Which person each device is: a per-device `PeerId` to a per-human `UserId`, registered by a device's
/// first contribution via `RegistryDelta::RegisterPeer` and again whenever its user changes. Last writer
/// wins on the stamp like every other field, so undo and history authorship scope by person across the
/// peer ids one person accumulates.
pub peer_users: HashMap<PeerId, PeerRegistration>,
pub attributes: Attributes,
#[serde(default)]
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
#[serde(default)]
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
#[serde(default)]
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
}
/// A device's registration to a person, and when it was made.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerRegistration {
pub user: UserId,
pub at: TimeStamp,
}
/// A removed entity: its content as of the removal, for reviving it, and when it was removed, for
/// deciding whether a later-arriving op is older or newer than the removal.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Tombstone<T> {
pub content: T,
pub at: TimeStamp,
/// Nothing has added the entity yet: the content only holds writes that arrived ahead of the addition,
/// and the entity stays dead until one folds in. See [`Registry::removed_nodes`].
#[serde(default)]
pub placeholder: bool,
}
impl Registry {
/// The node under `id`, live or as it was when removed. For a reference to a node the runtime cannot
/// hold, which still needs the id the node had there.
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&Node> {
self.node_instances.get(&id).or_else(|| self.removed_nodes.get(&id).map(|mark| &mark.content))
}
/// The network under `id`, live or as it was when removed.
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&Network> {
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
}
/// Whether both registries removed the same entities at the same times. The removal marks decide
/// how ops still to arrive land, so two registries that agree on their values but not on these
/// will not stay agreed.
pub fn removal_marks_equal(&self, other: &Self) -> bool {
fn same<K: std::hash::Hash + Eq, T>(a: &HashMap<K, Tombstone<T>>, b: &HashMap<K, Tombstone<T>>) -> bool {
a.len() == b.len() && a.iter().all(|(id, mark)| b.get(id).is_some_and(|other| other.at == mark.at && other.placeholder == mark.placeholder))
}
same(&self.removed_nodes, &other.removed_nodes) && same(&self.removed_networks, &other.removed_networks) && same(&self.removed_resources, &other.removed_resources)
}
/// True if both registries agree on every value-bearing field, ignoring per-slot and
/// per-attribute timestamps. Mirrors `compute_deltas`'s value-only semantics, so unchanged
/// state at a stamped slot doesn't count as drift. `peer_users` is excluded: it isn't diffed by
@@ -85,10 +140,10 @@ impl Registry {
}
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
if a.len() != b.len() {
if crate::attributes::live(a).count() != crate::attributes::live(b).count() {
return false;
}
a.iter().all(|(key, value)| b.get(key).is_some_and(|other| value.value == other.value))
crate::attributes::live(a).all(|(key, value)| b.get(key).is_some_and(|other| !other.deleted && value.value == other.value))
}
/// Value-level resource comparison: same resolved hashes and same source chains (keyed by
@@ -100,8 +155,8 @@ pub(crate) fn resources_value_equal(a: &ResourceStore, b: &ResourceStore) -> boo
a.iter().all(|(id, entry)| {
b.get(id).is_some_and(|other| {
entry.hash == other.hash
&& entry.sources.len() == other.sources.len()
&& entry.sources.iter().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
&& entry.live_sources().count() == other.live_sources().count()
&& entry.live_sources().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
})
})
}
+122 -30
View File
@@ -18,6 +18,21 @@ pub struct SourceKey {
pub struct SourceValue {
pub source: serde_json::Value,
pub timestamp: TimeStamp,
/// A removed source stays as a stamped tombstone, so an addition older than the removal is recognised
/// as older whichever order the two land in; readers see a tombstone as absent.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub deleted: bool,
}
impl SourceValue {
/// The tombstone of a source removed at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
source: serde_json::Value::Null,
timestamp,
deleted: true,
}
}
}
/// A single content-addressable resource: an ordered, conflict-mergeable chain of fallback sources
@@ -26,8 +41,13 @@ pub struct SourceValue {
/// resource agree by construction, since the hash is content-derived).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct ResourceEntry {
/// When the entry was last added; see [`Node::presence`](crate::Node).
pub presence: TimeStamp,
/// Fallback chain kept sorted by `SourceKey`, so iteration yields highest-priority first.
pub sources: Vec<(SourceKey, SourceValue)>,
/// When `sources` was last written whole, by an addition of the entry: a key the chain does not hold
/// is deleted as of then, the way [`Attributes`](crate::Attributes) work.
pub sources_timestamp: TimeStamp,
pub hash: Option<ResourceHash>,
pub hash_timestamp: TimeStamp,
}
@@ -39,12 +59,22 @@ impl<'de> Deserialize<'de> for ResourceEntry {
// collapse any duplicate keys, keeping the higher-timestamp value (LWW).
#[derive(Deserialize)]
struct Raw {
#[serde(default)]
presence: TimeStamp,
sources: Vec<(SourceKey, SourceValue)>,
#[serde(default)]
sources_timestamp: TimeStamp,
hash: Option<ResourceHash>,
hash_timestamp: TimeStamp,
}
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
let Raw {
presence,
mut sources,
sources_timestamp,
hash,
hash_timestamp,
} = Raw::deserialize(deserializer)?;
sources.sort_by_key(|(a, _)| *a);
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
@@ -57,7 +87,13 @@ impl<'de> Deserialize<'de> for ResourceEntry {
true
});
Ok(Self { sources, hash, hash_timestamp })
Ok(Self {
presence,
sources,
sources_timestamp,
hash,
hash_timestamp,
})
}
}
@@ -68,52 +104,106 @@ impl ResourceEntry {
pub fn embedded(hash: ResourceHash, peer: PeerId, timestamp: TimeStamp) -> Self {
let embedded = serde_json::to_value(graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let priority = Priority::new(0.).expect("0. is finite");
let sources = vec![(SourceKey { priority, peer }, SourceValue { source: embedded, timestamp })];
let sources = vec![(
SourceKey { priority, peer },
SourceValue {
source: embedded,
timestamp,
deleted: false,
},
)];
Self {
presence: timestamp,
sources,
sources_timestamp: timestamp,
hash: Some(hash),
hash_timestamp: timestamp,
}
}
/// The source body and timestamp stored under `key`, if any.
/// The live source stored under `key`, if any; a tombstone is absent.
pub fn source(&self, key: &SourceKey) -> Option<&SourceValue> {
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)).ok().map(|index| &self.sources[index].1)
self.sources
.binary_search_by(|(candidate, _)| candidate.cmp(key))
.ok()
.map(|index| &self.sources[index].1)
.filter(|value| !value.deleted)
}
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => {
if value.timestamp > self.sources[index].1.timestamp {
self.sources[index].1 = value;
}
}
Err(index) => self.sources.insert(index, (key, value)),
}
/// The live sources in precedence order, tombstones skipped.
pub fn live_sources(&self) -> impl Iterator<Item = (&SourceKey, &SourceValue)> {
self.sources.iter().filter(|(_, value)| !value.deleted).map(|(key, value)| (key, value))
}
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind), where the
/// precomputed reverse/forward value is authoritative even if its timestamp ties what it replaces.
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
/// The stamp that decides a write to `key`: its entry's, tombstone included, or the chain's floor.
fn decided(&self, key: &SourceKey) -> TimeStamp {
self.sources
.binary_search_by(|(candidate, _)| candidate.cmp(key))
.ok()
.map_or(self.sources_timestamp, |index| self.sources[index].1.timestamp)
}
fn put(&mut self, key: SourceKey, value: SourceValue) {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => self.sources[index].1 = value,
Err(index) => self.sources.insert(index, (key, value)),
}
}
/// Remove the entry at `key` if its timestamp is strictly older than `timestamp` (LWW). Returns
/// whether anything was removed.
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
Ok(index) if timestamp > self.sources[index].1.timestamp => {
self.sources.remove(index);
true
}
_ => false,
/// Writes the chain whole at `at`: every source is written then and every other key is deleted as of
/// then, which the floor records without a tombstone per key.
pub(crate) fn stamp_sources(&mut self, at: TimeStamp) {
self.sources.retain(|(_, value)| !value.deleted);
for (_, value) in &mut self.sources {
value.timestamp = at;
}
self.sources_timestamp = at;
}
/// Folds another chain in key by key, the way attribute maps merge: a key only one chain holds is
/// dead when the other chain's floor is newer than it, and the newer entry wins where both hold a key.
pub(crate) fn merge_sources(&mut self, other: Vec<(SourceKey, SourceValue)>, other_floor: TimeStamp) {
self.sources.retain(|(_, value)| value.timestamp >= other_floor);
for (key, value) in other {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => {
if value.timestamp > self.sources[index].1.timestamp {
self.sources[index].1 = value;
}
}
Err(index) => {
if value.timestamp >= self.sources_timestamp {
self.sources.insert(index, (key, value));
}
}
}
}
self.sources_timestamp = self.sources_timestamp.max(other_floor);
}
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
if value.timestamp > self.decided(&key) {
self.put(key, value);
}
}
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind), where the
/// precomputed reverse/forward value is authoritative even if its timestamp ties what it replaces.
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
self.put(key, value);
}
/// Remove the source at `key` if what decides it is strictly older than `timestamp` (LWW), leaving a
/// tombstone. Returns whether the removal landed.
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
if timestamp <= self.decided(key) {
return false;
}
self.put(*key, SourceValue::deleted(timestamp));
true
}
/// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind).
@@ -130,7 +220,7 @@ impl ResourceEntry {
/// True if the chain already carries a `DataSource::Embedded` source. Decodes each source body into
/// `DataSource` so a shape change in the serialized form can't slip an embedded source past detection.
pub fn has_embedded_source(&self) -> bool {
self.sources.iter().any(|(_, value)| {
self.live_sources().any(|(_, value)| {
matches!(
serde_json::from_value::<graphene_resource::DataSource>(value.source.clone()),
Ok(graphene_resource::DataSource::Embedded)
@@ -141,7 +231,7 @@ impl ResourceEntry {
/// A `SourceKey` ordered strictly ahead of every current source, so an inserted entry becomes the
/// highest-precedence fallback.
pub fn highest_precedence_key(&self, peer: PeerId) -> SourceKey {
let min_priority = self.sources.first().map(|(key, _)| key.priority.value()).unwrap_or(0.);
let min_priority = self.live_sources().next().map(|(key, _)| key.priority.value()).unwrap_or(0.);
SourceKey {
priority: Priority::new(min_priority - 1.).expect("finite priority minus one is finite"),
peer,
@@ -250,6 +340,7 @@ mod tests {
SourceValue {
source: serde_json::json!(priority),
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
)
};
@@ -280,6 +371,7 @@ mod tests {
SourceValue {
source: serde_json::json!(body),
timestamp: TimeStamp { counter, peer: PeerId(1) },
deleted: false,
},
)
};
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,608 @@
use std::collections::HashSet;
use crate::{AttributeDelta, Delta, History, MergeOutcome, Network, NetworkId, NodeId, PeerId, RegistryDelta, ResourceEntry, ResourceHash, ResourceId, Rev, Session, UserId};
fn set_attribute(key: &str, value: u32) -> RegistryDelta {
RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: key.to_string(),
value: Some(serde_json::json!(value)),
},
}
}
fn add_network(id: u64) -> RegistryDelta {
RegistryDelta::AddNetwork {
id: NetworkId(id),
network: Network::default(),
}
}
/// The tips as a scan finds them, for checking the maintained set against.
fn scanned_tips(history: &History) -> Vec<Rev> {
let referenced: HashSet<Rev> = history.iter().flat_map(|delta| delta.all_parents()).collect();
let mut tips: Vec<Rev> = history.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
tips.sort_unstable();
tips
}
/// Two peers that branch from a shared base, so their histories hold two tips until merged.
fn branched_pair() -> (Session, Session) {
let mut a = Session::with_peer(PeerId(1));
a.commit_op_for_test(set_attribute("base", 0)).expect("base");
let mut b = a.clone();
b.document.peer = PeerId(2);
b.document.clock = crate::LamportClock::new(PeerId(2));
a.commit_op_for_test(set_attribute("a", 1)).expect("a edit");
b.commit_op_for_test(set_attribute("b", 2)).expect("b edit");
(a, b)
}
#[test]
fn the_tip_set_follows_pushes_merges_and_sorts() {
let (mut a, b) = branched_pair();
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
a.merge(b.cloned_deltas()).expect("merge");
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history), "after a merge joining two branches");
assert_eq!(a.document.history.tips().len(), 1, "the merge delta is the one tip");
a.commit_op_for_test(set_attribute("after", 3)).expect("edit after the merge");
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
// A reload builds the same indexes from the ordered deltas.
let reloaded = History::from_ordered(a.cloned_deltas());
assert_eq!(reloaded.tips(), a.document.history.tips());
for delta in a.history() {
assert!(reloaded.contains_timestamp(delta.timestamp));
}
}
#[test]
fn history_names_the_resource_hashes_it_carries() {
let hash = ResourceHash::from(b"bytes".as_slice());
let id = ResourceId::new();
let mut session = Session::with_peer(PeerId(1));
session
.commit_op_for_test(RegistryDelta::AddResource {
id,
entry: ResourceEntry::embedded(hash, PeerId(1), crate::TimeStamp::ORIGIN),
})
.expect("add");
assert!(session.document.history.resource_hashes().contains(&hash));
let entry = session.retired_registry().resources[&id].clone();
session.commit_op_for_test(RegistryDelta::RemoveResource { id, snapshot: entry }).expect("remove");
assert!(session.all_referenced_resource_hashes().contains(&hash), "a removed resource's hash is still referenced from history");
}
/// A retirement from the host chains off the guest's last delta, so it is placed without a sort and
/// without walking ancestry, and the result is exactly what the sort would have produced.
#[test]
fn a_chain_off_the_last_delta_fast_forwards_without_sorting() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(set_attribute("base", 0)).expect("base");
let mut guest = host.clone();
guest.document.peer = PeerId(2);
host.commit_op_for_test(set_attribute("x", 1)).expect("x");
host.commit_op_for_test(add_network(5)).expect("network");
host.commit_op_for_test(set_attribute("y", 2)).expect("y");
let incoming: Vec<Delta> = host.cloned_deltas().into_iter().filter(|delta| guest.delta(delta.id).is_none()).collect();
assert!(guest.document.history.extends_canonically(guest.history_len()), "an empty tail extends trivially");
let outcome = guest.merge(incoming).expect("merge");
assert!(matches!(outcome, MergeOutcome::FastForward(rev) if Some(rev) == host.head_rev()), "{outcome:?}");
assert_eq!(guest.history().map(|delta| delta.id).collect::<Vec<_>>(), host.history().map(|delta| delta.id).collect::<Vec<_>>());
let mut sorted = guest.document.history.clone();
sorted.canonical_sort();
assert_eq!(
sorted.iter().map(|delta| delta.id).collect::<Vec<_>>(),
guest.history().map(|delta| delta.id).collect::<Vec<_>>(),
"the appended order was already canonical"
);
assert!(guest.retired_registry().value_equal(host.retired_registry()));
}
#[test]
fn a_batch_off_an_earlier_delta_is_sorted_into_place() {
let (mut a, b) = branched_pair();
let before = a.history_len();
let incoming: Vec<Delta> = b.cloned_deltas().into_iter().filter(|delta| a.delta(delta.id).is_none()).collect();
a.merge(incoming).expect("merge");
assert!(!a.document.history.extends_canonically(before), "b's delta hangs off the base, not off a's last delta");
let mut sorted = a.document.history.clone();
sorted.canonical_sort();
assert_eq!(sorted.iter().map(|delta| delta.id).collect::<Vec<_>>(), a.history().map(|delta| delta.id).collect::<Vec<_>>());
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
}
/// Retirement takes the ops under the cutoff whatever order the log applied them in: every op commutes,
/// so the snapshot folds to the working registry's values with a later-stamped op left hot.
#[test]
fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
let mut host = Session::with_peer(PeerId(1));
// A guest's op stamped late sits first in the log, ahead of an op stamped earlier: the log is in
// arrival order, and stamps are the authors' clocks, not the arrival order.
let late = crate::HotOp {
op: add_network(9),
timestamp: crate::TimeStamp { counter: 50, peer: PeerId(2) },
sequence: crate::HotSequence(1),
};
let own = crate::HotOp {
op: set_attribute("x", 1),
timestamp: crate::TimeStamp { counter: 20, peer: PeerId(3) },
sequence: crate::HotSequence(1),
};
host.apply_hot_op(late.clone()).expect("the late-stamped op lands first");
host.apply_hot_op(own.clone()).expect("the earlier-stamped op lands second");
assert_eq!(host.hot_ops_up_to(own.timestamp).len(), 1, "only the op under the cutoff retires");
host.retire(own.timestamp).expect("retire");
assert_eq!(host.hot_log().len(), 1, "the later-stamped op stays hot");
assert!(!host.retired_registry().networks.contains_key(&NetworkId(9)));
assert!(host.registry().networks.contains_key(&NetworkId(9)));
assert!(host.retired_registry().attributes.get("x").is_some_and(|value| !value.deleted));
host.retire(late.timestamp).expect("retire the rest");
assert!(host.hot_log().is_empty());
assert!(host.registry().value_equal(host.retired_registry()));
}
/// A transaction closes with a marker its author stages, and only closed transactions retire: an author's
/// ops past its last marker stay hot however old they are, while a later transaction from someone else
/// retires around them.
#[test]
fn only_closed_transactions_retire_and_an_open_one_stays_hot() {
let mut host = Session::with_peer(PeerId(1));
let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp {
op,
timestamp: crate::TimeStamp { counter, peer: PeerId(2) },
sequence: crate::HotSequence(sequence),
};
assert!(host.end_transaction().expect("nothing to close").is_empty(), "no op of this peer is open");
// The guest opens a transaction and leaves it open, stamped earlier than everything the host does.
host.apply_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
host.apply_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("guest op");
host.stage_ops([set_attribute("host", 1)]).expect("host op");
let marker = host.end_transaction().expect("close").pop().expect("the host's transaction was open");
assert!(matches!(marker.op, RegistryDelta::EndTransaction));
assert!(host.end_transaction().expect("nothing more to close").is_empty(), "closing twice stages nothing");
let closed = host.closed_transactions();
assert_eq!(closed.len(), 1, "the guest's open transaction is not listed: {closed:?}");
assert_eq!(closed[0].author, PeerId(1));
assert!(closed[0].contiguous);
assert_eq!(closed[0].ops.len(), 3, "RegisterPeer, the attribute write and the marker");
let revs = host.retire_transaction(&closed[0]).expect("retire");
assert_eq!(revs.len(), 2, "the marker commits no delta");
assert!(host.history().any(|delta| delta.id == revs[1] && delta.is_interaction_end()), "the transaction is one interaction");
assert_eq!(host.hot_log().len(), 2, "the guest's ops stay hot");
assert!(host.hot_log().iter().all(|hot_op| hot_op.timestamp.peer == PeerId(2)));
assert!(!host.retired_registry().networks.contains_key(&NetworkId(9)));
assert!(host.registry().networks.contains_key(&NetworkId(9)));
// The guest closes: its transaction retires after the host's although it is stamped before it.
host.apply_hot_op(guest_op(12, 3, RegistryDelta::EndTransaction)).expect("guest marker");
let closed = host.closed_transactions();
assert_eq!(closed.len(), 1);
assert_eq!(closed[0].author, PeerId(2));
host.retire_transaction(&closed[0]).expect("retire");
assert!(host.hot_log().is_empty());
assert!(host.registry().value_equal(host.retired_registry()));
assert!(host.document.history.extends_canonically(0), "retirement order is the parent chain, so history stays append-only");
}
/// A transaction with a gap in its author's run is listed as not contiguous, so the retirer can wait for
/// the re-announcement, and closes normally once the gap fills.
#[test]
fn a_transaction_with_a_gap_is_not_contiguous_until_the_gap_fills() {
let mut host = Session::with_peer(PeerId(1));
let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp {
op,
timestamp: crate::TimeStamp { counter, peer: PeerId(2) },
sequence: crate::HotSequence(sequence),
};
host.apply_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
host.apply_hot_op(guest_op(12, 3, RegistryDelta::EndTransaction)).expect("guest marker, op 2 still in flight");
let closed = host.closed_transactions();
assert_eq!(closed.len(), 1);
assert!(!closed[0].contiguous);
host.apply_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("the late op");
let closed = host.closed_transactions();
assert!(closed[0].contiguous);
assert_eq!(closed[0].ops.len(), 3);
}
/// Taking a hot transaction back removes its ops for good and re-derives what they touched from the
/// snapshot and the other hot ops, so a concurrent write to the same entity survives; the ops never
/// retire, and a late copy is dropped.
#[test]
fn a_retracted_transaction_leaves_no_trace_and_keeps_what_others_wrote() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(add_network(3)).expect("base");
host.document.working_registry = host.document.retired_snapshot.clone();
// A guest's write to the network and the host's own gesture on the same network, interleaved.
let guest_write = crate::HotOp {
op: RegistryDelta::ChangeNetworkAttribute {
id: NetworkId(3),
delta: AttributeDelta {
key: "guest".into(),
value: Some(serde_json::json!(1)),
},
},
timestamp: crate::TimeStamp { counter: 40, peer: PeerId(2) },
sequence: crate::HotSequence(1),
};
host.stage_ops([RegistryDelta::ChangeNetworkAttribute {
id: NetworkId(3),
delta: AttributeDelta {
key: "host".into(),
value: Some(serde_json::json!(1)),
},
}])
.expect("host op");
host.apply_hot_op(guest_write.clone()).expect("guest op");
host.stage_ops([add_network(9)]).expect("host op");
let own: Vec<crate::HotOpId> = host.hot_log().iter().filter(|hot_op| hot_op.timestamp.peer == PeerId(1)).map(crate::HotOp::id).collect();
let crate::Retraction { ids, touched, ops } = host.retract_transaction().expect("retract").expect("the host's transaction is hot");
assert_eq!(ops.len(), 3, "RegisterPeer and the two writes come back for a redo, the marker does not");
assert_eq!(ids, own, "the whole open transaction is taken back");
assert!(touched.networks.contains(&NetworkId(3)) && touched.networks.contains(&NetworkId(9)));
assert_eq!(host.hot_log().len(), 1, "only the guest's op stays");
assert!(!host.registry().networks.contains_key(&NetworkId(9)));
let network = &host.registry().networks[&NetworkId(3)];
assert!(!network.attributes.contains_key("host"), "the host's write is gone");
assert!(network.attributes.contains_key("guest"), "the guest's concurrent write survives");
assert!(host.retract_transaction().expect("nothing left").is_none());
// A late copy of a retracted op is dropped, and nothing of it ever retires.
let late = crate::HotOp {
op: add_network(9),
timestamp: crate::TimeStamp { counter: 2, peer: PeerId(1) },
sequence: own[1].sequence,
};
host.replay_hot_op(late).expect("dropped, not an error");
assert_eq!(host.hot_log().len(), 1);
assert!(host.closed_transactions().is_empty());
// Another peer learns of the retraction from the marks alone.
let mut guest = Session::with_peer(PeerId(2));
guest.commit_op_for_test(add_network(3)).expect("base");
guest.document.working_registry = guest.document.retired_snapshot.clone();
guest
.apply_hot_op(crate::HotOp {
op: add_network(9),
timestamp: crate::TimeStamp { counter: 2, peer: PeerId(1) },
sequence: own[1].sequence,
})
.expect("the host's op reached the guest");
assert!(guest.registry().networks.contains_key(&NetworkId(9)));
let touched = guest.absorb_retracted_marks(host.retracted_marks());
assert!(touched.networks.contains(&NetworkId(9)));
assert!(!guest.registry().networks.contains_key(&NetworkId(9)));
assert!(guest.hot_log().is_empty());
}
/// A step the cursor walked away from is not sent to a peer, and a merge never joins it: the peer gets the
/// branch the cursor is on, and the undone step's effect stays gone.
#[test]
fn an_undone_branch_is_kept_to_itself() {
let mut author = Session::with_peer(PeerId(1));
author.commit_op_for_test(set_attribute("base", 0)).expect("base");
let base = author.head_rev().expect("base rev");
author.mark_interaction_end(base);
let mut peer = author.clone();
peer.document.peer = PeerId(2);
author.commit_op_for_test(set_attribute("undone", 1)).expect("the step to undo");
let undone = author.head_rev().expect("rev");
author.mark_interaction_end(undone);
author.undo().expect("undo");
assert_eq!(author.head_rev(), Some(base));
author.commit_op_for_test(set_attribute("kept", 2)).expect("a new branch");
let kept = author.head_rev().expect("rev");
let sent: Vec<Rev> = author.deltas_unknown_to(peer.known_revs()).into_iter().map(|delta| delta.id).collect();
assert_eq!(sent, vec![kept], "only the branch the cursor is on goes out, not the undone step");
assert!(author.delta(undone).is_some(), "the undone step stays in the author's DAG for a history panel");
let incoming: Vec<Delta> = sent.iter().filter_map(|&rev| author.delta(rev).cloned()).collect();
let outcome = peer.merge(incoming).expect("merge");
assert!(matches!(outcome, MergeOutcome::FastForward(rev) if rev == kept), "{outcome:?}");
assert!(peer.retired_registry().attributes.get("kept").is_some_and(|value| !value.deleted));
assert!(!peer.retired_registry().attributes.contains_key("undone"), "the undone step never reached the peer");
}
/// Undoing a retired step in a session drops it out of the shared line: the later steps are minted again
/// on its parent, the head moves, every peer that follows the move holds the same history and registry,
/// a field a later step wrote keeps that value, and the dropped step comes back on redo as a copy on top.
#[test]
fn a_dropped_interaction_leaves_the_line_and_the_room_follows() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(set_attribute("base", 0)).expect("base");
let base = host.head_rev().expect("rev");
host.mark_interaction_end(base);
// The guest's step, retired by the host: it writes its own key and one the host writes after it. A
// guest of its own, clock included, so its ops carry its authorship.
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
let guest_ops = [set_attribute("guest", 1), set_attribute("shared", 1)];
let hot = guest.stage_ops(guest_ops).expect("stage");
for hot_op in &hot {
host.apply_hot_op(hot_op.clone()).expect("the guest's ops reach the host");
}
let guest_ids: Vec<crate::HotOpId> = hot.iter().map(crate::HotOp::id).collect();
let revs = host.retire_hot_ops(&guest_ids).expect("retire");
let undone = *revs.last().expect("the guest's step");
host.mark_interaction_end(undone);
guest
.merge(host.cloned_deltas().into_iter().filter(|delta| guest.delta(delta.id).is_none()).collect::<Vec<Delta>>())
.expect("merge");
guest.discard_hot_ops(&guest_ids).expect("discard");
// A later step by the host writes the shared key.
host.commit_op_for_test(set_attribute("shared", 2)).expect("later step");
let later = host.head_rev().expect("rev");
host.mark_interaction_end(later);
host.stamp_retired_at(&[later], 1_234);
guest
.merge(host.cloned_deltas().into_iter().filter(|delta| guest.delta(delta.id).is_none()).collect::<Vec<Delta>>())
.expect("merge");
assert_eq!(guest.head_rev(), host.head_rev());
assert_eq!(guest.latest_own_interaction(), Some(undone));
let (moved, touched) = host.drop_interaction(undone).expect("drop");
assert_eq!(moved.from, Some(later));
assert_eq!(moved.copies.len(), 1, "the later step is minted again");
assert_eq!(moved.copies[0].parent, Some(base), "the copy hangs off the dropped step's parent");
assert!(moved.copies[0].is_interaction_end(), "the copy keeps its interaction end");
assert_eq!(moved.copies[0].retired_at(), Some(1_234), "the copy keeps when the original was retired");
assert!(touched.nodes.is_empty() && !touched.resources, "document attributes only");
let snapshot = host.retired_registry();
assert!(snapshot.attributes.get("guest").is_none_or(|value| value.deleted), "the dropped step's write is gone");
assert_eq!(
snapshot.attributes.get("shared").map(|value| &value.value),
Some(&serde_json::json!(2)),
"the later step's write stands"
);
assert!(host.delta(undone).is_some() && host.delta(later).is_some(), "the abandoned branch stays for a history panel");
assert!(host.registry().value_equal(host.retired_registry()));
guest.apply_head_move(&moved).expect("follow");
assert_eq!(guest.head_rev(), host.head_rev());
assert_eq!(guest.retired_registry(), host.retired_registry());
assert_eq!(guest.history().map(|delta| delta.id).collect::<Vec<_>>(), host.history().map(|delta| delta.id).collect::<Vec<_>>());
assert!(
matches!(guest.apply_head_move(&moved), Err(crate::CrdtError::CursorMismatch { .. })),
"a move only applies from where it started"
);
// Redo: the dropped step returns as a copy on top, its older stamp losing the shared key.
let restored = host.restore_interaction(undone).expect("restore");
assert_eq!(restored.len(), 3, "RegisterPeer and the two writes come back");
assert!(host.retired_registry().attributes.get("guest").is_some_and(|value| value.value == serde_json::json!(1)));
assert_eq!(host.retired_registry().attributes.get("shared").map(|value| &value.value), Some(&serde_json::json!(2)));
guest
.merge(host.cloned_deltas().into_iter().filter(|delta| guest.delta(delta.id).is_none()).collect::<Vec<Delta>>())
.expect("merge the copies");
assert_eq!(guest.head_rev(), host.head_rev());
assert_eq!(guest.retired_registry(), host.retired_registry());
}
/// An author's ops can reach the retirer out of order, the later ones first through a re-announcement
/// after a lapsed link. Coarsening keeps the newest write by stamp, not by position in the log, so the
/// retired delta carries the value every working registry shows.
#[test]
fn a_transaction_that_arrived_out_of_order_retires_to_its_newest_write() {
let mut author = Session::with_peer(PeerId(2));
author.stage_ops(vec![set_attribute("name", 1), set_attribute("name", 2)]).expect("stage");
author.end_transaction().expect("close");
let ops = author.hot_log().to_vec();
let mut in_order = Session::with_peer(PeerId(1));
let mut reversed = Session::with_peer(PeerId(1));
for hot_op in &ops {
in_order.replay_hot_op(hot_op.clone()).expect("replay");
}
for hot_op in ops.iter().rev() {
reversed.replay_hot_op(hot_op.clone()).expect("replay");
}
for host in [&mut in_order, &mut reversed] {
let closed = host.closed_transactions();
assert_eq!(closed.len(), 1);
host.retire_transaction(&closed[0]).expect("retire");
assert!(host.registry().value_equal(host.retired_registry()), "the retired value is the one the working registry showed");
}
assert_eq!(reversed.retired_registry(), in_order.retired_registry(), "arrival order decides nothing");
}
/// A transaction retires coarsened: of the writes to one field only the newest becomes a delta, a
/// whole-list input write supersedes the slot writes before it, a write wiring an input to a node stays
/// while what supersedes it wires elsewhere, and the fold is the one every op would have produced.
#[test]
fn a_transaction_retires_to_one_delta_per_field() {
let attribute = |value: u32| set_attribute("name", value);
let wire = |target: u64| RegistryDelta::ChangeNodeInput {
id: NodeId(1),
index: 0,
new_input: crate::NodeInput::Node { id: NodeId(target), index: 0 },
};
let value = |value: u32| RegistryDelta::ChangeNodeInput {
id: NodeId(1),
index: 1,
new_input: crate::NodeInput::Value {
value: serde_json::json!(value),
exposed: false,
},
};
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(add_network(3)).expect("network");
host.document.working_registry = host.document.retired_snapshot.clone();
let node = |id: u64| RegistryDelta::AddNode {
id: NodeId(id),
node: crate::Node::new(NetworkId(3), crate::Implementation::ProtoNode(ResourceId::from(7)), 2),
};
let ops = vec![node(1), node(2), node(4), attribute(1), value(1), attribute(2), wire(2), value(2), wire(4), attribute(3), value(3)];
let mut raw = host.clone();
raw.stage_ops(ops.clone()).expect("stage");
host.stage_ops(ops).expect("stage");
host.end_transaction().expect("close");
raw.end_transaction().expect("close");
let closed = host.closed_transactions();
assert_eq!(closed.len(), 1);
let coarsened = host.retire_transaction(&closed[0]).expect("retire");
let raw_ids: Vec<crate::HotOpId> = raw.hot_log().iter().map(crate::HotOp::id).collect();
let uncoarsened = raw.retire_hot_ops(&raw_ids).expect("retire raw");
assert_eq!(uncoarsened.len(), 12, "RegisterPeer, three additions and eight writes");
assert_eq!(
coarsened.len(),
8,
"RegisterPeer, three additions, the newest attribute, the newest value, and both wires: {coarsened:?}"
);
assert!(host.hot_log().is_empty());
assert!(host.retired_registry().value_equal(raw.retired_registry()), "the fold is unchanged");
assert!(host.registry().value_equal(host.retired_registry()), "the working registry, built from every op, agrees");
assert_eq!(host.retired_registry(), raw.retired_registry(), "stamps included: the survivor keeps its own");
let kinds: Vec<&RegistryDelta> = host.history().map(|delta| &delta.kind).collect();
assert!(kinds.iter().filter(|kind| matches!(kind, RegistryDelta::ChangeDocumentAttribute { .. })).count() == 1);
assert!(
kinds.iter().filter(|kind| matches!(kind, RegistryDelta::ChangeNodeInput { index: 0, .. })).count() == 2,
"the wire to node 2 stays as evidence node 2 exists"
);
assert!(kinds.iter().filter(|kind| matches!(kind, RegistryDelta::ChangeNodeInput { index: 1, .. })).count() == 1);
assert!(host.history().last().is_some_and(|delta| delta.is_interaction_end()));
}
/// A merge delta joins a line this peer holds as a branch it walked away from. Following it as a plain
/// extension of the line would leave that branch's effects out of the snapshot, so the snapshot is
/// folded from the joined head's whole ancestry instead, and matches the host's.
#[test]
fn following_a_merge_refolds_the_branch_it_joins() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(add_network(1)).expect("root");
let mut guest = Session::with_peer(PeerId(2));
let root: Vec<crate::Delta> = host.history().cloned().collect();
guest.follow(root, host.head_rev()).expect("follow the root");
// The guest retires a step of its own while apart, then follows the host's line, which leaves it behind.
guest.commit_op_for_test(add_network(2)).expect("own step");
let own: Vec<crate::Delta> = guest.history().filter(|delta| delta.author == PeerId(2)).cloned().collect();
host.commit_op_for_test(add_network(3)).expect("host step");
let line: Vec<crate::Delta> = host.history().cloned().collect();
guest.follow(line, host.head_rev()).expect("follow the host");
assert!(!guest.retired_registry().networks.contains_key(&NetworkId(2)), "the guest's own step is off the line");
// The host merges the guest's step and the guest follows to the joined head.
host.merge(own).expect("merge");
let merged: Vec<crate::Delta> = host.history().cloned().collect();
guest.follow(merged, host.head_rev()).expect("follow the merge");
let fold = guest.snapshot_from_history().expect("fold");
assert_eq!(guest.retired_registry(), &fold, "the snapshot is the fold of the joined head's ancestry");
assert!(guest.retired_registry().networks.contains_key(&NetworkId(2)), "the branch is back on the line");
assert_eq!(guest.retired_registry(), host.retired_registry());
assert!(guest.registry().value_equal(guest.retired_registry()));
}
/// A device's registration to a person is a write like any other: a later one replaces it, and a peer that
/// receives the two in the other order ends up with the same mapping.
#[test]
fn a_peers_registration_is_the_newest_by_stamp_whatever_order_it_lands() {
// Registration rides the staging path, so the steps go through the hot log and retire.
fn stage_and_retire(session: &mut Session, op: RegistryDelta) {
let hot = session.stage_ops([op]).expect("stage");
let ids: Vec<crate::HotOpId> = hot.iter().map(crate::HotOp::id).collect();
session.retire_hot_ops(&ids).expect("retire");
}
let mut device = Session::with_identity(PeerId(1), UserId(10));
stage_and_retire(&mut device, set_attribute("first", 1));
assert_eq!(device.user_of(PeerId(1)), Some(UserId(10)));
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10));
// The person at the device changes: the next batch registers again, and the newer registration wins.
device.set_user(UserId(20));
stage_and_retire(&mut device, set_attribute("second", 2));
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(20));
let registrations = device.history().filter(|delta| matches!(delta.kind, RegistryDelta::RegisterPeer { .. })).count();
assert_eq!(registrations, 2, "one registration per person the device stood for");
let mut reversed = Session::with_peer(PeerId(2));
let deltas: Vec<Delta> = device.cloned_deltas().into_iter().rev().collect();
reversed.merge(deltas).expect("merge");
assert_eq!(reversed.user_of(PeerId(1)), Some(UserId(20)), "the newest registration wins in any order");
assert_eq!(reversed.user_of(PeerId(2)), Some(UserId(2)), "a peer without a stored identity stands for itself");
}
/// Undo of a retired step in a session names the person's latest step, not the device's: a fresh copy of
/// the document under a new peer id still undoes what its user did from the old one, and nobody else's.
#[test]
fn undo_in_a_session_finds_the_users_step_from_another_peer() {
let mut host = Session::with_identity(PeerId(1), UserId(1));
host.commit_op_for_test(set_attribute("base", 0)).expect("base");
let base = host.head_rev().expect("rev");
host.mark_interaction_end(base);
let mut old_device = Session::load(PeerId(2), UserId(7), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
let hot = old_device.stage_ops([set_attribute("mine", 1)]).expect("stage");
for hot_op in &hot {
host.apply_hot_op(hot_op.clone()).expect("the step reaches the host");
}
let ids: Vec<crate::HotOpId> = hot.iter().map(crate::HotOp::id).collect();
let revs = host.retire_hot_ops(&ids).expect("retire");
let step = *revs.last().expect("the step");
host.mark_interaction_end(step);
let new_device = Session::load(PeerId(3), UserId(7), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
assert_eq!(new_device.latest_own_interaction(), Some(step), "the same person under a new peer id owns the step");
assert!(new_device.is_mine(PeerId(2)));
let stranger = Session::load(PeerId(4), UserId(8), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
assert_eq!(stranger.latest_own_interaction(), None, "someone else has nothing of theirs to undo");
assert!(!stranger.is_mine(PeerId(2)));
}
#[test]
fn moving_the_head_back_leaves_the_line_since_as_a_branch_everyone_follows() {
let mut host = Session::with_identity(PeerId(1), UserId(1));
host.commit_op_for_test(set_attribute("a", 1)).expect("first");
let first = host.head_rev().expect("rev");
host.mark_interaction_end(first);
host.commit_op_for_test(set_attribute("b", 2)).expect("second");
let second = host.head_rev().expect("rev");
host.mark_interaction_end(second);
host.commit_op_for_test(set_attribute("c", 3)).expect("third");
let third = host.head_rev().expect("rev");
host.mark_interaction_end(third);
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
let (moved, touched) = host.move_head_to(first).expect("move");
assert_eq!(moved.from, Some(third));
assert_eq!(moved.head, Some(first));
assert!(moved.copies.is_empty(), "nothing is minted: the line since is left behind");
assert!(touched.nodes.is_empty() && !touched.resources, "document attributes only");
let snapshot = host.retired_registry();
assert!(snapshot.attributes.get("b").is_none_or(|value| value.deleted), "the second step's write is gone");
assert!(snapshot.attributes.get("c").is_none_or(|value| value.deleted), "the third step's write is gone");
assert_eq!(snapshot.attributes.get("a").map(|value| &value.value), Some(&serde_json::json!(1)));
assert!(host.delta(second).is_some() && host.delta(third).is_some(), "the steps left behind stay as a branch");
assert!(host.registry().value_equal(host.retired_registry()));
guest.apply_head_move(&moved).expect("follow");
assert_eq!(guest.head_rev(), Some(first));
assert!(guest.retired_registry().value_equal(host.retired_registry()), "the follower folds to the same state");
}
+698 -47
View File
@@ -40,6 +40,7 @@ fn apply_hot_op_advances_clock_past_observed_timestamp() {
let hot_op = HotOp {
op: remove_node_op(NodeId(99)),
timestamp: observed,
sequence: crate::HotSequence(1),
};
document.apply_hot_op(hot_op).expect("RemoveNode on absent node is a no-op, not an error");
@@ -182,9 +183,10 @@ fn merge_converges_to_identical_history() {
// Cross-merge: feed each peer the other's full delta set. The shared base dedups by `Rev`.
let deltas_a = session_a.cloned_deltas();
let deltas_b = session_b.cloned_deltas();
let merge_a = session_a.merge(deltas_b).expect("merge into A failed").expect("A produced a merge");
let merge_b = session_b.merge(deltas_a).expect("merge into B failed").expect("B produced a merge");
let merge_a = session_a.merge(deltas_b).expect("merge into A failed");
let merge_b = session_b.merge(deltas_a).expect("merge into B failed");
assert!(matches!(merge_a, crate::MergeOutcome::Merged(_)), "divergent branches must produce a merge delta");
assert_eq!(merge_a, merge_b, "same tips must mint the identical parent-set-addressed merge commit");
let order_a: Vec<crate::Rev> = session_a.history().map(|d| d.id).collect();
@@ -193,9 +195,31 @@ fn merge_converges_to_identical_history() {
assert_eq!(session_a.head_rev(), session_b.head_rev(), "both peers land on the same merge head");
}
/// Resurrection must reach into a merged-in branch: a network added then removed on the other peer's
/// branch lives only under the merge's secondary parent, so a `SetNetworkExport` targeting it after
/// the merge can only restore it by traversing all ancestors (not the primary-parent chain).
/// A peer whose history is a prefix of the incoming one moves its head forward without minting a
/// merge delta, and the negotiated transfer sends only the deltas past the sampled known revs.
#[test]
fn merge_fast_forwards_a_prefix_history() {
let mut session_a = Session::with_peer(PeerId(1));
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
let mut session_b = session_a.clone();
for value in 1..=5 {
session_b.commit_op_for_test(set_document_attribute("compute::b", value)).expect("B edit");
}
let known = session_a.known_revs();
let missing: Vec<_> = session_b.deltas_unknown_to(known).into_iter().cloned().collect();
assert_eq!(missing.len(), 5, "only B's new commits are unknown to A");
let outcome = session_a.merge(missing).expect("merge failed");
assert_eq!(outcome, crate::MergeOutcome::FastForward(session_b.head_rev().unwrap()));
assert_eq!(session_a.history().count(), session_b.history().count(), "no merge delta was added");
assert_eq!(session_b.merge(session_a.cloned_deltas()).expect("merge failed"), crate::MergeOutcome::NoOp);
}
/// A write to a network removed on a merged-in branch revives it: the removal keeps the network as a
/// tombstone, and the write is newer than the removal.
#[test]
fn resurrection_reaches_across_a_merge() {
let network_id = NetworkId(7);
@@ -222,15 +246,15 @@ fn resurrection_reaches_across_a_merge() {
// A merges B's branch: 7's AddNetwork now lives only under the merge's secondary parent.
session_a.merge(session_b.cloned_deltas()).expect("merge failed");
// A SetNetworkExport on 7 must resurrect it by walking into the merged-in branch. Before the
// all-ancestors fix this failed with NetworkNotInHistory (the primary-parent walk missed B's branch).
// A SetNetworkExport on 7 is newer than its removal, so it brings 7 back from its tombstone.
session_a
.commit_op_for_test(RegistryDelta::SetNetworkExport {
id: network_id,
index: 0,
export: None,
})
.expect("resurrection must find the AddNetwork on the merged-in branch");
.expect("a write newer than the removal revives the network");
assert!(session_a.retired_registry().networks.contains_key(&network_id));
}
/// Committing the same NodeNetwork twice must produce zero history entries on the second commit.
@@ -263,7 +287,11 @@ fn first_contribution_registers_the_peer() {
let registrations = first.iter().filter(|hot_op| matches!(hot_op.op, RegistryDelta::RegisterPeer { .. })).count();
assert_eq!(registrations, 1, "exactly one RegisterPeer on first contribution");
assert!(matches!(first[0].op, RegistryDelta::RegisterPeer { .. }), "RegisterPeer must precede the edit ops");
assert_eq!(session.registry().peer_users.get(&PeerId(7)), Some(&crate::UserId(7)), "peer mapped to its UserId");
assert_eq!(
session.registry().peer_users.get(&PeerId(7)).map(|registration| registration.user),
Some(crate::UserId(7)),
"peer mapped to its UserId"
);
// A second, distinct contribution must not re-register.
let mut other_network = tiny_network();
@@ -284,7 +312,7 @@ fn first_contribution_registers_the_peer() {
assert_eq!(fresh.registry().peer_users, peers_before, "a no-op batch must not add a registration");
}
/// A SetExport against a removed network must restore the network from history rather than error.
/// A SetExport newer than a network.s removal revives the network from its tombstone rather than error.
#[test]
fn set_export_resurrects_absent_network() {
let mut document = fresh_document(PeerId(1));
@@ -318,7 +346,7 @@ fn set_export_resurrects_absent_network() {
assert!(document.working_registry.networks.contains_key(&network_id), "SetExport should have resurrected the network");
}
/// Cascading resurrection: bringing a node back must also restore its owning network when absent.
/// An addition into a removed network is evidence the network exists, so it brings the network back.
#[test]
fn add_node_resurrects_owning_network() {
use crate::Node;
@@ -352,9 +380,8 @@ fn add_node_resurrects_owning_network() {
assert!(document.working_registry.node_instances.contains_key(&node_id), "the node itself should also be present");
}
/// Reverting the same removal twice (the moral equivalent of two peers concurrently resurrecting
/// the same node) must not error on the second apply. Today the second revert hits
/// `apply_op(AddNode, false)` against a present node and returns `NodeAlreadyExists`.
/// The same revival arriving twice, from two peers reverting one removal, lands once: the second copy
/// is not newer than what the first wrote.
#[test]
fn concurrent_resurrection_via_revert_is_idempotent() {
use crate::Node;
@@ -375,38 +402,17 @@ fn concurrent_resurrection_via_revert_is_idempotent() {
commit_op(&mut document, RegistryDelta::RemoveNode { id: node_id, snapshot: node });
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed before the resurrection test");
document.restore_node_from_history(RegistryTarget::Working, node_id).expect("first resurrection should succeed");
assert!(document.working_registry.node_instances.contains_key(&node_id), "first resurrection should bring the node back");
let revive = RegistryDelta::AddNode {
id: node_id,
node: Node { network: network_id, ..Node::dummy() },
};
let at = document.clock.tick();
document.apply_op_idempotent(revive.clone(), at).expect("first revival");
assert!(document.working_registry.node_instances.contains_key(&node_id), "the first revival brings the node back");
let second = document.restore_node_from_history(RegistryTarget::Working, node_id);
assert!(second.is_ok(), "second resurrection of an already-present node should be a no-op, got {second:?}");
}
/// History-based resurrection must work when the matching delta is the *root* commit. The history
/// walk used to drop the root (its empty parent list short-circuited the iterator before yielding
/// it), so a node removed by the very first commit could not be restored.
#[test]
fn restore_node_from_root_commit() {
use crate::Node;
let mut document = fresh_document(PeerId(1));
let node_id = NodeId(42);
let node = Node::dummy();
// Seed the working state so the root commit can remove the node (its reverse is the `AddNode` the
// resurrection looks for). This `RemoveNode` is the only commit, so the match sits at the root.
document.working_registry.networks.insert(ROOT_NETWORK, Network::default());
document.retired_snapshot.networks.insert(ROOT_NETWORK, Network::default());
document.working_registry.node_instances.insert(node_id, node.clone());
document.retired_snapshot.node_instances.insert(node_id, node.clone());
commit_op(&mut document, RegistryDelta::RemoveNode { id: node_id, snapshot: node });
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed by the root commit");
document
.restore_node_from_history(RegistryTarget::Working, node_id)
.expect("resurrection from the root commit should succeed");
assert!(document.working_registry.node_instances.contains_key(&node_id), "node must be restored from the root commit");
let second = document.apply_op_idempotent(revive, at);
assert!(second.is_ok(), "the same revival again is a no-op, got {second:?}");
assert!(document.working_registry.node_instances.contains_key(&node_id));
}
/// Erroring ops still bump the clock: we observed the timestamp on the wire, the fact that the
@@ -439,6 +445,11 @@ fn source_key(priority: f64, peer: u64) -> SourceKey {
}
}
/// Whether the map holds a live value under `key`: a deleted key stays as a tombstone.
fn holds(attributes: &crate::Attributes, key: &str) -> bool {
crate::attributes::live(attributes).any(|(held, _)| held == key)
}
fn ts(counter: u64, peer: u64) -> TimeStamp {
TimeStamp { counter, peer: PeerId(peer) }
}
@@ -563,7 +574,10 @@ fn remove_source_reverse_restores_prior() {
}
document.apply_op(RD::RemoveSource { id, key }, ts(5, 1)).unwrap();
assert!(document.working_registry.resources.get(&id).unwrap().sources.is_empty(), "source removed");
assert!(
document.working_registry.resources.get(&id).unwrap().live_sources().next().is_none(),
"source removed, a tombstone left"
);
// Applying the reverse restores the chain.
document.apply_op(reverse, ts(6, 1)).unwrap();
@@ -623,7 +637,16 @@ use crate::{ResourceEntry, ResourceStore, SourceValue};
fn entry_with_source(priority: f64, peer: u64, body: serde_json::Value, hash: Option<ResourceHash>) -> ResourceEntry {
ResourceEntry {
sources: vec![(source_key(priority, peer), SourceValue { source: body, timestamp: ts(1, peer) })],
presence: ts(1, peer),
sources: vec![(
source_key(priority, peer),
SourceValue {
source: body,
timestamp: ts(1, peer),
deleted: false,
},
)],
sources_timestamp: TimeStamp::ORIGIN,
hash,
hash_timestamp: ts(1, peer),
}
@@ -674,6 +697,7 @@ fn compute_deltas_diffs_resources_and_round_trips() {
SourceValue {
source: serde_json::json!("url"),
timestamp: ts(1, 1),
deleted: false,
},
);
to.insert(kept, kept_entry);
@@ -699,6 +723,8 @@ fn compute_deltas_diffs_resources_and_round_trips() {
// Apply the diff to a document seeded with `from`, then check it matches `to` by value.
let mut document = fresh_document(PeerId(1));
document.working_registry = registry_with_resources(from);
// A clock is past every stamp in the registry it edits, as a session.s persisted clock is.
document.clock.observe(ts(1, 1));
for op in deltas {
let timestamp = document.clock.tick();
document.apply_op(op, timestamp).expect("apply resource delta");
@@ -833,12 +859,18 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
input: crate::NodeInput::Import { index: 0 },
timestamp: TimeStamp::ORIGIN,
attributes: input_attributes,
attributes_timestamp: TimeStamp::ORIGIN,
}];
Node {
presence: Default::default(),
added: Default::default(),
inputs_timestamp: Default::default(),
implementation: implementation.clone(),
implementation_timestamp: Default::default(),
inputs,
attributes,
attributes_timestamp: Default::default(),
network: ROOT_NETWORK,
}
};
@@ -879,3 +911,622 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
assert_eq!(delta_forward.id, delta_reversed.id, "Rev must not depend on attribute insertion order");
}
/// Commit a retired delta and mirror it onto the working registry; `commit_op_for_test` alone only
/// advances the snapshot zone.
fn commit_retired(session: &mut Session, op: RegistryDelta) {
let before = session.history().count();
session.commit_op_for_test(op).expect("commit failed");
for delta in session.cloned_deltas().into_iter().skip(before) {
session.document.apply_op_idempotent(delta.kind, delta.timestamp).expect("mirroring onto the working registry");
}
}
/// Merge `deltas` into a copy of `base` in the given order, reporting node 7's surviving `tint`.
fn merge_order_outcome(base: &Session, deltas: &[Delta], order: [usize; 2]) -> Option<(serde_json::Value, TimeStamp)> {
let mut session = base.clone();
let ordered: Vec<Delta> = order.iter().map(|&index| deltas[index].clone()).collect();
session.merge(ordered).expect("merge failed");
session
.retired_registry()
.node_instances
.get(&NodeId(7))
.and_then(|node| node.attributes.get("tint"))
.map(|value| (value.value.clone(), value.timestamp))
}
/// The raw ops are arrival-order dependent: change-first leaves the node gone, remove-first resurrects
/// it from the removal's snapshot. Merge has to fold both orders onto the same retired registry.
#[test]
fn a_concurrent_remove_and_attribute_change_commute() {
let network_id = NetworkId(5);
let node = Node::new(network_id, crate::Implementation::Network(network_id), 0);
// Shared base holding node 7, then the two peers diverge.
let mut base = Session::with_peer(PeerId(1));
commit_retired(
&mut base,
RegistryDelta::AddNetwork {
id: network_id,
network: Network::default(),
},
);
commit_retired(&mut base, RegistryDelta::AddNode { id: NodeId(7), node: node.clone() });
let mut remover = base.clone();
commit_retired(&mut remover, RegistryDelta::RemoveNode { id: NodeId(7), snapshot: node });
let mut changer = Session::with_peer(PeerId(2));
changer.merge(base.cloned_deltas()).expect("changer adopts the base");
commit_retired(
&mut changer,
RegistryDelta::ChangeNodeAttribute {
id: NodeId(7),
delta: crate::AttributeDelta {
key: "tint".to_string(),
value: Some(serde_json::json!(75)),
},
},
);
// One delta from each branch, neither an ancestor of the other.
let removal = remover.cloned_deltas().into_iter().last().expect("removal delta");
let change = changer.cloned_deltas().into_iter().last().expect("change delta");
let deltas = [removal, change];
let removal_first = merge_order_outcome(&base, &deltas, [0, 1]);
let change_first = merge_order_outcome(&base, &deltas, [1, 0]);
assert_eq!(removal_first, change_first, "the retired registry must not depend on delta arrival order");
}
/// An op can retire before an earlier one from its author arrives, so the marks cover it out of order.
/// The prefix absorbs it once the gap fills, which bounds the exception set.
#[test]
fn retired_marks_cover_a_gap_and_compact_once_it_fills() {
let author = PeerId(1);
let id = |sequence: u64| crate::HotOpId {
peer: author,
sequence: crate::HotSequence(sequence),
};
let mut marks = crate::RetiredHotOps::default();
marks.extend([id(1), id(2)]);
assert_eq!(marks.retired_up_to.get(&author), Some(&crate::HotSequence(2)), "a contiguous run folds straight into the prefix");
assert!(marks.retired_beyond.is_empty());
// Sequence 3 never arrived, so 4 retires above the prefix rather than extending it.
marks.extend([id(4)]);
assert_eq!(marks.retired_up_to.get(&author), Some(&crate::HotSequence(2)));
assert!(marks.covers(id(4)), "an op past the gap is still recognized as retired");
assert!(!marks.covers(id(3)), "the missing op is not claimed");
// The gap fills, so the prefix swallows both it and the exception behind it.
marks.extend([id(3)]);
assert_eq!(marks.retired_up_to.get(&author), Some(&crate::HotSequence(4)));
assert!(marks.retired_beyond.is_empty(), "the exception set empties once the prefix reaches it");
}
/// Marks merge by union, so adopting a peer's wholesale must not lose local coverage.
#[test]
fn absorbing_marks_keeps_both_sides_coverage() {
let author = PeerId(1);
let id = |sequence: u64| crate::HotOpId {
peer: author,
sequence: crate::HotSequence(sequence),
};
let mut local = crate::RetiredHotOps::default();
local.extend([id(1), id(4)]);
let mut remote = crate::RetiredHotOps::default();
remote.extend([id(1), id(2), id(3), id(5)]);
local.absorb(&remote);
// The union is 1..=5 contiguous, so it all collapses into the prefix.
assert_eq!(local.retired_up_to.get(&author), Some(&crate::HotSequence(5)));
assert!(local.retired_beyond.is_empty());
for sequence in 1..=5 {
assert!(local.covers(id(sequence)), "sequence {sequence} must stay covered");
}
}
/// Undo rewinds retired history and must leave the hot tail alone: copying the working registry onto
/// the snapshot promotes unretired work. Hot ops exist between staging and retirement even solo.
#[test]
fn undo_does_not_promote_hot_ops_into_the_retired_snapshot() {
let mut session = Session::with_peer(PeerId(1));
// Two retired interactions, so the second is undoable.
commit_retired(&mut session, set_document_attribute("first", 1));
let boundary = session.history().last().expect("a committed delta").id;
session.mark_interaction_end(boundary);
commit_retired(&mut session, set_document_attribute("second", 2));
// Unretired live work sitting on top, on a key no retired delta touches.
session.stage_ops([set_document_attribute("hot", 3)]).expect("stage");
assert!(holds(&session.registry().attributes, "hot"), "the hot op must be in the working registry");
assert!(!holds(&session.retired_registry().attributes, "hot"), "and must not be in the snapshot");
session.undo().expect("undo");
assert!(!holds(&session.retired_registry().attributes, "second"), "undo must rewind the retired snapshot");
assert!(!holds(&session.retired_registry().attributes, "hot"), "undo promoted an unretired hot op into the retired snapshot");
}
/// Redo puts the interaction back on both zones, so the pair does not drift the other way.
#[test]
fn redo_restores_the_retired_snapshot_without_the_hot_tail() {
let mut session = Session::with_peer(PeerId(1));
commit_retired(&mut session, set_document_attribute("first", 1));
let boundary = session.history().last().expect("a committed delta").id;
session.mark_interaction_end(boundary);
commit_retired(&mut session, set_document_attribute("second", 2));
session.stage_ops([set_document_attribute("hot", 3)]).expect("stage");
session.undo().expect("undo");
session.redo().expect("redo");
assert!(holds(&session.retired_registry().attributes, "second"), "redo must restore the retired delta");
assert!(!holds(&session.retired_registry().attributes, "hot"), "redo promoted an unretired hot op into the retired snapshot");
assert!(holds(&session.registry().attributes, "hot"), "the hot op must survive an undo/redo round trip");
}
/// Silent undo emits nothing, so it is only legal while a commit is unpublished. Once peers hold it, a
/// rewind would diverge from them for good.
#[test]
fn publishing_a_commit_disables_silent_undo() {
let mut session = Session::with_peer(PeerId(1));
commit_retired(&mut session, set_document_attribute("first", 1));
let boundary = session.history().last().expect("a committed delta").id;
session.mark_interaction_end(boundary);
commit_retired(&mut session, set_document_attribute("second", 2));
let head = session.head_rev().expect("a head");
assert!(session.can_undo(), "an unpublished interaction is undoable");
session.publish_up_to(head);
assert!(!session.can_undo(), "a published interaction must not be silently rewound");
}
/// An undone delta stays in the DAG for redo, outside `head`'s ancestry. A fold that ignores that
/// restores work the user undid.
#[test]
fn snapshot_from_history_ignores_undone_deltas() {
let mut session = Session::with_peer(PeerId(1));
commit_retired(&mut session, set_document_attribute("first", 1));
let boundary = session.history().last().expect("a committed delta").id;
session.mark_interaction_end(boundary);
commit_retired(&mut session, set_document_attribute("second", 2));
session.undo().expect("undo");
assert!(!holds(&session.retired_registry().attributes, "second"), "undo rewound the snapshot");
let folded = session.snapshot_from_history().expect("fold");
assert!(holds(&folded.attributes, "first"), "history still holds the kept interaction");
assert!(!holds(&folded.attributes, "second"), "a fold restored an undone delta");
}
/// A node removed, revived by a reference and removed again with a snapshot placing it elsewhere folds
/// to the same snapshot whether the deltas land one by one or all at once (simulation seed 3588534,
/// which once caught a revival reading the wrong removal).
#[test]
fn snapshot_from_history_reproduces_a_revival_between_two_removals() {
let node_id = NodeId(3);
let first_network = NetworkId(1);
let later_network = NetworkId(3);
let node_in = |network: NetworkId| Node { network, ..Node::dummy() };
let mut session = Session::with_peer(PeerId(1));
commit_retired(
&mut session,
RegistryDelta::AddNetwork {
id: first_network,
network: Network::default(),
},
);
commit_retired(
&mut session,
RegistryDelta::AddNode {
id: node_id,
node: node_in(first_network),
},
);
commit_retired(
&mut session,
RegistryDelta::RemoveNode {
id: node_id,
snapshot: node_in(first_network),
},
);
// Resurrects the node from the removal above, the only one so far.
commit_retired(
&mut session,
RegistryDelta::SetNetworkExport {
id: first_network,
index: 0,
export: Some(crate::NodeInput::Node { id: node_id, index: 0 }),
},
);
commit_retired(
&mut session,
RegistryDelta::AddNetwork {
id: later_network,
network: Network::default(),
},
);
// A later removal whose snapshot places the node in the network created after the export.
commit_retired(
&mut session,
RegistryDelta::RemoveNode {
id: node_id,
snapshot: node_in(later_network),
},
);
let folded = session.snapshot_from_history().expect("fold");
assert_eq!(&folded, session.retired_registry(), "the fold must reproduce the snapshot the deltas built as they landed");
}
/// The newtype is `#[serde(transparent)]`, so persisted state and the wire carry a bare number and the
/// field's encoding is unchanged.
#[test]
fn hot_sequence_serializes_as_a_bare_number() {
let encoded = serde_json::to_string(&crate::HotSequence(7)).expect("serialize");
assert_eq!(encoded, "7");
assert_eq!(serde_json::from_str::<crate::HotSequence>("7").expect("deserialize"), crate::HotSequence(7));
}
/// Retirement drains the hot log, so a retirer that never received an author's earlier op cannot
/// retire it. The later op still retires, landing beyond the author's prefix instead of extending it.
#[test]
fn retiring_over_a_gap_lands_beyond_the_prefix() {
let author = PeerId(2);
let mut host = Session::with_peer(PeerId(1));
// Only the author's second op reaches this peer; the first was lost with the link that carried it.
let second = HotOp {
op: set_document_attribute("late", 1),
timestamp: TimeStamp { counter: 9, peer: author },
sequence: crate::HotSequence(2),
};
host.apply_hot_op(second.clone()).expect("apply");
host.retire(second.timestamp).expect("retire");
let retired = host.retired_marks();
let prefix = retired.retired_up_to.get(&author).copied().unwrap_or(crate::HotSequence::NONE);
assert_eq!(prefix, crate::HotSequence::NONE, "sequence 1 never arrived, so the prefix cannot move");
assert!(retired.retired_beyond.contains_key(&author), "the retired op has to be recorded past the gap");
assert!(retired.covers(second.id()), "and still count as retired");
}
/// A gap that never fills pins the prefix, so every later op from that author lands past it. Stored as
/// runs, that stays one entry however many ops follow.
#[test]
fn a_permanent_gap_accumulates_every_later_op() {
let author = PeerId(2);
let id = |sequence: u64| crate::HotOpId {
peer: author,
sequence: crate::HotSequence(sequence),
};
let mut marks = crate::RetiredHotOps::default();
// Sequence 1 is lost for good; everything this author writes afterwards still retires.
for sequence in 2..=20 {
marks.extend([id(sequence)]);
}
let runs = marks.retired_beyond.get(&author).map(Vec::len).unwrap_or_default();
assert_eq!(runs, 1, "the ops after the gap coalesce into a single run");
for sequence in 2..=20 {
assert!(marks.covers(id(sequence)), "sequence {sequence} must stay covered");
}
assert!(!marks.covers(id(1)), "the lost op is not claimed");
}
/// A retired delta keeps its op's authoring timestamp, so the snapshot resolves LWW on the same stamps
/// the live view did rather than on retirement order.
#[test]
fn retirement_preserves_the_live_lww_winner() {
let mut host = Session::with_peer(PeerId(1));
// Same key from two authors, the newer op arriving first, so LWW keeps it and discards the older.
let newer = HotOp {
op: set_document_attribute("k", 1),
timestamp: TimeStamp { counter: 10, peer: PeerId(2) },
sequence: crate::HotSequence(1),
};
let older = HotOp {
op: set_document_attribute("k", 2),
timestamp: TimeStamp { counter: 5, peer: PeerId(3) },
sequence: crate::HotSequence(1),
};
host.apply_hot_op(newer.clone()).expect("apply newer");
host.apply_hot_op(older).expect("apply older");
let live = host.registry().attributes.get("k").cloned();
host.retire(newer.timestamp).expect("retire");
assert_eq!(host.registry().attributes.get("k"), live.as_ref(), "retirement must not move the live value");
assert_eq!(
host.retired_registry().attributes.get("k").map(|attribute| &attribute.value),
live.as_ref().map(|attribute| &attribute.value),
"the snapshot has to record the value the live view settled on"
);
}
/// A straggler LWW discarded still retires, and must not return by doing so: stamped at retirement it
/// would outrank the op that beat it, putting the discarded value into history itself.
#[test]
fn retiring_a_straggler_leaves_the_discarded_value_behind() {
let mut host = Session::with_peer(PeerId(1));
let winner = HotOp {
op: set_document_attribute("k", 1),
timestamp: TimeStamp { counter: 10, peer: PeerId(2) },
sequence: crate::HotSequence(1),
};
host.apply_hot_op(winner.clone()).expect("apply winner");
host.retire(winner.timestamp).expect("retire winner");
// Arriving behind the winner, this op loses in the live view and its value is dropped.
let straggler = HotOp {
op: set_document_attribute("k", 2),
timestamp: TimeStamp { counter: 5, peer: PeerId(3) },
sequence: crate::HotSequence(1),
};
host.apply_hot_op(straggler.clone()).expect("apply straggler");
host.retire(straggler.timestamp).expect("retire straggler");
let value = |registry: &crate::Registry| registry.attributes.get("k").map(|attribute| attribute.value.clone());
assert_eq!(value(host.registry()), Some(serde_json::json!(1)), "the live view keeps the winner");
assert_eq!(value(host.retired_registry()), Some(serde_json::json!(1)), "and retiring the straggler must not overwrite it");
let replayed = host.snapshot_from_history().expect("refold");
assert_eq!(value(&replayed), Some(serde_json::json!(1)), "nor may history replay to the discarded value");
}
/// Every field of the registry is last-writer-wins on a timestamp, whether an entity exists included, so
/// a set of ops folds to one registry whatever order it lands in. Random sets of structural and field
/// ops, attribute deletions included, over a few ids so additions, removals and writes collide, folded
/// in random orders with an op naming an entity not yet seen retried after the rest.
#[test]
fn a_set_of_ops_folds_to_one_registry_in_any_order() {
use crate::Priority;
use crate::{Implementation, ResourceEntry, SourceKey};
use graphene_resource::ResourceId;
struct Lcg(u64);
impl Lcg {
fn below(&mut self, bound: u64) -> u64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(self.0 >> 33) % bound
}
}
fn random_op(rng: &mut Lcg, at: TimeStamp) -> RegistryDelta {
let node_id = NodeId(1 + rng.below(4));
let network_id = NetworkId(1 + rng.below(3));
let resource_id = ResourceId::from(1 + rng.below(2));
let input = |rng: &mut Lcg| match rng.below(3) {
0 => crate::NodeInput::Node {
id: NodeId(1 + rng.below(4)),
index: 0,
},
_ => crate::NodeInput::Value {
value: serde_json::json!(rng.below(100)),
exposed: false,
},
};
match rng.below(18) {
0 => RegistryDelta::AddNetwork {
id: network_id,
network: Network::default(),
},
1 => RegistryDelta::RemoveNetwork {
id: network_id,
snapshot: Network::default(),
},
2 | 3 => RegistryDelta::AddNode {
id: node_id,
node: Node::new(network_id, Implementation::ProtoNode(ResourceId::from(7)), 1 + rng.below(2) as usize),
},
// A real snapshot is a fold of ops the remover saw, so two snapshots agreeing on a stamp agree on the
// value; a fabricated one has to be constant for that to hold.
4 => RegistryDelta::RemoveNode {
id: node_id,
snapshot: Node::new(NetworkId(1), Implementation::ProtoNode(ResourceId::from(7)), 2),
},
5 | 6 => RegistryDelta::ChangeNodeInput {
id: node_id,
index: rng.below(2) as u32,
new_input: input(rng),
},
7 => RegistryDelta::SetNodeInputs {
id: node_id,
inputs: (0..1 + rng.below(3))
.map(|_| InputSlot {
input: input(rng),
timestamp: TimeStamp::ORIGIN,
attributes: Default::default(),
attributes_timestamp: TimeStamp::ORIGIN,
})
.collect(),
},
8 => RegistryDelta::ChangeNodeAttribute {
id: node_id,
delta: crate::AttributeDelta {
key: ["name", "lock"][rng.below(2) as usize].into(),
value: (rng.below(4) > 0).then(|| serde_json::json!(rng.below(100))),
},
},
15 => RegistryDelta::ChangeNodeInputAttribute {
id: node_id,
index: rng.below(2) as u32,
delta: crate::AttributeDelta {
key: "label".into(),
value: (rng.below(4) > 0).then(|| serde_json::json!(rng.below(100))),
},
},
16 => RegistryDelta::ChangeNetworkAttribute {
id: network_id,
delta: crate::AttributeDelta {
key: "name".into(),
value: (rng.below(4) > 0).then(|| serde_json::json!(rng.below(100))),
},
},
9 => RegistryDelta::SetNodeImplementation {
id: node_id,
implementation: match rng.below(2) {
0 => Implementation::Network(network_id),
_ => Implementation::ProtoNode(ResourceId::from(rng.below(3))),
},
},
10 => RegistryDelta::SetNetworkExport {
id: network_id,
index: rng.below(2) as u32,
export: match rng.below(2) {
0 => None,
_ => Some(input(rng)),
},
},
11 => RegistryDelta::AddResource {
id: resource_id,
entry: ResourceEntry::default(),
},
12 => RegistryDelta::RemoveResource {
id: resource_id,
snapshot: ResourceEntry::default(),
},
13 => RegistryDelta::SetResourceHash {
id: resource_id,
hash: Some(graphene_resource::ResourceHash::from([rng.below(2) as u8; 32])),
},
_ => RegistryDelta::AddSource {
id: resource_id,
key: SourceKey {
priority: Priority::new(rng.below(2) as f64).expect("finite"),
peer: at.peer,
},
source: serde_json::json!(rng.below(100)),
},
}
}
/// Folds the ops in the order given, retrying the ones that name an entity not yet seen until no
/// retry lands, and returns the working registry.
fn fold(ops: &[(RegistryDelta, TimeStamp)]) -> crate::Registry {
let mut document = fresh_document(PeerId(9));
let mut pending: Vec<&(RegistryDelta, TimeStamp)> = ops.iter().collect();
loop {
let before = pending.len();
pending.retain(|(op, at)| document.apply_op_idempotent(op.clone(), *at).is_err());
if pending.is_empty() || pending.len() == before {
return document.working_registry;
}
}
}
for seed in 0..300u64 {
let mut rng = Lcg(seed);
let ops: Vec<(RegistryDelta, TimeStamp)> = (0..8 + rng.below(24))
.map(|i| {
let at = TimeStamp {
counter: 1 + i,
peer: PeerId(1 + rng.below(3)),
};
(random_op(&mut rng, at), at)
})
.collect();
let reference = fold(&ops);
for _ in 0..6 {
let mut shuffled = ops.clone();
for i in (1..shuffled.len()).rev() {
shuffled.swap(i, rng.below(i as u64 + 1) as usize);
}
let folded = fold(&shuffled);
assert_eq!(
folded,
reference,
"seed {seed}: the ops {:?} folded differently in the order {:?}",
ops.iter().map(|(_, at)| at.counter).collect::<Vec<_>>(),
shuffled.iter().map(|(_, at)| at.counter).collect::<Vec<_>>()
);
}
}
}
/// A removal's snapshot is a copy of the node, stamped exactly as the addition stamped it. Folding it in
/// must keep what the addition wrote: an entry stamped at a map's floor was written by the same op that
/// set the floor, not before it. Caught in the editor as a revived node missing `reflection_metadata`.
#[test]
fn a_removal_snapshot_keeps_the_attributes_the_addition_wrote() {
use crate::{AttributesRead, AttributesWrite};
let mut document = fresh_document(PeerId(1));
let node_id = NodeId(4);
let mut node = Node::new(ROOT_NETWORK, crate::Implementation::ProtoNode(graphene_resource::ResourceId::from(7)), 1);
node.attributes.set("ui::name", serde_json::json!("Layer"), TimeStamp::ORIGIN);
node.inputs[0].attributes.set("reflection_metadata", serde_json::json!("meta"), TimeStamp::ORIGIN);
commit_op(
&mut document,
RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
);
commit_op(&mut document, RegistryDelta::AddNode { id: node_id, node });
let added = document.working_registry.node_instances[&node_id].clone();
// A removal and a concurrent, newer write to the node: the write revives it from the tombstone.
let removed_at = document.clock.tick();
document
.apply_op_idempotent(RegistryDelta::RemoveNode { id: node_id, snapshot: added.clone() }, removed_at)
.expect("removal");
let written_at = document.clock.tick();
document
.apply_op_idempotent(
RegistryDelta::ChangeNodeAttribute {
id: node_id,
delta: crate::AttributeDelta {
key: "ui::lock".into(),
value: Some(serde_json::json!(true)),
},
},
written_at,
)
.expect("write");
let revived = &document.working_registry.node_instances[&node_id];
assert_eq!(
revived.attributes.get_typed::<String>("ui::name").as_deref(),
Some("Layer"),
"the node attribute the addition wrote survives"
);
assert_eq!(
revived.inputs()[0].attributes.get_typed::<String>("reflection_metadata").as_deref(),
Some("meta"),
"the slot attribute the addition wrote survives"
);
// The same snapshot folding into the live node, from a removal too old to land, changes nothing.
let mut untouched = document.clone();
untouched
.apply_op_idempotent(RegistryDelta::RemoveNode { id: node_id, snapshot: added }, removed_at)
.expect("a replayed removal");
assert_eq!(untouched.working_registry, document.working_registry);
}
@@ -0,0 +1,156 @@
use std::collections::BTreeSet;
use core_types::uuid::NodeId as RuntimeNodeId;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
use crate::{NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, Registry};
fn proto(identifier: &'static str, inputs: Vec<NodeInput>) -> DocumentNode {
DocumentNode {
inputs,
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
..Default::default()
}
}
/// A root network holding a proto node and a group, with another proto node and a nested group inside
/// the group, so projection is exercised two networks deep.
fn nested_network() -> NodeNetwork {
let inner = NodeNetwork {
exports: vec![NodeInput::node(RuntimeNodeId(30), 0)],
nodes: [(RuntimeNodeId(30), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::import(concrete!(u32), 0)]))]
.into_iter()
.collect(),
..Default::default()
};
let group = NodeNetwork {
exports: vec![NodeInput::node(RuntimeNodeId(20), 0)],
nodes: [
(RuntimeNodeId(20), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::node(RuntimeNodeId(21), 0)])),
(
RuntimeNodeId(21),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Integer(3), false)],
implementation: DocumentNodeImplementation::Network(inner),
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
};
NodeNetwork {
exports: vec![NodeInput::node(RuntimeNodeId(1), 0)],
nodes: [
(RuntimeNodeId(1), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::node(RuntimeNodeId(2), 0)])),
(
RuntimeNodeId(2),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Integer(7), true)],
implementation: DocumentNodeImplementation::Network(group),
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
}
}
fn find_node<'a>(network: &'a NodeNetwork, path: &[RuntimeNodeId], id: RuntimeNodeId) -> &'a DocumentNode {
let nested = network.nested_network(path).expect("the path should resolve");
nested.nodes.get(&id).expect("the node should exist")
}
/// A node projected on its own must be what the whole-document conversion holds for it, metadata
/// included, since a mirror patched from projections has to match a mirror rebuilt whole.
#[test]
fn projecting_a_node_matches_the_whole_conversion() {
let resources = graphene_resource::ResourceRegistry::new();
let conversion = Registry::convert_from_runtime(&nested_network(), &NoMetadata, &resources, PeerId(1)).expect("conversion");
let registry = &conversion.registry;
let (whole, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
let projection = registry.runtime_projection(&conversion.declarations);
for &id in registry.node_instances.keys() {
let projected = projection.node(id).expect("every stored node projects");
let (path, local_id) = projection.node_address(id).expect("every stored node has an address");
assert_eq!((path.as_slice(), local_id), (projected.network_path.as_slice(), projected.local_id));
assert_eq!(
&projected.node,
find_node(&whole, &path, local_id),
"node {id} projected differently than the whole conversion converts it"
);
let own_entry = node_entries.iter().find(|entry| entry.storage_id == id).expect("the whole conversion emits an entry per node");
assert_eq!(projected.node_entries.first(), Some(own_entry), "the node's own entry comes first");
// The nested entries are exactly the whole conversion's entries under this node.
let nested_prefix: Vec<RuntimeNodeId> = [path.as_slice(), &[local_id]].concat();
let expected_nested: BTreeSet<_> = node_entries
.iter()
.filter(|entry| entry.network_path.starts_with(&nested_prefix))
.map(|entry| entry.storage_id)
.collect();
let projected_nested: BTreeSet<_> = projected.node_entries.iter().skip(1).map(|entry| entry.storage_id).collect();
assert_eq!(projected_nested, expected_nested, "nested node entries under {id}");
let expected_networks: BTreeSet<_> = network_entries
.iter()
.filter(|entry| entry.network_path.starts_with(&nested_prefix))
.map(|entry| entry.network_id)
.collect();
let projected_networks: BTreeSet<_> = projected.network_entries.iter().map(|entry| entry.network_id).collect();
assert_eq!(projected_networks, expected_networks, "nested network entries under {id}");
}
}
#[test]
fn a_network_entry_projects_its_dense_exports_and_path() {
let resources = graphene_resource::ResourceRegistry::new();
let conversion = Registry::convert_from_runtime(&nested_network(), &NoMetadata, &resources, PeerId(1)).expect("conversion");
let registry = &conversion.registry;
let (whole, _, _) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
let projection = registry.runtime_projection(&conversion.declarations);
let root = projection.network_entry(ROOT_NETWORK).expect("root");
assert!(root.network_path.is_empty());
assert_eq!(root.exports, whole.exports);
for &network_id in registry.networks.keys() {
let entry = projection.network_entry(network_id).expect("every stored network projects");
let nested = whole.nested_network(&entry.network_path).expect("the projected path exists in the whole conversion");
assert_eq!(entry.exports, nested.exports, "exports of the network at {:?}", entry.network_path);
assert_eq!(entry.scope_injections, nested.scope_injections);
if let Some(owner) = projection.owner(network_id) {
let (owner_path, owner_local) = projection.node_address(owner).expect("owner address");
assert_eq!(
entry.network_path,
[owner_path.as_slice(), &[owner_local]].concat(),
"a network's path ends in the node implementing it"
);
}
}
}
/// A network no node implements is not in the runtime, so nothing inside it has an address.
#[test]
fn an_unreachable_network_has_no_address() {
let mut registry = Registry::default();
registry.networks.insert(crate::NetworkId(5), crate::Network::default());
let mut node = Node::dummy();
node.network = crate::NetworkId(5);
registry.node_instances.insert(NodeId(9), node);
let declarations = crate::Declarations::new();
let projection = registry.runtime_projection(&declarations);
assert_eq!(projection.network_path(crate::NetworkId(5)), None);
assert_eq!(projection.node_address(NodeId(9)), None);
assert!(matches!(projection.node(NodeId(9)), Err(crate::to_runtime::ConversionError::NetworkNotFound(_))));
}
+17 -9
View File
@@ -20,12 +20,10 @@ fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
/// Convert a runtime network to a storage `Registry`, returning the declarations alongside it.
/// Proto-node declaration content is no longer stored in the registry (it lives in a byte store);
/// these tests have no byte store, so they keep the extracted bytes in hand and rebuild a
/// `Declarations` map for the back-conversion.
/// these tests have no byte store, so they keep the extracted `Declarations` in hand for the back-conversion.
fn to_registry(network: &NodeNetwork) -> (Registry, crate::Declarations) {
let conversion = Registry::convert_from_runtime(network, &crate::NoMetadata, &Default::default(), PeerId(0)).expect("Failed to convert NodeNetwork to Registry");
let declarations = conversion.declarations().expect("rebuild declarations");
(conversion.registry, declarations)
(conversion.registry, conversion.declarations)
}
/// A one-node network whose single node references `id` via a `TaggedValue::Resource` input, so
@@ -477,7 +475,7 @@ fn test_ui_metadata_round_trip() {
);
let conversion = Registry::convert_from_runtime(&network, &metadata, &Default::default(), PeerId(0)).expect("Failed to convert to Registry with metadata");
let declarations = conversion.declarations().expect("rebuild declarations");
let declarations = conversion.declarations;
let registry = conversion.registry;
let (converted, entries) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back with metadata");
@@ -611,7 +609,7 @@ fn unreferenced_runtime_resource_is_not_snapshotted() {
assert!(!registry.resources.contains_key(&orphan), "the unreferenced (orphan) resource must not be snapshotted");
}
/// A node-input `TaggedValue::F64` must survive the storage round-trip bit-exact. Inputs are stored as a
/// A node-input `TaggedValue::Number` must survive the storage round-trip bit-exact. Inputs are stored as a
/// self-describing `serde_json::Value` (encoded with the registry's MessagePack codec), so this guards
/// against any precision loss in the f64 -> serde_json::Number -> f64 path for a value with a full
/// 17-significant-digit mantissa.
@@ -625,7 +623,7 @@ fn node_input_f64_round_trips_bit_exact() {
nodes: [(
NodeId(0),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::F64(precise), false)],
inputs: vec![NodeInput::value(TaggedValue::Number(precise), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
..Default::default()
},
@@ -642,8 +640,8 @@ fn node_input_f64_round_trips_bit_exact() {
let NodeInput::Value { tagged_value, .. } = input else {
panic!("expected a value input, got {input:?}")
};
let TaggedValue::F64(actual) = &**tagged_value else {
panic!("expected F64, got {:?}", tagged_value)
let TaggedValue::Number(actual) = &**tagged_value else {
panic!("expected Number, got {:?}", tagged_value)
};
assert_eq!(actual.to_bits(), precise.to_bits(), "f64 node input drifted: {actual} != {precise}");
@@ -760,18 +758,28 @@ fn cyclic_network_reference_is_rejected() {
registry.node_instances.insert(
crate::NodeId(0),
Node {
presence: Default::default(),
added: Default::default(),
inputs_timestamp: Default::default(),
implementation: Implementation::Network(child_network_id),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
attributes: crate::Attributes::default(),
attributes_timestamp: Default::default(),
network: crate::ROOT_NETWORK,
},
);
registry.node_instances.insert(
crate::NodeId(1),
Node {
presence: Default::default(),
added: Default::default(),
inputs_timestamp: Default::default(),
implementation: Implementation::Network(crate::ROOT_NETWORK),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
attributes: crate::Attributes::default(),
attributes_timestamp: Default::default(),
network: child_network_id,
},
);
+165 -26
View File
@@ -38,7 +38,8 @@ pub enum ConversionError {
pub type Declarations = std::collections::HashMap<ResourceId, ProtoNode>;
impl Registry {
/// Returns the network plus per-node metadata entries (one per node carrying any `ui::*` attribute).
/// Returns the network plus one metadata entry per node, since every node carries an identity to
/// restore even when it has no `ui::*` attribute.
pub fn to_runtime_with_metadata(&self, declarations: &Declarations) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>), ConversionError> {
let (network, node_entries, _) = self.to_runtime_with_full_metadata(declarations)?;
Ok((network, node_entries))
@@ -50,19 +51,10 @@ impl Registry {
let mut node_metadata = Some(Vec::new());
let mut network_metadata = Some(Vec::new());
// Group nodes by their owning network in one pass, so each `convert_network` call (one per
// Nodes are grouped by their owning network in one pass, so each `convert_network` call (one per
// network, including nested ones) takes its node list by lookup instead of rescanning the whole
// flat `node_instances` map, which would be quadratic on graphs with many networks.
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
for (&global_id, node) in &self.node_instances {
nodes_by_network.entry(node.network).or_default().push((global_id, node));
}
let context = ConversionContext {
registry: self,
declarations,
nodes_by_network,
};
let context = ConversionContext::new(self, declarations);
// Reject cycles up front so the recursive conversion below can assume the network reference
// graph is acyclic and never blow the stack on a self-referential `Implementation::Network`.
@@ -81,7 +73,7 @@ impl Registry {
let mut registry = graphene_resource::ResourceRegistry::new();
for (id, entry) in &self.resources {
for (_, source) in &entry.sources {
for (_, source) in entry.live_sources() {
let decoded: graphene_resource::DataSource = serde_json::from_value(source.source.clone()).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
registry.push_source_back(id, decoded);
}
@@ -103,6 +95,155 @@ struct ConversionContext<'a> {
nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &'a Node)>>,
}
impl<'a> ConversionContext<'a> {
fn new(registry: &'a Registry, declarations: &'a Declarations) -> Self {
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
for (&global_id, node) in &registry.node_instances {
nodes_by_network.entry(node.network).or_default().push((global_id, node));
}
Self {
registry,
declarations,
nodes_by_network,
}
}
}
/// The id the node had in the runtime it was converted from, which storage keeps as an attribute so a
/// conversion back lands the node under the id the editor's metadata is keyed by.
fn runtime_node_id(global_id: NodeId, node: &Node) -> RuntimeNodeId {
RuntimeNodeId(node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|value| value.value.as_u64()).unwrap_or(global_id.0))
}
/// One node in runtime form together with the metadata for it and everything nested under it, as
/// [`RuntimeProjection::node`] produces it. Entry paths are absolute, the way a whole-document
/// conversion writes them.
pub struct ProjectedNode {
/// The runtime path of the network the node sits in.
pub network_path: Vec<RuntimeNodeId>,
pub local_id: RuntimeNodeId,
pub node: DocumentNode,
/// The node's own entry first, then one per nested node.
pub node_entries: Vec<NodeMetadataEntry>,
/// One per network the node's implementation nests, outermost first.
pub network_entries: Vec<NetworkMetadataEntry>,
}
/// A network's own runtime form without its nodes, as [`RuntimeProjection::network_entry`] produces it.
pub struct ProjectedNetwork {
pub network_path: Vec<RuntimeNodeId>,
/// Dense, the way the runtime holds them: a storage slot holding nothing is skipped.
pub exports: Vec<GraphCraftNodeInput>,
pub scope_injections: FxHashMap<String, (RuntimeNodeId, Type)>,
pub metadata: NetworkMetadataEntry,
}
/// Converts single entities of the registry to their runtime form, for a caller keeping a runtime
/// mirror in step with the registry rather than rebuilding it. Owner relationships are gathered once at
/// construction so each address lookup is a probe.
pub struct RuntimeProjection<'a> {
context: ConversionContext<'a>,
/// The node whose implementation each nested network is.
owners: FxHashMap<NetworkId, NodeId>,
}
impl Registry {
pub fn runtime_projection<'a>(&'a self, declarations: &'a Declarations) -> RuntimeProjection<'a> {
let owners = self
.node_instances
.iter()
.filter_map(|(&id, node)| match node.implementation {
Implementation::Network(network) => Some((network, id)),
Implementation::ProtoNode(_) => None,
})
.collect();
RuntimeProjection {
context: ConversionContext::new(self, declarations),
owners,
}
}
}
impl RuntimeProjection<'_> {
/// The node implementing `network`, or `None` for the root and for a network no node implements.
pub fn owner(&self, network: NetworkId) -> Option<NodeId> {
self.owners.get(&network).copied()
}
/// The runtime path of `network`: the nodes implementing it and its ancestors, outermost first.
/// `None` for a network the root does not reach, which the runtime does not hold.
pub fn network_path(&self, network: NetworkId) -> Option<Vec<RuntimeNodeId>> {
let mut chain = Vec::new();
let mut current = network;
while current != ROOT_NETWORK {
let owner = self.owner(current)?;
let node = self.context.registry.node_instances.get(&owner)?;
// Owners can form a cycle through concurrent implementation swaps, which the runtime rejects.
if chain.contains(&owner) {
return None;
}
chain.push(owner);
current = node.network;
}
Some(chain.into_iter().rev().map(|owner| runtime_node_id(owner, &self.context.registry.node_instances[&owner])).collect())
}
/// Where the node sits in the runtime: the path of its network, and its id within that network.
pub fn node_address(&self, id: NodeId) -> Option<(Vec<RuntimeNodeId>, RuntimeNodeId)> {
let node = self.context.registry.node_instances.get(&id)?;
Some((self.network_path(node.network)?, runtime_node_id(id, node)))
}
/// The node and everything nested under it, converted the way a whole-document conversion converts
/// them, so a mirror patched with the result matches a rebuild.
pub fn node(&self, id: NodeId) -> Result<ProjectedNode, ConversionError> {
let node = self.context.registry.node_instances.get(&id).ok_or(ConversionError::NodeNotFound(id))?;
let network_path = self.network_path(node.network).ok_or(ConversionError::NetworkNotFound(node.network))?;
let local_id = runtime_node_id(id, node);
if let Implementation::Network(nested) = node.implementation {
detect_network_cycle(&self.context, nested)?;
}
let mut node_entries = Some(vec![extract_ui_metadata(node, id, &network_path, local_id)]);
let mut network_entries = Some(Vec::new());
let document_node = convert_node(&self.context, node, &network_path, local_id, &mut node_entries, &mut network_entries)?;
Ok(ProjectedNode {
network_path,
local_id,
node: document_node,
node_entries: node_entries.expect("seeded above"),
network_entries: network_entries.expect("seeded above"),
})
}
/// The network's exports, scope injections and metadata, without its nodes.
pub fn network_entry(&self, id: NetworkId) -> Result<ProjectedNetwork, ConversionError> {
let registry = self.context.registry;
// A network removed concurrently with a write into it renders as it was, so the nodes still in it
// keep their place.
let network = registry.network_or_removed(id).ok_or(ConversionError::NetworkNotFound(id))?;
let network_path = self.network_path(id).ok_or(ConversionError::NetworkNotFound(id))?;
let empty_attrs = crate::Attributes::new();
let exports = network
.exports
.iter()
.filter_map(|slot| slot.target.as_ref())
.map(|input| convert_input(registry, id, input, &empty_attrs))
.collect::<Result<Vec<_>, _>>()?;
Ok(ProjectedNetwork {
metadata: extract_network_metadata(registry, &network.attributes, &network_path, id),
scope_injections: read_scope_injections(registry, id, &network.attributes)?,
exports,
network_path,
})
}
}
/// Converts a single network. Recurses through `Implementation::Network` owning nodes.
///
/// **ID remapping:** Registry uses globally hashed IDs; runtime networks need local IDs. We pull
@@ -165,7 +306,7 @@ fn convert_network(
node_collector: &mut Option<Vec<NodeMetadataEntry>>,
network_collector: &mut Option<Vec<NetworkMetadataEntry>>,
) -> Result<NodeNetwork, ConversionError> {
let network = context.registry.networks.get(&network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
let network = context.registry.network_or_removed(network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
if let Some(collector) = network_collector.as_mut() {
collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id));
@@ -173,8 +314,8 @@ fn convert_network(
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
for &(global_id, node) in context.nodes_by_network.get(&network_id).map(Vec::as_slice).unwrap_or_default() {
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(global_id.0);
let runtime_id = RuntimeNodeId(local_id);
let runtime_id = runtime_node_id(global_id, node);
let local_id = runtime_id.0;
if let Some(collector) = node_collector.as_mut() {
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
@@ -231,8 +372,7 @@ fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes:
});
};
let local_id = referenced.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(storage_id.0);
Ok((key, (RuntimeNodeId(local_id), ty)))
Ok((key, (runtime_node_id(storage_id, referenced), ty)))
})
.collect()
}
@@ -266,12 +406,11 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
/// Node references stored here are storage IDs, resolved back to runtime-local IDs the way
/// `read_scope_injections` does. A reference to a node that is no longer in this network is dropped
/// rather than failing the conversion: the preview target or a pinned node can have been deleted.
/// rather than failing the conversion: a pinned node can have been deleted.
fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
let to_runtime_id = |storage_id: NodeId| {
let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?;
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|value| value.value.as_u64()).unwrap_or(storage_id.0);
Some(RuntimeNodeId(local_id))
Some(runtime_node_id(storage_id, node))
};
let pinned_order = attributes
@@ -291,8 +430,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
/// Reassembles `input_data` by scanning every attribute under `ui::input_data::` and stripping the prefix.
fn extract_input_metadata(attributes: &crate::Attributes) -> InputMetadataEntry {
let input_data: HashMap<String, serde_json::Value> = attributes
.iter()
let input_data: HashMap<String, serde_json::Value> = crate::attributes::live(attributes)
.filter_map(|(key, value)| key.strip_prefix(node::input::ui::DATA_PREFIX).map(|sub_key| (sub_key.to_owned(), value.value.clone())))
.collect();
@@ -334,7 +472,9 @@ fn convert_node(
fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
Ok(match input {
NodeInput::Node { id: node_id, index: output_index } => {
let referenced = registry.node_instances.get(node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
// A reference to a node removed concurrently keeps the id it had, the way the editor holds a
// dangling input; only a node never seen has no id to map to.
let referenced = registry.node_or_removed(*node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
// Runtime references are local to one network. A cross-network reference would remap to a
// local ID that doesn't exist in the current runtime network, so reject it.
@@ -345,9 +485,8 @@ fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput,
});
}
let local_id = referenced.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(node_id.0);
GraphCraftNodeInput::Node {
node_id: RuntimeNodeId(local_id),
node_id: runtime_node_id(*node_id, referenced),
output_index: *output_index as usize,
}
}
+146
View File
@@ -0,0 +1,146 @@
//! Which entities a run of ops named, for a runtime mirror of the registry to bring back into line
//! without being rebuilt from the whole registry.
//!
//! The set is over-approximate on purpose: an op is recorded whether or not it changed anything, so a
//! late-writer-wins loser, an idempotent replay and a failed apply all land here. What the op did to the
//! registry is settled by comparing the entity's stored and mirrored forms afterwards, which is cheaper
//! than having every apply arm report its outcome and stays correct when an op resurrects an entity it
//! only references.
use std::collections::BTreeSet;
use crate::{NetworkId, NodeId, NodeInput, RegistryDelta};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Touched {
pub nodes: BTreeSet<NodeId>,
pub networks: BTreeSet<NetworkId>,
/// Some resource entry changed. Resources are mirrored as one registry rather than per entity.
pub resources: bool,
}
impl Touched {
/// Records every entity `op` names: its target, and any node it references, since applying it can
/// resurrect a referenced node that was concurrently removed.
pub fn record(&mut self, op: &RegistryDelta) {
match op {
RegistryDelta::AddNode { id, node } => {
self.nodes.insert(*id);
self.reference_inputs(node.inputs().iter().map(|slot| &slot.input));
}
RegistryDelta::RemoveNode { id, .. }
| RegistryDelta::SetNodeImplementation { id, .. }
| RegistryDelta::ChangeNodeAttribute { id, .. }
| RegistryDelta::ChangeNodeInputAttribute { id, .. } => {
self.nodes.insert(*id);
}
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
self.nodes.insert(*id);
self.reference_inputs([new_input]);
}
RegistryDelta::SetNodeInputs { id, inputs } => {
self.nodes.insert(*id);
self.reference_inputs(inputs.iter().map(|slot| &slot.input));
}
RegistryDelta::SetNetworkExport { id, export, .. } => {
self.networks.insert(*id);
self.reference_inputs(export.iter());
}
RegistryDelta::ChangeNetworkAttribute { id, .. } | RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => {
self.networks.insert(*id);
}
RegistryDelta::AddResource { .. } | RegistryDelta::SetResourceHash { .. } | RegistryDelta::RemoveResource { .. } | RegistryDelta::AddSource { .. } | RegistryDelta::RemoveSource { .. } => {
self.resources = true;
}
RegistryDelta::RegisterPeer { .. } | RegistryDelta::ChangeDocumentAttribute { .. } | RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {}
}
}
pub fn extend(&mut self, other: Touched) {
self.nodes.extend(other.nodes);
self.networks.extend(other.networks);
self.resources |= other.resources;
}
pub fn is_empty(&self) -> bool {
self.nodes.is_empty() && self.networks.is_empty() && !self.resources
}
fn reference_inputs<'a>(&mut self, inputs: impl IntoIterator<Item = &'a NodeInput>) {
for input in inputs {
if let NodeInput::Node { id, .. } = input {
self.nodes.insert(*id);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{AttributeDelta, Network, Node};
#[test]
fn an_input_write_touches_the_node_it_references_as_well_as_its_target() {
let mut touched = Touched::default();
touched.record(&RegistryDelta::ChangeNodeInput {
id: NodeId(1),
index: 0,
new_input: NodeInput::Node { id: NodeId(2), index: 0 },
});
assert_eq!(touched.nodes, BTreeSet::from([NodeId(1), NodeId(2)]));
assert!(touched.networks.is_empty());
assert!(!touched.resources);
}
#[test]
fn an_export_touches_the_network_and_the_node_it_targets() {
let mut touched = Touched::default();
touched.record(&RegistryDelta::SetNetworkExport {
id: NetworkId(3),
index: 0,
export: Some(NodeInput::Node { id: NodeId(4), index: 0 }),
});
assert_eq!(touched.networks, BTreeSet::from([NetworkId(3)]));
assert_eq!(touched.nodes, BTreeSet::from([NodeId(4)]));
}
#[test]
fn ops_outside_the_graph_touch_nothing_or_only_the_resource_flag() {
let mut touched = Touched::default();
touched.record(&RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta { key: "key".into(), value: None },
});
touched.record(&RegistryDelta::Merge { extra_parents: Vec::new() });
assert!(touched.is_empty());
touched.record(&RegistryDelta::SetResourceHash {
id: crate::ResourceId::new(),
hash: None,
});
assert!(touched.resources);
assert!(touched.nodes.is_empty());
}
#[test]
fn a_node_add_touches_the_node_and_what_its_inputs_reference() {
let mut node = Node::dummy();
node.inputs.push(crate::InputSlot {
input: NodeInput::Node { id: NodeId(9), index: 0 },
timestamp: crate::TimeStamp::ORIGIN,
attributes: Default::default(),
attributes_timestamp: crate::TimeStamp::ORIGIN,
});
let mut touched = Touched::default();
touched.record(&RegistryDelta::AddNode { id: NodeId(8), node });
touched.record(&RegistryDelta::AddNetwork {
id: NetworkId(5),
network: Network::default(),
});
assert_eq!(touched.nodes, BTreeSet::from([NodeId(8), NodeId(9)]));
assert_eq!(touched.networks, BTreeSet::from([NetworkId(5)]));
}
}
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "document-live"
description = "A memory-backed document following or hosting a collaborative session, for viewers and embedders"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[dependencies]
document-container = { workspace = true }
document-format = { workspace = true }
document-graph-storage = { workspace = true }
peer-transport = { workspace = true }
graph-craft = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
[lints]
workspace = true
+124
View File
@@ -0,0 +1,124 @@
//! A document that lives in a collaborative session rather than on disk. Hosts a session or follows
//! one, and hands out the current runtime `NodeNetwork` on demand. Owns no executor, window, or
//! async runtime: the caller spawns the transport driver and decides how to render.
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout, ResourceProxy};
use document_graph_storage::{PeerId, UserId};
use graph_craft::application_io::resource::ResourceHash;
use graph_craft::document::NodeNetwork;
use peer_transport::{Room, SyncTarget};
pub use document_format::Error as FormatError;
pub use document_graph_storage::to_runtime::ConversionError;
pub use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, MessageLoopFuture, Role, SessionToken};
#[derive(Debug, thiserror::Error)]
pub enum LiveError {
#[error(transparent)]
Format(#[from] FormatError),
#[error(transparent)]
Conversion(#[from] ConversionError),
}
pub struct LiveDocument {
gdd: GddV1,
token: SessionToken,
}
impl LiveDocument {
/// Create an empty document and host a session under `token`. `spawn` must drive the returned
/// future for as long as the session lives.
pub async fn host(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
let gdd = Self::empty_document(peer).await?;
Ok(Self::host_document(gdd, signaling_server, token, user, spawn))
}
/// Host a session on an already opened document.
pub fn host_document(mut gdd: GddV1, signaling_server: &str, token: SessionToken, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Self {
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
spawn(driver);
gdd.share(room, user);
Self { gdd, token }
}
/// Join the session under `token`; the document fills in once the host's sync arrives.
pub async fn join(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
let mut gdd = Self::empty_document(peer).await?;
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
spawn(driver);
gdd.join(room, user);
Ok(Self { gdd, token })
}
async fn empty_document(peer: PeerId) -> Result<GddV1, FormatError> {
let version = env!("CARGO_PKG_VERSION").to_string();
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, peer, UserId(peer.0), peer.0, version.clone(), version).await
}
pub fn token(&self) -> SessionToken {
self.token
}
pub fn role(&self) -> Option<Role> {
self.gdd.role()
}
pub fn is_synced(&self) -> bool {
self.gdd.is_synced()
}
/// Synced and holding every resource the document references, so `network` can be built and run.
pub fn is_ready(&self) -> bool {
self.is_synced() && SyncTarget::missing_resources(&self.gdd).is_empty()
}
/// Resources the document references whose bytes no peer has sent yet; `is_ready` waits on them.
pub fn missing_resources(&self) -> Vec<ResourceHash> {
let mut missing: Vec<ResourceHash> = SyncTarget::missing_resources(&self.gdd).into_iter().collect();
missing.sort_unstable();
missing
}
/// Apply whatever peers sent since the last call and answer their resource requests. Call it regularly.
pub async fn poll(&mut self) -> Vec<Event> {
let events = self.gdd.poll_peers();
for event in &events {
let Event::ResourceRequested { from, hash } = event else { continue };
match self.gdd.read_resource(hash).await {
Ok(bytes) => {
if let Err(error) = self.gdd.send_resource(*from, *hash, bytes.as_slice().to_vec()) {
log::warn!("Failed to send resource {hash}: {error}");
}
}
Err(error) => log::warn!("Peer asked for resource {hash} which is not in this document: {error}"),
}
}
events
}
pub fn document(&self) -> &GddV1 {
&self.gdd
}
pub fn document_mut(&mut self) -> &mut GddV1 {
&mut self.gdd
}
/// The current runtime graph, rebuilt from the registry. Async because proto-node declarations are resources.
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
let declarations = self.gdd.declarations(&self.gdd).await;
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations)?;
Ok(network)
}
/// Byte store for resources received from peers, for an executor to load from.
pub fn resource_proxy(&self) -> ResourceProxy<GddV1Layout> {
self.gdd.resource_proxy()
}
pub fn leave(&mut self) {
self.gdd.leave();
}
}
+34
View File
@@ -0,0 +1,34 @@
[package]
name = "peer-transport"
description = "Peer-to-peer sync of hot ops and retired history between document-graph-storage sessions over WebRTC"
rust-version.workspace = true
edition.workspace = true
authors.workspace = true
homepage.workspace = true
repository.workspace = true
license.workspace = true
version.workspace = true
publish.workspace = true
[dependencies]
core-types = { workspace = true }
document-graph-storage = { workspace = true }
matchbox_socket = "0.14.0"
futures = { workspace = true }
log = { workspace = true }
serde = { workspace = true }
serde_bytes = { workspace = true }
rmp-serde = { workspace = true }
base64 = { workspace = true }
thiserror = { workspace = true }
uuid = "1"
[target.'cfg(not(target_family = "wasm"))'.dependencies]
rustls = { version = "0.23", default-features = false, features = ["ring"] }
[dev-dependencies]
serde_json = { workspace = true }
env_logger = { workspace = true }
[lints]
workspace = true
+19
View File
@@ -0,0 +1,19 @@
pub mod mock;
mod packet;
mod replica;
mod room;
mod target;
mod token;
mod transport;
pub use packet::{CursorPosition, CursorSpace, PacketError, Role, SyncPacket, SyncPayload};
pub use replica::{Event, RemotePeer, Replica, ReplicaError};
pub use room::{Incoming, Room};
pub use target::{SyncTarget, TargetError};
pub use token::{InvalidSessionToken, SessionToken};
pub use transport::{Transport, TransportEvent, TransportPeerId};
pub use matchbox_socket::MessageLoopFuture;
/// Matchbox signaling server for sessions, behind TLS so browsers on HTTPS pages can reach it.
pub const DEFAULT_SIGNALING_SERVER: &str = "wss://graphite.kobert.dev";
+175
View File
@@ -0,0 +1,175 @@
//! In-process transport for deterministic simulation. Every packet sits in a per-(sender, receiver)
//! queue until `step` delivers it, so interleavings across peers are driven by the seed while each
//! pair stays ordered like a reliable channel.
use crate::packet::{PacketError, SyncPacket};
use crate::transport::{Transport, TransportEvent, TransportPeerId};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::{Arc, Mutex};
#[derive(Default)]
struct Shared {
connected: Vec<TransportPeerId>,
inboxes: HashMap<TransportPeerId, VecDeque<TransportEvent>>,
in_flight: BTreeMap<(TransportPeerId, TransportPeerId), VecDeque<SyncPacket>>,
next_peer: u128,
}
impl Shared {
fn disconnect(&mut self, id: TransportPeerId) {
self.connected.retain(|&other| other != id);
self.in_flight.retain(|&(from, to), _| from != id && to != id);
for &other in &self.connected.clone() {
self.inboxes.entry(other).or_default().push_back(TransportEvent::PeerDisconnected(id));
self.inboxes.entry(id).or_default().push_back(TransportEvent::PeerDisconnected(other));
}
}
}
pub struct MockNetwork {
shared: Arc<Mutex<Shared>>,
rng: SplitMix64,
}
impl MockNetwork {
pub fn new(seed: u64) -> Self {
Self {
shared: Arc::new(Mutex::new(Shared::default())),
rng: SplitMix64(seed),
}
}
/// A new, not yet connected peer.
pub fn endpoint(&mut self) -> MockEndpoint {
let mut shared = self.shared.lock().unwrap();
shared.next_peer += 1;
let id = TransportPeerId(uuid::Uuid::from_u128(shared.next_peer));
shared.inboxes.insert(id, VecDeque::new());
MockEndpoint {
id,
shared: self.shared.clone(),
known_peers: Vec::new(),
}
}
pub fn connect(&mut self, id: TransportPeerId) {
let mut shared = self.shared.lock().unwrap();
if shared.connected.contains(&id) {
return;
}
for &other in &shared.connected.clone() {
shared.inboxes.entry(other).or_default().push_back(TransportEvent::PeerConnected(id));
shared.inboxes.entry(id).or_default().push_back(TransportEvent::PeerConnected(other));
}
shared.connected.push(id);
}
pub fn disconnect(&mut self, id: TransportPeerId) {
self.shared.lock().unwrap().disconnect(id);
}
pub fn pending(&self) -> usize {
self.shared.lock().unwrap().in_flight.values().map(VecDeque::len).sum()
}
/// Deliver one in-flight packet from a randomly chosen sender/receiver pair.
pub fn step(&mut self) -> bool {
let mut shared = self.shared.lock().unwrap();
let queues: Vec<_> = shared.in_flight.iter().filter(|(_, queue)| !queue.is_empty()).map(|(&key, _)| key).collect();
if queues.is_empty() {
return false;
}
let (from, to) = queues[self.rng.below(queues.len())];
let packet = shared.in_flight.get_mut(&(from, to)).and_then(VecDeque::pop_front).expect("queue is non-empty");
shared.inboxes.entry(to).or_default().push_back(TransportEvent::Packet(from, packet));
true
}
pub fn deliver_all(&mut self) {
while self.step() {}
}
/// Deliver everything in flight to one peer, leaving every other peer's queues untouched. Random
/// stepping cannot target a receiver, so this is how a test puts a packet in one peer's hands and
/// not another's.
pub fn deliver_to(&mut self, to: TransportPeerId) {
let mut shared = self.shared.lock().unwrap();
let queues: Vec<_> = shared.in_flight.keys().copied().filter(|&(_, receiver)| receiver == to).collect();
for key in queues {
let packets: VecDeque<SyncPacket> = shared.in_flight.get_mut(&key).map(std::mem::take).unwrap_or_default();
for packet in packets {
shared.inboxes.entry(to).or_default().push_back(TransportEvent::Packet(key.0, packet));
}
}
}
pub fn random_below(&mut self, bound: usize) -> usize {
self.rng.below(bound)
}
}
/// Like a real socket, an endpoint only knows the peers whose connect events it has polled, so it
/// can't send to a peer before it had the chance to greet it.
pub struct MockEndpoint {
id: TransportPeerId,
shared: Arc<Mutex<Shared>>,
known_peers: Vec<TransportPeerId>,
}
impl MockEndpoint {
pub fn id(&self) -> TransportPeerId {
self.id
}
}
impl Transport for MockEndpoint {
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError> {
if self.known_peers.contains(&to) {
self.shared.lock().unwrap().in_flight.entry((self.id, to)).or_default().push_back(packet.clone());
}
Ok(())
}
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError> {
for to in self.known_peers.clone() {
if Some(to) != excluded {
self.send(to, packet)?;
}
}
Ok(())
}
fn poll(&mut self) -> Vec<TransportEvent> {
let events: Vec<_> = self.shared.lock().unwrap().inboxes.get_mut(&self.id).map(|inbox| inbox.drain(..).collect()).unwrap_or_default();
for event in &events {
match event {
TransportEvent::PeerConnected(peer) => self.known_peers.push(*peer),
TransportEvent::PeerDisconnected(peer) => self.known_peers.retain(|known| known != peer),
_ => {}
}
}
events
}
fn close(&mut self) {
self.shared.lock().unwrap().disconnect(self.id);
}
}
struct SplitMix64(u64);
impl SplitMix64 {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
fn below(&mut self, bound: usize) -> usize {
(self.next() % bound as u64) as usize
}
}
+161
View File
@@ -0,0 +1,161 @@
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredHotOps, Rev, UserId};
use serde::{Deserialize, Serialize};
/// The host is the single peer that retires hot ops.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Role {
Host,
Guest,
/// Connected to the document's room without knowing yet whether a host is there: a host's hello makes
/// this peer a guest, and a room with no host makes it the host after a grace period.
Undecided,
}
/// How far one peer's broadcasts had got. A peer keeps its `PeerId` across a reconnect but restarts
/// `seq`, so `epoch` names the incarnation that produced it and counters from different epochs are
/// never compared.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerSeq {
pub peer: PeerId,
pub epoch: u64,
pub seq: u64,
}
/// MessagePack-encoded on the wire.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum SyncPacket {
/// Sent first on every new connection. `epoch` and `seq` anchor the receiver's counter for this
/// sender, since broadcasts made before the connection were never sent to it.
Hello {
peer: PeerId,
user: UserId,
role: Role,
epoch: u64,
seq: u64,
},
/// `known_revs` come from `Session::known_revs`, so the host can send only what's missing.
SyncRequest {
known_revs: Vec<Rev>,
},
Sync(Box<SyncPayload>),
Broadcast(Broadcast),
/// A guest asks the host to undo (`restore: false`) or redo (`restore: true`) one of its retired
/// interactions, named by its last delta. The host answers the room with a `HeadMove` or new deltas.
UndoRequest {
rev: Rev,
restore: bool,
},
/// A guest asks the host to move the shared head to `rev`, an ancestor of it, leaving the line since as a
/// branch. The host answers the room with a `HeadMove` without copies.
MoveRequest {
rev: Rev,
},
ResourceRequest(Vec<ResourceHash>),
Resource {
hash: ResourceHash,
#[serde(with = "serde_bytes")]
bytes: Vec<u8>,
},
/// Who the sender is, for display. Sent to a peer after the hello and to everyone when it changes; the
/// newest wins. Presence like this is never history, so it stays outside the causal broadcast.
Profile {
name: String,
},
/// Where the sender's pointer is, `None` when it left the viewport. Sent at most once a frame and identified
/// by the link it arrives on, so it carries nothing but the position and the space it is in.
Cursor {
position: Option<CursorPosition>,
},
/// A peer's statements about the history, users and their names among it. Outside the causal order: the
/// record merges the same whatever order it arrives in.
Metadata(HistoryMetadata),
}
/// The host's answer to a `SyncRequest`. `registry` is only sent when the host recognized none of
/// the requester's revs; otherwise `deltas` extend the requester's history. `seen` is the host's
/// delivery vector at snapshot time, which the guest adopts so later broadcasts line up.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SyncPayload {
pub registry: Option<Registry>,
pub deltas: Vec<Delta>,
pub head: Option<Rev>,
pub hot_log: Vec<HotOp>,
pub known_revs: Vec<Rev>,
pub seen: Vec<PeerSeq>,
/// Which hot ops the history being handed over already covers, so the requester can recognize one
/// it is holding rather than re-entering it as live work.
pub retired: RetiredHotOps,
/// Which hot ops their authors took back, so the requester drops any it still holds.
#[serde(default)]
pub retracted: RetiredHotOps,
/// The document's identity, so a peer that started from an empty document adopts it and can reconnect
/// to the same room by opening its own copy later.
#[serde(default)]
pub document_id: Option<u64>,
/// What the host has on record about the history's users, so a joiner can name every author.
#[serde(default)]
pub metadata: HistoryMetadata,
}
/// Causal broadcast envelope. `seq` numbers the sender's broadcasts from 1 within `epoch`, and `seen`
/// is the sender's delivery vector; a receiver holds the packet until it has delivered everything in
/// `seen`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Broadcast {
pub epoch: u64,
pub seq: u64,
pub seen: Vec<PeerSeq>,
pub body: BroadcastBody,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum BroadcastBody {
HotOps(Vec<HotOp>),
/// `deltas` are in causal order. `retires` names the hot ops they replace (empty for a plain history transfer).
Deltas {
deltas: Vec<Delta>,
retires: Vec<HotOpId>,
},
/// Hot ops their author took back: they leave every hot log and never retire.
Retract(Vec<HotOpId>),
/// Everything a peer knows to have been taken back, re-announced on a membership change the way hot
/// ops are, so a peer that joined while a retraction was in flight still hears of it.
RetractedMarks(RetiredHotOps),
/// The host dropped a retired interaction out of the line: every peer walks back and follows the head.
HeadMove(HeadMove),
}
#[derive(Debug, thiserror::Error)]
pub enum PacketError {
#[error("failed to encode packet: {0}")]
Encode(#[from] rmp_serde::encode::Error),
#[error("failed to decode packet: {0}")]
Decode(#[from] rmp_serde::decode::Error),
}
impl SyncPacket {
pub fn encode(&self) -> Result<Box<[u8]>, PacketError> {
Ok(rmp_serde::to_vec(self)?.into_boxed_slice())
}
pub fn decode(bytes: &[u8]) -> Result<Self, PacketError> {
Ok(rmp_serde::from_slice(bytes)?)
}
}
/// A peer's pointer: where, and in which of the editor's spaces, so it is drawn only where it means something.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CursorPosition {
pub position: [f64; 2],
pub space: CursorSpace,
/// The icon name of the tool the peer holds, shown beside the pointer; `None` from a viewer with no tools.
pub tool: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CursorSpace {
/// Document coordinates over the canvas.
Document,
/// Node-graph coordinates of the network at this path of node ids, from the document network down.
Graph { network: Vec<u64> },
}
File diff suppressed because it is too large. Load diff
+332
View File
@@ -0,0 +1,332 @@
use crate::packet::{PacketError, SyncPacket};
use crate::transport::{Transport, TransportEvent, TransportPeerId};
use futures::StreamExt;
use futures::channel::mpsc::UnboundedSender;
use matchbox_socket::{MessageLoopFuture, Packet, PeerState, WebRtcSocket};
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
const CHANNEL: usize = 0;
/// Largest SCTP message every browser accepts.
const CHUNK_BYTES: usize = 16 * 1024;
const FRAME_FINAL: u8 = 1;
const FRAME_MORE: u8 = 0;
/// Split a packet into `[flag][bytes]` chunks, the last carrying [`FRAME_FINAL`] so a receiver finds
/// the packet boundary without a length prefix.
fn frames(bytes: &[u8]) -> Vec<Box<[u8]>> {
// An empty packet still gets one frame. Chunking it would yield none at all, and the packet would
// leave no trace on the wire rather than arriving empty.
let chunks: Vec<&[u8]> = if bytes.is_empty() { vec![&[]] } else { bytes.chunks(CHUNK_BYTES).collect() };
chunks
.iter()
.enumerate()
.map(|(index, chunk)| {
let flag = if index + 1 == chunks.len() { FRAME_FINAL } else { FRAME_MORE };
std::iter::once(flag).chain(chunk.iter().copied()).collect()
})
.collect()
}
/// Per-peer reassembly of framed packets. The channel is reliable and ordered per peer, so chunks
/// arrive in the order they were sent and a packet ends at the first [`FRAME_FINAL`].
#[derive(Default)]
struct Reassembler {
partial: HashMap<TransportPeerId, Vec<u8>>,
}
impl Reassembler {
/// The packet's bytes once its final chunk lands, or `None` while more are still to come.
fn accept(&mut self, peer: TransportPeerId, frame: &[u8]) -> Option<Vec<u8>> {
let (&flag, chunk) = frame.split_first()?;
let buffer = self.partial.entry(peer).or_default();
buffer.extend_from_slice(chunk);
(flag == FRAME_FINAL).then(|| std::mem::take(buffer))
}
/// Drop a peer's half-received packet, which nothing will ever complete.
fn forget(&mut self, peer: TransportPeerId) {
self.partial.remove(&peer);
}
}
/// Packets that arrived and wait to be polled, and whoever is waiting for them.
#[derive(Debug, Default)]
struct Inbox {
packets: VecDeque<(TransportPeerId, Packet)>,
waker: Option<Waker>,
/// Set once the socket loop ended: nothing more will arrive.
closed: bool,
}
fn lock(inbox: &Mutex<Inbox>) -> std::sync::MutexGuard<'_, Inbox> {
inbox.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
/// A handle onto a room's inbox that resolves when a packet is waiting, so the room is polled as packets
/// arrive rather than once per frame. A hidden browser tab gets about one frame a second, which made a
/// host answer each step of a join a second late while the data channel itself delivered on time.
#[derive(Clone, Debug)]
pub struct Incoming {
inbox: Arc<Mutex<Inbox>>,
}
impl Incoming {
/// Resolves to `true` once a packet is waiting, and to `false` once the room's loop has ended and
/// nothing more can arrive, so the caller knows not to wait again.
pub async fn wait(&self) -> bool {
std::future::poll_fn(|cx| self.poll_ready(cx)).await
}
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<bool> {
let mut inbox = lock(&self.inbox);
if !inbox.packets.is_empty() {
return Poll::Ready(true);
}
if inbox.closed {
return Poll::Ready(false);
}
inbox.waker = Some(cx.waker().clone());
Poll::Pending
}
}
/// One matchbox room over WebRTC. Packets are split into `[flag][bytes]` chunks; the reliable
/// channel is ordered per peer, so the receiver reassembles by appending until the final flag.
/// The returned future must be polled continuously by the caller.
pub struct Room {
socket: WebRtcSocket,
outgoing: UnboundedSender<(TransportPeerId, Packet)>,
inbox: Arc<Mutex<Inbox>>,
incoming: Reassembler,
}
impl Room {
pub fn connect(signaling_url: &str) -> (Self, MessageLoopFuture) {
// WebRTC's DTLS goes through rustls, which needs one provider chosen when several are linked.
#[cfg(not(target_family = "wasm"))]
let _ = rustls::crypto::ring::default_provider().install_default();
let (mut socket, driver) = WebRtcSocket::new_reliable(signaling_url);
let (outgoing, mut received) = socket.take_channel(CHANNEL).expect("a reliable socket has its one channel").split();
let inbox = Arc::new(Mutex::new(Inbox::default()));
// Arrivals move into the inbox as they happen and wake whoever waits on it. The forwarder ends with
// the socket loop, which drops its senders when it returns; the loop's result stays the driver's.
let forwarder = {
let inbox = Arc::clone(&inbox);
async move {
while let Some(arrived) = received.next().await {
let mut inbox = lock(&inbox);
inbox.packets.push_back(arrived);
if let Some(waker) = inbox.waker.take() {
waker.wake();
}
}
let mut inbox = lock(&inbox);
inbox.closed = true;
if let Some(waker) = inbox.waker.take() {
waker.wake();
}
}
};
let driver: MessageLoopFuture = Box::pin(async move {
let (result, ()) = futures::join!(driver, forwarder);
result
});
(
Self {
socket,
outgoing,
inbox,
incoming: Reassembler::default(),
},
driver,
)
}
/// A handle that resolves whenever a packet waits in this room.
pub fn incoming(&self) -> Incoming {
Incoming { inbox: Arc::clone(&self.inbox) }
}
fn send_chunks(&mut self, bytes: &[u8], peers: &[TransportPeerId]) {
for frame in frames(bytes) {
for &peer in peers {
// A send only fails once the socket loop has ended, which the loop's own future reports.
if self.outgoing.unbounded_send((peer, frame.clone())).is_err() {
return;
}
}
}
}
}
impl Transport for Room {
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError> {
let bytes = packet.encode()?;
self.send_chunks(&bytes, &[to]);
Ok(())
}
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError> {
let bytes = packet.encode()?;
let peers: Vec<_> = self.socket.connected_peers().filter(|&peer| Some(peer) != excluded).collect();
self.send_chunks(&bytes, &peers);
Ok(())
}
fn poll(&mut self) -> Vec<TransportEvent> {
let mut events = Vec::new();
for (peer, state) in self.socket.update_peers() {
events.push(match state {
PeerState::Connected => TransportEvent::PeerConnected(peer),
PeerState::Disconnected => {
self.incoming.forget(peer);
TransportEvent::PeerDisconnected(peer)
}
});
}
let received: Vec<_> = lock(&self.inbox).packets.drain(..).collect();
for (peer, frame) in received {
let Some(bytes) = self.incoming.accept(peer, &frame) else { continue };
events.push(match SyncPacket::decode(&bytes) {
Ok(packet) => TransportEvent::Packet(peer, packet),
Err(error) => TransportEvent::Malformed(peer, error),
});
}
events
}
fn close(&mut self) {
self.socket.close();
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::FutureExt;
fn peer(byte: u128) -> TransportPeerId {
TransportPeerId(uuid::Uuid::from_u128(byte))
}
/// The inbox handle resolves on an arrival and once more when the loop ends, and is pending otherwise,
/// so a poll driven by it runs on packets rather than on frames.
#[test]
fn the_inbox_wakes_on_arrival_and_reports_the_end() {
let inbox = Arc::new(Mutex::new(Inbox::default()));
let incoming = Incoming { inbox: Arc::clone(&inbox) };
assert_eq!(incoming.wait().now_or_never(), None, "nothing arrived yet");
lock(&inbox).packets.push_back((peer(1), Box::new([FRAME_FINAL, 7])));
assert_eq!(incoming.wait().now_or_never(), Some(true), "an arrival resolves the wait");
assert_eq!(incoming.wait().now_or_never(), Some(true), "and keeps it resolved until the inbox is drained");
lock(&inbox).packets.clear();
assert_eq!(incoming.wait().now_or_never(), None, "drained: pending again");
lock(&inbox).closed = true;
assert_eq!(incoming.wait().now_or_never(), Some(false), "the end of the loop resolves the wait for good");
}
/// Push every frame at a reassembler and collect whatever packets come back out.
fn round_trip(bytes: &[u8]) -> Vec<Vec<u8>> {
let mut incoming = Reassembler::default();
frames(bytes).into_iter().filter_map(|frame| incoming.accept(peer(1), &frame)).collect()
}
/// A packet within one chunk travels as a single final frame.
#[test]
fn a_small_packet_is_one_frame() {
let bytes = b"hello".to_vec();
let framed = frames(&bytes);
assert_eq!(framed.len(), 1);
assert_eq!(framed[0][0], FRAME_FINAL);
assert_eq!(round_trip(&bytes), vec![bytes]);
}
/// Chunking an empty packet yields no chunks at all, so it needs a frame of its own or it would
/// leave no trace on the wire.
#[test]
fn an_empty_packet_still_produces_one_frame() {
let framed = frames(&[]);
assert_eq!(framed.len(), 1, "an empty packet must still be framed");
assert_eq!(framed[0][0], FRAME_FINAL);
assert_eq!(round_trip(&[]), vec![Vec::<u8>::new()]);
}
/// The boundary either side of the SCTP limit: exactly one chunk stays one frame, one byte more
/// splits, and both rebuild byte for byte.
#[test]
fn packets_around_the_chunk_boundary_round_trip() {
for length in [CHUNK_BYTES - 1, CHUNK_BYTES, CHUNK_BYTES + 1, CHUNK_BYTES * 3 + 7] {
let bytes: Vec<u8> = (0..length).map(|index| (index % 251) as u8).collect();
let framed = frames(&bytes);
assert_eq!(framed.len(), length.div_ceil(CHUNK_BYTES), "wrong frame count for {length} bytes");
assert!(framed.iter().all(|frame| frame.len() <= CHUNK_BYTES + 1), "a frame exceeded the SCTP limit");
assert!(framed.iter().rev().skip(1).all(|frame| frame[0] == FRAME_MORE), "only the last frame is final");
assert_eq!(framed.last().expect("at least one frame")[0], FRAME_FINAL);
assert_eq!(round_trip(&bytes), vec![bytes], "{length} bytes did not round trip");
}
}
/// Two peers' chunks interleave on one channel, so reassembly is per peer or one packet would be
/// spliced into the other.
#[test]
fn interleaved_peers_reassemble_separately() {
let (first, second) = (peer(1), peer(2));
let mut incoming = Reassembler::default();
let long: Vec<u8> = (0..CHUNK_BYTES + 32).map(|index| (index % 97) as u8).collect();
let short = b"short".to_vec();
let long_frames = frames(&long);
let short_frames = frames(&short);
assert_eq!(long_frames.len(), 2, "the long packet must span two frames to interleave");
// The short packet arrives whole between the long packet's two chunks.
assert_eq!(incoming.accept(first, &long_frames[0]), None);
assert_eq!(incoming.accept(second, &short_frames[0]), Some(short));
assert_eq!(incoming.accept(first, &long_frames[1]), Some(long));
}
/// A peer that drops mid-packet leaves a partial buffer, which must not be prepended to whatever
/// the next peer to reuse that id sends.
#[test]
fn forgetting_a_peer_discards_its_partial_packet() {
let sender = peer(1);
let mut incoming = Reassembler::default();
let long: Vec<u8> = (0..CHUNK_BYTES + 8).map(|index| (index % 89) as u8).collect();
assert_eq!(incoming.accept(sender, &frames(&long)[0]), None);
incoming.forget(sender);
let fresh = b"fresh".to_vec();
assert_eq!(incoming.accept(sender, &frames(&fresh)[0]), Some(fresh), "the abandoned prefix must be gone");
}
/// A zero-length frame carries no flag byte, so it is ignored rather than read past its end.
#[test]
fn an_empty_frame_is_ignored() {
let mut incoming = Reassembler::default();
assert_eq!(incoming.accept(peer(1), &[]), None);
}
}
+199
View File
@@ -0,0 +1,199 @@
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredHotOps, Rev, Session};
use std::collections::HashSet;
pub type TargetError = Box<dyn std::error::Error>;
/// The document state a `Replica` reads from and applies remote changes to.
pub trait SyncTarget {
fn peer(&self) -> PeerId;
/// The identity of the document this target holds, if it has one; a session token is derived from it.
fn document_id(&self) -> Option<u64> {
None
}
/// Take on the host's document identity after a full sync, so this copy is the same document from now on.
fn adopt_document_id(&mut self, _document_id: u64) -> Result<(), TargetError> {
Ok(())
}
fn head(&self) -> Option<Rev>;
fn retired_registry(&self) -> Registry;
fn hot_log(&self) -> Vec<HotOp>;
fn known_revs(&self) -> Vec<Rev>;
fn contains_rev(&self, rev: Rev) -> bool;
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta>;
/// Highest hot-op counter retired per author.
fn retired_marks(&self) -> RetiredHotOps;
/// Which hot ops were taken back by their authors. See [`Session::retracted_marks`].
fn retracted_marks(&self) -> RetiredHotOps;
/// Take on a peer's retirement marks, dropping any hot op they show as already retired.
fn absorb_retired_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError>;
/// Take on a peer's retractions, dropping what they cover from the hot log.
fn absorb_retracted_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError>;
/// What people state about the history, users and their names among it, kept beside it and merged
/// last-writer-wins. Empty for a target that keeps none.
fn metadata(&self) -> HistoryMetadata {
HistoryMetadata::default()
}
/// Take on a peer's statements about the history. Returns whether any of them was news.
fn absorb_metadata(&mut self, _remote: &HistoryMetadata) -> Result<bool, TargetError> {
Ok(false)
}
/// Replace all state with the given retired state.
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError>;
/// Must be idempotent on structural ops: a buffered op may already be reflected by the sync.
/// Returns the ops it could not apply, whose referents have not arrived yet; the caller retries
/// them as later ops fill the gaps.
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError>;
/// Take the host's deltas on and follow its head, `head` being where the host is after them (the
/// batch's last delta when `None`). See [`Session::follow`].
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId], head: Option<Rev>) -> Result<(), TargetError>;
/// Host only: take a peer's deltas on, and where its line diverged from this one, join the two heads
/// with a merge delta rather than follow it. Returns what the room has yet to see, the deltas absorbed
/// and the merge, for the host to broadcast so every guest follows to the joined head.
fn merge_divergent(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<Vec<Delta>, TargetError>;
/// A peer took back hot ops of its own: drop them and re-derive what they touched.
fn retract_hot_ops(&mut self, ops: &[HotOpId]) -> Result<(), TargetError>;
/// Host only: drop a retired interaction out of the shared line. See [`Session::drop_interaction`].
fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError>;
/// Host only: mint a dropped interaction again on top of the line. See [`Session::restore_interaction`].
fn restore_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, TargetError>;
/// Host only: move the shared head to an ancestor, leaving the line since as a branch. See [`Session::move_head_to`].
fn move_head_to(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
let _ = rev;
Err("this target cannot move its head".into())
}
/// Follow the host's cursor move. See [`Session::apply_head_move`].
fn apply_head_move(&mut self, moved: &HeadMove) -> Result<(), TargetError>;
/// Make everything applied since the last flush durable. Called once per [`Replica::poll`](crate::Replica::poll),
/// so a target that rewrites whole files can do it once for a batch rather than once per packet.
fn flush(&mut self) -> Result<(), TargetError> {
Ok(())
}
/// Referenced resources whose bytes are not available locally.
fn missing_resources(&self) -> HashSet<ResourceHash> {
HashSet::new()
}
/// `None` when the bytes can't be produced synchronously; the request is then surfaced as an event.
fn resource_bytes(&self, hash: ResourceHash) -> Option<Vec<u8>> {
let _ = hash;
None
}
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
let _ = (hash, bytes);
Ok(())
}
}
impl SyncTarget for Session {
fn peer(&self) -> PeerId {
Session::peer(self)
}
fn head(&self) -> Option<Rev> {
self.head_rev()
}
fn retired_registry(&self) -> Registry {
Session::retired_registry(self).clone()
}
fn hot_log(&self) -> Vec<HotOp> {
Session::hot_log(self).to_vec()
}
fn known_revs(&self) -> Vec<Rev> {
Session::known_revs(self)
}
fn contains_rev(&self, rev: Rev) -> bool {
self.delta(rev).is_some()
}
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta> {
Session::deltas_unknown_to(self, known.iter().copied()).into_iter().cloned().collect()
}
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
// Kept across the replace: a sequence this peer already spent must not come round again, or an
// op of its own would be taken for one already retired.
let spent = self.next_hot_sequence();
*self = Session::load(self.peer(), self.user(), registry, history, head, Vec::new(), self.next_node_counter());
self.restore_hot_sequence(spent);
Ok(())
}
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
// Every op gets its turn even if one fails, since the broadcast that carried them is consumed by
// the time this runs. A failure usually means the entity the op names has not arrived here yet,
// so it is handed back to be retried rather than dropped.
let mut deferred = Vec::new();
for hot_op in ops {
if self.replay_hot_op(hot_op.clone()).is_err() {
deferred.push(hot_op);
}
}
Ok(deferred)
}
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId], head: Option<Rev>) -> Result<(), TargetError> {
self.follow(deltas, head)?;
self.discard_hot_ops(retires)?;
Ok(())
}
fn merge_divergent(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<Vec<Delta>, TargetError> {
let mut absorbed: Vec<Delta> = deltas.iter().filter(|delta| !self.contains_rev(delta.id)).cloned().collect();
let outcome = self.merge(deltas)?;
self.discard_hot_ops(retires)?;
if let document_graph_storage::MergeOutcome::Merged(rev) = outcome {
absorbed.extend(self.delta(rev).cloned());
}
Ok(absorbed)
}
fn retired_marks(&self) -> RetiredHotOps {
Session::retired_marks(self).clone()
}
fn absorb_retired_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError> {
Session::absorb_retired_marks(self, remote)?;
Ok(())
}
fn retracted_marks(&self) -> RetiredHotOps {
Session::retracted_marks(self).clone()
}
fn absorb_retracted_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError> {
Session::absorb_retracted_marks(self, remote);
Ok(())
}
fn retract_hot_ops(&mut self, ops: &[HotOpId]) -> Result<(), TargetError> {
Session::retract_hot_ops(self, ops);
Ok(())
}
fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
let (moved, _) = Session::drop_interaction(self, rev)?;
Ok(moved)
}
fn restore_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, TargetError> {
let revs = Session::restore_interaction(self, rev)?;
Ok(revs.into_iter().filter_map(|rev| self.delta(rev).cloned()).collect())
}
fn apply_head_move(&mut self, moved: &HeadMove) -> Result<(), TargetError> {
Session::apply_head_move(self, moved)?;
Ok(())
}
fn move_head_to(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
Ok(Session::move_head_to(self, rev)?.0)
}
}
+103
View File
@@ -0,0 +1,103 @@
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use std::fmt;
use std::str::FromStr;
/// Identifies the text form as a Graphite session token, like GitLab's `glpat-` tokens.
const PREFIX: &str = "graphite-";
/// Random session ID, used as the matchbox room name. Entropy is supplied by the caller.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct SessionToken(pub [u8; 16]);
impl SessionToken {
pub fn signaling_url(&self, signaling_server: &str) -> String {
format!("{}/{}", signaling_server.trim_end_matches('/'), self)
}
}
impl fmt::Display for SessionToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{PREFIX}{}", URL_SAFE_NO_PAD.encode(self.0))
}
}
#[derive(Debug, thiserror::Error)]
#[error("invalid session token")]
pub struct InvalidSessionToken;
impl FromStr for SessionToken {
type Err = InvalidSessionToken;
/// Parses the bare token, or a share link carrying it as the `session` query parameter, so a pasted link
/// works wherever a token does: the editor's join field, the CLI, a URL scheme.
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.trim();
let s = match s.split_once("session=") {
Some((_, rest)) => rest.split(['&', '#', ' ']).next().unwrap_or(""),
None => s,
};
let encoded = s.strip_prefix(PREFIX).ok_or(InvalidSessionToken)?;
let bytes = URL_SAFE_NO_PAD.decode(encoded).map_err(|_| InvalidSessionToken)?;
let bytes = bytes.try_into().map_err(|_| InvalidSessionToken)?;
Ok(Self(bytes))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_through_string() {
let token = SessionToken([7; 16]);
assert_eq!(token.to_string().parse::<SessionToken>().unwrap(), token);
}
#[test]
fn parses_the_token_out_of_a_share_link() {
let token = SessionToken([7; 16]);
let link = format!(" https://editor.graphite.rs/?session={token}#top ");
assert_eq!(link.parse::<SessionToken>().unwrap(), token);
assert_eq!(format!("http://localhost:8080/?debug=1&session={token}").parse::<SessionToken>().unwrap(), token);
}
#[test]
fn rejects_wrong_length_or_missing_prefix() {
assert!("graphite-AAAA".parse::<SessionToken>().is_err());
assert!("BwcHBwcHBwcHBwcHBwcHBw".parse::<SessionToken>().is_err());
}
}
impl SessionToken {
/// The token every copy of one document shares: derived from the document's id, so a copy edited
/// apart reconnects to the same room as the others by opening the same file, with no link to pass
/// around. Document ids are random 64-bit values, so the room is no more guessable than the id; the
/// mixing only spreads the id over the token's width.
pub fn for_document(document_id: u64) -> Self {
fn mix(mut value: u64) -> u64 {
value = value.wrapping_add(0x9E37_79B9_7F4A_7C15);
value = (value ^ (value >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
value = (value ^ (value >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
value ^ (value >> 31)
}
let mut bytes = [0u8; 16];
bytes[..8].copy_from_slice(&mix(document_id).to_le_bytes());
bytes[8..].copy_from_slice(&mix(document_id ^ 0x5A5A_5A5A_5A5A_5A5A).to_le_bytes());
Self(bytes)
}
}
#[cfg(test)]
mod derived_token_tests {
use super::SessionToken;
/// Every copy of a document derives the same token, and different documents different ones.
#[test]
fn a_document_id_derives_one_token() {
assert_eq!(SessionToken::for_document(7), SessionToken::for_document(7));
assert_ne!(SessionToken::for_document(7), SessionToken::for_document(8));
let text = SessionToken::for_document(7).to_string();
assert_eq!(text.parse::<SessionToken>().expect("round trip"), SessionToken::for_document(7));
}
}
+23
View File
@@ -0,0 +1,23 @@
use crate::packet::{PacketError, SyncPacket};
pub use matchbox_socket::PeerId as TransportPeerId;
pub enum TransportEvent {
PeerConnected(TransportPeerId),
PeerDisconnected(TransportPeerId),
Packet(TransportPeerId, SyncPacket),
Malformed(TransportPeerId, PacketError),
}
/// Packet delivery between the peers of one session. Delivery must be reliable and ordered per
/// sender, which is what lets the `Replica` skip acknowledgements and buffering.
pub trait Transport: Send + Sync {
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError>;
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError>;
fn poll(&mut self) -> Vec<TransportEvent>;
fn close(&mut self);
fn broadcast(&mut self, packet: &SyncPacket) -> Result<(), PacketError> {
self.broadcast_except(None, packet)
}
}
File diff suppressed because it is too large. Load diff
+1
View File
@@ -19,6 +19,7 @@ graph-craft = { workspace = true }
document-format = { workspace = true }
document-graph-storage = { workspace = true, features = ["conversion"] }
document-container = { workspace = true }
peer-transport = { workspace = true }
graphene-hash = { workspace = true }
interpreted-executor = { workspace = true }
graphene-std = { workspace = true } # NOTE: `core-types` should not be added here because `graphene-std` re-exports its contents
+3
View File
@@ -255,6 +255,7 @@ impl Dispatcher {
ipp: &self.message_handlers.input_preprocessor_message_handler,
preferences: &self.message_handlers.preferences_message_handler,
current_tool: &self.message_handlers.tool_message_handler.tool_state.tool_data.active_tool_type,
current_tool_icon: self.message_handlers.tool_message_handler.active_tool_icon(),
reset_node_definitions_on_open: self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open,
timing_information: self.message_handlers.animation_message_handler.timing_information(),
animation: &self.message_handlers.animation_message_handler,
@@ -269,6 +270,8 @@ impl Dispatcher {
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.workspace.panel_layout.focus_document;
let layout = &self.message_handlers.portfolio_message_handler.workspace.panel_layout;
menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data);
menu_bar_message_handler.session_panel_open = layout.is_panel_present(PanelType::Session);
menu_bar_message_handler.history_panel_open = layout.is_panel_present(PanelType::History);
menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers);
menu_bar_message_handler.properties_panel_open = layout.is_panel_present(PanelType::Properties);
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
@@ -5,7 +5,7 @@ use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewIm
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, NodeGraphErrorDiagnostic,
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
};
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
@@ -150,6 +150,10 @@ pub enum FrontendMessage {
url: String,
},
TriggerClipboardRead,
/// Copy a link to join the live session behind `token`, built from the page's own origin.
TriggerSessionLinkCopy {
token: String,
},
TriggerClipboardWrite {
content: String,
},
@@ -200,6 +204,15 @@ pub enum FrontendMessage {
#[serde(rename = "box")]
box_selection: Option<BoxSelection>,
},
UpdateDocumentCursors {
cursors: Vec<FrontendRemoteCursor>,
},
UpdateHistoryPanel {
state: crate::messages::portfolio::history::utility_types::HistoryPanelState,
},
UpdateNodeGraphCursors {
cursors: Vec<FrontendRemoteCursor>,
},
UpdateContextMenuInformation {
#[serde(rename = "contextMenuInformation")]
context_menu_information: Option<ContextMenuInformation>,
@@ -17,6 +17,18 @@ pub struct DocumentInfo {
#[serde(default)]
pub path: Option<PathBuf>,
pub is_saved: bool,
/// The document's live session, `None` when it is not shared.
#[serde(default)]
pub session: Option<SessionStatus>,
}
/// Whether a shared document is in its room right now.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum SessionStatus {
Connected,
/// Shared, but the transport is down or the document is not mounted yet; it reconnects on mount.
Disconnected,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints, from_wasm_abi))]
@@ -5,13 +5,46 @@ use crate::messages::prelude::*;
#[impl_message(Message, InputPreprocessor)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum InputPreprocessorMessage {
DoubleClick { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
KeyDown { key: Key, key_repeat: bool, modifier_keys: ModifierKeys },
KeyUp { key: Key, key_repeat: bool, modifier_keys: ModifierKeys },
PointerDown { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
PointerMove { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
PointerUp { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
PointerShake { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
CurrentTime { timestamp: u64 },
WheelScroll { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
DoubleClick {
editor_mouse_state: EditorPointerState,
modifier_keys: ModifierKeys,
},
KeyDown {
key: Key,
key_repeat: bool,
modifier_keys: ModifierKeys,
},
KeyUp {
key: Key,
key_repeat: bool,
modifier_keys: ModifierKeys,
},
PointerDown {
editor_mouse_state: EditorPointerState,
modifier_keys: ModifierKeys,
},
PointerMove {
editor_mouse_state: EditorPointerState,
modifier_keys: ModifierKeys,
},
/// The pointer moved over GUI that covers the canvas, the node graph say: only the position is recorded, for
/// presence and the like, and no tool hears of it.
PointerHover {
editor_mouse_state: EditorPointerState,
},
PointerUp {
editor_mouse_state: EditorPointerState,
modifier_keys: ModifierKeys,
},
PointerShake {
editor_mouse_state: EditorPointerState,
modifier_keys: ModifierKeys,
},
CurrentTime {
timestamp: u64,
},
WheelScroll {
editor_mouse_state: EditorPointerState,
modifier_keys: ModifierKeys,
},
}
@@ -66,6 +66,9 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
self.translate_mouse_event(pointer_state, true, responses);
}
InputPreprocessorMessage::PointerHover { editor_mouse_state } => {
self.mouse.position = editor_mouse_state.to_pointer_state(viewport).position;
}
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, responses);
@@ -70,6 +70,8 @@ define_layout_target!(
NodeGraphControlBar,
/// The body of the Properties panel containing many collapsable sections.
PropertiesPanel,
/// The body of the Session panel: the active document's live session state, join link, peers and sharing actions.
SessionPanel,
/// The contextual input key/mouse combination shortcuts shown in the status bar at the bottom of the window.
StatusBarHints,
/// The version information shown in the status bar at the bottom right of the window.
@@ -20,6 +20,8 @@ pub struct MenuBarMessageHandler {
pub show_storage_preferences: bool,
pub make_path_editable_is_allowed: bool,
pub data_panel_open: bool,
pub session_panel_open: bool,
pub history_panel_open: bool,
pub layers_panel_open: bool,
pub properties_panel_open: bool,
pub focus_document: bool,
@@ -679,6 +681,16 @@ impl LayoutHolder for MenuBarMessageHandler {
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleDataPanelOpen))
.on_commit(|_| WorkspaceMessage::ToggleDataPanelOpen.into())
.disabled(self.focus_document),
MenuListEntry::new("Session")
.label("Session")
.icon(if self.session_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| WorkspaceMessage::ToggleSessionPanelOpen.into())
.disabled(self.focus_document),
MenuListEntry::new("History")
.label("History")
.icon(if self.history_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| WorkspaceMessage::ToggleHistoryPanelOpen.into())
.disabled(self.focus_document),
],
])
.widget_instance(),
@@ -215,10 +215,6 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
List<Gradient>,
List<String>,
List<f64>,
List<f32>,
List<u32>,
List<u64>,
List<i32>,
List<i64>,
List<bool>,
List<DVec2>,
@@ -275,10 +271,6 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
Item<Gradient>,
Item<String>,
Item<f64>,
Item<f32>,
Item<u32>,
Item<u64>,
Item<i32>,
Item<i64>,
Item<bool>,
Item<DVec2>,
@@ -577,7 +569,7 @@ impl TableItemLayout for Coverage {
impl TableItemLayout for TransferCurve {
fn type_name() -> &'static str {
"Transfer Curve"
"TransferCurve"
}
fn identifier(&self) -> String {
let points = self.points().len();
@@ -842,37 +834,12 @@ impl TableItemLayout for Gradient {
}
}
macro_rules! impl_table_item_layout_for_number {
($($ty:ty => $type_name:literal),* $(,)?) => {
$(
impl TableItemLayout for $ty {
fn type_name() -> &'static str {
$type_name
}
fn identifier(&self) -> String {
format!("{self}")
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
}
}
)*
}
}
impl_table_item_layout_for_number!(
u32 => "Number (u32)",
i32 => "Number (i32)",
u64 => "Number (u64)",
i64 => "Number (i64)",
);
impl TableItemLayout for f32 {
impl TableItemLayout for i64 {
fn type_name() -> &'static str {
"Number (f32)"
"Integer"
}
fn identifier(&self) -> String {
// Only infinity widens to f64 without gaining digits, so finite values keep the f32 spelling
if self.is_infinite() { format_f64(*self as f64) } else { format!("{self}") }
format!("{self}")
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
@@ -968,26 +935,6 @@ fn string_preview(value: &str) -> String {
first_line.chars().take(MAX_CHARACTERS - 1).chain(['…']).collect()
}
impl TableItemLayout for Option<f64> {
fn type_name() -> &'static str {
"Option<f64>"
}
fn identifier(&self) -> String {
"Option<f64>".to_string()
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
let text = match self {
Some(value) => format!("Some({})", format_f64(round_away_float_noise(*value))),
None => "None".to_string(),
};
vec![TextLabel::new(text).selectable(true).narrow(true).widget_instance()]
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), _data))]
}
}
impl TableItemLayout for DVec2 {
fn type_name() -> &'static str {
"Vec2"
@@ -1272,13 +1219,8 @@ macro_rules! known_item_types {
DVec2,
Affine2,
Vec2,
Option<f64>,
f64,
f32,
u8,
u32,
u64,
i32,
i64,
bool,
String,
@@ -1,12 +1,12 @@
use std::collections::VecDeque;
use std::collections::{BTreeMap, HashSet};
use document_graph_storage::Registry;
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
use document_graph_storage::{Declarations, Registry};
use graph_craft::application_io::resource::{ResourceHash, ResourceId, ResourceRegistry, ResourceStorage};
use super::utility_types::network_interface::NodeNetworkInterface;
use super::utility_types::network_interface::editor_delta::{EditorDelta, construct_batch};
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, collect_network_view_settings};
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, build_interface_from_storage, collect_network_view_settings};
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
/// becoming the authoritative history. Owns the dual-stack bookkeeping push/pop/clear and the cursor's stage/retire/move/verify
@@ -25,6 +25,39 @@ pub struct DocumentHistory {
/// future built by `load_document` resolves.
#[derivative(Debug = "ignore")]
storage: Option<document_format::GddV1>,
/// Decoded proto-node declarations for every registry state the cursor can reach, filled at mount
/// and extended on each staging, so a cursor rebuild never touches the byte store.
#[derivative(Debug = "ignore")]
declarations: Declarations,
/// Whether the next commit must convert the whole document rather than stage what the store recorded.
///
/// True when the working copy holds no baseline for a batch to apply to, and whenever the runtime has
/// moved without recording it (an upgrade on open), since the recorded batch would then describe only
/// part of the distance between the two.
needs_whole_document_stage: bool,
/// For each step on the legacy redo stack, how storage undid it, so redo takes the matching way back
/// rather than diffing a snapshot that predates what peers wrote meanwhile.
retracted_undos: Vec<UndoNote>,
}
/// How storage undid a step, paired with the legacy redo entry pushed for it.
#[derive(Clone, Debug)]
pub enum UndoNote {
/// The step was still hot and its ops were taken back; redo stages them again.
Retracted(Vec<document_graph_storage::RegistryDelta>),
/// The step had retired in a session and was dropped out of the shared line; redo puts it back on top.
Dropped(document_graph_storage::Rev),
/// The storage cursor moved back over it; redo moves it forward.
Cursor,
}
/// Why [`DocumentHistory::move_cursor`] produced no interface.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CursorMoveError {
/// Nothing to move to, unmounted, or the move itself failed. The cursor did not move.
NotMoved,
/// The cursor moved but the rebuild from it failed. It stays moved unless the caller reverts it.
RebuildFailed,
}
impl DocumentHistory {
@@ -58,6 +91,7 @@ impl DocumentHistory {
/// Clear the redo stack, called when a fresh edit invalidates the redo future.
pub fn clear_redo(&mut self) {
self.legacy_redo_stack.clear();
self.retracted_undos.clear();
}
/// Add the resources referenced by every snapshot in both history stacks into `resources`, so
@@ -80,14 +114,146 @@ impl DocumentHistory {
self.storage.as_mut()
}
/// Attach (or clear) the `Gdd` working copy once the mount future resolves.
pub fn set_storage(&mut self, storage: Option<document_format::GddV1>) {
self.storage = storage;
/// The decoded proto-node declarations the working copy's registry states reference.
pub fn declarations(&self) -> &Declarations {
&self.declarations
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit. Called at each undo-step
/// boundary (a new `StartTransaction`) and before undo/redo, so the per-`CommitTransaction` staging
/// coalesces into one interaction aligned with the legacy step. No-op while unmounted.
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
self.needs_whole_document_stage |= storage.registry().node_instances.is_empty();
self.storage = Some(storage);
self.declarations = declarations;
}
/// Marks the working copy as needing a whole-document stage on its next commit, for a change to the
/// runtime that went unrecorded and so cannot be described by the recorded batch.
pub fn require_whole_document_stage(&mut self) {
self.needs_whole_document_stage = true;
}
/// Close the open storage transaction at an undo-step boundary (a new `StartTransaction`), so the
/// per-`CommitTransaction` staging since the last boundary is one unit for retirement and undo, aligned
/// with the legacy step. Retirement itself follows the working copy's policy. No-op while unmounted.
pub fn end_storage_transaction(&mut self) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.end_transaction() {
log::error!("Closing the storage transaction failed: {error}");
}
}
/// Undo the latest storage transaction while it is still hot by taking it back, so it leaves every hot
/// log and never becomes a history step. `false` when the step already retired. No-op while unmounted.
pub fn retract_storage_transaction(&mut self) -> Option<Vec<document_graph_storage::RegistryDelta>> {
let storage = self.storage.as_mut()?;
match storage.retract_transaction() {
Ok(retracted) => retracted,
Err(error) => {
log::error!("Taking the storage transaction back failed: {error}");
None
}
}
}
/// Stage ops a retraction took back, as a fresh transaction: the redo of a step taken back. What they
/// name lands in the remote changes, for the interface to follow.
pub fn restage_ops(&mut self, ops: Vec<document_graph_storage::RegistryDelta>) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.restage_ops(ops) {
log::error!("Staging the redone step failed: {error}");
}
}
/// Whether there is a legacy undo step to pop, and so a step storage may take back.
pub fn has_undo_step(&self) -> bool {
!self.legacy_undo_stack.is_empty()
}
/// Whether there is a legacy redo step to pop.
pub fn has_redo_step(&self) -> bool {
!self.legacy_redo_stack.is_empty()
}
/// The resource bytes the steps taken back still name, so garbage collection keeps them for a redo:
/// once taken back, nothing in the registry or history refers to them any more.
pub fn retracted_resource_hashes(&self) -> impl Iterator<Item = graph_craft::application_io::resource::ResourceHash> + '_ {
self.retracted_undos
.iter()
.filter_map(|note| match note {
UndoNote::Retracted(ops) => Some(ops),
_ => None,
})
.flatten()
.filter_map(|op| match op {
document_graph_storage::RegistryDelta::AddResource { entry, .. } => entry.hash,
document_graph_storage::RegistryDelta::SetResourceHash { hash, .. } => *hash,
_ => None,
})
}
/// Whether the next redo step is one storage undid on its own, taken back or dropped, so the caller can
/// decide how to redo before it moves the legacy stacks.
pub fn next_redo_is_storage_driven(&self) -> bool {
!matches!(self.retracted_undos.last(), None | Some(UndoNote::Cursor))
}
/// Record how the step just undone reached storage, paired with the legacy redo entry pushed for it.
pub fn note_undo(&mut self, note: UndoNote) {
self.retracted_undos.push(note);
}
/// How the step about to be redone was undone, cursor-undone when nothing was noted.
pub fn take_undo_note(&mut self) -> UndoNote {
self.retracted_undos.pop().unwrap_or(UndoNote::Cursor)
}
/// Undo this peer's latest retired step in a session; see [`document_format::Gdd::undo_retired_step`].
pub fn undo_retired_step(&mut self) -> Option<document_graph_storage::Rev> {
let storage = self.storage.as_mut()?;
match storage.undo_retired_step() {
Ok(rev) => rev,
Err(error) => {
log::error!("Undoing the retired step failed: {error}");
None
}
}
}
/// Redo a step dropped out of a session's line.
pub fn redo_retired_step(&mut self, rev: document_graph_storage::Rev) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.redo_retired_step(rev) {
log::error!("Redoing the dropped step failed: {error}");
}
}
/// Drop any retired interaction out of the line; see [`document_format::Gdd::drop_step`].
pub fn drop_step(&mut self, rev: document_graph_storage::Rev) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.drop_step(rev) {
log::error!("Removing the step failed: {error}");
}
}
/// Move the shared head to an ancestor; see [`document_format::Gdd::move_head`].
pub fn move_head_to(&mut self, rev: document_graph_storage::Rev) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.move_head(rev) {
log::error!("Moving the head failed: {error}");
}
}
/// Forget the legacy snapshots: after a move made from the History panel they describe states off the line the
/// head is on, so Ctrl+Z resumes from the next edit and the panel is the way back meanwhile.
pub fn clear_legacy(&mut self) {
self.legacy_undo_stack.clear();
self.legacy_redo_stack.clear();
self.retracted_undos.clear();
}
/// Close this peer's open transaction and retire every closed one into durable Gdd history, so the
/// interaction being undone is in history. Called before undo/redo and after the first commit of a
/// newly mounted document. No-op while unmounted.
pub fn retire_storage_interaction(&mut self) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.retire_pending_interaction() {
@@ -95,11 +261,10 @@ impl DocumentHistory {
}
}
/// Stage the runtime snapshot into the `Gdd` working copy at each `CommitTransaction`. No-op while
/// unmounted. Proto-node declaration bytes go into `byte_store` (the app-global resource cache). The
/// staged hot ops are retired by [`retire_storage_interaction`](Self::retire_storage_interaction) at
/// undo-step boundaries. `validate` (the `validate_storage_round_trip` preference) gates the per-commit
/// round-trip check, off by default for its perf cost.
/// Stage a `CommitTransaction` into the `Gdd` working copy: the first commit writes the whole document,
/// every later one stages the `deltas` the store recorded. No-op while unmounted. Proto-node declaration
/// bytes go into `byte_store` (the app-global resource cache). The staged hot ops are closed into one
/// transaction by [`end_storage_transaction`](Self::end_storage_transaction) at undo-step boundaries.
pub fn stage_snapshot(
&mut self,
deltas: &[EditorDelta],
@@ -109,31 +274,51 @@ impl DocumentHistory {
legacy_document: &str,
byte_store: &dyn ResourceStorage,
) {
let Some(storage) = self.storage.as_mut() else { return };
// A working copy that does not hold the document yet has no baseline for a batch of changes to
// apply to, so the first commit writes the whole document and every later one stages only what
// the store recorded. Reading that from the working copy rather than from the caller means a path
// that mounts storage and then commits does not have to know which of the two it is.
let staged = match storage.registry().node_instances.is_empty() {
true => Self::stage_whole_document(storage, interface, registry, byte_store),
// An autosave with nothing edited since the last commit still persists the view state below.
false if deltas.is_empty() => Ok(()),
false => Self::stage_recorded(storage, deltas, interface, registry, byte_store),
};
if let Err(error) = staged {
log::error!("Storage snapshot staging failed: {error}");
if !self.stage_graph(deltas, interface, registry, byte_store) {
return;
}
self.persist_view_state(interface, view_settings, legacy_document);
}
/// The graph half of [`stage_snapshot`](Self::stage_snapshot), without the view state. A session
/// does this every frame, so a peer sees each movement of a drag as its own hot op rather than
/// whatever the autosave timer happened to catch; retirement coarsens them later. Returns whether the
/// working copy is mounted and took the batch.
pub fn stage_graph(&mut self, deltas: &[EditorDelta], interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> bool {
let needs_whole_document_stage = self.needs_whole_document_stage;
let Some(storage) = self.storage.as_mut() else { return false };
let staged = match needs_whole_document_stage {
true => Self::stage_whole_document(storage, interface, registry, byte_store),
// An autosave with nothing edited since the last commit still persists the view state below.
false if deltas.is_empty() => Ok(Declarations::new()),
// The batch is drained by the time it reaches here, so a failed staging would leave the working copy
// permanently behind. Converting the whole document restages the same edit from whatever the working
// copy holds, including a batch that failed partway through.
false => Self::stage_recorded(storage, deltas, interface, registry, byte_store).or_else(|error| {
log::error!("Staging recorded deltas failed, falling back to a whole document snapshot: {error}");
Self::stage_whole_document(storage, interface, registry, byte_store)
}),
};
match staged {
Ok(declarations) => {
self.declarations.extend(declarations);
self.needs_whole_document_stage = false;
true
}
Err(error) => {
log::error!("Storage snapshot staging failed: {error}");
false
}
}
}
/// Converts the whole document and stages the difference from what the working copy holds.
///
/// Stages without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo
/// step, so the ops accumulate in the hot log and coalesce at the next undo-step boundary.
fn stage_whole_document(storage: &mut document_format::GddV1, interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> Result<(), String> {
fn stage_whole_document(storage: &mut document_format::GddV1, interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> Result<Declarations, String> {
let metadata_view = StorageMetadataView::new(interface);
storage
.stage_runtime_snapshot(interface.document_network(), &metadata_view, registry, byte_store)
@@ -152,19 +337,19 @@ impl DocumentHistory {
interface: &NodeNetworkInterface,
registry: &ResourceRegistry,
byte_store: &dyn ResourceStorage,
) -> Result<(), String> {
) -> Result<Declarations, String> {
let peer = storage.session().peer();
let metadata_view = StorageMetadataView::new(interface);
let constructed = construct_batch(deltas, storage.registry(), registry, &metadata_view, peer).map_err(|error| error.to_string())?;
storage
.stage_constructed_ops(constructed.ops, &constructed.declaration_bytes, byte_store)
.map_err(|error| error.to_string())
.stage_constructed_ops(constructed.ops, &constructed.declarations.bytes, byte_store)
.map_err(|error| error.to_string())?;
Ok(constructed.declarations.decoded)
}
/// The parts of a commit that are not the graph: the per-peer view settings, and the legacy bytes the
/// dual-write soak validates the new format against. Both staging paths persist them; they differ
/// only in how the graph ops are derived.
/// dual-write soak validates the new format against.
fn persist_view_state(&mut self, interface: &NodeNetworkInterface, view_settings: BTreeMap<String, serde_json::Value>, legacy_document: &str) {
let Some(storage) = self.storage.as_mut() else { return };
@@ -189,31 +374,98 @@ impl DocumentHistory {
}
/// Move the `Gdd` undo/redo cursor along the retired interaction chain, flushing any open interaction
/// first. Returns a clone of the post-move `Gdd` (`Arc`-shared) so a `'static` rebuild future can read
/// the rewound state while the live document keeps its cursor. `None` when there is nothing to move to,
/// unmounted, or the move failed.
pub fn move_cursor(&mut self, undo: bool) -> Option<document_format::GddV1> {
/// first, and rebuild the interface from the rewound registry using the declaration cache.
pub fn move_cursor(&mut self, undo: bool) -> Result<NodeNetworkInterface, CursorMoveError> {
self.retire_storage_interaction();
let storage = self.storage.as_mut()?;
let storage = self.storage.as_mut().ok_or(CursorMoveError::NotMoved)?;
let moved = if undo {
if !storage.can_undo() {
return None;
return Err(CursorMoveError::NotMoved);
}
storage.undo().map(|_| ())
} else {
if !storage.can_redo() {
return None;
return Err(CursorMoveError::NotMoved);
}
storage.redo().map(|_| ())
};
if let Err(error) = moved {
log::error!("Storage undo/redo cursor move failed: {error}");
return None;
return Err(CursorMoveError::NotMoved);
}
Some(storage.clone())
self.rebuild_interface().ok_or(CursorMoveError::RebuildFailed)
}
/// Build a fresh interface from the working registry, using the declaration cache so no resource load
/// is needed. `None` (logged) when the registry does not convert.
pub fn rebuild_interface(&self) -> Option<NodeNetworkInterface> {
let storage = self.storage.as_ref()?;
let rebuilt = storage
.registry()
.to_runtime_with_full_metadata(&self.declarations)
.map_err(|error| error.to_string())
.and_then(|(network, node_entries, network_entries)| build_interface_from_storage(network, node_entries, network_entries).map_err(|error| error.to_string()));
match rebuilt {
Ok(interface) => Some(interface),
Err(error) => {
log::error!("Storage interface rebuild failed: {error}");
None
}
}
}
/// The hashes of declaration resources the working copy names but holds no decoded declaration for.
/// A remote change can name a declaration whose bytes are already in the byte store from an earlier
/// session, so it is never requested from a peer and has to be decoded from what is on hand.
pub fn undecoded_declaration_hashes(&self) -> Vec<ResourceHash> {
let Some(storage) = self.storage.as_ref() else { return Vec::new() };
let mut hashes: Vec<ResourceHash> = storage
.session()
.all_declaration_resources()
.into_iter()
.filter_map(|(id, hash)| (!self.declarations.contains_key(&id)).then_some(hash?))
.collect();
hashes.sort_unstable();
hashes.dedup();
hashes
}
/// Cache a resource that arrived from a peer as a proto-node declaration, under every declaration
/// resource referencing its hash. Ignores resources no declaration refers to (images, fonts).
pub fn cache_declaration_bytes(&mut self, hash: ResourceHash, bytes: &[u8]) {
let Some(storage) = self.storage.as_ref() else { return };
let referencing: Vec<ResourceId> = storage
.session()
.all_declaration_resources()
.into_iter()
.filter_map(|(id, declaration_hash)| (declaration_hash == Some(hash)).then_some(id))
.collect();
if referencing.is_empty() {
return;
}
match document_graph_storage::decode_declaration(bytes) {
Ok(declaration) => self.declarations.extend(referencing.into_iter().map(|id| (id, declaration.clone()))),
Err(error) => log::error!("Failed to deserialize a received ProtoNode declaration: {error}"),
}
}
/// Step the cursor back the other way, undoing a [`move_cursor`](Self::move_cursor) in the `undo`
/// direction whose rebuild failed.
pub fn revert_cursor(&mut self, undo: bool) {
let Some(storage) = self.storage.as_mut() else { return };
let reverted = if undo { storage.redo() } else { storage.undo() };
if let Err(error) = reverted {
log::error!("Storage undo/redo cursor revert failed: {error}");
}
}
// Soak round-trip verification (runtime-gated by `validate_storage_round_trip`)
@@ -240,13 +492,7 @@ impl DocumentHistory {
}
};
let target = &conversion.registry;
let declarations = match conversion.declarations() {
Ok(declarations) => declarations,
Err(error) => {
log::error!("storage round-trip: declaration rebuild failed: {error}");
return;
}
};
let declarations = &conversion.declarations;
let stored = storage.registry();
if !stored.value_equal(target) {
@@ -260,7 +506,7 @@ impl DocumentHistory {
panic!("storage round-trip: timestamp order inconsistent between stored and target");
}
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(&declarations) {
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(declarations) {
Ok(result) => result,
Err(error) => {
log::error!("storage round-trip: to_runtime failed: {error}");
@@ -54,6 +54,18 @@ pub enum DocumentMessage {
DeselectAllLayers,
DocumentHistoryBackward,
DocumentHistoryForward,
/// From the History panel: move the shared head to an earlier interaction, the steps since staying as a branch.
HistoryMoveHead {
rev: document_graph_storage::Rev,
},
/// From the History panel: drop one retired interaction out of the line, the later ones minted again on its parent.
HistoryRemoveStep {
rev: document_graph_storage::Rev,
},
/// From the History panel: mint a dropped or abandoned interaction again on top of the line.
HistoryRestoreStep {
rev: document_graph_storage::Rev,
},
DocumentStructureChanged,
DrawArtboardOverlays {
context: OverlayContext,
@@ -1,10 +1,11 @@
use super::DocumentHistory;
use super::document_diff::diff_networks;
use super::document_history::UndoNote;
use super::node_graph::document_node_definitions;
use super::utility_types::error::EditorError;
use super::utility_types::misc::{GroupFolderType, SNAP_FUNCTIONS_FOR_BOUNDING_BOXES, SNAP_FUNCTIONS_FOR_PATHS, SnappingOptions, SnappingState};
use super::utility_types::network_interface::{self, NodeNetworkInterface, TransactionStatus};
use super::utility_types::nodes::{CollapsedLayers, LayerStructureEntry, SelectedNodes};
use super::{CursorMoveError, DocumentHistory};
use crate::application::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
use crate::consts::{
ASYMPTOTIC_EFFECT, BLEND_COUNT_PER_LAYER, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, SCALE_EFFECT, SCROLLBAR_SPACING,
@@ -23,7 +24,7 @@ use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType
use crate::messages::portfolio::document::properties_panel::properties_panel_message_handler::PropertiesPanelMessageContext;
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, OutputConnector, ReconcileError, Reconciled};
use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{self, get_blend_mode, get_fill, get_opacity};
@@ -32,8 +33,12 @@ use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys;
use crate::messages::tool::tool_messages::tool_prelude::Key;
use crate::messages::tool::utility_types::ToolType;
use crate::node_graph_executor::NodeGraphExecutor;
use document_graph_storage::Declarations;
/// The document attribute holding the document's name, so a session shares it and a rename reaches every peer.
pub const DOCUMENT_NAME_ATTRIBUTE: &str = "name";
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::application_io::resource::{ResourceId, ResourceStorage};
use graph_craft::application_io::wgpu_available;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
@@ -148,6 +153,11 @@ pub struct DocumentMessageHandler {
/// Undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor.
#[serde(skip)]
history: DocumentHistory,
/// What peers changed in the working registry that the interface does not show yet. Applied once every
/// declaration it needs is cached. Local edits stage meanwhile: they are constructed against the
/// registry rather than diffed from the interface, so nothing here reads as reverting them.
#[serde(skip)]
pub(crate) pending_remote: document_format::network::RemoteChanges,
/// Hash of the document snapshot that was most recently saved to disk by the user.
#[serde(skip)]
saved_hash: Option<u64>,
@@ -199,6 +209,7 @@ impl Default for DocumentMessageHandler {
breadcrumb_network_path: Vec::new(),
selection_network_path: Vec::new(),
history: DocumentHistory::default(),
pending_remote: Default::default(),
saved_hash: None,
auto_saved_hash: None,
layer_range_selection_reference: None,
@@ -406,8 +417,11 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![] });
self.layer_range_selection_reference = None;
}
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(document_id, viewport, resource_storage, responses),
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, resource_storage, responses),
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::DocumentHistoryForward => self.redo_with_history(viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::HistoryMoveHead { rev } => self.apply_history_action(|history| history.move_head_to(rev), responses),
DocumentMessage::HistoryRemoveStep { rev } => self.apply_history_action(|history| history.drop_step(rev), responses),
DocumentMessage::HistoryRestoreStep { rev } => self.apply_history_action(|history| history.redo_retired_step(rev), responses),
DocumentMessage::DocumentStructureChanged => {
if layers_panel_open {
self.network_interface.load_structure();
@@ -942,6 +956,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.path = None;
self.set_save_state(false);
self.set_auto_save_state(false);
self.stage_name_attribute();
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::UpdateNewNodeGraph);
@@ -1348,7 +1363,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
// Note: A transaction should never be started in a scope that mutates the network interface, since it will only be run after that scope ends.
DocumentMessage::StartTransaction => {
self.retire_storage_interaction();
self.end_storage_transaction();
self.network_interface.start_transaction();
self.history.push_undo(self.network_interface.clone());
@@ -1808,7 +1823,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
impl DocumentMessageHandler {
/// Build a document handler from a `.gdd` working copy.
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, name: String, path: Option<std::path::PathBuf>) -> Self {
pub fn from_storage(
interface: NodeNetworkInterface,
storage: document_format::GddV1,
declarations: Declarations,
byte_store: Arc<dyn ResourceStorage>,
name: String,
path: Option<std::path::PathBuf>,
) -> Self {
let mut document = Self {
network_interface: interface,
name,
@@ -1817,11 +1839,7 @@ impl DocumentMessageHandler {
};
document.apply_stored_document_settings(storage.view_settings());
match storage.registry().to_resource_registry() {
Ok(resource_registry) => document.resources.registry = resource_registry,
Err(error) => log::error!("Opening .gdd: failed to rebuild resource registry: {error}"),
}
document.history.set_storage(Some(storage));
document.set_storage(storage, declarations, byte_store);
document
}
@@ -1833,6 +1851,12 @@ impl DocumentMessageHandler {
self.network_interface.validate_output_names(node_id, node, &path);
}
// Restoring the parallel-array invariant is how the document arrives, not an edit to it, so what the
// fix-ups recorded must not ride along in the first real commit. They still have to reach storage,
// so the next commit converts the whole document rather than staging the batch that follows them.
self.network_interface.discard_deltas();
self.history.require_whole_document_stage();
self.network_interface.load_structure();
}
@@ -2002,6 +2026,51 @@ impl DocumentMessageHandler {
/// Path to the subnetwork that the user's selection is currently scoped to.
/// Empty when the selection lives in the root document network.
/// The network the node graph shows, from the document network down.
pub fn breadcrumb_network_path(&self) -> &[NodeId] {
&self.breadcrumb_network_path
}
/// Write the document's name into its registry as a document attribute, so peers in a session see it and a
/// rename reaches them; a no-op without a working copy or when the registry already holds this name.
pub fn stage_name_attribute(&mut self) {
let name = self.name.clone();
let Some(gdd) = self.storage_mut() else { return };
if gdd
.registry()
.attributes
.get(DOCUMENT_NAME_ATTRIBUTE)
.is_some_and(|value| !value.deleted && value.value.as_str() == Some(name.as_str()))
{
return;
}
let delta = document_graph_storage::AttributeDelta {
key: DOCUMENT_NAME_ATTRIBUTE.to_string(),
value: Some(serde_json::Value::String(name)),
};
if let Err(error) = gdd.stage_ops([document_graph_storage::RegistryDelta::ChangeDocumentAttribute { delta }]) {
log::error!("Staging the document name failed: {error}");
}
}
/// Take the name the registry holds, after peers changed it. Returns whether the name changed.
pub fn adopt_name_from_storage(&mut self) -> bool {
let Some(name) = self
.storage()
.and_then(|gdd| gdd.registry().attributes.get(DOCUMENT_NAME_ATTRIBUTE))
.filter(|value| !value.deleted)
.and_then(|value| value.value.as_str())
.map(str::to_string)
else {
return false;
};
if name == self.name {
return false;
}
self.name = name;
true
}
pub fn selection_network_path(&self) -> &[NodeId] {
&self.selection_network_path
}
@@ -2016,9 +2085,16 @@ impl DocumentMessageHandler {
self.history.storage_mut()
}
/// Attach (or clear) the `Gdd` working copy once the mount future resolves.
pub fn set_storage(&mut self, storage: Option<document_format::GddV1>) {
self.history.set_storage(storage);
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
pub fn set_storage(&mut self, mut storage: document_format::GddV1, declarations: Declarations, byte_store: Arc<dyn ResourceStorage>) {
storage.set_byte_store(byte_store);
self.history.set_storage(storage, declarations);
self.refresh_resource_registry();
}
/// Close the open storage transaction at an undo-step boundary.
pub(crate) fn end_storage_transaction(&mut self) {
self.history.end_storage_transaction();
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit.
@@ -2026,6 +2102,12 @@ impl DocumentMessageHandler {
self.history.retire_storage_interaction();
}
/// Marks the working copy as needing a whole-document stage on its next commit, for a change to the
/// runtime that went unrecorded.
pub(crate) fn require_whole_document_stage(&mut self) {
self.history.require_whole_document_stage();
}
/// Stages what the store recorded since the last commit into the `Gdd` working copy.
///
/// The batch boundary: everything the interface recorded since the last one is this commit's batch.
@@ -2041,7 +2123,9 @@ impl DocumentMessageHandler {
self.history
.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, legacy_document.as_str(), byte_store);
if validate {
// The interface is behind the registry by what peers changed, so the two are only expected to
// agree once that is applied.
if validate && self.pending_remote.is_empty() {
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
}
}
@@ -2091,24 +2175,120 @@ impl DocumentMessageHandler {
}
}
/// Move the `Gdd` undo/redo cursor and spawn the async future that rebuilds the
/// interface from the cursor and swaps it in. `had_oracle` records whether the legacy snapshot already
/// applied, so the completion can compare; it travels with the spawned message. Returns whether the
/// cursor moved, so callers know a rebuild is pending.
fn drive_storage_undo_redo(&mut self, document_id: DocumentId, resource_storage: &ResourceStorageMessageHandler, had_oracle: bool, undo: bool, responses: &mut VecDeque<Message>) -> bool {
let Some(gdd) = self.history.move_cursor(undo) else { return false };
/// Move the `Gdd` undo/redo cursor and swap in the interface rebuilt from it. `had_oracle` records
/// whether the legacy snapshot already applied, so the rebuild can be compared against it.
fn drive_storage_undo_redo(&mut self, had_oracle: bool, undo: bool, validate: bool, responses: &mut VecDeque<Message>) {
match self.history.move_cursor(undo) {
Ok(rebuilt) => self.apply_gdd_cursor_rebuild(rebuilt, had_oracle, validate, responses),
Err(CursorMoveError::NotMoved) => {}
// Without the legacy snapshot the interface stayed put, so the cursor has to follow it back.
Err(CursorMoveError::RebuildFailed) => {
if !had_oracle {
self.history.revert_cursor(undo);
}
}
}
}
responses.add(crate::messages::portfolio::document_storage_io::rebuild_gdd_cursor(
gdd,
resource_storage.resources_mut(),
document_id,
had_oracle,
));
/// Rebuild the runtime resource registry from storage, which holds each resource's id, content hash
/// and sources. The preprocessor resolves a node's `Resource` input through it, so an interface
/// swapped in from storage needs it refreshed alongside. Keeps the current registry on failure.
fn refresh_resource_registry(&mut self) {
let Some(storage) = self.history.storage() else { return };
match storage.registry().to_resource_registry() {
Ok(resource_registry) => self.resources.registry = resource_registry,
Err(error) => log::error!("Failed to rebuild the resource registry from storage: {error}"),
}
}
/// Stages what the interface recorded since the last drain, so a session sends each movement in the
/// frame it was made rather than at the next commit or autosave. Nothing else a commit does is done here.
pub(crate) fn stage_pending_edits(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage) {
let deltas = self.network_interface.take_deltas();
if deltas.is_empty() {
return;
}
self.history.stage_graph(&deltas, &self.network_interface, &self.resources.registry, byte_store);
}
/// Brings the interface into line with what peers changed in the registry. Returns whether nothing is
/// left pending: a declaration still on its way keeps the changes for a later call.
///
/// The touched entities are reconciled in place. Only a registry rederived wholesale, or a reconcile
/// that fails for some other reason, costs a rebuild of the whole interface.
pub(crate) fn apply_remote_changes(&mut self, responses: &mut VecDeque<Message>) -> bool {
let changes = std::mem::take(&mut self.pending_remote);
if changes.is_empty() {
return true;
}
if !changes.rebuilt
&& let Some(gdd) = self.history.storage()
{
let peer = gdd.session().peer();
match self.network_interface.reconcile_remote(gdd.registry(), self.history.declarations(), &changes.touched, peer) {
Ok(reconciled) => {
self.finish_remote_reconcile(reconciled, changes.touched.resources, responses);
return true;
}
Err(ReconcileError::DeclarationMissing(id)) => {
log::debug!("Remote changes wait for declaration {id}");
self.pending_remote = changes;
return false;
}
Err(error) => log::warn!("Reconciling remote changes failed, rebuilding the interface instead: {error}"),
}
}
if let Some(rebuilt) = self.history.rebuild_interface() {
self.apply_gdd_cursor_rebuild(rebuilt, false, false, responses);
}
true
}
/// What a rebuild does for the whole interface, for the networks a reconcile changed: drops what the
/// changed nodes feed and re-derives the layer structure.
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, responses: &mut VecDeque<Message>) {
for path in &reconciled.networks {
if self.network_interface.document_network().nested_network(path).is_none() {
continue;
}
self.network_interface.unload_stack_dependents(path);
self.network_interface.unload_import_export_ports(path);
self.network_interface.unload_modify_import_export(path);
self.network_interface.unload_all_nodes_bounding_box(path);
self.network_interface.unload_outward_wires(path);
self.network_interface.unload_all_nodes_click_targets(path);
}
self.network_interface.load_structure();
if let Some(gdd) = self.history.storage_mut() {
gdd.mark_runtime_current();
}
if resources_changed {
self.refresh_resource_registry();
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires);
}
/// Cache a resource received from a peer as a proto-node declaration, so a rebuild can resolve it.
pub(crate) fn cache_declaration_bytes(&mut self, hash: graph_craft::application_io::resource::ResourceHash, bytes: &[u8]) {
self.history.cache_declaration_bytes(hash, bytes);
}
/// Declaration resources the working copy names whose bytes are on hand but not yet decoded.
pub(crate) fn undecoded_declaration_hashes(&self) -> Vec<graph_craft::application_io::resource::ResourceHash> {
self.history.undecoded_declaration_hashes()
}
/// Swap in the interface rebuilt from the `Gdd` cursor. Always overwrites the interface.
pub(crate) fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
rebuilt.copy_all_transient_view_state(&self.network_interface);
std::mem::swap(&mut rebuilt.resolved_types, &mut self.network_interface.resolved_types);
rebuilt.load_structure();
@@ -2118,6 +2298,11 @@ impl DocumentMessageHandler {
}
self.network_interface = rebuilt;
self.pending_remote = Default::default();
if let Some(gdd) = self.history.storage_mut() {
gdd.mark_runtime_current();
}
self.refresh_resource_registry();
if validate {
let current_resources: std::collections::HashSet<_> = self.used_resources(false).iter().copied().collect();
@@ -2419,15 +2604,79 @@ impl DocumentMessageHandler {
paths
}
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
pub fn undo_with_history(&mut self, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
// A step still hot is taken back and never becomes history. The legacy snapshot is not installed: it
// predates whatever peers wrote in the meantime, so the interface keeps what it holds and follows the
// registry on just the entities the step named. Only a retired step moves the cursor.
if self.history.has_undo_step()
&& let Some(ops) = self.history.retract_storage_transaction()
{
if let Some(snapshot) = self.history.pop_undo() {
self.history.push_redo(snapshot);
}
self.history.note_undo(UndoNote::Retracted(ops));
self.follow_storage_changes(responses);
return;
}
// In a session a retired step is public: it is dropped out of the shared line, by the retirer or on
// request, and the room follows the head. Nothing else in a session may install a legacy snapshot.
if self.is_in_session() {
if self.history.has_undo_step()
&& let Some(rev) = self.history.undo_retired_step()
{
if let Some(snapshot) = self.history.pop_undo() {
self.history.push_redo(snapshot);
}
self.history.note_undo(UndoNote::Dropped(rev));
self.follow_storage_changes(responses);
}
return;
}
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
self.history.push_redo(previous_network);
true
} else {
false
};
if legacy_applied {
self.history.note_undo(UndoNote::Cursor);
}
self.drive_storage_undo_redo(legacy_applied, true, validate, responses);
}
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, true, responses);
/// An action from the History panel: storage performs it and records what it named, the interface follows on
/// just those entities, and the legacy snapshots go since they describe states off the line the head is on now.
fn apply_history_action(&mut self, action: impl FnOnce(&mut super::document_history::DocumentHistory), responses: &mut VecDeque<Message>) {
if self.network_interface.transaction_status() != TransactionStatus::Finished {
return;
}
responses.add(EventMessage::ToolAbort);
self.history.retire_storage_interaction();
action(&mut self.history);
self.history.clear_legacy();
self.follow_storage_changes(responses);
responses.add(OverlaysMessage::Draw);
responses.add(EventMessage::SelectionChanged);
}
/// Bring the interface into line with what storage just changed under it, a step taken back or staged
/// again, by reconciling the entities those ops named, the way remote changes are applied. Anything a
/// peer wrote meanwhile stays as the interface holds it.
fn follow_storage_changes(&mut self, responses: &mut VecDeque<Message>) {
if let Some(gdd) = self.history.storage_mut() {
let changes = gdd.take_remote_changes();
self.pending_remote.extend(changes);
}
self.apply_remote_changes(responses);
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
responses.add(NodeGraphMessage::UnloadWires);
}
fn is_in_session(&self) -> bool {
self.storage().is_some_and(|gdd| gdd.role().is_some())
}
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
@@ -2461,15 +2710,35 @@ impl DocumentMessageHandler {
Some(previous_network)
}
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
pub fn redo_with_history(&mut self, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
// A step that was taken back is staged afresh from the ops themselves: they are gone from every hot log,
// so redo is a new edit, and the interface follows the registry on what they name, as for the undo.
if self.history.has_redo_step() && self.history.next_redo_is_storage_driven() {
if let Some(snapshot) = self.history.pop_redo() {
self.history.push_undo(snapshot);
}
match self.history.take_undo_note() {
UndoNote::Retracted(ops) => self.history.restage_ops(ops),
UndoNote::Dropped(rev) => self.history.redo_retired_step(rev),
UndoNote::Cursor => {}
}
self.follow_storage_changes(responses);
return;
}
if self.is_in_session() {
return;
}
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
self.history.push_undo(previous_network);
true
} else {
false
};
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, false, responses);
if legacy_applied {
self.history.take_undo_note();
}
self.drive_storage_undo_redo(legacy_applied, false, validate, responses);
}
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
@@ -2804,9 +3073,9 @@ impl DocumentMessageHandler {
self.network_interface.move_node_to_chain_start(&solidify_id, layer, &[], false);
if has_fill && has_stroke {
let (existing_index, new_index) = (0_f64, 1_f64);
let (existing_index, new_index) = (0_i64, 1_i64);
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Integer(existing_index), false))]);
let existing_index_id = NodeId::new();
self.network_interface.insert_node(existing_index_id, existing_index_template, &[]);
self.network_interface.move_node_to_chain_start(&existing_index_id, layer, &[], false);
@@ -2828,7 +3097,7 @@ impl DocumentMessageHandler {
self.network_interface.set_display_name(&new_layer_id, original_name, &[]);
}
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Integer(new_index), false))]);
let new_index_id = NodeId::new();
self.network_interface.insert_node(new_index_id, new_index_template, &[]);
self.network_interface.move_node_to_chain_start(&new_index_id, new_layer, &[], false);
@@ -3797,6 +4066,11 @@ impl DocumentMessageHandler {
self.resources.collect_garbage(&used_resources);
}
/// Resource bytes only a step taken back on undo still names; see [`DocumentHistory::retracted_resource_hashes`].
pub fn retracted_resource_hashes(&self) -> impl Iterator<Item = graph_craft::application_io::resource::ResourceHash> + '_ {
self.history.retracted_resource_hashes()
}
pub fn used_resources(&self, include_history: bool) -> Box<[ResourceId]> {
let mut resources = HashSet::new();
self.network_interface.collect_used_resources(&mut resources);
@@ -287,7 +287,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
// Insert the main chain node (Blend or Morph) depending on whether a blend count is provided, referencing
// its control path input by the Blend template's named position or the Morph proto node's parameter symbol
let (path_input_connector, layer_alias, path_alias) = if let Some(count) = blend_count {
let blend_node_id = modify_inputs.insert_blend_data(layer, count as f64);
let blend_node_id = modify_inputs.insert_blend_data(layer, count as i64);
(InputConnector::node_at_index(blend_node_id, BLEND_PATH_INPUT_INDEX), "Blend", "Blend Path")
} else {
let morph_node_id = modify_inputs.insert_morph_data(layer);
@@ -881,9 +881,9 @@ fn insert_brush_strokes_chain(network_interface: &mut NodeNetworkInterface, laye
let strokes_node = strokes_node_type.node_template_input_override([
Some(NodeInput::value(TaggedValue::Strokes(Vec::new()), false)),
Some(NodeInput::value(TaggedValue::Color(color), false)),
Some(NodeInput::value(TaggedValue::F64(diameter), false)),
Some(NodeInput::value(TaggedValue::F64(hardness), false)),
Some(NodeInput::value(TaggedValue::F64(flow), false)),
Some(NodeInput::value(TaggedValue::Number(diameter), false)),
Some(NodeInput::value(TaggedValue::Number(hardness), false)),
Some(NodeInput::value(TaggedValue::Number(flow), false)),
]);
network_interface.insert_node(strokes_node_id, strokes_node, &[]);
network_interface.set_input(&InputConnector::node_at_index(layer.to_node(), 1), NodeInput::node(strokes_node_id, 0), &[]);
@@ -19,7 +19,7 @@ pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &
);
network_interface.set_input(
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::RotationInput),
NodeInput::value(TaggedValue::F64(rotation), false),
NodeInput::value(TaggedValue::Number(rotation), false),
&[],
);
network_interface.set_input(
@@ -70,7 +70,7 @@ pub fn get_current_transform(inputs: &[NodeInput]) -> DAffine2 {
} else {
DVec2::ZERO
};
let rotation = if let Some(&TaggedValue::F64(rotation)) = inputs[2].as_value() { rotation } else { 0. };
let rotation = if let Some(&TaggedValue::Number(rotation)) = inputs[2].as_value() { rotation } else { 0. };
let scale = if let Some(&TaggedValue::DVec2(scale)) = inputs[3].as_value() { scale } else { DVec2::ONE };
let skew = if let Some(&TaggedValue::DVec2(skew)) = inputs[4].as_value() { skew } else { DVec2::ZERO };
@@ -94,10 +94,10 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.move_node_to_chain_start(&boolean_id, layer, &[], self.import);
}
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: f64) -> NodeId {
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: i64) -> NodeId {
let blend = resolve_network_node_type("Blend")
.expect("Blend node does not exist")
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(count), false))]);
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::Integer(count), false))]);
let blend_id = NodeId::new();
self.network_interface.insert_node(blend_id, blend, &[]);
@@ -109,7 +109,7 @@ impl<'a> ModifyInputsContext<'a> {
pub fn insert_morph_data(&mut self, layer: LayerNodeIdentifier) -> NodeId {
let morph = resolve_proto_node_type(graphene_std::vector::morph::IDENTIFIER)
.expect("Morph node does not exist")
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::Number(0.5), false))]);
let morph_id = NodeId::new();
self.network_interface.insert_node(morph_id, morph, &[]);
@@ -131,7 +131,7 @@ impl<'a> ModifyInputsContext<'a> {
// Add Auto-Tangents node (between Origins to Polyline and Path), with spread=1 and preserve_existing=false
let auto_tangents = resolve_proto_node_type(graphene_std::vector::auto_tangents::IDENTIFIER)
.expect("Auto-Tangents node does not exist")
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(1.), false)), Some(NodeInput::value(TaggedValue::Bool(false), false))]);
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Number(1.), false)), Some(NodeInput::value(TaggedValue::Bool(false), false))]);
let auto_tangents_id = NodeId::new();
self.network_interface.insert_node(auto_tangents_id, auto_tangents, &[]);
self.network_interface.move_node_to_chain_start(&auto_tangents_id, layer, &[], self.import);
@@ -193,14 +193,14 @@ impl<'a> ModifyInputsContext<'a> {
Some(NodeInput::value(TaggedValue::None, false)),
Some(NodeInput::value(TaggedValue::String(text), false)),
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.font_size), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.line_height_ratio), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.letter_spacing), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.letter_tilt), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.font_size), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.line_height_ratio), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_spacing), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_tilt), false)),
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_width.is_some()), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.max_width.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.max_width.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_height.is_some()), false)),
Some(NodeInput::value(TaggedValue::F64(typesetting.max_height.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.max_height.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
]);
let text_to_vector = resolve_proto_node_type(graphene_std::text::text_to_vector::IDENTIFIER)
@@ -526,7 +526,7 @@ impl<'a> ModifyInputsContext<'a> {
);
self.set_input_with_refresh(
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::OpacityInput),
NodeInput::value(TaggedValue::F64(opacity * 100.), false),
NodeInput::value(TaggedValue::Number(opacity * 100.), false),
false,
);
}
@@ -555,7 +555,7 @@ impl<'a> ModifyInputsContext<'a> {
);
self.set_input_with_refresh(
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::FillInput),
NodeInput::value(TaggedValue::F64(fill * 100.), false),
NodeInput::value(TaggedValue::Number(fill * 100.), false),
false,
);
}
@@ -666,7 +666,7 @@ impl<'a> ModifyInputsContext<'a> {
}
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_positions::PositionsInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(positions), false), false);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Numbers(positions), false), false);
}
/// The 'Gradient Midpoints' counterpart of [`Self::gradient_positions_set`], likewise update-only.
@@ -690,7 +690,7 @@ impl<'a> ModifyInputsContext<'a> {
}
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_midpoints::MidpointsInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(midpoints), false), false);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Numbers(midpoints), false), false);
}
/// Update the transform to map the unit gradient ((0,0), (1, 0)) to the geometry's local space.
@@ -865,7 +865,7 @@ impl<'a> ModifyInputsContext<'a> {
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput);
self.set_input_with_refresh(input_connector, NodeInput::value(color.map_or_else(TaggedValue::no_paint, TaggedValue::Color), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.weight), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeAlign(stroke.align), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::CapInput);
@@ -873,11 +873,11 @@ impl<'a> ModifyInputsContext<'a> {
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::JoinInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeJoin(stroke.join), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::MiterLimitInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.join_miter_limit), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true);
}
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
@@ -15,7 +15,7 @@ pub mod resource;
pub mod utility_types;
pub(crate) use document_diff::diff_networks;
pub(crate) use document_history::DocumentHistory;
pub(crate) use document_history::{CursorMoveError, DocumentHistory};
#[doc(inline)]
pub use document_message::{DocumentMessage, DocumentMessageDiscriminant};
#[doc(inline)]
@@ -40,17 +40,30 @@ pub struct NodePropertiesContext<'a> {
impl NodePropertiesContext<'_> {
pub fn call_widget_override(&mut self, node_id: &NodeId, index: usize) -> Option<Vec<LayoutGroup>> {
let input_properties_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
if let Some(widget_override) = &input_properties_row.widget_override {
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(widget_override) else {
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
// The stored override wins, falling back to the definition's own so documents saved before it gained one still
// pick it up. Only `Custom` is recovered, since the other kinds also need input data stored at insertion time.
let widget_override = input_properties_row.widget_override.clone().or_else(|| {
let implementation = self.network_interface.implementation(node_id, self.selection_network_path)?;
let DocumentNodeImplementation::ProtoNode(proto_node_identifier) = implementation else {
return None;
};
widget_override_lambda(*node_id, index, self)
.map_err(|error| log::error!("Error in widget override lambda: {error}"))
.ok()
} else {
None
}
let metadata = registry::NODE_METADATA.lock().unwrap();
let field = metadata.get(proto_node_identifier)?.fields.get(index)?;
match field.widget_override {
registry::RegistryWidgetOverride::Custom(name) => Some(name.to_string()),
_ => None,
}
})?;
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else {
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
return None;
};
widget_override_lambda(*node_id, index, self)
.map_err(|error| log::error!("Error in widget override lambda: {error}"))
.ok()
}
}
@@ -348,14 +361,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 2: Max (clamp subpath count to at least 1 for empty path case)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
..Default::default()
},
// 3: Floor (integer count per subpath)
// 3: As Number (the integer count enters the network's decimal math)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
inputs: vec![NodeInput::import(item!(f64), 1)],
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER),
inputs: vec![NodeInput::import(item!(i64), 1)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
..Default::default()
},
@@ -369,14 +382,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 5: Subtract (count - 1, open subpath denominator)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
..Default::default()
},
// 6: Read Index (current repetition index)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::U32(0), false)],
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
..Default::default()
},
@@ -425,7 +438,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::F64(0.9999999999), false)],
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
..Default::default()
},
@@ -459,14 +472,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// 17: Max (clamp count to at least 1)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
..Default::default()
},
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::F64(1.), false)],
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
..Default::default()
},
@@ -479,7 +492,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
}),
inputs: vec![
NodeInput::type_default(list!(Vector), true),
NodeInput::value(TaggedValue::F64(10.), false),
NodeInput::value(TaggedValue::Integer(10), false),
NodeInput::value(TaggedValue::Bool(Default::default()), false),
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
NodeInput::type_default(item!(Vector), false),
@@ -801,7 +814,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
inputs: vec![
NodeInput::import(item!(String), 0),
NodeInput::import(item!(String), 1),
NodeInput::import(item!(f64), 2),
NodeInput::import(item!(i64), 2),
NodeInput::import(item!(bool), 3),
NodeInput::import(item!(bool), 4),
],
@@ -811,14 +824,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
..Default::default()
},
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
..Default::default()
@@ -833,7 +846,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
inputs: vec![
NodeInput::value(TaggedValue::String(String::new()), true),
NodeInput::value(TaggedValue::String(String::new()), false),
NodeInput::value(TaggedValue::F64(0.), false),
NodeInput::value(TaggedValue::Integer(0), false),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::value(TaggedValue::Bool(false), false),
],
@@ -927,7 +940,6 @@ fn static_node_properties() -> NodeProperties {
map.insert("offset_path_properties".to_string(), Box::new(node_properties::offset_path_properties));
map.insert("selective_color_properties".to_string(), Box::new(node_properties::selective_color_properties));
map.insert("exposure_properties".to_string(), Box::new(node_properties::exposure_properties));
map.insert("math_properties".to_string(), Box::new(node_properties::math_properties));
map.insert("format_number_properties".to_string(), Box::new(node_properties::format_number_properties));
map.insert("string_capitalization_properties".to_string(), Box::new(node_properties::string_capitalization_properties));
map.insert("rectangle_properties".to_string(), Box::new(node_properties::rectangle_properties));
@@ -1098,6 +1110,11 @@ fn static_input_properties() -> InputProperties {
))])
}),
);
map.insert(
// A type-witness input, whose stored value's type selects the node's row: the dropdown lists the types the rows accept there
"type_choice".to_string(),
Box::new(|node_id, index, context| Ok(vec![node_properties::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
);
map.insert(
"vec2".to_string(),
Box::new(|node_id, index, context| {
@@ -1351,7 +1368,7 @@ fn static_input_properties() -> InputProperties {
let Some(input) = document_node.inputs.get(index) else {
return Err("Input not found in transform rotation input override".to_string());
};
if let Some(&TaggedValue::F64(val)) = input.as_non_exposed_value() {
if let Some(&TaggedValue::Number(val)) = input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(val))
@@ -1360,7 +1377,7 @@ fn static_input_properties() -> InputProperties {
.range_min(Some(-180.))
.range_max(Some(180.))
.on_update(node_properties::update_value_at_index(
|number_input: &NumberInput| TaggedValue::F64(number_input.value.unwrap()),
|number_input: &NumberInput| TaggedValue::Number(number_input.value.unwrap()),
node_id,
index,
))
@@ -60,6 +60,7 @@ pub enum NodeGraphMessage {
DisconnectInput {
input_connector: InputConnector,
},
DisconnectRootNode,
EnterNestedNetwork,
DuplicateSelectedNodes,
ExposeInput {
@@ -406,6 +406,9 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
NodeGraphMessage::DisconnectInput { input_connector } => {
network_interface.disconnect_input(&input_connector, selection_network_path);
}
NodeGraphMessage::DisconnectRootNode => {
network_interface.start_previewing_without_restore(selection_network_path);
}
NodeGraphMessage::DuplicateSelectedNodes => {
let all_selected_nodes = network_interface.upstream_chain_nodes(selection_network_path);
@@ -1096,8 +1099,18 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.wire_in_progress_to_connector = Some(point);
// Disconnect if the wire was previously connected to an input
if let Some(disconnecting) = &self.disconnecting {
// Previewing leaves the export alone, so dragging its wire off is an ordinary disconnect
responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting });
let mut disconnect_root_node = false;
if let Previewing::Yes { root_node_to_restore } = network_interface.previewing(selection_network_path)
&& root_node_to_restore.is_some()
&& *disconnecting == InputConnector::Export(0)
{
disconnect_root_node = true;
}
if disconnect_root_node {
responses.add(NodeGraphMessage::DisconnectRootNode);
} else {
responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting });
}
// Update the frontend that the node is disconnected
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SendGraph);
@@ -2678,8 +2691,8 @@ impl NodeGraphMessageHandler {
wire_path_update: None,
}));
if let Some(wire_to_preview) = network_interface.wire_to_preview(graph_wire_style, breadcrumb_network_path) {
added_wires.push(wire_to_preview);
if let Some(wire_to_root) = network_interface.wire_to_root(graph_wire_style, breadcrumb_network_path) {
added_wires.push(wire_to_root);
} else {
added_wires.push(WirePathUpdate {
id: NodeId(u64::MAX),
@@ -2730,8 +2743,11 @@ impl NodeGraphMessageHandler {
log::error!("Could not get position for node: {node_id}");
continue;
};
// Asked of the preview itself rather than inferred from the export, which previewing no longer rewires
let previewed = matches!(network_interface.previewing(breadcrumb_network_path), Previewing::Yes { previewed } if previewed.node_id == node_id);
let is_export = network_interface
.input_from_connector(&InputConnector::Export(0), breadcrumb_network_path)
.is_some_and(|export| export.as_node().is_some_and(|export_node_id| node_id == export_node_id));
let is_root_node = network_interface.root_node(breadcrumb_network_path).is_some_and(|root_node| root_node.node_id == node_id);
let previewed = is_export && !is_root_node;
let locked = network_interface.is_locked(&node_id, breadcrumb_network_path);
@@ -24,7 +24,7 @@ use graphene_std::raster::{
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RedGreenBlueAlpha,
RelativeAbsolute, SelectiveColorChoice, TonalRange,
};
use graphene_std::raster_types::Image;
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
use graphene_std::text::{Font, TextAlign};
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
@@ -38,6 +38,7 @@ use graphene_std::vector::style::{
build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, Graphic, Vector};
use graphene_std::{NodeParameter, ParameterRef};
use std::path::PathBuf;
@@ -170,14 +171,19 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
widgets
}
/// The numeric bounds and widget mode of a number parameter, sourced from the node's field metadata.
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
#[derive(Clone, Copy, Default)]
pub(crate) struct NumberOptions {
pub(crate) struct ParameterOptions {
pub soft_min: Option<f64>,
pub soft_max: Option<f64>,
pub hard_min: Option<f64>,
pub hard_max: Option<f64>,
pub slider: bool,
pub multiline: bool,
pub progression: bool,
pub unit: Option<&'static str>,
pub display_decimal_places: Option<u32>,
pub step: Option<f64>,
}
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
@@ -206,29 +212,25 @@ fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> O
let input = resolve_document_node_type(&identifier)?.node_template.inputs.get(parameter_widgets_info.index)?;
match input.as_value()? {
TaggedValue::F64(value) => Some(*value),
TaggedValue::F32(value) => Some(*value as f64),
TaggedValue::Number(value) => Some(*value),
_ => None,
}
}
pub(crate) fn property_from_type(
node_id: NodeId,
index: usize,
ty: &Type,
number_options: NumberOptions,
unit: Option<&str>,
display_decimal_places: Option<u32>,
step: Option<f64>,
context: &mut NodePropertiesContext,
) -> Result<Vec<LayoutGroup>, Vec<LayoutGroup>> {
let NumberOptions {
pub(crate) fn property_from_type(node_id: NodeId, index: usize, ty: &Type, options: ParameterOptions, context: &mut NodePropertiesContext) -> Result<Vec<LayoutGroup>, Vec<LayoutGroup>> {
let ParameterOptions {
soft_min,
soft_max,
hard_min,
hard_max,
slider,
} = number_options;
multiline,
progression,
unit,
display_decimal_places,
step,
} = options;
let mut number_input = NumberInput::default();
if slider {
number_input = number_input.mode_range();
@@ -243,10 +245,8 @@ pub(crate) fn property_from_type(
number_input = number_input.step(step);
}
// Applies the parameter's typing clamp and slider extent to the widget, given the type's own default bounds.
// Per end: the clamp is the hard bound (or unbounded if only a soft bound is given, since soft is a suggested
// extent rather than a limit), and the slider extent is the soft bound, each falling back to the hard bound
// and then to the type default when unspecified. An end with any explicit bound ignores the type default.
// The hard bound sets the typing clamp, and the soft bound (or the hard one) the slider extent, each falling
// back to the passed-in default. A soft bound alone leaves that end unclamped, since soft is only a suggestion.
let bounded = |number_input: NumberInput, type_min: f64, type_max: f64| {
let clamp_min = hard_min.unwrap_or(if soft_min.is_some() { f64::NEG_INFINITY } else { type_min });
let clamp_max = hard_max.unwrap_or(if soft_max.is_some() { f64::INFINITY } else { type_max });
@@ -260,12 +260,11 @@ pub(crate) fn property_from_type(
.range_max(Some(extent_max).filter(|bound| bound.is_finite()))
};
// A range-mode number clamped at both ends by its own hard bounds, or by a type whose extent is a true limit, becomes a range
// slider beside its number input, unless a soft bound lets typing pass the slider. An Angle's type default is no such limit.
// A range-mode number hard-clamped at both ends becomes a range slider beside its number input, unless a soft bound lets typing pass it
let no_soft_bounds = soft_min.is_none() && soft_max.is_none();
let hard_both_ends = hard_min.is_some() && hard_max.is_some();
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput, type_limits: bool| -> LayoutGroup {
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && (hard_both_ends || type_limits);
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput| -> LayoutGroup {
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && hard_both_ends;
match (number_input.min, number_input.max) {
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
let default = definition_default_number(&default_info);
@@ -298,112 +297,98 @@ pub(crate) fn property_from_type(
let mut extra_widgets = vec![];
let widgets = match ty {
Type::Concrete(concrete_type) => {
match concrete_type.alias.as_ref().map(|x| x.as_ref()) {
// Aliased types (ambiguous values)
Some("Percentage") | Some("PercentageF32") => number_or_slider(default_info, bounded(number_input.percentage(), 0., 100.), true),
Some("SignedPercentage") | Some("SignedPercentageF32") => number_or_slider(default_info, bounded(number_input.percentage(), -100., 100.), true),
Some("Angle") | Some("AngleF32") => number_or_slider(default_info, bounded(number_input.mode_range(), -180., 180.).unit(unit.unwrap_or("°")), false),
Some("Multiplier") => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY).unit(unit.unwrap_or("x"))).into(),
Some("PixelLength") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY).unit(unit.unwrap_or(" px"))).into(),
Some("Length") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
Some("Fraction") => number_or_slider(default_info, bounded(number_input.mode_range(), 0., 1.), true),
Some("Progression") => progression_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
Some("SignedInteger") => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
Some("SeedValue") => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
Some("PixelSize") => vec2_widget(default_info, "X", "Y", unit.unwrap_or(" px"), None, false),
Some("TextArea") => text_area_widget(default_info).into(),
use std::any::TypeId;
// For all other types, use TypeId-based matching
_ => {
use std::any::TypeId;
// The compiler peels a rank-0 `Item` cell to its element before this arm runs, so widgets dispatch on the bare element `T`
fn id_is<T: 'static>(id: TypeId) -> bool {
id == TypeId::of::<T>()
}
// The compiler peels a rank-0 `Item` cell to its element before this arm runs, so widgets dispatch on the bare element `T`
fn id_is<T: 'static>(id: TypeId) -> bool {
id == TypeId::of::<T>()
}
match concrete_type.id {
// ===============
// PRIMITIVE TYPES
// ===============
Some(x) if id_is::<f64>(x) || id_is::<f32>(x) => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY), false),
Some(x) if id_is::<u32>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::from(u32::MAX))).into(),
Some(x) if id_is::<u64>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if id_is::<String>(x) => text_widget(default_info).into(),
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", "", None, false),
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
// ============
// STRUCT TYPES
// ============
Some(x) if id_is::<Font>(x) => font_widget(default_info),
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
// ===============================
// MANUALLY IMPLEMENTED ENUM TYPES
// ===============================
Some(x) if id_is::<ReferencePoint>(x) => reference_point_widget(default_info, false).into(),
Some(x) if id_is::<BlendMode>(x) => blend_mode_widget(default_info),
// =========================
// AUTO-GENERATED ENUM TYPES
// =========================
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientInterpolation>(x) => enum_choice::<GradientInterpolation>().for_socket(default_info).property_row(),
Some(x) if id_is::<RealTimeMode>(x) => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlue>(x) => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlueAlpha>(x) => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
Some(x) if id_is::<XY>(x) => enum_choice::<XY>().for_socket(default_info).property_row(),
Some(x) if id_is::<StringCapitalization>(x) => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
Some(x) if id_is::<TextDenomination>(x) => enum_choice::<TextDenomination>().for_socket(default_info).property_row(),
Some(x) if id_is::<NoiseType>(x) => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
Some(x) if id_is::<FractalType>(x) => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<TonalRange>(x) => enum_choice::<TonalRange>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<AdjustmentChannel>(x) => enum_choice::<AdjustmentChannel>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<HueSaturationRange>(x) => enum_choice::<HueSaturationRange>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<GridType>(x) => enum_choice::<GridType>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).property_row(),
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
Some(x) if id_is::<MergeByDistanceAlgorithm>(x) => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
Some(x) if id_is::<ExtrudeJoiningAlgorithm>(x) => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
Some(x) if id_is::<PointSpacingType>(x) => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).property_row(),
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
// =====
// OTHER
// =====
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
}
}
match concrete_type.id {
// ===============
// PRIMITIVE TYPES
// ===============
Some(x) if id_is::<f64>(x) => match progression {
true => progression_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
false => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
},
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if id_is::<String>(x) => match multiline {
true => text_area_widget(default_info).into(),
false => text_widget(default_info).into(),
},
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false),
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
// ============
// STRUCT TYPES
// ============
Some(x) if id_is::<Font>(x) => font_widget(default_info),
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
// ===============================
// MANUALLY IMPLEMENTED ENUM TYPES
// ===============================
Some(x) if id_is::<ReferencePoint>(x) => reference_point_widget(default_info, false).into(),
Some(x) if id_is::<BlendMode>(x) => blend_mode_widget(default_info),
// =========================
// AUTO-GENERATED ENUM TYPES
// =========================
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).property_row(),
Some(x) if id_is::<GradientInterpolation>(x) => enum_choice::<GradientInterpolation>().for_socket(default_info).property_row(),
Some(x) if id_is::<RealTimeMode>(x) => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlue>(x) => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlueAlpha>(x) => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
Some(x) if id_is::<XY>(x) => enum_choice::<XY>().for_socket(default_info).property_row(),
Some(x) if id_is::<StringCapitalization>(x) => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
Some(x) if id_is::<TextDenomination>(x) => enum_choice::<TextDenomination>().for_socket(default_info).property_row(),
Some(x) if id_is::<NoiseType>(x) => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
Some(x) if id_is::<FractalType>(x) => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<TonalRange>(x) => enum_choice::<TonalRange>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<AdjustmentChannel>(x) => enum_choice::<AdjustmentChannel>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<HueSaturationRange>(x) => enum_choice::<HueSaturationRange>().for_socket(default_info).disabled(false).property_row(),
Some(x) if id_is::<GridType>(x) => enum_choice::<GridType>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).property_row(),
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
Some(x) if id_is::<MergeByDistanceAlgorithm>(x) => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
Some(x) if id_is::<ExtrudeJoiningAlgorithm>(x) => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
Some(x) if id_is::<PointSpacingType>(x) => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).property_row(),
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
// =====
// OTHER
// =====
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
}
}
Type::Item(element) => return property_from_type(node_id, index, element, number_options, unit, display_decimal_places, step, context),
Type::Item(element) => return property_from_type(node_id, index, element, options, context),
Type::List(element) => match element.as_ref() {
Type::Concrete(element_type) if element_type.name == std::any::type_name::<f64>() => array_of_number_widget(default_info, TextInput::default()).into(),
_ => return Err(unsupported_widgets(default_info, ty.to_string())),
},
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
Type::Fn(_, out) => return property_from_type(node_id, index, out, options, context),
Type::Future(out) => return property_from_type(node_id, index, out, options, context),
};
extra_widgets.push(widgets);
@@ -807,7 +792,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.widget_instance(),
]);
}
Some(&TaggedValue::F64(value)) => {
Some(&TaggedValue::Number(value)) => {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(value))
@@ -846,14 +831,14 @@ pub fn array_of_number_widget(parameter_widgets_info: ParameterWidgetsInfo, text
.filter(|x| !x.is_empty())
.map(graphene_std::core_types::misc::parse_f64)
.collect::<Option<Vec<_>>>()
.map(TaggedValue::F64Array)
.map(TaggedValue::Numbers)
};
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
if let Some(TaggedValue::F64Array(values)) = &input.as_non_exposed_value() {
if let Some(TaggedValue::Numbers(values)) = &input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
text_input
@@ -1008,7 +993,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
if let Some(&TaggedValue::F64(x)) = input.as_non_exposed_value() {
if let Some(&TaggedValue::Number(x)) = input.as_non_exposed_value() {
let whole_part = x.trunc();
let fractional_part = x.fract();
@@ -1021,7 +1006,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
.min(0.)
.max(0.99999)
.value(Some(fractional_part))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::F64(whole_part + input.value.unwrap())))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::Number(whole_part + input.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
@@ -1033,7 +1018,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
.min(0.)
.is_integer(true)
.value(Some(whole_part))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::F64(input.value.unwrap() + fractional_part)))
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::Number(input.value.unwrap() + fractional_part)))
.on_commit(commit_value)
.widget_instance(),
])
@@ -1120,35 +1105,19 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
return vec![];
};
match input.as_non_exposed_value() {
Some(&TaggedValue::F64(x)) => widgets.extend_from_slice(&[
Some(&TaggedValue::Number(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap())))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Number(x.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
]),
Some(&TaggedValue::F32(x)) => widgets.extend_from_slice(&[
Some(&TaggedValue::Integer(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x as f64))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F32(x.value.unwrap() as f32)))
.on_commit(commit_value)
.widget_instance(),
]),
Some(&TaggedValue::U32(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x as f64))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::U32((x.value.unwrap()) as u32)))
.on_commit(commit_value)
.widget_instance(),
]),
Some(&TaggedValue::U64(x)) => widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(x as f64))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::U64((x.value.unwrap()) as u64)))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Integer(x.value.unwrap().round() as i64)))
.on_commit(commit_value)
.widget_instance(),
]),
@@ -1157,7 +1126,7 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
number_props
// We use an arbitrary `y` instead of an arbitrary `x` here because the "Grid" node's "Spacing" value's height should be used from rectangular mode when transferred to "Y Spacing" in isometric mode
.value(Some(dvec2.y))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap())))
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Number(x.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
]),
@@ -1201,6 +1170,96 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
}
/// A dropdown choosing among the types this input takes across the node's registered rows. The input is a type witness:
/// its stored value's type, not the value itself, selects the row, which is how a node offers a choice of output type.
pub fn type_choice_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(current) = parameter_widgets_info.input().and_then(|input| input.as_non_exposed_value()) else {
return LayoutGroup::row(widgets);
};
// Every element type the node's rows accept at this input
let mut offered: Vec<Type> = Vec::new();
let implementation = parameter_widgets_info
.network_interface
.implementation(&parameter_widgets_info.node_id, parameter_widgets_info.selection_network_path);
if let Some(DocumentNodeImplementation::ProtoNode(identifier)) = implementation
&& let Some(rows) = interpreted_executor::node_registry::NODE_REGISTRY.get(identifier)
{
for row in rows.keys() {
let Some(ty) = row.inputs.get(parameter_widgets_info.index) else { continue };
let element = wire_element(ty);
if !offered.contains(&element) {
offered.push(element);
}
}
}
let sections = type_choice_sections(&offered);
let entry_sections = sections
.iter()
.map(|section| {
section
.iter()
.map(|ty| {
let chosen = TaggedValue::from_type_or_none(ty);
MenuListEntry::new(ty.to_string())
.label(ty.to_string())
.on_update(parameter_widgets_info.update_value(move |_| chosen.clone()))
.on_commit(commit_value)
})
.collect()
})
.collect();
// The dropdown counts its selection across every section, since separators divide the entries without renumbering them
let current_element = wire_element(&current.ty());
let selected = sections.iter().flatten().position(|ty| *ty == current_element).map(|position| position as u32);
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(entry_sections).selected_index(selected).widget_instance(),
]);
LayoutGroup::row(widgets)
}
/// The element a wire type carries, peeling the `Item` or `List` rank a registry row or stored value wraps it in.
fn wire_element(ty: &Type) -> Type {
match ty.nested_type() {
Type::Item(element) | Type::List(element) => (**element).clone(),
other => other.clone(),
}
}
/// The canonical order and grouping of the graph's types, which a type choice renders as dropdown sections divided by separators.
/// Enums stay unlisted on purpose, joining any other unnamed type in a trailing alphabetical section.
fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
let vocabulary = [
vec![concrete!(bool), concrete!(i64), concrete!(f64)],
vec![concrete!(DVec2)],
vec![concrete!(DAffine2)],
vec![concrete!(Artboard)],
vec![
concrete!(Graphic),
concrete!(Vector),
concrete!(Raster<CPU>),
concrete!(Raster<GPU>),
concrete!(Color),
concrete!(Gradient),
concrete!(String),
],
];
let mut sections: Vec<Vec<Type>> = vocabulary.iter().map(|section| section.iter().filter(|ty| offered.contains(ty)).cloned().collect()).collect();
let mut unlisted: Vec<Type> = offered.iter().filter(|ty| !vocabulary.iter().any(|section| section.contains(ty))).cloned().collect();
unlisted.sort_by_key(|ty| ty.to_string());
sections.push(unlisted);
sections.retain(|section| !section.is_empty());
sections
}
pub fn color_widget(parameter_widgets_info: ParameterWidgetsInfo, color_button: ColorInput) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
@@ -1719,7 +1778,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
let exposed = input.is_some_and(|input| input.is_exposed());
let value = input
.and_then(|input| input.as_value())
.and_then(|tagged| if let TaggedValue::F32(value) = tagged { Some(*value as f64) } else { None })
.and_then(|tagged| if let TaggedValue::Number(value) = tagged { Some(*value) } else { None })
.unwrap_or(0.);
(exposed, value)
})
@@ -1842,7 +1901,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
NodeGraphMessage::SetInputValue {
node_id,
input_index,
value: TaggedValue::F32(scale.value(scale_position) as f32).into(),
value: TaggedValue::Number(scale.value(scale_position)).into(),
}
.into()
}
@@ -1878,11 +1937,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
.value(Some(current))
.min_width(60)
.max_width(60)
.on_update(update_value_at_index(
move |widget: &NumberInput| TaggedValue::F32(widget.value.unwrap_or(0.) as f32),
node_id,
input_index,
))
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::Number(widget.value.unwrap_or(0.)), node_id, input_index))
.on_commit(commit_value)
.widget_instance(),
);
@@ -1906,8 +1961,8 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
Some(TaggedValue::HueSaturationRange(range)) => *range,
_ => HueSaturationRange::Master,
};
let f32_value = |parameter: &ParameterRef| match document_node.inputs.get(parameter.input_index).and_then(|input| input.as_value()) {
Some(TaggedValue::F32(value)) => *value,
let slider_value = |parameter: &ParameterRef| match document_node.inputs.get(parameter.input_index).and_then(|input| input.as_value()) {
Some(TaggedValue::Number(value)) => *value as f32,
_ => 0.,
};
@@ -1975,9 +2030,9 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
Gradient::from((0..=stops).map(stop).collect::<Vec<_>>())
};
let saturation_track = if colorize_value {
toward_hue(f32_value(&hue) / 360.)
toward_hue(slider_value(&hue) / 360.)
} else if let Some([_, range_start, range_end, _]) = &range_values {
let (start, end) = (f32_value(range_start), f32_value(range_end));
let (start, end) = (slider_value(range_start), slider_value(range_end));
let center = start + (end - start).rem_euclid(360.) / 2.;
toward_hue(center / 360.)
} else {
@@ -2121,8 +2176,7 @@ fn slider_row(
};
// An exposed input shows only its label and source
let (current, tagged_value): (f64, fn(f64) -> TaggedValue) = match input.as_non_exposed_value() {
Some(&TaggedValue::F64(value)) => (value, TaggedValue::F64),
Some(&TaggedValue::F32(value)) => (value as f64, |value| TaggedValue::F32(value as f32)),
Some(&TaggedValue::Number(value)) => (value, TaggedValue::Number),
_ => return widgets,
};
let ParameterWidgetsInfo { node_id, index, .. } = parameter_widgets_info;
@@ -2184,7 +2238,7 @@ fn gradient_slider_row(
.ok()
.and_then(|document_node| document_node.inputs.get(input_index))
.and_then(|input| input.as_non_exposed_value())
.and_then(|tagged| if let TaggedValue::F32(value) = tagged { Some(*value as f64) } else { None });
.and_then(|tagged| if let TaggedValue::Number(value) = tagged { Some(*value) } else { None });
// Only add the slider and number widgets when the input is not exposed
if let Some(current) = current {
@@ -2193,7 +2247,7 @@ fn gradient_slider_row(
max: value_max,
default: Some(default_value),
};
let value_at = move |position| TaggedValue::F32(slider.value(position) as f32);
let value_at = move |position| TaggedValue::Number(slider.value(position));
row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
row.push(
@@ -2216,11 +2270,7 @@ fn gradient_slider_row(
.min_width(60)
.max_width(60)
.display_decimal_places(0)
.on_update(update_value_at_index(
move |widget: &NumberInput| TaggedValue::F32(widget.value.unwrap_or(0.) as f32),
node_id,
input_index,
))
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::Number(widget.value.unwrap_or(0.)), node_id, input_index))
.on_commit(commit_value)
.widget_instance(),
);
@@ -2642,7 +2692,7 @@ pub(crate) fn format_number_properties(node_id: NodeId, context: &mut NodeProper
let (no_decimals, decimal_sep_value, use_thousands, thousands_sep_value) = match get_document_node(node_id, context) {
Ok(document_node) => {
let decimal_places = match document_node.input(DecimalPlacesInput).and_then(|input| input.as_value()) {
Some(&TaggedValue::U32(x)) => x,
Some(&TaggedValue::Integer(x)) => x,
_ => 2,
};
let decimal_sep = match document_node.input(DecimalSeparatorInput).and_then(|input| input.as_non_exposed_value()) {
@@ -2966,10 +3016,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
return Vec::new();
};
let mut number_options = NumberOptions::default();
let mut display_decimal_places = None;
let mut step = None;
let mut unit_suffix = None;
let mut options = ParameterOptions::default();
let input_type = match implementation {
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
@@ -2982,16 +3029,18 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
.get(&proto_node_identifier)
.and_then(|metadata| metadata.fields.get(input_index))
{
number_options = NumberOptions {
options = ParameterOptions {
soft_min: field.number_soft_min,
soft_max: field.number_soft_max,
hard_min: field.number_hard_min,
hard_max: field.number_hard_max,
slider: field.number_mode_range,
multiline: field.multiline,
progression: field.progression,
unit: field.unit,
display_decimal_places: field.number_display_decimal_places,
step: field.number_step,
};
display_decimal_places = field.number_display_decimal_places;
unit_suffix = field.unit;
step = field.number_step;
default_type = field.default_type.clone();
}
@@ -3019,7 +3068,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
.unwrap_or(concrete!(())),
};
property_from_type(node_id, input_index, &input_type, number_options, unit_suffix, display_decimal_places, step, context).unwrap_or_else(|value| value)
property_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
});
layout.extend(row);
@@ -3404,63 +3453,6 @@ pub fn offset_path_properties(node_id: NodeId, context: &mut NodePropertiesConte
vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)]
}
pub fn math_properties(node_id: NodeId, context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
use graphene_std::math_nodes::math::*;
let expression = (|| {
let mut widgets = start_widgets(&ParameterWidgetsInfo::new(node_id, ExpressionInput, true, context));
let document_node = match get_document_node(node_id, context) {
Ok(document_node) => document_node,
Err(err) => {
log::error!("Could not get document node in offset_path_properties: {err}");
return Vec::new();
}
};
let Some(input) = document_node.input(ExpressionInput) else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
if let Some(TaggedValue::String(x)) = &input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextInput::new(x.clone())
.centered(true)
.on_update(update_value(
|x: &TextInput| {
TaggedValue::String({
let mut expression = x.value.trim().to_string();
if ["+", "-", "*", "/", "^"].iter().any(|&infix| infix == expression) {
expression = format!("A {expression} B");
} else if expression == "^" {
expression = String::from("A^B");
} else if expression == "%" || expression == "mod" {
expression = String::from("mod(a, b)");
}
expression
})
},
node_id,
ExpressionInput,
))
.on_commit(commit_value)
.widget_instance(),
])
}
widgets
})();
let operand_b = number_widget(ParameterWidgetsInfo::new(node_id, OperandBInput, true, context), NumberInput::default());
let operand_a_hint = vec![TextLabel::new("(Operand A is the primary input)").widget_instance()];
vec![
LayoutGroup::row(expression).with_tooltip_description(r#"A math expression that may incorporate "A" and/or "B", such as "sqrt(A + B) - B^2"."#),
LayoutGroup::row(operand_b).with_tooltip_description(r#"The value of "B" when calculating the expression."#),
LayoutGroup::row(operand_a_hint).with_tooltip_description(r#""A" is fed by the value from the previous node in the primary data flow, or it is 0 if disconnected."#),
]
}
pub struct ParameterWidgetsInfo<'a> {
document_id: DocumentId,
network_interface: &'a NodeNetworkInterface,
@@ -3699,3 +3691,23 @@ pub mod choice {
pub struct ForValue<W>(PhantomData<W>);
}
#[cfg(test)]
mod tests {
use super::*;
use graph_craft::{item, list};
#[test]
fn wire_element_reads_every_spelling_down_to_the_element() {
// A stored value's ranked type, a registry row's fn type, and a mapped row's list all carry the same element
let row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(item!(f64)))));
let mapped_row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(list!(f64)))));
for ty in [TaggedValue::Number(0.).ty(), item!(f64), list!(f64), row, mapped_row] {
assert_eq!(wire_element(&ty), concrete!(f64), "{ty:?} should read down to its element");
}
// The element of a stored value and of the row that accepts it agree, which is what selects the dropdown entry
assert_eq!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(i64)));
assert_ne!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(f64)));
}
}
@@ -33,7 +33,7 @@ impl FrontendGraphDataType {
"Color" => Self::Color,
"Gradient" => Self::Gradient,
"String" => Self::Typography,
"f64" | "f32" | "u32" | "u64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
raster if raster.starts_with("Raster") => Self::Raster,
_ => Self::General,
}
@@ -208,3 +208,17 @@ pub enum Direction {
Left,
Right,
}
/// Another peer's pointer over the node graph, in viewport pixels, with how to label it.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FrontendRemoteCursor {
pub x: f64,
pub y: f64,
pub name: String,
/// A stand-in name for someone who gave none, shown in italics.
pub anonymous: bool,
pub color: String,
/// The icon name of the tool the peer holds, if it told.
pub tool: Option<String>,
}
@@ -28,7 +28,7 @@ fn editor_metadata_round_trip_against_demo() {
let network = interface.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &source, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations().expect("rebuild declarations");
let declarations = conversion.declarations;
let registry = conversion.registry;
let (_converted_network, entries) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime_with_metadata failed");
@@ -137,7 +137,7 @@ fn editor_interface_rebuild_round_trip() {
let network = original.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &original_view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations().expect("rebuild declarations");
let declarations = conversion.declarations;
let registry = conversion.registry;
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
@@ -256,7 +256,7 @@ fn rebuilt_interface_keeps_storage_identities() {
let network = document.network_interface.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations().expect("rebuild declarations");
let declarations = conversion.declarations;
let registry = conversion.registry;
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
@@ -272,10 +272,7 @@ fn rebuilt_interface_keeps_storage_identities() {
assert_eq!(reconverted_ids, stored_ids, "re-converting the rebuilt interface under a different peer changed the node identities");
}
/// Opening an old document runs its upgrades through the ordinary mutators, so the store records them.
/// Those recordings are the document arriving rather than edits to it, so the migration has to leave
/// the buffer empty instead of handing the first commit a pile of changes to the document's own
/// starting state.
/// Migrating an opened document must leave the recorded-delta buffer empty.
#[test]
fn migrating_a_document_records_no_changes() {
let mut document = load_demo("painted-dreams.graphite");
@@ -308,7 +305,7 @@ fn pinned_order_round_trips_through_the_registry() {
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations().expect("rebuild declarations");
let declarations = conversion.declarations;
let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime failed");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
@@ -4,11 +4,13 @@
//! MessagePack codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
//! `verify_storage_round_trip` only checks in-process without an actual save/reopen.
use crate::messages::resource_storage::ResourcesHandle;
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NodeMetadataSource, PeerId};
use document_graph_storage::{NodeMetadataSource, PeerId, UserId};
use graph_craft::application_io::resource::HashMapResourceStorage;
use std::sync::Arc;
use super::test_support::{RoundTrip, node_paths, round_trip_through_gdd};
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
@@ -156,9 +158,9 @@ async fn edit_after_open_commits_cleanly() {
// Persist the document into a fresh Gdd and reopen it, then build a runtime document from the
// reopened registry: the editor's .gdd-open path.
let byte_store = HashMapResourceStorage::new();
let byte_store = ResourcesHandle::new(Arc::new(HashMapResourceStorage::new()));
let source = editor.active_document();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let source_network = source.network_interface.document_network().clone();
@@ -176,7 +178,7 @@ async fn edit_after_open_commits_cleanly() {
{
let document = editor.active_document_mut();
document.network_interface = rebuilt;
document.set_storage(Some(reopened));
document.set_storage(reopened, declarations, byte_store.storage());
document.finalize_storage_load();
}
@@ -210,7 +212,7 @@ async fn edit_after_open_commits_cleanly() {
#[tokio::test]
async fn gdd_undo_redo_walks_interactions() {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
@@ -263,7 +265,7 @@ async fn gdd_undo_redo_walks_interactions() {
#[tokio::test]
async fn reopen_after_undo_restores_consistent_registry() {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
@@ -387,7 +389,7 @@ async fn gdd_archive_round_trips_view_settings() {
use document_graph_storage::attr::session::doc;
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
@@ -437,7 +439,7 @@ async fn per_network_navigation_round_trips_via_session_not_registry() {
let expected_pan = editor.active_document().network_interface.node_graph_ptz(&[]).unwrap().pan;
// Commit the document into a fresh `Gdd`, collecting the per-network view state the editor persists.
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
let document = editor.active_document();
@@ -674,12 +676,13 @@ fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
/// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real
/// autosave path) runs against it. Returns the byte store the document's resources resolve through.
async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourceStorage {
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0x5EED, "test".into(), "test".into())
async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> ResourcesHandle {
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0x5EED, "test".into(), "test".into())
.await
.expect("create_in");
editor.active_document_mut().set_storage(Some(gdd));
HashMapResourceStorage::new()
let byte_store = ResourcesHandle::new(Arc::new(HashMapResourceStorage::new()));
editor.active_document_mut().set_storage(gdd, Default::default(), byte_store.storage());
byte_store
}
/// Open a real demo artwork, mount storage, edit it, and trigger autosave. The autosave runs
@@ -713,8 +716,10 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
let after_edit = editor.active_document().network_interface.document_network().clone();
assert_ne!(before_edit, after_edit, "drawing a rectangle should change the document network");
// Second autosave: again verifies the round-trip, and the edit must produce new retired history.
// Second autosave: again verifies the round-trip, and the edit, once its transaction is closed and
// retired, must produce new retired history. Retirement follows a policy rather than the commit.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().retire_storage_interaction();
let history_after_edit = editor.active_document().storage().unwrap().session().history().count();
assert!(
history_after_edit > history_after_open,
@@ -897,3 +902,42 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
"the transform input should shift down intact, but became {transform:?}"
);
}
/// Undoing a step that is still hot takes it back rather than moving the cursor: the hot log empties,
/// history gains nothing, and the interface follows the registry. Redo stages the same ops afresh.
#[tokio::test]
async fn undoing_a_hot_step_takes_it_back_and_redo_stages_it_again() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor).await;
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().retire_storage_interaction();
let history_base = editor.active_document().storage().unwrap().session().history().count();
let before_edit = editor.active_document().network_interface.document_network().clone();
editor.draw_rect(64., 64., 192., 192.).await;
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let after_edit = editor.active_document().network_interface.document_network().clone();
assert_ne!(after_edit, before_edit);
assert!(!editor.active_document().storage().unwrap().session().hot_log().is_empty(), "the step is hot");
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(editor.active_document().network_interface.document_network(), &before_edit, "undo restores the pre-edit network");
let storage = editor.active_document().storage().unwrap();
assert!(storage.session().hot_log().is_empty(), "the step was taken back, not retired: {:?}", storage.session().hot_log());
assert_eq!(storage.session().history().count(), history_base, "nothing entered history");
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
// The step's declaration bytes are named by nothing in storage now, so garbage collection would drop
// them and a redo could not be served to peers; the step held for redo keeps them alive.
assert!(
editor.active_document().retracted_resource_hashes().next().is_some(),
"the retracted step names its declaration resource"
);
editor.handle_message(DocumentMessage::Redo).await;
assert_eq!(editor.active_document().network_interface.document_network(), &after_edit, "redo restores the edit");
let storage = editor.active_document().storage().unwrap();
assert!(!storage.session().hot_log().is_empty(), "the redone step is staged afresh");
assert_eq!(storage.session().history().count(), history_base);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
}
@@ -5,7 +5,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::PeerId;
use document_graph_storage::{PeerId, UserId};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNodeImplementation, NodeId};
@@ -56,7 +56,7 @@ pub struct RoundTrip {
pub async fn round_trip_through_gdd(document: &DocumentMessageHandler) -> RoundTrip {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into())
.await
.expect("create_in");
@@ -14,6 +14,7 @@ mod layout;
mod memo_network;
mod mutations;
mod queries;
mod reconcile;
mod resolved_types;
pub mod storage_metadata;
mod store;
@@ -25,6 +26,7 @@ mod validation;
mod view;
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
pub use reconcile::{ReconcileError, Reconciled};
use store::Guarded;
pub use store::NodeLocator;
pub use template::*;
@@ -1,11 +1,6 @@
use super::*;
use graph_craft::runtime_delta::RuntimeDelta;
// Replay: putting a delta back into the interface, the inverse of the store recording one.
//
// Mechanism only. A mutator decides policy, validates, and lays nodes out, then records what it
// settled on; replaying reproduces that outcome rather than deciding it again. A peer running
// different layout rules must still end up with the state the delta describes.
impl NodeNetworkInterface {
/// Mirrors a delta into the interface without recording it.
///
@@ -13,7 +8,6 @@ impl NodeNetworkInterface {
/// never made back to whoever sent it. Writing through the store and then dropping what the store
/// recorded keeps the two parallel trees written by one place, which is the property the store
/// exists for, without the echo.
#[cfg_attr(not(test), expect(dead_code, reason = "no caller until deltas from another peer are replayed; the replay tests exercise it"))]
pub(crate) fn apply(&mut self, delta: &EditorDelta) {
let recorded = self.deltas.len();
self.mirror(delta);
@@ -23,8 +17,7 @@ impl NodeNetworkInterface {
fn mirror(&mut self, delta: &EditorDelta) {
match delta {
// The metadata arrives separately, so a node lands with default metadata that the paired
// snapshot then fills in. Replacing an entry and adding one are the same write here; they
// differ only in what the storage side has to remove first.
// snapshot then fills in
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, node }) | EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
let template = NodeTemplate::from_parts((**node).clone(), DocumentNodePersistentMetadata::default());
self.insert_node_entry(NodeLocator::new(*node_id, network_path), template);
@@ -30,11 +30,10 @@ impl NodeNetworkInterface {
self.unload_stack_dependents(network_path);
let Some(history) = self.selection_history_mut(network_path) else {
log::error!("Could not get nested network_metadata in selected_nodes");
log::error!("Could not get nested network_metadata in selected_nodes_mut");
return None;
};
// Initialize default value if selection_undo_history is empty
if history.undo.is_empty() {
history.undo.push_back(SelectedNodes::default());
}
@@ -81,7 +80,7 @@ impl NodeNetworkInterface {
pub(crate) fn try_load_stack_dependents(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in stack_dependents");
log::error!("Could not get nested network_metadata in try_load_stack_dependents");
return;
};
@@ -101,7 +100,7 @@ impl NodeNetworkInterface {
return None;
};
let Some(stack_dependents) = transient.stack_dependents.get_loaded_mut() else {
log::error!("could not load stack_dependents");
log::error!("Could not load stack dependents in try_get_stack_dependents");
return None;
};
Some(stack_dependents)
@@ -148,7 +147,7 @@ impl NodeNetworkInterface {
.get(&OutputConnector::primary_output(current_node))
.map(|layer_outward_wires| layer_outward_wires.first().copied())
}) else {
log::error!("Cannot load outward wires in load_stack_dependents");
log::error!("Cannot load outward wires in load_stack_dependents_for_nodes");
return;
};
let Some(first_downstream_input) = first_downstream_input else {
@@ -188,7 +187,7 @@ impl NodeNetworkInterface {
new_owned_nodes.insert(*layer_sole_dependent);
}
let Some(layer_node) = self.node_metadata(&upstream_layer, network_path) else {
log::error!("Could not get layer node in load_stack_dependents");
log::error!("Could not get layer node in load_stack_dependents_for_nodes");
continue;
};
layer_node.transient_metadata.owned_nodes.store(new_owned_nodes);
@@ -232,7 +231,7 @@ impl NodeNetworkInterface {
}
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get current network in load_stack_dependents");
log::error!("Could not get current network in load_stack_dependents_for_nodes");
return;
};
@@ -277,11 +276,11 @@ impl NodeNetworkInterface {
self.load_import_export_ports(network_path);
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in export_ports");
log::error!("Could not get nested network_metadata in import_export_ports");
return None;
};
let Some(ports) = transient.import_export_ports.get_loaded_mut() else {
log::error!("could not load import ports");
log::error!("Could not load import export ports in import_export_ports");
return None;
};
Some(ports)
@@ -297,7 +296,7 @@ impl NodeNetworkInterface {
pub fn load_import_export_ports(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in export_ports");
log::error!("Could not get nested network_metadata in load_import_export_ports");
return;
};
network_metadata.transient_metadata.import_export_ports.ensure_loaded(|| self.compute_import_export_ports(network_path));
@@ -305,7 +304,7 @@ impl NodeNetworkInterface {
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_export_ports");
log::error!("Could not get nested network_metadata in unload_import_export_ports");
return;
};
transient.import_export_ports.unload();
@@ -313,13 +312,13 @@ impl NodeNetworkInterface {
// Always unload all wires connected to them as well
let number_of_imports = self.number_of_imports(network_path);
let Some(outward_wires) = self.outward_wires(network_path) else {
log::error!("Could not get outward wires in remove_import");
log::error!("Could not get outward wires in unload_import_export_ports");
return;
};
let mut input_connectors = Vec::new();
for import_index in 0..number_of_imports {
let Some(outward_wires_for_import) = outward_wires.get(&OutputConnector::Import(import_index)).cloned() else {
log::error!("Could not get outward wires for import in remove_import");
log::error!("Could not get outward wires for import in unload_import_export_ports");
return;
};
input_connectors.extend(outward_wires_for_import);
@@ -343,7 +342,7 @@ impl NodeNetworkInterface {
return None;
};
let Some(click_targets) = transient.modify_import_export.get_loaded_mut() else {
log::error!("could not load modify import export ports");
log::error!("Could not load modify import export in modify_import_export");
return None;
};
Some(click_targets)
@@ -351,7 +350,7 @@ impl NodeNetworkInterface {
pub fn load_modify_import_export(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in modify_import_export");
log::error!("Could not get nested network_metadata in load_modify_import_export");
return;
};
network_metadata
@@ -362,7 +361,7 @@ impl NodeNetworkInterface {
pub(crate) fn unload_modify_import_export(&mut self, network_path: &[NodeId]) {
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_export_ports");
log::error!("Could not get nested network_metadata in unload_modify_import_export");
return;
};
transient.modify_import_export.unload();
@@ -388,7 +387,7 @@ impl NodeNetworkInterface {
.all_nodes_bounding_box
.with_loaded_or(|| self.compute_all_nodes_bounding_box(network_path), |bounds| *bounds);
if bounding_box.is_none() {
log::error!("could not load all nodes bounding box");
log::error!("Could not load all nodes bounding box in all_nodes_bounding_box");
}
bounding_box
}
@@ -424,7 +423,7 @@ impl NodeNetworkInterface {
return None;
};
let Some(outward_wires) = transient.outward_wires.get_loaded_mut() else {
log::error!("could not load outward wires");
log::error!("Could not load outward wires in outward_wires");
return None;
};
@@ -441,7 +440,7 @@ impl NodeNetworkInterface {
fn load_outward_wires(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in outward_wires");
log::error!("Could not get nested network_metadata in load_outward_wires");
return;
};
network_metadata.transient_metadata.outward_wires.ensure_loaded(|| self.compute_outward_wires(network_path));
@@ -469,7 +468,7 @@ impl NodeNetworkInterface {
// A missing entry means a wire references a node output or import that does not exist, so log it and register the connector anyway rather than crashing
let push_outward_wire = |outward_wires: &mut HashMap<OutputConnector, Vec<InputConnector>>, output_connector: OutputConnector, input_connector: InputConnector| {
let outward_wires_entry = outward_wires.entry(output_connector).or_insert_with(|| {
log::error!("Output connector {output_connector:?} should be initialized in load_outward_wires");
log::error!("Output connector {output_connector:?} should be initialized in compute_outward_wires");
Vec::new()
});
outward_wires_entry.push(input_connector);
@@ -546,7 +545,7 @@ impl NodeNetworkInterface {
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width)
}
/// Unloads layer width if the node is a layer
/// Unloads layer width if the node is a layer.
pub fn try_unload_layer_width(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
let is_layer = self.is_layer(node_id, network_path);
@@ -554,7 +553,6 @@ impl NodeNetworkInterface {
return;
};
// If the node is a layer, then the width and click targets need to be recalculated
if is_layer {
transient.layer_width.unload();
}
@@ -599,14 +597,8 @@ impl NodeNetworkInterface {
}
fn load_wire(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) {
let dashed = match self.previewing(network_path) {
Previewing::Yes { .. } => match input {
InputConnector::Node { .. } => false,
InputConnector::Export(export_index) => *export_index == 0,
},
Previewing::No => false,
};
let Some(wire) = self.wire_path_from_input(input, graph_wire_style, dashed, network_path) else {
// The export keeps its own solid wire while previewing, since previewing does not rewire it
let Some(wire) = self.wire_path_from_input(input, graph_wire_style, false, network_path) else {
log::error!("Could not load wire path from input");
return;
};
@@ -663,7 +655,7 @@ impl NodeNetworkInterface {
fn unload_wires_for_node(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
let number_of_outputs = self.number_of_outputs(node_id, network_path);
let Some(outward_wires) = self.outward_wires(network_path) else {
log::error!("Could not get outward wires in reorder_export");
log::error!("Could not get outward wires in unload_wires_for_node");
return;
};
let mut input_connectors = Vec::new();
@@ -688,27 +680,26 @@ impl NodeNetworkInterface {
network_metadata.transient_metadata.wires.borrow_mut().remove(input);
}
/// The dashed wire from the previewed node to the export, drawn alongside the solid wire the export
/// is really connected to.
///
/// Previewing does not rewire the export, so both are shown: the solid wire says what the document
/// renders, and this one says what this peer is looking at instead.
pub fn wire_to_preview(&self, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<WirePathUpdate> {
/// When previewing, there may be a second path to the root node.
pub fn wire_to_root(&self, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<WirePathUpdate> {
let input = InputConnector::Export(0);
let current_export = self.upstream_output_connector(&input, network_path)?;
let Previewing::Yes { previewed } = self.previewing(network_path) else { return None };
let root_node = match self.previewing(network_path) {
Previewing::Yes { root_node_to_restore } => root_node_to_restore,
Previewing::No => None,
}?;
// The export already reaches it, so a second wire would land on top of the solid one
if self.upstream_output_connector(&input, network_path).and_then(|export| export.node_id()) == Some(previewed.node_id) {
if Some(root_node.node_id) == current_export.node_id() {
return None;
}
let Some(input_position) = self.get_input_center(&input, network_path) else {
log::error!("Could not get input position for wire end in preview: {input:?}");
log::error!("Could not get input position for wire end in root node: {input:?}");
return None;
};
let upstream_output = OutputConnector::node(previewed.node_id, previewed.output_index);
let upstream_output = OutputConnector::node(root_node.node_id, root_node.output_index);
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
log::error!("Could not get output position for wire start in preview: {upstream_output:?}");
log::error!("Could not get output position for wire start in root node: {upstream_output:?}");
return None;
};
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
@@ -726,7 +717,7 @@ impl NodeNetworkInterface {
path_string,
data_type,
thick,
dashed: false,
dashed: true,
is_list,
center_path_string,
});
@@ -749,7 +740,7 @@ impl NodeNetworkInterface {
return Some((BezPath::new(), BezPath::new(), false));
};
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
log::error!("Could not get output port for wire start: {:?}", upstream_output);
log::error!("Could not get output port for wire start: {upstream_output:?}");
return None;
};
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
@@ -786,7 +777,7 @@ impl NodeNetworkInterface {
let transient = self.node_transient_mut(node_id, network_path)?;
let Some(click_targets) = transient.click_targets.get_loaded_mut() else {
log::error!("Could not load node type metadata when getting click targets");
log::error!("Could not load click targets in node_click_targets");
return None;
};
Some(click_targets)
@@ -794,7 +785,7 @@ impl NodeNetworkInterface {
pub(crate) fn load_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in node_click_targets");
log::error!("Could not get nested node_metadata in load_node_click_targets");
return;
};
node_metadata.transient_metadata.click_targets.ensure_loaded(|| self.compute_node_click_targets(node_id, network_path));
@@ -821,16 +812,18 @@ impl NodeNetworkInterface {
let node_metadata = self.node_metadata(node_id, network_path)?;
let result = node_metadata.transient_metadata.click_targets.with_loaded(read);
if result.is_none() {
log::error!("Could not load node type metadata when getting click targets");
log::error!("Could not load click targets in with_node_click_targets_if_loaded");
}
result
}
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
self.load_node_click_targets(node_id, network_path);
self.try_get_node_bounding_box(node_id, network_path)
self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
.flatten()
}
/// The bounding box only if the click targets are already loaded, for a caller that is walking many
/// nodes and cannot afford to load each one it looks at.
pub fn try_get_node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
self.with_node_click_targets_if_loaded(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
.flatten()
@@ -848,7 +841,7 @@ impl NodeNetworkInterface {
pub fn unload_node_click_targets(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
let Some(transient) = self.node_transient_mut(node_id, network_path) else {
log::error!("Could not get nested node_metadata in unload_node_click_target");
log::error!("Could not get nested node_metadata in unload_node_click_targets");
return;
};
transient.click_targets.unload();
@@ -127,7 +127,7 @@ async fn cyclic_connection_is_rejected_without_side_effects() {
}
/// The check answers for the network with the proposed input substituted, so it has to see a loop that
/// closes through intermediate nodes rather than only one that connects two neighbours.
/// closes through intermediate nodes rather than only one that connects two neighbors.
#[tokio::test]
async fn a_cycle_closing_through_a_chain_is_rejected() {
let mut editor = EditorTestUtils::create();
@@ -172,6 +172,31 @@ async fn connecting_an_export_is_never_cyclic() {
assert_invariants(&editor, "after connecting the export");
}
#[tokio::test]
async fn toggling_preview_on_a_disconnected_export() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.disconnect_input(&InputConnector::Export(0), &[]);
// Previewing a node while the export is disconnected is a preview with nothing to restore
network_interface.toggle_preview(node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None });
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]);
assert_eq!(export.and_then(|input| input.as_node()), Some(node), "The previewed node should be wired to the export");
// Ending the preview restores the disconnected export
network_interface.toggle_preview(node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]);
assert!(export.is_some_and(|input| input.as_node().is_none()), "Ending the preview should disconnect the export again");
assert_invariants(&editor, "after toggling preview twice");
}
#[tokio::test]
async fn artboard_identity_is_independent_of_scene_connectivity() {
let mut editor = EditorTestUtils::create();
@@ -381,10 +406,8 @@ async fn signature_edits_keep_parallel_metadata_in_sync() {
assert_invariants(&editor, "after removing the added export");
}
/// Previewing renders a different node without rewiring anything: the export keeps whatever it is
/// connected to, so ending a preview has nothing to restore and cannot disconnect anything.
#[tokio::test]
async fn previewing_leaves_the_export_alone() {
async fn toggle_preview_transitions_with_a_connected_export() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
@@ -396,125 +419,31 @@ async fn previewing_leaves_the_export_alone() {
let export_node = |network_interface: &super::NodeNetworkInterface| network_interface.input_from_connector(&InputConnector::Export(0), &[]).and_then(|input| input.as_node());
assert_eq!(export_node(network_interface), Some(artboard));
// Previewing a node names it without touching the export
// Previewing a node remembers the artboard as the connection to restore
network_interface.toggle_preview(node, &[]);
assert_eq!(export_node(network_interface), Some(node));
assert_eq!(
network_interface.previewing(&[]),
Previewing::Yes {
previewed: RootNode { node_id: node, output_index: 0 }
root_node_to_restore: Some(RootNode { node_id: artboard, output_index: 0 })
}
);
assert_eq!(export_node(network_interface), Some(artboard), "Previewing must not rewire the export");
// Previewing a different node moves the preview, still without touching the export
network_interface.toggle_preview(artboard, &[]);
assert_eq!(
network_interface.previewing(&[]),
Previewing::Yes {
previewed: RootNode { node_id: artboard, output_index: 0 }
}
);
// Toggling the previewed node again restores the artboard connection
network_interface.toggle_preview(node, &[]);
assert_eq!(export_node(network_interface), Some(artboard));
// Toggling the previewed node again ends the preview, leaving the export as it always was
network_interface.toggle_preview(artboard, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
// Toggling the restore node while previewing promotes it to the export with nothing left to restore
network_interface.toggle_preview(node, &[]);
network_interface.toggle_preview(artboard, &[]);
assert_eq!(export_node(network_interface), Some(artboard));
assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None });
// Toggling it once more ends the preview by disconnecting the export entirely
network_interface.toggle_preview(artboard, &[]);
assert_eq!(export_node(network_interface), None);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
assert_invariants(&editor, "after cycling through the preview states");
}
/// The graph handed to the compiler renders the previewed node, which is the whole point of a preview
/// that does not rewire the document.
#[tokio::test]
async fn the_evaluated_network_renders_the_previewed_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.toggle_preview(node, &[]);
let evaluated = network_interface.network_to_evaluate();
assert_eq!(
evaluated.exports.first().and_then(|export| export.as_node()),
Some(node),
"The network being evaluated should export the previewed node"
);
assert_eq!(
network_interface.document_network().exports.first().and_then(|export| export.as_node()),
Some(artboard),
"The document itself should be unchanged"
);
}
/// The previewed node is marked for the frontend so it can be highlighted. Derived from the preview
/// itself: it used to be inferred from the export, which previewing no longer rewires, so inferring it
/// would silently mark nothing.
#[tokio::test]
async fn the_previewed_node_is_flagged_for_the_frontend() {
use crate::messages::portfolio::document::node_graph::NodeGraphMessageHandler;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
let handler = NodeGraphMessageHandler::default();
let network_interface = &mut editor.active_document_mut().network_interface;
let flagged = |handler: &NodeGraphMessageHandler, network_interface: &mut super::NodeNetworkInterface| {
handler
.collect_nodes(network_interface, &[])
.into_iter()
.filter(|node| node.previewed)
.map(|node| node.id)
.collect::<Vec<_>>()
};
assert!(flagged(&handler, network_interface).is_empty(), "Nothing is previewed to begin with");
network_interface.toggle_preview(node, &[]);
assert_eq!(flagged(&handler, network_interface), vec![node], "The previewed node should be the one flagged");
network_interface.toggle_preview(node, &[]);
assert!(flagged(&handler, network_interface).is_empty(), "Ending the preview should unflag it");
}
/// Resolving a batch of positions shares one downstream walk, so it has to agree with resolving each
/// node on its own. A stack is the case that matters: every layer walks through the ones below it, so
/// a shared memo is what keeps the batch from being quadratic.
#[tokio::test]
async fn batched_positions_agree_with_resolving_each_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(new_artboard_message(NodeId::new())).await;
for offset in 0..4 {
editor.draw_rect(0., offset as f64 * 20., 100., offset as f64 * 20. + 10.).await;
}
let network_interface = &editor.active_document().network_interface;
let node_ids = network_interface.document_network().nodes.keys().copied().collect::<Vec<_>>();
assert!(node_ids.len() > 4, "the fixture should build a stack, found {} nodes", node_ids.len());
let batched = network_interface.positions(node_ids.iter().copied(), &[]);
let individually = node_ids
.iter()
.filter_map(|node_id| network_interface.position(node_id, &[]).map(|position| (*node_id, position)))
.collect::<Vec<_>>();
assert_eq!(batched.len(), individually.len(), "The batch should resolve exactly the nodes that resolve on their own");
for (node_id, position) in individually {
assert_eq!(
batched.iter().find(|(batched_id, _)| *batched_id == node_id).map(|(_, position)| *position),
Some(position),
"Batched position disagrees for node {node_id}"
);
}
}
@@ -82,7 +82,15 @@ pub enum NetworkMetadataChange {
pub struct ConstructedOps {
pub ops: Vec<RegistryDelta>,
pub declaration_bytes: DeclarationBytes,
pub declarations: BatchDeclarations,
}
/// The proto-node declarations a batch extracted: the bytes for the caller's byte store, and the same
/// declarations decoded for its declaration cache, which a cursor rebuild reads instead of the bytes.
#[derive(Default)]
pub struct BatchDeclarations {
pub bytes: DeclarationBytes,
pub decoded: document_graph_storage::Declarations,
}
/// Constructs the storage ops for one gesture's deltas, in delta order. Removal closures and
@@ -100,54 +108,64 @@ pub fn construct_batch(
peer: document_graph_storage::PeerId,
) -> Result<ConstructedOps, ConversionError> {
let identities = IdentitiesOnly(metadata);
let resolver = PathResolver::new(Some(&identities), peer);
let context = ConversionContext {
resources,
identities: &identities,
resolver: PathResolver::new(Some(&identities), peer),
peer,
};
let mut batch = BatchRegistry::new(working);
let mut ops = Vec::new();
let mut declaration_bytes = DeclarationBytes::new();
let mut declarations = BatchDeclarations::default();
let mut batch_removed_nodes = Vec::new();
// In delta order, so each delta reads what the ones before it did. Removals accumulate as they are
// met rather than being gathered up front, since a removal can name a node an earlier delta added.
// In delta order, so each delta reads what the ones before it did
for delta in deltas {
delta.construct(resources, peer, &identities, &resolver, &mut batch, &mut batch_removed_nodes, &mut ops, &mut declaration_bytes)?;
delta.construct(&context, &mut batch, &mut batch_removed_nodes, &mut ops, &mut declarations)?;
}
batch_removed_nodes.sort();
batch_removed_nodes.dedup();
batch_removed_nodes.sort_by_key(|(id, _)| *id);
batch_removed_nodes.dedup_by_key(|(id, _)| *id);
construct_resource_removals(&batch_removed_nodes, &batch, &mut ops);
Ok(ConstructedOps { ops, declaration_bytes })
Ok(ConstructedOps { ops, declarations })
}
/// What every delta in a batch converts against, fixed for the whole batch.
struct ConversionContext<'a> {
resources: &'a ResourceRegistry,
identities: &'a dyn NodeMetadataSource,
resolver: PathResolver<'a>,
peer: document_graph_storage::PeerId,
}
impl EditorDelta {
#[allow(clippy::too_many_arguments)]
fn construct(
&self,
resources: &ResourceRegistry,
peer: document_graph_storage::PeerId,
identities: &dyn NodeMetadataSource,
resolver: &PathResolver,
context: &ConversionContext,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<document_graph_storage::NodeId>,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
declaration_bytes: &mut DeclarationBytes,
declarations: &mut BatchDeclarations,
) -> Result<(), ConversionError> {
match self {
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, node }) => {
construct_structural_additions(network_path, *node_id, node, batch, resources, identities, peer, ops, declaration_bytes)?;
construct_structural_additions(network_path, *node_id, node, batch, context, ops, declarations)?;
}
EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
construct_removals(resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
construct_structural_additions(network_path, *node_id, node, batch, resources, identities, peer, ops, declaration_bytes)?;
// Only what the previous implementation owned goes; the node stays so the addition below
// updates it in place and its `ui::*` attributes survive the swap.
construct_removals_below(context.resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
construct_structural_additions(network_path, *node_id, node, batch, context, ops, declarations)?;
}
EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id }) => {
construct_removals(resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
construct_removals(context.resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
}
EditorDelta::Graph(RuntimeDelta::SetVisibility { network_path, node_id, visible }) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: resolver.node_id(network_path, *node_id),
id: context.resolver.node_id(network_path, *node_id),
delta: AttributeDelta {
key: node_attr::VISIBLE.to_string(),
value: (!visible).then_some(serde_json::Value::Bool(false)),
@@ -161,24 +179,32 @@ impl EditorDelta {
input_index,
input,
}) => {
let new_input = context.resolver.convert_input_at(input, network_path)?;
construct_referenced_resource(Some(context.resolver.node_id(network_path, *node_id)), &new_input, context, batch, ops)?;
ops.push(RegistryDelta::ChangeNodeInput {
id: resolver.node_id(network_path, *node_id),
id: context.resolver.node_id(network_path, *node_id),
index: (*input_index).try_into().map_err(|_| ConversionError::IndexOverflow(*input_index))?,
new_input: resolver.convert_input_at(input, network_path)?,
new_input,
});
}
EditorDelta::Graph(RuntimeDelta::SetExport { network_path, export_index, input }) => {
let export = input.as_ref().map(|input| context.resolver.convert_input_at(input, network_path)).transpose()?;
if let Some(export) = export.as_ref() {
construct_referenced_resource(None, export, context, batch, ops)?;
}
ops.push(RegistryDelta::SetNetworkExport {
id: resolver.network_id(network_path),
id: context.resolver.network_id(network_path),
index: (*export_index).try_into().map_err(|_| ConversionError::IndexOverflow(*export_index))?,
export: input.as_ref().map(|input| resolver.convert_input_at(input, network_path)).transpose()?,
export,
});
}
EditorDelta::Graph(RuntimeDelta::SetCallArgument { network_path, node_id, call_argument }) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: resolver.node_id(network_path, *node_id),
id: context.resolver.node_id(network_path, *node_id),
delta: document_graph_storage::from_runtime::encode_call_argument(call_argument)?,
});
}
@@ -189,38 +215,41 @@ impl EditorDelta {
context_features,
}) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: resolver.node_id(network_path, *node_id),
id: context.resolver.node_id(network_path, *node_id),
delta: document_graph_storage::from_runtime::encode_context_features(context_features)?,
});
}
EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata } => {
construct_metadata_snapshot(network_path, *node_id, metadata, batch, resolver, ops)?;
construct_metadata_snapshot(network_path, *node_id, metadata, batch, &context.resolver, ops)?;
}
EditorDelta::Graph(RuntimeDelta::SetInputs { network_path, node_id, inputs }) => {
// Only the slots are written, so the node's attributes and everything nested under it are
// left as they are: an edit made earlier in this batch is not reverted by the rebuild.
// The slots' `ui::*` attributes arrive with the paired input metadata delta.
// The slots' `ui::*` attributes arrive with the paired input metadata delta
let inputs = inputs
.iter()
.map(|input| {
Ok(document_graph_storage::InputSlot {
input: resolver.convert_input_at(input, network_path)?,
input: context.resolver.convert_input_at(input, network_path)?,
timestamp: TimeStamp::ORIGIN,
attributes: convert_input_attributes(input)?,
attributes_timestamp: TimeStamp::ORIGIN,
})
})
.collect::<Result<Vec<_>, ConversionError>>()?;
for slot in &inputs {
construct_referenced_resource(Some(context.resolver.node_id(network_path, *node_id)), &slot.input, context, batch, ops)?;
}
ops.push(RegistryDelta::SetNodeInputs {
id: resolver.node_id(network_path, *node_id),
id: context.resolver.node_id(network_path, *node_id),
inputs,
});
}
EditorDelta::NodeMetadata { network_path, node_id, change } => {
ops.extend(node_metadata_ops(resolver.node_id(network_path, *node_id), change)?);
ops.extend(node_metadata_ops(context.resolver.node_id(network_path, *node_id), change)?);
}
EditorDelta::NodeInputMetadata {
@@ -228,12 +257,10 @@ impl EditorDelta {
node_id,
input_metadata,
} => {
let global_id = resolver.node_id(network_path, *node_id);
let global_id = context.resolver.node_id(network_path, *node_id);
let source = InputMetadataSource(input_metadata);
let working_node = batch.node(global_id);
// An insert shifts every later slot, so the array is asserted whole: a `ui::` key the slot
// no longer carries is cleared rather than left behind at its old index.
for input_index in 0..input_metadata.len() {
let mut encoded = Attributes::new();
encode_input_ui_attributes(&mut encoded, &source, network_path, *node_id, input_index, TimeStamp::ORIGIN)?;
@@ -256,7 +283,7 @@ impl EditorDelta {
value: reference.clone().map(serde_json::Value::String),
},
NetworkMetadataChange::PinnedOrder(order) => {
let stored: Vec<_> = order.iter().map(|node_id| resolver.node_id(network_path, *node_id)).collect();
let stored: Vec<_> = order.iter().map(|node_id| context.resolver.node_id(network_path, *node_id)).collect();
AttributeDelta {
key: network_attr::PINNED_ORDER.to_string(),
value: (!stored.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &stored)).transpose()?,
@@ -265,7 +292,7 @@ impl EditorDelta {
};
ops.push(RegistryDelta::ChangeNetworkAttribute {
id: resolver.network_id(network_path),
id: context.resolver.network_id(network_path),
delta,
});
}
@@ -296,8 +323,7 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
})
};
// Absence is how the encoder spells an unset flag, and the empty string is the runtime's own
// sentinel for an unset name.
// The empty string is the runtime's own sentinel for an unset name
let flag = |value: bool| value.then_some(serde_json::Value::Bool(true));
let non_empty = |value: &str| (!value.is_empty()).then(|| serde_json::Value::String(value.to_string()));
Ok(match change {
@@ -325,36 +351,67 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
/// Converts through the same encoders as a whole-document conversion, with identities only as the
/// source: ui attributes arrive via the gesture's paired `NodeMetadata` delta.
#[allow(clippy::too_many_arguments)]
fn construct_structural_additions(
network_path: &[NodeId],
node_id: NodeId,
node: &graph_craft::document::DocumentNode,
batch: &mut BatchRegistry,
resources: &ResourceRegistry,
identities: &dyn NodeMetadataSource,
peer: document_graph_storage::PeerId,
context: &ConversionContext,
ops: &mut Vec<RegistryDelta>,
declaration_bytes: &mut DeclarationBytes,
declarations: &mut BatchDeclarations,
) -> Result<(), ConversionError> {
let mut scoped = ScopedConversion::new(identities, peer);
let mut scoped = ScopedConversion::new(context.identities, context.peer);
let mut scratch = Registry::default();
scoped.convert_node_at(&mut scratch, network_path, node_id, node, true)?;
declaration_bytes.extend(scoped.finish());
let (bytes, decoded) = scoped.finish();
declarations.bytes.extend(bytes);
declarations.decoded.extend(decoded);
let mut networks: Vec<_> = scratch.networks.iter().collect();
networks.sort_by_key(|(id, _)| **id);
let mut networks: Vec<_> = scratch.networks.iter().map(|(id, network)| (*id, network.clone())).collect();
networks.sort_by_key(|(id, _)| *id);
for (id, network) in networks {
ops.push(RegistryDelta::AddNetwork { id: *id, network: network.clone() });
ops.push(RegistryDelta::AddNetwork { id, network: network.clone() });
batch.record_network(id, network);
}
// Recorded as well as emitted, so a later delta in this batch that reads one of these nodes back
// finds it rather than looking only at the registry the batch started from.
// Recorded as well as emitted, so a later delta in this batch can read these nodes back
let mut nodes: Vec<_> = scratch.node_instances.iter().collect();
nodes.sort_by_key(|(id, _)| **id);
let added: Vec<_> = nodes.into_iter().map(|(id, node)| (*id, node.clone())).collect();
for (id, node) in added {
ops.push(RegistryDelta::AddNode { id, node: node.clone() });
// A node the registry already holds is updated rather than rebuilt: rebuilding would clear the
// `ui::*` attributes it carries, and restating those would clobber whatever a concurrent peer
// wrote to its name, lock or pin.
match batch.node(id) {
Some(held) => {
// The swap did not write the slots' `ui::*` attributes, and a whole-slot assignment would
// otherwise drop the names and descriptions this peer holds for the slots that survive it.
let inputs = node
.inputs()
.iter()
.enumerate()
.map(|(index, slot)| {
let mut slot = slot.clone();
if let Some(previous) = held.inputs().get(index) {
slot.attributes.extend(
previous
.attributes
.iter()
.filter(|(key, value)| key.starts_with("ui::") && !value.deleted)
.map(|(key, value)| (key.clone(), value.clone())),
);
}
slot
})
.collect();
ops.push(RegistryDelta::SetNodeImplementation {
id,
implementation: node.implementation().clone(),
});
ops.push(RegistryDelta::SetNodeInputs { id, inputs });
}
None => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
}
batch.record_addition(id, node);
}
@@ -376,7 +433,7 @@ fn construct_structural_additions(
for id in tagged {
if batch.resource(id).is_none()
&& !scratch.resources.contains_key(&id)
&& let Some(entry) = convert_resource_entry(resources, id, peer)?
&& let Some(entry) = convert_resource_entry(context.resources, id, context.peer)?
{
batch.record_resource(id, entry.clone());
ops.push(RegistryDelta::AddResource { id, entry });
@@ -386,6 +443,31 @@ fn construct_structural_additions(
Ok(())
}
/// Stages the resource a value input references, so setting an input to an asset persists the entry
/// alongside the reference rather than leaving the registry pointing at something it does not hold.
fn construct_referenced_resource(
owner: Option<document_graph_storage::NodeId>,
input: &document_graph_storage::NodeInput,
context: &ConversionContext,
batch: &mut BatchRegistry,
ops: &mut Vec<RegistryDelta>,
) -> Result<(), ConversionError> {
let Some(id) = value_resource_ref(input) else { return Ok(()) };
if let Some(owner) = owner {
batch.record_input_resource(owner, id);
}
if batch.resource(id).is_some() {
return Ok(());
}
let Some(entry) = convert_resource_entry(context.resources, id, context.peer)? else {
return Ok(());
};
batch.record_resource(id, entry.clone());
ops.push(RegistryDelta::AddResource { id, entry });
Ok(())
}
fn construct_metadata_snapshot(
network_path: &[NodeId],
node_id: NodeId,
@@ -430,10 +512,11 @@ fn construct_metadata_snapshot(
let network_id = resolver.network_id(&nested_path);
let target = network_metadata.persistent_metadata.reference.clone().map(serde_json::Value::String);
// Read through the batch rather than the pre-batch registry: a `ReplaceNode` earlier in this
// batch rebuilds the network without a reference, so comparing against the old state would
// suppress the write and leave the rebuilt network missing it.
let current = batch
.working
.networks
.get(&network_id)
.network(network_id)
.and_then(|network| network.attributes.get(node_attr::ui::REFERENCE))
.map(|value| value.value.clone());
if current != target {
@@ -446,6 +529,22 @@ fn construct_metadata_snapshot(
});
}
// Restated alongside the reference, since a rebuild clears the network's attributes and the
// order would otherwise be lost for every nested network the snapshot covers.
let pinned_order: Vec<_> = network_metadata
.persistent_metadata
.pinned_node_order
.iter()
.map(|pinned| resolver.node_id(&nested_path, *pinned))
.collect();
ops.push(RegistryDelta::ChangeNetworkAttribute {
id: network_id,
delta: AttributeDelta {
key: network_attr::PINNED_ORDER.to_string(),
value: (!pinned_order.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &pinned_order)).transpose()?,
},
});
for (child_id, child) in &network_metadata.persistent_metadata.node_metadata {
pending.push((nested_path.clone(), *child_id, &child.persistent_metadata));
}
@@ -486,37 +585,69 @@ fn ui_attribute_writes(current: Option<&Attributes>, encoded: &Attributes) -> Ve
/// Emits the removal of a node and everything nested under it, recording what was removed so the
/// batch's resource liveness accounts for all of it at the end.
fn construct_removals(node_id: document_graph_storage::NodeId, batch: &BatchRegistry, batch_removed_nodes: &mut Vec<document_graph_storage::NodeId>, ops: &mut Vec<RegistryDelta>) {
fn construct_removals(
node_id: document_graph_storage::NodeId,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
) {
construct_removals_with(node_id, true, batch, batch_removed_nodes, ops)
}
/// Removes everything the node's implementation owns while leaving the node itself, for a swap that
/// keeps the node in place.
fn construct_removals_below(
node_id: document_graph_storage::NodeId,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
) {
construct_removals_with(node_id, false, batch, batch_removed_nodes, ops)
}
fn construct_removals_with(
node_id: document_graph_storage::NodeId,
include_node: bool,
batch: &mut BatchRegistry,
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
ops: &mut Vec<RegistryDelta>,
) {
let (mut removed_nodes, mut removed_networks) = removal_closure(node_id, batch);
removed_nodes.sort();
removed_networks.sort();
for id in &removed_nodes {
let Some(snapshot) = batch.node(*id) else { continue };
if !include_node && *id == node_id {
continue;
}
let Some(snapshot) = batch.node(*id).cloned() else { continue };
ops.push(RegistryDelta::RemoveNode { id: *id, snapshot: snapshot.clone() });
// Kept by value: a replacement later in this batch re-adds the same ID with different content, so
// looking the node up again at the end would read what replaced it rather than what was removed.
batch_removed_nodes.push((*id, snapshot));
batch.record_removal(*id);
}
for id in &removed_networks {
let Some(snapshot) = batch.working.networks.get(id) else { continue };
let Some(snapshot) = batch.network(*id) else { continue };
ops.push(RegistryDelta::RemoveNetwork { id: *id, snapshot: snapshot.clone() });
}
batch_removed_nodes.extend(removed_nodes);
}
/// Emits removals for resources referenced only by the batch's removed nodes, checked after every
/// removal is known.
fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::NodeId], batch: &BatchRegistry, ops: &mut Vec<RegistryDelta>) {
let removed_node_set: HashSet<_> = batch_removed_nodes.iter().copied().collect();
fn construct_resource_removals(batch_removed_nodes: &[(document_graph_storage::NodeId, document_graph_storage::Node)], batch: &BatchRegistry, ops: &mut Vec<RegistryDelta>) {
// A node this batch wrote an input on and then removed orphans whatever that write referenced, which
// the stored node does not mention.
let mut candidates: Vec<ResourceId> = batch_removed_nodes
.iter()
.filter_map(|id| batch.node(*id))
.flat_map(|node| {
.flat_map(|(id, _)| batch.input_resources.get(id).into_iter().flatten().copied())
.chain(batch_removed_nodes.iter().map(|(_, node)| node).flat_map(|node| {
let declaration = match node.implementation() {
Implementation::ProtoNode(declaration) => Some(*declaration),
Implementation::Network(_) => None,
};
declaration.into_iter().chain(node_value_resource_refs(node))
})
}))
.collect();
candidates.sort();
candidates.dedup();
@@ -526,16 +657,18 @@ fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::No
// Gathered in one pass so each candidate is a lookup rather than another scan of the whole registry
let mut still_referenced: HashSet<ResourceId> = HashSet::new();
for (id, node) in batch.working.node_instances.iter().chain(&batch.added) {
if removed_node_set.contains(id) {
continue;
}
for (id, node) in batch.live_nodes() {
if let Implementation::ProtoNode(declaration) = node.implementation() {
still_referenced.insert(*declaration);
}
still_referenced.extend(node_value_resource_refs(node));
// What this batch wrote onto a node that survives it is a live reference, even though the stored
// node still carries the input it had before.
still_referenced.extend(batch.input_resources.get(&id).into_iter().flatten().copied());
}
for network in batch.working.networks.values() {
// The batch's own networks count too: one added earlier in it can export a resource the removal would
// otherwise see as orphaned.
for network in batch.working.networks.values().chain(batch.added_networks.values()) {
still_referenced.extend(network.exports.iter().filter_map(|slot| slot.target.as_ref().and_then(value_resource_ref)));
}
@@ -552,20 +685,24 @@ fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::No
}
/// The registry a delta is constructed against: what the batch started from, plus the nodes deltas
/// earlier in the same batch have added.
///
/// A delta that reads a node back cannot read only the starting registry. A node added and removed
/// within one batch is not in it, and a later delta that rebuilds a node would rebuild the version
/// that predates the batch. Additions are tracked rather than the whole registry copied, so the cost
/// is the size of the batch rather than of the document.
/// earlier in the same batch have added, since a delta can read back or remove a node an earlier one
/// added.
///
/// Nodes are also indexed by network, so a removal closure walks only the subtree it removes instead
/// of rescanning every node for each nested network it meets.
struct BatchRegistry<'a> {
working: &'a Registry,
added: HashMap<document_graph_storage::NodeId, document_graph_storage::Node>,
added_networks: HashMap<document_graph_storage::NetworkId, document_graph_storage::Network>,
added_resources: HashMap<ResourceId, document_graph_storage::ResourceEntry>,
by_network: HashMap<document_graph_storage::NetworkId, Vec<document_graph_storage::NodeId>>,
/// Nodes the batch has removed and not since re-added, so a lookup answers with the state the ops so
/// far have produced rather than the state the batch started from.
removed: HashSet<document_graph_storage::NodeId>,
/// Resources the batch's own input writes reference, keyed by the node written to. The stored node
/// still holds its pre-batch inputs, so liveness would otherwise miss both the reference these writes
/// create and the orphan they leave when that node is later removed.
input_resources: HashMap<document_graph_storage::NodeId, HashSet<ResourceId>>,
}
impl<'a> BatchRegistry<'a> {
@@ -577,17 +714,38 @@ impl<'a> BatchRegistry<'a> {
Self {
working,
added: HashMap::new(),
added_networks: HashMap::new(),
added_resources: HashMap::new(),
by_network,
removed: HashSet::new(),
input_resources: HashMap::new(),
}
}
/// Records that an input write on `owner` references `resource`.
fn record_input_resource(&mut self, owner: document_graph_storage::NodeId, resource: ResourceId) {
self.input_resources.entry(owner).or_default().insert(resource);
}
/// Records a node an earlier delta in this batch added, so a later one can read it back.
fn record_addition(&mut self, id: document_graph_storage::NodeId, node: document_graph_storage::Node) {
self.by_network.entry(node.network()).or_default().push(id);
self.removed.remove(&id);
self.added.insert(id, node);
}
/// Records a node this batch removed, so a later delta reading it back finds it gone.
fn record_removal(&mut self, id: document_graph_storage::NodeId) {
self.added.remove(&id);
self.removed.insert(id);
}
/// Records a network an earlier delta in this batch added, so removing the node that owns it finds
/// the network to remove alongside it.
fn record_network(&mut self, id: document_graph_storage::NetworkId, network: document_graph_storage::Network) {
self.added_networks.insert(id, network);
}
/// Records a resource this batch added. Returns whether it is new to the batch, so the caller emits
/// one addition for a resource several nodes reference.
fn record_resource(&mut self, id: ResourceId, entry: document_graph_storage::ResourceEntry) -> bool {
@@ -595,9 +753,29 @@ impl<'a> BatchRegistry<'a> {
}
fn node(&self, id: document_graph_storage::NodeId) -> Option<&document_graph_storage::Node> {
if self.removed.contains(&id) {
return None;
}
self.added.get(&id).or_else(|| self.working.node_instances.get(&id))
}
/// Every node the batch leaves in place, which is what the working registry held plus what the batch
/// added, less what it removed.
fn live_nodes(&self) -> impl Iterator<Item = (document_graph_storage::NodeId, &document_graph_storage::Node)> {
self.working
.node_instances
.keys()
.chain(self.added.keys())
.copied()
.collect::<HashSet<_>>()
.into_iter()
.filter_map(|id| Some((id, self.node(id)?)))
}
fn network(&self, id: document_graph_storage::NetworkId) -> Option<&document_graph_storage::Network> {
self.added_networks.get(&id).or_else(|| self.working.networks.get(&id))
}
fn resource(&self, id: ResourceId) -> Option<&document_graph_storage::ResourceEntry> {
self.added_resources.get(&id).or_else(|| self.working.resources.get(&id))
}
@@ -78,7 +78,7 @@ async fn set_input_value_constructs_the_exact_diff_op() {
let node = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
let input = NodeInput::value(TaggedValue::F64(42.), false);
let input = NodeInput::value(TaggedValue::Number(42.), false);
editor.active_document_mut().network_interface.set_input(&InputConnector::node_at_index(node, 1), input.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetInput {
@@ -195,9 +195,8 @@ async fn per_field_metadata_edits_match_the_diff() {
assert_same_stored_effect(&working, constructed, diffed, "per-field metadata edits");
}
/// The encoding spells "unset" as an absent attribute, so a field set back to its unset value has to
/// clear the key rather than write a sentinel. The wholesale copy got this by omitting the key; a
/// per-field delta has to say it, and saying it wrong leaves the old value stored.
/// The encoding spells "unset" as an absent attribute, so a per-field delta that sets a field back to
/// its unset value must clear the key rather than write a sentinel.
#[tokio::test]
async fn clearing_a_metadata_field_removes_the_attribute() {
let mut editor = EditorTestUtils::create();
@@ -227,9 +226,9 @@ async fn clearing_a_metadata_field_removes_the_attribute() {
assert_same_stored_effect(&working, constructed, diffed, "cleared metadata fields");
}
/// The gate emission exists for: what the store says it wrote has to be what a whole-document
/// conversion of the result would show. Hand-written deltas cannot catch a setter that forgets to
/// emit, or emits the wrong field; taking them from the interface after a real edit can.
/// The deltas the interface emits for a real edit must store what a whole-document conversion of the
/// result would. Taking them from the interface rather than writing them by hand is what catches a
/// setter that forgets to emit, or emits the wrong field.
#[tokio::test]
async fn emitted_deltas_reproduce_the_diff() {
let mut editor = EditorTestUtils::create();
@@ -338,7 +337,7 @@ async fn emitted_deltas_reproduce_the_diff_for_an_arity_change() {
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
assert!(!emitted.is_empty(), "adding an import should have emitted deltas");
@@ -379,7 +378,7 @@ async fn an_arity_change_keeps_an_earlier_edit_to_the_same_node() {
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
let constructed = construct(&editor, &emitted, &working);
@@ -387,10 +386,9 @@ async fn an_arity_change_keeps_an_earlier_edit_to_the_same_node() {
assert_same_stored_effect(&working, constructed, diffed, "rename then arity change");
}
/// The gate replay exists for: what the store recorded has to be enough to reproduce the write that
/// produced it. Clone the interface before an edit, apply what the edit recorded onto the clone, and
/// the two should agree. Something the store failed to record, or recorded wrongly, surfaces here
/// rather than as drift on another peer.
/// What an edit records must be enough to reproduce it: applying the recorded deltas to a clone of the
/// interface taken before the edit must yield the edited interface. A write recorded wrongly or not at
/// all surfaces here rather than as drift on another peer.
async fn assert_replay_reproduces(edit: impl FnOnce(&mut EditorTestUtils)) {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
@@ -454,7 +452,7 @@ async fn replaying_an_arity_change_reproduces_the_interface() {
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
})
.await;
}
@@ -552,3 +550,311 @@ async fn removing_a_nested_network_node_matches_the_diff() {
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "nested network removal");
}
/// A group carries a nested network, so adding and removing one inside a batch has to cancel out the
/// network as well as the nodes. The proto-node case above does not reach this, since a proto node has
/// no network of its own.
#[tokio::test]
async fn a_group_added_and_removed_in_one_batch_leaves_nothing_behind() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
let group = only_group(&editor);
editor.active_document_mut().network_interface.delete_nodes(vec![group], true, &[]);
let emitted = editor.active_document_mut().network_interface.take_deltas();
let constructed = construct(&editor, &emitted, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "group added then removed in one batch");
}
/// Swapping a node's implementation must not restate the node's own metadata: the swap did not write it,
/// and asserting it would overwrite whatever a concurrent peer set for the node's name, lock or pin.
#[tokio::test]
async fn swapping_an_implementation_leaves_the_node_in_place() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
let working = convert(&editor);
let deltas = {
let interface = &mut editor.active_document_mut().network_interface;
interface.discard_deltas();
let Some(mut cursor) = interface.node_mut(super::NodeLocator::new(node, &[])) else {
panic!("the node should resolve")
};
cursor.replace_implementation(graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), None);
interface.take_deltas()
};
let ops = construct(&editor, &deltas, &working);
assert!(
ops.iter().any(|op| matches!(op, RegistryDelta::SetNodeImplementation { .. })),
"the swap should update the implementation in place"
);
assert!(
!ops.iter().any(|op| matches!(op, RegistryDelta::RemoveNode { .. })),
"the node itself should not be rebuilt, since that would clear the attributes it carries"
);
assert!(
!deltas.iter().any(|delta| matches!(delta, EditorDelta::NodeMetadataSnapshot { node_id, .. } if *node_id == node)),
"the node's own metadata should not be restated by a swap that did not write it"
);
}
/// What a peer receives must bring its interface to what the editing peer holds: the recorded deltas are
/// constructed into storage ops, applied to the peer's registry, and the touched entities reconciled
/// into a clone of the interface taken before the edit. Anything the reconcile expresses wrongly, or
/// not at all, shows here as a difference from the edited interface, and the reconciled interface has
/// to convert back to the registry it was reconciled from.
async fn assert_remote_reconcile_reproduces(edit: impl FnOnce(&mut EditorTestUtils)) {
use document_graph_storage::Touched;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
editor.active_document_mut().network_interface.discard_deltas();
// Both interfaces address nodes the way storage does, so they compare directly.
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
// The peer's registry holds what a conversion of the interface holds before the edit.
let mut mirror = editor.active_document().network_interface.clone();
let baseline = {
let document = editor.active_document();
Registry::convert_from_runtime(
document.network_interface.document_network(),
&StorageMetadataView::new(&document.network_interface),
&document.resources.registry,
PEER,
)
.expect("conversion")
};
let mut peer = Session::with_peer(PeerId(8));
peer.stage_computed_ops(compute_deltas(&Registry::default(), &baseline.registry)).expect("the peer takes the baseline");
let mut declarations = baseline.declarations;
edit(&mut editor);
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
let recorded = editor.active_document_mut().network_interface.take_deltas();
assert!(!recorded.is_empty(), "the edit should have recorded something to send");
let constructed = {
let document = editor.active_document();
construct_batch(
&recorded,
&baseline.registry,
&document.resources.registry,
&StorageMetadataView::new(&document.network_interface),
PEER,
)
.expect("construction")
};
declarations.extend(constructed.declarations.decoded);
let mut touched = Touched::default();
for op in &constructed.ops {
touched.record(op);
}
peer.stage_computed_ops(constructed.ops).expect("the peer applies the batch");
mirror.reconcile_remote(peer.registry(), &declarations, &touched, PEER).expect("reconcile");
let edited = &editor.active_document().network_interface;
assert!(
mirror.document_network() == edited.document_network(),
"reconciling {} recorded deltas did not reproduce the edited graph:\n{}",
recorded.len(),
crate::messages::portfolio::document::document_diff::diff_networks(edited.document_network(), mirror.document_network())
);
let metadata = |interface: &super::NodeNetworkInterface| serde_json::to_value(interface.document_network_metadata()).expect("metadata serializes");
let (reconciled_metadata, edited_metadata) = (metadata(&mirror), metadata(edited));
assert!(
reconciled_metadata == edited_metadata,
"reconciling {} recorded deltas did not reproduce the edited metadata:\n{}",
recorded.len(),
json_diff(&edited_metadata, &reconciled_metadata, "")
);
let converted = Registry::convert_from_runtime(mirror.document_network(), &StorageMetadataView::new(&mirror), &editor.active_document().resources.registry, PEER)
.expect("the reconciled interface converts")
.registry;
assert!(
peer.registry().value_equal(&converted),
"the reconciled interface must convert back to the registry it was reconciled from\nresidual: {:#?}",
compute_deltas(&converted, peer.registry())
);
}
/// The paths at which two JSON values differ, one per line, so a metadata mismatch names the field.
fn json_diff(expected: &serde_json::Value, actual: &serde_json::Value, path: &str) -> String {
use serde_json::Value;
match (expected, actual) {
(Value::Object(expected), Value::Object(actual)) => {
let keys: std::collections::BTreeSet<_> = expected.keys().chain(actual.keys()).collect();
keys.into_iter()
.map(|key| match (expected.get(key), actual.get(key)) {
(Some(expected), Some(actual)) => json_diff(expected, actual, &format!("{path}/{key}")),
(Some(expected), None) => format!("{path}/{key}: missing, expected {expected}\n"),
(None, Some(actual)) => format!("{path}/{key}: unexpected {actual}\n"),
(None, None) => String::new(),
})
.collect()
}
(Value::Array(expected), Value::Array(actual)) if expected.len() == actual.len() => expected
.iter()
.zip(actual)
.enumerate()
.map(|(index, (expected, actual))| json_diff(expected, actual, &format!("{path}[{index}]")))
.collect(),
_ if expected == actual => String::new(),
_ => format!("{path}: expected {expected}\n{path}: actual {actual}\n"),
}
}
#[tokio::test]
async fn reconciling_metadata_edits_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&group, "Renamed".to_string(), &[]);
network_interface.set_locked(&group, &[], true);
network_interface.set_pinned(&group, &[], true);
network_interface.set_visibility(&group, &[], false);
network_interface.shift_node(&group, glam::IVec2::new(3, 5), &[]);
})
.await;
}
#[tokio::test]
async fn reconciling_an_arity_change_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
})
.await;
}
#[tokio::test]
async fn reconciling_a_node_insertion_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17A), template, &[]);
})
.await;
}
#[tokio::test]
async fn reconciling_a_node_insertion_inside_a_group_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17B), template, &[group]);
})
.await;
}
#[tokio::test]
async fn reconciling_a_group_removal_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
editor.active_document_mut().network_interface.delete_nodes(vec![group], true, &[]);
})
.await;
}
#[tokio::test]
async fn reconciling_an_implementation_swap_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
let interface = &mut editor.active_document_mut().network_interface;
let Some(mut cursor) = interface.node_mut(super::NodeLocator::new(group, &[])) else {
panic!("the group should resolve")
};
cursor.replace_implementation(graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), None);
})
.await;
}
#[tokio::test]
async fn reconciling_an_input_value_edit_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
let interface = &mut editor.active_document_mut().network_interface;
let inner = interface
.nested_network(&[group])
.expect("the group's network")
.nodes
.iter()
.find(|(_, node)| node.inputs.iter().any(|input| input.as_value().is_some()))
.map(|(id, _)| *id)
.expect("a node with a value input inside the group");
let index = interface
.nested_network(&[group])
.and_then(|network| network.nodes.get(&inner))
.and_then(|node| node.inputs.iter().position(|input| input.as_value().is_some()))
.expect("the value input");
interface.set_input(&InputConnector::node_at_index(inner, index), NodeInput::value(TaggedValue::Number(42.), false), &[group]);
})
.await;
}
/// A touched node the registry holds unchanged, which is what a late-writer-wins loser leaves behind,
/// must not disturb the interface.
#[tokio::test]
async fn reconciling_an_untouched_node_changes_nothing() {
use document_graph_storage::Touched;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
let baseline = convert(&editor);
let declarations = {
let document = editor.active_document();
Registry::convert_from_runtime(
document.network_interface.document_network(),
&StorageMetadataView::new(&document.network_interface),
&document.resources.registry,
PEER,
)
.expect("conversion")
.declarations
};
let mut touched = Touched::default();
touched.nodes.extend(baseline.node_instances.keys().copied());
touched.networks.extend(baseline.networks.keys().copied());
let before = editor.active_document().network_interface.clone();
let reconciled = editor
.active_document_mut()
.network_interface
.reconcile_remote(&baseline, &declarations, &touched, PEER)
.expect("reconcile");
assert!(reconciled.networks.is_empty(), "nothing differed, so nothing should have been applied: {:?}", reconciled.networks);
assert_eq!(editor.active_document().network_interface, before);
}
@@ -21,7 +21,6 @@ impl NodeNetworkInterface {
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
let mut port_click_targets = Ports::new();
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
// Create input/output click targets
let mut input_row_count = 0;
for (input_index, input) in document_node.inputs.iter().enumerate() {
if input.is_exposed() {
@@ -59,7 +58,6 @@ impl NodeNetworkInterface {
node_type_metadata: NodeTypeClickTargets::Node,
}
} else {
// Layer inputs
port_click_targets.insert_layer_input(0, node_top_left);
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
port_click_targets.insert_layer_input(1, node_top_left);
@@ -67,7 +65,7 @@ impl NodeNetworkInterface {
port_click_targets.insert_layer_output(node_top_left);
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
log::error!("Could not get layer width in load_node_click_targets");
log::error!("Could not get layer width in compute_node_click_targets");
0
});
let width = layer_width_cells * GRID_SIZE;
@@ -79,7 +77,6 @@ impl NodeNetworkInterface {
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
// Update visibility button click target
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
@@ -101,8 +98,7 @@ impl NodeNetworkInterface {
None
};
// Update grip button click target, which is positioned to the left of the leftmost icon.
// The grip is 8px wide but spans the full layer-vertical-center band.
// The grip sits to the left of the leftmost icon, 8px wide but spanning the full layer-vertical-center band
const GRIP_WIDTH: f64 = 8.;
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
@@ -113,8 +109,8 @@ impl NodeNetworkInterface {
);
let grip_click_target = ClickTarget::new_with_path(path, 0.);
// Update display-name text click target, used to detect double-click rename. Sized to the text bounds
// (not the surrounding `.details` area) so the rest of the layer still drills into the subgraph on double-click.
// The double-click rename target is sized to the text bounds, not the surrounding `.details` area,
// so the rest of the layer still drills into the subgraph on double-click
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
@@ -147,7 +143,7 @@ impl NodeNetworkInterface {
}
};
// Create layer click target, which is contains the layer and the chain background
// The layer click target spans the layer and its chain background
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
@@ -180,7 +176,7 @@ impl NodeNetworkInterface {
let ports_built = self.with_import_export_ports(network_path, |import_exports| {
for (import_index, import_click_target) in import_exports.output_ports() {
let Some(import_bounding_box) = import_click_target.bounding_box() else {
log::error!("Could not get export bounding box in load_modify_import_export");
log::error!("Could not get export bounding box in compute_modify_import_export");
continue;
};
let reorder_import_center = (import_bounding_box[0] + import_bounding_box[1]) / 2. + DVec2::new(-12., 0.);
@@ -200,7 +196,7 @@ impl NodeNetworkInterface {
for (export_index, export_click_target) in import_exports.input_ports() {
let Some(export_bounding_box) = export_click_target.bounding_box() else {
log::error!("Could not get export bounding box in load_modify_import_export");
log::error!("Could not get export bounding box in compute_modify_import_export");
continue;
};
let reorder_export_center = (export_bounding_box[0] + export_bounding_box[1]) / 2. + DVec2::new(12., 0.);
@@ -275,16 +271,16 @@ impl NodeNetworkInterface {
}
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
log::error!("Could not get all nodes bounding box in load_export_ports");
log::error!("Could not get all nodes bounding box in import_export_position");
return None;
};
let Some(network) = self.nested_network(network_path) else {
log::error!("Could not get current network in load_export_ports");
log::error!("Could not get current network in import_export_position");
return None;
};
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in load_export_ports");
log::error!("Could not get nested network_metadata in import_export_position");
return None;
};
let node_graph_to_viewport = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport;
@@ -9,19 +9,14 @@ impl NodeNetworkInterface {
/// Unloads everything a node's position feeds: its own geometry, the geometry of every node placed
/// relative to it, and the network bounds. A chain node also sets the width of the layer encapsulating
/// its chain, so that layer reloads too.
///
/// Takes the changed nodes as a batch, so a run of moves walks the upstream cone once.
pub(crate) fn invalidate_positions(&mut self, node_ids: Vec<NodeId>, network_path: &[NodeId]) {
let encapsulating_layers = node_ids
.iter()
.filter(|node_id| self.is_chain(node_id, network_path))
.filter_map(|node_id| self.downstream_layer_for_chain_node(node_id, network_path))
.collect::<Vec<_>>();
for downstream_layer in encapsulating_layers {
pub(crate) fn invalidate_position(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
if self.is_chain(node_id, network_path)
&& let Some(downstream_layer) = self.downstream_layer_for_chain_node(node_id, network_path)
{
self.unload_node_click_targets(&downstream_layer, network_path);
}
self.unload_upstream_node_click_targets(node_ids, network_path);
self.unload_upstream_node_click_targets(vec![*node_id], network_path);
self.unload_all_nodes_bounding_box(network_path);
}
@@ -9,18 +9,18 @@ impl NodeNetworkInterface {
self.position_from_downstream(node_id, network_path, &mut HashSet::new(), &mut HashMap::new())
}
/// The positions of many nodes at once, resolving each one only once.
/// The positions of many nodes at once, sharing one memo so a stack is walked once rather than once per node.
///
/// Asking node by node re-walks the same downstream chain for every node on it, which is quadratic
/// down a tall stack. Sharing one memo across the batch keeps a node reached on someone else.s walk,
/// so the whole set costs one pass. Not cached between calls: a position read between a write and its
/// invalidation would be stale, and the layout code does exactly that.
/// The memo is deliberately not kept between calls, since layout reads positions between a write and its invalidation.
pub(crate) fn positions(&self, node_ids: impl IntoIterator<Item = NodeId>, network_path: &[NodeId]) -> Vec<(NodeId, IVec2)> {
let mut resolved = HashMap::new();
node_ids
.into_iter()
.filter_map(|node_id| {
let position = self.position_from_downstream(&node_id, network_path, &mut HashSet::new(), &mut resolved)?;
let Some(position) = self.position_from_downstream(&node_id, network_path, &mut HashSet::new(), &mut resolved) else {
log::error!("Could not get position for node {node_id}");
return None;
};
Some((node_id, position))
})
.collect()
@@ -54,10 +54,10 @@ impl NodeNetworkInterface {
position
}
/// The position itself, once the memo has been missed and the cycle guard passed.
/// Reads a node's stored position, resolving a stack or chain position against the node it is placed relative to.
fn resolve_position(&self, node_id: &NodeId, network_path: &[NodeId], visited: &mut HashSet<NodeId>, resolved: &mut HashMap<NodeId, IVec2>) -> Option<IVec2> {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in position_from_downstream");
log::error!("Could not get nested node_metadata in resolve_position");
return None;
};
@@ -140,7 +140,7 @@ impl NodeNetworkInterface {
}
self.transaction_modified();
self.invalidate_positions(vec![*node_id], network_path);
self.invalidate_position(node_id, network_path);
}
/// Sets the position of a layer to a stack position
@@ -155,7 +155,7 @@ impl NodeNetworkInterface {
self.transaction_modified();
}
self.invalidate_positions(vec![*node_id], network_path);
self.invalidate_position(node_id, network_path);
}
/// Sets the position of a node to a stack position without changing its y offset
@@ -184,7 +184,7 @@ impl NodeNetworkInterface {
self.transaction_modified();
}
self.invalidate_positions(vec![*node_id], network_path);
self.invalidate_position(node_id, network_path);
}
pub(crate) fn valid_upstream_chain_nodes(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Vec<NodeId> {
@@ -240,7 +240,6 @@ impl NodeNetworkInterface {
/// Input connector is the input to the layer
pub fn try_set_upstream_to_chain(&mut self, input_connector: &InputConnector, network_path: &[NodeId]) {
// If the new input is to a non layer node on the same y position as the input connector, or the input connector is the side input of a layer, then set it to chain position
let valid_upstream_chain_nodes = self.valid_upstream_chain_nodes(input_connector, network_path);
for node_id in &valid_upstream_chain_nodes {
@@ -307,7 +306,6 @@ impl NodeNetworkInterface {
log::error!("Could not get position in set_upstream_chain_to_absolute");
return;
};
// Set any chain nodes to absolute positioning
if self.is_chain(upstream_id, network_path) {
self.set_absolute_position(upstream_id, previous_position, network_path);
// Reload click target of the layer which used to encapsulate the chain
@@ -380,7 +378,6 @@ impl NodeNetworkInterface {
};
if is_layer && outward_wires.len() == 1 && outward_wires[0].input_index() == 0 {
// A layer left feeding the bottom of a node keeps the position it already resolved to
if let Some(downstream_node_id) = outward_wires[0].node_id()
&& self.is_layer(&downstream_node_id, network_path)
{
@@ -397,8 +394,6 @@ impl NodeNetworkInterface {
}
pub fn nodes_sorted_top_to_bottom<'a>(&mut self, node_ids: impl Iterator<Item = &'a NodeId>, network_path: &[NodeId]) -> Option<Vec<NodeId>> {
// Resolved as one batch: every node here is likely on the same stack, so walking each one
// separately would re-walk that stack per node.
let mut node_ids_with_position = self.positions(node_ids.copied(), network_path);
node_ids_with_position.sort_unstable_by_key(|(_, position)| position.y);
@@ -426,7 +421,7 @@ impl NodeNetworkInterface {
if shifted_any {
self.transaction_modified();
}
self.invalidate_positions(vec![*layer], network_path);
self.invalidate_position(layer, network_path);
}
pub fn shift_selected_nodes(&mut self, direction: Direction, shift_without_push: bool, network_path: &[NodeId]) {
@@ -625,7 +620,7 @@ impl NodeNetworkInterface {
}
}
/// Returns every node the shift pushed out of place to where it started, as far as nothing has since
/// Moves every node the shift pushed out of place back to where it started, as far as nothing has since
/// moved into its way. `seed_nodes` are the nodes the caller asked to move, which keep their new place.
fn settle_drag_offsets(&mut self, seed_nodes: &HashSet<NodeId>, network_path: &[NodeId]) {
let Some(stack_dependents) = self
@@ -685,7 +680,6 @@ impl NodeNetworkInterface {
}
fn vertical_shift_with_push(&mut self, node_id: &NodeId, shift_sign: i32, shifted_nodes: &mut HashSet<NodeId>, network_path: &[NodeId]) {
// Do not shift a node more than once
if shifted_nodes.contains(node_id) {
return;
}
@@ -718,7 +712,6 @@ impl NodeNetworkInterface {
}
}
// Shift the nodes that are owned by the layer (if any)
if let Some(owned_nodes) = self.with_owned_nodes_if_loaded(node_id, network_path, |owned_nodes| owned_nodes.clone()) {
for owned_node in owned_nodes {
if self.is_absolute(&owned_node, network_path) {
@@ -732,9 +725,8 @@ impl NodeNetworkInterface {
self.load_all_node_click_targets(network_path);
self.try_load_stack_dependents(network_path);
// Check collisions and for all owned nodes and recursively shift them
let nodes_to_shift = self.with_stack_dependents_if_loaded(network_path, |stack_dependents| {
// Hot path during drags: borrow the owned nodes for the sweep rather than cloning them per call
// Borrow the owned nodes for the sweep rather than cloning them per call
let collect_collisions = |owned_nodes: &HashSet<NodeId>| {
let mut nodes_to_shift = Vec::new();
@@ -858,7 +850,7 @@ impl NodeNetworkInterface {
}
}
self.invalidate_positions(vec![*node_id], network_path);
self.invalidate_position(node_id, network_path);
}
/// The grid rows a node occupies when stacked, as absolute `(top, bottom)` rows. A layer's box starts
@@ -909,10 +901,8 @@ impl NodeNetworkInterface {
self.set_input_for_import(&post_node, layer_output, network_path);
}
NodeInput::Node { .. } => {
// Subsequent child: insert layer between post_node and its current upstream...
// 1. Disconnect old upstream from post_node, wire layer output to post_node
// Subsequent child: the layer takes over the post node's input, and the old upstream moves onto the layer's stack input
self.set_input_for_import(&post_node, layer_output, network_path);
// 2. Wire old upstream into layer's primary (stack) input
self.set_input_for_import(&InputConnector::primary_input(layer.to_node()), post_node_input, network_path);
}
NodeInput::Import { .. } => {
@@ -952,12 +942,11 @@ impl NodeNetworkInterface {
return;
};
// If the moved layer is a child of the new parent, then get its index after the disconnect
if let Some(moved_layer_previous_index) = parent.children(&self.document_metadata).position(|child| child == layer) {
// Adjust the insert index if the layer's previous index is less than the insert index
if moved_layer_previous_index < insert_index {
insert_index -= 1;
}
// A layer already under this parent vacates its own slot when it disconnects, shifting the target down one
if let Some(moved_layer_previous_index) = parent.children(&self.document_metadata).position(|child| child == layer)
&& moved_layer_previous_index < insert_index
{
insert_index -= 1;
}
// Disconnect layer to move
@@ -1043,7 +1032,7 @@ impl NodeNetworkInterface {
let shift = final_layer_position - previous_layer_position;
self.shift_absolute_node_position(&layer.to_node(), shift, network_path);
}
// Move to the top of a stack.
// Move to the top of a stack
NodeInput::Node { node_id, .. } => {
let Some(stack_top_position) = self.position(&node_id, network_path) else {
log::error!("Could not get stack x position in move_layer_to_stack");
@@ -1180,12 +1169,12 @@ impl NodeNetworkInterface {
self.set_input(&InputConnector::primary_input(*node_id), current_input, network_path);
self.set_input(input_connector, NodeInput::node(*node_id, 0), network_path);
// If `set_input` chain-positioned the node (it joined a layer chain), there's nothing more to do.
// If `set_input` chain-positioned the node (it joined a layer chain), there's nothing more to do
if !self.is_absolute(node_id, network_path) {
return;
}
// Otherwise place the node where the displaced feeder was, then shift the feeder's branch left to make room.
// Otherwise place the node where the displaced feeder was, then shift the feeder's branch left to make room
let Some(feeder) = feeder else { return };
let Some(node_position) = self.position(node_id, network_path) else { return };
let Some(feeder_position) = self.position(&feeder, network_path) else { return };
@@ -1198,7 +1187,7 @@ impl NodeNetworkInterface {
return;
}
// Deduplicate, since `UpstreamFlow` can yield a shared node more than once and we must shift each node only once.
// Deduplicate, since `UpstreamFlow` can yield a shared node more than once and each node must shift only once
let upstream_nodes: HashSet<NodeId> = self.upstream_flow_back_from_nodes(vec![feeder], network_path, FlowType::UpstreamFlow).collect();
for upstream_node in &upstream_nodes {
self.shift_node(upstream_node, IVec2::new(-NODE_CHAIN_WIDTH, 0), network_path);
@@ -1236,7 +1225,6 @@ impl NodeNetworkInterface {
self.create_wire(&OutputConnector::primary_output(*node_id), &parent_input, network_path);
}
// Mark this lone node as chain-positioned
self.set_chain_position(node_id, network_path);
}
// Chain already has nodes: splice this node between the parent and the chain's existing final downstream node
@@ -2,62 +2,34 @@ use super::*;
// Public mutable methods
impl NodeNetworkInterface {
/// Walk every network at every nesting level, invoking `visit` with each network's path and a mutable
/// reference to its metadata. Only nodes that contain a nested network are recursed into.
fn for_each_network_metadata_mut(&mut self, mut visit: impl FnMut(&[NodeId], &mut NodeNetworkMetadata)) {
let mut stack = vec![vec![]];
while let Some(path) = stack.pop() {
let Some(self_network_metadata) = self.network_metadata_mut(&path) else {
continue;
};
visit(&path, self_network_metadata);
// Only nodes that contain a nested network have metadata to recurse into, so skip leaf nodes.
stack.extend(
self_network_metadata
.persistent_metadata
.node_metadata
.iter()
.filter(|(_, node_metadata)| node_metadata.persistent_metadata.network_metadata.is_some())
.map(|(node_id, _)| {
let mut current_path: Vec<NodeId> = path.clone();
current_path.push(*node_id);
current_path
}),
);
}
}
pub fn copy_all_navigation_metadata(&mut self, other_interface: &NodeNetworkInterface) {
self.for_each_network_metadata_mut(|path, self_network_metadata| {
self.for_each_network_view_state_mut(|path, view| {
if let Some(other_network_metadata) = other_interface.network_metadata(path) {
self_network_metadata.persistent_metadata.navigation_metadata = other_network_metadata.persistent_metadata.navigation_metadata.clone();
*view.navigation = other_network_metadata.persistent_metadata.navigation_metadata.clone();
}
});
}
/// Copy all transient view and selection state from `other_interface` onto `self` at every nesting level:
/// navigation metadata (pan/zoom), selection undo/redo history, and the document-to-viewport camera. Lets
/// an interface rebuilt from storage keep the user's current view rather than reset it. `resolved_types`
/// is a separate runtime cache the caller handles.
/// an interface rebuilt from storage keep the user's current view rather than reset it.
pub fn copy_all_transient_view_state(&mut self, other_interface: &NodeNetworkInterface) {
self.for_each_network_metadata_mut(|path, self_network_metadata| {
self.for_each_network_view_state_mut(|path, view| {
if let Some(other_network_metadata) = other_interface.network_metadata(path) {
let self_persistent = &mut self_network_metadata.persistent_metadata;
let other_persistent = &other_network_metadata.persistent_metadata;
self_persistent.navigation_metadata = other_persistent.navigation_metadata.clone();
*view.navigation = other_persistent.navigation_metadata.clone();
// The preview is this peer's and survives a rebuild, unless it names a node the rebuilt
// network no longer contains (e.g. after a storage undo), in which case there is nothing
// left to look at.
self_persistent.previewing = match other_persistent.previewing {
Previewing::Yes { previewed } if !self_persistent.node_metadata.contains_key(&previewed.node_id) => Previewing::No,
// The live preview root may name a node that the rebuilt-from-storage network no longer contains
// (e.g. after a storage undo), so only carry it over when the root still exists; otherwise drop it.
*view.previewing = match other_persistent.previewing {
Previewing::Yes {
root_node_to_restore: Some(root_node),
} if !view.nodes.contains_key(&root_node.node_id) => Previewing::No,
previewing => previewing,
};
self_persistent.selection_undo_history = other_persistent.selection_undo_history.clone();
self_persistent.selection_redo_history = other_persistent.selection_redo_history.clone();
*view.selection.undo = other_persistent.selection_undo_history.clone();
*view.selection.redo = other_persistent.selection_redo_history.clone();
}
});
@@ -90,10 +62,11 @@ impl NodeNetworkInterface {
self.edit_input_value(&InputConnector::node_at_index(*node_id, 1), &[], |value| {
let TaggedValue::VectorModification(modification) = value else {
log::error!("Path node {node_id} does not have a modification input");
return;
return false;
};
modification.modify(&modification_type);
modified = true;
true
});
if modified {
@@ -125,9 +98,9 @@ impl NodeNetworkInterface {
self.unload_outward_wires(network_path);
// Update the outward wires and bounding box for all nodes in the encapsulating network
if let Some(encapsulating_network_metadata) = self.encapsulating_network_metadata_mut(network_path) {
encapsulating_network_metadata.transient_metadata.outward_wires.unload();
encapsulating_network_metadata.transient_metadata.all_nodes_bounding_box.unload();
if let Some(encapsulating_transient) = self.encapsulating_network_transient_mut(network_path) {
encapsulating_transient.outward_wires.unload();
encapsulating_transient.all_nodes_bounding_box.unload();
}
// Update the click targets for the encapsulating node, if it exists. There is no encapsulating node if the network is the document network
@@ -142,7 +115,7 @@ impl NodeNetworkInterface {
}
}
/// Inserts a new input at insert index. If the insert index is -1 it is inserted at the end. The output_name is used by the encapsulating node.
/// Inserts a new input at insert index. If the insert index is -1 it is inserted at the end. The input_name is used by the encapsulating node.
pub fn add_import(&mut self, default_value: TaggedValue, exposed: bool, insert_index: isize, input_name: &str, input_description: &str, network_path: &[NodeId]) {
let mut encapsulating_network_path = network_path.to_vec();
let Some(node_id) = encapsulating_network_path.pop() else {
@@ -431,7 +404,7 @@ impl NodeNetworkInterface {
Some(node.replace_inputs(new_inputs, new_input_metadata))
}
/// Used when opening an old document to add the persistent metadata for each input if it doesnt exist, which is where the name/description are saved.
/// Used when opening an old document to add the persistent metadata for each input if it doesn't exist, which is where the name/description are saved.
pub fn validate_input_metadata(&mut self, node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId]) {
let number_of_inputs = node.inputs.len();
let definition = self.reference(node_id, network_path).as_ref().and_then(resolve_document_node_type);
@@ -560,7 +533,7 @@ impl NodeNetworkInterface {
self.set_to_node_or_layer(layer_id, layer_path, false);
}
// A no-op unless one of the two inputs is a wire, which covers every case the match distinguishes
// A no-op unless one of the two inputs is a wire
self.update_outward_wires(network_path, input_connector, &old_input, &new_input);
match (&old_input, &new_input) {
@@ -630,11 +603,10 @@ impl NodeNetworkInterface {
/// Whether writing `new_input` at `input_connector` would leave the network cyclic.
///
/// Asked of the network as it stands, with the proposed input substituted only while the question is
/// answered, so nothing is written and nothing is recorded. An input that is not there reports
/// `true`, so the caller abandons a write that would fail anyway.
/// answered, so nothing is written. An input that is not there reports `true`, so the caller abandons
/// a write that would fail anyway.
///
/// Writing an export can never close a cycle: the dependency graph is built from what nodes take as
/// input, and an export is not something a node can take.
/// Writing an export can never close a cycle, since nothing takes an export as its input.
fn would_create_cycle(&self, input_connector: &InputConnector, new_input: &NodeInput, network_path: &[NodeId]) -> bool {
let InputConnector::Node { node_id, input_index } = input_connector else { return false };
@@ -733,9 +705,7 @@ impl NodeNetworkInterface {
/// Used to insert a group of nodes into the network
pub fn insert_node_group(&mut self, nodes: Vec<(NodeId, NodeTemplate)>, new_ids: HashMap<NodeId, NodeId>, network_path: &[NodeId]) {
for (old_node_id, mut node_template) in nodes {
// Get the new node template
node_template = self.map_ids(node_template, &old_node_id, &new_ids, network_path);
// Insert node into network
let node_id = *new_ids.get(&old_node_id).unwrap();
self.insert_node_entry(NodeLocator::new(node_id, network_path), node_template);
@@ -850,7 +820,7 @@ impl NodeNetworkInterface {
}
}
// Prune this network's pinned display order down to the nodes that still exist, dropping any that were actually removed
// Prune this network's pinned display order down to the nodes that still exist
let surviving_nodes = self.nested_network(network_path).map(|network| network.nodes.keys().copied().collect::<HashSet<_>>());
if let Some(surviving_nodes) = surviving_nodes
&& let Some(mut network) = self.network_mut(network_path)
@@ -858,7 +828,7 @@ impl NodeNetworkInterface {
network.retain_pinned(|node_id| surviving_nodes.contains(node_id));
}
// Purge the deleted nodes' cached wire paths, since the per-node unload can no longer reach them once the nodes are gone
// Purge the deleted nodes' cached wire paths, which the per-node unload can no longer reach
if let Some(network_metadata) = self.network_metadata(network_path) {
network_metadata
.transient_metadata
@@ -868,7 +838,7 @@ impl NodeNetworkInterface {
}
self.unload_all_nodes_bounding_box(network_path);
// Instead of unloaded all node click targets, just unload the nodes upstream from the deleted nodes. unload_upstream_node_click_targets will not work since the nodes have been deleted.
// The per-node unload cannot reach nodes that no longer exist
self.unload_all_nodes_click_targets(network_path);
let Some(selected_nodes) = self.selected_nodes_mut(network_path) else {
log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes");
@@ -879,15 +849,10 @@ impl NodeNetworkInterface {
/// Removes all references to the node with the given id from the network, and reconnects the input to the node below.
pub fn remove_references_from_network(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
// A preview of the node being removed cannot outlive it. A preview of any other node is untouched:
// previewing does not rewire anything, so the reconnection below cannot invalidate it.
if matches!(self.previewing(network_path), Previewing::Yes { previewed } if previewed.node_id == *node_id)
&& let Some(mut network) = self.network_mut(network_path)
{
network.set_previewing(Previewing::No);
}
// TODO: Add more logic to support retaining preview when removing references. Since there are so many edge cases/possible crashes, for now the preview is ended.
self.stop_previewing(network_path);
// Check whether the being-deleted node's first (primary) input is a node
// The wire the downstream inputs reconnect to, which is the first exposed input of the node being removed
let reconnect_to_input = self.document_node(node_id, network_path).and_then(|node| {
node.inputs
.iter()
@@ -895,7 +860,6 @@ impl NodeNetworkInterface {
.filter(|input| matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. }))
.cloned()
});
// Get all upstream references
let number_of_outputs = self.number_of_outputs(node_id, network_path);
let Some(all_outward_wires) = self.outward_wires(network_path) else {
log::error!("Could not get outward wires in remove_references_from_network");
@@ -953,6 +917,34 @@ impl NodeNetworkInterface {
true
}
pub fn start_previewing_without_restore(&mut self, network_path: &[NodeId]) {
// Some logic will have to be performed to prevent the graph positions from being completely changed when the export changes to some previewed node
let Some(mut network) = self.network_mut(network_path) else {
log::error!("Could not get nested network_metadata in start_previewing_without_restore");
return;
};
network.set_previewing(Previewing::Yes { root_node_to_restore: None });
}
fn stop_previewing(&mut self, network_path: &[NodeId]) {
if let Previewing::Yes {
root_node_to_restore: Some(root_node_to_restore),
} = self.previewing(network_path)
{
self.set_input(
&InputConnector::Export(0),
NodeInput::node(root_node_to_restore.node_id, root_node_to_restore.output_index),
network_path,
);
}
let Some(mut network) = self.network_mut(network_path) else {
log::error!("Could not get nested network_metadata in stop_previewing");
return;
};
network.set_previewing(Previewing::No);
}
pub fn set_display_name(&mut self, node_id: &NodeId, display_name: String, network_path: &[NodeId]) {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
log::error!("Could not get node {node_id} in set_display_name");
@@ -995,7 +987,6 @@ impl NodeNetworkInterface {
};
node.set_pinned(pinned);
// Track the node in this network's pinned display order: append when newly pinned, prune when unpinned
if let Some(mut network) = self.network_mut(network_path) {
network.record_pinned(*node_id, pinned);
}
@@ -1147,20 +1138,87 @@ impl NodeNetworkInterface {
self.load_structure();
}
/// Renders `toggle_id` instead of the network's export, or stops doing so if it already is.
///
/// Per-peer and not a change to the document: the export keeps whatever it is wired to, and the
/// compile path substitutes the previewed node into the graph it evaluates. So there is nothing to
/// restore when the preview ends, and nothing another peer would see.
pub fn toggle_preview(&mut self, toggle_id: NodeId, network_path: &[NodeId]) {
let previewing = match self.previewing(network_path) {
Previewing::Yes { previewed } if previewed.node_id == toggle_id => Previewing::No,
_ => Previewing::Yes {
previewed: RootNode { node_id: toggle_id, output_index: 0 },
},
let Some(network) = self.nested_network(network_path) else {
return;
};
// If new_export is None then disconnect
let mut new_export = None;
let mut new_previewing_state = Previewing::No;
if let Some(export) = network.exports.first() {
// If there currently an export
if let NodeInput::Node { node_id, output_index, .. } = export {
let previous_export_id = *node_id;
let previous_output_index = *output_index;
// The export is clicked
if *node_id == toggle_id {
// If the current export is clicked and is being previewed end the preview and set either export back to root node or disconnect
if let Previewing::Yes { root_node_to_restore } = self.previewing(network_path) {
new_export = root_node_to_restore.map(|root_node| root_node.to_connector());
new_previewing_state = Previewing::No;
}
// The export is clicked and there is no preview
else {
new_previewing_state = Previewing::Yes {
root_node_to_restore: Some(RootNode {
node_id: previous_export_id,
output_index: previous_output_index,
}),
};
}
}
// The export is not clicked
else {
new_export = Some(OutputConnector::primary_output(toggle_id));
// There is currently a dashed line being drawn
if let Previewing::Yes { root_node_to_restore } = self.previewing(network_path) {
// There is also a solid line being drawn
if let Some(root_node_to_restore) = root_node_to_restore {
// If the node with the solid line is clicked, then start previewing that node without restore
if root_node_to_restore.node_id == toggle_id {
new_export = Some(OutputConnector::primary_output(toggle_id));
new_previewing_state = Previewing::Yes { root_node_to_restore: None };
} else {
// Root node to restore does not change
new_previewing_state = Previewing::Yes {
root_node_to_restore: Some(root_node_to_restore),
};
}
}
// There is a dashed line without a solid line.
else {
new_previewing_state = Previewing::Yes { root_node_to_restore: None };
}
}
// Not previewing, there is no dashed line being drawn
else {
new_export = Some(OutputConnector::primary_output(toggle_id));
new_previewing_state = Previewing::Yes {
root_node_to_restore: Some(RootNode {
node_id: previous_export_id,
output_index: previous_output_index,
}),
};
}
}
}
// The primary export is disconnected, so preview the node with nothing to restore, which disconnects the export again when the preview ends
else {
new_export = Some(OutputConnector::primary_output(toggle_id));
new_previewing_state = Previewing::Yes { root_node_to_restore: None };
}
}
match new_export {
Some(new_export) => {
self.create_wire(&new_export, &InputConnector::Export(0), network_path);
}
None => {
self.disconnect_input(&InputConnector::Export(0), network_path);
}
}
let Some(mut network) = self.network_mut(network_path) else { return };
network.set_previewing(previewing);
network.set_previewing(new_previewing_state);
}
}
@@ -22,24 +22,6 @@ impl NodeNetworkInterface {
pub fn document_network(&self) -> &NodeNetwork {
self.network.network()
}
/// The document network as it should be evaluated, which is the document itself with the previewed
/// node substituted for the export.
///
/// Previewing is this peer's alone, so it is applied to the copy being compiled rather than written
/// into the document. Every path that compiles the graph goes through here, so none of them can
/// render the export while the user is previewing something else.
pub fn network_to_evaluate(&self) -> NodeNetwork {
let mut network = self.document_network().clone();
if let Previewing::Yes { previewed } = self.previewing(&[])
&& let Some(export) = network.exports.first_mut()
{
*export = NodeInput::node(previewed.node_id, previewed.output_index);
}
network
}
/// Gets the nested network based on network_path
pub fn nested_network(&self, network_path: &[NodeId]) -> Option<&NodeNetwork> {
let Some(network) = self.document_network().nested_network(network_path) else {
@@ -923,32 +905,3 @@ impl NodeNetworkInterface {
Self::from_trees(node_network, network_metadata)
}
}
// Private mutable getters for use within the network interface
impl NodeNetworkInterface {
/// Mutably get the network which the encapsulating node of the currently viewed network is part of. Will always be None in the document network.
pub(super) fn encapsulating_network_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkMetadata> {
let mut encapsulating_path = network_path.to_vec();
encapsulating_path.pop()?;
let Some(parent_metadata) = self.network_metadata_mut(&encapsulating_path) else {
log::error!("Could not get parent network in encapsulating_node_metadata");
return None;
};
Some(parent_metadata)
}
/// Get the node metadata for the node which encapsulates the currently viewed network. Will always be None in the document network.
pub(super) fn encapsulating_node_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut DocumentNodeMetadata> {
let mut encapsulating_path = network_path.to_vec();
let encapsulating_node_id = encapsulating_path.pop()?;
let Some(parent_metadata) = self.network_metadata_mut(&encapsulating_path) else {
log::error!("Could not get parent network in encapsulating_node_metadata");
return None;
};
let Some(encapsulating_node_metadata) = parent_metadata.persistent_metadata.node_metadata.get_mut(&encapsulating_node_id) else {
log::error!("Could not get encapsulating node metadata in encapsulating_node_metadata");
return None;
};
Some(encapsulating_node_metadata)
}
}
@@ -0,0 +1,387 @@
//! Brings the interface into line with the working registry for the entities peers touched, so a remote
//! batch costs deltas for what changed rather than a rebuild of the whole interface.
//!
//! Each touched node is projected to its runtime form and compared with what the interface holds. The
//! difference is applied as the same `EditorDelta`s a local edit records, through `apply`, which mirrors
//! without recording, so nothing here is offered back to the peer that sent it. A node held on one side
//! only is added or removed whole. What a comparison cannot express as a field write, a changed
//! implementation or scope injection, replaces the node.
//!
//! The touched set is an over-approximation: a late-writer-wins loser or an op that failed to apply
//! names an entity that did not change, and the comparison finds nothing to emit for it.
use std::collections::{BTreeSet, HashMap};
use document_graph_storage::to_runtime::ConversionError;
use document_graph_storage::{Declarations, NodeId as StorageNodeId, ROOT_NETWORK, Registry, RuntimeProjection, Touched};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
use graph_craft::runtime_delta::RuntimeDelta;
use super::storage_metadata::{InterfaceRebuildError, node_metadata_from_projection};
use super::{DocumentNodePersistentMetadata, EditorDelta, NetworkMetadataChange, NodeMetadataChange, NodeNetworkInterface};
#[derive(Debug, thiserror::Error)]
pub enum ReconcileError {
/// A declaration the touched nodes need is not cached yet. Nothing was applied; retry once it lands.
#[error("waiting for proto-node declaration {0}")]
DeclarationMissing(document_graph_storage::ResourceId),
#[error("the interface lacks the network at {0:?} that the registry places a node in")]
NetworkMissing(Vec<NodeId>),
#[error(transparent)]
Conversion(ConversionError),
#[error(transparent)]
Metadata(#[from] InterfaceRebuildError),
}
impl From<ConversionError> for ReconcileError {
fn from(error: ConversionError) -> Self {
match error {
ConversionError::DeclarationNotFound(id) => Self::DeclarationMissing(id),
other => Self::Conversion(other),
}
}
}
/// What a reconcile changed, for the caller to unload what those changes feed.
#[derive(Debug, Default)]
pub struct Reconciled {
/// The networks a delta was applied in.
pub networks: BTreeSet<Vec<NodeId>>,
}
/// Where the interface holds each node storage knows, keyed by the identity storage addresses it by.
type StorageIndex = HashMap<StorageNodeId, (Vec<NodeId>, NodeId)>;
impl NodeNetworkInterface {
/// Applies to the interface whatever the registry holds differently for the touched entities.
///
/// Can fail part-way through, leaving some of them reconciled. That is safe to retry with the same
/// touched set, since a reconciled node compares equal and emits nothing, which is what the caller
/// does when a declaration is still on its way; on any other error it rebuilds from the whole registry.
pub(crate) fn reconcile_remote(&mut self, registry: &Registry, declarations: &Declarations, touched: &Touched, peer: document_graph_storage::PeerId) -> Result<Reconciled, ReconcileError> {
let projection = registry.runtime_projection(declarations);
let index = self.pin_storage_identities(peer);
// A touched network is reconciled through the node implementing it, whose comparison covers the
// network's exports and metadata. The root has no such node.
let mut ids = touched.nodes.clone();
let mut root = false;
for &network in &touched.networks {
match projection.owner(network) {
Some(owner) => {
ids.insert(owner);
}
None => root |= network == ROOT_NETWORK,
}
}
// A node the runtime cannot reach and the interface does not hold has nothing to reconcile.
let mut items: Vec<(Vec<NodeId>, NodeId, StorageNodeId)> = ids
.into_iter()
.filter_map(|id| {
let (path, local_id) = projection.node_address(id).or_else(|| index.get(&id).cloned())?;
Some((path, local_id, id))
})
.collect();
// A network's path is a prefix of the paths inside it, so this puts each node after the one
// implementing its network, and a nested node finds its network in place.
items.sort();
let mut reconciled = Reconciled::default();
for (path, local_id, id) in items {
self.reconcile_node(&projection, &index, &path, local_id, id, &mut reconciled)?;
}
if root {
let target = projection.network_entry(ROOT_NETWORK)?;
let current_exports = self.document_network().exports.clone();
let current = &self.document_network_metadata().persistent_metadata;
let mut deltas = Vec::new();
export_deltas(&[], &current_exports, &target.exports, &mut deltas);
network_metadata_deltas(
&[],
current.reference.as_deref(),
&current.pinned_node_order,
target.metadata.reference.as_deref(),
&target.metadata.pinned_order,
&mut deltas,
);
self.apply_reconciled(&[], deltas, &mut reconciled);
}
Ok(reconciled)
}
fn reconcile_node(
&mut self,
projection: &RuntimeProjection,
index: &StorageIndex,
path: &[NodeId],
local_id: NodeId,
id: StorageNodeId,
reconciled: &mut Reconciled,
) -> Result<(), ReconcileError> {
// The interface holds the node somewhere else: under another id, or in a network it has since
// left. That copy goes before the one the registry describes is put in place.
if let Some((held_path, held_id)) = index.get(&id)
&& (held_path.as_slice() != path || *held_id != local_id)
&& self.holds_node(held_path, *held_id)
{
self.apply_reconciled(held_path, vec![remove_node(held_path, *held_id)], reconciled);
}
let stored = projection.node_address(id).is_some();
let held = self.holds_node(path, local_id);
match (stored, held) {
(false, false) => {}
(false, true) => self.apply_reconciled(path, vec![remove_node(path, local_id)], reconciled),
(true, false) => {
if !self.holds_network(path) {
return Err(ReconcileError::NetworkMissing(path.to_vec()));
}
let (node, metadata) = node_metadata_from_projection(projection.node(id)?)?;
let nested = matches!(node.implementation, DocumentNodeImplementation::Network(_));
let deltas = vec![
EditorDelta::Graph(RuntimeDelta::AddNode {
network_path: path.to_vec(),
node_id: local_id,
node: Box::new(node),
}),
EditorDelta::NodeMetadataSnapshot {
network_path: path.to_vec(),
node_id: local_id,
metadata: Box::new(metadata),
},
];
self.apply_reconciled(path, deltas, reconciled);
if nested {
reconciled.networks.insert(nested_path(path, local_id));
}
}
(true, true) => {
let (node, metadata) = node_metadata_from_projection(projection.node(id)?)?;
self.diff_node(path, local_id, node, metadata, reconciled);
}
}
Ok(())
}
/// Emits what differs between the node the interface holds at `path` / `local_id` and `target`, which
/// the registry describes. A network node's contents are left to their own reconciliation: only its
/// exports and its network's metadata are compared here.
fn diff_node(&mut self, path: &[NodeId], local_id: NodeId, target: DocumentNode, target_metadata: DocumentNodePersistentMetadata, reconciled: &mut Reconciled) {
let Some(current) = self.document_network().nested_network(path).and_then(|network| network.nodes.get(&local_id)) else {
return;
};
let Some(current_metadata) = self
.document_network_metadata()
.nested_metadata(path)
.and_then(|network| network.persistent_metadata.node_metadata.get(&local_id))
.map(|node| &node.persistent_metadata)
else {
return;
};
let mut deltas = Vec::new();
let mut nested_changed = false;
let at = |change: NodeMetadataChange| EditorDelta::NodeMetadata {
network_path: path.to_vec(),
node_id: local_id,
change,
};
// What no field write expresses replaces the node whole, and its metadata with it.
if !same_implementation(&current.implementation, &target.implementation) || current.skip_deduplication != target.skip_deduplication {
nested_changed = matches!(target.implementation, DocumentNodeImplementation::Network(_)) || matches!(current.implementation, DocumentNodeImplementation::Network(_));
deltas.push(EditorDelta::Graph(RuntimeDelta::ReplaceNode {
network_path: path.to_vec(),
node_id: local_id,
node: Box::new(target),
}));
deltas.push(EditorDelta::NodeMetadataSnapshot {
network_path: path.to_vec(),
node_id: local_id,
metadata: Box::new(target_metadata),
});
} else {
// The slots first, so the metadata array that indexes them lands on a list of the right length.
if current.inputs.len() != target.inputs.len() {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInputs {
network_path: path.to_vec(),
node_id: local_id,
inputs: target.inputs.clone(),
}));
deltas.push(EditorDelta::NodeInputMetadata {
network_path: path.to_vec(),
node_id: local_id,
input_metadata: target_metadata.input_metadata.clone(),
});
} else {
for (input_index, (held, wanted)) in current.inputs.iter().zip(&target.inputs).enumerate() {
if held != wanted {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInput {
network_path: path.to_vec(),
node_id: local_id,
input_index,
input: wanted.clone(),
}));
}
}
if current_metadata.input_metadata != target_metadata.input_metadata {
deltas.push(EditorDelta::NodeInputMetadata {
network_path: path.to_vec(),
node_id: local_id,
input_metadata: target_metadata.input_metadata.clone(),
});
}
}
// Export slot writes rename the encapsulating node's outputs as a side effect, so the names are
// restated after them whenever the slot count moved.
let mut restate_output_names = false;
if let (DocumentNodeImplementation::Network(held), DocumentNodeImplementation::Network(wanted)) = (&current.implementation, &target.implementation) {
let nested = nested_path(path, local_id);
let before = deltas.len();
export_deltas(&nested, &held.exports, &wanted.exports, &mut deltas);
restate_output_names = held.exports.len() != wanted.exports.len();
let (held_reference, held_order) = current_metadata
.network_metadata
.as_ref()
.map(|network| (network.persistent_metadata.reference.as_deref(), network.persistent_metadata.pinned_node_order.as_slice()))
.unwrap_or((None, &[]));
let (wanted_reference, wanted_order) = target_metadata
.network_metadata
.as_ref()
.map(|network| (network.persistent_metadata.reference.as_deref(), network.persistent_metadata.pinned_node_order.as_slice()))
.unwrap_or((None, &[]));
network_metadata_deltas(&nested, held_reference, held_order, wanted_reference, wanted_order, &mut deltas);
nested_changed = deltas.len() != before;
}
if current.visible != target.visible {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetVisibility {
network_path: path.to_vec(),
node_id: local_id,
visible: target.visible,
}));
}
if current.call_argument != target.call_argument {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetCallArgument {
network_path: path.to_vec(),
node_id: local_id,
call_argument: target.call_argument.clone(),
}));
}
if current.context_features != target.context_features {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetContextFeatures {
network_path: path.to_vec(),
node_id: local_id,
context_features: target.context_features,
}));
}
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
deltas.push(at(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone())));
}
if current_metadata.display_name != target_metadata.display_name {
deltas.push(at(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
}
if current_metadata.locked != target_metadata.locked {
deltas.push(at(NodeMetadataChange::Locked(target_metadata.locked)));
}
if current_metadata.pinned != target_metadata.pinned {
deltas.push(at(NodeMetadataChange::Pinned(target_metadata.pinned)));
}
if restate_output_names || current_metadata.output_names != target_metadata.output_names {
deltas.push(at(NodeMetadataChange::OutputNames(target_metadata.output_names.clone())));
}
}
if deltas.is_empty() {
return;
}
self.apply_reconciled(path, deltas, reconciled);
if nested_changed {
reconciled.networks.insert(nested_path(path, local_id));
}
}
fn apply_reconciled(&mut self, path: &[NodeId], deltas: Vec<EditorDelta>, reconciled: &mut Reconciled) {
if deltas.is_empty() {
return;
}
for delta in &deltas {
self.apply(delta);
}
reconciled.networks.insert(path.to_vec());
}
fn holds_node(&self, path: &[NodeId], local_id: NodeId) -> bool {
self.document_network().nested_network(path).is_some_and(|network| network.nodes.contains_key(&local_id))
&& self
.document_network_metadata()
.nested_metadata(path)
.is_some_and(|network| network.persistent_metadata.node_metadata.contains_key(&local_id))
}
fn holds_network(&self, path: &[NodeId]) -> bool {
self.document_network().nested_network(path).is_some() && self.document_network_metadata().nested_metadata(path).is_some()
}
}
fn remove_node(path: &[NodeId], local_id: NodeId) -> EditorDelta {
EditorDelta::Graph(RuntimeDelta::RemoveNode {
network_path: path.to_vec(),
node_id: local_id,
})
}
fn nested_path(path: &[NodeId], local_id: NodeId) -> Vec<NodeId> {
[path, &[local_id]].concat()
}
/// Whether a field-by-field comparison can bring `current` to `target`, which it cannot across a
/// change of what the node computes.
fn same_implementation(current: &DocumentNodeImplementation, target: &DocumentNodeImplementation) -> bool {
match (current, target) {
(DocumentNodeImplementation::ProtoNode(held), DocumentNodeImplementation::ProtoNode(wanted)) => held == wanted,
(DocumentNodeImplementation::Network(held), DocumentNodeImplementation::Network(wanted)) => held.scope_injections == wanted.scope_injections,
_ => false,
}
}
/// The slot writes taking `current` to `target`: a write per slot that differs, then a removal at the
/// end for each slot too many, which the mirror applies as removals of that index in turn.
fn export_deltas(network_path: &[NodeId], current: &[NodeInput], target: &[NodeInput], deltas: &mut Vec<EditorDelta>) {
for (export_index, input) in target.iter().enumerate() {
if current.get(export_index) != Some(input) {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index,
input: Some(input.clone()),
}));
}
}
for _ in target.len()..current.len() {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: target.len(),
input: None,
}));
}
}
fn network_metadata_deltas(network_path: &[NodeId], current_reference: Option<&str>, current_order: &[NodeId], target_reference: Option<&str>, target_order: &[NodeId], deltas: &mut Vec<EditorDelta>) {
if current_reference != target_reference {
deltas.push(EditorDelta::NetworkMetadata {
network_path: network_path.to_vec(),
change: NetworkMetadataChange::Reference(target_reference.map(str::to_string)),
});
}
if current_order != target_order {
deltas.push(EditorDelta::NetworkMetadata {
network_path: network_path.to_vec(),
change: NetworkMetadataChange::PinnedOrder(target_order.to_vec()),
});
}
}
@@ -15,7 +15,7 @@ use graphene_std::vector::style::RenderMode;
use super::{
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface, NodeNetworkMetadata,
NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ,
NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing,
};
use crate::messages::portfolio::document::overlays::utility_types::OverlaysVisibilitySettings;
use crate::messages::portfolio::document::utility_types::misc::SnappingState;
@@ -147,8 +147,6 @@ impl DocumentSettings<'_> {
}
}
/// Inverse of the position extraction in `NodeMetadataSource::position`.
/// `(Stack, !is_layer)` and `(Chain, is_layer)` shouldn't arise from a faithful round-trip; they fall back to a default of the matching variant.
/// The stored position of a node, which pairs with `is_layer` to reconstruct the runtime node type.
pub fn position_from_runtime(node_type: &NodeTypePersistentMetadata) -> Position {
match node_type {
@@ -163,6 +161,8 @@ pub fn position_from_runtime(node_type: &NodeTypePersistentMetadata) -> Position
}
}
/// Inverse of the position extraction in `NodeMetadataSource::position`.
/// `(Stack, !is_layer)` and `(Chain, is_layer)` shouldn't arise from a faithful round-trip; they fall back to a default of the matching variant.
pub fn position_to_runtime(position: Position, is_layer: bool) -> NodeTypePersistentMetadata {
match (position, is_layer) {
(Position::Absolute([x, y]), true) => NodeTypePersistentMetadata::layer(IVec2::new(x, y)),
@@ -179,9 +179,6 @@ pub fn position_to_runtime(position: Position, is_layer: bool) -> NodeTypePersis
}
/// Builds a `NodeNetworkInterface` from a `NodeNetwork` plus the metadata vecs `Registry::to_runtime_with_full_metadata` emits.
///
/// Sets private fields directly (rather than via public setters) because we're constructing a fresh self-consistent snapshot;
/// the setters' transient-cache invalidation isn't needed.
pub fn build_interface_from_storage(network: NodeNetwork, node_entries: Vec<NodeMetadataEntry>, network_entries: Vec<NetworkMetadataEntry>) -> Result<NodeNetworkInterface, InterfaceRebuildError> {
let mut network_metadata = NodeNetworkMetadata::default();
seed_metadata_tree(&network, &mut network_metadata);
@@ -191,6 +188,47 @@ pub fn build_interface_from_storage(network: NodeNetwork, node_entries: Vec<Node
Ok(NodeNetworkInterface::from_trees(network, network_metadata))
}
/// The runtime node and the persistent metadata for it and everything nested under it, from a
/// single-node projection of the registry. Built through the same entry patching as a whole rebuild, on
/// a tree holding just this node, so a reconciled node matches what a rebuild would hold for it.
pub(super) fn node_metadata_from_projection(projected: document_graph_storage::ProjectedNode) -> Result<(graph_craft::document::DocumentNode, DocumentNodePersistentMetadata), InterfaceRebuildError> {
let document_graph_storage::ProjectedNode {
network_path: prefix,
local_id,
node,
node_entries,
network_entries,
} = projected;
// The entries carry absolute paths; the scratch tree is rooted at the node's own network.
let rebase = |path: Vec<NodeId>| path.get(prefix.len()..).map(<[NodeId]>::to_vec).unwrap_or_default();
let node_entries = node_entries
.into_iter()
.map(|entry| NodeMetadataEntry {
network_path: rebase(entry.network_path),
..entry
})
.collect();
let network_entries = network_entries
.into_iter()
.map(|entry| NetworkMetadataEntry {
network_path: rebase(entry.network_path),
..entry
})
.collect();
let mut scratch = NodeNetwork::default();
scratch.nodes.insert(local_id, node);
let mut metadata = NodeNetworkMetadata::default();
seed_metadata_tree(&scratch, &mut metadata);
apply_entries_into_tree(&scratch, &mut metadata, node_entries)?;
apply_network_entries_into_tree(&mut metadata, network_entries);
let persistent = metadata.persistent_metadata.node_metadata.remove(&local_id).map(|node| node.persistent_metadata).unwrap_or_default();
let node = scratch.nodes.remove(&local_id).expect("inserted above");
Ok((node, persistent))
}
/// Build the runtime-`network_path` -> stable-`NetworkId` map from the `NetworkMetadataEntry`s that
/// `to_runtime_with_full_metadata` emits, so the open path can apply per-network view settings.
pub fn network_ids_from_entries(network_entries: &[NetworkMetadataEntry]) -> HashMap<Vec<NodeId>, document_graph_storage::NetworkId> {
@@ -233,6 +271,13 @@ pub fn collect_network_view_settings(
settings.insert(session::network::NAV_WIDTH.to_string(), value);
}
// Skip the inert `Previewing::No` default so a network that has never been previewed stays empty.
if !matches!(network_metadata.persistent_metadata.previewing, Previewing::No)
&& let Ok(value) = serde_json::to_value(network_metadata.persistent_metadata.previewing)
{
settings.insert(session::network::PREVIEWING.to_string(), value);
}
if !settings.is_empty() {
out.insert(network_id, settings);
}
@@ -271,6 +316,13 @@ pub fn apply_network_view_settings(
{
navigation.node_graph_width = width;
}
if let Some(value) = settings.get(session::network::PREVIEWING)
&& let Ok(previewing) = serde_json::from_value::<Previewing>(value.clone())
&& let Some(mut network) = interface.network_mut(network_path)
{
network.set_previewing(previewing);
}
}
}
@@ -1,936 +0,0 @@
use super::*;
use graph_craft::runtime_delta::RuntimeDelta;
/// Holds one of the two parallel trees so that only this module can write it.
///
/// `Deref` passes reads straight through, so a query reads the tree as though the interface held it
/// directly. There is deliberately no `DerefMut` and the field is private to this module, so the only
/// route to a `&mut` is the store API below, and a write that skips it does not compile rather than
/// silently going unrecorded.
///
/// Transparent to serde, so wrapping a field does not change the document format.
#[derive(Debug, Default, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct Guarded<T>(T);
impl<T> std::ops::Deref for Guarded<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> Guarded<T> {
/// Both of these are private to the store, which is what makes the wrapper worth having: a sibling
/// module can neither write a tree in place nor swap a different one into its place.
fn new(value: T) -> Self {
Self(value)
}
fn get_mut(&mut self) -> &mut T {
&mut self.0
}
}
/// A network's selection undo and redo stacks, borrowed together since every operation on one is
/// paired with one on the other.
pub(crate) struct SelectionHistoryMut<'a> {
pub(crate) undo: &'a mut VecDeque<SelectedNodes>,
pub(crate) redo: &'a mut VecDeque<SelectedNodes>,
}
/// Addresses one node: the network it lives in, and its ID within that network.
///
/// The store is the only place node identity is used for addressing, so this is the one type that
/// changes when identity stops being derived from the node's location.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NodeLocator<'a> {
pub node_id: NodeId,
pub network_path: &'a [NodeId],
}
impl<'a> NodeLocator<'a> {
pub fn new(node_id: NodeId, network_path: &'a [NodeId]) -> Self {
Self { node_id, network_path }
}
/// The path of the network this node owns, if it implements one.
pub fn owned_network_path(&self) -> Vec<NodeId> {
[self.network_path, &[self.node_id]].concat()
}
}
/// The graph and metadata halves of one node, resolved together so the two parallel trees are never
/// reached separately and cannot drift apart.
///
/// Holds the halves directly rather than the interface, so a write cannot reach back out to query the
/// graph or unload a cache: what a write invalidates is declared, not performed here.
pub(crate) struct NodeMut<'a> {
node: &'a mut DocumentNode,
metadata: &'a mut DocumentNodePersistentMetadata,
deltas: NodeDeltas<'a>,
}
/// Where a node's writes record what they changed, carrying the node's address so each setter names
/// what it wrote without its caller repeating it.
struct NodeDeltas<'a> {
deltas: &'a mut Vec<EditorDelta>,
locator: NodeLocator<'a>,
}
impl NodeDeltas<'_> {
fn metadata(&mut self, change: NodeMetadataChange) {
self.deltas.push(EditorDelta::NodeMetadata {
network_path: self.locator.network_path.to_vec(),
node_id: self.locator.node_id,
change,
});
}
/// The nested network a node owns is addressed by the node's own path extended with its ID, which
/// is the path a scoped conversion resolves that network's ID from.
fn owned_network(&mut self, change: NetworkMetadataChange) {
self.deltas.push(EditorDelta::NetworkMetadata {
network_path: self.locator.owned_network_path(),
change,
});
}
fn graph(&mut self, delta: RuntimeDelta) {
self.deltas.push(EditorDelta::Graph(delta));
}
fn input_metadata(&mut self, input_metadata: Vec<InputMetadata>) {
self.deltas.push(EditorDelta::NodeInputMetadata {
network_path: self.locator.network_path.to_vec(),
node_id: self.locator.node_id,
input_metadata,
});
}
fn snapshot(&mut self, metadata: Box<DocumentNodePersistentMetadata>) {
self.deltas.push(EditorDelta::NodeMetadataSnapshot {
network_path: self.locator.network_path.to_vec(),
node_id: self.locator.node_id,
metadata,
});
}
fn network_path(&self) -> Vec<NodeId> {
self.locator.network_path.to_vec()
}
fn node_id(&self) -> NodeId {
self.locator.node_id
}
}
impl NodeMut<'_> {
/// Places the node at an absolute grid position, keeping whether it is displayed as a layer or a node.
pub(crate) fn set_absolute_position(&mut self, position: IVec2) -> bool {
let node_type = match self.metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(_) => NodeTypePersistentMetadata::layer(position),
NodeTypePersistentMetadata::Node(_) => NodeTypePersistentMetadata::node(position),
};
self.set_node_type(node_type)
}
/// Offsets a node that is absolutely positioned, leaving a stack or chain node where it is.
pub(crate) fn shift_absolute_position(&mut self, shift: IVec2) -> bool {
let shifted = match self.metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Absolute(position),
}) => NodeTypePersistentMetadata::layer(position + shift),
NodeTypePersistentMetadata::Node(ref node) => match node.position {
NodePosition::Absolute(position) => NodeTypePersistentMetadata::node(position + shift),
NodePosition::Chain => return false,
},
NodeTypePersistentMetadata::Layer(_) => return false,
};
self.set_node_type(shifted)
}
/// Stacks a layer `y_offset` below the sibling it feeds. Nodes are never stacked.
pub(crate) fn set_stack_position(&mut self, y_offset: u32) -> bool {
if !self.metadata.is_layer() {
return false;
}
self.set_node_type(NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Stack(y_offset),
}))
}
/// Chains a node to the left of the layer it feeds. Layers are never chained.
pub(crate) fn set_chain_position(&mut self) -> bool {
if self.metadata.is_layer() {
return false;
}
self.set_node_type(NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Chain)))
}
/// Whether the node is displayed as a layer, which decides the kinds of position it can hold.
pub(crate) fn is_layer(&self) -> bool {
self.metadata.is_layer()
}
/// Whether the node is rendered, which the compiler reads to replace it with a passthrough.
pub(crate) fn set_visible(&mut self, visible: bool) -> bool {
let changed = self.node.visible != visible;
self.node.visible = visible;
if changed {
let delta = RuntimeDelta::SetVisibility {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
visible,
};
self.deltas.graph(delta);
}
changed
}
/// The type of argument the node can be evaluated with.
pub(crate) fn set_call_argument(&mut self, call_argument: Type) -> bool {
let changed = self.node.call_argument != call_argument;
self.node.call_argument = call_argument;
if changed {
let delta = RuntimeDelta::SetCallArgument {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
call_argument: self.node.call_argument.clone(),
};
self.deltas.graph(delta);
}
changed
}
/// The Extract and Inject annotations the node declares for the Context.
pub(crate) fn set_context_features(&mut self, context_features: ContextDependencies) -> bool {
let changed = self.node.context_features != context_features;
self.node.context_features = context_features;
if changed {
let delta = RuntimeDelta::SetContextFeatures {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
context_features: self.node.context_features,
};
self.deltas.graph(delta);
}
changed
}
/// The user-chosen name for this instance, empty when it has none.
pub(crate) fn set_display_name(&mut self, display_name: String) -> bool {
let changed = self.metadata.display_name != display_name;
self.metadata.display_name = display_name;
if changed {
let change = NodeMetadataChange::DisplayName(self.metadata.display_name.clone());
self.deltas.metadata(change);
}
changed
}
pub(crate) fn set_locked(&mut self, locked: bool) -> bool {
let changed = self.metadata.locked != locked;
self.metadata.locked = locked;
if changed {
self.deltas.metadata(NodeMetadataChange::Locked(locked));
}
changed
}
pub(crate) fn set_pinned(&mut self, pinned: bool) -> bool {
let changed = self.metadata.pinned != pinned;
self.metadata.pinned = pinned;
if changed {
self.deltas.metadata(NodeMetadataChange::Pinned(pinned));
}
changed
}
/// Whether the node is displayed as a layer or a node, together with its position, which are one
/// choice: a layer and a node do not have the same kinds of position.
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
let changed = self.metadata.node_type_metadata != node_type;
self.metadata.node_type_metadata = node_type;
if changed {
let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
self.deltas.metadata(change);
}
changed
}
/// The definition this node's nested network was instantiated from, dropped once the node is edited
/// away from it. Only network nodes carry one.
pub(crate) fn set_reference(&mut self, reference: Option<String>) -> bool {
let Some(network_metadata) = self.metadata.network_metadata.as_mut() else { return false };
let changed = network_metadata.persistent_metadata.reference != reference;
network_metadata.persistent_metadata.reference = reference;
if changed {
let change = NetworkMetadataChange::Reference(network_metadata.persistent_metadata.reference.clone());
self.deltas.owned_network(change);
}
changed
}
pub(crate) fn set_input_name(&mut self, input_index: usize, input_name: String) -> bool {
let Some(input_metadata) = self.metadata.input_metadata.get_mut(input_index) else { return false };
let changed = input_metadata.persistent_metadata.input_name != input_name;
input_metadata.persistent_metadata.input_name = input_name;
if changed {
let change = NodeMetadataChange::InputName {
index: input_index,
name: input_metadata.persistent_metadata.input_name.clone(),
};
self.deltas.metadata(change);
}
changed
}
/// The identifier of the widget override the properties panel uses for this input, or `None` for the
/// widget generated from its type.
pub(crate) fn set_widget_override(&mut self, input_index: usize, widget_override: Option<String>) -> bool {
let Some(input_metadata) = self.metadata.input_metadata.get_mut(input_index) else { return false };
input_metadata.persistent_metadata.widget_override = widget_override;
let change = NodeMetadataChange::WidgetOverride {
index: input_index,
widget_override: input_metadata.persistent_metadata.widget_override.clone(),
};
self.deltas.metadata(change);
true
}
pub(crate) fn set_output_name(&mut self, output_index: usize, output_name: String) -> bool {
let Some(existing) = self.metadata.output_names.get_mut(output_index) else { return false };
let changed = *existing != output_name;
*existing = output_name;
if changed {
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
self.deltas.metadata(change);
}
changed
}
/// The encapsulating node's names for every one of the network's exports, replaced together since
/// they are stored as one array.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn set_output_names(&mut self, output_names: Vec<String>) -> bool {
let changed = self.metadata.output_names != output_names;
self.metadata.output_names = output_names;
if changed {
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
self.deltas.metadata(change);
}
changed
}
/// The metadata array the node's inputs index, one entry per input.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn input_metadata(&self) -> &[InputMetadata] {
&self.metadata.input_metadata
}
/// Grows `output_names` to one entry per export, which an older document may be missing.
pub(crate) fn resize_output_names(&mut self, number_of_exports: usize) {
if self.metadata.output_names.len() == number_of_exports {
return;
}
self.metadata.output_names.resize(number_of_exports, String::new());
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
self.deltas.metadata(change);
}
/// Appends input metadata until there is one entry per input, filling from `defaults` where it has an
/// entry for the added index. Restores the parallel-array invariant for an older document.
pub(crate) fn pad_input_metadata(&mut self, number_of_inputs: usize, defaults: impl Fn(usize) -> Option<InputMetadata>) {
if self.metadata.input_metadata.len() >= number_of_inputs {
return;
}
for added_input_index in self.metadata.input_metadata.len()..number_of_inputs {
self.metadata.input_metadata.push(defaults(added_input_index).unwrap_or_default());
}
self.emit_input_metadata();
}
/// Swaps in a new implementation together with the nested network metadata that belongs to it.
///
/// Replaces the node and everything nested under it, since the nested network goes with the
/// implementation.
pub(crate) fn replace_implementation(&mut self, implementation: DocumentNodeImplementation, network_metadata: Option<NodeNetworkMetadata>) {
self.node.implementation = implementation;
self.metadata.network_metadata = network_metadata;
let delta = RuntimeDelta::ReplaceNode {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
node: Box::new(self.node.clone()),
};
self.deltas.graph(delta);
let metadata = Box::new(self.metadata.clone());
self.deltas.snapshot(metadata);
}
/// Replaces the node's whole persistent metadata, including that of everything nested under it,
/// which is the write a metadata snapshot describes.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn replace_metadata(&mut self, metadata: DocumentNodePersistentMetadata) {
*self.metadata = metadata;
let snapshot = Box::new(self.metadata.clone());
self.deltas.snapshot(snapshot);
}
/// Replaces the metadata array the node's inputs index, leaving the inputs themselves alone.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn set_input_metadata(&mut self, input_metadata: Vec<InputMetadata>) {
self.metadata.input_metadata = input_metadata;
self.emit_input_metadata();
}
/// Swaps in new inputs together with their metadata, returning the inputs replaced.
pub(crate) fn replace_inputs(&mut self, inputs: Vec<NodeInput>, input_metadata: Vec<InputMetadata>) -> Vec<NodeInput> {
self.metadata.input_metadata = input_metadata;
let previous = std::mem::replace(&mut self.node.inputs, inputs);
self.emit_inputs();
previous
}
/// Records the node's input list and the metadata array indexed by it, which change together
/// whenever the number or order of slots does.
fn emit_inputs(&mut self) {
let delta = RuntimeDelta::SetInputs {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
inputs: self.node.inputs.clone(),
};
self.deltas.graph(delta);
self.emit_input_metadata();
}
fn emit_input_metadata(&mut self) {
let input_metadata = self.metadata.input_metadata.clone();
self.deltas.input_metadata(input_metadata);
}
}
/// The persistent metadata of one network, resolved once so a run of writes walks the tree a single time.
///
/// Metadata only: the graph half of a network is its export slots, which are addressed through
/// [`NodeNetworkInterface::set_input_slot`] like any other input.
pub(crate) struct NetworkMut<'a> {
metadata: &'a mut NodeNetworkPersistentMetadata,
deltas: &'a mut Vec<EditorDelta>,
network_path: &'a [NodeId],
}
impl NetworkMut<'_> {
/// Which node the network renders instead of its export.
///
/// Per-peer view state, so this is not recorded: the document is untouched, and the compile path
/// substitutes the previewed node into the graph it evaluates.
pub(crate) fn set_previewing(&mut self, previewing: Previewing) -> bool {
let changed = self.metadata.previewing != previewing;
self.metadata.previewing = previewing;
changed
}
/// The definition this network was instantiated from, dropped once it is edited away from it.
pub(crate) fn set_reference(&mut self, reference: Option<String>) -> bool {
let changed = self.metadata.reference != reference;
self.metadata.reference = reference;
if changed {
let change = NetworkMetadataChange::Reference(self.metadata.reference.clone());
self.emit(change);
}
changed
}
/// The display order of pinned nodes in the Properties panel.
pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec<NodeId>) -> bool {
let changed = self.metadata.pinned_node_order != pinned_node_order;
self.metadata.pinned_node_order = pinned_node_order;
if changed {
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
self.emit(change);
}
changed
}
/// Appends a newly pinned node to the display order, or drops one that is no longer pinned.
pub(crate) fn record_pinned(&mut self, node_id: NodeId, pinned: bool) -> bool {
let order = &mut self.metadata.pinned_node_order;
let changed = match pinned {
true if !order.contains(&node_id) => {
order.push(node_id);
true
}
true => false,
false => {
let before = order.len();
order.retain(|id| *id != node_id);
order.len() != before
}
};
if changed {
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
self.emit(change);
}
changed
}
/// Drops every node the order names that is no longer in the network.
pub(crate) fn retain_pinned(&mut self, surviving: impl Fn(&NodeId) -> bool) -> bool {
let before = self.metadata.pinned_node_order.len();
self.metadata.pinned_node_order.retain(&surviving);
let changed = self.metadata.pinned_node_order.len() != before;
if changed {
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
self.emit(change);
}
changed
}
fn emit(&mut self, change: NetworkMetadataChange) {
self.deltas.push(EditorDelta::NetworkMetadata {
network_path: self.network_path.to_vec(),
change,
});
}
/// The transform from node graph space to viewport space.
pub(crate) fn set_navigation_transform(&mut self, transform: DAffine2) -> bool {
let changed = self.metadata.navigation_metadata.node_graph_to_viewport != transform;
self.metadata.navigation_metadata.node_graph_to_viewport = transform;
changed
}
/// The width of the node graph in viewport space.
pub(crate) fn set_navigation_width(&mut self, node_graph_width: f64) -> bool {
let changed = self.metadata.navigation_metadata.node_graph_width != node_graph_width;
self.metadata.navigation_metadata.node_graph_width = node_graph_width;
changed
}
}
// The store: the only writer of the node graph and its parallel metadata tree. Every write keeps the
// two halves in step by construction, so the invariants checked by `validate_invariants` hold without
// each caller restating them.
impl NodeNetworkInterface {
/// Builds an interface around a freshly-assembled pair of trees, for a document arriving from
/// storage or from an older format rather than being edited into existence.
///
/// The only way to install them, since `Guarded` cannot be constructed outside this module either.
/// Nothing is recorded: the trees are the document, not a set of changes to it.
pub(super) fn from_trees(network: NodeNetwork, network_metadata: NodeNetworkMetadata) -> Self {
Self {
network: Guarded::new(MemoNetwork::new(network)),
network_metadata: Guarded::new(network_metadata),
..Default::default()
}
}
/// The transient caches of a network.
///
/// Deliberately separate from the document write API: unloading a cache is not a change to the
/// document, so there is nothing to record. Handing these out through their own accessor is what
/// lets the document-writing ones stay closed.
pub(super) fn network_transient_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkTransientMetadata> {
Some(&mut self.network_metadata_mut(network_path)?.transient_metadata)
}
/// The transient caches of one node, for the same reason.
pub(super) fn node_transient_mut(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&mut DocumentNodeTransientMetadata> {
let network_metadata = self.network_metadata_mut(network_path)?;
Some(&mut network_metadata.persistent_metadata.node_metadata.get_mut(node_id)?.transient_metadata)
}
/// What the selection was, for the undo and redo of selection alone.
///
/// Stored in the persistent tree but not part of the document: which nodes a peer has selected is
/// that peer's, so these writes are not recorded and do not reach storage.
pub(super) fn selection_history_mut(&mut self, network_path: &[NodeId]) -> Option<SelectionHistoryMut<'_>> {
let persistent = &mut self.network_metadata_mut(network_path)?.persistent_metadata;
Some(SelectionHistoryMut {
undo: &mut persistent.selection_undo_history,
redo: &mut persistent.selection_redo_history,
})
}
/// The graph of the network at `network_path`. Private: every write to it is one of the primitives
/// below, which is what keeps a change from going unrecorded.
fn network_graph_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetwork> {
self.document_network_mut().nested_network_mut(network_path)
}
/// Rewrites the whole graph in place, for a document arriving in an older shape than the current one.
///
/// Nothing is recorded: a migration produces the document the peer should have had rather than
/// changing the one they have. Not a route for editing, which goes through the writes below.
pub(super) fn migrate_graph(&mut self, migrate: impl FnOnce(&mut NodeNetwork)) {
migrate(self.document_network_mut());
}
/// Where the node graph is panned and zoomed to.
///
/// Per-peer view state like the selection: it rides in the persistent tree but is persisted to
/// `session.json` rather than the registry, so these writes are deliberately not recorded.
pub(super) fn navigation_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NavigationMetadata> {
Some(&mut self.network_metadata_mut(network_path)?.persistent_metadata.navigation_metadata)
}
/// The root of the graph tree. The only `&mut` to it in the codebase, since `Guarded` withholds one
/// everywhere else.
fn document_network_mut(&mut self) -> &mut NodeNetwork {
self.network.get_mut().network_mut()
}
/// The metadata tree at `network_path`. The only `&mut` to it, for the same reason.
pub(super) fn network_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkMetadata> {
self.network_metadata.get_mut().nested_metadata_mut(network_path)
}
/// The persistent metadata of a network, or `None` if the network is missing.
pub(crate) fn network_mut<'a>(&'a mut self, network_path: &'a [NodeId]) -> Option<NetworkMut<'a>> {
let metadata = &mut self.network_metadata.get_mut().nested_metadata_mut(network_path)?.persistent_metadata;
Some(NetworkMut {
metadata,
deltas: &mut self.deltas,
network_path,
})
}
/// Both halves of a node, or `None` if either is missing.
pub(crate) fn node_mut<'a>(&'a mut self, locator: NodeLocator<'a>) -> Option<NodeMut<'a>> {
let node = self.network.get_mut().network_mut().nested_network_mut(locator.network_path)?.nodes.get_mut(&locator.node_id)?;
let metadata = self
.network_metadata
.get_mut()
.nested_metadata_mut(locator.network_path)?
.persistent_metadata
.node_metadata
.get_mut(&locator.node_id)?;
Some(NodeMut {
node,
metadata: &mut metadata.persistent_metadata,
deltas: NodeDeltas { deltas: &mut self.deltas, locator },
})
}
/// Inserts an input and its metadata at `index`, clamped to the end. Returns whether the node was found.
pub(crate) fn insert_input_slot(&mut self, locator: NodeLocator, index: usize, input: NodeInput, metadata: InputMetadata) -> bool {
let Some(mut node) = self.node_mut(locator) else {
log::error!("Could not get node {} in _input_slot", locator.node_id);
return false;
};
let index = index.min(node.node.inputs.len());
node.node.inputs.insert(index, input);
node.metadata.input_metadata.insert(index.min(node.metadata.input_metadata.len()), metadata);
node.emit_inputs();
true
}
/// Removes the input at `index` together with its metadata, returning both.
pub(crate) fn remove_input_slot(&mut self, locator: NodeLocator, index: usize) -> Option<(NodeInput, InputMetadata)> {
let Some(mut node) = self.node_mut(locator) else {
log::error!("Could not get node {} in _input_slot", locator.node_id);
return None;
};
if index >= node.node.inputs.len() {
log::error!("Input index {index} out of bounds in remove_input_slot for node {}", locator.node_id);
return None;
}
let input = node.node.inputs.remove(index);
let metadata = (index < node.metadata.input_metadata.len()).then(|| node.metadata.input_metadata.remove(index));
node.emit_inputs();
Some((input, metadata.unwrap_or_default()))
}
/// Moves the input at `from` to `to`, carrying its metadata with it.
///
/// Records the removal and the insertion separately, so the list is briefly one slot short. Both
/// land in the same batch, where the second supersedes the first.
pub(crate) fn move_input_slot(&mut self, locator: NodeLocator, from: usize, to: usize) -> bool {
let Some((input, metadata)) = self.remove_input_slot(locator, from) else { return false };
self.insert_input_slot(locator, to, input, metadata)
}
/// Inserts an export at `index`, clamped to the end, along with the name the encapsulating node shows
/// for it. The document network has no encapsulating node, so it carries no name.
pub(crate) fn insert_export_slot(&mut self, network_path: &[NodeId], index: usize, export: NodeInput, output_name: String) -> bool {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in insert_export_slot");
return false;
};
let index = index.min(network.exports.len());
network.exports.insert(index, export);
if let Some(encapsulating_node_metadata) = self.encapsulating_node_metadata_mut(network_path) {
let output_names = &mut encapsulating_node_metadata.persistent_metadata.output_names;
output_names.insert(index.min(output_names.len()), output_name);
}
self.emit_exports_from(network_path, index, None);
true
}
/// Removes the export at `index` together with the encapsulating node's name for it.
pub(crate) fn remove_export_slot(&mut self, network_path: &[NodeId], index: usize) -> Option<NodeInput> {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in remove_export_slot");
return None;
};
if index >= network.exports.len() {
log::error!("Export index {index} out of bounds in remove_export_slot");
return None;
}
let export = network.exports.remove(index);
// The list shrank by one, so what was the last index now has no slot and has to be cleared.
let vacated = network.exports.len();
if let Some(encapsulating_node_metadata) = self.encapsulating_node_metadata_mut(network_path) {
let output_names = &mut encapsulating_node_metadata.persistent_metadata.output_names;
if index < output_names.len() {
output_names.remove(index);
}
}
self.emit_exports_from(network_path, index, Some(vacated));
Some(export)
}
/// Records every export slot from `index` on, plus a clear for `vacated` when the list shrank.
///
/// Export slots are addressed by index, so inserting or removing one changes the meaning of every
/// later slot and each has to be restated. The encapsulating node's names for them ride along as one
/// whole-array metadata write.
fn emit_exports_from(&mut self, network_path: &[NodeId], index: usize, vacated: Option<usize>) {
let Some(network) = self.network.network().nested_network(network_path) else { return };
let exports: Vec<_> = network.exports.iter().skip(index).cloned().collect();
for (offset, export) in exports.into_iter().enumerate() {
self.deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: index + offset,
input: Some(export),
}));
}
if let Some(vacated) = vacated {
self.deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: vacated,
input: None,
}));
}
let Some((&node_id, parent_path)) = network_path.split_last() else { return };
let Some(metadata) = self.encapsulating_node_metadata(network_path) else { return };
let change = NodeMetadataChange::OutputNames(metadata.persistent_metadata.output_names.clone());
self.deltas.push(EditorDelta::NodeMetadata {
network_path: parent_path.to_vec(),
node_id,
change,
});
}
/// Moves the export at `from` to `to`, carrying the encapsulating node's name for it.
pub(crate) fn move_export_slot(&mut self, network_path: &[NodeId], from: usize, to: usize) -> bool {
let name = self
.encapsulating_node_metadata(network_path)
.and_then(|metadata| metadata.persistent_metadata.output_names.get(from).cloned())
.unwrap_or_default();
let Some(export) = self.remove_export_slot(network_path, from) else { return false };
self.insert_export_slot(network_path, to, export, name)
}
/// Writes the input at `connector`, returning the input it replaced.
pub(crate) fn set_input_slot(&mut self, connector: &InputConnector, network_path: &[NodeId], input: NodeInput) -> Option<NodeInput> {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in set_input_slot");
return None;
};
let slot = match connector {
InputConnector::Node { node_id, input_index } => network.nodes.get_mut(node_id).and_then(|node| node.inputs.get_mut(*input_index)),
InputConnector::Export(export_index) => network.exports.get_mut(*export_index),
};
let Some(slot) = slot else {
log::error!("Could not get input {connector:?} in set_input_slot");
return None;
};
if *slot == input {
return Some(input);
}
let previous = std::mem::replace(slot, input.clone());
self.deltas.push(EditorDelta::Graph(match connector {
InputConnector::Node { node_id, input_index } => RuntimeDelta::SetInput {
network_path: network_path.to_vec(),
node_id: *node_id,
input_index: *input_index,
input,
},
InputConnector::Export(export_index) => RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: *export_index,
input: Some(input),
},
}));
Some(previous)
}
/// Edits the value at `connector` in place, recording the value the edit leaves behind.
///
/// For a change expressed as an operation on the existing value rather than as a replacement of it.
/// Reading the value out, editing it, and writing it back would copy it twice; the recorded delta
/// still carries the whole result, since the storage op is a whole-value write.
pub(crate) fn edit_input_value(&mut self, connector: &InputConnector, network_path: &[NodeId], edit: impl FnOnce(&mut TaggedValue)) -> bool {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in edit_input_value");
return false;
};
let slot = match connector {
InputConnector::Node { node_id, input_index } => network.nodes.get_mut(node_id).and_then(|node| node.inputs.get_mut(*input_index)),
InputConnector::Export(export_index) => network.exports.get_mut(*export_index),
};
let Some(slot) = slot else {
log::error!("Could not get input {connector:?} in edit_input_value");
return false;
};
let Some(mut value) = slot.as_value_mut() else {
log::error!("Input {connector:?} is not a value in edit_input_value");
return false;
};
edit(&mut value);
drop(value);
let input = slot.clone();
self.deltas.push(EditorDelta::Graph(match connector {
InputConnector::Node { node_id, input_index } => RuntimeDelta::SetInput {
network_path: network_path.to_vec(),
node_id: *node_id,
input_index: *input_index,
input,
},
InputConnector::Export(export_index) => RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: *export_index,
input: Some(input),
},
}));
true
}
/// Inserts a node and its metadata, returning the entry it replaced.
pub(crate) fn insert_node_entry(&mut self, locator: NodeLocator, template: NodeTemplate) -> Option<NodeTemplate> {
if !self.network_pair_exists(locator.network_path) {
log::error!("Could not get network {:?} in insert_node_entry", locator.network_path);
return None;
}
let (document_node, persistent_metadata) = template.into_parts();
let node = Box::new(document_node.clone());
let metadata = Box::new(persistent_metadata.clone());
let previous_node = self
.network
.get_mut()
.network_mut()
.nested_network_mut(locator.network_path)?
.nodes
.insert(locator.node_id, document_node);
let previous_metadata = self.network_metadata.get_mut().nested_metadata_mut(locator.network_path)?.persistent_metadata.node_metadata.insert(
locator.node_id,
DocumentNodeMetadata {
persistent_metadata,
transient_metadata: DocumentNodeTransientMetadata::default(),
},
);
// Overwriting an existing entry replaces the node and everything nested under it, which is what
// distinguishes the two from the storage side.
let network_path = locator.network_path.to_vec();
let node_id = locator.node_id;
self.deltas.push(EditorDelta::Graph(match previous_node.is_some() {
true => RuntimeDelta::ReplaceNode {
network_path: network_path.clone(),
node_id,
node,
},
false => RuntimeDelta::AddNode {
network_path: network_path.clone(),
node_id,
node,
},
}));
self.deltas.push(EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata });
previous_node
.zip(previous_metadata)
.map(|(node, metadata)| NodeTemplate::from_parts(node, metadata.persistent_metadata))
}
/// Removes a node and its metadata, returning them joined as a template.
pub(crate) fn remove_node_entry(&mut self, locator: NodeLocator) -> Option<NodeTemplate> {
if !self.network_pair_exists(locator.network_path) {
log::error!("Could not get network {:?} in remove_node_entry", locator.network_path);
return None;
}
let node = self.network.get_mut().network_mut().nested_network_mut(locator.network_path)?.nodes.remove(&locator.node_id);
let metadata = self
.network_metadata
.get_mut()
.nested_metadata_mut(locator.network_path)?
.persistent_metadata
.node_metadata
.remove(&locator.node_id);
if node.is_some() {
self.deltas.push(EditorDelta::Graph(RuntimeDelta::RemoveNode {
network_path: locator.network_path.to_vec(),
node_id: locator.node_id,
}));
}
node.zip(metadata).map(|(node, metadata)| NodeTemplate::from_parts(node, metadata.persistent_metadata))
}
/// Whether both trees hold the network, checked before a write so a missing one cannot leave the two
/// halves out of step.
fn network_pair_exists(&self, network_path: &[NodeId]) -> bool {
self.network.network().nested_network(network_path).is_some() && self.network_metadata.nested_metadata(network_path).is_some()
}
/// Takes what the writes since the last drain changed, in write order, leaving the buffer empty.
pub(crate) fn take_deltas(&mut self) -> Vec<EditorDelta> {
std::mem::take(&mut self.deltas)
}
/// Drops what the writes since the last drain changed, for writes that are not edits to the
/// document. Bringing an old document up to date produces the document rather than changing it, so
/// there is nothing to report.
pub(crate) fn discard_deltas(&mut self) {
self.deltas.clear();
}
/// Drops the network's link to the definition it was instantiated from, which no longer describes it
/// once its signature is edited.
pub(crate) fn clear_encapsulating_reference(&mut self, network_path: &[NodeId]) {
if let Some(mut network) = self.network_mut(network_path) {
network.set_reference(None);
}
}
}
@@ -0,0 +1,140 @@
//! Every route to a mutable reference inside the two trees, gathered here so the whole mutable
//! surface can be read in one place.
//!
//! Two tiers of visibility carry the rule. `pub(super)` reaches only the rest of `store` and hands
//! out the raw trees, so an unrecorded write to the document cannot be spelled outside this module.
//! `pub(in super::super)` reaches the rest of the network interface, and hands out only state the
//! registry never holds: transient caches, and this peer's view state.
use super::*;
impl NodeNetworkInterface {
// ===== Raw trees, reachable only from the store =====
/// The root of the graph tree.
fn document_network_mut(&mut self) -> &mut NodeNetwork {
self.network.get_mut().network_mut()
}
/// The graph of the network at `network_path`, written only by the store's primitives.
pub(super) fn network_graph_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetwork> {
self.document_network_mut().nested_network_mut(network_path)
}
/// The metadata tree at `network_path`.
fn network_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkMetadata> {
self.network_metadata.get_mut().nested_metadata_mut(network_path)
}
/// The metadata of the node that encapsulates the network at `network_path`, or `None` for the
/// document network, which no node encapsulates.
pub(super) fn encapsulating_node_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut DocumentNodeMetadata> {
let mut encapsulating_path = network_path.to_vec();
let encapsulating_node_id = encapsulating_path.pop()?;
self.network_metadata_mut(&encapsulating_path)?.persistent_metadata.node_metadata.get_mut(&encapsulating_node_id)
}
/// Rewrites the whole graph in place, for a document arriving in an older shape than the current one.
///
/// Nothing is recorded: a migration produces the document the peer should have had rather than
/// changing the one they have.
pub(in super::super) fn migrate_graph(&mut self, migrate: impl FnOnce(&mut NodeNetwork)) {
migrate(self.document_network_mut());
}
// ===== Recorded writes =====
/// The persistent metadata of a network, or `None` if the network is missing.
pub(crate) fn network_mut<'a>(&'a mut self, network_path: &'a [NodeId]) -> Option<NetworkMut<'a>> {
let metadata = &mut self.network_metadata.get_mut().nested_metadata_mut(network_path)?.persistent_metadata;
Some(NetworkMut::new(metadata, &mut self.deltas, network_path))
}
/// Both halves of a node, or `None` if either is missing.
pub(crate) fn node_mut<'a>(&'a mut self, locator: NodeLocator<'a>) -> Option<NodeMut<'a>> {
let node = self.network.get_mut().network_mut().nested_network_mut(locator.network_path)?.nodes.get_mut(&locator.node_id)?;
let metadata = self
.network_metadata
.get_mut()
.nested_metadata_mut(locator.network_path)?
.persistent_metadata
.node_metadata
.get_mut(&locator.node_id)?;
Some(NodeMut::new(node, &mut metadata.persistent_metadata, &mut self.deltas, locator))
}
// ===== Unrecorded state, reachable from the whole network interface =====
/// The transient caches of a network, which are not part of the document and so record nothing.
pub(in super::super) fn network_transient_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkTransientMetadata> {
Some(&mut self.network_metadata_mut(network_path)?.transient_metadata)
}
/// The transient caches of one node.
pub(in super::super) fn node_transient_mut(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&mut DocumentNodeTransientMetadata> {
let network_metadata = self.network_metadata_mut(network_path)?;
Some(&mut network_metadata.persistent_metadata.node_metadata.get_mut(node_id)?.transient_metadata)
}
/// The transient caches of the network that the network at `network_path` sits inside.
pub(in super::super) fn encapsulating_network_transient_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkTransientMetadata> {
let mut encapsulating_path = network_path.to_vec();
encapsulating_path.pop()?;
self.network_transient_mut(&encapsulating_path)
}
/// The selection undo and redo stacks. Per-peer state that is not recorded and does not reach storage.
pub(in super::super) fn selection_history_mut(&mut self, network_path: &[NodeId]) -> Option<SelectionHistoryMut<'_>> {
let persistent = &mut self.network_metadata_mut(network_path)?.persistent_metadata;
Some(SelectionHistoryMut {
undo: &mut persistent.selection_undo_history,
redo: &mut persistent.selection_redo_history,
})
}
/// Where the node graph is panned and zoomed to. This write is not recorded.
pub(in super::super) fn navigation_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NavigationMetadata> {
Some(&mut self.network_metadata_mut(network_path)?.persistent_metadata.navigation_metadata)
}
/// Visits every network at every nesting level with its view state, for restoring what the peer was
/// looking at onto an interface rebuilt from storage.
pub(in super::super) fn for_each_network_view_state_mut(&mut self, mut visit: impl FnMut(&[NodeId], NetworkViewStateMut)) {
let mut stack = vec![Vec::new()];
while let Some(network_path) = stack.pop() {
let Some(network_metadata) = self.network_metadata_mut(&network_path) else { continue };
let persistent = &mut network_metadata.persistent_metadata;
stack.extend(
persistent
.node_metadata
.iter()
.filter(|(_, node_metadata)| node_metadata.persistent_metadata.network_metadata.is_some())
.map(|(node_id, _)| [network_path.as_slice(), &[*node_id]].concat()),
);
visit(
&network_path,
NetworkViewStateMut {
navigation: &mut persistent.navigation_metadata,
previewing: &mut persistent.previewing,
selection: SelectionHistoryMut {
undo: &mut persistent.selection_undo_history,
redo: &mut persistent.selection_redo_history,
},
nodes: &persistent.node_metadata,
},
);
}
}
}
/// One network's per-peer view state: what a rebuild restores, and what the registry never records.
pub(crate) struct NetworkViewStateMut<'a> {
pub(crate) navigation: &'a mut NavigationMetadata,
pub(crate) previewing: &'a mut Previewing,
pub(crate) selection: SelectionHistoryMut<'a>,
/// The network's nodes, for a view field that may only name one that still exists.
pub(crate) nodes: &'a HashMap<NodeId, DocumentNodeMetadata>,
}
@@ -0,0 +1,517 @@
//! The recorded-write cursors: the only handles through which a node or a network is edited.
//!
//! Each setter writes its field and records a delta naming exactly what it wrote, so a write cannot
//! reach the document without also reaching the delta buffer.
use super::*;
use graph_craft::runtime_delta::RuntimeDelta;
/// A network's selection undo and redo stacks, borrowed together since every operation on one is
/// paired with one on the other.
pub(crate) struct SelectionHistoryMut<'a> {
pub(crate) undo: &'a mut VecDeque<SelectedNodes>,
pub(crate) redo: &'a mut VecDeque<SelectedNodes>,
}
/// Addresses one node: the network it lives in, and its ID within that network.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NodeLocator<'a> {
pub node_id: NodeId,
pub network_path: &'a [NodeId],
}
impl<'a> NodeLocator<'a> {
pub fn new(node_id: NodeId, network_path: &'a [NodeId]) -> Self {
Self { node_id, network_path }
}
/// The path of the network this node owns, if it implements one.
pub fn owned_network_path(&self) -> Vec<NodeId> {
[self.network_path, &[self.node_id]].concat()
}
}
/// The graph and metadata halves of one node, resolved together so the two parallel trees are never
/// reached separately and cannot drift apart.
///
/// Holds the halves directly rather than the interface, so a write cannot reach back out to query the
/// graph or unload a cache: what a write invalidates is declared, not performed here.
pub(crate) struct NodeMut<'a> {
pub(super) node: &'a mut DocumentNode,
pub(super) metadata: &'a mut DocumentNodePersistentMetadata,
deltas: NodeDeltas<'a>,
}
impl<'a> NodeMut<'a> {
pub(super) fn new(node: &'a mut DocumentNode, metadata: &'a mut DocumentNodePersistentMetadata, deltas: &'a mut Vec<EditorDelta>, locator: NodeLocator<'a>) -> Self {
Self {
node,
metadata,
deltas: NodeDeltas { deltas, locator },
}
}
}
/// Where a node's writes record what they changed, carrying the node's address so each setter names
/// what it wrote without its caller repeating it.
struct NodeDeltas<'a> {
pub(super) deltas: &'a mut Vec<EditorDelta>,
locator: NodeLocator<'a>,
}
impl NodeDeltas<'_> {
fn metadata(&mut self, change: NodeMetadataChange) {
self.deltas.push(EditorDelta::NodeMetadata {
network_path: self.locator.network_path.to_vec(),
node_id: self.locator.node_id,
change,
});
}
/// Records a change to the network this node owns, addressed by the node's path extended with its ID.
fn owned_network(&mut self, change: NetworkMetadataChange) {
self.deltas.push(EditorDelta::NetworkMetadata {
network_path: self.locator.owned_network_path(),
change,
});
}
fn graph(&mut self, delta: RuntimeDelta) {
self.deltas.push(EditorDelta::Graph(delta));
}
fn input_metadata(&mut self, input_metadata: Vec<InputMetadata>) {
self.deltas.push(EditorDelta::NodeInputMetadata {
network_path: self.locator.network_path.to_vec(),
node_id: self.locator.node_id,
input_metadata,
});
}
fn snapshot(&mut self, metadata: Box<DocumentNodePersistentMetadata>) {
self.deltas.push(EditorDelta::NodeMetadataSnapshot {
network_path: self.locator.network_path.to_vec(),
node_id: self.locator.node_id,
metadata,
});
}
/// Records a snapshot for a node inside the network this one owns, for metadata that arrived with a
/// new nested network rather than describing this node.
fn snapshot_owned(&mut self, node_id: NodeId, metadata: Box<DocumentNodePersistentMetadata>) {
self.deltas.push(EditorDelta::NodeMetadataSnapshot {
network_path: self.locator.owned_network_path(),
node_id,
metadata,
});
}
fn network_path(&self) -> Vec<NodeId> {
self.locator.network_path.to_vec()
}
fn node_id(&self) -> NodeId {
self.locator.node_id
}
}
impl NodeMut<'_> {
/// Places the node at an absolute grid position, keeping whether it is displayed as a layer or a node.
pub(crate) fn set_absolute_position(&mut self, position: IVec2) -> bool {
let node_type = match self.metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(_) => NodeTypePersistentMetadata::layer(position),
NodeTypePersistentMetadata::Node(_) => NodeTypePersistentMetadata::node(position),
};
self.set_node_type(node_type)
}
/// Offsets a node that is absolutely positioned, leaving a stack or chain node where it is.
pub(crate) fn shift_absolute_position(&mut self, shift: IVec2) -> bool {
let shifted = match self.metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Absolute(position),
}) => NodeTypePersistentMetadata::layer(position + shift),
NodeTypePersistentMetadata::Node(ref node) => match node.position {
NodePosition::Absolute(position) => NodeTypePersistentMetadata::node(position + shift),
NodePosition::Chain => return false,
},
NodeTypePersistentMetadata::Layer(_) => return false,
};
self.set_node_type(shifted)
}
/// Stacks a layer `y_offset` below the sibling it feeds. Nodes are never stacked.
pub(crate) fn set_stack_position(&mut self, y_offset: u32) -> bool {
if !self.metadata.is_layer() {
return false;
}
self.set_node_type(NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Stack(y_offset),
}))
}
/// Chains a node to the left of the layer it feeds. Layers are never chained.
pub(crate) fn set_chain_position(&mut self) -> bool {
if self.metadata.is_layer() {
return false;
}
self.set_node_type(NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Chain)))
}
/// Whether the node is displayed as a layer, which decides the kinds of position it can hold.
pub(crate) fn is_layer(&self) -> bool {
self.metadata.is_layer()
}
/// Whether the node is rendered, which the compiler reads to replace it with a passthrough.
pub(crate) fn set_visible(&mut self, visible: bool) -> bool {
let changed = self.node.visible != visible;
self.node.visible = visible;
if changed {
let delta = RuntimeDelta::SetVisibility {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
visible,
};
self.deltas.graph(delta);
}
changed
}
/// The type of argument the node can be evaluated with.
pub(crate) fn set_call_argument(&mut self, call_argument: Type) -> bool {
let changed = self.node.call_argument != call_argument;
self.node.call_argument = call_argument;
if changed {
let delta = RuntimeDelta::SetCallArgument {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
call_argument: self.node.call_argument.clone(),
};
self.deltas.graph(delta);
}
changed
}
/// The Extract and Inject annotations the node declares for the Context.
pub(crate) fn set_context_features(&mut self, context_features: ContextDependencies) -> bool {
let changed = self.node.context_features != context_features;
self.node.context_features = context_features;
if changed {
let delta = RuntimeDelta::SetContextFeatures {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
context_features: self.node.context_features,
};
self.deltas.graph(delta);
}
changed
}
/// The user-chosen name for this instance, empty when it has none.
pub(crate) fn set_display_name(&mut self, display_name: String) -> bool {
let changed = self.metadata.display_name != display_name;
self.metadata.display_name = display_name;
if changed {
let change = NodeMetadataChange::DisplayName(self.metadata.display_name.clone());
self.deltas.metadata(change);
}
changed
}
pub(crate) fn set_locked(&mut self, locked: bool) -> bool {
let changed = self.metadata.locked != locked;
self.metadata.locked = locked;
if changed {
self.deltas.metadata(NodeMetadataChange::Locked(locked));
}
changed
}
pub(crate) fn set_pinned(&mut self, pinned: bool) -> bool {
let changed = self.metadata.pinned != pinned;
self.metadata.pinned = pinned;
if changed {
self.deltas.metadata(NodeMetadataChange::Pinned(pinned));
}
changed
}
/// Whether the node is displayed as a layer or a node, together with its position.
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
let changed = self.metadata.node_type_metadata != node_type;
self.metadata.node_type_metadata = node_type;
if changed {
let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
self.deltas.metadata(change);
}
changed
}
/// The definition this node's nested network was instantiated from. Only network nodes carry one.
pub(crate) fn set_reference(&mut self, reference: Option<String>) -> bool {
let Some(network_metadata) = self.metadata.network_metadata.as_mut() else { return false };
let changed = network_metadata.persistent_metadata.reference != reference;
network_metadata.persistent_metadata.reference = reference;
if changed {
let change = NetworkMetadataChange::Reference(network_metadata.persistent_metadata.reference.clone());
self.deltas.owned_network(change);
}
changed
}
pub(crate) fn set_input_name(&mut self, input_index: usize, input_name: String) -> bool {
let Some(input_metadata) = self.metadata.input_metadata.get_mut(input_index) else { return false };
let changed = input_metadata.persistent_metadata.input_name != input_name;
input_metadata.persistent_metadata.input_name = input_name;
if changed {
let change = NodeMetadataChange::InputName {
index: input_index,
name: input_metadata.persistent_metadata.input_name.clone(),
};
self.deltas.metadata(change);
}
changed
}
/// The identifier of the widget override the properties panel uses for this input, or `None` for the
/// widget generated from its type.
pub(crate) fn set_widget_override(&mut self, input_index: usize, widget_override: Option<String>) -> bool {
let Some(input_metadata) = self.metadata.input_metadata.get_mut(input_index) else { return false };
let changed = input_metadata.persistent_metadata.widget_override != widget_override;
input_metadata.persistent_metadata.widget_override = widget_override;
if changed {
let change = NodeMetadataChange::WidgetOverride {
index: input_index,
widget_override: input_metadata.persistent_metadata.widget_override.clone(),
};
self.deltas.metadata(change);
}
changed
}
pub(crate) fn set_output_name(&mut self, output_index: usize, output_name: String) -> bool {
let Some(existing) = self.metadata.output_names.get_mut(output_index) else { return false };
let changed = *existing != output_name;
*existing = output_name;
if changed {
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
self.deltas.metadata(change);
}
changed
}
/// The encapsulating node's names for every one of the network's exports, replaced together since
/// they are stored as one array.
pub(crate) fn set_output_names(&mut self, output_names: Vec<String>) -> bool {
let changed = self.metadata.output_names != output_names;
self.metadata.output_names = output_names;
if changed {
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
self.deltas.metadata(change);
}
changed
}
/// The metadata array the node's inputs index, one entry per input.
pub(crate) fn input_metadata(&self) -> &[InputMetadata] {
&self.metadata.input_metadata
}
/// Grows `output_names` to one entry per export, which an older document may be missing.
pub(crate) fn resize_output_names(&mut self, number_of_exports: usize) {
if self.metadata.output_names.len() == number_of_exports {
return;
}
self.metadata.output_names.resize(number_of_exports, String::new());
let change = NodeMetadataChange::OutputNames(self.metadata.output_names.clone());
self.deltas.metadata(change);
}
/// Appends input metadata until there is one entry per input, filling from `defaults` where it has an
/// entry for the added index. Restores the parallel-array invariant for an older document.
pub(crate) fn pad_input_metadata(&mut self, number_of_inputs: usize, defaults: impl Fn(usize) -> Option<InputMetadata>) {
if self.metadata.input_metadata.len() >= number_of_inputs {
return;
}
for added_input_index in self.metadata.input_metadata.len()..number_of_inputs {
self.metadata.input_metadata.push(defaults(added_input_index).unwrap_or_default());
}
self.emit_input_metadata();
}
/// Swaps in a new implementation together with the nested network metadata that belongs to it.
///
/// Replaces the node and everything nested under it, since the nested network goes with the
/// implementation.
pub(crate) fn replace_implementation(&mut self, implementation: DocumentNodeImplementation, network_metadata: Option<NodeNetworkMetadata>) {
self.node.implementation = implementation;
self.metadata.network_metadata = network_metadata;
let delta = RuntimeDelta::ReplaceNode {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
node: Box::new(self.node.clone()),
};
self.deltas.graph(delta);
// Only what the new implementation brought with it. A swap leaves the node's own metadata alone,
// and restating it would assert values this peer did not write, clobbering a concurrent rename.
let owned: Vec<_> = self
.metadata
.network_metadata
.iter()
.flat_map(|network_metadata| &network_metadata.persistent_metadata.node_metadata)
.map(|(child_id, child)| (*child_id, Box::new(child.persistent_metadata.clone())))
.collect();
for (child_id, metadata) in owned {
self.deltas.snapshot_owned(child_id, metadata);
}
}
/// Replaces the node's whole persistent metadata, including that of everything nested under it,
/// which is the write a metadata snapshot describes.
pub(crate) fn replace_metadata(&mut self, metadata: DocumentNodePersistentMetadata) {
*self.metadata = metadata;
let snapshot = Box::new(self.metadata.clone());
self.deltas.snapshot(snapshot);
}
/// Replaces the metadata array the node's inputs index, leaving the inputs themselves alone.
pub(crate) fn set_input_metadata(&mut self, input_metadata: Vec<InputMetadata>) {
self.metadata.input_metadata = input_metadata;
self.emit_input_metadata();
}
/// Swaps in new inputs together with their metadata, returning the inputs replaced.
pub(crate) fn replace_inputs(&mut self, inputs: Vec<NodeInput>, input_metadata: Vec<InputMetadata>) -> Vec<NodeInput> {
self.metadata.input_metadata = input_metadata;
let previous = std::mem::replace(&mut self.node.inputs, inputs);
self.emit_inputs();
previous
}
/// Records the node's input list and the metadata array indexed by it, which change together
/// whenever the number or order of slots does.
pub(super) fn emit_inputs(&mut self) {
let delta = RuntimeDelta::SetInputs {
network_path: self.deltas.network_path(),
node_id: self.deltas.node_id(),
inputs: self.node.inputs.clone(),
};
self.deltas.graph(delta);
self.emit_input_metadata();
}
fn emit_input_metadata(&mut self) {
let input_metadata = self.metadata.input_metadata.clone();
self.deltas.input_metadata(input_metadata);
}
}
/// The persistent metadata of one network, resolved once so a run of writes walks the tree a single time.
///
/// Metadata only: the graph half of a network is its export slots, which are addressed through
/// [`NodeNetworkInterface::set_input_slot`] like any other input.
pub(crate) struct NetworkMut<'a> {
pub(super) metadata: &'a mut NodeNetworkPersistentMetadata,
pub(super) deltas: &'a mut Vec<EditorDelta>,
pub(super) network_path: &'a [NodeId],
}
impl<'a> NetworkMut<'a> {
pub(super) fn new(metadata: &'a mut NodeNetworkPersistentMetadata, deltas: &'a mut Vec<EditorDelta>, network_path: &'a [NodeId]) -> Self {
Self { metadata, deltas, network_path }
}
}
impl NetworkMut<'_> {
/// Which node the network renders instead of its export. This write is not recorded.
pub(crate) fn set_previewing(&mut self, previewing: Previewing) -> bool {
let changed = self.metadata.previewing != previewing;
self.metadata.previewing = previewing;
changed
}
/// The definition this network was instantiated from.
pub(crate) fn set_reference(&mut self, reference: Option<String>) -> bool {
let changed = self.metadata.reference != reference;
self.metadata.reference = reference;
if changed {
let change = NetworkMetadataChange::Reference(self.metadata.reference.clone());
self.emit(change);
}
changed
}
/// The display order of pinned nodes in the Properties panel.
pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec<NodeId>) -> bool {
let changed = self.metadata.pinned_node_order != pinned_node_order;
self.metadata.pinned_node_order = pinned_node_order;
if changed {
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
self.emit(change);
}
changed
}
/// Appends a newly pinned node to the display order, or drops one that is no longer pinned.
pub(crate) fn record_pinned(&mut self, node_id: NodeId, pinned: bool) -> bool {
let order = &mut self.metadata.pinned_node_order;
let changed = match pinned {
true if !order.contains(&node_id) => {
order.push(node_id);
true
}
true => false,
false => {
let before = order.len();
order.retain(|id| *id != node_id);
order.len() != before
}
};
if changed {
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
self.emit(change);
}
changed
}
/// Drops every node the order names that is no longer in the network.
pub(crate) fn retain_pinned(&mut self, surviving: impl Fn(&NodeId) -> bool) -> bool {
let before = self.metadata.pinned_node_order.len();
self.metadata.pinned_node_order.retain(&surviving);
let changed = self.metadata.pinned_node_order.len() != before;
if changed {
let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone());
self.emit(change);
}
changed
}
fn emit(&mut self, change: NetworkMetadataChange) {
self.deltas.push(EditorDelta::NetworkMetadata {
network_path: self.network_path.to_vec(),
change,
});
}
/// The transform from node graph space to viewport space.
pub(crate) fn set_navigation_transform(&mut self, transform: DAffine2) -> bool {
let changed = self.metadata.navigation_metadata.node_graph_to_viewport != transform;
self.metadata.navigation_metadata.node_graph_to_viewport = transform;
changed
}
/// The width of the node graph in viewport space.
pub(crate) fn set_navigation_width(&mut self, node_graph_width: f64) -> bool {
let changed = self.metadata.navigation_metadata.node_graph_width != node_graph_width;
self.metadata.navigation_metadata.node_graph_width = node_graph_width;
changed
}
}
@@ -0,0 +1,408 @@
use super::*;
use graph_craft::runtime_delta::RuntimeDelta;
mod accessors;
mod cursor;
pub use cursor::NodeLocator;
pub(crate) use cursor::{NetworkMut, NodeMut, SelectionHistoryMut};
/// Holds one of the two parallel trees so that only this module can write it.
///
/// `Deref` passes reads straight through, so a query reads the tree as though the interface held it
/// directly. There is deliberately no `DerefMut` and the field is private to this module, so the only
/// route to a `&mut` is the store API below, and a write that skips it does not compile rather than
/// silently going unrecorded.
///
/// Transparent to serde, so wrapping a field does not change the document format.
#[derive(Debug, Default, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct Guarded<T>(T);
impl<T> std::ops::Deref for Guarded<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> Guarded<T> {
fn new(value: T) -> Self {
Self(value)
}
fn get_mut(&mut self) -> &mut T {
&mut self.0
}
}
// The store: the only writer of the node graph and its parallel metadata tree, keeping the two halves
// in step by construction.
impl NodeNetworkInterface {
/// Builds an interface around a freshly-assembled pair of trees, for a document arriving from
/// storage or from an older format rather than being edited into existence. Nothing is recorded: the
/// trees are the document, not a set of changes to it.
pub(super) fn from_trees(network: NodeNetwork, network_metadata: NodeNetworkMetadata) -> Self {
Self {
network: Guarded::new(MemoNetwork::new(network)),
network_metadata: Guarded::new(network_metadata),
..Default::default()
}
}
/// Inserts an input and its metadata at `index`, clamped to the end. Returns whether the node was found.
pub(crate) fn insert_input_slot(&mut self, locator: NodeLocator, index: usize, input: NodeInput, metadata: InputMetadata) -> bool {
let Some(mut node) = self.node_mut(locator) else {
log::error!("Could not get node {} in insert_input_slot", locator.node_id);
return false;
};
let index = index.min(node.node.inputs.len());
node.node.inputs.insert(index, input);
node.metadata.input_metadata.insert(index.min(node.metadata.input_metadata.len()), metadata);
node.emit_inputs();
true
}
/// Removes the input at `index` together with its metadata, returning both.
pub(crate) fn remove_input_slot(&mut self, locator: NodeLocator, index: usize) -> Option<(NodeInput, InputMetadata)> {
let Some(mut node) = self.node_mut(locator) else {
log::error!("Could not get node {} in remove_input_slot", locator.node_id);
return None;
};
if index >= node.node.inputs.len() {
log::error!("Input index {index} out of bounds in remove_input_slot for node {}", locator.node_id);
return None;
}
let input = node.node.inputs.remove(index);
let metadata = (index < node.metadata.input_metadata.len()).then(|| node.metadata.input_metadata.remove(index));
node.emit_inputs();
Some((input, metadata.unwrap_or_default()))
}
/// Moves the input at `from` to `to`, carrying its metadata with it.
///
/// Records the removal and the insertion separately, so the list is briefly one slot short. Both
/// land in the same batch, where the second supersedes the first.
pub(crate) fn move_input_slot(&mut self, locator: NodeLocator, from: usize, to: usize) -> bool {
let Some((input, metadata)) = self.remove_input_slot(locator, from) else { return false };
self.insert_input_slot(locator, to, input, metadata)
}
/// Inserts an export at `index`, clamped to the end, along with the name the encapsulating node shows
/// for it. The document network has no encapsulating node, so it carries no name.
pub(crate) fn insert_export_slot(&mut self, network_path: &[NodeId], index: usize, export: NodeInput, output_name: String) -> bool {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in insert_export_slot");
return false;
};
let index = index.min(network.exports.len());
network.exports.insert(index, export);
if let Some(encapsulating_node_metadata) = self.encapsulating_node_metadata_mut(network_path) {
let output_names = &mut encapsulating_node_metadata.persistent_metadata.output_names;
output_names.insert(index.min(output_names.len()), output_name);
}
self.emit_exports_from(network_path, index, None);
true
}
/// Removes the export at `index` together with the encapsulating node's name for it.
pub(crate) fn remove_export_slot(&mut self, network_path: &[NodeId], index: usize) -> Option<NodeInput> {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in remove_export_slot");
return None;
};
if index >= network.exports.len() {
log::error!("Export index {index} out of bounds in remove_export_slot");
return None;
}
let export = network.exports.remove(index);
// The list shrank by one, so what was the last index now has no slot and has to be cleared.
let vacated = network.exports.len();
if let Some(encapsulating_node_metadata) = self.encapsulating_node_metadata_mut(network_path) {
let output_names = &mut encapsulating_node_metadata.persistent_metadata.output_names;
if index < output_names.len() {
output_names.remove(index);
}
}
self.emit_exports_from(network_path, index, Some(vacated));
Some(export)
}
/// Records every export slot from `index` on, plus a clear for `vacated` when the list shrank.
///
/// Export slots are addressed by index, so inserting or removing one changes the meaning of every
/// later slot and each has to be restated. The encapsulating node's names for them ride along as one
/// whole-array metadata write.
fn emit_exports_from(&mut self, network_path: &[NodeId], index: usize, vacated: Option<usize>) {
let Some(network) = self.network.network().nested_network(network_path) else { return };
let exports: Vec<_> = network.exports.iter().skip(index).cloned().collect();
for (offset, export) in exports.into_iter().enumerate() {
self.deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: index + offset,
input: Some(export),
}));
}
if let Some(vacated) = vacated {
self.deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: vacated,
input: None,
}));
}
let Some((&node_id, parent_path)) = network_path.split_last() else { return };
let Some(metadata) = self.encapsulating_node_metadata(network_path) else { return };
let change = NodeMetadataChange::OutputNames(metadata.persistent_metadata.output_names.clone());
self.deltas.push(EditorDelta::NodeMetadata {
network_path: parent_path.to_vec(),
node_id,
change,
});
}
/// Moves the export at `from` to `to`, carrying the encapsulating node's name for it.
pub(crate) fn move_export_slot(&mut self, network_path: &[NodeId], from: usize, to: usize) -> bool {
let name = self
.encapsulating_node_metadata(network_path)
.and_then(|metadata| metadata.persistent_metadata.output_names.get(from).cloned())
.unwrap_or_default();
let Some(export) = self.remove_export_slot(network_path, from) else { return false };
self.insert_export_slot(network_path, to, export, name)
}
/// Writes the input at `connector`, returning the input it replaced.
pub(crate) fn set_input_slot(&mut self, connector: &InputConnector, network_path: &[NodeId], input: NodeInput) -> Option<NodeInput> {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in set_input_slot");
return None;
};
let Some(slot) = input_slot_mut(network, connector) else {
log::error!("Could not get input {connector:?} in set_input_slot");
return None;
};
if *slot == input {
return Some(input);
}
let previous = std::mem::replace(slot, input.clone());
self.deltas.push(input_write_delta(connector, network_path, input));
Some(previous)
}
/// Edits the value at `connector` in place, recording the value the edit leaves behind.
///
/// For a change expressed as an operation on the existing value rather than as a replacement of it,
/// which avoids copying the value out and back. The recorded delta still carries the whole result,
/// since the storage op is a whole-value write.
pub(crate) fn edit_input_value(&mut self, connector: &InputConnector, network_path: &[NodeId], edit: impl FnOnce(&mut TaggedValue) -> bool) -> bool {
let Some(network) = self.network_graph_mut(network_path) else {
log::error!("Could not get nested network in edit_input_value");
return false;
};
let Some(slot) = input_slot_mut(network, connector) else {
log::error!("Could not get input {connector:?} in edit_input_value");
return false;
};
let Some(mut value) = slot.as_value_mut() else {
log::error!("Input {connector:?} is not a value in edit_input_value");
return false;
};
// The edit reports whether it changed anything, rather than this comparing before and after.
// Comparing the values would mean copying one out, which is the copy this method exists to avoid,
// and comparing their memoized hashes would let a collision silently drop a real edit.
let changed = edit(&mut value);
drop(value);
// An edit that changes nothing still carries a timestamp, which would let it supersede a concurrent
// peer's real edit to the same input.
if !changed {
return true;
}
let input = slot.clone();
self.deltas.push(input_write_delta(connector, network_path, input));
true
}
/// Inserts a node and its metadata, returning the entry it replaced.
pub(crate) fn insert_node_entry(&mut self, locator: NodeLocator, template: NodeTemplate) -> Option<NodeTemplate> {
if !self.network_pair_exists(locator.network_path) {
log::error!("Could not get network {:?} in insert_node_entry", locator.network_path);
return None;
}
let (document_node, persistent_metadata) = template.into_parts();
let node = Box::new(document_node.clone());
let metadata = Box::new(persistent_metadata.clone());
let previous_node = self
.network
.get_mut()
.network_mut()
.nested_network_mut(locator.network_path)?
.nodes
.insert(locator.node_id, document_node);
let previous_metadata = self.network_metadata.get_mut().nested_metadata_mut(locator.network_path)?.persistent_metadata.node_metadata.insert(
locator.node_id,
DocumentNodeMetadata {
persistent_metadata,
transient_metadata: DocumentNodeTransientMetadata::default(),
},
);
// Overwriting an existing entry replaces the node and everything nested under it, which is what
// distinguishes the two from the storage side.
let network_path = locator.network_path.to_vec();
let node_id = locator.node_id;
self.deltas.push(EditorDelta::Graph(match previous_node.is_some() {
true => RuntimeDelta::ReplaceNode {
network_path: network_path.clone(),
node_id,
node,
},
false => RuntimeDelta::AddNode {
network_path: network_path.clone(),
node_id,
node,
},
}));
self.deltas.push(EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata });
previous_node
.zip(previous_metadata)
.map(|(node, metadata)| NodeTemplate::from_parts(node, metadata.persistent_metadata))
}
/// Removes a node and its metadata, returning them joined as a template.
pub(crate) fn remove_node_entry(&mut self, locator: NodeLocator) -> Option<NodeTemplate> {
if !self.network_pair_exists(locator.network_path) {
log::error!("Could not get network {:?} in remove_node_entry", locator.network_path);
return None;
}
let node = self.network.get_mut().network_mut().nested_network_mut(locator.network_path)?.nodes.remove(&locator.node_id);
let metadata = self
.network_metadata
.get_mut()
.nested_metadata_mut(locator.network_path)?
.persistent_metadata
.node_metadata
.remove(&locator.node_id);
if node.is_some() {
self.deltas.push(EditorDelta::Graph(RuntimeDelta::RemoveNode {
network_path: locator.network_path.to_vec(),
node_id: locator.node_id,
}));
}
node.zip(metadata).map(|(node, metadata)| NodeTemplate::from_parts(node, metadata.persistent_metadata))
}
/// Whether both trees hold the network, checked before a write so a missing one cannot leave the two
/// halves out of step.
fn network_pair_exists(&self, network_path: &[NodeId]) -> bool {
self.network.network().nested_network(network_path).is_some() && self.network_metadata.nested_metadata(network_path).is_some()
}
/// Takes what the writes since the last drain changed, in write order, leaving the buffer empty.
pub(crate) fn take_deltas(&mut self) -> Vec<EditorDelta> {
std::mem::take(&mut self.deltas)
}
/// Drops what the writes since the last drain changed, for writes that are not edits to the document.
pub(crate) fn discard_deltas(&mut self) {
self.deltas.clear();
}
/// Pins every node to the identity storage addresses it by, returning where each is held.
///
/// A node the interface built from storage is already pinned; one created here is addressed by a
/// hash of its location until now, which is what a conversion derives for it anyway. Pinning changes
/// no document content, so nothing is recorded: the identity is a fact about the node, not an edit.
pub(crate) fn pin_storage_identities(&mut self, peer: document_graph_storage::PeerId) -> HashMap<document_graph_storage::NodeId, (Vec<NodeId>, NodeId)> {
let mut index = HashMap::new();
let mut unpinned = Vec::new();
{
let view = super::storage_metadata::StorageMetadataView::new(self);
let resolver = document_graph_storage::PathResolver::new(Some(&view), peer);
let mut stack = vec![(Vec::new(), &*self.network_metadata)];
while let Some((path, metadata)) = stack.pop() {
for (&local_id, node) in &metadata.persistent_metadata.node_metadata {
let storage_id = match node.persistent_metadata.storage_id {
Some(pinned) => document_graph_storage::NodeId(pinned),
None => {
let derived = resolver.node_id(&path, local_id);
unpinned.push((path.clone(), local_id, derived));
derived
}
};
index.insert(storage_id, (path.clone(), local_id));
if let Some(nested) = &node.persistent_metadata.network_metadata {
stack.push(([path.as_slice(), &[local_id]].concat(), nested));
}
}
}
}
for (path, local_id, storage_id) in unpinned {
if let Some(node) = self
.network_metadata
.get_mut()
.nested_metadata_mut(&path)
.and_then(|network| network.persistent_metadata.node_metadata.get_mut(&local_id))
{
node.persistent_metadata.storage_id = Some(storage_id.0);
}
}
index
}
/// Drops the network's link to the definition it was instantiated from, which no longer describes it
/// once its signature is edited.
pub(crate) fn clear_encapsulating_reference(&mut self, network_path: &[NodeId]) {
if let Some(mut network) = self.network_mut(network_path) {
network.set_reference(None);
}
}
}
/// The slot `connector` addresses, whether it is a node's input or one of the network's exports.
fn input_slot_mut<'a>(network: &'a mut NodeNetwork, connector: &InputConnector) -> Option<&'a mut NodeInput> {
match connector {
InputConnector::Node { node_id, input_index } => network.nodes.get_mut(node_id).and_then(|node| node.inputs.get_mut(*input_index)),
InputConnector::Export(export_index) => network.exports.get_mut(*export_index),
}
}
/// What a whole-value write to `connector` records, which is a different delta for an input than for
/// an export.
fn input_write_delta(connector: &InputConnector, network_path: &[NodeId], input: NodeInput) -> EditorDelta {
EditorDelta::Graph(match connector {
InputConnector::Node { node_id, input_index } => RuntimeDelta::SetInput {
network_path: network_path.to_vec(),
node_id: *node_id,
input_index: *input_index,
input,
},
InputConnector::Export(export_index) => RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: *export_index,
input: Some(input),
},
})
}
Loaded 100 of 225 files, more files were not shown because too many files have changed in this diff. Show more