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
449 changed files with 23254 additions and 30653 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/ca7dd793caba8999ec33fde99bb721a69c3d221f.tar.gz
77e8a6b68d67a8d5fcfd6268a6b7938ac9322d877378c6563e933a57df6da821
https://github.com/Keavon/graphite-branded-assets/archive/6687dc6d3d8552948458d00d35e2bee3a40ab66b.tar.gz
7663b4a35f377a5d3363430a725a1d5f634fbdc56adca5e43167786b8fe1b253
+2 -15
View File
@@ -7,15 +7,9 @@ on:
- master
paths:
- website/**
- frontend/eslint.config.js
- frontend/eslint-require-data-selectors.js
- frontend/package-lock.json
pull_request:
paths:
- website/**
- frontend/eslint.config.js
- frontend/eslint-require-data-selectors.js
- frontend/package-lock.json
env:
CARGO_TERM_COLOR: always
INDEX_HTML_HEAD_INCLUSION: <script defer data-domain="graphite.art" data-api="/visit/event" src="/visit/script.hash.js"></script>
@@ -36,10 +30,6 @@ jobs:
uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
cache: npm
cache-dependency-path: |
frontend/package-lock.json
website/package-lock.json
- name: 🕸 Install Zola
uses: taiki-e/install-action@v2
@@ -65,12 +55,9 @@ jobs:
cargo run -p crate-hierarchy-viz -- website/generated
cargo run -p editor-message-tree -- website/generated
- name: 🔧 Install website and frontend npm dependencies
- name: 🔧 Install website npm dependencies
run: |
# The website is linted by the frontend's ESLint config and the tools it installs
cd frontend
npm ci
cd ../website
cd website
npm ci
- name: 📃 Generate node catalog documentation
+2 -22
View File
@@ -61,9 +61,7 @@ in
graphite-bundle = (lib.call ./pkgs/graphite-bundle.nix) { };
graphite-bundle-dev = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
graphite-flatpak-manifest = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { };
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) {
graphite-bundle = graphite-bundle-dev;
};
graphite-flatpak-manifest-dev = (lib.call ./pkgs/graphite-flatpak-manifest.nix) { graphite-bundle = graphite-bundle-dev; };
graphite-cef = lib.call ./pkgs/graphite-cef.nix;
# TODO: graphene-cli = lib.call ./pkgs/graphene-cli.nix;
@@ -72,26 +70,8 @@ in
devShells = withArgs (
{ lib, ... }:
let
shell = lib.makeOverridable (lib.call ./dev.nix);
in
{
default = shell {
desktop = true;
};
full = shell {
desktop = true;
x11 = true;
playwright = true;
};
minimal = shell { };
x11 = shell {
desktop = true;
x11 = true;
};
playwright = shell {
playwright = true;
};
default = lib.call ./dev.nix;
}
);
+5 -6
View File
@@ -1,7 +1,7 @@
{ pkgs, ... }:
let
toolchain = pkgs.rust-bin.nightly."2026-07-03".default.override {
toolchain = pkgs.rust-bin.nightly."2026-04-11".default.override {
extensions = [
"rust-src"
"rust-analyzer"
@@ -32,12 +32,11 @@ let
(finalAttrs: {
pname = "rustc_codegen_spirv";
version = "0.10.0-alpha.1";
src = pkgs.fetchgit {
url = "https://github.com/Rust-GPU/rust-gpu";
rev = "2fff75a21a1909945ac85f5818843dd9960004d7";
sha256 = "sha256-clUt4jUh4D9EmoXZFgur1RrMYob4X5jti2e2hvBnAx8=";
src = pkgs.fetchCrate {
inherit (finalAttrs) pname version;
sha256 = "sha256-zJEpExkPgYzwo7fR4ge4GxJNj7H5yo4bJ4eTOw36+7c=";
};
cargoHash = "sha256-9dGb+RDYpJKaIhkMPkZAx1M1VGE3gMfCD2T84i1VtV8=";
cargoHash = "sha256-J1rtbfGqrL2NJ7Bu2pYfDwCdUmnECB/kzxrpYluA0kY=";
cargoBuildFlags = [
"-p"
"rustc_codegen_spirv"
+52 -80
View File
@@ -3,90 +3,62 @@
deps,
self,
system,
lib,
...
}:
{
desktop ? false,
x11 ? false,
playwright ? false,
}:
let
features = [
{
packages = [
pkgs.pkg-config
libs = [
pkgs.wayland
pkgs.vulkan-loader
pkgs.libGL
pkgs.openssl
pkgs.libraw
pkgs.lld
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_121
pkgs.cargo-about
pkgs.rustc
pkgs.cargo
pkgs.rust-analyzer
pkgs.clippy
pkgs.rustfmt
pkgs.git
pkgs.cargo-nextest
pkgs.cargo-expand
# Linker
pkgs.mold
# Profiling tools
pkgs.gnuplot
pkgs.samply
pkgs.cargo-flamegraph
# Plotting tools
pkgs.graphviz
];
}
deps.rustGPU
(lib.optionalAttrs desktop (
{
libs = [
pkgs.wayland
pkgs.vulkan-loader
pkgs.libGL
pkgs.libxkbcommon
self.packages.${system}.graphite-cef
];
env = {
CEF_PATH = "${self.packages.${system}.graphite-cef}/lib";
XDG_DATA_DIRS = "${pkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${pkgs.gsettings-desktop-schemas.name}:${pkgs.gtk3}/share/gsettings-schemas/${pkgs.gtk3.name}:$XDG_DATA_DIRS";
};
}
))
(lib.optionalAttrs x11 {
libs = [
pkgs.libXcursor
pkgs.libxcb
pkgs.libX11
];
})
(lib.optionalAttrs playwright (
assert pkgs.playwright-driver.version == (lib.importJSON ../tools/web-editor-driver/playwright/package-lock.json).packages."node_modules/playwright-core".version;
{
env = {
PLAYWRIGHT_BROWSERS_PATH = pkgs.playwright-driver.browsers-chromium;
PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS = "true";
};
}
))
# X11 Support
pkgs.libxkbcommon
pkgs.libXcursor
pkgs.libxcb
pkgs.libX11
];
libs = lib.concatMap (feature: feature.libs or [ ]) features;
in
pkgs.mkShell {
packages = libs ++ lib.concatMap (feature: feature.packages or [ ]) features;
env = lib.mergeAttrsList (map (feature: feature.env or { }) features) // {
LD_LIBRARY_PATH = lib.makeLibraryPath libs;
};
}
pkgs.mkShell (
{
packages = libs ++ [
pkgs.pkg-config
pkgs.lld
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_121
pkgs.cargo-about
pkgs.rustc
pkgs.cargo
pkgs.rust-analyzer
pkgs.clippy
pkgs.rustfmt
pkgs.git
pkgs.cargo-nextest
pkgs.cargo-expand
# Linker
pkgs.mold
# Profiling tools
pkgs.gnuplot
pkgs.samply
pkgs.cargo-flamegraph
# Plotting tools
pkgs.graphviz
];
CEF_PATH = self.packages.${system}.graphite-cef;
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}";
XDG_DATA_DIRS = "${pkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${pkgs.gsettings-desktop-schemas.name}:${pkgs.gtk3}/share/gsettings-schemas/${pkgs.gtk3.name}:$XDG_DATA_DIRS";
}
// deps.rustGPU.env
)
+5 -6
View File
@@ -30,13 +30,12 @@ pkgs.cef-binary.overrideAttrs {
postInstall = ''
rm -r $out/* $out/.* || true
strip ./Release/*.so*
mkdir $out/lib
mv ./Release/* $out/lib/
mv ./Release/* $out/
find "./Resources/locales" -maxdepth 1 -type f ! -name 'en-US.pak' -delete
mv ./Resources/* $out/lib/
mv ./include $out/lib/
mv ./Resources/* $out/
mv ./include $out/
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/lib/CREDITS.html.xz
cat ./CREDITS.html | ${pkgs.xz}/bin/xz -9 -e -c > $out/CREDITS.html.xz
echo '${
builtins.toJSON {
@@ -44,6 +43,6 @@ pkgs.cef-binary.overrideAttrs {
name = builtins.baseNameOf url;
sha1 = "";
}
}' > $out/lib/archive.json
}' > $out/archive.json
'';
}
+3 -4
View File
@@ -20,7 +20,6 @@ let
pkgs.libGL
pkgs.openssl
pkgs.libraw
self.packages.${system}.graphite-cef
# X11 Support
pkgs.libxkbcommon
pkgs.libXcursor
@@ -51,7 +50,7 @@ let
pkgs.pkg-config
pkgs.lld
];
env.CEF_PATH = "${self.packages.${system}.graphite-cef}/lib";
env.CEF_PATH = self.packages.${system}.graphite-cef;
buildPhase =
let
profile = if dev then "dev" else "release";
@@ -100,7 +99,7 @@ deps.crane.lib.buildPackage (
RASTER_NODES_SHADER_PATH = self.packages.${system}.graphite-raster-nodes-shaders;
GRAPHITE_GIT_COMMIT_HASH = self.rev or "unknown";
GRAPHITE_GIT_COMMIT_DATE = self.lastModified or "unknown";
CEF_PATH = "${self.packages.${system}.graphite-cef}/lib";
CEF_PATH = self.packages.${system}.graphite-cef;
};
postPatch = ''
@@ -149,7 +148,7 @@ deps.crane.lib.buildPackage (
remove-references-to -t "${common.cargoVendorDir}" $out/bin/graphite
patchelf \
--set-rpath "${pkgs.lib.makeLibraryPath libs}" \
--set-rpath "${pkgs.lib.makeLibraryPath libs}:${self.packages.${system}.graphite-cef}" \
--add-needed libGL.so \
--add-needed libEGL.so \
$out/bin/graphite
Generated
+1835 -235
View File
File diff suppressed because it is too large. Load diff
+11 -16
View File
@@ -11,8 +11,9 @@ members = [
"document/format",
"document/graph-storage",
"document/container",
"document/peer-transport",
"document/live",
"editor",
"editor/control-protocol",
"frontend/wrapper",
"libraries/dyn-any",
"libraries/math-parser",
@@ -36,7 +37,6 @@ members = [
"tools/third-party-licenses",
"tools/editor-message-tree",
"tools/node-docs",
"tools/web-editor-driver",
]
default-members = [
"editor",
@@ -55,7 +55,7 @@ default-members = [
resolver = "2"
[workspace.package]
rust-version = "1.98"
rust-version = "1.88"
edition = "2024"
authors = ["Graphite Authors <[email protected]>"]
homepage = "https://graphite.art"
@@ -79,7 +79,6 @@ preprocessor = { path = "node-graph/preprocessor" }
math-parser = { path = "libraries/math-parser" }
graphene-application-io = { path = "node-graph/libraries/application-io" }
graphene-resource = { path = "node-graph/libraries/resources" }
graphene-animation = { path = "node-graph/libraries/animation" }
core-types = { path = "node-graph/libraries/core-types" }
no-std-types = { path = "node-graph/libraries/no-std-types" }
raster-types = { path = "node-graph/libraries/raster-types" }
@@ -101,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" }
@@ -109,7 +110,6 @@ wgpu-executor = { path = "node-graph/libraries/wgpu-executor" }
wgpu-sync = { path = "libraries/wgpu-sync" }
graphite-proc-macros = { path = "proc-macros" }
graphite-editor = { path = "editor" }
graphite-editor-control-protocol = { path = "editor/control-protocol" }
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
ipsum = { path = "libraries/ipsum" }
@@ -118,7 +118,7 @@ rustc-hash = "2.0"
bytemuck = { version = "1.13", features = ["derive", "min_const_generics"] }
serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = "1.0"
postcard = { version = "1.1", default-features = false, features = ["use-std"] }
rmp-serde = "1.3"
serde_bytes = "0.11"
serde-wasm-bindgen = "0.6"
reqwest = { version = "0.13", features = ["blocking", "json"] }
@@ -127,7 +127,7 @@ env_logger = "0.11"
log = "0.4"
bitflags = { version = "2.4", features = ["serde"] }
ctor = "0.2"
convert_case = "0.12"
convert_case = "0.8"
titlecase = "3.6"
fancy-regex = "0.18.0"
unicode-segmentation = "1.13.2"
@@ -176,6 +176,7 @@ tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-mult
kurbo = { version = "0.13", features = ["serde"] }
vello = "0.10"
vello_encoding = "0.10"
resvg = "0.47"
usvg = "0.47"
simplecss = "0.2"
parley = { version = "0.9", default-features = false, features = ["std"] }
@@ -185,12 +186,10 @@ color = "0.3"
# Linebender ecosystem (END)
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.33", default-features = false, features = [
glam = { version = "0.32.1", default-features = false, features = [
"nostd-libm",
"scalar-math",
"bytemuck",
"debug-glam-assert",
"all-types",
] }
base64 = "0.22"
blake3 = "1.5"
@@ -244,12 +243,8 @@ rfd = "0.17"
open = "5.3"
spin = "0.10"
clap = "4.5"
# Ensure these are kept in sync with .nix/deps/rust-gpu.nix
# Git commit required for glam=0.33 support (TODO: use release when new version is published. Last publish was Apr 17)
spirv-std = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "2fff75a21a1909945ac85f5818843dd9960004d7", features = ["bytemuck"] }
cargo-gpu-install = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "2fff75a21a1909945ac85f5818843dd9960004d7", default-features = false }
spirv-std = { version = "0.10.0-alpha.1", features = ["bytemuck"] }
cargo-gpu-install = { version = "0.10.0-alpha.1", default-features = false }
qrcodegen = "1.8"
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.25"
+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":{"Number":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_deduplicationLine 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":{"Number":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]Line 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::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":{"Number":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":{"Integer":0},"exposed":false}},{"Value":{"tagged_value":{"Number":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"Integer":3},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"Number":0.5},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed"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":{"Number":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<allocLine 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":{"Number":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"Number":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":{"Number":4000.0},"exposed":false}},{"Value":{"tagged_value":{"Number":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":1415828794531Line 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]]]},"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
{"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
-6
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[[bin]]
name = "graphite"
path = "src/main.rs"
-6
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[dependencies]
cef-dll-sys = { workspace = true }
-3
View File
@@ -7,9 +7,6 @@ mod mac;
#[cfg(target_os = "windows")]
mod win;
// Avoid incorrect warnings about an unused dependency (this crate sets `DEP_CEF_DLL_WRAPPER_CEF_DIR` which is used in `build.rs`)
use cef_dll_sys as _;
fn main() {
#[cfg(target_os = "linux")]
linux::main().unwrap();
-3
View File
@@ -5,9 +5,6 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
-6
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[[bin]]
name = "graphite"
path = "src/main.rs"
-6
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
main = ["dep:graphite-desktop"]
helper = ["dep:graphite-desktop-ui"]
-6
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[[bin]]
name = "graphite"
path = "src/main.rs"
+15 -8
View File
@@ -25,7 +25,7 @@ use crate::render::{RenderError, RenderState};
use crate::ui::{InputEvent, UiCommand, UiInstance};
use crate::window::Window;
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction, Preferences};
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
pub(crate) struct App {
render_state: Option<RenderState>,
@@ -99,13 +99,7 @@ impl App {
let wake = Arc::new(move || {
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
});
let desktop_wrapper = DesktopWrapper::new(
rand::rng().random(),
Arc::new(resource_storage),
Arc::new(FolderStore::new(dirs::app_autosave_documents_dir())),
wgpu_context.clone(),
wake,
);
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
Self {
render_state: None,
@@ -313,6 +307,19 @@ impl App {
DesktopFrontendMessage::PersistenceReadState => {
responses.push(DesktopWrapperMessage::LoadPersistedState { state: persist::read_state() });
}
DesktopFrontendMessage::PersistenceReadDocument { id } => {
if let Some(document) = persist::read_document_content(&id) {
responses.push(DesktopWrapperMessage::LoadDocumentContent { id, document });
} else {
tracing::error!("Failed to read document content for {id:?}");
}
}
DesktopFrontendMessage::PersistenceWriteDocument { id, document_serialized_content } => {
persist::write_document_content(id, document_serialized_content);
}
DesktopFrontendMessage::PersistenceDeleteDocument { id } => {
persist::delete_document(&id);
}
DesktopFrontendMessage::PersistenceWritePreferences { preferences } => {
preferences::write(preferences);
}
+52 -50
View File
@@ -1,9 +1,6 @@
use crate::wrapper::messages::PersistedState;
use crate::wrapper::messages::{DocumentId, PersistedState};
pub(crate) fn read_state() -> PersistedState {
if let Err(error) = migrate_documents() {
tracing::error!("Autosave migration failed: {error}");
}
let path = state_file_path();
let data = match std::fs::read_to_string(&path) {
Ok(d) => d,
@@ -16,13 +13,16 @@ pub(crate) fn read_state() -> PersistedState {
return PersistedState::default();
}
};
match ron::from_str(&data) {
let loaded = match ron::from_str(&data) {
Ok(d) => d,
Err(e) => {
tracing::error!("Failed to deserialize persistent data: {e}");
PersistedState::default()
return PersistedState::default();
}
}
};
garbage_collect_document_files(&loaded);
loaded
}
pub(crate) fn write_state(state: PersistedState) {
@@ -37,6 +37,47 @@ pub(crate) fn write_state(state: PersistedState) {
if let Err(e) = std::fs::write(state_file_path(), data) {
tracing::error!("Failed to write persistent data to disk: {e}");
}
garbage_collect_document_files(state);
}
pub(crate) fn write_document_content(id: DocumentId, document_content: String) {
if let Err(e) = std::fs::write(document_content_path(&id), document_content) {
tracing::error!("Failed to write document {id:?} to disk: {e}");
}
}
pub(crate) fn read_document_content(id: &DocumentId) -> Option<String> {
std::fs::read_to_string(document_content_path(id)).ok()
}
pub(crate) fn delete_document(id: &DocumentId) {
if let Err(e) = std::fs::remove_file(document_content_path(id)) {
tracing::error!("Failed to delete document {id:?} from disk: {e}");
}
}
fn garbage_collect_document_files(state: &PersistedState) {
let valid_paths: std::collections::HashSet<_> = state.documents.iter().map(|doc| document_content_path(&doc.id)).collect();
let directory = crate::dirs::app_autosave_documents_dir();
let entries = match std::fs::read_dir(&directory) {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
Err(e) => {
tracing::error!("Failed to read autosave documents directory: {e}");
return;
}
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_file()
&& !valid_paths.contains(&path)
&& let Err(e) = std::fs::remove_file(&path)
{
tracing::error!("Failed to remove orphaned document file {path:?}: {e}");
}
}
}
fn state_file_path() -> std::path::PathBuf {
@@ -45,47 +86,8 @@ fn state_file_path() -> std::path::PathBuf {
path
}
// TODO: Remove this migration code
fn migrate_documents() -> std::io::Result<()> {
let root = crate::dirs::app_autosave_documents_dir();
let entries = match std::fs::read_dir(&root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error),
};
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(error) => {
tracing::error!("Skipping an unreadable autosave entry: {error}");
continue;
}
};
if let Err(error) = migrate_document(&root, &entry) {
tracing::error!("Autosave migration of {} failed: {error}", entry.path().display());
}
}
Ok(())
}
fn migrate_document(root: &std::path::Path, entry: &std::fs::DirEntry) -> std::io::Result<()> {
let path = entry.path();
if !entry.file_type()?.is_file() || path.extension().and_then(|s| s.to_str()) != Some(graphite_desktop_wrapper::FILE_EXTENSION) {
return Ok(());
}
let Some(id) = path.file_stem().and_then(|s| s.to_str()).and_then(|s| u64::from_str_radix(s, 16).ok()) else {
return Ok(());
};
let destination = root.join(format!("{id:016x}"));
if !destination.join("legacy.graphite").exists() && !destination.join("manifest.json").exists() {
std::fs::create_dir_all(&destination)?;
let staging = destination.join("legacy.graphite.migrating");
std::fs::copy(&path, &staging)?;
std::fs::rename(staging, destination.join("legacy.graphite"))?;
}
let backup = path.with_extension(format!("{}.migrated", graphite_desktop_wrapper::FILE_EXTENSION));
if backup.exists() {
return Ok(());
}
std::fs::rename(path, backup)
fn document_content_path(id: &DocumentId) -> std::path::PathBuf {
let mut path = crate::dirs::app_autosave_documents_dir();
path.push(format!("{:x}.{}", id.0, graphite_desktop_wrapper::FILE_EXTENSION));
path
}
-6
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
default = []
embedded_resources = ["dep:graphite-desktop-embedded-resources"]
-6
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
@@ -44,6 +44,10 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
let message = FrontendMessage::UpdateFullscreen { fullscreen };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadDocumentContent { id, document } => {
let message = PersistentStateMessage::LoadDocument { document_id: id, document };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadPersistedState { state } => {
let message = PersistentStateMessage::LoadState { state };
dispatcher.queue_editor_message(message);
@@ -69,6 +69,18 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
FrontendMessage::TriggerPersistenceWriteState { state } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteState { state });
}
FrontendMessage::TriggerPersistenceReadDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceReadDocument { id: document_id });
}
FrontendMessage::TriggerPersistenceDeleteDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceDeleteDocument { id: document_id });
}
FrontendMessage::TriggerPersistenceWriteDocument { document_id, document } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteDocument {
id: document_id,
document_serialized_content: document,
});
}
FrontendMessage::TriggerOpenLaunchDocuments => {
dispatcher.respond(DesktopFrontendMessage::OpenLaunchDocuments);
}
@@ -103,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);
}
+2 -3
View File
@@ -10,7 +10,6 @@ use std::sync::Arc;
pub use graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
pub use graphite_editor::document_store::{DocumentStore, FolderStore};
pub use wgpu_executor::Texture;
pub use wgpu_executor::WgpuBackends;
pub use wgpu_executor::WgpuContext;
@@ -33,7 +32,7 @@ pub struct DesktopWrapper {
}
impl DesktopWrapper {
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn DocumentStore>, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, working_copy_root: std::path::PathBuf, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
#[cfg(target_os = "windows")]
let host = Host::Windows;
#[cfg(target_os = "macos")]
@@ -44,7 +43,7 @@ impl DesktopWrapper {
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
Self {
editor: Editor::new(env, uuid_random_seed, resource_storage, document_store, application_io, schedule_wake),
editor: Editor::new(env, uuid_random_seed, resource_storage, Some(working_copy_root), application_io, schedule_wake),
}
}
+11
View File
@@ -44,6 +44,13 @@ pub enum DesktopFrontendMessage {
enabled: bool,
},
UpdateOverlays(vello::Scene),
PersistenceWriteDocument {
id: DocumentId,
document_serialized_content: String,
},
PersistenceDeleteDocument {
id: DocumentId,
},
PersistenceWritePreferences {
preferences: Preferences,
},
@@ -52,6 +59,9 @@ pub enum DesktopFrontendMessage {
state: PersistedState,
},
PersistenceReadState,
PersistenceReadDocument {
id: DocumentId,
},
UpdateMenu {
entries: Vec<MenuItem>,
},
@@ -82,6 +92,7 @@ pub enum DesktopWrapperMessage {
PollNodeGraphEvaluation,
UpdateMaximized { maximized: bool },
UpdateFullscreen { fullscreen: bool },
LoadDocumentContent { id: DocumentId, document: String },
LoadPersistedState { state: PersistedState },
LoadPreferences { preferences: Preferences },
MenuEvent { id: String },
-4
View File
@@ -134,10 +134,6 @@ pub(crate) mod menu {
// Return None for shortcuts that include mouse motion because we can't show them in native menu
return None;
};
// Native menu shortcuts allow only one non-modifier key, so a shortcut with more (like a double tap) would otherwise trigger on a single press of its last key
if key.is_some() && !matches!(labeled_key.key(), Key::Shift | Key::Control | Key::Alt | Key::Meta | Key::Command | Key::Accel) {
return None;
}
match labeled_key.key() {
Key::Shift => modifiers |= Modifiers::SHIFT,
Key::Control => modifiers |= Modifiers::CONTROL,
-7
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
default = []
zip = ["dep:zip"]
@@ -40,7 +34,6 @@ web-sys = { workspace = true, features = [
"FileSystemFileHandle",
"FileSystemGetFileOptions",
"FileSystemGetDirectoryOptions",
"FileSystemRemoveOptions",
"FileSystemHandle",
"FileSystemHandleKind",
"FileSystemWritableFileStream",
@@ -6,7 +6,6 @@ use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
#[derive(Clone)]
pub struct FolderBackend {
root: PathBuf,
}
+3 -3
View File
@@ -2,11 +2,11 @@
use crate::{ByteHolder, Container, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use std::sync::Mutex;
#[derive(Clone, Default)]
#[derive(Default)]
pub struct MemoryBackend {
files: Arc<Mutex<HashMap<String, Vec<u8>>>>,
files: Mutex<HashMap<String, Vec<u8>>>,
}
impl MemoryBackend {
+11 -67
View File
@@ -3,7 +3,6 @@
use crate::{AsyncContainer, ByteHolder, ContainerError, Result, validate_path, validate_prefix, with_trailing_slash};
use futures::channel::oneshot;
use js_sys::Uint8Array;
use std::cell::Cell;
use std::collections::{HashSet, VecDeque};
use std::sync::{Arc, Mutex};
use wasm_bindgen::JsCast;
@@ -41,33 +40,6 @@ struct Inner {
worker_active: bool,
}
thread_local! {
static LAST_WRITE_FAILURE_ALERT: Cell<Option<f64>> = const { Cell::new(None) };
}
fn report_write_error(operation: &str, path: &str, error: &JsValue) {
if is_not_found(error) {
log::warn!("OPFS {operation} on {path} dropped: the container no longer exists");
return;
}
log::error!("OPFS {operation} failure on {path}:\n{error:?}");
let now = js_sys::Date::now();
// Debounce alerts to avoid spamming the user
if LAST_WRITE_FAILURE_ALERT.get().is_some_and(|last| now - last < 60. * 1000.) {
return;
}
LAST_WRITE_FAILURE_ALERT.set(Some(now));
if let Some(window) = web_sys::window() {
let message = format!(
"Autosave is not working. Save your documents manually to avoid losing changes.\n\n\
Please report it at https://github.com/GraphiteEditor/Graphite/issues/new and include this error:\n\n\
{operation} {path}: {error:?}"
);
let _ = window.alert_with_message(&message);
}
}
#[derive(Clone)]
pub struct OpfsBackend {
inner: Arc<Mutex<Inner>>,
}
@@ -105,6 +77,8 @@ impl OpfsBackend {
guard.queue.push_back(Mutation::Barrier(sender));
kick_worker(&self.inner, &mut guard);
}
// The sender is only dropped without sending if the worker is torn down mid-drain; either way
// there is nothing left to wait for, so a receive error is treated as "already flushed".
let _ = receiver.await;
}
}
@@ -265,12 +239,12 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
match mutation {
Mutation::Write { path, bytes } => {
if let Err(error) = write_file(&directory, &path, &bytes).await {
report_write_error("write", &path, &error);
log::error!("OPFS background write for {path} failed: {error:?}");
}
}
Mutation::Append { path, bytes } => {
if let Err(error) = append_file(&directory, &path, &bytes).await {
report_write_error("append", &path, &error);
log::error!("OPFS background append for {path} failed: {error:?}");
}
}
Mutation::Delete { path } => {
@@ -278,7 +252,7 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
if let Err(error) = remove_file(&directory, &path).await
&& !is_not_found(&error)
{
report_write_error("delete", &path, &error);
log::error!("OPFS background delete for {path} failed: {error:?}");
}
}
// A receive error on the waiter side just means the reader gave up; nothing to apply.
@@ -289,11 +263,16 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
}
}
fn js_err(error: JsValue) -> ContainerError {
ContainerError::Backend(format!("{error:?}"))
}
/// Resolve `directory_path` (a `/`-separated relative path) under the OPFS root, creating each
/// segment. OPFS rejects directory names containing `/`, so a multi-segment path like
/// `documents/<id>` must be descended one segment at a time rather than passed whole.
async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
let mut current = opfs_root().await?;
let storage = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?.navigator().storage();
let mut current: FileSystemDirectoryHandle = JsFuture::from(storage.get_directory()).await?.dyn_into()?;
for segment in directory_path.split('/').filter(|segment| !segment.is_empty()) {
let options = FileSystemGetDirectoryOptions::new();
@@ -304,37 +283,6 @@ async fn open_directory(directory_path: &str) -> std::result::Result<FileSystemD
Ok(current)
}
/// List the subdirectories directly under `directory_path`.
pub async fn list_directories(directory_path: &str) -> Result<Vec<String>> {
crate::validate_prefix(directory_path)?;
let root = opfs_root().await.map_err(js_err)?;
list_entries(&root, directory_path, EntryKind::Directory).await.map_err(|error| list_error(directory_path, error))
}
/// Remove `directory_path` recursively.
pub async fn remove_directory(directory_path: &str) -> Result<()> {
validate_path(directory_path)?;
let root = opfs_root().await.map_err(js_err)?;
let removed = async {
let (parent, name) = descend(&root, directory_path, false).await?;
let options = web_sys::FileSystemRemoveOptions::new();
options.set_recursive(true);
JsFuture::from(parent.remove_entry_with_options(name, &options)).await
}
.await;
match removed {
Ok(_) => Ok(()),
Err(error) if is_not_found(&error) => Ok(()),
Err(error) => Err(js_err(error)),
}
}
async fn opfs_root() -> std::result::Result<FileSystemDirectoryHandle, JsValue> {
let storage = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?.navigator().storage();
JsFuture::from(storage.get_directory()).await?.dyn_into()
}
/// Descend the `/`-separated path against `root` and return the directory handle plus the final segment.
async fn descend<'a>(root: &FileSystemDirectoryHandle, relative: &'a str, create_dirs: bool) -> std::result::Result<(FileSystemDirectoryHandle, &'a str), JsValue> {
let mut current = root.clone();
@@ -525,7 +473,3 @@ fn list_error(prefix: &str, error: JsValue) -> ContainerError {
js_err(error)
}
}
fn js_err(error: JsValue) -> ContainerError {
ContainerError::Backend(format!("{error:?}"))
}
-2
View File
@@ -12,7 +12,6 @@
pub mod archive;
pub mod backends;
pub mod store;
pub enum ByteHolder {
/// Bytes synthesized in memory (decompressed from an archive, produced by serialization).
@@ -351,7 +350,6 @@ impl<C: Container + ?Sized> AsyncContainer for C {
/// `AsyncContainer::read` returns `impl Future`, so `dyn AsyncContainer` is not object-safe.
/// `AnyContainer` is the workaround: `Gdd` holds one of these by value, and the `AsyncContainer`
/// impl forwards to the active variant.
#[derive(Clone)]
pub enum AnyContainer {
Memory(backends::memory::MemoryBackend),
#[cfg(not(target_family = "wasm"))]
-145
View File
@@ -1,145 +0,0 @@
use crate::backends::memory::MemoryBackend;
use crate::{AnyContainer, Result};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Mutex;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DocumentKey(pub u64);
#[cfg(not(target_family = "wasm"))]
pub type StoreFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'a>>;
#[cfg(target_family = "wasm")]
pub type StoreFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + 'a>>;
pub trait DocumentStore: Send + Sync {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>>;
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer>;
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()>;
}
fn directory_name(key: DocumentKey) -> String {
format!("{:016x}", key.0)
}
fn parse_directory_name(name: &str) -> Option<DocumentKey> {
(name.len() == 16 && name.bytes().all(|byte| byte.is_ascii_hexdigit()))
.then(|| u64::from_str_radix(name, 16).ok().map(DocumentKey))
.flatten()
}
#[derive(Default)]
pub struct MemoryStore {
documents: Mutex<HashMap<DocumentKey, MemoryBackend>>,
}
impl DocumentStore for MemoryStore {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>> {
let mut keys: Vec<_> = self.documents.lock().unwrap().keys().copied().collect();
keys.sort();
Box::pin(async move { Ok(keys) })
}
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer> {
let backend = self.documents.lock().unwrap().entry(key).or_default().clone();
Box::pin(async move { Ok(AnyContainer::Memory(backend)) })
}
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()> {
self.documents.lock().unwrap().remove(&key);
Box::pin(async { Ok(()) })
}
}
#[cfg(not(target_family = "wasm"))]
pub struct FolderStore {
root: std::path::PathBuf,
}
#[cfg(not(target_family = "wasm"))]
impl FolderStore {
pub fn new(root: impl Into<std::path::PathBuf>) -> Self {
Self { root: root.into() }
}
}
#[cfg(not(target_family = "wasm"))]
impl DocumentStore for FolderStore {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>> {
Box::pin(async {
let entries = match std::fs::read_dir(&self.root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(error.into()),
};
let mut keys: Vec<_> = entries
.filter_map(|entry| entry.ok())
.filter(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_dir()))
.filter_map(|entry| parse_directory_name(&entry.file_name().to_string_lossy()))
.collect();
keys.sort();
Ok(keys)
})
}
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer> {
Box::pin(async move {
let backend = crate::backends::folder::FolderBackend::create(self.root.join(directory_name(key)))?;
Ok(AnyContainer::Folder(backend))
})
}
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()> {
Box::pin(async move {
match std::fs::remove_dir_all(self.root.join(directory_name(key))) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
}
})
}
}
#[cfg(target_family = "wasm")]
pub struct OpfsStore {
root: String,
}
#[cfg(target_family = "wasm")]
impl OpfsStore {
pub fn new(root: impl Into<String>) -> Self {
Self {
root: root.into().trim_matches('/').to_string(),
}
}
fn document_path(&self, key: DocumentKey) -> String {
let name = directory_name(key);
if self.root.is_empty() { name } else { format!("{}/{name}", self.root) }
}
}
#[cfg(target_family = "wasm")]
impl DocumentStore for OpfsStore {
fn list(&self) -> StoreFuture<'_, Vec<DocumentKey>> {
Box::pin(async {
let paths = crate::backends::opfs::list_directories(&self.root).await?;
let mut keys: Vec<_> = paths.iter().filter_map(|path| parse_directory_name(path.rsplit('/').next()?)).collect();
keys.sort();
Ok(keys)
})
}
fn open(&self, key: DocumentKey) -> StoreFuture<'_, AnyContainer> {
Box::pin(async move {
let backend = crate::backends::opfs::OpfsBackend::open(&self.document_path(key)).await?;
Ok(AnyContainer::Opfs(backend))
})
}
fn remove(&self, key: DocumentKey) -> StoreFuture<'_, ()> {
Box::pin(async move { crate::backends::opfs::remove_directory(&self.document_path(key)).await })
}
}
-12
View File
@@ -176,15 +176,3 @@ fn folder_backend_write_sized_fills_via_mmap() {
let read_back = backend.read("resources/sized").unwrap();
assert_eq!(read_back.as_slice(), payload);
}
#[test]
fn memory_backend_clones_share_the_store() {
let backend = MemoryBackend::new();
let clone = backend.clone();
backend.write("file", b"through the original").unwrap();
assert_eq!(clone.read("file").unwrap().as_slice(), b"through the original");
clone.remove("file").unwrap();
assert!(!backend.exists("file"));
}
+5 -8
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
# Runtime bridge: the editor <-> storage conversion methods (stage/commit from a `NodeNetwork`,
# `network_ids`, `declarations`). Off lets a standalone migration tool build without `graph-craft`
@@ -23,17 +17,20 @@ 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 }
serde = { workspace = true }
serde_json = { workspace = true }
postcard = { workspace = true }
rmp-serde = { workspace = true }
futures = { workspace = true }
thiserror = "2.0"
log = { workspace = true }
+51 -33
View File
@@ -8,16 +8,18 @@ pub enum Codec {
Json,
/// Newline-delimited compact JSON, one value per line.
JsonLines,
/// A single postcard blob. `append` to a non-empty buffer errors.
Postcard,
/// Length-prefixed postcard frames: `[u32 big-endian length][postcard bytes]` per value.
PostcardFrames,
/// A single MessagePack blob. `append` to a non-empty buffer errors.
MessagePack,
/// Length-prefixed MessagePack frames: `[u32 big-endian length][MessagePack bytes]` per value.
MessagePackFrames,
}
#[derive(Debug, thiserror::Error)]
pub enum CodecError {
#[error("postcard error: {0}")]
Postcard(#[from] postcard::Error),
#[error("MessagePack encode error: {0}")]
MessagePackEncode(#[from] rmp_serde::encode::Error),
#[error("MessagePack decode error: {0}")]
MessagePackDecode(#[from] rmp_serde::decode::Error),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("frame length {0} exceeds u32")]
@@ -39,8 +41,8 @@ impl Codec {
match self {
Codec::Json => "json",
Codec::JsonLines => "jsonl",
Codec::Postcard => "bin",
Codec::PostcardFrames => "frames",
Codec::MessagePack => "bin",
Codec::MessagePackFrames => "frames",
}
}
@@ -60,15 +62,15 @@ impl Codec {
output.push(b'\n');
Ok(())
}
Codec::Postcard => {
Codec::MessagePack => {
if !output.is_empty() {
return Err(CodecError::SingleValueAlreadyWritten);
}
postcard::to_io(value, &mut *output)?;
rmp_serde::encode::write(output, value)?;
Ok(())
}
Codec::PostcardFrames => {
let payload = postcard::to_stdvec(value)?;
Codec::MessagePackFrames => {
let payload = rmp_serde::to_vec(value)?;
let length = u32::try_from(payload.len()).map_err(|_| CodecError::FrameTooLarge(payload.len()))?;
output.extend_from_slice(&length.to_be_bytes());
output.extend_from_slice(&payload);
@@ -89,11 +91,11 @@ impl Codec {
remaining: bytes,
_marker: std::marker::PhantomData,
}),
Codec::Postcard => {
let single = postcard::from_bytes::<T>(bytes).map_err(CodecError::from);
Codec::MessagePack => {
let single = rmp_serde::from_slice::<T>(bytes).map_err(CodecError::from);
Box::new(std::iter::once(single))
}
Codec::PostcardFrames => Box::new(PostcardFrameIter {
Codec::MessagePackFrames => Box::new(MessagePackFrameIter {
remaining: bytes,
_marker: std::marker::PhantomData,
}),
@@ -151,12 +153,12 @@ impl<T: DeserializeOwned> Iterator for JsonLineIter<'_, T> {
}
}
struct PostcardFrameIter<'a, T> {
struct MessagePackFrameIter<'a, T> {
remaining: &'a [u8],
_marker: std::marker::PhantomData<fn() -> T>,
}
impl<T: DeserializeOwned> Iterator for PostcardFrameIter<'_, T> {
impl<T: DeserializeOwned> Iterator for MessagePackFrameIter<'_, T> {
type Item = Result<T, CodecError>;
fn next(&mut self) -> Option<Self::Item> {
@@ -181,7 +183,7 @@ impl<T: DeserializeOwned> Iterator for PostcardFrameIter<'_, T> {
let (frame, after) = tail.split_at(length);
self.remaining = after;
Some(postcard::from_bytes(frame).map_err(CodecError::from))
Some(rmp_serde::from_slice(frame).map_err(CodecError::from))
}
}
@@ -222,20 +224,31 @@ mod tests {
}
#[test]
fn postcard_round_trip_single() {
fn message_pack_round_trip_single() {
let frame = Frame { id: 99, label: "blob".into() };
let bytes = Codec::Postcard.write_single(&frame).unwrap();
let decoded: Frame = Codec::Postcard.read_single(&bytes).unwrap();
let bytes = Codec::MessagePack.write_single(&frame).unwrap();
let decoded: Frame = Codec::MessagePack.read_single(&bytes).unwrap();
assert_eq!(decoded, frame);
}
#[test]
fn postcard_append_to_non_empty_errors() {
fn message_pack_append_to_non_empty_errors() {
let mut buffer = vec![0xAB];
let result = Codec::Postcard.append(&mut buffer, &Frame { id: 1, label: "x".into() });
let result = Codec::MessagePack.append(&mut buffer, &Frame { id: 1, label: "x".into() });
assert!(matches!(result, Err(CodecError::SingleValueAlreadyWritten)), "got {result:?}");
}
/// A type-erased `serde_json::Value` round-trips through the binary codec: the property postcard
/// could not satisfy (it raises `WontImplement` on self-describing values), which is why the
/// resource/attribute deltas that carry `serde_json::Value` bodies need a self-describing codec.
#[test]
fn message_pack_round_trips_serde_json_value() {
let value = serde_json::json!({ "kind": "embedded", "priority": 1.5, "tags": ["a", "b"] });
let bytes = Codec::MessagePack.write_single(&value).unwrap();
let decoded: serde_json::Value = Codec::MessagePack.read_single(&bytes).unwrap();
assert_eq!(decoded, value);
}
#[test]
fn json_lines_round_trip_and_skip_blanks() {
let frames = [Frame { id: 1, label: "alpha".into() }, Frame { id: 2, label: "beta".into() }];
@@ -250,13 +263,13 @@ mod tests {
}
#[test]
fn postcard_frames_round_trip() {
fn message_pack_frames_round_trip() {
let frames = frames();
let mut buffer = Vec::new();
for frame in &frames {
Codec::PostcardFrames.append(&mut buffer, frame).unwrap();
Codec::MessagePackFrames.append(&mut buffer, frame).unwrap();
}
let decoded: Vec<Frame> = Codec::PostcardFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
let decoded: Vec<Frame> = Codec::MessagePackFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
assert_eq!(decoded, frames);
}
@@ -264,27 +277,27 @@ mod tests {
/// deterministically (declared length exceeds the bytes that actually made it to disk) rather
/// than decoding a partial value into a plausible-but-wrong one.
#[test]
fn postcard_frames_detect_truncation() {
fn message_pack_frames_detect_truncation() {
let mut buffer = Vec::new();
Codec::PostcardFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
Codec::MessagePackFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
buffer.truncate(buffer.len() - 1);
let last = Codec::PostcardFrames.iter::<Frame>(&buffer).last().unwrap();
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
assert!(matches!(last, Err(CodecError::TruncatedFrame { .. })), "got {last:?}");
}
/// A buffer whose first record's length prefix itself is incomplete (fewer than 4 bytes) is
/// reported as a truncated prefix rather than mis-read as a zero-length frame.
#[test]
fn postcard_frames_detect_truncated_length_prefix() {
fn message_pack_frames_detect_truncated_length_prefix() {
let buffer = vec![0x00, 0x00];
let last = Codec::PostcardFrames.iter::<Frame>(&buffer).last().unwrap();
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
assert!(matches!(last, Err(CodecError::TruncatedLengthPrefix(2))), "got {last:?}");
}
#[test]
fn write_single_then_read_with_iter_yields_one() {
let frame = Frame { id: 5, label: "one".into() };
for codec in [Codec::Json, Codec::JsonLines, Codec::Postcard, Codec::PostcardFrames] {
for codec in [Codec::Json, Codec::JsonLines, Codec::MessagePack, Codec::MessagePackFrames] {
let bytes = codec.write_single(&frame).unwrap();
let collected: Vec<Frame> = codec.iter(&bytes).collect::<Result<_, _>>().unwrap();
assert_eq!(collected, vec![Frame { id: 5, label: "one".into() }], "codec {codec:?}");
@@ -302,7 +315,12 @@ mod tests {
#[test]
fn extensions_are_distinct() {
let exts = [Codec::Json.extension(), Codec::JsonLines.extension(), Codec::Postcard.extension(), Codec::PostcardFrames.extension()];
let exts = [
Codec::Json.extension(),
Codec::JsonLines.extension(),
Codec::MessagePack.extension(),
Codec::MessagePackFrames.extension(),
];
let unique: std::collections::HashSet<_> = exts.iter().collect();
assert_eq!(unique.len(), exts.len(), "extensions collide: {exts:?}");
}
+4 -3
View File
@@ -35,9 +35,6 @@ pub enum Error {
#[cfg(feature = "conversion")]
#[error("commit error: {0}")]
Commit(#[from] CommitError),
/// The container has no manifest, cannot be opened.
#[error("container has no manifest")]
MissingManifest,
/// The manifest's `format` field is not the `.gdd` magic, so this is not a `.gdd` document.
#[error("not a .gdd document (manifest format = {found:?}, expected {expected:?})")]
WrongFormat { found: String, expected: &'static str },
@@ -50,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),
}
+13 -10
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.
@@ -151,10 +151,20 @@ impl<L: Layout> Gdd<L> {
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();
@@ -195,15 +205,8 @@ impl<L: Layout> Gdd<L> {
if options.include_registry {
// With history, the persisted snapshot is the retired registry and the hot log layers on top
// (mirrors `Session::load`); without history it must be the full working registry, since
// `bootstrap_from_registry` reconstructs the whole document from it alone. That document starts a history of
// its own, so the tombstones go.
let live;
let snapshot = if options.include_history {
export_session.retired_registry()
} else {
live = export_session.registry().without_tombstones();
&live
};
// `bootstrap_from_registry` reconstructs the whole document from it alone.
let snapshot = if options.include_history { export_session.retired_registry() } else { export_session.registry() };
sink.write_entry(&io::path_for(self.layout.registry_basename(), codecs.registry), &codecs.registry.write_single(snapshot)?)?;
}
+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"
}
+151 -35
View File
@@ -6,6 +6,7 @@
//!
//! See the "On-disk container" section of `node-graph/rfcs/document-format.md` for the format spec.
use std::sync::Arc;
// `Path` and `FolderBackend` are only used by the native-only path-based open/create, so they're
// gated off wasm to avoid unused-import warnings.
#[cfg(not(target_family = "wasm"))]
@@ -13,13 +14,13 @@ use std::path::Path;
#[cfg(not(target_family = "wasm"))]
use document_container::backends::folder::FolderBackend;
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
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, UserId};
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;
@@ -27,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;
@@ -48,39 +51,108 @@ pub type GddV1 = Gdd<GddV1Layout>;
pub const MANIFEST_CODEC: Codec = Codec::Json;
/// Working-copy codecs. The working copy lives in appdata, not under VCS — these defaults
/// optimize for size and write cost. JSON/JSONL is opt-in via `ExportFormat::Folder` for 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.
/// optimize for size and write cost. MessagePack is self-describing, so it round-trips the
/// type-erased `serde_json::Value` bodies that resource and attribute deltas carry (a non-self-
/// describing format like postcard cannot). JSON/JSONL is opt-in via `ExportFormat::Folder` for
/// 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;
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::Postcard;
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::PostcardFrames;
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::PostcardFrames;
/// 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;
/// Editor-facing handle. Owns the `Session` and the working-copy container; mutations are mirrored
/// to disk continuously (every retirement appends to the history file and re-snapshots the registry).
///
/// The per-edit persist path (`commit_from_runtime`, `apply_hot_op`, `retire`) is synchronous and
/// read-free: the manifest is cached in memory (so payload codecs need no disk read), and writes go
/// through the container's sync write surface. Only `open` / `export` are async, since they
/// through the container's sync write surface. Only `open` / `create` / `export` are async, since they
/// read.
/// `Clone` shares the working-copy container (`AnyContainer` is a handle) so a cloned handle reads and writes
/// `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: AnyContainer,
pub(crate) working: Arc<AnyContainer>,
pub(crate) layout: L,
/// In-memory copy of the manifest, kept authoritative since `Gdd` is its sole writer. Holds the
/// 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, document_graph_storage::Value>,
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, document_graph_storage::Value>>,
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
@@ -98,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 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)
Self::create_in(working, layout, peer, user, document_uuid, editor_version, stdlib_version).await
}
}
@@ -121,14 +193,10 @@ impl<L: Layout> Gdd<L> {
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
///
/// # Errors
/// [`Error::MissingManifest`] if the container holds no manifest, [`Error::WrongFormat`] / [`Error::UnsupportedVersion`]
/// if it fails validation, plus the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
/// [`Error::WrongFormat`] / [`Error::UnsupportedVersion`] if the manifest fails validation, plus
/// the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
let manifest: Manifest = match io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await {
Ok(manifest) => manifest,
Err(io::ReadError::NotFound { .. }) => return Err(Error::MissingManifest),
Err(error) => return Err(error.into()),
};
let manifest: Manifest = io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await?;
validate_manifest(&manifest)?;
let codecs = manifest.codecs;
@@ -136,12 +204,20 @@ 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;
let user = session_state.user_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?;
@@ -160,42 +236,70 @@ impl<L: Layout> Gdd<L> {
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?;
Ok(Self {
session,
working,
working: Arc::new(working),
layout,
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 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,
user_id: UserId(peer.0),
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 {
session,
working,
working: Arc::new(working),
layout,
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,
})
}
}
@@ -262,13 +366,13 @@ impl<L: Layout> Gdd<L> {
/// The per-peer view settings read from `session.json` (PTZ, rulers, overlays, snapping, collapse).
/// Opaque `ui::doc::*` blobs; the editor decodes them. Empty for a fresh document.
pub fn view_settings(&self) -> &std::collections::BTreeMap<String, document_graph_storage::Value> {
pub fn view_settings(&self) -> &std::collections::BTreeMap<String, serde_json::Value> {
&self.view_settings
}
/// The per-network view settings read from `session.json` (node-graph nav + previewing), keyed by
/// [`NetworkId`](document_graph_storage::NetworkId). Opaque `ui::nav::*` / `ui::previewing` blobs the editor decodes.
pub fn network_view_settings(&self) -> &std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>> {
pub fn network_view_settings(&self) -> &std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>> {
&self.network_view_settings
}
@@ -291,8 +395,11 @@ impl<L: Layout> Gdd<L> {
}
/// Drop the session and return the working-copy container + layout.
/// Intended for test code that needs to reopen against the same container; panics if the container
/// is still shared by a `Gdd` clone (tests don't clone before calling this).
pub fn into_storage(self) -> (AnyContainer, L) {
(self.working, self.layout)
let working = Arc::try_unwrap(self.working).unwrap_or_else(|_| panic!("into_storage called while the working-copy container is still shared by a Gdd clone"));
(working, self.layout)
}
/// Resolve every proto-node declaration referenced by the registry or its history into a
@@ -323,7 +430,16 @@ impl<L: Layout> Gdd<L> {
declarations
}
/// Read the embedded legacy `.graphite` document, if present.
/// Store the legacy `.graphite` document bytes verbatim inside the working copy (dual-write soak).
/// Synchronous (hot-path safe via `write_non_blocking`): called at the autosave boundary alongside
/// the registry snapshot. The bytes are opaque to `Gdd` — it never deserializes them.
// TODO: Add feature gate for legacy embedding
pub fn store_legacy_document(&self, bytes: &[u8]) -> Result<(), ContainerError> {
self.working.write_non_blocking(self.layout.legacy_path(), bytes)
}
/// Read back the embedded legacy `.graphite` document, if present. The compare-on-open oracle and
/// the recovery fallback both go through here. `None` when no legacy blob was ever written.
pub async fn read_legacy_document(&self) -> Option<ByteHolder> {
self.working.read(self.layout.legacy_path()).await.ok()
}
+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(())
}
}
+391 -65
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, Value};
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)?;
@@ -62,10 +72,7 @@ impl<L: Layout> Gdd<L> {
byte_store: &dyn ResourceStorage,
) -> Result<document_graph_storage::Declarations, Error> {
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
for hot_op in &hot_ops {
self.append_hot_frame(hot_op)?;
}
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
@@ -80,34 +87,42 @@ impl<L: Layout> Gdd<L> {
/// 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
@@ -134,29 +149,39 @@ impl<L: Layout> Gdd<L> {
/// advanced past what the working copy reflects, so the caller should treat the document as needing
/// re-persist (mirrors [`stage_runtime_snapshot`](Self::stage_runtime_snapshot)).
pub fn apply_hot_op(&mut self, op: HotOp) -> Result<(), Error> {
self.session.replay_hot_op(op.clone())?;
self.session.apply_hot_op(op.clone())?;
self.append_hot_frame(&op)?;
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,9 +196,9 @@ 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: Value) -> Result<(), Error> {
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> Result<(), Error> {
if self.session.annotate_delta(rev, key, value) {
self.rewrite_history()?;
}
@@ -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,7 +216,58 @@ 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(),
@@ -199,6 +275,8 @@ impl<L: Layout> Gdd<L> {
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(),
};
@@ -206,16 +284,18 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
/// Re-snapshot the retired registry to `registry.bin`. `Session::load` trusts it to match the persisted `head`
/// and replays the hot log on top, so it must hold no hot op, and any cursor move must re-persist it.
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.retired_registry())?;
/// Re-snapshot the materialized working registry to `registry.bin`. `Session::load` trusts the stored
/// 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`).
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(())
}
/// Replace the per-peer view settings and persist them to `session.json`. Called by the editor when
/// the viewport or a document-level toggle changes; never enters the registry, history, or CRDT.
pub fn set_view_settings(&mut self, view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>) -> Result<(), Error> {
pub fn set_view_settings(&mut self, view_settings: std::collections::BTreeMap<String, serde_json::Value>) -> Result<(), Error> {
self.view_settings = view_settings;
self.persist_session_state()
}
@@ -231,51 +311,297 @@ impl<L: Layout> Gdd<L> {
/// enters the registry, history, or CRDT.
pub fn set_network_view_settings(
&mut self,
network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>>,
network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
) -> Result<(), Error> {
self.network_view_settings = network_view_settings;
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(())
}
}
+39 -2
View File
@@ -4,6 +4,7 @@
#[cfg(not(target_family = "wasm"))]
use std::path::Path;
use std::sync::Arc;
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
use graphene_resource::ResourceFuture;
@@ -38,7 +39,7 @@ impl<L: Layout> Gdd<L> {
#[cfg(not(target_family = "wasm"))]
pub fn add_resource_from_path(&mut self, id: document_graph_storage::ResourceId, hash: ResourceHash, src: &Path) -> Result<(), Error> {
let dest_path = self.layout.resource_path(&hash);
if let AnyContainer::Folder(folder) = &self.working {
if let AnyContainer::Folder(folder) = self.working.as_ref() {
let full = folder.root().join(&dest_path);
if let Some(parent) = full.parent() {
std::fs::create_dir_all(parent).map_err(ContainerError::Io)?;
@@ -90,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> {
@@ -101,7 +132,13 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
}
}
pub struct ResourceProxy<T: Layout>(AnyContainer, T);
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<'_> {
+15 -6
View File
@@ -4,7 +4,7 @@
//!
//! Lives in `session.json`. Rewritten on retirement.
use document_graph_storage::{NetworkId, PeerId, Rev, UserId, Value};
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev, UserId};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
@@ -15,7 +15,8 @@ pub struct SessionState {
/// tiebreaking and minting peer-scoped IDs.
#[serde(default)]
pub peer_id: PeerId,
/// The person using this device, registered in the CRDT so undo and authorship follow them across peer ids.
/// 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
@@ -24,7 +25,7 @@ pub struct SessionState {
pub head_rev: Option<Rev>,
/// Published frontier: the latest retired commit broadcast to a peer. Commits after it are silently
/// rewritable on undo; commits at or before it are published. `None` until broadcast transport lands.
#[serde(default)]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_broadcast_rev: Option<Rev>,
/// Revs the user has undone past, so redo survives a reopen. (The legacy `VecDeque` redo history
/// is not persisted, so within the shadow phase this is strictly more capable than the live editor.)
@@ -36,10 +37,18 @@ pub struct SessionState {
pub next_node_counter: u64,
/// Per-peer view settings (PTZ, rulers, overlays, snapping, panel collapse). Local to the viewer,
/// so kept out of the CRDT/history. Editor owns the keys/values (opaque `ui::doc::*` blobs).
#[serde(default)]
pub view_settings: BTreeMap<String, Value>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub view_settings: BTreeMap<String, serde_json::Value>,
/// Per-network view settings (node-graph nav + previewing), keyed by the stable storage [`NetworkId`].
/// 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 network_view_settings: BTreeMap<NetworkId, BTreeMap<String, Value>>,
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));
}
});
}
+73 -60
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()) {
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,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
assert_eq!(gdd.session().peer(), PeerId(13));
@@ -97,7 +99,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
gdd.update_manifest(|m| m.editor_version = "ed-NEW".into())
.unwrap_or_else(|error| panic!("update_manifest failed: {error:?}"));
@@ -112,7 +116,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
// AddNetwork on the root network. Idempotent at apply, so two hot ops applied in sequence
// produces one network in the registry.
@@ -122,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:?}"));
@@ -137,7 +144,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
// Two hot ops: one with low timestamp (will retire), one with high (will stay).
let early = HotOp {
@@ -146,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 {
@@ -153,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();
@@ -181,7 +192,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
// Retire one op so there is a real retired rev to mark as published.
let op = HotOp {
@@ -190,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:?}"));
@@ -210,7 +224,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("export");
@@ -219,7 +235,7 @@ fn export_folder_round_trips_through_open() {
.await
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
// Payloads keep the working-copy codecs: registry is postcard (`.bin`), manifest is JSON.
// Payloads keep the working-copy codecs: registry is MessagePack (`.bin`), manifest is JSON.
assert!(dest.join("registry.bin").exists());
assert!(dest.join("manifest.json").exists());
assert!(dest.join("session.json").exists());
@@ -238,7 +254,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("doc.gdd.zip");
@@ -263,7 +281,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("nope");
@@ -286,7 +306,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
let payload = b"deadbeef cafe babe";
let hash = ResourceHash::from(&payload[..]);
@@ -316,7 +338,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
let payload = b"persistent bytes";
let hash = ResourceHash::from(&payload[..]);
@@ -345,7 +369,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
// Source file outside the working copy.
let payload = b"external resource bytes";
@@ -369,7 +395,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
let payload = b"exported resource";
let hash = ResourceHash::from(&payload[..]);
@@ -392,12 +420,14 @@ fn export_carries_resources() {
#[test]
fn embed_all_resources_materializes_link_only_resource() {
use document_format::{ExportFormat, ExportOptions};
use document_graph_storage::{NoMetadata, to_value};
use document_graph_storage::NoMetadata;
use graph_craft::application_io::resource::ResourceStorage;
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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
// A resource whose only source is a URL, resolved to a hash. The bytes live solely in the
// byte store; the working copy never holds them.
@@ -444,8 +474,8 @@ fn embed_all_resources_materializes_link_only_resource() {
let entry = reopened.registry().resources.get(&id).expect("resource entry survived export");
assert_eq!(entry.hash, Some(hash));
let embedded = to_value(&DataSource::Embedded).unwrap();
let url = to_value(&DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
let embedded = serde_json::to_value(DataSource::Embedded).unwrap();
let url = serde_json::to_value(DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
let chain: Vec<_> = entry.sources.iter().map(|(_, value)| value.source.clone()).collect();
assert_eq!(chain, vec![embedded, url], "Embedded leads the chain, URL kept as fallback");
});
@@ -462,7 +492,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
// An Embedded resource whose bytes live only in the byte store, not the working copy.
let payload = b"embedded bytes in the cache";
@@ -503,7 +535,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
let payload = b"hot resource bytes";
let hash = graphene_resource::ResourceHash::from(&payload[..]);
@@ -556,12 +590,14 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
let codecs = gdd.manifest().codecs;
assert_eq!(codecs.registry, Codec::Postcard);
assert_eq!(codecs.history, Codec::PostcardFrames);
assert_eq!(codecs.hot_log, Codec::PostcardFrames);
assert_eq!(codecs.registry, Codec::MessagePack);
assert_eq!(codecs.history, Codec::MessagePackFrames);
assert_eq!(codecs.hot_log, Codec::MessagePackFrames);
assert_eq!(codecs.session, Codec::Json);
});
}
@@ -577,7 +613,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
let network = NodeNetwork {
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
@@ -619,7 +657,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
let hot_op = HotOp {
op: RegistryDelta::AddNetwork {
@@ -627,12 +667,13 @@ 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:?}"));
let (working, layout) = gdd.into_storage();
// Defaults: hot log is PostcardFrames (.frames), manifest is always JSON.
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::PostcardFrames)).await);
// Defaults: hot log is MessagePackFrames (.frames), manifest is always JSON.
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::MessagePackFrames)).await);
assert!(working.exists(&io::path_for(layout.manifest_basename(), Codec::Json)).await);
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
@@ -670,7 +711,9 @@ 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()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
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:?}"));
// Commit: declaration bytes flow into the byte store, not the Gdd container.
let byte_store = HashMapResourceStorage::new();
@@ -690,33 +733,3 @@ fn declarations_round_trip_through_byte_store() {
}
});
}
#[cfg(feature = "conversion")]
#[test]
fn an_export_without_history_drops_tombstones() {
use document_format::{ExportFormat, ExportOptions};
use document_graph_storage::{Network, NetworkId, RegistryDelta};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xAC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let id = NetworkId(7);
gdd.stage_constructed_ops(vec![RegistryDelta::AddNetwork { id, network: Network::default() }], &Default::default(), &empty_byte_store())
.unwrap();
gdd.stage_constructed_ops(vec![RegistryDelta::RemoveNetwork { id, snapshot: Network::default() }], &Default::default(), &empty_byte_store())
.unwrap();
assert!(gdd.registry().removed_networks.contains_key(&id));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("flat");
let options = ExportOptions {
include_history: false,
..ExportOptions::default()
};
gdd.export(&dest, ExportFormat::Folder, options, &empty_byte_store(), None)
.await
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
let reopened = GddV1::open(&dest).await.unwrap_or_else(|error| panic!("open failed: {error:?}"));
assert!(reopened.registry().removed_networks.is_empty(), "a document without history starts without tombstones");
});
}
@@ -1,69 +0,0 @@
// Staging a whole document after a recorded batch, and what a reopen must carry over.
#![cfg(feature = "conversion")]
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NoMetadata, PeerId, Registry};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_resource::ResourceRegistry;
fn network_with_one_node() -> NodeNetwork {
let node = DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
call_argument: concrete!(()),
..Default::default()
};
NodeNetwork {
nodes: [(NodeId(1), node)].into_iter().collect(),
..Default::default()
}
}
/// A whole-document stage after a recorded batch stages nothing new: restating the batch would fail on the node it added.
#[test]
fn restaging_the_whole_document_after_a_batch_stages_nothing() {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
let store = HashMapResourceStorage::new();
let resources = ResourceRegistry::new();
gdd.stage_runtime_snapshot(&NodeNetwork::default(), &NoMetadata, &resources, &store)
.expect("first whole-document stage");
let target = Registry::convert_from_runtime(&network_with_one_node(), &NoMetadata, &resources, PeerId(21)).unwrap();
let ops = document_graph_storage::delta::compute_deltas(gdd.registry(), &target.registry);
gdd.stage_constructed_ops(ops, &target.declaration_bytes, &store).expect("recorded batch");
let hot_before = gdd.session().hot_log().len();
gdd.stage_runtime_snapshot(&network_with_one_node(), &NoMetadata, &resources, &store)
.expect("the runtime already matches what was staged");
assert_eq!(gdd.session().hot_log().len(), hot_before, "nothing new to stage");
}
/// `registry.bin` is the retired snapshot the hot log replays onto, so an op still hot at save time must stay out of it.
#[test]
fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
use document_graph_storage::{AttributeDelta, HotOp, RegistryDelta, TimeStamp, Value};
let set = |value: u32, counter: u64| HotOp {
op: RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: "k".into(),
value: Some(Value::from(serde_json::json!(value))),
},
},
timestamp: TimeStamp { counter, peer: PeerId(22) },
};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap();
gdd.apply_hot_op(set(1, 1)).unwrap();
gdd.apply_hot_op(set(2, 2)).unwrap();
gdd.retire(TimeStamp { counter: 1, peer: PeerId(22) }).unwrap();
let retired = gdd.session().retired_registry().clone();
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap();
assert!(reopened.session().retired_registry().value_equal(&retired), "the hot op leaked into the retired snapshot");
assert_eq!(reopened.session().hot_log().len(), 1);
});
}
@@ -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");
});
}
+1 -7
View File
@@ -5,15 +5,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
conversion = ["dep:graph-craft", "dep:core-types"]
default = ["conversion"]
@@ -28,7 +22,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
blake3 = { workspace = true }
rustc-hash = { workspace = true }
postcard = { workspace = true }
rmp-serde = { workspace = true }
[dev-dependencies]
graph-craft = { workspace = true, features = ["loading"] }
+41 -170
View File
@@ -1,6 +1,6 @@
use crate::{AttributeDelta, TimeStamp, Value, ValueError, from_value, to_value};
use crate::TimeStamp;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, btree_map};
use std::collections::BTreeMap;
/// Attribute keys. Glob-import (`use crate::attr::*`) at conversion sites.
///
@@ -8,214 +8,85 @@ use std::collections::{BTreeMap, btree_map};
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
pub mod attr;
/// An attribute value and when it was last set. A deleted key stays as a stamped tombstone, which readers see as absent.
/// 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 AttributeValue {
pub value: Value,
pub struct Value {
pub value: serde_json::Value,
pub timestamp: TimeStamp,
// No skipping: the registry is positional on disk.
#[serde(default)]
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub deleted: bool,
}
impl AttributeValue {
pub fn new(value: Value, timestamp: TimeStamp) -> Self {
impl Value {
pub fn new(value: serde_json::Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp, deleted: false }
}
/// The tombstone of a key deleted at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
value: Value::None,
value: serde_json::Value::Null,
timestamp,
deleted: true,
}
}
}
/// Attribute keys and their values, each last-writer-wins on its own timestamp. A key the map lacks is deleted as of
/// its floor, when the map was last written whole.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Attributes {
entries: BTreeMap<String, AttributeValue>,
#[serde(default)]
floor: TimeStamp,
/// 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)
}
impl Attributes {
pub fn new() -> Self {
Self::default()
}
/// An empty map written whole at `floor`, which deletes every key older than it.
pub fn empty_at(floor: TimeStamp) -> Self {
Self { entries: BTreeMap::new(), floor }
}
/// When the map was last written whole.
pub fn floor(&self) -> TimeStamp {
self.floor
}
/// Carries `floor` with the entries, so they land as the map they were taken from rather than as a new write.
pub fn set_floor(&mut self, floor: TimeStamp) {
self.floor = floor;
}
pub fn get(&self, key: &str) -> Option<&AttributeValue> {
self.entries.get(key)
}
pub fn contains_key(&self, key: &str) -> bool {
self.entries.contains_key(key)
}
/// Every entry, tombstones included.
pub fn iter(&self) -> btree_map::Iter<'_, String, AttributeValue> {
self.entries.iter()
}
pub fn keys(&self) -> btree_map::Keys<'_, String, AttributeValue> {
self.entries.keys()
}
/// The live entries: every key that is not a tombstone.
pub fn live(&self) -> impl Iterator<Item = (&String, &AttributeValue)> {
self.entries.iter().filter(|(_, value)| !value.deleted)
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn insert(&mut self, key: String, value: AttributeValue) -> Option<AttributeValue> {
self.entries.insert(key, value)
}
pub fn remove(&mut self, key: &str) -> Option<AttributeValue> {
self.entries.remove(key)
}
/// Lands a single-key write if it is newer than the key's value, or than the floor for a key the map lacks. A
/// deletion leaves a tombstone.
pub(crate) fn apply_delta(&mut self, delta: AttributeDelta, timestamp: TimeStamp, force: bool) {
let AttributeDelta { key, value } = delta;
let decided = self.get(&key).map_or(self.floor, |existing| existing.timestamp);
if !force && timestamp <= decided {
return;
}
let entry = match value {
Some(value) => AttributeValue::new(value, timestamp),
None => AttributeValue::deleted(timestamp),
};
self.insert(key, entry);
}
/// Inserts `value` under `key`.
pub fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp) {
self.insert(key.to_string(), AttributeValue::new(value, timestamp));
}
/// Write helpers for `Attributes`.
pub trait AttributesWrite {
/// Inserts a JSON value under `key`.
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp);
/// Serializes `value` and inserts it under `key`.
pub fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
self.set(key, to_value(value)?, timestamp);
fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), serde_json::Error> {
self.set(key, serde_json::to_value(value)?, timestamp);
Ok(())
}
/// Inserts only when `value != default`, so the read side falls back to the same default.
pub fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), serde_json::Error> {
if value != default {
self.set_serialized(key, value, timestamp)?;
}
Ok(())
}
}
/// Deserializes the value under `key`, or `None` if missing, deleted or undecodable.
pub fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
self.get(key).filter(|v| !v.deleted).and_then(|v| from_value(&v.value).ok())
impl AttributesWrite for Attributes {
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp) {
self.insert(key.to_string(), Value::new(value, timestamp));
}
}
/// Typed read helpers for `Attributes`.
pub trait AttributesRead {
/// Deserializes the value under `key`, or `None` if missing or undecodable.
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T>;
/// Same as `get_typed`, falling back to `default`.
pub fn get_or<T: serde::de::DeserializeOwned>(&self, key: &str, default: T) -> T {
fn get_or<T: serde::de::DeserializeOwned>(&self, key: &str, default: T) -> T {
self.get_typed(key).unwrap_or(default)
}
/// Same as `get_typed`, falling back to `T::default()`.
pub fn get_or_default<T: serde::de::DeserializeOwned + Default>(&self, key: &str) -> T {
fn get_or_default<T: serde::de::DeserializeOwned + Default>(&self, key: &str) -> T {
self.get_typed(key).unwrap_or_default()
}
/// Writes the map whole at `timestamp`: the floor deletes every other key without a tombstone per key.
pub(crate) fn stamp(&mut self, timestamp: TimeStamp) {
self.entries.retain(|_, value| !value.deleted);
self.entries.values_mut().for_each(|value| value.timestamp = timestamp);
self.floor = timestamp;
}
/// Stamps what arrives unstamped: the whole map if it carries no floor, else only the entries at the origin.
pub(crate) fn stamp_unstamped(&mut self, timestamp: TimeStamp) {
if self.floor == TimeStamp::ORIGIN {
return self.stamp(timestamp);
}
self.entries
.values_mut()
.filter(|value| value.timestamp == TimeStamp::ORIGIN)
.for_each(|value| value.timestamp = timestamp);
}
/// Folds `other` in key by key: the newer entry wins, and a key only one map holds dies if the other map's floor is
/// newer, as that map was written whole after it.
pub(crate) fn merge(&mut self, other: Attributes) {
self.entries.retain(|_, value| value.timestamp >= other.floor);
for (key, value) in other.entries {
match self.entries.entry(key) {
btree_map::Entry::Occupied(entry) if value.timestamp > entry.get().timestamp => *entry.into_mut() = value,
btree_map::Entry::Vacant(entry) if value.timestamp >= self.floor => {
entry.insert(value);
}
_ => {}
}
}
self.floor = self.floor.max(other.floor);
}
/// The newest stamp the map carries, its floor included.
pub(crate) fn newest(&self) -> TimeStamp {
self.entries.values().map(|value| value.timestamp).fold(self.floor, TimeStamp::max)
}
}
impl FromIterator<(String, AttributeValue)> for Attributes {
fn from_iter<I: IntoIterator<Item = (String, AttributeValue)>>(iter: I) -> Self {
Self {
entries: iter.into_iter().collect(),
floor: TimeStamp::ORIGIN,
}
}
}
impl Extend<(String, AttributeValue)> for Attributes {
fn extend<I: IntoIterator<Item = (String, AttributeValue)>>(&mut self, iter: I) {
self.entries.extend(iter);
}
}
impl IntoIterator for Attributes {
type Item = (String, AttributeValue);
type IntoIter = btree_map::IntoIter<String, AttributeValue>;
fn into_iter(self) -> Self::IntoIter {
self.entries.into_iter()
}
}
impl<'a> IntoIterator for &'a Attributes {
type Item = (&'a String, &'a AttributeValue);
type IntoIter = btree_map::Iter<'a, String, AttributeValue>;
fn into_iter(self) -> Self::IntoIter {
self.entries.iter()
impl AttributesRead for Attributes {
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
self.get(key).filter(|v| !v.deleted).and_then(|v| serde_json::from_value(v.value.clone()).ok())
}
}
@@ -69,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";
}
+38 -45
View File
@@ -1,10 +1,15 @@
use crate::{Attributes, Implementation, 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};
/// Content-addressed delta: `id` is `blake3_128(parents, author, timestamp, delta_type)`.
///
/// `reverse` is undo bookkeeping that depends on local state, so it is stored but left out of the identity hash.
/// `reverse` is state-dependent undo bookkeeping (it captures pre-state at the moment the forward
/// op was applied), so it's serialized for storage but excluded from the identity hash — two peers
/// observing the same forward delta against different local states would otherwise compute
/// different Revs for the same logical op.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Delta {
pub id: Rev,
@@ -17,12 +22,8 @@ pub struct Delta {
/// Local, mutable annotations on this commit (interaction-end marker, future commit messages / labels).
/// Deliberately excluded from `compute_rev`: relabeling a commit must not change its content-addressed
/// identity, and two peers annotating the same op differently must still dedup to one `Rev`.
#[serde(default)]
#[serde(default, skip_serializing_if = "Attributes::is_empty")]
pub attributes: Attributes,
/// When the delta entered history, in Unix milliseconds by the retiring peer's clock; display only and outside the rev.
/// Zero means unrecorded, saving the tag byte of an `Option`. Last, since the history codec is positional.
#[serde(default)]
pub(crate) retired_at_ms: u64,
}
impl Delta {
@@ -36,7 +37,6 @@ impl Delta {
kind,
reverse,
attributes: Attributes::default(),
retired_at_ms: 0,
}
}
@@ -57,7 +57,6 @@ impl Delta {
reverse: kind.clone(),
kind,
attributes: Attributes::default(),
retired_at_ms: 0,
}
}
@@ -72,16 +71,16 @@ impl Delta {
/// Mark this delta as the last op of a user interaction, so the undo cursor treats it as a checkpoint.
pub fn mark_interaction_end(&mut self, timestamp: TimeStamp) {
self.attributes.set(attr::delta::INTERACTION_END, Value::Bool(true), timestamp);
self.attributes.set(attr::delta::INTERACTION_END, serde_json::Value::Bool(true), timestamp);
}
pub fn is_interaction_end(&self) -> bool {
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == Value::Bool(true))
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 the peer that retired it recorded it.
/// When the delta entered history in wall-clock milliseconds, if its retirer recorded it.
pub fn retired_at(&self) -> Option<u64> {
(self.retired_at_ms != 0).then_some(self.retired_at_ms)
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
@@ -106,7 +105,8 @@ pub enum RegistryDelta {
id: NodeId,
node: Node,
},
/// `snapshot` is the node as removed, which folds in like any write so a removal of a node never seen still lands.
/// `snapshot` lets the reverse `AddNode` rebuild without reading the (already-removed) node from
/// the registry, mirroring `RemoveNetwork`.
RemoveNode {
id: NodeId,
snapshot: Node,
@@ -159,12 +159,13 @@ pub enum RegistryDelta {
id: NetworkId,
network: Network,
},
/// `snapshot` is the network as removed; see [`RemoveNode`](Self::RemoveNode).
/// `snapshot` lets the reverse delta rebuild without re-walking history.
RemoveNetwork {
id: NetworkId,
snapshot: Network,
},
/// Register a whole resource entry at once, the way `AddNetwork` pairs with `RemoveNetwork`.
/// Register a whole resource entry at once. Overwrites any existing entry for `id`; the reverse
/// of `RemoveResource`, the way `AddNetwork` pairs with `RemoveNetwork`.
AddResource {
id: ResourceId,
entry: ResourceEntry,
@@ -186,14 +187,16 @@ pub enum RegistryDelta {
AddSource {
id: ResourceId,
key: SourceKey,
source: Value,
source: serde_json::Value,
},
/// Remove one entry from a resource's source chain. LWW against the entry's timestamp.
RemoveSource {
id: ResourceId,
key: SourceKey,
},
/// Registers a device's `PeerId` to the `UserId` behind it; the newest registration wins.
/// Append-only registration of a device's `PeerId` against its owning `UserId`.
/// First write wins; conflicting re-registration errors. Duplicate identical registration
/// is a no-op. Not LWW — the mapping is forever.
RegisterPeer {
peer: PeerId,
user: UserId,
@@ -208,15 +211,18 @@ 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(Value),
Other(serde_json::Value),
}
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeDelta {
pub key: String,
pub value: Option<Value>,
pub value: Option<serde_json::Value>,
}
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
@@ -226,30 +232,17 @@ pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attri
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unrecorded_retired_at_costs_one_byte_and_round_trips() {
let base = Delta::new(
None,
PeerId(1),
TimeStamp { counter: 1, peer: PeerId(1) },
RegistryDelta::Other(Value::None),
RegistryDelta::Other(Value::None),
);
let mut stamped = base.clone();
stamped.retired_at_ms = 1_790_000_000_000;
let bare_base = postcard::to_allocvec(&base).expect("encode");
let bare_stamped = postcard::to_allocvec(&stamped).expect("encode");
// Only the integer's varint differs: one byte for zero, six for today's milliseconds, no tag byte in either.
assert_eq!(bare_stamped.len() - bare_base.len(), postcard::to_allocvec(&1_790_000_000_000u64).unwrap().len() - 1);
let decoded: Delta = postcard::from_bytes(&bare_stamped).expect("decode");
assert_eq!(decoded.retired_at(), Some(1_790_000_000_000));
let decoded: Delta = postcard::from_bytes(&bare_base).expect("decode");
assert_eq!(decoded.retired_at(), None);
/// 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;
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);
}
+19 -13
View File
@@ -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.live() {
if to.get(key).is_none_or(|value| value.deleted) {
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.live() {
if from.get(key).is_none_or(|from_value| from_value.deleted || 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()),
@@ -218,7 +219,7 @@ fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) ->
#[cfg(test)]
mod tests {
use super::*;
use crate::{Attributes, ExportSlot, Network, Node, NodeInput, TimeStamp, Value};
use crate::{Attributes, ExportSlot, Network, Node, NodeInput, TimeStamp};
#[test]
fn test_compute_deltas_empty() {
@@ -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);
@@ -298,13 +300,17 @@ mod tests {
#[test]
fn test_compute_deltas_change_network_attribute() {
use crate::TimeStamp;
use crate::{AttributesWrite, TimeStamp};
let mut from = Registry::default();
from.networks.insert(NetworkId(0), Network::default());
let mut to = from.clone();
to.networks.get_mut(&NetworkId(0)).unwrap().attributes.set("ui::nav::width", Value::Float(640.), TimeStamp::ORIGIN);
to.networks
.get_mut(&NetworkId(0))
.unwrap()
.attributes
.set("ui::nav::width", serde_json::json!(640.0), TimeStamp::ORIGIN);
let deltas = compute_deltas(&from, &to);
assert_eq!(deltas.len(), 1, "a changed per-network attribute must emit one delta");
@@ -337,8 +343,8 @@ mod tests {
let stamp = |counter: u64| TimeStamp { counter, peer: crate::PeerId(0) };
node.attributes.insert(
"test".to_string(),
crate::AttributeValue {
value: Value::Str("old".into()),
crate::Value {
value: serde_json::json!("old"),
timestamp: stamp(0),
deleted: false,
},
@@ -348,8 +354,8 @@ mod tests {
let mut to = from.clone();
to.node_instances.get_mut(&NodeId(42)).unwrap().attributes.insert(
"test".to_string(),
crate::AttributeValue {
value: Value::Str("new".into()),
crate::Value {
value: serde_json::json!("new"),
timestamp: stamp(1),
deleted: false,
},
@@ -374,8 +380,8 @@ mod tests {
let mut to = from.clone();
to.attributes.insert(
"doc::test_attribute".to_string(),
crate::AttributeValue {
value: Value::Str("value".into()),
crate::Value {
value: serde_json::json!("value"),
timestamp: stamp(1),
deleted: false,
},
File diff suppressed because it is too large. Load diff
+34 -35
View File
@@ -10,12 +10,9 @@ use serde::Serialize;
use crate::attr::*;
use crate::metadata_source::{NoMetadata, NodeMetadataSource};
use crate::{
ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp, Value, ValueError, from_value,
to_value,
};
use crate::{AttributesWrite, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp};
fn map_serialization_error(key: &str) -> impl FnOnce(ValueError) -> ConversionError + '_ {
fn map_serialization_error(key: &str) -> impl FnOnce(serde_json::Error) -> ConversionError + '_ {
move |e| ConversionError::SerializationError(format!("{key}: {e:?}"))
}
@@ -43,7 +40,7 @@ impl NodePath {
}
fn to_global_id(&self, peer: PeerId) -> NodeId {
let bytes = postcard::to_stdvec(&(peer, self)).expect("NodePath must serialize");
let bytes = rmp_serde::to_vec(&(peer, self)).expect("NodePath must serialize");
let digest = blake3::hash(&bytes);
let mut truncated = [0u8; 8];
truncated.copy_from_slice(&digest.as_bytes()[..8]);
@@ -55,7 +52,7 @@ impl NodePath {
/// depending on traversal order. A domain tag keeps it from colliding with this node's own
/// `to_global_id`. The root network is `ROOT_NETWORK` and never goes through here.
fn owned_network_id(&self, peer: PeerId) -> NetworkId {
let bytes = postcard::to_stdvec(&("network", peer, self)).expect("NodePath must serialize");
let bytes = rmp_serde::to_vec(&("network", peer, self)).expect("NodePath must serialize");
let digest = blake3::hash(&bytes);
let mut truncated = [0u8; 8];
truncated.copy_from_slice(&digest.as_bytes()[..8]);
@@ -131,18 +128,18 @@ pub struct RuntimeConversion {
pub network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
}
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through the self-describing
/// [`Value`] (so serde aliases keep working and the on-disk shape stays migratable), then postcard.
/// Paired with [`decode_declaration`].
/// 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`].
pub fn encode_declaration(proto: &ProtoNode) -> Result<Vec<u8>, String> {
let value = to_value(proto).map_err(|error| error.to_string())?;
postcard::to_stdvec(&value).map_err(|error| error.to_string())
let value = serde_json::to_value(proto).map_err(|error| error.to_string())?;
rmp_serde::to_vec(&value).map_err(|error| error.to_string())
}
/// Decode a [`ProtoNode`] declaration from the bytes [`encode_declaration`] produced.
pub fn decode_declaration(bytes: &[u8]) -> Result<ProtoNode, String> {
let value: Value = postcard::from_bytes(bytes).map_err(|error| error.to_string())?;
from_value(&value).map_err(|error| error.to_string())
let value: serde_json::Value = rmp_serde::from_slice(bytes).map_err(|error| error.to_string())?;
serde_json::from_value(value).map_err(|error| error.to_string())
}
impl Registry {
@@ -192,7 +189,7 @@ impl Registry {
/// Snapshot the runtime [`ResourceRegistry`](graphene_resource::ResourceRegistry) into the storage
/// [`ResourceStore`](crate::ResourceStore). Each source's chain position becomes a fractional
/// [`Priority`](crate::Priority) (index-as-priority preserves order); the `DataSource` body is
/// stored type-erased as [`Value`] so its on-disk shape can migrate freely. All
/// stored type-erased as `serde_json::Value` so its on-disk shape can migrate freely. All
/// timestamps are `ORIGIN`, since this is a bootstrap snapshot, not an edit.
fn convert_resources(resources: &graphene_resource::ResourceRegistry, referenced: &std::collections::HashSet<ResourceId>, peer: PeerId, registry: &mut Registry) -> Result<(), ConversionError> {
for id in resources.ids() {
@@ -220,7 +217,7 @@ pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, i
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
peer,
};
let body = to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
// Built rather than written: the chain is put in place as converted, floor and all at the origin.
entry.force_set_source(
key,
@@ -322,7 +319,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
runtime_node_id: *runtime_node_id,
};
let mut node = convert_node(doc_node, location, registry, ctx, true)?;
node.attributes.set(node::ORIGINAL_NODE_ID, Value::Int(runtime_node_id.0.into()), TimeStamp::ORIGIN);
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(runtime_node_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(global_id, node);
}
@@ -346,8 +343,8 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
Network {
presence: TimeStamp::ORIGIN,
exports,
exports_timestamp: TimeStamp::ORIGIN,
attributes,
attributes_timestamp: TimeStamp::ORIGIN,
},
);
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
@@ -421,13 +418,13 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
let mut inputs = Vec::with_capacity(doc_node.inputs.len());
for (input_index, input) in doc_node.inputs.iter().enumerate() {
let mut input_attrs = convert_input_attributes(input)?;
input_attrs.set_floor(timestamp);
write_ui_input_attributes(&mut input_attrs, ctx.metadata, metadata_path, runtime_node_id, input_index, timestamp)?;
inputs.push(InputSlot {
input: convert_input(input, parent_path, network_id, ctx.ids(metadata_path))?,
timestamp,
attributes: input_attrs,
attributes_timestamp: timestamp,
});
}
@@ -443,7 +440,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx, recurse)?;
// Defaults match `DocumentNode::default()`; `to_runtime` rehydrates absent keys from the same defaults.
let mut attributes = crate::Attributes::empty_at(timestamp);
let mut attributes = crate::Attributes::new();
attributes
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
@@ -461,12 +458,13 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
Ok(Node {
presence: timestamp,
network_timestamp: timestamp,
added: timestamp,
inputs_timestamp: timestamp,
implementation,
implementation_timestamp: timestamp,
inputs,
attributes,
attributes_timestamp: timestamp,
network: network_id,
})
}
@@ -483,7 +481,11 @@ pub fn encode_context_features(context_features: &ContextDependencies) -> Result
}
fn encode_if_not_default<T: Serialize + PartialEq>(key: &str, value: &T, default: &T) -> Result<crate::AttributeDelta, ConversionError> {
let value = if value == default { None } else { Some(to_value(value).map_err(map_serialization_error(key))?) };
let value = if value == default {
None
} else {
Some(serde_json::to_value(value).map_err(map_serialization_error(key))?)
};
Ok(crate::AttributeDelta { key: key.to_string(), value })
}
@@ -531,14 +533,14 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
(node::ui::PINNED, metadata.pinned(metadata_path, runtime_node_id)),
] {
if value {
attributes.set(key, Value::Bool(true), timestamp);
attributes.set(key, serde_json::Value::Bool(true), timestamp);
}
}
if let Some(name) = metadata.display_name(metadata_path, runtime_node_id)
&& !name.is_empty()
{
attributes.set(node::ui::DISPLAY_NAME, Value::Str(name.to_string()), timestamp);
attributes.set(node::ui::DISPLAY_NAME, serde_json::Value::String(name.to_string()), timestamp);
}
// One whole-vec attribute; per-slot LWW would be overkill for rename-on-output.
@@ -566,7 +568,7 @@ fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
// 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, Value::Str(reference.to_string()), timestamp);
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);
@@ -597,7 +599,7 @@ fn write_ui_input_attributes<M: NodeMetadataSource + ?Sized>(
) -> Result<(), ConversionError> {
let non_empty_string = |key: &'static str, value: Option<&str>, attributes: &mut crate::Attributes| {
if let Some(value) = value.filter(|s| !s.is_empty()) {
attributes.set(key, Value::Str(value.to_string()), timestamp);
attributes.set(key, serde_json::Value::String(value.to_string()), timestamp);
}
};
@@ -619,7 +621,7 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
index: (*output_index).try_into().map_err(|_| ConversionError::IndexOverflow(*output_index))?,
},
GraphCraftNodeInput::Value { tagged_value, exposed } => {
let value = to_value(&**tagged_value).map_err(|e| ConversionError::SerializationError(format!("{e:?}")))?;
let value = serde_json::to_value(&**tagged_value).map_err(|e| ConversionError::SerializationError(format!("{e:?}")))?;
NodeInput::Value { value, exposed: *exposed }
}
GraphCraftNodeInput::Scope(s) => NodeInput::Scope(s.clone()),
@@ -800,7 +802,7 @@ impl<'m> ScopedConversion<'m> {
};
let mut node = convert_node(doc_node, location, registry, &mut self.ctx, recurse)?;
node.attributes.set(node::ORIGINAL_NODE_ID, Value::Int(local_id.0.into()), TimeStamp::ORIGIN);
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(local_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(self.resolver.node_id(local_path, local_id), node);
Ok(())
}
@@ -831,8 +833,8 @@ impl<'m> ScopedConversion<'m> {
Network {
presence: TimeStamp::ORIGIN,
exports,
exports_timestamp: TimeStamp::ORIGIN,
attributes,
attributes_timestamp: TimeStamp::ORIGIN,
},
);
Ok(())
@@ -857,10 +859,7 @@ pub fn node_value_resource_refs(node: &Node) -> impl Iterator<Item = ResourceId>
/// The `TaggedValue::Resource` ID referenced by a stored value input, if any.
pub fn value_resource_ref(input: &NodeInput) -> Option<ResourceId> {
match input {
NodeInput::Value { value: Value::Object(fields), .. } => match fields.as_slice() {
[(key, id)] if key == "Resource" => from_value(id).ok(),
_ => None,
},
NodeInput::Value { value, .. } => value.get("Resource").and_then(|id| serde_json::from_value(id.clone()).ok()),
_ => None,
}
}
@@ -872,8 +871,8 @@ mod resource_ref_shape {
#[test]
fn resource_ref_shape_matches_serde() {
let id = ResourceId::from_hash(&ResourceHash::from(b"shape test".as_slice()));
let value = to_value(&TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
let parsed = value_resource_ref(&NodeInput::Value { value, exposed: false });
let value = serde_json::to_value(TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
let parsed: Option<ResourceId> = value.get("Resource").and_then(|inner| serde_json::from_value(inner.clone()).ok());
assert_eq!(parsed, Some(id), "The shape peek in node_value_resource_refs must match TaggedValue's serde form");
}
}
+91 -25
View File
@@ -3,20 +3,26 @@
//! [`History`] owns the deltas in topological order (every parent precedes its children) plus an
//! index from [`Rev`] to position for O(1) lookup. The order is a valid replay order, so it is what
//! gets serialized to the on-disk history file and what [`crate::Session::replay_from_history`]
//! consumes. Appending a commit keeps the order; deltas arriving out of it are put back by
//! a canonical sort.
//! consumes. Retired commits have a single writer in every regime (solo editing, or leader-ordered
//! collaboration where the leader serializes retired commits), so appending preserves the order by
//! 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, HashSet};
use crate::{CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp, Value};
use crate::{AttributesWrite, CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp};
/// Every mutator maintains the indexes, so the tips and named hashes are probes, not scans of a growing history.
/// 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.
@@ -33,10 +39,17 @@ 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 mut history = Self::default();
deltas.into_iter().for_each(|delta| history.push(delta));
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> {
self.index.get(&rev).map(|&position| &self.deltas[position])
}
@@ -45,11 +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()
}
@@ -62,12 +99,10 @@ 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),
RegistryDelta::SetResourceHash { hash: Some(hash), .. } => {
self.resource_hashes.insert(*hash);
}
_ => {}
}
if let Some(&position) = self.index.get(&delta.id) {
@@ -90,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();
@@ -146,19 +176,55 @@ impl History {
}
/// `roots` and everything reachable from them through all parent links. Unknown roots are skipped.
pub(crate) fn ancestors(&self, roots: impl IntoIterator<Item = Rev>) -> HashSet<Rev> {
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)
&& let Some(delta) = self.get(rev)
{
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> {
@@ -181,7 +247,7 @@ impl History {
/// Set a local annotation attribute (e.g. a commit message) on a retired delta in place. Excluded
/// from the delta's `Rev`, so identity and the index are unchanged. Returns whether the delta was found.
pub fn annotate(&mut self, rev: Rev, key: &str, value: Value, timestamp: TimeStamp) -> bool {
pub fn annotate(&mut self, rev: Rev, key: &str, value: serde_json::Value, timestamp: TimeStamp) -> bool {
match self.index.get(&rev) {
Some(&position) => {
self.deltas[position].attributes.set(key, value, timestamp);
@@ -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 -2
View File
@@ -121,9 +121,9 @@ pub(crate) fn compute_rev(parent: Option<Rev>, author: PeerId, timestamp: TimeSt
let mut parents: Vec<Rev> = parent.into_iter().chain(extra_parents.iter().copied()).collect();
parents.sort_unstable();
parents.dedup();
postcard::to_stdvec(&("merge", parents)).expect("Merge identity fields must serialize")
rmp_serde::to_vec(&("merge", parents)).expect("Merge identity fields must serialize")
}
_ => postcard::to_stdvec(&(parent, author, timestamp, delta_type)).expect("Delta identity fields must serialize"),
_ => rmp_serde::to_vec(&(parent, author, timestamp, delta_type)).expect("Delta identity fields must serialize"),
};
hasher.update(&bytes);
let digest = hasher.finalize();
+6 -3
View File
@@ -5,12 +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 value;
pub mod touched;
#[cfg(any(feature = "conversion", test))]
pub mod from_runtime;
@@ -23,12 +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 value::{Value, ValueError, from_value, to_value};
pub use touched::Touched;
#[cfg(any(feature = "conversion", test))]
pub use from_runtime::{
@@ -38,11 +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;
}
@@ -8,8 +8,6 @@ use std::collections::HashMap;
use core_types::uuid::NodeId as RuntimeNodeId;
use crate::Value;
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per
/// node, since every node carries an identity to restore even when it carries no `ui::*` attribute.
#[derive(Clone, Debug, PartialEq)]
@@ -54,11 +52,11 @@ pub struct InputMetadataEntry {
pub input_description: Option<String>,
pub widget_override: Option<String>,
/// Reassembled from `ui::input_data::<sub_key>` attributes.
pub input_data: HashMap<String, Value>,
pub input_data: HashMap<String, serde_json::Value>,
}
/// Editor-side metadata source. Methods default to "no data" so implementors only override what
/// they carry. Returns are type-erased as [`Value`] where the underlying types live editor-side (PTZ, etc.).
/// they carry. Returns are JSON-shaped where the underlying types live editor-side (PTZ, etc.).
pub trait NodeMetadataSource {
fn position(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<Position> {
None
@@ -90,7 +88,7 @@ pub trait NodeMetadataSource {
None
}
/// Returns owned to stay object-safe. Each entry is stored as `ui::input_data::<key>` for per-key LWW.
fn input_data(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> HashMap<String, Value> {
fn input_data(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId, _input_index: usize) -> HashMap<String, serde_json::Value> {
HashMap::new()
}
+54 -24
View File
@@ -1,26 +1,33 @@
use crate::{Attributes, NetworkId, NodeId, ResourceId, TimeStamp, Value, attributes_value_equal};
use crate::{Attributes, NetworkId, NodeId, ResourceId, TimeStamp, attributes_value_equal};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
/// The latest addition or write, so a concurrent removal resolves by stamp; see [`Registry::removed_nodes`](crate::Registry::removed_nodes).
/// 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,
pub(crate) network: NetworkId,
/// When the node was last added, which decides its network between concurrent additions of one id.
/// 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) network_timestamp: TimeStamp,
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>,
/// When the input list last changed shape, so list and slot writes resolve alike in either order.
#[serde(default)]
pub(crate) inputs_timestamp: TimeStamp,
pub(crate) attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub(crate) attributes_timestamp: TimeStamp,
pub(crate) network: NetworkId,
}
impl Node {
@@ -60,21 +67,40 @@ impl Node {
/// `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,
network_timestamp: TimeStamp::ORIGIN,
added: TimeStamp::ORIGIN,
inputs_timestamp: TimeStamp::ORIGIN,
implementation,
implementation_timestamp: TimeStamp::ORIGIN,
inputs: vec![InputSlot::unset(TimeStamp::ORIGIN); inputs],
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::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::new()), 0)
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,
}
}
}
@@ -85,20 +111,24 @@ 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 `timestamp`.
pub fn unset(timestamp: TimeStamp) -> Self {
/// 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: Value::Str("None".to_string()),
value: serde_json::Value::String("None".to_string()),
exposed: false,
},
timestamp,
attributes: Attributes::empty_at(timestamp),
timestamp: at,
attributes: Attributes::new(),
attributes_timestamp: at,
}
}
}
@@ -110,7 +140,7 @@ pub enum NodeInput {
index: u32,
},
Value {
value: Value,
value: serde_json::Value,
exposed: bool,
},
Scope(Cow<'static, str>),
@@ -132,16 +162,16 @@ pub enum Implementation {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Network {
/// The latest addition or write; see [`Node::presence`](crate::Node).
/// When the network was last added; see [`Node::presence`].
#[serde(default)]
pub(crate) presence: TimeStamp,
pub presence: TimeStamp,
pub exports: Vec<ExportSlot>,
/// When the export list last changed shape; see [`Node::inputs_timestamp`](crate::Node).
#[serde(default)]
pub(crate) exports_timestamp: TimeStamp,
/// 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 {
@@ -166,7 +196,7 @@ impl Network {
/// One positional export slot. `target == None` marks an empty/removed slot. Timestamp drives LWW
/// on concurrent `SetExport` ops.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ExportSlot {
pub target: Option<NodeInput>,
pub timestamp: TimeStamp,
@@ -209,7 +239,7 @@ mod tests {
panic!("a fresh slot holds a value input");
};
let tagged: graph_craft::document::value::TaggedValue = crate::from_value(value).expect("the unset slot value must deserialize");
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);
}
+41 -72
View File
@@ -2,9 +2,13 @@ use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry,
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// The live document. Every field, existence included, is last-writer-wins on a timestamp, so the registry depends on the
/// set of ops applied and not their order. A removed entity keeps a tombstone: an older op lands on it, a newer one
/// revives the entity.
/// 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>,
@@ -12,38 +16,42 @@ pub struct Registry {
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
/// by `ResourceId`. See [`ResourceStore`].
pub resources: ResourceStore,
/// Which person each device is, from `RegistryDelta::RegisterPeer`, so undo and authorship scope by person.
/// 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,
/// Tombstones of removed nodes, so an op on one is ordered against its removal whichever arrives first.
#[serde(default)]
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
/// Tombstones of removed networks; see [`removed_nodes`](Self::removed_nodes).
#[serde(default)]
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
/// Tombstones of removed resources; see [`removed_nodes`](Self::removed_nodes).
#[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 timestamp: TimeStamp,
pub at: TimeStamp,
}
/// A removed entity's content, for reviving it, and its removal stamp.
/// 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 timestamp: TimeStamp,
/// Nothing has added the entity yet: it stays dead until an addition folds in, the content holding writes that came first.
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 removed, for a reference to a node the runtime cannot hold.
/// 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))
}
@@ -53,15 +61,14 @@ impl Registry {
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
}
/// The live entities alone, for a document starting a history of its own: tombstones only order removals against ops
/// that share this one.
pub fn without_tombstones(&self) -> Registry {
Registry {
removed_nodes: HashMap::new(),
removed_networks: HashMap::new(),
removed_resources: HashMap::new(),
..self.clone()
/// 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
@@ -133,10 +140,10 @@ impl Registry {
}
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
if a.live().count() != b.live().count() {
if crate::attributes::live(a).count() != crate::attributes::live(b).count() {
return false;
}
a.live().all(|(key, value)| b.get(key).is_some_and(|other| !other.deleted && 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
@@ -154,86 +161,48 @@ pub(crate) fn resources_value_equal(a: &ResourceStore, b: &ResourceStore) -> boo
})
}
/// Stable identity for any timestamp in a `Registry`, tombstoned content and existence stamps included. Used by
/// `order_consistent`.
/// Stable identity for any timestamped slot in a `Registry`. Used by `order_consistent`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum TimestampKey {
/// A whole-entity stamp under its field name: presence, a shape or floor, a removal.
Node(NodeId, &'static str),
NodeInput(NodeId, usize),
NodeInputFloor(NodeId, usize),
NodeInputAttribute(NodeId, usize, String),
NodeAttribute(NodeId, String),
Network(NetworkId, &'static str),
NetworkExport(NetworkId, usize),
NetworkAttribute(NetworkId, String),
DocumentAttribute(String),
Resource(ResourceId, &'static str),
ResourceHash(ResourceId),
ResourceSource(ResourceId, SourceKey),
Document(&'static str),
PeerRegistration(PeerId),
}
fn collect_timestamps(registry: &Registry) -> HashMap<TimestampKey, TimeStamp> {
let mut out = HashMap::new();
let nodes = registry.node_instances.iter().chain(registry.removed_nodes.iter().map(|(id, mark)| (id, &mark.content)));
for (&id, node) in nodes {
for (field, timestamp) in [
("presence", node.presence),
("network", node.network_timestamp),
("inputs", node.inputs_timestamp),
("implementation", node.implementation_timestamp),
("attributes", node.attributes.floor()),
] {
out.insert(TimestampKey::Node(id, field), timestamp);
}
for (node_id, node) in &registry.node_instances {
for (i, slot) in node.inputs.iter().enumerate() {
out.insert(TimestampKey::NodeInput(id, i), slot.timestamp);
out.insert(TimestampKey::NodeInputFloor(id, i), slot.attributes.floor());
out.insert(TimestampKey::NodeInput(*node_id, i), slot.timestamp);
for (key, value) in &slot.attributes {
out.insert(TimestampKey::NodeInputAttribute(id, i, key.clone()), value.timestamp);
out.insert(TimestampKey::NodeInputAttribute(*node_id, i, key.clone()), value.timestamp);
}
}
for (key, value) in &node.attributes {
out.insert(TimestampKey::NodeAttribute(id, key.clone()), value.timestamp);
out.insert(TimestampKey::NodeAttribute(*node_id, key.clone()), value.timestamp);
}
}
let networks = registry.networks.iter().chain(registry.removed_networks.iter().map(|(id, mark)| (id, &mark.content)));
for (&id, network) in networks {
for (field, timestamp) in [("presence", network.presence), ("exports", network.exports_timestamp), ("attributes", network.attributes.floor())] {
out.insert(TimestampKey::Network(id, field), timestamp);
}
for (network_id, network) in &registry.networks {
for (i, slot) in network.exports.iter().enumerate() {
out.insert(TimestampKey::NetworkExport(id, i), slot.timestamp);
out.insert(TimestampKey::NetworkExport(*network_id, i), slot.timestamp);
}
for (key, value) in &network.attributes {
out.insert(TimestampKey::NetworkAttribute(id, key.clone()), value.timestamp);
out.insert(TimestampKey::NetworkAttribute(*network_id, key.clone()), value.timestamp);
}
}
out.insert(TimestampKey::Document("attributes"), registry.attributes.floor());
for (key, value) in &registry.attributes {
out.insert(TimestampKey::DocumentAttribute(key.clone()), value.timestamp);
}
let resources = registry.resources.iter().chain(registry.removed_resources.iter().map(|(id, mark)| (id, &mark.content)));
for (&id, entry) in resources {
for (field, timestamp) in [("presence", entry.presence), ("hash", entry.hash_timestamp), ("sources", entry.sources_timestamp)] {
out.insert(TimestampKey::Resource(id, field), timestamp);
}
for (id, entry) in &registry.resources {
out.insert(TimestampKey::ResourceHash(*id), entry.hash_timestamp);
for (source_key, source_value) in &entry.sources {
out.insert(TimestampKey::ResourceSource(id, *source_key), source_value.timestamp);
out.insert(TimestampKey::ResourceSource(*id, *source_key), source_value.timestamp);
}
}
for (&id, mark) in &registry.removed_nodes {
out.insert(TimestampKey::Node(id, "removed"), mark.timestamp);
}
for (&id, mark) in &registry.removed_networks {
out.insert(TimestampKey::Network(id, "removed"), mark.timestamp);
}
for (&id, mark) in &registry.removed_resources {
out.insert(TimestampKey::Resource(id, "removed"), mark.timestamp);
}
for (&peer, registration) in &registry.peer_users {
out.insert(TimestampKey::PeerRegistration(peer), registration.timestamp);
}
out
}
+79 -60
View File
@@ -1,4 +1,4 @@
use crate::{PeerId, TimeStamp, Value, from_value, to_value};
use crate::{PeerId, TimeStamp};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
@@ -11,15 +11,16 @@ pub struct SourceKey {
pub peer: PeerId,
}
/// One entry in a resource's source chain. The `source` body is type-erased (`Value`)
/// One entry in a resource's source chain. The `source` body is type-erased (`serde_json::Value`)
/// so the on-disk `DataSource` shape can evolve through migrations without the storage layer
/// committing to a Rust enum; `timestamp` drives LWW on re-setting this same entry.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceValue {
pub source: Value,
pub source: serde_json::Value,
pub timestamp: TimeStamp,
/// A removed source stays as a stamped tombstone, which readers see as absent.
#[serde(default)]
/// 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,
}
@@ -27,7 +28,7 @@ impl SourceValue {
/// The tombstone of a source removed at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
source: Value::None,
source: serde_json::Value::Null,
timestamp,
deleted: true,
}
@@ -40,11 +41,12 @@ impl SourceValue {
/// resource agree by construction, since the hash is content-derived).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct ResourceEntry {
/// The latest addition or write; see [`Node::presence`](crate::Node).
pub(crate) presence: TimeStamp,
/// 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; a key the chain lacks is deleted as of then.
/// 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,
@@ -100,7 +102,7 @@ impl ResourceEntry {
/// source entry and the resolved hash carry `timestamp` so later LWW writes order against it.
/// The bytes themselves are persisted separately by the caller's byte store.
pub fn embedded(hash: ResourceHash, peer: PeerId, timestamp: TimeStamp) -> Self {
let embedded = to_value(&graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
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 },
@@ -122,65 +124,82 @@ impl ResourceEntry {
/// The live source stored under `key`, if any; a tombstone is absent.
pub fn source(&self, key: &SourceKey) -> Option<&SourceValue> {
self.find(key).ok().map(|index| &self.sources[index].1).filter(|value| !value.deleted)
self.sources
.binary_search_by(|(candidate, _)| candidate.cmp(key))
.ok()
.map(|index| &self.sources[index].1)
.filter(|value| !value.deleted)
}
/// The live sources in precedence order, tombstones skipped.
pub(crate) fn live_sources(&self) -> impl Iterator<Item = (&SourceKey, &SourceValue)> {
pub fn live_sources(&self) -> impl Iterator<Item = (&SourceKey, &SourceValue)> {
self.sources.iter().filter(|(_, value)| !value.deleted).map(|(key, value)| (key, value))
}
fn find(&self, key: &SourceKey) -> Result<usize, usize> {
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key))
}
/// The stamp that decides a write to `key`: its entry's, tombstone included, or the chain's floor.
fn deciding_timestamp(&self, key: &SourceKey) -> TimeStamp {
self.find(key).map_or(self.sources_timestamp, |index| self.sources[index].1.timestamp)
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.find(&key) {
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)),
}
}
/// Writes the chain whole at `timestamp`: the floor deletes every other key without a tombstone per key.
pub(crate) fn stamp_sources(&mut self, timestamp: TimeStamp) {
/// 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);
self.sources.iter_mut().for_each(|(_, value)| value.timestamp = timestamp);
self.sources_timestamp = timestamp;
for (_, value) in &mut self.sources {
value.timestamp = at;
}
self.sources_timestamp = at;
}
/// Folds another chain in key by key, as attribute maps merge.
/// 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.find(&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)),
_ => {}
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 wins only with a strictly newer stamp.
/// 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.deciding_timestamp(&key) {
if value.timestamp > self.decided(&key) {
self.put(key, value);
}
}
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind, or building an entry).
/// 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 `timestamp` is newer than what decides it, leaving a tombstone. Returns whether it landed.
/// 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.deciding_timestamp(key) {
if timestamp <= self.decided(key) {
return false;
}
self.put(*key, SourceValue::deleted(timestamp));
@@ -201,8 +220,12 @@ 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.live_sources()
.any(|(_, value)| matches!(from_value::<graphene_resource::DataSource>(&value.source), Ok(graphene_resource::DataSource::Embedded)))
self.live_sources().any(|(_, value)| {
matches!(
serde_json::from_value::<graphene_resource::DataSource>(value.source.clone()),
Ok(graphene_resource::DataSource::Embedded)
)
})
}
/// A `SourceKey` ordered strictly ahead of every current source, so an inserted entry becomes the
@@ -292,15 +315,15 @@ mod tests {
}
/// Deserialization routes through `Priority::new`, so a non-finite value on disk is rejected rather
/// than silently producing an unsound map key. Postcard (the storage format) can carry a
/// than silently producing an unsound map key. MessagePack (the storage format) can carry a
/// non-finite `f64`, unlike JSON, so this guards the real round-trip path.
#[test]
fn priority_deserialize_validates_finiteness() {
let finite = postcard::to_stdvec(&3.5_f64).unwrap();
assert!(postcard::from_bytes::<Priority>(&finite).is_ok());
let finite = rmp_serde::to_vec(&3.5_f64).unwrap();
assert!(rmp_serde::from_slice::<Priority>(&finite).is_ok());
let non_finite = postcard::to_stdvec(&f64::INFINITY).unwrap();
assert!(postcard::from_bytes::<Priority>(&non_finite).is_err(), "a non-finite priority on disk must be rejected");
let non_finite = rmp_serde::to_vec(&f64::INFINITY).unwrap();
assert!(rmp_serde::from_slice::<Priority>(&non_finite).is_err(), "a non-finite priority on disk must be rejected");
}
/// `ResourceEntry`'s accessors rely on `sources` being sorted by `SourceKey`. Deserializing an
@@ -315,23 +338,21 @@ mod tests {
peer: PeerId(1),
},
SourceValue {
source: Value::Float(priority),
source: serde_json::json!(priority),
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
)
};
// Build a deliberately unsorted chain as a literal (bypassing the sorted-insert API), then round-trip it through `Value`.
let unsorted = ResourceEntry {
presence: TimeStamp::ORIGIN,
sources_timestamp: TimeStamp::ORIGIN,
sources: vec![source(2.), source(0.), source(1.)],
hash: None,
hash_timestamp: TimeStamp::ORIGIN,
};
// Serialize a deliberately unsorted chain through the raw shape, then deserialize as `ResourceEntry`.
let unsorted = serde_json::json!({
"sources": [source(2.), source(0.), source(1.)],
"hash": null,
"hash_timestamp": TimeStamp::ORIGIN,
});
let entry: ResourceEntry = from_value(&to_value(&unsorted).expect("serialize")).expect("deserialize");
let entry: ResourceEntry = serde_json::from_value(unsorted).expect("deserialize");
let priorities: Vec<f64> = entry.sources.iter().map(|(key, _)| key.priority.value()).collect();
assert_eq!(priorities, vec![0., 1., 2.], "sources must be sorted by SourceKey after deserialization");
}
@@ -348,23 +369,21 @@ mod tests {
(
key,
SourceValue {
source: Value::Str(body.into()),
source: serde_json::json!(body),
timestamp: TimeStamp { counter, peer: PeerId(1) },
deleted: false,
},
)
};
let with_duplicates = ResourceEntry {
presence: TimeStamp::ORIGIN,
sources_timestamp: TimeStamp::ORIGIN,
sources: vec![entry(5, "newer"), entry(1, "older")],
hash: None,
hash_timestamp: TimeStamp::ORIGIN,
};
let with_duplicates = serde_json::json!({
"sources": [entry(5, "newer"), entry(1, "older")],
"hash": null,
"hash_timestamp": TimeStamp::ORIGIN,
});
let resource: ResourceEntry = from_value(&to_value(&with_duplicates).expect("serialize")).expect("deserialize");
let resource: ResourceEntry = serde_json::from_value(with_duplicates).expect("deserialize");
assert_eq!(resource.sources.len(), 1, "duplicate keys must collapse to one entry");
assert_eq!(resource.sources[0].1.source, Value::Str("newer".into()), "the higher-timestamp value must win");
assert_eq!(resource.sources[0].1.source, serde_json::json!("newer"), "the higher-timestamp value must win");
}
}
File diff suppressed because it is too large. Load diff
+556 -38
View File
@@ -1,10 +1,12 @@
use crate::{AttributeDelta, CrdtError, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, Session, UserId, Value};
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(Value::from(serde_json::json!(value))),
value: Some(serde_json::json!(value)),
},
}
}
@@ -16,18 +18,129 @@ fn add_network(id: u64) -> RegistryDelta {
}
}
/// Every op commutes, so the snapshot folds to the working registry's values whatever the log order.
/// 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));
// The log is in arrival order: a guest's later-stamped op sits ahead of an earlier one.
let hot = |op, counter, peer| crate::HotOp {
op,
timestamp: crate::TimeStamp { counter, peer: PeerId(peer) },
// 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 (late, own) = (hot(add_network(9), 50, 2), hot(set_attribute("x", 1), 20, 3));
host.replay_hot_op(late.clone()).expect("the late-stamped op lands first");
host.replay_hot_op(own.clone()).expect("the earlier-stamped op lands second");
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");
@@ -40,51 +153,456 @@ fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
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 newest_peer_registration_wins_in_any_order() {
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");
session.retire(hot.last().expect("staged").timestamp).expect("retire");
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, so the next batch registers again.
device.document.user = UserId(20);
// 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 other = Session::with_peer(PeerId(2));
for delta in device.cloned_deltas().into_iter().rev() {
other.document.apply_op_idempotent(delta.kind, delta.timestamp).unwrap();
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");
}
assert_eq!(other.user_of(PeerId(1)), Some(UserId(20)), "the newest registration wins in any order");
assert_eq!(other.user_of(PeerId(3)), None, "a peer never registered has no user");
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 a_refused_local_op_leaves_the_working_registry_unchanged() {
let mut s = Session::with_peer(PeerId(1));
let node = Node::new(NetworkId(1), Implementation::Network(NetworkId(1)), 1);
s.stage_ops([
RegistryDelta::AddNetwork {
id: NetworkId(1),
network: Network::default(),
},
RegistryDelta::AddNode { id: NodeId(1), node },
])
.unwrap();
let before = s.registry().clone();
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 refused = s.stage_ops([RegistryDelta::ChangeNodeInput {
id: NodeId(1),
index: 0,
new_input: NodeInput::Node { id: NodeId(404), index: 0 },
}]);
assert!(matches!(refused, Err(CrdtError::TargetNodeDoesNotExist(_))));
assert_eq!(s.registry(), &before, "the refused op's write to node 1 stayed in the working registry");
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");
}
File diff suppressed because it is too large. Load diff
@@ -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(_))));
}
+13 -8
View File
@@ -7,7 +7,7 @@ use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput,
use graph_craft::graphene_compiler::Compiler;
use graph_craft::{ProtoNodeIdentifier, Type, concrete};
use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry, from_value};
use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry};
/// Helper function to verify a NodeNetwork can be compiled successfully.
/// Note: This only works for complete networks with all inputs resolved.
@@ -530,7 +530,7 @@ fn resources_round_trip_through_from_runtime() {
assert_eq!(entry.sources.len(), 2, "both sources carried through");
// The chain iterates in priority order; decode bodies back to DataSource to compare.
let decoded: Vec<DataSource> = entry.sources.iter().map(|(_, v)| from_value(&v.source).expect("source body decodes")).collect();
let decoded: Vec<DataSource> = entry.sources.iter().map(|(_, v)| serde_json::from_value(v.source.clone()).expect("source body decodes")).collect();
assert_eq!(decoded, vec![DataSource::Embedded, DataSource::Url("https://example.com/img.png".parse().unwrap())]);
// All source keys carry the document peer.
@@ -609,9 +609,10 @@ 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::Number` must survive the storage round-trip bit-exact. Inputs are stored
/// type-erased as a `Value`, so this guards against any precision loss in the f64
/// -> Value -> f64 path for a value with a full 17-significant-digit mantissa.
/// 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.
#[test]
fn node_input_f64_round_trips_bit_exact() {
use graph_craft::document::value::TaggedValue;
@@ -650,6 +651,7 @@ fn node_input_f64_round_trips_bit_exact() {
/// Conversion must reject this rather than silently collapse them and drop a node.
#[test]
fn duplicate_runtime_node_id_is_rejected() {
use crate::AttributesWrite;
use crate::TimeStamp;
use crate::to_runtime::ConversionError;
@@ -657,7 +659,7 @@ fn duplicate_runtime_node_id_is_rejected() {
// Force both root-network nodes onto the same runtime ID.
for node in registry.node_instances.values_mut() {
node.attributes.set(crate::attr::node::ORIGINAL_NODE_ID, crate::Value::Int(7), TimeStamp::ORIGIN);
node.attributes.set(crate::attr::node::ORIGINAL_NODE_ID, serde_json::json!(7), TimeStamp::ORIGIN);
}
let error = registry.to_runtime_with_metadata(&declarations).expect_err("duplicate runtime ID must error");
@@ -716,6 +718,7 @@ fn scope_injections_round_trip() {
/// network) must error rather than emit an injection pointing at a nonexistent runtime node.
#[test]
fn dangling_scope_injection_is_rejected() {
use crate::AttributesWrite;
use crate::TimeStamp;
use crate::to_runtime::ConversionError;
@@ -756,12 +759,13 @@ fn cyclic_network_reference_is_rejected() {
crate::NodeId(0),
Node {
presence: Default::default(),
network_timestamp: 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,
},
);
@@ -769,12 +773,13 @@ fn cyclic_network_reference_is_rejected() {
crate::NodeId(1),
Node {
presence: Default::default(),
network_timestamp: 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,
},
);
+143 -13
View File
@@ -10,7 +10,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
use crate::attr::*;
use crate::metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry};
use crate::{Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
use crate::{AttributesRead, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId};
#[derive(Debug, thiserror::Error)]
pub enum ConversionError {
@@ -51,6 +51,9 @@ impl Registry {
let mut node_metadata = Some(Vec::new());
let mut network_metadata = Some(Vec::new());
// 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 context = ConversionContext::new(self, declarations);
// Reject cycles up front so the recursive conversion below can assume the network reference
@@ -63,7 +66,7 @@ impl Registry {
/// Rebuild the runtime [`ResourceRegistry`](graphene_resource::ResourceRegistry) from the stored
/// `resources`. Each entry's source chain is restored in priority order (the chain is kept
/// sorted by key) with bodies decoded from their type-erased `Value` form back to
/// sorted by key) with bodies decoded from their type-erased `serde_json::Value` form back to
/// `DataSource`; the resolved hash, if any, is restored last. Inverse of `convert_resources` in
/// `from_runtime`.
pub fn to_resource_registry(&self) -> Result<graphene_resource::ResourceRegistry, ConversionError> {
@@ -71,7 +74,7 @@ impl Registry {
for (id, entry) in &self.resources {
for (_, source) in entry.live_sources() {
let decoded: graphene_resource::DataSource = from_value(&source.source).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
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);
}
if let Some(hash) = entry.hash {
@@ -106,10 +109,139 @@ impl<'a> ConversionContext<'a> {
}
}
/// The id the node had in the runtime it was converted from, kept as an attribute so a conversion back
/// lands it under the id the editor's metadata is keyed by.
/// 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_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0))
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.
@@ -298,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, Value> = attributes
.live()
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();
@@ -341,14 +472,13 @@ 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 } => {
// A node removed concurrently keeps its id, as the editor holds a dangling input. So does one whose addition has not
// arrived yet, though its placeholder knows nothing of its network.
// 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))?;
let placeholder = registry.removed_nodes.get(node_id).is_some_and(|mark| mark.placeholder);
// 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.
if !placeholder && referenced.network != network_id {
if referenced.network != network_id {
return Err(ConversionError::CrossNetworkReference {
network: network_id,
referenced: *node_id,
@@ -361,7 +491,7 @@ fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput,
}
}
NodeInput::Value { value, exposed } => {
let tagged_value: TaggedValue = from_value(value).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
let tagged_value: TaggedValue = serde_json::from_value(value.clone()).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
GraphCraftNodeInput::Value {
tagged_value: MemoHash::new(tagged_value),
exposed: *exposed,
+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)]));
}
}
-265
View File
@@ -1,265 +0,0 @@
use serde::de::{self, DeserializeOwned, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
pub fn to_value<T: Serialize + ?Sized>(value: &T) -> Result<Value, ValueError> {
serde_json::to_value(value).map(Value::from).map_err(ValueError)
}
pub fn from_value<T: DeserializeOwned>(value: &Value) -> Result<T, ValueError> {
serde_json::from_value(value.clone().into()).map_err(ValueError)
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self")]
pub enum Value {
None,
Bool(bool),
Int(i128),
Float(f64),
Str(String),
Array(Vec<Value>),
Object(Vec<(String, Value)>),
}
// Using `Serializer::is_human_readable` to determine whether to serialize tagged.
// We assume that any human-readable format is self describing and does not need tags.
impl Serialize for Value {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if !serializer.is_human_readable() {
return Value::serialize(self, serializer);
}
match self {
Value::None => serializer.serialize_unit(),
Value::Bool(boolean) => serializer.serialize_bool(*boolean),
Value::Int(int) => serializer.serialize_i128(*int),
Value::Float(float) => serializer.serialize_f64(*float),
Value::Str(string) => serializer.serialize_str(string),
Value::Array(array) => serializer.collect_seq(array),
Value::Object(object) => serializer.collect_map(object.iter().map(|(key, value)| (key, value))),
}
}
}
// Using `Deserialize::is_human_readable` to determine whether to deserialize tagged.
// We assume that any human-readable format is self describing and does not need tags.
impl<'de> Deserialize<'de> for Value {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if !deserializer.is_human_readable() {
return Value::deserialize(deserializer);
}
struct Untagged;
impl<'de> Visitor<'de> for Untagged {
type Value = Value;
fn visit_unit<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_none<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Value, D::Error> {
Deserialize::deserialize(deserializer)
}
fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
Ok(Value::Bool(value))
}
fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_u64<E>(self, value: u64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_i128<E>(self, value: i128) -> Result<Value, E> {
Ok(Value::Int(value))
}
fn visit_u128<E: de::Error>(self, value: u128) -> Result<Value, E> {
i128::try_from(value).map(Value::Int).map_err(E::custom)
}
fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
Ok(Value::Float(value))
}
fn visit_str<E>(self, value: &str) -> Result<Value, E> {
Ok(Value::Str(value.to_owned()))
}
fn visit_string<E>(self, value: String) -> Result<Value, E> {
Ok(Value::Str(value))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {
let mut array = Vec::with_capacity(seq.size_hint().unwrap_or(0));
while let Some(value) = seq.next_element()? {
array.push(value);
}
Ok(Value::Array(array))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
let mut object: Vec<(String, Value)> = Vec::with_capacity(map.size_hint().unwrap_or(0));
while let Some(entry) = map.next_entry()? {
object.push(entry);
}
object.sort_by(|a, b| a.0.cmp(&b.0));
object.dedup_by(|b, a| {
let dedup = b.0 == a.0;
if dedup {
std::mem::swap(&mut a.1, &mut b.1);
}
dedup
});
Ok(Value::Object(object))
}
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid Value")
}
}
deserializer.deserialize_any(Untagged)
}
}
impl From<serde_json::Value> for Value {
fn from(value: serde_json::Value) -> Self {
use serde_json::Value as Json;
match value {
Json::Null => Value::None,
Json::Bool(boolean) => Value::Bool(boolean),
Json::Number(number) => {
if let Some(int) = number.as_i64() {
Value::Int(int.into())
} else if let Some(int) = number.as_u64() {
Value::Int(int.into())
} else {
Value::Float(number.as_f64().unwrap_or(f64::NAN))
}
}
Json::String(string) => Value::Str(string),
Json::Array(array) => Value::Array(array.into_iter().map(Into::into).collect()),
Json::Object(object) => Value::Object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
}
}
}
impl From<Value> for serde_json::Value {
fn from(value: Value) -> Self {
use serde_json::Value as Json;
match value {
Value::None => Json::Null,
Value::Bool(boolean) => Json::Bool(boolean),
Value::Int(int) => match (i64::try_from(int), u64::try_from(int)) {
(Ok(int), _) => int.into(),
(_, Ok(int)) => int.into(),
(Err(_), Err(_)) => (int as f64).into(),
},
Value::Float(float) => float.into(),
Value::Str(string) => Json::String(string),
Value::Array(array) => Json::Array(array.into_iter().map(Into::into).collect()),
Value::Object(object) => Json::Object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
}
}
}
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct ValueError(serde_json::Error);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_through_postcard() {
let value = serde_json::json!({
"null": null,
"bools": [true, false],
"ints": [0, -1, i64::MIN, u64::MAX],
"floats": [1.5, -0.25, 1e300],
"str": "text",
"empty": { "array": [], "object": {} },
"nested": { "b": [{ "c": 1 }], "a": "z" },
});
let bytes = postcard::to_stdvec(&Value::from(value.clone())).unwrap();
let decoded: Value = postcard::from_bytes(&bytes).unwrap();
assert_eq!(serde_json::Value::from(decoded), value);
}
#[test]
fn round_trips_through_json_untagged() {
let json = serde_json::json!({ "a": [1, -2, 2.5, "s", null, true], "b": {}, "c": [] });
let value = Value::from(json.clone());
let text = serde_json::to_string(&value).unwrap();
assert_eq!(text, serde_json::to_string(&json).unwrap());
assert_eq!(serde_json::to_value(&value).unwrap(), json);
assert_eq!(serde_json::from_str::<Value>(&text).unwrap(), value);
}
#[test]
fn json_object_keys_sort_and_last_duplicate_wins() {
let value: Value = serde_json::from_str(r#"{"b": 1, "a": 2, "b": 3}"#).unwrap();
assert_eq!(value, Value::Object(vec![("a".into(), Value::Int(2)), ("b".into(), Value::Int(3))]));
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
enum Sample {
Unit,
Newtype(u8),
Tuple(i64, String),
Struct { flag: bool, nested: Option<Box<Sample>> },
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Record {
samples: Vec<Sample>,
by_id: std::collections::BTreeMap<u32, f64>,
bytes: Vec<u8>,
letter: char,
unit: (),
big: u64,
}
fn record() -> Record {
Record {
samples: vec![
Sample::Unit,
Sample::Newtype(7),
Sample::Tuple(-3, "t".into()),
Sample::Struct {
flag: true,
nested: Some(Box::new(Sample::Unit)),
},
Sample::Struct { flag: false, nested: None },
],
by_id: [(2, 0.5), (10, -1.)].into(),
bytes: vec![0, 255],
letter: 'x',
unit: (),
big: u64::MAX,
}
}
#[test]
fn from_value_round_trips_serde_types() {
assert_eq!(from_value::<Record>(&to_value(&record()).unwrap()).unwrap(), record());
}
#[test]
fn number_variants_map_to_serde_json_numbers() {
let json = |value: Value| serde_json::Value::from(value);
assert_eq!(json(Value::Int(u64::MAX.into())), serde_json::json!(u64::MAX));
assert_eq!(json(Value::Int(-1)), serde_json::json!(-1));
assert_eq!(json(Value::Int(i128::MAX)), serde_json::json!(i128::MAX as f64));
assert_eq!(json(Value::Float(2.)), serde_json::json!(2.));
assert_eq!(Value::from(serde_json::json!(2.)), Value::Float(2.));
assert_eq!(Value::from(serde_json::json!(2)), Value::Int(2));
}
#[test]
fn postcard_tags_follow_declaration_order() {
let encode = |value: Value| postcard::to_stdvec(&value).unwrap();
assert_eq!(encode(Value::None), [0]);
assert_eq!(encode(Value::Bool(true)), [1, 1]);
assert_eq!(encode(Value::Int(-1)), [2, 1]);
assert_eq!(encode(Value::Float(0.)), [3, 0, 0, 0, 0, 0, 0, 0, 0]);
assert_eq!(encode(Value::Str("ab".into())), [4, 2, b'a', b'b']);
assert_eq!(encode(Value::Array(vec![Value::None])), [5, 1, 0]);
assert_eq!(encode(Value::Object(vec![("k".into(), Value::None)])), [6, 1, 1, b'k', 0]);
}
}
+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 -6
View File
@@ -4,15 +4,9 @@ version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[features]
default = ["gpu"]
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen"]
@@ -25,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
-21
View File
@@ -1,21 +0,0 @@
[package]
name = "graphite-editor-control-protocol"
description = "The commands, results, and scenarios that scripts, QA, and agents use to operate the Graphite editor"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[dependencies]
# Workspace dependencies
serde = { workspace = true }
serde_json = { workspace = true }
glam = { workspace = true, features = ["serde"] }
-354
View File
@@ -1,354 +0,0 @@
//! The commands that scripts, QA, and agents send to operate the Graphite editor the way a person does, the results they get back,
//! the scenario files that hold a sequence of commands, and the messages that carry them between a client and an editor host.
//!
//! Each message travels as one line of JSON.
use glam::{DVec2, UVec2};
use serde::{Deserialize, Serialize};
use std::num::NonZeroU32;
use std::path::PathBuf;
/// Increases whenever a change would break a client or host written against an earlier version.
pub const PROTOCOL_VERSION: u32 = 1;
/// Which origin a point is measured from.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Space {
/// The page's top left corner.
#[default]
Page,
/// The document viewport's top left corner.
Viewport,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MouseButton {
#[default]
Left,
Middle,
Right,
}
/// An area of the page, in CSS pixels.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct Rectangle {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
/// Frames captured along a drag and laid out in one image, each marked with where the pointer was.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Filmstrip {
/// Where the image is written, with a relative path landing in the host's output directory.
pub path: PathBuf,
/// How many frames to capture, spread evenly along the drag.
pub frames: Option<NonZeroU32>,
/// Limits each frame to the document viewport (`"viewport"`) or the first element matching a CSS selector.
pub region: Option<String>,
/// Limits each frame to an exact area of the page, overriding the region.
pub clip: Option<Rectangle>,
}
/// One step of operating the editor with the mouse and keyboard, or of observing the result.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase", deny_unknown_fields)]
pub enum Command {
/// Moves the pointer one small step per rendered frame, as a real pointer does, or in the given number of steps.
Move { to: DVec2, space: Option<Space>, steps: Option<NonZeroU32> },
/// Presses a mouse button.
Down { button: Option<MouseButton> },
/// Releases a mouse button.
Up { button: Option<MouseButton> },
/// Moves the pointer to a point and clicks there, with the keys held from before the first press.
Click {
at: DVec2,
space: Option<Space>,
button: Option<MouseButton>,
count: Option<NonZeroU32>,
keys: Option<Vec<String>>,
},
/// Drags between two points with the keys held from before the press.
/// With `release` set to false, the button and keys stay held once the drag succeeds.
Drag {
from: DVec2,
to: DVec2,
space: Option<Space>,
button: Option<MouseButton>,
keys: Option<Vec<String>>,
steps: Option<NonZeroU32>,
release: Option<bool>,
filmstrip: Option<Filmstrip>,
},
/// Holds a key, named as in `KeyboardEvent.key` or `KeyboardEvent.code`, such as `Shift` or `KeyP`.
KeyDown { key: String },
/// Releases a held key.
KeyUp { key: String },
/// Taps a key, or a combination such as `Control+KeyZ`, where a final `+` is the plus key itself.
Press { key: String },
/// Types text into the focused field.
Type { text: String },
/// Turns the mouse wheel, in notches of up to 100 pixels, optionally after moving the pointer to a point.
Scroll { delta: DVec2, at: Option<DVec2>, space: Option<Space> },
/// Pauses for a number of milliseconds.
Wait { milliseconds: u64 },
/// Waits until the editor stops redrawing, giving up after the timeout in milliseconds.
WaitIdle { timeout: Option<u64> },
/// Captures the page, or part of it, optionally marking the pointer with a crosshair.
Screenshot {
path: PathBuf,
cursor: Option<bool>,
region: Option<String>,
clip: Option<Rectangle>,
},
/// Finds elements by a `data-*` attribute name, the visible text they contain, or both.
Locate { data: Option<String>, text: Option<String> },
/// Fails unless the page shows the expected elements, found as `locate` finds them and narrowed to those with a field holding `value`.
/// With only a `value`, it looks among every field. It expects exactly `count` elements, or at least one without a count.
Expect {
data: Option<String>,
text: Option<String>,
value: Option<String>,
count: Option<u32>,
},
/// Changes the size of the page, in CSS pixels.
Resize { size: UVec2 },
/// Reports the state of the session.
Status {},
}
impl Command {
/// The name the command is given by its `type` field.
pub fn name(&self) -> &'static str {
match self {
Command::Move { .. } => "move",
Command::Down { .. } => "down",
Command::Up { .. } => "up",
Command::Click { .. } => "click",
Command::Drag { .. } => "drag",
Command::KeyDown { .. } => "keyDown",
Command::KeyUp { .. } => "keyUp",
Command::Press { .. } => "press",
Command::Type { .. } => "type",
Command::Scroll { .. } => "scroll",
Command::Wait { .. } => "wait",
Command::WaitIdle { .. } => "waitIdle",
Command::Screenshot { .. } => "screenshot",
Command::Locate { .. } => "locate",
Command::Expect { .. } => "expect",
Command::Resize { .. } => "resize",
Command::Status {} => "status",
}
}
}
/// An element found by a `locate` command.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Located {
#[serde(rename = "box")]
pub bounds: Rectangle,
pub center: DVec2,
/// The start of the element's text, with its whitespace collapsed.
pub text: String,
/// What the element holds if it is a field, or else what the first field inside it holds.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionStatus {
pub url: String,
pub size: UVec2,
pub pointer: DVec2,
/// Where the document viewport is on the page, if one is open.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub viewport: Option<Rectangle>,
pub held_keys: Vec<String>,
pub held_buttons: Vec<MouseButton>,
pub crashed: bool,
}
/// What came of one command.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CommandResult {
/// The `type` of the command this reports on.
#[serde(rename = "type")]
pub command: String,
pub ok: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
/// Where a screenshot or filmstrip was written.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<PathBuf>,
/// The pointer's position on the page in each frame of a filmstrip, in the order the frames are laid out.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub frames: Option<Vec<DVec2>>,
/// Whether the editor stopped redrawing before the timeout.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stable: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub located: Option<Vec<Located>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<SessionStatus>,
/// The errors the page logged since the previous command, or for the first, since it loaded.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub console_errors: Vec<String>,
}
impl CommandResult {
pub fn succeeded(command: &Command) -> Self {
Self {
command: command.name().to_string(),
ok: true,
..Default::default()
}
}
pub fn failed(command: &Command, error: String) -> Self {
Self {
command: command.name().to_string(),
ok: false,
error: Some(error),
..Default::default()
}
}
}
/// Reads the steps of a scenario file, which holds one command per line written as JSON, leaving out blank lines and `//` comments.
pub fn parse_scenario(text: &str) -> Result<Vec<Command>, String> {
text.lines()
.enumerate()
.filter(|(_, line)| {
let line = line.trim();
!line.is_empty() && !line.starts_with("//")
})
.map(|(index, line)| serde_json::from_str(line).map_err(|error| format!("Line {}: {error}", index + 1)))
.collect()
}
/// A message from a client to an editor host.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum ClientMessage {
/// Attaches to the session, which the host refuses unless the protocol version matches and the token is the host's own.
Attach { version: u32, token: String },
/// Performs commands in order, stopping at the first that fails, since the later ones were written assuming it succeeded.
/// With `fail_on_console_errors`, a command also fails if the page has logged an error since the previous one.
Perform {
id: u64,
commands: Vec<Command>,
#[serde(default)]
fail_on_console_errors: bool,
},
/// Ends the session and closes the editor.
Shutdown,
}
/// A message from an editor host to a client.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum HostMessage {
/// Accepts a connection, naming the host's process so a client can tell it apart from one that has replaced it.
Attached { version: u32, process_id: u32 },
/// Turns away a connection, after which the host closes it.
Refused { reason: String },
/// Reports on each command performed, in order.
Results { id: u64, results: Vec<CommandResult> },
/// Confirms a shutdown, after which the connection closes once the host has exited.
ShuttingDown,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scenario_steps_parse() {
let steps = parse_scenario(
r#"// Draw a rectangle
{ "type": "resize", "size": [1600, 1000] }
{ "type": "press", "key": "KeyM" }
// Drag out the rectangle
{ "type": "drag", "from": [200, 150], "to": [500, 350], "space": "viewport", "filmstrip": { "path": "drag.png", "frames": 4 } }
{ "type": "waitIdle" }
{ "type": "screenshot", "path": "rectangle.png", "region": "viewport" }
{ "type": "status" }
"#,
)
.unwrap();
assert_eq!(steps.len(), 6);
assert_eq!(steps[0], Command::Resize { size: UVec2::new(1600, 1000) });
assert!(
matches!(&steps[2], Command::Drag { to, space: Some(Space::Viewport), filmstrip: Some(Filmstrip { frames: Some(frames), .. }), .. } if *to == DVec2::new(500., 350.) && frames.get() == 4)
);
assert_eq!(steps[5], Command::Status {});
}
#[test]
fn scenario_mistakes_name_their_line() {
let error = parse_scenario("// A mistake on the third line\n{ \"type\": \"status\" }\n{ \"type\": \"teleport\" }").unwrap_err();
assert!(error.starts_with("Line 3:"));
}
#[test]
fn qa_fields_parse() {
let steps = parse_scenario("{ \"type\": \"expect\", \"data\": \"layer\", \"count\": 0 }\n{ \"type\": \"expect\", \"value\": \"500.26\" }").unwrap();
assert!(matches!(steps[0], Command::Expect { count: Some(0), .. }));
assert!(matches!(&steps[1], Command::Expect { value: Some(value), count: None, .. } if value == "500.26"));
// Clients that predate the option leave it out
let perform: ClientMessage = serde_json::from_str(r#"{ "type": "perform", "id": 1, "commands": [] }"#).unwrap();
assert!(matches!(perform, ClientMessage::Perform { fail_on_console_errors: false, .. }));
}
#[test]
fn mistakes_are_refused() {
// A misspelled field
assert!(serde_json::from_str::<Command>(r#"{ "type": "move", "to": [1, 2], "stpes": 3 }"#).is_err());
// A count that must be a positive integer
assert!(serde_json::from_str::<Command>(r#"{ "type": "click", "at": [1, 2], "count": 0 }"#).is_err());
// An unknown command
assert!(serde_json::from_str::<Command>(r#"{ "type": "teleport", "to": [1, 2] }"#).is_err());
// A field on a command that takes none
assert!(serde_json::from_str::<Command>(r#"{ "type": "status", "milliseconds": 5 }"#).is_err());
}
#[test]
fn names_match_the_type_field() {
let commands = [Command::KeyDown { key: "Shift".into() }, Command::WaitIdle { timeout: None }, Command::Status {}];
for command in commands {
let json = serde_json::to_value(&command).unwrap();
assert_eq!(json["type"], command.name());
}
}
}
+2 -2
View File
@@ -14,14 +14,14 @@ impl Editor {
environment: Environment,
uuid_random_seed: u64,
resource_storage: Arc<dyn ResourceStorage>,
document_store: Arc<dyn document_container::store::DocumentStore>,
working_copy_root: Option<std::path::PathBuf>,
mut application_io: PlatformApplicationIo,
wake: Wake,
) -> Self {
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
let mut dispatcher = Dispatcher::new(resource_storage, document_store);
let mut dispatcher = Dispatcher::new(resource_storage, working_copy_root);
dispatcher.message_handlers.future_message_handler.set_wake(wake);
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
crate::node_graph_executor::replace_application_io(application_io);
-10
View File
@@ -37,10 +37,6 @@ pub const VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR: f64 = 0.95;
pub const DRAG_BEYOND_VIEWPORT_MAX_OVEREXTENSION_PIXELS: f64 = 50.;
pub const DRAG_BEYOND_VIEWPORT_SPEED_FACTOR: f64 = 20.;
/// How long a dragged wire must stay beyond the node graph's edge before auto-panning begins, so passing over to another panel doesn't pan.
pub const WIRE_DRAG_AUTO_PAN_DELAY_MILLISECONDS: u64 = 400;
/// How long a dragged wire must rest over a node before the node reveals its hidden inputs the wire could connect to.
pub const WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS: u64 = 250;
// SNAPPING POINT
pub const SNAP_POINT_TOLERANCE: f64 = 5.;
@@ -191,17 +187,11 @@ pub const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 1;
// INPUT
pub const DOUBLE_CLICK_MILLISECONDS: u64 = 500;
/// Maximum duration of the whole double-tap gesture, measured from the first tap's key-down to the second tap's key-up.
pub const DOUBLE_TAP_MILLISECONDS: u64 = 1000;
// UI
pub const UI_SCALE_DEFAULT: f64 = 1.;
pub const UI_SCALE_MIN: f64 = 0.5;
pub const UI_SCALE_MAX: f64 = 3.;
// DIALOGS
pub const MAX_UNSAVED_DOCUMENTS_IN_DIALOG: usize = 5;
pub const MAX_DOCUMENT_NAME_LENGTH_IN_DIALOG: usize = 60;
// ACTIONS
pub const BLEND_COUNT_PER_LAYER: usize = 10;
+11 -35
View File
@@ -2,7 +2,6 @@ use crate::messages::debug::utility_types::MessageLoggingVerbosity;
use crate::messages::defer::DeferMessageContext;
use crate::messages::dialog::DialogMessageContext;
use crate::messages::layout::layout_message_handler::LayoutMessageContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::preferences::preferences_message_handler::PreferencesMessageContext;
use crate::messages::prelude::*;
@@ -65,9 +64,6 @@ const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
NodeGraphMessageDiscriminant::RunDocumentGraph,
))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
NodeGraphMessageDiscriminant::UpdateLayerPanel,
))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitActiveGraphRender),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::SubmitEyedropperPreviewRender),
MessageDiscriminant::Frontend(FrontendMessageDiscriminant::UpdateUIScale),
@@ -93,19 +89,16 @@ const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"];
impl Dispatcher {
pub fn new(resource_storage: Arc<dyn ResourceStorage>, document_store: Arc<dyn document_container::store::DocumentStore>) -> Self {
pub fn new(resource_storage: Arc<dyn ResourceStorage>, working_copy_root: Option<std::path::PathBuf>) -> Self {
let mut s = Self::default();
s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage);
s.message_handlers.portfolio_message_handler.set_document_store(document_store);
s.message_handlers.portfolio_message_handler.set_working_copy_root(working_copy_root);
s
}
#[cfg(test)]
pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self {
let mut s = Self::new(
Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()),
Arc::new(document_container::store::MemoryStore::default()),
);
let mut s = Self::new(Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()), None);
s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor);
s
}
@@ -262,7 +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,
tool_edit_target: &self.message_handlers.tool_message_handler.edit_target,
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,
@@ -277,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;
@@ -289,45 +284,26 @@ impl Dispatcher {
.active_document_id
.and_then(|document_id| self.message_handlers.portfolio_message_handler.documents.get_mut(&document_id))
{
let selected_nodes = document.network_interface.selected_nodes_in_nested_network(document.selection_network_path()).unwrap_or_default();
let network_interface = &document.network_interface;
let layer_metadata = document.metadata();
let metadata = &network_interface.document_network_metadata().persistent_metadata;
// Layers only exist in the document network, so a selection inside a subgraph has none
let in_document_network = document.selection_network_path().is_empty();
let selected_nodes = document.network_interface.selected_nodes();
let metadata = &document.network_interface.document_network_metadata().persistent_metadata;
menu_bar_message_handler.has_active_document = true;
menu_bar_message_handler.canvas_tilted = document.document_ptz.tilt() != 0.;
menu_bar_message_handler.canvas_flipped = document.document_ptz.flip;
menu_bar_message_handler.rulers_visible = document.rulers_visible;
menu_bar_message_handler.node_graph_open = document.is_graph_overlay_open();
menu_bar_message_handler.has_artboards = LayerNodeIdentifier::ROOT_PARENT
.children(layer_metadata)
.any(|layer| network_interface.is_artboard(&layer.to_node(), &[]));
menu_bar_message_handler.has_selected_nodes = selected_nodes.selected_nodes().next().is_some();
menu_bar_message_handler.has_selected_layers = in_document_network && selected_nodes.selected_layers(layer_metadata).next().is_some();
menu_bar_message_handler.has_selected_visible_layers = in_document_network && selected_nodes.selected_visible_layers(network_interface).next().is_some();
menu_bar_message_handler.has_selected_visible_and_unlocked_layers =
in_document_network && selected_nodes.selected_visible_and_unlocked_layers(network_interface).next().is_some();
menu_bar_message_handler.has_selected_groups = in_document_network
&& selected_nodes
.selected_layers(layer_metadata)
.any(|layer| layer.has_children(layer_metadata) && !network_interface.is_artboard(&layer.to_node(), &[]));
menu_bar_message_handler.has_selected_layers = selected_nodes.selected_visible_layers(&document.network_interface).next().is_some();
menu_bar_message_handler.has_selection_history = (!metadata.selection_undo_history.is_empty(), !metadata.selection_redo_history.is_empty());
menu_bar_message_handler.make_path_editable_is_allowed = in_document_network && make_path_editable_is_allowed(&mut document.network_interface).is_some();
menu_bar_message_handler.make_path_editable_is_allowed = make_path_editable_is_allowed(&mut document.network_interface).is_some();
} else {
menu_bar_message_handler.has_active_document = false;
menu_bar_message_handler.canvas_tilted = false;
menu_bar_message_handler.canvas_flipped = false;
menu_bar_message_handler.rulers_visible = false;
menu_bar_message_handler.node_graph_open = false;
menu_bar_message_handler.has_artboards = false;
menu_bar_message_handler.has_selected_nodes = false;
menu_bar_message_handler.has_selected_layers = false;
menu_bar_message_handler.has_selected_visible_layers = false;
menu_bar_message_handler.has_selected_visible_and_unlocked_layers = false;
menu_bar_message_handler.has_selected_groups = false;
menu_bar_message_handler.has_selection_history = (false, false);
menu_bar_message_handler.make_path_editable_is_allowed = false;
}
@@ -514,7 +490,7 @@ mod test {
});
// Check if the graph renders
if let Err(e) = editor.eval_graph_until_finished().await {
if let Err(e) = editor.eval_graph().await {
print_problem_to_terminal_on_failure(&format!("Failed to evaluate the graph for document '{document_name}':\n{e}"));
}
-2
View File
@@ -19,5 +19,3 @@ pub mod node_graph_executor;
pub mod test_utils;
pub mod utility_traits;
pub mod utility_types;
pub use document_container::store as document_store;
@@ -1,6 +1,5 @@
use crate::consts::DEFAULT_STROKE_WIDTH;
use crate::messages::clipboard::utility_types::{ClipboardContent, ClipboardContentRaw, ClipboardItem, ClipboardLayer, ClipboardResource, ResourceData};
use crate::messages::portfolio::document::SelectionParts;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -80,18 +79,23 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
}
ClipboardMessage::CopyLayers => {
let Some(active_document) = portfolio.active_document() else { return };
// The Path tool copies the points it's editing in the viewport
if current_tool == &ToolType::Path && !active_document.graph_view_overlay_open() {
if current_tool == &ToolType::Path {
responses.add(PathToolMessage::Copy);
return;
}
let SelectionParts { layers, chain_nodes, other_nodes } = active_document.partition_selection();
let mut items = Vec::new();
let Some(active_document) = portfolio.active_document_id.and_then(|id| portfolio.documents.get_mut(&id)) else {
return;
};
let mut ordered_last_elements = layers;
if active_document.graph_view_overlay_open() {
responses.add(NodeGraphMessage::Copy);
return;
}
let mut buffer = Vec::new();
let mut ordered_last_elements = active_document.network_interface.shallowest_unique_layers(&[]).collect::<Vec<_>>();
ordered_last_elements.sort_by_key(|layer| {
let Some(parent) = layer.parent(active_document.metadata()) else { return usize::MAX };
DocumentMessageHandler::get_calculated_insert_index(active_document.metadata(), &SelectedNodes(vec![layer.to_node()]), parent)
@@ -119,69 +123,38 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
.collect::<Vec<_>>();
tree_path.reverse();
items.push(ClipboardItem::Layer(ClipboardLayer {
buffer.push(ClipboardLayer {
nodes: active_document.network_interface.copy_nodes(&copy_ids, &[]).collect(),
visible: active_document.network_interface.selected_nodes().layer_visible(layer, &active_document.network_interface),
locked: active_document.network_interface.selected_nodes().layer_locked(layer, &active_document.network_interface),
collapsed: active_document.collapsed.0.contains(&tree_path),
}));
});
}
let copies = chain_nodes
.iter()
.filter_map(|node_id| active_document.network_interface.copy_chain_node(node_id, &[]))
.collect::<Vec<_>>();
if !copies.is_empty() {
items.push(ClipboardItem::ChainNodes(copies));
}
// Other nodes are kept under their own IDs, so a paste can tell when it's over the same nodes
if !other_nodes.is_empty() {
let copy_ids = active_document.with_layer_content(&other_nodes).into_iter().map(|node_id| (node_id, node_id)).collect();
let nodes = active_document.network_interface.copy_nodes(&copy_ids, active_document.selection_network_path()).collect();
items.push(ClipboardItem::Nodes(nodes));
}
responses.add(ClipboardMessage::WriteItems { items });
responses.add(ClipboardMessage::WriteItems {
items: buffer.into_iter().map(ClipboardItem::Layer).collect(),
});
}
ClipboardMessage::CutLayers => {
let Some(active_document) = portfolio.active_document() else { return };
if current_tool == &ToolType::Path && !active_document.graph_view_overlay_open() {
if current_tool == &ToolType::Path {
responses.add(PathToolMessage::Cut);
return;
}
let SelectionParts { layers, chain_nodes, other_nodes } = active_document.partition_selection();
responses.add(ClipboardMessage::CopyLayers);
// Layers and other nodes go along with what only they use, while chain nodes go alone so pasting them can wire back to what fed them
let deleted_with_children = layers.iter().map(|layer| layer.to_node()).chain(other_nodes).collect::<Vec<_>>();
if deleted_with_children.is_empty() && chain_nodes.is_empty() {
if let Some(active_document) = portfolio.active_document()
&& active_document.graph_view_overlay_open()
{
responses.add(NodeGraphMessage::Cut);
return;
}
responses.add(DocumentMessage::AddTransaction);
if !deleted_with_children.is_empty() {
responses.add(NodeGraphMessage::DeleteNodes {
node_ids: deleted_with_children,
delete_children: true,
});
}
if !chain_nodes.is_empty() {
responses.add(NodeGraphMessage::DeleteNodes {
node_ids: chain_nodes,
delete_children: false,
});
}
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::SendGraph);
responses.add(ClipboardMessage::CopyLayers);
responses.add(DocumentMessage::DeleteSelectedLayers);
}
ClipboardMessage::WriteItems { items } => {
let has_content = items.iter().any(|item| match item {
ClipboardItem::Layer(entry) => !entry.nodes.is_empty(),
ClipboardItem::Nodes(nodes) => !nodes.is_empty(),
ClipboardItem::ChainNodes(copies) => !copies.is_empty(),
ClipboardItem::Vector(vector) => !vector.is_empty(),
ClipboardItem::Resource(_) => true,
});
@@ -194,7 +167,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
match item {
ClipboardItem::Layer(entry) => entry.nodes.iter().for_each(|(_, template)| network_interface::collect_template_resources(template, &mut resource_ids)),
ClipboardItem::Nodes(nodes) => nodes.iter().for_each(|(_, template)| network_interface::collect_template_resources(template, &mut resource_ids)),
ClipboardItem::ChainNodes(copies) => copies.iter().for_each(|copy| network_interface::collect_template_resources(&copy.template, &mut resource_ids)),
ClipboardItem::Vector(_) | ClipboardItem::Resource(_) => {}
}
}
@@ -255,7 +227,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
let mut layers = Vec::new();
let mut node_groups = Vec::new();
let mut chain_node_groups = Vec::new();
let mut vectors = Vec::new();
let mut resources = Vec::new();
for item in items {
@@ -273,12 +244,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
}
node_groups.push(nodes);
}
ClipboardItem::ChainNodes(mut copies) => {
for copy in &mut copies {
copy.template.normalize_stored_types();
}
chain_node_groups.push(copies);
}
ClipboardItem::Vector(vector) => vectors.push(vector),
ClipboardItem::Resource(resource) => resources.push(resource),
}
@@ -314,10 +279,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
responses.add(ClipboardMessage::PasteLayers { entries: layers });
}
for nodes in node_groups {
responses.add(DocumentMessage::PasteNodes { nodes });
}
for copies in chain_node_groups {
responses.add(DocumentMessage::PasteChainNodes { copies });
responses.add(NodeGraphMessage::InsertNodes { nodes });
}
for paths in vectors {
responses.add(ClipboardMessage::PasteVectors { paths });
@@ -340,6 +302,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
.collect::<Vec<_>>();
parent_tree_path.reverse();
let mut all_new_ids = Vec::new();
let mut layers = Vec::new();
let mut added_nodes = false;
@@ -358,6 +321,8 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
added_nodes = true;
}
all_new_ids.extend(new_ids.values().copied());
responses.add(NodeGraphMessage::AddNodes { nodes: entry.nodes, new_ids });
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index: 0 });
@@ -386,24 +351,22 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
}
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: layers.iter().map(|layer| layer.to_node()).collect(),
});
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: all_new_ids });
responses.add(DeferMessage::AfterGraphRun {
messages: vec![PortfolioMessage::CenterLayers { layers }.into()],
});
}
}
ClipboardMessage::PasteVectors { paths } => {
// The Path tool pastes points into the path it's editing in the viewport
// If using Path tool then send the operation to Path tool
// TODO: Consider if this is actually the correct place to put this logic
// TODO: Consider making paste in general go through the current tool, so that the tool can decide what to do
if *current_tool == ToolType::Path && portfolio.active_document().is_some_and(|document| !document.graph_view_overlay_open()) {
if *current_tool == ToolType::Path {
responses.add(PathToolMessage::Paste { paths });
return;
}
// Otherwise, create new layers and add paths into those
// If not using Path tool, create new layers and add paths into those
if let Some(document) = portfolio.active_document() {
let mut layers = Vec::new();
@@ -1,5 +1,5 @@
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{ChainNodeCopy, NodeTemplate};
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use glam::DAffine2;
@@ -27,8 +27,6 @@ pub type ClipboardVectorEntry = (LayerNodeIdentifier, Vector, DAffine2);
pub enum ClipboardItem {
Layer(ClipboardLayer),
Nodes(Vec<(NodeId, NodeTemplate)>),
/// Nodes copied from layers' chains, ordered by their layer's place in the Layers panel, then from the layer outward.
ChainNodes(Vec<ChainNodeCopy>),
Vector(Vec<ClipboardVectorEntry>),
Resource(ClipboardResource),
}
Loaded 100 of 449 files, more files were not shown because too many files have changed in this diff. Show more