mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
54b308efc6 | ||
|
|
90adad8c89 | ||
|
|
8619ae05fe | ||
|
|
f976f95cdc | ||
|
|
7c0f7bc29f | ||
|
|
58c35aa475 | ||
|
|
932da8abb0 | ||
|
|
c6cdc7fe92 | ||
|
|
a7ac19fd6b | ||
|
|
717103866e | ||
|
|
d3f51f1522 | ||
|
|
9350e2f3b2 | ||
|
|
be72f25f9a | ||
|
|
ddf91d237a | ||
|
|
5f8dd62107 | ||
|
|
6eec6ae17c | ||
|
|
ca7706826f | ||
|
|
8d675ab949 | ||
|
|
3788ceb0bb | ||
|
|
afc60d23b3 | ||
|
|
de08019677 | ||
|
|
c88d9d366f | ||
|
|
e45a397abf | ||
|
|
b40c57d200 | ||
|
|
1d3ebc5454 | ||
|
|
db32addcb0 | ||
|
|
045cdfd5ee | ||
|
|
1d6b93a6d1 | ||
|
|
baced334ec | ||
|
|
4c4e0ba39b | ||
|
|
fbbae5876b | ||
|
|
fba33376bc | ||
|
|
a8104cf230 | ||
|
|
778e979c41 | ||
|
|
5ee999b847 | ||
|
|
9044a9c09a | ||
|
|
a1ff88ae30 | ||
|
|
d96f03fe90 | ||
|
|
708cca339d | ||
|
|
6e9208c004 | ||
|
|
412979278e | ||
|
|
7f7262c3cd |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/4e42efe8dbf2ae2d82e12123aa9c103d5740a465.tar.gz
|
||||
6b7883a26952c77aad56758a11207761c2fcd1b61bf6dd5996c3cf9d4eb1cb5e
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/70b260c21afad29140bbc63ddab952fec3dd024c.tar.gz
|
||||
5b05e7f4449b5f962755542e9b156891bbf2e0a87b7fc90798b8352d9225757d
|
||||
@@ -12,7 +12,7 @@
|
||||
},
|
||||
// NOTICE: keep these tool versions in sync with `.github/workflows/build.yml`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
"containerEnv": {
|
||||
"WASM_BINDGEN_CLI_VERSION": "0.2.127",
|
||||
"WASM_BINDGEN_CLI_VERSION": "0.2.129",
|
||||
"CARGO_ABOUT_VERSION": "0.9.2",
|
||||
"BINARYEN_VERSION": "130",
|
||||
"CARGO_BINSTALL_VERSION": "1.23.0"
|
||||
|
||||
@@ -62,7 +62,7 @@ jobs:
|
||||
SCCACHE_GHA_RW_MODE: ${{ (github.event_name == 'push' && github.ref == 'refs/heads/master') && 'READ_WRITE' || 'READ_ONLY' }}
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `check.yml` (sccache), `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
SCCACHE_VERSION: "v0.19.0"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.127"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.129"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.2"
|
||||
steps:
|
||||
@@ -348,7 +348,7 @@ jobs:
|
||||
|
||||
env:
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.127"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.129"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.2"
|
||||
CARGO_BINSTALL_VERSION: "1.23.0"
|
||||
@@ -617,7 +617,7 @@ jobs:
|
||||
|
||||
env:
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.127"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.129"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.2"
|
||||
CARGO_BINSTALL_VERSION: "1.23.0"
|
||||
|
||||
@@ -174,23 +174,12 @@ jobs:
|
||||
env:
|
||||
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
|
||||
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
||||
run: cargo test --all-features
|
||||
|
||||
# The plain `cargo test` above only covers the workspace's default members, which leave these out
|
||||
- name: 🧪 Run document migration tests
|
||||
env:
|
||||
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
||||
# The desktop crates need CEF, and `third-party-licenses` only pulls it in through its `desktop` feature, so it runs on its own without `--all-features`
|
||||
run: >-
|
||||
cargo test --all-features
|
||||
--package migration-core
|
||||
--package migration-runner
|
||||
--package migration-formats
|
||||
--package migration-nodes
|
||||
--package migration-snapshot
|
||||
--package document-graph-storage
|
||||
--package document-format
|
||||
--package graphene-cli
|
||||
--package regression
|
||||
cargo test --workspace --all-features
|
||||
--exclude 'graphite-desktop*'
|
||||
--exclude third-party-licenses
|
||||
&& cargo test --package third-party-licenses
|
||||
|
||||
# Render the documents of the regression corpus and compare them with their reference images
|
||||
regression-corpus:
|
||||
@@ -215,7 +204,7 @@ jobs:
|
||||
- name: 📥 Clone regression corpus
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
with:
|
||||
repository: tagtraumen/graphite-corpus
|
||||
repository: GraphiteEditor/document-corpus
|
||||
path: target/regression-corpus
|
||||
lfs: true
|
||||
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ let
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_127
|
||||
pkgs.wasm-bindgen-cli_0_2_129
|
||||
deps.cargoAbout
|
||||
|
||||
pkgs.rustc
|
||||
|
||||
@@ -83,7 +83,7 @@ deps.crane.lib.buildPackage (
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_127
|
||||
pkgs.wasm-bindgen-cli_0_2_129
|
||||
deps.cargoAbout
|
||||
pkgs.removeReferencesTo
|
||||
pkgs.importNpmLock.npmConfigHook
|
||||
|
||||
Generated
+1995
-2430
File diff suppressed because it is too large.
Load diff
+28
-27
@@ -19,6 +19,7 @@ members = [
|
||||
"document/migrations/nodes",
|
||||
"document/migrations/compiled",
|
||||
"document/peer-transport",
|
||||
"document/live",
|
||||
"editor",
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
@@ -45,7 +46,6 @@ members = [
|
||||
"tools/node-docs",
|
||||
"tools/regression",
|
||||
"tools/web-editor-driver",
|
||||
"tools/compression_test",
|
||||
]
|
||||
default-members = [
|
||||
"editor",
|
||||
@@ -118,6 +118,7 @@ migration-formats = { path = "document/migrations/formats" }
|
||||
migration-compiled = { path = "document/migrations/compiled" }
|
||||
migration-nodes = { path = "document/migrations/nodes" }
|
||||
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" }
|
||||
@@ -146,10 +147,10 @@ web-time = "1.1"
|
||||
env_logger = "0.11"
|
||||
log = "0.4"
|
||||
bitflags = { version = "2.4", features = ["serde"] }
|
||||
ctor = "0.2"
|
||||
ctor = "1.0"
|
||||
convert_case = "0.12"
|
||||
titlecase = "3.6"
|
||||
fancy-regex = "0.18.0"
|
||||
fancy-regex = "0.20.0"
|
||||
unicode-segmentation = "1.13.2"
|
||||
indoc = "2.0.5"
|
||||
derivative = "2.2"
|
||||
@@ -175,10 +176,10 @@ wgpu = { version = "30.0", default-features = false, features = [
|
||||
"strict_asserts",
|
||||
] }
|
||||
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
|
||||
wasm-bindgen = "=0.2.127" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen = "=0.2.129" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "=0.3.104"
|
||||
web-sys = { version = "=0.3.104", features = [
|
||||
js-sys = "=0.3.106"
|
||||
web-sys = { version = "=0.3.106", features = [
|
||||
"Document",
|
||||
"DomRect",
|
||||
"Element",
|
||||
@@ -209,25 +210,25 @@ tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-mult
|
||||
# Linebender ecosystem (BEGIN)
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support"] }
|
||||
usvg = "0.47"
|
||||
usvg = "0.49"
|
||||
simplecss = "0.2"
|
||||
parley = { version = "0.9", default-features = false, features = ["std"] }
|
||||
skrifa = "0.42"
|
||||
parley = { version = "0.12", default-features = false, features = ["std"] }
|
||||
skrifa = "0.44"
|
||||
polycool = "0.4"
|
||||
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 = [
|
||||
rand = { version = "0.10", default-features = false, features = ["std_rng"] }
|
||||
rand_chacha = "0.10"
|
||||
glam = { version = "0.34", default-features = false, features = [
|
||||
"std",
|
||||
"scalar-math",
|
||||
"bytemuck",
|
||||
"debug-glam-assert",
|
||||
"all-types",
|
||||
] }
|
||||
base64 = "0.22"
|
||||
base64 = "0.23"
|
||||
blake3 = "1.5"
|
||||
mmap-io = { version = "0.9", features = ["hugepages"] }
|
||||
mmap-io = { version = "1.0", features = ["hugepages"] }
|
||||
image = { version = "0.25", default-features = false, features = [
|
||||
"png",
|
||||
"jpeg",
|
||||
@@ -244,10 +245,10 @@ image = { version = "0.25", default-features = false, features = [
|
||||
pretty_assertions = "1.4"
|
||||
fern = { version = "0.7", features = ["colored"] }
|
||||
num_enum = { version = "0.7", default-features = false }
|
||||
num-derive = "0.4"
|
||||
num-derive = "0.5"
|
||||
num-traits = "0.2"
|
||||
tsify = { version = "0.5", default-features = false, features = ["js"] }
|
||||
syn = { version = "2.0", default-features = false, features = [
|
||||
syn = { version = "3.0", default-features = false, features = [
|
||||
"full",
|
||||
"derive",
|
||||
"parsing",
|
||||
@@ -261,14 +262,14 @@ syn = { version = "2.0", default-features = false, features = [
|
||||
lyon_geom = "1.0"
|
||||
delaunator = "1.0"
|
||||
robust = "1.2"
|
||||
petgraph = { version = "0.7", default-features = false, features = ["graphmap"] }
|
||||
petgraph = { version = "0.8", default-features = false, features = ["graphmap"] }
|
||||
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
|
||||
tinyvec = { version = "1", features = ["std"] }
|
||||
criterion = { version = "0.7", features = ["html_reports"] }
|
||||
gungraun = { version = "0.18" }
|
||||
ndarray = "0.16"
|
||||
ollev = "0.1.1"
|
||||
dirs = "6.0"
|
||||
criterion = { version = "0.8", features = ["html_reports"] }
|
||||
gungraun = { version = "0.20" }
|
||||
ndarray = "0.17"
|
||||
ollev = "0.1.2"
|
||||
dirs = "7.0"
|
||||
cef = "156"
|
||||
cef-dll-sys = "156"
|
||||
include_dir = "0.7"
|
||||
@@ -276,14 +277,14 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tracing = "0.1"
|
||||
rfd = "0.17"
|
||||
open = "5.3"
|
||||
spin = "0.10"
|
||||
spin = "0.12"
|
||||
clap = "4.5"
|
||||
qrcodegen = "1.8"
|
||||
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
|
||||
scraper = "0.25"
|
||||
linesweeper = "0.4"
|
||||
lzma-rust2 = { version = "0.25", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
|
||||
scraper = "0.29"
|
||||
linesweeper = "0.5"
|
||||
smallvec = "1.13.2"
|
||||
zip = { version = "8", default-features = false }
|
||||
zip = { version = "9", default-features = false }
|
||||
|
||||
[workspace.lints]
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
|
||||
|
||||
<a href="https://graphite.art/">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/9366c148-4405-484f-909a-9a3526eb9209">
|
||||
@@ -83,3 +81,13 @@ Are you a graphics programmer or Rust developer? Graphite aims to be one of the
|
||||
## License
|
||||
|
||||
Graphite's source code is dual-licensed under your choice of either the [MIT license](LICENSE-MIT) or the [Apache License 2.0](LICENSE-APACHE), at your option, unless otherwise noted within the repository. By submitting code for inclusion in the project, you agree to license your contributions under both licenses, and that you have the authority to do so.
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
We're grateful to these programs and organizations for the grants and services that help make Graphite possible.
|
||||
|
||||
[<img width="600" alt="European Commission, NGI Zero, and NLnet Foundation" src="https://github.com/user-attachments/assets/d5b3c623-710a-4809-916b-263e80c28184" />](https://nlnet.nl/commonsfund/)
|
||||
|
||||
[<img width="600" alt="Google Summer of Code" src="https://github.com/user-attachments/assets/37284dfe-fccd-4abd-904c-1165ff36da53" />](https://summerofcode.withgoogle.com/)
|
||||
|
||||
[<img width="300" alt="CI Powered by Blacksmith" src="https://github.com/user-attachments/assets/72bd48c2-ab21-4aed-b0a5-d440a8662128" />](https://www.blacksmith.sh/)
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
use rand::Rng;
|
||||
use rand::RngExt;
|
||||
use rfd::AsyncFileDialog;
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
|
||||
@@ -34,7 +34,7 @@ serde_json = { workspace = true }
|
||||
rand = { workspace = true, features = ["thread_rng"] }
|
||||
cef = { workspace = true }
|
||||
bytemuck = { workspace = true, optional = true }
|
||||
ipc-channel = "0.22"
|
||||
ipc-channel = "0.23"
|
||||
|
||||
# Linux-specific dependencies
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
|
||||
@@ -99,6 +99,12 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::TriggerClipboardWrite { content } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite { content });
|
||||
}
|
||||
// No web origin here, so use the hosted editor
|
||||
FrontendMessage::TriggerSessionLinkCopy { token } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite {
|
||||
content: format!("https://editor.graphite.rs/?session={token}"),
|
||||
});
|
||||
}
|
||||
FrontendMessage::WindowPointerLock => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PointerLock);
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ impl Archive for Zip {
|
||||
if !entry.is_file() {
|
||||
continue;
|
||||
}
|
||||
let name = entry.name().to_string();
|
||||
let name = entry.name().map_err(zip_err)?.to_string();
|
||||
validate_path(&name)?;
|
||||
|
||||
let size = checked_entry_size(&mut total_size, entry.size())?;
|
||||
|
||||
@@ -91,7 +91,7 @@ impl MmappedBytes {
|
||||
/// later degrading to the `&[]` fallback in [`AsRef::as_ref`], which cannot return an error.
|
||||
pub fn new(file: mmap_io::mmap::MemoryMappedFile) -> Result<Self> {
|
||||
let len = file.len();
|
||||
file.as_slice(0, len)
|
||||
file.as_slice_bytes(0, len)
|
||||
.map_err(|error| ContainerError::Backend(format!("mmap slice of {:?} failed: {error}", file.path())))?;
|
||||
Ok(Self(file))
|
||||
}
|
||||
@@ -105,7 +105,7 @@ impl MmappedBytes {
|
||||
impl AsRef<[u8]> for MmappedBytes {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
let len = self.0.len();
|
||||
match self.0.as_slice(0, len) {
|
||||
match self.0.as_slice_bytes(0, len) {
|
||||
Ok(slice) => slice,
|
||||
Err(error) => {
|
||||
log::error!("Failed to obtain mmap slice: {error}");
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
//! The working copy's blob records, one `blobs/<hash>` file each. A record holds the blob's bytes in full, or a copy
|
||||
//! delta against the blob its node input held before. Values change in a few places per edit, so consecutive versions
|
||||
//! of one input share nearly all of their bytes, which a delta stores once. Chains are unbounded, which costs nothing
|
||||
//! while loading decodes every blob anyway. Records stay uncompressed, so an archive codec can compress across them.
|
||||
//! Blob records in the working copy, one `blobs/<hash>` file each.
|
||||
//!
|
||||
//! A record starts with its kind byte. A delta record follows it with its base's 32 hash bytes. The payload makes up the rest.
|
||||
//! A record holds a blob in full or as a copy delta against an older blob of the same node input. Most edits change only a
|
||||
//! few bytes of a value, so a delta is small. Records are not compressed. This lets an archive codec compress across them.
|
||||
//!
|
||||
//! Record layout is a kind byte, then the 32 base hash bytes for a delta, then the payload.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
@@ -16,32 +16,36 @@ use crate::layout::Layout;
|
||||
const FULL: u8 = 0;
|
||||
const DELTA: u8 = 1;
|
||||
|
||||
/// The decoded bytes of every blob the document names, with the record each is stored as.
|
||||
/// The decoded bytes of every blob the document names.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct BlobStore {
|
||||
pub(crate) bytes: BlobBytes,
|
||||
records: HashMap<BlobHash, Vec<u8>>,
|
||||
/// The records of blobs stored as deltas. Other blobs are stored in full.
|
||||
delta_records: HashMap<BlobHash, Vec<u8>>,
|
||||
}
|
||||
|
||||
impl BlobStore {
|
||||
/// Hold a new blob, returning the record to write for it, which is a delta against `base` when that is held.
|
||||
/// A blob already held returns `None`.
|
||||
/// Hold a new blob and return the record to write for it. The record is a delta when `base` is held.
|
||||
/// Returns `None` for a blob that is already held.
|
||||
pub(crate) fn insert(&mut self, hash: BlobHash, bytes: Vec<u8>, base: Option<BlobHash>) -> Option<Vec<u8>> {
|
||||
if self.bytes.contains_key(&hash) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let record = match base.and_then(|base| Some((base, self.bytes.get(&base)?))) {
|
||||
Some((base, base_bytes)) => delta_record(&base, base_bytes, &bytes),
|
||||
Some((base, base_bytes)) => {
|
||||
let record = delta_record(base, base_bytes, &bytes);
|
||||
self.delta_records.insert(hash, record.clone());
|
||||
record
|
||||
}
|
||||
None => full_record(&bytes),
|
||||
};
|
||||
|
||||
self.bytes.insert(hash, bytes);
|
||||
self.records.insert(hash, record.clone());
|
||||
Some(record)
|
||||
}
|
||||
|
||||
/// [`insert`](Self::insert) every blob in hash order, each base ahead of the blobs encoded against it.
|
||||
/// [`insert`](Self::insert) every blob in hash order. A base goes in before the blobs that use it.
|
||||
pub(crate) fn insert_all(&mut self, blobs: NewBlobs) -> Vec<(BlobHash, Vec<u8>)> {
|
||||
let NewBlobs { bytes: mut blobs, bases } = blobs;
|
||||
let mut hashes: Vec<_> = blobs.keys().copied().collect();
|
||||
@@ -59,33 +63,35 @@ impl BlobStore {
|
||||
records
|
||||
}
|
||||
|
||||
/// The record of every held blob, in hash order but each after its base.
|
||||
/// The record of every held blob in hash order. A base comes before the blobs that use it.
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) fn records(&self) -> Vec<(BlobHash, Vec<u8>)> {
|
||||
let mut hashes: Vec<_> = self.records.keys().copied().collect();
|
||||
let mut hashes: Vec<_> = self.bytes.keys().copied().collect();
|
||||
hashes.sort_unstable();
|
||||
|
||||
let mut listed = HashSet::new();
|
||||
let mut records = Vec::new();
|
||||
for hash in hashes {
|
||||
let unlisted_base = |hash: &BlobHash| record_base(self.records.get(hash)?).filter(|base| !listed.contains(base) && self.records.contains_key(base));
|
||||
let unlisted_base = |hash: &BlobHash| record_base(self.delta_records.get(hash)?).filter(|base| !listed.contains(base) && self.bytes.contains_key(base));
|
||||
for hash in chain_to(hash, unlisted_base) {
|
||||
if listed.insert(hash) {
|
||||
records.push((hash, self.records[&hash].clone()));
|
||||
if listed.insert(hash)
|
||||
&& let Some(record) = self.delta_records.get(&hash).cloned().or_else(|| self.full_record(&hash))
|
||||
{
|
||||
records.push((hash, record));
|
||||
}
|
||||
}
|
||||
}
|
||||
records
|
||||
}
|
||||
|
||||
/// Hold the blobs of records from elsewhere, checking each against its hash, and return those held for writing.
|
||||
/// A record whose base isn't held here, or that is malformed, is skipped.
|
||||
/// Hold the blobs of records from a peer and return the records to write.
|
||||
/// Skips a record that is malformed, fails its hash check or needs a base that is not held.
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) fn absorb(&mut self, records: Vec<(BlobHash, Vec<u8>)>) -> Vec<(BlobHash, Vec<u8>)> {
|
||||
let mut pending = records;
|
||||
let mut held = Vec::new();
|
||||
|
||||
// Repeat while a pass holds more, since a record can arrive ahead of its base
|
||||
// A record can arrive before its base, so repeat until a pass holds nothing new
|
||||
loop {
|
||||
let waiting = pending.len();
|
||||
pending.retain(|(hash, record)| {
|
||||
@@ -93,10 +99,10 @@ impl BlobStore {
|
||||
return false;
|
||||
}
|
||||
let bytes = match decode_record(record) {
|
||||
Some(Record::Full(bytes)) => bytes,
|
||||
Some(Record::Full(bytes)) => bytes.to_vec(),
|
||||
Some(Record::Delta { base, delta }) => {
|
||||
let Some(base_bytes) = self.bytes.get(&base) else { return true };
|
||||
let Some(bytes) = apply_copy_delta(base_bytes, &delta) else { return false };
|
||||
let Some(bytes) = apply_copy_delta(base_bytes, delta) else { return false };
|
||||
bytes
|
||||
}
|
||||
None => return false,
|
||||
@@ -116,7 +122,7 @@ impl BlobStore {
|
||||
held
|
||||
}
|
||||
|
||||
/// A record holding the held blob `hash` in full, standing on no base.
|
||||
/// A full record of the held blob `hash`.
|
||||
pub(crate) fn full_record(&self, hash: &BlobHash) -> Option<Vec<u8>> {
|
||||
Some(full_record(self.bytes.get(hash)?))
|
||||
}
|
||||
@@ -124,12 +130,16 @@ impl BlobStore {
|
||||
/// Drop a blob whose record never got written.
|
||||
pub(crate) fn forget(&mut self, hash: &BlobHash) {
|
||||
self.bytes.remove(hash);
|
||||
self.records.remove(hash);
|
||||
self.delta_records.remove(hash);
|
||||
}
|
||||
|
||||
/// Read and decode the record of `hash` and those of the bases it stands on, checking each blob against its hash.
|
||||
/// Read and decode the record of `hash` and the records of its bases. Each blob is checked against its hash.
|
||||
pub(crate) async fn load(&mut self, hash: BlobHash, working: &AnyContainer, layout: &impl Layout) -> Result<(), String> {
|
||||
// Walk down the chain to a blob already held or a full record, then apply the deltas on the way back up
|
||||
if self.bytes.contains_key(&hash) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Follow the bases down to a held blob or a full record, then apply the deltas in reverse
|
||||
let mut deltas = Vec::new();
|
||||
let mut visited = HashSet::new();
|
||||
let mut current = hash;
|
||||
@@ -145,11 +155,12 @@ impl BlobStore {
|
||||
let record = record.as_slice().to_vec();
|
||||
match decode_record(&record).ok_or_else(|| format!("Blob {current} has a malformed record"))? {
|
||||
Record::Full(bytes) => {
|
||||
let bytes = bytes.to_vec();
|
||||
self.hold_checked(current, bytes.clone(), record)?;
|
||||
break bytes;
|
||||
}
|
||||
Record::Delta { base, delta } => {
|
||||
deltas.push((current, delta, record));
|
||||
deltas.push((current, delta.to_vec(), record));
|
||||
current = base;
|
||||
}
|
||||
}
|
||||
@@ -168,12 +179,14 @@ impl BlobStore {
|
||||
}
|
||||
|
||||
self.bytes.insert(hash, bytes);
|
||||
self.records.insert(hash, record);
|
||||
if record.first() == Some(&DELTA) {
|
||||
self.delta_records.insert(hash, record);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// `hash` and the bases below it that `base_of` names, deepest first. Bounded in case bases ever form a cycle.
|
||||
/// `hash` and the chain of bases that `base_of` returns, deepest base first. Stops if the chain loops.
|
||||
fn chain_to(hash: BlobHash, base_of: impl Fn(&BlobHash) -> Option<BlobHash>) -> Vec<BlobHash> {
|
||||
let mut chain = vec![hash];
|
||||
let mut visited = HashSet::from([hash]);
|
||||
@@ -186,15 +199,22 @@ fn chain_to(hash: BlobHash, base_of: impl Fn(&BlobHash) -> Option<BlobHash>) ->
|
||||
chain
|
||||
}
|
||||
|
||||
/// The base a delta record names.
|
||||
fn record_base(record: &[u8]) -> Option<BlobHash> {
|
||||
/// The base hash and the payload of a delta record.
|
||||
fn split_delta_record(record: &[u8]) -> Option<(BlobHash, &[u8])> {
|
||||
let (&DELTA, rest) = record.split_first()? else { return None };
|
||||
Some(BlobHash(ResourceHash::from(<[u8; 32]>::try_from(rest.get(..32)?).ok()?)))
|
||||
let (base, delta) = rest.split_first_chunk::<32>()?;
|
||||
Some((BlobHash(ResourceHash::from(*base)), delta))
|
||||
}
|
||||
|
||||
enum Record {
|
||||
Full(Vec<u8>),
|
||||
Delta { base: BlobHash, delta: Vec<u8> },
|
||||
/// The base hash of a delta record.
|
||||
#[cfg(feature = "network")]
|
||||
fn record_base(record: &[u8]) -> Option<BlobHash> {
|
||||
split_delta_record(record).map(|(base, _)| base)
|
||||
}
|
||||
|
||||
enum Record<'a> {
|
||||
Full(&'a [u8]),
|
||||
Delta { base: BlobHash, delta: &'a [u8] },
|
||||
}
|
||||
|
||||
fn full_record(bytes: &[u8]) -> Vec<u8> {
|
||||
@@ -203,32 +223,32 @@ fn full_record(bytes: &[u8]) -> Vec<u8> {
|
||||
record
|
||||
}
|
||||
|
||||
fn delta_record(base: &BlobHash, base_bytes: &[u8], bytes: &[u8]) -> Vec<u8> {
|
||||
fn delta_record(base: BlobHash, base_bytes: &[u8], bytes: &[u8]) -> Vec<u8> {
|
||||
let mut record = vec![DELTA];
|
||||
record.extend_from_slice(&<[u8; 32]>::from(&base.0));
|
||||
record.extend(copy_delta(base_bytes, bytes));
|
||||
record
|
||||
}
|
||||
|
||||
fn decode_record(record: &[u8]) -> Option<Record> {
|
||||
let (&kind, rest) = record.split_first()?;
|
||||
match kind {
|
||||
FULL => Some(Record::Full(rest.to_vec())),
|
||||
DELTA => Some(Record::Delta {
|
||||
base: record_base(record)?,
|
||||
delta: rest.get(32..)?.to_vec(),
|
||||
}),
|
||||
fn decode_record(record: &[u8]) -> Option<Record<'_>> {
|
||||
match *record.first()? {
|
||||
FULL => Some(Record::Full(&record[1..])),
|
||||
DELTA => split_delta_record(record).map(|(base, delta)| Record::Delta { base, delta }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// A copy delta rebuilds the target from runs copied out of the base and literal runs it carries itself.
|
||||
// It indexes the base's aligned blocks and matches them anywhere in the target, like git's delta encoding.
|
||||
// A copy delta is a list of COPY and INSERT operations. COPY takes a byte range from the base. INSERT carries new bytes.
|
||||
// Like git's delta encoding, it indexes aligned blocks of the base and finds them at any offset in the target.
|
||||
const COPY_BLOCK: usize = 16;
|
||||
const COPY: u8 = 0;
|
||||
const INSERT: u8 = 1;
|
||||
|
||||
/// O(base + target) expected: one index entry per base block, one lookup per unmatched target byte.
|
||||
/// A delta that decodes to more bytes is rejected. A small delta from a peer could otherwise copy the same base range
|
||||
/// until it fills memory. This matches the peer transport's packet limit, so no larger blob could be sent in full.
|
||||
const MAX_BLOB_BYTES: usize = 256 * 1024 * 1024;
|
||||
|
||||
/// Expected O(base + target) time. Each base block is indexed once and each unmatched target byte is looked up once.
|
||||
fn copy_delta(base: &[u8], target: &[u8]) -> Vec<u8> {
|
||||
let block_key = |bytes: &[u8]| -> u128 {
|
||||
let mut key = [0; COPY_BLOCK];
|
||||
@@ -236,7 +256,7 @@ fn copy_delta(base: &[u8], target: &[u8]) -> Vec<u8> {
|
||||
u128::from_le_bytes(key)
|
||||
};
|
||||
|
||||
let mut index: HashMap<u128, usize> = HashMap::new();
|
||||
let mut index = HashMap::new();
|
||||
for offset in (0..base.len().saturating_sub(COPY_BLOCK - 1)).step_by(COPY_BLOCK) {
|
||||
index.entry(block_key(&base[offset..])).or_insert(offset);
|
||||
}
|
||||
@@ -250,7 +270,7 @@ fn copy_delta(base: &[u8], target: &[u8]) -> Vec<u8> {
|
||||
continue;
|
||||
};
|
||||
|
||||
// Base blocks are aligned but target matches are not, so extend backward into the pending literal too
|
||||
// A match can start before the aligned block, so also extend it backward into the pending literal
|
||||
let backward = base[..base_offset].iter().rev().zip(target[literal_start..position].iter().rev()).take_while(|(a, b)| a == b).count();
|
||||
let forward = base[base_offset..].iter().zip(&target[position..]).take_while(|(a, b)| a == b).count();
|
||||
|
||||
@@ -275,6 +295,9 @@ fn apply_copy_delta(base: &[u8], mut delta: &[u8]) -> Option<Vec<u8>> {
|
||||
COPY => {
|
||||
let offset = read_varint(&mut delta)?;
|
||||
let length = read_varint(&mut delta)?;
|
||||
if output.len().checked_add(length)? > MAX_BLOB_BYTES {
|
||||
return None;
|
||||
}
|
||||
output.extend_from_slice(base.get(offset..offset.checked_add(length)?)?);
|
||||
}
|
||||
INSERT => {
|
||||
@@ -308,7 +331,7 @@ fn push_varint(output: &mut Vec<u8>, mut value: usize) {
|
||||
}
|
||||
|
||||
fn read_varint(delta: &mut &[u8]) -> Option<usize> {
|
||||
let mut value: usize = 0;
|
||||
let mut value = 0;
|
||||
for shift in (0..usize::BITS).step_by(7) {
|
||||
let (&byte, rest) = delta.split_first()?;
|
||||
*delta = rest;
|
||||
@@ -359,7 +382,7 @@ mod tests {
|
||||
panic!("a delta record")
|
||||
};
|
||||
assert_eq!(decoded_base, base_hash);
|
||||
assert_eq!(apply_copy_delta(&base, &delta).unwrap(), changed);
|
||||
assert_eq!(apply_copy_delta(&base, delta).unwrap(), changed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -367,6 +390,15 @@ mod tests {
|
||||
assert!(apply_copy_delta(b"short", &[COPY, 0, 10]).is_none());
|
||||
assert!(apply_copy_delta(b"", &[INSERT, 5, 1]).is_none());
|
||||
assert!(apply_copy_delta(b"", &[9]).is_none());
|
||||
|
||||
let base = vec![0; 1024 * 1024];
|
||||
let mut expanding = Vec::new();
|
||||
for _ in 0..=MAX_BLOB_BYTES / base.len() {
|
||||
expanding.push(COPY);
|
||||
push_varint(&mut expanding, 0);
|
||||
push_varint(&mut expanding, base.len());
|
||||
}
|
||||
assert!(apply_copy_delta(&base, &expanding).is_none(), "a delta past the size limit is rejected");
|
||||
assert!(decode_record(&[DELTA, 1, 2]).is_none());
|
||||
}
|
||||
}
|
||||
@@ -181,6 +181,19 @@ impl<L: Layout> Gdd<L> {
|
||||
}
|
||||
export_session.embed_resource_sources(links_to_promote)?;
|
||||
|
||||
// If the export includes history, also embed every resource referenced by the history.
|
||||
if options.include_history {
|
||||
let current: std::collections::HashSet<ResourceHash> = export_session.registry().resources.values().filter_map(|entry| entry.hash).collect();
|
||||
for hash in export_session.all_referenced_resource_hashes() {
|
||||
if current.contains(&hash) || working_copy_hashes.contains(&hash) {
|
||||
continue;
|
||||
}
|
||||
if let Some(resource) = byte_store.load(hash).await {
|
||||
embedded_bytes.push((hash, resource));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
|
||||
let mut session_state = self.exported_session_state(&export_session);
|
||||
|
||||
@@ -234,27 +247,27 @@ impl<L: Layout> Gdd<L> {
|
||||
}
|
||||
}
|
||||
|
||||
// Every resource and blob record in path order, whether its bytes sit in the working copy or come from the byte store,
|
||||
// so where they sat does not change the archive. `None` marks bytes the working copy already holds.
|
||||
// Every resource and blob record in path order. The archive is the same wherever the bytes are stored.
|
||||
// `None` marks bytes the working copy already holds.
|
||||
let mut entries: std::collections::BTreeMap<String, Option<Resource>> = std::collections::BTreeMap::new();
|
||||
let directories = self.working.list_dirs("").await?;
|
||||
if directories.iter().any(|name| name == self.layout.resources_dir()) {
|
||||
let has_directory = |directory: &str| directories.iter().any(|name| name == directory);
|
||||
if has_directory(self.layout.resources_dir()) {
|
||||
entries.extend(self.working.list(self.layout.resources_dir()).await?.into_iter().map(|path| (path, None)));
|
||||
}
|
||||
for (hash, resource) in embedded_bytes {
|
||||
entries.entry(self.layout.resource_path(&hash)).or_insert(Some(resource));
|
||||
}
|
||||
|
||||
// A copy without history carries only the current values, each in full since the blobs it was based on stay behind
|
||||
// A copy without history has no older blobs to use as bases, so each blob is written in full
|
||||
match &flat {
|
||||
Some(flat) => {
|
||||
for hash in flat.registry().blob_hashes() {
|
||||
if let Some(record) = self.blobs.full_record(&hash) {
|
||||
entries.insert(self.layout.blob_path(&hash), Some(Resource::new_unchecked(record, hash.into())));
|
||||
}
|
||||
let record = self.blobs.full_record(&hash).ok_or(Error::MissingResource(hash.into()))?;
|
||||
entries.insert(self.layout.blob_path(&hash), Some(Resource::new_unchecked(record, hash.into())));
|
||||
}
|
||||
}
|
||||
None if directories.iter().any(|name| name == self.layout.blobs_dir()) => {
|
||||
None if has_directory(self.layout.blobs_dir()) => {
|
||||
entries.extend(self.working.list(self.layout.blobs_dir()).await?.into_iter().map(|path| (path, None)));
|
||||
}
|
||||
None => {}
|
||||
|
||||
@@ -16,9 +16,9 @@ pub trait Layout: Send + Sync {
|
||||
fn metadata_basename(&self) -> &str;
|
||||
fn resources_dir(&self) -> &str;
|
||||
fn resource_path(&self, hash: &ResourceHash) -> String;
|
||||
/// The directory of blob records. See `blob_store`.
|
||||
/// The directory of blob records.
|
||||
fn blobs_dir(&self) -> &str;
|
||||
/// The record of one blob.
|
||||
/// The path of one blob record.
|
||||
fn blob_path(&self, hash: &BlobHash) -> String;
|
||||
/// The embedded legacy `.graphite` document, stored verbatim during the dual-write soak so the
|
||||
/// new format can be validated against (and recovered from) the old one. Dropped once `.gdd`
|
||||
|
||||
@@ -97,6 +97,7 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
pub(crate) manifest: Manifest,
|
||||
/// See [`HistoryMetadata`].
|
||||
pub(crate) metadata: HistoryMetadata,
|
||||
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>,
|
||||
@@ -106,19 +107,44 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
pub(crate) migrated: bool,
|
||||
/// Where resource bytes live. `None` means the working copy's own content-addressed store.
|
||||
pub(crate) byte_store: Option<Arc<dyn ResourceStorage>>,
|
||||
/// Decoded bytes of every blob the document names.
|
||||
/// Every blob the document names.
|
||||
pub(crate) blobs: BlobStore,
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) network: Option<peer_transport::Replica>,
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) pending_persist: PendingPersist,
|
||||
/// What peers changed since [`take_remote_changes`](Self::take_remote_changes) last took it.
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) remote_changes: network::RemoteChanges,
|
||||
/// What changed since [`take_remote_changes`](Self::take_remote_changes) last took it.
|
||||
pub(crate) remote_changes: RemoteChanges,
|
||||
/// The step a guest asked the host to undo, with the head it asked under. A repeat waits until the head moves.
|
||||
pub(crate) undo_requested: Option<(document_graph_storage::Rev, Option<document_graph_storage::Rev>)>,
|
||||
pub(crate) interactions_seen: std::collections::HashMap<document_graph_storage::HotOpId, f64>,
|
||||
pub(crate) own_last_staged_ms: Option<f64>,
|
||||
pub(crate) own_staged_since_tick: bool,
|
||||
/// Whether the document belongs in its room, persisted so a reopen reconnects.
|
||||
pub(crate) shared: bool,
|
||||
}
|
||||
|
||||
/// Changes to the working registry that the runtime mirror has not seen yet, such as peer edits and undos of retired
|
||||
/// steps. The mirror reconciles just the touched entities.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RemoteChanges {
|
||||
pub touched: document_graph_storage::Touched,
|
||||
/// A full sync replaced the working registry, so the touched set no longer bounds what changed and the mirror
|
||||
/// must be rebuilt.
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whole-file rewrites deferred to the end of a poll, so a batch of remote packets costs one rewrite per file.
|
||||
#[cfg(feature = "network")]
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
@@ -144,10 +170,14 @@ impl<L: Layout + Clone> Clone for Gdd<L> {
|
||||
Self {
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
wall_clock_ms: self.wall_clock_ms,
|
||||
byte_store: self.byte_store.clone(),
|
||||
blobs: self.blobs.clone(),
|
||||
migrated: self.migrated,
|
||||
shared: self.shared,
|
||||
interactions_seen: self.interactions_seen.clone(),
|
||||
own_last_staged_ms: self.own_last_staged_ms,
|
||||
own_staged_since_tick: self.own_staged_since_tick,
|
||||
..Self::assemble(self.session.clone(), self.working.clone(), self.layout.clone(), self.manifest.clone(), self.metadata.clone())
|
||||
}
|
||||
}
|
||||
@@ -162,6 +192,7 @@ impl<L: Layout> Gdd<L> {
|
||||
layout,
|
||||
manifest,
|
||||
metadata,
|
||||
wall_clock_ms: None,
|
||||
view_settings: Default::default(),
|
||||
network_view_settings: Default::default(),
|
||||
byte_store: None,
|
||||
@@ -171,8 +202,11 @@ impl<L: Layout> Gdd<L> {
|
||||
network: None,
|
||||
#[cfg(feature = "network")]
|
||||
pending_persist: PendingPersist::default(),
|
||||
#[cfg(feature = "network")]
|
||||
remote_changes: network::RemoteChanges::default(),
|
||||
remote_changes: RemoteChanges::default(),
|
||||
undo_requested: None,
|
||||
interactions_seen: Default::default(),
|
||||
own_last_staged_ms: None,
|
||||
own_staged_since_tick: false,
|
||||
shared: false,
|
||||
}
|
||||
}
|
||||
@@ -227,6 +261,11 @@ impl<L: Layout> Gdd<L> {
|
||||
Self::open_in_with(working, layout, byte_store, host).await
|
||||
}
|
||||
|
||||
/// Reads the manifest without opening the copy, which may be another writer's.
|
||||
pub async fn read_manifest(working: &AnyContainer, layout: &L) -> Result<Manifest, Error> {
|
||||
Ok(io::read_single(working, layout.manifest_basename(), MANIFEST_CODEC).await?)
|
||||
}
|
||||
|
||||
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
|
||||
///
|
||||
/// # Errors
|
||||
@@ -337,7 +376,7 @@ impl<L: Layout> Gdd<L> {
|
||||
if let Some(blobs) = migrated_blobs {
|
||||
gdd.keep_blobs_durably(blobs).await?;
|
||||
}
|
||||
// Before node migrations, which read the values blobs hold
|
||||
// Node migrations read values stored in blobs, so load them first
|
||||
gdd.load_blobs().await;
|
||||
|
||||
#[cfg(feature = "migrations")]
|
||||
@@ -464,6 +503,10 @@ impl<L: Layout> Gdd<L> {
|
||||
self.session.all_referenced_resource_hashes()
|
||||
}
|
||||
|
||||
pub fn resource_gc_roots(&self) -> std::collections::HashSet<ResourceHash> {
|
||||
self.session.resource_gc_roots()
|
||||
}
|
||||
|
||||
/// Drop the session and return the working-copy container + layout.
|
||||
pub fn into_storage(self) -> (AnyContainer, L) {
|
||||
(self.working, self.layout)
|
||||
|
||||
@@ -6,52 +6,14 @@ use std::collections::HashSet;
|
||||
|
||||
use document_container::AsyncContainer;
|
||||
use document_graph_storage::blob::{BlobBytes, NewBlobs};
|
||||
use document_graph_storage::{BlobHash, CrdtError, Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, RegistryDelta, ResourceHash, RetiredMarks, Rev, Session, Touched, UserId};
|
||||
use document_graph_storage::{BlobHash, Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, RegistryDelta, ResourceHash, RetiredMarks, Rev, Session, UserId};
|
||||
use peer_transport::{BlobRecord, 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 it was last taken, so a runtime mirror can reconcile
|
||||
/// just the touched entities.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RemoteChanges {
|
||||
pub touched: Touched,
|
||||
/// A full sync replaced the working registry, so the touched set no longer bounds what changed and the mirror
|
||||
/// must be rebuilt.
|
||||
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> {
|
||||
pub fn take_remote_changes(&mut self) -> RemoteChanges {
|
||||
std::mem::take(&mut self.remote_changes)
|
||||
}
|
||||
|
||||
/// Restore a dropped interaction and publish it, recording what it named in the remote changes. Returns the new deltas.
|
||||
pub(crate) fn restore_dropped_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, CrdtError> {
|
||||
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);
|
||||
}
|
||||
Ok(deltas)
|
||||
}
|
||||
|
||||
/// Host this document's room, and remember it is shared so a reopen reconnects.
|
||||
pub fn share(&mut self, transport: impl Transport + 'static, user: UserId) -> Result<(), Error> {
|
||||
self.network = Some(Replica::host(transport, self.session.peer(), user));
|
||||
@@ -88,6 +50,7 @@ impl<L: Layout> Gdd<L> {
|
||||
/// Drop the connection but keep the document shared, so a reopen reconnects. A host first retires every closed
|
||||
/// interaction with no ops still on their way.
|
||||
pub fn disconnect(&mut self) {
|
||||
self.undo_requested = None;
|
||||
let closed = self.contiguous_interactions();
|
||||
if let Err(error) = self.retire_interactions(&closed) {
|
||||
log::error!("Retiring before leaving failed: {error}");
|
||||
@@ -126,6 +89,10 @@ impl<L: Layout> Gdd<L> {
|
||||
self.network.iter().flat_map(|replica| replica.peers())
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -367,7 +334,7 @@ impl<L: Layout> SyncTarget for Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Includes blobs this peer holds no record for, which it asks for in full like resources.
|
||||
/// Also includes missing blobs. They are fetched in full like resources.
|
||||
fn missing_resources(&self) -> HashSet<ResourceHash> {
|
||||
let missing_blobs = self.session.all_blob_hashes().into_iter().filter(|hash| !self.blobs.bytes.contains_key(hash));
|
||||
self.unstored_resources().into_iter().chain(missing_blobs.map(ResourceHash::from)).collect()
|
||||
@@ -379,7 +346,7 @@ impl<L: Layout> SyncTarget for Gdd<L> {
|
||||
|
||||
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
|
||||
let blob = BlobHash(hash);
|
||||
if self.session.all_blob_hashes().contains(&blob) {
|
||||
if self.session.names_blob(blob) {
|
||||
let bytes = BlobBytes::from([(blob, bytes.to_vec())]);
|
||||
self.keep_blobs(NewBlobs { bytes, ..Default::default() })?;
|
||||
return Ok(());
|
||||
@@ -394,8 +361,12 @@ impl<L: Layout> SyncTarget for Gdd<L> {
|
||||
|
||||
fn absorb_blob_records(&mut self, records: Vec<BlobRecord>) -> Result<(), TargetError> {
|
||||
let held = self.blobs.absorb(records.into_iter().map(|BlobRecord { hash, record }| (hash, record)).collect());
|
||||
for (hash, record) in held {
|
||||
self.working.write_non_blocking(&self.layout.blob_path(&hash), &record)?;
|
||||
for (index, (hash, record)) in held.iter().enumerate() {
|
||||
if let Err(error) = self.working.write_non_blocking(&self.layout.blob_path(hash), record) {
|
||||
// Forget the unwritten blobs so that they are asked for again
|
||||
held[index..].iter().for_each(|(hash, _)| self.blobs.forget(hash));
|
||||
return Err(error.into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+230
-21
@@ -4,10 +4,12 @@
|
||||
//! surface absorbs durability.
|
||||
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::NodeMetadataSource;
|
||||
use document_graph_storage::blob::{BlobBytes, NewBlobs};
|
||||
use document_graph_storage::{BlobHash, HistoryMetadata, HotOp, MetadataFact, PeerId, RegistryDelta, Rev, Sorted, Subject, TimeStamp, UserId, Value, WallStamp};
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::from_runtime::RuntimeConversion;
|
||||
use document_graph_storage::{BlobHash, CrdtError, Delta, HistoryMetadata, HotOp, MetadataFact, PeerId, RegistryDelta, Rev, Sorted, Subject, TimeStamp, UserId, Value, WallStamp};
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::{CommitError, NodeMetadataSource, Registry};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::ResourceStorage;
|
||||
|
||||
@@ -15,7 +17,7 @@ use crate::SessionState;
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::manifest::Manifest;
|
||||
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, encode_facts, io};
|
||||
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, RemoteChanges, encode_facts, io};
|
||||
|
||||
/// Written after every staged payload, so its presence means the whole rewrite is ready to move into place.
|
||||
const STAGING_COMMITTED: &str = "committed";
|
||||
@@ -51,21 +53,35 @@ impl<L: Layout> Gdd<L> {
|
||||
/// Move the undo cursor back one commit (silent-zone reflog undo) and persist the new cursor. Returns
|
||||
/// the undone `Rev`. The working registry is rewound in place by the reverse delta, so re-snapshot it
|
||||
/// (alongside `head`) or a reopen would read a `registry.bin` inconsistent with the persisted cursor.
|
||||
/// Records what the step named for [`take_remote_changes`](Self::take_remote_changes).
|
||||
pub fn undo(&mut self) -> Result<Rev, Error> {
|
||||
let rev = self.session.undo()?;
|
||||
self.remote_changes.touched.extend(self.session.touched_between(self.session.head_rev(), rev));
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
Ok(rev)
|
||||
}
|
||||
|
||||
/// Re-apply the most-recently-undone commit and persist the new cursor and re-snapshotted registry.
|
||||
/// Re-apply the most-recently-undone commit and persist the new cursor and re-snapshotted registry. Records what
|
||||
/// the step named like [`undo`](Self::undo).
|
||||
pub fn redo(&mut self) -> Result<Rev, Error> {
|
||||
let from = self.session.head_rev();
|
||||
let rev = self.session.redo()?;
|
||||
self.remote_changes.touched.extend(self.session.touched_between(from, rev));
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
Ok(rev)
|
||||
}
|
||||
|
||||
/// Forget the latest undone commit, so redo can't bring it back, and persist the cursor.
|
||||
pub fn forget_latest_undo(&mut self) -> Result<Option<Rev>, Error> {
|
||||
let forgotten = self.session.forget_latest_undo();
|
||||
if forgotten.is_some() {
|
||||
self.persist_session_state()?;
|
||||
}
|
||||
Ok(forgotten)
|
||||
}
|
||||
|
||||
/// Set the person using this device. `peer` must be unused, so the previous user keeps their steps. Refused while connected.
|
||||
pub fn set_user(&mut self, user: UserId, peer: PeerId) -> Result<(), Error> {
|
||||
if self.session.user() == user {
|
||||
@@ -76,6 +92,7 @@ impl<L: Layout> Gdd<L> {
|
||||
return Err(Error::UserChangeWhileConnected);
|
||||
}
|
||||
let closing = self.session.set_user(user, peer)?;
|
||||
self.own_last_staged_ms = None;
|
||||
self.persist_staged(&closing, Vec::new())?;
|
||||
self.persist_session_state()
|
||||
}
|
||||
@@ -106,16 +123,19 @@ impl<L: Layout> Gdd<L> {
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<document_graph_storage::Declarations, Error> {
|
||||
let conversion = document_graph_storage::Registry::convert_from_runtime(network, metadata, resources, self.session.peer()).map_err(document_graph_storage::CommitError::from)?;
|
||||
let document_graph_storage::from_runtime::RuntimeConversion {
|
||||
let RuntimeConversion {
|
||||
registry,
|
||||
blob_bytes,
|
||||
declaration_bytes,
|
||||
declarations,
|
||||
..
|
||||
} = conversion;
|
||||
let ops = document_graph_storage::delta::compute_deltas(self.registry(), ®istry);
|
||||
self.stage_with_blobs(ops, blob_bytes)?;
|
||||
} = Registry::convert_from_runtime(network, metadata, resources, self.session.peer()).map_err(CommitError::from)?;
|
||||
|
||||
// The converted registry already names its large values as blobs
|
||||
let ops = self.session.runtime_diff(®istry);
|
||||
let bases = self.registry().blob_bases(&ops);
|
||||
let hot_ops = self.session.stage_runtime_diff(ops, registry)?;
|
||||
self.persist_with_blobs(&hot_ops, NewBlobs { bytes: blob_bytes, bases })?;
|
||||
|
||||
// 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
|
||||
@@ -145,26 +165,30 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(hot_ops)
|
||||
}
|
||||
|
||||
/// Stage raw registry ops as hot ops, without the runtime diff. Large input values they write become blobs.
|
||||
/// Stage raw registry ops as hot ops, without the runtime diff. Large input values become blobs.
|
||||
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, Error> {
|
||||
self.stage_with_blobs(ops.into_iter().collect(), BlobBytes::new())
|
||||
}
|
||||
|
||||
/// Stage `ops` with large values moved into blobs, writing blob records ahead of the hot frames. `blobs` holds the bytes
|
||||
/// of blobs the ops already name.
|
||||
fn stage_with_blobs(&mut self, mut ops: Vec<RegistryDelta>, mut blobs: BlobBytes) -> Result<Vec<HotOp>, Error> {
|
||||
let mut ops: Vec<_> = ops.into_iter().collect();
|
||||
let mut blobs = BlobBytes::new();
|
||||
ops.iter_mut().for_each(|op| op.move_values_into_blobs(&mut blobs));
|
||||
let bases = self.registry().blob_bases(&ops);
|
||||
|
||||
let hot_ops = self.session.stage_computed_ops(ops)?;
|
||||
let records = self.keep_blobs(NewBlobs { bytes: blobs, bases })?;
|
||||
self.persist_staged(&hot_ops, records)?;
|
||||
self.persist_with_blobs(&hot_ops, NewBlobs { bytes: blobs, bases })?;
|
||||
Ok(hot_ops)
|
||||
}
|
||||
|
||||
/// Append the frames of freshly staged hot ops, then broadcast them with the records of the blobs they introduced.
|
||||
/// Write the records of new blobs, then persist the hot frames that name them.
|
||||
fn persist_with_blobs(&mut self, hot_ops: &[HotOp], blobs: NewBlobs) -> Result<(), Error> {
|
||||
let records = self.keep_blobs(blobs)?;
|
||||
self.persist_staged(hot_ops, records)
|
||||
}
|
||||
|
||||
/// Append the frames of freshly staged hot ops, then broadcast them together with their new blob records.
|
||||
#[cfg_attr(not(feature = "network"), expect(unused_variables, reason = "only peers receive the blob records"))]
|
||||
fn persist_staged(&mut self, hot_ops: &[HotOp], blobs: Vec<(BlobHash, Vec<u8>)>) -> Result<(), Error> {
|
||||
if hot_ops.iter().any(|hot_op| !matches!(hot_op.op, RegistryDelta::Meta)) {
|
||||
self.own_staged_since_tick = true;
|
||||
}
|
||||
for hot_op in hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
@@ -403,6 +427,13 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How many closed interactions wait before they retire. Retiring later merges more of a gesture into one delta.
|
||||
pub const RETIRE_AFTER_INTERACTIONS: usize = 10;
|
||||
/// Gives every peer time to see the whole interaction.
|
||||
pub const RETIRE_MIN_AGE_MS: f64 = 2_000.0;
|
||||
/// The longest anything waits, so quiet sessions and interactions with gaps still retire.
|
||||
pub const RETIRE_MAX_AGE_MS: f64 = 60_000.0;
|
||||
|
||||
/// Close this peer's open interaction, if any, with a marker staged like any other hot op.
|
||||
pub fn end_interaction(&mut self) -> Result<(), Error> {
|
||||
let staged = self.session.end_interaction()?;
|
||||
@@ -410,10 +441,186 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Undo this peer's latest hot interaction, here and on peers. `None` if it already retired.
|
||||
pub fn retract_interaction(&mut self) -> Result<Option<Vec<RegistryDelta>>, Error> {
|
||||
let Some(retraction) = self.session.retract_interaction()? else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.own_last_staged_ms = None;
|
||||
self.rewrite_hot_log()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
self.remote_changes.touched.extend(retraction.touched);
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_retraction(&retraction.ids)?;
|
||||
}
|
||||
Ok(Some(retraction.ops))
|
||||
}
|
||||
|
||||
pub fn take_remote_changes(&mut self) -> RemoteChanges {
|
||||
std::mem::take(&mut self.remote_changes)
|
||||
}
|
||||
|
||||
pub fn undo_retired_step(&mut self) -> Result<Option<Rev>, Error> {
|
||||
if !self.can_change_line() {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(rev) = self.session.latest_own_interaction() else {
|
||||
return Ok(None);
|
||||
};
|
||||
// A peer promoted to host drops the step itself, so an unanswered request no longer blocks it
|
||||
let asked = (!self.retires_locally()).then_some((rev, self.session.head_rev()));
|
||||
if asked.is_some() && self.undo_requested == asked {
|
||||
return Ok(None);
|
||||
}
|
||||
self.drop_step(rev)?;
|
||||
self.undo_requested = asked;
|
||||
Ok(Some(rev))
|
||||
}
|
||||
|
||||
pub fn can_change_line(&self) -> bool {
|
||||
#[cfg(feature = "network")]
|
||||
if self.network.as_ref().is_some_and(|replica| replica.has_host()) {
|
||||
return true;
|
||||
}
|
||||
self.retires_locally()
|
||||
}
|
||||
|
||||
/// Drop a retired interaction from the line. A non-retiring peer asks the retirer.
|
||||
pub fn drop_step(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if !self.retires_locally() {
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.request_undo(rev, false)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let (moved, touched) = self.session.drop_interaction(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.persist_rewritten_line()?;
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_head_move(moved)?;
|
||||
}
|
||||
#[cfg(not(feature = "network"))]
|
||||
let _ = moved;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Move the head back to an ancestor, keeping the later line as a branch. A non-retiring peer 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);
|
||||
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 dropped step as a copy on top of the line. A non-retiring peer asks the retirer.
|
||||
pub fn redo_retired_step(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if !self.retires_locally() {
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.request_undo(rev, true)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let deltas = self.restore_dropped_interaction(rev)?;
|
||||
self.persist_rewritten_line()?;
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_retired(&deltas, &[])?;
|
||||
}
|
||||
#[cfg(not(feature = "network"))]
|
||||
let _ = deltas;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Restore a dropped interaction and record what it named in the remote changes. Returns the new deltas.
|
||||
pub(crate) fn restore_dropped_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, CrdtError> {
|
||||
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);
|
||||
}
|
||||
// Only the deltas peers will see are published, so a local redo stays silently undoable
|
||||
#[cfg(feature = "network")]
|
||||
if self.network.is_some()
|
||||
&& let Some(&last) = revs.last()
|
||||
{
|
||||
self.session.publish_up_to(last);
|
||||
}
|
||||
Ok(deltas)
|
||||
}
|
||||
|
||||
fn persist_rewritten_line(&mut self) -> Result<(), Error> {
|
||||
self.rewrite_history()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
/// Stage retracted ops as a new interaction. They count as remote changes.
|
||||
pub fn restage_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<(), Error> {
|
||||
for op in &ops {
|
||||
self.remote_changes.touched.record(op);
|
||||
}
|
||||
self.stage_ops(ops)?;
|
||||
self.end_interaction()
|
||||
}
|
||||
|
||||
/// Retire what is due at `now_ms`. Open interactions never retire. `idle` means the editor is between steps.
|
||||
pub fn retire_due(&mut self, now_ms: f64, idle: bool) -> Result<Vec<Rev>, Error> {
|
||||
self.wall_clock_ms = Some(now_ms);
|
||||
// Close a quiet interaction only between steps, so a pause doesn't split a gesture
|
||||
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_interaction()?;
|
||||
self.own_last_staged_ms = None;
|
||||
}
|
||||
if !self.retires_locally() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let closed = self.session.closed_interactions();
|
||||
let mut seen = std::mem::take(&mut self.interactions_seen);
|
||||
let mut due = Vec::new();
|
||||
let mut oldest_age: f64 = 0.0;
|
||||
for interaction in &closed {
|
||||
let Some(&marker) = interaction.ops.last() else { continue };
|
||||
let age = now_ms - *seen.entry(marker).or_insert(now_ms);
|
||||
if age >= Self::RETIRE_MIN_AGE_MS && (interaction.contiguous || age >= Self::RETIRE_MAX_AGE_MS) {
|
||||
due.push(interaction.clone());
|
||||
oldest_age = oldest_age.max(age);
|
||||
}
|
||||
}
|
||||
seen.retain(|marker, _| closed.iter().any(|interaction| interaction.ops.last() == Some(marker)));
|
||||
self.interactions_seen = seen;
|
||||
|
||||
if due.len() >= Self::RETIRE_AFTER_INTERACTIONS || oldest_age >= Self::RETIRE_MAX_AGE_MS {
|
||||
self.retire_interactions(&due)
|
||||
} else {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
/// Close this peer's open interaction and retire every closed one with no ops still on their way, whoever authored
|
||||
/// it. A peer that does not retire only closes its own.
|
||||
pub fn retire_pending_interaction(&mut self) -> Result<Vec<Rev>, Error> {
|
||||
self.end_interaction()?;
|
||||
self.own_last_staged_ms = None;
|
||||
let closed = self.contiguous_interactions();
|
||||
self.retire_interactions(&closed)
|
||||
}
|
||||
@@ -449,8 +656,10 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
/// Publish and persist freshly retired deltas, then broadcast them with the hot ops they retired.
|
||||
fn finish_retirement(&mut self, new_revs: &[Rev], retired_hot_ops: &[document_graph_storage::HotOpId]) -> Result<(), Error> {
|
||||
if let Some(wall_ms) = self.wall_clock_ms {
|
||||
self.session.stamp_retired_at(new_revs, wall_ms as u64);
|
||||
}
|
||||
// Deltas peers hold are published, so undo past them moves the shared head instead of rewinding.
|
||||
#[cfg(feature = "network")]
|
||||
if self.network.is_some()
|
||||
|
||||
@@ -127,19 +127,19 @@ impl<L: Layout> Gdd<L> {
|
||||
self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.holds_resource(hash)).collect()
|
||||
}
|
||||
|
||||
/// The decoded bytes of every blob the document names, for `to_runtime`.
|
||||
/// The decoded bytes of every blob the document names.
|
||||
pub fn blobs(&self) -> &BlobBytes {
|
||||
&self.blobs.bytes
|
||||
}
|
||||
|
||||
/// Hold staged blobs and queue their records ahead of the hot frames naming them, each a delta against its base where it has one.
|
||||
/// Returns the records, for peers to receive with the ops.
|
||||
/// Hold staged blobs and queue their records before the hot frames that name them.
|
||||
/// Returns the records so peers can receive them with the ops.
|
||||
pub(crate) fn keep_blobs(&mut self, blobs: NewBlobs) -> Result<Vec<(BlobHash, Vec<u8>)>, ContainerError> {
|
||||
let records = self.blobs.insert_all(blobs);
|
||||
|
||||
for (index, (hash, record)) in records.iter().enumerate() {
|
||||
if let Err(error) = self.working.write_non_blocking(&self.layout.blob_path(hash), record) {
|
||||
// Unwritten blobs leave the store, so staging them again writes them
|
||||
// Forget the unwritten blobs so that staging them again writes them
|
||||
records[index..].iter().for_each(|(hash, _)| self.blobs.forget(hash));
|
||||
return Err(error);
|
||||
}
|
||||
@@ -147,7 +147,8 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(records)
|
||||
}
|
||||
|
||||
/// [`keep_blobs`](Self::keep_blobs), returning once the records are written, for a migration replacing the records that held the values inline.
|
||||
/// Like [`keep_blobs`](Self::keep_blobs), but waits until the records are written.
|
||||
/// A migration needs this before it replaces the old records.
|
||||
#[cfg(feature = "migrations")]
|
||||
pub(crate) async fn keep_blobs_durably(&mut self, blobs: NewBlobs) -> Result<(), ContainerError> {
|
||||
for (hash, record) in self.blobs.insert_all(blobs) {
|
||||
@@ -156,7 +157,7 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decode the record of every blob the document names, so `to_runtime` can resolve any state the cursor reaches.
|
||||
/// Decode every blob the document names. This includes blobs of history states the cursor can move to.
|
||||
pub(crate) async fn load_blobs(&mut self) {
|
||||
for hash in self.session.all_blob_hashes() {
|
||||
if let Err(error) = self.blobs.load(hash, &self.working, &self.layout).await {
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
// History metadata has its own file, travels in exports and merges across copies.
|
||||
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
use document_format::{GddV1, GddV1Layout, Layout};
|
||||
use document_graph_storage::{PeerId, Rev, Subject, UserId, rev_attr, user_attr};
|
||||
use document_graph_storage::{Network, NetworkId, PeerId, RegistryDelta, Rev, Subject, TimeStamp, UserId, rev_attr, user_attr};
|
||||
|
||||
const NOW_MS: f64 = 1_700_000_000_000.;
|
||||
const ADA: Subject = Subject::User(UserId(10));
|
||||
|
||||
fn document(peer: u64) -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
fn document(peer: u64, user: u64) -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(user), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
}
|
||||
|
||||
/// Let the room settle through greetings, the sync handshake and whatever was broadcast.
|
||||
@@ -24,49 +25,76 @@ fn settle(network: &mut peer_transport::mock::MockNetwork, peers: &mut [&mut Gdd
|
||||
}
|
||||
}
|
||||
|
||||
fn document_naming_ada() -> GddV1 {
|
||||
let mut gdd = document(1);
|
||||
assert!(gdd.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS).expect("record"));
|
||||
gdd
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recorded_facts_survive_a_reopen() {
|
||||
fn a_recorded_name_survives_a_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document_naming_ada();
|
||||
assert!(!gdd.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"), "the same name is no change");
|
||||
let step = Rev::new(7).expect("non-zero");
|
||||
gdd.record(Subject::Rev(step), rev_attr::LABEL, "Fixed the eye".into(), NOW_MS).expect("record");
|
||||
let mut gdd = document(1, 10);
|
||||
assert!(gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record"));
|
||||
assert!(
|
||||
!gdd.record(Subject::User(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(Subject::Rev(step), rev_attr::LABEL, "Fixed the eye".into(), NOW_MS).expect("record"));
|
||||
assert!(gdd.record(Subject::Rev(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");
|
||||
let mut 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"));
|
||||
|
||||
reopened.record(Subject::User(UserId(11)), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
|
||||
let (working, layout) = reopened.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(11)), Some("Bea"));
|
||||
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"]);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "conversion", feature = "zip"))]
|
||||
#[test]
|
||||
fn an_export_carries_the_metadata_only_with_the_history() {
|
||||
fn recording_an_unchanged_value_writes_nothing() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = document_naming_ada();
|
||||
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
|
||||
for include_history in [true, false] {
|
||||
let options = document_format::ExportOptions {
|
||||
include_history,
|
||||
..Default::default()
|
||||
};
|
||||
let archive = gdd.export_to_bytes(document_format::ExportFormat::Zip, options, &byte_store, None).await.expect("export");
|
||||
let reopened = GddV1::open_from_archive(&archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), include_history.then_some("Ada"));
|
||||
}
|
||||
let mut gdd = document(1, 10);
|
||||
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
let metadata = gdd.metadata().clone();
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let path = document_format::io::path_for(layout.metadata_basename(), document_format::METADATA_CODEC);
|
||||
let before = working.read(&path).await.expect("read").as_slice().to_vec();
|
||||
|
||||
let mut reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert!(!reopened.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"));
|
||||
assert_eq!(reopened.metadata(), &metadata);
|
||||
let (working, _) = reopened.into_storage();
|
||||
assert_eq!(working.read(&path).await.expect("read").as_slice().trim_ascii(), before.trim_ascii());
|
||||
});
|
||||
}
|
||||
|
||||
/// A line that doesn't decode is skipped, so a torn write can't block opening.
|
||||
#[test]
|
||||
fn an_unreadable_metadata_line_is_skipped() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document(1, 10);
|
||||
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let path = document_format::io::path_for(layout.metadata_basename(), document_format::METADATA_CODEC);
|
||||
working
|
||||
.append_non_blocking(
|
||||
&path,
|
||||
b"{\"subject\":{\"Branch\":3},\"key\":\"name\",\"value\":1,\"stamp\":{\"ms\":1,\"peer\":1}}\n{\"subject\":{\"User\":",
|
||||
)
|
||||
.expect("append");
|
||||
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_torn_tail_is_skipped_and_the_next_fact_is_not_joined_to_it() {
|
||||
futures::executor::block_on(async {
|
||||
let (working, layout) = document_naming_ada().into_storage();
|
||||
let mut gdd = document(1, 10);
|
||||
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let path = document_format::io::path_for(layout.metadata_basename(), document_format::METADATA_CODEC);
|
||||
working.append_non_blocking(&path, b"{\"subject\":{\"User\":").expect("append");
|
||||
|
||||
@@ -82,29 +110,75 @@ fn a_torn_tail_is_skipped_and_the_next_fact_is_not_joined_to_it() {
|
||||
#[cfg(feature = "network")]
|
||||
#[test]
|
||||
fn names_reach_the_room_with_the_sync_and_as_they_change() {
|
||||
let mut host = document(1);
|
||||
let mut guest = document(2);
|
||||
host.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
// A name given before joining travels with the joiner and reaches the host.
|
||||
guest.record(Subject::User(UserId(20)), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
|
||||
futures::executor::block_on(async {
|
||||
let mut host = document(1, 10);
|
||||
let mut guest = document(2, 20);
|
||||
host.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
guest.record(Subject::User(UserId(20)), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
|
||||
|
||||
let mut network = peer_transport::mock::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)).expect("share");
|
||||
guest.connect(guest_endpoint, UserId(20)).expect("connect");
|
||||
network.connect(host_id);
|
||||
network.connect(guest_id);
|
||||
settle(&mut network, &mut [&mut host, &mut guest]);
|
||||
let mut network = peer_transport::mock::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)).expect("share");
|
||||
guest.connect(guest_endpoint, UserId(20)).expect("connect");
|
||||
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");
|
||||
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(Subject::User(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");
|
||||
assert!(guest.record(Subject::User(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);
|
||||
gdd.retire_due(NOW_MS, true).expect("tick");
|
||||
|
||||
gdd.stage_ops([RegistryDelta::AddNetwork {
|
||||
id: NetworkId(9),
|
||||
network: Network::default(),
|
||||
}])
|
||||
.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));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// An export without history carries no facts, since they'd name missing revs.
|
||||
#[cfg(all(feature = "conversion", feature = "zip"))]
|
||||
#[test]
|
||||
fn an_export_carries_the_metadata_only_with_the_history() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document(1, 10);
|
||||
gdd.record(Subject::User(UserId(10)), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
|
||||
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
|
||||
for include_history in [true, false] {
|
||||
let options = document_format::ExportOptions {
|
||||
include_history,
|
||||
..Default::default()
|
||||
};
|
||||
let archive = gdd.export_to_bytes(document_format::ExportFormat::Zip, options, &byte_store, None).await.expect("export");
|
||||
let reopened = GddV1::open_from_archive(&archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.expect("open");
|
||||
let expected = include_history.then_some("Ada");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), expected, "include_history: {include_history}");
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -538,6 +538,46 @@ fn export_materializes_embedded_resource_from_byte_store() {
|
||||
});
|
||||
}
|
||||
|
||||
/// An export with history carries the bytes of a resource only history still names, so undoing its removal
|
||||
/// after a reopen finds them, even when they live in the byte store rather than the working copy.
|
||||
#[test]
|
||||
fn export_with_history_carries_history_only_resources() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
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(9), UserId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"bytes of a removed resource";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
let byte_store = empty_byte_store();
|
||||
byte_store.store(payload);
|
||||
|
||||
let mut resources = ResourceRegistry::new();
|
||||
let id = ResourceId::new();
|
||||
resources.push_source_back(&id, DataSource::Embedded);
|
||||
resources.resolve(&id, hash);
|
||||
gdd.commit_from_runtime(&network_referencing_resource(id), &NoMetadata, &resources, &byte_store)
|
||||
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
||||
gdd.commit_from_runtime(&graph_craft::document::NodeNetwork::default(), &NoMetadata, &ResourceRegistry::new(), &byte_store)
|
||||
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
||||
|
||||
assert!(!gdd.registry().resources.contains_key(&id), "the resource should only be named by history");
|
||||
assert!(!gdd.has_resource(&hash).await, "bytes should not be in the working copy");
|
||||
|
||||
let archive = gdd
|
||||
.export_to_bytes(ExportFormat::Zip, ExportOptions::default(), &byte_store, None)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
|
||||
let reopened = GddV1::open_from_archive(&archive, empty_container(), GddV1Layout)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("reopen failed: {error:?}"));
|
||||
assert!(reopened.has_resource(&hash).await, "history-only bytes should travel with the export");
|
||||
});
|
||||
}
|
||||
|
||||
/// A document with un-retired hot ops (e.g. a freshly converted document saved without an interaction
|
||||
/// boundary, or a save mid-drag) must export losslessly: the hot log travels alongside history and the
|
||||
/// reopened document reflects the staged edits. Regression for the converted-artwork "no history"
|
||||
|
||||
@@ -147,8 +147,8 @@ fn a_user_change_survives_a_reopen() {
|
||||
});
|
||||
}
|
||||
|
||||
/// Large input values are staged as blobs, an edited one as a delta against its predecessor. A reopen and an archive
|
||||
/// round trip both find them again, for the current state and an undone one.
|
||||
/// Large input values are staged as blobs. An edit is stored as a delta against the previous value.
|
||||
/// Both the current state and an undone one survive a reopen and an archive round trip.
|
||||
#[test]
|
||||
fn blobs_resolve_after_a_reopen_and_an_archive_round_trip() {
|
||||
use document_container::AsyncContainer;
|
||||
@@ -167,7 +167,7 @@ fn blobs_resolve_after_a_reopen_and_an_archive_round_trip() {
|
||||
let store = HashMapResourceStorage::new();
|
||||
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &store).unwrap();
|
||||
|
||||
// An op built outside a conversion carries the value inline until staging moves it into a blob
|
||||
// This op is not from a conversion, so the value stays inline until staging moves it into a blob
|
||||
let id = *gdd.registry().node_instances.keys().next().unwrap();
|
||||
let value = Value::from(serde_json::to_value(&edited).unwrap());
|
||||
let new_input = NodeInput::Value { value, exposed: false };
|
||||
|
||||
@@ -121,7 +121,7 @@ fn the_user_cannot_change_while_connected() {
|
||||
assert_eq!(host.session().user(), UserId(1));
|
||||
}
|
||||
|
||||
/// Edits to a large input reach a peer as deltas against what it already holds, and a peer joining later gets every blob with its sync.
|
||||
/// Edits to a large input reach a peer as deltas. A peer that joins later gets every blob with its sync.
|
||||
#[test]
|
||||
fn blobs_reach_peers_as_deltas_and_with_a_sync() {
|
||||
use document_container::AsyncContainer;
|
||||
@@ -184,7 +184,7 @@ fn blobs_reach_peers_as_deltas_and_with_a_sync() {
|
||||
assert!(record.as_slice().len() < 100, "the delta is small, got {} bytes", record.as_slice().len());
|
||||
}
|
||||
|
||||
/// A record whose base isn't held is dropped, and the blob is asked for in full like any missing resource.
|
||||
/// A record whose base is missing is dropped. The blob is then fetched in full like a missing resource.
|
||||
#[test]
|
||||
fn a_blob_without_its_base_is_asked_for_in_full() {
|
||||
use document_graph_storage::blob::BLOB_THRESHOLD;
|
||||
@@ -214,10 +214,10 @@ fn a_blob_without_its_base_is_asked_for_in_full() {
|
||||
.expect("edit"),
|
||||
);
|
||||
let latest = author.registry().node_instances[&id].inputs()[0].input.blob().expect("the input is a blob");
|
||||
// Blobs are fetched through the resource path, keyed by the same hash
|
||||
// Blobs are fetched through the resource path with the same hash
|
||||
let resource = ResourceHash::from(latest);
|
||||
|
||||
// Only the edit's delta record arrives, not the full record it is based on
|
||||
// Only the delta record of the edit arrives, without the full record of its base
|
||||
let mut reader = document(2);
|
||||
let records = author.blob_records().into_iter().filter(|record| record.hash == latest).collect();
|
||||
reader.apply_remote_hot_ops(hot_ops).expect("apply");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Large node input values move out of the registry, history, and hot log into blobs, leaving a [`Value::Blob`]
|
||||
//! naming their bytes. A blob's bytes are the value's postcard encoding, so its hash identifies the value.
|
||||
//! Large node input values are stored as blobs outside the registry, history and hot log. The input keeps a
|
||||
//! [`Value::Blob`] with the hash. Blob bytes are the postcard encoding of the value, so equal values share one blob.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fmt;
|
||||
@@ -12,7 +12,7 @@ pub const BLOB_THRESHOLD: usize = 1024;
|
||||
/// Blob bytes by hash.
|
||||
pub type BlobBytes = HashMap<BlobHash, Vec<u8>>;
|
||||
|
||||
/// Blobs about to be stored, with the base each can be encoded against.
|
||||
/// Blobs to store, with the base blob that each one can be encoded against.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct NewBlobs {
|
||||
pub bytes: BlobBytes,
|
||||
@@ -32,7 +32,7 @@ impl fmt::Display for BlobHash {
|
||||
}
|
||||
}
|
||||
|
||||
/// Blob bytes are content addressed like resource bytes, so a peer can fetch a blob through the resource path.
|
||||
/// Blobs are content addressed like resources, so a peer can fetch a blob through the resource path.
|
||||
impl From<BlobHash> for ResourceHash {
|
||||
fn from(hash: BlobHash) -> Self {
|
||||
hash.0
|
||||
@@ -45,7 +45,7 @@ pub fn decode_blob(bytes: &[u8]) -> Result<Value, postcard::Error> {
|
||||
}
|
||||
|
||||
impl NodeInput {
|
||||
/// Replace a value of at least [`BLOB_THRESHOLD`] encoded bytes with the blob of those bytes, collecting them into `bytes`.
|
||||
/// Replace a value of at least [`BLOB_THRESHOLD`] encoded bytes with a blob. The blob bytes are added to `bytes`.
|
||||
pub fn move_into_blob(&mut self, bytes: &mut BlobBytes) {
|
||||
let NodeInput::Value { value, .. } = self else { return };
|
||||
if matches!(value, Value::Blob(_)) {
|
||||
@@ -68,12 +68,18 @@ impl RegistryDelta {
|
||||
/// Move the large values this op writes into blobs. See [`NodeInput::move_into_blob`].
|
||||
pub fn move_values_into_blobs(&mut self, bytes: &mut BlobBytes) {
|
||||
let slots = match self {
|
||||
RegistryDelta::ChangeNodeInput { new_input, .. } => return new_input.move_into_blob(bytes),
|
||||
RegistryDelta::AddNode { node, .. } => &mut node.inputs,
|
||||
RegistryDelta::ChangeNodeInput { new_input, .. } => {
|
||||
new_input.move_into_blob(bytes);
|
||||
return;
|
||||
}
|
||||
RegistryDelta::AddNode { node, .. } | RegistryDelta::RemoveNode { snapshot: node, .. } => &mut node.inputs,
|
||||
RegistryDelta::SetNodeInputs { inputs, .. } => inputs,
|
||||
_ => return,
|
||||
};
|
||||
slots.iter_mut().for_each(|slot| slot.input.move_into_blob(bytes));
|
||||
|
||||
for slot in slots {
|
||||
slot.input.move_into_blob(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,14 +91,14 @@ impl Registry {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every blob the live nodes and the tombstones of removed ones name.
|
||||
/// Every blob that live nodes and tombstones of removed nodes name.
|
||||
pub fn blob_hashes(&self) -> impl Iterator<Item = BlobHash> + '_ {
|
||||
let live = self.node_instances.values();
|
||||
let removed = self.removed_nodes.values().map(|tombstone| &tombstone.content);
|
||||
live.chain(removed).flat_map(|node| node.inputs()).filter_map(|slot| slot.input.blob())
|
||||
}
|
||||
|
||||
/// The base each blob written by `ops` encodes against: the blob its slot held before, earlier in `ops` or in `self`.
|
||||
/// The base of each blob that `ops` write. The base is the blob that the same input slot held before.
|
||||
pub fn blob_bases(&self, ops: &[RegistryDelta]) -> HashMap<BlobHash, BlobHash> {
|
||||
let mut latest: HashMap<(NodeId, usize), BlobHash> = HashMap::new();
|
||||
let mut written = HashSet::new();
|
||||
@@ -101,10 +107,9 @@ impl Registry {
|
||||
let mut write = |id: NodeId, index: usize, input: &NodeInput| {
|
||||
let Some(hash) = input.blob() else { return };
|
||||
|
||||
// Only a blob's first write takes a base, which keeps bases acyclic
|
||||
let previous = latest.get(&(id, index)).copied().or_else(|| self.node_instances.get(&id)?.inputs().get(index)?.input.blob());
|
||||
// Only the first write of a blob takes a base. This keeps bases acyclic
|
||||
if written.insert(hash)
|
||||
&& let Some(previous) = previous
|
||||
&& let Some(previous) = latest.get(&(id, index)).copied().or_else(|| self.input_blob(id, index))
|
||||
&& previous != hash
|
||||
{
|
||||
bases.insert(hash, previous);
|
||||
@@ -123,7 +128,7 @@ impl Registry {
|
||||
bases
|
||||
}
|
||||
|
||||
/// [`blob_bases`](Self::blob_bases) for the blobs `self` holds where `previous` held another in the same slot, in node ID order.
|
||||
/// Like [`blob_bases`](Self::blob_bases), but compares the slots of `self` with the same slots in `previous`.
|
||||
pub fn blob_bases_since(&self, previous: &Registry) -> HashMap<BlobHash, BlobHash> {
|
||||
let mut nodes: Vec<_> = self.node_instances.iter().collect();
|
||||
nodes.sort_unstable_by_key(|(id, _)| **id);
|
||||
@@ -134,15 +139,20 @@ impl Registry {
|
||||
for (index, slot) in node.inputs().iter().enumerate() {
|
||||
if let Some(hash) = slot.input.blob()
|
||||
&& written.insert(hash)
|
||||
&& let Some(base) = previous.node_instances.get(id).and_then(|node| node.inputs().get(index)?.input.blob())
|
||||
&& let Some(base) = previous.input_blob(*id, index)
|
||||
&& base != hash
|
||||
{
|
||||
bases.insert(hash, base);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bases
|
||||
}
|
||||
|
||||
fn input_blob(&self, id: NodeId, index: usize) -> Option<BlobHash> {
|
||||
self.node_instances.get(&id)?.inputs().get(index)?.input.blob()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -79,8 +79,8 @@ impl Delta {
|
||||
self.id == self.recomputed_id()
|
||||
}
|
||||
|
||||
/// The blobs the op writes or its priors restore.
|
||||
pub fn blob_hashes(&self) -> impl Iterator<Item = BlobHash> + '_ {
|
||||
/// The blobs that the op writes or that its priors restore.
|
||||
pub(crate) fn blob_hashes(&self) -> impl Iterator<Item = BlobHash> + '_ {
|
||||
let prior_slots = self.reverse.iter().flat_map(|prior| match prior {
|
||||
Prior::Node { node, .. }
|
||||
| Prior::RemovedNode {
|
||||
@@ -112,7 +112,7 @@ impl RegistryDelta {
|
||||
}
|
||||
}
|
||||
|
||||
/// The blobs in the input values the op writes.
|
||||
/// The blobs in the input values that the op writes.
|
||||
pub(crate) fn blob_hashes(&self) -> impl Iterator<Item = BlobHash> + '_ {
|
||||
let (input, slots): (Option<&NodeInput>, &[InputSlot]) = match self {
|
||||
RegistryDelta::ChangeNodeInput { new_input, .. } => (Some(new_input), &[]),
|
||||
|
||||
@@ -119,7 +119,7 @@ pub struct RuntimeConversion {
|
||||
pub registry: Registry,
|
||||
pub declaration_bytes: DeclarationBytes,
|
||||
pub declarations: crate::Declarations,
|
||||
/// The bytes of the large input values the registry holds as blobs, for the caller to store.
|
||||
/// The bytes of the blobs that the registry names. The caller stores them.
|
||||
pub blob_bytes: BlobBytes,
|
||||
/// The storage `NetworkId` of each runtime network location, to key per-network view state in `session.json`.
|
||||
pub network_ids: HashMap<NetworkLocation, NetworkId>,
|
||||
@@ -168,8 +168,9 @@ pub fn decode_declaration(bytes: &[u8]) -> Result<ProtoNode, String> {
|
||||
impl Registry {
|
||||
/// Convenience wrapper returning only the registry (declaration bytes discarded). For callers
|
||||
/// that don't persist a byte store — e.g. the graph-only `TryFrom` and value-comparison tests.
|
||||
/// Large values stay inline, so the registry converts back without blob bytes.
|
||||
pub fn from_runtime_with_metadata<M: NodeMetadataSource>(node_network: &NodeNetwork, metadata: &M, resources: &graphene_resource::ResourceRegistry, peer: PeerId) -> Result<Self, ConversionError> {
|
||||
Ok(Self::convert_from_runtime(node_network, metadata, resources, peer)?.registry)
|
||||
Ok(Self::convert_from_runtime_inline(node_network, metadata, resources, peer)?.registry)
|
||||
}
|
||||
|
||||
/// Full conversion: returns the registry and the extracted declaration bytes for the caller to
|
||||
@@ -179,6 +180,18 @@ impl Registry {
|
||||
metadata: &M,
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
peer: PeerId,
|
||||
) -> Result<RuntimeConversion, ConversionError> {
|
||||
let mut conversion = Self::convert_from_runtime_inline(node_network, metadata, resources, peer)?;
|
||||
conversion.registry.move_values_into_blobs(&mut conversion.blob_bytes);
|
||||
Ok(conversion)
|
||||
}
|
||||
|
||||
/// [`convert_from_runtime`](Self::convert_from_runtime) without moving large values into blobs.
|
||||
pub(crate) fn convert_from_runtime_inline<M: NodeMetadataSource>(
|
||||
node_network: &NodeNetwork,
|
||||
metadata: &M,
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
peer: PeerId,
|
||||
) -> Result<RuntimeConversion, ConversionError> {
|
||||
let mut registry = Registry::default();
|
||||
let mut ctx = ConversionContext {
|
||||
@@ -215,14 +228,11 @@ impl Registry {
|
||||
let referenced = collect_referenced_resources(node_network, &reachable);
|
||||
convert_resources(resources, &referenced, peer, &mut registry)?;
|
||||
|
||||
let mut blob_bytes = BlobBytes::new();
|
||||
registry.move_values_into_blobs(&mut blob_bytes);
|
||||
|
||||
Ok(RuntimeConversion {
|
||||
registry,
|
||||
declaration_bytes: ctx.declaration_bytes,
|
||||
declarations: ctx.declarations,
|
||||
blob_bytes,
|
||||
blob_bytes: BlobBytes::new(),
|
||||
network_ids: ctx.network_ids,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ impl Node {
|
||||
}
|
||||
|
||||
impl NodeInput {
|
||||
/// The hash a value input's bytes are stored under, when it holds a [`Value::Blob`].
|
||||
/// The blob hash of a value input that holds a [`Value::Blob`].
|
||||
pub fn blob(&self) -> Option<BlobHash> {
|
||||
match self {
|
||||
NodeInput::Value { value: Value::Blob(hash), .. } => Some(*hash),
|
||||
@@ -142,8 +142,7 @@ mod tests {
|
||||
assert_eq!(tagged, graph_craft::document::value::TaggedValue::None);
|
||||
}
|
||||
|
||||
/// A `SetExport(None)` truncation leaves a trailing empty slot. Such a network is value-equal to
|
||||
/// the same network without that slot, so the soak oracle doesn't false-report drift.
|
||||
/// A `SetExport(None)` truncation leaves a trailing empty slot, which doesn't change the network's value.
|
||||
#[test]
|
||||
fn trailing_empty_export_slot_is_value_equal() {
|
||||
let compact = Network {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{Attributes, NetworkId, NodeId, PeerId, Registry, ResourceId, ResourceStore, SourceKey, TimeStamp, Tombstone};
|
||||
use std::collections::HashMap;
|
||||
use crate::{Attributes, Implementation, NetworkId, NodeId, ROOT_NETWORK, Registry, ResourceStore, Tombstone};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
impl Registry {
|
||||
/// The node under `id`, live or as removed, for a reference to a node the runtime cannot hold.
|
||||
@@ -25,6 +25,31 @@ impl Registry {
|
||||
}
|
||||
}
|
||||
|
||||
/// The registry as `to_runtime` renders it. A removed network the root still reaches counts as present.
|
||||
pub(crate) fn as_rendered(&self) -> Registry {
|
||||
let mut nodes_by_network: HashMap<NetworkId, Vec<&crate::Node>> = HashMap::new();
|
||||
for node in self.node_instances.values() {
|
||||
nodes_by_network.entry(node.network).or_default().push(node);
|
||||
}
|
||||
|
||||
let mut rendered = self.clone();
|
||||
let mut reached = HashSet::from([ROOT_NETWORK]);
|
||||
let mut pending = vec![ROOT_NETWORK];
|
||||
while let Some(network) = pending.pop() {
|
||||
for node in nodes_by_network.get(&network).into_iter().flatten() {
|
||||
if let Implementation::Network(id) = node.implementation
|
||||
&& reached.insert(id)
|
||||
{
|
||||
pending.push(id);
|
||||
if let Some(mark) = rendered.removed_networks.remove(&id) {
|
||||
rendered.networks.insert(id, mark.content);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
rendered
|
||||
}
|
||||
|
||||
/// Whether both registries removed the same entities at the same times. Registries equal in value but not in their
|
||||
/// removal marks resolve later ops differently.
|
||||
pub fn removal_marks_equal(&self, other: &Self) -> bool {
|
||||
@@ -72,36 +97,6 @@ impl Registry {
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// True if the relative timestamp order on every shared timestamped slot agrees across
|
||||
/// the two registries. Catches LWW-bookkeeping bugs that `value_equal` deliberately ignores.
|
||||
///
|
||||
/// For every pair of shared keys (a, b), checks that `self[a].cmp(self[b])` and
|
||||
/// `other[a].cmp(other[b])` are compatible: `Equal` on either side is always compatible;
|
||||
/// otherwise both sides must agree on direction. Equality on one side imposes no order, so
|
||||
/// a registry with all-equal timestamps trivially passes against any other.
|
||||
///
|
||||
/// Slots present in only one registry are skipped. O(N²) in the number of shared timestamped
|
||||
/// slots; intended for debug-only use.
|
||||
pub fn order_consistent(&self, other: &Self) -> bool {
|
||||
let self_stamps = collect_timestamps(self);
|
||||
let other_stamps = collect_timestamps(other);
|
||||
|
||||
let shared: Vec<(TimestampKey, TimeStamp, TimeStamp)> = self_stamps.into_iter().filter_map(|(key, ts)| other_stamps.get(&key).map(|other_ts| (key, ts, *other_ts))).collect();
|
||||
|
||||
for i in 0..shared.len() {
|
||||
for j in (i + 1)..shared.len() {
|
||||
let self_order = shared[i].1.cmp(&shared[j].1);
|
||||
let other_order = shared[i].2.cmp(&shared[j].2);
|
||||
use std::cmp::Ordering::*;
|
||||
let compatible = matches!((self_order, other_order), (Equal, _) | (_, Equal) | (Less, Less) | (Greater, Greater));
|
||||
if !compatible {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
|
||||
@@ -125,87 +120,3 @@ 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`.
|
||||
#[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),
|
||||
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 (i, slot) in node.inputs.iter().enumerate() {
|
||||
out.insert(TimestampKey::NodeInput(id, i), slot.timestamp);
|
||||
out.insert(TimestampKey::NodeInputFloor(id, i), slot.attributes.floor());
|
||||
for (key, value) in &slot.attributes {
|
||||
out.insert(TimestampKey::NodeInputAttribute(id, i, key.clone()), value.timestamp);
|
||||
}
|
||||
}
|
||||
for (key, value) in &node.attributes {
|
||||
out.insert(TimestampKey::NodeAttribute(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 (i, slot) in network.exports.iter().enumerate() {
|
||||
out.insert(TimestampKey::NetworkExport(id, i), slot.timestamp);
|
||||
}
|
||||
for (key, value) in &network.attributes {
|
||||
out.insert(TimestampKey::NetworkAttribute(id, key.clone()), value.timestamp);
|
||||
}
|
||||
}
|
||||
out.insert(TimestampKey::Document("attributes"), registry.attributes.floor());
|
||||
for (key, value) in ®istry.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 (source_key, source_value) in &entry.sources {
|
||||
out.insert(TimestampKey::ResourceSource(id, *source_key), source_value.timestamp);
|
||||
}
|
||||
}
|
||||
for (&id, mark) in ®istry.removed_nodes {
|
||||
out.insert(TimestampKey::Node(id, "removed"), mark.timestamp);
|
||||
}
|
||||
for (&id, mark) in ®istry.removed_networks {
|
||||
out.insert(TimestampKey::Network(id, "removed"), mark.timestamp);
|
||||
}
|
||||
for (&id, mark) in ®istry.removed_resources {
|
||||
out.insert(TimestampKey::Resource(id, "removed"), mark.timestamp);
|
||||
}
|
||||
for (&peer, registration) in ®istry.peer_users {
|
||||
out.insert(TimestampKey::PeerRegistration(peer), registration.timestamp);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -13,7 +13,7 @@ pub struct NodeId(pub u64);
|
||||
#[serde(transparent)]
|
||||
pub struct NetworkId(pub u64);
|
||||
|
||||
/// Content-addressed identity for a blob, the stored bytes of a large node input value. See `blob`.
|
||||
/// The content hash of a blob, which stores a large node input value.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct BlobHash(pub ResourceHash);
|
||||
|
||||
@@ -14,7 +14,7 @@ pub enum Value {
|
||||
Str(String),
|
||||
Array(Vec<Value>),
|
||||
Object(Vec<(String, Value)>),
|
||||
/// A large node input value, stored as a blob under the hash of its postcard bytes. See [`crate::blob`].
|
||||
/// A large node input value that is stored as a blob. See [`crate::blob`].
|
||||
Blob(BlobHash),
|
||||
}
|
||||
|
||||
@@ -113,12 +113,12 @@ impl<'de> Deserialize<'de> for Value {
|
||||
}
|
||||
|
||||
impl Value {
|
||||
/// The key of the single-entry object a [`Value::Blob`] is written as in human-readable formats. The key is reserved:
|
||||
/// an object holding only it with a hash string reads back as a blob.
|
||||
pub const BLOB_KEY: &str = "$blob";
|
||||
/// In human-readable formats a [`Value::Blob`] is written as an object with only this key. The key is reserved.
|
||||
/// Such an object with a hash string is read back as a blob.
|
||||
pub(crate) const BLOB_KEY: &str = "$blob";
|
||||
|
||||
/// An object, unless it is the single-entry form a [`Value::Blob`] takes in human-readable formats.
|
||||
pub fn from_object(object: Vec<(String, Value)>) -> Self {
|
||||
/// An object, or a [`Value::Blob`] if the object has the form of one.
|
||||
pub(crate) fn from_object(object: Vec<(String, Value)>) -> Self {
|
||||
if let [(key, Value::Str(hex))] = object.as_slice()
|
||||
&& key == Self::BLOB_KEY
|
||||
&& let Ok(hash) = ResourceHash::try_from(hex.as_str())
|
||||
|
||||
@@ -19,6 +19,8 @@ pub struct Session {
|
||||
/// leader-eligibility computation (lowest PeerId among peers whose tip matches the session max).
|
||||
#[expect(dead_code, reason = "Populated once heartbeat/leader-election transport lands; held now so the field and constructors are in place.")]
|
||||
remote_tips: HashMap<PeerId, Rev>,
|
||||
/// The base of local diffs, so peers' edits to the working registry aren't diffed away.
|
||||
runtime_base: Option<Registry>,
|
||||
/// What the ops this peer took back named. A retirement racing the take-back may still name them, and this peer may
|
||||
/// hold the only copy, so they stay garbage collection roots for the life of the session.
|
||||
taken_back_resources: HashSet<ResourceHash>,
|
||||
@@ -43,6 +45,7 @@ impl Session {
|
||||
Self {
|
||||
document: Document::empty(peer, user),
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
taken_back_resources: HashSet::new(),
|
||||
}
|
||||
}
|
||||
@@ -97,7 +100,7 @@ impl Session {
|
||||
/// pushed onto the hot log. The caller persists the returned hot frames and then calls `retire`
|
||||
/// to promote them into durable history.
|
||||
///
|
||||
/// Large values stay inline, so this is for tests. `Gdd::stage_runtime_snapshot` stages a runtime diff through blobs.
|
||||
/// Only for tests because it does not store the blob bytes. `Gdd::stage_runtime_snapshot` does.
|
||||
#[cfg(test)]
|
||||
pub fn stage_from_runtime<M: NodeMetadataSource>(
|
||||
&mut self,
|
||||
@@ -106,16 +109,36 @@ impl Session {
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
) -> Result<(Vec<HotOp>, from_runtime::RuntimeConversion), CommitError> {
|
||||
let conversion = Registry::convert_from_runtime(network, metadata, resources, self.document.peer)?;
|
||||
let ops = crate::delta::compute_deltas(&self.document.working_registry, &conversion.registry);
|
||||
let hot_ops = self.stage_ops(ops)?;
|
||||
let ops = self.runtime_diff(&conversion.registry);
|
||||
let hot_ops = self.stage_runtime_diff(ops, conversion.registry.clone())?;
|
||||
Ok((hot_ops, conversion))
|
||||
}
|
||||
|
||||
/// The ops from the last staged runtime state to `registry`, a fresh conversion of the runtime network.
|
||||
pub fn runtime_diff(&self, registry: &Registry) -> Vec<RegistryDelta> {
|
||||
match &self.runtime_base {
|
||||
Some(base) => crate::delta::compute_deltas(base, registry),
|
||||
None => crate::delta::compute_deltas(&self.document.working_registry.as_rendered(), registry),
|
||||
}
|
||||
}
|
||||
|
||||
/// Stage the [`runtime_diff`](Self::runtime_diff) ops of `registry` and keep `registry` as the last runtime state.
|
||||
pub fn stage_runtime_diff(&mut self, ops: Vec<RegistryDelta>, registry: Registry) -> Result<Vec<HotOp>, CrdtError> {
|
||||
// Lenient since a peer's concurrent write may have reshaped what the diff names.
|
||||
let hot_ops = self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())), ApplyMode::Idempotent)?;
|
||||
self.runtime_base = Some(registry);
|
||||
Ok(hot_ops)
|
||||
}
|
||||
|
||||
pub fn mark_runtime_current(&mut self) {
|
||||
self.runtime_base = Some(self.document.working_registry.as_rendered());
|
||||
}
|
||||
|
||||
/// The stable [`NetworkId`] of each runtime network location for this document's peer, to key per-network view state in `session.json`.
|
||||
/// It depends only on the network structure, not on resources or declarations.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub fn network_ids<M: NodeMetadataSource>(&self, network: &graph_craft::document::NodeNetwork, metadata: &M) -> Result<HashMap<graph_craft::document::NetworkLocation, NetworkId>, CommitError> {
|
||||
let conversion = Registry::convert_from_runtime(network, metadata, &graphene_resource::ResourceRegistry::new(), self.document.peer)?;
|
||||
let conversion = Registry::convert_from_runtime_inline(network, metadata, &graphene_resource::ResourceRegistry::new(), self.document.peer)?;
|
||||
Ok(conversion.network_ids)
|
||||
}
|
||||
|
||||
@@ -170,7 +193,8 @@ impl Session {
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
/// Stages ops computed outside the session, such as a runtime diff or an incremental projection, as hot ops.
|
||||
/// Stages ops computed outside the session (an incremental runtime projection) as hot ops, the
|
||||
/// same way `stage_from_runtime` stages a diff's ops.
|
||||
pub fn stage_computed_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
self.stage_ops(ops)
|
||||
}
|
||||
@@ -183,10 +207,10 @@ impl Session {
|
||||
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
|
||||
/// before any of its edits. A no-op batch doesn't register, since registration rides a real edit.
|
||||
pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())))
|
||||
self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())), ApplyMode::Strict)
|
||||
}
|
||||
|
||||
fn stage_ops_with(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Attributes)>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
fn stage_ops_with(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Attributes)>, mode: ApplyMode) -> Result<Vec<HotOp>, CrdtError> {
|
||||
// A batch is staged whole or not at all.
|
||||
let mut pending: Vec<(RegistryDelta, Attributes)> = ops.into_iter().collect();
|
||||
if pending.is_empty() {
|
||||
@@ -194,7 +218,10 @@ impl Session {
|
||||
}
|
||||
|
||||
let (peer, user) = (self.document.peer, self.document.user);
|
||||
if self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
|
||||
let carried = pending
|
||||
.iter()
|
||||
.any(|(op, _)| matches!(op, RegistryDelta::RegisterPeer { peer: named, user: naming } if *named == peer && *naming == user));
|
||||
if !carried && self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
|
||||
pending.insert(0, (RegistryDelta::RegisterPeer { peer, user }, Attributes::new()));
|
||||
}
|
||||
|
||||
@@ -213,7 +240,7 @@ impl Session {
|
||||
sequence,
|
||||
attributes,
|
||||
};
|
||||
if let Err(error) = self.document.stage_hot_op(hot_op.clone(), ApplyMode::Strict) {
|
||||
if let Err(error) = self.document.stage_hot_op(hot_op.clone(), mode) {
|
||||
// The run continues where it was, so no sequence goes unused.
|
||||
self.document.last_hot_sequence = sequence_before;
|
||||
if !staged.is_empty() {
|
||||
@@ -227,9 +254,20 @@ impl Session {
|
||||
self.document.last_hot_sequence = sequence;
|
||||
staged.push(hot_op);
|
||||
}
|
||||
self.advance_runtime_base(&staged);
|
||||
Ok(staged)
|
||||
}
|
||||
|
||||
/// Keeps a later whole-document stage from restating a local batch.
|
||||
fn advance_runtime_base(&mut self, staged: &[HotOp]) {
|
||||
let Some(base) = self.runtime_base.take() else { return };
|
||||
let working = std::mem::replace(&mut self.document.working_registry, base);
|
||||
for hot_op in staged {
|
||||
let _ = self.document.apply_op_with(RegistryTarget::Working, hot_op.op.clone(), hot_op.timestamp, ApplyMode::Idempotent);
|
||||
}
|
||||
self.runtime_base = Some(std::mem::replace(&mut self.document.working_registry, working));
|
||||
}
|
||||
|
||||
/// Wrap each op as a `Delta`, apply it, and chain it onto the local history. One tick per op.
|
||||
///
|
||||
/// Operates on the retired snapshot, so each `reverse` holds the true pre-op state; the working registry already
|
||||
@@ -303,6 +341,7 @@ impl Session {
|
||||
..Document::empty(peer, user)
|
||||
},
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
taken_back_resources: HashSet::new(),
|
||||
}
|
||||
}
|
||||
@@ -328,6 +367,7 @@ impl Session {
|
||||
/// Drop hot ops another peer retired, without retiring them here. Until their deltas arrive, the working registry
|
||||
/// shows the snapshot plus what is still hot.
|
||||
pub fn discard_hot_ops(&mut self, retired: &[HotOpId]) -> Touched {
|
||||
self.runtime_base = None;
|
||||
self.document.mark_retired(retired.iter().copied())
|
||||
}
|
||||
|
||||
@@ -352,6 +392,7 @@ impl Session {
|
||||
if ids.iter().any(|&id| retired.covers(id)) || !retired.took_back_all(peer, own[own.len() - 1].sequence, self.document.last_hot_sequence) {
|
||||
return Ok(None);
|
||||
}
|
||||
self.runtime_base = None;
|
||||
let (touched, taken) = self.document.retract_hot_ops(&ids);
|
||||
self.taken_back_resources.extend(taken.iter().filter_map(|hot_op| hot_op.op.resource_hash()));
|
||||
let ops = taken.into_iter().map(|hot_op| hot_op.op).filter(|op| !matches!(op, RegistryDelta::Meta)).collect();
|
||||
@@ -360,6 +401,7 @@ impl Session {
|
||||
|
||||
/// Take back hot ops another peer retracted. See [`retract_interaction`](Self::retract_interaction).
|
||||
pub fn retract_hot_ops(&mut self, ids: &[HotOpId]) -> Touched {
|
||||
self.runtime_base = None;
|
||||
self.document.retract_hot_ops(ids).0
|
||||
}
|
||||
|
||||
@@ -422,6 +464,7 @@ impl Session {
|
||||
|
||||
self.document.redo_stack.clear();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
if let Some(head) = self.document.head {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
@@ -449,6 +492,7 @@ impl Session {
|
||||
self.document.retired_snapshot = snapshot;
|
||||
self.document.redo_stack.clear();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
self.publish_up_to(target);
|
||||
Ok((
|
||||
HeadMove {
|
||||
@@ -496,12 +540,25 @@ impl Session {
|
||||
}
|
||||
self.document.redo_stack.clear();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
if let Some(head) = moved.head {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
Ok(touched)
|
||||
}
|
||||
|
||||
/// What the deltas from `tip` back along its parents to `base` named, without `base` itself.
|
||||
pub fn touched_between(&self, base: Option<Rev>, tip: Rev) -> Touched {
|
||||
let mut touched = Touched::default();
|
||||
let mut cursor = Some(tip);
|
||||
while cursor != base {
|
||||
let Some(delta) = cursor.and_then(|rev| self.document.history.get(rev)) else { break };
|
||||
touched.record(&delta.kind);
|
||||
cursor = delta.parent;
|
||||
}
|
||||
touched
|
||||
}
|
||||
|
||||
/// What the deltas on the head's line but not on `base`'s named, merged branches included. Fails unless `base` is
|
||||
/// on the head's line.
|
||||
fn touched_since(&self, base: Option<Rev>) -> Result<Touched, CrdtError> {
|
||||
@@ -542,6 +599,7 @@ impl Session {
|
||||
}
|
||||
self.document.history.canonical_sort();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
@@ -552,7 +610,11 @@ impl Session {
|
||||
|
||||
/// Take on a peer's marks, or this peer's persisted ones, dropping the hot ops they cover. Returns what those named.
|
||||
pub fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Touched {
|
||||
self.document.absorb_retired_marks(remote)
|
||||
let touched = self.document.absorb_retired_marks(remote);
|
||||
if !touched.is_empty() {
|
||||
self.runtime_base = None;
|
||||
}
|
||||
touched
|
||||
}
|
||||
|
||||
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
|
||||
@@ -600,7 +662,7 @@ impl Session {
|
||||
}
|
||||
let mut closing = Attributes::new();
|
||||
closing.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), TimeStamp::ORIGIN);
|
||||
self.stage_ops_with([(RegistryDelta::Meta, closing)])
|
||||
self.stage_ops_with([(RegistryDelta::Meta, closing)], ApplyMode::Strict)
|
||||
}
|
||||
|
||||
/// Every author's closed interactions in the hot log, the earliest closed first.
|
||||
@@ -694,6 +756,7 @@ impl Session {
|
||||
} else {
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
}
|
||||
if !self.document.history.extends_canonically(length_before) {
|
||||
self.document.history.canonical_sort();
|
||||
@@ -768,6 +831,7 @@ impl Session {
|
||||
if refold {
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
}
|
||||
|
||||
Ok(outcome)
|
||||
@@ -843,6 +907,13 @@ impl Session {
|
||||
self.document.history.mark_interaction_end(rev, timestamp);
|
||||
}
|
||||
|
||||
/// Record the retirer's clock for these deltas. Not part of their revs and never used for ordering.
|
||||
pub fn stamp_retired_at(&mut self, revs: &[Rev], wall_ms: u64) {
|
||||
for &rev in revs {
|
||||
self.document.history.set_retired_at(rev, wall_ms);
|
||||
}
|
||||
}
|
||||
|
||||
/// Give a minted copy the attributes and retirement time of the delta it stands for.
|
||||
fn carry_attributes(&mut self, original: &Delta, copy: Rev) {
|
||||
if let Some(wall_ms) = original.retired_at() {
|
||||
@@ -889,6 +960,11 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Forget the latest undone interaction, so redo can't bring it back.
|
||||
pub fn forget_latest_undo(&mut self) -> Option<Rev> {
|
||||
self.document.redo_stack.pop()
|
||||
}
|
||||
|
||||
pub fn can_redo(&self) -> bool {
|
||||
!self.document.redo_stack.is_empty()
|
||||
}
|
||||
@@ -898,6 +974,7 @@ impl Session {
|
||||
pub fn undo(&mut self) -> Result<Rev, CrdtError> {
|
||||
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
|
||||
let base = self.interaction_start_parent(checkpoint, true).ok_or(CrdtError::NothingToUndo)?;
|
||||
self.runtime_base = None;
|
||||
|
||||
while let Some(rev) = self.document.head.filter(|&rev| rev != base) {
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
|
||||
@@ -918,6 +995,7 @@ impl Session {
|
||||
/// parents back from the checkpoint to `head` (the chain is linear in the silent solo zone).
|
||||
pub fn redo(&mut self) -> Result<Rev, CrdtError> {
|
||||
let checkpoint = self.document.redo_stack.pop().ok_or(CrdtError::NothingToRedo)?;
|
||||
self.runtime_base = None;
|
||||
|
||||
let mut forward = Vec::new();
|
||||
let mut cursor = Some(checkpoint);
|
||||
@@ -1013,12 +1091,20 @@ impl Session {
|
||||
hashes
|
||||
}
|
||||
|
||||
/// Every blob the current registry, its tombstones, history, or hot log names, so any state the cursor reaches can be resolved.
|
||||
/// Every blob that the registry, its tombstones, the history or the hot log names.
|
||||
pub fn all_blob_hashes(&self) -> HashSet<BlobHash> {
|
||||
let mut hashes: HashSet<BlobHash> = self.document.working_registry.blob_hashes().collect();
|
||||
hashes.extend(self.document.history.iter().flat_map(Delta::blob_hashes));
|
||||
hashes.extend(self.document.hot_log.iter().flat_map(|hot_op| hot_op.op.blob_hashes()));
|
||||
hashes
|
||||
self.blob_hashes().collect()
|
||||
}
|
||||
|
||||
/// Whether the registry, its tombstones, the history or the hot log names `hash`.
|
||||
pub fn names_blob(&self, hash: BlobHash) -> bool {
|
||||
self.blob_hashes().any(|named| named == hash)
|
||||
}
|
||||
|
||||
fn blob_hashes(&self) -> impl Iterator<Item = BlobHash> + '_ {
|
||||
let history = self.document.history.iter().flat_map(Delta::blob_hashes);
|
||||
let hot_log = self.document.hot_log.iter().flat_map(|hot_op| hot_op.op.blob_hashes());
|
||||
self.document.working_registry.blob_hashes().chain(history).chain(hot_log)
|
||||
}
|
||||
|
||||
/// Every referenced resource hash plus what the ops this peer took back named. Garbage collection must keep these.
|
||||
|
||||
@@ -1406,23 +1406,6 @@ fn a_network_re_added_shorter_keeps_only_its_own_exports() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Two registries ordering a removal differently against a write are not order-consistent, though their values agree.
|
||||
#[test]
|
||||
fn order_consistency_covers_removal_stamps() {
|
||||
let with_removal_at = |counter: u64| {
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let node = Node::new(NetworkId(1), crate::Implementation::ProtoNode(graphene_resource::ResourceId::from(7)), 0);
|
||||
document.apply_op_idempotent(RegistryDelta::AddNode { id: NodeId(2), node: node.clone() }, ts(3, 1)).expect("add");
|
||||
document
|
||||
.apply_op_idempotent(RegistryDelta::RemoveNode { id: NodeId(1), snapshot: node }, ts(counter, 1))
|
||||
.expect("remove");
|
||||
document.working_registry
|
||||
};
|
||||
let (earlier, later) = (with_removal_at(2), with_removal_at(4));
|
||||
assert!(earlier.value_equal(&later));
|
||||
assert!(!earlier.order_consistent(&later));
|
||||
}
|
||||
|
||||
/// An input naming a node whose addition has not arrived renders as a dangling input, as one naming a removed node does,
|
||||
/// rather than failing the conversion: the placeholder knows nothing of the node's network.
|
||||
#[test]
|
||||
|
||||
@@ -862,7 +862,7 @@ fn an_unreached_table_entry_is_not_stored() {
|
||||
assert_eq!(registry.networks.keys().copied().collect::<Vec<_>>(), vec![crate::ROOT_NETWORK]);
|
||||
}
|
||||
|
||||
/// A large input value is stored as a blob and resolved from the blob bytes on the way back.
|
||||
/// A large input value is stored as a blob and read back from the blob bytes.
|
||||
#[test]
|
||||
fn large_input_value_round_trips_through_a_blob() {
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
//! Peers exchanging retired history, moving the shared head, and undoing against what other peers hold.
|
||||
|
||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput as RuntimeInput, NodeNetwork};
|
||||
|
||||
use crate::{
|
||||
AttributeDelta, CrdtError, Delta, History, HotOp, HotOpId, Implementation, InputSlot, MergeOutcome, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry,
|
||||
ResourceHash, ResourceId, Rev, Session, TimeStamp, UserId, Value,
|
||||
AttributeDelta, CrdtError, Delta, History, HotOp, HotOpId, Implementation, InputSlot, MergeOutcome, Network, NetworkId, NoMetadata, Node, NodeId, NodeInput, PeerId, Registry, RegistryDelta,
|
||||
ResourceEntry, ResourceHash, ResourceId, Rev, Session, TimeStamp, UserId, Value,
|
||||
};
|
||||
use std::collections::HashSet;
|
||||
|
||||
@@ -397,6 +402,46 @@ fn rebuilt_working(session: &Session) -> Registry {
|
||||
copy.document.working_registry
|
||||
}
|
||||
|
||||
fn runtime_network(values: [u32; 2]) -> NodeNetwork {
|
||||
NodeNetwork {
|
||||
exports: vec![RuntimeInput::node(RuntimeNodeId(0), 0)],
|
||||
nodes: [(
|
||||
RuntimeNodeId(0),
|
||||
DocumentNode {
|
||||
inputs: values.iter().map(|&value| RuntimeInput::value(TaggedValue::Integer(value as i64), false)).collect(),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A stage past a peer's shrunken input list lands like a peer's write, so later stages don't fail.
|
||||
#[test]
|
||||
fn a_local_stage_after_a_peers_input_list_change_still_lands() {
|
||||
let resources = graphene_resource::ResourceRegistry::new();
|
||||
let mut a = Session::with_peer(PeerId(1));
|
||||
a.stage_from_runtime(&runtime_network([1, 2]), &NoMetadata, &resources).expect("first stage");
|
||||
let up_to = a.hot_log().last().unwrap().timestamp;
|
||||
a.retire(up_to).unwrap();
|
||||
|
||||
let mut b = Session::with_peer(PeerId(2));
|
||||
sync(&mut a, &mut b);
|
||||
let (&id, node) = b.registry().node_instances.iter().find(|(_, node)| node.inputs().len() == 2).expect("the converted node");
|
||||
let first = node.inputs()[0].clone();
|
||||
let shrink = b.stage_ops([RegistryDelta::SetNodeInputs { id, inputs: vec![first] }]).unwrap();
|
||||
for hot_op in shrink {
|
||||
a.replay_hot_op(hot_op).unwrap();
|
||||
}
|
||||
|
||||
let edit = a.stage_from_runtime(&runtime_network([1, 5]), &NoMetadata, &resources);
|
||||
let later = a.stage_from_runtime(&runtime_network([9, 5]), &NoMetadata, &resources);
|
||||
assert!(edit.is_ok() || later.is_ok(), "a later stage still lands: first {:?}, later {:?}", edit.err(), later.err());
|
||||
}
|
||||
|
||||
struct Lcg(u64);
|
||||
impl Lcg {
|
||||
fn below(&mut self, bound: u64) -> u64 {
|
||||
@@ -439,7 +484,11 @@ fn local_op(rng: &mut Lcg, registry: &Registry) -> Option<RegistryDelta> {
|
||||
key: key.into(),
|
||||
value: (rng.below(4) > 0).then(|| Value::from(serde_json::json!(rng.below(50)))),
|
||||
};
|
||||
Some(match rng.below(9) {
|
||||
let source_key = |rng: &mut Lcg| crate::SourceKey {
|
||||
priority: crate::Priority::new(rng.below(2) as f64).expect("finite"),
|
||||
peer: PeerId(1 + rng.below(2)),
|
||||
};
|
||||
Some(match rng.below(17) {
|
||||
0 | 1 => RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: {
|
||||
let key = ["x", "y"][rng.below(2) as usize];
|
||||
@@ -500,7 +549,7 @@ fn local_op(rng: &mut Lcg, registry: &Registry) -> Option<RegistryDelta> {
|
||||
new_input: input(rng),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
8 => {
|
||||
let id = pick(rng, seen_nodes.clone())?;
|
||||
let inputs = (0..1 + rng.below(3))
|
||||
.map(|_| InputSlot {
|
||||
@@ -511,6 +560,55 @@ fn local_op(rng: &mut Lcg, registry: &Registry) -> Option<RegistryDelta> {
|
||||
.collect();
|
||||
RegistryDelta::SetNodeInputs { id: NodeId(id), inputs }
|
||||
}
|
||||
9 => RegistryDelta::SetNetworkExport {
|
||||
id: NetworkId(pick(rng, seen_networks.clone())?),
|
||||
index: rng.below(2) as u32,
|
||||
export: (rng.below(3) > 0).then(|| input(rng)),
|
||||
},
|
||||
10 => RegistryDelta::ChangeNetworkAttribute {
|
||||
id: NetworkId(pick(rng, seen_networks.clone())?),
|
||||
delta: attribute(rng, "name"),
|
||||
},
|
||||
11 => RegistryDelta::SetNodeImplementation {
|
||||
id: NodeId(pick(rng, seen_nodes.clone())?),
|
||||
implementation: Implementation::Network(NetworkId(pick(rng, seen_networks.clone())?)),
|
||||
},
|
||||
12 => {
|
||||
let mut entry = ResourceEntry {
|
||||
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
|
||||
..Default::default()
|
||||
};
|
||||
entry.force_set_source(
|
||||
source_key(rng),
|
||||
crate::SourceValue {
|
||||
source: Value::from(serde_json::json!(rng.below(9))),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
RegistryDelta::AddResource {
|
||||
id: ResourceId::from(1 + rng.below(2)),
|
||||
entry,
|
||||
}
|
||||
}
|
||||
13 => {
|
||||
let id = ResourceId::from(1 + rng.below(2));
|
||||
let snapshot = registry.resources.get(&id)?.clone();
|
||||
RegistryDelta::RemoveResource { id, snapshot }
|
||||
}
|
||||
14 => RegistryDelta::SetResourceHash {
|
||||
id: ResourceId::from(1 + rng.below(2)),
|
||||
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
|
||||
},
|
||||
15 => RegistryDelta::AddSource {
|
||||
id: ResourceId::from(1 + rng.below(2)),
|
||||
key: source_key(rng),
|
||||
source: Value::from(serde_json::json!(rng.below(9))),
|
||||
},
|
||||
_ => RegistryDelta::RemoveSource {
|
||||
id: ResourceId::from(1 + rng.below(2)),
|
||||
key: source_key(rng),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -774,7 +872,7 @@ fn a_dropped_interaction_leaves_the_line_and_the_room_follows() {
|
||||
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.document.history.set_retired_at(later, 1_234);
|
||||
host.stamp_retired_at(&[later], 1_234);
|
||||
catch_up(&mut guest, &host);
|
||||
assert_eq!(guest.head_rev(), host.head_rev());
|
||||
assert_eq!(guest.latest_own_interaction(), Some(undone));
|
||||
@@ -1017,6 +1115,68 @@ fn discarded_hot_ops_leave_the_working_registry_at_the_snapshot() {
|
||||
assert_eq!(session.registry(), session.retired_registry());
|
||||
}
|
||||
|
||||
/// Staging a rebuilt runtime unchanged must not restore a network a peer removed while another kept writing to its owner.
|
||||
#[test]
|
||||
fn restaging_an_unchanged_runtime_does_not_revive_a_nested_network_removed_under_a_live_owner() {
|
||||
let resources = graphene_resource::ResourceRegistry::new();
|
||||
let outer = NodeNetwork {
|
||||
exports: vec![RuntimeInput::node(RuntimeNodeId(0), 0)],
|
||||
nodes: [(
|
||||
RuntimeNodeId(0),
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Definition(graph_craft::document::NetworkId(9)),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
definitions: [(graph_craft::document::NetworkId(9), runtime_network([1, 2]))].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut a = Session::with_peer(PeerId(1));
|
||||
let (_, conversion) = a.stage_from_runtime(&outer, &NoMetadata, &resources).expect("first stage");
|
||||
let up_to = a.hot_log().last().unwrap().timestamp;
|
||||
a.retire(up_to).unwrap();
|
||||
let mut b = Session::with_peer(PeerId(2));
|
||||
sync(&mut a, &mut b);
|
||||
|
||||
let (&owner, owner_node) = b
|
||||
.registry()
|
||||
.node_instances
|
||||
.iter()
|
||||
.find(|(_, node)| matches!(node.implementation(), Implementation::Network(_)))
|
||||
.expect("the owner");
|
||||
let Implementation::Network(nested) = *owner_node.implementation() else { unreachable!() };
|
||||
let mut removal = vec![RegistryDelta::RemoveNode {
|
||||
id: owner,
|
||||
snapshot: owner_node.clone(),
|
||||
}];
|
||||
for (&id, node) in b.registry().node_instances.iter().filter(|(_, node)| node.network() == nested) {
|
||||
removal.push(RegistryDelta::RemoveNode { id, snapshot: node.clone() });
|
||||
}
|
||||
removal.push(RegistryDelta::RemoveNetwork {
|
||||
id: nested,
|
||||
snapshot: b.registry().networks[&nested].clone(),
|
||||
});
|
||||
let removal = b.stage_ops(removal).unwrap();
|
||||
|
||||
// A writes after the removal, so only the nested network goes.
|
||||
for _ in 0..10 {
|
||||
a.document.clock.tick();
|
||||
}
|
||||
a.stage_ops([change_node_attribute(owner, "tint", serde_json::json!(1))]).unwrap();
|
||||
for hot_op in removal {
|
||||
a.replay_hot_op(hot_op).unwrap();
|
||||
}
|
||||
assert!(a.registry().node_instances.contains_key(&owner));
|
||||
assert!(!a.registry().networks.contains_key(&nested));
|
||||
|
||||
let (runtime, _) = a.registry().to_runtime_with_metadata(&conversion.declarations, &conversion.blob_bytes).expect("to runtime");
|
||||
a.mark_runtime_current();
|
||||
a.stage_from_runtime(&runtime, &NoMetadata, &resources).expect("restage");
|
||||
assert!(!a.registry().networks.contains_key(&nested), "the removed network stays removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drop_whose_copy_fails_leaves_the_session_unchanged() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
@@ -1047,3 +1207,74 @@ fn a_drop_whose_copy_fails_leaves_the_session_unchanged() {
|
||||
assert_eq!(session.retired_registry(), &retired);
|
||||
assert_eq!(session.registry(), ®istry);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_carrying_its_registration_is_not_given_another() {
|
||||
let mut session = Session::with_peer(crate::PeerId(1));
|
||||
let register = RegistryDelta::RegisterPeer {
|
||||
peer: crate::PeerId(1),
|
||||
user: session.user(),
|
||||
};
|
||||
assert_eq!(session.stage_computed_ops(vec![register]).expect("stage").len(), 1);
|
||||
}
|
||||
|
||||
/// Only what the root reaches renders, so a removal no rendered node undoes stays a removal.
|
||||
#[test]
|
||||
fn a_removed_network_counts_as_rendered_only_when_the_root_reaches_it() {
|
||||
let (run_by_root, nested, run_by_stray, stray) = (NetworkId(1), NetworkId(2), NetworkId(3), NetworkId(4));
|
||||
let node = |network, runs| crate::Node {
|
||||
presence: TimeStamp::default(),
|
||||
network,
|
||||
network_timestamp: TimeStamp::default(),
|
||||
implementation: Implementation::Network(runs),
|
||||
implementation_timestamp: TimeStamp::default(),
|
||||
inputs: Vec::new(),
|
||||
inputs_timestamp: TimeStamp::default(),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
let mut registry = Registry::default();
|
||||
for (id, network, runs) in [(1, crate::ROOT_NETWORK, run_by_root), (2, run_by_root, nested), (3, stray, run_by_stray)] {
|
||||
registry.node_instances.insert(crate::NodeId(id), node(network, runs));
|
||||
}
|
||||
for id in [run_by_root, nested, run_by_stray] {
|
||||
let mark = crate::Tombstone {
|
||||
content: Network::default(),
|
||||
timestamp: TimeStamp::default(),
|
||||
placeholder: false,
|
||||
};
|
||||
registry.removed_networks.insert(id, mark);
|
||||
}
|
||||
|
||||
let rendered = registry.as_rendered();
|
||||
assert!(rendered.networks.contains_key(&run_by_root) && rendered.networks.contains_key(&nested));
|
||||
assert!(!rendered.networks.contains_key(&run_by_stray) && rendered.removed_networks.contains_key(&run_by_stray));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_span_an_undo_walks_names_only_the_undone_step() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
let base = step(&mut session, add_network(1));
|
||||
let tip = step(&mut session, add_network(2));
|
||||
|
||||
let undone = session.undo().expect("undo");
|
||||
assert_eq!(undone, tip);
|
||||
let touched = session.touched_between(session.head_rev(), undone);
|
||||
assert_eq!(touched.networks, [NetworkId(2)].into_iter().collect());
|
||||
assert_eq!(session.head_rev(), Some(base));
|
||||
|
||||
let from = session.head_rev();
|
||||
let redone = session.redo().expect("redo");
|
||||
assert_eq!(session.touched_between(from, redone).networks, [NetworkId(2)].into_iter().collect());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_forgotten_undo_cannot_be_redone() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
step(&mut session, add_network(1));
|
||||
let tip = step(&mut session, add_network(2));
|
||||
|
||||
session.undo().expect("undo");
|
||||
assert_eq!(session.forget_latest_undo(), Some(tip));
|
||||
assert!(!session.can_redo());
|
||||
assert!(session.redo_stack().is_empty());
|
||||
}
|
||||
@@ -117,7 +117,7 @@ impl<'a> ConversionContext<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The value blob `hash` holds.
|
||||
/// The value stored in blob `hash`.
|
||||
fn resolve_blob(&self, hash: BlobHash) -> Result<Value, ConversionError> {
|
||||
let bytes = self.blobs.get(&hash).ok_or(ConversionError::BlobNotFound(hash))?;
|
||||
decode_blob(bytes).map_err(|error| ConversionError::DeserializationError(format!("Blob {hash}: {error}")))
|
||||
@@ -201,6 +201,21 @@ impl RuntimeProjection<'_> {
|
||||
(network == ROOT_NETWORK || self.reachable.contains(&network)).then(|| runtime_location(network))
|
||||
}
|
||||
|
||||
pub fn definitions(&self) -> impl Iterator<Item = RuntimeNetworkId> + '_ {
|
||||
self.reachable.iter().map(|&id| runtime_network_id(id))
|
||||
}
|
||||
|
||||
pub fn network_nodes(&self, network: NetworkId) -> impl Iterator<Item = NodeId> + '_ {
|
||||
self.context.nodes_by_network.get(&network).into_iter().flatten().map(|&(id, _)| id)
|
||||
}
|
||||
|
||||
pub fn implemented_network(&self, id: NodeId) -> Option<NetworkId> {
|
||||
match self.context.registry.node_instances.get(&id)?.implementation {
|
||||
Implementation::Network(network) => Some(network),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The location of the node's network in the runtime, and the node's ID in that network.
|
||||
pub fn node_address(&self, id: NodeId) -> Option<(NetworkLocation, RuntimeNodeId)> {
|
||||
let node = self.context.registry.node_instances.get(&id)?;
|
||||
|
||||
@@ -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, features = ["network"] }
|
||||
document-graph-storage = { workspace = true }
|
||||
peer-transport = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,109 @@
|
||||
//! A memory-backed document in a collaborative session. The caller spawns the transport driver.
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
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, 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 {
|
||||
/// Host an empty document under `token`. `spawn` must drive the returned future for the whole session.
|
||||
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, user).await?;
|
||||
Self::host_document(gdd, signaling_server, token, user, spawn)
|
||||
}
|
||||
|
||||
pub fn host_document(mut gdd: GddV1, signaling_server: &str, token: SessionToken, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
|
||||
gdd.share(Self::connect(signaling_server, token, spawn), user)?;
|
||||
Ok(Self { gdd, token })
|
||||
}
|
||||
|
||||
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, user).await?;
|
||||
gdd.connect(Self::connect(signaling_server, token, spawn), user)?;
|
||||
Ok(Self { gdd, token })
|
||||
}
|
||||
|
||||
fn connect(signaling_server: &str, token: SessionToken, spawn: impl FnOnce(MessageLoopFuture)) -> Room {
|
||||
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
|
||||
spawn(driver);
|
||||
room
|
||||
}
|
||||
|
||||
async fn empty_document(peer: PeerId, user: UserId) -> Result<GddV1, FormatError> {
|
||||
let version = env!("CARGO_PKG_VERSION").to_string();
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, peer, user, peer.0, version.clone(), version)
|
||||
}
|
||||
|
||||
pub fn token(&self) -> SessionToken {
|
||||
self.token
|
||||
}
|
||||
|
||||
pub fn is_synced(&self) -> bool {
|
||||
self.gdd.is_synced()
|
||||
}
|
||||
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.is_synced() && SyncTarget::missing_resources(&self.gdd).is_empty()
|
||||
}
|
||||
|
||||
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 what peers sent and answer their 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
|
||||
}
|
||||
|
||||
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, self.gdd.blobs())?;
|
||||
Ok(network)
|
||||
}
|
||||
|
||||
pub fn leave(&mut self) {
|
||||
self.gdd.leave();
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,7 @@ impl MigrationHost for CompilerHost {
|
||||
}
|
||||
|
||||
// A state that doesn't convert answers nothing, so each migration asking takes its fallback.
|
||||
// Node migrations run on states whose blobs are already resolved, so none are passed.
|
||||
// Node migrations only see states with resolved blobs, so no blobs are needed.
|
||||
let (mut inlined, nodes, _) = state.to_runtime_with_full_metadata(&declarations, &BlobBytes::new()).ok()?;
|
||||
inlined.inline_definitions().ok()?;
|
||||
|
||||
|
||||
@@ -29,9 +29,9 @@ pub struct DocumentPayloads {
|
||||
pub history: Vec<Payload>,
|
||||
pub hot_log: Vec<Payload>,
|
||||
pub session: Option<Payload>,
|
||||
/// Blob bytes by hash that steps moved values into, for the load path to store.
|
||||
/// Blobs that steps moved values into. The load path stores them.
|
||||
pub blobs: HashMap<ResourceHash, Vec<u8>>,
|
||||
/// For each blob in `blobs`, the blob a store can encode it against.
|
||||
/// The base blob of each blob in `blobs`.
|
||||
pub blob_bases: HashMap<ResourceHash, ResourceHash>,
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ pub trait FormatMigration: Send + Sync {
|
||||
fn migrate_session(&self, session: &Payload) -> Result<Payload, MigrationError> {
|
||||
Ok(session.clone())
|
||||
}
|
||||
/// Transform the whole document once its records are converted, for a change needing state across records.
|
||||
/// Transform the whole document after its records are converted. Use this when a change needs state across records.
|
||||
fn migrate_document(&self, _document: &mut DocumentPayloads) -> Result<(), MigrationError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Format step 3 to 4, generated by `cargo run migration snapshot`. Types that only reach a changed one convert on their own. Finish the changed ones (Value) where a `compile_error!` or a type mismatch points.
|
||||
//! Format step 3 to 4, generated by `cargo run migration snapshot`.
|
||||
|
||||
use crate::{v3, v4};
|
||||
use graphene_resource::ResourceHash;
|
||||
@@ -541,10 +541,10 @@ impl Upgrade for v3::Value {
|
||||
}
|
||||
}
|
||||
|
||||
/// Values whose postcard encoding reaches this many bytes move into blobs, as the live threshold had it when version 4 began.
|
||||
/// Values whose postcard encoding reaches this many bytes move into blobs. This is the live threshold at version 4.
|
||||
const BLOB_THRESHOLD: usize = 1024;
|
||||
|
||||
/// Move large node input values into blobs, in stored order so each blob's base is the one its slot held before.
|
||||
/// Move large node input values into blobs. Records are visited in stored order, so the base of a blob is the previous blob of its slot.
|
||||
fn move_values_into_blobs(document: &mut DocumentPayloads) -> Result<(), MigrationError> {
|
||||
let mut blobs = Blobs::default();
|
||||
|
||||
@@ -561,7 +561,7 @@ fn move_values_into_blobs(document: &mut DocumentPayloads) -> Result<(), Migrati
|
||||
}
|
||||
if let Some(record) = &mut document.registry {
|
||||
let mut registry: v4::Registry = record.decode()?;
|
||||
// In ID order, so which of two slots sharing a new value bases it doesn't depend on hashing
|
||||
// Sort by ID so the base choice does not depend on hash map order
|
||||
let mut nodes: Vec<_> = registry.node_instances.iter_mut().collect();
|
||||
nodes.sort_unstable_by_key(|(id, _)| **id);
|
||||
for (id, node) in nodes {
|
||||
@@ -580,7 +580,7 @@ fn move_values_into_blobs(document: &mut DocumentPayloads) -> Result<(), Migrati
|
||||
struct Blobs {
|
||||
bytes: HashMap<ResourceHash, Vec<u8>>,
|
||||
bases: HashMap<ResourceHash, ResourceHash>,
|
||||
/// The blob each input slot last held, by node and input index.
|
||||
/// The last blob of each input slot, by node and input index.
|
||||
latest: HashMap<(v4::NodeId, u32), ResourceHash>,
|
||||
}
|
||||
|
||||
@@ -599,7 +599,7 @@ impl Blobs {
|
||||
}
|
||||
}
|
||||
|
||||
/// Priors only restore earlier values, so they never advance a slot's latest blob.
|
||||
/// Priors only restore earlier values, so they never change the latest blob of a slot.
|
||||
fn prior(&mut self, prior: &mut v4::Prior) {
|
||||
match prior {
|
||||
v4::Prior::Node { node, .. } => self.loose_node(node),
|
||||
@@ -634,11 +634,11 @@ impl Blobs {
|
||||
}
|
||||
}
|
||||
|
||||
/// A write into an input slot, whose blob is based on the one the slot held before.
|
||||
/// A write into an input slot. Its blob is based on the previous blob of the slot.
|
||||
fn write(&mut self, id: v4::NodeId, index: u32, input: &mut v4::NodeInput) {
|
||||
let Some((hash, created)) = self.move_into_blob(input) else { return };
|
||||
|
||||
// Only a blob created here takes a base, which keeps bases acyclic
|
||||
// Only a newly created blob takes a base. This keeps bases acyclic
|
||||
if let Some(previous) = self.latest.insert((id, index), hash)
|
||||
&& created
|
||||
&& previous != hash
|
||||
@@ -647,7 +647,7 @@ impl Blobs {
|
||||
}
|
||||
}
|
||||
|
||||
/// The blob `input` now names, and whether this call created it.
|
||||
/// The blob that `input` now names, and whether this call created it.
|
||||
fn move_into_blob(&mut self, input: &mut v4::NodeInput) -> Option<(ResourceHash, bool)> {
|
||||
let v4::NodeInput::Value { value, .. } = input else { return None };
|
||||
if let v4::Value::Blob(hash) = value {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The step into version 4 moves large node input values into blobs that match what the live staging path would make.
|
||||
//! The step to version 4 moves large node input values into the same blobs that live staging makes.
|
||||
|
||||
use document_graph_storage::blob::{BLOB_THRESHOLD, BlobBytes, decode_blob};
|
||||
use document_graph_storage::{Delta, HotOp, Implementation, Network, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, ResourceId, Session, UserId, Value};
|
||||
@@ -20,7 +20,7 @@ fn postcard_payload(value: &impl serde::Serialize) -> Payload {
|
||||
|
||||
#[test]
|
||||
fn version_four_moves_large_values_into_blobs_based_on_their_slot() {
|
||||
// A version 3 document is a live one without blobs, since `Value::Blob` is the only change
|
||||
// `Value::Blob` is the only change in version 4, so a version 3 document is a live one without blobs
|
||||
let id = NodeId(1);
|
||||
let mut session = Session::with_identity(PeerId(1), UserId(1));
|
||||
let mut node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(1)), 1);
|
||||
@@ -60,7 +60,7 @@ fn version_four_moves_large_values_into_blobs_based_on_their_slot() {
|
||||
document.hot_log = document.hot_log.iter().map(|record| step.migrate_hot_op(record).unwrap()).collect();
|
||||
step.migrate_document(&mut document).unwrap();
|
||||
|
||||
// The live path hashes the same bytes, so a migrated blob and a freshly staged one are the same blob
|
||||
// Both paths hash the same bytes, so the migrated blob equals the staged one
|
||||
let staged_blob = |input: NodeInput| {
|
||||
let mut input = input;
|
||||
input.move_into_blob(&mut BlobBytes::new());
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn rename(input: TokenStream) -> TokenStream {
|
||||
|
||||
/// Registers a format step converting the listed stored roots through their `Upgrade` impls:
|
||||
/// `format_migration!(1 => 2, registry: v1::Registry, delta: v1::Delta);`. Roots left out keep their payloads.
|
||||
/// `document: function` adds a pass over the whole converted document, for changes needing state across records.
|
||||
/// `document: function` adds a pass over the whole converted document. Use it when a change needs state across records.
|
||||
#[proc_macro]
|
||||
pub fn format_migration(input: TokenStream) -> TokenStream {
|
||||
let step = parse_macro_input!(input as format::FormatStep);
|
||||
@@ -245,7 +245,7 @@ fn registration(core: &TokenStream2, register: TokenStream2, migration: TokenStr
|
||||
quote! {
|
||||
use #core::ctor::ctor;
|
||||
|
||||
#[cfg_attr(not(target_family = "wasm"), ctor)]
|
||||
#[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = #core::ctor))]
|
||||
fn register() {
|
||||
#core::#register(#migration);
|
||||
}
|
||||
|
||||
@@ -2,4 +2,5 @@
|
||||
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
|
||||
|
||||
mod graphene_core;
|
||||
mod math_nodes;
|
||||
mod raster_nodes;
|
||||
@@ -0,0 +1,107 @@
|
||||
use migration_core::{Node, Target, decl, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const EXPRESSION: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration reads.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
String(String),
|
||||
}
|
||||
|
||||
/// The lone operators 'Math f(…)' applied across its items, in every spelling its classifier read when the node was split.
|
||||
const OPERATORS: &[&str] = &["+", "-", "*", "/", "^", "&&", "∧", "||", "∨", "<", "<=", "≤", ">", ">=", "≥", "==", "!=", "≠"];
|
||||
|
||||
/// The variadic functions 'Math f(…)' called with all its items when given a lone name, also spelled with a leading `\`.
|
||||
const FUNCTIONS: &[&str] = &[
|
||||
"hypot",
|
||||
"min",
|
||||
"max",
|
||||
"mean",
|
||||
"median",
|
||||
"variance",
|
||||
"variancepop",
|
||||
"stdev",
|
||||
"stdevpop",
|
||||
"geomean",
|
||||
"harmmean",
|
||||
"rms",
|
||||
"mode",
|
||||
"count",
|
||||
"xor",
|
||||
"gcd",
|
||||
"lcm",
|
||||
];
|
||||
|
||||
/// 'Math f(…)' split by the kind of string it held: a lone operator or function name, which it applied across its items, moves to
|
||||
/// 'Math Aggregate', and an expression stays as 'Math Formula'. A wired string can't be read before it runs, so it stays an expression.
|
||||
#[migration("math_nodes::MathFNode"@1 => "math_nodes::MathFormulaNode"@2)]
|
||||
pub fn math_formula_from_math_f(node: &Node, target: &mut Target) {
|
||||
let Some(slot) = node.inputs().get(EXPRESSION) else { return };
|
||||
let Some(Tagged::String(expression)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
let token = expression.trim();
|
||||
let function = token.strip_prefix('\\').unwrap_or(token);
|
||||
if OPERATORS.contains(&token) || FUNCTIONS.contains(&function) {
|
||||
target.set(decl!("math_nodes::MathAggregateNode"@1));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{Declaration, NodeInput, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
const MATH_F: Declaration = decl!("math_nodes::MathFNode"@1);
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
// Only the items can read another 'Math f(…)', since the expression and output type don't take its number
|
||||
SourceContract {
|
||||
reads_own_output: |slot| slot == 0,
|
||||
..SourceContract::new(3, |random, slot| match slot {
|
||||
EXPRESSION => literal(Tagged::String(["+", "a * b", "\\max", " ≤ ", "min(a, b)"][random.below(5)].to_string())),
|
||||
_ => literal(random.below(4) as f64),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn migrated_declaration(expression: NodeInput) -> Option<Declaration> {
|
||||
let mut fixture = Fixture::new(&MathFormulaFromMathF);
|
||||
let anchor = fixture.add(MATH_F, vec![literal(1.), expression, literal(0.)]);
|
||||
let migrated = fixture.migrate(&MathFormulaFromMathF).unwrap();
|
||||
fixture.declaration_of(&migrated, anchor)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MathFormulaFromMathF, &contract());
|
||||
check_undo(&MathFormulaFromMathF, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lone_operators_and_functions_become_aggregates() {
|
||||
let aggregate = Some(decl!("math_nodes::MathAggregateNode"@1));
|
||||
let formula = Some(decl!("math_nodes::MathFormulaNode"@2));
|
||||
let expression = |text: &str| literal(Tagged::String(text.to_string()));
|
||||
|
||||
assert_eq!(migrated_declaration(expression("+")), aggregate);
|
||||
assert_eq!(migrated_declaration(expression(" ≠ ")), aggregate);
|
||||
assert_eq!(migrated_declaration(expression("max")), aggregate);
|
||||
assert_eq!(migrated_declaration(expression("\\mean")), aggregate);
|
||||
assert_eq!(migrated_declaration(expression("a + b")), formula);
|
||||
assert_eq!(migrated_declaration(expression("max(a, b)")), formula);
|
||||
assert_eq!(migrated_declaration(expression("")), formula);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wired_expression_becomes_a_formula() {
|
||||
let mut fixture = Fixture::new(&MathFormulaFromMathF);
|
||||
let source = fixture.add(MATH_F, vec![literal(1.), literal(Tagged::String("+".to_string())), literal(0.)]);
|
||||
let anchor = fixture.add(MATH_F, vec![literal(1.), NodeInput::Node { id: source, index: 0 }, literal(0.)]);
|
||||
let migrated = fixture.migrate(&MathFormulaFromMathF).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("math_nodes::MathFormulaNode"@2)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, source), Some(decl!("math_nodes::MathAggregateNode"@1)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Migrations of the nodes in `math_nodes`.
|
||||
|
||||
mod math_formula_from_math_f;
|
||||
mod renames;
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
|
||||
|
||||
use migration_core::rename;
|
||||
|
||||
rename!("math_nodes::MathFxNode"@1 => "math_nodes::MathFunctionNode"@2);
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Node migrations read and write values, not the blobs a document stores large ones in, so each run sees a state with its blobs decoded
|
||||
//! and its output moves large values back into blobs. A value the run left alone encodes to the blob it came from, so it diffs as unchanged.
|
||||
//! Node migrations work on values, not blobs. Each run sees its blobs decoded, and its output moves large values back into blobs.
|
||||
//! An unchanged value encodes to the same blob, so it does not show up in the diff.
|
||||
|
||||
use crate::RunnerError;
|
||||
use document_graph_storage::blob::{BlobBytes, NewBlobs, decode_blob};
|
||||
@@ -8,12 +8,12 @@ use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
/// The blobs a document stores, and those migrations moved new values into.
|
||||
/// The blobs of a document, plus the new blobs that migrations create.
|
||||
pub struct MigrationBlobs<'a> {
|
||||
stored: &'a BlobBytes,
|
||||
/// Blobs no stored one already holds.
|
||||
/// New blobs that are not stored yet.
|
||||
added: BlobBytes,
|
||||
/// For each added blob, the blob its input slot held before the migration, as the base a store can encode it against.
|
||||
/// The base of each added blob. The base is the blob its input slot held before the migration.
|
||||
bases: HashMap<BlobHash, BlobHash>,
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ impl Default for MigrationBlobs<'static> {
|
||||
}
|
||||
|
||||
impl<'a> MigrationBlobs<'a> {
|
||||
/// Resolve through the blobs a document `stored`.
|
||||
/// Resolve values from the `stored` blobs of a document.
|
||||
pub fn new(stored: &'a BlobBytes) -> Self {
|
||||
Self {
|
||||
stored,
|
||||
@@ -35,16 +35,16 @@ impl<'a> MigrationBlobs<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The blobs migrations added.
|
||||
/// The blobs that migrations added.
|
||||
pub fn into_added(self) -> NewBlobs {
|
||||
NewBlobs { bytes: self.added, bases: self.bases }
|
||||
}
|
||||
|
||||
/// `registry` with the blobs in the inputs of `nodes`, or of every node for `None`, decoded back into values.
|
||||
/// `registry` with the blobs in the inputs of `nodes` decoded back into values. `None` decodes every node.
|
||||
pub(crate) fn resolve<'r>(&self, registry: &'r Registry, nodes: Option<&[NodeId]>) -> Result<Cow<'r, Registry>, RunnerError> {
|
||||
let ids: Vec<NodeId> = match nodes {
|
||||
Some(nodes) => nodes.to_vec(),
|
||||
None => registry.node_instances.keys().copied().collect(),
|
||||
let ids: Cow<[NodeId]> = match nodes {
|
||||
Some(nodes) => Cow::Borrowed(nodes),
|
||||
None => Cow::Owned(registry.node_instances.keys().copied().collect()),
|
||||
};
|
||||
let holds_blob = |id: &NodeId| registry.node_instances.get(id).is_some_and(|node| node.inputs().iter().any(|slot| slot.input.blob().is_some()));
|
||||
if !ids.iter().any(holds_blob) {
|
||||
@@ -52,8 +52,8 @@ impl<'a> MigrationBlobs<'a> {
|
||||
}
|
||||
|
||||
let mut resolved = registry.clone();
|
||||
for id in ids {
|
||||
let Some(node) = resolved.node_instances.get_mut(&id) else { continue };
|
||||
for id in ids.iter() {
|
||||
let Some(node) = resolved.node_instances.get_mut(id) else { continue };
|
||||
for slot in node.inputs_mut() {
|
||||
let NodeInput::Value { value, .. } = &mut slot.input else { continue };
|
||||
let Value::Blob(hash) = *value else { continue };
|
||||
@@ -66,7 +66,7 @@ impl<'a> MigrationBlobs<'a> {
|
||||
Ok(Cow::Owned(resolved))
|
||||
}
|
||||
|
||||
/// Move the large values of `migrated` back into blobs, basing each new one on the blob its slot held in `source`.
|
||||
/// Move the large values of `migrated` back into blobs. A new blob is based on the blob its slot held in `source`.
|
||||
pub(crate) fn store(&mut self, migrated: &mut Registry, source: &Registry) {
|
||||
let mut bytes = BlobBytes::new();
|
||||
migrated.move_values_into_blobs(&mut bytes);
|
||||
@@ -75,11 +75,7 @@ impl<'a> MigrationBlobs<'a> {
|
||||
return;
|
||||
}
|
||||
|
||||
for (hash, base) in migrated.blob_bases_since(source) {
|
||||
if bytes.contains_key(&hash) {
|
||||
self.bases.insert(hash, base);
|
||||
}
|
||||
}
|
||||
self.bases.extend(migrated.blob_bases_since(source).into_iter().filter(|(hash, _)| bytes.contains_key(hash)));
|
||||
self.added.extend(bytes);
|
||||
}
|
||||
}
|
||||
@@ -73,7 +73,7 @@ pub(crate) fn apply_migration(
|
||||
return Ok(source.clone());
|
||||
}
|
||||
|
||||
// A migration reading past its anchors, itself or through the compiler, needs every value decoded
|
||||
// A migration that reads beyond its anchors needs every value decoded
|
||||
let reads_beyond_anchors = migration.footprint().reads_network() || migration.asks_compiler();
|
||||
let resolved = blobs.resolve(source, (!reads_beyond_anchors).then_some(anchors.as_slice()))?;
|
||||
|
||||
|
||||
@@ -76,8 +76,8 @@ pub fn order_migrations(migrations: &[&'static dyn NodeMigration]) -> Result<Vec
|
||||
|
||||
/// Rewrite `history` through every migration whose source declaration it references, in dependency order. A migration is pending
|
||||
/// even when no live node uses its source, since a removed node keeps its old shape in history and undo can bring it back. `kept` names the
|
||||
/// states a cursor rests on, which even a migration only running at interaction boundaries has to keep. `blobs` resolves the
|
||||
/// blobs migrations read and collects the ones they add.
|
||||
/// states a cursor rests on, which even a migration only running at interaction boundaries has to keep. `blobs` resolves
|
||||
/// the blobs that migrations read and collects the blobs they add.
|
||||
pub fn migrate_history(
|
||||
migrations: &[&'static dyn NodeMigration],
|
||||
history: Vec<Delta>,
|
||||
|
||||
@@ -55,7 +55,7 @@ impl Fixture {
|
||||
apply_migration(migration, &self.registry, &self.table, host, &mut MigrationBlobs::default())
|
||||
}
|
||||
|
||||
/// Migrate a registry whose inputs name the blobs in `blobs`.
|
||||
/// Migrate a registry whose inputs name blobs from `blobs`.
|
||||
pub fn migrate_blobs(&self, migration: &dyn NodeMigration, blobs: &mut MigrationBlobs) -> Result<Registry, RunnerError> {
|
||||
apply_migration(migration, &self.registry, &self.table, None, blobs)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Migrations read the values a document stores in blobs, and the large values they write go back into blobs.
|
||||
//! Migrations read values that are stored in blobs. The large values they write go back into blobs.
|
||||
|
||||
use document_graph_storage::blob::{BLOB_THRESHOLD, BlobBytes};
|
||||
use document_graph_storage::{BlobHash, NodeInput, Value};
|
||||
@@ -13,7 +13,7 @@ pub fn append_to_text(node: &Node, inputs: &mut Inputs) {
|
||||
inputs.set(0, literal(format!("{text}!")));
|
||||
}
|
||||
|
||||
/// A large literal stored as a blob, with the bytes the document keeps for it.
|
||||
/// A large literal stored as a blob, together with its blob bytes.
|
||||
fn blob_literal(text: &str, blobs: &mut BlobBytes) -> (NodeInput, BlobHash) {
|
||||
let mut input = literal(text.to_string());
|
||||
input.move_into_blob(blobs);
|
||||
|
||||
@@ -13,7 +13,7 @@ publish.workspace = true
|
||||
[dependencies]
|
||||
core-types = { workspace = true }
|
||||
document-graph-storage = { workspace = true }
|
||||
matchbox_socket = "0.14.0"
|
||||
matchbox_socket = "0.15.0"
|
||||
futures = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -82,7 +82,7 @@ pub struct SyncPayload {
|
||||
pub document_id: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub metadata: HistoryMetadata,
|
||||
/// Every blob the synced state names, each after its base.
|
||||
/// Every blob that the synced state names. A base comes before the blobs that use it.
|
||||
#[serde(default)]
|
||||
pub blobs: Vec<BlobRecord>,
|
||||
}
|
||||
@@ -99,7 +99,7 @@ pub struct Broadcast {
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum BroadcastBody {
|
||||
/// Carries the records of the blobs the ops name, so a peer can resolve them on arrival.
|
||||
/// The records of new blobs that the ops name.
|
||||
HotOps {
|
||||
ops: Vec<HotOp>,
|
||||
blobs: Vec<BlobRecord>,
|
||||
@@ -117,7 +117,7 @@ pub enum BroadcastBody {
|
||||
HeadMove(HeadMove),
|
||||
}
|
||||
|
||||
/// A blob's stored record: its value in full, or a delta against a base the receiver usually holds already. Opaque to the transport.
|
||||
/// The stored record of a blob. It holds the value in full or as a delta against a base. The transport does not read it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct BlobRecord {
|
||||
pub hash: BlobHash,
|
||||
|
||||
@@ -124,6 +124,10 @@ impl Replica {
|
||||
Some(Role::Host)
|
||||
}
|
||||
|
||||
pub fn has_host(&self) -> bool {
|
||||
self.current_host().is_some()
|
||||
}
|
||||
|
||||
/// The link and id of the peer greeting as host. While two coexist this is the one with the lower id, which keeps
|
||||
/// the role once they meet.
|
||||
fn current_host(&self) -> Option<(TransportPeerId, PeerId)> {
|
||||
@@ -322,7 +326,7 @@ impl Replica {
|
||||
self.requested_resources.iter().copied()
|
||||
}
|
||||
|
||||
/// Broadcast staged `ops`, with the records of the new blobs they name.
|
||||
/// Broadcast staged `ops` together with the records of their new blobs.
|
||||
pub fn broadcast_hot_ops(&mut self, ops: &[HotOp], blobs: Vec<BlobRecord>) -> Result<(), PacketError> {
|
||||
if ops.is_empty() {
|
||||
return Ok(());
|
||||
@@ -402,6 +406,12 @@ impl Replica {
|
||||
}
|
||||
|
||||
pub fn send_resource(&mut self, to: TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), PacketError> {
|
||||
if let Some(recipients) = self.owed_resources.get_mut(&hash) {
|
||||
recipients.remove(&to);
|
||||
if recipients.is_empty() {
|
||||
self.owed_resources.remove(&hash);
|
||||
}
|
||||
}
|
||||
self.transport.send(to, &SyncPacket::Resource { hash, bytes })
|
||||
}
|
||||
|
||||
@@ -870,7 +880,7 @@ impl Replica {
|
||||
// A failure is logged rather than abandoning the bookkeeping and the rest of the queue.
|
||||
let applied = match broadcast.body {
|
||||
BroadcastBody::HotOps { ops, blobs } => {
|
||||
// A blob whose base isn't held here is asked for like a missing resource
|
||||
// A blob with a missing base is fetched like a missing resource
|
||||
self.resources_stale = true;
|
||||
target
|
||||
.absorb_blob_records(blobs)
|
||||
@@ -1132,4 +1142,18 @@ mod tests {
|
||||
host.poll(&mut session);
|
||||
assert!(host.owed_resources.is_empty(), "nothing is owed to a link that closed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answered_request_is_owed_no_more() {
|
||||
let (mut network, mut host, host_link, mut session) = hosted_room();
|
||||
let mut bare = connect_bare_peer(&mut network, &mut host, &mut session);
|
||||
let hash = ResourceHash::from(b"bytes".as_slice());
|
||||
|
||||
bare.send(host_link, &hello(0)).unwrap();
|
||||
bare.send(host_link, &SyncPacket::ResourceRequest(vec![hash])).unwrap();
|
||||
network.deliver_all();
|
||||
host.poll(&mut session);
|
||||
host.send_resource(bare.id(), hash, b"bytes".to_vec()).unwrap();
|
||||
assert!(host.owed_resources.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ const FRAME_FINAL: u8 = 1;
|
||||
const FRAME_MORE: u8 = 0;
|
||||
|
||||
/// Split a packet into `[flag][bytes]` chunks, the last carrying [`FRAME_FINAL`] so no length prefix is needed.
|
||||
fn frames(bytes: &[u8]) -> Vec<Box<[u8]>> {
|
||||
fn frames(bytes: &[u8]) -> Vec<Packet> {
|
||||
// Chunking an empty packet would yield no frame at all.
|
||||
let chunks: Vec<&[u8]> = if bytes.is_empty() { vec![&[]] } else { bytes.chunks(CHUNK_BYTES).collect() };
|
||||
|
||||
@@ -200,7 +200,8 @@ impl Transport for Room {
|
||||
fn poll(&mut self) -> Vec<TransportEvent> {
|
||||
let mut events = Vec::new();
|
||||
|
||||
for (peer, state) in self.socket.update_peers() {
|
||||
// Errs only once the socket loop ended, which its future reports, after handing over the changes before that.
|
||||
for (peer, state) in self.socket.try_update_peers().unwrap_or_default() {
|
||||
match state {
|
||||
PeerState::Connected => events.push(TransportEvent::PeerConnected(peer)),
|
||||
PeerState::Disconnected => {
|
||||
@@ -258,7 +259,7 @@ mod tests {
|
||||
|
||||
assert_eq!(incoming.wait().now_or_never(), None, "nothing arrived yet");
|
||||
|
||||
lock(&inbox).packets.push_back((peer(1), Box::new([FRAME_FINAL, 7])));
|
||||
lock(&inbox).packets.push_back((peer(1), Packet::from_static(&[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");
|
||||
|
||||
|
||||
@@ -69,11 +69,11 @@ pub trait SyncTarget {
|
||||
fn store_resource(&mut self, _hash: ResourceHash, _bytes: &[u8]) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
/// The record of every blob held here, each after its base, for a peer syncing from this one.
|
||||
/// The record of every held blob, for a peer that syncs from this one. A base comes before the blobs that use it.
|
||||
fn blob_records(&self) -> Vec<BlobRecord> {
|
||||
Vec::new()
|
||||
}
|
||||
/// Hold the blobs of records from a peer. One whose base isn't held here is dropped, and asked for as a missing resource.
|
||||
/// Hold the blobs of records from a peer. A record with a missing base is dropped and later fetched as a missing resource.
|
||||
fn absorb_blob_records(&mut self, _records: Vec<BlobRecord>) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -10,25 +10,33 @@ use document_graph_storage::{
|
||||
};
|
||||
use peer_transport::mock::{MockEndpoint, MockNetwork};
|
||||
use peer_transport::{BlobRecord, Event, Replica, Role, SyncTarget, TargetError, TransportPeerId};
|
||||
use std::cell::Cell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::thread::LocalKey;
|
||||
|
||||
static TOTAL_NODES: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_WIRED: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_EXPORTS: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_INPUT_ATTRIBUTES: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_SOURCES: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_COLLECTED: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_REDONE_RETRACTIONS: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_BLOBS: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_BLOB_DELTAS: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_BLOB_FETCHES: AtomicUsize = AtomicUsize::new(0);
|
||||
// Per thread, since each test runs its corpus on its own thread
|
||||
thread_local! {
|
||||
static TOTAL_NODES: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_WIRED: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_EXPORTS: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_INPUT_ATTRIBUTES: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_SOURCES: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_COLLECTED: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_REDONE_RETRACTIONS: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_BLOBS: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_BLOB_DELTAS: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_BLOB_FETCHES: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
fn count(counter: &'static LocalKey<Cell<usize>>, amount: usize) {
|
||||
counter.set(counter.get() + amount);
|
||||
}
|
||||
|
||||
/// A peer's document plus a byte store, since bare `Session` has no-op resource defaults.
|
||||
struct SimTarget {
|
||||
session: Session,
|
||||
resources: HashMap<ResourceHash, Vec<u8>>,
|
||||
/// Blob bytes, and the record each arrived or was staged as. See [`SimTarget::blob_record`].
|
||||
/// Blob bytes and the record of each blob. See [`SimTarget::blob_record`].
|
||||
blobs: BlobBytes,
|
||||
blob_records: HashMap<BlobHash, Vec<u8>>,
|
||||
/// History as of the last `flush`.
|
||||
@@ -61,8 +69,8 @@ impl SimTarget {
|
||||
self.session.history().map(|delta| delta.id).collect()
|
||||
}
|
||||
|
||||
/// A stand-in for a stored blob record: the bytes, after the base they need when it is held. A receiver must hold the base
|
||||
/// to take a record naming one, as with a real delta, which `document-format` tests on its own.
|
||||
/// A stand-in for a blob record. It holds the base hash if the base is held, then the bytes. Like a real delta,
|
||||
/// a receiver can only take it when it holds the base. `document-format` tests real deltas.
|
||||
fn blob_record(&self, bytes: &[u8], base: Option<BlobHash>) -> Vec<u8> {
|
||||
let mut record = Vec::new();
|
||||
match base.filter(|base| self.blobs.contains_key(base)) {
|
||||
@@ -76,7 +84,7 @@ impl SimTarget {
|
||||
record
|
||||
}
|
||||
|
||||
/// Hold staged blobs, returning the records peers receive with the ops.
|
||||
/// Hold staged blobs and return the records that peers receive with the ops.
|
||||
fn hold_blobs(&mut self, blobs: BlobBytes, bases: &HashMap<BlobHash, BlobHash>) -> Vec<BlobRecord> {
|
||||
let mut blobs: Vec<_> = blobs.into_iter().filter(|(hash, _)| !self.blobs.contains_key(hash)).collect();
|
||||
blobs.sort_unstable_by_key(|(hash, _)| *hash);
|
||||
@@ -88,7 +96,7 @@ impl SimTarget {
|
||||
self.blob_records.insert(hash, record.clone());
|
||||
records.push(BlobRecord { hash, record });
|
||||
}
|
||||
TOTAL_BLOBS.fetch_add(records.len(), Ordering::Relaxed);
|
||||
count(&TOTAL_BLOBS, records.len());
|
||||
records
|
||||
}
|
||||
}
|
||||
@@ -219,8 +227,8 @@ impl SyncTarget for SimTarget {
|
||||
|
||||
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
|
||||
let blob = BlobHash(hash);
|
||||
if self.session.all_blob_hashes().contains(&blob) {
|
||||
TOTAL_BLOB_FETCHES.fetch_add(1, Ordering::Relaxed);
|
||||
if self.session.names_blob(blob) {
|
||||
count(&TOTAL_BLOB_FETCHES, 1);
|
||||
let record = self.blob_record(bytes, None);
|
||||
self.blobs.insert(blob, bytes.to_vec());
|
||||
self.blob_records.insert(blob, record);
|
||||
@@ -252,7 +260,7 @@ impl SyncTarget for SimTarget {
|
||||
if !self.blobs.contains_key(&base) {
|
||||
return true;
|
||||
}
|
||||
TOTAL_BLOB_DELTAS.fetch_add(1, Ordering::Relaxed);
|
||||
count(&TOTAL_BLOB_DELTAS, 1);
|
||||
&rest[32..]
|
||||
}
|
||||
Some((_, rest)) => rest,
|
||||
@@ -263,7 +271,7 @@ impl SyncTarget for SimTarget {
|
||||
self.blob_records.insert(*hash, record.clone());
|
||||
false
|
||||
});
|
||||
// What stays waits on a base this peer lacks, and is asked for in full as a missing resource
|
||||
// The remaining records need a base this peer lacks. They are fetched in full as missing resources
|
||||
if pending.is_empty() || pending.len() == waiting {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -334,7 +342,7 @@ impl Peer {
|
||||
self.stage_ops(vec![op]).expect("stage");
|
||||
}
|
||||
|
||||
/// Stage `ops` with their large values moved into blobs, broadcasting the blobs' records with them.
|
||||
/// Stage `ops`, move their large values into blobs and broadcast the blob records with them.
|
||||
fn stage_ops(&mut self, mut ops: Vec<RegistryDelta>) -> Result<(), document_graph_storage::CrdtError> {
|
||||
let mut blobs = BlobBytes::new();
|
||||
ops.iter_mut().for_each(|op| op.move_values_into_blobs(&mut blobs));
|
||||
@@ -379,7 +387,7 @@ impl Peer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Edit one input of a live node a few times in a row, as drawing does, so its blobs chain on each other.
|
||||
/// Edit one input of a live node a few times in a row, like drawing does. Each new blob is based on the one before.
|
||||
fn stroke(&mut self, network: &mut MockNetwork) {
|
||||
let live_nodes: Vec<NodeId> = sorted(self.session().registry().node_instances.keys().copied());
|
||||
let Some(&id) = pick(network, &live_nodes) else { return };
|
||||
@@ -413,7 +421,7 @@ impl Peer {
|
||||
return;
|
||||
}
|
||||
self.end_interaction();
|
||||
TOTAL_REDONE_RETRACTIONS.fetch_add(1, Ordering::Relaxed);
|
||||
count(&TOTAL_REDONE_RETRACTIONS, 1);
|
||||
}
|
||||
|
||||
/// Drop every held byte outside the GC root set. `needed` is what present peers name and lack.
|
||||
@@ -424,7 +432,7 @@ impl Peer {
|
||||
self.target.collected_while_needed.extend(dropped);
|
||||
let before = self.target.resources.len();
|
||||
self.target.resources.retain(|hash, _| roots.contains(hash));
|
||||
TOTAL_COLLECTED.fetch_add(before - self.target.resources.len(), Ordering::Relaxed);
|
||||
count(&TOTAL_COLLECTED, before - self.target.resources.len());
|
||||
}
|
||||
|
||||
/// Every hash this peer's registry, history, hot log or retracted steps name, gathered independently of the GC
|
||||
@@ -511,12 +519,12 @@ fn random_value(network: &mut MockNetwork) -> Value {
|
||||
Value::from(serde_json::json!(network.random_below(100)))
|
||||
}
|
||||
|
||||
/// A value large enough to become a blob, from a pool small enough that peers sometimes stage the same one concurrently.
|
||||
/// A value large enough to become a blob. The pool is small, so peers sometimes stage the same value at once.
|
||||
fn large_value(network: &mut MockNetwork) -> Value {
|
||||
Value::Str(format!("{}{}", "x".repeat(BLOB_THRESHOLD), network.random_below(64)))
|
||||
}
|
||||
|
||||
/// A literal input value, a third of the time a [`large_value`].
|
||||
/// A literal input value. One in three is a [`large_value`].
|
||||
fn random_input_value(network: &mut MockNetwork) -> Value {
|
||||
match network.random_below(3) {
|
||||
0 => large_value(network),
|
||||
@@ -561,7 +569,7 @@ fn random_node_op(network: &mut MockNetwork, session: &Session) -> Option<Regist
|
||||
})
|
||||
}
|
||||
2 => registry.node_instances.get(&node_id).map(|node| RegistryDelta::RemoveNode { id: node_id, snapshot: node.clone() }),
|
||||
// Repeated edits to one slot chain its blobs, so most arrive as deltas against the one before
|
||||
// Repeated edits to one slot chain its blobs, so most of them arrive as deltas
|
||||
5 => {
|
||||
let id = *pick(network, &live_nodes)?;
|
||||
let index = network.random_below(2) as u32;
|
||||
@@ -754,11 +762,11 @@ fn quiesce(network: &mut MockNetwork, peers: &mut [Peer]) -> usize {
|
||||
panic!("the room never went idle");
|
||||
}
|
||||
|
||||
/// What a run mostly does.
|
||||
/// The main kind of step in a run.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Workload {
|
||||
Mixed,
|
||||
/// Half the steps are strokes, as live drawing makes.
|
||||
/// Half the steps are strokes, like live drawing.
|
||||
Strokes,
|
||||
}
|
||||
|
||||
@@ -1048,26 +1056,26 @@ fn assert_converged(seed: u64, peers: &[Peer]) {
|
||||
fn peers_converge_under_random_interleavings() {
|
||||
run_corpus(Workload::Mixed, 5000);
|
||||
// The generator's ops are guarded on registry state, so a change can quietly stop producing them.
|
||||
assert!(TOTAL_NODES.load(Ordering::Relaxed) > 0, "the corpus produced no nodes");
|
||||
assert!(TOTAL_WIRED.load(Ordering::Relaxed) > 0, "the corpus produced no node-to-node inputs");
|
||||
assert!(TOTAL_EXPORTS.load(Ordering::Relaxed) > 0, "the corpus set no network exports");
|
||||
assert!(TOTAL_INPUT_ATTRIBUTES.load(Ordering::Relaxed) > 0, "the corpus wrote no input-slot attributes");
|
||||
assert!(TOTAL_SOURCES.load(Ordering::Relaxed) > 0, "the corpus never stacked a second source on a resource");
|
||||
assert!(TOTAL_COLLECTED.load(Ordering::Relaxed) > 0, "garbage collection never dropped a resource");
|
||||
assert!(TOTAL_REDONE_RETRACTIONS.load(Ordering::Relaxed) > 0, "the corpus never redid a step taken back");
|
||||
assert!(TOTAL_BLOBS.load(Ordering::Relaxed) > 0, "the corpus staged no blobs");
|
||||
assert!(TOTAL_NODES.get() > 0, "the corpus produced no nodes");
|
||||
assert!(TOTAL_WIRED.get() > 0, "the corpus produced no node-to-node inputs");
|
||||
assert!(TOTAL_EXPORTS.get() > 0, "the corpus set no network exports");
|
||||
assert!(TOTAL_INPUT_ATTRIBUTES.get() > 0, "the corpus wrote no input-slot attributes");
|
||||
assert!(TOTAL_SOURCES.get() > 0, "the corpus never stacked a second source on a resource");
|
||||
assert!(TOTAL_COLLECTED.get() > 0, "garbage collection never dropped a resource");
|
||||
assert!(TOTAL_REDONE_RETRACTIONS.get() > 0, "the corpus never redid a step taken back");
|
||||
assert!(TOTAL_BLOBS.get() > 0, "the corpus staged no blobs");
|
||||
}
|
||||
|
||||
/// Mostly strokes, so blobs chain on each other, reach peers as deltas, and are fetched in full by a peer lacking a base.
|
||||
/// Mostly strokes. Blobs chain, reach peers as deltas and are fetched in full by peers that lack a base.
|
||||
#[test]
|
||||
fn blobs_reach_every_peer_under_strokes() {
|
||||
run_corpus(Workload::Strokes, 2000);
|
||||
assert!(TOTAL_BLOB_DELTAS.load(Ordering::Relaxed) > 0, "no blob arrived as a delta against one already held");
|
||||
assert!(TOTAL_BLOB_FETCHES.load(Ordering::Relaxed) > 0, "no blob was fetched in full for a missing base");
|
||||
run_corpus(Workload::Strokes, 10_000);
|
||||
assert!(TOTAL_BLOB_DELTAS.get() > 0, "no blob arrived as a delta against one already held");
|
||||
assert!(TOTAL_BLOB_FETCHES.get() > 0, "no blob was fetched in full for a missing base");
|
||||
}
|
||||
|
||||
/// Run `SIM_SEEDS` seeds, or `default_seeds`, checking each converges. `SIM_KEEP_GOING` runs every seed and lists the failures,
|
||||
/// to tell one bug from several.
|
||||
/// Run `SIM_SEEDS` seeds (or `default_seeds`) and check that each one converges.
|
||||
/// `SIM_KEEP_GOING` runs every seed and lists all failures. This tells one bug from several.
|
||||
fn run_corpus(workload: Workload, default_seeds: u64) {
|
||||
let seeds = std::env::var("SIM_SEEDS").ok().and_then(|value| value.parse::<u64>().ok()).unwrap_or(default_seeds);
|
||||
let keep_going = std::env::var_os("SIM_KEEP_GOING").is_some();
|
||||
@@ -1090,13 +1098,13 @@ fn run_corpus(workload: Workload, default_seeds: u64) {
|
||||
|
||||
fn count_coverage(registry: &Registry) {
|
||||
let inputs = || registry.node_instances.values().flat_map(|node| node.inputs());
|
||||
TOTAL_NODES.fetch_add(registry.node_instances.len(), Ordering::Relaxed);
|
||||
TOTAL_WIRED.fetch_add(inputs().filter(|slot| matches!(slot.input, NodeInput::Node { .. })).count(), Ordering::Relaxed);
|
||||
TOTAL_INPUT_ATTRIBUTES.fetch_add(inputs().filter(|slot| !slot.attributes.is_empty()).count(), Ordering::Relaxed);
|
||||
count(&TOTAL_NODES, registry.node_instances.len());
|
||||
count(&TOTAL_WIRED, inputs().filter(|slot| matches!(slot.input, NodeInput::Node { .. })).count());
|
||||
count(&TOTAL_INPUT_ATTRIBUTES, inputs().filter(|slot| !slot.attributes.is_empty()).count());
|
||||
let exports = registry.networks.values().flat_map(|network| &network.exports).filter(|slot| slot.target.is_some()).count();
|
||||
TOTAL_EXPORTS.fetch_add(exports, Ordering::Relaxed);
|
||||
count(&TOTAL_EXPORTS, exports);
|
||||
// A second source can only come from `AddSource`.
|
||||
TOTAL_SOURCES.fetch_add(registry.resources.values().filter(|entry| entry.sources.len() > 1).count(), Ordering::Relaxed);
|
||||
count(&TOTAL_SOURCES, registry.resources.values().filter(|entry| entry.sources.len() > 1).count());
|
||||
}
|
||||
|
||||
/// A rejoining guest keeps its `PeerId` but restarts its broadcast sequence, which the room must follow
|
||||
|
||||
+2
-1
@@ -22,12 +22,13 @@ gpu = ["interpreted-executor/gpu", "dep:wgpu-executor"]
|
||||
# Local dependencies
|
||||
graphite-proc-macros = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
document-format = { workspace = true, features = ["migrations"] }
|
||||
document-format = { workspace = true, features = ["migrations", "network"] }
|
||||
migration-formats = { workspace = true }
|
||||
migration-compiled = { workspace = true }
|
||||
migration-nodes = { workspace = true }
|
||||
document-graph-storage = { workspace = true, features = ["conversion"] }
|
||||
document-container = { workspace = true }
|
||||
peer-transport = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
blake3 = { workspace = true }
|
||||
interpreted-executor = { workspace = true }
|
||||
|
||||
@@ -208,8 +208,7 @@ pub const COLOR_OVERLAY_BLACK_75: &str = "#000000bf";
|
||||
|
||||
// DOCUMENT
|
||||
pub const FILE_EXTENSION: &str = "graphite";
|
||||
/// New document container format. Save writes a `.gdd` with the legacy `.graphite` embedded as a fallback
|
||||
/// during the dual-write soak; `.graphite` stays a supported open/import input.
|
||||
/// Extension of documents saved before the `.gdd` container took the `.graphite` extension. Still opened and imported.
|
||||
pub const GDD_FILE_EXTENSION: &str = "gdd";
|
||||
pub const DEFAULT_DOCUMENT_NAME: &str = "Untitled Document";
|
||||
pub const MAX_UNDO_HISTORY_LEN: usize = 100; // TODO: Add this to user preferences
|
||||
|
||||
@@ -291,6 +291,7 @@ impl Dispatcher {
|
||||
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,
|
||||
tools: &self.message_handlers.tool_message_handler,
|
||||
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,
|
||||
@@ -305,11 +306,12 @@ 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.collaboration_panel_open = layout.is_panel_present(PanelType::Collaboration);
|
||||
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.inspector_open = layout.is_panel_present(PanelType::Inspector);
|
||||
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
|
||||
menu_bar_message_handler.reset_node_definitions_on_open = self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open;
|
||||
menu_bar_message_handler.show_storage_preferences = self.message_handlers.preferences_message_handler.show_storage_preferences;
|
||||
|
||||
if let Some(document) = self
|
||||
.message_handlers
|
||||
|
||||
+15
-39
@@ -303,57 +303,33 @@ impl PreferencesDialogMessageHandler {
|
||||
// =========
|
||||
// DOCUMENTS
|
||||
// =========
|
||||
// Soak-only `.gdd` storage options, hidden unless enabled from the developer debug menu.
|
||||
if preferences.show_storage_preferences {
|
||||
{
|
||||
let header = vec![TextLabel::new("Documents").italic(true).widget_instance()];
|
||||
|
||||
let save_as_gdd_description = "
|
||||
Save documents in the new .gdd container format (with the legacy .graphite file embedded as a recovery fallback) instead of a plain .graphite file. The .gdd format is still being validated, so this is opt-in for now.\n\
|
||||
let save_with_history_description = "
|
||||
Include the document's edit history in saved files.\n\
|
||||
\n\
|
||||
*Default: Off.*
|
||||
"
|
||||
.trim();
|
||||
let save_as_gdd_checkbox_id = CheckboxId::new();
|
||||
let save_as_gdd = vec![
|
||||
let save_with_history_checkbox_id = CheckboxId::new();
|
||||
let save_with_history = vec![
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
CheckboxInput::new(preferences.save_as_gdd)
|
||||
.tooltip_label("Save as .gdd")
|
||||
.tooltip_description(save_as_gdd_description)
|
||||
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::SaveAsGdd { enabled: checkbox_input.checked }.into())
|
||||
.for_label(save_as_gdd_checkbox_id)
|
||||
CheckboxInput::new(preferences.save_with_history)
|
||||
.tooltip_label("Save with History")
|
||||
.tooltip_description(save_with_history_description)
|
||||
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::SaveWithHistory { enabled: checkbox_input.checked }.into())
|
||||
.for_label(save_with_history_checkbox_id)
|
||||
.widget_instance(),
|
||||
TextLabel::new("Save as .gdd")
|
||||
.tooltip_label("Save as .gdd")
|
||||
.tooltip_description(save_as_gdd_description)
|
||||
.for_checkbox(save_as_gdd_checkbox_id)
|
||||
TextLabel::new("Save with History")
|
||||
.tooltip_label("Save with History")
|
||||
.tooltip_description(save_with_history_description)
|
||||
.for_checkbox(save_with_history_checkbox_id)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let validate_description = "
|
||||
Validate every document save, open, and undo by round-tripping it through the .gdd storage format and comparing against the legacy path, logging any mismatch. Useful for debugging the .gdd format during its soak, but the per-edit round-trip has a performance cost.\n\
|
||||
\n\
|
||||
*Default: Off.*
|
||||
"
|
||||
.trim();
|
||||
let validate_checkbox_id = CheckboxId::new();
|
||||
let validate_storage_round_trip = vec![
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
CheckboxInput::new(preferences.validate_storage_round_trip)
|
||||
.tooltip_label("Validate Storage Round-Trip")
|
||||
.tooltip_description(validate_description)
|
||||
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::ValidateStorageRoundTrip { enabled: checkbox_input.checked }.into())
|
||||
.for_label(validate_checkbox_id)
|
||||
.widget_instance(),
|
||||
TextLabel::new("Validate Storage Round-Trip")
|
||||
.tooltip_label("Validate Storage Round-Trip")
|
||||
.tooltip_description(validate_description)
|
||||
.for_checkbox(validate_checkbox_id)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
rows.extend_from_slice(&[header, save_as_gdd, validate_storage_round_trip]);
|
||||
rows.extend_from_slice(&[header, save_with_history]);
|
||||
}
|
||||
|
||||
// =============
|
||||
|
||||
@@ -3,7 +3,8 @@ use crate::messages::prelude::*;
|
||||
|
||||
/// Lists the stored documents that stayed closed because another tab has them open.
|
||||
pub struct DocumentsOpenElsewhereDialog {
|
||||
pub documents: Vec<(DocumentId, String)>,
|
||||
/// Id, name and whether it is in a live session.
|
||||
pub documents: Vec<(DocumentId, String, bool)>,
|
||||
}
|
||||
|
||||
impl DialogLayoutHolder for DocumentsOpenElsewhereDialog {
|
||||
@@ -24,22 +25,26 @@ impl LayoutHolder for DocumentsOpenElsewhereDialog {
|
||||
let mut rows = vec![
|
||||
LayoutGroup::row(vec![TextLabel::new(format!("{count} {documents} open in another tab.")).bold(true).multiline(true).widget_instance()]),
|
||||
LayoutGroup::row(vec![
|
||||
TextLabel::new(format!("{are} closed here so the two tabs don't overwrite each other.\nA copy opens here as a separate document."))
|
||||
.multiline(true)
|
||||
.widget_instance(),
|
||||
TextLabel::new(format!(
|
||||
"{are} closed here so the two tabs don't overwrite each other.\nA copy is a separate document, while joining a session edits it live."
|
||||
))
|
||||
.multiline(true)
|
||||
.widget_instance(),
|
||||
]),
|
||||
];
|
||||
rows.extend(self.documents.iter().cloned().map(|(source, name)| {
|
||||
let label = TextLabel::new(name.clone()).widget_instance();
|
||||
let button = TextButton::new("Open a Copy")
|
||||
.on_update(move |_| {
|
||||
DialogMessage::CloseAndThen {
|
||||
followups: vec![PortfolioMessage::OpenDocumentCopy { source, document_name: name.clone() }.into()],
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance();
|
||||
LayoutGroup::row(vec![label, Separator::new(SeparatorStyle::Unrelated).widget_instance(), button])
|
||||
rows.extend(self.documents.iter().cloned().map(|(source, name, shared)| {
|
||||
let button = |label: &str, followup: Box<dyn Fn() -> PortfolioMessage + Send + Sync>| {
|
||||
TextButton::new(label)
|
||||
.on_update(move |_| DialogMessage::CloseAndThen { followups: vec![followup().into()] }.into())
|
||||
.widget_instance()
|
||||
};
|
||||
let mut widgets = vec![TextLabel::new(name.clone()).widget_instance(), Separator::new(SeparatorStyle::Unrelated).widget_instance()];
|
||||
// A copy stays possible, since joining needs the other tab to be connected
|
||||
if shared {
|
||||
widgets.push(button("Join in This Tab", Box::new(move || PortfolioMessage::JoinStoredSession { source })));
|
||||
}
|
||||
widgets.push(button("Open a Copy", Box::new(move || PortfolioMessage::OpenDocumentCopy { source, document_name: name.clone() })));
|
||||
LayoutGroup::row(widgets)
|
||||
}));
|
||||
|
||||
Layout(rows)
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, NodeGraphErrorDiagnostic,
|
||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
||||
@@ -140,6 +140,9 @@ pub enum FrontendMessage {
|
||||
url: String,
|
||||
},
|
||||
TriggerClipboardRead,
|
||||
TriggerSessionLinkCopy {
|
||||
token: String,
|
||||
},
|
||||
TriggerClipboardWrite {
|
||||
content: String,
|
||||
},
|
||||
@@ -190,6 +193,15 @@ pub enum FrontendMessage {
|
||||
#[serde(rename = "box")]
|
||||
box_selection: Option<BoxSelection>,
|
||||
},
|
||||
UpdateDocumentCursors {
|
||||
cursors: Vec<FrontendRemoteCursor>,
|
||||
},
|
||||
UpdateHistoryPanel {
|
||||
state: crate::messages::portfolio::history::utility_types::HistoryPanelState,
|
||||
},
|
||||
UpdateNodeGraphCursors {
|
||||
cursors: Vec<FrontendRemoteCursor>,
|
||||
},
|
||||
UpdateContextMenuInformation {
|
||||
#[serde(rename = "contextMenuInformation")]
|
||||
context_menu_information: Option<ContextMenuInformation>,
|
||||
|
||||
@@ -12,9 +12,20 @@ pub struct DocumentInfo {
|
||||
#[serde(default)]
|
||||
pub path: Option<PathBuf>,
|
||||
pub is_saved: bool,
|
||||
/// `None` when not shared.
|
||||
#[serde(default)]
|
||||
pub session: Option<SessionStatus>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints, from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum SessionStatus {
|
||||
Connected,
|
||||
/// The transport is down or the document isn't mounted. It reconnects on mount.
|
||||
Disconnected,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PersistedState {
|
||||
pub documents: Vec<DocumentInfo>,
|
||||
@@ -51,7 +62,7 @@ pub enum RenderStatus {
|
||||
Panic,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum FileType {
|
||||
#[default]
|
||||
|
||||
@@ -99,7 +99,7 @@ impl MessageHandler<FutureMessage, ()> for FutureMessageHandler {
|
||||
}));
|
||||
}
|
||||
FutureMessage::Drain => {
|
||||
while let Ok(Some(message)) = self.results_receiver.try_next() {
|
||||
while let Ok(message) = self.results_receiver.try_recv() {
|
||||
responses.push_back(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
|
||||
};
|
||||
|
||||
// The reply carries the source it read, so the frontend can drop one that a later keystroke has outdated
|
||||
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(&source, input.accepts_reducers);
|
||||
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(&source, input.operator_only);
|
||||
let completions = caret.map(|caret| math_expression_completions(&source, caret, asked));
|
||||
responses.add(FrontendMessage::UpdateMathExpressionAnalysis {
|
||||
widget_id,
|
||||
@@ -371,9 +371,9 @@ impl LayoutMessageHandler {
|
||||
};
|
||||
|
||||
// The widget is resent as stored, so its tokens and errors must be for its new value rather than its old one
|
||||
let accepts_reducers = math_expression_input.accepts_reducers;
|
||||
let error = math_expression_error(update_value, accepts_reducers);
|
||||
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(update_value, accepts_reducers);
|
||||
let operator_only = math_expression_input.operator_only;
|
||||
let error = math_expression_error(update_value, operator_only);
|
||||
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(update_value, operator_only);
|
||||
math_expression_input.tokens = tokens;
|
||||
math_expression_input.tooltips = tooltips;
|
||||
math_expression_input.errors = math_expression_error_ranges(update_value, error.as_ref());
|
||||
|
||||
@@ -24,7 +24,7 @@ impl core::fmt::Display for WidgetId {
|
||||
|
||||
macro_rules! define_layout_target {
|
||||
($($(#[$attr:meta])* $variant:ident),* $(,)?) => {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Clone, Debug, Hash, Eq, Copy, serde::Serialize, serde::Deserialize)]
|
||||
#[repr(u8)]
|
||||
pub enum LayoutTarget {
|
||||
@@ -76,6 +76,7 @@ define_layout_target!(
|
||||
NodeGraphControlBar,
|
||||
/// The body of the Inspector containing many collapsable sections.
|
||||
Inspector,
|
||||
CollaborationPanel,
|
||||
/// The contextual input key/mouse combination shortcuts shown in the status bar at the bottom of the window.
|
||||
StatusBarHints,
|
||||
/// The version information shown in the status bar at the bottom right of the window.
|
||||
|
||||
@@ -16,13 +16,16 @@ fn utf16_offsets(source: &str) -> Vec<u32> {
|
||||
units
|
||||
}
|
||||
|
||||
/// Why a math expression fails to parse, or `None` when it parses. Where the node applies a lone operator or function name like
|
||||
/// `+` or `min` across its items, that counts as valid too.
|
||||
pub fn math_expression_error(expression: &str, accepts_reducers: bool) -> Option<ParseError> {
|
||||
/// Why a math expression fails to parse, or `None` when it parses. Where the node takes only a lone operator or function name like
|
||||
/// `+` or `min` to apply across its items, anything else is the error instead.
|
||||
pub fn math_expression_error(expression: &str, operator_only: bool) -> Option<ParseError> {
|
||||
// A blank expression is unfinished rather than wrong, so it goes unflagged like any empty field
|
||||
if expression.trim().is_empty() || (accepts_reducers && math_parser::reducer::classify_reducer(expression, math_parser::context::NothingMap).is_some()) {
|
||||
if expression.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
if operator_only {
|
||||
return math_parser::reducer::reducer_error(expression);
|
||||
}
|
||||
math_parser::ast::Node::try_parse_from_str(expression).err()
|
||||
}
|
||||
|
||||
@@ -143,11 +146,11 @@ pub struct MathExpressionTokens {
|
||||
}
|
||||
|
||||
/// The tokens of a math expression for the frontend to color and typeset, with the parser's byte offsets converted to code units.
|
||||
pub fn math_expression_tokens(source: &str, accepts_reducers: bool) -> MathExpressionTokens {
|
||||
pub fn math_expression_tokens(source: &str, operator_only: bool) -> MathExpressionTokens {
|
||||
let units = utf16_offsets(source);
|
||||
let mut tooltips: Vec<MathExpressionTooltip> = Vec::new();
|
||||
|
||||
let tokens = math_parser::highlight::highlight(source, accepts_reducers).into_iter().map(|token| {
|
||||
let tokens = math_parser::highlight::highlight(source, operator_only).into_iter().map(|token| {
|
||||
let tooltip = token.tooltip.map(|tooltip| MathExpressionTooltip {
|
||||
label: tooltip.label,
|
||||
form: tooltip.form,
|
||||
|
||||
@@ -502,9 +502,9 @@ pub struct MathExpressionInput {
|
||||
pub tooltips: Vec<MathExpressionTooltip>,
|
||||
/// The stretches of the value its parse errors point at, which the frontend underlines.
|
||||
pub errors: Vec<MathExpressionRange>,
|
||||
/// Whether a lone operator or function name like `+` or `max` is an expression, applied across a list as by the Math node.
|
||||
/// Whether the value is a lone operator or function name like `+` or `max`, applied across a list, rather than an expression.
|
||||
#[serde(skip)]
|
||||
pub accepts_reducers: bool,
|
||||
pub operator_only: bool,
|
||||
pub disabled: bool,
|
||||
|
||||
// Tooltips
|
||||
|
||||
@@ -21,9 +21,10 @@ pub struct MenuBarMessageHandler {
|
||||
pub has_selection_history: (bool, bool),
|
||||
pub message_logging_verbosity: MessageLoggingVerbosity,
|
||||
pub reset_node_definitions_on_open: bool,
|
||||
pub show_storage_preferences: bool,
|
||||
pub make_path_editable_is_allowed: bool,
|
||||
pub data_panel_open: bool,
|
||||
pub collaboration_panel_open: bool,
|
||||
pub history_panel_open: bool,
|
||||
pub layers_panel_open: bool,
|
||||
pub inspector_open: bool,
|
||||
pub focus_document: bool,
|
||||
@@ -59,7 +60,6 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
let message_logging_verbosity_names = self.message_logging_verbosity == MessageLoggingVerbosity::Names;
|
||||
let message_logging_verbosity_contents = self.message_logging_verbosity == MessageLoggingVerbosity::Contents;
|
||||
let reset_node_definitions_on_open = self.reset_node_definitions_on_open;
|
||||
let show_storage_preferences = self.show_storage_preferences;
|
||||
let make_path_editable_is_allowed = self.make_path_editable_is_allowed;
|
||||
|
||||
let about = MenuListEntry::new("About Graphite…")
|
||||
@@ -687,6 +687,16 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleDataPanelOpen))
|
||||
.on_commit(|_| WorkspaceMessage::ToggleDataPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
MenuListEntry::new("Collaboration")
|
||||
.label("Collaboration")
|
||||
.icon(if self.collaboration_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.on_commit(|_| WorkspaceMessage::ToggleCollaborationPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
MenuListEntry::new("History")
|
||||
.label("History")
|
||||
.icon(if self.history_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.on_commit(|_| WorkspaceMessage::ToggleHistoryPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
],
|
||||
])
|
||||
.widget_instance(),
|
||||
@@ -728,10 +738,6 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.label("Reset Nodes to Definitions on Open")
|
||||
.icon(if reset_node_definitions_on_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.on_commit(|_| PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen.into()),
|
||||
MenuListEntry::new("Show Storage Preferences")
|
||||
.label("Show Storage Preferences")
|
||||
.icon(if show_storage_preferences { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.on_commit(|_| PreferencesMessage::ToggleShowStoragePreferences.into()),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Print Trace Logs")
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! Human-readable pretty-printers for the dual-write soak's validation checks: registry-vs-registry and
|
||||
//! runtime-network-vs-runtime-network diffs. The callers are gated behind the `validate_storage_round_trip`
|
||||
//! preference, so these ship in release but only run when the soak is turned on.
|
||||
//! Human-readable pretty-printers for storage test failures: registry-vs-registry and
|
||||
//! runtime-network-vs-runtime-network diffs.
|
||||
|
||||
use std::fmt::Write;
|
||||
|
||||
|
||||
@@ -1,26 +1,20 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
use document_graph_storage::{Declarations, Registry, Value};
|
||||
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
|
||||
use document_graph_storage::{Declarations, Value};
|
||||
use graph_craft::application_io::resource::{ResourceHash, ResourceId, ResourceRegistry, ResourceStorage};
|
||||
|
||||
use super::utility_types::network_interface::NodeNetworkInterface;
|
||||
use super::utility_types::network_interface::editor_delta::{EditorDelta, StagingError, construct_batch};
|
||||
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, build_interface_from_storage, collect_network_view_settings};
|
||||
use crate::messages::portfolio::history::utility_types::LineChange;
|
||||
|
||||
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
|
||||
/// becoming the authoritative history. Owns the dual-stack bookkeeping push/pop/clear and the cursor's stage/retire/move/verify
|
||||
/// lifecycle, so the handler drives history through one surface rather than three loose fields.
|
||||
/// Per-document undo/redo state, kept in the `Gdd` working copy.
|
||||
///
|
||||
/// Not serialized: the legacy stacks are runtime-only, and a clone shares the working-copy container by
|
||||
/// `Arc`, so it keeps reading the live working copy.
|
||||
/// Not serialized: a clone shares the working-copy container by `Arc`, so it keeps reading the live working copy.
|
||||
#[derive(derivative::Derivative)]
|
||||
#[derivative(Clone, Debug, Default)]
|
||||
pub struct DocumentHistory {
|
||||
/// Stack of document network snapshots for previous history states.
|
||||
legacy_undo_stack: VecDeque<NodeNetworkInterface>,
|
||||
/// Stack of document network snapshots for future history states.
|
||||
legacy_redo_stack: VecDeque<NodeNetworkInterface>,
|
||||
/// The `Gdd` working copy: owns the CRDT `Session` and mirrors edits to disk. `None` until the mount
|
||||
/// future built by `load_document` resolves.
|
||||
#[derivative(Debug = "ignore")]
|
||||
@@ -35,56 +29,24 @@ pub struct DocumentHistory {
|
||||
/// moved without recording it (an upgrade on open), since the recorded batch would then describe only
|
||||
/// part of the distance between the two.
|
||||
needs_whole_document_stage: bool,
|
||||
/// How storage undid each step that redo can bring back, latest last.
|
||||
undo_notes: VecDeque<UndoNote>,
|
||||
}
|
||||
|
||||
/// Why [`DocumentHistory::move_cursor`] produced no interface.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CursorMoveError {
|
||||
/// Nothing to move to, unmounted, or the move itself failed. The cursor did not move.
|
||||
NotMoved,
|
||||
/// The cursor moved but the rebuild from it failed. It stays moved unless the caller reverts it.
|
||||
RebuildFailed,
|
||||
#[derive(Clone, Debug)]
|
||||
enum UndoNote {
|
||||
/// The step was hot and got taken back.
|
||||
Retracted(Vec<document_graph_storage::RegistryDelta>),
|
||||
/// The step had retired and was dropped from the shared line.
|
||||
Dropped(document_graph_storage::Rev),
|
||||
/// The storage cursor moved back over the step.
|
||||
Cursor,
|
||||
}
|
||||
|
||||
impl DocumentHistory {
|
||||
// ===== Legacy snapshot stacks =====
|
||||
|
||||
/// Push a snapshot onto the undo stack, evicting the oldest entry past the history cap.
|
||||
pub fn push_undo(&mut self, snapshot: NodeNetworkInterface) {
|
||||
Self::push_capped(&mut self.legacy_undo_stack, snapshot);
|
||||
}
|
||||
|
||||
/// Push a snapshot onto the redo stack, evicting the oldest entry past the history cap.
|
||||
pub fn push_redo(&mut self, snapshot: NodeNetworkInterface) {
|
||||
Self::push_capped(&mut self.legacy_redo_stack, snapshot);
|
||||
}
|
||||
|
||||
/// Pop the most recent undo snapshot, or `None` when the stack is empty.
|
||||
pub fn pop_undo(&mut self) -> Option<NodeNetworkInterface> {
|
||||
self.legacy_undo_stack.pop_back()
|
||||
}
|
||||
|
||||
/// Pop the most recent redo snapshot, or `None` when the stack is empty.
|
||||
pub fn pop_redo(&mut self) -> Option<NodeNetworkInterface> {
|
||||
self.legacy_redo_stack.pop_back()
|
||||
}
|
||||
|
||||
/// Drop the most recently pushed undo snapshot (used to cancel a transaction that ended up unmodified).
|
||||
pub fn discard_last_undo(&mut self) {
|
||||
self.legacy_undo_stack.pop_back();
|
||||
}
|
||||
|
||||
/// Clear the redo stack, called when a fresh edit invalidates the redo future.
|
||||
/// Forget the steps redo could bring back.
|
||||
pub fn clear_redo(&mut self) {
|
||||
self.legacy_redo_stack.clear();
|
||||
}
|
||||
|
||||
/// Add the resources referenced by every snapshot in both history stacks into `resources`, so
|
||||
/// history-only resources stay alive for legacy undo/redo.
|
||||
pub fn collect_used_resources(&self, resources: &mut HashSet<ResourceId>) {
|
||||
for interface in self.legacy_undo_stack.iter().chain(&self.legacy_redo_stack) {
|
||||
interface.collect_used_resources(resources);
|
||||
}
|
||||
self.undo_notes.clear();
|
||||
}
|
||||
|
||||
// ===== Gdd working-copy cursor =====
|
||||
@@ -99,6 +61,10 @@ impl DocumentHistory {
|
||||
self.storage.as_mut()
|
||||
}
|
||||
|
||||
pub fn declarations(&self) -> &Declarations {
|
||||
&self.declarations
|
||||
}
|
||||
|
||||
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
|
||||
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
|
||||
self.needs_whole_document_stage |= storage.registry().node_instances.is_empty();
|
||||
@@ -112,9 +78,134 @@ impl DocumentHistory {
|
||||
self.needs_whole_document_stage = true;
|
||||
}
|
||||
|
||||
/// Retire the pending staged hot ops into durable Gdd history as one undo unit. Called at each undo-step
|
||||
/// boundary (a new `StartTransaction`) and before undo/redo, so the per-`CommitTransaction` staging
|
||||
/// coalesces into one interaction aligned with the legacy step. No-op while unmounted.
|
||||
pub fn end_storage_interaction(&mut self) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if let Err(error) = storage.end_interaction() {
|
||||
log::error!("Closing the storage interaction failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Undoes the latest step in storage, so it can be redone. Returns whether a step was undone.
|
||||
pub fn undo(&mut self, in_session: bool) -> bool {
|
||||
let Some(note) = self.undo_step(in_session) else { return false };
|
||||
|
||||
self.undo_notes.push_back(note);
|
||||
if self.undo_notes.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
|
||||
self.undo_notes.pop_front();
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Undoes the latest step in storage without a way to redo it. Returns whether a step was undone.
|
||||
pub fn discard_step(&mut self, in_session: bool) -> bool {
|
||||
let Some(note) = self.undo_step(in_session) else { return false };
|
||||
|
||||
if matches!(note, UndoNote::Cursor)
|
||||
&& let Some(storage) = self.storage.as_mut()
|
||||
&& let Err(error) = storage.forget_latest_undo()
|
||||
{
|
||||
log::error!("Forgetting the discarded step failed: {error}");
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Takes the latest step back. A hot step is retracted, a retired one is dropped from a session's shared line,
|
||||
/// and otherwise the cursor moves back over it.
|
||||
fn undo_step(&mut self, in_session: bool) -> Option<UndoNote> {
|
||||
// A failed retract may already have taken the step back, so no older step is undone after it
|
||||
let retracted = match self.retract_storage_interaction() {
|
||||
Ok(retracted) => retracted,
|
||||
Err(error) => {
|
||||
log::error!("Taking the storage interaction back failed: {error}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if let Some(ops) = retracted {
|
||||
return Some(UndoNote::Retracted(ops));
|
||||
}
|
||||
// A session's history is shared, so its cursor never moves
|
||||
if in_session {
|
||||
return self.undo_retired_step().map(UndoNote::Dropped);
|
||||
}
|
||||
self.move_cursor(true).then_some(UndoNote::Cursor)
|
||||
}
|
||||
|
||||
/// Brings back the latest undone step. Returns whether it was redone.
|
||||
pub fn redo(&mut self) -> bool {
|
||||
let Some(note) = self.undo_notes.pop_back() else { return false };
|
||||
|
||||
let line_reachable = self.storage.as_ref().is_some_and(|storage| storage.can_change_line());
|
||||
let redone = match ¬e {
|
||||
UndoNote::Retracted(ops) => self.restage_ops(ops.clone()),
|
||||
UndoNote::Dropped(rev) => line_reachable && self.redo_retired_step(*rev),
|
||||
UndoNote::Cursor => self.move_cursor(false),
|
||||
};
|
||||
if !redone {
|
||||
self.undo_notes.push_back(note);
|
||||
}
|
||||
redone
|
||||
}
|
||||
|
||||
/// Move the cursor along the retired interaction chain, flushing any open interaction first. Returns whether it moved.
|
||||
fn move_cursor(&mut self, undo: bool) -> bool {
|
||||
self.retire_storage_interaction();
|
||||
let Some(storage) = self.storage.as_mut() else { return false };
|
||||
|
||||
let moved = if undo {
|
||||
if !storage.can_undo() {
|
||||
return false;
|
||||
}
|
||||
storage.undo()
|
||||
} else {
|
||||
if !storage.can_redo() {
|
||||
return false;
|
||||
}
|
||||
storage.redo()
|
||||
};
|
||||
moved.inspect_err(|error| log::error!("Storage undo/redo cursor move failed: {error}")).is_ok()
|
||||
}
|
||||
|
||||
fn retract_storage_interaction(&mut self) -> Result<Option<Vec<document_graph_storage::RegistryDelta>>, document_format::Error> {
|
||||
match self.storage.as_mut() {
|
||||
Some(storage) => storage.retract_interaction(),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn restage_ops(&mut self, ops: Vec<document_graph_storage::RegistryDelta>) -> bool {
|
||||
let Some(storage) = self.storage.as_mut() else { return false };
|
||||
storage.restage_ops(ops).inspect_err(|error| log::error!("Staging the redone step failed: {error}")).is_ok()
|
||||
}
|
||||
|
||||
fn undo_retired_step(&mut self) -> Option<document_graph_storage::Rev> {
|
||||
self.storage.as_mut()?.undo_retired_step().unwrap_or_else(|error| {
|
||||
log::error!("Undoing the retired step failed: {error}");
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
pub fn resource_gc_roots(&self) -> HashSet<ResourceHash> {
|
||||
self.storage.as_ref().map(|storage| storage.resource_gc_roots()).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn redo_retired_step(&mut self, rev: document_graph_storage::Rev) -> bool {
|
||||
let Some(storage) = self.storage.as_mut() else { return false };
|
||||
storage.redo_retired_step(rev).inspect_err(|error| log::error!("Redoing the dropped step failed: {error}")).is_ok()
|
||||
}
|
||||
|
||||
/// Returns whether storage made the change.
|
||||
pub fn change_line(&mut self, rev: document_graph_storage::Rev, change: LineChange) -> bool {
|
||||
let Some(storage) = self.storage.as_mut().filter(|storage| storage.can_change_line()) else {
|
||||
return false;
|
||||
};
|
||||
let result = match change {
|
||||
LineChange::MoveHead => storage.move_head(rev),
|
||||
LineChange::Remove => storage.drop_step(rev),
|
||||
LineChange::Restore => storage.redo_retired_step(rev),
|
||||
};
|
||||
result.inspect_err(|error| log::error!("Changing the history line with {change:?} failed: {error}")).is_ok()
|
||||
}
|
||||
|
||||
pub fn retire_storage_interaction(&mut self) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if let Err(error) = storage.retire_pending_interaction() {
|
||||
@@ -124,10 +215,19 @@ impl DocumentHistory {
|
||||
|
||||
/// Stage a `CommitTransaction` into the `Gdd` working copy: the first commit writes the whole document,
|
||||
/// every later one stages the `deltas` the store recorded. No-op while unmounted. Proto-node declaration
|
||||
/// bytes go into `byte_store` (the app-global resource cache). The staged hot ops are retired by
|
||||
/// [`retire_storage_interaction`](Self::retire_storage_interaction) at undo-step boundaries.
|
||||
/// bytes go into `byte_store` (the app-global resource cache). The staged hot ops are closed into one
|
||||
/// interaction by [`end_storage_interaction`](Self::end_storage_interaction) at undo-step boundaries.
|
||||
pub fn stage_snapshot(&mut self, deltas: &[EditorDelta], interface: &NodeNetworkInterface, registry: &ResourceRegistry, view_settings: BTreeMap<String, Value>, byte_store: &dyn ResourceStorage) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if !self.stage_graph(deltas, interface, registry, byte_store) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.persist_view_state(interface, view_settings);
|
||||
}
|
||||
|
||||
/// [`stage_snapshot`](Self::stage_snapshot) without the view state. Returns whether the working copy took the batch.
|
||||
pub fn stage_graph(&mut self, deltas: &[EditorDelta], interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> bool {
|
||||
let Some(storage) = self.storage.as_mut() else { return false };
|
||||
|
||||
let staged = match self.needs_whole_document_stage {
|
||||
true => Self::stage_whole_document(storage, interface, registry, byte_store),
|
||||
@@ -148,14 +248,13 @@ impl DocumentHistory {
|
||||
Ok(declarations) => {
|
||||
self.declarations.extend(declarations);
|
||||
self.needs_whole_document_stage = false;
|
||||
true
|
||||
}
|
||||
Err(error) => {
|
||||
log::error!("Storage snapshot staging failed: {error}");
|
||||
return;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
self.persist_view_state(interface, view_settings);
|
||||
}
|
||||
|
||||
/// Converts the whole document and stages the difference from what the working copy holds.
|
||||
@@ -171,8 +270,7 @@ impl DocumentHistory {
|
||||
|
||||
/// Stages what the store recorded since the last drain.
|
||||
///
|
||||
/// This and the whole-document conversion produce the same registry for the same edit, which
|
||||
/// `verify_round_trip` checks when the `validate_storage_round_trip` preference is on. They differ in
|
||||
/// This and the whole-document conversion produce the same registry for the same edit. They differ in
|
||||
/// what they cost and in what they can miss: a conversion sees every change however it was made,
|
||||
/// while this sees only what went through the store, so a write that bypasses it is not persisted.
|
||||
fn stage_recorded(
|
||||
@@ -212,138 +310,56 @@ impl DocumentHistory {
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the `Gdd` undo/redo cursor along the retired interaction chain, flushing any open interaction
|
||||
/// first, and rebuild the interface from the rewound registry using the declaration cache.
|
||||
pub fn move_cursor(&mut self, undo: bool) -> Result<NodeNetworkInterface, CursorMoveError> {
|
||||
self.retire_storage_interaction();
|
||||
|
||||
let storage = self.storage.as_mut().ok_or(CursorMoveError::NotMoved)?;
|
||||
|
||||
let moved = if undo {
|
||||
if !storage.can_undo() {
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
}
|
||||
storage.undo().map(|_| ())
|
||||
} else {
|
||||
if !storage.can_redo() {
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
}
|
||||
storage.redo().map(|_| ())
|
||||
};
|
||||
if let Err(error) = moved {
|
||||
log::error!("Storage undo/redo cursor move failed: {error}");
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
}
|
||||
/// Build a new interface from the working registry and cached declarations. `None` when it doesn't convert.
|
||||
pub fn rebuild_interface(&self) -> Option<NodeNetworkInterface> {
|
||||
let storage = self.storage.as_ref()?;
|
||||
|
||||
storage
|
||||
.registry()
|
||||
.to_runtime_with_full_metadata(&self.declarations, storage.blobs())
|
||||
.map_err(|error| error.to_string())
|
||||
.and_then(|(network, node_entries, network_entries)| build_interface_from_storage(network, node_entries, network_entries).map_err(|error| error.to_string()))
|
||||
.map_err(|error| {
|
||||
log::error!("Storage undo/redo rebuild failed: {error}");
|
||||
CursorMoveError::RebuildFailed
|
||||
})
|
||||
.inspect_err(|error| log::error!("Storage interface rebuild failed: {error}"))
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Step the cursor back the other way, undoing a [`move_cursor`](Self::move_cursor) in the `undo`
|
||||
/// direction whose rebuild failed.
|
||||
pub fn revert_cursor(&mut self, undo: bool) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
pub fn undecoded_declaration_hashes(&self) -> Vec<ResourceHash> {
|
||||
let Some(storage) = self.storage.as_ref() else { return Vec::new() };
|
||||
|
||||
let reverted = if undo { storage.redo() } else { storage.undo() };
|
||||
if let Err(error) = reverted {
|
||||
log::error!("Storage undo/redo cursor revert failed: {error}");
|
||||
let mut hashes: Vec<ResourceHash> = storage
|
||||
.session()
|
||||
.all_declaration_resources()
|
||||
.into_iter()
|
||||
.filter_map(|(id, hash)| hash.filter(|_| !self.declarations.contains_key(&id)))
|
||||
.collect();
|
||||
hashes.sort_unstable();
|
||||
hashes.dedup();
|
||||
hashes
|
||||
}
|
||||
|
||||
/// Cache a peer's resource as a declaration if one names its hash. Returns false when the bytes don't decode.
|
||||
pub fn cache_declaration_bytes(&mut self, hash: ResourceHash, bytes: &[u8]) -> bool {
|
||||
let Some(storage) = self.storage.as_ref() else { return true };
|
||||
|
||||
let referencing: Vec<ResourceId> = storage
|
||||
.session()
|
||||
.all_declaration_resources()
|
||||
.into_iter()
|
||||
.filter_map(|(id, declaration_hash)| (declaration_hash == Some(hash)).then_some(id))
|
||||
.collect();
|
||||
if referencing.is_empty() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Soak round-trip verification (runtime-gated by `validate_storage_round_trip`)
|
||||
// These log drift rather than panicking, since the soak can run in release where a crash is
|
||||
// unacceptable; tests still fail loud via the `#[cfg(test)]` panics.
|
||||
|
||||
/// Soak check: the stored registry should equal a fresh `from_runtime`, and a `to_runtime` of it should
|
||||
/// equal the original network.
|
||||
pub fn verify_round_trip(&self, interface: &NodeNetworkInterface, registry: &ResourceRegistry) {
|
||||
use super::diff_networks;
|
||||
use super::document_diff::diff_registries;
|
||||
|
||||
let Some(storage) = &self.storage else { return };
|
||||
let peer = storage.session().peer();
|
||||
|
||||
let network = interface.document_network();
|
||||
let metadata_view = StorageMetadataView::new(interface);
|
||||
|
||||
let conversion = match Registry::convert_from_runtime(network, &metadata_view, registry, peer) {
|
||||
Ok(conversion) => conversion,
|
||||
Err(error) => {
|
||||
log::error!("storage round-trip: from_runtime failed: {error}");
|
||||
return;
|
||||
match document_graph_storage::decode_declaration(bytes) {
|
||||
Ok(declaration) => {
|
||||
self.declarations.extend(referencing.into_iter().map(|id| (id, declaration.clone())));
|
||||
true
|
||||
}
|
||||
};
|
||||
let target = &conversion.registry;
|
||||
let declarations = &conversion.declarations;
|
||||
|
||||
let stored = storage.registry();
|
||||
if !stored.value_equal(target) {
|
||||
log::error!("storage round-trip: registry value drift after commit\n{}", diff_registries(stored, target));
|
||||
#[cfg(test)]
|
||||
panic!("storage round-trip: registry value drift after commit");
|
||||
}
|
||||
if !stored.order_consistent(target) {
|
||||
log::error!("storage round-trip: timestamp order inconsistent between stored and target");
|
||||
#[cfg(test)]
|
||||
panic!("storage round-trip: timestamp order inconsistent between stored and target");
|
||||
}
|
||||
|
||||
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(declarations, storage.blobs()) {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
log::error!("storage round-trip: to_runtime failed: {error}");
|
||||
return;
|
||||
log::error!("Failed to deserialize a received ProtoNode declaration: {error}");
|
||||
false
|
||||
}
|
||||
};
|
||||
if &round_tripped != network {
|
||||
log::error!("storage round-trip: network drift after to_runtime\n{}", diff_networks(network, &round_tripped));
|
||||
#[cfg(test)]
|
||||
panic!("storage round-trip: network drift after to_runtime");
|
||||
}
|
||||
}
|
||||
|
||||
/// Soak check: after a cursor move, the cursor's registry should equal a fresh `from_runtime` of the
|
||||
/// current (legacy-restored) interface. `current_resources` are the resources the live network
|
||||
/// references; history-only resources the cursor dropped are expected, not drift.
|
||||
pub fn verify_cursor_matches_runtime(&self, interface: &NodeNetworkInterface, registry: &ResourceRegistry, current_resources: &HashSet<ResourceId>) {
|
||||
use super::document_diff::diff_registries;
|
||||
|
||||
let Some(storage) = &self.storage else { return };
|
||||
let peer = storage.session().peer();
|
||||
|
||||
let network = interface.document_network();
|
||||
let metadata_view = StorageMetadataView::new(interface);
|
||||
|
||||
let Ok(mut conversion) = Registry::convert_from_runtime(network, &metadata_view, registry, peer) else {
|
||||
log::error!("undo/redo shadow: from_runtime failed");
|
||||
return;
|
||||
};
|
||||
|
||||
let stored = storage.registry();
|
||||
|
||||
// The cursor reverts the interaction's `AddResource` while the runtime keeps the resource alive for
|
||||
// legacy redo, so a history-only resource the cursor dropped is expected. Drop those before comparing.
|
||||
conversion.registry.resources.retain(|id, _| stored.resources.contains_key(id) || current_resources.contains(id));
|
||||
|
||||
if !stored.value_equal(&conversion.registry) {
|
||||
log::error!(
|
||||
"undo/redo shadow: cursor registry diverged from the restored interface\n{}",
|
||||
diff_registries(stored, &conversion.registry)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_capped(stack: &mut VecDeque<NodeNetworkInterface>, snapshot: NodeNetworkInterface) {
|
||||
stack.push_back(snapshot);
|
||||
if stack.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
|
||||
stack.pop_front();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,10 @@ pub enum DocumentMessage {
|
||||
DeselectAllLayers,
|
||||
DocumentHistoryBackward,
|
||||
DocumentHistoryForward,
|
||||
ChangeHistoryLine {
|
||||
rev: document_graph_storage::Rev,
|
||||
change: crate::messages::portfolio::history::utility_types::LineChange,
|
||||
},
|
||||
DocumentStructureChanged,
|
||||
DrawArtboardOverlays {
|
||||
context: OverlayContext,
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
use super::document_diff::diff_networks;
|
||||
use super::DocumentHistory;
|
||||
use super::node_graph::{document_node_definitions, node_inspector};
|
||||
use super::utility_types::error::EditorError;
|
||||
use super::utility_types::layers_in_view::LayersInView;
|
||||
use super::utility_types::misc::{ANGLE_STEP_MAX, ANGLE_STEP_MIN, GroupFolderType, SNAPPING_OPTION_GROUPS, SnappingState};
|
||||
use super::utility_types::network_interface::{self, NodeNetworkInterface, TransactionStatus};
|
||||
use super::utility_types::nodes::{CollapsedLayers, LayerStructureEntry, SelectedNodes};
|
||||
use super::{CursorMoveError, DocumentHistory};
|
||||
use crate::application::{Environment, GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
|
||||
use crate::consts::{
|
||||
ASYMPTOTIC_EFFECT, BLEND_COUNT_PER_LAYER, COLOR_OVERLAY_GRAY, CURVATURE_COMB_DEFAULT_SCALE, CURVATURE_COMB_MAX_SCALE, CURVATURE_COMB_MIN_SCALE, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION,
|
||||
@@ -23,7 +22,8 @@ use crate::messages::portfolio::document::overlays::grid_overlays::{grid_overlay
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType, OverlaysVisibilitySettings, Pivot};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
|
||||
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, FlowType, InputConnector, NodeTemplate, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, FlowType, InputConnector, NodeTemplate, OutputConnector, ReconcileError, Reconciled};
|
||||
use crate::messages::portfolio::history::utility_types::LineChange;
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::edit_target::EditTarget;
|
||||
@@ -35,9 +35,9 @@ use crate::messages::tool::tool_messages::tool_prelude::Key;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use document_container::AnyContainer;
|
||||
use document_graph_storage::Declarations;
|
||||
use document_graph_storage::{Declarations, Rev};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::application_io::resource::{ResourceHash, ResourceId, ResourceStorage};
|
||||
use graph_craft::document::value::{TaggedValue, deserialize_replacing_null_floats_with_zero};
|
||||
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
|
||||
use graph_craft::list;
|
||||
@@ -53,8 +53,12 @@ use graphene_std::vector::style::{GradientStops, RenderMode};
|
||||
use kurbo::{Affine, BezPath, Line, PathSeg, Shape};
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
/// The document attribute holding its name, shared so renames reach peers.
|
||||
pub const DOCUMENT_NAME_ATTRIBUTE: &str = "name";
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct DocumentMessageContext<'a> {
|
||||
pub document_id: DocumentId,
|
||||
@@ -172,6 +176,9 @@ pub struct DocumentMessageHandler {
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore")]
|
||||
pub(crate) container: Option<AnyContainer>,
|
||||
/// Peer changes not yet applied, held until their declarations are cached.
|
||||
#[serde(skip)]
|
||||
pub(crate) pending_remote: document_format::RemoteChanges,
|
||||
/// Hash of the document snapshot that was most recently saved to disk by the user.
|
||||
#[serde(skip)]
|
||||
saved_hash: Option<u64>,
|
||||
@@ -235,6 +242,7 @@ impl Default for DocumentMessageHandler {
|
||||
selection_network_path: Vec::new(),
|
||||
history: DocumentHistory::default(),
|
||||
container: None,
|
||||
pending_remote: Default::default(),
|
||||
saved_hash: None,
|
||||
auto_saved_hash: None,
|
||||
layer_range_selection_reference: None,
|
||||
@@ -461,10 +469,18 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.chain_node_range_selection_reference = None;
|
||||
}
|
||||
DocumentMessage::DocumentHistoryBackward => {
|
||||
self.stage_edits_outside_transaction(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
|
||||
self.undo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses)
|
||||
self.stage_edits_outside_transaction(&resource_storage.resources_mut());
|
||||
self.undo_with_history(document_id, responses);
|
||||
self.resolve_unresolved_resources(document_id, responses);
|
||||
}
|
||||
DocumentMessage::DocumentHistoryForward => {
|
||||
self.redo_with_history(document_id, responses);
|
||||
self.resolve_unresolved_resources(document_id, responses);
|
||||
}
|
||||
DocumentMessage::ChangeHistoryLine { rev, change } => {
|
||||
self.change_history_line(document_id, rev, change, &resource_storage.resources_mut(), responses);
|
||||
self.resolve_unresolved_resources(document_id, responses);
|
||||
}
|
||||
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
|
||||
DocumentMessage::DocumentStructureChanged => {
|
||||
if layers_panel_open {
|
||||
self.network_interface.load_structure();
|
||||
@@ -1147,6 +1163,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.path = None;
|
||||
self.set_save_state(false);
|
||||
self.set_auto_save_state(false);
|
||||
self.stage_name_attribute();
|
||||
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(NodeGraphMessage::UpdateNewNodeGraph);
|
||||
@@ -1243,15 +1260,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::SaveDocument | DocumentMessage::SaveDocumentAs => {
|
||||
responses.add(PortfolioMessage::AutoSaveActiveDocument);
|
||||
|
||||
// Save as a `.gdd` container or a plain legacy `.graphite`, per the editor preference.
|
||||
let save_as_gdd = preferences.save_as_gdd;
|
||||
let extension = if save_as_gdd { GDD_FILE_EXTENSION } else { FILE_EXTENSION };
|
||||
let name = format!("{}.{}", self.name.clone(), extension);
|
||||
let include_history = preferences.save_with_history;
|
||||
|
||||
// Keep the path's extension in sync with the chosen format so bytes and filename agree.
|
||||
// Saved as a `.gdd` container under the `.graphite` extension
|
||||
let name = format!("{}.{FILE_EXTENSION}", self.name.clone());
|
||||
|
||||
// A document opened from a `.gdd` file is saved back under the `.graphite` extension
|
||||
let path = match message {
|
||||
DocumentMessage::SaveDocumentAs => None,
|
||||
_ => self.path.clone().map(|path| path.with_extension(extension)),
|
||||
_ => self.path.clone().map(|path| path.with_extension(FILE_EXTENSION)),
|
||||
};
|
||||
if path.is_some() || environment.is_web() {
|
||||
responses.add(DocumentMessage::MarkAsSaved);
|
||||
@@ -1265,22 +1282,21 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let export_load_handle = resource_storage.resources();
|
||||
|
||||
responses.add(async move {
|
||||
document.resources.collect_garbage(document.used_resources(false).as_ref());
|
||||
document.resources.collect_garbage(document.used_resources().as_ref());
|
||||
document.resources.embed_resources(resources_load_handle).await;
|
||||
|
||||
// Legacy .graphite blob with resources embedded inline, so it is self-contained and also
|
||||
// serves as the .gdd recovery fallback.
|
||||
let legacy_document = document.serialize_document().into_bytes();
|
||||
|
||||
// A .gdd exports the working copy with the legacy blob embedded, falling back to the bare
|
||||
// Export the working copy with the legacy blob embedded, falling back to the bare
|
||||
// blob when there is no working copy or the export fails.
|
||||
let content = match (save_as_gdd, document.history.storage()) {
|
||||
(false, _) => legacy_document,
|
||||
(true, Some(storage)) => storage
|
||||
let content = match document.history.storage() {
|
||||
Some(storage) => storage
|
||||
.export_to_bytes(
|
||||
document_format::ExportFormat::Xz,
|
||||
document_format::ExportFormat::Zip,
|
||||
document_format::ExportOptions {
|
||||
include_history: false,
|
||||
include_history,
|
||||
..Default::default()
|
||||
},
|
||||
export_load_handle.as_ref(),
|
||||
@@ -1291,7 +1307,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
log::error!("Save: building .gdd export failed, falling back to legacy .graphite: {error}");
|
||||
legacy_document
|
||||
}),
|
||||
(true, None) => {
|
||||
None => {
|
||||
log::warn!("Save: working copy not mounted yet, saving legacy .graphite only");
|
||||
legacy_document
|
||||
}
|
||||
@@ -1304,7 +1320,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
folder,
|
||||
filters: vec![FileFilter {
|
||||
name: "Graphite Document".into(),
|
||||
extensions: vec![extension.into()],
|
||||
extensions: vec![FILE_EXTENSION.into()],
|
||||
mime_types: Vec::new(),
|
||||
}],
|
||||
content: content.into(),
|
||||
@@ -1658,11 +1674,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
// Note: A transaction should never be started in a scope that mutates the network interface, since it will only be run after that scope ends.
|
||||
DocumentMessage::StartTransaction => {
|
||||
self.stage_edits_outside_transaction(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
|
||||
self.retire_storage_interaction();
|
||||
self.stage_edits_outside_transaction(&resource_storage.resources_mut());
|
||||
self.end_storage_interaction();
|
||||
|
||||
self.network_interface.start_transaction();
|
||||
self.history.push_undo(self.network_interface.clone());
|
||||
// Push the UpdateOpenDocumentsList message to the bus in order to update the save status of the open documents
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
@@ -1678,7 +1693,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
},
|
||||
DocumentMessage::CancelTransaction => {
|
||||
self.network_interface.finish_transaction();
|
||||
self.history.discard_last_undo();
|
||||
}
|
||||
DocumentMessage::CommitTransaction => {
|
||||
if self.network_interface.transaction_status() == TransactionStatus::Finished {
|
||||
@@ -1687,7 +1701,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.network_interface.finish_transaction();
|
||||
self.history.clear_redo();
|
||||
|
||||
self.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
|
||||
self.commit_storage_snapshot(&resource_storage.resources_mut());
|
||||
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
@@ -1705,9 +1719,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
return;
|
||||
}
|
||||
|
||||
for _ in 0..undo_count {
|
||||
self.undo(viewport, responses);
|
||||
}
|
||||
self.abort_steps(document_id, undo_count, &resource_storage.resources_mut(), responses);
|
||||
|
||||
self.network_interface.finish_transaction();
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
@@ -2177,7 +2189,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
impl DocumentMessageHandler {
|
||||
/// Build a document handler from a `.gdd` working copy.
|
||||
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, declarations: Declarations, name: String, path: Option<std::path::PathBuf>) -> Self {
|
||||
pub fn from_storage(
|
||||
interface: NodeNetworkInterface,
|
||||
storage: document_format::GddV1,
|
||||
declarations: Declarations,
|
||||
byte_store: Arc<dyn ResourceStorage>,
|
||||
name: String,
|
||||
path: Option<std::path::PathBuf>,
|
||||
) -> Self {
|
||||
let mut document = Self {
|
||||
network_interface: interface,
|
||||
name,
|
||||
@@ -2186,11 +2205,8 @@ impl DocumentMessageHandler {
|
||||
};
|
||||
|
||||
document.apply_stored_document_settings(storage.view_settings());
|
||||
match storage.registry().to_resource_registry() {
|
||||
Ok(resource_registry) => document.resources.registry = resource_registry,
|
||||
Err(error) => log::error!("Opening .gdd: failed to rebuild resource registry: {error}"),
|
||||
}
|
||||
document.history.set_storage(storage, declarations);
|
||||
document.set_storage(storage, declarations, byte_store);
|
||||
document.refresh_resource_registry();
|
||||
|
||||
document
|
||||
}
|
||||
@@ -2373,6 +2389,40 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.document_metadata()
|
||||
}
|
||||
|
||||
pub fn breadcrumb_network_path(&self) -> &[NodeId] {
|
||||
&self.breadcrumb_network_path
|
||||
}
|
||||
|
||||
fn stored_name(&self) -> Option<&str> {
|
||||
let attribute = self.storage()?.registry().attributes.get(DOCUMENT_NAME_ATTRIBUTE).filter(|attribute| !attribute.deleted)?;
|
||||
match &attribute.value {
|
||||
document_graph_storage::Value::Str(name) => Some(name),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stage_name_attribute(&mut self) {
|
||||
if self.stored_name() == Some(self.name.as_str()) {
|
||||
return;
|
||||
}
|
||||
let delta = document_graph_storage::AttributeDelta {
|
||||
key: DOCUMENT_NAME_ATTRIBUTE.to_string(),
|
||||
value: Some(document_graph_storage::Value::Str(self.name.clone())),
|
||||
};
|
||||
let Some(gdd) = self.storage_mut() else { return };
|
||||
if let Err(error) = gdd.stage_ops([document_graph_storage::RegistryDelta::ChangeDocumentAttribute { delta }]) {
|
||||
log::error!("Staging the document name failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn adopt_name_from_storage(&mut self) -> bool {
|
||||
let Some(name) = self.stored_name().filter(|name| *name != self.name).map(str::to_string) else {
|
||||
return false;
|
||||
};
|
||||
self.name = name;
|
||||
true
|
||||
}
|
||||
|
||||
/// Path to the subnetwork that the user's selection is currently scoped to.
|
||||
/// Empty when the selection lives in the root document network.
|
||||
pub fn selection_network_path(&self) -> &[NodeId] {
|
||||
@@ -2390,10 +2440,15 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
|
||||
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
|
||||
pub fn set_storage(&mut self, mut storage: document_format::GddV1, declarations: Declarations, byte_store: Arc<dyn ResourceStorage>) {
|
||||
storage.set_byte_store(byte_store);
|
||||
self.history.set_storage(storage, declarations);
|
||||
}
|
||||
|
||||
pub(crate) fn end_storage_interaction(&mut self) {
|
||||
self.history.end_storage_interaction();
|
||||
}
|
||||
|
||||
/// Retire the pending staged hot ops into durable Gdd history as one undo unit.
|
||||
pub(crate) fn retire_storage_interaction(&mut self) {
|
||||
self.history.retire_storage_interaction();
|
||||
@@ -2410,7 +2465,7 @@ impl DocumentMessageHandler {
|
||||
/// The batch boundary: everything the interface recorded since the last one is this commit's batch.
|
||||
/// Draining happens whether or not a working copy is mounted, so the buffer cannot grow across a
|
||||
/// session that never mounts one.
|
||||
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
|
||||
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage) {
|
||||
self.network_interface.settle_definitions();
|
||||
let deltas = self.network_interface.take_deltas();
|
||||
if self.history.storage().is_none() {
|
||||
@@ -2419,17 +2474,13 @@ impl DocumentMessageHandler {
|
||||
|
||||
let view_settings = self.storage_view_settings();
|
||||
self.history.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, byte_store);
|
||||
|
||||
if validate {
|
||||
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
|
||||
}
|
||||
}
|
||||
|
||||
/// Stages edits made after a transaction finished, such as those queued behind an `AddTransaction`, whose commit runs
|
||||
/// first. They belong to the undo step that just ended, so they must reach storage before it closes.
|
||||
fn stage_edits_outside_transaction(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
|
||||
fn stage_edits_outside_transaction(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage) {
|
||||
if self.network_interface.transaction_status() == TransactionStatus::Finished && self.network_interface.has_deltas() {
|
||||
self.commit_storage_snapshot(byte_store, validate);
|
||||
self.commit_storage_snapshot(byte_store);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2476,40 +2527,108 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the `Gdd` undo/redo cursor, swap in the interface rebuilt from it, and autosave so the legacy
|
||||
/// document matches the cursor. `had_oracle` records whether the legacy snapshot already applied, so the
|
||||
/// rebuild can be compared against it.
|
||||
fn drive_storage_undo_redo(&mut self, document_id: DocumentId, had_oracle: bool, undo: bool, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
match self.history.move_cursor(undo) {
|
||||
Ok(rebuilt) => {
|
||||
self.apply_gdd_cursor_rebuild(rebuilt, had_oracle, validate, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
|
||||
/// Rebuild the resource registry from storage, or keep it on failure. `Resource` inputs resolve through it.
|
||||
fn refresh_resource_registry(&mut self) {
|
||||
let Some(storage) = self.history.storage() else { return };
|
||||
|
||||
let mut resource_registry = match storage.registry().to_resource_registry() {
|
||||
Ok(resource_registry) => resource_registry,
|
||||
Err(error) => {
|
||||
log::error!("Failed to rebuild the resource registry from storage: {error}");
|
||||
return;
|
||||
}
|
||||
Err(CursorMoveError::NotMoved) => {}
|
||||
// Without the legacy snapshot the interface stayed put, so the cursor has to follow it back.
|
||||
Err(CursorMoveError::RebuildFailed) => {
|
||||
if !had_oracle {
|
||||
self.history.revert_cursor(undo);
|
||||
};
|
||||
|
||||
// Preserve completed resolutions across undo and redo
|
||||
let stored_resources = &storage.registry().resources;
|
||||
for resolved in self.resources.registry.resolved() {
|
||||
let Some(&hash) = resolved.hash else { continue };
|
||||
|
||||
match resource_registry.info(&resolved.id) {
|
||||
// Storage has its own hash, or a peer changed where the resource comes from
|
||||
Some(stored) if stored.hash.is_some() || stored.sources != resolved.sources => continue,
|
||||
Some(_) => {}
|
||||
// Kept for a redo of the undone step that added it
|
||||
None if !stored_resources.contains_key(&resolved.id) => resolved.sources.iter().for_each(|source| resource_registry.push_source_back(&resolved.id, source.clone())),
|
||||
// Storage holds it with neither a hash nor sources
|
||||
None => continue,
|
||||
}
|
||||
resource_registry.resolve(&resolved.id, hash);
|
||||
}
|
||||
|
||||
self.resources.registry = resource_registry;
|
||||
}
|
||||
|
||||
/// Queues resolving the resources that history left without a hash, as applying a peer's changes does.
|
||||
fn resolve_unresolved_resources(&self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
|
||||
if self.resources.registry.unresolved().next().is_some() {
|
||||
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn stage_pending_edits(&mut self, byte_store: &dyn ResourceStorage) {
|
||||
let deltas = self.network_interface.take_deltas();
|
||||
if deltas.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.history.stage_graph(&deltas, &self.network_interface, &self.resources.registry, byte_store);
|
||||
}
|
||||
|
||||
/// Updates the interface with peer changes, in place unless a rebuild is needed. Returns false and keeps what it can't apply.
|
||||
pub(crate) fn apply_remote_changes(&mut self, responses: &mut VecDeque<Message>) -> bool {
|
||||
let changes = std::mem::take(&mut self.pending_remote);
|
||||
if changes.is_empty() {
|
||||
return true;
|
||||
}
|
||||
|
||||
if !changes.rebuilt
|
||||
&& let Some(gdd) = self.history.storage()
|
||||
{
|
||||
let peer = gdd.session().peer();
|
||||
match self
|
||||
.network_interface
|
||||
.reconcile_remote(gdd.registry(), self.history.declarations(), gdd.blobs(), &changes.touched, peer)
|
||||
{
|
||||
Ok(reconciled) => {
|
||||
self.finish_remote_reconcile(reconciled, changes.touched.resources, responses);
|
||||
return true;
|
||||
}
|
||||
Err(ReconcileError::DeclarationMissing(id)) => {
|
||||
log::debug!("Remote changes wait for declaration {id}");
|
||||
self.pending_remote = changes;
|
||||
return false;
|
||||
}
|
||||
Err(error) => log::warn!("Reconciling remote changes failed, rebuilding the interface instead: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
match self.history.rebuild_interface() {
|
||||
Some(rebuilt) => {
|
||||
self.apply_gdd_cursor_rebuild(rebuilt, responses);
|
||||
true
|
||||
}
|
||||
None => {
|
||||
self.pending_remote = changes;
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Swap in the interface rebuilt from the `Gdd` cursor. Always overwrites the interface.
|
||||
fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
rebuilt.copy_all_transient_view_state(&self.network_interface);
|
||||
std::mem::swap(&mut rebuilt.resolved_types, &mut self.network_interface.resolved_types);
|
||||
rebuilt.load_structure();
|
||||
|
||||
if validate && had_oracle {
|
||||
self.compare_rebuild_against_legacy(&rebuilt);
|
||||
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, responses: &mut VecDeque<Message>) {
|
||||
for path in self.network_interface.paths_reaching(&reconciled.networks) {
|
||||
self.network_interface.unload_stack_dependents(&path);
|
||||
self.network_interface.unload_import_export_ports(&path);
|
||||
self.network_interface.unload_all_nodes_bounding_box(&path);
|
||||
self.network_interface.unload_outward_wires(&path);
|
||||
self.network_interface.unload_all_nodes_click_targets(&path);
|
||||
}
|
||||
self.network_interface.load_structure();
|
||||
|
||||
self.network_interface = rebuilt;
|
||||
|
||||
if validate {
|
||||
let current_resources: std::collections::HashSet<_> = self.used_resources(false).iter().copied().collect();
|
||||
self.history.verify_cursor_matches_runtime(&self.network_interface, &self.resources.registry, ¤t_resources);
|
||||
if let Some(gdd) = self.history.storage_mut() {
|
||||
gdd.mark_runtime_current();
|
||||
}
|
||||
if resources_changed {
|
||||
self.refresh_resource_registry();
|
||||
}
|
||||
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
@@ -2519,15 +2638,32 @@ impl DocumentMessageHandler {
|
||||
responses.add(NodeGraphMessage::SendWires);
|
||||
}
|
||||
|
||||
/// Check if the rebuilt network equals the legacy-restored one. Logs drift (panics in tests).
|
||||
fn compare_rebuild_against_legacy(&self, rebuilt: &NodeNetworkInterface) {
|
||||
let legacy = self.network_interface.document_network();
|
||||
let candidate = rebuilt.document_network();
|
||||
if candidate != legacy {
|
||||
log::error!("undo/redo rebuild diverged from the legacy snapshot\n{}", diff_networks(legacy, candidate));
|
||||
#[cfg(test)]
|
||||
panic!("undo/redo rebuild diverged from the legacy snapshot")
|
||||
pub(crate) fn cache_declaration_bytes(&mut self, hash: ResourceHash, bytes: &[u8]) -> bool {
|
||||
self.history.cache_declaration_bytes(hash, bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn undecoded_declaration_hashes(&self) -> Vec<ResourceHash> {
|
||||
self.history.undecoded_declaration_hashes()
|
||||
}
|
||||
|
||||
/// Swap in the interface rebuilt from the `Gdd` cursor. Always overwrites the interface.
|
||||
fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, responses: &mut VecDeque<Message>) {
|
||||
rebuilt.copy_all_transient_view_state(&self.network_interface);
|
||||
std::mem::swap(&mut rebuilt.resolved_types, &mut self.network_interface.resolved_types);
|
||||
rebuilt.load_structure();
|
||||
|
||||
self.network_interface = rebuilt;
|
||||
self.pending_remote = Default::default();
|
||||
if let Some(gdd) = self.history.storage_mut() {
|
||||
gdd.mark_runtime_current();
|
||||
}
|
||||
self.refresh_resource_registry();
|
||||
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
responses.add(NodeGraphMessage::SendWires);
|
||||
}
|
||||
|
||||
pub fn serialize_document(&self) -> String {
|
||||
@@ -2826,75 +2962,87 @@ impl DocumentMessageHandler {
|
||||
paths
|
||||
}
|
||||
|
||||
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
|
||||
self.history.push_redo(previous_network);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
self.drive_storage_undo_redo(document_id, legacy_applied, true, validate, responses);
|
||||
}
|
||||
|
||||
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
|
||||
fn install_history_snapshot(&mut self, mut network_interface: NodeNetworkInterface, viewport: &ViewportMessageHandler) -> NodeNetworkInterface {
|
||||
// Set the previous network navigation metadata to the current navigation metadata
|
||||
network_interface.copy_all_navigation_metadata(&self.network_interface);
|
||||
std::mem::swap(&mut network_interface.resolved_types, &mut self.network_interface.resolved_types);
|
||||
|
||||
// Update the metadata transform based on document PTZ
|
||||
let transform = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
network_interface.set_document_to_viewport_transform(transform);
|
||||
|
||||
// Ensure document structure is loaded so that updating the selected nodes has the correct metadata
|
||||
network_interface.load_structure();
|
||||
|
||||
std::mem::replace(&mut self.network_interface, network_interface)
|
||||
}
|
||||
|
||||
pub fn undo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
|
||||
// If there is no history return and don't broadcast SelectionChanged
|
||||
let network_interface = self.history.pop_undo()?;
|
||||
// Settled first, so the interface stored for redo keeps none of the offsets of a glide underway
|
||||
pub fn undo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
|
||||
// Settled before storage moves, so the glide's offsets don't outlive the step
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
let previous_network = self.install_history_snapshot(network_interface, viewport);
|
||||
|
||||
// Push the UpdateOpenDocumentsList message to the bus in order to update the save status of the open documents
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
|
||||
|
||||
// TODO: Remove once the footprint is used to load the imports/export distances from the edge
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
|
||||
Some(previous_network)
|
||||
}
|
||||
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
|
||||
self.history.push_undo(previous_network);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
self.drive_storage_undo_redo(document_id, legacy_applied, false, validate, responses);
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
if self.history.undo(self.is_in_session()) {
|
||||
self.follow_storage_changes(stored_name, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
|
||||
// If there is no history return and don't broadcast SelectionChanged
|
||||
let network_interface = self.history.pop_redo()?;
|
||||
// Settled first, as when undoing
|
||||
pub fn redo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
let previous_network = self.install_history_snapshot(network_interface, viewport);
|
||||
|
||||
// Push the UpdateOpenDocumentsList message to the bus in order to update the save status of the open documents
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
responses.add(NodeGraphMessage::SendWires);
|
||||
Some(previous_network)
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
if self.history.redo() {
|
||||
self.follow_storage_changes(stored_name, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes back the open transaction along with the `undo_count - 1` steps before it, leaving nothing to redo.
|
||||
fn abort_steps(&mut self, document_id: DocumentId, undo_count: usize, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) {
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
|
||||
let open_transaction_has_edits = self.network_interface.transaction_status() == TransactionStatus::Modified;
|
||||
if open_transaction_has_edits {
|
||||
// Staged so they are taken back with the steps before them
|
||||
self.commit_storage_snapshot(byte_store);
|
||||
}
|
||||
let steps = if open_transaction_has_edits { undo_count } else { undo_count.saturating_sub(1) };
|
||||
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
let in_session = self.is_in_session();
|
||||
let discarded = (0..steps).take_while(|_| self.history.discard_step(in_session)).count();
|
||||
if discarded == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
// Staging the open transaction's edits made storage's own redo unreachable
|
||||
if open_transaction_has_edits {
|
||||
self.history.clear_redo();
|
||||
}
|
||||
self.follow_storage_changes(stored_name, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
|
||||
}
|
||||
|
||||
/// Makes a History panel change in storage and drops the steps redo could bring back, which are off the head's line.
|
||||
fn change_history_line(&mut self, document_id: DocumentId, rev: Rev, change: LineChange, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
}
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
responses.add(EventMessage::ToolAbort);
|
||||
self.stage_edits_outside_transaction(byte_store);
|
||||
self.history.retire_storage_interaction();
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
if !self.history.change_line(rev, change) {
|
||||
return;
|
||||
}
|
||||
self.history.clear_redo();
|
||||
self.follow_storage_changes(stored_name, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
responses.add(EventMessage::SelectionChanged);
|
||||
}
|
||||
|
||||
/// Reconciles the interface with storage. The tab takes the stored name only if it changed from `name_before`.
|
||||
fn follow_storage_changes(&mut self, name_before: Option<String>, responses: &mut VecDeque<Message>) {
|
||||
if let Some(gdd) = self.history.storage_mut() {
|
||||
let changes = gdd.take_remote_changes();
|
||||
self.pending_remote.extend(changes);
|
||||
}
|
||||
self.apply_remote_changes(responses);
|
||||
if self.stored_name() != name_before.as_deref() && self.adopt_name_from_storage() {
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_in_session(&self) -> bool {
|
||||
self.storage().is_some_and(|gdd| gdd.role().is_some())
|
||||
}
|
||||
|
||||
pub fn current_hash(&self) -> u64 {
|
||||
@@ -4107,16 +4255,18 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
pub fn garbage_collect_resources(&mut self) {
|
||||
let used_resources = self.used_resources(true);
|
||||
let used_resources = self.used_resources();
|
||||
self.resources.collect_garbage(&used_resources);
|
||||
}
|
||||
|
||||
pub fn used_resources(&self, include_history: bool) -> Box<[ResourceId]> {
|
||||
pub fn resource_gc_roots(&self) -> HashSet<ResourceHash> {
|
||||
self.history.resource_gc_roots()
|
||||
}
|
||||
|
||||
/// The resources the current network references.
|
||||
pub fn used_resources(&self) -> Box<[ResourceId]> {
|
||||
let mut resources = HashSet::new();
|
||||
self.network_interface.collect_used_resources(&mut resources);
|
||||
if include_history {
|
||||
self.history.collect_used_resources(&mut resources);
|
||||
}
|
||||
resources.into_iter().collect::<Vec<_>>().into_boxed_slice()
|
||||
}
|
||||
}
|
||||
@@ -4460,6 +4610,31 @@ mod document_message_handler_tests {
|
||||
use crate::messages::portfolio::document::utility_types::misc::GridType;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn deleting_the_bottom_layer_leaves_the_layer_above_it_the_empty_stack_value() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.draw_rect(200., 0., 300., 100.).await;
|
||||
|
||||
let [top, bottom] = editor.active_document().metadata().all_layers().collect::<Vec<_>>()[..] else {
|
||||
panic!("there should be two layers")
|
||||
};
|
||||
let stack_bottom = |editor: &EditorTestUtils, layer: LayerNodeIdentifier| {
|
||||
editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.input_from_connector(&InputConnector::node_at_index(layer.to_node(), 0), &[])
|
||||
.cloned()
|
||||
};
|
||||
let empty_stack = stack_bottom(&editor, bottom);
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![bottom.to_node()] }).await;
|
||||
editor.handle_message(DocumentMessage::DeleteSelectedLayers).await;
|
||||
|
||||
assert_eq!(stack_bottom(&editor, top), empty_stack);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_gradient_bakes_round_trip_through_serialization() {
|
||||
let document = DocumentMessageHandler {
|
||||
@@ -5116,4 +5291,20 @@ mod document_message_handler_tests {
|
||||
nudge(&mut editor, DVec2::new(NUDGE_AMOUNT, 0.)).await;
|
||||
assert_bounds(&editor, rectangle, [DVec2::new(105., 32.), DVec2::new(165., 76.)]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_changes_that_neither_reconcile_nor_rebuild_are_kept_for_a_retry() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
let document = editor.active_document_mut();
|
||||
let storage = document.storage().expect("the document has a working copy").clone();
|
||||
document.history.set_storage(storage, Declarations::default());
|
||||
assert!(document.history.rebuild_interface().is_none(), "the registry should not convert without its declarations");
|
||||
|
||||
document.pending_remote.rebuilt = true;
|
||||
document.apply_remote_changes(&mut VecDeque::new());
|
||||
assert!(document.pending_remote.rebuilt, "the changes should be kept when the interface could not be rebuilt");
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
#[cfg(test)]
|
||||
pub(crate) mod document_diff;
|
||||
mod document_history;
|
||||
mod document_message;
|
||||
@@ -14,8 +15,7 @@ pub mod overlays;
|
||||
pub mod resource;
|
||||
pub mod utility_types;
|
||||
|
||||
pub(crate) use document_diff::diff_networks;
|
||||
pub(crate) use document_history::{CursorMoveError, DocumentHistory};
|
||||
pub(crate) use document_history::DocumentHistory;
|
||||
#[doc(inline)]
|
||||
pub use document_message::{DocumentMessage, DocumentMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
|
||||
@@ -1394,8 +1394,8 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// Like `math_expression`, where a lone reducer token like `+` or `min` applied across the node's items is also valid
|
||||
"math_expression_or_reducer".to_string(),
|
||||
// Like `math_expression`, but taking only a lone operator or function name like `+` or `min` to apply across the node's items
|
||||
"math_operator".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![LayoutGroup::row(node_inspector::math_expression_widget(info, true))])
|
||||
@@ -1448,6 +1448,13 @@ fn static_input_inspector() -> InputInspector {
|
||||
Ok(vec![choices])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"vec2_uv".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false)])
|
||||
}),
|
||||
);
|
||||
map
|
||||
}
|
||||
|
||||
|
||||
@@ -208,6 +208,7 @@ pub enum NodeGraphMessage {
|
||||
SendWires,
|
||||
UpdateVisibleNodes,
|
||||
SendGraph,
|
||||
SendNodePositions,
|
||||
SetInputValue {
|
||||
node_id: NodeId,
|
||||
input_index: usize,
|
||||
|
||||
@@ -131,9 +131,9 @@ pub struct NodeGraphMessageHandler {
|
||||
reordering_export: Option<usize>,
|
||||
/// The end index of the moved connector
|
||||
end_index: Option<usize>,
|
||||
/// Used to keep track of what nodes are sent to the front end so that only visible ones are sent to the frontend
|
||||
frontend_nodes: Vec<NodeId>,
|
||||
/// Used to keep track of what wires are sent to the front end so the old ones can be removed
|
||||
/// The nodes the frontend currently knows about
|
||||
frontend_nodes: Vec<FrontendNode>,
|
||||
/// Used to keep track of what wires are sent to the frontend so the old ones can be removed
|
||||
frontend_wires: HashSet<(NodeId, usize)>,
|
||||
evaluation_errors: Vec<NodeEvaluationError>,
|
||||
}
|
||||
@@ -650,6 +650,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
insert_node_input_index,
|
||||
} => {
|
||||
network_interface.insert_node_between(&node_id, &input_connector, insert_node_input_index, selection_network_path);
|
||||
network_interface.connect_read_node_to_map(&node_id, selection_network_path);
|
||||
}
|
||||
NodeGraphMessage::InsertDotOnWire { node_id, input_connector, x, y } => {
|
||||
network_interface.insert_dot_on_wire(node_id, &input_connector, IVec2::new(x, y), selection_network_path);
|
||||
@@ -2017,7 +2018,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
let document_bbox: [DVec2; 2] = viewport_bbox.map(|p| network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(p));
|
||||
|
||||
let mut nodes = Vec::new();
|
||||
for node_id in &self.frontend_nodes {
|
||||
for node_id in self.frontend_nodes.iter().map(|node| &node.id) {
|
||||
let Some(node_bbox) = network_interface.node_bounding_box(node_id, breadcrumb_network_path) else {
|
||||
log::error!("Could not get bbox for node: {node_id:?}");
|
||||
continue;
|
||||
@@ -2052,9 +2053,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
responses.add(InspectorMessage::Refresh);
|
||||
responses.add(EventMessage::GraphChanged);
|
||||
if breadcrumb_network_path == selection_network_path && graph_view_overlay_open {
|
||||
let nodes = self.collect_nodes(network_interface, breadcrumb_network_path);
|
||||
self.frontend_nodes = nodes.iter().map(|node| node.id).collect();
|
||||
responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes });
|
||||
self.frontend_nodes = self.collect_nodes(network_interface, breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes: self.frontend_nodes.clone() });
|
||||
|
||||
let errors = self.node_graph_errors(network_interface, breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors });
|
||||
@@ -2071,6 +2071,36 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
self.update_node_graph_hints(responses);
|
||||
}
|
||||
}
|
||||
NodeGraphMessage::SendNodePositions => {
|
||||
if breadcrumb_network_path != selection_network_path || !graph_view_overlay_open {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(network) = network_interface.nested_network(breadcrumb_network_path) else { return };
|
||||
let same_nodes = network.nodes.len() == self.frontend_nodes.len() && self.frontend_nodes.iter().all(|node| network.nodes.contains_key(&node.id));
|
||||
if !same_nodes {
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
return;
|
||||
}
|
||||
|
||||
for node in &mut self.frontend_nodes {
|
||||
if let Some(position) = network_interface.position(&node.id, breadcrumb_network_path) {
|
||||
node.position = position.into();
|
||||
}
|
||||
}
|
||||
responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes: self.frontend_nodes.clone() });
|
||||
|
||||
let errors = self.node_graph_errors(network_interface, breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors });
|
||||
|
||||
let (layer_widths, chain_widths, has_left_input_wire) = network_interface.collect_layer_widths(breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateLayerWidths {
|
||||
layer_widths,
|
||||
chain_widths,
|
||||
has_left_input_wire,
|
||||
});
|
||||
responses.add(NodeGraphMessage::UpdateImportsExports);
|
||||
}
|
||||
NodeGraphMessage::SetInputValue { node_id, input_index, value } => {
|
||||
use graphene_std::vector::generator_nodes::*;
|
||||
|
||||
@@ -2134,12 +2164,15 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
|
||||
if graph_view_overlay_open {
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
if !rubber_band {
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
responses.add(DocumentMessage::RenderScrollbars);
|
||||
}
|
||||
}
|
||||
NodeGraphMessage::ShiftSelectedNodesByAmount { mut graph_delta, rubber_band, glide } => {
|
||||
let moved = graph_delta != IVec2::ZERO;
|
||||
while graph_delta != IVec2::ZERO {
|
||||
match graph_delta.x.cmp(&0) {
|
||||
Ordering::Greater => {
|
||||
@@ -2183,6 +2216,9 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SendWires);
|
||||
if rubber_band && moved {
|
||||
responses.add(NodeGraphMessage::SendNodePositions);
|
||||
}
|
||||
}
|
||||
NodeGraphMessage::ToggleSelectedAsLayersOrNodes => {
|
||||
let Some(selected_nodes) = network_interface.selected_nodes_in_nested_network(selection_network_path) else {
|
||||
@@ -3410,7 +3446,8 @@ impl NodeGraphMessageHandler {
|
||||
.exports
|
||||
.iter()
|
||||
.any(|export| matches!(export, NodeInput::Node { node_id: export_node_id, .. } if *export_node_id == node_id));
|
||||
if selection_is_not_already_the_output && no_other_selections {
|
||||
let has_outputs = network_interface.number_of_outputs(&node_id, breadcrumb_network_path) > 0;
|
||||
if selection_is_not_already_the_output && no_other_selections && has_outputs {
|
||||
let button = TextButton::new("Preview")
|
||||
.icon("FrameAll")
|
||||
.tooltip_label("Preview")
|
||||
|
||||
@@ -481,16 +481,16 @@ pub fn text_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetIn
|
||||
}
|
||||
|
||||
/// A math expression's typeset text field, with a warning icon in the assist area giving the error in its tooltip while the expression fails to parse.
|
||||
pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo, accepts_reducers: bool) -> Vec<WidgetInstance> {
|
||||
pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo, operator_only: bool) -> Vec<WidgetInstance> {
|
||||
let Some(TaggedValue::String(expression)) = parameter_widgets_info.input().and_then(|input| input.as_non_exposed_value()) else {
|
||||
return text_widget(parameter_widgets_info);
|
||||
};
|
||||
let error = math_expression_error(expression, accepts_reducers);
|
||||
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(expression, accepts_reducers);
|
||||
let error = math_expression_error(expression, operator_only);
|
||||
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(expression, operator_only);
|
||||
let input = MathExpressionInput::new(expression.clone())
|
||||
.tokens(tokens)
|
||||
.tooltips(tooltips)
|
||||
.accepts_reducers(accepts_reducers)
|
||||
.operator_only(operator_only)
|
||||
.errors(math_expression_error_ranges(expression, error.as_ref()))
|
||||
.on_update(parameter_widgets_info.update_value(|x: &MathExpressionInput| TaggedValue::String(x.value.clone())))
|
||||
.on_commit(commit_value)
|
||||
@@ -500,7 +500,7 @@ pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo,
|
||||
// padded to a checkbox's 16px so the field lines up with the rows around it
|
||||
let icon = match &error {
|
||||
Some(error) => IconLabel::new("Warning")
|
||||
.tooltip_label("Invalid Math Expression")
|
||||
.tooltip_label(if operator_only { "Invalid Operator" } else { "Invalid Math Expression" })
|
||||
.tooltip_description(math_expression_error_description(error)),
|
||||
None => IconLabel::new("Empty12px"),
|
||||
};
|
||||
@@ -3942,12 +3942,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn math_expressions_are_flagged_only_when_they_fail_to_parse() {
|
||||
for (expression, accepts_reducers) in [("x * 2", false), ("", false), (" ", true), ("min", false), ("+", true), ("min", true)] {
|
||||
assert!(math_expression_error(expression, accepts_reducers).is_none(), "`{expression}`");
|
||||
for (expression, operator_only) in [("x * 2", false), ("", false), (" ", true), ("min", false), ("+", true), ("min", true), (" ≤ ", true)] {
|
||||
assert!(math_expression_error(expression, operator_only).is_none(), "`{expression}`");
|
||||
}
|
||||
|
||||
assert!(math_expression_error("2 +", false).is_some());
|
||||
assert!(math_expression_error("+", false).is_some(), "a lone reducer is an error where the node applies none");
|
||||
assert!(math_expression_error("+", false).is_some(), "a lone operator is an error where the node takes an expression");
|
||||
assert!(math_expression_error("a + b", true).is_some(), "an expression is an error where the node takes a lone operator");
|
||||
assert_eq!(description("sin(I)").as_deref(), Some("A matrix stands where a value is needed"));
|
||||
}
|
||||
|
||||
|
||||
@@ -233,3 +233,16 @@ pub enum Direction {
|
||||
Left,
|
||||
Right,
|
||||
}
|
||||
|
||||
/// Another peer's pointer over the node graph, in viewport pixels.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FrontendRemoteCursor {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub name: String,
|
||||
/// A stand-in name, shown in italics.
|
||||
pub anonymous: bool,
|
||||
pub color: String,
|
||||
pub tool: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
const TEMPLATE_DIRECTORY: &str = "../node-graph/compiler-spike/workloads/templates";
|
||||
|
||||
/// Draws three rectangle layers with the Rectangle tool and saves the document as the compiler spike's layer template.
|
||||
/// Run with `cargo test -p graphite-editor export_compiler_spike_templates -- --ignored`, then rerun the spike's workload export.
|
||||
#[tokio::test]
|
||||
#[ignore]
|
||||
async fn export_compiler_spike_templates() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
for i in 0..3 {
|
||||
let offset = i as f64 * 20.;
|
||||
editor.draw_rect(offset, offset, offset + 10., offset + 10.).await;
|
||||
}
|
||||
|
||||
std::fs::create_dir_all(TEMPLATE_DIRECTORY).unwrap();
|
||||
std::fs::write(format!("{TEMPLATE_DIRECTORY}/rectangle-layers.graphite"), editor.active_document().serialize_document()).unwrap();
|
||||
}
|
||||
@@ -4,6 +4,7 @@ use crate::messages::frontend::utility_types::PersistedState;
|
||||
use crate::messages::portfolio::document_storage_io::document_key;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::test_utils::EditorTestUtils;
|
||||
use document_container::archive::ArchiveFormat;
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
|
||||
fn dispatch(editor: &mut EditorTestUtils, message: impl Into<Message>) -> Vec<FrontendMessage> {
|
||||
@@ -118,20 +119,22 @@ async fn legacy_only_container_gets_storage() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_save_format_still_keeps_a_working_copy() {
|
||||
async fn saving_writes_a_zip_archive_with_the_graphite_extension() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled: false });
|
||||
let id = new_document(&mut editor, "Legacy");
|
||||
let id = new_document(&mut editor, "Saved");
|
||||
let container = container(&editor, id).await;
|
||||
assert!(editor.active_document().storage().is_some(), "every document gets a working copy, whatever the save format");
|
||||
assert!(container.exists("manifest.json").await);
|
||||
|
||||
let saved = dispatch(&mut editor, DocumentMessage::SaveDocumentAs);
|
||||
let name = saved.iter().find_map(|message| match message {
|
||||
FrontendMessage::TriggerSaveDocument { name, .. } => Some(name.clone()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(name.as_deref(), Some("Legacy.graphite"));
|
||||
let (name, content) = saved
|
||||
.iter()
|
||||
.find_map(|message| match message {
|
||||
FrontendMessage::TriggerSaveDocument { name, content, .. } => Some((name.clone(), content.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the save is sent to the frontend");
|
||||
assert_eq!(name, "Saved.graphite");
|
||||
assert_eq!(ArchiveFormat::detect(&content), Some(ArchiveFormat::Zip));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -173,6 +176,8 @@ async fn unchanged_content_keeps_cursor_and_redo_across_restart() {
|
||||
let network_before = editor.active_document().document_network().clone();
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
dispatch(&mut editor, PortfolioMessage::AutoSaveDocument { document_id: id });
|
||||
// Undoing a hot step takes it back instead of moving the cursor
|
||||
editor.active_document_mut().retire_storage_interaction();
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(editor.active_document().document_network(), &network_before);
|
||||
@@ -200,20 +205,6 @@ async fn closing_removes_the_stored_document() {
|
||||
assert!(portfolio(&editor).persisted_state_snapshot().documents.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn storage_preference_keeps_the_working_copy() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
let id = new_document(&mut editor, "Toggle");
|
||||
let container = container(&editor, id).await;
|
||||
assert!(editor.active_document().storage().is_some());
|
||||
assert!(container.exists("legacy.graphite").await);
|
||||
|
||||
for enabled in [false, true] {
|
||||
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled });
|
||||
assert!(editor.active_document().storage().is_some(), "the preference only picks the save format");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unreadable_document_is_reported_and_kept_until_discarded() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//!
|
||||
//! Shared fixtures live in [`test_support`].
|
||||
|
||||
mod compiler_spike_templates;
|
||||
mod lifecycle_tests;
|
||||
mod metadata_tests;
|
||||
mod round_trip_tests;
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
//! End-to-end storage round-trip tests: drive real edits through the editor, push the document
|
||||
//! through a fresh in-memory `Gdd` (stage → retire → persist), reopen from the same container, and
|
||||
//! assert the reopened document matches. Exercises the full persistence pipeline (conversion,
|
||||
//! postcard codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
|
||||
//! `verify_storage_round_trip` only checks in-process without an actual save/reopen.
|
||||
//! postcard codecs, hot-op retirement, file layout, replay-on-open).
|
||||
|
||||
use crate::messages::resource_storage::ResourcesHandle;
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{NodeMetadataSource, PeerId, UserId, to_value};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::application_io::resource::{DataSource, HashMapResourceStorage, ResourceHash, ResourceId};
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::test_support::{RoundTrip, node_locations, node_paths, round_trip_through_gdd};
|
||||
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
|
||||
@@ -158,7 +159,7 @@ async fn edit_after_open_commits_cleanly() {
|
||||
|
||||
// Persist the document into a fresh Gdd and reopen it, then build a runtime document from the
|
||||
// reopened registry: the editor's .gdd-open path.
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
let byte_store = ResourcesHandle::new(Arc::new(HashMapResourceStorage::new()));
|
||||
let source = editor.active_document();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
|
||||
let source_network = source.network_interface.document_network().clone();
|
||||
@@ -176,14 +177,14 @@ async fn edit_after_open_commits_cleanly() {
|
||||
{
|
||||
let document = editor.active_document_mut();
|
||||
document.network_interface = rebuilt;
|
||||
document.set_storage(reopened, declarations);
|
||||
document.set_storage(reopened, declarations, byte_store.storage());
|
||||
document.finalize_storage_load();
|
||||
}
|
||||
|
||||
// Mirror the live sequence via the real `commit_storage_snapshot`: initial commit after open, then a
|
||||
// deletion, then commit again. Deletion (not addition) is the trigger, since it emits a `RemoveNode`
|
||||
// whose retire/reverse is where "Target node does not exist" surfaced live.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("at least one layer");
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
@@ -332,7 +333,7 @@ async fn live_undo_shadows_storage_cursor() {
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
// Capture the loaded state as the base interaction, then make a real edit (fires CommitTransaction).
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
let before_edit = editor.active_document().network_interface.document_network().clone();
|
||||
editor.draw_ellipse(50., 50., 150., 150.).await;
|
||||
let after_edit = editor.active_document().network_interface.document_network().clone();
|
||||
@@ -473,7 +474,7 @@ async fn live_undo_new_document_draw_rect() {
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
// Mount-time snapshot: capture the new-document graph as the base interaction.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
|
||||
let before_rect = editor.active_document().network_interface.document_network().clone();
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
@@ -560,7 +561,7 @@ async fn undo_image_paste_resources_subset_of_runtime() {
|
||||
editor.new_document().await;
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
|
||||
editor.handle_message(paste_named_image()).await;
|
||||
|
||||
@@ -571,7 +572,7 @@ async fn undo_image_paste_resources_subset_of_runtime() {
|
||||
let stored: std::collections::BTreeSet<_> = storage.registry().resources.keys().copied().collect();
|
||||
|
||||
// Every resource the restored network still references must be in the cursor.
|
||||
let current: std::collections::BTreeSet<_> = document.used_resources(false).iter().copied().collect();
|
||||
let current: std::collections::BTreeSet<_> = document.used_resources().iter().copied().collect();
|
||||
assert!(
|
||||
current.is_subset(&stored),
|
||||
"cursor is missing a resource the restored network references: current={current:?} stored={stored:?}"
|
||||
@@ -592,7 +593,7 @@ async fn undo_twice_steps_cursor_two_interactions() {
|
||||
editor.new_document().await;
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
let base = editor.active_document().network_interface.document_network().clone();
|
||||
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
@@ -613,7 +614,7 @@ async fn undo_twice_steps_cursor_two_interactions() {
|
||||
// cached for redo though its node is gone, so a naive snapshot would re-detect it as a new `AddResource`
|
||||
// and retire a phantom interaction, knocking the cursor out of lockstep. Scoping the snapshot to
|
||||
// network-referenced resources must keep this a no-op.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
|
||||
// Second undo: removes the rectangle, back to the loaded base. The cursor must step a second interaction
|
||||
// and land on the base, not one short.
|
||||
@@ -632,7 +633,7 @@ async fn undo_twice_steps_cursor_two_interactions() {
|
||||
}
|
||||
|
||||
/// Assert the `Gdd` cursor's stored registry matches a fresh `from_runtime` of the current interface (node
|
||||
/// set, network set, per-network export wiring), mirroring the live `verify_cursor_matches_runtime` check.
|
||||
/// set, network set, per-network export wiring).
|
||||
/// The runtime's resource set may be a superset (it keeps undone resources alive for redo), but every
|
||||
/// resource the current network references must be present.
|
||||
fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
|
||||
@@ -662,12 +663,149 @@ fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pasted_image_resource_survives_inserting_a_node() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
|
||||
editor.handle_message(paste_named_image()).await;
|
||||
editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER)).await;
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
|
||||
let document = editor.active_document();
|
||||
let stored: std::collections::BTreeSet<_> = document.storage().expect("storage mounted").registry().resources.keys().copied().collect();
|
||||
let used: std::collections::BTreeSet<_> = document.used_resources().iter().copied().collect();
|
||||
assert!(used.is_subset(&stored), "storage lost a resource the network references: used={used:?} stored={stored:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pasted_image_resource_survives_storage_mounting_after_the_paste() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
editor.handle_message(paste_named_image()).await;
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
|
||||
let document = editor.active_document();
|
||||
let stored: std::collections::BTreeSet<_> = document.storage().expect("storage mounted").registry().resources.keys().copied().collect();
|
||||
let used: std::collections::BTreeSet<_> = document.used_resources().iter().copied().collect();
|
||||
assert!(used.is_subset(&stored), "storage lost a resource the network references: used={used:?} stored={stored:?}");
|
||||
}
|
||||
|
||||
/// Pastes an image and points it at a resource from `source` that is staged before it resolves, then resolves it, giving the resource and its hash.
|
||||
async fn image_resource_resolved_after_staging(editor: &mut EditorTestUtils, source: DataSource) -> (ResourceId, ResourceHash) {
|
||||
use graph_craft::document::DocumentNodeImplementation;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::raster_nodes::std_nodes::image;
|
||||
|
||||
editor.new_document().await;
|
||||
let byte_store = mount_in_memory_storage(editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.handle_message(paste_named_image()).await;
|
||||
|
||||
// Point the image at a resource that is still being fetched, so its entry is staged without a hash
|
||||
let image_node_id = editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.document_network()
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == image::IDENTIFIER))
|
||||
.map(|(id, _)| *id)
|
||||
.expect("the pasted image should be an Image node");
|
||||
let resource_id = ResourceId::new();
|
||||
editor.active_document_mut().resources.registry.push_source_back(&resource_id, source.clone());
|
||||
editor.dispatch(DocumentMessage::StartTransaction);
|
||||
editor.dispatch(NodeGraphMessage::SetInputValue {
|
||||
node_id: image_node_id,
|
||||
input_index: image::ResourceInput::INDEX,
|
||||
value: TaggedValue::Resource(resource_id).into(),
|
||||
});
|
||||
editor.dispatch(DocumentMessage::CommitTransaction);
|
||||
let stored = editor
|
||||
.active_document()
|
||||
.storage()
|
||||
.expect("storage mounted")
|
||||
.registry()
|
||||
.resources
|
||||
.get(&resource_id)
|
||||
.map(|entry| entry.hash);
|
||||
assert_eq!(stored, Some(None), "storage should hold the resource without its hash");
|
||||
|
||||
// The fetch finishes, which caches a font's hash for a later resolve
|
||||
let data: Arc<[u8]> = Image::new(2, 2, Color::BLACK).to_png().into();
|
||||
let hash = ResourceHash::from(data.as_ref());
|
||||
let document_id = editor.portfolio_message_handler().active_document_id.expect("a document is open");
|
||||
editor.dispatch(ResourceStorageMessage::Store { data });
|
||||
editor.dispatch(PortfolioMessage::DocumentPassMessage {
|
||||
document_id,
|
||||
message: ResourceMessage::Resolved { resource_id, source, hash }.into(),
|
||||
});
|
||||
|
||||
(resource_id, hash)
|
||||
}
|
||||
|
||||
/// Undo and redo keep the hash of a resource resolved after its entry was staged.
|
||||
#[tokio::test]
|
||||
async fn resource_resolved_after_staging_stays_resolved_through_undo_and_redo() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
// An embedded source can't be fetched again, so only the runtime's resolution keeps it resolved
|
||||
let (resource_id, hash) = image_resource_resolved_after_staging(&mut editor, DataSource::Embedded).await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
// Undo and redo the rectangle, then the step that set the resource
|
||||
for (message, step) in [
|
||||
(DocumentMessage::Undo, "undoing the rectangle"),
|
||||
(DocumentMessage::Redo, "redoing the rectangle"),
|
||||
(DocumentMessage::Undo, "undoing the rectangle again"),
|
||||
(DocumentMessage::Undo, "undoing the resource change"),
|
||||
(DocumentMessage::Redo, "redoing the resource change"),
|
||||
] {
|
||||
editor.dispatch(message);
|
||||
let document = editor.active_document();
|
||||
let registry = &document.resources.registry;
|
||||
assert!(registry.unresolved().next().is_none(), "{step} left a resource unresolved, which stops rendering");
|
||||
assert!(document.used_resources().iter().all(|id| registry.hash(id).is_some()), "{step} left a used resource without its hash");
|
||||
}
|
||||
assert_eq!(editor.active_document().resources.registry.hash(&resource_id), Some(hash));
|
||||
}
|
||||
|
||||
/// A resource that history leaves without its hash is resolved again.
|
||||
#[tokio::test]
|
||||
async fn resource_left_unresolved_by_history_is_resolved_again() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
// A font resolves again from its cached hash, without a download
|
||||
let font = DataSource::Font {
|
||||
family: "Test Family".into(),
|
||||
style: Some("Regular (400)".into()),
|
||||
};
|
||||
let (resource_id, hash) = image_resource_resolved_after_staging(&mut editor, font).await;
|
||||
|
||||
// No snapshot uses the resource once its step is undone, so collection drops the runtime's resolution
|
||||
editor.dispatch(DocumentMessage::Undo);
|
||||
editor.active_document_mut().garbage_collect_resources();
|
||||
assert!(
|
||||
editor.active_document().resources.registry.info(&resource_id).is_none(),
|
||||
"garbage collection should drop the undone step's resource"
|
||||
);
|
||||
|
||||
editor.dispatch(DocumentMessage::Redo);
|
||||
let registry = &editor.active_document().resources.registry;
|
||||
assert_eq!(registry.hash(&resource_id), Some(hash), "redoing the step should resolve its resource again");
|
||||
assert!(registry.unresolved().next().is_none(), "redoing the step left a resource unresolved, which stops rendering");
|
||||
}
|
||||
|
||||
/// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real
|
||||
/// autosave path) runs against it. Returns the byte store the document's resources resolve through.
|
||||
fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourceStorage {
|
||||
fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> ResourcesHandle {
|
||||
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0x5EED, "test".into(), "test".into()).expect("create_in");
|
||||
editor.active_document_mut().set_storage(gdd, Default::default());
|
||||
HashMapResourceStorage::new()
|
||||
let byte_store = ResourcesHandle::new(Arc::new(HashMapResourceStorage::new()));
|
||||
editor.active_document_mut().set_storage(gdd, Default::default(), byte_store.storage());
|
||||
byte_store
|
||||
}
|
||||
|
||||
/// Open a real demo artwork, mount storage, edit it, and trigger autosave. The autosave runs
|
||||
@@ -692,7 +830,7 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
|
||||
// First autosave: captures the loaded document. `verify_storage_round_trip` panics on drift.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
let history_after_open = editor.active_document().storage().unwrap().session().history().count();
|
||||
|
||||
// Snapshot the network, then make a real modification.
|
||||
@@ -701,8 +839,8 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
|
||||
let after_edit = editor.active_document().network_interface.document_network().clone();
|
||||
assert_ne!(before_edit, after_edit, "drawing a rectangle should change the document network");
|
||||
|
||||
// Second autosave: again verifies the round-trip, and the edit must produce new retired history.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().retire_storage_interaction();
|
||||
let history_after_edit = editor.active_document().storage().unwrap().session().history().count();
|
||||
assert!(
|
||||
history_after_edit > history_after_open,
|
||||
@@ -715,7 +853,7 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
|
||||
assert_eq!(after_undo, before_edit, "undo should restore the pre-edit network");
|
||||
|
||||
// Autosaving the undone state still round-trips cleanly (no drift panic).
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
}
|
||||
|
||||
/// Manual edits ride a saved document as a folded `VectorModification`, so opening the artworks carrying the most
|
||||
@@ -936,3 +1074,81 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
|
||||
"the transform input should shift down intact, but became {transform:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn undoing_a_hot_step_takes_it_back_and_redo_stages_it_again() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().retire_storage_interaction();
|
||||
let history_base = editor.active_document().storage().unwrap().session().history().count();
|
||||
let before_edit = editor.active_document().network_interface.document_network().clone();
|
||||
|
||||
editor.draw_rect(64., 64., 192., 192.).await;
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
let after_edit = editor.active_document().network_interface.document_network().clone();
|
||||
assert_ne!(after_edit, before_edit);
|
||||
assert!(!editor.active_document().storage().unwrap().session().hot_log().is_empty(), "the step is hot");
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(editor.active_document().network_interface.document_network(), &before_edit, "undo restores the pre-edit network");
|
||||
let storage = editor.active_document().storage().unwrap();
|
||||
assert!(storage.session().hot_log().is_empty(), "the step was taken back, not retired: {:?}", storage.session().hot_log());
|
||||
assert_eq!(storage.session().history().count(), history_base, "nothing entered history");
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
// The step held for redo keeps its declaration bytes from collection
|
||||
let storage = editor.active_document().storage().unwrap();
|
||||
assert!(
|
||||
!editor.active_document().resource_gc_roots().is_subset(&storage.all_referenced_resource_hashes()),
|
||||
"the retracted step names its declaration resource"
|
||||
);
|
||||
|
||||
editor.handle_message(DocumentMessage::Redo).await;
|
||||
assert_eq!(editor.active_document().network_interface.document_network(), &after_edit, "redo restores the edit");
|
||||
let storage = editor.active_document().storage().unwrap();
|
||||
assert!(!storage.session().hot_log().is_empty(), "the redone step is staged afresh");
|
||||
assert_eq!(storage.session().history().count(), history_base);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
}
|
||||
|
||||
/// Draws three ellipses, undoes all of them, redoes them and one more, then undoes once. `retire` retires each
|
||||
/// drawing first, so the steps undo through the cursor rather than by retraction.
|
||||
async fn redone_steps_undo_one_at_a_time(retire: bool) {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
|
||||
for offset in [0., 200., 400.] {
|
||||
editor.draw_ellipse(offset, 0., offset + 100., 100.).await;
|
||||
if retire {
|
||||
editor.active_document_mut().retire_storage_interaction();
|
||||
}
|
||||
}
|
||||
let layer_count = |editor: &EditorTestUtils| editor.active_document().metadata().all_layers().count();
|
||||
assert_eq!(layer_count(&editor), 3);
|
||||
|
||||
for expected in [2, 1, 0] {
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(layer_count(&editor), expected, "undoing down to {expected} ellipses");
|
||||
}
|
||||
for expected in [1, 2, 3, 3] {
|
||||
editor.handle_message(DocumentMessage::Redo).await;
|
||||
assert_eq!(layer_count(&editor), expected, "redoing up to {expected} ellipses");
|
||||
}
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(layer_count(&editor), 2, "undo takes back only the last redone ellipse");
|
||||
assert_cursor_matches_runtime(editor.active_document(), "after undoing a redone step");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn redone_hot_steps_undo_one_at_a_time() {
|
||||
redone_steps_undo_one_at_a_time(false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn redone_retired_steps_undo_one_at_a_time() {
|
||||
redone_steps_undo_one_at_a_time(true).await;
|
||||
}
|
||||
@@ -17,6 +17,7 @@ mod layout;
|
||||
mod memo_network;
|
||||
mod mutations;
|
||||
mod queries;
|
||||
mod reconcile;
|
||||
mod resolved_types;
|
||||
pub mod storage_metadata;
|
||||
mod store;
|
||||
@@ -28,6 +29,7 @@ mod validation;
|
||||
mod view;
|
||||
|
||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||
pub use reconcile::{ReconcileError, Reconciled};
|
||||
use store::Guarded;
|
||||
pub use store::NodeLocator;
|
||||
pub use template::*;
|
||||
|
||||
@@ -8,7 +8,6 @@ impl NodeNetworkInterface {
|
||||
/// never made back to whoever sent it. Writing through the store and then dropping what the store
|
||||
/// recorded keeps the two parallel trees written by one place, which is the property the store
|
||||
/// exists for, without the echo.
|
||||
#[cfg_attr(not(test), expect(dead_code, reason = "no caller until deltas from another peer are replayed; the replay tests exercise it"))]
|
||||
pub(crate) fn apply(&mut self, delta: &EditorDelta) {
|
||||
let recorded = self.deltas.len();
|
||||
self.mirror(delta);
|
||||
|
||||
+12
@@ -1,6 +1,7 @@
|
||||
use super::template::NodeTemplateImplementation;
|
||||
use super::{InputConnector, OutputConnector, catalog};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
|
||||
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NetworkId, NodeInput};
|
||||
use graphene_std::uuid::NodeId;
|
||||
@@ -148,3 +149,14 @@ async fn an_entry_that_diverged_under_a_catalog_id_gets_a_fresh_id_on_open() {
|
||||
assert!(!network.definitions.contains_key(&shipped));
|
||||
assert!(network.definitions[&renamed].exports.len() > catalog::entry(shipped).expect("shipped").network.exports.len());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_reopened_document_keeps_its_catalog_entries() {
|
||||
let (editor, blends) = editor_with_blends(1).await;
|
||||
let shipped = entry_of(&editor, blends[0]);
|
||||
|
||||
let mut reopened = round_trip_through_gdd(editor.active_document()).await.rebuilt;
|
||||
reopened.give_diverged_catalog_entries_new_ids();
|
||||
|
||||
assert!(reopened.document_network().definitions.contains_key(&shipped));
|
||||
}
|
||||
+178
-8
@@ -4,7 +4,9 @@ use super::{
|
||||
};
|
||||
use crate::consts::{GRID_SIZE, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction};
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -41,9 +43,6 @@ fn new_artboard_message(id: NodeId) -> GraphOperationMessage {
|
||||
async fn invariants_hold_through_basic_editing_flow() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
// This test covers the interface's structural invariants. The storage dual-write is out of its scope and asserted by the storage round-trip tests.
|
||||
editor.editor.handle_message(PreferencesMessage::ValidateStorageRoundTrip { enabled: false });
|
||||
|
||||
editor.new_document().await;
|
||||
assert_invariants(&editor, "after opening a new document");
|
||||
|
||||
@@ -1177,8 +1176,6 @@ fn fed_inputs(editor: &EditorTestUtils, output_connector: &OutputConnector, netw
|
||||
async fn dragging_a_dot_out_of_an_import_takes_over_the_wires_the_import_fed() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
// TODO: Remove once staging the recorded edits stores a node wired to an import inside a subgraph as it is, instead of drifting from it
|
||||
editor.handle_message(PreferencesMessage::ValidateStorageRoundTrip { enabled: false }).await;
|
||||
|
||||
let merge = editor.create_node_by_name_at(merge_definition(), 0, 0).await;
|
||||
let path = vec![merge];
|
||||
@@ -2995,9 +2992,6 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire
|
||||
|
||||
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
|
||||
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
|
||||
// TODO: Remove once staging the recorded edits stores a node wired to an import inside a subgraph as it is, instead of drifting from it
|
||||
editor.handle_message(PreferencesMessage::ValidateStorageRoundTrip { enabled: false }).await;
|
||||
|
||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
|
||||
editor.handle_message(NodeGraphMessage::AddImport).await;
|
||||
@@ -3532,3 +3526,179 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
|
||||
"The evaluated network should fall back to the document's own export"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cannot_preview_node_without_outputs() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
|
||||
assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0);
|
||||
|
||||
// Attempting to toggle preview on a node without outputs should not enable previewing
|
||||
network_interface.toggle_preview(custom_node, &[]);
|
||||
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
||||
}
|
||||
|
||||
fn map_definition() -> DefinitionIdentifier {
|
||||
DefinitionIdentifier::ProtoNode(graphene_std::graphic::map::IDENTIFIER)
|
||||
}
|
||||
|
||||
async fn layer_with_chain_and_unwired_map(editor: &mut EditorTestUtils) -> (NodeId, NodeId, NodeId) {
|
||||
let (layer, near, ..) = layer_with_chain(editor).await;
|
||||
editor
|
||||
.active_document_mut()
|
||||
.network_interface
|
||||
.create_wire(&OutputConnector::primary_output(layer), &InputConnector::Export(0), &[]);
|
||||
editor.handle_message(NodeGraphMessage::RunDocumentGraph).await;
|
||||
|
||||
let map = editor.create_node_by_name_at(map_definition(), 0, 30).await;
|
||||
(layer, near, map)
|
||||
}
|
||||
|
||||
async fn drop_map_onto_chain(editor: &mut EditorTestUtils, layer: NodeId, map: NodeId) {
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::InsertNodeBetween {
|
||||
node_id: map,
|
||||
input_connector: InputConnector::layer_secondary_input(layer),
|
||||
insert_node_input_index: 0,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_a_map_node_onto_a_wire_feeds_it_the_matching_read_node() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, near, map) = layer_with_chain_and_unwired_map(&mut editor).await;
|
||||
|
||||
drop_map_onto_chain(&mut editor, layer, map).await;
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let Some(NodeInput::Node { node_id: read_node, .. }) = network_interface.input_from_connector(&InputConnector::node_at_index(map, 1), &[]).cloned() else {
|
||||
panic!("The Map node's mapped input should be fed by a new node");
|
||||
};
|
||||
assert_eq!(
|
||||
network_interface.reference(&read_node, &[]),
|
||||
Some(DefinitionIdentifier::ProtoNode(graphene_std::context::read_vector::IDENTIFIER))
|
||||
);
|
||||
|
||||
let map_position = network_interface.position(&map, &[]).unwrap();
|
||||
let near_position = network_interface.position(&near, &[]).unwrap();
|
||||
let near_bottom = near_position.y + network_interface.node_height(&near, &[]) as i32;
|
||||
let read_node_position = network_interface.position(&read_node, &[]).unwrap();
|
||||
assert_eq!(read_node_position.x, map_position.x - crate::consts::NODE_CHAIN_WIDTH);
|
||||
assert!(
|
||||
read_node_position.y > near_bottom,
|
||||
"The Read node should sit below the Map node's content source rather than overlap it"
|
||||
);
|
||||
assert_invariants(&editor, "after dropping a Map node onto a wire");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_content_types_resolve_to_the_read_node_of_their_element() {
|
||||
use super::layout::read_node_for_content;
|
||||
use super::resolved_types::TypeSource;
|
||||
use graph_craft::{item, list};
|
||||
use graphene_std::context::{read_graphic, read_number, read_vector};
|
||||
use graphene_std::list::Bundle;
|
||||
use graphene_std::text_nodes::read_string;
|
||||
use graphene_std::{Graphic, Vector};
|
||||
|
||||
assert_eq!(read_node_for_content(&TypeSource::Compiled(list!(Vector))), Some(read_vector::IDENTIFIER));
|
||||
assert_eq!(read_node_for_content(&TypeSource::Compiled(item!(Graphic))), Some(read_graphic::IDENTIFIER));
|
||||
assert_eq!(read_node_for_content(&TypeSource::Compiled(list!(f64))), Some(read_number::IDENTIFIER));
|
||||
assert_eq!(read_node_for_content(&TypeSource::TaggedValue(list!(String))), Some(read_string::IDENTIFIER));
|
||||
assert_eq!(read_node_for_content(&TypeSource::Compiled(item!(Bundle<Vector>))), Some(read_vector::IDENTIFIER));
|
||||
|
||||
assert_eq!(
|
||||
read_node_for_content(&TypeSource::Compiled(list!(i64))),
|
||||
None,
|
||||
"Read Number yields f64, which a Map over integers can't take"
|
||||
);
|
||||
assert_eq!(read_node_for_content(&TypeSource::Compiled(list!(bool))), None);
|
||||
assert_eq!(read_node_for_content(&TypeSource::Unknown), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_a_map_node_onto_a_wire_keeps_its_wired_mapped_input() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, _, map) = layer_with_chain_and_unwired_map(&mut editor).await;
|
||||
|
||||
let mapped_source = NodeId::new();
|
||||
let read_vector = resolve_proto_node_type(graphene_std::context::read_vector::IDENTIFIER).unwrap().default_node_template();
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.insert_node(mapped_source, read_vector, &[]);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(mapped_source), &InputConnector::node_at_index(map, 1), &[]);
|
||||
let node_count = editor.active_document().network_interface.document_network().nodes.len();
|
||||
|
||||
drop_map_onto_chain(&mut editor, layer, map).await;
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert_eq!(
|
||||
network_interface.input_from_connector(&InputConnector::node_at_index(map, 1), &[]),
|
||||
Some(&NodeInput::node(mapped_source, 0))
|
||||
);
|
||||
assert_eq!(network_interface.document_network().nodes.len(), node_count);
|
||||
}
|
||||
|
||||
/// Pairs of layers in the root network whose boxes in the graph, which span their chains, intersect.
|
||||
fn overlapping_layers(editor: &EditorTestUtils) -> Vec<(LayerNodeIdentifier, LayerNodeIdentifier)> {
|
||||
let document = editor.active_document();
|
||||
let layers: Vec<_> = document.metadata().all_layers().collect();
|
||||
let bounds = |layer: LayerNodeIdentifier| document.network_interface.node_bounding_box(&layer.to_node(), &[]).expect("a layer should have a box in the graph");
|
||||
|
||||
let mut overlapping = Vec::new();
|
||||
for (index, &first) in layers.iter().enumerate() {
|
||||
for &second in &layers[index + 1..] {
|
||||
let ([first_min, first_max], [second_min, second_max]) = (bounds(first), bounds(second));
|
||||
if first_min.cmplt(second_max).all() && second_min.cmplt(first_max).all() {
|
||||
overlapping.push((first, second));
|
||||
}
|
||||
}
|
||||
}
|
||||
overlapping
|
||||
}
|
||||
|
||||
async fn group_selected_layers(editor: &mut EditorTestUtils) {
|
||||
editor
|
||||
.handle_message(DocumentMessage::GroupSelectedLayers {
|
||||
group_folder_type: GroupFolderType::Layer,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn grouping_the_top_layer_leaves_no_layers_overlapping_in_the_graph() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.draw_rect(50., 50., 150., 150.).await;
|
||||
|
||||
group_selected_layers(&mut editor).await;
|
||||
|
||||
assert_eq!(overlapping_layers(&editor), Vec::new());
|
||||
assert_invariants(&editor, "after grouping the top layer");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn grouping_a_group_moves_the_layer_below_it_past_all_of_its_contents() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.draw_rect(50., 50., 150., 150.).await;
|
||||
let bottom = editor.active_document().metadata().all_layers().last().expect("the bottom rectangle should be a layer");
|
||||
editor.draw_rect(100., 100., 200., 200.).await;
|
||||
editor.handle_message(DocumentMessage::SelectAllLayers).await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesRemove { nodes: vec![bottom.to_node()] }).await;
|
||||
group_selected_layers(&mut editor).await;
|
||||
assert_eq!(overlapping_layers(&editor), Vec::new(), "grouping the top two layers should leave none overlapping");
|
||||
|
||||
group_selected_layers(&mut editor).await;
|
||||
|
||||
assert_eq!(overlapping_layers(&editor), Vec::new());
|
||||
assert_invariants(&editor, "after grouping a group");
|
||||
}
|
||||
+246
-1
@@ -1,7 +1,7 @@
|
||||
use super::DocumentNodePersistentMetadata;
|
||||
use super::InputConnector;
|
||||
use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange, construct_batch, ui_attribute_writes};
|
||||
use super::storage_metadata::StorageMetadataView;
|
||||
use super::{InputConnector, NodeTemplate};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use document_graph_storage::delta::compute_deltas;
|
||||
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
|
||||
@@ -660,6 +660,251 @@ async fn swapping_an_implementation_leaves_the_node_in_place() {
|
||||
}
|
||||
}
|
||||
|
||||
fn conversion(editor: &EditorTestUtils) -> document_graph_storage::RuntimeConversion {
|
||||
let document = editor.active_document();
|
||||
Registry::convert_from_runtime(
|
||||
document.network_interface.document_network(),
|
||||
&StorageMetadataView::new(&document.network_interface),
|
||||
&document.resources.registry,
|
||||
PEER,
|
||||
)
|
||||
.expect("conversion should succeed")
|
||||
}
|
||||
|
||||
/// Checks that a clone reconciled from `edit`'s storage ops equals the edited interface.
|
||||
async fn assert_remote_reconcile_reproduces(edit: impl FnOnce(&mut EditorTestUtils)) {
|
||||
use document_graph_storage::Touched;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor
|
||||
.handle_message(DocumentMessage::GroupSelectedLayers {
|
||||
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
|
||||
})
|
||||
.await;
|
||||
editor.active_document_mut().network_interface.discard_deltas();
|
||||
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
|
||||
|
||||
let mut mirror = editor.active_document().network_interface.clone();
|
||||
let baseline = conversion(&editor);
|
||||
let mut peer = Session::with_peer(PeerId(8));
|
||||
peer.stage_computed_ops(compute_deltas(&Registry::default(), &baseline.registry)).expect("the peer takes the baseline");
|
||||
let mut declarations = baseline.declarations;
|
||||
|
||||
edit(&mut editor);
|
||||
editor.active_document_mut().network_interface.settle_definitions();
|
||||
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
|
||||
|
||||
let recorded = editor.active_document_mut().network_interface.take_deltas();
|
||||
assert!(!recorded.is_empty(), "the edit should have recorded something to send");
|
||||
let constructed = {
|
||||
let document = editor.active_document();
|
||||
construct_batch(
|
||||
&recorded,
|
||||
&baseline.registry,
|
||||
&document.resources.registry,
|
||||
&StorageMetadataView::new(&document.network_interface),
|
||||
PEER,
|
||||
)
|
||||
.expect("construction")
|
||||
};
|
||||
declarations.extend(constructed.declarations.decoded);
|
||||
|
||||
let mut touched = Touched::default();
|
||||
for op in &constructed.ops {
|
||||
touched.record(op);
|
||||
}
|
||||
peer.stage_computed_ops(constructed.ops).expect("the peer applies the batch");
|
||||
|
||||
mirror.reconcile_remote(peer.registry(), &declarations, &baseline.blob_bytes, &touched, PEER).expect("reconcile");
|
||||
|
||||
let edited = &editor.active_document().network_interface;
|
||||
assert!(
|
||||
mirror.document_network() == edited.document_network(),
|
||||
"reconciling {} recorded deltas did not reproduce the edited graph:\n{}",
|
||||
recorded.len(),
|
||||
crate::messages::portfolio::document::document_diff::diff_networks(edited.document_network(), mirror.document_network())
|
||||
);
|
||||
let metadata = |interface: &super::NodeNetworkInterface| serde_json::to_value(interface.document_network_metadata()).expect("metadata serializes");
|
||||
let (reconciled_metadata, edited_metadata) = (metadata(&mirror), metadata(edited));
|
||||
assert!(
|
||||
reconciled_metadata == edited_metadata,
|
||||
"reconciling {} recorded deltas did not reproduce the edited metadata:\n{}",
|
||||
recorded.len(),
|
||||
json_diff(&edited_metadata, &reconciled_metadata, "")
|
||||
);
|
||||
|
||||
let converted = Registry::convert_from_runtime(mirror.document_network(), &StorageMetadataView::new(&mirror), &editor.active_document().resources.registry, PEER)
|
||||
.expect("the reconciled interface converts")
|
||||
.registry;
|
||||
assert!(
|
||||
peer.registry().value_equal(&converted),
|
||||
"the reconciled interface must convert back to the registry it was reconciled from\nresidual: {:#?}",
|
||||
compute_deltas(&converted, peer.registry())
|
||||
);
|
||||
}
|
||||
|
||||
fn json_diff(expected: &serde_json::Value, actual: &serde_json::Value, path: &str) -> String {
|
||||
use serde_json::Value;
|
||||
match (expected, actual) {
|
||||
(Value::Object(expected), Value::Object(actual)) => {
|
||||
let keys: std::collections::BTreeSet<_> = expected.keys().chain(actual.keys()).collect();
|
||||
keys.into_iter()
|
||||
.map(|key| match (expected.get(key), actual.get(key)) {
|
||||
(Some(expected), Some(actual)) => json_diff(expected, actual, &format!("{path}/{key}")),
|
||||
(Some(expected), None) => format!("{path}/{key}: missing, expected {expected}\n"),
|
||||
(None, Some(actual)) => format!("{path}/{key}: unexpected {actual}\n"),
|
||||
(None, None) => String::new(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
(Value::Array(expected), Value::Array(actual)) if expected.len() == actual.len() => expected
|
||||
.iter()
|
||||
.zip(actual)
|
||||
.enumerate()
|
||||
.map(|(index, (expected, actual))| json_diff(expected, actual, &format!("{path}[{index}]")))
|
||||
.collect(),
|
||||
_ if expected == actual => String::new(),
|
||||
_ => format!("{path}: expected {expected}\n{path}: actual {actual}\n"),
|
||||
}
|
||||
}
|
||||
|
||||
fn rectangle_template() -> NodeTemplate {
|
||||
crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
|
||||
.expect("rectangle definition")
|
||||
.default_node_template()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_metadata_edits_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.set_display_name(&group, "Renamed".to_string(), &[]);
|
||||
network_interface.set_locked(&group, &[], true);
|
||||
network_interface.set_pinned(&group, &[], true);
|
||||
network_interface.set_visibility(&group, &[], false);
|
||||
network_interface.shift_node(&group, glam::IVec2::new(3, 5), &[]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_an_arity_change_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
editor
|
||||
.active_document_mut()
|
||||
.network_interface
|
||||
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_a_node_insertion_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17A), rectangle_template(), &[]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_a_node_insertion_inside_a_group_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17B), rectangle_template(), &[group]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_a_new_instance_of_a_shared_network_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
insert_shared_copy(editor, group);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_an_edit_inside_a_shared_network_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
insert_shared_copy(editor, group);
|
||||
editor
|
||||
.active_document_mut()
|
||||
.network_interface
|
||||
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_a_group_removal_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
editor.active_document_mut().network_interface.delete_nodes(vec![group], true, &[]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_an_implementation_swap_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
let Some(mut cursor) = interface.node_mut(super::NodeLocator::new(group, &[])) else {
|
||||
panic!("the group should resolve")
|
||||
};
|
||||
cursor.replace_implementation(graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_an_input_value_edit_reproduces_the_interface() {
|
||||
assert_remote_reconcile_reproduces(|editor| {
|
||||
let group = only_group(editor);
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
let (inner, index) = interface
|
||||
.nested_network(&[group])
|
||||
.expect("the group's network")
|
||||
.nodes
|
||||
.iter()
|
||||
.find_map(|(id, node)| Some((*id, node.inputs.iter().position(|input| input.as_value().is_some())?)))
|
||||
.expect("a node with a value input inside the group");
|
||||
interface.set_input(&InputConnector::node_at_index(inner, index), NodeInput::value(TaggedValue::Number(42.), false), &[group]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reconciling_an_untouched_node_changes_nothing() {
|
||||
use document_graph_storage::Touched;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
|
||||
|
||||
let baseline = conversion(&editor);
|
||||
let mut touched = Touched::default();
|
||||
touched.nodes.extend(baseline.registry.node_instances.keys().copied());
|
||||
touched.networks.extend(baseline.registry.networks.keys().copied());
|
||||
|
||||
let before = editor.active_document().network_interface.clone();
|
||||
let reconciled = editor
|
||||
.active_document_mut()
|
||||
.network_interface
|
||||
.reconcile_remote(&baseline.registry, &baseline.declarations, &baseline.blob_bytes, &touched, PEER)
|
||||
.expect("reconcile");
|
||||
|
||||
assert!(reconciled.networks.is_empty(), "nothing differed, so nothing should have been applied: {:?}", reconciled.networks);
|
||||
assert_eq!(editor.active_document().network_interface, before);
|
||||
}
|
||||
|
||||
/// A `ui::` key the registry already holds as deleted is not cleared again on every snapshot.
|
||||
#[test]
|
||||
fn a_deleted_ui_key_is_not_cleared_again() {
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
use super::resolved_types::TypeSource;
|
||||
use super::*;
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::vector::style::Gradient;
|
||||
use graphene_std::{Color, Graphic};
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
/// The top left corner of a node in node graph grid coordinates.
|
||||
@@ -1080,10 +1085,82 @@ impl NodeNetworkInterface {
|
||||
self.take_over_outward_wires(layer.to_node(), network_path);
|
||||
}
|
||||
self.unload_upstream_node_click_targets(vec![layer.to_node()], network_path);
|
||||
self.push_stacks_below_ancestors_past_their_content(layer.to_node(), network_path);
|
||||
|
||||
self.remove_orphaned_dots(network_path);
|
||||
}
|
||||
|
||||
/// Moves the layers stacked below each layer that `layer` is nested within down past that layer's grown content.
|
||||
fn push_stacks_below_ancestors_past_their_content(&mut self, layer: NodeId, network_path: &[NodeId]) {
|
||||
let mut visited = HashSet::new();
|
||||
let mut ancestor = self.content_parent(layer, network_path, &mut visited);
|
||||
while let Some(parent) = ancestor {
|
||||
let stack_below = self
|
||||
.input_from_connector(&InputConnector::primary_input(parent), network_path)
|
||||
.and_then(NodeInput::as_node)
|
||||
.filter(|stack_below| self.is_layer(stack_below, network_path));
|
||||
if let (Some(stack_below), Some(parent_position)) = (stack_below, self.position(&parent, network_path))
|
||||
&& let Some(stack_below_position) = self.position(&stack_below, network_path)
|
||||
{
|
||||
let content_bottom_row = self
|
||||
.upstream_nodes_below_layer(&parent, network_path)
|
||||
.iter()
|
||||
.filter_map(|node_id| self.stacked_box_rows(node_id, network_path))
|
||||
.map(|(_, bottom)| bottom)
|
||||
.fold(parent_position.y + STACK_VERTICAL_GAP, i32::max);
|
||||
if content_bottom_row > stack_below_position.y {
|
||||
self.shift_stack_down(stack_below, content_bottom_row - stack_below_position.y, network_path);
|
||||
}
|
||||
}
|
||||
ancestor = self.content_parent(parent, network_path, &mut visited);
|
||||
}
|
||||
}
|
||||
|
||||
/// Shifts a stack of layers down by `rows`, along with the absolutely positioned content they own, which would otherwise stay behind.
|
||||
fn shift_stack_down(&mut self, stack_top: NodeId, rows: i32, network_path: &[NodeId]) {
|
||||
let stack = self
|
||||
.upstream_flow_back_from_nodes(vec![stack_top], network_path, FlowType::PrimaryFlow)
|
||||
.take_while(|node_id| self.is_layer(node_id, network_path))
|
||||
.collect::<Vec<_>>();
|
||||
let absolute_content = stack
|
||||
.iter()
|
||||
.flat_map(|layer| self.upstream_nodes_below_layer(layer, network_path))
|
||||
.filter(|node_id| self.is_absolute(node_id, network_path))
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
self.shift_node(&stack_top, IVec2::new(0, rows), network_path);
|
||||
for node_id in absolute_content {
|
||||
self.shift_node(&node_id, IVec2::new(0, rows), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer whose content holds the stack `layer` is part of, reached through any chain nodes feeding that layer.
|
||||
/// `visited` stops the walk on a cyclic graph, which concurrent edits can produce.
|
||||
fn content_parent(&self, layer: NodeId, network_path: &[NodeId], visited: &mut HashSet<NodeId>) -> Option<NodeId> {
|
||||
let mut current = layer;
|
||||
while visited.insert(current) {
|
||||
let consumers = self.with_outward_wires(network_path, |outward_wires| outward_wires.get(&OutputConnector::primary_output(current)).cloned())??;
|
||||
|
||||
let mut layer_stacked_upon = None;
|
||||
for consumer in consumers {
|
||||
let Some(consumer_node) = consumer.node_id() else { continue };
|
||||
if !self.is_layer(&consumer_node, network_path) {
|
||||
if self.is_chain(&consumer_node, network_path) {
|
||||
return self.downstream_layer_for_chain_node(&consumer_node, network_path);
|
||||
}
|
||||
} else if consumer.input_index() == 0 {
|
||||
layer_stacked_upon = Some(consumer_node);
|
||||
} else {
|
||||
return Some(consumer_node);
|
||||
}
|
||||
}
|
||||
current = layer_stacked_upon?;
|
||||
}
|
||||
|
||||
log::error!("Cycle reached while finding the content parent of layer {layer}");
|
||||
None
|
||||
}
|
||||
|
||||
/// Shifts `upstream_node_id` and everything stacked below it down until a layer needing
|
||||
/// `height_above` rows above it and `height_below` below fits between it and `post_layer_position`.
|
||||
///
|
||||
@@ -1155,6 +1232,41 @@ impl NodeNetworkInterface {
|
||||
self.create_wire(&upstream_output, &InputConnector::node_at_index(*node_id, insert_node_input_index), network_path);
|
||||
}
|
||||
|
||||
/// Feeds an unconnected Map node's mapped input with the Read node matching the element type of its content.
|
||||
pub fn connect_read_node_to_map(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||
if self.reference(node_id, network_path) != Some(DefinitionIdentifier::ProtoNode(graphene_std::graphic::map::IDENTIFIER)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let mapped_input = InputConnector::node_at_index(*node_id, 1);
|
||||
if !matches!(self.input_from_connector(&mapped_input, network_path), Some(NodeInput::Value { .. })) {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(content_source) = self.upstream_output_connector(&InputConnector::primary_input(*node_id), network_path) else {
|
||||
return;
|
||||
};
|
||||
let Some(mut read_node_template) = read_node_for_content(&self.output_type(&content_source, network_path))
|
||||
.and_then(resolve_proto_node_type)
|
||||
.map(|definition| definition.default_node_template())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(map_position) = self.position(node_id, network_path) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let below_content_source = content_source
|
||||
.node_id()
|
||||
.and_then(|source| Some(self.position(&source, network_path)?.y + self.node_height(&source, network_path) as i32 + 1));
|
||||
let read_node_position = IVec2::new(map_position.x - NODE_CHAIN_WIDTH, below_content_source.unwrap_or(map_position.y + 2));
|
||||
read_node_template.node_type_metadata = NodeTypePersistentMetadata::node(read_node_position);
|
||||
|
||||
let read_node_id = NodeId::new();
|
||||
self.insert_node(read_node_id, read_node_template, network_path);
|
||||
self.create_wire(&OutputConnector::primary_output(read_node_id), &mapped_input, network_path);
|
||||
}
|
||||
|
||||
/// Inserts the freshly-created `node_id` onto the wire feeding `input_connector`: the previous upstream becomes the
|
||||
/// new node's primary (index 0) input, and the new node feeds `input_connector`.
|
||||
///
|
||||
@@ -1575,3 +1687,30 @@ impl NodeNetworkInterface {
|
||||
self.layer_chain(layer, network_path) == intended_chain
|
||||
}
|
||||
}
|
||||
|
||||
/// The Read node yielding each element of a Map node's content, unbundling a whole-list `Item<Bundle<T>>` wire to its `T`.
|
||||
pub(super) fn read_node_for_content(content_type: &TypeSource) -> Option<ProtoNodeIdentifier> {
|
||||
use graphene_std::context::{read_color, read_gradient, read_graphic, read_number, read_raster, read_vector};
|
||||
use graphene_std::text_nodes::read_string;
|
||||
|
||||
let bundle_element = content_type.compiled_nested_type().and_then(Type::bundle_element_name);
|
||||
let element_type = content_type.compiled_element_type()?;
|
||||
|
||||
[
|
||||
(concrete!(Vector), read_vector::IDENTIFIER),
|
||||
(concrete!(Graphic), read_graphic::IDENTIFIER),
|
||||
(concrete!(Raster<CPU>), read_raster::IDENTIFIER),
|
||||
(concrete!(Color), read_color::IDENTIFIER),
|
||||
(concrete!(Gradient), read_gradient::IDENTIFIER),
|
||||
(concrete!(f64), read_number::IDENTIFIER),
|
||||
(concrete!(String), read_string::IDENTIFIER),
|
||||
]
|
||||
.into_iter()
|
||||
.find_map(|(candidate, read_node)| {
|
||||
let matches = match (bundle_element, &candidate) {
|
||||
(Some(bundle_element), Type::Concrete(descriptor)) => descriptor.name == bundle_element,
|
||||
_ => candidate == *element_type,
|
||||
};
|
||||
matches.then_some(read_node)
|
||||
})
|
||||
}
|
||||
@@ -1408,8 +1408,10 @@ impl NodeNetworkInterface {
|
||||
let primary_output = RootNode { node_id: toggle_id, output_index: 0 };
|
||||
let previewing = if self.previewing(network_path).previews(toggle_id) || self.root_node(network_path) == Some(primary_output) {
|
||||
Previewing::No
|
||||
} else {
|
||||
} else if self.number_of_outputs(&toggle_id, network_path) > 0 {
|
||||
Previewing::Yes { previewed: primary_output }
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
self.set_previewing(previewing, network_path);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
//! Updates the interface from the registry for the entities peers touched, through `EditorDelta`s it doesn't record.
|
||||
//! The touched set may be too large. An unchanged entity compares equal and emits nothing.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
use document_graph_storage::blob::BlobBytes;
|
||||
use document_graph_storage::to_runtime::ConversionError;
|
||||
use document_graph_storage::{Declarations, NetworkId as StorageNetworkId, NodeId as StorageNodeId, Registry, RuntimeProjection, Touched};
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkId, NetworkLocation, NodeId, NodeInput, NodeNetwork};
|
||||
use graph_craft::runtime_delta::RuntimeDelta;
|
||||
|
||||
use super::storage_metadata::{InterfaceRebuildError, input_metadata_entry_to_runtime, node_metadata_from_projection};
|
||||
use super::{DocumentNodePersistentMetadata, EditorDelta, NetworkMetadataChange, NodeMetadataChange, NodeNetworkInterface};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ReconcileError {
|
||||
/// A declaration the touched nodes need is not cached yet.
|
||||
#[error("waiting for proto-node declaration {0}")]
|
||||
DeclarationMissing(document_graph_storage::ResourceId),
|
||||
#[error("the interface lacks the network at {0:?} that the registry places a node in")]
|
||||
NetworkMissing(NetworkLocation),
|
||||
/// No delta writes a held network's scope injections.
|
||||
#[error("the scope injections of the network at {0:?} changed")]
|
||||
ScopeInjectionsChanged(NetworkLocation),
|
||||
#[error(transparent)]
|
||||
Conversion(ConversionError),
|
||||
#[error(transparent)]
|
||||
Metadata(#[from] InterfaceRebuildError),
|
||||
}
|
||||
|
||||
impl From<ConversionError> for ReconcileError {
|
||||
fn from(error: ConversionError) -> Self {
|
||||
match error {
|
||||
ConversionError::DeclarationNotFound(id) => Self::DeclarationMissing(id),
|
||||
other => Self::Conversion(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Reconciled {
|
||||
pub networks: BTreeSet<NetworkLocation>,
|
||||
}
|
||||
|
||||
type StorageIndex = HashMap<StorageNodeId, (NetworkLocation, NodeId)>;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
/// Applies what the registry holds differently for the touched entities. Can fail part-way, and a retry is safe.
|
||||
pub(crate) fn reconcile_remote(
|
||||
&mut self,
|
||||
registry: &Registry,
|
||||
declarations: &Declarations,
|
||||
blobs: &BlobBytes,
|
||||
touched: &Touched,
|
||||
peer: document_graph_storage::PeerId,
|
||||
) -> Result<Reconciled, ReconcileError> {
|
||||
let projection = registry.runtime_projection(declarations, blobs);
|
||||
let index = self.pin_storage_identities(peer);
|
||||
let mut reconciled = Reconciled::default();
|
||||
|
||||
let mut nodes = touched.nodes.clone();
|
||||
let mut networks = touched.networks.clone();
|
||||
networks.extend(nodes.iter().filter_map(|&node| projection.implemented_network(node)));
|
||||
self.add_newly_reached_networks(&projection, &mut nodes, &mut networks, &mut reconciled)?;
|
||||
|
||||
let mut items: Vec<(NetworkLocation, NodeId, StorageNodeId)> = nodes
|
||||
.into_iter()
|
||||
.filter_map(|id| {
|
||||
let (location, local_id) = projection.node_address(id).or_else(|| index.get(&id).copied())?;
|
||||
Some((location, local_id, id))
|
||||
})
|
||||
.collect();
|
||||
items.sort();
|
||||
for (location, local_id, id) in items {
|
||||
self.reconcile_node(&projection, &index, location, local_id, id, &mut reconciled)?;
|
||||
}
|
||||
|
||||
for &network in &networks {
|
||||
if projection.network_location(network).is_some() {
|
||||
self.reconcile_network(&projection, network, &mut reconciled)?;
|
||||
}
|
||||
}
|
||||
self.remove_unreached_networks(&projection, &mut reconciled);
|
||||
|
||||
Ok(reconciled)
|
||||
}
|
||||
|
||||
/// Adds each table entry the touched entities newly reach, and queues everything under it as touched.
|
||||
fn add_newly_reached_networks(
|
||||
&mut self,
|
||||
projection: &RuntimeProjection,
|
||||
nodes: &mut BTreeSet<StorageNodeId>,
|
||||
networks: &mut BTreeSet<StorageNetworkId>,
|
||||
reconciled: &mut Reconciled,
|
||||
) -> Result<(), ReconcileError> {
|
||||
let mut pending: Vec<StorageNetworkId> = networks.iter().copied().collect();
|
||||
while let Some(network) = pending.pop() {
|
||||
let Some(location) = projection.network_location(network) else { continue };
|
||||
let Some(id) = location else { continue };
|
||||
if self.holds_network(location) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let target = projection.network_entry(network)?;
|
||||
let added = NodeNetwork {
|
||||
exports: target.exports,
|
||||
scope_injections: target.scope_injections,
|
||||
..Default::default()
|
||||
};
|
||||
self.apply_reconciled(location, vec![EditorDelta::Graph(RuntimeDelta::AddNetwork { id, network: Box::new(added) })], reconciled);
|
||||
|
||||
networks.insert(network);
|
||||
for node in projection.network_nodes(network) {
|
||||
nodes.insert(node);
|
||||
pending.extend(projection.implemented_network(node));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_unreached_networks(&mut self, projection: &RuntimeProjection, reconciled: &mut Reconciled) {
|
||||
let reached: BTreeSet<NetworkId> = projection.definitions().collect();
|
||||
let unreached: Vec<NetworkId> = self.document_network().definitions.keys().copied().filter(|id| !reached.contains(id)).collect();
|
||||
for id in unreached {
|
||||
self.apply_reconciled(Some(id), vec![EditorDelta::Graph(RuntimeDelta::RemoveNetwork { id })], reconciled);
|
||||
}
|
||||
}
|
||||
|
||||
fn reconcile_network(&mut self, projection: &RuntimeProjection, network: StorageNetworkId, reconciled: &mut Reconciled) -> Result<(), ReconcileError> {
|
||||
let target = projection.network_entry(network)?;
|
||||
let location = target.network;
|
||||
let (Some(current), Some(current_metadata)) = (
|
||||
self.document_network().located_network(location),
|
||||
self.network_metadata.nested_metadata(location).map(|metadata| &metadata.persistent_metadata),
|
||||
) else {
|
||||
return Err(ReconcileError::NetworkMissing(location));
|
||||
};
|
||||
if current.scope_injections != target.scope_injections {
|
||||
return Err(ReconcileError::ScopeInjectionsChanged(location));
|
||||
}
|
||||
|
||||
let mut deltas = Vec::new();
|
||||
export_deltas(location, ¤t.exports, &target.exports, &mut deltas);
|
||||
// An export slot write resizes the names and descriptions, so restate them
|
||||
let resized = current.exports.len() != target.exports.len();
|
||||
|
||||
let change = |change| EditorDelta::NetworkMetadata { network: location, change };
|
||||
if current_metadata.reference != target.metadata.reference {
|
||||
deltas.push(change(NetworkMetadataChange::Reference(target.metadata.reference.clone())));
|
||||
}
|
||||
if current_metadata.pinned_node_order != target.metadata.pinned_order {
|
||||
deltas.push(change(NetworkMetadataChange::PinnedOrder(target.metadata.pinned_order.clone())));
|
||||
}
|
||||
// An empty list states nothing, since an older document keeps its interface on the instances
|
||||
let import_metadata: Vec<_> = target.metadata.import_metadata.iter().cloned().map(input_metadata_entry_to_runtime).collect();
|
||||
if !import_metadata.is_empty() && current_metadata.import_metadata != import_metadata {
|
||||
deltas.push(change(NetworkMetadataChange::ImportMetadata(import_metadata)));
|
||||
}
|
||||
if !target.metadata.export_names.is_empty() && (resized || current_metadata.export_names != target.metadata.export_names) {
|
||||
deltas.push(change(NetworkMetadataChange::ExportNames(target.metadata.export_names.clone())));
|
||||
}
|
||||
if !target.metadata.export_names.is_empty() && (resized || current_metadata.export_descriptions != target.metadata.export_descriptions) {
|
||||
deltas.push(change(NetworkMetadataChange::ExportDescriptions(target.metadata.export_descriptions.clone())));
|
||||
}
|
||||
|
||||
self.apply_reconciled(location, deltas, reconciled);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reconcile_node(
|
||||
&mut self,
|
||||
projection: &RuntimeProjection,
|
||||
index: &StorageIndex,
|
||||
location: NetworkLocation,
|
||||
local_id: NodeId,
|
||||
id: StorageNodeId,
|
||||
reconciled: &mut Reconciled,
|
||||
) -> Result<(), ReconcileError> {
|
||||
// A copy held under another id or in another network goes first
|
||||
if let Some(&(held_location, held_id)) = index.get(&id)
|
||||
&& (held_location != location || held_id != local_id)
|
||||
&& self.holds_node(held_location, held_id)
|
||||
{
|
||||
self.apply_reconciled(held_location, vec![remove_node(held_location, held_id)], reconciled);
|
||||
}
|
||||
|
||||
let stored = projection.node_address(id).is_some();
|
||||
match (stored, self.holds_node(location, local_id)) {
|
||||
(false, false) => {}
|
||||
(false, true) => self.apply_reconciled(location, vec![remove_node(location, local_id)], reconciled),
|
||||
(true, false) => {
|
||||
if !self.holds_network(location) {
|
||||
return Err(ReconcileError::NetworkMissing(location));
|
||||
}
|
||||
let (node, metadata) = node_metadata_from_projection(projection.node(id)?)?;
|
||||
let deltas = vec![
|
||||
EditorDelta::Graph(RuntimeDelta::AddNode {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
node: Box::new(node),
|
||||
}),
|
||||
EditorDelta::NodeMetadataSnapshot {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
metadata: Box::new(metadata),
|
||||
},
|
||||
];
|
||||
self.apply_reconciled(location, deltas, reconciled);
|
||||
}
|
||||
(true, true) => {
|
||||
let (node, metadata) = node_metadata_from_projection(projection.node(id)?)?;
|
||||
self.diff_node(location, local_id, node, metadata, reconciled);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn diff_node(&mut self, location: NetworkLocation, local_id: NodeId, target: DocumentNode, target_metadata: DocumentNodePersistentMetadata, reconciled: &mut Reconciled) {
|
||||
let Some(current) = self.document_network().located_network(location).and_then(|network| network.nodes.get(&local_id)) else {
|
||||
return;
|
||||
};
|
||||
let Some(current_metadata) = self
|
||||
.network_metadata
|
||||
.nested_metadata(location)
|
||||
.and_then(|network| network.persistent_metadata.node_metadata.get(&local_id))
|
||||
.map(|node| &node.persistent_metadata)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let deltas = if current.implementation == target.implementation && current.skip_deduplication == target.skip_deduplication {
|
||||
field_deltas(location, local_id, (current, current_metadata), (&target, &target_metadata))
|
||||
} else {
|
||||
vec![
|
||||
EditorDelta::Graph(RuntimeDelta::ReplaceNode {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
node: Box::new(target),
|
||||
}),
|
||||
EditorDelta::NodeMetadataSnapshot {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
metadata: Box::new(target_metadata),
|
||||
},
|
||||
]
|
||||
};
|
||||
self.apply_reconciled(location, deltas, reconciled);
|
||||
}
|
||||
|
||||
fn apply_reconciled(&mut self, location: NetworkLocation, deltas: Vec<EditorDelta>, reconciled: &mut Reconciled) {
|
||||
if deltas.is_empty() {
|
||||
return;
|
||||
}
|
||||
for delta in &deltas {
|
||||
self.apply(delta);
|
||||
}
|
||||
reconciled.networks.insert(location);
|
||||
}
|
||||
|
||||
/// Every document path to one of `locations`. A shared network has one per instance.
|
||||
pub(crate) fn paths_reaching(&self, locations: &BTreeSet<NetworkLocation>) -> Vec<Vec<NodeId>> {
|
||||
let root = self.document_network();
|
||||
let mut paths = Vec::new();
|
||||
let mut pending = vec![(Vec::new(), root)];
|
||||
while let Some((path, network)) = pending.pop() {
|
||||
for (&node_id, node) in &network.nodes {
|
||||
if let Some(nested) = root.implementation_network(&node.implementation) {
|
||||
pending.push(([path.as_slice(), &[node_id]].concat(), nested));
|
||||
}
|
||||
}
|
||||
if root.locate(&path).is_some_and(|location| locations.contains(&location)) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
fn holds_node(&self, location: NetworkLocation, local_id: NodeId) -> bool {
|
||||
self.document_network().located_network(location).is_some_and(|network| network.nodes.contains_key(&local_id))
|
||||
&& self
|
||||
.network_metadata
|
||||
.nested_metadata(location)
|
||||
.is_some_and(|network| network.persistent_metadata.node_metadata.contains_key(&local_id))
|
||||
}
|
||||
|
||||
fn holds_network(&self, location: NetworkLocation) -> bool {
|
||||
self.document_network().located_network(location).is_some() && self.network_metadata.nested_metadata(location).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
fn field_deltas(
|
||||
location: NetworkLocation,
|
||||
local_id: NodeId,
|
||||
(current, current_metadata): (&DocumentNode, &DocumentNodePersistentMetadata),
|
||||
(target, target_metadata): (&DocumentNode, &DocumentNodePersistentMetadata),
|
||||
) -> Vec<EditorDelta> {
|
||||
let mut deltas = Vec::new();
|
||||
let metadata = |change: NodeMetadataChange| EditorDelta::NodeMetadata {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
change,
|
||||
};
|
||||
let input_metadata = || EditorDelta::NodeInputMetadata {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
input_metadata: target_metadata.input_metadata.clone(),
|
||||
};
|
||||
|
||||
// An instance's input metadata belongs to its implementing network
|
||||
let instance = matches!(target.implementation, DocumentNodeImplementation::Definition(_));
|
||||
|
||||
// Slots first, so the metadata indexing them finds the right length
|
||||
if current.inputs.len() != target.inputs.len() {
|
||||
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInputs {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
inputs: target.inputs.clone(),
|
||||
}));
|
||||
if !instance {
|
||||
deltas.push(input_metadata());
|
||||
}
|
||||
} else {
|
||||
for (input_index, (held, wanted)) in current.inputs.iter().zip(&target.inputs).enumerate() {
|
||||
if held != wanted {
|
||||
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInput {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
input_index,
|
||||
input: wanted.clone(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
if !instance && current_metadata.input_metadata != target_metadata.input_metadata {
|
||||
deltas.push(input_metadata());
|
||||
}
|
||||
}
|
||||
|
||||
if current.visible != target.visible {
|
||||
deltas.push(EditorDelta::Graph(RuntimeDelta::SetVisibility {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
visible: target.visible,
|
||||
}));
|
||||
}
|
||||
if current.call_argument != target.call_argument {
|
||||
deltas.push(EditorDelta::Graph(RuntimeDelta::SetCallArgument {
|
||||
network: location,
|
||||
node_id: local_id,
|
||||
call_argument: target.call_argument.clone(),
|
||||
}));
|
||||
}
|
||||
|
||||
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
|
||||
deltas.push(metadata(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone())));
|
||||
}
|
||||
if current_metadata.display_name != target_metadata.display_name {
|
||||
deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
|
||||
}
|
||||
if current_metadata.locked != target_metadata.locked {
|
||||
deltas.push(metadata(NodeMetadataChange::Locked(target_metadata.locked)));
|
||||
}
|
||||
if current_metadata.pinned != target_metadata.pinned {
|
||||
deltas.push(metadata(NodeMetadataChange::Pinned(target_metadata.pinned)));
|
||||
}
|
||||
if current_metadata.output_names != target_metadata.output_names {
|
||||
deltas.push(metadata(NodeMetadataChange::OutputNames(target_metadata.output_names.clone())));
|
||||
}
|
||||
if current_metadata.output_descriptions != target_metadata.output_descriptions {
|
||||
deltas.push(metadata(NodeMetadataChange::OutputDescriptions(target_metadata.output_descriptions.clone())));
|
||||
}
|
||||
|
||||
deltas
|
||||
}
|
||||
|
||||
fn remove_node(location: NetworkLocation, local_id: NodeId) -> EditorDelta {
|
||||
EditorDelta::Graph(RuntimeDelta::RemoveNode { network: location, node_id: local_id })
|
||||
}
|
||||
|
||||
fn export_deltas(location: NetworkLocation, current: &[NodeInput], target: &[NodeInput], deltas: &mut Vec<EditorDelta>) {
|
||||
let set_export = |export_index, input| {
|
||||
EditorDelta::Graph(RuntimeDelta::SetExport {
|
||||
network: location,
|
||||
export_index,
|
||||
input,
|
||||
})
|
||||
};
|
||||
let changed = target.iter().enumerate().filter(|&(export_index, input)| current.get(export_index) != Some(input));
|
||||
deltas.extend(changed.map(|(export_index, input)| set_export(export_index, Some(input.clone()))));
|
||||
deltas.extend((target.len()..current.len()).map(|_| set_export(target.len(), None)));
|
||||
}
|
||||
+17
-1
@@ -10,6 +10,7 @@ use interpreted_executor::dynamic_executor::{NodeTypes, ResolvedDocumentNodeType
|
||||
use interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
|
||||
@@ -328,8 +329,10 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
|
||||
// A List-typed default drops to its Item counterpart (when that has a default value and the connector accepts rank 0),
|
||||
// since a stored Item default can promote back onto a List connector but a stored List default can never return to rank 0
|
||||
// since a stored Item default can promote back onto a List connector but a stored List default can never return to rank 0.
|
||||
// An input whose definition defaults to a list keeps the empty list, since promoting an Item default would leave it a placeholder element.
|
||||
if let Some(element) = guaranteed_type.nested_type().list_element()
|
||||
&& !self.definition_defaults_to_list(input_connector, network_path)
|
||||
&& let Some(item_type) = self
|
||||
.potential_valid_input_types(input_connector, network_path)
|
||||
.into_iter()
|
||||
@@ -342,6 +345,19 @@ impl NodeNetworkInterface {
|
||||
TaggedValue::from_type_or_none(&guaranteed_type)
|
||||
}
|
||||
|
||||
/// Whether the definition of the node owning this input gives it a list as its default value.
|
||||
fn definition_defaults_to_list(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> bool {
|
||||
let InputConnector::Node { node_id, input_index } = input_connector else { return false };
|
||||
let Some(definition) = self.reference(node_id, network_path).as_ref().and_then(resolve_document_node_type) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
matches!(
|
||||
definition.node_template.inputs.get(*input_index),
|
||||
Some(NodeInput::Value { tagged_value, .. }) if matches!(tagged_value.ty().nested_type(), Type::List(_))
|
||||
)
|
||||
}
|
||||
|
||||
/// A list of all valid input types for this specific node.
|
||||
pub fn potential_valid_input_types(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Vec<Type> {
|
||||
let InputConnector::Node { node_id, input_index } = input_connector else {
|
||||
|
||||
+24
-2
@@ -10,7 +10,7 @@ use std::collections::{BTreeMap, HashMap};
|
||||
use document_graph_storage::attr::session;
|
||||
use document_graph_storage::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry, NodeMetadataSource, Position, Value, from_value, to_value};
|
||||
use glam::IVec2;
|
||||
use graph_craft::document::{NetworkLocation, NodeId, NodeNetwork};
|
||||
use graph_craft::document::{DocumentNodeImplementation, NetworkLocation, NodeId, NodeNetwork};
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
|
||||
use super::{
|
||||
@@ -210,6 +210,28 @@ pub fn build_interface_from_storage(network: NodeNetwork, node_entries: Vec<Node
|
||||
Ok(NodeNetworkInterface::from_trees(network, network_metadata))
|
||||
}
|
||||
|
||||
/// The node and its metadata from a single-node projection, patched like a whole rebuild's entry.
|
||||
pub(super) fn node_metadata_from_projection(projected: document_graph_storage::ProjectedNode) -> Result<(graph_craft::document::DocumentNode, DocumentNodePersistentMetadata), InterfaceRebuildError> {
|
||||
let document_graph_storage::ProjectedNode { local_id, node, metadata: entry, .. } = projected;
|
||||
|
||||
let entry = NodeMetadataEntry { network: None, ..entry };
|
||||
|
||||
let mut scratch = NodeNetwork::default();
|
||||
scratch.nodes.insert(local_id, node);
|
||||
let mut metadata = NodeNetworkMetadata::default();
|
||||
seed_metadata_tree(&scratch, &mut metadata);
|
||||
apply_entries_into_tree(&scratch, &mut metadata, vec![entry])?;
|
||||
|
||||
let mut persistent = metadata.persistent_metadata.node_metadata.remove(&local_id).map(|node| node.persistent_metadata).unwrap_or_default();
|
||||
let node = scratch.nodes.remove(&local_id).expect("inserted above");
|
||||
if matches!(node.implementation, DocumentNodeImplementation::Definition(_)) {
|
||||
persistent.input_metadata.clear();
|
||||
persistent.output_names.clear();
|
||||
persistent.output_descriptions.clear();
|
||||
}
|
||||
Ok((node, persistent))
|
||||
}
|
||||
|
||||
/// Maps each runtime network location to its stable `NetworkId`, from the entries `to_runtime_with_full_metadata` returns.
|
||||
pub fn network_ids_from_entries(network_entries: &[NetworkMetadataEntry]) -> HashMap<NetworkLocation, document_graph_storage::NetworkId> {
|
||||
network_entries.iter().map(|entry| (entry.network, entry.network_id)).collect()
|
||||
@@ -423,7 +445,7 @@ pub(super) fn input_metadata_entry_from_runtime(input_metadata: &InputMetadata)
|
||||
}
|
||||
|
||||
/// Storage-side `None` restores as `""` (the runtime's "unset" sentinel for `input_name` / `input_description`).
|
||||
fn input_metadata_entry_to_runtime(entry: InputMetadataEntry) -> InputMetadata {
|
||||
pub(super) fn input_metadata_entry_to_runtime(entry: InputMetadataEntry) -> InputMetadata {
|
||||
InputMetadata {
|
||||
persistent_metadata: InputPersistentMetadata {
|
||||
input_name: entry.input_name.unwrap_or_default(),
|
||||
|
||||
+48
-1
@@ -567,9 +567,11 @@ impl NodeNetworkInterface {
|
||||
return false;
|
||||
};
|
||||
let Some(network) = self.document_network().definitions.get(&id).cloned() else { return false };
|
||||
let Some(metadata) = self.network_metadata.persistent_metadata.definitions.get(&id).cloned() else {
|
||||
let Some(mut metadata) = self.network_metadata.persistent_metadata.definitions.get(&id).cloned() else {
|
||||
return false;
|
||||
};
|
||||
// The copy's nodes are new and can't keep the originals' storage identities
|
||||
clear_storage_ids(&mut metadata.persistent_metadata);
|
||||
|
||||
let unique = NetworkId::new();
|
||||
self.insert_definition(unique, network, metadata);
|
||||
@@ -658,6 +660,42 @@ impl NodeNetworkInterface {
|
||||
self.dots_that_lost_a_wire.clear();
|
||||
}
|
||||
|
||||
/// Pins each unpinned node to the identity a conversion derives from its location, and returns where each identity is held.
|
||||
pub(crate) fn pin_storage_identities(&mut self, peer: document_graph_storage::PeerId) -> HashMap<document_graph_storage::NodeId, (NetworkLocation, NodeId)> {
|
||||
let mut index = HashMap::new();
|
||||
let mut unpinned = Vec::new();
|
||||
{
|
||||
let view = super::storage_metadata::StorageMetadataView::new(self);
|
||||
let resolver = document_graph_storage::PathResolver::new(Some(&view), peer);
|
||||
let definitions = self.network_metadata.persistent_metadata.definitions.iter().map(|(id, metadata)| (Some(*id), metadata));
|
||||
for (location, metadata) in definitions.chain([(None, &*self.network_metadata)]) {
|
||||
for (&local_id, node) in &metadata.persistent_metadata.node_metadata {
|
||||
let storage_id = match node.persistent_metadata.storage_id {
|
||||
Some(pinned) => document_graph_storage::NodeId(pinned),
|
||||
None => {
|
||||
let derived = resolver.node_id(location, local_id);
|
||||
unpinned.push((location, local_id, derived));
|
||||
derived
|
||||
}
|
||||
};
|
||||
index.insert(storage_id, (location, local_id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (location, local_id, storage_id) in unpinned {
|
||||
if let Some(node) = self
|
||||
.network_metadata
|
||||
.get_mut()
|
||||
.nested_metadata_mut(location)
|
||||
.and_then(|network| network.persistent_metadata.node_metadata.get_mut(&local_id))
|
||||
{
|
||||
node.persistent_metadata.storage_id = Some(storage_id.0);
|
||||
}
|
||||
}
|
||||
index
|
||||
}
|
||||
|
||||
/// Records the open transaction's bookkeeping, so writes that are undone before [`Self::restore_transaction_checkpoint`] don't count toward it.
|
||||
pub fn transaction_checkpoint(&mut self) -> TransactionCheckpoint {
|
||||
self.scan_transaction_edited_nodes();
|
||||
@@ -726,6 +764,15 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_storage_ids(metadata: &mut NodeNetworkPersistentMetadata) {
|
||||
for node in metadata.node_metadata.values_mut() {
|
||||
node.persistent_metadata.storage_id = None;
|
||||
if let Some(nested) = &mut node.persistent_metadata.network_metadata {
|
||||
clear_storage_ids(&mut nested.persistent_metadata);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any of `descriptions` says anything, since storage keeps the whole list then, but not a list that's all empty.
|
||||
fn has_description(descriptions: &[String]) -> bool {
|
||||
descriptions.iter().any(|description| !description.is_empty())
|
||||
|
||||
@@ -504,7 +504,7 @@ impl<'de> serde::Deserialize<'de> for Previewing {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two networks' metadata match, ignoring view state.
|
||||
/// Whether two networks' metadata match, ignoring view state and storage identities.
|
||||
pub(crate) fn same_content(first: &NodeNetworkPersistentMetadata, second: &NodeNetworkPersistentMetadata) -> bool {
|
||||
let content = |metadata: &NodeNetworkPersistentMetadata| {
|
||||
let mut content = metadata.clone();
|
||||
@@ -519,6 +519,9 @@ fn clear_view_state(metadata: &mut NodeNetworkPersistentMetadata) {
|
||||
metadata.navigation_metadata = NavigationMetadata::default();
|
||||
metadata.selection_undo_history.clear();
|
||||
metadata.selection_redo_history.clear();
|
||||
for node in metadata.node_metadata.values_mut() {
|
||||
node.persistent_metadata.storage_id = None;
|
||||
}
|
||||
|
||||
let nested_networks = metadata
|
||||
.node_metadata
|
||||
|
||||
@@ -376,6 +376,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_math_nodes::LogicalOrNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::math_function::IDENTIFIER,
|
||||
aliases: &["math_nodes::MathFxNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::max::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::MaxNode", "graphene_core::ops::MaxNode"],
|
||||
@@ -1266,6 +1270,10 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), under.clone(), &network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), over.clone(), &network_path);
|
||||
}
|
||||
|
||||
if *new == graphene_std::math_nodes::math_function::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Math f(x)");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1384,8 +1392,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut definition.default_node_template());
|
||||
}
|
||||
|
||||
// The old "Math" node evaluated an expression over "A" and "B". A lexable static expression not reading a wired `B` becomes "Math f(x)"
|
||||
// with `A` as `x` and a constant `B` inlined. Anything else becomes "Extend" feeding "Math f(…)", which reads the pair as `a` and `b`.
|
||||
// The old "Math" node evaluated an expression over "A" and "B". A lexable static expression not reading a wired `B` becomes "Math Function"
|
||||
// with `A` as `x` and a constant `B` inlined. Anything else becomes "Extend" feeding "Math Formula", which reads the pair as `a` and `b`.
|
||||
let math_nodes: Vec<(NodeId, Vec<NodeId>, Vec<NodeInput>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
@@ -1416,7 +1424,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
})
|
||||
.is_some();
|
||||
|
||||
// The rewritten "Math f(x)" expression, or `None` when only the Extend + "Math f(…)" form can preserve the node's meaning
|
||||
// The rewritten "Math Function" expression, or `None` when only the Extend + "Math Formula" form can preserve the node's meaning
|
||||
let inline_b_constant = match operand_b.as_value() {
|
||||
Some(TaggedValue::Number(constant)) => Some(*constant),
|
||||
_ => None,
|
||||
@@ -1436,8 +1444,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
};
|
||||
|
||||
if let Some(fx_expression) = fx_expression {
|
||||
// "Math f(x)": forward the old `A` input and the rewritten expression; the old `B` input is dropped
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER)) else {
|
||||
// "Math Function": forward the old `A` input and the rewritten expression; the old `B` input is dropped
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_function::IDENTIFIER)) else {
|
||||
continue;
|
||||
};
|
||||
let mut node_template = definition.default_node_template();
|
||||
@@ -1451,7 +1459,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::String(fx_expression), false), network_path);
|
||||
} else {
|
||||
// "Extend" joins the two operands into the list "Math f(…)" reads; an unwired constant operand becomes a one-item list value
|
||||
// "Extend" joins the two operands into the list "Math Formula" reads; an unwired constant operand becomes a one-item list value
|
||||
let as_list_input = |input: &NodeInput| match input.as_value() {
|
||||
Some(TaggedValue::Number(value)) => NodeInput::value(TaggedValue::Numbers(vec![*value]), input.is_exposed()),
|
||||
_ => input.clone(),
|
||||
@@ -1461,7 +1469,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
};
|
||||
let extend_template = extend_definition.default_node_template();
|
||||
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_f::IDENTIFIER)) else {
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_formula::IDENTIFIER)) else {
|
||||
continue;
|
||||
};
|
||||
let mut node_template = definition.default_node_template();
|
||||
@@ -1854,6 +1862,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
|
||||
migrate_assign_colors_nodes(document);
|
||||
migrate_math_f_nodes(document);
|
||||
|
||||
// Last, so the rest of the graph is upgraded enough to compile when each Copy to Points node's content type is resolved
|
||||
migrate_copy_to_points_nodes(document);
|
||||
@@ -1976,10 +1985,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
let mut inputs_count = node.inputs.len();
|
||||
|
||||
// The expression nodes gained an output-type input, a type witness the Inspector edits. A node from before it
|
||||
// takes the definition's default choice, Number, which is the output type every such node had.
|
||||
let expression_node_identifiers = [graphene_std::math_nodes::math_fx::IDENTIFIER, graphene_std::math_nodes::math_f::IDENTIFIER];
|
||||
if expression_node_identifiers.iter().any(|identifier| reference == DefinitionIdentifier::ProtoNode(identifier.clone())) && inputs_count == 2 {
|
||||
// The expression nodes gained an output-type input, a type witness the Inspector edits. A node from before it takes the definition's
|
||||
// default choice, Number, which is the output type every such node had. Math f(…) nodes get it as `migrate_math_f` splits them.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_function::IDENTIFIER) && inputs_count == 2 {
|
||||
let definition = resolve_document_node_type(&reference)?;
|
||||
let mut template = definition.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut template);
|
||||
@@ -3840,6 +3848,46 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
|
||||
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
|
||||
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter(|(_, node, _)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().ends_with("::MathFNode")))
|
||||
.map(|(node_id, _, path)| (*node_id, path))
|
||||
.collect();
|
||||
|
||||
for (node_id, network_path) in math_f_nodes {
|
||||
migrate_math_f(&node_id, &network_path, document);
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuilds a removed Math f(…) node as Math Aggregate if its string was a lone operator or function name it applied across its items, or as
|
||||
/// Math Formula otherwise, including when the string is wired, since a wired string can't be read before it runs.
|
||||
fn migrate_math_f(node_id: &NodeId, network_path: &[NodeId], document: &mut DocumentMessageHandler) -> Option<()> {
|
||||
use graphene_std::math_nodes::{math_aggregate, math_formula};
|
||||
|
||||
let old_node = document.network_interface.document_node(node_id, network_path)?;
|
||||
let applies_operator = matches!(
|
||||
old_node.inputs.get(1).and_then(|input| input.as_value()),
|
||||
Some(TaggedValue::String(expression)) if math_parser::reducer::classify_reducer(expression, math_parser::context::NothingMap).is_some()
|
||||
);
|
||||
|
||||
let identifier = if applies_operator { math_aggregate::IDENTIFIER } else { math_formula::IDENTIFIER };
|
||||
let mut node_template = resolve_proto_node_type(identifier)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
reset_default_display_name(document, node_id, network_path, "Math f(…)");
|
||||
|
||||
// The items, string, and output type keep their places, where a node from before the output type takes its default, Number
|
||||
for (index, input) in old_inputs.into_iter().enumerate().take(3) {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Splits each removed Assign Colors node into the Vary Fill Colors and Vary Stroke Colors nodes its Fill and Stroke toggles call for.
|
||||
fn migrate_assign_colors_nodes(document: &mut DocumentMessageHandler) {
|
||||
let assign_colors_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
@@ -4556,7 +4604,7 @@ mod tests {
|
||||
document.network_interface.insert_node(
|
||||
node_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_function::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::Number(4.), false), NodeInput::value(TaggedValue::String("x^2".into()), false)],
|
||||
..Default::default()
|
||||
},
|
||||
@@ -4591,7 +4639,7 @@ mod tests {
|
||||
document.network_interface.insert_node(
|
||||
node_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_function::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::Number(4.), false), NodeInput::value(TaggedValue::String("x^2".into()), false)],
|
||||
..Default::default()
|
||||
},
|
||||
@@ -4614,8 +4662,44 @@ mod tests {
|
||||
assert_eq!(outward_wires.as_deref(), Some([InputConnector::node_at_index(node_id, 0)].as_slice()));
|
||||
}
|
||||
|
||||
// The old Math node's expression decides its replacement: a static string that never reads `B` becomes "Math f(x)",
|
||||
// while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math f(…)"
|
||||
// Math f(…) either applied a lone operator across its items or evaluated an expression over them, which are now two nodes
|
||||
#[test]
|
||||
fn math_f_nodes_split_into_aggregate_and_formula() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use graphene_std::math_nodes::{math_aggregate, math_formula};
|
||||
|
||||
let migrated_implementation = |inputs: Vec<NodeInput>| {
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
document.network_interface.insert_node(
|
||||
node_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("math_nodes::MathFNode")),
|
||||
inputs,
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&node_id];
|
||||
assert_eq!(node.inputs.len(), 3, "the output type is kept, or added to a node from before it");
|
||||
match &node.implementation {
|
||||
DocumentNodeImplementation::ProtoNode(identifier) => identifier.clone(),
|
||||
other => panic!("expected a proto node implementation, got {other:?}"),
|
||||
}
|
||||
};
|
||||
let items = || NodeInput::value(TaggedValue::None, false);
|
||||
let expression = |text: &str| NodeInput::value(TaggedValue::String(text.into()), false);
|
||||
let output_type = || NodeInput::value(TaggedValue::Number(0.), false);
|
||||
|
||||
assert_eq!(migrated_implementation(vec![items(), expression(" max "), output_type()]), math_aggregate::IDENTIFIER);
|
||||
assert_eq!(migrated_implementation(vec![items(), expression("+")]), math_aggregate::IDENTIFIER);
|
||||
assert_eq!(migrated_implementation(vec![items(), expression("a * b + c"), output_type()]), math_formula::IDENTIFIER);
|
||||
}
|
||||
|
||||
// The old Math node's expression decides its replacement: a static string that never reads `B` becomes "Math Function",
|
||||
// while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math Formula"
|
||||
#[test]
|
||||
fn old_math_nodes_split_into_the_expression_node_pair() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
@@ -4666,7 +4750,7 @@ mod tests {
|
||||
.expect("an Extend node should be spliced in")
|
||||
};
|
||||
|
||||
// A static expression that never reads `B` becomes "Math f(x)" with `A` renamed to `x` and the `B` input dropped
|
||||
// A static expression that never reads `B` becomes "Math Function" with `A` renamed to `x` and the `B` input dropped
|
||||
{
|
||||
let inputs = vec![
|
||||
NodeInput::node(source_a_id, 0),
|
||||
@@ -4676,7 +4760,7 @@ mod tests {
|
||||
let mut document = build_document("math_nodes::MathNode", inputs);
|
||||
migrate(&mut document);
|
||||
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_function::IDENTIFIER);
|
||||
let node = &document.network_interface.document_network().nodes[&math_id];
|
||||
assert_eq!(
|
||||
node.inputs.len(),
|
||||
@@ -4698,7 +4782,7 @@ mod tests {
|
||||
let mut document = build_document("graphene_core::ops::MathNode", inputs);
|
||||
migrate(&mut document);
|
||||
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_function::IDENTIFIER);
|
||||
let node = &document.network_interface.document_network().nodes[&math_id];
|
||||
assert_eq!(
|
||||
node.inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
@@ -4717,7 +4801,7 @@ mod tests {
|
||||
let mut document = build_document("math_nodes::MathNode", inputs);
|
||||
migrate(&mut document);
|
||||
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::IDENTIFIER);
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_formula::IDENTIFIER);
|
||||
let extend_id = find_extend(&document);
|
||||
let network = document.network_interface.document_network();
|
||||
assert_eq!(network.nodes[&math_id].inputs.first(), Some(&NodeInput::node(extend_id, 0)));
|
||||
@@ -4739,7 +4823,7 @@ mod tests {
|
||||
let mut document = build_document("math_nodes::MathNode", inputs);
|
||||
migrate(&mut document);
|
||||
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::IDENTIFIER);
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_formula::IDENTIFIER);
|
||||
let extend_id = find_extend(&document);
|
||||
let network = document.network_interface.document_network();
|
||||
assert_eq!(network.nodes[&math_id].inputs.get(1), Some(&NodeInput::node(source_expression_id, 0)));
|
||||
|
||||
@@ -11,8 +11,10 @@ use super::document_locks;
|
||||
use super::document_migration::*;
|
||||
use super::portfolio_message::PortfolioMessage;
|
||||
use crate::application::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
|
||||
use crate::messages::dialog::DialogMessage;
|
||||
use crate::messages::message::Message;
|
||||
use crate::messages::portfolio::document::utility_types::misc::DocumentId;
|
||||
use crate::messages::portfolio::sync::SyncMessage;
|
||||
use crate::messages::resource_storage::ResourcesHandle;
|
||||
use document_container::store::{DocumentKey, DocumentStore, MemoryStore};
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
@@ -138,6 +140,30 @@ pub(super) async fn remove_stored_document(store: DocumentStoreHandle, document_
|
||||
Message::NoOp
|
||||
}
|
||||
|
||||
/// Joins the session of a stored document another tab holds, as a document and peer of this tab's own.
|
||||
pub(super) async fn join_stored_session(store: DocumentStoreHandle, source: DocumentId) -> Message {
|
||||
let manifest = async {
|
||||
// Opening a missing key creates it, and the other tab may have closed the document since
|
||||
if !store.list().await.map_err(|error| error.to_string())?.contains(&document_key(source)) {
|
||||
return Err("the other tab closed it".to_string());
|
||||
}
|
||||
let container = store.open(document_key(source)).await.map_err(|error| error.to_string())?;
|
||||
GddV1::read_manifest(&container, &GddV1Layout).await.map_err(|error| error.to_string())
|
||||
}
|
||||
.await;
|
||||
match manifest {
|
||||
Ok(manifest) => SyncMessage::Join {
|
||||
token: peer_transport::SessionToken::for_document(manifest.document_id).to_string(),
|
||||
}
|
||||
.into(),
|
||||
Err(error) => DialogMessage::DisplayDialogError {
|
||||
title: "Failed to join the session".into(),
|
||||
description: format!("The session's document could not be read: {error}"),
|
||||
}
|
||||
.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a copy of a stored document that another tab may be writing. Its fresh manifest id separates it from the original.
|
||||
pub(super) async fn copy_stored_document(store: DocumentStoreHandle, source: DocumentId, document_id: DocumentId, document_name: String, resources: ResourcesHandle, reset_nodes: bool) -> Message {
|
||||
document_locks::claim(document_id).await;
|
||||
@@ -182,12 +208,14 @@ pub(super) async fn copy_stored_document(store: DocumentStoreHandle, source: Doc
|
||||
}
|
||||
|
||||
/// Materializes a `.gdd` archive into a fresh store container and loads it like a stored document.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn open_document_file(
|
||||
store: DocumentStoreHandle,
|
||||
document_id: DocumentId,
|
||||
document_name: Option<String>,
|
||||
document_path: Option<PathBuf>,
|
||||
content: Vec<u8>,
|
||||
fresh_identity: bool,
|
||||
resources: ResourcesHandle,
|
||||
reset_nodes: bool,
|
||||
) -> Message {
|
||||
@@ -198,13 +226,21 @@ pub(super) async fn open_document_file(
|
||||
Ok::<_, String>(container)
|
||||
}
|
||||
.await;
|
||||
let (document, gdd) = match materialized {
|
||||
let (mut document, mut gdd) = match materialized {
|
||||
Ok(container) => load_from_container(container, document_id, &resources, reset_nodes).await,
|
||||
Err(error) => {
|
||||
log::error!("Opening the document archive for {document_id:?} failed: {error}");
|
||||
(None, None)
|
||||
}
|
||||
};
|
||||
// The room derives from the manifest's document id, so a fresh id is a fresh room
|
||||
if fresh_identity
|
||||
&& let Some(storage) = gdd.as_mut().or_else(|| document.as_mut().and_then(|document| document.storage_mut()))
|
||||
&& let Err(error) = storage.update_manifest(|manifest| manifest.document_id = generate_uuid())
|
||||
{
|
||||
log::error!("Giving the copy of {document_id:?} its own id failed: {error}");
|
||||
(document, gdd) = (None, None);
|
||||
}
|
||||
let declarations = load_declarations(gdd.as_ref(), &resources, document_id).await;
|
||||
PortfolioMessage::DocumentFileLoaded {
|
||||
document_id,
|
||||
@@ -340,7 +376,7 @@ async fn build_document_from_storage(gdd: GddV1, byte_store: &ResourcesHandle, d
|
||||
interface.give_diverged_catalog_entries_new_ids();
|
||||
// TODO: Run document upgrades here once this format has a versioned migration
|
||||
|
||||
let mut document = DocumentMessageHandler::from_storage(interface, gdd, declarations, String::new(), None);
|
||||
let mut document = DocumentMessageHandler::from_storage(interface, gdd, declarations, byte_store.storage(), String::new(), None);
|
||||
document.finalize_storage_load();
|
||||
Some(document)
|
||||
}
|
||||
|
||||
Loaded 100 of 285 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user