mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8b38e7100c | ||
|
|
54fff8e129 | ||
|
|
92c5a6a7d0 | ||
|
|
8206b4cc88 | ||
|
|
b05af55d50 | ||
|
|
39b8d23a34 |
No files matched your search
Generated
+69
-1
@@ -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"
|
||||
@@ -2090,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"
|
||||
@@ -2925,6 +2949,7 @@ dependencies = [
|
||||
"ash",
|
||||
"bytemuck",
|
||||
"cef",
|
||||
"dirs",
|
||||
"graphite-desktop-embedded-resources",
|
||||
"ipc-channel",
|
||||
"libc",
|
||||
@@ -2950,7 +2975,6 @@ name = "graphite-desktop-wrapper"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs",
|
||||
"graph-craft",
|
||||
"graphite-editor",
|
||||
"graphite-wasm-wrapper",
|
||||
@@ -4202,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"
|
||||
@@ -4390,6 +4423,7 @@ dependencies = [
|
||||
"blake3",
|
||||
"ctor",
|
||||
"document-graph-storage",
|
||||
"graphene-resource",
|
||||
"migration-macros",
|
||||
"postcard",
|
||||
"serde",
|
||||
@@ -7742,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"
|
||||
@@ -9871,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"
|
||||
|
||||
@@ -45,6 +45,7 @@ members = [
|
||||
"tools/node-docs",
|
||||
"tools/regression",
|
||||
"tools/web-editor-driver",
|
||||
"tools/compression_test",
|
||||
]
|
||||
default-members = [
|
||||
"editor",
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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(¤t) {
|
||||
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(¤t)).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(&[], ©_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());
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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()))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -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(), ®istry);
|
||||
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(())
|
||||
}
|
||||
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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,6 +1,7 @@
|
||||
pub use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
pub mod attributes;
|
||||
pub mod blob;
|
||||
pub mod crdt;
|
||||
pub mod delta;
|
||||
pub mod document;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
@@ -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 ®istry.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,
|
||||
|
||||
@@ -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,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 {
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 }
|
||||
@@ -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(®istry)?;
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
@@ -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)?;
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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(®istered_migrations(), history.clone(), &table, Some(&compiler::AnswerHost::default()), None).unwrap();
|
||||
let migrated = migrate_history(
|
||||
®istered_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() {
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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() },
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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));
|
||||
|
||||
|
||||
@@ -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}");
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -2059,7 +2059,8 @@ pub fn combine_paths(_: impl Ctx, content: List<Graphic>) -> Item<Vector> {
|
||||
let node_id = layer_path.iter_element_values().next_back().map(|node_id| node_id.0).unwrap_or_default();
|
||||
|
||||
let mut hasher = DefaultHasher::new();
|
||||
(index, node_id).hash(&mut hasher);
|
||||
// Hash as u32 to avoid platform differences
|
||||
(index as u32, node_id).hash(&mut hasher);
|
||||
let collision_hash_seed = hasher.finish();
|
||||
|
||||
let source_transform = flattened.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "compression_test"
|
||||
rust-version.workspace = true
|
||||
edition.workspace = true
|
||||
authors.workspace = true
|
||||
homepage.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
document-format = { workspace = true, features = ["migrations"] }
|
||||
document-container.workspace = true
|
||||
document-graph-storage.workspace = true
|
||||
migration-formats.workspace = true
|
||||
postcard.workspace = true
|
||||
lz4_flex = { version = "0.14.0", features = ["alloc"] }
|
||||
futures.workspace = true
|
||||
blake3.workspace = true
|
||||
fastcdc = "3"
|
||||
flate2 = { version = "1.1", default-features = false, features = ["zlib-rs"] }
|
||||
zstd = "0.13"
|
||||
zstd-safe = "7"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,141 @@
|
||||
//! Compares a document's stored size with node input values inline against the blob store, uncompressed and packed as zip and xz.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use document_container::archive::{Archive, ArchiveWriter, Xz, Zip};
|
||||
use document_container::{AnyContainer, AsyncContainer, backends::memory::MemoryBackend};
|
||||
use document_format::{Gdd, GddV1Layout};
|
||||
|
||||
// Format steps register when linked
|
||||
use migration_formats as _;
|
||||
|
||||
/// Every file of a working copy, with its bytes.
|
||||
async fn files(working: &AnyContainer) -> Vec<(String, Vec<u8>)> {
|
||||
let mut paths = working.list("").await.unwrap_or_default();
|
||||
for directory in working.list_dirs("").await.unwrap_or_default() {
|
||||
paths.extend(working.list(&directory).await.unwrap_or_default());
|
||||
}
|
||||
paths.sort();
|
||||
|
||||
let mut files = Vec::new();
|
||||
for path in paths {
|
||||
let bytes = working.read(&path).await.unwrap().as_slice().to_vec();
|
||||
files.push((path, bytes));
|
||||
}
|
||||
files
|
||||
}
|
||||
|
||||
fn pack<A: Archive>(files: &[(String, Vec<u8>)]) -> usize
|
||||
where
|
||||
A::Writer<std::io::Cursor<Vec<u8>>>: ArchiveWriter<Sink = std::io::Cursor<Vec<u8>>>,
|
||||
{
|
||||
let mut writer = A::writer(std::io::Cursor::new(Vec::new())).unwrap();
|
||||
for (path, bytes) in files {
|
||||
writer.write_entry(path, bytes).unwrap();
|
||||
}
|
||||
writer.finish_into().unwrap().into_inner().len()
|
||||
}
|
||||
|
||||
fn report(label: &str, files: &[(String, Vec<u8>)]) -> [usize; 3] {
|
||||
let sizes = [files.iter().map(|(_, bytes)| bytes.len()).sum(), pack::<Zip>(files), pack::<Xz>(files)];
|
||||
println!("{label:<34}{:>12}{:>12}{:>12}", sizes[0], sizes[1], sizes[2]);
|
||||
sizes
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let document_path = std::env::args().nth(1).unwrap_or_else(|| "Brush Big.gdd".to_string());
|
||||
let archive = std::fs::read(Path::new(&document_path)).unwrap();
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut inline = AnyContainer::Memory(MemoryBackend::new());
|
||||
document_container::archive::open_auto(&archive, &mut inline).unwrap();
|
||||
let inline_files = files(&inline).await;
|
||||
|
||||
let gdd = Gdd::open_from_archive(archive.as_ref(), AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.unwrap();
|
||||
let values: Vec<usize> = gdd.blobs().values().map(Vec::len).collect();
|
||||
println!(
|
||||
"blob values: {}, mean {} bytes, max {} bytes",
|
||||
values.len(),
|
||||
values.iter().sum::<usize>() / values.len().max(1),
|
||||
values.iter().max().unwrap_or(&0)
|
||||
);
|
||||
let (working, _) = gdd.into_storage();
|
||||
let blob_files = files(&working).await;
|
||||
|
||||
let without_legacy = |files: &[(String, Vec<u8>)]| files.iter().filter(|(path, _)| !path.starts_with("legacy")).cloned().collect::<Vec<_>>();
|
||||
|
||||
println!("{:<34}{:>12}{:>12}{:>12}", "bytes", "uncompressed", "zip", "xz");
|
||||
let inline_sizes = report("values inline", &inline_files);
|
||||
let blob_sizes = report("blob store", &blob_files);
|
||||
let inline_core = report("values inline, no legacy.graphite", &without_legacy(&inline_files));
|
||||
let blob_core = report("blob store, no legacy.graphite", &without_legacy(&blob_files));
|
||||
|
||||
archive_variants(&blob_files);
|
||||
|
||||
for (label, before, after) in [("ratio", inline_sizes, blob_sizes), ("ratio, no legacy.graphite", inline_core, blob_core)] {
|
||||
let ratio = |i: usize| before[i] as f64 / after[i] as f64;
|
||||
println!("{label:<34}{:>11.2}x{:>11.2}x{:>11.2}x", ratio(0), ratio(1), ratio(2));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A blob record's kind byte and its base hash bytes if it has one.
|
||||
fn split_record(record: &[u8]) -> (u8, &[u8]) {
|
||||
let header = if record[0] == 1 { 33 } else { 1 };
|
||||
(record[0], &record[1..header])
|
||||
}
|
||||
|
||||
/// Records ordered so each follows its base, chain by chain, which keeps related bytes close for xz's window.
|
||||
fn chain_order(blobs: &[(String, Vec<u8>)]) -> Vec<(String, Vec<u8>)> {
|
||||
use std::collections::HashMap;
|
||||
|
||||
let name = |path: &str| path.rsplit('/').next().unwrap().to_string();
|
||||
let mut children: HashMap<String, Vec<usize>> = HashMap::new();
|
||||
let mut roots = Vec::new();
|
||||
for (index, (_, record)) in blobs.iter().enumerate() {
|
||||
let (kind, base) = split_record(record);
|
||||
match kind {
|
||||
1 => children.entry(base.iter().map(|byte| format!("{byte:02x}")).collect()).or_default().push(index),
|
||||
_ => roots.push(index),
|
||||
}
|
||||
}
|
||||
|
||||
let mut ordered = Vec::new();
|
||||
let mut pending: Vec<usize> = roots.into_iter().rev().collect();
|
||||
while let Some(index) = pending.pop() {
|
||||
ordered.push(blobs[index].clone());
|
||||
pending.extend(children.get(&name(&blobs[index].0)).into_iter().flatten().rev());
|
||||
}
|
||||
ordered
|
||||
}
|
||||
|
||||
pub fn archive_variants(files: &[(String, Vec<u8>)]) {
|
||||
let (blobs, rest): (Vec<_>, Vec<_>) = files.iter().filter(|(path, _)| !path.starts_with("legacy")).cloned().partition(|(path, _)| path.starts_with("blobs/"));
|
||||
let packed = |records: &[(String, Vec<u8>)]| {
|
||||
let mut pack = Vec::new();
|
||||
for (path, record) in records {
|
||||
pack.extend_from_slice(path.as_bytes());
|
||||
pack.extend_from_slice(&(record.len() as u32).to_le_bytes());
|
||||
pack.extend_from_slice(record);
|
||||
}
|
||||
("blobs.pack".to_string(), pack)
|
||||
};
|
||||
|
||||
let deltas: Vec<usize> = blobs.iter().filter(|(_, record)| record[0] == 1).map(|(_, record)| record.len()).collect();
|
||||
let mut sorted = deltas.clone();
|
||||
sorted.sort_unstable();
|
||||
println!(
|
||||
"\ndelta records: {}, mean {} bytes, median {} bytes, max {} bytes",
|
||||
deltas.len(),
|
||||
deltas.iter().sum::<usize>() / deltas.len().max(1),
|
||||
sorted.get(sorted.len() / 2).unwrap_or(&0),
|
||||
sorted.last().unwrap_or(&0)
|
||||
);
|
||||
let ordered = chain_order(&blobs);
|
||||
let with = |blob_files: Vec<(String, Vec<u8>)>| rest.iter().cloned().chain(blob_files).collect::<Vec<_>>();
|
||||
|
||||
println!("\nno legacy.graphite, by blob layout");
|
||||
report("files (current)", &with(blobs.clone()));
|
||||
report("one pack, hash order", &with(vec![packed(&blobs)]));
|
||||
report("one pack, chain order", &with(vec![packed(&ordered)]));
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! Content-defined chunking of the resource model's large values, as an alternative to per-input delta chains.
|
||||
//! A value becomes a list of chunk hashes and every distinct chunk is stored once, deflated on its own.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::time::Instant;
|
||||
|
||||
use fastcdc::v2020::FastCDC;
|
||||
|
||||
use crate::models::{Chains, deflate};
|
||||
|
||||
const AVERAGE_SIZES: [u32; 5] = [1024, 2048, 4096, 8192, 16_384];
|
||||
const HASH_LENGTH: usize = 32;
|
||||
|
||||
#[derive(Default)]
|
||||
struct ChunkStore {
|
||||
known: HashSet<[u8; HASH_LENGTH]>,
|
||||
data_count: usize,
|
||||
data_raw: usize,
|
||||
data_deflated: usize,
|
||||
/// Hash lists are random bytes, so they are counted raw.
|
||||
list_raw: usize,
|
||||
}
|
||||
|
||||
impl ChunkStore {
|
||||
fn insert(&mut self, bytes: &[u8], is_list: bool) -> [u8; HASH_LENGTH] {
|
||||
let hash = *blake3::hash(bytes).as_bytes();
|
||||
if !self.known.insert(hash) {
|
||||
return hash;
|
||||
}
|
||||
|
||||
if is_list {
|
||||
self.list_raw += bytes.len();
|
||||
} else {
|
||||
self.data_count += 1;
|
||||
self.data_raw += bytes.len();
|
||||
self.data_deflated += deflate(bytes).len();
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
/// Store `bytes` as chunks and return the hash of the list naming them. With `recursive`, a list longer than one
|
||||
/// average chunk is itself chunked, so versions sharing most of their chunks also share most of their list.
|
||||
fn store_value(&mut self, bytes: &[u8], average: u32, recursive: bool, is_list: bool) -> [u8; HASH_LENGTH] {
|
||||
let mut list = Vec::new();
|
||||
for chunk in FastCDC::new(bytes, average / 4, average, average * 4) {
|
||||
let chunk_bytes = &bytes[chunk.offset..chunk.offset + chunk.length];
|
||||
list.extend(self.insert(chunk_bytes, is_list));
|
||||
}
|
||||
|
||||
if recursive && list.len() > average as usize {
|
||||
return self.store_value(&list, average, true, true);
|
||||
}
|
||||
self.insert(&list, true)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn compare(chains: &Chains) {
|
||||
let versions: usize = chains.values().map(Vec::len).sum();
|
||||
let raw: usize = chains.values().flatten().map(Vec::len).sum();
|
||||
|
||||
println!();
|
||||
println!("content-defined chunking over the same {versions} versions ({raw} bytes raw), threshold 256:");
|
||||
println!(
|
||||
" {:>7} {:>7} {:>10} {:>10} {:>10} {:>10} {:>10} {:>10} {:>9}",
|
||||
"average", "chunks", "data-raw", "data-defl", "list-flat", "list-tree", "total-flat", "total-tree", "ms"
|
||||
);
|
||||
|
||||
for average in AVERAGE_SIZES {
|
||||
let start = Instant::now();
|
||||
let mut flat = ChunkStore::default();
|
||||
for blob in chains.values().flatten() {
|
||||
flat.store_value(blob, average, false, false);
|
||||
}
|
||||
let elapsed = start.elapsed();
|
||||
|
||||
let mut tree = ChunkStore::default();
|
||||
for blob in chains.values().flatten() {
|
||||
tree.store_value(blob, average, true, false);
|
||||
}
|
||||
|
||||
println!(
|
||||
" {average:>7} {:>7} {:>10} {:>10} {:>10} {:>10} {:>10} {:>10} {:>9.1}",
|
||||
flat.data_count,
|
||||
flat.data_raw,
|
||||
flat.data_deflated,
|
||||
flat.list_raw,
|
||||
tree.list_raw,
|
||||
flat.data_deflated + flat.list_raw,
|
||||
tree.data_deflated + tree.list_raw,
|
||||
elapsed.as_secs_f64() * 1000.
|
||||
);
|
||||
}
|
||||
println!(" total = deflated chunk data + hash lists, comparable to the store columns above.");
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
use std::collections::HashMap;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use document_container::{AnyContainer, backends::memory::MemoryBackend};
|
||||
use document_format::{Codec, Gdd, GddV1Layout};
|
||||
use document_graph_storage::{Delta, NodeInput, RegistryDelta};
|
||||
use lz4_flex::frame::{BlockMode, FrameEncoder, FrameInfo};
|
||||
|
||||
mod cdc;
|
||||
mod models;
|
||||
|
||||
fn main() {
|
||||
let document_path = std::env::args().nth(1).unwrap_or_else(|| "value-diff-test.gdd".to_string());
|
||||
let document_path = Path::new(&document_path);
|
||||
let archive = std::fs::read(document_path).unwrap();
|
||||
let memory = MemoryBackend::new();
|
||||
let container = AnyContainer::Memory(memory);
|
||||
let gdd = futures::executor::block_on(Gdd::open_from_archive(archive.as_ref(), container, GddV1Layout)).unwrap();
|
||||
|
||||
let deltas: Vec<&Delta> = gdd.session().history().collect();
|
||||
|
||||
// What `history.frames` holds today: every delta as a length-prefixed postcard frame.
|
||||
let mut current = Vec::new();
|
||||
for delta in &deltas {
|
||||
Codec::PostcardFrames.append(&mut current, delta).unwrap();
|
||||
}
|
||||
let frames: Vec<Vec<u8>> = deltas.iter().map(|delta| postcard::to_allocvec(delta).unwrap()).collect();
|
||||
let frames_total: usize = frames.iter().map(Vec::len).sum();
|
||||
|
||||
println!("history: {} deltas", deltas.len());
|
||||
println!("archive (.gdd, xz): {:>9} bytes", archive.len());
|
||||
println!("history.frames as stored today: {:>9} bytes", current.len());
|
||||
println!();
|
||||
|
||||
let report = |label: &str, bytes: usize| {
|
||||
println!("{label:<42}{bytes:>9} bytes {:>6.2}x smaller than today", current.len() as f64 / bytes as f64);
|
||||
};
|
||||
|
||||
report("each delta lz4 independently", independent(&frames));
|
||||
report("one linked lz4 chain over the whole history", linked_chain(&frames).iter().sum());
|
||||
report("linked lz4 chain per node input", per_input_chains(&deltas, &frames));
|
||||
report("whole history as one lz4 frame (reference)", lz4_flex::frame::FrameEncoder::new(Vec::new()).write_and_finish(¤t));
|
||||
report("zstd chain level 3 (16 MiB window)", zstd_chain(&frames, 3).iter().sum());
|
||||
report("zstd chain level 9 (16 MiB window)", zstd_chain(&frames, 9).iter().sum());
|
||||
report("zstd chain level 19 (16 MiB window)", zstd_chain(&frames, 19).iter().sum());
|
||||
|
||||
// Only the new value: what a store that doesn't persist `reverse` would need.
|
||||
let kinds: Vec<Vec<u8>> = deltas.iter().map(|delta| postcard::to_allocvec(&delta.kind).unwrap()).collect();
|
||||
let kinds_total: usize = kinds.iter().map(Vec::len).sum();
|
||||
println!();
|
||||
println!("`kind` only (dropping `reverse`): {kinds_total:>9} bytes ({frames_total} with reverse)");
|
||||
report("linked lz4 chain over `kind` only", linked_chain(&kinds).iter().sum());
|
||||
|
||||
// Detail for the most-edited large input.
|
||||
let key = |delta: &Delta| match &delta.kind {
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id,
|
||||
index,
|
||||
new_input: NodeInput::Value { .. },
|
||||
} => Some((*id, *index)),
|
||||
_ => None,
|
||||
};
|
||||
let mut per_key: HashMap<_, Vec<usize>> = HashMap::new();
|
||||
for (i, delta) in deltas.iter().enumerate() {
|
||||
if let Some(k) = key(delta) {
|
||||
per_key.entry(k).or_default().push(i);
|
||||
}
|
||||
}
|
||||
let (k, indices) = per_key.iter().max_by_key(|(_, v)| v.iter().map(|&i| frames[i].len()).sum::<usize>()).unwrap();
|
||||
let payloads: Vec<Vec<u8>> = indices.iter().map(|&i| frames[i].clone()).collect();
|
||||
let ind = payloads.iter().map(|p| lz4_flex::block::compress(p).len()).collect::<Vec<_>>();
|
||||
let lnk = linked_chain(&payloads);
|
||||
let zst = zstd_chain(&payloads, 3);
|
||||
let pred = predecessor_only(&payloads, 3);
|
||||
println!();
|
||||
println!("largest input {k:?}: {} versions", payloads.len());
|
||||
println!(
|
||||
" {:>4} {:>8} {:>7} {:>10} {:>10} {:>11} {:>9} {:>10}",
|
||||
"#", "raw", "growth", "lz4-indep", "lz4-suffix", "zstd-suffix", "zstd/new", "pred-only"
|
||||
);
|
||||
let mut prev_raw = 0;
|
||||
for (i, ((((p, ind), lnk), zst), pred)) in payloads.iter().zip(&ind).zip(&lnk).zip(&zst).zip(&pred).enumerate().take(40) {
|
||||
let growth = p.len() - prev_raw;
|
||||
println!(
|
||||
" {i:>4} {:>8} {growth:>7} {ind:>10} {lnk:>10} {zst:>11} {:>8.1}% {pred:>10}",
|
||||
p.len(),
|
||||
100.0 * *zst as f64 / growth as f64
|
||||
);
|
||||
prev_raw = p.len();
|
||||
}
|
||||
let growth_total = payloads.last().unwrap().len();
|
||||
let zst_total: usize = zst.iter().sum();
|
||||
let pred_total: usize = pred.iter().sum();
|
||||
println!(
|
||||
" new bytes total: {growth_total} lz4 suffix total: {} zstd suffix total: {zst_total} predecessor-only total: {pred_total}",
|
||||
lnk.iter().sum::<usize>()
|
||||
);
|
||||
println!(
|
||||
" zstd suffix / new bytes: {:.1}% (compression overhead relative to storing only the raw new bytes)",
|
||||
100.0 * zst_total as f64 / growth_total as f64
|
||||
);
|
||||
println!(" predecessor-only / new bytes: {:.1}%", 100.0 * pred_total as f64 / growth_total as f64);
|
||||
|
||||
// Predecessor-only over the whole history: group by input, each version sees only the previous
|
||||
// version of the same input; non-value deltas are compressed standalone.
|
||||
let mut by_input: HashMap<_, Vec<Vec<u8>>> = HashMap::new();
|
||||
let mut standalone = Vec::new();
|
||||
for (delta, frame) in deltas.iter().zip(&frames) {
|
||||
match key(delta) {
|
||||
Some(k) => by_input.entry(k).or_default().push(frame.clone()),
|
||||
None => standalone.push(frame.clone()),
|
||||
}
|
||||
}
|
||||
let pred_history: usize =
|
||||
by_input.values().map(|p| predecessor_only(p, 3).iter().sum::<usize>()).sum::<usize>() + standalone.iter().map(|f| predecessor_only(std::slice::from_ref(f), 3)[0]).sum::<usize>();
|
||||
report("predecessor-only zstd (per input, level 3)", pred_history);
|
||||
|
||||
// Same estimate over the whole history: "new bytes" = growth vs. the previous version of the same
|
||||
// input, or the full frame for the first version / non-value deltas.
|
||||
let mut last_len: HashMap<_, usize> = HashMap::new();
|
||||
let mut new_bytes_total = 0;
|
||||
for (delta, frame) in deltas.iter().zip(&frames) {
|
||||
new_bytes_total += match key(delta) {
|
||||
Some(k) => {
|
||||
let prev = last_len.insert(k, frame.len()).unwrap_or(0);
|
||||
frame.len().saturating_sub(prev)
|
||||
}
|
||||
None => frame.len(),
|
||||
};
|
||||
}
|
||||
let zstd_total: usize = zstd_chain(&frames, 3).iter().sum();
|
||||
println!();
|
||||
println!(
|
||||
"whole history: new bytes {new_bytes_total} zstd chain {zstd_total} ratio {:.1}%",
|
||||
100.0 * zstd_total as f64 / new_bytes_total as f64
|
||||
);
|
||||
|
||||
// Micro-bench: time to get at the *last* payload. For the streaming chain that means decoding the
|
||||
// entire stream (block n references everything before it); for predecessor-only it means walking the
|
||||
// per-input chain from version 0.
|
||||
let iterations = 100;
|
||||
println!();
|
||||
println!("decode-to-last-payload, {iterations} iterations (debug build):");
|
||||
|
||||
let (_, chain_largest) = zstd_chain_with_output(&payloads, 3);
|
||||
let expected_last = payloads.last().unwrap().len();
|
||||
bench(&format!("zstd chain, largest input ({} versions, {} B)", payloads.len(), chain_largest.len()), iterations, || {
|
||||
let decoded = zstd::decode_all(chain_largest.as_slice()).unwrap();
|
||||
assert_eq!(decoded.len(), payloads.iter().map(Vec::len).sum::<usize>());
|
||||
expected_last
|
||||
});
|
||||
|
||||
let pred_frames = predecessor_only_frames(&payloads, 3);
|
||||
let pred_bytes: usize = pred_frames.iter().map(Vec::len).sum();
|
||||
bench(&format!("predecessor-only, largest input ({} frames, {} B)", pred_frames.len(), pred_bytes), iterations, || {
|
||||
let last = decode_predecessor_chain(&pred_frames);
|
||||
assert_eq!(&last, payloads.last().unwrap());
|
||||
last.len()
|
||||
});
|
||||
|
||||
let (_, chain_all) = zstd_chain_with_output(&frames, 3);
|
||||
bench(&format!("zstd chain, whole history ({} deltas, {} B)", frames.len(), chain_all.len()), iterations, || {
|
||||
let decoded = zstd::decode_all(chain_all.as_slice()).unwrap();
|
||||
assert_eq!(decoded.len(), frames_total);
|
||||
frames.last().unwrap().len()
|
||||
});
|
||||
|
||||
let lz4_all = lz4_flex::frame::FrameEncoder::new(Vec::new()).write_and_finish_bytes(¤t);
|
||||
bench(&format!("lz4 whole history, for reference ({} B)", lz4_all.len()), iterations, || {
|
||||
let mut out = Vec::with_capacity(current.len());
|
||||
std::io::copy(&mut lz4_flex::frame::FrameDecoder::new(lz4_all.as_slice()), &mut out).unwrap();
|
||||
out.len()
|
||||
});
|
||||
|
||||
let hot_log = gdd.session().hot_log();
|
||||
let mut hot_kinds: HashMap<String, (usize, usize)> = HashMap::new();
|
||||
for hot_op in hot_log {
|
||||
let name = format!("{:?}", hot_op.op).split([' ', '(', '{']).next().unwrap_or_default().to_string();
|
||||
let entry = hot_kinds.entry(name).or_default();
|
||||
entry.0 += 1;
|
||||
entry.1 += postcard::to_allocvec(hot_op).unwrap().len();
|
||||
}
|
||||
println!();
|
||||
println!("hot log: {} ops {hot_kinds:?}", hot_log.len());
|
||||
println!("hot sequence range: {:?} .. {:?}", hot_log.first().map(|op| op.sequence), hot_log.last().map(|op| op.sequence));
|
||||
|
||||
models::compare(&gdd, &deltas);
|
||||
}
|
||||
|
||||
trait WriteAndFinish {
|
||||
fn write_and_finish_bytes(self, bytes: &[u8]) -> Vec<u8>;
|
||||
fn write_and_finish(self, bytes: &[u8]) -> usize;
|
||||
}
|
||||
impl WriteAndFinish for FrameEncoder<Vec<u8>> {
|
||||
fn write_and_finish_bytes(mut self, bytes: &[u8]) -> Vec<u8> {
|
||||
self.write_all(bytes).unwrap();
|
||||
self.finish().unwrap()
|
||||
}
|
||||
fn write_and_finish(self, bytes: &[u8]) -> usize {
|
||||
self.write_and_finish_bytes(bytes).len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Baseline: every payload compressed on its own, no shared context.
|
||||
fn independent(payloads: &[Vec<u8>]) -> usize {
|
||||
payloads.iter().map(|p| lz4_flex::block::compress(p).len()).sum()
|
||||
}
|
||||
|
||||
/// Streaming approach: one linked frame, `flush()` after each payload.
|
||||
/// The bytes emitted between two flushes are the suffix that would be stored for that block.
|
||||
fn linked_chain(payloads: &[Vec<u8>]) -> Vec<usize> {
|
||||
let mut frame_info = FrameInfo::new();
|
||||
frame_info.block_mode = BlockMode::Linked;
|
||||
let mut encoder = FrameEncoder::with_frame_info(frame_info, Vec::new());
|
||||
|
||||
let mut sizes = Vec::with_capacity(payloads.len());
|
||||
let mut previous = 0;
|
||||
for p in payloads {
|
||||
encoder.write_all(p).unwrap();
|
||||
encoder.flush().unwrap();
|
||||
let len = encoder.get_ref().len();
|
||||
sizes.push(len - previous);
|
||||
previous = len;
|
||||
}
|
||||
// The end mark is stored once for the whole chain, not attributed to any block.
|
||||
encoder.finish().unwrap();
|
||||
sizes
|
||||
}
|
||||
|
||||
/// Same as [`linked_chain`] but with zstd streaming and a window large enough to hold many
|
||||
/// previous versions (`window_log` 24 = 16 MiB). `flush()` emits a zstd block boundary without
|
||||
/// resetting the window, so the bytes between flushes are the suffix for that payload.
|
||||
fn zstd_chain(payloads: &[Vec<u8>], level: i32) -> Vec<usize> {
|
||||
zstd_chain_with_output(payloads, level).0
|
||||
}
|
||||
|
||||
fn zstd_chain_with_output(payloads: &[Vec<u8>], level: i32) -> (Vec<usize>, Vec<u8>) {
|
||||
let mut encoder = zstd::Encoder::new(Vec::new(), level).unwrap();
|
||||
encoder.window_log(24).unwrap();
|
||||
// Long-distance matching finds the "previous payload as prefix" match even far back.
|
||||
encoder.long_distance_matching(true).unwrap();
|
||||
|
||||
let mut sizes = Vec::with_capacity(payloads.len());
|
||||
let mut previous = 0;
|
||||
for p in payloads {
|
||||
encoder.write_all(p).unwrap();
|
||||
encoder.flush().unwrap();
|
||||
let len = encoder.get_ref().len();
|
||||
sizes.push(len - previous);
|
||||
previous = len;
|
||||
}
|
||||
let out = encoder.finish().unwrap();
|
||||
(sizes, out)
|
||||
}
|
||||
|
||||
/// Predecessor-only, but also returning the compressed frames so they can be decoded back.
|
||||
fn predecessor_only_frames(payloads: &[Vec<u8>], level: i32) -> Vec<Vec<u8>> {
|
||||
use zstd_safe::{CCtx, CParameter};
|
||||
let mut frames = Vec::with_capacity(payloads.len());
|
||||
let mut previous: &[u8] = &[];
|
||||
for p in payloads {
|
||||
let mut cctx = CCtx::create();
|
||||
cctx.set_parameter(CParameter::CompressionLevel(level)).unwrap();
|
||||
cctx.set_parameter(CParameter::WindowLog(24)).unwrap();
|
||||
cctx.set_parameter(CParameter::EnableLongDistanceMatching(true)).unwrap();
|
||||
cctx.ref_prefix(previous).unwrap();
|
||||
let mut out = Vec::with_capacity(zstd_safe::compress_bound(p.len()));
|
||||
cctx.compress2(&mut out, p).unwrap();
|
||||
frames.push(out);
|
||||
previous = p;
|
||||
}
|
||||
frames
|
||||
}
|
||||
|
||||
/// Walk a predecessor-only chain from the first frame to the last, returning the last payload.
|
||||
fn decode_predecessor_chain(frames: &[Vec<u8>]) -> Vec<u8> {
|
||||
use zstd_safe::DCtx;
|
||||
let mut previous = Vec::new();
|
||||
for frame in frames {
|
||||
let size = zstd_safe::get_frame_content_size(frame).unwrap().unwrap() as usize;
|
||||
let mut out = Vec::with_capacity(size);
|
||||
{
|
||||
// `DCtx<'a>` borrows the prefix until dropped, so it must go before `previous` is reassigned.
|
||||
let mut dctx = DCtx::create();
|
||||
dctx.set_parameter(zstd_safe::DParameter::WindowLogMax(24)).unwrap();
|
||||
dctx.ref_prefix(&previous).unwrap();
|
||||
dctx.decompress(&mut out, frame).unwrap();
|
||||
}
|
||||
previous = out;
|
||||
}
|
||||
previous
|
||||
}
|
||||
|
||||
fn bench(label: &str, iterations: u32, mut f: impl FnMut() -> usize) {
|
||||
let mut checksum = 0;
|
||||
let start = std::time::Instant::now();
|
||||
for _ in 0..iterations {
|
||||
checksum = checksum.max(f());
|
||||
}
|
||||
let elapsed = start.elapsed();
|
||||
println!(" {label:<52} {:>9.3} ms / iter (last payload {checksum} bytes)", elapsed.as_secs_f64() * 1000.0 / iterations as f64);
|
||||
}
|
||||
|
||||
/// Each payload compressed as its own zstd frame, with only its immediate predecessor supplied as a
|
||||
/// prefix dictionary (`ZSTD_CCtx_refPrefix`). No stream state is shared: decoding version `n` needs
|
||||
/// just the raw bytes of version `n-1`. `window_log` must cover prefix + payload for the match to be
|
||||
/// representable.
|
||||
fn predecessor_only(payloads: &[Vec<u8>], level: i32) -> Vec<usize> {
|
||||
use zstd_safe::{CCtx, CParameter};
|
||||
let mut sizes = Vec::with_capacity(payloads.len());
|
||||
let mut previous: &[u8] = &[];
|
||||
let mut out = Vec::new();
|
||||
for p in payloads {
|
||||
let mut cctx = CCtx::create();
|
||||
cctx.set_parameter(CParameter::CompressionLevel(level)).unwrap();
|
||||
cctx.set_parameter(CParameter::WindowLog(24)).unwrap();
|
||||
cctx.set_parameter(CParameter::EnableLongDistanceMatching(true)).unwrap();
|
||||
cctx.ref_prefix(previous).unwrap();
|
||||
out.clear();
|
||||
out.reserve(zstd_safe::compress_bound(p.len()));
|
||||
let n = cctx.compress2(&mut out, p).unwrap();
|
||||
sizes.push(n);
|
||||
previous = p;
|
||||
}
|
||||
sizes
|
||||
}
|
||||
|
||||
/// One linked chain per `(node, input)` for value changes; everything else goes into a shared chain.
|
||||
/// Keeps consecutive versions of the same value adjacent in the window regardless of interleaving.
|
||||
fn per_input_chains(deltas: &[&Delta], frames: &[Vec<u8>]) -> usize {
|
||||
let mut groups: HashMap<Option<(document_graph_storage::NodeId, u32)>, Vec<Vec<u8>>> = HashMap::new();
|
||||
for (delta, frame) in deltas.iter().zip(frames) {
|
||||
let key = match &delta.kind {
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id,
|
||||
index,
|
||||
new_input: NodeInput::Value { .. },
|
||||
} => Some((*id, *index)),
|
||||
_ => None,
|
||||
};
|
||||
groups.entry(key).or_default().push(frame.clone());
|
||||
}
|
||||
groups.values().map(|payloads| linked_chain(payloads).iter().sum::<usize>()).sum()
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
//! Compares storing large node input values inline in history against storing them as resources, and xz against zip
|
||||
//! for the outer archive.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::io::Write;
|
||||
use std::time::Instant;
|
||||
|
||||
use document_container::archive::{Archive, Zip};
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
use document_format::{ExportFormat, ExportOptions, GddV1};
|
||||
use document_graph_storage::{Delta, HotOp, NodeField, NodeId, NodeInput, Prior, RegistryDelta, ResourceHash, Value};
|
||||
use flate2::{Compress, Compression, FlushCompress, Status};
|
||||
|
||||
use crate::predecessor_only;
|
||||
|
||||
const HISTORY_PATH: &str = "history.frames";
|
||||
const HOT_LOG_PATH: &str = "hot-log.frames";
|
||||
const THRESHOLDS: [usize; 4] = [256, 4096, 16_384, 65_536];
|
||||
|
||||
pub type InputKey = (NodeId, u32);
|
||||
pub type Chains = HashMap<InputKey, Vec<Vec<u8>>>;
|
||||
|
||||
pub fn compare(gdd: &GddV1, deltas: &[&Delta]) {
|
||||
let hot_log = gdd.session().hot_log();
|
||||
|
||||
let zip = compare_archives(gdd);
|
||||
let files = futures::executor::block_on(archive_files(&zip));
|
||||
let rest_deflated: usize = files
|
||||
.iter()
|
||||
.filter(|(path, _)| path != HISTORY_PATH && path != HOT_LOG_PATH)
|
||||
.map(|(_, bytes)| deflate(bytes).len())
|
||||
.sum();
|
||||
for (path, bytes) in files.iter().filter(|(_, bytes)| bytes.len() > 10_000) {
|
||||
println!(" {path:<20} {:>10} raw {:>10} deflated", bytes.len(), deflate(bytes).len());
|
||||
}
|
||||
let inline_history = history_frames(deltas.iter().copied());
|
||||
let inline_hot_log = hot_log_frames(hot_log.iter());
|
||||
|
||||
println!();
|
||||
println!("resource model over history and hot log, every other file deflated as in a zip: {rest_deflated} bytes");
|
||||
println!(
|
||||
" {:>9} {:>6} {:>10} {:>10} {:>10} {:>10} {:>10} {:>10} {:>10}",
|
||||
"threshold", "chains", "logs", "logs-defl", "raw-blobs", "loose-defl", "dict-defl", "copy-defl", "pred-zstd"
|
||||
);
|
||||
println!(
|
||||
" {:>9} {:>6} {:>10} {:>10}",
|
||||
"inline",
|
||||
"-",
|
||||
inline_history.len() + inline_hot_log.len(),
|
||||
deflate(&inline_history).len() + deflate(&inline_hot_log).len()
|
||||
);
|
||||
|
||||
let mut timings = Vec::new();
|
||||
let mut smallest_threshold_chains = None;
|
||||
for threshold in THRESHOLDS {
|
||||
let (stripped, stripped_hot_log, chains) = split_large_values(deltas, hot_log, threshold);
|
||||
let history = history_frames(stripped.iter());
|
||||
let hot_log = hot_log_frames(stripped_hot_log.iter());
|
||||
let blobs = chains.values().flatten();
|
||||
|
||||
let raw: usize = blobs.clone().map(Vec::len).sum();
|
||||
let loose: usize = blobs.map(|blob| deflate(blob).len()).sum();
|
||||
let dictionary: usize = chains.values().map(|chain| dictionary_chain(chain)).sum();
|
||||
|
||||
let start = Instant::now();
|
||||
let copy: usize = chains.values().map(|chain| copy_chain(chain)).sum();
|
||||
let copy_time = start.elapsed();
|
||||
|
||||
let start = Instant::now();
|
||||
let zstd: usize = chains.values().map(|chain| predecessor_only(chain, 3).iter().sum::<usize>()).sum();
|
||||
let zstd_time = start.elapsed();
|
||||
timings.push((threshold, raw, copy_time, zstd_time));
|
||||
if threshold == THRESHOLDS[0] {
|
||||
smallest_threshold_chains = Some(chains.clone());
|
||||
}
|
||||
|
||||
println!(
|
||||
" {threshold:>9} {:>6} {:>10} {:>10} {raw:>10} {loose:>10} {dictionary:>10} {copy:>10} {zstd:>10}",
|
||||
chains.len(),
|
||||
history.len() + hot_log.len(),
|
||||
deflate(&history).len() + deflate(&hot_log).len()
|
||||
);
|
||||
}
|
||||
println!(" logs-defl + any store column + {rest_deflated} estimates the whole zip archive.");
|
||||
|
||||
println!();
|
||||
println!("store encode time:");
|
||||
for (threshold, raw, copy_time, zstd_time) in timings {
|
||||
let megabytes = raw as f64 / 1_000_000.;
|
||||
println!(
|
||||
" threshold {threshold:>6}: copy-defl {:>8.1} ms ({:>6.1} MB/s) pred-zstd {:>8.1} ms ({:>6.1} MB/s)",
|
||||
copy_time.as_secs_f64() * 1000.,
|
||||
megabytes / copy_time.as_secs_f64(),
|
||||
zstd_time.as_secs_f64() * 1000.,
|
||||
megabytes / zstd_time.as_secs_f64()
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(chains) = smallest_threshold_chains {
|
||||
change_locality(&chains);
|
||||
sample_value_diff(&chains);
|
||||
crate::cdc::compare(&chains);
|
||||
}
|
||||
}
|
||||
|
||||
/// Export the document as xz and zip, returning the zip so its entries can be inspected.
|
||||
fn compare_archives(gdd: &GddV1) -> Vec<u8> {
|
||||
let legacy = futures::executor::block_on(gdd.read_legacy_document());
|
||||
let legacy = legacy.as_ref().map(|bytes| bytes.as_slice());
|
||||
|
||||
println!();
|
||||
println!("archive export, whole document:");
|
||||
let mut zip = Vec::new();
|
||||
for (label, format) in [("xz", ExportFormat::Xz), ("zip (deflate)", ExportFormat::Zip)] {
|
||||
let start = Instant::now();
|
||||
let bytes = futures::executor::block_on(gdd.export_to_bytes(format, ExportOptions::default(), gdd, legacy)).unwrap();
|
||||
println!(" {label:<16} {:>9} bytes {:>9.1} ms", bytes.len(), start.elapsed().as_secs_f64() * 1000.);
|
||||
if matches!(format, ExportFormat::Zip) {
|
||||
zip = bytes;
|
||||
}
|
||||
}
|
||||
zip
|
||||
}
|
||||
|
||||
/// Every file in a zip archive with its uncompressed bytes.
|
||||
async fn archive_files(zip: &[u8]) -> Vec<(String, Vec<u8>)> {
|
||||
let mut memory = MemoryBackend::new();
|
||||
Zip::open(std::io::Cursor::new(zip), &mut memory).unwrap();
|
||||
let container = AnyContainer::Memory(memory);
|
||||
|
||||
let mut files = Vec::new();
|
||||
for path in container.list("").await.unwrap() {
|
||||
let bytes = container.read(&path).await.unwrap().as_slice().to_vec();
|
||||
files.push((path, bytes));
|
||||
}
|
||||
files
|
||||
}
|
||||
|
||||
/// Replace every node input value of at least `threshold` encoded bytes with a hash-sized stand-in, collecting each
|
||||
/// distinct value into the chain of the input it belongs to in history order, then hot log order.
|
||||
fn split_large_values(deltas: &[&Delta], hot_log: &[HotOp], threshold: usize) -> (Vec<Delta>, Vec<HotOp>, Chains) {
|
||||
let mut chains: Chains = HashMap::new();
|
||||
let mut seen = HashSet::new();
|
||||
|
||||
let mut strip = |key: InputKey, input: &mut NodeInput| {
|
||||
let NodeInput::Value { value, .. } = input else { return };
|
||||
let bytes = postcard::to_allocvec(value).unwrap();
|
||||
if bytes.len() < threshold {
|
||||
return;
|
||||
}
|
||||
|
||||
*value = Value::Str("0".repeat(32));
|
||||
if seen.insert(ResourceHash::from(bytes.as_slice())) {
|
||||
chains.entry(key).or_default().push(bytes);
|
||||
}
|
||||
};
|
||||
|
||||
let stripped = deltas
|
||||
.iter()
|
||||
.map(|&delta| {
|
||||
let mut delta = delta.clone();
|
||||
|
||||
// The prior value comes first, since it is the predecessor of the new one in the chain
|
||||
for prior in &mut delta.reverse {
|
||||
if let Prior::NodeField {
|
||||
id,
|
||||
field: NodeField::Input { index, previous },
|
||||
..
|
||||
} = prior
|
||||
{
|
||||
strip((*id, *index), &mut previous.input);
|
||||
}
|
||||
}
|
||||
if let RegistryDelta::ChangeNodeInput { id, index, new_input } = &mut delta.kind {
|
||||
strip((*id, *index), new_input);
|
||||
}
|
||||
|
||||
delta
|
||||
})
|
||||
.collect();
|
||||
|
||||
let stripped_hot_log = hot_log
|
||||
.iter()
|
||||
.map(|hot_op| {
|
||||
let mut hot_op = hot_op.clone();
|
||||
if let RegistryDelta::ChangeNodeInput { id, index, new_input } = &mut hot_op.op {
|
||||
strip((*id, *index), new_input);
|
||||
}
|
||||
hot_op
|
||||
})
|
||||
.collect();
|
||||
|
||||
(stripped, stripped_hot_log, chains)
|
||||
}
|
||||
|
||||
fn hot_log_frames<'a>(hot_ops: impl Iterator<Item = &'a HotOp>) -> Vec<u8> {
|
||||
let mut buffer = Vec::new();
|
||||
for hot_op in hot_ops {
|
||||
document_format::Codec::PostcardFrames.append(&mut buffer, hot_op).unwrap();
|
||||
}
|
||||
buffer
|
||||
}
|
||||
|
||||
fn history_frames<'a>(deltas: impl Iterator<Item = &'a Delta>) -> Vec<u8> {
|
||||
let mut buffer = Vec::new();
|
||||
for delta in deltas {
|
||||
document_format::Codec::PostcardFrames.append(&mut buffer, delta).unwrap();
|
||||
}
|
||||
buffer
|
||||
}
|
||||
|
||||
pub fn deflate(bytes: &[u8]) -> Vec<u8> {
|
||||
let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), Compression::default());
|
||||
encoder.write_all(bytes).unwrap();
|
||||
encoder.finish().unwrap()
|
||||
}
|
||||
|
||||
/// Block size the predecessor is indexed at, as in git's delta encoder.
|
||||
const COPY_BLOCK: usize = 16;
|
||||
const COPY: u8 = 0;
|
||||
const INSERT: u8 = 1;
|
||||
|
||||
/// Each version as git-style copy and insert instructions against its predecessor, deflated. Pure Rust, O(n) to
|
||||
/// encode with a block index of the predecessor, and decoding is a plain copy loop.
|
||||
fn copy_chain(chain: &[Vec<u8>]) -> usize {
|
||||
let mut previous: &[u8] = &[];
|
||||
let mut total = 0;
|
||||
for current in chain {
|
||||
let delta = copy_delta(previous, current);
|
||||
assert_eq!(&apply_copy_delta(previous, &delta), current, "copy delta does not round trip");
|
||||
total += deflate(&delta).len();
|
||||
previous = current;
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
fn copy_delta(base: &[u8], target: &[u8]) -> Vec<u8> {
|
||||
let block_key = |bytes: &[u8]| u128::from_le_bytes(bytes[..COPY_BLOCK].try_into().unwrap());
|
||||
|
||||
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 read_varint(delta: &mut &[u8]) -> usize {
|
||||
let mut value = 0;
|
||||
let mut shift = 0;
|
||||
loop {
|
||||
let byte = delta[0];
|
||||
*delta = &delta[1..];
|
||||
value |= ((byte & 0x7f) as usize) << shift;
|
||||
if byte < 0x80 {
|
||||
return value;
|
||||
}
|
||||
shift += 7;
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_copy_delta(base: &[u8], mut delta: &[u8]) -> Vec<u8> {
|
||||
let mut output = Vec::new();
|
||||
while let Some((&tag, rest)) = delta.split_first() {
|
||||
delta = rest;
|
||||
if tag == COPY {
|
||||
let offset = read_varint(&mut delta);
|
||||
let length = read_varint(&mut delta);
|
||||
output.extend_from_slice(&base[offset..offset + length]);
|
||||
} else {
|
||||
let length = read_varint(&mut delta);
|
||||
output.extend_from_slice(&delta[..length]);
|
||||
delta = &delta[length..];
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
/// Each version deflated with the last 32 KiB of its predecessor as a preset dictionary, the most of it deflate's window can see.
|
||||
fn dictionary_chain(chain: &[Vec<u8>]) -> usize {
|
||||
let mut previous: &[u8] = &[];
|
||||
let mut total = 0;
|
||||
for current in chain {
|
||||
let mut compress = Compress::new(Compression::default(), false);
|
||||
let dictionary = &previous[previous.len().saturating_sub(32 * 1024)..];
|
||||
if !dictionary.is_empty() {
|
||||
compress.set_dictionary(dictionary).unwrap();
|
||||
}
|
||||
|
||||
let mut output = Vec::with_capacity(current.len() / 2 + 1024);
|
||||
loop {
|
||||
let consumed = compress.total_in() as usize;
|
||||
if compress.compress_vec(¤t[consumed..], &mut output, FlushCompress::Finish).unwrap() == Status::StreamEnd {
|
||||
break;
|
||||
}
|
||||
output.reserve(output.capacity());
|
||||
}
|
||||
|
||||
total += output.len();
|
||||
previous = current;
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
/// How scattered the changes between consecutive versions are: inserted runs and bytes per version, and where in the
|
||||
/// version the runs start.
|
||||
pub fn change_locality(chains: &Chains) {
|
||||
let mut versions = 0;
|
||||
let mut runs = 0;
|
||||
let mut inserted = 0;
|
||||
let mut length = 0;
|
||||
let mut histogram = [0_usize; 6];
|
||||
// Runs starting in the first 1%, the middle, and the last 10% of the version
|
||||
let mut regions = [0_usize; 3];
|
||||
|
||||
for chain in chains.values() {
|
||||
for pair in chain.windows(2) {
|
||||
let delta = copy_delta(&pair[0], &pair[1]);
|
||||
let mut cursor = delta.as_slice();
|
||||
let mut position = 0;
|
||||
let mut version_runs = 0;
|
||||
while let Some((&tag, rest)) = cursor.split_first() {
|
||||
cursor = rest;
|
||||
if tag == COPY {
|
||||
read_varint(&mut cursor);
|
||||
position += read_varint(&mut cursor);
|
||||
continue;
|
||||
}
|
||||
|
||||
let run_length = read_varint(&mut cursor);
|
||||
cursor = &cursor[run_length..];
|
||||
let fraction = position as f64 / pair[1].len() as f64;
|
||||
regions[if fraction < 0.01 {
|
||||
0
|
||||
} else if fraction < 0.9 {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
}] += 1;
|
||||
version_runs += 1;
|
||||
inserted += run_length;
|
||||
position += run_length;
|
||||
}
|
||||
|
||||
versions += 1;
|
||||
runs += version_runs;
|
||||
length += pair[1].len();
|
||||
histogram[version_runs.min(5)] += 1;
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!(
|
||||
"change locality over {versions} version pairs: {:.1} inserted runs and {:.0} inserted bytes per version, average version {:.0} bytes",
|
||||
runs as f64 / versions as f64,
|
||||
inserted as f64 / versions as f64,
|
||||
length as f64 / versions as f64
|
||||
);
|
||||
println!(" versions by inserted run count (0, 1, 2, 3, 4, 5+): {histogram:?}");
|
||||
println!(" runs starting in the first 1%, middle, last 10%: {regions:?}");
|
||||
}
|
||||
|
||||
/// Print the paths that differ between two consecutive versions in the middle of the longest chain.
|
||||
pub fn sample_value_diff(chains: &Chains) {
|
||||
let Some(chain) = chains.values().max_by_key(|chain| chain.len()) else { return };
|
||||
let middle = chain.len() / 2;
|
||||
let before: Value = postcard::from_bytes(&chain[middle]).unwrap();
|
||||
let after: Value = postcard::from_bytes(&chain[middle + 1]).unwrap();
|
||||
|
||||
println!();
|
||||
println!("changed paths between versions {middle} and {} of the longest chain ({} versions):", middle + 1, chain.len());
|
||||
let mut printed = 0;
|
||||
diff_values(&before, &after, &mut String::new(), &mut printed);
|
||||
}
|
||||
|
||||
fn diff_values(before: &Value, after: &Value, path: &mut String, printed: &mut usize) {
|
||||
if before == after || *printed >= 30 {
|
||||
return;
|
||||
}
|
||||
|
||||
match (before, after) {
|
||||
(Value::Array(before), Value::Array(after)) => {
|
||||
if before.len() != after.len() {
|
||||
println!(" {path}: array length {} -> {}", before.len(), after.len());
|
||||
*printed += 1;
|
||||
}
|
||||
for (index, (before, after)) in before.iter().zip(after).enumerate() {
|
||||
let length = path.len();
|
||||
path.push_str(&format!("[{index}]"));
|
||||
diff_values(before, after, path, printed);
|
||||
path.truncate(length);
|
||||
}
|
||||
}
|
||||
(Value::Object(before), Value::Object(after)) => {
|
||||
for ((key, before), (_, after)) in before.iter().zip(after) {
|
||||
let length = path.len();
|
||||
path.push_str(&format!(".{key}"));
|
||||
diff_values(before, after, path, printed);
|
||||
path.truncate(length);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let shorten = |value: &Value| format!("{value:?}").chars().take(60).collect::<String>();
|
||||
println!(" {path}: {} -> {}", shorten(before), shorten(after));
|
||||
*printed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Reference in new issue
Block a user