Compare commits

..
Author SHA1 Message Date
Dennis Kobert 8b38e7100c Resolve blobs for node migrations, send blob deltas to peers, and type blob hashes as BlobHash 2026-11-06 13:48:31 +00:00
Dennis Kobert 54fff8e129 Store large node input values as delta-compressed blobs and migrate existing documents into them 2026-11-06 10:22:50 +00:00
Dennis Kobert 92c5a6a7d0 Implement node input compression test tool 2026-11-03 10:32:42 +00:00
Timon 8206b4cc88 Fix 'Combine Paths' hashing differently across platforms (#4911) 2026-11-02 22:50:39 +00:00
Dennis Kobert b05af55d50 Mint a fresh peer when the user changes (#4889) 2026-11-02 22:53:38 +01:00
Timon 39b8d23a34 Desktop: Confine CEF disk and network more (#4910) 2026-11-02 20:05:09 +00:00
Dennis Kobert 1199d312e4 Compile the definitions table directly instead of inlining it before preprocessing (#4903)
* Compile the definitions table directly instead of inlining it before preprocessing

* Resolve scope inputs against each instance's enclosing scopes, specializing entries whose contexts differ in type
2026-11-02 18:59:22 +01:00
Timon b2cffdfd26 Fix saving leaving the document marked as unsaved on web (#4909) 2026-11-02 17:55:03 +00:00
Timon 6479e0aeba Simplify node graph runtime scheduling (#4907)
* Revert "Limit number of instant graph reevaluations (#4758)"

* Read requests and apply graph updates once per frame
2026-11-02 17:37:00 +00:00
Keavon Chambers bfd85cab6f Replace 'Copy to Points' and 'Assign Colors' with a family of 'Vary' nodes (#4906)
* Replace 'Copy to Points' and 'Assign Colors' with a family of 'Vary' nodes

* Resolve the type of Copy to Points content wired from a secondary output
2026-11-02 14:45:28 +00:00
Dennis Kobert 67e5b899d4 Let migrations choose a target per anchor, ask the compiler, and run on whole states 2026-11-02 14:17:49 +00:00
Dennis Kobert 488c992250 Run headless editor tests on a vulkan software GPU (#4880)
* Run headless editor tests on a software GPU

* Update comment
2026-11-02 10:49:00 +00:00
Keavon Chambers 640aded2b2 Add mipmaps to images so they average their pixels when zoomed out (#4908) 2026-11-02 09:55:45 +00:00
113 changed files with 5654 additions and 1075 deletions

No files matched your search

+1 -13
View File
@@ -237,16 +237,10 @@ jobs:
run: sudo apt-get update && sudo apt-get install --yes mesa-vulkan-drivers
- name: 🖼️ Check the corpus renders against its references
id: corpus
continue-on-error: true
run: cargo run --package regression -- --corpus target/regression-corpus check --output target/regression
- name: ⚠️ Warn about mismatched renders
if: ${{ steps.corpus.outcome == 'failure' }}
run: echo "::warning title=Regression corpus::Some corpus documents render differently from their references. Their renders and diffs are in the regression-mismatches artifact."
- name: 📤 Upload the renders and diffs of mismatches
if: ${{ steps.corpus.outcome == 'failure' }}
if: ${{ failure() }}
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
name: regression-mismatches
@@ -279,14 +273,8 @@ jobs:
run: git fetch --depth=1 origin "$BASE_SHA"
- name: 🔬 Check migrations against the base commit
id: migrations
continue-on-error: true
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
- name: ⚠️ Warn about missing migrations
if: ${{ steps.migrations.outcome == 'failure' }}
run: echo "::warning title=Migrations::Some node changes lack a version bump or a migration. The log of the check above lists them."
# Rust format check on GitHub runner
rust-fmt:
needs: skip-check
Generated
+71 -1
View File
@@ -1150,6 +1150,24 @@ dependencies = [
"memchr",
]
[[package]]
name = "compression_test"
version = "0.0.0"
dependencies = [
"blake3",
"document-container",
"document-format",
"document-graph-storage",
"fastcdc",
"flate2",
"futures",
"lz4_flex",
"migration-formats",
"postcard",
"zstd",
"zstd-safe",
]
[[package]]
name = "concurrent-queue"
version = "2.5.0"
@@ -1300,6 +1318,7 @@ dependencies = [
"tinyvec",
"tsify",
"wasm-bindgen",
"web-time",
]
[[package]]
@@ -2089,6 +2108,12 @@ dependencies = [
"regex-syntax 0.8.6",
]
[[package]]
name = "fastcdc"
version = "3.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf51ceb43e96afbfe4dd5c6f6082af5dfd60e220820b8123792d61963f2ce6bc"
[[package]]
name = "fastnoise-lite"
version = "1.1.1"
@@ -2924,6 +2949,7 @@ dependencies = [
"ash",
"bytemuck",
"cef",
"dirs",
"graphite-desktop-embedded-resources",
"ipc-channel",
"libc",
@@ -2949,7 +2975,6 @@ name = "graphite-desktop-wrapper"
version = "0.0.0"
dependencies = [
"base64 0.22.1",
"dirs",
"graph-craft",
"graphite-editor",
"graphite-wasm-wrapper",
@@ -4201,6 +4226,15 @@ dependencies = [
"num-traits",
]
[[package]]
name = "lz4_flex"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226"
dependencies = [
"twox-hash",
]
[[package]]
name = "lzma-rust2"
version = "0.16.2"
@@ -4389,6 +4423,7 @@ dependencies = [
"blake3",
"ctor",
"document-graph-storage",
"graphene-resource",
"migration-macros",
"postcard",
"serde",
@@ -4425,6 +4460,7 @@ dependencies = [
name = "migration-nodes"
version = "0.0.0"
dependencies = [
"document-graph-storage",
"migration-core",
"migration-runner",
"serde",
@@ -7740,6 +7776,12 @@ dependencies = [
"webrtc-util",
]
[[package]]
name = "twox-hash"
version = "2.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2"
[[package]]
name = "typed-path"
version = "0.12.3"
@@ -9869,6 +9911,34 @@ version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40990edd51aae2c2b6907af74ffb635029d5788228222c4bb811e9351c0caad3"
[[package]]
name = "zstd"
version = "0.13.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb02c3132d251ab1606e9fc913a7da6c6ed08cc263df15edf082e1dc497d157"
dependencies = [
"zstd-safe",
]
[[package]]
name = "zstd-safe"
version = "7.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c8ea04668f5de8d8d51051714ba560c9536519cadcdb8829bba4fe2ad159b03"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-sys"
version = "2.1.2+zstd.1.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3"
dependencies = [
"cc",
"pkg-config",
]
[[package]]
name = "zune-core"
version = "0.4.12"
+2
View File
@@ -45,6 +45,7 @@ members = [
"tools/node-docs",
"tools/regression",
"tools/web-editor-driver",
"tools/compression_test",
]
default-members = [
"editor",
@@ -141,6 +142,7 @@ serde_bytes = "0.11"
serde-wasm-bindgen = "0.6"
reqwest = { version = "0.13", features = ["blocking", "json"] }
futures = "0.3"
web-time = "1.1"
env_logger = "0.11"
log = "0.4"
bitflags = { version = "2.4", features = ["serde"] }
+35 -26
View File
@@ -4,8 +4,7 @@ use std::fs;
use std::io::Read;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, SyncSender};
use std::sync::mpsc::{Receiver, Sender};
use std::thread;
use std::time::{Duration, Instant};
use winit::application::ApplicationHandler;
@@ -43,14 +42,14 @@ pub(crate) struct App {
app_event_receiver: Receiver<AppEvent>,
app_event_scheduler: AppEventScheduler,
desktop_wrapper: DesktopWrapper,
runtime_command_sender: Sender<RuntimeCommand>,
ui: UiInstance,
ui_frame_received: bool,
start_render_sender: SyncSender<()>,
ui_initialized: Option<Instant>,
web_communication_startup_buffer: Vec<Vec<u8>>,
ui_frame_received: bool,
ui_startup_buffer: Vec<Vec<u8>>,
preferences: preferences::DesktopPreferences,
launch_documents: Option<Vec<PathBuf>>,
exiting: Arc<AtomicBool>,
exiting: bool,
exit_reason: ExitReason,
}
@@ -74,9 +73,7 @@ impl App {
})
.expect("Error setting Ctrl-C handler");
let exiting = Arc::new(AtomicBool::new(false));
let (start_render_sender, start_render_receiver) = std::sync::mpsc::sync_channel(1);
let (runtime_command_sender, start_render_receiver) = std::sync::mpsc::channel();
let async_runtime = tokio::runtime::Builder::new_multi_thread()
.thread_name("graphite-async")
@@ -90,9 +87,9 @@ impl App {
let editor_wake = move || {
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
};
let runtime_wake_sender = start_render_sender.clone();
let runtime_wake_sender = runtime_command_sender.clone();
let runtime_wake = move || {
let _ = runtime_wake_sender.try_send(());
let _ = runtime_wake_sender.send(RuntimeCommand::Run);
};
let wgpu_executor = WgpuExecutor::with_context(wgpu_context).expect("Failed to create WgpuExecutor");
let (desktop_wrapper, mut node_runtime) = DesktopWrapper::new(
@@ -106,17 +103,23 @@ impl App {
);
let rendering_app_event_scheduler = app_event_scheduler.clone();
let exiting_clone = exiting.clone();
std::thread::spawn(move || {
let mut update = false;
loop {
if update {
node_runtime.update();
}
let texture = async_runtime.block_on(node_runtime.run());
rendering_app_event_scheduler.schedule(AppEvent::ViewportTexture(texture));
let timeout = node_runtime.until_next_frame().unwrap_or(Duration::from_millis(10));
if start_render_receiver.recv_timeout(timeout).is_err() {
node_runtime.begin_frame();
}
if exiting_clone.load(Ordering::Relaxed) {
break;
let first = start_render_receiver.recv_timeout(Duration::from_millis(100)).unwrap_or(RuntimeCommand::Update);
update = false;
for reason in std::iter::once(first).chain(start_render_receiver.try_iter()) {
match reason {
RuntimeCommand::Update => update = true,
RuntimeCommand::Run => {}
RuntimeCommand::Exit => return,
}
}
}
});
@@ -138,12 +141,12 @@ impl App {
desktop_wrapper,
ui,
ui_frame_received: false,
start_render_sender,
runtime_command_sender,
ui_initialized: None,
web_communication_startup_buffer: Vec::new(),
ui_startup_buffer: Vec::new(),
preferences,
launch_documents: Some(launch_documents),
exiting,
exiting: false,
exit_reason: ExitReason::Shutdown,
}
}
@@ -154,10 +157,10 @@ impl App {
}
fn exit(&mut self, reason: Option<ExitReason>) {
if self.exiting.swap(true, Ordering::Relaxed) {
if std::mem::replace(&mut self.exiting, true) {
return;
}
let _ = self.start_render_sender.send(());
let _ = self.runtime_command_sender.send(RuntimeCommand::Exit);
if let Some(reason) = reason {
self.exit_reason = reason;
}
@@ -464,7 +467,7 @@ impl App {
if self.ui_initialized.is_some() {
self.ui.send(UiCommand::Message(message));
} else {
self.web_communication_startup_buffer.push(message);
self.ui_startup_buffer.push(message);
}
}
@@ -473,7 +476,7 @@ impl App {
AppEvent::WebCommunicationInitialized => {
self.ui_initialized = Some(Instant::now());
self.ui_frame_received = false;
for message in self.web_communication_startup_buffer.drain(..) {
for message in self.ui_startup_buffer.drain(..) {
self.ui.send(UiCommand::Message(message));
}
}
@@ -649,7 +652,7 @@ impl ApplicationHandler for App {
}
Err(other) => tracing::error!("Render error: {:?}", other),
}
let _ = self.start_render_sender.try_send(());
let _ = self.runtime_command_sender.send(RuntimeCommand::Update);
}
if !self.ui_frame_received
@@ -759,6 +762,12 @@ impl ApplicationHandler for App {
}
}
enum RuntimeCommand {
Update,
Run,
Exit,
}
pub(crate) enum ExitReason {
Shutdown,
Restart,
-8
View File
@@ -45,11 +45,3 @@ pub(crate) fn app_resources_dir() -> PathBuf {
ensure_dir_exists(&path);
path
}
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
pub(crate) fn delete_old_cef_browser_directory() {
let old_browser_dir = crate::dirs::app_data_dir().join("browser");
if old_browser_dir.is_dir() {
let _ = std::fs::remove_dir_all(&old_browser_dir);
}
}
-3
View File
@@ -74,9 +74,6 @@ pub fn start() -> ExitCode {
dirs::clear_dir(&ui::temp_dir_root());
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
dirs::delete_old_cef_browser_directory();
// Must be called before event loop initialization or native window integrations will break
App::init();
+1
View File
@@ -28,6 +28,7 @@ wgpu-sync = { workspace = true }
winit = { workspace = true, features = ["serde"] }
thiserror = { workspace = true }
tracing = { workspace = true }
dirs = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
rand = { workspace = true, features = ["thread_rng"] }
+1 -1
View File
@@ -8,7 +8,7 @@ const APP_DIRECTORY_NAME: &str = "graphite";
const APP_DIRECTORY_NAME: &str = "Graphite";
pub(crate) fn app_tmp_dir() -> PathBuf {
let path = std::env::temp_dir().join(APP_DIRECTORY_NAME);
let path = dirs::cache_dir().unwrap_or_else(std::env::temp_dir).join(APP_DIRECTORY_NAME).join("ui");
if let Err(e) = fs::create_dir_all(&path) {
tracing::error!("Failed to create temp directory at {path:?}: {e}");
}
@@ -48,6 +48,10 @@ impl ImplApp for BrowserProcessAppImpl {
cmd.append_switch(Some(&"disable-default-apps".into()));
cmd.append_switch(Some(&"disable-breakpad".into()));
cmd.append_switch_with_value(Some(&"disable-blink-features".into()), Some(&"WebBluetooth,WebUSB,Serial".into()));
cmd.append_switch_with_value(
Some(&"host-resolver-rules".into()),
Some(&"MAP * ~NOTFOUND, EXCLUDE fonts.googleapis.com, EXCLUDE fonts.gstatic.com".into()),
);
let extra_disabled_features = ["OptimizationHints", "OnDeviceModelService", "TranslateUI"];
let disabled_features_switch = Some(&"disable-features".into());
-1
View File
@@ -27,7 +27,6 @@ wgpu-executor = { workspace = true }
wgpu = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
dirs = { workspace = true }
image = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+1 -2
View File
@@ -8,7 +8,6 @@ use graphite_editor::node_graph_executor::NodeRuntime;
use message_dispatcher::DesktopWrapperMessageDispatcher;
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
use std::sync::Arc;
use std::time::Instant;
pub use graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
@@ -64,7 +63,7 @@ impl DesktopWrapper {
.with_resource_storage(resource_storage)
.with_document_store(document_store),
)
.with_runtime(RuntimeBuilder::new(Arc::new(Instant::now())).with_wake(runtime_wake).with_application_io(application_io))
.with_runtime(RuntimeBuilder::new().with_wake(runtime_wake).with_application_io(application_io))
.with_spawner(spawner)
.with_random_seed(random_seed)
.build();
+372
View File
@@ -0,0 +1,372 @@
//! 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.
//!
//! 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.
use std::collections::{HashMap, HashSet};
use document_container::{AnyContainer, AsyncContainer};
use document_graph_storage::blob::{BlobBytes, NewBlobs};
use document_graph_storage::{BlobHash, ResourceHash};
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.
#[derive(Clone, Debug, Default)]
pub(crate) struct BlobStore {
pub(crate) bytes: BlobBytes,
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`.
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),
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.
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();
hashes.sort_unstable();
let mut records = Vec::new();
for hash in hashes {
for hash in chain_to(hash, |hash| bases.get(hash).filter(|base| blobs.contains_key(base)).copied()) {
let Some(bytes) = blobs.remove(&hash) else { continue };
if let Some(record) = self.insert(hash, bytes, bases.get(&hash).copied()) {
records.push((hash, record));
}
}
}
records
}
/// The record of every held blob, in hash order but each after its base.
#[cfg(feature = "network")]
pub(crate) fn records(&self) -> Vec<(BlobHash, Vec<u8>)> {
let mut hashes: Vec<_> = self.records.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));
for hash in chain_to(hash, unlisted_base) {
if listed.insert(hash) {
records.push((hash, self.records[&hash].clone()));
}
}
}
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.
#[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
loop {
let waiting = pending.len();
pending.retain(|(hash, record)| {
if self.bytes.contains_key(hash) {
return false;
}
let bytes = match decode_record(record) {
Some(Record::Full(bytes)) => bytes,
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 };
bytes
}
None => return false,
};
match self.hold_checked(*hash, bytes, record.clone()) {
Ok(()) => held.push((*hash, record.clone())),
Err(error) => log::warn!("{error}"),
}
false
});
if pending.is_empty() || pending.len() == waiting {
break;
}
}
held
}
/// A record holding the held blob `hash` in full, standing on no base.
pub(crate) fn full_record(&self, hash: &BlobHash) -> Option<Vec<u8>> {
Some(full_record(self.bytes.get(hash)?))
}
/// Drop a blob whose record never got written.
pub(crate) fn forget(&mut self, hash: &BlobHash) {
self.bytes.remove(hash);
self.records.remove(hash);
}
/// Read and decode the record of `hash` and those of the bases it stands on, checking each blob 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
let mut deltas = Vec::new();
let mut visited = HashSet::new();
let mut current = hash;
let mut bytes = loop {
if let Some(bytes) = self.bytes.get(&current) {
break bytes.clone();
}
if !visited.insert(current) {
return Err(format!("Blob {hash} sits on a chain that loops back to {current}"));
}
let record = working.read(&layout.blob_path(&current)).await.map_err(|error| format!("Blob {current} could not be read: {error}"))?;
let record = record.as_slice().to_vec();
match decode_record(&record).ok_or_else(|| format!("Blob {current} has a malformed record"))? {
Record::Full(bytes) => {
self.hold_checked(current, bytes.clone(), record)?;
break bytes;
}
Record::Delta { base, delta } => {
deltas.push((current, delta, record));
current = base;
}
}
};
for (hash, delta, record) in deltas.into_iter().rev() {
bytes = apply_copy_delta(&bytes, &delta).ok_or_else(|| format!("Blob {hash} has a malformed delta"))?;
self.hold_checked(hash, bytes.clone(), record)?;
}
Ok(())
}
fn hold_checked(&mut self, hash: BlobHash, bytes: Vec<u8>, record: Vec<u8>) -> Result<(), String> {
if BlobHash::of(&bytes) != hash {
return Err(format!("Blob {hash} decodes to bytes of a different hash"));
}
self.bytes.insert(hash, bytes);
self.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.
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]);
while let Some(base) = chain.last().and_then(&base_of)
&& visited.insert(base)
{
chain.push(base);
}
chain.reverse();
chain
}
/// The base a delta record names.
fn record_base(record: &[u8]) -> Option<BlobHash> {
let (&DELTA, rest) = record.split_first()? else { return None };
Some(BlobHash(ResourceHash::from(<[u8; 32]>::try_from(rest.get(..32)?).ok()?)))
}
enum Record {
Full(Vec<u8>),
Delta { base: BlobHash, delta: Vec<u8> },
}
fn full_record(bytes: &[u8]) -> Vec<u8> {
let mut record = vec![FULL];
record.extend_from_slice(bytes);
record
}
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(),
}),
_ => 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.
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.
fn copy_delta(base: &[u8], target: &[u8]) -> Vec<u8> {
let block_key = |bytes: &[u8]| -> u128 {
let mut key = [0; COPY_BLOCK];
key.copy_from_slice(&bytes[..COPY_BLOCK]);
u128::from_le_bytes(key)
};
let mut index: HashMap<u128, usize> = 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);
}
let mut output = Vec::new();
let mut literal_start = 0;
let mut position = 0;
while position + COPY_BLOCK <= target.len() {
let Some(&base_offset) = index.get(&block_key(&target[position..])) else {
position += 1;
continue;
};
// Base blocks are aligned but target matches are not, so extend backward into the pending literal too
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();
push_insert(&mut output, &target[literal_start..position - backward]);
output.push(COPY);
push_varint(&mut output, base_offset - backward);
push_varint(&mut output, backward + forward);
position += forward;
literal_start = position;
}
push_insert(&mut output, &target[literal_start..]);
output
}
fn apply_copy_delta(base: &[u8], mut delta: &[u8]) -> Option<Vec<u8>> {
let mut output = Vec::new();
while let Some((&operation, rest)) = delta.split_first() {
delta = rest;
match operation {
COPY => {
let offset = read_varint(&mut delta)?;
let length = read_varint(&mut delta)?;
output.extend_from_slice(base.get(offset..offset.checked_add(length)?)?);
}
INSERT => {
let length = read_varint(&mut delta)?;
let (literal, rest) = delta.split_at_checked(length)?;
output.extend_from_slice(literal);
delta = rest;
}
_ => return None,
}
}
Some(output)
}
fn push_insert(output: &mut Vec<u8>, literal: &[u8]) {
if literal.is_empty() {
return;
}
output.push(INSERT);
push_varint(output, literal.len());
output.extend_from_slice(literal);
}
fn push_varint(output: &mut Vec<u8>, mut value: usize) {
while value >= 0x80 {
output.push(value as u8 | 0x80);
value >>= 7;
}
output.push(value as u8);
}
fn read_varint(delta: &mut &[u8]) -> Option<usize> {
let mut value: usize = 0;
for shift in (0..usize::BITS).step_by(7) {
let (&byte, rest) = delta.split_first()?;
*delta = rest;
value |= ((byte & 0x7f) as usize).checked_shl(shift)?;
if byte < 0x80 {
return Some(value);
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
fn hashed(bytes: &[u8]) -> (BlobHash, Vec<u8>) {
(BlobHash::of(bytes), bytes.to_vec())
}
#[test]
fn copy_delta_round_trips() {
let base: Vec<u8> = (0..4096_u32).flat_map(|i| (i * 7).to_le_bytes()).collect();
let mut target = base.clone();
target.splice(100..108, [1, 2, 3]);
target[9000] ^= 0xff;
target.extend_from_slice(b"tail");
let delta = copy_delta(&base, &target);
assert!(delta.len() < 200, "a few edits encode as a small delta, got {} bytes", delta.len());
assert_eq!(apply_copy_delta(&base, &delta).unwrap(), target);
assert_eq!(apply_copy_delta(&[], &copy_delta(&[], &target)).unwrap(), target);
}
#[test]
fn records_decode_to_what_was_inserted() {
let mut store = BlobStore::default();
let (base_hash, base) = hashed(&[7; 2048]);
let mut changed = base.clone();
changed[1000] = 0;
let (changed_hash, changed) = hashed(&changed);
let full = store.insert(base_hash, base.clone(), None).unwrap();
let delta = store.insert(changed_hash, changed.clone(), Some(base_hash)).unwrap();
assert!(store.insert(changed_hash, changed.clone(), Some(base_hash)).is_none(), "a held blob writes nothing");
assert!(matches!(decode_record(&full), Some(Record::Full(bytes)) if bytes == base));
let Some(Record::Delta { base: decoded_base, delta }) = decode_record(&delta) else {
panic!("a delta record")
};
assert_eq!(decoded_base, base_hash);
assert_eq!(apply_copy_delta(&base, &delta).unwrap(), changed);
}
#[test]
fn malformed_deltas_are_rejected() {
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());
assert!(decode_record(&[DELTA, 1, 2]).is_none());
}
}
+4
View File
@@ -58,4 +58,8 @@ pub enum Error {
#[cfg(feature = "network")]
#[error("network error: {0}")]
Network(#[from] peer_transport::PacketError),
/// The room knows this device by its peer, so the user can't change.
#[cfg(feature = "network")]
#[error("the user cannot change while the document is connected")]
UserChangeWhileConnected,
}
+23 -8
View File
@@ -234,18 +234,33 @@ impl<L: Layout> Gdd<L> {
}
}
// Every resource 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.
let mut resources: std::collections::BTreeMap<String, Option<Resource>> = std::collections::BTreeMap::new();
let resources_dir = self.layout.resources_dir();
if self.working.list_dirs("").await?.iter().any(|d| d == resources_dir) {
resources.extend(self.working.list(resources_dir).await?.into_iter().map(|path| (path, None)));
// 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.
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()) {
entries.extend(self.working.list(self.layout.resources_dir()).await?.into_iter().map(|path| (path, None)));
}
for (hash, resource) in embedded_bytes {
resources.entry(self.layout.resource_path(&hash)).or_insert(Some(resource));
entries.entry(self.layout.resource_path(&hash)).or_insert(Some(resource));
}
for (path, resource) in resources {
// A copy without history carries only the current values, each in full since the blobs it was based on stay behind
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())));
}
}
}
None if directories.iter().any(|name| name == self.layout.blobs_dir()) => {
entries.extend(self.working.list(self.layout.blobs_dir()).await?.into_iter().map(|path| (path, None)));
}
None => {}
}
for (path, resource) in entries {
if let Some(resource) = resource {
sink.write_entry(&path, resource.as_ref())?;
continue;
+11
View File
@@ -4,6 +4,7 @@
//! read/write call site. Working-copy creation, exports, and migrations may all hit the same
//! basename with different codecs.
use document_graph_storage::BlobHash;
use graphene_resource::ResourceHash;
pub trait Layout: Send + Sync {
@@ -15,6 +16,10 @@ 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`.
fn blobs_dir(&self) -> &str;
/// The record of one blob.
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`
/// becomes the sole source of truth.
@@ -51,6 +56,12 @@ impl Layout for GddV1Layout {
fn resource_path(&self, hash: &ResourceHash) -> String {
format!("{}/{hash}", self.resources_dir())
}
fn blobs_dir(&self) -> &str {
"blobs"
}
fn blob_path(&self, hash: &BlobHash) -> String {
format!("{}/{hash}", self.blobs_dir())
}
fn legacy_path(&self) -> &str {
"legacy.graphite"
}
+20 -6
View File
@@ -24,6 +24,7 @@ use document_graph_storage::{HistoryMetadata, MetadataFact, PeerId, Registry, Se
use graphene_resource::LoadResource;
use graphene_resource::{ResourceHash, ResourceStorage};
mod blob_store;
pub mod codec;
pub mod error;
pub mod export;
@@ -47,6 +48,8 @@ pub use layout::{GddV1Layout, Layout};
pub use manifest::{Manifest, PayloadCodecs};
pub use resource::ResourceProxy;
use blob_store::BlobStore;
/// The default [`Layout`], so callers write `GddV1` for the common `Gdd<GddV1Layout>` handle.
pub type GddV1 = Gdd<GddV1Layout>;
@@ -103,6 +106,8 @@ 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.
pub(crate) blobs: BlobStore,
#[cfg(feature = "network")]
pub(crate) network: Option<peer_transport::Replica>,
#[cfg(feature = "network")]
@@ -140,6 +145,7 @@ impl<L: Layout + Clone> Clone for Gdd<L> {
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
byte_store: self.byte_store.clone(),
blobs: self.blobs.clone(),
migrated: self.migrated,
shared: self.shared,
..Self::assemble(self.session.clone(), self.working.clone(), self.layout.clone(), self.manifest.clone(), self.metadata.clone())
@@ -159,6 +165,7 @@ impl<L: Layout> Gdd<L> {
view_settings: Default::default(),
network_view_settings: Default::default(),
byte_store: None,
blobs: BlobStore::default(),
migrated: false,
#[cfg(feature = "network")]
network: None,
@@ -186,10 +193,10 @@ impl<L: Layout + Default> Gdd<L> {
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
pub fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub fn create(path: &Path, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
let working = AnyContainer::Folder(FolderBackend::create(path)?);
let layout = L::default();
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version)
Self::create_in(working, layout, peer, user, document_uuid, editor_version, stdlib_version)
}
}
@@ -251,7 +258,7 @@ impl<L: Layout> Gdd<L> {
#[cfg_attr(not(feature = "migrations"), expect(unused_mut, reason = "only format migrations change the stored records"))]
let mut records = load::StoredRecords::read(&working, &layout, codecs).await?;
#[cfg(feature = "migrations")]
let format_outcome = migrate::migrate_format(&mut records, codecs, manifest.format_version)?;
let (format_outcome, migrated_blobs) = migrate::migrate_format(&mut records, codecs, manifest.format_version)?.unzip();
#[cfg_attr(not(feature = "migrations"), expect(unused_mut, reason = "only format migrations change the decoded payloads"))]
let mut payloads = records.decode(codecs)?;
#[cfg(feature = "migrations")]
@@ -326,6 +333,13 @@ impl<L: Layout> Gdd<L> {
..Self::assemble(session, working, layout, manifest, metadata)
};
#[cfg(feature = "migrations")]
if let Some(blobs) = migrated_blobs {
gdd.keep_blobs_durably(blobs).await?;
}
// Before node migrations, which read the values blobs hold
gdd.load_blobs().await;
#[cfg(feature = "migrations")]
{
let migrated_nodes = gdd.migrate_nodes(inputs.byte_store, inputs.host).await?;
@@ -344,18 +358,18 @@ impl<L: Layout> Gdd<L> {
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
/// the manifest and writes each payload with its recorded codec.
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
let codecs = manifest.codecs;
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
let session_state = SessionState {
peer_id: peer,
user_id: UserId(peer.0),
user_id: user,
..Default::default()
};
io::write_single(&working, layout.session_basename(), codecs.session, &Sorted(&session_state))?;
let session = Session::with_peer(peer);
let session = Session::with_identity(peer, user);
io::write_single(&working, layout.registry_basename(), codecs.registry, &Sorted(session.registry()))?;
Ok(Self::assemble(session, working, layout, manifest, HistoryMetadata::default()))
+1 -1
View File
@@ -9,7 +9,7 @@ use crate::{DEFAULT_HISTORY_CODEC, DEFAULT_HOT_LOG_CODEC, DEFAULT_REGISTRY_CODEC
pub const FORMAT_MAGIC: &str = "gdd";
/// Newest format version this build can open, which older documents migrate to. `cargo run migration snapshot` bumps it when the stored types change.
pub const SUPPORTED_FORMAT_VERSION: u32 = 3;
pub const SUPPORTED_FORMAT_VERSION: u32 = 4;
/// The on-disk codec for each working-copy payload, recorded so reads/writes never have to probe
/// the filesystem to discover it. The manifest itself is excluded: it is always JSON, since it must
+16 -6
View File
@@ -4,10 +4,12 @@
use std::collections::{BTreeSet, HashMap};
use document_container::AsyncContainer;
use document_graph_storage::BlobHash;
use document_graph_storage::blob::NewBlobs;
use document_graph_storage::{Declarations, Delta, EncodedDeclaration, HistoryMetadata, PeerId, Registry, ResourceEntry, ResourceId, Rev, Session, Subject, TimeStamp};
use graphene_resource::LoadResource;
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, Payload, PayloadCodec};
use migration_runner::{DocumentPayloads, HistoryOutcome, RunnerError, holds, migrate_history, migrate_registry, references, registry_at, run_format_migrations};
use migration_runner::{DocumentPayloads, HistoryOutcome, MigrationBlobs, RunnerError, holds, migrate_history, migrate_registry, references, registry_at, run_format_migrations};
use crate::error::Error;
use crate::layout::Layout;
@@ -16,7 +18,7 @@ use crate::manifest::{PayloadCodecs, SUPPORTED_FORMAT_VERSION};
use crate::{Codec, Gdd};
/// Bring `records` from `format_version` to [`SUPPORTED_FORMAT_VERSION`]. `None` when they already are.
pub(crate) fn migrate_format(records: &mut StoredRecords, codecs: PayloadCodecs, format_version: u32) -> Result<Option<HistoryOutcome>, Error> {
pub(crate) fn migrate_format(records: &mut StoredRecords, codecs: PayloadCodecs, format_version: u32) -> Result<Option<(HistoryOutcome, NewBlobs)>, Error> {
if format_version >= SUPPORTED_FORMAT_VERSION {
return Ok(None);
}
@@ -28,6 +30,7 @@ pub(crate) fn migrate_format(records: &mut StoredRecords, codecs: PayloadCodecs,
history: records.history.iter().flatten().map(|record| payload(record, codecs.history)).collect(),
hot_log: records.hot_log.iter().map(|record| payload(record, codecs.hot_log)).collect(),
session: records.session.as_ref().map(|record| payload(record, codecs.session)),
..Default::default()
};
let outcome = run_format_migrations(&migration_core::registered_format_migrations(), &mut payloads, SUPPORTED_FORMAT_VERSION)?;
log::info!("Migrated the document format from version {format_version} to {SUPPORTED_FORMAT_VERSION}");
@@ -40,7 +43,11 @@ pub(crate) fn migrate_format(records: &mut StoredRecords, codecs: PayloadCodecs,
records.hot_log = payloads.hot_log.into_iter().map(|payload| payload.bytes).collect();
records.session = payloads.session.map(|payload| payload.bytes);
Ok(Some(outcome))
let blobs = NewBlobs {
bytes: payloads.blobs.into_iter().map(|(hash, bytes)| (BlobHash(hash), bytes)).collect(),
bases: payloads.blob_bases.into_iter().map(|(hash, base)| (BlobHash(hash), BlobHash(base))).collect(),
};
Ok(Some((outcome, blobs)))
}
/// The facts in `metadata` with their revs mapped by `remap`, which drops the facts of a rev it has no answer for.
@@ -91,14 +98,16 @@ impl<L: Layout> Gdd<L> {
// Hot ops join history first, so they migrate with it
self.session.retire_all()?;
let migrated = migrate_registry(&migrations, self.session.retired_registry(), &resolver, host)?;
(self.session, self.metadata) = match self.session_with_rewritten_history(&migrations, &migrated, &resolver, host) {
let mut blobs = MigrationBlobs::new(&self.blobs.bytes);
let migrated = migrate_registry(&migrations, self.session.retired_registry(), &resolver, host, &mut blobs)?;
(self.session, self.metadata) = match self.session_with_rewritten_history(&migrations, &migrated, &resolver, host, &mut blobs) {
Ok(rewritten) => rewritten,
Err(error) => {
log::warn!("Migrating this document's history failed, so undo can't reach before this point: {error}");
(self.session_with_truncated_history(migrated)?, remap_metadata(&self.metadata, |_| None))
}
};
self.keep_blobs_durably(blobs.into_added()).await?;
// Declarations the migrations introduced need their bytes next to the other resources
let referenced = self.session.all_declaration_resources();
@@ -156,10 +165,11 @@ impl<L: Layout> Gdd<L> {
migrated: &Registry,
resolver: &DocumentDeclarations,
host: Option<&dyn MigrationHost>,
blobs: &mut MigrationBlobs,
) -> Result<(Session, HistoryMetadata), RunnerError> {
let history: Vec<Delta> = self.session.history().cloned().collect();
let cursors = self.session.head_rev().into_iter().chain(self.session.redo_stack().iter().copied());
let rewritten = migrate_history(migrations, history, resolver, host, cursors)?;
let rewritten = migrate_history(migrations, history, resolver, host, cursors, blobs)?;
let remap = |rev: Rev| rewritten.revs.get(&rev).copied().flatten();
let head = self.session.head_rev().and_then(remap);
+30 -4
View File
@@ -4,8 +4,10 @@
use std::collections::HashSet;
use document_graph_storage::{CrdtError, Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, RegistryDelta, ResourceHash, RetiredMarks, Rev, Session, Touched, UserId};
use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, Transport};
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 peer_transport::{BlobRecord, Event, Replica, Role, SyncTarget, TargetError, Transport};
use crate::error::Error;
use crate::layout::Layout;
@@ -365,12 +367,36 @@ impl<L: Layout> SyncTarget for Gdd<L> {
Ok(())
}
/// Includes blobs this peer holds no record for, which it asks for in full like resources.
fn missing_resources(&self) -> HashSet<ResourceHash> {
self.unstored_resources().into_iter().collect()
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()
}
fn store_resource(&mut self, _hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
fn resource_bytes(&self, hash: ResourceHash) -> Option<Vec<u8>> {
self.blobs.bytes.get(&BlobHash(hash)).cloned()
}
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
let blob = BlobHash(hash);
if self.session.all_blob_hashes().contains(&blob) {
let bytes = BlobBytes::from([(blob, bytes.to_vec())]);
self.keep_blobs(NewBlobs { bytes, ..Default::default() })?;
return Ok(());
}
self.hold_resource(bytes)?;
Ok(())
}
fn blob_records(&self) -> Vec<BlobRecord> {
self.blobs.records().into_iter().map(|(hash, record)| BlobRecord { hash, record }).collect()
}
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)?;
}
Ok(())
}
}
+48 -13
View File
@@ -6,7 +6,8 @@
use document_container::{AnyContainer, AsyncContainer};
#[cfg(feature = "conversion")]
use document_graph_storage::NodeMetadataSource;
use document_graph_storage::{HistoryMetadata, HotOp, MetadataFact, RegistryDelta, Rev, Sorted, Subject, TimeStamp, Value, WallStamp};
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 graphene_resource::ResourceStorage;
@@ -65,6 +66,20 @@ impl<L: Layout> Gdd<L> {
Ok(rev)
}
/// 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 {
return Ok(());
}
#[cfg(feature = "network")]
if self.network.is_some() {
return Err(Error::UserChangeWhileConnected);
}
let closing = self.session.set_user(user, peer)?;
self.persist_staged(&closing, Vec::new())?;
self.persist_session_state()
}
/// Edit the cached manifest and persist it. Always JSON, synchronous.
pub fn update_manifest(&mut self, edit: impl FnOnce(&mut Manifest)) -> Result<(), Error> {
edit(&mut self.manifest);
@@ -91,16 +106,24 @@ impl<L: Layout> Gdd<L> {
resources: &graphene_resource::ResourceRegistry,
byte_store: &dyn ResourceStorage,
) -> Result<document_graph_storage::Declarations, Error> {
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
self.persist_staged(&hot_ops)?;
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 {
registry,
blob_bytes,
declaration_bytes,
declarations,
..
} = conversion;
let ops = document_graph_storage::delta::compute_deltas(self.registry(), &registry);
self.stage_with_blobs(ops, blob_bytes)?;
// Persist proto-node declaration content to the byte store (the global cache in the editor,
// the working-copy container for standalone export). Content-addressed, so re-storing
// identical bytes on every commit is an idempotent no-op.
for bytes in conversion.declaration_bytes.values() {
for bytes in declaration_bytes.values() {
byte_store.store(bytes);
}
Ok(conversion.declarations)
Ok(declarations)
}
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
@@ -122,21 +145,33 @@ impl<L: Layout> Gdd<L> {
Ok(hot_ops)
}
/// Stage raw registry ops as hot ops, without the runtime diff.
/// Stage raw registry ops as hot ops, without the runtime diff. Large input values they write become blobs.
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, Error> {
let hot_ops = self.session.stage_computed_ops(ops.into_iter().collect())?;
self.persist_staged(&hot_ops)?;
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> {
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)?;
Ok(hot_ops)
}
/// Append the frames of freshly staged hot ops, then broadcast them.
fn persist_staged(&mut self, hot_ops: &[HotOp]) -> Result<(), Error> {
/// Append the frames of freshly staged hot ops, then broadcast them with the records of the blobs they introduced.
#[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> {
for hot_op in hot_ops {
self.append_hot_frame(hot_op)?;
}
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
replica.broadcast_hot_ops(hot_ops)?;
let blobs = blobs.into_iter().map(|(hash, record)| peer_transport::BlobRecord { hash, record }).collect();
replica.broadcast_hot_ops(hot_ops, blobs)?;
}
Ok(())
}
@@ -183,7 +218,7 @@ impl<L: Layout> Gdd<L> {
if !self.retires_locally() {
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
replica.broadcast_hot_ops(hot_ops)?;
replica.broadcast_hot_ops(hot_ops, Vec::new())?;
}
return Ok(Vec::new());
}
@@ -371,7 +406,7 @@ impl<L: Layout> Gdd<L> {
/// 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()?;
self.persist_staged(&staged)?;
self.persist_staged(&staged, Vec::new())?;
Ok(())
}
+40
View File
@@ -7,6 +7,8 @@ use std::path::Path;
use std::sync::Arc;
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
use document_graph_storage::BlobHash;
use document_graph_storage::blob::{BlobBytes, NewBlobs};
use graphene_resource::ResourceFuture;
use graphene_resource::{LoadResource, Resource, ResourceHash, ResourceStorage};
@@ -124,6 +126,44 @@ impl<L: Layout> Gdd<L> {
pub(crate) fn unstored_resources(&self) -> Vec<ResourceHash> {
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`.
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.
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
records[index..].iter().for_each(|(hash, _)| self.blobs.forget(hash));
return Err(error);
}
}
Ok(records)
}
/// [`keep_blobs`](Self::keep_blobs), returning once the records are written, for a migration replacing the records that held the values inline.
#[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) {
self.working.write(&self.layout.blob_path(&hash), &record).await?;
}
Ok(())
}
/// Decode the record of every blob the document names, so `to_runtime` can resolve any state the cursor reaches.
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 {
log::error!("{error}");
}
}
}
}
impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
+2 -2
View File
@@ -4,7 +4,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{ExportFormat, ExportOptions, GddV1, GddV1Layout};
use document_graph_storage::{Implementation, Network, NetworkId, Node, NodeId, PeerId, Priority, RegistryDelta, ResourceId, SourceKey, TimeStamp, to_value};
use document_graph_storage::{Implementation, Network, NetworkId, Node, NodeId, PeerId, Priority, RegistryDelta, ResourceId, SourceKey, TimeStamp, UserId, to_value};
use graph_craft::application_io::resource::{HashMapResourceStorage, ResourceStorage};
use graphene_resource::DataSource;
use std::collections::BTreeMap;
@@ -16,7 +16,7 @@ const LATEST: TimeStamp = TimeStamp {
};
fn document(peer: u64) -> GddV1 {
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
}
/// Networks and nodes, some of each removed again, plus link-only resources whose bytes sit in the byte store.
+1 -1
View File
@@ -7,7 +7,7 @@ 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), 1, "editor".into(), "stdlib".into()).expect("create")
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
}
/// Let the room settle through greetings, the sync handshake and whatever was broadcast.
+3 -3
View File
@@ -4,7 +4,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId, Registry};
use document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId, Registry, UserId};
use futures::executor::block_on;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
@@ -91,7 +91,7 @@ fn stored(nodes: &[(u64, &'static str)]) -> AnyContainer {
/// A document whose declaration bytes went to `store`, as the editor sends them to its global cache.
fn stored_with_bytes_in(nodes: &[(u64, &'static str)], store: &HashMapResourceStorage) -> AnyContainer {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap();
gdd.commit_from_runtime(&network_of(nodes), &NoMetadata, &ResourceRegistry::new(), store).unwrap();
gdd.into_storage().0
}
@@ -143,7 +143,7 @@ fn declarations_come_from_the_container_when_the_cache_lacks_them() {
let nodes = [(1, "test_nodes::CopyNode"), (2, "test_nodes::OtherNode")];
// An archive carries its declarations in the container, which a device's cache hasn't seen yet
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap();
gdd.commit_from_runtime(&network_of(&nodes), &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
.unwrap();
for (_, identifier) in nodes {
+3 -3
View File
@@ -31,7 +31,7 @@ fn network_of(nodes: &[(u64, &'static str)]) -> NodeNetwork {
}
fn create() -> GddV1 {
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap()
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap()
}
fn commit(gdd: &mut GddV1, nodes: &[(u64, &'static str)], store: &HashMapResourceStorage) {
@@ -79,7 +79,7 @@ fn a_migration_on_disk_leaves_no_staging_behind() {
block_on(async {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("document");
let mut gdd = GddV1::create(&path, PeerId(7), 1, "editor".into(), "std".into()).unwrap();
let mut gdd = GddV1::create(&path, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap();
commit(&mut gdd, &[(1, FADE)], &HashMapResourceStorage::new());
drop(gdd);
@@ -259,7 +259,7 @@ fn reopening_with_an_undone_implementation_swap_can_redo() {
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
let declarations = reopened.declarations(&store).await;
reopened.redo().unwrap();
let converted = reopened.registry().to_runtime_with_full_metadata(&declarations);
let converted = reopened.registry().to_runtime_with_full_metadata(&declarations, reopened.blobs());
assert!(converted.is_ok(), "{}", converted.err().unwrap());
});
}
+2 -2
View File
@@ -4,7 +4,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{Error, GddV1, GddV1Layout, manifest};
use document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId};
use document_graph_storage::{EncodedDeclaration, Implementation, NoMetadata, PeerId, UserId};
use futures::executor::block_on;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
@@ -28,7 +28,7 @@ fn network_of(nodes: &[(u64, &'static str)]) -> NodeNetwork {
}
fn create() -> GddV1 {
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), 1, "editor".into(), "std".into()).unwrap()
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(7), UserId(7), 1, "editor".into(), "std".into()).unwrap()
}
fn implementations(gdd: &GddV1) -> Vec<Implementation> {
+28 -25
View File
@@ -5,7 +5,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp, UserId};
fn empty_container() -> AnyContainer {
AnyContainer::Memory(MemoryBackend::new())
@@ -44,7 +44,7 @@ fn create_in_round_trips_empty_document() {
futures::executor::block_on(async {
let container = empty_container();
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), UserId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
Ok(gdd) => gdd,
Err(error) => panic!("create_in failed: {error:?}"),
};
@@ -82,7 +82,7 @@ fn open_in_rejects_wrong_format_magic() {
#[test]
fn manifest_returns_what_create_in_wrote() {
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), UserId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
assert_eq!(gdd.session().peer(), PeerId(13));
@@ -99,7 +99,7 @@ fn an_empty_registry_file_is_corrupt_rather_than_absent() {
use document_container::AsyncContainer;
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let codec = gdd.manifest().codecs.registry;
let (working, layout) = gdd.into_storage();
@@ -114,7 +114,7 @@ fn opening_a_registry_without_history_keeps_the_node_counter() {
use document_container::AsyncContainer;
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let codecs = gdd.manifest().codecs;
let (working, layout) = gdd.into_storage();
@@ -135,7 +135,7 @@ fn opening_a_registry_without_history_keeps_the_node_counter() {
#[test]
fn update_manifest_changes_visible_after_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
gdd.update_manifest(|m| m.editor_version = "ed-NEW".into())
.unwrap_or_else(|error| panic!("update_manifest failed: {error:?}"));
@@ -150,7 +150,7 @@ fn update_manifest_changes_visible_after_reopen() {
#[test]
fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// AddNetwork on the root network. Idempotent at apply, so two hot ops applied in sequence
// produces one network in the registry.
@@ -177,7 +177,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
#[test]
fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Two hot ops: one with low timestamp (will retire), one with high (will stay).
let early = HotOp {
@@ -225,7 +225,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
#[test]
fn last_broadcast_rev_persists_across_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Retire one op so there is a real retired rev to mark as published.
let op = HotOp {
@@ -256,7 +256,7 @@ fn export_folder_round_trips_through_open() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("export");
@@ -284,7 +284,7 @@ fn export_zip_round_trips_via_deserialize() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), UserId(4), 0xCD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("doc.gdd.zip");
@@ -309,7 +309,7 @@ fn export_rejects_invalid_options() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("nope");
@@ -332,7 +332,7 @@ fn resource_round_trip_add_read_remove() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), UserId(99), 0xCAFE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"deadbeef cafe babe";
let hash = ResourceHash::from(&payload[..]);
@@ -362,7 +362,7 @@ fn resource_survives_reopen() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), UserId(7), 0xC0DE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"persistent bytes";
let hash = ResourceHash::from(&payload[..]);
@@ -391,7 +391,7 @@ fn resource_from_path_uses_fs_copy_on_folder_backend() {
// Need a folder-backed working copy to exercise the fs::copy path.
let working_dir = tempfile::tempdir().unwrap();
let working = AnyContainer::Folder(FolderBackend::create(working_dir.path()).unwrap());
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Source file outside the working copy.
let payload = b"external resource bytes";
@@ -415,7 +415,7 @@ fn export_carries_resources() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), UserId(2), 0xBC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"exported resource";
let hash = ResourceHash::from(&payload[..]);
@@ -443,7 +443,7 @@ fn embed_all_resources_materializes_link_only_resource() {
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), UserId(8), 0xF00D, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// A resource whose only source is a URL, resolved to a hash. The bytes live solely in the
// byte store; the working copy never holds them.
@@ -508,7 +508,7 @@ fn export_materializes_embedded_resource_from_byte_store() {
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// An Embedded resource whose bytes live only in the byte store, not the working copy.
let payload = b"embedded bytes in the cache";
@@ -549,7 +549,7 @@ fn export_round_trips_unretired_hot_ops() {
use graphene_resource::{DataSource, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xF15E, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"hot resource bytes";
let hash = graphene_resource::ResourceHash::from(&payload[..]);
@@ -602,7 +602,7 @@ fn open_in_rejects_future_format_version() {
#[test]
fn create_in_records_default_codecs_in_manifest() {
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let codecs = gdd.manifest().codecs;
assert_eq!(codecs.registry, Codec::Postcard);
@@ -623,7 +623,7 @@ fn first_commit_registers_peer_and_survives_reopen() {
use graphene_resource::ResourceRegistry;
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), UserId(21), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let network = NodeNetwork {
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
@@ -665,7 +665,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
futures::executor::block_on(async {
use document_container::AsyncContainer;
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let hot_op = HotOp {
op: RegistryDelta::AddNetwork {
@@ -718,7 +718,7 @@ fn declarations_round_trip_through_byte_store() {
..Default::default()
};
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
// Commit: declaration bytes flow into the byte store, not the Gdd container.
let byte_store = HashMapResourceStorage::new();
@@ -729,7 +729,10 @@ fn declarations_round_trip_through_byte_store() {
let declarations = gdd.declarations(&byte_store).await;
assert_eq!(declarations.len(), 1, "expected one proto-node declaration resolved from the byte store");
let (converted, _entries) = gdd.registry().to_runtime_with_metadata(&declarations).unwrap_or_else(|error| panic!("to_runtime failed: {error:?}"));
let (converted, _entries) = gdd
.registry()
.to_runtime_with_metadata(&declarations, gdd.blobs())
.unwrap_or_else(|error| panic!("to_runtime failed: {error:?}"));
let node = converted.nodes.values().next().expect("converted network has the node");
match &node.implementation {
@@ -746,7 +749,7 @@ fn an_export_without_history_drops_tombstones() {
use document_graph_storage::{Network, NetworkId, RegistryDelta};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xAC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xAC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let id = NetworkId(7);
gdd.stage_constructed_ops(vec![RegistryDelta::AddNetwork { id, network: Network::default() }], &Default::default(), &empty_byte_store())
.unwrap();
+121 -13
View File
@@ -4,7 +4,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NoMetadata, PeerId, Registry};
use document_graph_storage::{NoMetadata, PeerId, Registry, UserId};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
use graph_craft::{ProtoNodeIdentifier, concrete};
@@ -25,7 +25,7 @@ fn network_with_one_node() -> NodeNetwork {
/// A whole-document stage after a recorded batch stages nothing new: restating the batch would fail on the node it added.
#[test]
fn restaging_the_whole_document_after_a_batch_stages_nothing() {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), UserId(21), 1, "ed".into(), "std".into()).unwrap();
let store = HashMapResourceStorage::new();
let resources = ResourceRegistry::new();
gdd.stage_runtime_snapshot(&NodeNetwork::default(), &NoMetadata, &resources, &store)
@@ -57,7 +57,7 @@ fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
attributes: Default::default(),
};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), UserId(22), 1, "ed".into(), "std".into()).unwrap();
gdd.apply_hot_op(set(1, 1)).unwrap();
gdd.apply_hot_op(set(2, 2)).unwrap();
gdd.retire(TimeStamp { counter: 1, peer: PeerId(22) }).unwrap();
@@ -80,28 +80,136 @@ fn a_reopen_continues_the_hot_op_sequence() {
value: Some(Value::from(serde_json::json!(value))),
},
};
fn stage(gdd: &mut GddV1, op: RegistryDelta) -> u64 {
gdd.stage_constructed_ops(vec![op], &Default::default(), &HashMapResourceStorage::new()).unwrap();
gdd.session().hot_log().last().unwrap().sequence.0
}
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), 1, "ed".into(), "std".into()).unwrap();
stage(&mut gdd, set(1));
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), UserId(23), 1, "ed".into(), "std".into()).unwrap();
gdd.stage_ops([set(1)]).unwrap();
let up_to = gdd.session().hot_log().last().unwrap().timestamp;
gdd.retire(up_to).unwrap();
let last = stage(&mut gdd, set(2));
let last = gdd.stage_ops([set(2)]).unwrap().last().unwrap().sequence;
let (working, layout) = gdd.into_storage();
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
assert_eq!(stage(&mut reopened, set(3)), last + 1);
assert_eq!(reopened.stage_ops([set(3)]).unwrap()[0].sequence.0, last.0 + 1);
let up_to = reopened.session().hot_log().last().unwrap().timestamp;
reopened.retire(up_to).unwrap();
let last = reopened.session().last_hot_sequence().0;
let last = reopened.session().last_hot_sequence();
let clock = reopened.session().clock_counter();
let (working, layout) = reopened.into_storage();
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
assert_eq!(reopened.session().clock_counter(), clock, "the clock carries over");
assert_eq!(stage(&mut reopened, set(4)), last + 1);
assert_eq!(reopened.stage_ops([set(4)]).unwrap()[0].sequence.0, last.0 + 1);
});
}
#[test]
fn a_user_change_survives_a_reopen() {
use document_graph_storage::{AttributeDelta, RegistryDelta, Value};
let set = |key: &str| RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: key.into(),
value: Some(Value::from(serde_json::json!(1))),
},
};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(24), UserId(240), 1, "ed".into(), "std".into()).unwrap();
gdd.stage_ops([set("a")]).unwrap();
gdd.retire_pending_interaction().unwrap();
gdd.stage_ops([set("b")]).unwrap();
gdd.set_user(UserId(250), PeerId(25)).unwrap();
let clock = gdd.session().clock_counter();
let (working, layout) = gdd.into_storage();
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
assert_eq!(reopened.session().peer(), PeerId(25));
assert_eq!(reopened.session().user(), UserId(250));
assert_eq!(reopened.session().clock_counter(), clock);
let staged = reopened.stage_ops([set("c")]).unwrap();
assert!(staged.iter().all(|hot_op| hot_op.timestamp.peer == PeerId(25) && hot_op.timestamp.counter > clock));
assert_eq!(staged[0].sequence.0, 1, "the new peer's run starts over");
reopened.retire_pending_interaction().unwrap();
let (working, layout) = reopened.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap();
let session = reopened.session();
assert!(session.hot_log().is_empty(), "the previous user's open step closed and retired");
assert_eq!(session.user_of(PeerId(24)), Some(UserId(240)));
assert_eq!(session.user_of(PeerId(25)), Some(UserId(250)));
assert!(!session.is_mine(PeerId(24)));
assert!(session.is_mine(PeerId(25)));
let authors: Vec<PeerId> = session
.history()
.filter(|delta| matches!(delta.kind, RegistryDelta::ChangeDocumentAttribute { .. }))
.map(|delta| delta.author)
.collect();
assert_eq!(authors, [PeerId(24), PeerId(24), PeerId(25)]);
});
}
/// 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.
#[test]
fn blobs_resolve_after_a_reopen_and_an_archive_round_trip() {
use document_container::AsyncContainer;
use document_format::export::{ExportFormat, ExportOptions};
use document_format::layout::Layout;
use document_graph_storage::{NodeInput, RegistryDelta, Value, blob::BLOB_THRESHOLD};
use graph_craft::document::value::TaggedValue;
let original = TaggedValue::String("a".repeat(BLOB_THRESHOLD));
let edited = TaggedValue::String(format!("b{}", "a".repeat(BLOB_THRESHOLD)));
let mut network = network_with_one_node();
network.nodes.get_mut(&NodeId(1)).unwrap().inputs = vec![graph_craft::document::NodeInput::value(original.clone(), false)];
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(26), UserId(26), 1, "ed".into(), "std".into()).unwrap();
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
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 };
gdd.stage_ops([RegistryDelta::ChangeNodeInput { id, index: 0, new_input }]).unwrap();
gdd.retire_pending_interaction().unwrap();
let edited_blob = gdd.registry().node_instances[&id].inputs()[0].input.blob().expect("staging moves the value into a blob");
let (working, layout) = gdd.into_storage();
let record = working.read(&layout.blob_path(&edited_blob)).await.unwrap();
assert_eq!(record.as_slice()[0], 1, "the edit is stored as a delta");
assert!(record.as_slice().len() < 100, "the delta is small, got {} bytes", record.as_slice().len());
let input_value = |gdd: &GddV1, declarations: &document_graph_storage::Declarations| {
let (converted, _) = gdd.registry().to_runtime_with_metadata(declarations, gdd.blobs()).expect("to_runtime");
let node = converted.nodes.values().next().expect("the node converts");
let graph_craft::document::NodeInput::Value { tagged_value, .. } = &node.inputs[0] else {
panic!("a value input")
};
(**tagged_value).clone()
};
let reopened = GddV1::open_in(working, layout).await.unwrap();
let archive = reopened.export_to_bytes(ExportFormat::Zip, ExportOptions::default(), &store, None).await.unwrap();
let unpacked = GddV1::open_from_archive(&archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.unwrap();
let flat_options = ExportOptions {
include_history: false,
..Default::default()
};
let flat_archive = reopened.export_to_bytes(ExportFormat::Zip, flat_options, &store, None).await.unwrap();
let flat = GddV1::open_from_archive(&flat_archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.unwrap();
let declarations = flat.declarations(&store).await;
assert_eq!(flat.blobs().len(), 1, "a copy without history leaves the undone value behind");
assert_eq!(input_value(&flat, &declarations), edited);
for mut gdd in [reopened, unpacked] {
let declarations = gdd.declarations(&store).await;
assert_eq!(gdd.blobs().len(), 2, "both values' blobs load, the undone one included");
assert_eq!(input_value(&gdd, &declarations), edited);
gdd.undo().unwrap();
assert_eq!(input_value(&gdd, &declarations), original);
}
});
}
+121 -1
View File
@@ -9,7 +9,7 @@ use peer_transport::mock::MockNetwork;
use peer_transport::{Event, SyncTarget};
fn document(peer: u64) -> GddV1 {
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(peer), 1, "editor".into(), "stdlib".into()).expect("create")
}
fn settle(network: &mut MockNetwork, peers: &mut [&mut GddV1]) {
@@ -110,3 +110,123 @@ fn an_interaction_past_a_gap_waits_to_retire() {
assert!(!host.retire_pending_interaction().expect("retire").is_empty());
assert!(host.session().hot_log().is_empty());
}
#[test]
fn the_user_cannot_change_while_connected() {
let mut host = document(1);
let mut network = MockNetwork::new(1);
host.share(network.endpoint(), UserId(1)).expect("share");
assert!(matches!(host.set_user(UserId(2), PeerId(2)), Err(document_format::Error::UserChangeWhileConnected)));
assert_eq!(host.session().peer(), PeerId(1));
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.
#[test]
fn blobs_reach_peers_as_deltas_and_with_a_sync() {
use document_container::AsyncContainer;
use document_format::layout::Layout;
use document_graph_storage::blob::BLOB_THRESHOLD;
use document_graph_storage::{Implementation, Node, NodeId, NodeInput, ROOT_NETWORK, Value};
let text = |length: usize| NodeInput::Value {
value: Value::Str("a".repeat(length)),
exposed: false,
};
let id = NodeId(1);
let mut host = document(1);
let mut guest = document(2);
let mut network = MockNetwork::new(1);
let (host_endpoint, guest_endpoint) = (network.endpoint(), network.endpoint());
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
host.share(host_endpoint, UserId(1)).expect("share");
guest.connect(guest_endpoint, UserId(2)).expect("connect");
network.connect(host_id);
network.connect(guest_id);
settle(&mut network, &mut [&mut host, &mut guest]);
let mut node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(1)), 1);
node.inputs_mut()[0].input = text(BLOB_THRESHOLD);
let root = RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
};
guest.stage_ops([root, RegistryDelta::AddNode { id, node }]).expect("add");
for length in BLOB_THRESHOLD + 1..BLOB_THRESHOLD + 4 {
guest
.stage_ops([RegistryDelta::ChangeNodeInput {
id,
index: 0,
new_input: text(length),
}])
.expect("edit");
}
settle(&mut network, &mut [&mut host, &mut guest]);
let latest = guest.registry().node_instances[&id].inputs()[0].input.blob().expect("the input is a blob");
assert_eq!(host.registry().node_instances[&id].inputs()[0].input.blob(), Some(latest));
assert_eq!(host.blobs().len(), 4, "every version reached the host");
assert!(host.session().all_blob_hashes().iter().all(|hash| host.blobs().contains_key(hash)));
let late_endpoint = network.endpoint();
let late_id = late_endpoint.id();
let mut late = document(3);
late.connect(late_endpoint, UserId(3)).expect("connect");
network.connect(late_id);
settle(&mut network, &mut [&mut host, &mut guest, &mut late]);
assert!(late.is_synced());
assert_eq!(late.blobs(), host.blobs(), "a sync carries every blob");
let (working, layout) = host.into_storage();
let record = futures::executor::block_on(working.read(&layout.blob_path(&latest))).expect("the host wrote the record");
assert_eq!(record.as_slice()[0], 1, "an edit arrives as a delta");
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.
#[test]
fn a_blob_without_its_base_is_asked_for_in_full() {
use document_graph_storage::blob::BLOB_THRESHOLD;
use document_graph_storage::{Implementation, Node, NodeId, NodeInput, ROOT_NETWORK, Value};
let text = |length: usize| NodeInput::Value {
value: Value::Str("a".repeat(length)),
exposed: false,
};
let id = NodeId(1);
let mut author = document(1);
let mut node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(1)), 1);
node.inputs_mut()[0].input = text(BLOB_THRESHOLD);
let root = RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
};
let mut hot_ops = author.stage_ops([root, RegistryDelta::AddNode { id, node }]).expect("add");
hot_ops.extend(
author
.stage_ops([RegistryDelta::ChangeNodeInput {
id,
index: 0,
new_input: text(BLOB_THRESHOLD + 1),
}])
.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
let resource = ResourceHash::from(latest);
// Only the edit's delta record arrives, not the full record it is based on
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");
reader.absorb_blob_records(records).expect("absorb");
assert!(!reader.blobs().contains_key(&latest));
assert!(reader.missing_resources().contains(&resource));
let bytes = author.resource_bytes(resource).expect("the author serves the blob in full");
reader.store_resource(resource, &bytes).expect("store");
assert_eq!(reader.blobs().get(&latest), Some(&bytes));
assert!(!reader.missing_resources().contains(&resource));
}
+196
View File
@@ -0,0 +1,196 @@
//! 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.
use std::collections::{HashMap, HashSet};
use std::fmt;
use crate::{BlobHash, NodeId, NodeInput, Registry, RegistryDelta, ResourceHash, Value};
/// Values whose encoding reaches this many bytes are stored as blobs.
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.
#[derive(Clone, Debug, Default)]
pub struct NewBlobs {
pub bytes: BlobBytes,
pub bases: HashMap<BlobHash, BlobHash>,
}
impl BlobHash {
/// The hash of a blob holding `bytes`.
pub fn of(bytes: &[u8]) -> Self {
Self(ResourceHash::from(bytes))
}
}
impl fmt::Display for BlobHash {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(formatter)
}
}
/// Blob bytes are content addressed like resource bytes, so a peer can fetch a blob through the resource path.
impl From<BlobHash> for ResourceHash {
fn from(hash: BlobHash) -> Self {
hash.0
}
}
/// The value a blob's bytes encode.
pub fn decode_blob(bytes: &[u8]) -> Result<Value, postcard::Error> {
postcard::from_bytes(bytes)
}
impl NodeInput {
/// Replace a value of at least [`BLOB_THRESHOLD`] encoded bytes with the blob of those bytes, collecting them into `bytes`.
pub fn move_into_blob(&mut self, bytes: &mut BlobBytes) {
let NodeInput::Value { value, .. } = self else { return };
if matches!(value, Value::Blob(_)) {
return;
}
// Encoding into memory can't fail
let Ok(encoded) = postcard::to_stdvec(value) else { return };
if encoded.len() < BLOB_THRESHOLD {
return;
}
let hash = BlobHash::of(&encoded);
*value = Value::Blob(hash);
bytes.insert(hash, encoded);
}
}
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::SetNodeInputs { inputs, .. } => inputs,
_ => return,
};
slots.iter_mut().for_each(|slot| slot.input.move_into_blob(bytes));
}
}
impl Registry {
/// Move the large values of every node input into blobs. See [`NodeInput::move_into_blob`].
pub fn move_values_into_blobs(&mut self, bytes: &mut BlobBytes) {
for slot in self.node_instances.values_mut().flat_map(|node| &mut node.inputs) {
slot.input.move_into_blob(bytes);
}
}
/// Every blob the live nodes and the tombstones of removed ones 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`.
pub fn blob_bases(&self, ops: &[RegistryDelta]) -> HashMap<BlobHash, BlobHash> {
let mut latest: HashMap<(NodeId, usize), BlobHash> = HashMap::new();
let mut written = HashSet::new();
let mut bases = HashMap::new();
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());
if written.insert(hash)
&& let Some(previous) = previous
&& previous != hash
{
bases.insert(hash, previous);
}
latest.insert((id, index), hash);
};
for op in ops {
match op {
RegistryDelta::ChangeNodeInput { id, index, new_input } => write(*id, *index as usize, new_input),
RegistryDelta::SetNodeInputs { id, inputs } => inputs.iter().enumerate().for_each(|(index, slot)| write(*id, index, &slot.input)),
_ => {}
}
}
bases
}
/// [`blob_bases`](Self::blob_bases) for the blobs `self` holds where `previous` held another in the same slot, in node ID order.
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);
let mut written = HashSet::new();
let mut bases = HashMap::new();
for (id, node) in nodes {
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())
&& base != hash
{
bases.insert(hash, base);
}
}
}
bases
}
}
#[cfg(test)]
mod tests {
use super::*;
fn value_input(value: Value) -> NodeInput {
NodeInput::Value { value, exposed: false }
}
#[test]
fn only_large_values_become_blobs() {
let mut bytes = BlobBytes::new();
let mut small = value_input(Value::Str("small".into()));
small.move_into_blob(&mut bytes);
assert_eq!(small, value_input(Value::Str("small".into())));
assert!(bytes.is_empty());
let large_value = Value::Str("x".repeat(BLOB_THRESHOLD));
let mut large = value_input(large_value.clone());
large.move_into_blob(&mut bytes);
let hash = large.blob().expect("a large value becomes a blob");
assert_eq!(decode_blob(&bytes[&hash]).unwrap(), large_value);
}
#[test]
fn moving_twice_keeps_the_blob() {
let mut bytes = BlobBytes::new();
let mut input = value_input(Value::Str("x".repeat(BLOB_THRESHOLD)));
input.move_into_blob(&mut bytes);
let once = input.clone();
input.move_into_blob(&mut bytes);
assert_eq!(input, once);
assert_eq!(bytes.len(), 1);
}
#[test]
fn bases_stay_acyclic_when_slots_swap_blobs() {
let [x, a] = [b"x", b"a"].map(|bytes| BlobHash::of(bytes));
let write = |node: u64, hash: BlobHash| RegistryDelta::ChangeNodeInput {
id: NodeId(node),
index: 0,
new_input: value_input(Value::Blob(hash)),
};
let bases = Registry::default().blob_bases(&[write(1, x), write(1, a), write(2, a), write(2, x)]);
assert_eq!(bases, HashMap::from([(a, x)]), "only first writes take a base");
}
}
+35 -1
View File
@@ -1,4 +1,4 @@
use crate::{Attributes, Delta, PeerId, Prior, RegistryDelta, Rev, TimeStamp, Value, attr, compute_rev};
use crate::{Attributes, BlobHash, Delta, InputSlot, NodeField, NodeInput, PeerId, Prior, RegistryDelta, Rev, TimeStamp, Tombstone, Value, attr, compute_rev};
use graphene_resource::ResourceHash;
impl Delta {
@@ -78,6 +78,28 @@ impl Delta {
pub fn has_valid_id(&self) -> bool {
self.id == self.recomputed_id()
}
/// The blobs the op writes or its priors restore.
pub fn blob_hashes(&self) -> impl Iterator<Item = BlobHash> + '_ {
let prior_slots = self.reverse.iter().flat_map(|prior| match prior {
Prior::Node { node, .. }
| Prior::RemovedNode {
tombstone: Tombstone { content: node, .. },
..
} => node.inputs(),
Prior::NodeField {
field: NodeField::Input { previous, .. },
..
} => std::slice::from_ref(previous),
Prior::NodeField {
field: NodeField::Inputs { previous, .. },
..
} => previous.as_slice(),
_ => &[],
});
self.kind.blob_hashes().chain(prior_slots.filter_map(|slot| slot.input.blob()))
}
}
impl RegistryDelta {
@@ -89,6 +111,18 @@ impl RegistryDelta {
_ => None,
}
}
/// The blobs in the input values 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), &[]),
RegistryDelta::AddNode { node, .. } | RegistryDelta::RemoveNode { snapshot: node, .. } => (None, node.inputs()),
RegistryDelta::SetNodeInputs { inputs, .. } => (None, inputs),
_ => (None, &[]),
};
input.into_iter().chain(slots.iter().map(|slot| &slot.input)).filter_map(NodeInput::blob)
}
}
#[cfg(test)]
@@ -9,6 +9,7 @@ use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkId
use serde::Serialize;
use crate::attr::*;
use crate::blob::BlobBytes;
use crate::metadata_source::{NoMetadata, NodeMetadataSource};
use crate::{
ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp, Value, ValueError, from_value,
@@ -118,6 +119,8 @@ 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.
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>,
}
@@ -212,10 +215,14 @@ 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,
network_ids: ctx.network_ids,
})
}
+1
View File
@@ -1,6 +1,7 @@
pub use graphene_resource::{ResourceHash, ResourceId};
pub mod attributes;
pub mod blob;
pub mod crdt;
pub mod delta;
pub mod document;
+11 -1
View File
@@ -1,5 +1,5 @@
use crate::registry::attributes_value_equal;
use crate::{Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeInput, TimeStamp, Value};
use crate::{Attributes, BlobHash, Implementation, InputSlot, Network, NetworkId, Node, NodeInput, TimeStamp, Value};
impl Node {
pub fn implementation(&self) -> &Implementation {
@@ -64,6 +64,16 @@ impl Node {
}
}
impl NodeInput {
/// The hash a value input's bytes are stored under, when it holds a [`Value::Blob`].
pub fn blob(&self) -> Option<BlobHash> {
match self {
NodeInput::Value { value: Value::Blob(hash), .. } => Some(*hash),
_ => None,
}
}
}
impl InputSlot {
/// A slot holding nothing, stamped `timestamp`.
pub fn unset(timestamp: TimeStamp) -> Self {
+6
View File
@@ -1,3 +1,4 @@
use graphene_resource::ResourceHash;
use serde::{Deserialize, Serialize};
/// Stable, document-scoped identity for a node. Minted as a truncated `blake3(peer, counter)` so it
@@ -12,6 +13,11 @@ 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`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct BlobHash(pub ResourceHash);
/// Content-addressed identity for a `Delta`.
/// 128-bit blake3 truncation: comfortable collision headroom for any plausible document lifetime
/// without being adversarial-grade. Same delta content always produces the same `Rev`. Non-zero so
@@ -10,7 +10,7 @@ use std::collections::BTreeMap;
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct SessionState {
/// This peer's identity for the document, stable per (device, document). Per-peer rather than
/// This peer's identity for the document, stable per (device, document, user). Per-peer rather than
/// document identity, so it lives with the cursor here, not in the manifest. Used for CRDT
/// tiebreaking and minting peer-scoped IDs.
#[serde(default)]
+23 -1
View File
@@ -1,3 +1,5 @@
use crate::BlobHash;
use graphene_resource::ResourceHash;
use serde::de::{self, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
@@ -12,6 +14,8 @@ 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`].
Blob(BlobHash),
}
// Using `Serializer::is_human_readable` to determine whether to serialize tagged.
@@ -29,6 +33,7 @@ impl Serialize for Value {
Value::Str(string) => serializer.serialize_str(string),
Value::Array(array) => serializer.collect_seq(array),
Value::Object(object) => serializer.collect_map(object.iter().map(|(key, value)| (key, value))),
Value::Blob(hash) => serializer.collect_map(std::iter::once((Value::BLOB_KEY, hash))),
}
}
}
@@ -97,7 +102,7 @@ impl<'de> Deserialize<'de> for Value {
}
dedup
});
Ok(Value::Object(object))
Ok(Value::from_object(object))
}
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid Value")
@@ -106,3 +111,20 @@ impl<'de> Deserialize<'de> for Value {
deserializer.deserialize_any(Untagged)
}
}
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";
/// 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 {
if let [(key, Value::Str(hex))] = object.as_slice()
&& key == Self::BLOB_KEY
&& let Ok(hash) = ResourceHash::try_from(hex.as_str())
{
return Value::Blob(BlobHash(hash));
}
Value::Object(object)
}
}
+27 -5
View File
@@ -3,8 +3,8 @@ use crate::NodeMetadataSource;
#[cfg(any(feature = "conversion", test))]
use crate::from_runtime;
use crate::{
ApplyMode, Attributes, Delta, Document, History, HotOp, HotOpId, HotSequence, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry,
RetiredMarks, Rev, TimeStamp, Touched, UserId, Value, to_value,
ApplyMode, Attributes, BlobHash, Delta, Document, History, HotOp, HotOpId, HotSequence, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget,
ResourceEntry, RetiredMarks, Rev, TimeStamp, Touched, UserId, Value, to_value,
};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
@@ -55,6 +55,19 @@ impl Session {
self.document.user
}
/// Hand this device to `user` under `peer`, an unused id, so the old peer's ops keep their author.
pub fn set_user(&mut self, user: UserId, peer: PeerId) -> Result<Vec<HotOp>, CrdtError> {
let closing = self.end_interaction()?;
let mut clock = LamportClock::new(peer);
clock.counter = self.document.clock.counter;
self.document.clock = clock;
self.document.peer = peer;
self.document.user = user;
self.document.last_hot_sequence = HotSequence::NONE;
self.document.redo_stack.clear();
Ok(closing)
}
pub fn user_of(&self, peer: PeerId) -> Option<UserId> {
let registered = || self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user);
(peer == self.document.peer).then_some(self.document.user).or_else(registered)
@@ -83,7 +96,9 @@ impl Session {
/// Stages the diff as hot ops rather than retired deltas: each op is applied to the registry and
/// pushed onto the hot log. The caller persists the returned hot frames and then calls `retire`
/// to promote them into durable history.
#[cfg(any(feature = "conversion", test))]
///
/// Large values stay inline, so this is for tests. `Gdd::stage_runtime_snapshot` stages a runtime diff through blobs.
#[cfg(test)]
pub fn stage_from_runtime<M: NodeMetadataSource>(
&mut self,
network: &graph_craft::document::NodeNetwork,
@@ -155,8 +170,7 @@ impl Session {
Ok(revs)
}
/// Stages ops computed outside the session (an incremental runtime projection) as hot ops, the
/// same way `stage_from_runtime` stages a diff's ops.
/// Stages ops computed outside the session, such as a runtime diff or an incremental projection, as hot ops.
pub fn stage_computed_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
self.stage_ops(ops)
}
@@ -999,6 +1013,14 @@ impl Session {
hashes
}
/// Every blob the current registry, its tombstones, history, or hot log names, so any state the cursor reaches can be resolved.
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
}
/// Every referenced resource hash plus what the ops this peer took back named. Garbage collection must keep these.
pub fn resource_gc_roots(&self) -> HashSet<ResourceHash> {
let mut roots = self.all_referenced_resource_hashes();
@@ -281,7 +281,6 @@ fn newest_peer_registration_wins_in_any_order() {
stage_and_retire(&mut device, set_attribute("first", 1));
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10));
// The person at the device changes, so the next batch registers again.
device.document.user = UserId(20);
stage_and_retire(&mut device, set_attribute("second", 2));
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(20));
@@ -296,6 +295,56 @@ fn newest_peer_registration_wins_in_any_order() {
assert_eq!(other.user_of(PeerId(3)), None, "a peer never registered has no user");
}
#[test]
fn a_new_user_takes_a_fresh_peer_and_leaves_the_old_steps_to_their_maker() {
fn interaction(session: &mut Session, key: &str) {
session.stage_ops([set_attribute(key, 1)]).expect("stage");
session.end_interaction().expect("close");
for closed in session.closed_interactions() {
session.retire_interaction(&closed).expect("retire");
}
}
let mut device = Session::with_identity(PeerId(1), UserId(10));
for key in ["a", "b", "c"] {
interaction(&mut device, key);
}
device.undo().expect("undo c");
assert!(device.can_redo());
device.stage_ops([set_attribute("d", 1)]).expect("stage d, left open");
let clock_before = device.clock_counter();
let closing = device.set_user(UserId(20), PeerId(2)).expect("switch");
assert!(closing.iter().all(|hot_op| hot_op.timestamp.peer == PeerId(1)), "the old peer closes its own interaction");
assert!(closing.last().is_some_and(crate::HotOp::ends_interaction));
assert_eq!(device.peer(), PeerId(2));
assert!(device.clock_counter() >= clock_before);
assert!(!device.can_undo(), "the previous user's steps are not this person's to undo");
assert!(!device.can_redo());
assert_eq!(device.user_of(PeerId(1)), Some(UserId(10)));
assert!(!device.is_mine(PeerId(1)));
device.stage_ops([set_attribute("e", 1)]).expect("stage e");
device.end_interaction().expect("close e");
let new_ops: Vec<_> = device.hot_log().iter().filter(|hot_op| hot_op.timestamp.peer == PeerId(2)).collect();
assert_eq!(new_ops.first().map(|hot_op| hot_op.sequence), Some(crate::HotSequence(1)), "the new peer's run starts over");
assert!(new_ops.iter().all(|hot_op| hot_op.timestamp.counter > clock_before));
for closed in device.closed_interactions() {
device.retire_interaction(&closed).expect("retire");
}
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10), "the old registration stands");
assert_eq!(device.user_of(PeerId(2)), Some(UserId(20)));
assert!(device.is_mine(PeerId(2)));
for delta in device.history().filter(|delta| !matches!(delta.kind, RegistryDelta::RegisterPeer { .. })) {
let expected = if delta.author == PeerId(1) { UserId(10) } else { UserId(20) };
assert_eq!(device.user_of(delta.author), Some(expected));
}
assert!(device.can_undo(), "the new user's own step undoes");
device.undo().expect("undo e");
assert!(!device.can_undo(), "but not past it into the previous user's");
}
#[test]
fn a_batch_past_the_last_sequence_is_refused_whole() {
let mut session = Session::with_peer(PeerId(1));
+4 -1
View File
@@ -1453,7 +1453,10 @@ fn an_input_naming_a_node_not_yet_added_renders_dangling() {
}
assert!(document.working_registry.removed_nodes.get(&unseen).is_some_and(|mark| mark.placeholder));
document.working_registry.to_runtime_with_metadata(&crate::Declarations::new()).expect("converts with a dangling input");
document
.working_registry
.to_runtime_with_metadata(&crate::Declarations::new(), &crate::blob::BlobBytes::new())
.expect("converts with a dangling input");
}
/// Remapped tips can swap order, and a merge's `parent` has to stay the lowest.
@@ -4,6 +4,7 @@ use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkId as RuntimeNetworkId, NetworkLocation, NodeInput, NodeNetwork};
use crate::blob::BlobBytes;
use crate::to_runtime::ConversionError;
use crate::{Declarations, Network, NetworkId, NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, Registry};
@@ -72,9 +73,9 @@ fn projecting_a_node_matches_the_whole_conversion() {
let resources = graphene_resource::ResourceRegistry::new();
let conversion = Registry::convert_from_runtime(&nested_network(), &NoMetadata, &resources, PeerId(1)).expect("conversion");
let registry = &conversion.registry;
let (whole, node_entries, _) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
let (whole, node_entries, _) = registry.to_runtime_with_full_metadata(&conversion.declarations, &conversion.blob_bytes).expect("whole conversion");
let projection = registry.runtime_projection(&conversion.declarations);
let projection = registry.runtime_projection(&conversion.declarations, &conversion.blob_bytes);
for &id in registry.node_instances.keys() {
let projected = projection.node(id).expect("every stored node projects");
let (network, local_id) = projection.node_address(id).expect("every stored node has an address");
@@ -96,8 +97,8 @@ fn a_network_entry_projects_its_dense_exports_and_location() {
let resources = graphene_resource::ResourceRegistry::new();
let conversion = Registry::convert_from_runtime(&nested_network(), &NoMetadata, &resources, PeerId(1)).expect("conversion");
let registry = &conversion.registry;
let (whole, _, _) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
let projection = registry.runtime_projection(&conversion.declarations);
let (whole, _, _) = registry.to_runtime_with_full_metadata(&conversion.declarations, &conversion.blob_bytes).expect("whole conversion");
let projection = registry.runtime_projection(&conversion.declarations, &conversion.blob_bytes);
let root = projection.network_entry(ROOT_NETWORK).expect("root");
assert_eq!(root.network, NetworkLocation::default());
@@ -120,8 +121,8 @@ fn an_unreachable_network_has_no_address() {
node.network = NetworkId(5);
registry.node_instances.insert(NodeId(9), node);
let declarations = Declarations::new();
let projection = registry.runtime_projection(&declarations);
let (declarations, blobs) = (Declarations::new(), BlobBytes::new());
let projection = registry.runtime_projection(&declarations, &blobs);
assert_eq!(projection.network_location(NetworkId(5)), None);
assert_eq!(projection.node_address(NodeId(9)), None);
assert!(matches!(projection.node(NodeId(9)), Err(ConversionError::NetworkNotFound(_))));
@@ -140,8 +141,8 @@ fn a_network_several_nodes_implement_has_one_location() {
registry.node_instances.insert(NodeId(id), node);
}
let declarations = Declarations::new();
let projection = registry.runtime_projection(&declarations);
let (declarations, blobs) = (Declarations::new(), BlobBytes::new());
let projection = registry.runtime_projection(&declarations, &blobs);
assert_eq!(projection.network_location(NetworkId(5)), Some(Some(RuntimeNetworkId(5))));
assert_eq!(projection.network_location(ROOT_NETWORK), Some(NetworkLocation::default()));
}
+64 -28
View File
@@ -20,12 +20,12 @@ fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
Ok(())
}
/// Convert a runtime network to a storage `Registry`, returning the declarations alongside it.
/// Convert a runtime network to a storage `Registry`, returning the declarations and blobs alongside it.
/// Proto-node declaration content is no longer stored in the registry (it lives in a byte store);
/// these tests have no byte store, so they keep the extracted `Declarations` in hand for the back-conversion.
fn to_registry(network: &NodeNetwork) -> (Registry, crate::Declarations) {
/// these tests have no byte store, so they keep the extracted `Declarations` and blob bytes in hand for the back-conversion.
fn to_registry(network: &NodeNetwork) -> (Registry, crate::Declarations, crate::blob::BlobBytes) {
let conversion = Registry::convert_from_runtime(network, &crate::NoMetadata, &Default::default(), PeerId(0)).expect("Failed to convert NodeNetwork to Registry");
(conversion.registry, conversion.declarations)
(conversion.registry, conversion.declarations, conversion.blob_bytes)
}
/// A one-node network whose single node references `id` via a `TaggedValue::Resource` input, so
@@ -137,10 +137,10 @@ fn test_simple_round_trip() {
let original_network = create_simple_network();
// Convert to Registry
let (registry, declarations) = to_registry(&original_network);
let (registry, declarations, blobs) = to_registry(&original_network);
// Convert back to NodeNetwork
let (converted_network, _) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back to NodeNetwork");
let (converted_network, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("Failed to convert Registry back to NodeNetwork");
// Verify structure is preserved
assert_eq!(converted_network.nodes.len(), original_network.nodes.len(), "Node count should be preserved");
@@ -185,10 +185,10 @@ fn test_nested_network_round_trip() {
let original_network = create_nested_network();
// Convert to Registry
let (registry, declarations) = to_registry(&original_network);
let (registry, declarations, blobs) = to_registry(&original_network);
// Convert back to NodeNetwork
let (converted_network, _) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back to NodeNetwork");
let (converted_network, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("Failed to convert Registry back to NodeNetwork");
// Verify structure is preserved
assert_eq!(converted_network.nodes.len(), original_network.nodes.len(), "Node count should be preserved");
@@ -213,7 +213,7 @@ fn test_nested_network_round_trip() {
fn test_registry_structure() {
let network = create_simple_network();
let (registry, _declarations) = to_registry(&network);
let (registry, _declarations, _blobs) = to_registry(&network);
assert!(registry.resources.len() >= 2, "Should have proto-node declaration resources");
assert!(!registry.networks.is_empty(), "Should have at least one network");
@@ -281,8 +281,8 @@ fn test_metadata_preservation() {
};
// Convert to Registry and back
let (registry, declarations) = to_registry(&network);
let (converted, _) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert back to NodeNetwork");
let (registry, declarations, blobs) = to_registry(&network);
let (converted, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("Failed to convert back to NodeNetwork");
// Verify call_argument is preserved
let orig_node_0 = network.nodes.get(&NodeId(0)).unwrap();
@@ -327,11 +327,11 @@ fn test_demo_artwork_round_trip() {
original_network.lift_nested_networks();
// Convert to Registry
let (registry, declarations) = to_registry(&original_network);
let (registry, declarations, blobs) = to_registry(&original_network);
// Convert back to NodeNetwork
let (converted_network, _) = registry
.to_runtime_with_metadata(&declarations)
.to_runtime_with_metadata(&declarations, &blobs)
.unwrap_or_else(|e| panic!("Failed to convert {} back to NodeNetwork: {:?}", artwork_name, e));
// Basic structural checks
@@ -470,9 +470,10 @@ fn test_ui_metadata_round_trip() {
let conversion = Registry::convert_from_runtime(&network, &metadata, &Default::default(), PeerId(0)).expect("Failed to convert to Registry with metadata");
let declarations = conversion.declarations;
let blobs = conversion.blob_bytes;
let registry = conversion.registry;
let (converted, entries) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back with metadata");
let (converted, entries) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("Failed to convert Registry back with metadata");
// Graph structure still round-trips.
assert_eq!(converted.nodes.len(), network.nodes.len());
@@ -629,8 +630,8 @@ fn node_input_f64_round_trips_bit_exact() {
..Default::default()
};
let (registry, declarations) = to_registry(&network);
let (converted, _) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime");
let (registry, declarations, blobs) = to_registry(&network);
let (converted, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("to_runtime");
let input = &converted.nodes.get(&NodeId(0)).expect("node 0").inputs[0];
let NodeInput::Value { tagged_value, .. } = input else {
@@ -650,14 +651,14 @@ fn duplicate_runtime_node_id_is_rejected() {
use crate::TimeStamp;
use crate::to_runtime::ConversionError;
let (mut registry, declarations) = to_registry(&create_simple_network());
let (mut registry, declarations, blobs) = to_registry(&create_simple_network());
// Force both root-network nodes onto the same runtime ID.
for node in registry.node_instances.values_mut() {
node.attributes.set(crate::attr::node::ORIGINAL_NODE_ID, crate::Value::Int(7), TimeStamp::ORIGIN);
}
let error = registry.to_runtime_with_metadata(&declarations).expect_err("duplicate runtime ID must error");
let error = registry.to_runtime_with_metadata(&declarations, &blobs).expect_err("duplicate runtime ID must error");
assert!(
matches!(error, ConversionError::DuplicateRuntimeNodeId { runtime_id: 7, .. }),
"expected DuplicateRuntimeNodeId, got {error:?}"
@@ -671,7 +672,7 @@ fn cross_network_reference_is_rejected() {
use crate::to_runtime::ConversionError;
use crate::{Network, NodeInput};
let (mut registry, declarations) = to_registry(&create_simple_network());
let (mut registry, declarations, blobs) = to_registry(&create_simple_network());
// `create_simple_network` wires one node's input to another, both in the root network. Find the
// referenced storage ID, then move that node into a fresh second network so the reference crosses
@@ -690,7 +691,7 @@ fn cross_network_reference_is_rejected() {
registry.networks.insert(other_network, Network::default());
registry.node_instances.get_mut(&referenced_storage_id).expect("referenced node exists").network = other_network;
let error = registry.to_runtime_with_metadata(&declarations).expect_err("cross-network reference must error");
let error = registry.to_runtime_with_metadata(&declarations, &blobs).expect_err("cross-network reference must error");
assert!(matches!(error, ConversionError::CrossNetworkReference { .. }), "expected CrossNetworkReference, got {error:?}");
}
@@ -701,8 +702,8 @@ fn scope_injections_round_trip() {
let mut network = create_simple_network();
network.scope_injections.insert("editor-api".to_string(), (NodeId(0), concrete!(u32)));
let (registry, declarations) = to_registry(&network);
let (converted, _) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime");
let (registry, declarations, blobs) = to_registry(&network);
let (converted, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("to_runtime");
let (node_id, ty) = converted.scope_injections.get("editor-api").expect("scope injection must survive the round trip");
assert_eq!(*node_id, NodeId(0), "the injection's node reference must resolve back to its original runtime ID");
@@ -716,7 +717,7 @@ fn dangling_scope_injection_is_rejected() {
use crate::TimeStamp;
use crate::to_runtime::ConversionError;
let (mut registry, declarations) = to_registry(&create_simple_network());
let (mut registry, declarations, blobs) = to_registry(&create_simple_network());
// Store an injection pointing at a storage ID that no node carries, leaving the reference dangling
// while the rest of the graph stays valid. The root network is whichever one holds the nodes.
@@ -730,7 +731,7 @@ fn dangling_scope_injection_is_rejected() {
.set_serialized(crate::attr::network::SCOPE_INJECTIONS, &injections, TimeStamp::ORIGIN)
.expect("serialize injections");
let error = registry.to_runtime_with_metadata(&declarations).expect_err("dangling scope injection must error");
let error = registry.to_runtime_with_metadata(&declarations, &blobs).expect_err("dangling scope injection must error");
assert!(matches!(error, ConversionError::DanglingScopeInjection { .. }), "expected DanglingScopeInjection, got {error:?}");
}
@@ -776,7 +777,9 @@ fn cyclic_network_reference_is_rejected() {
},
);
let error = registry.to_runtime_with_metadata(&crate::Declarations::new()).expect_err("cyclic network reference must error");
let error = registry
.to_runtime_with_metadata(&crate::Declarations::new(), &crate::blob::BlobBytes::new())
.expect_err("cyclic network reference must error");
assert!(matches!(error, ConversionError::CyclicNetwork(_)), "expected CyclicNetwork, got {error:?}");
}
@@ -805,7 +808,7 @@ fn a_shared_table_entry_round_trips_as_one_network() {
network.nodes.get_mut(&NodeId(1)).expect("node 1").implementation = DocumentNodeImplementation::Definition(shared);
network.nodes.get_mut(&NodeId(1)).expect("node 1").inputs = vec![NodeInput::node(NodeId(0), 0)];
let (registry, declarations) = to_registry(&network);
let (registry, declarations, blobs) = to_registry(&network);
assert_eq!(registry.networks.len(), 2, "the root and the one shared entry");
assert!(registry.networks.contains_key(&NetworkId(shared.0)), "the entry is stored under its own ID");
@@ -815,7 +818,7 @@ fn a_shared_table_entry_round_trips_as_one_network() {
"the shared body is stored once"
);
let (converted, _) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime");
let (converted, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("to_runtime");
assert_eq!(converted, network);
}
@@ -855,6 +858,39 @@ fn an_unreached_table_entry_is_not_stored() {
let mut network = create_simple_network();
network.definitions.insert(RuntimeNetworkId(5), create_simple_network());
let (registry, _) = to_registry(&network);
let (registry, ..) = to_registry(&network);
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.
#[test]
fn large_input_value_round_trips_through_a_blob() {
use graph_craft::document::value::TaggedValue;
let large = TaggedValue::String("x".repeat(crate::blob::BLOB_THRESHOLD));
let network = NodeNetwork {
nodes: [(
NodeId(0),
DocumentNode {
inputs: vec![NodeInput::value(large, false), NodeInput::value(TaggedValue::Number(1.), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
..Default::default()
},
)]
.into_iter()
.collect(),
..Default::default()
};
let (registry, declarations, blobs) = to_registry(&network);
let inputs = registry.node_instances.values().next().expect("the node converts").inputs();
let blob = inputs[0].input.blob().expect("the large value becomes a blob");
assert!(inputs[1].input.blob().is_none(), "a small value stays inline");
assert_eq!(blobs.keys().collect::<Vec<_>>(), [&blob]);
let (converted, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("to_runtime");
assert_eq!(converted, network);
let error = registry.to_runtime_with_metadata(&declarations, &crate::blob::BlobBytes::new()).expect_err("a missing blob must error");
assert!(matches!(error, crate::to_runtime::ConversionError::BlobNotFound(hash) if hash == blob), "{error}");
}
+34 -16
View File
@@ -9,8 +9,9 @@ use graph_craft::{ProtoNodeIdentifier, Type, concrete};
use rustc_hash::{FxHashMap, FxHashSet};
use crate::attr::*;
use crate::blob::{BlobBytes, decode_blob};
use crate::metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry};
use crate::{Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
use crate::{BlobHash, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
#[derive(Debug, thiserror::Error)]
pub enum ConversionError {
@@ -22,6 +23,8 @@ pub enum ConversionError {
DeclarationNotFound(ResourceId),
#[error("Deserialization error: {0}")]
DeserializationError(String),
#[error("Blob {0} not found in provided blobs")]
BlobNotFound(BlobHash),
#[error("Network {network} has two nodes mapping to runtime ID {runtime_id}")]
DuplicateRuntimeNodeId { network: NetworkId, runtime_id: u64 },
#[error("Network {network} references node {referenced}, which lives in a different network")]
@@ -40,8 +43,8 @@ pub type Declarations = std::collections::HashMap<ResourceId, ProtoNode>;
impl Registry {
/// Returns the network plus one metadata entry per node, since every node carries an identity to
/// restore even when it has no `ui::*` attribute.
pub fn to_runtime_with_metadata(&self, declarations: &Declarations) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>), ConversionError> {
let (network, node_entries, _) = self.to_runtime_with_full_metadata(declarations)?;
pub fn to_runtime_with_metadata(&self, declarations: &Declarations, blobs: &BlobBytes) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>), ConversionError> {
let (network, node_entries, _) = self.to_runtime_with_full_metadata(declarations, blobs)?;
Ok((network, node_entries))
}
@@ -50,11 +53,11 @@ impl Registry {
///
/// Every network the root reaches becomes an entry in the root's definitions table under its storage ID.
/// The nodes that implement it name it by that ID.
pub fn to_runtime_with_full_metadata(&self, declarations: &Declarations) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>, Vec<NetworkMetadataEntry>), ConversionError> {
pub fn to_runtime_with_full_metadata(&self, declarations: &Declarations, blobs: &BlobBytes) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>, Vec<NetworkMetadataEntry>), ConversionError> {
let mut node_metadata = Vec::new();
let mut network_metadata = Vec::new();
let context = ConversionContext::new(self, declarations);
let context = ConversionContext::new(self, declarations, blobs);
// Reject cycles first because the runtime cannot inline a definition that contains itself
detect_network_cycle(&context, ROOT_NETWORK)?;
@@ -96,11 +99,12 @@ impl Registry {
struct ConversionContext<'a> {
registry: &'a Registry,
declarations: &'a Declarations,
blobs: &'a BlobBytes,
nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &'a Node)>>,
}
impl<'a> ConversionContext<'a> {
fn new(registry: &'a Registry, declarations: &'a Declarations) -> Self {
fn new(registry: &'a Registry, declarations: &'a Declarations, blobs: &'a BlobBytes) -> Self {
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
for (&global_id, node) in &registry.node_instances {
nodes_by_network.entry(node.network).or_default().push((global_id, node));
@@ -108,10 +112,17 @@ impl<'a> ConversionContext<'a> {
Self {
registry,
declarations,
blobs,
nodes_by_network,
}
}
/// The value blob `hash` holds.
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}")))
}
/// The networks other than the root that the root reaches through node implementations.
fn reachable_definitions(&self) -> FxHashSet<NetworkId> {
let mut reached = FxHashSet::default();
@@ -175,8 +186,8 @@ pub struct RuntimeProjection<'a> {
}
impl Registry {
pub fn runtime_projection<'a>(&'a self, declarations: &'a Declarations) -> RuntimeProjection<'a> {
let context = ConversionContext::new(self, declarations);
pub fn runtime_projection<'a>(&'a self, declarations: &'a Declarations, blobs: &'a BlobBytes) -> RuntimeProjection<'a> {
let context = ConversionContext::new(self, declarations, blobs);
RuntimeProjection {
reachable: context.reachable_definitions(),
context,
@@ -225,7 +236,7 @@ impl RuntimeProjection<'_> {
Ok(ProjectedNetwork {
metadata: extract_network_metadata(registry, &network.attributes, location, id),
scope_injections: read_scope_injections(registry, id, &network.attributes)?,
exports: convert_exports(registry, id, network)?,
exports: convert_exports(&self.context, id, network)?,
network: location,
})
}
@@ -233,7 +244,7 @@ impl RuntimeProjection<'_> {
/// Rejects a registry whose root reaches a network cycle.
pub(crate) fn reject_network_cycles(registry: &Registry, declarations: &Declarations) -> Result<(), ConversionError> {
detect_network_cycle(&ConversionContext::new(registry, declarations), ROOT_NETWORK)
detect_network_cycle(&ConversionContext::new(registry, declarations, &BlobBytes::new()), ROOT_NETWORK)
}
/// Rejects any cycle in the graph of `Implementation::Network` references from a network to the networks its nodes implement.
@@ -314,7 +325,7 @@ fn convert_network(
}
}
let exports = convert_exports(context.registry, network_id, network)?;
let exports = convert_exports(context, network_id, network)?;
let scope_injections = read_scope_injections(context.registry, network_id, &network.attributes)?;
Ok(NodeNetwork {
@@ -327,14 +338,14 @@ fn convert_network(
}
/// The network's exports, compacted into the runtime's dense list.
fn convert_exports(registry: &Registry, network_id: NetworkId, network: &crate::Network) -> Result<Vec<GraphCraftNodeInput>, ConversionError> {
fn convert_exports(context: &ConversionContext, network_id: NetworkId, network: &crate::Network) -> Result<Vec<GraphCraftNodeInput>, ConversionError> {
// Input attributes aren't round-tripped for exports — Reflection/Import inputs don't appear there.
let empty_attrs = crate::Attributes::new();
network
.exports
.iter()
.filter_map(|slot| slot.target.as_ref())
.map(|input| convert_input(registry, network_id, input, &empty_attrs))
.map(|input| convert_input(context, network_id, input, &empty_attrs))
.collect()
}
@@ -438,7 +449,7 @@ fn convert_node(context: &ConversionContext, node: &crate::Node) -> Result<Docum
let inputs = node
.inputs
.iter()
.map(|slot| convert_input(context.registry, node.network, &slot.input, &slot.attributes))
.map(|slot| convert_input(context, node.network, &slot.input, &slot.attributes))
.collect::<Result<Vec<_>, _>>()?;
// Defaults must match `DocumentNode::default()` (and the `set_if_not_default` calls in `from_runtime`).
@@ -454,7 +465,9 @@ fn convert_node(context: &ConversionContext, node: &crate::Node) -> Result<Docum
})
}
fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
fn convert_input(context: &ConversionContext, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
let registry = context.registry;
Ok(match input {
NodeInput::Node { id: node_id, index: output_index } => {
// A node removed concurrently keeps its id, as the editor holds a dangling input. So does one whose addition has not
@@ -477,7 +490,12 @@ fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput,
}
}
NodeInput::Value { value, exposed } => {
let tagged_value: TaggedValue = from_value(value).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
let value = match value {
Value::Blob(hash) => Cow::Owned(context.resolve_blob(*hash)?),
value => Cow::Borrowed(value),
};
let tagged_value: TaggedValue = from_value(&value).map_err(|e| ConversionError::DeserializationError(format!("TaggedValue: {e:?}")))?;
GraphCraftNodeInput::Value {
tagged_value: MemoHash::new(tagged_value),
exposed: *exposed,
+24 -1
View File
@@ -27,7 +27,7 @@ impl From<serde_json::Value> for Value {
}
Json::String(string) => Value::Str(string),
Json::Array(array) => Value::Array(array.into_iter().map(Into::into).collect()),
Json::Object(object) => Value::Object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
Json::Object(object) => Value::from_object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
}
}
}
@@ -47,6 +47,7 @@ impl From<Value> for serde_json::Value {
Value::Str(string) => Json::String(string),
Value::Array(array) => Json::Array(array.into_iter().map(Into::into).collect()),
Value::Object(object) => Json::Object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
Value::Blob(hash) => serde_json::json!({ Value::BLOB_KEY: String::from(&hash.0) }),
}
}
}
@@ -58,6 +59,7 @@ pub struct ValueError(serde_json::Error);
#[cfg(test)]
mod tests {
use super::*;
use crate::{BlobHash, ResourceHash};
use serde::Deserialize;
#[test]
@@ -157,5 +159,26 @@ mod tests {
assert_eq!(encode(Value::Str("ab".into())), [4, 2, b'a', b'b']);
assert_eq!(encode(Value::Array(vec![Value::None])), [5, 1, 0]);
assert_eq!(encode(Value::Object(vec![("k".into(), Value::None)])), [6, 1, 1, b'k', 0]);
assert_eq!(encode(Value::Blob(BlobHash(ResourceHash::from([9; 32]))))[..2], [7, 32]);
}
#[test]
fn blob_round_trips_as_reserved_object() {
let blob = Value::Blob(BlobHash::of(b"bytes"));
let text = serde_json::to_string(&blob).unwrap();
assert!(text.starts_with(r#"{"$blob":""#), "got {text}");
assert_eq!(serde_json::from_str::<Value>(&text).unwrap(), blob);
assert_eq!(Value::from(serde_json::Value::from(blob.clone())), blob);
let bytes = postcard::to_stdvec(&blob).unwrap();
assert_eq!(postcard::from_bytes::<Value>(&bytes).unwrap(), blob);
}
#[test]
fn reserved_key_without_a_hash_stays_an_object() {
for json in [r#"{"$blob": "not a hash"}"#, r#"{"$blob": 1}"#, r#"{"$blob": "", "other": 1}"#] {
assert!(matches!(serde_json::from_str::<Value>(json).unwrap(), Value::Object(_)), "{json}");
}
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ graph-craft = { workspace = true }
graphene-std = { workspace = true }
migration-core = { workspace = true, features = ["typed"] }
preprocessor = { workspace = true }
serde = { workspace = true }
[dev-dependencies]
migration-runner = { workspace = true, features = ["testing"] }
serde = { workspace = true }
+4 -2
View File
@@ -1,3 +1,4 @@
use document_graph_storage::blob::BlobBytes;
use document_graph_storage::{Declarations, Implementation, NodeId, Registry, ResourceId};
use graph_craft::Type;
use graph_craft::document::{NodeId as RuntimeNodeId, NodeNetwork};
@@ -58,8 +59,9 @@ impl MigrationHost for CompilerHost {
}
}
// A state that doesn't convert answers nothing, so each migration asking takes its fallback
let (mut inlined, nodes, _) = state.to_runtime_with_full_metadata(&declarations).ok()?;
// 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.
let (mut inlined, nodes, _) = state.to_runtime_with_full_metadata(&declarations, &BlobBytes::new()).ok()?;
inlined.inline_definitions().ok()?;
Some(Box::new(StateCompiler {
+1
View File
@@ -2,5 +2,6 @@
//! Unlike `migration-nodes`, these link the node crates and depend on the build they run in, so a document's peers can't all reach the same result.
mod compiler;
mod vary_nodes_from_copy_to_points;
pub use compiler::CompilerHost;
@@ -0,0 +1,272 @@
use document_graph_storage::attr::node::VISIBLE;
use graphene_std::Color;
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::vector::Vector;
use graphene_std::vector::style::Gradient;
use migration_core::{Compiler, Inputs, MigrationError, NewNode, Node, NodeInput, Target, Upstream, decl, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const CONTENT: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration uses.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Integer(i64),
Bool(bool),
}
fn number(input: &NodeInput) -> Option<f64> {
match literal_of::<Tagged>(input) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
}
}
/// Copy to Points becomes Into Group, Repeat on Points, Vary Rotations, Vary Scales, and a flatten back to the content's element type, ending at the
/// anchor to keep its downstream wires. Grouping makes each copy one row for the vary nodes, and keeps the offsets of its content, whose translation
/// Repeat on Points overwrites. Content that doesn't compile takes Flatten Graphic, which can't make that state any worse. A hidden node only passes
/// its points through, so it needs nothing past the repeat, and its unused scale and rotation are dropped.
#[migration("core_types::vector::CopyToPointsNode"@1 => "transform_nodes::transform_nodes::VaryRotationsNode"@2)]
pub fn vary_nodes_from_copy_to_points(node: &Node, compiler: Option<&dyn Compiler>, inputs: &mut Inputs, upstream: &mut Upstream, target: &mut Target) -> Result<(), MigrationError> {
let slots: Vec<NodeInput> = node.inputs().iter().map(|slot| slot.input.clone()).collect();
let [points, content, scale_min, scale_max, scale_bias, scale_seed, rotation, rotation_seed] =
<[NodeInput; 8]>::try_from(slots).map_err(|_| MigrationError::invariant("Copy to Points has eight inputs"))?;
let repeat = decl!("repeat_nodes::repeat_nodes::RepeatOnPointsNode"@1);
let unset = || literal(Tagged::Bool(false));
let visible = node.attributes().get_or(VISIBLE, true);
if !visible {
target.set(repeat);
replace_inputs(inputs, vec![points, content, unset()]);
return Ok(());
}
let content_type = compiler.and_then(|compiler| compiler.input_type(node, CONTENT));
let fallback = decl!("graphic_nodes::graphic::FlattenGraphicNode"@1);
let flatten = match &content_type {
Some(content) if content.element_is::<Vector>() => decl!("graphic_nodes::graphic::FlattenVectorNode"@1),
Some(content) if content.element_is::<Raster<CPU>>() => decl!("graphic_nodes::graphic::FlattenRasterNode"@1),
Some(content) if content.element_is::<Color>() => decl!("graphic_nodes::graphic::FlattenColorNode"@1),
Some(content) if content.element_is::<Gradient>() => decl!("graphic_nodes::graphic::FlattenGradientNode"@1),
_ => fallback,
};
// Text has no group to go in, so its rows are repeated as they are
let groups = !content_type.as_ref().is_some_and(|content| content.element_is::<String>());
let group = groups.then(|| {
upstream.add_node(NewNode {
declaration: decl!("graphic_nodes::graphic::IntoGroupNode"@1),
inputs: vec![content.clone()],
})
});
let repeated_content = group.map_or(content, |group| NodeInput::Node { id: group, index: 0 });
let mut stages = vec![(repeat, vec![points, repeated_content, unset()])];
// The rotation range was centered on zero, so a wired one is halved to each side by Multiply nodes
if number(&rotation) != Some(0.) {
let mut half = |factor: f64, key: &str| match number(&rotation) {
Some(rotation) => literal(Tagged::Number(rotation * factor)),
None => {
let multiply = upstream.add_node_keyed(
NewNode {
declaration: decl!("math_nodes::MultiplyNode"@1),
inputs: vec![rotation.clone(), literal(Tagged::Number(factor))],
},
key,
);
NodeInput::Node { id: multiply, index: 0 }
}
};
let (min, max) = (half(-0.5, "min"), half(0.5, "max"));
stages.push((
decl!("transform_nodes::transform_nodes::VaryRotationsNode"@2),
vec![
unset(),
min,
max,
literal(Tagged::Number(0.5)),
unset(),
literal(Tagged::Bool(true)),
rotation_seed,
literal(Tagged::Integer(0)),
],
));
}
// A wired bias can't be converted, so it is left at the default
if number(&scale_min) != Some(1.) || number(&scale_max) != Some(1.) {
let bias = number(&scale_bias).map_or(0.5, bias_keeping_average_scale);
stages.push((
decl!("transform_nodes::transform_nodes::VaryScalesNode"@1),
vec![
unset(),
scale_min,
scale_max,
literal(Tagged::Number(bias)),
unset(),
literal(Tagged::Bool(true)),
scale_seed,
literal(Tagged::Integer(0)),
],
));
}
if groups {
let fully_flatten = (flatten == fallback).then(unset);
stages.push((flatten, std::iter::once(unset()).chain(fully_flatten).collect()));
}
// Each stage reads the one before it, up to the last, which is the anchor
let Some((last_declaration, mut last_inputs)) = stages.pop() else { return Ok(()) };
let mut previous = None;
for (declaration, mut stage_inputs) in stages {
if let Some(id) = previous {
stage_inputs[0] = NodeInput::Node { id, index: 0 };
}
previous = Some(upstream.add_node(NewNode { declaration, inputs: stage_inputs }));
}
if let Some(id) = previous {
last_inputs[0] = NodeInput::Node { id, index: 0 };
}
target.set(last_declaration);
replace_inputs(inputs, last_inputs);
Ok(())
}
fn replace_inputs(inputs: &mut Inputs, replacement: Vec<NodeInput>) {
inputs.truncate(0);
for input in replacement {
inputs.push(input);
}
}
/// The Vary Scales bias giving the same average scale, as a fraction of its range, that Copy to Points' random scale distribution had for its bias.
fn bias_keeping_average_scale(bias: f64) -> f64 {
if bias.abs() < 1e-6 {
return 0.5;
}
// Its bias curve `log2(1 + r (2^b - 1)) / b` averages `2^b / (2^b - 1) - 1 / (b ln 2)`, written with `x = b ln 2` to stay finite for a large bias
let x = bias * std::f64::consts::LN_2;
let average = -1. / (-x).exp_m1() - 1. / x;
// The new curve averages `k / (k + 1)` for `1 - (1 - t)^k` below a bias of 0.5, where `k = -log2(1 - bias)`, and `1 / (p + 1)` for `t^p` above it, where `p = -log2(bias)`
if average < 0.5 {
let k = average / (1. - average);
1. - (-k).exp2()
} else {
let p = 1. / average - 1.;
(-p).exp2()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::CompilerHost;
use migration_core::Declaration;
use migration_runner::testing::{Fixture, Random, SourceContract, check_commutation_with, check_undo_with};
const COPY_TO_POINTS: Declaration = decl!("core_types::vector::CopyToPointsNode"@1);
const STAR: Declaration = decl!("vector_nodes::generator_nodes::StarNode"@1);
const FLATTEN_VECTOR: Declaration = decl!("graphic_nodes::graphic::FlattenVectorNode"@1);
const FLATTEN_GRAPHIC: Declaration = decl!("graphic_nodes::graphic::FlattenGraphicNode"@1);
const VARY_ROTATIONS: Declaration = decl!("transform_nodes::transform_nodes::VaryRotationsNode"@2);
fn host() -> CompilerHost {
CompilerHost::default()
}
fn contract() -> SourceContract {
SourceContract::new(8, |random: &mut Random, slot| match slot {
2 | 3 | 4 | 6 => literal(Tagged::Number(random.below(3) as f64)),
_ => literal(Tagged::Integer(random.below(3) as i64)),
})
}
fn star_inputs() -> Vec<NodeInput> {
vec![literal(Tagged::None), literal(Tagged::Integer(5)), literal(Tagged::Number(50.)), literal(Tagged::Number(25.))]
}
fn inputs(content: NodeInput, scale: f64, rotation: f64) -> Vec<NodeInput> {
let number = |number| literal(Tagged::Number(number));
let integer = |integer| literal(Tagged::Integer(integer));
vec![literal(Tagged::Integer(0)), content, number(scale), number(scale), number(0.), integer(1), number(rotation), integer(2)]
}
#[test]
fn rewrites_history() {
let host = host();
check_commutation_with(&VaryNodesFromCopyToPoints, &contract(), Some(&host));
check_undo_with(&VaryNodesFromCopyToPoints, &contract(), Some(&host));
}
#[test]
fn typed_content_ends_in_the_flatten_of_its_element() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let star = fixture.add(STAR, star_inputs());
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 1., 0.));
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
assert_eq!(fixture.declaration_of(&migrated, copies), Some(FLATTEN_VECTOR));
assert_eq!(fixture.inputs(&migrated, copies).len(), 1);
}
#[test]
fn content_that_does_not_compile_keeps_flatten_graphic() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let unknown = fixture.add(decl!("migration_testing::unknown"@1), vec![]);
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: unknown, index: 0 }, 2., 0.));
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
assert_eq!(fixture.declaration_of(&migrated, copies), Some(FLATTEN_GRAPHIC));
assert_eq!(fixture.inputs(&migrated, copies).len(), 2);
}
#[test]
fn text_is_repeated_without_a_group() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let text = fixture.add(decl!("text_nodes::AsStringNode"@1), vec![literal(Tagged::Number(1.))]);
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: text, index: 0 }, 1., 90.));
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
assert_eq!(fixture.declaration_of(&migrated, copies), Some(VARY_ROTATIONS));
let NodeInput::Node { id: repeat, .. } = fixture.inputs(&migrated, copies)[0] else {
panic!("the rotations read the repeat")
};
assert_eq!(fixture.inputs(&migrated, repeat)[1], NodeInput::Node { id: text, index: 0 });
}
#[test]
fn rotation_range_is_centered() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let star = fixture.add(STAR, star_inputs());
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 1., 90.));
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
let NodeInput::Node { id: rotations, .. } = fixture.inputs(&migrated, copies)[0] else {
panic!("the flatten reads the last stage")
};
assert_eq!(fixture.declaration_of(&migrated, rotations), Some(VARY_ROTATIONS));
assert_eq!(number(&fixture.inputs(&migrated, rotations)[1]), Some(-45.));
assert_eq!(number(&fixture.inputs(&migrated, rotations)[2]), Some(45.));
}
#[test]
fn bias_keeps_its_average() {
assert_eq!(bias_keeping_average_scale(0.), 0.5);
assert!(bias_keeping_average_scale(-10.) < 0.5);
assert!(bias_keeping_average_scale(10.) > 0.5);
assert!(bias_keeping_average_scale(100.).is_finite());
}
}
+1
View File
@@ -16,6 +16,7 @@ typed = ["dep:document-graph-storage", "dep:blake3"]
[dependencies]
document-graph-storage = { workspace = true, optional = true }
migration-macros = { workspace = true }
graphene-resource = { workspace = true }
blake3 = { workspace = true, optional = true }
ctor = { workspace = true }
+24
View File
@@ -1,3 +1,7 @@
use std::collections::HashMap;
use graphene_resource::ResourceHash;
use crate::{MigrationError, Payload};
/// How stored history survives a format step.
@@ -15,6 +19,22 @@ pub enum HistoryPolicy {
Truncate,
}
/// The serialized payloads of one document, as handed over by the load path before typed
/// deserialization. History records are unframed: one [`Payload`] per retired delta, in stored
/// (topological) order. A working copy that only has history has no registry.
#[derive(Clone, Debug, Default)]
pub struct DocumentPayloads {
pub format_version: u32,
pub registry: Option<Payload>,
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.
pub blobs: HashMap<ResourceHash, Vec<u8>>,
/// For each blob in `blobs`, the blob a store can encode it against.
pub blob_bases: HashMap<ResourceHash, ResourceHash>,
}
/// One whole-document format step, migrating version `migrates_from()` to `migrates_from() + 1`.
///
/// Usually generated by `format_migration!` over the frozen types of `migration-formats`. Steps only transform payload
@@ -42,6 +62,10 @@ 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.
fn migrate_document(&self, _document: &mut DocumentPayloads) -> Result<(), MigrationError> {
Ok(())
}
}
/// Converts a frozen stored type to its counterpart in the next format version. `cargo run migration snapshot`
+1 -1
View File
@@ -31,7 +31,7 @@ pub use declaration::{Declaration, DeclarationResolver};
#[cfg(feature = "typed")]
pub use document_graph_storage::NodeInput;
pub use error::MigrationError;
pub use format::{FormatMigration, HistoryPolicy, Upgrade};
pub use format::{DocumentPayloads, FormatMigration, HistoryPolicy, Upgrade};
#[cfg(feature = "typed")]
pub use migration::{NodeMigration, Rename};
pub use migration_macros::format_migration;
+1 -1
View File
@@ -11,11 +11,11 @@ publish.workspace = true
migration-core = { workspace = true }
graphene-resource = { workspace = true, features = ["serde"] }
postcard = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }
[dev-dependencies]
document-graph-storage = { workspace = true }
postcard = { workspace = true }
serde_json = { workspace = true }
+2 -1
View File
@@ -7,6 +7,7 @@
pub mod v1;
pub mod v2;
pub mod v3;
pub use v3 as latest;
pub mod v4;
pub use v4 as latest;
mod steps;
@@ -2,3 +2,4 @@
mod v1_to_v2;
mod v2_to_v3;
mod v3_to_v4;
@@ -0,0 +1,667 @@
//! 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.
use crate::{v3, v4};
use graphene_resource::ResourceHash;
use migration_core::{DocumentPayloads, MigrationError, Upgrade, format_migration};
use std::collections::HashMap;
format_migration! {
3 => 4,
registry: v3::Registry,
delta: v3::Delta,
hot_op: v3::HotOp,
session: v3::SessionState,
document: move_values_into_blobs,
}
impl Upgrade for v3::AttributeValue {
type Next = v4::AttributeValue;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
let v3::AttributeValue { value, timestamp, deleted } = self;
Ok(v4::AttributeValue {
value: Upgrade::upgrade(value)?,
timestamp,
deleted,
})
}
}
impl Upgrade for v3::Attributes {
type Next = v4::Attributes;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
let v3::Attributes { entries, floor } = self;
Ok(v4::Attributes {
entries: entries
.into_iter()
.map(|(key, entry)| Ok::<_, MigrationError>((key, Upgrade::upgrade(entry)?)))
.collect::<Result<_, MigrationError>>()?,
floor,
})
}
}
impl Upgrade for v3::Delta {
type Next = v4::Delta;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
let v3::Delta {
id,
parent,
author,
timestamp,
kind,
reverse,
attributes,
retired_at_ms,
} = self;
Ok(v4::Delta {
id,
parent,
author,
timestamp,
kind: Upgrade::upgrade(kind)?,
reverse: reverse.into_iter().map(Upgrade::upgrade).collect::<Result<_, MigrationError>>()?,
attributes: Upgrade::upgrade(attributes)?,
retired_at_ms,
})
}
}
impl Upgrade for v3::RegistryDelta {
type Next = v4::RegistryDelta;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
Ok(match self {
v3::RegistryDelta::AddNode { id, node } => v4::RegistryDelta::AddNode { id, node: Upgrade::upgrade(node)? },
v3::RegistryDelta::RemoveNode { id, snapshot } => v4::RegistryDelta::RemoveNode {
id,
snapshot: Upgrade::upgrade(snapshot)?,
},
v3::RegistryDelta::ChangeNodeInput { id, index, new_input } => v4::RegistryDelta::ChangeNodeInput {
id,
index,
new_input: Upgrade::upgrade(new_input)?,
},
v3::RegistryDelta::SetNodeInputs { id, inputs } => v4::RegistryDelta::SetNodeInputs {
id,
inputs: inputs.into_iter().map(Upgrade::upgrade).collect::<Result<_, MigrationError>>()?,
},
v3::RegistryDelta::SetNodeImplementation { id, implementation } => v4::RegistryDelta::SetNodeImplementation { id, implementation },
v3::RegistryDelta::ChangeNodeAttribute { id, delta } => v4::RegistryDelta::ChangeNodeAttribute { id, delta: Upgrade::upgrade(delta)? },
v3::RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => v4::RegistryDelta::ChangeNodeInputAttribute {
id,
index,
delta: Upgrade::upgrade(delta)?,
},
v3::RegistryDelta::SetNetworkExport { id, index, export } => v4::RegistryDelta::SetNetworkExport {
id,
index,
export: export.map(Upgrade::upgrade).transpose()?,
},
v3::RegistryDelta::ChangeNetworkAttribute { id, delta } => v4::RegistryDelta::ChangeNetworkAttribute { id, delta: Upgrade::upgrade(delta)? },
v3::RegistryDelta::AddNetwork { id, network } => v4::RegistryDelta::AddNetwork {
id,
network: Upgrade::upgrade(network)?,
},
v3::RegistryDelta::RemoveNetwork { id, snapshot } => v4::RegistryDelta::RemoveNetwork {
id,
snapshot: Upgrade::upgrade(snapshot)?,
},
v3::RegistryDelta::AddResource { id, entry } => v4::RegistryDelta::AddResource { id, entry: Upgrade::upgrade(entry)? },
v3::RegistryDelta::SetResourceHash { id, hash } => v4::RegistryDelta::SetResourceHash { id, hash },
v3::RegistryDelta::RemoveResource { id, snapshot } => v4::RegistryDelta::RemoveResource {
id,
snapshot: Upgrade::upgrade(snapshot)?,
},
v3::RegistryDelta::AddSource { id, key, source } => v4::RegistryDelta::AddSource {
id,
key,
source: Upgrade::upgrade(source)?,
},
v3::RegistryDelta::RemoveSource { id, key } => v4::RegistryDelta::RemoveSource { id, key },
v3::RegistryDelta::RegisterPeer { peer, user } => v4::RegistryDelta::RegisterPeer { peer, user },
v3::RegistryDelta::ChangeDocumentAttribute { delta } => v4::RegistryDelta::ChangeDocumentAttribute { delta: Upgrade::upgrade(delta)? },
v3::RegistryDelta::Merge { extra_parents } => v4::RegistryDelta::Merge { extra_parents },
v3::RegistryDelta::Meta => v4::RegistryDelta::Meta,
v3::RegistryDelta::Other(field_0) => v4::RegistryDelta::Other(Upgrade::upgrade(field_0)?),
})
}
}
impl Upgrade for v3::AttributeDelta {
type Next = v4::AttributeDelta;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
let v3::AttributeDelta { key, value } = self;
Ok(v4::AttributeDelta {
key,
value: value.map(Upgrade::upgrade).transpose()?,
})
}
}
impl Upgrade for v3::Node {
type Next = v4::Node;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
let v3::Node {
presence,
network,
network_timestamp,
implementation,
implementation_timestamp,
inputs,
inputs_timestamp,
attributes,
} = self;
Ok(v4::Node {
presence,
network,
network_timestamp,
implementation,
implementation_timestamp,
inputs: inputs.into_iter().map(Upgrade::upgrade).collect::<Result<_, MigrationError>>()?,
inputs_timestamp,
attributes: Upgrade::upgrade(attributes)?,
})
}
}
impl Upgrade for v3::InputSlot {
type Next = v4::InputSlot;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
let v3::InputSlot { input, timestamp, attributes } = self;
Ok(v4::InputSlot {
input: Upgrade::upgrade(input)?,
timestamp,
attributes: Upgrade::upgrade(attributes)?,
})
}
}
impl Upgrade for v3::NodeInput {
type Next = v4::NodeInput;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
Ok(match self {
v3::NodeInput::Node { id, index } => v4::NodeInput::Node { id, index },
v3::NodeInput::Value { value, exposed } => v4::NodeInput::Value {
value: Upgrade::upgrade(value)?,
exposed,
},
v3::NodeInput::Scope(field_0) => v4::NodeInput::Scope(field_0),
v3::NodeInput::Import { index } => v4::NodeInput::Import { index },
v3::NodeInput::Reflection => v4::NodeInput::Reflection,
v3::NodeInput::Other => v4::NodeInput::Other,
})
}
}
impl Upgrade for v3::Network {
type Next = v4::Network;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
let v3::Network {
presence,
exports,
exports_timestamp,
attributes,
} = self;
Ok(v4::Network {
presence,
exports: exports.into_iter().map(Upgrade::upgrade).collect::<Result<_, MigrationError>>()?,
exports_timestamp,
attributes: Upgrade::upgrade(attributes)?,
})
}
}
impl Upgrade for v3::ExportSlot {
type Next = v4::ExportSlot;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
let v3::ExportSlot { target, timestamp } = self;
Ok(v4::ExportSlot {
target: target.map(Upgrade::upgrade).transpose()?,
timestamp,
})
}
}
impl Upgrade for v3::ProtoNode {
type Next = v4::ProtoNode;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
let v3::ProtoNode { identifier, version, attributes } = self;
Ok(v4::ProtoNode {
identifier,
version,
attributes: Upgrade::upgrade(attributes)?,
})
}
}
impl Upgrade for v3::Prior {
type Next = v4::Prior;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
Ok(match self {
v3::Prior::Node { id, node } => v4::Prior::Node { id, node: Upgrade::upgrade(node)? },
v3::Prior::RemovedNode { id, tombstone } => v4::Prior::RemovedNode {
id,
tombstone: {
let v3::Tombstone { content, timestamp, placeholder } = tombstone;
v4::Tombstone {
content: Upgrade::upgrade(content)?,
timestamp,
placeholder,
}
},
},
v3::Prior::AbsentNode { id } => v4::Prior::AbsentNode { id },
v3::Prior::Network { id, network } => v4::Prior::Network {
id,
network: Upgrade::upgrade(network)?,
},
v3::Prior::RemovedNetwork { id, tombstone } => v4::Prior::RemovedNetwork {
id,
tombstone: {
let v3::Tombstone { content, timestamp, placeholder } = tombstone;
v4::Tombstone {
content: Upgrade::upgrade(content)?,
timestamp,
placeholder,
}
},
},
v3::Prior::AbsentNetwork { id } => v4::Prior::AbsentNetwork { id },
v3::Prior::Resource { id, resource } => v4::Prior::Resource {
id,
resource: Upgrade::upgrade(resource)?,
},
v3::Prior::RemovedResource { id, tombstone } => v4::Prior::RemovedResource {
id,
tombstone: {
let v3::Tombstone { content, timestamp, placeholder } = tombstone;
v4::Tombstone {
content: Upgrade::upgrade(content)?,
timestamp,
placeholder,
}
},
},
v3::Prior::AbsentResource { id } => v4::Prior::AbsentResource { id },
v3::Prior::NodeField { id, presence, field } => v4::Prior::NodeField {
id,
presence,
field: Upgrade::upgrade(field)?,
},
v3::Prior::NetworkField { id, presence, field } => v4::Prior::NetworkField {
id,
presence,
field: Upgrade::upgrade(field)?,
},
v3::Prior::DocumentAttribute { key, previous } => v4::Prior::DocumentAttribute {
key,
previous: previous.map(Upgrade::upgrade).transpose()?,
},
v3::Prior::PeerUser { peer, previous } => v4::Prior::PeerUser { peer, previous },
})
}
}
impl Upgrade for v3::NodeField {
type Next = v4::NodeField;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
Ok(match self {
v3::NodeField::Presence => v4::NodeField::Presence,
v3::NodeField::Attribute { key, previous } => v4::NodeField::Attribute {
key,
previous: previous.map(Upgrade::upgrade).transpose()?,
},
v3::NodeField::Input { index, previous } => v4::NodeField::Input {
index,
previous: Upgrade::upgrade(previous)?,
},
v3::NodeField::InputAttribute { index, key, previous } => v4::NodeField::InputAttribute {
index,
key,
previous: previous.map(Upgrade::upgrade).transpose()?,
},
v3::NodeField::Inputs { previous, inputs_timestamp } => v4::NodeField::Inputs {
previous: previous.into_iter().map(Upgrade::upgrade).collect::<Result<_, MigrationError>>()?,
inputs_timestamp,
},
v3::NodeField::Implementation { previous, implementation_timestamp } => v4::NodeField::Implementation { previous, implementation_timestamp },
})
}
}
impl Upgrade for v3::NetworkField {
type Next = v4::NetworkField;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
Ok(match self {
v3::NetworkField::Presence => v4::NetworkField::Presence,
v3::NetworkField::Attribute { key, previous } => v4::NetworkField::Attribute {
key,
previous: previous.map(Upgrade::upgrade).transpose()?,
},
v3::NetworkField::Exports { previous } => v4::NetworkField::Exports {
previous: previous.into_iter().map(Upgrade::upgrade).collect::<Result<_, MigrationError>>()?,
},
})
}
}
impl Upgrade for v3::Registry {
type Next = v4::Registry;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
let v3::Registry {
node_instances,
networks,
resources,
peer_users,
attributes,
removed_nodes,
removed_networks,
removed_resources,
} = self;
Ok(v4::Registry {
node_instances: node_instances
.into_iter()
.map(|(key, entry)| Ok::<_, MigrationError>((key, Upgrade::upgrade(entry)?)))
.collect::<Result<_, MigrationError>>()?,
networks: networks
.into_iter()
.map(|(key, entry)| Ok::<_, MigrationError>((key, Upgrade::upgrade(entry)?)))
.collect::<Result<_, MigrationError>>()?,
resources: resources
.into_iter()
.map(|(key, entry)| Ok::<_, MigrationError>((key, Upgrade::upgrade(entry)?)))
.collect::<Result<_, MigrationError>>()?,
peer_users,
attributes: Upgrade::upgrade(attributes)?,
removed_nodes: removed_nodes
.into_iter()
.map(|(key, entry)| {
Ok::<_, MigrationError>((key, {
let v3::Tombstone { content, timestamp, placeholder } = entry;
v4::Tombstone {
content: Upgrade::upgrade(content)?,
timestamp,
placeholder,
}
}))
})
.collect::<Result<_, MigrationError>>()?,
removed_networks: removed_networks
.into_iter()
.map(|(key, entry)| {
Ok::<_, MigrationError>((key, {
let v3::Tombstone { content, timestamp, placeholder } = entry;
v4::Tombstone {
content: Upgrade::upgrade(content)?,
timestamp,
placeholder,
}
}))
})
.collect::<Result<_, MigrationError>>()?,
removed_resources: removed_resources
.into_iter()
.map(|(key, entry)| {
Ok::<_, MigrationError>((key, {
let v3::Tombstone { content, timestamp, placeholder } = entry;
v4::Tombstone {
content: Upgrade::upgrade(content)?,
timestamp,
placeholder,
}
}))
})
.collect::<Result<_, MigrationError>>()?,
})
}
}
impl Upgrade for v3::SourceValue {
type Next = v4::SourceValue;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
let v3::SourceValue { source, timestamp, deleted } = self;
Ok(v4::SourceValue {
source: Upgrade::upgrade(source)?,
timestamp,
deleted,
})
}
}
impl Upgrade for v3::ResourceEntry {
type Next = v4::ResourceEntry;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
let v3::ResourceEntry {
presence,
sources,
sources_timestamp,
hash,
hash_timestamp,
} = self;
Ok(v4::ResourceEntry {
presence,
sources: sources
.into_iter()
.map(|element| {
Ok::<_, MigrationError>({
let (element_0, element_1) = element;
(element_0, Upgrade::upgrade(element_1)?)
})
})
.collect::<Result<_, MigrationError>>()?,
sources_timestamp,
hash,
hash_timestamp,
})
}
}
impl Upgrade for v3::HotOp {
type Next = v4::HotOp;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
let v3::HotOp { op, timestamp, sequence, attributes } = self;
Ok(v4::HotOp {
op: Upgrade::upgrade(op)?,
timestamp,
sequence,
attributes: Upgrade::upgrade(attributes)?,
})
}
}
impl Upgrade for v3::SessionState {
type Next = v4::SessionState;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
let v3::SessionState {
peer_id,
user_id,
head_rev,
last_broadcast_rev,
redo_stack,
next_node_counter,
last_hot_sequence,
view_settings,
network_view_settings,
retired_marks,
clock_counter,
shared,
} = self;
Ok(v4::SessionState {
peer_id,
user_id,
head_rev,
last_broadcast_rev,
redo_stack,
next_node_counter,
last_hot_sequence,
view_settings: view_settings
.into_iter()
.map(|(key, entry)| Ok::<_, MigrationError>((key, Upgrade::upgrade(entry)?)))
.collect::<Result<_, MigrationError>>()?,
network_view_settings: network_view_settings
.into_iter()
.map(|(key, entry)| {
Ok::<_, MigrationError>((
key,
entry
.into_iter()
.map(|(key, entry)| Ok::<_, MigrationError>((key, Upgrade::upgrade(entry)?)))
.collect::<Result<_, MigrationError>>()?,
))
})
.collect::<Result<_, MigrationError>>()?,
retired_marks,
clock_counter,
shared,
})
}
}
impl Upgrade for v3::Value {
type Next = v4::Value;
fn upgrade(self) -> Result<Self::Next, MigrationError> {
Ok(match self {
v3::Value::None => v4::Value::None,
v3::Value::Bool(field_0) => v4::Value::Bool(field_0),
v3::Value::Int(field_0) => v4::Value::Int(field_0),
v3::Value::Float(field_0) => v4::Value::Float(field_0),
v3::Value::Str(field_0) => v4::Value::Str(field_0),
v3::Value::Array(field_0) => v4::Value::Array(field_0.into_iter().map(Upgrade::upgrade).collect::<Result<_, MigrationError>>()?),
v3::Value::Object(field_0) => v4::Value::Object(
field_0
.into_iter()
.map(|element| {
Ok::<_, MigrationError>({
let (element_0, element_1) = element;
(element_0, Upgrade::upgrade(element_1)?)
})
})
.collect::<Result<_, MigrationError>>()?,
),
})
}
}
/// Values whose postcard encoding reaches this many bytes move into blobs, as the live threshold had it when version 4 began.
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.
fn move_values_into_blobs(document: &mut DocumentPayloads) -> Result<(), MigrationError> {
let mut blobs = Blobs::default();
for record in &mut document.history {
let mut delta: v4::Delta = record.decode()?;
blobs.op(&mut delta.kind);
delta.reverse.iter_mut().for_each(|prior| blobs.prior(prior));
*record = record.encode_as(&delta)?;
}
for record in &mut document.hot_log {
let mut hot_op: v4::HotOp = record.decode()?;
blobs.op(&mut hot_op.op);
*record = record.encode_as(&hot_op)?;
}
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
let mut nodes: Vec<_> = registry.node_instances.iter_mut().collect();
nodes.sort_unstable_by_key(|(id, _)| **id);
for (id, node) in nodes {
blobs.node(*id, node);
}
registry.removed_nodes.values_mut().for_each(|tombstone| blobs.loose_node(&mut tombstone.content));
*record = record.encode_as(&registry)?;
}
document.blobs.extend(blobs.bytes);
document.blob_bases.extend(blobs.bases);
Ok(())
}
#[derive(Default)]
struct Blobs {
bytes: HashMap<ResourceHash, Vec<u8>>,
bases: HashMap<ResourceHash, ResourceHash>,
/// The blob each input slot last held, by node and input index.
latest: HashMap<(v4::NodeId, u32), ResourceHash>,
}
impl Blobs {
fn op(&mut self, op: &mut v4::RegistryDelta) {
match op {
v4::RegistryDelta::AddNode { id, node } => self.node(*id, node),
v4::RegistryDelta::RemoveNode { snapshot, .. } => self.loose_node(snapshot),
v4::RegistryDelta::ChangeNodeInput { id, index, new_input } => self.write(*id, *index, new_input),
v4::RegistryDelta::SetNodeInputs { id, inputs } => {
for (index, slot) in (0..).zip(inputs) {
self.write(*id, index, &mut slot.input);
}
}
_ => {}
}
}
/// Priors only restore earlier values, so they never advance a slot's latest blob.
fn prior(&mut self, prior: &mut v4::Prior) {
match prior {
v4::Prior::Node { node, .. } => self.loose_node(node),
v4::Prior::RemovedNode { tombstone, .. } => self.loose_node(&mut tombstone.content),
v4::Prior::NodeField {
field: v4::NodeField::Input { previous, .. },
..
} => {
self.move_into_blob(&mut previous.input);
}
v4::Prior::NodeField {
field: v4::NodeField::Inputs { previous, .. },
..
} => {
for slot in previous {
self.move_into_blob(&mut slot.input);
}
}
_ => {}
}
}
fn node(&mut self, id: v4::NodeId, node: &mut v4::Node) {
for (index, slot) in (0..).zip(&mut node.inputs) {
self.write(id, index, &mut slot.input);
}
}
fn loose_node(&mut self, node: &mut v4::Node) {
for slot in &mut node.inputs {
self.move_into_blob(&mut slot.input);
}
}
/// A write into an input slot, whose blob is based on the one the slot held before.
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
if let Some(previous) = self.latest.insert((id, index), hash)
&& created
&& previous != hash
{
self.bases.insert(hash, previous);
}
}
/// The blob `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 {
return Some((hash.0, false));
}
let encoded = postcard::to_stdvec(value).ok()?;
if encoded.len() < BLOB_THRESHOLD {
return None;
}
let hash = ResourceHash::from(encoded.as_slice());
*value = v4::Value::Blob(v4::BlobHash(hash));
let created = self.bytes.insert(hash, encoded).is_none();
Some((hash, created))
}
}
+398
View File
@@ -0,0 +1,398 @@
//! Format version 4, frozen by `cargo run migration snapshot`. Never edit it: old documents decode through these definitions.
pub use super::v3::{HotOpId, HotSequence, Implementation, NetworkId, NodeId, NonFinitePriority, PeerId, PeerRegistration, Priority, RetiredMarks, Rev, SourceKey, TimeStamp, Tombstone, UserId};
use graphene_resource::{ResourceHash, ResourceId};
use serde::de::{self, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::fmt;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeValue {
pub value: Value,
pub timestamp: TimeStamp,
#[serde(default)]
pub deleted: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Attributes {
pub entries: BTreeMap<String, AttributeValue>,
#[serde(default)]
pub floor: TimeStamp,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Delta {
pub id: Rev,
pub parent: Option<Rev>,
pub author: PeerId,
pub timestamp: TimeStamp,
pub kind: RegistryDelta,
pub reverse: Vec<Prior>,
#[serde(default)]
pub attributes: Attributes,
#[serde(default)]
pub retired_at_ms: u64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RegistryDelta {
AddNode { id: NodeId, node: Node },
RemoveNode { id: NodeId, snapshot: Node },
ChangeNodeInput { id: NodeId, index: u32, new_input: NodeInput },
SetNodeInputs { id: NodeId, inputs: Vec<InputSlot> },
SetNodeImplementation { id: NodeId, implementation: Implementation },
ChangeNodeAttribute { id: NodeId, delta: AttributeDelta },
ChangeNodeInputAttribute { id: NodeId, index: u32, delta: AttributeDelta },
SetNetworkExport { id: NetworkId, index: u32, export: Option<NodeInput> },
ChangeNetworkAttribute { id: NetworkId, delta: AttributeDelta },
AddNetwork { id: NetworkId, network: Network },
RemoveNetwork { id: NetworkId, snapshot: Network },
AddResource { id: ResourceId, entry: ResourceEntry },
SetResourceHash { id: ResourceId, hash: Option<ResourceHash> },
RemoveResource { id: ResourceId, snapshot: ResourceEntry },
AddSource { id: ResourceId, key: SourceKey, source: Value },
RemoveSource { id: ResourceId, key: SourceKey },
RegisterPeer { peer: PeerId, user: UserId },
ChangeDocumentAttribute { delta: AttributeDelta },
Merge { extra_parents: Vec<Rev> },
Meta,
Other(Value),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeDelta {
pub key: String,
pub value: Option<Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
#[serde(default)]
pub presence: TimeStamp,
pub network: NetworkId,
#[serde(default)]
pub network_timestamp: TimeStamp,
pub implementation: Implementation,
#[serde(default)]
pub implementation_timestamp: TimeStamp,
pub inputs: Vec<InputSlot>,
#[serde(default)]
pub inputs_timestamp: TimeStamp,
pub attributes: Attributes,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InputSlot {
pub input: NodeInput,
pub timestamp: TimeStamp,
pub attributes: Attributes,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NodeInput {
Node { id: NodeId, index: u32 },
Value { value: Value, exposed: bool },
Scope(Cow<'static, str>),
Import { index: u32 },
Reflection,
Other,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Network {
#[serde(default)]
pub presence: TimeStamp,
pub exports: Vec<ExportSlot>,
#[serde(default)]
pub exports_timestamp: TimeStamp,
pub attributes: Attributes,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ExportSlot {
pub target: Option<NodeInput>,
pub timestamp: TimeStamp,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProtoNode {
pub identifier: String,
#[serde(default = "ProtoNode::first_version", skip_serializing_if = "ProtoNode::is_first_version")]
pub version: u32,
pub attributes: Attributes,
}
impl ProtoNode {
pub fn first_version() -> u32 {
1
}
pub fn is_first_version(version: &u32) -> bool {
*version == 1
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Prior {
Node { id: NodeId, node: Node },
RemovedNode { id: NodeId, tombstone: Tombstone<Node> },
AbsentNode { id: NodeId },
Network { id: NetworkId, network: Network },
RemovedNetwork { id: NetworkId, tombstone: Tombstone<Network> },
AbsentNetwork { id: NetworkId },
Resource { id: ResourceId, resource: ResourceEntry },
RemovedResource { id: ResourceId, tombstone: Tombstone<ResourceEntry> },
AbsentResource { id: ResourceId },
NodeField { id: NodeId, presence: TimeStamp, field: NodeField },
NetworkField { id: NetworkId, presence: TimeStamp, field: NetworkField },
DocumentAttribute { key: String, previous: Option<AttributeValue> },
PeerUser { peer: PeerId, previous: Option<PeerRegistration> },
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NodeField {
Presence,
Attribute { key: String, previous: Option<AttributeValue> },
Input { index: u32, previous: InputSlot },
InputAttribute { index: u32, key: String, previous: Option<AttributeValue> },
Inputs { previous: Vec<InputSlot>, inputs_timestamp: TimeStamp },
Implementation { previous: Implementation, implementation_timestamp: TimeStamp },
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NetworkField {
Presence,
Attribute { key: String, previous: Option<AttributeValue> },
Exports { previous: Vec<ExportSlot> },
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Registry {
pub node_instances: HashMap<NodeId, Node>,
pub networks: HashMap<NetworkId, Network>,
pub resources: ResourceStore,
pub peer_users: HashMap<PeerId, PeerRegistration>,
pub attributes: Attributes,
#[serde(default)]
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
#[serde(default)]
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
#[serde(default)]
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SourceValue {
pub source: Value,
pub timestamp: TimeStamp,
#[serde(default)]
pub deleted: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct ResourceEntry {
pub presence: TimeStamp,
pub sources: Vec<(SourceKey, SourceValue)>,
pub sources_timestamp: TimeStamp,
pub hash: Option<ResourceHash>,
pub hash_timestamp: TimeStamp,
}
impl<'de> Deserialize<'de> for ResourceEntry {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
struct Raw {
#[serde(default)]
presence: TimeStamp,
sources: Vec<(SourceKey, SourceValue)>,
#[serde(default)]
sources_timestamp: TimeStamp,
hash: Option<ResourceHash>,
hash_timestamp: TimeStamp,
}
let Raw {
presence,
mut sources,
sources_timestamp,
hash,
hash_timestamp,
} = Raw::deserialize(deserializer)?;
sources.sort_by_key(|(key, _)| *key);
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
if later_key != kept_key {
return false;
}
if later_value.timestamp > kept_value.timestamp {
*kept_value = later_value.clone();
}
true
});
Ok(Self {
presence,
sources,
sources_timestamp,
hash,
hash_timestamp,
})
}
}
pub type ResourceStore = HashMap<ResourceId, ResourceEntry>;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HotOp {
pub op: RegistryDelta,
pub timestamp: TimeStamp,
pub sequence: HotSequence,
#[serde(default)]
pub attributes: Attributes,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct SessionState {
#[serde(default)]
pub peer_id: PeerId,
#[serde(default)]
pub user_id: UserId,
#[serde(default)]
pub head_rev: Option<Rev>,
#[serde(default)]
pub last_broadcast_rev: Option<Rev>,
#[serde(default)]
pub redo_stack: Vec<Rev>,
#[serde(default)]
pub next_node_counter: u64,
#[serde(default)]
pub last_hot_sequence: HotSequence,
#[serde(default)]
pub view_settings: BTreeMap<String, Value>,
#[serde(default)]
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, Value>>,
#[serde(default)]
pub retired_marks: RetiredMarks,
#[serde(default)]
pub clock_counter: u64,
#[serde(default)]
pub shared: bool,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct BlobHash(pub ResourceHash);
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self")]
pub enum Value {
None,
Bool(bool),
Int(i128),
Float(f64),
Str(String),
Array(Vec<Value>),
Object(Vec<(String, Value)>),
Blob(BlobHash),
}
impl Serialize for Value {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if !serializer.is_human_readable() {
return Value::serialize(self, serializer);
}
match self {
Value::None => serializer.serialize_unit(),
Value::Bool(boolean) => serializer.serialize_bool(*boolean),
Value::Int(int) => serializer.serialize_i128(*int),
Value::Float(float) => serializer.serialize_f64(*float),
Value::Str(string) => serializer.serialize_str(string),
Value::Array(array) => serializer.collect_seq(array),
Value::Object(object) => serializer.collect_map(object.iter().map(|(key, value)| (key, value))),
Value::Blob(hash) => serializer.collect_map(std::iter::once((Value::BLOB_KEY, hash))),
}
}
}
impl<'de> Deserialize<'de> for Value {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if !deserializer.is_human_readable() {
return Value::deserialize(deserializer);
}
struct Untagged;
impl<'de> Visitor<'de> for Untagged {
type Value = Value;
fn visit_unit<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_none<E>(self) -> Result<Value, E> {
Ok(Value::None)
}
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Value, D::Error> {
Deserialize::deserialize(deserializer)
}
fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
Ok(Value::Bool(value))
}
fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_u64<E>(self, value: u64) -> Result<Value, E> {
Ok(Value::Int(value.into()))
}
fn visit_i128<E>(self, value: i128) -> Result<Value, E> {
Ok(Value::Int(value))
}
fn visit_u128<E: de::Error>(self, value: u128) -> Result<Value, E> {
i128::try_from(value).map(Value::Int).map_err(E::custom)
}
fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
Ok(Value::Float(value))
}
fn visit_str<E>(self, value: &str) -> Result<Value, E> {
Ok(Value::Str(value.to_owned()))
}
fn visit_string<E>(self, value: String) -> Result<Value, E> {
Ok(Value::Str(value))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {
let mut array = Vec::with_capacity(seq.size_hint().unwrap_or(0));
while let Some(value) = seq.next_element()? {
array.push(value);
}
Ok(Value::Array(array))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
let mut object: Vec<(String, Value)> = Vec::with_capacity(map.size_hint().unwrap_or(0));
while let Some(entry) = map.next_entry()? {
object.push(entry);
}
object.sort_by(|a, b| a.0.cmp(&b.0));
object.dedup_by(|b, a| {
let dedup = b.0 == a.0;
if dedup {
std::mem::swap(&mut a.1, &mut b.1);
}
dedup
});
Ok(Value::from_object(object))
}
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid Value")
}
}
deserializer.deserialize_any(Untagged)
}
}
impl Value {
pub const BLOB_KEY: &str = "$blob";
pub 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())
{
return Value::Blob(BlobHash(hash));
}
Value::Object(object)
}
}
@@ -0,0 +1,91 @@
//! The step into version 4 moves large node input values into blobs that match what the live staging path would make.
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};
use migration_core::{DocumentPayloads, Payload, PayloadCodec};
// Format steps register when linked
use migration_formats as _;
fn large_input(prefix: &str) -> NodeInput {
NodeInput::Value {
value: Value::Str(format!("{prefix}{}", "a".repeat(BLOB_THRESHOLD))),
exposed: false,
}
}
fn postcard_payload(value: &impl serde::Serialize) -> Payload {
Payload::encode(value, PayloadCodec::Postcard).unwrap()
}
#[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
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);
node.inputs_mut()[0].input = large_input("");
let network = RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
};
session.stage_computed_ops(vec![network, RegistryDelta::AddNode { id, node }]).unwrap();
session
.stage_computed_ops(vec![RegistryDelta::ChangeNodeInput {
id,
index: 0,
new_input: large_input("b"),
}])
.unwrap();
session.retire_all().unwrap();
session
.stage_computed_ops(vec![RegistryDelta::ChangeNodeInput {
id,
index: 0,
new_input: large_input("c"),
}])
.unwrap();
let mut document = DocumentPayloads {
format_version: 3,
registry: Some(postcard_payload(session.retired_registry())),
history: session.history().map(postcard_payload).collect(),
hot_log: session.hot_log().iter().map(postcard_payload).collect(),
..Default::default()
};
let steps = migration_core::registered_format_migrations();
let step = steps.iter().find(|step| step.migrates_from() == 3).expect("the step into version 4");
document.registry = Some(step.migrate_registry(document.registry.as_ref().unwrap()).unwrap());
document.history = document.history.iter().map(|record| step.migrate_delta(record).unwrap()).collect();
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
let staged_blob = |input: NodeInput| {
let mut input = input;
input.move_into_blob(&mut BlobBytes::new());
input.blob().unwrap()
};
let [first, second, third] = [large_input(""), large_input("b"), large_input("c")].map(staged_blob);
let history: Vec<Delta> = document.history.iter().map(|record| record.decode().unwrap()).collect();
let hot_log: Vec<HotOp> = document.hot_log.iter().map(|record| record.decode().unwrap()).collect();
let registry: Registry = document.registry.as_ref().unwrap().decode().unwrap();
let written = |op: &RegistryDelta| match op {
RegistryDelta::AddNode { node, .. } => node.inputs()[0].input.blob(),
RegistryDelta::ChangeNodeInput { new_input, .. } => new_input.blob(),
_ => None,
};
let retired: Vec<_> = history.iter().filter_map(|delta| written(&delta.kind)).collect();
let hot: Vec<_> = hot_log.iter().filter_map(|hot_op| written(&hot_op.op)).collect();
assert_eq!(retired, [first, second]);
assert_eq!(hot, [third]);
assert_eq!(registry.node_instances[&id].inputs()[0].input.blob(), Some(second));
assert_eq!(document.blobs.len(), 3);
let [first, second, third] = [first, second, third].map(|hash| hash.0);
assert_eq!(decode_blob(&document.blobs[&third]).unwrap(), Value::Str(format!("c{}", "a".repeat(BLOB_THRESHOLD))));
assert_eq!(document.blob_bases.get(&first), None, "the first value of a slot has nothing to be based on");
assert_eq!(document.blob_bases.get(&second), Some(&first));
assert_eq!(document.blob_bases.get(&third), Some(&second));
}
+22 -2
View File
@@ -1,7 +1,7 @@
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::parse::{Parse, ParseStream};
use syn::{Error, Ident, LitInt, Token, Type};
use syn::{Error, Ident, LitInt, Path, Token, Type};
/// The stored roots a format step can convert, by the `FormatMigration` method converting each.
const ROOTS: &[(&str, &str)] = &[
@@ -16,6 +16,7 @@ pub(crate) struct FormatStep {
pub from: u32,
pub to: u32,
roots: Vec<(Ident, Type)>,
document: Option<Path>,
}
impl Parse for FormatStep {
@@ -34,8 +35,18 @@ impl Parse for FormatStep {
}
let mut roots: Vec<(Ident, Type)> = Vec::new();
let mut document = None;
while input.parse::<Option<Token![,]>>()?.is_some() && !input.is_empty() {
let root: Ident = input.parse()?;
if root == "document" {
if document.is_some() {
return Err(Error::new(root.span(), "the document function is already named"));
}
input.parse::<Token![:]>()?;
document = Some(input.parse()?);
continue;
}
if !ROOTS.iter().any(|(name, _)| root == name) {
let names: Vec<&str> = ROOTS.iter().map(|(name, _)| *name).collect();
return Err(Error::new(root.span(), format!("the stored roots are {}", names.join(", "))));
@@ -48,7 +59,7 @@ impl Parse for FormatStep {
roots.push((root, input.parse()?));
}
Ok(Self { from, to, roots })
Ok(Self { from, to, roots, document })
}
}
@@ -75,6 +86,14 @@ pub(crate) fn expand(core: &TokenStream2, step: &FormatStep) -> TokenStream2 {
}
});
let document = step.document.as_ref().map(|function| {
quote! {
fn migrate_document(&self, document: &mut #core::DocumentPayloads) -> ::core::result::Result<(), #core::MigrationError> {
#function(document)
}
}
});
quote! {
struct FormatStep;
@@ -84,6 +103,7 @@ pub(crate) fn expand(core: &TokenStream2, step: &FormatStep) -> TokenStream2 {
}
#history_policy
#(#methods)*
#document
}
}
}
+1
View File
@@ -36,6 +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.
#[proc_macro]
pub fn format_migration(input: TokenStream) -> TokenStream {
let step = parse_macro_input!(input as format::FormatStep);
+1 -4
View File
@@ -12,8 +12,5 @@ migration-core = { workspace = true, features = ["typed"] }
serde = { workspace = true }
[dev-dependencies]
document-graph-storage = { workspace = true, default-features = false }
migration-runner = { workspace = true, features = ["testing"] }
[package.metadata.cargo-shear]
# Frozen mirrors of stored values, once a node migration needs one
ignored = ["serde"]
@@ -2,3 +2,4 @@
mod passthrough_from_upload_texture_node;
mod renames;
mod vary_colors_from_assign_colors;
@@ -0,0 +1,131 @@
use migration_core::{Declaration, Downstream, Inputs, MigrationError, NewNode, Node, NodeInput, OutputConnector, Target, decl, literal_of, migration};
use serde::{Deserialize, Serialize};
const FILL: u32 = 1;
const STROKE: u32 = 2;
/// Frozen mirror of the `TaggedValue` variant this migration reads.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
}
/// Assign Colors splits by its Fill and Stroke toggles into Vary Fill Colors, Vary Stroke Colors, or both in a row, with the same parameters.
/// A wired toggle counts as enabled, and with both off it only ever passed its content through, which a Passthrough still does. With both on,
/// the stroke goes downstream of the anchor so toggling never rewires the content, since a wire written to a removed node would revive it.
#[migration("graphene_core::vector::AssignColorsNode"@1 => "graphene_core::vector::VaryFillColorsNode"@2)]
pub fn vary_colors_from_assign_colors(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, target: &mut Target) -> Result<(), MigrationError> {
let slots: Vec<NodeInput> = node.inputs().iter().map(|slot| slot.input.clone()).collect();
if slots.len() != 8 {
return Err(MigrationError::invariant("Assign Colors has eight inputs"));
}
let enabled = |slot: u32| !matches!(literal_of::<Tagged>(&slots[slot as usize]), Some(Tagged::Bool(false)));
let (fill, stroke) = (enabled(FILL), enabled(STROKE));
let vary_fill: Declaration = decl!("graphene_core::vector::VaryFillColorsNode"@2);
let vary_stroke: Declaration = decl!("graphene_core::vector::VaryStrokeColorsNode"@1);
if !fill && !stroke {
target.set(decl!("graphene_core::ops::PassthroughNode"@2));
inputs.truncate(1);
return Ok(());
}
inputs.remove(STROKE);
inputs.remove(FILL);
if !fill {
target.set(vary_stroke);
return Ok(());
}
target.set(vary_fill);
if stroke {
let consumers = downstream.consumers(0);
let mut stroke_inputs = vec![NodeInput::Node { id: node.id(), index: 0 }];
stroke_inputs.extend(slots[3..].iter().cloned());
let strokes = downstream.add_node(NewNode {
declaration: vary_stroke,
inputs: stroke_inputs,
});
for consumer in consumers {
downstream.connect(OutputConnector { node: strokes, output: 0 }, consumer);
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const ASSIGN_COLORS: Declaration = decl!("graphene_core::vector::AssignColorsNode"@1);
fn contract() -> SourceContract {
// Only the content can read another Assign Colors, since the other inputs don't take its output type
SourceContract {
reads_own_output: |slot| slot == 0,
..SourceContract::new(8, |random, slot| match slot {
1 | 2 => literal(Tagged::Bool(random.below(2) == 0)),
_ => literal(random.below(4) as f64),
})
}
}
fn node(fill: bool, stroke: bool) -> Vec<NodeInput> {
let parameter = |number: u32| literal(f64::from(number));
vec![
parameter(0),
literal(Tagged::Bool(fill)),
literal(Tagged::Bool(stroke)),
parameter(3),
parameter(4),
parameter(5),
parameter(6),
parameter(7),
]
}
fn migrated_declaration(fill: bool, stroke: bool) -> (Option<Declaration>, usize) {
let mut fixture = Fixture::new(&VaryColorsFromAssignColors);
let anchor = fixture.add(ASSIGN_COLORS, node(fill, stroke));
let migrated = fixture.migrate(&VaryColorsFromAssignColors).unwrap();
(fixture.declaration_of(&migrated, anchor), fixture.inputs(&migrated, anchor).len())
}
#[test]
fn rewrites_history() {
check_commutation(&VaryColorsFromAssignColors, &contract());
check_undo(&VaryColorsFromAssignColors, &contract());
}
#[test]
fn each_toggle_chooses_its_node() {
assert_eq!(migrated_declaration(true, false), (Some(decl!("graphene_core::vector::VaryFillColorsNode"@2)), 6));
assert_eq!(migrated_declaration(false, true), (Some(decl!("graphene_core::vector::VaryStrokeColorsNode"@1)), 6));
assert_eq!(migrated_declaration(false, false), (Some(decl!("graphene_core::ops::PassthroughNode"@2)), 1));
}
#[test]
fn both_toggles_chain_fill_into_stroke() {
let mut fixture = Fixture::new(&VaryColorsFromAssignColors);
let anchor = fixture.add(ASSIGN_COLORS, node(true, true));
fixture.export(NodeInput::Node { id: anchor, index: 0 });
let migrated = fixture.migrate(&VaryColorsFromAssignColors).unwrap();
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("graphene_core::vector::VaryFillColorsNode"@2)));
assert_eq!(fixture.inputs(&migrated, anchor)[0], literal(0.));
let export = migrated.networks[&document_graph_storage::ROOT_NETWORK].exports[0].target.clone();
let Some(NodeInput::Node { id: strokes, .. }) = export else {
panic!("the export reads the stroke")
};
assert_eq!(fixture.declaration_of(&migrated, strokes), Some(decl!("graphene_core::vector::VaryStrokeColorsNode"@1)));
assert_eq!(fixture.inputs(&migrated, strokes)[0], NodeInput::Node { id: anchor, index: 0 });
}
}
+85
View File
@@ -0,0 +1,85 @@
//! 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.
use crate::RunnerError;
use document_graph_storage::blob::{BlobBytes, NewBlobs, decode_blob};
use document_graph_storage::{BlobHash, NodeId, NodeInput, Registry, Value};
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::LazyLock;
/// The blobs a document stores, and those migrations moved new values into.
pub struct MigrationBlobs<'a> {
stored: &'a BlobBytes,
/// Blobs no stored one already holds.
added: BlobBytes,
/// For each added blob, the blob its input slot held before the migration, as the base a store can encode it against.
bases: HashMap<BlobHash, BlobHash>,
}
/// For a document without blobs.
impl Default for MigrationBlobs<'static> {
fn default() -> Self {
static NONE: LazyLock<BlobBytes> = LazyLock::new(BlobBytes::new);
Self::new(&NONE)
}
}
impl<'a> MigrationBlobs<'a> {
/// Resolve through the blobs a document `stored`.
pub fn new(stored: &'a BlobBytes) -> Self {
Self {
stored,
added: BlobBytes::new(),
bases: HashMap::new(),
}
}
/// The blobs 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.
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 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) {
return Ok(Cow::Borrowed(registry));
}
let mut resolved = registry.clone();
for id in ids {
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 };
let bytes = self.stored.get(&hash).or_else(|| self.added.get(&hash)).ok_or(RunnerError::MissingBlob(hash))?;
*value = decode_blob(bytes).map_err(|_| RunnerError::MissingBlob(hash))?;
}
}
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`.
pub(crate) fn store(&mut self, migrated: &mut Registry, source: &Registry) {
let mut bytes = BlobBytes::new();
migrated.move_values_into_blobs(&mut bytes);
bytes.retain(|hash, _| !self.stored.contains_key(hash) && !self.added.contains_key(hash));
if bytes.is_empty() {
return;
}
for (hash, base) in migrated.blob_bases_since(source) {
if bytes.contains_key(&hash) {
self.bases.insert(hash, base);
}
}
self.added.extend(bytes);
}
}
+2 -12
View File
@@ -1,18 +1,7 @@
//! Chains format steps over a document's serialized payloads, before they deserialize into the live types.
use crate::RunnerError;
use migration_core::{FormatMigration, HistoryPolicy, Payload};
/// The serialized payloads of one document, as handed over by the load path before typed
/// deserialization. History records are unframed: one [`Payload`] per retired delta, in stored
/// (topological) order. A working copy that only has history has no registry.
pub struct DocumentPayloads {
pub format_version: u32,
pub registry: Option<Payload>,
pub history: Vec<Payload>,
pub hot_log: Vec<Payload>,
pub session: Option<Payload>,
}
use migration_core::{DocumentPayloads, FormatMigration, HistoryPolicy};
/// What the format tier did to history, so the load path knows whether a `Rev` rehash pass
/// (with session-cursor remap) is required after typed deserialization. Ordered by severity so
@@ -69,6 +58,7 @@ pub fn run_format_migrations(migrations: &[&'static dyn FormatMigration], payloa
if let Some(session) = &payloads.session {
payloads.session = Some(step.migrate_session(session).map_err(fail)?);
}
step.migrate_document(payloads).map_err(fail)?;
payloads.format_version += 1;
}
+6 -1
View File
@@ -1,6 +1,7 @@
//! Applies document migrations: format-version chaining over serialized payloads, then node migrations that rewrite history into the
//! current shape. See `node-graph/rfcs/document-format-migrations.md` for the pipeline design.
mod blobs;
mod format;
mod node;
mod order;
@@ -10,8 +11,10 @@ pub mod testing;
use document_graph_storage::{CrdtError, NodeId, Rev};
use migration_core::{Declaration, InputConnector, MigrationError};
pub use blobs::MigrationBlobs;
pub use document_graph_storage::rehash_deltas;
pub use format::{DocumentPayloads, HistoryOutcome, run_format_migrations};
pub use format::{HistoryOutcome, run_format_migrations};
pub use migration_core::DocumentPayloads;
pub use node::{DeclarationTable, RewrittenHistory, holds, registry_at};
pub use order::{migrate_history, migrate_registry, order_migrations, references};
@@ -49,6 +52,8 @@ pub enum RunnerError {
InvalidStep { from: Declaration, to: Declaration },
#[error("migrations from {0:?} depend on each other in a cycle")]
OrderCycle(Vec<Declaration>),
#[error("blob {0} is missing or fails to decode, so a migration can't read its value")]
MissingBlob(document_graph_storage::BlobHash),
#[error("failed to apply a delta: {0}")]
Crdt(#[from] CrdtError),
}
+22 -4
View File
@@ -1,6 +1,6 @@
//! The node tier: `M` as a function on registry states, and the history rewrite derived from it.
use crate::RunnerError;
use crate::{MigrationBlobs, RunnerError};
use document_graph_storage::delta::compute_deltas;
use document_graph_storage::{Delta, Implementation, NetworkId, Node, NodeId, NodeInput, ProtoNode, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op};
use migration_core::{AnchorContext, Compiler, Declaration, DeclarationResolver, Edits, InputConnector, InputsEdit, MigrationHost, NodeMigration, OutputConnector};
@@ -61,12 +61,29 @@ impl DeclarationResolver for DeclarationTable {
}
/// `M`: run `migration` on every anchor in `source` and apply the edits. Every run reads `source`, so no run observes another's edits.
/// A migration asking the compiler runs upstream anchors first instead, in rounds, since the compiler can't describe what's still in the old shape.
pub(crate) fn apply_migration(migration: &dyn NodeMigration, source: &Registry, resolver: &dyn DeclarationResolver, host: Option<&dyn MigrationHost>) -> Result<Registry, RunnerError> {
pub(crate) fn apply_migration(
migration: &dyn NodeMigration,
source: &Registry,
resolver: &dyn DeclarationResolver,
host: Option<&dyn MigrationHost>,
blobs: &mut MigrationBlobs,
) -> Result<Registry, RunnerError> {
let anchors = anchors(migration.source(), source, resolver);
if anchors.is_empty() {
return Ok(source.clone());
}
// A migration reading past its anchors, itself or through the compiler, 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()))?;
let mut migrated = apply_to_values(migration, &resolved, anchors, resolver, host)?;
blobs.store(&mut migrated, source);
Ok(migrated)
}
/// A migration asking the compiler runs upstream anchors first, in rounds, since the compiler can't describe what's still in the old shape.
fn apply_to_values(migration: &dyn NodeMigration, source: &Registry, anchors: Vec<NodeId>, resolver: &dyn DeclarationResolver, host: Option<&dyn MigrationHost>) -> Result<Registry, RunnerError> {
let Some(host) = host.filter(|_| migration.asks_compiler()) else {
return apply_runs(migration, source, &anchors, resolver, None);
};
@@ -299,6 +316,7 @@ pub(crate) fn rewrite_history(
resolver: &dyn DeclarationResolver,
host: Option<&dyn MigrationHost>,
kept: &HashSet<Rev>,
blobs: &mut MigrationBlobs,
) -> Result<RewrittenHistory, RunnerError> {
let mut children: HashMap<Option<Rev>, usize> = HashMap::new();
let mut child_authors: HashMap<Rev, HashSet<_>> = HashMap::new();
@@ -348,7 +366,7 @@ pub(crate) fn rewrite_history(
let passes = passes_through(&delta.kind);
let mut chain = if passes { vec![delta.kind.clone()] } else { Vec::new() };
if if whole_states_only { is_boundary(delta) } else { !passes } {
let migrated = apply_migration(migration, &branch.original, resolver, host)?;
let migrated = apply_migration(migration, &branch.original, resolver, host, blobs)?;
chain.extend(compute_deltas(&branch.rewritten, &migrated));
}
check_single_writes(&chain)?;
+14 -6
View File
@@ -1,7 +1,7 @@
//! Orders registered node migrations by the declarations they read and write, and runs every pending one over a history.
use crate::node::{apply_migration, rewrite_history};
use crate::{RewrittenHistory, RunnerError};
use crate::{MigrationBlobs, RewrittenHistory, RunnerError};
use document_graph_storage::{Delta, Implementation, Node, Registry, RegistryDelta, Rev};
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration};
use std::collections::{BTreeSet, HashMap, HashSet};
@@ -76,13 +76,15 @@ 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.
/// 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.
pub fn migrate_history(
migrations: &[&'static dyn NodeMigration],
history: Vec<Delta>,
resolver: &dyn DeclarationResolver,
host: Option<&dyn MigrationHost>,
kept: impl IntoIterator<Item = Rev>,
blobs: &mut MigrationBlobs,
) -> Result<RewrittenHistory, RunnerError> {
let mut kept: HashSet<Rev> = kept.into_iter().collect();
let mut revs: HashMap<Rev, Option<Rev>> = history.iter().map(|delta| (delta.id, Some(delta.id))).collect();
@@ -93,7 +95,7 @@ pub fn migrate_history(
continue;
}
let step = rewrite_history(migration, &deltas, resolver, host, &kept)?;
let step = rewrite_history(migration, &deltas, resolver, host, &kept, blobs)?;
kept = kept.iter().filter_map(|rev| step.revs.get(rev).copied().flatten()).collect();
for rev in revs.values_mut() {
*rev = rev.and_then(|rev| step.revs.get(&rev).copied().flatten());
@@ -104,11 +106,17 @@ pub fn migrate_history(
Ok(RewrittenHistory { deltas, revs })
}
/// `M` of every migration on one state, for a document whose history can't be rewritten. Undo can't cross the result.
pub fn migrate_registry(migrations: &[&'static dyn NodeMigration], registry: &Registry, resolver: &dyn DeclarationResolver, host: Option<&dyn MigrationHost>) -> Result<Registry, RunnerError> {
/// `M` of every migration on one state, for a document whose history can't be rewritten. Undo can't cross the result. See [`migrate_history`] for `blobs`.
pub fn migrate_registry(
migrations: &[&'static dyn NodeMigration],
registry: &Registry,
resolver: &dyn DeclarationResolver,
host: Option<&dyn MigrationHost>,
blobs: &mut MigrationBlobs,
) -> Result<Registry, RunnerError> {
let mut migrated = registry.clone();
for migration in order_migrations(migrations)? {
migrated = apply_migration(migration, &migrated, resolver, host)?;
migrated = apply_migration(migration, &migrated, resolver, host, blobs)?;
}
Ok(migrated)
}
+12 -7
View File
@@ -2,7 +2,7 @@
//! Panics on failure, since it only runs in tests.
use crate::node::{apply_migration, rewrite_history};
use crate::{DeclarationTable, RunnerError, references, registry_at};
use crate::{DeclarationTable, MigrationBlobs, RunnerError, references, registry_at};
use document_graph_storage::{Delta, ExportSlot, Implementation, Network, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Session, UserId, apply_retired_op};
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, decl, literal, registered_migrations};
use std::collections::HashSet;
@@ -52,7 +52,12 @@ impl Fixture {
}
pub fn migrate_with(&self, migration: &dyn NodeMigration, host: Option<&dyn MigrationHost>) -> Result<Registry, RunnerError> {
apply_migration(migration, &self.registry, &self.table, host)
apply_migration(migration, &self.registry, &self.table, host, &mut MigrationBlobs::default())
}
/// Migrate a registry whose inputs name the blobs in `blobs`.
pub fn migrate_blobs(&self, migration: &dyn NodeMigration, blobs: &mut MigrationBlobs) -> Result<Registry, RunnerError> {
apply_migration(migration, &self.registry, &self.table, None, blobs)
}
pub fn declaration_of(&self, registry: &Registry, node: NodeId) -> Option<Declaration> {
@@ -276,11 +281,11 @@ pub fn check_commutation_with(migration: &dyn NodeMigration, contract: &SourceCo
let (session, table) = generate(migration, contract, seed, 40);
let history: Vec<Delta> = session.history().cloned().collect();
let rewritten = rewrite_history(migration, &history, &table, host, &HashSet::new()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
let rewritten = rewrite_history(migration, &history, &table, host, &HashSet::new(), &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
for delta in &history {
let original = registry_at(&history, Some(delta.id)).unwrap_or_else(|error| panic!("seed {seed}: {error}"));
let expected = apply_migration(migration, &original, &table, host).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
let expected = apply_migration(migration, &original, &table, host, &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
let replayed = registry_at(&rewritten.deltas, rewritten.revs[&delta.id]).unwrap_or_else(|error| panic!("seed {seed}: {error}"));
assert!(
replayed.value_equal(&expected),
@@ -310,7 +315,7 @@ pub fn check_undo_with(migration: &dyn NodeMigration, contract: &SourceContract,
for seed in 1..20 {
let (session, table) = generate(migration, contract, seed, 30);
let history: Vec<Delta> = session.history().cloned().collect();
let rewritten = rewrite_history(migration, &history, &table, host, &HashSet::new()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
let rewritten = rewrite_history(migration, &history, &table, host, &HashSet::new(), &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
let head = session.head_rev();
let migrated_head = head.and_then(|head| rewritten.revs[&head]);
@@ -320,13 +325,13 @@ pub fn check_undo_with(migration: &dyn NodeMigration, contract: &SourceContract,
let mut original = Session::load(PeerId(1), UserId(1), original_registry, history, head, Vec::new(), 0);
let mut migrated = Session::load(PeerId(1), UserId(1), migrated_registry, rewritten.deltas, migrated_head, Vec::new(), 0);
let mut previous = apply_migration(migration, original.registry(), &table, host).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
let mut previous = apply_migration(migration, original.registry(), &table, host, &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
for undo in 0..5 {
// An interaction that only touched what `M` drops left no delta in the rewrite, so undo there passes over it
let mut expected = previous.clone();
while expected.value_equal(&previous) && original.can_undo() {
original.undo().expect("can_undo said so");
expected = apply_migration(migration, original.registry(), &table, host).unwrap_or_else(|error| panic!("seed {seed}, undo {undo}: M failed: {error}"));
expected = apply_migration(migration, original.registry(), &table, host, &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}, undo {undo}: M failed: {error}"));
}
if expected.value_equal(&previous) {
break;
@@ -31,6 +31,7 @@ fn format_tier_chains_and_bumps_version() {
history: vec![Payload::new(vec![1, 2, 3], PayloadCodec::Postcard)],
hot_log: Vec::new(),
session: None,
..Default::default()
};
let outcome = run_format_migrations(&[&RenameKey], &mut payloads, 2).unwrap();
@@ -50,6 +51,7 @@ fn format_tier_errors_on_missing_step() {
history: Vec::new(),
hot_log: Vec::new(),
session: None,
..Default::default()
};
let error = run_format_migrations(&[&RenameKey], &mut payloads, 2).unwrap_err();
@@ -64,6 +66,7 @@ fn truncating_a_document_without_a_registry_fails() {
history: vec![Payload::new(vec![1, 2, 3], PayloadCodec::Postcard)],
hot_log: Vec::new(),
session: None,
..Default::default()
};
let error = run_format_migrations(&[&RenameKey], &mut payloads, 2).unwrap_err();
@@ -0,0 +1,46 @@
//! Migrations read the values a document stores in blobs, and the large values they write go back into blobs.
use document_graph_storage::blob::{BLOB_THRESHOLD, BlobBytes};
use document_graph_storage::{BlobHash, NodeInput, Value};
use migration_core::{Inputs, Node, decl, literal, literal_of, migration};
use migration_runner::MigrationBlobs;
use migration_runner::testing::Fixture;
/// Appends a suffix to the text in the first input.
#[migration("blob_nodes::text"@1 => @2)]
pub fn append_to_text(node: &Node, inputs: &mut Inputs) {
let text: String = literal_of(&node.inputs()[0].input).unwrap_or_default();
inputs.set(0, literal(format!("{text}!")));
}
/// A large literal stored as a blob, with the bytes the document keeps for it.
fn blob_literal(text: &str, blobs: &mut BlobBytes) -> (NodeInput, BlobHash) {
let mut input = literal(text.to_string());
input.move_into_blob(blobs);
let hash = input.blob().expect("the literal is large enough to be a blob");
(input, hash)
}
#[test]
fn migrations_read_blob_values_and_write_large_ones_back_into_blobs() {
let text = "a".repeat(BLOB_THRESHOLD);
let mut stored = BlobBytes::new();
let (input, original) = blob_literal(&text, &mut stored);
let mut fixture = Fixture::new(&AppendToText);
let node = fixture.add(decl!("blob_nodes::text"@1), vec![input]);
let mut blobs = MigrationBlobs::new(&stored);
let migrated = fixture.migrate_blobs(&AppendToText, &mut blobs).unwrap();
let (_, appended) = blob_literal(&format!("{text}!"), &mut BlobBytes::new());
assert_eq!(
fixture.inputs(&migrated, node),
[NodeInput::Value {
value: Value::Blob(appended),
exposed: false
}]
);
let added = blobs.into_added();
assert!(added.bytes.contains_key(&appended), "the new value's bytes are handed back");
assert_eq!(added.bases.get(&appended), Some(&original), "it is based on the blob its slot held");
}
@@ -3,7 +3,7 @@
use document_graph_storage::{Implementation, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Session, UserId};
use migration_core::{Compiler, DeclarationResolver, Graph, MigrationError, MigrationHost, NodeMigration, Target, ValueType, decl, literal, literal_of, migration};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_commutation_with, check_undo, check_undo_with};
use migration_runner::{DeclarationTable, RunnerError, migrate_history, order_migrations};
use migration_runner::{DeclarationTable, MigrationBlobs, RunnerError, migrate_history, order_migrations};
use std::any::type_name;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -219,7 +219,7 @@ fn the_compiler_is_only_asked_at_interaction_boundaries() {
let history: Vec<_> = session.history().cloned().collect();
let host = AnswerHost::default();
let rewritten = migrate_history(&[&ByCompiler], history.clone(), &table, Some(&host), session.head_rev()).unwrap();
let rewritten = migrate_history(&[&ByCompiler], history.clone(), &table, Some(&host), session.head_rev(), &mut MigrationBlobs::default()).unwrap();
// The root network's interaction has no anchors yet, so it never asks, and each of the other two asks once for its one round of unrelated anchors
assert_eq!(host.asked.load(Ordering::Relaxed), 2);
@@ -242,7 +242,7 @@ fn a_cursor_inside_an_interaction_keeps_its_state() {
let inside = history[history.len() - 2].id;
let host = AnswerHost::default();
let rewritten = migrate_history(&[&ByCompiler], history, &table, Some(&host), [inside]).unwrap();
let rewritten = migrate_history(&[&ByCompiler], history, &table, Some(&host), [inside], &mut MigrationBlobs::default()).unwrap();
assert_eq!(host.asked.load(Ordering::Relaxed), 2, "the cursor and the interaction's end");
assert!(rewritten.revs[&inside].is_some());
}
@@ -254,7 +254,7 @@ fn reading_the_graph_also_only_sees_whole_states() {
let history: Vec<_> = session.history().cloned().collect();
let before = GRAPH_READS.load(Ordering::Relaxed);
migrate_history(&[&GraphReader], history, &table, None, session.head_rev()).unwrap();
migrate_history(&[&GraphReader], history, &table, None, session.head_rev(), &mut MigrationBlobs::default()).unwrap();
// All five anchors exist at the one boundary, and the anchorless root network's boundary reads nothing
assert_eq!(GRAPH_READS.load(Ordering::Relaxed) - before, 5);
@@ -1,3 +1,4 @@
mod blobs;
mod compiler;
mod examples;
mod registration;
@@ -5,7 +5,7 @@ use crate::examples::{ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, Transf
use document_graph_storage::{Delta, Implementation, Network, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, RegistryDelta, Session, UserId};
use migration_core::{AnchorContext, Declaration, DeclarationResolver, Edits, MigrationError, NodeMigration, Region, decl, literal, registered_migrations};
use migration_runner::testing::replay;
use migration_runner::{DeclarationTable, RunnerError, migrate_history, order_migrations};
use migration_runner::{DeclarationTable, MigrationBlobs, RunnerError, migrate_history, order_migrations};
#[test]
fn every_migration_registers_once() {
@@ -14,6 +14,7 @@ fn every_migration_registers_once() {
let mut expected = vec![
decl!("blending_nodes::opacity"@1),
decl!("blob_nodes::text"@1),
decl!("compiler::anchor"@1),
decl!("compiler::graph_reader"@1),
decl!("choice::toggle"@1),
@@ -207,7 +208,15 @@ fn migrate_history_chains_every_pending_migration() {
});
let history: Vec<Delta> = session.history().cloned().collect();
let migrated = migrate_history(&registered_migrations(), history.clone(), &table, Some(&compiler::AnswerHost::default()), None).unwrap();
let migrated = migrate_history(
&registered_migrations(),
history.clone(),
&table,
Some(&compiler::AnswerHost::default()),
None,
&mut MigrationBlobs::default(),
)
.unwrap();
let registry = replay(&migrated.deltas);
let declaration_of = |id: NodeId| match registry.node_instances[&id].implementation() {
+1 -1
View File
@@ -6,7 +6,7 @@ mod target;
mod token;
mod transport;
pub use packet::{CursorPosition, CursorSpace, MAX_PACKET_BYTES, PacketError, Role, SyncPacket, SyncPayload};
pub use packet::{BlobRecord, CursorPosition, CursorSpace, MAX_PACKET_BYTES, PacketError, Role, SyncPacket, SyncPayload};
pub use replica::{Event, RemotePeer, Replica, ReplicaError};
pub use room::{Incoming, Room};
pub use target::{SyncTarget, TargetError};
+17 -2
View File
@@ -1,4 +1,4 @@
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, UserId};
use document_graph_storage::{BlobHash, Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, UserId};
use serde::{Deserialize, Serialize};
/// The host is the single peer that retires hot ops.
@@ -82,6 +82,9 @@ pub struct SyncPayload {
pub document_id: Option<u64>,
#[serde(default)]
pub metadata: HistoryMetadata,
/// Every blob the synced state names, each after its base.
#[serde(default)]
pub blobs: Vec<BlobRecord>,
}
/// Causal broadcast envelope. `seq` numbers the sender's broadcasts from 1 within `epoch`. `seen` is the sender's
@@ -96,7 +99,11 @@ pub struct Broadcast {
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum BroadcastBody {
HotOps(Vec<HotOp>),
/// Carries the records of the blobs the ops name, so a peer can resolve them on arrival.
HotOps {
ops: Vec<HotOp>,
blobs: Vec<BlobRecord>,
},
/// `deltas` are in causal order. `retires` names the hot ops they replace, empty for a plain history transfer.
Deltas {
deltas: Vec<Delta>,
@@ -110,6 +117,14 @@ 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.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BlobRecord {
pub hash: BlobHash,
#[serde(with = "serde_bytes")]
pub record: Vec<u8>,
}
/// Largest encoded packet a peer sends or accepts. Generous, since a `Resource` carries a whole embedded file.
pub const MAX_PACKET_BYTES: usize = 256 * 1024 * 1024;
+17 -7
View File
@@ -1,4 +1,4 @@
use crate::packet::{Broadcast, BroadcastBody, CursorPosition, PacketError, PeerSeq, Role, SyncPacket, SyncPayload};
use crate::packet::{BlobRecord, Broadcast, BroadcastBody, CursorPosition, PacketError, PeerSeq, Role, SyncPacket, SyncPayload};
use crate::target::{SyncTarget, TargetError};
use crate::transport::{Transport, TransportEvent, TransportPeerId};
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, ResourceHash, Rev, UserId};
@@ -322,12 +322,13 @@ impl Replica {
self.requested_resources.iter().copied()
}
pub fn broadcast_hot_ops(&mut self, ops: &[HotOp]) -> Result<(), PacketError> {
/// Broadcast staged `ops`, with the records of the new blobs they name.
pub fn broadcast_hot_ops(&mut self, ops: &[HotOp], blobs: Vec<BlobRecord>) -> Result<(), PacketError> {
if ops.is_empty() {
return Ok(());
}
self.resources_stale = true;
self.broadcast(BroadcastBody::HotOps(ops.to_vec()))
self.broadcast(BroadcastBody::HotOps { ops: ops.to_vec(), blobs })
}
/// Ask the host to undo (`restore == false`) or redo (`restore == true`) this peer's retired interaction.
@@ -488,7 +489,7 @@ impl Replica {
let retired = target.retired_marks();
let unretired: Vec<HotOp> = target.hot_log().into_iter().filter(|hot_op| !retired.covers(hot_op.id())).collect();
self.broadcast_hot_ops(&unretired)?;
self.broadcast_hot_ops(&unretired, Vec::new())?;
if retired.is_empty() {
return Ok(());
}
@@ -682,6 +683,7 @@ impl Replica {
retired: target.retired_marks(),
document_id: target.document_id(),
metadata: target.metadata(),
blobs: target.blob_records(),
};
log::debug!("Join handshake: sync answered with {} deltas and {} hot ops", sync.deltas.len(), sync.hot_log.len());
self.transport.send(from, &SyncPacket::Sync(Box::new(sync)))?;
@@ -696,6 +698,7 @@ impl Replica {
// unretired ops, possibly the only copy of what never reached the host, are replayed on top.
let registry = sync.registry.filter(|_| target.known_revs().is_empty());
let replayed = if registry.is_some() { target.hot_log() } else { Vec::new() };
target.absorb_blob_records(sync.blobs)?;
match registry {
Some(registry) => target.load(registry, sync.deltas, sync.head)?,
None => target.merge_remote(sync.deltas, &[], sync.head)?,
@@ -742,7 +745,7 @@ impl Replica {
self.follow_current_host(&*target)?;
let own_hot_ops: Vec<HotOp> = target.hot_log().into_iter().filter(|hot_op| hot_op.timestamp.peer == self.peer).collect();
self.broadcast_hot_ops(&own_hot_ops)?;
self.broadcast_hot_ops(&own_hot_ops, Vec::new())?;
events.push(Event::Synced);
}
@@ -866,7 +869,14 @@ 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) => target.apply_remote_hot_ops(ops).map(|deferred| self.deferred.extend(deferred)),
BroadcastBody::HotOps { ops, blobs } => {
// A blob whose base isn't held here is asked for like a missing resource
self.resources_stale = true;
target
.absorb_blob_records(blobs)
.and_then(|()| target.apply_remote_hot_ops(ops))
.map(|deferred| self.deferred.extend(deferred))
}
// A host lets a step with a missing parent go, since its author's whole line arrives when the author syncs.
BroadcastBody::Deltas { deltas, .. } if has_missing_parent(&deltas, &*target) => {
if self.role == Role::Host {
@@ -991,7 +1001,7 @@ mod tests {
epoch: 1,
seq,
seen,
body: BroadcastBody::HotOps(Vec::new()),
body: BroadcastBody::HotOps { ops: Vec::new(), blobs: Vec::new() },
})
}
+9
View File
@@ -1,3 +1,4 @@
use crate::BlobRecord;
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, MergeOutcome, PeerId, Registry, ResourceHash, RetiredMarks, Rev, Session};
use std::collections::HashSet;
@@ -68,6 +69,14 @@ 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.
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.
fn absorb_blob_records(&mut self, _records: Vec<BlobRecord>) -> Result<(), TargetError> {
Ok(())
}
}
impl SyncTarget for Session {
+204 -29
View File
@@ -1,14 +1,15 @@
//! Deterministic simulation over the mock transport with random edits, delivery order and host retirement.
//! After quiescence every peer must hold the same retired state.
//!
//! Inspect one run with `SEED=<n> GUESTS=<n> cargo test -p peer-transport --test simulation inspect_seed -- --ignored --nocapture`.
//! Inspect one run with `SEED=<n> GUESTS=<n> [STROKES=1] cargo test -p peer-transport --test simulation inspect_seed -- --ignored --nocapture`.
use document_graph_storage::blob::{BLOB_THRESHOLD, BlobBytes};
use document_graph_storage::{
AttributeDelta, Delta, HeadMove, HotOp, HotOpId, HotSequence, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Priority, Registry, RegistryDelta, ResourceHash, ResourceId,
RetiredMarks, Rev, Session, SourceKey, UserId, Value,
AttributeDelta, BlobHash, Delta, HeadMove, HotOp, HotOpId, HotSequence, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Priority, Registry, RegistryDelta, ResourceHash,
ResourceId, RetiredMarks, Rev, Session, SourceKey, UserId, Value,
};
use peer_transport::mock::{MockEndpoint, MockNetwork};
use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, TransportPeerId};
use peer_transport::{BlobRecord, Event, Replica, Role, SyncTarget, TargetError, TransportPeerId};
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -19,11 +20,17 @@ 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);
/// 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`].
blobs: BlobBytes,
blob_records: HashMap<BlobHash, Vec<u8>>,
/// History as of the last `flush`.
durable_history: Vec<Rev>,
flushes: usize,
@@ -40,6 +47,8 @@ impl SimTarget {
Self {
session: Session::with_peer(peer),
resources: HashMap::new(),
blobs: BlobBytes::new(),
blob_records: HashMap::new(),
durable_history: Vec::new(),
flushes: 0,
seen_revs: HashSet::new(),
@@ -51,6 +60,37 @@ impl SimTarget {
fn history_revs(&self) -> Vec<Rev> {
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.
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)) {
Some(base) => {
record.push(1);
record.extend_from_slice(&<[u8; 32]>::from(&base.0));
}
None => record.push(0),
}
record.extend_from_slice(bytes);
record
}
/// Hold staged blobs, returning the records 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);
let mut records = Vec::new();
for (hash, bytes) in blobs {
let record = self.blob_record(&bytes, bases.get(&hash).copied());
self.blobs.insert(hash, bytes);
self.blob_records.insert(hash, record.clone());
records.push(BlobRecord { hash, record });
}
TOTAL_BLOBS.fetch_add(records.len(), Ordering::Relaxed);
records
}
}
impl SyncTarget for SimTarget {
@@ -168,17 +208,67 @@ impl SyncTarget for SimTarget {
}
fn missing_resources(&self) -> HashSet<ResourceHash> {
self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.resources.contains_key(hash)).collect()
let resources = self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.resources.contains_key(hash));
let blobs = self.session.all_blob_hashes().into_iter().filter(|hash| !self.blobs.contains_key(hash));
resources.chain(blobs.map(ResourceHash::from)).collect()
}
fn resource_bytes(&self, hash: ResourceHash) -> Option<Vec<u8>> {
self.resources.get(&hash).cloned()
self.resources.get(&hash).or_else(|| self.blobs.get(&BlobHash(hash))).cloned()
}
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);
let record = self.blob_record(bytes, None);
self.blobs.insert(blob, bytes.to_vec());
self.blob_records.insert(blob, record);
return Ok(());
}
self.resources.insert(hash, bytes.to_vec());
Ok(())
}
fn blob_records(&self) -> Vec<BlobRecord> {
let mut records: Vec<_> = self.blob_records.iter().map(|(&hash, record)| BlobRecord { hash, record: record.clone() }).collect();
records.sort_unstable_by_key(|record| record.hash);
records
}
fn absorb_blob_records(&mut self, records: Vec<BlobRecord>) -> Result<(), TargetError> {
let mut pending = records;
loop {
let waiting = pending.len();
pending.retain(|BlobRecord { hash, record }| {
if self.blobs.contains_key(hash) {
return false;
}
let bytes = match record.split_first() {
Some((1, rest)) => {
let base = <[u8; 32]>::try_from(&rest[..32])
.map(|bytes| BlobHash(ResourceHash::from(bytes)))
.expect("a delta record names its base");
if !self.blobs.contains_key(&base) {
return true;
}
TOTAL_BLOB_DELTAS.fetch_add(1, Ordering::Relaxed);
&rest[32..]
}
Some((_, rest)) => rest,
None => panic!("seed {}: an empty blob record arrived", self.seed),
};
assert_eq!(BlobHash::of(bytes), *hash, "seed {}: a blob record decodes to bytes of another hash", self.seed);
self.blobs.insert(*hash, bytes.to_vec());
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
if pending.is_empty() || pending.len() == waiting {
return Ok(());
}
}
}
}
struct Peer {
@@ -241,9 +331,19 @@ impl Peer {
fn stage(&mut self, op: RegistryDelta) {
self.retracted.clear();
let hot_ops = self.target.session.stage_computed_ops(vec![op]).expect("stage");
self.stage_ops(vec![op]).expect("stage");
}
self.replica.broadcast_hot_ops(&hot_ops).expect("broadcast");
/// Stage `ops` with their large values moved into blobs, broadcasting the blobs' 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));
let bases = self.target.session.registry().blob_bases(&ops);
let hot_ops = self.target.session.stage_computed_ops(ops)?;
let records = self.target.hold_blobs(blobs, &bases);
self.replica.broadcast_hot_ops(&hot_ops, records).expect("broadcast");
Ok(())
}
/// Introduce a resource only this peer holds the bytes for, so every other peer has to fetch them.
@@ -255,7 +355,7 @@ impl Peer {
// Per-peer, since a content-derived id would collide across peers.
let id = ResourceId::from(u64::from(ResourceId::from_hash(&hash)) ^ self.peer.0);
let hot_ops = self.target.session.stage_embedded_resource(id, hash).expect("stage resource");
self.replica.broadcast_hot_ops(&hot_ops).expect("broadcast");
self.replica.broadcast_hot_ops(&hot_ops, Vec::new()).expect("broadcast");
}
fn retire(&mut self) {
@@ -275,10 +375,26 @@ impl Peer {
let staged = self.target.session.end_interaction().expect("end interaction");
if let Some(marker) = staged.last() {
self.last_closed = marker.sequence;
self.replica.broadcast_hot_ops(&staged).expect("broadcast");
self.replica.broadcast_hot_ops(&staged, Vec::new()).expect("broadcast");
}
}
/// Edit one input of a live node a few times in a row, as drawing does, so its blobs chain on each other.
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 };
let index = network.random_below(2) as u32;
for _ in 0..2 + network.random_below(4) {
let new_input = NodeInput::Value {
value: large_value(network),
exposed: false,
};
self.stage(RegistryDelta::ChangeNodeInput { id, index, new_input });
}
self.end_interaction();
}
/// Undo this peer's latest interaction while hot. The ops leave every hot log and never become history.
fn retract(&mut self) {
if let Some(retraction) = self.target.session.retract_interaction().expect("retract") {
@@ -293,8 +409,9 @@ impl Peer {
/// Redo the hot step this peer took back last, staging its ops afresh. A redo that no longer fits is given up.
fn redo_retracted(&mut self) {
let Some(ops) = self.retracted.pop() else { return };
let Ok(hot_ops) = self.target.session.stage_computed_ops(ops) else { return };
self.replica.broadcast_hot_ops(&hot_ops).expect("broadcast");
if self.stage_ops(ops).is_err() {
return;
}
self.end_interaction();
TOTAL_REDONE_RETRACTIONS.fetch_add(1, Ordering::Relaxed);
}
@@ -394,6 +511,19 @@ 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.
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`].
fn random_input_value(network: &mut MockNetwork) -> Value {
match network.random_below(3) {
0 => large_value(network),
_ => random_value(network),
}
}
fn add_network(id: u64) -> RegistryDelta {
RegistryDelta::AddNetwork {
id: NetworkId(id),
@@ -431,6 +561,16 @@ 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
5 => {
let id = *pick(network, &live_nodes)?;
let index = network.random_below(2) as u32;
let new_input = NodeInput::Value {
value: large_value(network),
exposed: false,
};
Some(RegistryDelta::ChangeNodeInput { id, index, new_input })
}
3 | 4 => {
let node = registry.node_instances.get(&node_id)?;
let index = network.random_below(node.inputs().len().max(1)) as u32;
@@ -440,7 +580,7 @@ fn random_node_op(network: &mut MockNetwork, session: &Session) -> Option<Regist
let new_input = match wire_to {
Some(target) if network.random_below(3) > 0 => NodeInput::Node { id: target, index: 0 },
_ => NodeInput::Value {
value: random_value(network),
value: random_input_value(network),
exposed: false,
},
};
@@ -614,7 +754,15 @@ fn quiesce(network: &mut MockNetwork, peers: &mut [Peer]) -> usize {
panic!("the room never went idle");
}
fn simulate(seed: u64, guest_count: usize, steps: usize) -> (MockNetwork, Vec<Peer>) {
/// What a run mostly does.
#[derive(Clone, Copy)]
enum Workload {
Mixed,
/// Half the steps are strokes, as live drawing makes.
Strokes,
}
fn simulate(seed: u64, guest_count: usize, steps: usize, workload: Workload) -> (MockNetwork, Vec<Peer>) {
let mut network = MockNetwork::new(seed);
let mut peers = open_room(&mut network, guest_count, seed);
@@ -624,7 +772,11 @@ fn simulate(seed: u64, guest_count: usize, steps: usize) -> (MockNetwork, Vec<Pe
continue;
}
match network.random_below(18) {
let action = match workload {
Workload::Strokes if network.random_below(2) == 0 => 14,
_ => network.random_below(18),
};
match action {
// Anything staged before syncing would be invisible to the room.
0..=2 if peers[index].replica.is_synced() => {
let op = random_op(&mut network, &peers[index].target);
@@ -642,6 +794,7 @@ fn simulate(seed: u64, guest_count: usize, steps: usize) -> (MockNetwork, Vec<Pe
peers[index].collect_garbage(&needed);
}
17 if peers[index].replica.is_synced() => peers[index].redo_retracted(),
14 if peers[index].replica.is_synced() => peers[index].stroke(&mut network),
// Bytes nothing names, as an abandoned import leaves behind.
8 if network.random_below(4) == 0 => {
let bytes = format!("stray-{}-{}", peers[index].peer.0, network.random_below(1 << 20)).into_bytes();
@@ -863,7 +1016,14 @@ fn assert_converged(seed: u64, peers: &[Peer]) {
// Bytes that left with a departed peer are gone, so only those a present peer holds, or collected while needed,
// must be served.
let servable: HashSet<ResourceHash> = present()
.flat_map(|(_, peer)| peer.target.resources.keys().chain(&peer.target.collected_while_needed).copied())
.flat_map(|(_, peer)| {
peer.target
.resources
.keys()
.chain(&peer.target.collected_while_needed)
.copied()
.chain(peer.target.blobs.keys().map(|hash| hash.0))
})
.collect();
for (index, peer) in present() {
@@ -886,14 +1046,36 @@ fn assert_converged(seed: u64, peers: &[Peer]) {
#[test]
fn peers_converge_under_random_interleavings() {
let seeds = std::env::var("SIM_SEEDS").ok().and_then(|value| value.parse::<u64>().ok()).unwrap_or(5000);
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");
}
// Runs every seed and lists the failures, to tell one bug from several.
/// Mostly strokes, so blobs chain on each other, reach peers as deltas, and are fetched in full by a peer lacking 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 `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.
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();
let mut failed = Vec::new();
for seed in 0..seeds {
let run = || {
let (_, peers) = simulate(seed, 1 + (seed % 3) as usize, 200);
let (_, peers) = simulate(seed, 1 + (seed % 3) as usize, 200, workload);
count_coverage(peers[expect_host(seed, &peers)].session().retired_registry());
assert_converged(seed, &peers);
};
@@ -904,14 +1086,6 @@ fn peers_converge_under_random_interleavings() {
}
}
assert!(failed.is_empty(), "{} seeds failed: {failed:?}", failed.len());
// 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");
}
fn count_coverage(registry: &Registry) {
@@ -954,7 +1128,8 @@ fn inspect_seed() {
let seed = std::env::var("SEED").ok().and_then(|value| value.parse().ok()).unwrap_or(0);
let guests = std::env::var("GUESTS").ok().and_then(|value| value.parse().ok()).unwrap_or(1);
let (_, peers) = simulate(seed, guests, 200);
let workload = if std::env::var_os("STROKES").is_some() { Workload::Strokes } else { Workload::Mixed };
let (_, peers) = simulate(seed, guests, 200, workload);
for (index, peer) in peers.iter().enumerate() {
eprintln!("=== peer {index} head {:?}", peer.session().head_rev());
eprintln!("registry {}", serde_json::to_string(peer.session().retired_registry()).unwrap());
@@ -1031,7 +1206,7 @@ fn a_witness_closes_an_authors_run_before_a_gap_forms() {
/// an edit or the wire.
#[test]
fn a_seed_fixes_the_run() {
let run = |seeds: u64| (0..seeds).map(|seed| simulate(seed, 1 + (seed % 3) as usize, 200).1).collect::<Vec<_>>();
let run = |seeds: u64| (0..seeds).map(|seed| simulate(seed, 1 + (seed % 3) as usize, 200, Workload::Mixed).1).collect::<Vec<_>>();
let (first, second) = (run(100), run(100));
+11 -28
View File
@@ -2,7 +2,7 @@ use crate::application::{Editor, Environment};
use crate::dispatcher::Dispatcher;
use crate::messages::prelude::*;
use crate::node_graph_executor::{NodeGraphExecutor, NodeRuntime};
use crate::task::{Clock, Scheduling, Spawn, Spawner};
use crate::task::{Spawn, Spawner};
use document_container::store::DocumentStore;
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::ResourceStorage;
@@ -96,8 +96,6 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
let RuntimeBuilder {
wake: runtime_wake,
mut application_io,
scheduling,
clock,
} = runtime;
graphene_std::uuid::set_uuid_seed(random_seed);
@@ -109,8 +107,7 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
node_runtime.replace_application_io(application_io);
node_runtime.replace_task_executor(spawner, runtime_wake, clock);
node_runtime.set_scheduling(scheduling);
node_runtime.replace_task_executor(spawner, runtime_wake);
(Editor { dispatcher }, node_runtime)
}
@@ -187,18 +184,17 @@ impl<W, E, R> EditorBuilder<W, E, R, ()> {
pub struct RuntimeBuilder<W = (), A = ()> {
wake: W,
application_io: A,
clock: Arc<dyn Clock>,
scheduling: Scheduling,
}
impl RuntimeBuilder {
pub fn new(clock: Arc<dyn Clock>) -> Self {
Self {
wake: (),
application_io: (),
clock,
scheduling: Scheduling::default(),
}
pub fn new() -> Self {
Self { wake: (), application_io: () }
}
}
impl Default for RuntimeBuilder {
fn default() -> Self {
Self::new()
}
}
@@ -208,25 +204,12 @@ impl<A> RuntimeBuilder<(), A> {
RuntimeBuilder {
wake: Arc::new(wake),
application_io: self.application_io,
clock: self.clock,
scheduling: self.scheduling,
}
}
}
impl<W> RuntimeBuilder<W, ()> {
pub fn with_application_io(self, application_io: PlatformApplicationIo) -> RuntimeBuilder<W, PlatformApplicationIo> {
RuntimeBuilder {
wake: self.wake,
application_io,
clock: self.clock,
scheduling: self.scheduling,
}
}
}
impl<W, A> RuntimeBuilder<W, A> {
pub fn with_scheduling(self, scheduling: Scheduling) -> Self {
Self { scheduling, ..self }
RuntimeBuilder { wake: self.wake, application_io }
}
}
@@ -237,7 +237,7 @@ impl DocumentHistory {
storage
.registry()
.to_runtime_with_full_metadata(&self.declarations)
.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| {
@@ -295,7 +295,7 @@ impl DocumentHistory {
panic!("storage round-trip: timestamp order inconsistent between stored and target");
}
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(declarations) {
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(declarations, storage.blobs()) {
Ok(result) => result,
Err(error) => {
log::error!("storage round-trip: to_runtime failed: {error}");
@@ -1253,7 +1253,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::SaveDocumentAs => None,
_ => self.path.clone().map(|path| path.with_extension(extension)),
};
if path.is_some() {
if path.is_some() || environment.is_web() {
responses.add(DocumentMessage::MarkAsSaved);
}
let folder = self.path.as_ref().and_then(|path| path.parent()).map(|parent| parent.to_path_buf());
@@ -4695,6 +4695,7 @@ mod document_message_handler_tests {
.executor
.submit_node_graph_evaluation(document, document_id, glam::UVec2::ONE, 1., Default::default(), merged, true, DVec2::ZERO)
.unwrap();
editor.runtime.update();
editor.runtime.run().await;
let frontend_messages = editor.editor.handle_message(Message::Wake);
@@ -38,9 +38,10 @@ fn editor_metadata_round_trip_against_demo() {
let conversion = Registry::convert_from_runtime(&network, &source, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations;
let blobs = conversion.blob_bytes;
let registry = conversion.registry;
let (_converted_network, entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
let (_converted_network, entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations, &blobs).expect("to_runtime_with_full_metadata failed");
// Index emitted entries by their (network, local_id) address.
let entries_by_address: HashMap<(NetworkLocation, NodeId), &document_graph_storage::NodeMetadataEntry> = entries.iter().map(|e| ((e.network, e.local_id), e)).collect();
@@ -167,8 +168,9 @@ fn editor_interface_rebuild_round_trip() {
let network = original.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &original_view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations;
let blobs = conversion.blob_bytes;
let registry = conversion.registry;
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations, &blobs).expect("to_runtime_with_full_metadata failed");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
let rebuilt_view = StorageMetadataView::new(&rebuilt);
@@ -283,8 +285,9 @@ fn rebuilt_interface_keeps_storage_identities() {
let network = document.network_interface.document_network().clone();
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations;
let blobs = conversion.blob_bytes;
let registry = conversion.registry;
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations, &blobs).expect("to_runtime_with_full_metadata failed");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
@@ -383,7 +386,7 @@ fn pinned_order_round_trips_through_the_registry() {
let view = StorageMetadataView::new(&document.network_interface);
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations;
let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime failed");
let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations, &conversion.blob_bytes).expect("to_runtime failed");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
let rebuilt_metadata = rebuilt.network_metadata(&[]).expect("the rebuilt document network should resolve");
@@ -7,7 +7,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NodeMetadataSource, PeerId, to_value};
use document_graph_storage::{NodeMetadataSource, PeerId, UserId, to_value};
use graph_craft::application_io::resource::HashMapResourceStorage;
use super::test_support::{RoundTrip, node_locations, node_paths, round_trip_through_gdd};
@@ -160,7 +160,7 @@ async fn edit_after_open_commits_cleanly() {
// reopened registry: the editor's .gdd-open path.
let byte_store = HashMapResourceStorage::new();
let source = editor.active_document();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
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();
let source_view = StorageMetadataView::new(&source.network_interface);
gdd.commit_from_runtime(&source_network, &source_view, &source.resources.registry, &byte_store)
@@ -169,7 +169,7 @@ async fn edit_after_open_commits_cleanly() {
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.expect("open_in");
let declarations = reopened.declarations(&byte_store).await;
let (rebuilt_network, node_entries, network_entries) = reopened.registry().to_runtime_with_full_metadata(&declarations).expect("to_runtime");
let (rebuilt_network, node_entries, network_entries) = reopened.registry().to_runtime_with_full_metadata(&declarations, reopened.blobs()).expect("to_runtime");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage");
// Install the rebuilt interface + reopened storage and finalize like the editor's open path does.
@@ -210,7 +210,7 @@ async fn edit_after_open_commits_cleanly() {
#[tokio::test]
async fn gdd_undo_redo_walks_interactions() {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
// Commit the active document's current runtime state as one interaction.
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
@@ -261,7 +261,7 @@ async fn gdd_undo_redo_walks_interactions() {
#[tokio::test]
async fn reopen_after_undo_restores_consistent_registry() {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
let network = document.network_interface.document_network().clone();
@@ -383,7 +383,7 @@ async fn gdd_archive_round_trips_view_settings() {
use document_graph_storage::attr::session::doc;
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
// Stage a distinctive PTZ into the working copy's `view_settings`, as `commit_storage_snapshot` does.
let mut ptz = crate::messages::portfolio::document::utility_types::misc::PTZ::default();
@@ -431,7 +431,7 @@ async fn per_network_navigation_round_trips_via_session_not_registry() {
let expected_pan = editor.active_document().network_interface.node_graph_ptz(&[]).unwrap().pan;
// Commit the document into a fresh `Gdd`, collecting the per-network view state the editor persists.
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let document = editor.active_document();
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
@@ -450,7 +450,7 @@ async fn per_network_navigation_round_trips_via_session_not_registry() {
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.expect("open_in");
let declarations = reopened.declarations(&byte_store).await;
let (rebuilt_network, node_entries, network_entries) = reopened.registry().to_runtime_with_full_metadata(&declarations).expect("to_runtime");
let (rebuilt_network, node_entries, network_entries) = reopened.registry().to_runtime_with_full_metadata(&declarations, reopened.blobs()).expect("to_runtime");
let mut rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries.clone()).expect("build_interface_from_storage");
let reopened_ids = network_ids_from_entries(&network_entries);
@@ -665,7 +665,7 @@ fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
/// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real
/// autosave path) runs against it. Returns the byte store the document's resources resolve through.
fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourceStorage {
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0x5EED, "test".into(), "test".into()).expect("create_in");
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()
}
@@ -5,7 +5,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::PeerId;
use document_graph_storage::{PeerId, UserId};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkLocation, NodeId, NodeNetwork};
@@ -110,7 +110,7 @@ pub struct RoundTrip {
pub async fn round_trip_through_gdd(document: &DocumentMessageHandler) -> RoundTrip {
let byte_store = HashMapResourceStorage::new();
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 0xABCD, "test".into(), "test".into()).expect("create_in");
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
@@ -132,7 +132,7 @@ pub async fn round_trip_through_gdd(document: &DocumentMessageHandler) -> RoundT
let reopened = GddV1::open_in(working, layout).await.expect("open_in");
let declarations = reopened.declarations(&byte_store).await;
let registry = reopened.registry().clone();
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata");
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations, reopened.blobs()).expect("to_runtime_with_full_metadata");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage");
let view_settings = reopened.view_settings().clone();
@@ -6,19 +6,14 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, NodeTemplateImplementation, OutputConnector};
use crate::messages::prelude::DocumentMessageHandler;
use crate::node_graph_executor::redirect_export_chain;
use glam::{DVec2, IVec2};
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
use graph_craft::document::DocumentNode;
use graph_craft::document::{DocumentNodeImplementation, NodeInput, NodeNetwork, value::TaggedValue};
use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::TypingContext;
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
use graph_craft::{Type, concrete, item, list};
use graphene_std::Color;
use graphene_std::ParameterRef;
use graphene_std::ProtoNodeIdentifier;
use graphene_std::RuntimeHandle;
use graphene_std::extract_xy::XY;
use graphene_std::raster::RedGreenBlueAlpha;
use graphene_std::text::{TextAlign, TypesettingConfig};
@@ -26,11 +21,9 @@ use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId;
use graphene_std::vector::graphic_types;
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use interpreted_executor::node_registry::NODE_REGISTRY;
use std::collections::{HashMap, HashSet};
use std::f64::consts::PI;
use std::ops::Range;
use std::sync::Arc;
const TEXT_REPLACEMENTS: &[(&str, &str)] = &[
("graphene_core::vector::vector_nodes::SamplePointsNode", "graphene_core::vector::SamplePolylineNode"),
@@ -3947,82 +3940,22 @@ fn migrate_copy_to_points_nodes(document: &mut DocumentMessageHandler) {
}
}
/// The compile-time type of the node output an input is wired to, resolved on a copy of the graph pruned to that output's upstream.
/// The compile-time type of the node output an input is wired to, resolved by compiling only that output's upstream.
/// It is `None` where that copy doesn't compile, such as for content reading a scope only the runtime provides.
fn resolved_output_type(document: &DocumentMessageHandler, preprocessor: &preprocessor::Preprocessor, input: &NodeInput, network_path: &[NodeId]) -> Option<Type> {
let NodeInput::Node { node_id, output_index, .. } = input else { return None };
let NodeInput::Node { node_id, .. } = input else { return None };
// A hidden node passes its primary input through rather than giving the output its type describes
if !document.network_interface.is_visible(node_id, network_path) {
return None;
}
// Subnetworks stored as shared definitions are inlined so the export chain can be redirected down through them
// Subnetworks stored as shared definitions are inlined so the type can be followed through them
let mut network = document.network_interface.document_network().clone();
network.inline_definitions().ok()?;
let output_path: Vec<NodeId> = network_path.iter().copied().chain([*node_id]).collect();
if !redirect_export_chain(&mut network, &output_path, *output_index) {
return None;
}
network.exports.truncate(1);
network.remove_dead_nodes(0);
// Wrap it in the scopes the runtime injects, given only as types since nothing is evaluated
let scope_stand_in = |ty: Type| DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::TypeDefault(ty), false)],
..Default::default()
};
let content_network = DocumentNode {
implementation: DocumentNodeImplementation::Network(network),
..Default::default()
};
let mut scoped_network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(0), 0)],
nodes: [
(NodeId(0), content_network),
(NodeId(1), scope_stand_in(item!(Arc<PlatformEditorApi>))),
(NodeId(2), scope_stand_in(item!(RuntimeHandle))),
]
.into_iter()
.collect(),
scope_injections: [
("editor-api".to_string(), (NodeId(1), item!(Arc<PlatformEditorApi>))),
("runtime".to_string(), (NodeId(2), item!(RuntimeHandle))),
]
.into_iter()
.collect(),
definitions: Default::default(),
generated: true,
};
let resources = &document.resources.registry;
preprocessor.preprocess(&mut scoped_network, &|resource_id| resources.hash(&resource_id)).ok()?;
// The compiler asserts every scope input resolves, so content reading any other scope is left unresolved
if !scope_inputs_resolve(&scoped_network, &HashSet::new()) {
return None;
}
let proto_network = Compiler {}.compile_single(scoped_network).ok()?.network;
let mut typing_context = TypingContext::new(&NODE_REGISTRY);
typing_context.update(&proto_network).ok()?;
typing_context.type_of(proto_network.output).map(|types| types.return_value.clone())
}
/// Whether every scope input in the network is injected by it or a network enclosing it.
fn scope_inputs_resolve(network: &NodeNetwork, enclosing_scopes: &HashSet<String>) -> bool {
let scopes: HashSet<String> = enclosing_scopes.iter().cloned().chain(network.scope_injections.keys().cloned()).collect();
network.nodes.values().all(|node| {
let inputs_resolve = node.inputs.iter().all(|input| !matches!(input, NodeInput::Scope(key) if !scopes.contains(key.as_ref())));
let nested_resolve = match &node.implementation {
DocumentNodeImplementation::Network(nested) => scope_inputs_resolve(nested, &scopes),
_ => true,
};
inputs_resolve && nested_resolve
})
preprocessor.type_of_input(&network, network_path.to_vec(), input.clone(), &|resource_id| resources.hash(&resource_id))
}
/// Rebuilds a removed Copy to Points node as a Repeat on Points, then Vary Rotations and Vary Scales, ending at the original node to keep its downstream wires.
@@ -17,7 +17,7 @@ use crate::messages::resource_storage::ResourcesHandle;
use document_container::store::{DocumentKey, DocumentStore, MemoryStore};
use document_container::{AnyContainer, AsyncContainer};
use document_format::{Error as DocumentFormatError, GddV1, GddV1Layout, Layout, ReadError};
use document_graph_storage::{Declarations, PeerId};
use document_graph_storage::{Declarations, PeerId, UserId};
use graph_craft::application_io::resource::LoadResource;
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceStorage};
use std::collections::HashSet;
@@ -274,7 +274,8 @@ async fn open_storage_or_fallback_to_legacy(container: AnyContainer, document_id
container.remove(&path).await?;
}
}
GddV1::create_in(container, GddV1Layout, PeerId(generate_uuid()), document_id.0, version.clone(), version)
let peer = PeerId(generate_uuid());
GddV1::create_in(container, GddV1Layout, peer, UserId(peer.0), document_id.0, version.clone(), version)
}
.await;
match created {
@@ -320,7 +321,7 @@ async fn build_document_from_storage(gdd: GddV1, byte_store: &ResourcesHandle, d
hydrate_resources(&gdd, byte_store, document_id).await;
let declarations = gdd.declarations(byte_store).await;
let (network, node_entries, network_entries) = match gdd.registry().to_runtime_with_full_metadata(&declarations) {
let (network, node_entries, network_entries) = match gdd.registry().to_runtime_with_full_metadata(&declarations, gdd.blobs()) {
Ok(result) => result,
Err(error) => {
log::error!("Opening document {document_id:?}: failed to convert registry to runtime: {error}");
@@ -428,7 +429,7 @@ mod tests {
#[tokio::test]
async fn a_failed_migration_keeps_the_stored_document() {
let container = AnyContainer::Memory(MemoryBackend::new());
let mut gdd = GddV1::create_in(container.clone(), GddV1Layout, PeerId(1), 1, "editor".into(), "std".into()).unwrap();
let mut gdd = GddV1::create_in(container.clone(), GddV1Layout, PeerId(1), UserId(1), 1, "editor".into(), "std".into()).unwrap();
// No format step starts from version 0, so the migration fails
gdd.update_manifest(|manifest| manifest.format_version = 0).unwrap();
@@ -13,6 +13,7 @@ async fn compile_and_run(editor: &mut EditorTestUtils) {
executor
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO)
.unwrap();
editor.runtime.update();
editor.runtime.run().await;
editor.dispatch(Message::Wake);
}
+426 -338
View File
@@ -1,32 +1,31 @@
use super::*;
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
use crate::task::{Scheduling, Spawn, Spawner, Task};
use crate::task::{Spawn, Spawner, Task};
use glam::{DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::concrete;
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler};
use graph_craft::proto::GraphErrors;
use graphene_hash::CacheHash;
use graphene_std::application_io::{ApplicationIo, ExportFormat, RenderConfig, Texture};
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
use graphene_std::list::{Item, List};
use graphene_std::memo::IORecord;
use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
use graphene_std::raster_types::Raster;
use graphene_std::runtime::{AsyncRuntime, Clock};
use graphene_std::runtime::AsyncRuntime;
use graphene_std::vector::style::RenderMode;
use graphene_std::vector::{Vector, VectorGeometry, paths_from_list_row_attributes};
use graphene_std::{Context, ContextFeatures, ContextOverrides, NodeError, OwnedContextImpl, Poll};
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::util::wrap_network_in_scope;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender};
use std::time::Duration;
use thumbnails::Thumbnails;
mod thumbnails;
@@ -42,15 +41,14 @@ pub struct NodeRuntime {
receiver: Receiver<GraphRuntimeRequest>,
sender: Sender<NodeGraphUpdate>,
editor_wake: Wake,
/// A re-evaluation waiting for the next frame, or for the end of an export.
rerun: bool,
dirty: Arc<AtomicBool>,
pending: Option<ExecutionRequest>,
pending_export: Option<ExecutionRequest>,
pending_eyedropper: Option<ExecutionRequest>,
pending_thumbnails: Option<DocumentId>,
/// The network the executor last compiled successfully, with previews applied.
old_graph: Option<NodeNetwork>,
async_runtime: Option<AsyncRuntime>,
scheduling: Scheduling,
frame_start: Duration,
editor_api: Arc<PlatformEditorApi>,
resources: ResourceRegistry,
@@ -128,14 +126,14 @@ impl NodeRuntime {
receiver,
sender,
editor_wake,
rerun: false,
dirty: Default::default(),
pending: None,
pending_export: None,
pending_eyedropper: None,
pending_thumbnails: None,
old_graph: None,
resources: ResourceRegistry::default(),
async_runtime: None,
scheduling: Scheduling::default(),
frame_start: Duration::ZERO,
editor_api: PlatformEditorApi {
#[cfg(not(test))]
@@ -163,256 +161,247 @@ impl NodeRuntime {
}
}
pub async fn run(&mut self) -> Option<Texture> {
let texture = self.handle_requests().await;
(self.editor_wake)();
texture
}
pub fn update(&mut self) {
if self.pending_export.is_some() {
return;
}
async fn handle_requests(&mut self) -> Option<Texture> {
let mut graph = None;
let mut eyedropper = None;
let mut execution = None;
let mut thumbnails_in_view = None;
let mut inspect_again = false;
for request in self.pending_export.is_none().then_some(&self.receiver).into_iter().flat_map(Receiver::try_iter) {
for request in self.receiver.try_iter() {
match request {
GraphRuntimeRequest::GraphUpdate(_) => graph = Some(request),
GraphRuntimeRequest::ExecutionRequest(ref execution_request) => {
if execution_request.render_config.for_eyedropper {
eyedropper = Some(request);
continue;
}
let for_export = execution_request.render_config.for_export;
execution = Some(request);
// If we get an export request we always execute it immedeatly otherwise it could get deduplicated
if for_export {
break;
}
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request),
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_export => {
self.pending_export = Some(request);
self.dirty.store(true, Ordering::Release);
break;
}
GraphRuntimeRequest::ExecutionRequest(request) => {
self.pending = Some(request);
self.dirty.store(true, Ordering::Release);
}
GraphRuntimeRequest::ThumbnailsInView { layers, document_id } => {
self.thumbnails.set_in_view(layers);
self.pending_thumbnails = Some(document_id);
}
GraphRuntimeRequest::ThumbnailsInView { layers, document_id } => thumbnails_in_view = Some((layers, document_id)),
// A graph update applied after this loop would otherwise inspect what was selected before
GraphRuntimeRequest::Inspect(node_to_inspect) => match &mut graph {
Some(GraphRuntimeRequest::GraphUpdate(update)) => update.node_to_inspect = node_to_inspect,
_ => self.inspect_state = InspectState::new(node_to_inspect),
Some(update) => update.node_to_inspect = node_to_inspect,
None => self.inspect_state = InspectState::new(node_to_inspect),
},
GraphRuntimeRequest::InspectContextOverrides(overrides) => {
if let Some(inspect_state) = &mut self.inspect_state {
inspect_state.overrides = overrides;
inspect_again = true;
inspect_state.overrides_changed = true;
}
}
}
}
// Without an execution to render them along with, the thumbnails that came into view are rendered on their own
if let Some((layers, document_id)) = thumbnails_in_view {
self.thumbnails.set_in_view(layers);
if execution.is_none() && graph.is_none() {
let Some(GraphUpdate {
mut network,
resources,
node_to_inspect,
previewed,
layers,
}) = graph
else {
return;
};
apply_previews(&mut network, &previewed);
match &mut self.inspect_state {
Some(inspect_state) if inspect_state.inspect_node_path == node_to_inspect => inspect_state.last_evaluation = None,
_ => self.inspect_state = InspectState::new(node_to_inspect),
}
self.resources = resources;
self.node_graph_errors.clear();
self.node_graph_warnings.clear();
let result = self.update_network(network.clone());
if result.is_ok() {
self.thumbnails.update_sources(&layers, &network, &self.executor);
self.old_graph = Some(network);
}
let node_graph_errors = self.node_graph_errors.clone();
let node_graph_warnings = self.node_graph_warnings.clone();
self.sender
.send(NodeGraphUpdate::CompilationResponse(CompilationResponse {
result,
node_graph_errors,
node_graph_warnings,
}))
.expect("Failed to send response");
}
pub async fn run(&mut self) -> Option<Texture> {
let dirty = self.dirty.swap(false, Ordering::Acquire);
let mut texture = None;
if let Some(export) = self.pending_export {
if dirty {
self.run_export(export).await;
}
} else {
let viewport = if dirty { self.pending } else { None };
if let Some(document_id) = self.pending_thumbnails.take()
&& viewport.is_none()
{
let mut responses = VecDeque::new();
self.thumbnails.render_stale(&self.executor, &self.editor_api, &mut responses).await;
if !responses.is_empty() {
self.sender.send(NodeGraphUpdate::Thumbnails { responses, document_id }).expect("Failed to send response");
}
}
}
let rerun = std::mem::take(&mut self.rerun) | self.async_runtime().take_bumped();
if rerun && execution.is_none() {
if self.frame_has_budget() {
execution = self.pending_export.or(self.pending).map(GraphRuntimeRequest::ExecutionRequest);
} else {
self.rerun = true;
if let Some(inspect_state) = &mut self.inspect_state
&& std::mem::take(&mut inspect_state.overrides_changed)
&& viewport.is_none()
{
let inspect_result = inspect_state.access(&self.executor, self.old_graph.as_ref());
self.sender.send(NodeGraphUpdate::InspectResult(Box::new(inspect_result))).expect("Failed to send response");
}
if let Some(eyedropper) = self.pending_eyedropper.take() {
self.run_eyedropper(eyedropper).await;
}
if let Some(viewport) = viewport {
texture = self.run_viewport(viewport).await;
}
}
// Eydropper should use the same time and pointer to not invalidate the cache
if let Some(GraphRuntimeRequest::ExecutionRequest(eyedropper)) = &mut eyedropper
&& let Some(GraphRuntimeRequest::ExecutionRequest(execution)) = &execution
(self.editor_wake)();
texture
}
async fn run_viewport(&mut self, request: ExecutionRequest) -> Option<Texture> {
self.thumbnails.set_scale(request.render_config.scale);
let mut result = self.evaluate(request)?;
let texture = if let Some(data) = result.render_output()
&& let RenderOutputType::Texture(texture) = data
{
eyedropper.render_config.time = execution.render_config.time;
eyedropper.render_config.pointer = execution.render_config.pointer;
}
#[cfg(all(target_family = "wasm", feature = "gpu"))]
{
self.current_viewport_texture = Some(texture.clone());
let requests = [graph, eyedropper, execution].into_iter().flatten();
let application_io = self.editor_api.application_io.as_ref().unwrap();
let executor = application_io.gpu_executor().expect("GPU executor should be available when we receive a texture");
self.wasm_canvas_cache.present(texture, executor);
for request in requests {
match request {
GraphRuntimeRequest::ThumbnailsInView { .. } | GraphRuntimeRequest::Inspect(_) | GraphRuntimeRequest::InspectContextOverrides(_) => {}
GraphRuntimeRequest::GraphUpdate(GraphUpdate {
mut network,
resources,
node_to_inspect,
previewed,
layers,
}) => {
apply_previews(&mut network, &previewed);
match &mut self.inspect_state {
Some(inspect_state) if inspect_state.inspect_node_path == node_to_inspect => inspect_state.last_evaluation = None,
_ => self.inspect_state = InspectState::new(node_to_inspect),
}
self.resources = resources;
self.node_graph_errors.clear();
self.node_graph_warnings.clear();
let result = self.update_network(network.clone());
if result.is_ok() {
self.thumbnails.update_sources(&layers, &network, &self.executor);
self.old_graph = Some(network);
}
let node_graph_errors = self.node_graph_errors.clone();
let node_graph_warnings = self.node_graph_warnings.clone();
self.sender
.send(NodeGraphUpdate::CompilationResponse(CompilationResponse {
result,
node_graph_errors,
node_graph_warnings,
}))
.expect("Failed to send response");
}
GraphRuntimeRequest::ExecutionRequest(request @ ExecutionRequest { execution_id, mut render_config, .. }) => {
if !render_config.for_export && !render_config.for_eyedropper {
self.thumbnails.set_scale(render_config.scale);
self.pending = Some(request);
}
if render_config.for_export {
self.pending_export = None;
}
// Render via the SVG pipeline even though raster was requested if SVG Preview render mode is active or there's no GPU, as in headless tests
if render_config.export_format == ExportFormat::Raster
&& (render_config.render_mode == RenderMode::SvgPreview || self.editor_api.application_io.as_ref().unwrap().gpu_executor().is_none())
{
render_config.export_format = ExportFormat::Svg;
}
let mut result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.execute_network(render_config))) {
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
Ok(Ok(Poll::Final(value) | Poll::Partial(value))) => ExecutionResult::Value(value),
Ok(Ok(Poll::Fallback(boxed))) => {
let (value, error) = *boxed;
ExecutionResult::Fallback(value, self.resolve_errors(&error))
}
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)),
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error).error()), NodeErrorTrace::default())]))),
Err(payload) => {
let response = ExecutionResponse {
execution_id,
result: ExecutionResult::Panic(payload),
responses: VecDeque::new(),
dropped_thumbnails: Vec::new(),
vector_modify: HashMap::new(),
inspect_result: None,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
return None;
}
};
match (render_config.for_export, &result) {
(true, ExecutionResult::Pending) => {
self.pending_export = Some(request);
return None;
}
(true, _) => self.rerun = true,
_ => {}
}
let mut responses = VecDeque::new();
let dropped_thumbnails = if !render_config.for_eyedropper {
self.process_monitor_nodes(&mut responses).await
} else {
Vec::new()
};
let inspect_result = self.inspect_state.as_mut().map(|state| state.access(&self.executor, self.old_graph.as_ref()));
let output = match &mut result {
ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _) => Some(value),
ExecutionResult::Pending | ExecutionResult::Error(_) | ExecutionResult::Panic(_) => None,
};
let texture = if let Some(TaggedValue::RenderOutput(RenderOutput { data, .. })) = output
&& let RenderOutputType::Texture(texture) = data
{
let texture = texture.clone();
if render_config.for_export || render_config.for_eyedropper {
let executor = self
.editor_api
.application_io
.as_ref()
.unwrap()
.gpu_executor()
.expect("GPU executor should be available when we receive a texture");
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await;
if render_config.for_eyedropper {
self.sender.send(NodeGraphUpdate::EyedropperPreview(raster_cpu)).expect("Failed to send response");
continue;
}
let (buffer, width, height) = raster_cpu.to_flat_u8();
*data = RenderOutputType::Buffer { data: buffer, width, height };
None
} else {
#[cfg(all(target_family = "wasm", feature = "gpu"))]
{
self.current_viewport_texture = Some(texture.clone());
let app_io = self.editor_api.application_io.as_ref().unwrap();
let executor = app_io.gpu_executor().expect("GPU executor should be available when we receive a texture");
self.wasm_canvas_cache.present(&texture, executor);
let logical_resolution = render_config.viewport.resolution.as_dvec2() / render_config.scale;
*data = RenderOutputType::CanvasFrame {
canvas_id: self.wasm_canvas_cache.id(),
resolution: logical_resolution,
};
None
}
#[cfg(not(all(target_family = "wasm", feature = "gpu")))]
{
Some(texture)
}
}
} else {
None
};
// Eyedropper render that didn't produce a texture (e.g., SVG fallback when GPU is unavailable); discard it
if render_config.for_eyedropper {
continue;
}
let response = ExecutionResponse {
execution_id,
result,
responses,
dropped_thumbnails,
vector_modify: self.vector_modify.clone(),
inspect_result,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
return texture;
}
*data = RenderOutputType::CanvasFrame {
canvas_id: self.wasm_canvas_cache.id(),
resolution: request.render_config.viewport.resolution.as_dvec2() / request.render_config.scale,
};
None
}
#[cfg(not(all(target_family = "wasm", feature = "gpu")))]
{
Some(texture.clone())
}
} else {
None
};
self.respond(request.execution_id, result).await;
texture
}
async fn run_export(&mut self, request: ExecutionRequest) {
let result = self.evaluate(request);
if matches!(result, Some(ExecutionResult::Pending)) {
return;
}
// Without an execution to send it along with, the inspected node is evaluated again with its new overrides once the graph is up to date
if inspect_again && let Some(inspect_state) = &mut self.inspect_state {
let inspect_result = inspect_state.access(&self.executor, self.old_graph.as_ref());
self.sender.send(NodeGraphUpdate::InspectResult(Box::new(inspect_result))).expect("Failed to send response");
self.pending_export = None;
let Some(mut result) = result else { return };
self.dirty.store(true, Ordering::Release);
if let Some(data) = result.render_output()
&& let RenderOutputType::Texture(texture) = data
{
let (buffer, width, height) = self.read_back(texture.clone()).await.to_flat_u8();
*data = RenderOutputType::Buffer { data: buffer, width, height };
}
self.respond(request.execution_id, result).await;
}
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
// Eyedropper should use the same time and pointer to not invalidate the cache
if let Some(viewport) = self.pending {
request.render_config.time = viewport.render_config.time;
request.render_config.pointer = viewport.render_config.pointer;
}
None
if let Some(mut result) = self.evaluate(request)
&& let Some(RenderOutputType::Texture(texture)) = result.render_output()
{
let raster = self.read_back(texture.clone()).await;
self.sender.send(NodeGraphUpdate::EyedropperPreview(raster)).expect("Failed to send response");
}
}
fn evaluate(&mut self, request: ExecutionRequest) -> Option<ExecutionResult> {
let ExecutionRequest { execution_id, mut render_config } = request;
// Render via the SVG pipeline even though raster was requested if SVG Preview render mode is active or there's no GPU
if render_config.export_format == ExportFormat::Raster && (render_config.render_mode == RenderMode::SvgPreview || self.editor_api.application_io.as_ref().unwrap().gpu_executor().is_none()) {
render_config.export_format = ExportFormat::Svg;
}
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.executor.output(), &context))) {
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
Ok(Ok(Poll::Final(value) | Poll::Partial(value))) => ExecutionResult::Value(value),
Ok(Ok(Poll::Fallback(boxed))) => {
let (value, error) = *boxed;
ExecutionResult::Fallback(value, self.resolve_errors(&error))
}
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)),
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error).error()), NodeErrorTrace::default())]))),
Err(payload) => {
let response = ExecutionResponse {
execution_id,
result: ExecutionResult::Panic(payload),
responses: VecDeque::new(),
dropped_thumbnails: Vec::new(),
vector_modify: HashMap::new(),
inspect_result: None,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
return None;
}
};
Some(result)
}
async fn respond(&mut self, execution_id: u64, result: ExecutionResult) {
let mut responses = VecDeque::new();
let dropped_thumbnails = self.process_monitor_nodes(&mut responses).await;
let inspect_result = self.inspect_state.as_mut().map(|state| state.access(&self.executor, self.old_graph.as_ref()));
let response = ExecutionResponse {
execution_id,
result,
responses,
dropped_thumbnails,
vector_modify: self.vector_modify.clone(),
inspect_result,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
}
async fn read_back(&self, texture: Texture) -> Raster<CPU> {
let application_io = self.editor_api.application_io.as_ref().unwrap();
let executor = application_io.gpu_executor().expect("GPU executor should be available when we receive a texture");
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
}
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
@@ -448,23 +437,10 @@ impl NodeRuntime {
self.node_graph_errors.clone_from(&e);
(types, format!("{e:?}"))
});
self.async_runtime().retain_sources(self.executor.sources());
self.async_runtime().update_sources(self.executor.sources());
result
}
fn execute_network(&mut self, render_config: RenderConfig) -> Result<Poll<TaggedValue>, String> {
use graph_craft::graphene_compiler::Executor;
match self.executor.input_type() {
Some(t) if t == concrete!(Context) => (&self.executor)
.execute(render_config.into_context_with_generations(self.async_runtime().snapshot()))
.map_err(|e| e.to_string()),
Some(t) if t == concrete!(()) => (&self.executor).execute(()).map_err(|e| e.to_string()),
Some(t) => Err(format!("Invalid input type {t:?}")),
_ => Err(format!("No input type:\n{:?}", self.node_graph_errors)),
}
}
fn resolve_errors(&self, error: &NodeError) -> EvaluationErrors {
let source_map = self.executor.tree().source_map();
let paths = |node: NodeId| -> NodePaths {
@@ -526,6 +502,14 @@ impl NodeRuntime {
}
}
impl ExecutionResult {
fn render_output(&mut self) -> Option<&mut RenderOutputType> {
let (Self::Value(value) | Self::Fallback(value, _)) = self else { return None };
let TaggedValue::RenderOutput(RenderOutput { data, .. }) = value else { return None };
Some(data)
}
}
/// The layer a monitor node belongs to, since monitor nodes sit within the network of the document node they monitor.
fn monitor_parent_node(monitor_node_path: &[NodeId]) -> Option<NodeId> {
monitor_node_path.len().checked_sub(2).and_then(|index| monitor_node_path.get(index)).copied()
@@ -577,54 +561,33 @@ impl NodeRuntime {
.into();
}
pub(crate) fn replace_task_executor(&mut self, spawner: Spawner, wake: Wake, clock: Arc<dyn Clock>) {
self.async_runtime = Some(AsyncRuntime::new(Arc::new(NodeTaskExecutor { spawner, wake }), clock));
self.begin_frame();
pub(crate) fn replace_task_executor(&mut self, spawner: Spawner, wake: Wake) {
let spawn = NodeTaskExecutor {
spawner,
dirty: self.dirty.clone(),
wake,
};
self.async_runtime = Some(AsyncRuntime::new(Arc::new(spawn)));
}
pub fn set_scheduling(&mut self, scheduling: Scheduling) {
self.scheduling = scheduling;
}
/// Called by the host once the previous output was presented.
pub fn begin_frame(&mut self) {
self.frame_start = self.async_runtime().clock().now();
}
/// How long a deferred re-evaluation waits for the next frame.
pub fn until_next_frame(&self) -> Option<Duration> {
let budget = self.frame_budget()?;
let elapsed = self.frame_elapsed().as_nanos() % budget.as_nanos();
self.rerun.then(|| budget - Duration::from_nanos(elapsed as u64))
}
fn frame_elapsed(&self) -> Duration {
self.async_runtime().clock().now().saturating_sub(self.frame_start)
}
fn frame_budget(&self) -> Option<Duration> {
self.scheduling.frame_budget.filter(|budget| !budget.is_zero())
}
fn frame_has_budget(&self) -> bool {
self.frame_budget().is_none_or(|budget| self.frame_elapsed() < budget)
}
pub(crate) fn async_runtime(&self) -> &AsyncRuntime {
fn async_runtime(&self) -> &AsyncRuntime {
self.async_runtime.as_ref().expect("the task executor is installed before the first graph update")
}
}
struct NodeTaskExecutor {
spawner: Spawner,
dirty: Arc<AtomicBool>,
wake: Wake,
}
impl Spawn for NodeTaskExecutor {
fn spawn(&self, task: Task) {
let dirty = self.dirty.clone();
let wake = self.wake.clone();
self.spawner.spawn(Box::pin(async move {
task.await;
dirty.store(true, Ordering::Release);
wake();
}));
}
@@ -635,6 +598,7 @@ struct InspectState {
inspect_node_path: Vec<NodeId>,
overrides: ContextOverrides,
last_evaluation: Option<(NodeId, u64, Option<InspectedData>)>,
overrides_changed: bool,
}
type InspectedData = Arc<dyn std::any::Any + Send + Sync + 'static>;
@@ -680,6 +644,7 @@ impl InspectState {
inspect_node_path,
overrides: ContextOverrides::default(),
last_evaluation: None,
overrides_changed: false,
})
}
@@ -733,11 +698,196 @@ impl InspectState {
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::{EditorTestUtils, FakeClock};
use crate::test_utils::EditorTestUtils;
use graph_craft::document::DocumentNode;
use graphene_std::SourceId;
use graphene_std::runtime::Runtime;
const SOURCE: SourceId = SourceId(1);
async fn editor() -> EditorTestUtils {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// We use the svg pipeline for these tests since we don't read back the result for editor tests anyway
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
editor.draw_rect(0., 0., 100., 100.).await;
editor.runtime.async_runtime().update_sources(&[SOURCE]);
editor
}
/// Sends a network update and a request to evaluate it, as the editor does for a change to the graph.
fn send_update(editor: &mut EditorTestUtils) {
let portfolio = editor.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
executor
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), Vec::new(), true, DVec2::ZERO)
.unwrap();
}
/// Sends a network update and a request to export it, as the editor does for an export.
fn send_export(editor: &mut EditorTestUtils) {
let portfolio = editor.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
let export_config = ExportConfig {
name: "export".to_string(),
file_type: FileType::Svg,
scale_factor: 1.,
bounds: ExportBounds::AllArtwork,
..Default::default()
};
executor.submit_document_export(document, document_id, export_config).unwrap();
}
/// Whether the runtime evaluated the graph since this was last called.
fn evaluated(editor: &mut EditorTestUtils) -> bool {
editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::UpdateDocumentArtwork { .. }))
}
/// Whether the runtime finished an export since this was last called.
fn exported(editor: &mut EditorTestUtils) -> bool {
editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }))
}
/// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations.
fn vectorize_layer(editor: &mut EditorTestUtils) {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
let layer = editor.active_document().metadata().all_layers().next().unwrap();
let mut create = |node_type| {
let node_id = NodeId::new();
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(node_id),
node_type,
xy: None,
add_transaction: true,
});
node_id
};
let noise = create(DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER));
let vectorize = create(DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER));
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(noise),
input_connector: InputConnector::node_at_index(vectorize, 0),
});
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(vectorize),
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
});
}
/// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one.
fn last_request(editor: &EditorTestUtils) -> Option<u64> {
editor.runtime.pending.map(|request| request.execution_id)
}
#[tokio::test]
async fn only_update_reads_the_channel() {
let mut editor = editor().await;
send_update(&mut editor);
editor.runtime.run().await;
assert!(!evaluated(&mut editor), "run read the request");
editor.runtime.update();
editor.runtime.run().await;
assert!(evaluated(&mut editor));
}
#[tokio::test]
async fn an_export_goes_ahead_of_what_was_sent_after_it() {
let mut editor = editor().await;
let last = last_request(&editor);
send_export(&mut editor);
send_update(&mut editor);
editor.runtime.update();
assert!(editor.runtime.pending_export.is_some());
assert_eq!(last_request(&editor), last, "the request sent after the export was read ahead of it");
editor.runtime.run().await;
assert!(exported(&mut editor));
editor.runtime.update();
assert_ne!(last_request(&editor), last);
editor.runtime.run().await;
assert!(evaluated(&mut editor), "the request sent after the export was lost");
}
#[tokio::test]
async fn a_parked_export_holds_back_everything_sent_after_it() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
editor.draw_rect(0., 0., 512., 512.).await;
vectorize_layer(&mut editor);
send_export(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
assert!(editor.runtime.pending_export.is_some(), "the export took a single evaluation");
let last = last_request(&editor);
send_update(&mut editor);
let mut runs = 0;
while editor.runtime.pending_export.is_some() {
editor.runtime.update();
assert_eq!(last_request(&editor), last, "a request got ahead of the parked export");
editor.runtime.run().await;
runs += 1;
assert!(runs < 100_000, "the export never finished");
}
assert!(exported(&mut editor));
editor.runtime.update();
assert_ne!(last_request(&editor), last);
editor.runtime.run().await;
assert!(evaluated(&mut editor), "the request sent after the export was lost");
}
#[tokio::test]
async fn a_graph_settles_while_network_updates_keep_arriving() {
let mut editor = editor().await;
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
assert!(evaluated(&mut editor));
let last = last_request(&editor);
for _ in 0..3 {
send_update(&mut editor);
editor.runtime.async_runtime().spawn(SOURCE, Box::pin(async {}));
editor.runtime.run().await;
assert!(evaluated(&mut editor), "the finished task didn't evaluate the graph again");
assert_eq!(last_request(&editor), last, "run read the request");
}
editor.runtime.update();
assert_ne!(last_request(&editor), last);
assert!(editor.runtime.receiver.try_recv().is_err(), "update left a request in the channel");
editor.runtime.run().await;
assert!(evaluated(&mut editor));
}
#[tokio::test]
async fn several_network_updates_evaluate_once() {
let mut editor = editor().await;
for _ in 0..3 {
send_update(&mut editor);
}
editor.runtime.update();
editor.runtime.run().await;
assert!(evaluated(&mut editor));
editor.runtime.run().await;
assert!(!evaluated(&mut editor), "the requests of the older network updates evaluated again");
}
#[test]
fn a_preview_replaces_the_export_of_the_graph_being_compiled() {
let previewed_node = NodeId(1);
@@ -761,66 +911,4 @@ mod tests {
assert_eq!(network.exports.first().and_then(|export| export.as_node()), Some(previewed_node));
}
const SOURCE: SourceId = SourceId(1);
async fn editor(clock: &Arc<FakeClock>) -> EditorTestUtils {
let mut editor = EditorTestUtils::create_with(Scheduling::default(), clock.clone());
editor.new_document().await;
// We use the svg pipeline for these tests since we don't read back the result for editor tests anyway
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
editor.draw_rect(0., 0., 100., 100.).await;
editor.runtime.async_runtime().retain_sources(&[SOURCE]);
editor.runtime.begin_frame();
editor
}
fn finish_task(editor: &EditorTestUtils) {
editor.runtime.async_runtime().spawn(SOURCE, Box::pin(async {}));
}
async fn evaluates(editor: &mut EditorTestUtils) -> bool {
editor.runtime.run().await;
let messages = editor.editor.handle_message(Message::Wake);
messages.iter().any(|message| matches!(message, FrontendMessage::UpdateDocumentArtwork { .. }))
}
#[tokio::test]
async fn reevaluations_past_the_frame_budget_wait_for_the_next_frame() {
let clock = Arc::new(FakeClock::default());
let mut editor = editor(&clock).await;
finish_task(&editor);
finish_task(&editor);
assert!(evaluates(&mut editor).await);
assert!(!evaluates(&mut editor).await, "two finished tasks re-evaluated twice");
clock.advance(Duration::from_millis(20));
finish_task(&editor);
assert!(!evaluates(&mut editor).await);
assert_eq!(editor.runtime.until_next_frame(), Some(Duration::from_millis(12)));
editor.runtime.begin_frame();
assert!(evaluates(&mut editor).await);
assert_eq!(editor.runtime.until_next_frame(), None);
}
#[tokio::test]
async fn explicit_requests_ignore_the_frame_budget() {
let clock = Arc::new(FakeClock::default());
let mut editor = editor(&clock).await;
clock.advance(Duration::from_millis(100));
finish_task(&editor);
let portfolio = &mut editor.editor.dispatcher.message_handlers.portfolio_message_handler;
let document_id = portfolio.active_document_id.unwrap();
let document = portfolio.documents.get_mut(&document_id).unwrap();
portfolio
.executor
.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO)
.unwrap();
assert!(evaluates(&mut editor).await);
assert!(!evaluates(&mut editor).await, "the finished task re-evaluated after the explicit request");
}
}
@@ -458,6 +458,7 @@ mod tests {
executor
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO)
.unwrap();
editor.runtime.update();
editor.runtime.run().await;
editor.dispatch(Message::Wake);
}
+1 -1
View File
@@ -1,4 +1,4 @@
pub use graphene_std::runtime::{Clock, Scheduling, Spawn, Task};
pub use graphene_std::runtime::{Spawn, Task};
use std::sync::Arc;
pub type Spawner = Arc<dyn Spawn + Send + Sync>;
+4 -25
View File
@@ -10,18 +10,16 @@ use crate::messages::tool::tool_messages::tool_prelude::Key;
use crate::messages::tool::utility_types::ToolType;
use crate::node_graph_executor::Instrumented;
use crate::node_graph_executor::{EvaluationErrors, NodeRuntime};
use crate::task::{Scheduling, Spawn, Task};
use crate::task::{Spawn, Task};
use crate::test_utils::test_prelude::LayerNodeIdentifier;
use document_container::store::MemoryStore;
use glam::{DVec2, UVec2};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::application_io::{ApplicationIo, PlatformApplicationIo};
use graphene_std::raster::color::Color;
use graphene_std::runtime::Clock;
use graphene_std::uuid::NodeId;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, LazyLock, Mutex, PoisonError};
use std::time::Duration;
use std::sync::{Arc, LazyLock};
/// A set of utility functions to make the writing of editor test more declarative
pub struct EditorTestUtils {
@@ -32,10 +30,6 @@ pub struct EditorTestUtils {
impl EditorTestUtils {
pub fn create() -> Self {
Self::create_with(Scheduling::UNLIMITED, Arc::new(FakeClock::default()))
}
pub fn create_with(scheduling: Scheduling, clock: Arc<dyn Clock>) -> Self {
init_test_logger();
let woken = Arc::new(AtomicBool::new(false));
@@ -48,7 +42,7 @@ impl EditorTestUtils {
.with_resource_storage(Arc::new(HashMapResourceStorage::new()))
.with_document_store(Arc::new(MemoryStore::default())),
)
.with_runtime(RuntimeBuilder::new(clock).with_wake(|| {}).with_application_io(gpu_application_io()).with_scheduling(scheduling))
.with_runtime(RuntimeBuilder::new().with_wake(|| {}).with_application_io(gpu_application_io()))
.with_spawner(BlockingSpawner)
.with_random_seed(0)
.build();
@@ -88,6 +82,7 @@ impl EditorTestUtils {
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
return Err(TestGraphError::Other(format!("submit_current_node_graph_evaluation failed\n\n{e}")));
}
self.runtime.update();
self.runtime.run().await;
let frontend_messages = self.dispatch(Message::Wake);
@@ -509,22 +504,6 @@ pub fn capture_logged_errors<T>(operation: impl FnOnce() -> T) -> (T, Vec<String
(result, errors)
}
/// A clock that only moves when advanced.
#[derive(Debug, Default)]
pub struct FakeClock(Mutex<Duration>);
impl FakeClock {
pub fn advance(&self, by: Duration) {
*self.0.lock().unwrap_or_else(PoisonError::into_inner) += by;
}
}
impl Clock for FakeClock {
fn now(&self) -> Duration {
*self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
struct BlockingSpawner;
impl Spawn for BlockingSpawner {
fn spawn(&self, task: Task) {
+1 -1
View File
@@ -36,7 +36,7 @@ serde-wasm-bindgen = { workspace = true }
js-sys = { workspace = true }
wasm-bindgen-futures = { workspace = true }
wgpu = { workspace = true, optional = true }
web-sys = { workspace = true, features = ["Performance"] }
web-sys = { workspace = true, features = ["IdleDeadline"] }
serde_json = { workspace = true }
spin = { workspace = true, optional = true }
tsify = { workspace = true }
+2 -13
View File
@@ -81,11 +81,7 @@ impl EditorWrapper {
.with_resource_storage(storage)
.with_document_store(document_store),
)
.with_runtime(
RuntimeBuilder::new(std::sync::Arc::new(crate::helpers::PerformanceClock))
.with_wake(crate::helpers::wake_runtime)
.with_application_io(application_io),
)
.with_runtime(RuntimeBuilder::new().with_wake(crate::helpers::wake_runtime).with_application_io(application_io))
.with_spawner(crate::helpers::WasmSpawner)
.with_random_seed(uuid_random_seed)
.build();
@@ -197,14 +193,7 @@ impl EditorWrapper {
*g.borrow_mut() = Some(Closure::new(move |_timestamp| {
#[cfg(not(feature = "native"))]
{
if let Some(mut runtime) = crate::NODE_RUNTIME.try_lock()
&& let Some(runtime) = runtime.as_mut()
{
runtime.begin_frame();
}
wasm_bindgen_futures::spawn_local(run_node_runtime());
}
wasm_bindgen_futures::spawn_local(run_node_runtime(true));
#[cfg(any(not(feature = "native"), target_family = "wasm"))]
wrapper(|wrapper| {
+43 -14
View File
@@ -7,8 +7,12 @@ use editor::messages::input_mapper::utility_types::keyboard::Key;
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
use editor::messages::prelude::*;
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
use editor::task::{Clock, Spawn, Task};
use editor::task::{Spawn, Task};
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
use graphene_std::runtime::Instant;
use js_sys::{Object, Reflect};
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
use std::cell::Cell;
use std::cell::RefCell;
use std::collections::HashSet;
#[cfg(not(feature = "native"))]
@@ -50,7 +54,7 @@ pub(crate) fn wrapper(callback: impl FnOnce(&mut EditorWrapper)) {
}
#[cfg(not(feature = "native"))]
pub(crate) async fn run_node_runtime() {
pub(crate) async fn run_node_runtime(update: bool) {
// Process no further messages after a crash to avoid spamming the console
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
return;
@@ -58,6 +62,9 @@ pub(crate) async fn run_node_runtime() {
let Some(mut runtime) = crate::NODE_RUNTIME.try_lock() else { return };
let Some(runtime) = runtime.as_mut() else { return };
if update {
runtime.update();
}
runtime.run().await;
}
@@ -70,16 +77,6 @@ impl Spawn for WasmSpawner {
}
}
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
pub(crate) struct PerformanceClock;
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
impl Clock for PerformanceClock {
fn now(&self) -> Duration {
let performance = window().and_then(|window| window.performance()).expect("the editor runs in a window with `performance`");
Duration::from_secs_f64(performance.now() / 1000.)
}
}
/// Web editor wake: queues a microtask that dispatches [`Message::Wake`].
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
pub(crate) fn wake_editor() {
@@ -88,10 +85,42 @@ pub(crate) fn wake_editor() {
});
}
/// Web runtime wake: queues a run of the node runtime. Used to wake the runtime on async task completion.
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
thread_local! {
static IDLE_RUN_QUEUED: Cell<bool> = const { Cell::new(false) };
static IDLE_PERIOD: RefCell<Option<(web_sys::IdleDeadline, Instant)>> = const { RefCell::new(None) };
static IDLE_RUN: Closure<dyn FnMut(web_sys::IdleDeadline)> = Closure::new(|deadline| {
IDLE_RUN_QUEUED.set(false);
IDLE_PERIOD.set(Some((deadline, Instant::now())));
wasm_bindgen_futures::spawn_local(run_node_runtime(false));
});
}
/// Web runtime wake: runs the node runtime in the time left before the next frame, so it can't hold up the browser's painting
/// Within an idle period it runs again at once if the time the last run took still fits.
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
pub(crate) fn wake_runtime() {
wasm_bindgen_futures::spawn_local(run_node_runtime());
let fits = IDLE_PERIOD.with_borrow_mut(|period| {
period.as_mut().is_some_and(|(deadline, run_start)| {
let now = Instant::now();
let fits = deadline.time_remaining() > (now - *run_start).as_secs_f64() * 1000.;
if fits {
*run_start = now;
}
fits
})
});
if fits {
wasm_bindgen_futures::spawn_local(run_node_runtime(false));
return;
}
let Some(window) = window() else { return };
if Reflect::has(&window, &"requestIdleCallback".into()).unwrap_or(false) && !IDLE_RUN_QUEUED.replace(true) {
IDLE_RUN.with(|run| {
let _ = window.request_idle_callback(run.as_ref().unchecked_ref());
});
}
}
thread_local! {
+399 -8
View File
@@ -556,6 +556,14 @@ pub struct NodeNetwork {
/// Where a network of the document lives: a definitions table entry, or `None` for the document network itself.
pub type NetworkLocation = Option<NetworkId>;
/// The output count of `implementation`, or `None` for a table entry that `definitions` lacks.
fn output_count_in(implementation: &DocumentNodeImplementation, definitions: &FxHashMap<NetworkId, NodeNetwork>) -> Option<usize> {
match implementation {
DocumentNodeImplementation::Definition(id) => definitions.get(id).map(|definition| definition.exports.len()),
_ => Some(implementation.output_count()),
}
}
/// One inline network that [`NodeNetwork::lift_nested_networks`] moved into the definitions table.
/// The node `node_id` in table entry `containing` (`None` for the document network) now names it as `id`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -584,6 +592,75 @@ impl std::fmt::Display for DefinitionError {
impl std::error::Error for DefinitionError {}
fn validate_named_definitions(
network: &NodeNetwork,
definitions: &FxHashMap<NetworkId, NodeNetwork>,
visiting: &mut Vec<NetworkId>,
validated: &mut FxHashSet<NetworkId>,
) -> Result<(), DefinitionError> {
for node in network.nodes.values() {
match &node.implementation {
DocumentNodeImplementation::Definition(id) => {
if let Some(start) = visiting.iter().position(|visiting| visiting == id) {
return Err(DefinitionError::Cycle(visiting[start..].to_vec()));
}
if validated.contains(id) {
continue;
}
let definition = definitions.get(id).ok_or(DefinitionError::Missing(*id))?;
if !definition.definitions.is_empty() {
return Err(DefinitionError::NestedTable);
}
visiting.push(*id);
validate_named_definitions(definition, definitions, visiting, validated)?;
visiting.pop();
validated.insert(*id);
}
DocumentNodeImplementation::Network(nested) => {
if !nested.definitions.is_empty() {
return Err(DefinitionError::NestedTable);
}
validate_named_definitions(nested, definitions, visiting, validated)?;
}
_ => {}
}
}
Ok(())
}
/// Every table entry, each listed after the entries its nodes name. O(entries + nodes).
fn definitions_children_first(definitions: &FxHashMap<NetworkId, NodeNetwork>) -> Vec<NetworkId> {
fn visit_network(network: &NodeNetwork, definitions: &FxHashMap<NetworkId, NodeNetwork>, visited: &mut FxHashSet<NetworkId>, order: &mut Vec<NetworkId>) {
for node in network.nodes.values() {
match &node.implementation {
DocumentNodeImplementation::Definition(id) => visit_definition(*id, definitions, visited, order),
DocumentNodeImplementation::Network(nested) => visit_network(nested, definitions, visited, order),
_ => {}
}
}
}
fn visit_definition(id: NetworkId, definitions: &FxHashMap<NetworkId, NodeNetwork>, visited: &mut FxHashSet<NetworkId>, order: &mut Vec<NetworkId>) {
if !visited.insert(id) {
return;
}
if let Some(definition) = definitions.get(&id) {
visit_network(definition, definitions, visited, order);
}
order.push(id);
}
let mut ids: Vec<NetworkId> = definitions.keys().copied().collect();
ids.sort();
let mut visited = FxHashSet::default();
let mut order = Vec::with_capacity(ids.len());
for id in ids {
visit_definition(id, definitions, &mut visited, &mut order);
}
order
}
struct DefinitionInliner {
definitions: FxHashMap<NetworkId, NodeNetwork>,
inlined: FxHashMap<NetworkId, NodeNetwork>,
@@ -725,10 +802,7 @@ impl NodeNetwork {
}
pub fn implementation_output_count(&self, implementation: &DocumentNodeImplementation) -> usize {
match implementation {
DocumentNodeImplementation::Definition(_) => self.implementation_network(implementation).map_or(0, |network| network.exports.len()),
_ => implementation.output_count(),
}
output_count_in(implementation, &self.definitions).unwrap_or(0)
}
/// The path of the node producing this output once compiled, following network exports and the primary inputs of hidden and Passthrough nodes.
@@ -836,6 +910,11 @@ impl NodeNetwork {
dropped
}
/// Checks that every table entry a node names exists, that no entries name each other in a cycle, and that only this network holds a table.
pub fn validate_definitions(&self) -> Result<(), DefinitionError> {
validate_named_definitions(self, &self.definitions, &mut Vec::new(), &mut FxHashSet::default())
}
pub fn inline_definitions(&mut self) -> Result<(), DefinitionError> {
let mut inliner = DefinitionInliner {
definitions: std::mem::take(&mut self.definitions),
@@ -894,12 +973,104 @@ impl NodeNetwork {
// Functions for resolving scope inputs
impl NodeNetwork {
/// Resolves each scope input to the node injecting it, adding imports to carry it into nested networks.
///
/// Each table entry is resolved once per scope context, children first: the keys an entry does not inject become its imports,
/// and every node naming the entry gets a matching scope input that its own network then resolves, so the nearest injection wins.
/// An entry reached from contexts that give a key different types is specialized into one entry per context.
pub fn resolve_scope_inputs(&mut self) {
let mut free_keys = FxHashMap::default();
for id in definitions_children_first(&self.definitions) {
let Some(definition) = self.definitions.get(&id) else { continue };
let keys = definition.free_scope_keys(&free_keys);
free_keys.insert(id, keys);
}
let originals = std::mem::take(&mut self.definitions);
let mut specializer = ScopeSpecializer {
originals: &originals,
free_keys: &free_keys,
base_signatures: FxHashMap::default(),
contexts: FxHashMap::default(),
specialized: FxHashMap::default(),
};
let root_chain = self.scope_injections.clone();
specializer.specialize(self, &root_chain);
let ScopeSpecializer {
contexts,
specialized: mut definitions,
..
} = specializer;
let mut import_counts = FxHashMap::default();
for network in std::iter::once(&*self).chain(definitions.values()) {
network.collect_instance_input_counts(&mut import_counts);
}
let mut forwarded: FxHashMap<NetworkId, Vec<NodeInput>> = FxHashMap::default();
for id in definitions_children_first(&definitions) {
let (Some(definition), Some(context)) = (definitions.get_mut(&id), contexts.get(&id)) else {
continue;
};
definition.append_forwarded_scopes(&forwarded);
// Stands in for an instance's inputs, so the forwarded keys become imports after the existing ones
let import_count = import_counts.get(&id).copied().unwrap_or_default();
let mut instance_inputs = vec![NodeInput::value(TaggedValue::None, false); import_count];
let outside = ScopeChain { scopes: context, parent: None };
definition.resolve_scope_inputs_impl(Some(&outside), &mut instance_inputs);
forwarded.insert(id, instance_inputs.split_off(import_count));
}
self.append_forwarded_scopes(&forwarded);
self.definitions = definitions;
let mut leftover = Vec::new();
self.resolve_scope_inputs_impl(None, &mut leftover);
assert!(leftover.is_empty(), "Unresolved scope keys at top level: {leftover:?}");
}
/// The scope keys this network reads, directly or through the networks it contains, without injecting them itself.
fn free_scope_keys(&self, entry_keys: &FxHashMap<NetworkId, FxHashSet<String>>) -> FxHashSet<String> {
let mut keys = FxHashSet::default();
for node in self.nodes.values() {
keys.extend(node.inputs.iter().filter_map(|input| match input {
NodeInput::Scope(key) => Some(key.to_string()),
_ => None,
}));
match &node.implementation {
DocumentNodeImplementation::Definition(id) => keys.extend(entry_keys.get(id).into_iter().flatten().cloned()),
DocumentNodeImplementation::Network(nested) => keys.extend(nested.free_scope_keys(entry_keys)),
_ => {}
}
}
keys.retain(|key| !self.scope_injections.contains_key(key));
keys
}
fn collect_instance_input_counts(&self, counts: &mut FxHashMap<NetworkId, usize>) {
for node in self.nodes.values() {
match &node.implementation {
DocumentNodeImplementation::Definition(id) => {
counts.entry(*id).or_insert(node.inputs.len());
}
DocumentNodeImplementation::Network(nested) => nested.collect_instance_input_counts(counts),
_ => {}
}
}
}
fn append_forwarded_scopes(&mut self, forwarded: &FxHashMap<NetworkId, Vec<NodeInput>>) {
for node in self.nodes.values_mut() {
match &mut node.implementation {
DocumentNodeImplementation::Definition(id) => node.inputs.extend(forwarded.get(id).into_iter().flatten().cloned()),
DocumentNodeImplementation::Network(nested) => nested.append_forwarded_scopes(forwarded),
_ => {}
}
}
}
fn resolve_scope_inputs_impl(&mut self, parent: Option<&ScopeChain<'_>>, network_inputs: &mut Vec<NodeInput>) {
let scope_chain = ScopeChain {
scopes: &self.scope_injections,
@@ -935,8 +1106,73 @@ impl NodeNetwork {
}
}
type ScopeInjections = FxHashMap<String, (NodeId, Type)>;
/// Gives every instance the entry matching the scope types its context provides, copying an entry for each further context.
struct ScopeSpecializer<'a> {
originals: &'a FxHashMap<NetworkId, NodeNetwork>,
free_keys: &'a FxHashMap<NetworkId, FxHashSet<String>>,
/// The signature of the first context reaching each original entry, which keeps the entry's ID.
base_signatures: FxHashMap<NetworkId, Vec<(String, Type)>>,
/// The injections each specialized entry resolves its free keys against.
contexts: FxHashMap<NetworkId, ScopeInjections>,
specialized: FxHashMap<NetworkId, NodeNetwork>,
}
impl ScopeSpecializer<'_> {
/// Points every instance in `network` at its specialization, where `chain` holds the nearest injection of every key visible in `network`.
fn specialize(&mut self, network: &mut NodeNetwork, chain: &ScopeInjections) {
let mut node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
node_ids.sort();
for node_id in node_ids {
let Some(node) = network.nodes.get_mut(&node_id) else { continue };
match &mut node.implementation {
DocumentNodeImplementation::Definition(id) => *id = self.specialization(*id, chain),
DocumentNodeImplementation::Network(nested) => {
let mut nested_chain = chain.clone();
nested_chain.extend(nested.scope_injections.iter().map(|(key, injection)| (key.clone(), injection.clone())));
self.specialize(nested, &nested_chain);
}
_ => {}
}
}
}
fn specialization(&mut self, id: NetworkId, chain: &ScopeInjections) -> NetworkId {
let Some(original) = self.originals.get(&id) else { return id };
let context: ScopeInjections = self.free_keys.get(&id).into_iter().flatten().filter_map(|key| Some((key.clone(), chain.get(key)?.clone()))).collect();
let mut signature: Vec<(String, Type)> = context.iter().map(|(key, (_, ty))| (key.clone(), ty.clone())).collect();
signature.sort_by(|(a, _), (b, _)| a.cmp(b));
let base_signature = self.base_signatures.entry(id).or_insert_with(|| signature.clone());
let specialized_id = if *base_signature == signature { id } else { specialized_network_id(id, &signature) };
if self.contexts.contains_key(&specialized_id) {
return specialized_id;
}
let mut body = original.clone();
let mut inner_chain = context.clone();
inner_chain.extend(body.scope_injections.iter().map(|(key, injection)| (key.clone(), injection.clone())));
self.contexts.insert(specialized_id, context);
self.specialize(&mut body, &inner_chain);
self.specialized.insert(specialized_id, body);
specialized_id
}
}
fn specialized_network_id(id: NetworkId, signature: &[(String, Type)]) -> NetworkId {
let mut hasher = DefaultHasher::new();
"scope specialization".hash(&mut hasher);
id.hash(&mut hasher);
signature.hash(&mut hasher);
NetworkId(hasher.finish())
}
struct ScopeChain<'a> {
scopes: &'a FxHashMap<String, (NodeId, Type)>,
scopes: &'a ScopeInjections,
parent: Option<&'a ScopeChain<'a>>,
}
enum ScopeChainLookup<'a> {
@@ -1010,29 +1246,46 @@ impl NodeNetwork {
}
/// Populate the [`DocumentNode::path`], which stores the location of the document node to allow for matching the resulting proto nodes to the document node for the purposes of typing and finding monitor nodes.
///
/// Table entries are not visited, since each instance gets its paths when [`Self::flatten`] copies the entry.
pub fn generate_node_paths(&mut self, prefix: &[NodeId]) {
let definitions = std::mem::take(&mut self.definitions);
self.generate_node_paths_with(prefix, &definitions);
self.definitions = definitions;
}
fn generate_node_paths_with(&mut self, prefix: &[NodeId], definitions: &FxHashMap<NetworkId, NodeNetwork>) {
for (node_id, node) in &mut self.nodes {
let mut new_path = prefix.to_vec();
if !self.generated {
new_path.push(*node_id);
}
if let DocumentNodeImplementation::Network(network) = &mut node.implementation {
network.generate_node_paths(new_path.as_slice());
network.generate_node_paths_with(new_path.as_slice(), definitions);
}
if node.original_location.path.is_some() {
log::warn!("Attempting to overwrite node path");
} else {
node.original_location.path = Some(new_path);
node.original_location.dependants = (0..node.implementation.output_count()).map(|_| Vec::new()).collect();
let output_count = output_count_in(&node.implementation, definitions).unwrap_or(1);
node.original_location.dependants = vec![Vec::new(); output_count];
}
}
}
/// A copy of table entry `id` for the instance at `instance_path`, with its node paths and dependant slots in place.
fn instantiate_definition(&self, id: NetworkId, instance_path: &[NodeId]) -> Option<NodeNetwork> {
let mut instance = self.definitions.get(&id)?.clone();
instance.generate_node_paths_with(instance_path, &self.definitions);
Some(instance)
}
pub fn populate_dependants(&mut self) {
let mut dep_changes = Vec::new();
for (node_id, node) in &mut self.nodes {
let len = node.original_location.dependants.len();
node.original_location.dependants.extend(vec![vec![]; (node.implementation.output_count()).max(len) - len]);
let output_count = output_count_in(&node.implementation, &self.definitions).unwrap_or(len);
node.original_location.dependants.extend(vec![vec![]; output_count.max(len) - len]);
for input in &node.inputs {
if let NodeInput::Node { node_id: dep_id, output_index, .. } = input {
dep_changes.push((*dep_id, *output_index, *node_id));
@@ -1175,6 +1428,15 @@ impl NodeNetwork {
Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id);
}
if let DocumentNodeImplementation::Definition(definition) = node.implementation {
let Some(instance) = self.instantiate_definition(definition, &path) else {
log::error!("Node {id} names definition {definition:?}, which the definitions table lacks");
self.nodes.insert(id, node);
return;
};
node.implementation = DocumentNodeImplementation::Network(instance);
}
let DocumentNodeImplementation::Network(mut inner_network) = node.implementation else {
// If the node is not a network, it is a primitive node and can be inserted into the network as is.
assert!(!self.nodes.contains_key(&id), "Trying to insert a node into the network caused an id conflict");
@@ -2179,6 +2441,130 @@ mod test {
)
}
/// Two instances of `ADD`, one of them through another entry, with a scope input inside the entry it names.
fn shared_instances_with_a_scope_input() -> NodeNetwork {
let outer = NetworkId(2);
let mut add = add_network();
add.nodes.get_mut(&NodeId(1)).unwrap().inputs.push(NodeInput::scope("injected"));
let node = |implementation, inputs| DocumentNode {
implementation,
inputs,
..Default::default()
};
let value = |number| NodeInput::value(TaggedValue::Integer(number), false);
let outer_network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(10), 0)],
nodes: [(NodeId(10), node(DocumentNodeImplementation::Definition(ADD), vec![NodeInput::import(concrete!(i64), 0), value(2)]))]
.into_iter()
.collect(),
..Default::default()
};
let injected = node(DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::IdentityNode")), vec![value(7)]);
NodeNetwork {
exports: vec![NodeInput::node(NodeId(11), 0)],
nodes: [
(NodeId(10), node(DocumentNodeImplementation::Definition(outer), vec![value(1)])),
(NodeId(11), node(DocumentNodeImplementation::Definition(ADD), vec![NodeInput::node(NodeId(10), 0), value(3)])),
(NodeId(20), injected),
]
.into_iter()
.collect(),
scope_injections: [("injected".to_string(), (NodeId(20), concrete!(i64)))].into_iter().collect(),
definitions: [(ADD, add), (outer, outer_network)].into_iter().collect(),
..Default::default()
}
}
/// A root instance of `ADD` and one inside `group`, which shadows the root's `injected` with a node of type `shadowing_type`.
fn shadowed_scope_input(shadowing_type: Type) -> NodeNetwork {
let group = NetworkId(2);
let mut add = add_network();
add.nodes.get_mut(&NodeId(1)).unwrap().inputs.push(NodeInput::scope("injected"));
let node = |implementation| DocumentNode { implementation, ..Default::default() };
let identity = || node(DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::IdentityNode")));
let group_network = NodeNetwork {
nodes: [(NodeId(10), node(DocumentNodeImplementation::Definition(ADD))), (NodeId(21), identity())].into_iter().collect(),
scope_injections: [("injected".to_string(), (NodeId(21), shadowing_type))].into_iter().collect(),
..Default::default()
};
NodeNetwork {
nodes: [
(NodeId(10), node(DocumentNodeImplementation::Definition(group))),
(NodeId(11), node(DocumentNodeImplementation::Definition(ADD))),
(NodeId(20), identity()),
]
.into_iter()
.collect(),
scope_injections: [("injected".to_string(), (NodeId(20), concrete!(i64)))].into_iter().collect(),
definitions: [(ADD, add), (group, group_network)].into_iter().collect(),
..Default::default()
}
}
fn scope_import_types(network: &NodeNetwork) -> Vec<Type> {
let mut types: Vec<Type> = network
.definitions
.values()
.filter_map(|definition| match definition.nodes.get(&NodeId(1))?.inputs.last()? {
NodeInput::Import { import_type, .. } => Some(import_type.clone()),
_ => None,
})
.collect();
types.sort_by_key(|ty| format!("{ty:?}"));
types
}
#[test]
fn the_nearest_injection_resolves_a_scope_input() {
let mut network = shadowed_scope_input(concrete!(i64));
network.resolve_scope_inputs();
assert_eq!(scope_import_types(&network), vec![concrete!(i64)], "a shadowing injection of the same type shares the entry");
assert_eq!(network.nodes[&NodeId(11)].inputs.last(), Some(&NodeInput::node(NodeId(20), 0)));
assert_eq!(network.definitions[&NetworkId(2)].nodes[&NodeId(10)].inputs.last(), Some(&NodeInput::node(NodeId(21), 0)));
}
#[test]
fn a_shadowing_injection_of_another_type_specializes_the_entry() {
let mut network = shadowed_scope_input(concrete!(f64));
network.resolve_scope_inputs();
assert_eq!(scope_import_types(&network), vec![concrete!(i64), concrete!(f64)]);
let DocumentNodeImplementation::Definition(root_instance) = network.nodes[&NodeId(11)].implementation else {
panic!()
};
let DocumentNodeImplementation::Definition(group_instance) = network.definitions[&NetworkId(2)].nodes[&NodeId(10)].implementation else {
panic!()
};
assert_ne!(root_instance, group_instance);
assert_eq!(network.definitions[&NetworkId(2)].nodes[&NodeId(10)].inputs.last(), Some(&NodeInput::node(NodeId(21), 0)));
}
#[test]
fn a_table_compiles_like_its_inlined_network() {
let table = shared_instances_with_a_scope_input();
let mut inlined = table.clone();
inlined.inline_definitions().unwrap();
// Flattening gives value nodes random IDs, which their paths carry, so only the other paths are compared
let compile = |network| {
let mut compiled = crate::graphene_compiler::Compiler {}.compile_single(network).expect("the network compiles").network;
let mut paths: Vec<_> = compiled
.nodes
.iter()
.filter(|(_, node)| node.identifier != ProtoNodeIdentifier::new("core_types::value::ClonedNode"))
.map(|(_, node)| node.original_location.path.clone())
.collect();
paths.sort();
compiled.nodes.iter_mut().for_each(|(_, node)| node.original_location = OriginalLocation::default());
(compiled, paths)
};
assert_eq!(compile(table), compile(inlined));
}
#[test]
fn definitions_inline_into_copies_of_their_network() {
let mut network = two_add_instances();
@@ -2244,13 +2630,18 @@ mod test {
(second, network_with([(NodeId(10), DocumentNodeImplementation::Definition(first))], [])),
],
);
assert_eq!(cyclic.validate_definitions(), Err(DefinitionError::Cycle(vec![first, second])));
assert_eq!(cyclic.inline_definitions(), Err(DefinitionError::Cycle(vec![first, second])));
let mut missing = network_with([(NodeId(10), DocumentNodeImplementation::Definition(first))], []);
assert_eq!(missing.validate_definitions(), Err(DefinitionError::Missing(first)));
assert_eq!(missing.inline_definitions(), Err(DefinitionError::Missing(first)));
let mut nested = network_with([(NodeId(10), DocumentNodeImplementation::Network(two_add_instances()))], []);
assert_eq!(nested.validate_definitions(), Err(DefinitionError::NestedTable));
assert_eq!(nested.inline_definitions(), Err(DefinitionError::NestedTable));
assert_eq!(two_add_instances().validate_definitions(), Ok(()));
}
#[test]
@@ -41,6 +41,7 @@ impl Compiler {
for id in node_ids {
network.flatten(id);
}
network.definitions.clear();
network.remove_all_passthrough_nodes();
// network.remove_dead_nodes(0);
let proto_networks = network.into_proto_networks();
+3 -4
View File
@@ -61,7 +61,7 @@ pub async fn open_document(path: &Path, with_names: bool) -> Result<OpenedDocume
let archive = std::fs::read(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?;
let gdd = open_gdd(&archive).await?;
let declarations = gdd.declarations(&gdd).await;
let (network, nodes, networks) = gdd.registry().to_runtime_with_full_metadata(&declarations)?;
let (network, nodes, networks) = gdd.registry().to_runtime_with_full_metadata(&declarations, gdd.blobs())?;
let names = with_names.then(|| {
let references: HashMap<_, _> = networks.into_iter().filter_map(|network| Some((network.network, network.reference?))).collect();
let display_names: HashMap<_, _> = nodes.into_iter().filter_map(|node| Some(((node.network, node.local_id), node.display_name?))).collect();
@@ -95,7 +95,6 @@ pub struct CompiledDocument {
spawner: Arc<TokioSpawner>,
}
/// Compile `document` against a fresh GPU context, resolving its resources from its `.gdd`.
pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocument, Box<dyn Error>> {
log::info!("Creating GPU context");
let mut application_io = PlatformApplicationIo::new().await;
@@ -112,7 +111,7 @@ pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocume
application_io: Some(application_io.clone()),
});
let spawner = Arc::new(TokioSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(std::time::Instant::now()));
let runtime = AsyncRuntime::new(spawner.clone());
let mut network = wrap_network_in_scope(document.network, editor_api, runtime.handle());
@@ -143,7 +142,7 @@ impl CompiledDocument {
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
messages.join("\n")
})?;
self.runtime.retain_sources(executor.sources());
self.runtime.update_sources(executor.sources());
let device = self.application_io.gpu_executor().ok_or("No GPU executor is available")?.context().device.clone();
let polling = Arc::new(AtomicBool::new(true));
@@ -3,14 +3,14 @@ use criterion::measurement::Measurement;
use graph_craft::proto::ProtoNetwork;
use graph_craft::util::{DEMO_ART, compile, load_from_name};
use graphene_std::application_io::EditorApi;
use graphene_std::runtime::{AsyncRuntime, Clock, Spawn, Task};
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope;
pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
let network = load_from_name(name);
let editor_api = std::sync::Arc::new(EditorApi::default());
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner), std::sync::Arc::new(NoClock)).handle());
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
let preprocessor = preprocessor::Preprocessor::new();
preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network);
@@ -33,10 +33,3 @@ struct DummySpawner;
impl Spawn for DummySpawner {
fn spawn(&self, _task: Task) {}
}
struct NoClock;
impl Clock for NoClock {
fn now(&self) -> std::time::Duration {
std::time::Duration::ZERO
}
}
@@ -52,6 +52,7 @@ log = { workspace = true }
base64 = { workspace = true }
polycool = { workspace = true }
futures = { workspace = true }
web-time = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
+43 -155
View File
@@ -1,16 +1,14 @@
use crate::poll::Poll;
use crate::uuid::NodeId;
use dyn_any::WasmNotSend;
pub use futures::future::AbortHandle;
use futures::future::Abortable;
use futures::future::{AbortHandle, Abortable};
use std::collections::HashMap;
use std::future::Future;
use std::hash::{Hash, Hasher};
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::sync::{Arc, Mutex, PoisonError};
use std::task::{Context, Waker};
use std::time::Duration;
pub use web_time::Instant;
#[cfg(not(target_family = "wasm"))]
pub type Task = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
@@ -21,36 +19,6 @@ pub trait Spawn {
fn spawn(&self, task: Task);
}
/// Monotonic time since an arbitrary origin.
pub trait Clock: Send + Sync {
fn now(&self) -> Duration;
}
#[cfg(not(target_family = "wasm"))]
impl Clock for std::time::Instant {
fn now(&self) -> Duration {
self.elapsed()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Scheduling {
/// How far into a frame a re-evaluation caused by finished tasks may start. `None` never defers it.
pub frame_budget: Option<Duration>,
}
impl Scheduling {
pub const UNLIMITED: Self = Self { frame_budget: None };
}
impl Default for Scheduling {
fn default() -> Self {
Self {
frame_budget: Some(Duration::from_millis(16)),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, graphene_hash::CacheHash, dyn_any::DynAny)]
pub struct SourceId(pub u64);
@@ -66,22 +34,15 @@ impl SourceId {
pub type Generations = Arc<[(SourceId, u64)]>;
pub trait Runtime {
/// Bumps the generation of `source` once `task` finishes, unless it was aborted or the source was removed first.
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle;
fn spawn(&self, source: SourceId, task: Task);
}
#[derive(Clone, dyn_any::DynAny)]
pub struct RuntimeHandle(Arc<RuntimeInner>);
impl RuntimeHandle {
pub fn clock(&self) -> &dyn Clock {
&*self.0.clock
}
}
impl Runtime for RuntimeHandle {
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle {
self.0.spawn(source, task)
fn spawn(&self, source: SourceId, task: Task) {
self.0.spawn(source, task);
}
}
@@ -104,43 +65,28 @@ impl graphene_hash::CacheHash for RuntimeHandle {
pub struct AsyncRuntime(Arc<RuntimeInner>);
impl AsyncRuntime {
pub fn new(spawner: Arc<dyn Spawn + Send + Sync>, clock: Arc<dyn Clock>) -> Self {
pub fn new(spawner: Arc<dyn Spawn + Send + Sync>) -> Self {
Self(Arc::new(RuntimeInner {
sources: Mutex::default(),
next_task: AtomicU64::new(0),
bumped: AtomicBool::new(false),
generations: Mutex::default(),
spawner,
clock,
}))
}
/// Aborts the unfinished tasks of removed sources.
pub fn retain_sources(&self, live: &[SourceId]) {
let mut sources = self.0.lock();
for (_, state) in sources.extract_if(|source, _| !live.contains(source)) {
state.tasks.values().for_each(AbortHandle::abort);
}
pub fn update_sources(&self, live: &[SourceId]) {
let mut generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner);
generations.retain(|source, _| live.contains(source));
for source in live {
sources.entry(*source).or_default();
generations.entry(*source).or_insert(0);
}
}
pub fn snapshot(&self) -> Generations {
let sources = self.0.lock();
let mut snapshot: Vec<_> = sources.iter().map(|(source, state)| (*source, state.generation)).collect();
let generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner);
let mut snapshot: Vec<_> = generations.iter().map(|(source, generation)| (*source, *generation)).collect();
snapshot.sort_unstable();
snapshot.into()
}
/// Whether any generation was bumped since the last call.
pub fn take_bumped(&self) -> bool {
self.0.bumped.swap(false, Ordering::AcqRel)
}
pub fn clock(&self) -> &dyn Clock {
&*self.0.clock
}
#[must_use]
pub fn handle(&self) -> RuntimeHandle {
RuntimeHandle(Arc::clone(&self.0))
@@ -148,50 +94,25 @@ impl AsyncRuntime {
}
impl Runtime for AsyncRuntime {
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle {
self.0.spawn(source, task)
fn spawn(&self, source: SourceId, task: Task) {
self.0.spawn(source, task);
}
}
/// A live source's generation and its unfinished tasks.
#[derive(Default)]
struct SourceState {
generation: u64,
tasks: HashMap<u64, AbortHandle>,
}
struct RuntimeInner {
sources: Mutex<HashMap<SourceId, SourceState>>,
next_task: AtomicU64,
bumped: AtomicBool,
generations: Mutex<HashMap<SourceId, u64>>,
spawner: Arc<dyn Spawn + Send + Sync>,
clock: Arc<dyn Clock>,
}
impl RuntimeInner {
fn lock(&self) -> MutexGuard<'_, HashMap<SourceId, SourceState>> {
self.sources.lock().unwrap_or_else(PoisonError::into_inner)
}
fn spawn(self: &Arc<Self>, source: SourceId, task: Task) -> AbortHandle {
let (handle, registration) = AbortHandle::new_pair();
let id = self.next_task.fetch_add(1, Ordering::Relaxed);
if let Some(state) = self.lock().get_mut(&source) {
state.tasks.insert(id, handle.clone());
}
fn spawn(self: &Arc<Self>, source: SourceId, task: Task) {
let inner = Arc::clone(self);
self.spawner.spawn(Box::pin(async move {
let finished = Abortable::new(task, registration).await.is_ok();
if let Some(state) = inner.lock().get_mut(&source)
&& state.tasks.remove(&id).is_some()
&& finished
{
state.generation += 1;
inner.bumped.store(true, Ordering::Release);
task.await;
if let Some(generation) = inner.generations.lock().unwrap_or_else(PoisonError::into_inner).get_mut(&source) {
*generation += 1;
}
}));
handle
}
}
@@ -247,12 +168,14 @@ impl<T: Clone + WasmNotSend + 'static> Slots<T> {
return state;
}
let (handle, registration) = AbortHandle::new_pair();
let slots = Arc::downgrade(&self.0);
let handle = runtime.spawn(
runtime.spawn(
source,
Box::pin(async move {
let state = future.await;
if let Some(slots) = slots.upgrade() {
if let Ok(state) = Abortable::new(future, registration).await
&& let Some(slots) = slots.upgrade()
{
slots.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state));
}
}),
@@ -271,14 +194,7 @@ impl<T: Clone + WasmNotSend + 'static> Slots<T> {
#[cfg(test)]
mod tests {
use super::*;
struct NoClock;
impl Clock for NoClock {
fn now(&self) -> Duration {
Duration::ZERO
}
}
use std::sync::atomic::{AtomicBool, Ordering};
fn poll_once(task: &mut Task) -> bool {
task.as_mut().poll(&mut Context::from_waker(Waker::noop())).is_ready()
@@ -331,8 +247,8 @@ mod tests {
#[test]
fn a_completion_bumps_its_generation() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
let runtime = AsyncRuntime::new(spawner.clone());
runtime.update_sources(&[SOURCE]);
runtime.handle().spawn(SOURCE, Box::pin(YieldOnce(false)));
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]);
@@ -342,25 +258,25 @@ mod tests {
}
#[test]
fn retaining_sources_keeps_live_generations() {
fn updating_sources_keeps_live_generations() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
let runtime = AsyncRuntime::new(spawner.clone());
runtime.update_sources(&[SOURCE]);
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
spawner.drain();
runtime.retain_sources(&[SOURCE, SourceId(9)]);
runtime.update_sources(&[SOURCE, SourceId(9)]);
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1), (SourceId(9), 0)]);
runtime.retain_sources(&[SourceId(9)]);
runtime.update_sources(&[SourceId(9)]);
assert_eq!(&*runtime.snapshot(), &[(SourceId(9), 0)]);
}
#[test]
fn an_inline_completion_and_a_dropped_source_bump_nothing() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
let runtime = AsyncRuntime::new(spawner.clone());
runtime.update_sources(&[SOURCE]);
let slots = Slots::default();
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1));
@@ -368,7 +284,7 @@ mod tests {
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]);
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
runtime.retain_sources(&[]);
runtime.update_sources(&[]);
assert_eq!(spawner.drain(), 1);
assert!(runtime.snapshot().is_empty());
}
@@ -376,8 +292,8 @@ mod tests {
#[test]
fn a_slot_serves_the_placeholder_until_the_response_lands() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
let runtime = AsyncRuntime::new(spawner.clone());
runtime.update_sources(&[SOURCE]);
let slots = Slots::default();
let fetch = || async {
YieldOnce(false).await;
@@ -393,8 +309,8 @@ mod tests {
#[test]
fn a_blocking_spawner_lands_the_slot_in_the_same_resolve() {
let runtime = AsyncRuntime::new(Arc::new(BlockingSpawner), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
let runtime = AsyncRuntime::new(Arc::new(BlockingSpawner));
runtime.update_sources(&[SOURCE]);
let slots = Slots::default();
let fetch = || async {
YieldOnce(false).await;
@@ -408,7 +324,7 @@ mod tests {
#[test]
fn a_clone_keeps_the_task_running() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
let runtime = AsyncRuntime::new(spawner.clone());
let slots = Slots::default();
let fetch = || async {
YieldOnce(false).await;
@@ -425,7 +341,7 @@ mod tests {
#[test]
fn dropping_the_last_clone_aborts_the_task() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
let runtime = AsyncRuntime::new(spawner.clone());
let slots = Slots::default();
let finished = Arc::new(AtomicBool::new(false));
let fetch = || {
@@ -442,32 +358,4 @@ mod tests {
assert_eq!(spawner.drain(), 1);
assert!(!finished.load(Ordering::Relaxed));
}
#[test]
fn finished_tasks_bump_once() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
assert_eq!(spawner.drain(), 2);
assert!(runtime.take_bumped());
assert!(!runtime.take_bumped());
}
#[test]
fn aborted_tasks_bump_nothing() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE, SourceId(9)]);
runtime.spawn(SOURCE, Box::pin(std::future::pending())).abort();
let removed = runtime.spawn(SourceId(9), Box::pin(std::future::pending()));
runtime.retain_sources(&[SOURCE]);
assert!(removed.is_aborted());
assert_eq!(spawner.drain(), 2);
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]);
assert!(!runtime.take_bumped());
}
}
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more