mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9e0477de3 | ||
|
|
ad11756f4e | ||
|
|
789e9c90bf | ||
|
|
d51de170a7 | ||
|
|
994f18fb0d | ||
|
|
2ff42eef90 | ||
|
|
af0e8614ac | ||
|
|
0ef97e9dcc | ||
|
|
bffd30eca2 | ||
|
|
6d26c35b52 | ||
|
|
763ad33587 | ||
|
|
985a4f4a36 | ||
|
|
09175112aa |
No files matched your search
@@ -204,7 +204,7 @@ jobs:
|
||||
- name: 📥 Clone regression corpus
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
with:
|
||||
repository: GraphiteEditor/document-corpus
|
||||
repository: tagtraumen/graphite-corpus
|
||||
path: target/regression-corpus
|
||||
lfs: true
|
||||
|
||||
|
||||
Generated
-5
@@ -4225,7 +4225,6 @@ dependencies = [
|
||||
"blake3",
|
||||
"ctor",
|
||||
"document-graph-storage",
|
||||
"graphene-resource",
|
||||
"migration-macros",
|
||||
"postcard",
|
||||
"serde",
|
||||
@@ -5408,7 +5407,6 @@ dependencies = [
|
||||
"interpreted-executor",
|
||||
"log",
|
||||
"node-macro",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5936,9 +5934,7 @@ dependencies = [
|
||||
"clap",
|
||||
"document-format",
|
||||
"fern",
|
||||
"graph-craft",
|
||||
"graphene-cli",
|
||||
"graphene-std",
|
||||
"image",
|
||||
"log",
|
||||
"serde",
|
||||
@@ -7266,7 +7262,6 @@ dependencies = [
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"ipsum",
|
||||
"math-parser",
|
||||
"node-macro",
|
||||
"parley",
|
||||
"rand",
|
||||
|
||||
@@ -1,404 +0,0 @@
|
||||
//! Blob records in the working copy, one `blobs/<hash>` file each.
|
||||
//!
|
||||
//! A record holds a blob in full or as a copy delta against an older blob of the same node input. Most edits change only a
|
||||
//! few bytes of a value, so a delta is small. Records are not compressed. This lets an archive codec compress across them.
|
||||
//!
|
||||
//! Record layout is a kind byte, then the 32 base hash bytes for a delta, then the payload.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
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.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct BlobStore {
|
||||
pub(crate) bytes: BlobBytes,
|
||||
/// The records of blobs stored as deltas. Other blobs are stored in full.
|
||||
delta_records: HashMap<BlobHash, Vec<u8>>,
|
||||
}
|
||||
|
||||
impl BlobStore {
|
||||
/// Hold a new blob and return the record to write for it. The record is a delta when `base` is held.
|
||||
/// Returns `None` for a blob that is already held.
|
||||
pub(crate) fn insert(&mut self, hash: BlobHash, bytes: Vec<u8>, base: Option<BlobHash>) -> Option<Vec<u8>> {
|
||||
if self.bytes.contains_key(&hash) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let record = match base.and_then(|base| Some((base, self.bytes.get(&base)?))) {
|
||||
Some((base, base_bytes)) => {
|
||||
let record = delta_record(base, base_bytes, &bytes);
|
||||
self.delta_records.insert(hash, record.clone());
|
||||
record
|
||||
}
|
||||
None => full_record(&bytes),
|
||||
};
|
||||
|
||||
self.bytes.insert(hash, bytes);
|
||||
Some(record)
|
||||
}
|
||||
|
||||
/// [`insert`](Self::insert) every blob in hash order. A base goes in before the blobs that use it.
|
||||
pub(crate) fn insert_all(&mut self, blobs: NewBlobs) -> Vec<(BlobHash, Vec<u8>)> {
|
||||
let NewBlobs { bytes: mut blobs, bases } = blobs;
|
||||
let mut hashes: Vec<_> = blobs.keys().copied().collect();
|
||||
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. A base comes before the blobs that use it.
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) fn records(&self) -> Vec<(BlobHash, Vec<u8>)> {
|
||||
let mut hashes: Vec<_> = self.bytes.keys().copied().collect();
|
||||
hashes.sort_unstable();
|
||||
|
||||
let mut listed = HashSet::new();
|
||||
let mut records = Vec::new();
|
||||
for hash in hashes {
|
||||
let unlisted_base = |hash: &BlobHash| record_base(self.delta_records.get(hash)?).filter(|base| !listed.contains(base) && self.bytes.contains_key(base));
|
||||
for hash in chain_to(hash, unlisted_base) {
|
||||
if listed.insert(hash)
|
||||
&& let Some(record) = self.delta_records.get(&hash).cloned().or_else(|| self.full_record(&hash))
|
||||
{
|
||||
records.push((hash, record));
|
||||
}
|
||||
}
|
||||
}
|
||||
records
|
||||
}
|
||||
|
||||
/// Hold the blobs of records from a peer and return the records to write.
|
||||
/// Skips a record that is malformed, fails its hash check or needs a base that is not held.
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) fn absorb(&mut self, records: Vec<(BlobHash, Vec<u8>)>) -> Vec<(BlobHash, Vec<u8>)> {
|
||||
let mut pending = records;
|
||||
let mut held = Vec::new();
|
||||
|
||||
// A record can arrive before its base, so repeat until a pass holds nothing new
|
||||
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.to_vec(),
|
||||
Some(Record::Delta { base, delta }) => {
|
||||
let Some(base_bytes) = self.bytes.get(&base) else { return true };
|
||||
let Some(bytes) = apply_copy_delta(base_bytes, delta) else { return false };
|
||||
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 full record of the held blob `hash`.
|
||||
pub(crate) fn full_record(&self, hash: &BlobHash) -> Option<Vec<u8>> {
|
||||
Some(full_record(self.bytes.get(hash)?))
|
||||
}
|
||||
|
||||
/// Drop a blob whose record never got written.
|
||||
pub(crate) fn forget(&mut self, hash: &BlobHash) {
|
||||
self.bytes.remove(hash);
|
||||
self.delta_records.remove(hash);
|
||||
}
|
||||
|
||||
/// Read and decode the record of `hash` and the records of its bases. Each blob is checked against its hash.
|
||||
pub(crate) async fn load(&mut self, hash: BlobHash, working: &AnyContainer, layout: &impl Layout) -> Result<(), String> {
|
||||
if self.bytes.contains_key(&hash) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Follow the bases down to a held blob or a full record, then apply the deltas in reverse
|
||||
let mut deltas = Vec::new();
|
||||
let mut visited = HashSet::new();
|
||||
let mut current = hash;
|
||||
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) => {
|
||||
let bytes = bytes.to_vec();
|
||||
self.hold_checked(current, bytes.clone(), record)?;
|
||||
break bytes;
|
||||
}
|
||||
Record::Delta { base, delta } => {
|
||||
deltas.push((current, delta.to_vec(), 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);
|
||||
if record.first() == Some(&DELTA) {
|
||||
self.delta_records.insert(hash, record);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// `hash` and the chain of bases that `base_of` returns, deepest base first. Stops if the chain loops.
|
||||
fn chain_to(hash: BlobHash, base_of: impl Fn(&BlobHash) -> Option<BlobHash>) -> Vec<BlobHash> {
|
||||
let mut chain = vec![hash];
|
||||
let mut visited = HashSet::from([hash]);
|
||||
while let Some(base) = chain.last().and_then(&base_of)
|
||||
&& visited.insert(base)
|
||||
{
|
||||
chain.push(base);
|
||||
}
|
||||
chain.reverse();
|
||||
chain
|
||||
}
|
||||
|
||||
/// The base hash and the payload of a delta record.
|
||||
fn split_delta_record(record: &[u8]) -> Option<(BlobHash, &[u8])> {
|
||||
let (&DELTA, rest) = record.split_first()? else { return None };
|
||||
let (base, delta) = rest.split_first_chunk::<32>()?;
|
||||
Some((BlobHash(ResourceHash::from(*base)), delta))
|
||||
}
|
||||
|
||||
/// The base hash of a delta record.
|
||||
#[cfg(feature = "network")]
|
||||
fn record_base(record: &[u8]) -> Option<BlobHash> {
|
||||
split_delta_record(record).map(|(base, _)| base)
|
||||
}
|
||||
|
||||
enum Record<'a> {
|
||||
Full(&'a [u8]),
|
||||
Delta { base: BlobHash, delta: &'a [u8] },
|
||||
}
|
||||
|
||||
fn full_record(bytes: &[u8]) -> Vec<u8> {
|
||||
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<'_>> {
|
||||
match *record.first()? {
|
||||
FULL => Some(Record::Full(&record[1..])),
|
||||
DELTA => split_delta_record(record).map(|(base, delta)| Record::Delta { base, delta }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// A copy delta is a list of COPY and INSERT operations. COPY takes a byte range from the base. INSERT carries new bytes.
|
||||
// Like git's delta encoding, it indexes aligned blocks of the base and finds them at any offset in the target.
|
||||
const COPY_BLOCK: usize = 16;
|
||||
const COPY: u8 = 0;
|
||||
const INSERT: u8 = 1;
|
||||
|
||||
/// A delta that decodes to more bytes is rejected. A small delta from a peer could otherwise copy the same base range
|
||||
/// until it fills memory. This matches the peer transport's packet limit, so no larger blob could be sent in full.
|
||||
const MAX_BLOB_BYTES: usize = 256 * 1024 * 1024;
|
||||
|
||||
/// Expected O(base + target) time. Each base block is indexed once and each unmatched target byte is looked up once.
|
||||
fn copy_delta(base: &[u8], target: &[u8]) -> Vec<u8> {
|
||||
let block_key = |bytes: &[u8]| -> u128 {
|
||||
let mut key = [0; COPY_BLOCK];
|
||||
key.copy_from_slice(&bytes[..COPY_BLOCK]);
|
||||
u128::from_le_bytes(key)
|
||||
};
|
||||
|
||||
let mut index = HashMap::new();
|
||||
for offset in (0..base.len().saturating_sub(COPY_BLOCK - 1)).step_by(COPY_BLOCK) {
|
||||
index.entry(block_key(&base[offset..])).or_insert(offset);
|
||||
}
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
// A match can start before the aligned block, so also extend it backward into the pending literal
|
||||
let backward = base[..base_offset].iter().rev().zip(target[literal_start..position].iter().rev()).take_while(|(a, b)| a == b).count();
|
||||
let forward = base[base_offset..].iter().zip(&target[position..]).take_while(|(a, b)| a == b).count();
|
||||
|
||||
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)?;
|
||||
if output.len().checked_add(length)? > MAX_BLOB_BYTES {
|
||||
return None;
|
||||
}
|
||||
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 = 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());
|
||||
|
||||
let base = vec![0; 1024 * 1024];
|
||||
let mut expanding = Vec::new();
|
||||
for _ in 0..=MAX_BLOB_BYTES / base.len() {
|
||||
expanding.push(COPY);
|
||||
push_varint(&mut expanding, 0);
|
||||
push_varint(&mut expanding, base.len());
|
||||
}
|
||||
assert!(apply_copy_delta(&base, &expanding).is_none(), "a delta past the size limit is rejected");
|
||||
assert!(decode_record(&[DELTA, 1, 2]).is_none());
|
||||
}
|
||||
}
|
||||
@@ -247,33 +247,18 @@ impl<L: Layout> Gdd<L> {
|
||||
}
|
||||
}
|
||||
|
||||
// Every resource and blob record in path order. The archive is the same wherever the bytes are stored.
|
||||
// `None` marks bytes the working copy already holds.
|
||||
let mut entries: std::collections::BTreeMap<String, Option<Resource>> = std::collections::BTreeMap::new();
|
||||
let directories = self.working.list_dirs("").await?;
|
||||
let has_directory = |directory: &str| directories.iter().any(|name| name == directory);
|
||||
if has_directory(self.layout.resources_dir()) {
|
||||
entries.extend(self.working.list(self.layout.resources_dir()).await?.into_iter().map(|path| (path, None)));
|
||||
// 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)));
|
||||
}
|
||||
for (hash, resource) in embedded_bytes {
|
||||
entries.entry(self.layout.resource_path(&hash)).or_insert(Some(resource));
|
||||
resources.entry(self.layout.resource_path(&hash)).or_insert(Some(resource));
|
||||
}
|
||||
|
||||
// A copy without history has no older blobs to use as bases, so each blob is written in full
|
||||
match &flat {
|
||||
Some(flat) => {
|
||||
for hash in flat.registry().blob_hashes() {
|
||||
let record = self.blobs.full_record(&hash).ok_or(Error::MissingResource(hash.into()))?;
|
||||
entries.insert(self.layout.blob_path(&hash), Some(Resource::new_unchecked(record, hash.into())));
|
||||
}
|
||||
}
|
||||
None if has_directory(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 {
|
||||
for (path, resource) in resources {
|
||||
if let Some(resource) = resource {
|
||||
sink.write_entry(&path, resource.as_ref())?;
|
||||
continue;
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
//! 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 {
|
||||
@@ -16,10 +15,6 @@ 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.
|
||||
fn blobs_dir(&self) -> &str;
|
||||
/// The path of one blob record.
|
||||
fn blob_path(&self, hash: &BlobHash) -> String;
|
||||
/// The embedded legacy `.graphite` document, stored verbatim during the dual-write soak so the
|
||||
/// new format can be validated against (and recovered from) the old one. Dropped once `.gdd`
|
||||
/// becomes the sole source of truth.
|
||||
@@ -56,12 +51,6 @@ 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,7 +24,6 @@ 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;
|
||||
@@ -48,8 +47,6 @@ 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>;
|
||||
|
||||
@@ -107,15 +104,15 @@ 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>>,
|
||||
/// Every blob the document names.
|
||||
pub(crate) blobs: BlobStore,
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) network: Option<peer_transport::Replica>,
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) pending_persist: PendingPersist,
|
||||
/// What changed since [`take_remote_changes`](Self::take_remote_changes) last took it.
|
||||
pub(crate) remote_changes: RemoteChanges,
|
||||
/// What peers changed since [`take_remote_changes`](Self::take_remote_changes) last took it.
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) remote_changes: network::RemoteChanges,
|
||||
/// The step a guest asked the host to undo, with the head it asked under. A repeat waits until the head moves.
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) undo_requested: Option<(document_graph_storage::Rev, Option<document_graph_storage::Rev>)>,
|
||||
pub(crate) interactions_seen: std::collections::HashMap<document_graph_storage::HotOpId, f64>,
|
||||
pub(crate) own_last_staged_ms: Option<f64>,
|
||||
@@ -124,27 +121,6 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
pub(crate) shared: bool,
|
||||
}
|
||||
|
||||
/// Changes to the working registry that the runtime mirror has not seen yet, such as peer edits and undos of retired
|
||||
/// steps. The mirror reconciles just the touched entities.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RemoteChanges {
|
||||
pub touched: document_graph_storage::Touched,
|
||||
/// A full sync replaced the working registry, so the touched set no longer bounds what changed and the mirror
|
||||
/// must be rebuilt.
|
||||
pub rebuilt: bool,
|
||||
}
|
||||
|
||||
impl RemoteChanges {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.touched.is_empty() && !self.rebuilt
|
||||
}
|
||||
|
||||
pub fn extend(&mut self, other: RemoteChanges) {
|
||||
self.touched.extend(other.touched);
|
||||
self.rebuilt |= other.rebuilt;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whole-file rewrites deferred to the end of a poll, so a batch of remote packets costs one rewrite per file.
|
||||
#[cfg(feature = "network")]
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
@@ -172,7 +148,6 @@ impl<L: Layout + Clone> Clone for Gdd<L> {
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
wall_clock_ms: self.wall_clock_ms,
|
||||
byte_store: self.byte_store.clone(),
|
||||
blobs: self.blobs.clone(),
|
||||
migrated: self.migrated,
|
||||
shared: self.shared,
|
||||
interactions_seen: self.interactions_seen.clone(),
|
||||
@@ -196,13 +171,14 @@ 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,
|
||||
#[cfg(feature = "network")]
|
||||
pending_persist: PendingPersist::default(),
|
||||
remote_changes: RemoteChanges::default(),
|
||||
#[cfg(feature = "network")]
|
||||
remote_changes: network::RemoteChanges::default(),
|
||||
#[cfg(feature = "network")]
|
||||
undo_requested: None,
|
||||
interactions_seen: Default::default(),
|
||||
own_last_staged_ms: None,
|
||||
@@ -297,7 +273,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, migrated_blobs) = migrate::migrate_format(&mut records, codecs, manifest.format_version)?.unzip();
|
||||
let format_outcome = migrate::migrate_format(&mut records, codecs, manifest.format_version)?;
|
||||
#[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")]
|
||||
@@ -372,13 +348,6 @@ 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?;
|
||||
}
|
||||
// Node migrations read values stored in blobs, so load them first
|
||||
gdd.load_blobs().await;
|
||||
|
||||
#[cfg(feature = "migrations")]
|
||||
{
|
||||
let migrated_nodes = gdd.migrate_nodes(inputs.byte_store, inputs.host).await?;
|
||||
|
||||
@@ -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 = 4;
|
||||
pub const SUPPORTED_FORMAT_VERSION: u32 = 3;
|
||||
|
||||
/// 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,12 +4,10 @@
|
||||
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, MigrationBlobs, RunnerError, holds, migrate_history, migrate_registry, references, registry_at, run_format_migrations};
|
||||
use migration_runner::{DocumentPayloads, HistoryOutcome, RunnerError, holds, migrate_history, migrate_registry, references, registry_at, run_format_migrations};
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
@@ -18,7 +16,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, NewBlobs)>, Error> {
|
||||
pub(crate) fn migrate_format(records: &mut StoredRecords, codecs: PayloadCodecs, format_version: u32) -> Result<Option<HistoryOutcome>, Error> {
|
||||
if format_version >= SUPPORTED_FORMAT_VERSION {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -30,7 +28,6 @@ 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}");
|
||||
@@ -43,11 +40,7 @@ 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);
|
||||
|
||||
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)))
|
||||
Ok(Some(outcome))
|
||||
}
|
||||
|
||||
/// The facts in `metadata` with their revs mapped by `remap`, which drops the facts of a rev it has no answer for.
|
||||
@@ -98,16 +91,14 @@ impl<L: Layout> Gdd<L> {
|
||||
// Hot ops join history first, so they migrate with it
|
||||
self.session.retire_all()?;
|
||||
|
||||
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) {
|
||||
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) {
|
||||
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();
|
||||
@@ -165,11 +156,10 @@ 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, blobs)?;
|
||||
let rewritten = migrate_history(migrations, history, resolver, host, cursors)?;
|
||||
let remap = |rev: Rev| rewritten.revs.get(&rev).copied().flatten();
|
||||
|
||||
let head = self.session.head_rev().and_then(remap);
|
||||
|
||||
@@ -4,16 +4,52 @@
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use document_container::AsyncContainer;
|
||||
use document_graph_storage::blob::{BlobBytes, NewBlobs};
|
||||
use document_graph_storage::{BlobHash, Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, RegistryDelta, ResourceHash, RetiredMarks, Rev, Session, UserId};
|
||||
use peer_transport::{BlobRecord, Event, Replica, Role, SyncTarget, TargetError, Transport};
|
||||
use 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 crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::{Gdd, PendingPersist};
|
||||
|
||||
/// What peers changed in the working registry since it was last taken, so a runtime mirror can reconcile
|
||||
/// just the touched entities.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RemoteChanges {
|
||||
pub touched: Touched,
|
||||
/// A full sync replaced the working registry, so the touched set no longer bounds what changed and the mirror
|
||||
/// must be rebuilt.
|
||||
pub rebuilt: bool,
|
||||
}
|
||||
|
||||
impl RemoteChanges {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.touched.is_empty() && !self.rebuilt
|
||||
}
|
||||
|
||||
pub fn extend(&mut self, other: RemoteChanges) {
|
||||
self.touched.extend(other.touched);
|
||||
self.rebuilt |= other.rebuilt;
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
pub fn take_remote_changes(&mut self) -> RemoteChanges {
|
||||
std::mem::take(&mut self.remote_changes)
|
||||
}
|
||||
|
||||
/// Restore a dropped interaction and publish it, recording what it named in the remote changes. Returns the new deltas.
|
||||
pub(crate) fn restore_dropped_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, CrdtError> {
|
||||
let revs = self.session.restore_interaction(rev)?;
|
||||
let deltas: Vec<Delta> = revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
|
||||
for delta in &deltas {
|
||||
self.remote_changes.touched.record(&delta.kind);
|
||||
}
|
||||
if let Some(&last) = revs.last() {
|
||||
self.session.publish_up_to(last);
|
||||
}
|
||||
Ok(deltas)
|
||||
}
|
||||
|
||||
/// Host this document's room, and remember it is shared so a reopen reconnects.
|
||||
pub fn share(&mut self, transport: impl Transport + 'static, user: UserId) -> Result<(), Error> {
|
||||
self.network = Some(Replica::host(transport, self.session.peer(), user));
|
||||
@@ -334,40 +370,12 @@ impl<L: Layout> SyncTarget for Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Also includes missing blobs. They are fetched in full like resources.
|
||||
fn missing_resources(&self) -> HashSet<ResourceHash> {
|
||||
let missing_blobs = self.session.all_blob_hashes().into_iter().filter(|hash| !self.blobs.bytes.contains_key(hash));
|
||||
self.unstored_resources().into_iter().chain(missing_blobs.map(ResourceHash::from)).collect()
|
||||
self.unstored_resources().into_iter().collect()
|
||||
}
|
||||
|
||||
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.names_blob(blob) {
|
||||
let bytes = BlobBytes::from([(blob, bytes.to_vec())]);
|
||||
self.keep_blobs(NewBlobs { bytes, ..Default::default() })?;
|
||||
return Ok(());
|
||||
}
|
||||
fn store_resource(&mut self, _hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
|
||||
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 (index, (hash, record)) in held.iter().enumerate() {
|
||||
if let Err(error) = self.working.write_non_blocking(&self.layout.blob_path(hash), record) {
|
||||
// Forget the unwritten blobs so that they are asked for again
|
||||
held[index..].iter().for_each(|(hash, _)| self.blobs.forget(hash));
|
||||
return Err(error.into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+48
-115
@@ -4,12 +4,9 @@
|
||||
//! surface absorbs durability.
|
||||
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
use document_graph_storage::blob::{BlobBytes, NewBlobs};
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::from_runtime::RuntimeConversion;
|
||||
use document_graph_storage::{BlobHash, CrdtError, Delta, HistoryMetadata, HotOp, MetadataFact, PeerId, RegistryDelta, Rev, Sorted, Subject, TimeStamp, UserId, Value, WallStamp};
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::{CommitError, NodeMetadataSource, Registry};
|
||||
use document_graph_storage::NodeMetadataSource;
|
||||
use document_graph_storage::{HistoryMetadata, HotOp, MetadataFact, PeerId, RegistryDelta, Rev, Sorted, Subject, TimeStamp, UserId, Value, WallStamp};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::ResourceStorage;
|
||||
|
||||
@@ -17,7 +14,7 @@ use crate::SessionState;
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::manifest::Manifest;
|
||||
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, RemoteChanges, encode_facts, io};
|
||||
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, encode_facts, io};
|
||||
|
||||
/// Written after every staged payload, so its presence means the whole rewrite is ready to move into place.
|
||||
const STAGING_COMMITTED: &str = "committed";
|
||||
@@ -53,35 +50,21 @@ impl<L: Layout> Gdd<L> {
|
||||
/// Move the undo cursor back one commit (silent-zone reflog undo) and persist the new cursor. Returns
|
||||
/// the undone `Rev`. The working registry is rewound in place by the reverse delta, so re-snapshot it
|
||||
/// (alongside `head`) or a reopen would read a `registry.bin` inconsistent with the persisted cursor.
|
||||
/// Records what the step named for [`take_remote_changes`](Self::take_remote_changes).
|
||||
pub fn undo(&mut self) -> Result<Rev, Error> {
|
||||
let rev = self.session.undo()?;
|
||||
self.remote_changes.touched.extend(self.session.touched_between(self.session.head_rev(), rev));
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
Ok(rev)
|
||||
}
|
||||
|
||||
/// Re-apply the most-recently-undone commit and persist the new cursor and re-snapshotted registry. Records what
|
||||
/// the step named like [`undo`](Self::undo).
|
||||
/// Re-apply the most-recently-undone commit and persist the new cursor and re-snapshotted registry.
|
||||
pub fn redo(&mut self) -> Result<Rev, Error> {
|
||||
let from = self.session.head_rev();
|
||||
let rev = self.session.redo()?;
|
||||
self.remote_changes.touched.extend(self.session.touched_between(from, rev));
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
Ok(rev)
|
||||
}
|
||||
|
||||
/// Forget the latest undone commit, so redo can't bring it back, and persist the cursor.
|
||||
pub fn forget_latest_undo(&mut self) -> Result<Option<Rev>, Error> {
|
||||
let forgotten = self.session.forget_latest_undo();
|
||||
if forgotten.is_some() {
|
||||
self.persist_session_state()?;
|
||||
}
|
||||
Ok(forgotten)
|
||||
}
|
||||
|
||||
/// Set the person using this device. `peer` must be unused, so the previous user keeps their steps. Refused while connected.
|
||||
pub fn set_user(&mut self, user: UserId, peer: PeerId) -> Result<(), Error> {
|
||||
if self.session.user() == user {
|
||||
@@ -93,7 +76,7 @@ impl<L: Layout> Gdd<L> {
|
||||
}
|
||||
let closing = self.session.set_user(user, peer)?;
|
||||
self.own_last_staged_ms = None;
|
||||
self.persist_staged(&closing, Vec::new())?;
|
||||
self.persist_staged(&closing)?;
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
@@ -123,27 +106,16 @@ impl<L: Layout> Gdd<L> {
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<document_graph_storage::Declarations, Error> {
|
||||
let RuntimeConversion {
|
||||
registry,
|
||||
blob_bytes,
|
||||
declaration_bytes,
|
||||
declarations,
|
||||
..
|
||||
} = Registry::convert_from_runtime(network, metadata, resources, self.session.peer()).map_err(CommitError::from)?;
|
||||
|
||||
// The converted registry already names its large values as blobs
|
||||
let ops = self.session.runtime_diff(®istry);
|
||||
let bases = self.registry().blob_bases(&ops);
|
||||
let hot_ops = self.session.stage_runtime_diff(ops, registry)?;
|
||||
self.persist_with_blobs(&hot_ops, NewBlobs { bytes: blob_bytes, bases })?;
|
||||
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
|
||||
self.persist_staged(&hot_ops)?;
|
||||
|
||||
// Persist proto-node declaration content to the byte store (the global cache in the editor,
|
||||
// the working-copy container for standalone export). Content-addressed, so re-storing
|
||||
// identical bytes on every commit is an idempotent no-op.
|
||||
for bytes in declaration_bytes.values() {
|
||||
for bytes in conversion.declaration_bytes.values() {
|
||||
byte_store.store(bytes);
|
||||
}
|
||||
Ok(declarations)
|
||||
Ok(conversion.declarations)
|
||||
}
|
||||
|
||||
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
|
||||
@@ -165,27 +137,15 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(hot_ops)
|
||||
}
|
||||
|
||||
/// Stage raw registry ops as hot ops, without the runtime diff. Large input values become blobs.
|
||||
/// Stage raw registry ops as hot ops, without the runtime diff.
|
||||
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, Error> {
|
||||
let mut ops: Vec<_> = ops.into_iter().collect();
|
||||
let mut blobs = BlobBytes::new();
|
||||
ops.iter_mut().for_each(|op| op.move_values_into_blobs(&mut blobs));
|
||||
let bases = self.registry().blob_bases(&ops);
|
||||
|
||||
let hot_ops = self.session.stage_computed_ops(ops)?;
|
||||
self.persist_with_blobs(&hot_ops, NewBlobs { bytes: blobs, bases })?;
|
||||
let hot_ops = self.session.stage_computed_ops(ops.into_iter().collect())?;
|
||||
self.persist_staged(&hot_ops)?;
|
||||
Ok(hot_ops)
|
||||
}
|
||||
|
||||
/// Write the records of new blobs, then persist the hot frames that name them.
|
||||
fn persist_with_blobs(&mut self, hot_ops: &[HotOp], blobs: NewBlobs) -> Result<(), Error> {
|
||||
let records = self.keep_blobs(blobs)?;
|
||||
self.persist_staged(hot_ops, records)
|
||||
}
|
||||
|
||||
/// Append the frames of freshly staged hot ops, then broadcast them together with their new blob records.
|
||||
#[cfg_attr(not(feature = "network"), expect(unused_variables, reason = "only peers receive the blob records"))]
|
||||
fn persist_staged(&mut self, hot_ops: &[HotOp], blobs: Vec<(BlobHash, Vec<u8>)>) -> Result<(), Error> {
|
||||
/// Append the frames of freshly staged hot ops, then broadcast them.
|
||||
fn persist_staged(&mut self, hot_ops: &[HotOp]) -> Result<(), Error> {
|
||||
if hot_ops.iter().any(|hot_op| !matches!(hot_op.op, RegistryDelta::Meta)) {
|
||||
self.own_staged_since_tick = true;
|
||||
}
|
||||
@@ -194,8 +154,7 @@ impl<L: Layout> Gdd<L> {
|
||||
}
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
let blobs = blobs.into_iter().map(|(hash, record)| peer_transport::BlobRecord { hash, record }).collect();
|
||||
replica.broadcast_hot_ops(hot_ops, blobs)?;
|
||||
replica.broadcast_hot_ops(hot_ops)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -242,7 +201,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, Vec::new())?;
|
||||
replica.broadcast_hot_ops(hot_ops)?;
|
||||
}
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
@@ -437,10 +396,15 @@ 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, Vec::new())?;
|
||||
self.persist_staged(&staged)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Names this peer's open interaction. Closing it takes the name along.
|
||||
pub fn name_interaction(&mut self, action: &str) {
|
||||
self.session.name_interaction(action);
|
||||
}
|
||||
|
||||
/// Undo this peer's latest hot interaction, here and on peers. `None` if it already retired.
|
||||
pub fn retract_interaction(&mut self) -> Result<Option<Vec<RegistryDelta>>, Error> {
|
||||
let Some(retraction) = self.session.retract_interaction()? else {
|
||||
@@ -450,18 +414,17 @@ impl<L: Layout> Gdd<L> {
|
||||
self.rewrite_hot_log()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
self.remote_changes.touched.extend(retraction.touched);
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_retraction(&retraction.ids)?;
|
||||
{
|
||||
self.remote_changes.touched.extend(retraction.touched);
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_retraction(&retraction.ids)?;
|
||||
}
|
||||
}
|
||||
Ok(Some(retraction.ops))
|
||||
}
|
||||
|
||||
pub fn take_remote_changes(&mut self) -> RemoteChanges {
|
||||
std::mem::take(&mut self.remote_changes)
|
||||
}
|
||||
|
||||
#[cfg(feature = "network")]
|
||||
pub fn undo_retired_step(&mut self) -> Result<Option<Rev>, Error> {
|
||||
if !self.can_change_line() {
|
||||
return Ok(None);
|
||||
@@ -479,33 +442,24 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(Some(rev))
|
||||
}
|
||||
|
||||
#[cfg(feature = "network")]
|
||||
pub fn can_change_line(&self) -> bool {
|
||||
#[cfg(feature = "network")]
|
||||
if self.network.as_ref().is_some_and(|replica| replica.has_host()) {
|
||||
return true;
|
||||
}
|
||||
self.retires_locally()
|
||||
self.retires_locally() || self.network.as_ref().is_some_and(|replica| replica.has_host())
|
||||
}
|
||||
|
||||
/// Drop a retired interaction from the line. A non-retiring peer asks the retirer.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn drop_step(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if !self.retires_locally() {
|
||||
#[cfg(feature = "network")]
|
||||
if self.retires_locally() {
|
||||
let (moved, touched) = self.session.drop_interaction(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.persist_rewritten_line()?;
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.request_undo(rev, false)?;
|
||||
replica.broadcast_head_move(moved)?;
|
||||
}
|
||||
return Ok(());
|
||||
} else if let Some(replica) = &mut self.network {
|
||||
replica.request_undo(rev, false)?;
|
||||
}
|
||||
|
||||
let (moved, touched) = self.session.drop_interaction(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.persist_rewritten_line()?;
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_head_move(moved)?;
|
||||
}
|
||||
#[cfg(not(feature = "network"))]
|
||||
let _ = moved;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -527,43 +481,21 @@ impl<L: Layout> Gdd<L> {
|
||||
}
|
||||
|
||||
/// Redo a dropped step as a copy on top of the line. A non-retiring peer asks the retirer.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn redo_retired_step(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if !self.retires_locally() {
|
||||
#[cfg(feature = "network")]
|
||||
if self.retires_locally() {
|
||||
let deltas = self.restore_dropped_interaction(rev)?;
|
||||
self.persist_rewritten_line()?;
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.request_undo(rev, true)?;
|
||||
replica.broadcast_retired(&deltas, &[])?;
|
||||
}
|
||||
return Ok(());
|
||||
} else if let Some(replica) = &mut self.network {
|
||||
replica.request_undo(rev, true)?;
|
||||
}
|
||||
|
||||
let deltas = self.restore_dropped_interaction(rev)?;
|
||||
self.persist_rewritten_line()?;
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_retired(&deltas, &[])?;
|
||||
}
|
||||
#[cfg(not(feature = "network"))]
|
||||
let _ = deltas;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Restore a dropped interaction and record what it named in the remote changes. Returns the new deltas.
|
||||
pub(crate) fn restore_dropped_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, CrdtError> {
|
||||
let revs = self.session.restore_interaction(rev)?;
|
||||
let deltas: Vec<Delta> = revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
|
||||
for delta in &deltas {
|
||||
self.remote_changes.touched.record(&delta.kind);
|
||||
}
|
||||
// Only the deltas peers will see are published, so a local redo stays silently undoable
|
||||
#[cfg(feature = "network")]
|
||||
if self.network.is_some()
|
||||
&& let Some(&last) = revs.last()
|
||||
{
|
||||
self.session.publish_up_to(last);
|
||||
}
|
||||
Ok(deltas)
|
||||
}
|
||||
|
||||
#[cfg(feature = "network")]
|
||||
fn persist_rewritten_line(&mut self) -> Result<(), Error> {
|
||||
self.rewrite_history()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
@@ -572,11 +504,12 @@ impl<L: Layout> Gdd<L> {
|
||||
|
||||
/// Stage retracted ops as a new interaction. They count as remote changes.
|
||||
pub fn restage_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<(), Error> {
|
||||
#[cfg(feature = "network")]
|
||||
for op in &ops {
|
||||
self.remote_changes.touched.record(op);
|
||||
}
|
||||
self.stage_ops(ops)?;
|
||||
self.end_interaction()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retire what is due at `now_ms`. Open interactions never retire. `idle` means the editor is between steps.
|
||||
|
||||
@@ -7,8 +7,6 @@ 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};
|
||||
|
||||
@@ -126,45 +124,6 @@ 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.
|
||||
pub fn blobs(&self) -> &BlobBytes {
|
||||
&self.blobs.bytes
|
||||
}
|
||||
|
||||
/// Hold staged blobs and queue their records before the hot frames that name them.
|
||||
/// Returns the records so peers can receive them with the ops.
|
||||
pub(crate) fn keep_blobs(&mut self, blobs: NewBlobs) -> Result<Vec<(BlobHash, Vec<u8>)>, ContainerError> {
|
||||
let records = self.blobs.insert_all(blobs);
|
||||
|
||||
for (index, (hash, record)) in records.iter().enumerate() {
|
||||
if let Err(error) = self.working.write_non_blocking(&self.layout.blob_path(hash), record) {
|
||||
// Forget the unwritten blobs so that staging them again writes them
|
||||
records[index..].iter().for_each(|(hash, _)| self.blobs.forget(hash));
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Ok(records)
|
||||
}
|
||||
|
||||
/// Like [`keep_blobs`](Self::keep_blobs), but waits until the records are written.
|
||||
/// A migration needs this before it replaces the old records.
|
||||
#[cfg(feature = "migrations")]
|
||||
pub(crate) async fn keep_blobs_durably(&mut self, blobs: NewBlobs) -> Result<(), ContainerError> {
|
||||
for (hash, record) in self.blobs.insert_all(blobs) {
|
||||
self.working.write(&self.layout.blob_path(&hash), &record).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decode every blob the document names. This includes blobs of history states the cursor can move to.
|
||||
pub(crate) async fn load_blobs(&mut self) {
|
||||
for hash in self.session.all_blob_hashes() {
|
||||
if let Err(error) = self.blobs.load(hash, &self.working, &self.layout).await {
|
||||
log::error!("{error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
|
||||
|
||||
@@ -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, reopened.blobs());
|
||||
let converted = reopened.registry().to_runtime_with_full_metadata(&declarations);
|
||||
assert!(converted.is_ok(), "{}", converted.err().unwrap());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -769,10 +769,7 @@ 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, gdd.blobs())
|
||||
.unwrap_or_else(|error| panic!("to_runtime failed: {error:?}"));
|
||||
let (converted, _entries) = gdd.registry().to_runtime_with_metadata(&declarations).unwrap_or_else(|error| panic!("to_runtime failed: {error:?}"));
|
||||
|
||||
let node = converted.nodes.values().next().expect("converted network has the node");
|
||||
match &node.implementation {
|
||||
|
||||
@@ -146,70 +146,3 @@ fn a_user_change_survives_a_reopen() {
|
||||
assert_eq!(authors, [PeerId(24), PeerId(24), PeerId(25)]);
|
||||
});
|
||||
}
|
||||
|
||||
/// Large input values are staged as blobs. An edit is stored as a delta against the previous value.
|
||||
/// Both the current state and an undone one survive a reopen and an archive round trip.
|
||||
#[test]
|
||||
fn blobs_resolve_after_a_reopen_and_an_archive_round_trip() {
|
||||
use document_container::AsyncContainer;
|
||||
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();
|
||||
|
||||
// This op is not from a conversion, so the value stays inline until staging moves it into a blob
|
||||
let id = *gdd.registry().node_instances.keys().next().unwrap();
|
||||
let value = Value::from(serde_json::to_value(&edited).unwrap());
|
||||
let new_input = NodeInput::Value { value, exposed: false };
|
||||
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);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -120,113 +120,3 @@ fn the_user_cannot_change_while_connected() {
|
||||
assert_eq!(host.session().peer(), PeerId(1));
|
||||
assert_eq!(host.session().user(), UserId(1));
|
||||
}
|
||||
|
||||
/// Edits to a large input reach a peer as deltas. A peer that joins later gets every blob with its sync.
|
||||
#[test]
|
||||
fn blobs_reach_peers_as_deltas_and_with_a_sync() {
|
||||
use document_container::AsyncContainer;
|
||||
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 is missing is dropped. The blob is then fetched in full like a missing resource.
|
||||
#[test]
|
||||
fn a_blob_without_its_base_is_asked_for_in_full() {
|
||||
use document_graph_storage::blob::BLOB_THRESHOLD;
|
||||
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 with the same hash
|
||||
let resource = ResourceHash::from(latest);
|
||||
|
||||
// Only the delta record of the edit arrives, without the full record of its base
|
||||
let mut reader = document(2);
|
||||
let records = author.blob_records().into_iter().filter(|record| record.hash == latest).collect();
|
||||
reader.apply_remote_hot_ops(hot_ops).expect("apply");
|
||||
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));
|
||||
}
|
||||
@@ -74,4 +74,6 @@ pub mod delta {
|
||||
/// Marks the last delta of a user interaction, so the undo cursor steps per-interaction, not per-delta. Also set on
|
||||
/// the last hot op of an interaction.
|
||||
pub const INTERACTION_END: &str = "interaction_end";
|
||||
/// What the user did in an interaction, such as a tool action. Set on the last hot op and the last delta.
|
||||
pub const ACTION: &str = "action";
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
//! Large node input values are stored as blobs outside the registry, history and hot log. The input keeps a
|
||||
//! [`Value::Blob`] with the hash. Blob bytes are the postcard encoding of the value, so equal values share one blob.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fmt;
|
||||
|
||||
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 to store, with the base blob that each one 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)
|
||||
}
|
||||
}
|
||||
|
||||
/// Blobs are content addressed like resources, so a peer can fetch a blob through the resource path.
|
||||
impl From<BlobHash> for ResourceHash {
|
||||
fn from(hash: BlobHash) -> Self {
|
||||
hash.0
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 a blob. The blob bytes are added to `bytes`.
|
||||
pub fn move_into_blob(&mut self, bytes: &mut BlobBytes) {
|
||||
let NodeInput::Value { value, .. } = self else { return };
|
||||
if matches!(value, Value::Blob(_)) {
|
||||
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, .. } => {
|
||||
new_input.move_into_blob(bytes);
|
||||
return;
|
||||
}
|
||||
RegistryDelta::AddNode { node, .. } | RegistryDelta::RemoveNode { snapshot: node, .. } => &mut node.inputs,
|
||||
RegistryDelta::SetNodeInputs { inputs, .. } => inputs,
|
||||
_ => return,
|
||||
};
|
||||
|
||||
for slot in slots {
|
||||
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 that live nodes and tombstones of removed nodes name.
|
||||
pub fn blob_hashes(&self) -> impl Iterator<Item = BlobHash> + '_ {
|
||||
let live = self.node_instances.values();
|
||||
let removed = self.removed_nodes.values().map(|tombstone| &tombstone.content);
|
||||
live.chain(removed).flat_map(|node| node.inputs()).filter_map(|slot| slot.input.blob())
|
||||
}
|
||||
|
||||
/// The base of each blob that `ops` write. The base is the blob that the same input slot held before.
|
||||
pub fn blob_bases(&self, ops: &[RegistryDelta]) -> HashMap<BlobHash, BlobHash> {
|
||||
let mut latest: HashMap<(NodeId, usize), BlobHash> = HashMap::new();
|
||||
let mut written = HashSet::new();
|
||||
let mut bases = HashMap::new();
|
||||
|
||||
let mut write = |id: NodeId, index: usize, input: &NodeInput| {
|
||||
let Some(hash) = input.blob() else { return };
|
||||
|
||||
// Only the first write of a blob takes a base. This keeps bases acyclic
|
||||
if written.insert(hash)
|
||||
&& let Some(previous) = latest.get(&(id, index)).copied().or_else(|| self.input_blob(id, index))
|
||||
&& 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
|
||||
}
|
||||
|
||||
/// Like [`blob_bases`](Self::blob_bases), but compares the slots of `self` with the same slots in `previous`.
|
||||
pub fn blob_bases_since(&self, previous: &Registry) -> HashMap<BlobHash, BlobHash> {
|
||||
let mut nodes: Vec<_> = self.node_instances.iter().collect();
|
||||
nodes.sort_unstable_by_key(|(id, _)| **id);
|
||||
|
||||
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.input_blob(*id, index)
|
||||
&& base != hash
|
||||
{
|
||||
bases.insert(hash, base);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bases
|
||||
}
|
||||
|
||||
fn input_blob(&self, id: NodeId, index: usize) -> Option<BlobHash> {
|
||||
self.node_instances.get(&id)?.inputs().get(index)?.input.blob()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
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, BlobHash, Delta, InputSlot, NodeField, NodeInput, PeerId, Prior, RegistryDelta, Rev, TimeStamp, Tombstone, Value, attr, compute_rev};
|
||||
use crate::{Attributes, Delta, PeerId, Prior, RegistryDelta, Rev, TimeStamp, Value, attr, compute_rev};
|
||||
use graphene_resource::ResourceHash;
|
||||
|
||||
impl Delta {
|
||||
@@ -55,6 +55,14 @@ impl Delta {
|
||||
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == Value::Bool(true))
|
||||
}
|
||||
|
||||
/// What the user did in the interaction this delta ends, if it was named.
|
||||
pub fn action(&self) -> Option<&str> {
|
||||
match &self.attributes.get(attr::delta::ACTION)?.value {
|
||||
Value::Str(action) => Some(action),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Take over `original`'s annotations and retirement time, for a delta that replaces it in rewritten history.
|
||||
pub fn carry_annotations(&mut self, original: &Delta) {
|
||||
self.attributes = original.attributes.clone();
|
||||
@@ -78,28 +86,6 @@ impl Delta {
|
||||
pub fn has_valid_id(&self) -> bool {
|
||||
self.id == self.recomputed_id()
|
||||
}
|
||||
|
||||
/// The blobs that the op writes or that its priors restore.
|
||||
pub(crate) fn blob_hashes(&self) -> impl Iterator<Item = BlobHash> + '_ {
|
||||
let prior_slots = self.reverse.iter().flat_map(|prior| match prior {
|
||||
Prior::Node { node, .. }
|
||||
| Prior::RemovedNode {
|
||||
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 {
|
||||
@@ -111,18 +97,6 @@ impl RegistryDelta {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The blobs in the input values that the op writes.
|
||||
pub(crate) fn blob_hashes(&self) -> impl Iterator<Item = BlobHash> + '_ {
|
||||
let (input, slots): (Option<&NodeInput>, &[InputSlot]) = match self {
|
||||
RegistryDelta::ChangeNodeInput { new_input, .. } => (Some(new_input), &[]),
|
||||
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,7 +9,6 @@ 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,
|
||||
@@ -119,8 +118,6 @@ pub struct RuntimeConversion {
|
||||
pub registry: Registry,
|
||||
pub declaration_bytes: DeclarationBytes,
|
||||
pub declarations: crate::Declarations,
|
||||
/// The bytes of the blobs that the registry names. The caller stores them.
|
||||
pub blob_bytes: BlobBytes,
|
||||
/// The storage `NetworkId` of each runtime network location, to key per-network view state in `session.json`.
|
||||
pub network_ids: HashMap<NetworkLocation, NetworkId>,
|
||||
}
|
||||
@@ -168,9 +165,8 @@ pub fn decode_declaration(bytes: &[u8]) -> Result<ProtoNode, String> {
|
||||
impl Registry {
|
||||
/// Convenience wrapper returning only the registry (declaration bytes discarded). For callers
|
||||
/// that don't persist a byte store — e.g. the graph-only `TryFrom` and value-comparison tests.
|
||||
/// Large values stay inline, so the registry converts back without blob bytes.
|
||||
pub fn from_runtime_with_metadata<M: NodeMetadataSource>(node_network: &NodeNetwork, metadata: &M, resources: &graphene_resource::ResourceRegistry, peer: PeerId) -> Result<Self, ConversionError> {
|
||||
Ok(Self::convert_from_runtime_inline(node_network, metadata, resources, peer)?.registry)
|
||||
Ok(Self::convert_from_runtime(node_network, metadata, resources, peer)?.registry)
|
||||
}
|
||||
|
||||
/// Full conversion: returns the registry and the extracted declaration bytes for the caller to
|
||||
@@ -180,18 +176,6 @@ impl Registry {
|
||||
metadata: &M,
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
peer: PeerId,
|
||||
) -> Result<RuntimeConversion, ConversionError> {
|
||||
let mut conversion = Self::convert_from_runtime_inline(node_network, metadata, resources, peer)?;
|
||||
conversion.registry.move_values_into_blobs(&mut conversion.blob_bytes);
|
||||
Ok(conversion)
|
||||
}
|
||||
|
||||
/// [`convert_from_runtime`](Self::convert_from_runtime) without moving large values into blobs.
|
||||
pub(crate) fn convert_from_runtime_inline<M: NodeMetadataSource>(
|
||||
node_network: &NodeNetwork,
|
||||
metadata: &M,
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
peer: PeerId,
|
||||
) -> Result<RuntimeConversion, ConversionError> {
|
||||
let mut registry = Registry::default();
|
||||
let mut ctx = ConversionContext {
|
||||
@@ -232,7 +216,6 @@ impl Registry {
|
||||
registry,
|
||||
declaration_bytes: ctx.declaration_bytes,
|
||||
declarations: ctx.declarations,
|
||||
blob_bytes: BlobBytes::new(),
|
||||
network_ids: ctx.network_ids,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
pub use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
pub mod attributes;
|
||||
pub mod blob;
|
||||
pub mod crdt;
|
||||
pub mod delta;
|
||||
pub mod document;
|
||||
@@ -11,6 +10,7 @@ pub mod ids;
|
||||
pub mod model;
|
||||
mod prior;
|
||||
pub mod registry;
|
||||
mod repair;
|
||||
pub mod resources;
|
||||
mod schema;
|
||||
pub mod session;
|
||||
@@ -50,6 +50,7 @@ pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProje
|
||||
mod tests {
|
||||
mod bookkeeping;
|
||||
mod crdt;
|
||||
mod history_simulation;
|
||||
mod projection;
|
||||
mod round_trip;
|
||||
mod sessions;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::registry::attributes_value_equal;
|
||||
use crate::{Attributes, BlobHash, Implementation, InputSlot, Network, NetworkId, Node, NodeInput, TimeStamp, Value};
|
||||
use crate::{Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeInput, TimeStamp, Value};
|
||||
|
||||
impl Node {
|
||||
pub fn implementation(&self) -> &Implementation {
|
||||
@@ -64,16 +64,6 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeInput {
|
||||
/// The blob hash of a value input that holds a [`Value::Blob`].
|
||||
pub fn blob(&self) -> Option<BlobHash> {
|
||||
match self {
|
||||
NodeInput::Value { value: Value::Blob(hash), .. } => Some(*hash),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl InputSlot {
|
||||
/// A slot holding nothing, stamped `timestamp`.
|
||||
pub fn unset(timestamp: TimeStamp) -> Self {
|
||||
@@ -142,7 +132,8 @@ mod tests {
|
||||
assert_eq!(tagged, graph_craft::document::value::TaggedValue::None);
|
||||
}
|
||||
|
||||
/// A `SetExport(None)` truncation leaves a trailing empty slot, which doesn't change the network's value.
|
||||
/// A `SetExport(None)` truncation leaves a trailing empty slot. Such a network is value-equal to
|
||||
/// the same network without that slot, so the soak oracle doesn't false-report drift.
|
||||
#[test]
|
||||
fn trailing_empty_export_slot_is_value_equal() {
|
||||
let compact = Network {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{Attributes, Implementation, NetworkId, NodeId, ROOT_NETWORK, Registry, ResourceStore, Tombstone};
|
||||
use crate::{Attributes, Implementation, NetworkId, NodeId, PeerId, ROOT_NETWORK, Registry, ResourceId, ResourceStore, SourceKey, TimeStamp, Tombstone};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
impl Registry {
|
||||
@@ -97,6 +97,36 @@ impl Registry {
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// True if the relative timestamp order on every shared timestamped slot agrees across
|
||||
/// the two registries. Catches LWW-bookkeeping bugs that `value_equal` deliberately ignores.
|
||||
///
|
||||
/// For every pair of shared keys (a, b), checks that `self[a].cmp(self[b])` and
|
||||
/// `other[a].cmp(other[b])` are compatible: `Equal` on either side is always compatible;
|
||||
/// otherwise both sides must agree on direction. Equality on one side imposes no order, so
|
||||
/// a registry with all-equal timestamps trivially passes against any other.
|
||||
///
|
||||
/// Slots present in only one registry are skipped. O(N²) in the number of shared timestamped
|
||||
/// slots; intended for debug-only use.
|
||||
pub fn order_consistent(&self, other: &Self) -> bool {
|
||||
let self_stamps = collect_timestamps(self);
|
||||
let other_stamps = collect_timestamps(other);
|
||||
|
||||
let shared: Vec<(TimestampKey, TimeStamp, TimeStamp)> = self_stamps.into_iter().filter_map(|(key, ts)| other_stamps.get(&key).map(|other_ts| (key, ts, *other_ts))).collect();
|
||||
|
||||
for i in 0..shared.len() {
|
||||
for j in (i + 1)..shared.len() {
|
||||
let self_order = shared[i].1.cmp(&shared[j].1);
|
||||
let other_order = shared[i].2.cmp(&shared[j].2);
|
||||
use std::cmp::Ordering::*;
|
||||
let compatible = matches!((self_order, other_order), (Equal, _) | (_, Equal) | (Less, Less) | (Greater, Greater));
|
||||
if !compatible {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
|
||||
@@ -120,3 +150,87 @@ pub(crate) fn resources_value_equal(a: &ResourceStore, b: &ResourceStore) -> boo
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Stable identity for any timestamp in a `Registry`, tombstoned content and existence stamps included. Used by
|
||||
/// `order_consistent`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
enum TimestampKey {
|
||||
/// A whole-entity stamp under its field name: presence, a shape or floor, a removal.
|
||||
Node(NodeId, &'static str),
|
||||
NodeInput(NodeId, usize),
|
||||
NodeInputFloor(NodeId, usize),
|
||||
NodeInputAttribute(NodeId, usize, String),
|
||||
NodeAttribute(NodeId, String),
|
||||
Network(NetworkId, &'static str),
|
||||
NetworkExport(NetworkId, usize),
|
||||
NetworkAttribute(NetworkId, String),
|
||||
DocumentAttribute(String),
|
||||
Resource(ResourceId, &'static str),
|
||||
ResourceSource(ResourceId, SourceKey),
|
||||
Document(&'static str),
|
||||
PeerRegistration(PeerId),
|
||||
}
|
||||
|
||||
fn collect_timestamps(registry: &Registry) -> HashMap<TimestampKey, TimeStamp> {
|
||||
let mut out = HashMap::new();
|
||||
let nodes = registry.node_instances.iter().chain(registry.removed_nodes.iter().map(|(id, mark)| (id, &mark.content)));
|
||||
for (&id, node) in nodes {
|
||||
for (field, timestamp) in [
|
||||
("presence", node.presence),
|
||||
("network", node.network_timestamp),
|
||||
("inputs", node.inputs_timestamp),
|
||||
("implementation", node.implementation_timestamp),
|
||||
("attributes", node.attributes.floor()),
|
||||
] {
|
||||
out.insert(TimestampKey::Node(id, field), timestamp);
|
||||
}
|
||||
for (i, slot) in node.inputs.iter().enumerate() {
|
||||
out.insert(TimestampKey::NodeInput(id, i), slot.timestamp);
|
||||
out.insert(TimestampKey::NodeInputFloor(id, i), slot.attributes.floor());
|
||||
for (key, value) in &slot.attributes {
|
||||
out.insert(TimestampKey::NodeInputAttribute(id, i, key.clone()), value.timestamp);
|
||||
}
|
||||
}
|
||||
for (key, value) in &node.attributes {
|
||||
out.insert(TimestampKey::NodeAttribute(id, key.clone()), value.timestamp);
|
||||
}
|
||||
}
|
||||
let networks = registry.networks.iter().chain(registry.removed_networks.iter().map(|(id, mark)| (id, &mark.content)));
|
||||
for (&id, network) in networks {
|
||||
for (field, timestamp) in [("presence", network.presence), ("exports", network.exports_timestamp), ("attributes", network.attributes.floor())] {
|
||||
out.insert(TimestampKey::Network(id, field), timestamp);
|
||||
}
|
||||
for (i, slot) in network.exports.iter().enumerate() {
|
||||
out.insert(TimestampKey::NetworkExport(id, i), slot.timestamp);
|
||||
}
|
||||
for (key, value) in &network.attributes {
|
||||
out.insert(TimestampKey::NetworkAttribute(id, key.clone()), value.timestamp);
|
||||
}
|
||||
}
|
||||
out.insert(TimestampKey::Document("attributes"), registry.attributes.floor());
|
||||
for (key, value) in ®istry.attributes {
|
||||
out.insert(TimestampKey::DocumentAttribute(key.clone()), value.timestamp);
|
||||
}
|
||||
let resources = registry.resources.iter().chain(registry.removed_resources.iter().map(|(id, mark)| (id, &mark.content)));
|
||||
for (&id, entry) in resources {
|
||||
for (field, timestamp) in [("presence", entry.presence), ("hash", entry.hash_timestamp), ("sources", entry.sources_timestamp)] {
|
||||
out.insert(TimestampKey::Resource(id, field), timestamp);
|
||||
}
|
||||
for (source_key, source_value) in &entry.sources {
|
||||
out.insert(TimestampKey::ResourceSource(id, *source_key), source_value.timestamp);
|
||||
}
|
||||
}
|
||||
for (&id, mark) in ®istry.removed_nodes {
|
||||
out.insert(TimestampKey::Node(id, "removed"), mark.timestamp);
|
||||
}
|
||||
for (&id, mark) in ®istry.removed_networks {
|
||||
out.insert(TimestampKey::Network(id, "removed"), mark.timestamp);
|
||||
}
|
||||
for (&id, mark) in ®istry.removed_resources {
|
||||
out.insert(TimestampKey::Resource(id, "removed"), mark.timestamp);
|
||||
}
|
||||
for (&peer, registration) in ®istry.peer_users {
|
||||
out.insert(TimestampKey::PeerRegistration(peer), registration.timestamp);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
//! Repairs the graph after steps are replayed onto a line that changed since they were made, as bringing a step back
|
||||
//! or removing one does. Replayed writes keep their stamps, so a slot written since keeps the newer value, which can
|
||||
//! leave an input naming a removed node, two nodes on one, or a node nothing reaches any more.
|
||||
//!
|
||||
//! Nodes connected through their primary inputs form chains, like a stack of layers or a node feeding the next. Each
|
||||
//! chain hangs off a head slot: an export, or an input past the primary one. The repair rebuilds every chain from the
|
||||
//! order the line had before the replay and the order the replayed step left it in when it was made, so the step's
|
||||
//! own changes land on the chains as they are now.
|
||||
|
||||
use crate::{NetworkId, NodeId, NodeInput, Registry, RegistryDelta};
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
|
||||
/// Each node's network and newest primary input anywhere in history, for nodes this line no longer or never had.
|
||||
pub(crate) type KnownInputs = HashMap<NodeId, (NetworkId, NodeInput)>;
|
||||
|
||||
/// A slot that can name a node.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
enum Slot {
|
||||
Input(NodeId, u32),
|
||||
Export(NetworkId, u32),
|
||||
}
|
||||
|
||||
/// A chain's nodes from its head down, and what the last one rests on.
|
||||
struct Chain {
|
||||
head: Slot,
|
||||
nodes: Vec<NodeId>,
|
||||
bottom: Option<NodeInput>,
|
||||
}
|
||||
|
||||
/// The ops that repair `registry`, which is `before` with `replayed` folded in. `intended` is the document as the
|
||||
/// replayed step left it when it was made, and `gone` the nodes it must not have, as those the step deleted.
|
||||
/// - A node in `gone`, or in neither `before` nor `intended`, is removed. A newer write to a node revives it over an
|
||||
/// older removal, as one made on the line since does over a deletion brought back.
|
||||
/// - Every chain keeps the nodes it had before, in their order, except those the replayed step moved, which take
|
||||
/// their place from `intended`, after the node they followed there. A node the step added lands the same way.
|
||||
/// - A node on no chain any more, which was on one, goes back where it was.
|
||||
/// - An input naming a removed node takes that node's primary input instead, as deleting a node reconnects what it
|
||||
/// sat between. A node this line never had counts as removed, with the primary input `known` gives it.
|
||||
pub(crate) fn repair_ops(before: &Registry, registry: &Registry, intended: &Registry, replayed: &[RegistryDelta], gone: &HashSet<NodeId>, known: &KnownInputs) -> Vec<RegistryDelta> {
|
||||
let mut registry = registry.clone();
|
||||
let mut ops = Vec::new();
|
||||
|
||||
let mut unwanted: Vec<NodeId> = registry
|
||||
.node_instances
|
||||
.keys()
|
||||
.filter(|id| gone.contains(id) || (!before.node_instances.contains_key(id) && !intended.node_instances.contains_key(id)))
|
||||
.copied()
|
||||
.collect();
|
||||
unwanted.sort();
|
||||
for id in unwanted {
|
||||
if let Some(snapshot) = registry.node_instances.remove(&id) {
|
||||
ops.push(RegistryDelta::RemoveNode { id, snapshot });
|
||||
}
|
||||
}
|
||||
|
||||
let live = |id: &NodeId| registry.node_instances.contains_key(id);
|
||||
let placed_by_step: HashSet<NodeId> = replayed.iter().flat_map(placed_nodes).filter(live).collect();
|
||||
|
||||
let heads: BTreeSet<Slot> = [before, ®istry, intended].into_iter().flat_map(head_slots).filter(|&slot| owner_is_live(®istry, slot)).collect();
|
||||
let was_in = |registry: &Registry| -> HashMap<NodeId, Slot> { heads.iter().flat_map(|&head| chain(registry, head).nodes.into_iter().map(move |id| (id, head))).collect() };
|
||||
let (was_before, was_intended) = (was_in(before), was_in(intended));
|
||||
// Where each node goes: where the step put it if it placed it, else where it was
|
||||
let home = |id: &NodeId| match placed_by_step.contains(id) {
|
||||
true => was_intended.get(id).or(was_before.get(id)),
|
||||
false => was_before.get(id).or(was_intended.get(id)),
|
||||
};
|
||||
|
||||
let mut chains = Vec::new();
|
||||
let mut taken = HashSet::new();
|
||||
for &head in &heads {
|
||||
let owner = match head {
|
||||
Slot::Input(owner, _) => Some(owner),
|
||||
Slot::Export(..) => None,
|
||||
};
|
||||
let fits = |id: &NodeId| live(id) && Some(*id) != owner && home(id) == Some(&head);
|
||||
let earlier = chain(before, head);
|
||||
let wanted = chain(intended, head);
|
||||
// A node the step placed counts as moved when it sits on the other side of a node both orders have
|
||||
let common: Vec<NodeId> = earlier.nodes.iter().copied().filter(|id| live(id) && wanted.nodes.contains(id)).collect();
|
||||
let rank = |order: &[NodeId], id: &NodeId| order.iter().position(|node| node == id);
|
||||
let moved = |id: &NodeId| {
|
||||
placed_by_step.contains(id)
|
||||
&& common.contains(id)
|
||||
&& common
|
||||
.iter()
|
||||
.any(|other| other != id && (rank(&earlier.nodes, id) < rank(&earlier.nodes, other)) != (rank(&wanted.nodes, id) < rank(&wanted.nodes, other)))
|
||||
};
|
||||
let mut nodes: Vec<NodeId> = earlier.nodes.iter().copied().filter(|id| fits(id) && !moved(id)).collect();
|
||||
for (position, id) in wanted.nodes.iter().enumerate() {
|
||||
if nodes.contains(id) || !fits(id) {
|
||||
continue;
|
||||
}
|
||||
let after = wanted.nodes[..position].iter().rev().find_map(|above| nodes.iter().position(|node| node == above));
|
||||
nodes.insert(after.map_or(0, |index| index + 1), *id);
|
||||
}
|
||||
// What the chain rests on, as long as nothing else sits on it
|
||||
let bottom = [earlier.bottom, wanted.bottom].into_iter().flatten().find(|bottom| match bottom {
|
||||
NodeInput::Node { id, .. } => live(id) && home(id).is_none(),
|
||||
_ => true,
|
||||
});
|
||||
taken.extend(nodes.iter().copied());
|
||||
chains.push(Chain { head, nodes, bottom });
|
||||
}
|
||||
|
||||
for chain in &chains {
|
||||
let mut slot = chain.head;
|
||||
for &id in &chain.nodes {
|
||||
set(&mut registry, &mut ops, slot, Some(on(id)));
|
||||
slot = Slot::Input(id, 0);
|
||||
}
|
||||
if let Some(bottom) = &chain.bottom {
|
||||
set(&mut registry, &mut ops, slot, Some(bottom.clone()));
|
||||
} else if let Some(NodeInput::Node { id, .. }) = slot_value(®istry, slot)
|
||||
&& (taken.contains(&id) || !registry.node_instances.contains_key(&id))
|
||||
{
|
||||
// Resting on a node another chain holds, or one gone, it rests on nothing instead
|
||||
let cleared = match slot {
|
||||
Slot::Export(..) => None,
|
||||
Slot::Input(..) => reconnect(®istry, id, slot_network(®istry, slot), known).filter(|input| !matches!(input, NodeInput::Node { .. })),
|
||||
};
|
||||
if cleared.is_some() || matches!(slot, Slot::Export(..)) {
|
||||
set(&mut registry, &mut ops, slot, cleared);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Inputs off every chain still naming a removed node
|
||||
for (slot, named) in slots(®istry) {
|
||||
if registry.node_instances.contains_key(&named) {
|
||||
continue;
|
||||
}
|
||||
let reconnected = reconnect(®istry, named, slot_network(®istry, slot), known).or_else(|| slot_value(before, slot).filter(|earlier| !names_missing(®istry, earlier)));
|
||||
if reconnected.is_some() || matches!(slot, Slot::Export(..)) {
|
||||
set(&mut registry, &mut ops, slot, reconnected);
|
||||
}
|
||||
}
|
||||
ops
|
||||
}
|
||||
|
||||
fn on(id: NodeId) -> NodeInput {
|
||||
NodeInput::Node { id, index: 0 }
|
||||
}
|
||||
|
||||
fn names_missing(registry: &Registry, input: &NodeInput) -> bool {
|
||||
matches!(input, NodeInput::Node { id, .. } if !registry.node_instances.contains_key(id))
|
||||
}
|
||||
|
||||
/// The nodes a write places in a slot, or adds.
|
||||
fn placed_nodes(op: &RegistryDelta) -> Vec<NodeId> {
|
||||
match op {
|
||||
RegistryDelta::AddNode { id, .. } => vec![*id],
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
|
||||
let placed = match new_input {
|
||||
NodeInput::Node { id: placed, .. } => Some(*placed),
|
||||
_ => None,
|
||||
};
|
||||
(*index == 0).then_some(*id).into_iter().chain(placed).collect()
|
||||
}
|
||||
RegistryDelta::SetNetworkExport {
|
||||
export: Some(NodeInput::Node { id, .. }),
|
||||
..
|
||||
} => vec![*id],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every slot naming a node, in a fixed order.
|
||||
fn slots(registry: &Registry) -> Vec<(Slot, NodeId)> {
|
||||
let mut slots = Vec::new();
|
||||
for (&id, node) in ®istry.node_instances {
|
||||
for (index, slot) in node.inputs.iter().enumerate() {
|
||||
if let NodeInput::Node { id: named, .. } = slot.input {
|
||||
slots.push((Slot::Input(id, index as u32), named));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (&id, network) in ®istry.networks {
|
||||
for (index, slot) in network.exports.iter().enumerate() {
|
||||
if let Some(NodeInput::Node { id: named, .. }) = slot.target {
|
||||
slots.push((Slot::Export(id, index as u32), named));
|
||||
}
|
||||
}
|
||||
}
|
||||
slots.sort();
|
||||
slots
|
||||
}
|
||||
|
||||
/// The slots heading a chain: exports and inputs past the primary one, naming a node.
|
||||
fn head_slots(registry: &Registry) -> impl Iterator<Item = Slot> + '_ {
|
||||
slots(registry).into_iter().map(|(slot, _)| slot).filter(|slot| !matches!(slot, Slot::Input(_, 0)))
|
||||
}
|
||||
|
||||
fn owner_is_live(registry: &Registry, slot: Slot) -> bool {
|
||||
match slot {
|
||||
Slot::Input(id, _) => registry.node_instances.contains_key(&id),
|
||||
Slot::Export(id, _) => registry.networks.contains_key(&id),
|
||||
}
|
||||
}
|
||||
|
||||
/// The chain hanging off `head` in `registry`.
|
||||
fn chain(registry: &Registry, head: Slot) -> Chain {
|
||||
let mut nodes = Vec::new();
|
||||
let mut below = slot_value(registry, head);
|
||||
while let Some(NodeInput::Node { id, .. }) = below {
|
||||
if nodes.contains(&id) || !registry.node_instances.contains_key(&id) {
|
||||
return Chain { head, nodes, bottom: None };
|
||||
}
|
||||
nodes.push(id);
|
||||
below = slot_value(registry, Slot::Input(id, 0));
|
||||
}
|
||||
Chain { head, nodes, bottom: below }
|
||||
}
|
||||
|
||||
fn slot_network(registry: &Registry, slot: Slot) -> Option<NetworkId> {
|
||||
match slot {
|
||||
Slot::Input(id, _) => registry.node_instances.get(&id).map(|node| node.network),
|
||||
Slot::Export(id, _) => Some(id),
|
||||
}
|
||||
}
|
||||
|
||||
fn slot_value(registry: &Registry, slot: Slot) -> Option<NodeInput> {
|
||||
match slot {
|
||||
Slot::Input(id, index) => registry.node_instances.get(&id)?.inputs.get(index as usize).map(|slot| slot.input.clone()),
|
||||
Slot::Export(id, index) => registry.networks.get(&id)?.exports.get(index as usize)?.target.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a removed node's primary input led to, through removed nodes, staying in `network`. None when the chain ends
|
||||
/// at a node never seen or in another network.
|
||||
fn reconnect(registry: &Registry, removed: NodeId, network: Option<NetworkId>, known: &KnownInputs) -> Option<NodeInput> {
|
||||
let mut visited = HashSet::new();
|
||||
let mut current = removed;
|
||||
loop {
|
||||
if !visited.insert(current) {
|
||||
return None;
|
||||
}
|
||||
let (in_network, input) = match registry.removed_nodes.get(¤t) {
|
||||
Some(tombstone) => (tombstone.content.network, tombstone.content.inputs.first()?.input.clone()),
|
||||
None => known.get(¤t).cloned()?,
|
||||
};
|
||||
if Some(in_network) != network {
|
||||
return None;
|
||||
}
|
||||
match input {
|
||||
NodeInput::Node { id, .. } if !registry.node_instances.contains_key(&id) => current = id,
|
||||
NodeInput::Node { id, .. } if Some(registry.node_instances[&id].network) != network => return None,
|
||||
input => return Some(input),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the op setting `slot` to `input`, None clearing an export, and applies it to the scratch `registry`. Writes
|
||||
/// nothing when the slot holds it already.
|
||||
fn set(registry: &mut Registry, ops: &mut Vec<RegistryDelta>, slot: Slot, input: Option<NodeInput>) {
|
||||
if slot_value(registry, slot) == input {
|
||||
return;
|
||||
}
|
||||
match slot {
|
||||
Slot::Input(id, index) => {
|
||||
let Some(input) = input else { return };
|
||||
if let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) {
|
||||
slot.input = input.clone();
|
||||
}
|
||||
ops.push(RegistryDelta::ChangeNodeInput { id, index, new_input: input });
|
||||
}
|
||||
Slot::Export(id, index) => {
|
||||
if let Some(slot) = registry.networks.get_mut(&id).and_then(|network| network.exports.get_mut(index as usize)) {
|
||||
slot.target = input.clone();
|
||||
}
|
||||
ops.push(RegistryDelta::SetNetworkExport { id, index, export: input });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
use graphene_resource::ResourceHash;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Stable, document-scoped identity for a node. Minted as a truncated `blake3(peer, counter)` so it
|
||||
@@ -13,11 +12,6 @@ pub struct NodeId(pub u64);
|
||||
#[serde(transparent)]
|
||||
pub struct NetworkId(pub u64);
|
||||
|
||||
/// The content hash of a blob, which stores a large node input value.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct BlobHash(pub ResourceHash);
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use crate::BlobHash;
|
||||
use graphene_resource::ResourceHash;
|
||||
use serde::de::{self, MapAccess, SeqAccess, Visitor};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::fmt;
|
||||
@@ -14,8 +12,6 @@ pub enum Value {
|
||||
Str(String),
|
||||
Array(Vec<Value>),
|
||||
Object(Vec<(String, Value)>),
|
||||
/// A large node input value that is stored as a blob. See [`crate::blob`].
|
||||
Blob(BlobHash),
|
||||
}
|
||||
|
||||
// Using `Serializer::is_human_readable` to determine whether to serialize tagged.
|
||||
@@ -33,7 +29,6 @@ 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))),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,7 +97,7 @@ impl<'de> Deserialize<'de> for Value {
|
||||
}
|
||||
dedup
|
||||
});
|
||||
Ok(Value::from_object(object))
|
||||
Ok(Value::Object(object))
|
||||
}
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str("a valid Value")
|
||||
@@ -111,20 +106,3 @@ impl<'de> Deserialize<'de> for Value {
|
||||
deserializer.deserialize_any(Untagged)
|
||||
}
|
||||
}
|
||||
|
||||
impl Value {
|
||||
/// In human-readable formats a [`Value::Blob`] is written as an object with only this key. The key is reserved.
|
||||
/// Such an object with a hash string is read back as a blob.
|
||||
pub(crate) const BLOB_KEY: &str = "$blob";
|
||||
|
||||
/// An object, or a [`Value::Blob`] if the object has the form of one.
|
||||
pub(crate) fn from_object(object: Vec<(String, Value)>) -> Self {
|
||||
if let [(key, Value::Str(hex))] = object.as_slice()
|
||||
&& key == Self::BLOB_KEY
|
||||
&& let Ok(hash) = ResourceHash::try_from(hex.as_str())
|
||||
{
|
||||
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, BlobHash, 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, 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};
|
||||
@@ -24,6 +24,8 @@ pub struct Session {
|
||||
/// What the ops this peer took back named. A retirement racing the take-back may still name them, and this peer may
|
||||
/// hold the only copy, so they stay garbage collection roots for the life of the session.
|
||||
taken_back_resources: HashSet<ResourceHash>,
|
||||
/// What this peer's open interaction is doing, for its closing marker to carry.
|
||||
action: Option<String>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -47,6 +49,7 @@ impl Session {
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
taken_back_resources: HashSet::new(),
|
||||
action: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,9 +102,7 @@ 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.
|
||||
///
|
||||
/// Only for tests because it does not store the blob bytes. `Gdd::stage_runtime_snapshot` does.
|
||||
#[cfg(test)]
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub fn stage_from_runtime<M: NodeMetadataSource>(
|
||||
&mut self,
|
||||
network: &graph_craft::document::NodeNetwork,
|
||||
@@ -109,25 +110,20 @@ impl Session {
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
) -> Result<(Vec<HotOp>, from_runtime::RuntimeConversion), CommitError> {
|
||||
let conversion = Registry::convert_from_runtime(network, metadata, resources, self.document.peer)?;
|
||||
let ops = self.runtime_diff(&conversion.registry);
|
||||
let hot_ops = self.stage_runtime_diff(ops, conversion.registry.clone())?;
|
||||
Ok((hot_ops, conversion))
|
||||
}
|
||||
let rendered;
|
||||
let base = match &self.runtime_base {
|
||||
Some(base) => base,
|
||||
None => {
|
||||
rendered = self.document.working_registry.as_rendered();
|
||||
&rendered
|
||||
}
|
||||
};
|
||||
let ops = crate::delta::compute_deltas(base, &conversion.registry);
|
||||
|
||||
/// The ops from the last staged runtime state to `registry`, a fresh conversion of the runtime network.
|
||||
pub fn runtime_diff(&self, registry: &Registry) -> Vec<RegistryDelta> {
|
||||
match &self.runtime_base {
|
||||
Some(base) => crate::delta::compute_deltas(base, registry),
|
||||
None => crate::delta::compute_deltas(&self.document.working_registry.as_rendered(), registry),
|
||||
}
|
||||
}
|
||||
|
||||
/// Stage the [`runtime_diff`](Self::runtime_diff) ops of `registry` and keep `registry` as the last runtime state.
|
||||
pub fn stage_runtime_diff(&mut self, ops: Vec<RegistryDelta>, registry: Registry) -> Result<Vec<HotOp>, CrdtError> {
|
||||
// Lenient since a peer's concurrent write may have reshaped what the diff names.
|
||||
let hot_ops = self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())), ApplyMode::Idempotent)?;
|
||||
self.runtime_base = Some(registry);
|
||||
Ok(hot_ops)
|
||||
self.runtime_base = Some(conversion.registry.clone());
|
||||
Ok((hot_ops, conversion))
|
||||
}
|
||||
|
||||
pub fn mark_runtime_current(&mut self) {
|
||||
@@ -138,7 +134,7 @@ impl Session {
|
||||
/// It depends only on the network structure, not on resources or declarations.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub fn network_ids<M: NodeMetadataSource>(&self, network: &graph_craft::document::NodeNetwork, metadata: &M) -> Result<HashMap<graph_craft::document::NetworkLocation, NetworkId>, CommitError> {
|
||||
let conversion = Registry::convert_from_runtime_inline(network, metadata, &graphene_resource::ResourceRegistry::new(), self.document.peer)?;
|
||||
let conversion = Registry::convert_from_runtime(network, metadata, &graphene_resource::ResourceRegistry::new(), self.document.peer)?;
|
||||
Ok(conversion.network_ids)
|
||||
}
|
||||
|
||||
@@ -343,6 +339,7 @@ impl Session {
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
taken_back_resources: HashSet::new(),
|
||||
action: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -393,6 +390,10 @@ impl Session {
|
||||
return Ok(None);
|
||||
}
|
||||
self.runtime_base = None;
|
||||
// The name belongs to the open interaction being taken back
|
||||
if closed_before == own.len() {
|
||||
self.action = None;
|
||||
}
|
||||
let (touched, taken) = self.document.retract_hot_ops(&ids);
|
||||
self.taken_back_resources.extend(taken.iter().filter_map(|hot_op| hot_op.op.resource_hash()));
|
||||
let ops = taken.into_iter().map(|hot_op| hot_op.op).filter(|op| !matches!(op, RegistryDelta::Meta)).collect();
|
||||
@@ -437,23 +438,70 @@ impl Session {
|
||||
}
|
||||
let position = newest_first.iter().position(|delta| delta.id == undone).ok_or(CrdtError::NotFoundInHistory(undone))?;
|
||||
|
||||
// Minted on a scratch fold first, so a failing copy changes nothing.
|
||||
// Minted on a scratch fold first, so a failing copy changes nothing. Each copied interaction ends with the
|
||||
// repairs it needs on the changed line.
|
||||
let mut scratch = self.fold_scratch_at(Some(base))?;
|
||||
let mut copies = Vec::with_capacity(position);
|
||||
// Per copy, the delta it carries attributes from, and the repair now closing that delta's interaction
|
||||
let mut sources: Vec<(Option<&Delta>, Option<Rev>)> = Vec::with_capacity(position);
|
||||
let mut parent = Some(base);
|
||||
let mut replayed = Vec::new();
|
||||
let mut before = scratch.working_registry.clone();
|
||||
let known = self.known_inputs();
|
||||
// What the removed step added must not come back through a later step writing to it
|
||||
let gone: HashSet<NodeId> = newest_first[position..]
|
||||
.iter()
|
||||
.filter_map(|delta| match &delta.kind {
|
||||
RegistryDelta::AddNode { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
for original in newest_first[..position].iter().rev() {
|
||||
let reverse = crate::prior::capture(&scratch.working_registry, &original.kind);
|
||||
scratch.apply_op_with(RegistryTarget::Working, original.kind.clone(), original.timestamp, ApplyMode::Idempotent)?;
|
||||
let copy = Delta::new(parent, original.timestamp.peer, original.timestamp, original.kind.clone(), reverse);
|
||||
parent = Some(copy.id);
|
||||
copies.push(copy);
|
||||
sources.push((Some(original), None));
|
||||
replayed.push(original.kind.clone());
|
||||
if !original.is_interaction_end() {
|
||||
continue;
|
||||
}
|
||||
let closing_index = sources.len() - 1;
|
||||
for op in crate::repair::repair_ops(
|
||||
&before,
|
||||
&scratch.working_registry,
|
||||
&self.fold_scratch_at(Some(original.id))?.working_registry,
|
||||
&std::mem::take(&mut replayed),
|
||||
&gone,
|
||||
&known,
|
||||
) {
|
||||
let reverse = crate::prior::capture(&scratch.working_registry, &op);
|
||||
let timestamp = self.document.clock.tick();
|
||||
scratch.apply_op_with(RegistryTarget::Working, op.clone(), timestamp, ApplyMode::Strict)?;
|
||||
let repair = Delta::new(parent, original.author, timestamp, op, reverse);
|
||||
parent = Some(repair.id);
|
||||
sources[closing_index].1 = Some(repair.id);
|
||||
copies.push(repair);
|
||||
sources.push((None, None));
|
||||
}
|
||||
before = scratch.working_registry.clone();
|
||||
}
|
||||
|
||||
let mut touched = Touched::default();
|
||||
newest_first[position..].iter().for_each(|delta| touched.record(&delta.kind));
|
||||
for (original, copy) in newest_first[..position].iter().rev().zip(&mut copies) {
|
||||
for (copy, _) in copies.iter().zip(&sources).filter(|(_, (original, _))| original.is_none()) {
|
||||
touched.record(©.kind);
|
||||
}
|
||||
for copy in &copies {
|
||||
self.document.history.push(copy.clone());
|
||||
self.carry_attributes(original, copy.id);
|
||||
}
|
||||
for (&(original, closing), copy) in sources.iter().zip(&copies) {
|
||||
if let Some(original) = original {
|
||||
self.carry_attributes_closing(original, copy.id, closing);
|
||||
}
|
||||
}
|
||||
for copy in &mut copies {
|
||||
if let Some(carried) = self.document.history.get(copy.id) {
|
||||
*copy = carried.clone();
|
||||
}
|
||||
@@ -547,18 +595,6 @@ impl Session {
|
||||
Ok(touched)
|
||||
}
|
||||
|
||||
/// What the deltas from `tip` back along its parents to `base` named, without `base` itself.
|
||||
pub fn touched_between(&self, base: Option<Rev>, tip: Rev) -> Touched {
|
||||
let mut touched = Touched::default();
|
||||
let mut cursor = Some(tip);
|
||||
while cursor != base {
|
||||
let Some(delta) = cursor.and_then(|rev| self.document.history.get(rev)) else { break };
|
||||
touched.record(&delta.kind);
|
||||
cursor = delta.parent;
|
||||
}
|
||||
touched
|
||||
}
|
||||
|
||||
/// What the deltas on the head's line but not on `base`'s named, merged branches included. Fails unless `base` is
|
||||
/// on the head's line.
|
||||
fn touched_since(&self, base: Option<Rev>) -> Result<Touched, CrdtError> {
|
||||
@@ -578,7 +614,8 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Mint a dropped interaction's deltas again on top of the line as one interaction. They keep their
|
||||
/// original stamps, so a field someone wrote since keeps the newer value. Returns the new revs.
|
||||
/// original stamps, so a field someone wrote since keeps the newer value, and the graph is repaired where that
|
||||
/// left it broken (see [`repair_ops`](crate::repair::repair_ops)). Returns the new revs.
|
||||
pub fn restore_interaction(&mut self, dropped: Rev) -> Result<Vec<Rev>, CrdtError> {
|
||||
let base = self.interaction_start_parent(dropped, false).ok_or(CrdtError::NotUndoable(dropped))?;
|
||||
let mut originals = Vec::new();
|
||||
@@ -590,10 +627,32 @@ impl Session {
|
||||
originals.push(delta);
|
||||
}
|
||||
originals.reverse();
|
||||
let revs = self.commit_ops_authored_at(originals.iter().map(|delta| (delta.kind.clone(), Some(delta.timestamp))), true)?;
|
||||
let before = self.document.retired_snapshot.clone();
|
||||
let mut revs = self.commit_ops_authored_at(originals.iter().map(|delta| (delta.kind.clone(), Some(delta.timestamp))), true)?;
|
||||
let replayed: Vec<RegistryDelta> = originals.iter().map(|delta| delta.kind.clone()).collect();
|
||||
let deleted: HashSet<NodeId> = replayed
|
||||
.iter()
|
||||
.filter_map(|op| match op {
|
||||
RegistryDelta::RemoveNode { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let repairs = crate::repair::repair_ops(
|
||||
&before,
|
||||
&self.document.retired_snapshot,
|
||||
&self.fold_scratch_at(Some(dropped))?.working_registry,
|
||||
&replayed,
|
||||
&deleted,
|
||||
&self.known_inputs(),
|
||||
);
|
||||
let author = originals.last().map_or(self.document.peer, |delta| delta.author);
|
||||
let repaired = self.commit_repairs(repairs, author)?;
|
||||
let closing = repaired.last().copied();
|
||||
for (original, &rev) in originals.iter().zip(&revs) {
|
||||
self.carry_attributes(original, rev);
|
||||
let closes = original.id == dropped;
|
||||
self.carry_attributes_closing(original, rev, closing.filter(|_| closes));
|
||||
}
|
||||
revs.extend(repaired);
|
||||
if let Some(&last) = revs.last() {
|
||||
self.mark_interaction_end(last);
|
||||
}
|
||||
@@ -649,6 +708,7 @@ impl Session {
|
||||
/// Closes this peer's open interaction with a flagged [`RegistryDelta::Meta`] op. Returns the staged ops, a
|
||||
/// re-registration possibly before the marker; empty when nothing is open.
|
||||
pub fn end_interaction(&mut self) -> Result<Vec<HotOp>, CrdtError> {
|
||||
let action = self.action.take();
|
||||
let peer = self.document.peer;
|
||||
let open = self
|
||||
.document
|
||||
@@ -662,9 +722,22 @@ impl Session {
|
||||
}
|
||||
let mut closing = Attributes::new();
|
||||
closing.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), TimeStamp::ORIGIN);
|
||||
if let Some(action) = action {
|
||||
closing.set(crate::attr::delta::ACTION, Value::Str(action), TimeStamp::ORIGIN);
|
||||
}
|
||||
self.stage_ops_with([(RegistryDelta::Meta, closing)], ApplyMode::Strict)
|
||||
}
|
||||
|
||||
/// Names this peer's open interaction, replacing an earlier name. Closing it takes the name along.
|
||||
pub fn name_interaction(&mut self, action: &str) {
|
||||
self.action = Some(action.to_string());
|
||||
}
|
||||
|
||||
/// The name this peer's open interaction will close with.
|
||||
pub fn pending_action(&self) -> Option<&str> {
|
||||
self.action.as_deref()
|
||||
}
|
||||
|
||||
/// Every author's closed interactions in the hot log, the earliest closed first.
|
||||
pub fn closed_interactions(&self) -> Vec<ClosedInteraction> {
|
||||
let mut by_author: HashMap<PeerId, Vec<&HotOp>> = HashMap::new();
|
||||
@@ -861,9 +934,14 @@ impl Session {
|
||||
/// Retire one closed interaction, coarsened, marking its last delta as the interaction's end. Every op is retired,
|
||||
/// the ones coarsening drops included. Returns the new revs.
|
||||
pub fn retire_interaction(&mut self, interaction: &ClosedInteraction) -> Result<Vec<Rev>, CrdtError> {
|
||||
let marker = interaction.ops.last().and_then(|&id| self.document.hot_log.iter().find(|hot_op| hot_op.id() == id));
|
||||
let action = marker.and_then(|hot_op| hot_op.attributes.get(crate::attr::delta::ACTION)).cloned();
|
||||
let revs = self.retire_hot_ops_with(&interaction.ops, true)?;
|
||||
if let Some(&last) = revs.last() {
|
||||
self.mark_interaction_end(last);
|
||||
if let Some(action) = action {
|
||||
self.document.history.annotate(last, crate::attr::delta::ACTION, action.value, action.timestamp);
|
||||
}
|
||||
}
|
||||
Ok(revs)
|
||||
}
|
||||
@@ -914,16 +992,57 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Give a minted copy the attributes and retirement time of the delta it stands for.
|
||||
fn carry_attributes(&mut self, original: &Delta, copy: Rev) {
|
||||
if let Some(wall_ms) = original.retired_at() {
|
||||
self.document.history.set_retired_at(copy, wall_ms);
|
||||
/// Give a minted copy the attributes and retirement time of the delta it stands for, with what closes the interaction moved to `closing` when repairs minted after the copy now end it.
|
||||
fn carry_attributes_closing(&mut self, original: &Delta, copy: Rev, closing: Option<Rev>) {
|
||||
use crate::attr::delta::{ACTION, INTERACTION_END};
|
||||
|
||||
for rev in std::iter::once(copy).chain(closing) {
|
||||
if let Some(wall_ms) = original.retired_at() {
|
||||
self.document.history.set_retired_at(rev, wall_ms);
|
||||
}
|
||||
}
|
||||
for (key, value) in original.attributes.live() {
|
||||
self.document.history.annotate(copy, key, value.value.clone(), value.timestamp);
|
||||
let moved = closing.filter(|_| key == INTERACTION_END || key == ACTION);
|
||||
self.document.history.annotate(moved.unwrap_or(copy), key, value.value.clone(), value.timestamp);
|
||||
}
|
||||
}
|
||||
|
||||
/// Each node's network and newest primary input anywhere in history, branches included.
|
||||
fn known_inputs(&self) -> crate::repair::KnownInputs {
|
||||
let mut networks: HashMap<NodeId, NetworkId> = HashMap::new();
|
||||
let mut inputs: HashMap<NodeId, (TimeStamp, crate::NodeInput)> = HashMap::new();
|
||||
for delta in self.document.history.iter() {
|
||||
let (id, input) = match &delta.kind {
|
||||
RegistryDelta::AddNode { id, node } | RegistryDelta::RemoveNode { id, snapshot: node } => {
|
||||
networks.insert(*id, node.network);
|
||||
(*id, node.inputs.first().map(|slot| slot.input.clone()))
|
||||
}
|
||||
RegistryDelta::ChangeNodeInput { id, index: 0, new_input } => (*id, Some(new_input.clone())),
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => (*id, inputs.first().map(|slot| slot.input.clone())),
|
||||
_ => continue,
|
||||
};
|
||||
let Some(input) = input else { continue };
|
||||
if inputs.get(&id).is_none_or(|(newest, _)| *newest < delta.timestamp) {
|
||||
inputs.insert(id, (delta.timestamp, input));
|
||||
}
|
||||
}
|
||||
inputs.into_iter().filter_map(|(id, (_, input))| Some((id, (*networks.get(&id)?, input)))).collect()
|
||||
}
|
||||
|
||||
/// Commit repair ops on top of the line, authored by whoever made the interaction they finish.
|
||||
fn commit_repairs(&mut self, ops: Vec<RegistryDelta>, author: PeerId) -> Result<Vec<Rev>, CrdtError> {
|
||||
let mut revs = Vec::with_capacity(ops.len());
|
||||
for op in ops {
|
||||
let reverse = crate::prior::capture(&self.document.retired_snapshot, &op);
|
||||
let delta = Delta::new(self.document.head, author, self.document.clock.tick(), op, reverse);
|
||||
self.document.apply_op_with(RegistryTarget::Retired, delta.kind.clone(), delta.timestamp, ApplyMode::Strict)?;
|
||||
self.document.head = Some(delta.id);
|
||||
revs.push(delta.id);
|
||||
self.document.history.push(delta);
|
||||
}
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
/// Low-level: set a local annotation attribute (e.g. a commit message) on a retired delta in place.
|
||||
/// Excluded from the delta's content-addressed `Rev`, so identity is unchanged. Returns whether the
|
||||
/// delta was found. The `Gdd` layer re-persists the affected history frame after calling this.
|
||||
@@ -960,11 +1079,6 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Forget the latest undone interaction, so redo can't bring it back.
|
||||
pub fn forget_latest_undo(&mut self) -> Option<Rev> {
|
||||
self.document.redo_stack.pop()
|
||||
}
|
||||
|
||||
pub fn can_redo(&self) -> bool {
|
||||
!self.document.redo_stack.is_empty()
|
||||
}
|
||||
@@ -1091,22 +1205,6 @@ impl Session {
|
||||
hashes
|
||||
}
|
||||
|
||||
/// Every blob that the registry, its tombstones, the history or the hot log names.
|
||||
pub fn all_blob_hashes(&self) -> HashSet<BlobHash> {
|
||||
self.blob_hashes().collect()
|
||||
}
|
||||
|
||||
/// Whether the registry, its tombstones, the history or the hot log names `hash`.
|
||||
pub fn names_blob(&self, hash: BlobHash) -> bool {
|
||||
self.blob_hashes().any(|named| named == hash)
|
||||
}
|
||||
|
||||
fn blob_hashes(&self) -> impl Iterator<Item = BlobHash> + '_ {
|
||||
let history = self.document.history.iter().flat_map(Delta::blob_hashes);
|
||||
let hot_log = self.document.hot_log.iter().flat_map(|hot_op| hot_op.op.blob_hashes());
|
||||
self.document.working_registry.blob_hashes().chain(history).chain(hot_log)
|
||||
}
|
||||
|
||||
/// Every referenced resource hash plus what the ops this peer took back named. Garbage collection must keep these.
|
||||
pub fn resource_gc_roots(&self) -> HashSet<ResourceHash> {
|
||||
let mut roots = self.all_referenced_resource_hashes();
|
||||
|
||||
@@ -597,3 +597,37 @@ fn undo_takes_back_the_interaction_before_one_already_taken_back() {
|
||||
twice.retract_interaction().unwrap().expect("a is hot and now the latest");
|
||||
assert!(twice.hot_log().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interaction_keeps_its_name_into_history() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
session.name_interaction("Stale");
|
||||
session.end_interaction().unwrap();
|
||||
session.stage_ops([set_attribute("a", 1)]).unwrap();
|
||||
session.name_interaction("Move");
|
||||
session.end_interaction().unwrap();
|
||||
session.stage_ops([set_attribute("b", 1)]).unwrap();
|
||||
session.end_interaction().unwrap();
|
||||
|
||||
for interaction in session.closed_interactions() {
|
||||
session.retire_interaction(&interaction).unwrap();
|
||||
}
|
||||
let actions: Vec<Option<&str>> = session.history().filter(|delta| delta.is_interaction_end()).map(|delta| delta.action()).collect();
|
||||
assert_eq!(actions, [Some("Move"), None], "a name set while nothing was open is dropped at the next close");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_taken_back_interaction_takes_its_name_along() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
session.stage_ops([set_attribute("a", 1)]).unwrap();
|
||||
session.name_interaction("Move");
|
||||
session.retract_interaction().unwrap().expect("a is open and hot");
|
||||
session.stage_ops([set_attribute("b", 1)]).unwrap();
|
||||
session.end_interaction().unwrap();
|
||||
|
||||
for interaction in session.closed_interactions() {
|
||||
session.retire_interaction(&interaction).unwrap();
|
||||
}
|
||||
let actions: Vec<Option<&str>> = session.history().filter(|delta| delta.is_interaction_end()).map(|delta| delta.action()).collect();
|
||||
assert_eq!(actions, [None]);
|
||||
}
|
||||
@@ -1406,6 +1406,23 @@ fn a_network_re_added_shorter_keeps_only_its_own_exports() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Two registries ordering a removal differently against a write are not order-consistent, though their values agree.
|
||||
#[test]
|
||||
fn order_consistency_covers_removal_stamps() {
|
||||
let with_removal_at = |counter: u64| {
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let node = Node::new(NetworkId(1), crate::Implementation::ProtoNode(graphene_resource::ResourceId::from(7)), 0);
|
||||
document.apply_op_idempotent(RegistryDelta::AddNode { id: NodeId(2), node: node.clone() }, ts(3, 1)).expect("add");
|
||||
document
|
||||
.apply_op_idempotent(RegistryDelta::RemoveNode { id: NodeId(1), snapshot: node }, ts(counter, 1))
|
||||
.expect("remove");
|
||||
document.working_registry
|
||||
};
|
||||
let (earlier, later) = (with_removal_at(2), with_removal_at(4));
|
||||
assert!(earlier.value_equal(&later));
|
||||
assert!(!earlier.order_consistent(&later));
|
||||
}
|
||||
|
||||
/// An input naming a node whose addition has not arrived renders as a dangling input, as one naming a removed node does,
|
||||
/// rather than failing the conversion: the placeholder knows nothing of the node's network.
|
||||
#[test]
|
||||
@@ -1436,10 +1453,7 @@ 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(), &crate::blob::BlobBytes::new())
|
||||
.expect("converts with a dangling input");
|
||||
document.working_registry.to_runtime_with_metadata(&crate::Declarations::new()).expect("converts with a dangling input");
|
||||
}
|
||||
|
||||
/// Remapped tips can swap order, and a merge's `parent` has to stay the lowest.
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation the History
|
||||
//! panel offers mixed in: undo, redo, going back, removing a step and bringing one back. After every operation the
|
||||
//! document must still be a well-formed stack, the snapshot must be what history folds to, and a peer following the
|
||||
//! head moves must hold the same document.
|
||||
//!
|
||||
//! Inspect one run with `SEED=<n> cargo test -p document-graph-storage history_simulation::inspect_seed -- --ignored --nocapture`.
|
||||
|
||||
use crate::{Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// What every layer's implementation names, so nodes need no proto-node declarations.
|
||||
const LEAF: NetworkId = NetworkId(1);
|
||||
|
||||
/// A small xorshift generator, so a seed fixes the run.
|
||||
struct Random(u64);
|
||||
|
||||
impl Random {
|
||||
fn new(seed: u64) -> Self {
|
||||
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
|
||||
}
|
||||
|
||||
fn below(&mut self, bound: usize) -> usize {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
(self.0 % bound as u64) as usize
|
||||
}
|
||||
|
||||
fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
|
||||
(!options.is_empty()).then(|| options[self.below(options.len())])
|
||||
}
|
||||
}
|
||||
|
||||
/// The layers from the top of the stack down, following each layer's first input.
|
||||
fn stack(registry: &Registry) -> Vec<NodeId> {
|
||||
let mut layers = Vec::new();
|
||||
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
|
||||
while let Some(NodeInput::Node { id, .. }) = below {
|
||||
if layers.contains(&id) || layers.len() > registry.node_instances.len() {
|
||||
break;
|
||||
}
|
||||
layers.push(id);
|
||||
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
|
||||
}
|
||||
layers
|
||||
}
|
||||
|
||||
/// What feeds into `layer` from below.
|
||||
fn below(registry: &Registry, layer: NodeId) -> NodeInput {
|
||||
registry.node_instances[&layer].inputs[0].input.clone()
|
||||
}
|
||||
|
||||
/// Points what sits directly above `layer`, a layer or the export, at `input`.
|
||||
fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> RegistryDelta {
|
||||
let layers = stack(registry);
|
||||
match layers.iter().position(|&id| id == layer) {
|
||||
Some(0) | None => RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(input),
|
||||
},
|
||||
Some(position) => RegistryDelta::ChangeNodeInput {
|
||||
id: layers[position - 1],
|
||||
index: 0,
|
||||
new_input: input,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn on(id: NodeId) -> NodeInput {
|
||||
NodeInput::Node { id, index: 0 }
|
||||
}
|
||||
|
||||
fn value(number: usize) -> NodeInput {
|
||||
NodeInput::Value {
|
||||
value: Value::from(serde_json::json!(number)),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// One interaction's ops, as the editor would stage them for a random edit of the stack.
|
||||
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
|
||||
let registry = session.registry().clone();
|
||||
let layers = stack(®istry);
|
||||
match random.below(10) {
|
||||
// Draw a layer on top
|
||||
0..=3 => {
|
||||
let id = session.next_node_id();
|
||||
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
|
||||
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
|
||||
node.inputs[1].input = value(random.below(100));
|
||||
let mut ops = vec![
|
||||
RegistryDelta::AddNode { id, node },
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(id)),
|
||||
},
|
||||
];
|
||||
// The layer below moves into the stack under the new one, as the editor records with its position
|
||||
if let Some(&below) = layers.first() {
|
||||
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
|
||||
}
|
||||
ops
|
||||
}
|
||||
// Delete a layer, reconnecting what was above it to what was below
|
||||
4..=5 => {
|
||||
let Some(layer) = random.pick(&layers) else { return Vec::new() };
|
||||
let snapshot = registry.node_instances[&layer].clone();
|
||||
vec![rewire_above(®istry, layer, below(®istry, layer)), RegistryDelta::RemoveNode { id: layer, snapshot }]
|
||||
}
|
||||
// Move a layer to the top
|
||||
6 => {
|
||||
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
|
||||
vec![
|
||||
rewire_above(®istry, layer, below(®istry, layer)),
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 0,
|
||||
new_input: on(layers[0]),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(layer)),
|
||||
},
|
||||
]
|
||||
}
|
||||
// Change a layer's value
|
||||
_ => {
|
||||
let Some(layer) = random.pick(&layers) else { return Vec::new() };
|
||||
vec![RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 1,
|
||||
new_input: value(random.below(100)),
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ops of an edit, short enough to read in a failing run's log.
|
||||
fn summarize(ops: &[RegistryDelta]) -> String {
|
||||
let short = |id: &NodeId| id.0 % 1000;
|
||||
let input = |input: &NodeInput| match input {
|
||||
NodeInput::Node { id, .. } => format!("{}", short(id)),
|
||||
_ => "value".to_string(),
|
||||
};
|
||||
ops.iter()
|
||||
.map(|op| match op {
|
||||
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
|
||||
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
|
||||
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
|
||||
other => format!("{other:?}"),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
/// The revs closing each interaction on the head's line, newest first.
|
||||
fn line_steps(session: &Session) -> Vec<Rev> {
|
||||
let mut steps = Vec::new();
|
||||
let mut current = session.head_rev();
|
||||
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
|
||||
if delta.is_interaction_end() {
|
||||
steps.push(delta.id);
|
||||
}
|
||||
current = delta.parent;
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// The revs closing interactions left behind on branches.
|
||||
fn branch_steps(session: &Session) -> Vec<Rev> {
|
||||
let line: HashSet<Rev> = {
|
||||
let mut line = HashSet::new();
|
||||
let mut current = session.head_rev();
|
||||
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
|
||||
line.insert(delta.id);
|
||||
current = delta.parent;
|
||||
}
|
||||
line
|
||||
};
|
||||
let mut steps: Vec<Rev> = session
|
||||
.history()
|
||||
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
|
||||
.map(|delta| delta.id)
|
||||
.collect();
|
||||
steps.sort();
|
||||
steps
|
||||
}
|
||||
|
||||
/// The layers the interaction ending at `end` added and deleted, by what it did in all.
|
||||
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
|
||||
let (mut added, mut removed) = (Vec::new(), Vec::new());
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current {
|
||||
match &delta.kind {
|
||||
RegistryDelta::AddNode { id, .. } => added.push(*id),
|
||||
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
|
||||
_ => {}
|
||||
}
|
||||
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
|
||||
}
|
||||
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
|
||||
(net(&added, &removed), net(&removed, &added))
|
||||
}
|
||||
|
||||
/// The layers the step ending at `end` added that a newer deletion on its own line had taken again.
|
||||
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
|
||||
let mut lost = HashSet::new();
|
||||
let mut added_at = std::collections::HashMap::new();
|
||||
let mut line = Vec::new();
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current {
|
||||
line.push(delta);
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
for delta in &line {
|
||||
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
|
||||
added_at.entry(*id).or_insert(delta.timestamp);
|
||||
}
|
||||
}
|
||||
for delta in &line {
|
||||
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
|
||||
&& added.contains(id)
|
||||
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
|
||||
{
|
||||
lost.insert(*id);
|
||||
}
|
||||
}
|
||||
lost
|
||||
}
|
||||
|
||||
/// The layers live on the line just before the interaction ending at `end`.
|
||||
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
let mut line = Vec::new();
|
||||
while let Some(delta) = current {
|
||||
line.push(delta.clone());
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
line.reverse();
|
||||
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
|
||||
replayed.retired_registry().node_instances.keys().copied().collect()
|
||||
}
|
||||
|
||||
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
|
||||
/// left drawn by nothing.
|
||||
fn assert_well_formed(context: &str, registry: &Registry) {
|
||||
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
|
||||
let export = exports.first().and_then(|slot| slot.target.clone());
|
||||
if let Some(NodeInput::Node { id, .. }) = &export {
|
||||
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
for (index, slot) in node.inputs.iter().enumerate() {
|
||||
if let NodeInput::Node { id: named, .. } = &slot.input {
|
||||
assert!(registry.node_instances.contains_key(named), "{context}: input {index} of {id:?} names {named:?}, which is gone");
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut stacked_on = HashSet::new();
|
||||
let primary_inputs = registry.node_instances.values().filter_map(|node| node.inputs.first()).map(|slot| &slot.input);
|
||||
for input in primary_inputs.chain(export.iter()) {
|
||||
if let NodeInput::Node { id, .. } = input {
|
||||
assert!(stacked_on.insert(*id), "{context}: two layers or the export sit on {id:?}");
|
||||
}
|
||||
}
|
||||
let layers = stack(registry);
|
||||
let unique: HashSet<NodeId> = layers.iter().copied().collect();
|
||||
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
|
||||
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
|
||||
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
|
||||
}
|
||||
|
||||
fn assert_consistent(context: &str, session: &Session) {
|
||||
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
|
||||
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
|
||||
let folded = session.snapshot_from_history().expect("history folds");
|
||||
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
|
||||
assert_well_formed(context, session.retired_registry());
|
||||
}
|
||||
|
||||
/// Closes the open interaction and retires it as one step.
|
||||
fn retire_step(session: &mut Session) {
|
||||
session.end_interaction().expect("close");
|
||||
for interaction in session.closed_interactions() {
|
||||
session.retire_interaction(&interaction).expect("retire");
|
||||
}
|
||||
}
|
||||
|
||||
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
|
||||
fn catch_up(follower: &mut Session, host: &Session) {
|
||||
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
|
||||
follower.follow(missing, host.head_rev()).expect("follow");
|
||||
}
|
||||
|
||||
/// A peer that joins now and holds what the host holds.
|
||||
fn fresh_follower(host: &Session) -> Session {
|
||||
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
|
||||
}
|
||||
|
||||
fn simulate(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
|
||||
let mut random = Random::new(seed);
|
||||
let mut host = Session::with_identity(PeerId(1), UserId(1));
|
||||
let networks = [
|
||||
RegistryDelta::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
},
|
||||
RegistryDelta::AddNetwork {
|
||||
id: LEAF,
|
||||
network: Network::default(),
|
||||
},
|
||||
];
|
||||
host.stage_ops(networks).expect("stage the networks");
|
||||
retire_step(&mut host);
|
||||
let mut follower = fresh_follower(&host);
|
||||
|
||||
for step in 0..steps {
|
||||
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
|
||||
match random.below(12) {
|
||||
0..=5 => {
|
||||
let ops = random_edit(&mut random, &mut host);
|
||||
if ops.is_empty() {
|
||||
continue;
|
||||
}
|
||||
log.push(format!("{step}: edit {}", summarize(&ops)));
|
||||
host.stage_ops(ops).expect("stage");
|
||||
retire_step(&mut host);
|
||||
catch_up(&mut follower, &host);
|
||||
}
|
||||
6 if host.can_undo() => {
|
||||
log.push(format!("{step}: undo"));
|
||||
host.undo().expect("undo");
|
||||
follower = fresh_follower(&host);
|
||||
}
|
||||
7 if host.can_redo() => {
|
||||
log.push(format!("{step}: redo"));
|
||||
host.redo().expect("redo");
|
||||
follower = fresh_follower(&host);
|
||||
}
|
||||
8 => {
|
||||
// Not the newest step, which going back to would leave everything as it is
|
||||
let Some(target) = random.pick(&line_steps(&host)[1.min(line_steps(&host).len())..]) else {
|
||||
continue;
|
||||
};
|
||||
log.push(format!("{step}: go back to {target:?}"));
|
||||
let (moved, _) = host.move_head_to(target).expect("go back");
|
||||
follower.apply_head_move(&moved).expect("follow the move");
|
||||
}
|
||||
9 => {
|
||||
let steps = line_steps(&host);
|
||||
// The first step adds the networks, which nothing can do without
|
||||
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
|
||||
log.push(format!("{step}: remove {target:?}"));
|
||||
let (mut added, _) = added_and_removed(&host, target);
|
||||
// A layer the line had before the step stays
|
||||
let earlier = live_before(&host, target);
|
||||
added.retain(|id| !earlier.contains(id));
|
||||
let (moved, _) = host.drop_interaction(target).expect("remove the step");
|
||||
follower.apply_head_move(&moved).expect("follow the removal");
|
||||
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
|
||||
assert!(kept.is_empty(), "{}", context(&format!("the removed step's layers {kept:?} are still there"), log));
|
||||
}
|
||||
10 | 11 => {
|
||||
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
|
||||
log.push(format!("{step}: bring back {target:?}"));
|
||||
let (mut added, removed) = added_and_removed(&host, target);
|
||||
// A layer the line already had from this step and deleted since stays deleted
|
||||
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
|
||||
// As does one a newer deletion took on the step's own line
|
||||
let lost = lost_on_its_line(&host, target, &added);
|
||||
added.retain(|id| !lost.contains(id));
|
||||
host.restore_interaction(target).expect("bring back");
|
||||
catch_up(&mut follower, &host);
|
||||
let registry = host.retired_registry();
|
||||
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
|
||||
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
|
||||
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's layers {missing:?} are missing"), log));
|
||||
assert!(kept.is_empty(), "{}", context(&format!("the layers {kept:?} the brought back step deleted are still there"), log));
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
let what = log.last().cloned().unwrap_or_default();
|
||||
assert_consistent(&context(&what, log), &host);
|
||||
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
|
||||
assert!(
|
||||
follower.retired_registry().value_equal(host.retired_registry()),
|
||||
"{}",
|
||||
context("the follower holds another document", log)
|
||||
);
|
||||
}
|
||||
host
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_operations_keep_the_stack_whole_and_peers_converged() {
|
||||
let seeds: u64 = std::env::var("SEEDS").ok().and_then(|seeds| seeds.parse().ok()).unwrap_or(200);
|
||||
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
|
||||
for seed in 0..seeds {
|
||||
simulate(seed, steps, &mut Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
/// A seed fixes the run, so one that fails can be replayed.
|
||||
#[test]
|
||||
fn a_seed_fixes_the_history_run() {
|
||||
let stacks = |seed| stack(simulate(seed, 60, &mut Vec::new()).retired_registry());
|
||||
for seed in 0..5 {
|
||||
assert_eq!(stacks(seed), stacks(seed), "seed {seed}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn inspect_seed() {
|
||||
let seed = std::env::var("SEED").ok().and_then(|seed| seed.parse().ok()).unwrap_or(0);
|
||||
let mut log = Vec::new();
|
||||
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
|
||||
let host = simulate(seed, steps, &mut log);
|
||||
println!("{}\nstack {:?}", log.join("\n"), stack(host.retired_registry()));
|
||||
}
|
||||
@@ -4,7 +4,6 @@ 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};
|
||||
|
||||
@@ -73,9 +72,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, &conversion.blob_bytes).expect("whole conversion");
|
||||
let (whole, node_entries, _) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
|
||||
|
||||
let projection = registry.runtime_projection(&conversion.declarations, &conversion.blob_bytes);
|
||||
let projection = registry.runtime_projection(&conversion.declarations);
|
||||
for &id in registry.node_instances.keys() {
|
||||
let projected = projection.node(id).expect("every stored node projects");
|
||||
let (network, local_id) = projection.node_address(id).expect("every stored node has an address");
|
||||
@@ -97,8 +96,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, &conversion.blob_bytes).expect("whole conversion");
|
||||
let projection = registry.runtime_projection(&conversion.declarations, &conversion.blob_bytes);
|
||||
let (whole, _, _) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
|
||||
let projection = registry.runtime_projection(&conversion.declarations);
|
||||
|
||||
let root = projection.network_entry(ROOT_NETWORK).expect("root");
|
||||
assert_eq!(root.network, NetworkLocation::default());
|
||||
@@ -121,8 +120,8 @@ fn an_unreachable_network_has_no_address() {
|
||||
node.network = NetworkId(5);
|
||||
registry.node_instances.insert(NodeId(9), node);
|
||||
|
||||
let (declarations, blobs) = (Declarations::new(), BlobBytes::new());
|
||||
let projection = registry.runtime_projection(&declarations, &blobs);
|
||||
let declarations = Declarations::new();
|
||||
let projection = registry.runtime_projection(&declarations);
|
||||
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(_))));
|
||||
@@ -141,8 +140,8 @@ fn a_network_several_nodes_implement_has_one_location() {
|
||||
registry.node_instances.insert(NodeId(id), node);
|
||||
}
|
||||
|
||||
let (declarations, blobs) = (Declarations::new(), BlobBytes::new());
|
||||
let projection = registry.runtime_projection(&declarations, &blobs);
|
||||
let declarations = Declarations::new();
|
||||
let projection = registry.runtime_projection(&declarations);
|
||||
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 and blobs alongside it.
|
||||
/// Convert a runtime network to a storage `Registry`, returning the declarations alongside it.
|
||||
/// Proto-node declaration content is no longer stored in the registry (it lives in a byte store);
|
||||
/// these tests have no byte store, so they keep the extracted `Declarations` and blob bytes in hand for the back-conversion.
|
||||
fn to_registry(network: &NodeNetwork) -> (Registry, crate::Declarations, crate::blob::BlobBytes) {
|
||||
/// these tests have no byte store, so they keep the extracted `Declarations` in hand for the back-conversion.
|
||||
fn to_registry(network: &NodeNetwork) -> (Registry, crate::Declarations) {
|
||||
let conversion = Registry::convert_from_runtime(network, &crate::NoMetadata, &Default::default(), PeerId(0)).expect("Failed to convert NodeNetwork to Registry");
|
||||
(conversion.registry, conversion.declarations, conversion.blob_bytes)
|
||||
(conversion.registry, conversion.declarations)
|
||||
}
|
||||
|
||||
/// 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, blobs) = to_registry(&original_network);
|
||||
let (registry, declarations) = to_registry(&original_network);
|
||||
|
||||
// Convert back to NodeNetwork
|
||||
let (converted_network, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("Failed to convert Registry back to NodeNetwork");
|
||||
let (converted_network, _) = registry.to_runtime_with_metadata(&declarations).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, blobs) = to_registry(&original_network);
|
||||
let (registry, declarations) = to_registry(&original_network);
|
||||
|
||||
// Convert back to NodeNetwork
|
||||
let (converted_network, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("Failed to convert Registry back to NodeNetwork");
|
||||
let (converted_network, _) = registry.to_runtime_with_metadata(&declarations).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, _blobs) = to_registry(&network);
|
||||
let (registry, _declarations) = 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, blobs) = to_registry(&network);
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("Failed to convert back to NodeNetwork");
|
||||
let (registry, declarations) = to_registry(&network);
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations).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, blobs) = to_registry(&original_network);
|
||||
let (registry, declarations) = to_registry(&original_network);
|
||||
|
||||
// Convert back to NodeNetwork
|
||||
let (converted_network, _) = registry
|
||||
.to_runtime_with_metadata(&declarations, &blobs)
|
||||
.to_runtime_with_metadata(&declarations)
|
||||
.unwrap_or_else(|e| panic!("Failed to convert {} back to NodeNetwork: {:?}", artwork_name, e));
|
||||
|
||||
// Basic structural checks
|
||||
@@ -470,10 +470,9 @@ 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, &blobs).expect("Failed to convert Registry back with metadata");
|
||||
let (converted, entries) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back with metadata");
|
||||
|
||||
// Graph structure still round-trips.
|
||||
assert_eq!(converted.nodes.len(), network.nodes.len());
|
||||
@@ -630,8 +629,8 @@ fn node_input_f64_round_trips_bit_exact() {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let (registry, declarations, blobs) = to_registry(&network);
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("to_runtime");
|
||||
let (registry, declarations) = to_registry(&network);
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime");
|
||||
|
||||
let input = &converted.nodes.get(&NodeId(0)).expect("node 0").inputs[0];
|
||||
let NodeInput::Value { tagged_value, .. } = input else {
|
||||
@@ -651,14 +650,14 @@ fn duplicate_runtime_node_id_is_rejected() {
|
||||
use crate::TimeStamp;
|
||||
use crate::to_runtime::ConversionError;
|
||||
|
||||
let (mut registry, declarations, blobs) = to_registry(&create_simple_network());
|
||||
let (mut registry, declarations) = 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, &blobs).expect_err("duplicate runtime ID must error");
|
||||
let error = registry.to_runtime_with_metadata(&declarations).expect_err("duplicate runtime ID must error");
|
||||
assert!(
|
||||
matches!(error, ConversionError::DuplicateRuntimeNodeId { runtime_id: 7, .. }),
|
||||
"expected DuplicateRuntimeNodeId, got {error:?}"
|
||||
@@ -672,7 +671,7 @@ fn cross_network_reference_is_rejected() {
|
||||
use crate::to_runtime::ConversionError;
|
||||
use crate::{Network, NodeInput};
|
||||
|
||||
let (mut registry, declarations, blobs) = to_registry(&create_simple_network());
|
||||
let (mut registry, declarations) = 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
|
||||
@@ -691,7 +690,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, &blobs).expect_err("cross-network reference must error");
|
||||
let error = registry.to_runtime_with_metadata(&declarations).expect_err("cross-network reference must error");
|
||||
assert!(matches!(error, ConversionError::CrossNetworkReference { .. }), "expected CrossNetworkReference, got {error:?}");
|
||||
}
|
||||
|
||||
@@ -702,8 +701,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, blobs) = to_registry(&network);
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations, &blobs).expect("to_runtime");
|
||||
let (registry, declarations) = to_registry(&network);
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations).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");
|
||||
@@ -717,7 +716,7 @@ fn dangling_scope_injection_is_rejected() {
|
||||
use crate::TimeStamp;
|
||||
use crate::to_runtime::ConversionError;
|
||||
|
||||
let (mut registry, declarations, blobs) = to_registry(&create_simple_network());
|
||||
let (mut registry, declarations) = 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.
|
||||
@@ -731,7 +730,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, &blobs).expect_err("dangling scope injection must error");
|
||||
let error = registry.to_runtime_with_metadata(&declarations).expect_err("dangling scope injection must error");
|
||||
assert!(matches!(error, ConversionError::DanglingScopeInjection { .. }), "expected DanglingScopeInjection, got {error:?}");
|
||||
}
|
||||
|
||||
@@ -777,9 +776,7 @@ fn cyclic_network_reference_is_rejected() {
|
||||
},
|
||||
);
|
||||
|
||||
let error = registry
|
||||
.to_runtime_with_metadata(&crate::Declarations::new(), &crate::blob::BlobBytes::new())
|
||||
.expect_err("cyclic network reference must error");
|
||||
let error = registry.to_runtime_with_metadata(&crate::Declarations::new()).expect_err("cyclic network reference must error");
|
||||
assert!(matches!(error, ConversionError::CyclicNetwork(_)), "expected CyclicNetwork, got {error:?}");
|
||||
}
|
||||
|
||||
@@ -808,7 +805,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, blobs) = to_registry(&network);
|
||||
let (registry, declarations) = 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");
|
||||
@@ -818,7 +815,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, &blobs).expect("to_runtime");
|
||||
let (converted, _) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime");
|
||||
assert_eq!(converted, network);
|
||||
}
|
||||
|
||||
@@ -858,39 +855,6 @@ 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 read back from the blob bytes.
|
||||
#[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}");
|
||||
}
|
||||
@@ -1171,7 +1171,7 @@ fn restaging_an_unchanged_runtime_does_not_revive_a_nested_network_removed_under
|
||||
assert!(a.registry().node_instances.contains_key(&owner));
|
||||
assert!(!a.registry().networks.contains_key(&nested));
|
||||
|
||||
let (runtime, _) = a.registry().to_runtime_with_metadata(&conversion.declarations, &conversion.blob_bytes).expect("to runtime");
|
||||
let (runtime, _) = a.registry().to_runtime_with_metadata(&conversion.declarations).expect("to runtime");
|
||||
a.mark_runtime_current();
|
||||
a.stage_from_runtime(&runtime, &NoMetadata, &resources).expect("restage");
|
||||
assert!(!a.registry().networks.contains_key(&nested), "the removed network stays removed");
|
||||
@@ -1249,32 +1249,3 @@ fn a_removed_network_counts_as_rendered_only_when_the_root_reaches_it() {
|
||||
assert!(rendered.networks.contains_key(&run_by_root) && rendered.networks.contains_key(&nested));
|
||||
assert!(!rendered.networks.contains_key(&run_by_stray) && rendered.removed_networks.contains_key(&run_by_stray));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_span_an_undo_walks_names_only_the_undone_step() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
let base = step(&mut session, add_network(1));
|
||||
let tip = step(&mut session, add_network(2));
|
||||
|
||||
let undone = session.undo().expect("undo");
|
||||
assert_eq!(undone, tip);
|
||||
let touched = session.touched_between(session.head_rev(), undone);
|
||||
assert_eq!(touched.networks, [NetworkId(2)].into_iter().collect());
|
||||
assert_eq!(session.head_rev(), Some(base));
|
||||
|
||||
let from = session.head_rev();
|
||||
let redone = session.redo().expect("redo");
|
||||
assert_eq!(session.touched_between(from, redone).networks, [NetworkId(2)].into_iter().collect());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_forgotten_undo_cannot_be_redone() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
step(&mut session, add_network(1));
|
||||
let tip = step(&mut session, add_network(2));
|
||||
|
||||
session.undo().expect("undo");
|
||||
assert_eq!(session.forget_latest_undo(), Some(tip));
|
||||
assert!(!session.can_redo());
|
||||
assert!(session.redo_stack().is_empty());
|
||||
}
|
||||
@@ -9,9 +9,8 @@ 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::{BlobHash, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
|
||||
use crate::{Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConversionError {
|
||||
@@ -23,8 +22,6 @@ 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")]
|
||||
@@ -43,8 +40,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, blobs: &BlobBytes) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>), ConversionError> {
|
||||
let (network, node_entries, _) = self.to_runtime_with_full_metadata(declarations, blobs)?;
|
||||
pub fn to_runtime_with_metadata(&self, declarations: &Declarations) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>), ConversionError> {
|
||||
let (network, node_entries, _) = self.to_runtime_with_full_metadata(declarations)?;
|
||||
Ok((network, node_entries))
|
||||
}
|
||||
|
||||
@@ -53,11 +50,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, blobs: &BlobBytes) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>, Vec<NetworkMetadataEntry>), ConversionError> {
|
||||
pub fn to_runtime_with_full_metadata(&self, declarations: &Declarations) -> 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, blobs);
|
||||
let context = ConversionContext::new(self, declarations);
|
||||
|
||||
// Reject cycles first because the runtime cannot inline a definition that contains itself
|
||||
detect_network_cycle(&context, ROOT_NETWORK)?;
|
||||
@@ -99,12 +96,11 @@ 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, blobs: &'a BlobBytes) -> Self {
|
||||
fn new(registry: &'a Registry, declarations: &'a Declarations) -> Self {
|
||||
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
|
||||
for (&global_id, node) in ®istry.node_instances {
|
||||
nodes_by_network.entry(node.network).or_default().push((global_id, node));
|
||||
@@ -112,17 +108,10 @@ impl<'a> ConversionContext<'a> {
|
||||
Self {
|
||||
registry,
|
||||
declarations,
|
||||
blobs,
|
||||
nodes_by_network,
|
||||
}
|
||||
}
|
||||
|
||||
/// The value stored in blob `hash`.
|
||||
fn resolve_blob(&self, hash: BlobHash) -> Result<Value, ConversionError> {
|
||||
let bytes = self.blobs.get(&hash).ok_or(ConversionError::BlobNotFound(hash))?;
|
||||
decode_blob(bytes).map_err(|error| ConversionError::DeserializationError(format!("Blob {hash}: {error}")))
|
||||
}
|
||||
|
||||
/// The networks other than the root that the root reaches through node implementations.
|
||||
fn reachable_definitions(&self) -> FxHashSet<NetworkId> {
|
||||
let mut reached = FxHashSet::default();
|
||||
@@ -186,8 +175,8 @@ pub struct RuntimeProjection<'a> {
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
pub fn runtime_projection<'a>(&'a self, declarations: &'a Declarations, blobs: &'a BlobBytes) -> RuntimeProjection<'a> {
|
||||
let context = ConversionContext::new(self, declarations, blobs);
|
||||
pub fn runtime_projection<'a>(&'a self, declarations: &'a Declarations) -> RuntimeProjection<'a> {
|
||||
let context = ConversionContext::new(self, declarations);
|
||||
RuntimeProjection {
|
||||
reachable: context.reachable_definitions(),
|
||||
context,
|
||||
@@ -251,7 +240,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(&self.context, id, network)?,
|
||||
exports: convert_exports(registry, id, network)?,
|
||||
network: location,
|
||||
})
|
||||
}
|
||||
@@ -259,7 +248,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, &BlobBytes::new()), ROOT_NETWORK)
|
||||
detect_network_cycle(&ConversionContext::new(registry, declarations), ROOT_NETWORK)
|
||||
}
|
||||
|
||||
/// Rejects any cycle in the graph of `Implementation::Network` references from a network to the networks its nodes implement.
|
||||
@@ -340,7 +329,7 @@ fn convert_network(
|
||||
}
|
||||
}
|
||||
|
||||
let exports = convert_exports(context, network_id, network)?;
|
||||
let exports = convert_exports(context.registry, network_id, network)?;
|
||||
let scope_injections = read_scope_injections(context.registry, network_id, &network.attributes)?;
|
||||
|
||||
Ok(NodeNetwork {
|
||||
@@ -353,14 +342,14 @@ fn convert_network(
|
||||
}
|
||||
|
||||
/// The network's exports, compacted into the runtime's dense list.
|
||||
fn convert_exports(context: &ConversionContext, network_id: NetworkId, network: &crate::Network) -> Result<Vec<GraphCraftNodeInput>, ConversionError> {
|
||||
fn convert_exports(registry: &Registry, 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(context, network_id, input, &empty_attrs))
|
||||
.map(|input| convert_input(registry, network_id, input, &empty_attrs))
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -464,7 +453,7 @@ fn convert_node(context: &ConversionContext, node: &crate::Node) -> Result<Docum
|
||||
let inputs = node
|
||||
.inputs
|
||||
.iter()
|
||||
.map(|slot| convert_input(context, node.network, &slot.input, &slot.attributes))
|
||||
.map(|slot| convert_input(context.registry, node.network, &slot.input, &slot.attributes))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
// Defaults must match `DocumentNode::default()` (and the `set_if_not_default` calls in `from_runtime`).
|
||||
@@ -480,9 +469,7 @@ fn convert_node(context: &ConversionContext, node: &crate::Node) -> Result<Docum
|
||||
})
|
||||
}
|
||||
|
||||
fn convert_input(context: &ConversionContext, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
|
||||
let registry = context.registry;
|
||||
|
||||
fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
|
||||
Ok(match input {
|
||||
NodeInput::Node { id: node_id, index: output_index } => {
|
||||
// A node removed concurrently keeps its id, as the editor holds a dangling input. So does one whose addition has not
|
||||
@@ -505,12 +492,7 @@ fn convert_input(context: &ConversionContext, network_id: NetworkId, input: &Nod
|
||||
}
|
||||
}
|
||||
NodeInput::Value { value, exposed } => {
|
||||
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:?}")))?;
|
||||
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::from_object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
|
||||
Json::Object(object) => Value::Object(object.into_iter().map(|(key, value)| (key, value.into())).collect()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,6 @@ 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) }),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,7 +58,6 @@ pub struct ValueError(serde_json::Error);
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{BlobHash, ResourceHash};
|
||||
use serde::Deserialize;
|
||||
|
||||
#[test]
|
||||
@@ -159,26 +157,5 @@ 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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -99,7 +99,7 @@ impl LiveDocument {
|
||||
|
||||
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
|
||||
let declarations = self.gdd.declarations(&self.gdd).await;
|
||||
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations, self.gdd.blobs())?;
|
||||
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations)?;
|
||||
Ok(network)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
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};
|
||||
@@ -59,9 +58,8 @@ impl MigrationHost for CompilerHost {
|
||||
}
|
||||
}
|
||||
|
||||
// A state that doesn't convert answers nothing, so each migration asking takes its fallback.
|
||||
// Node migrations only see states with resolved blobs, so no blobs are needed.
|
||||
let (mut inlined, nodes, _) = state.to_runtime_with_full_metadata(&declarations, &BlobBytes::new()).ok()?;
|
||||
// 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()?;
|
||||
inlined.inline_definitions().ok()?;
|
||||
|
||||
Some(Box::new(StateCompiler {
|
||||
|
||||
@@ -16,7 +16,6 @@ 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,7 +1,3 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use graphene_resource::ResourceHash;
|
||||
|
||||
use crate::{MigrationError, Payload};
|
||||
|
||||
/// How stored history survives a format step.
|
||||
@@ -19,22 +15,6 @@ 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>,
|
||||
/// Blobs that steps moved values into. The load path stores them.
|
||||
pub blobs: HashMap<ResourceHash, Vec<u8>>,
|
||||
/// The base blob of each blob in `blobs`.
|
||||
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
|
||||
@@ -62,10 +42,6 @@ pub trait FormatMigration: Send + Sync {
|
||||
fn migrate_session(&self, session: &Payload) -> Result<Payload, MigrationError> {
|
||||
Ok(session.clone())
|
||||
}
|
||||
/// Transform the whole document after its records are converted. Use this when a change needs state across records.
|
||||
fn migrate_document(&self, _document: &mut DocumentPayloads) -> Result<(), MigrationError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 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::{DocumentPayloads, FormatMigration, HistoryPolicy, Upgrade};
|
||||
pub use format::{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,7 +7,6 @@
|
||||
pub mod v1;
|
||||
pub mod v2;
|
||||
pub mod v3;
|
||||
pub mod v4;
|
||||
pub use v4 as latest;
|
||||
pub use v3 as latest;
|
||||
|
||||
mod steps;
|
||||
@@ -2,4 +2,3 @@
|
||||
|
||||
mod v1_to_v2;
|
||||
mod v2_to_v3;
|
||||
mod v3_to_v4;
|
||||
@@ -1,667 +0,0 @@
|
||||
//! Format step 3 to 4, generated by `cargo run migration snapshot`.
|
||||
|
||||
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. This is the live threshold at version 4.
|
||||
const BLOB_THRESHOLD: usize = 1024;
|
||||
|
||||
/// Move large node input values into blobs. Records are visited in stored order, so the base of a blob is the previous blob of its slot.
|
||||
fn move_values_into_blobs(document: &mut DocumentPayloads) -> Result<(), MigrationError> {
|
||||
let mut blobs = Blobs::default();
|
||||
|
||||
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()?;
|
||||
// Sort by ID so the base choice does not depend on hash map order
|
||||
let mut nodes: Vec<_> = registry.node_instances.iter_mut().collect();
|
||||
nodes.sort_unstable_by_key(|(id, _)| **id);
|
||||
for (id, node) in nodes {
|
||||
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 last blob of each input slot, 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 change the latest blob of a slot.
|
||||
fn prior(&mut self, prior: &mut v4::Prior) {
|
||||
match prior {
|
||||
v4::Prior::Node { node, .. } => self.loose_node(node),
|
||||
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. Its blob is based on the previous blob of the slot.
|
||||
fn write(&mut self, id: v4::NodeId, index: u32, input: &mut v4::NodeInput) {
|
||||
let Some((hash, created)) = self.move_into_blob(input) else { return };
|
||||
|
||||
// Only a newly created blob takes a base. This keeps bases acyclic
|
||||
if let Some(previous) = self.latest.insert((id, index), hash)
|
||||
&& created
|
||||
&& previous != hash
|
||||
{
|
||||
self.bases.insert(hash, previous);
|
||||
}
|
||||
}
|
||||
|
||||
/// The blob that `input` now names, and whether this call created it.
|
||||
fn move_into_blob(&mut self, input: &mut v4::NodeInput) -> Option<(ResourceHash, bool)> {
|
||||
let v4::NodeInput::Value { value, .. } = input else { return None };
|
||||
if let v4::Value::Blob(hash) = value {
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -1,398 +0,0 @@
|
||||
//! 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)
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
//! The step to version 4 moves large node input values into the same blobs that live staging makes.
|
||||
|
||||
use document_graph_storage::blob::{BLOB_THRESHOLD, BlobBytes, decode_blob};
|
||||
use document_graph_storage::{Delta, HotOp, Implementation, Network, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, ResourceId, Session, UserId, Value};
|
||||
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() {
|
||||
// `Value::Blob` is the only change in version 4, so a version 3 document is a live one without blobs
|
||||
let id = NodeId(1);
|
||||
let mut session = Session::with_identity(PeerId(1), UserId(1));
|
||||
let mut node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(1)), 1);
|
||||
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();
|
||||
|
||||
// Both paths hash the same bytes, so the migrated blob equals the staged one
|
||||
let staged_blob = |input: NodeInput| {
|
||||
let mut input = input;
|
||||
input.move_into_blob(&mut BlobBytes::new());
|
||||
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, Path, Token, Type};
|
||||
use syn::{Error, Ident, LitInt, Token, Type};
|
||||
|
||||
/// The stored roots a format step can convert, by the `FormatMigration` method converting each.
|
||||
const ROOTS: &[(&str, &str)] = &[
|
||||
@@ -16,7 +16,6 @@ pub(crate) struct FormatStep {
|
||||
pub from: u32,
|
||||
pub to: u32,
|
||||
roots: Vec<(Ident, Type)>,
|
||||
document: Option<Path>,
|
||||
}
|
||||
|
||||
impl Parse for FormatStep {
|
||||
@@ -35,18 +34,8 @@ 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(", "))));
|
||||
@@ -59,7 +48,7 @@ impl Parse for FormatStep {
|
||||
roots.push((root, input.parse()?));
|
||||
}
|
||||
|
||||
Ok(Self { from, to, roots, document })
|
||||
Ok(Self { from, to, roots })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,14 +75,6 @@ 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;
|
||||
|
||||
@@ -103,7 +84,6 @@ pub(crate) fn expand(core: &TokenStream2, step: &FormatStep) -> TokenStream2 {
|
||||
}
|
||||
#history_policy
|
||||
#(#methods)*
|
||||
#document
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,6 @@ 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. Use it when a change needs state across records.
|
||||
#[proc_macro]
|
||||
pub fn format_migration(input: TokenStream) -> TokenStream {
|
||||
let step = parse_macro_input!(input as format::FormatStep);
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
//! Node migrations work on values, not blobs. Each run sees its blobs decoded, and its output moves large values back into blobs.
|
||||
//! An unchanged value encodes to the same blob, so it does not show up in the diff.
|
||||
|
||||
use crate::RunnerError;
|
||||
use document_graph_storage::blob::{BlobBytes, NewBlobs, decode_blob};
|
||||
use document_graph_storage::{BlobHash, NodeId, NodeInput, Registry, Value};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
/// The blobs of a document, plus the new blobs that migrations create.
|
||||
pub struct MigrationBlobs<'a> {
|
||||
stored: &'a BlobBytes,
|
||||
/// New blobs that are not stored yet.
|
||||
added: BlobBytes,
|
||||
/// The base of each added blob. The base is the blob its input slot held before the migration.
|
||||
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 values from the `stored` blobs of a document.
|
||||
pub fn new(stored: &'a BlobBytes) -> Self {
|
||||
Self {
|
||||
stored,
|
||||
added: BlobBytes::new(),
|
||||
bases: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The blobs that migrations added.
|
||||
pub fn into_added(self) -> NewBlobs {
|
||||
NewBlobs { bytes: self.added, bases: self.bases }
|
||||
}
|
||||
|
||||
/// `registry` with the blobs in the inputs of `nodes` decoded back into values. `None` decodes every node.
|
||||
pub(crate) fn resolve<'r>(&self, registry: &'r Registry, nodes: Option<&[NodeId]>) -> Result<Cow<'r, Registry>, RunnerError> {
|
||||
let ids: Cow<[NodeId]> = match nodes {
|
||||
Some(nodes) => Cow::Borrowed(nodes),
|
||||
None => Cow::Owned(registry.node_instances.keys().copied().collect()),
|
||||
};
|
||||
let holds_blob = |id: &NodeId| registry.node_instances.get(id).is_some_and(|node| node.inputs().iter().any(|slot| slot.input.blob().is_some()));
|
||||
if !ids.iter().any(holds_blob) {
|
||||
return Ok(Cow::Borrowed(registry));
|
||||
}
|
||||
|
||||
let mut resolved = registry.clone();
|
||||
for id in ids.iter() {
|
||||
let Some(node) = resolved.node_instances.get_mut(id) else { continue };
|
||||
for slot in node.inputs_mut() {
|
||||
let NodeInput::Value { value, .. } = &mut slot.input else { continue };
|
||||
let Value::Blob(hash) = *value else { continue };
|
||||
|
||||
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. A new blob is based on the blob its slot held in `source`.
|
||||
pub(crate) fn store(&mut self, migrated: &mut Registry, source: &Registry) {
|
||||
let mut bytes = BlobBytes::new();
|
||||
migrated.move_values_into_blobs(&mut bytes);
|
||||
bytes.retain(|hash, _| !self.stored.contains_key(hash) && !self.added.contains_key(hash));
|
||||
if bytes.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.bases.extend(migrated.blob_bases_since(source).into_iter().filter(|(hash, _)| bytes.contains_key(hash)));
|
||||
self.added.extend(bytes);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,18 @@
|
||||
//! Chains format steps over a document's serialized payloads, before they deserialize into the live types.
|
||||
|
||||
use crate::RunnerError;
|
||||
use migration_core::{DocumentPayloads, FormatMigration, HistoryPolicy};
|
||||
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>,
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -58,7 +69,6 @@ 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,7 +1,6 @@
|
||||
//! 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;
|
||||
@@ -11,10 +10,8 @@ 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::{HistoryOutcome, run_format_migrations};
|
||||
pub use migration_core::DocumentPayloads;
|
||||
pub use format::{DocumentPayloads, HistoryOutcome, run_format_migrations};
|
||||
pub use node::{DeclarationTable, RewrittenHistory, holds, registry_at};
|
||||
pub use order::{migrate_history, migrate_registry, order_migrations, references};
|
||||
|
||||
@@ -52,8 +49,6 @@ 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::{MigrationBlobs, RunnerError};
|
||||
use crate::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,29 +61,12 @@ 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.
|
||||
pub(crate) fn apply_migration(
|
||||
migration: &dyn NodeMigration,
|
||||
source: &Registry,
|
||||
resolver: &dyn DeclarationResolver,
|
||||
host: Option<&dyn MigrationHost>,
|
||||
blobs: &mut MigrationBlobs,
|
||||
) -> Result<Registry, RunnerError> {
|
||||
/// 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> {
|
||||
let anchors = anchors(migration.source(), source, resolver);
|
||||
if anchors.is_empty() {
|
||||
return Ok(source.clone());
|
||||
}
|
||||
|
||||
// A migration that reads beyond its anchors needs every value decoded
|
||||
let reads_beyond_anchors = migration.footprint().reads_network() || migration.asks_compiler();
|
||||
let resolved = blobs.resolve(source, (!reads_beyond_anchors).then_some(anchors.as_slice()))?;
|
||||
|
||||
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);
|
||||
};
|
||||
@@ -316,7 +299,6 @@ 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();
|
||||
@@ -366,7 +348,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, blobs)?;
|
||||
let migrated = apply_migration(migration, &branch.original, resolver, host)?;
|
||||
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::{MigrationBlobs, RewrittenHistory, RunnerError};
|
||||
use crate::{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,15 +76,13 @@ pub fn order_migrations(migrations: &[&'static dyn NodeMigration]) -> Result<Vec
|
||||
|
||||
/// Rewrite `history` through every migration whose source declaration it references, in dependency order. A migration is pending
|
||||
/// even when no live node uses its source, since a removed node keeps its old shape in history and undo can bring it back. `kept` names the
|
||||
/// states a cursor rests on, which even a migration only running at interaction boundaries has to keep. `blobs` resolves
|
||||
/// the blobs that migrations read and collects the blobs they add.
|
||||
/// states a cursor rests on, which even a migration only running at interaction boundaries has to keep.
|
||||
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();
|
||||
@@ -95,7 +93,7 @@ pub fn migrate_history(
|
||||
continue;
|
||||
}
|
||||
|
||||
let step = rewrite_history(migration, &deltas, resolver, host, &kept, blobs)?;
|
||||
let step = rewrite_history(migration, &deltas, resolver, host, &kept)?;
|
||||
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());
|
||||
@@ -106,17 +104,11 @@ 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. 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> {
|
||||
/// `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> {
|
||||
let mut migrated = registry.clone();
|
||||
for migration in order_migrations(migrations)? {
|
||||
migrated = apply_migration(migration, &migrated, resolver, host, blobs)?;
|
||||
migrated = apply_migration(migration, &migrated, resolver, host)?;
|
||||
}
|
||||
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, MigrationBlobs, RunnerError, references, registry_at};
|
||||
use crate::{DeclarationTable, 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,12 +52,7 @@ 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, &mut MigrationBlobs::default())
|
||||
}
|
||||
|
||||
/// Migrate a registry whose inputs name blobs from `blobs`.
|
||||
pub fn migrate_blobs(&self, migration: &dyn NodeMigration, blobs: &mut MigrationBlobs) -> Result<Registry, RunnerError> {
|
||||
apply_migration(migration, &self.registry, &self.table, None, blobs)
|
||||
apply_migration(migration, &self.registry, &self.table, host)
|
||||
}
|
||||
|
||||
pub fn declaration_of(&self, registry: &Registry, node: NodeId) -> Option<Declaration> {
|
||||
@@ -281,11 +276,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(), &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
|
||||
let rewritten = rewrite_history(migration, &history, &table, host, &HashSet::new()).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, &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
|
||||
let expected = apply_migration(migration, &original, &table, host).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),
|
||||
@@ -315,7 +310,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(), &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}"));
|
||||
let rewritten = rewrite_history(migration, &history, &table, host, &HashSet::new()).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]);
|
||||
@@ -325,13 +320,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, &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}"));
|
||||
let mut previous = apply_migration(migration, original.registry(), &table, host).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, &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}, undo {undo}: M failed: {error}"));
|
||||
expected = apply_migration(migration, original.registry(), &table, host).unwrap_or_else(|error| panic!("seed {seed}, undo {undo}: M failed: {error}"));
|
||||
}
|
||||
if expected.value_equal(&previous) {
|
||||
break;
|
||||
|
||||
@@ -31,7 +31,6 @@ 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();
|
||||
@@ -51,7 +50,6 @@ 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();
|
||||
@@ -66,7 +64,6 @@ 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();
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
//! Migrations read values that are stored in blobs. The large values they write go back into blobs.
|
||||
|
||||
use document_graph_storage::blob::{BLOB_THRESHOLD, BlobBytes};
|
||||
use document_graph_storage::{BlobHash, NodeInput, Value};
|
||||
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, together with its blob bytes.
|
||||
fn blob_literal(text: &str, blobs: &mut BlobBytes) -> (NodeInput, BlobHash) {
|
||||
let mut input = literal(text.to_string());
|
||||
input.move_into_blob(blobs);
|
||||
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, MigrationBlobs, RunnerError, migrate_history, order_migrations};
|
||||
use migration_runner::{DeclarationTable, 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(), &mut MigrationBlobs::default()).unwrap();
|
||||
let rewritten = migrate_history(&[&ByCompiler], history.clone(), &table, Some(&host), session.head_rev()).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], &mut MigrationBlobs::default()).unwrap();
|
||||
let rewritten = migrate_history(&[&ByCompiler], history, &table, Some(&host), [inside]).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(), &mut MigrationBlobs::default()).unwrap();
|
||||
migrate_history(&[&GraphReader], history, &table, None, session.head_rev()).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,4 +1,3 @@
|
||||
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, MigrationBlobs, RunnerError, migrate_history, order_migrations};
|
||||
use migration_runner::{DeclarationTable, RunnerError, migrate_history, order_migrations};
|
||||
|
||||
#[test]
|
||||
fn every_migration_registers_once() {
|
||||
@@ -14,7 +14,6 @@ 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),
|
||||
@@ -208,15 +207,7 @@ 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,
|
||||
&mut MigrationBlobs::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let migrated = migrate_history(®istered_migrations(), history.clone(), &table, Some(&compiler::AnswerHost::default()), None).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::{BlobRecord, CursorPosition, CursorSpace, MAX_PACKET_BYTES, PacketError, Role, SyncPacket, SyncPayload};
|
||||
pub use packet::{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::{BlobHash, Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, UserId};
|
||||
use document_graph_storage::{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,9 +82,6 @@ pub struct SyncPayload {
|
||||
pub document_id: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub metadata: HistoryMetadata,
|
||||
/// Every blob that the synced state names. A base comes before the blobs that use it.
|
||||
#[serde(default)]
|
||||
pub blobs: Vec<BlobRecord>,
|
||||
}
|
||||
|
||||
/// Causal broadcast envelope. `seq` numbers the sender's broadcasts from 1 within `epoch`. `seen` is the sender's
|
||||
@@ -99,11 +96,7 @@ pub struct Broadcast {
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum BroadcastBody {
|
||||
/// The records of new blobs that the ops name.
|
||||
HotOps {
|
||||
ops: Vec<HotOp>,
|
||||
blobs: Vec<BlobRecord>,
|
||||
},
|
||||
HotOps(Vec<HotOp>),
|
||||
/// `deltas` are in causal order. `retires` names the hot ops they replace, empty for a plain history transfer.
|
||||
Deltas {
|
||||
deltas: Vec<Delta>,
|
||||
@@ -117,14 +110,6 @@ pub enum BroadcastBody {
|
||||
HeadMove(HeadMove),
|
||||
}
|
||||
|
||||
/// The stored record of a blob. It holds the value in full or as a delta against a base. The transport does not read it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct BlobRecord {
|
||||
pub hash: BlobHash,
|
||||
#[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::{BlobRecord, Broadcast, BroadcastBody, CursorPosition, PacketError, PeerSeq, Role, SyncPacket, SyncPayload};
|
||||
use crate::packet::{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};
|
||||
@@ -326,13 +326,12 @@ impl Replica {
|
||||
self.requested_resources.iter().copied()
|
||||
}
|
||||
|
||||
/// Broadcast staged `ops` together with the records of their new blobs.
|
||||
pub fn broadcast_hot_ops(&mut self, ops: &[HotOp], blobs: Vec<BlobRecord>) -> Result<(), PacketError> {
|
||||
pub fn broadcast_hot_ops(&mut self, ops: &[HotOp]) -> Result<(), PacketError> {
|
||||
if ops.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.resources_stale = true;
|
||||
self.broadcast(BroadcastBody::HotOps { ops: ops.to_vec(), blobs })
|
||||
self.broadcast(BroadcastBody::HotOps(ops.to_vec()))
|
||||
}
|
||||
|
||||
/// Ask the host to undo (`restore == false`) or redo (`restore == true`) this peer's retired interaction.
|
||||
@@ -499,7 +498,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, Vec::new())?;
|
||||
self.broadcast_hot_ops(&unretired)?;
|
||||
if retired.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -693,7 +692,6 @@ 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)))?;
|
||||
@@ -708,7 +706,6 @@ 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)?,
|
||||
@@ -755,7 +752,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, Vec::new())?;
|
||||
self.broadcast_hot_ops(&own_hot_ops)?;
|
||||
|
||||
events.push(Event::Synced);
|
||||
}
|
||||
@@ -879,14 +876,7 @@ impl Replica {
|
||||
|
||||
// A failure is logged rather than abandoning the bookkeeping and the rest of the queue.
|
||||
let applied = match broadcast.body {
|
||||
BroadcastBody::HotOps { ops, blobs } => {
|
||||
// A blob with a missing base is fetched 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))
|
||||
}
|
||||
BroadcastBody::HotOps(ops) => 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 {
|
||||
@@ -1011,7 +1001,7 @@ mod tests {
|
||||
epoch: 1,
|
||||
seq,
|
||||
seen,
|
||||
body: BroadcastBody::HotOps { ops: Vec::new(), blobs: Vec::new() },
|
||||
body: BroadcastBody::HotOps(Vec::new()),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -200,8 +200,7 @@ impl Transport for Room {
|
||||
fn poll(&mut self) -> Vec<TransportEvent> {
|
||||
let mut events = Vec::new();
|
||||
|
||||
// Errs only once the socket loop ended, which its future reports, after handing over the changes before that.
|
||||
for (peer, state) in self.socket.try_update_peers().unwrap_or_default() {
|
||||
for (peer, state) in self.socket.update_peers() {
|
||||
match state {
|
||||
PeerState::Connected => events.push(TransportEvent::PeerConnected(peer)),
|
||||
PeerState::Disconnected => {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use crate::BlobRecord;
|
||||
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, MergeOutcome, PeerId, Registry, ResourceHash, RetiredMarks, Rev, Session};
|
||||
use std::collections::HashSet;
|
||||
|
||||
@@ -69,14 +68,6 @@ pub trait SyncTarget {
|
||||
fn store_resource(&mut self, _hash: ResourceHash, _bytes: &[u8]) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
/// The record of every held blob, for a peer that syncs from this one. A base comes before the blobs that use it.
|
||||
fn blob_records(&self) -> Vec<BlobRecord> {
|
||||
Vec::new()
|
||||
}
|
||||
/// Hold the blobs of records from a peer. A record with a missing base is dropped and later fetched as a missing resource.
|
||||
fn absorb_blob_records(&mut self, _records: Vec<BlobRecord>) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl SyncTarget for Session {
|
||||
|
||||
@@ -1,44 +1,29 @@
|
||||
//! 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> [STROKES=1] cargo test -p peer-transport --test simulation inspect_seed -- --ignored --nocapture`.
|
||||
//! Inspect one run with `SEED=<n> GUESTS=<n> cargo test -p peer-transport --test simulation inspect_seed -- --ignored --nocapture`.
|
||||
|
||||
use document_graph_storage::blob::{BLOB_THRESHOLD, BlobBytes};
|
||||
use document_graph_storage::{
|
||||
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,
|
||||
AttributeDelta, 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::{BlobRecord, Event, Replica, Role, SyncTarget, TargetError, TransportPeerId};
|
||||
use std::cell::Cell;
|
||||
use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, TransportPeerId};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::thread::LocalKey;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
// Per thread, since each test runs its corpus on its own thread
|
||||
thread_local! {
|
||||
static TOTAL_NODES: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_WIRED: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_EXPORTS: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_INPUT_ATTRIBUTES: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_SOURCES: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_COLLECTED: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_REDONE_RETRACTIONS: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_BLOBS: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_BLOB_DELTAS: Cell<usize> = const { Cell::new(0) };
|
||||
static TOTAL_BLOB_FETCHES: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
fn count(counter: &'static LocalKey<Cell<usize>>, amount: usize) {
|
||||
counter.set(counter.get() + amount);
|
||||
}
|
||||
static TOTAL_NODES: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_WIRED: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_EXPORTS: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_INPUT_ATTRIBUTES: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_SOURCES: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_COLLECTED: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL_REDONE_RETRACTIONS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// 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 of each blob. See [`SimTarget::blob_record`].
|
||||
blobs: BlobBytes,
|
||||
blob_records: HashMap<BlobHash, Vec<u8>>,
|
||||
/// History as of the last `flush`.
|
||||
durable_history: Vec<Rev>,
|
||||
flushes: usize,
|
||||
@@ -55,8 +40,6 @@ 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(),
|
||||
@@ -68,37 +51,6 @@ impl SimTarget {
|
||||
fn history_revs(&self) -> Vec<Rev> {
|
||||
self.session.history().map(|delta| delta.id).collect()
|
||||
}
|
||||
|
||||
/// A stand-in for a blob record. It holds the base hash if the base is held, then the bytes. Like a real delta,
|
||||
/// a receiver can only take it when it holds the base. `document-format` tests real deltas.
|
||||
fn blob_record(&self, bytes: &[u8], base: Option<BlobHash>) -> Vec<u8> {
|
||||
let mut record = Vec::new();
|
||||
match base.filter(|base| self.blobs.contains_key(base)) {
|
||||
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 and return the records that peers receive with the ops.
|
||||
fn hold_blobs(&mut self, blobs: BlobBytes, bases: &HashMap<BlobHash, BlobHash>) -> Vec<BlobRecord> {
|
||||
let mut blobs: Vec<_> = blobs.into_iter().filter(|(hash, _)| !self.blobs.contains_key(hash)).collect();
|
||||
blobs.sort_unstable_by_key(|(hash, _)| *hash);
|
||||
|
||||
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 });
|
||||
}
|
||||
count(&TOTAL_BLOBS, records.len());
|
||||
records
|
||||
}
|
||||
}
|
||||
|
||||
impl SyncTarget for SimTarget {
|
||||
@@ -216,67 +168,17 @@ impl SyncTarget for SimTarget {
|
||||
}
|
||||
|
||||
fn missing_resources(&self) -> HashSet<ResourceHash> {
|
||||
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()
|
||||
self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.resources.contains_key(hash)).collect()
|
||||
}
|
||||
|
||||
fn resource_bytes(&self, hash: ResourceHash) -> Option<Vec<u8>> {
|
||||
self.resources.get(&hash).or_else(|| self.blobs.get(&BlobHash(hash))).cloned()
|
||||
self.resources.get(&hash).cloned()
|
||||
}
|
||||
|
||||
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
|
||||
let blob = BlobHash(hash);
|
||||
if self.session.names_blob(blob) {
|
||||
count(&TOTAL_BLOB_FETCHES, 1);
|
||||
let record = self.blob_record(bytes, None);
|
||||
self.blobs.insert(blob, bytes.to_vec());
|
||||
self.blob_records.insert(blob, record);
|
||||
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;
|
||||
}
|
||||
count(&TOTAL_BLOB_DELTAS, 1);
|
||||
&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
|
||||
});
|
||||
// The remaining records need a base this peer lacks. They are fetched in full as missing resources
|
||||
if pending.is_empty() || pending.len() == waiting {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Peer {
|
||||
@@ -339,19 +241,9 @@ impl Peer {
|
||||
|
||||
fn stage(&mut self, op: RegistryDelta) {
|
||||
self.retracted.clear();
|
||||
self.stage_ops(vec![op]).expect("stage");
|
||||
}
|
||||
let hot_ops = self.target.session.stage_computed_ops(vec![op]).expect("stage");
|
||||
|
||||
/// Stage `ops`, move their large values into blobs and broadcast the blob records with them.
|
||||
fn stage_ops(&mut self, mut ops: Vec<RegistryDelta>) -> Result<(), document_graph_storage::CrdtError> {
|
||||
let mut blobs = BlobBytes::new();
|
||||
ops.iter_mut().for_each(|op| op.move_values_into_blobs(&mut blobs));
|
||||
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(())
|
||||
self.replica.broadcast_hot_ops(&hot_ops).expect("broadcast");
|
||||
}
|
||||
|
||||
/// Introduce a resource only this peer holds the bytes for, so every other peer has to fetch them.
|
||||
@@ -363,7 +255,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, Vec::new()).expect("broadcast");
|
||||
self.replica.broadcast_hot_ops(&hot_ops).expect("broadcast");
|
||||
}
|
||||
|
||||
fn retire(&mut self) {
|
||||
@@ -383,26 +275,10 @@ 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, Vec::new()).expect("broadcast");
|
||||
self.replica.broadcast_hot_ops(&staged).expect("broadcast");
|
||||
}
|
||||
}
|
||||
|
||||
/// Edit one input of a live node a few times in a row, like drawing does. Each new blob is based on the one before.
|
||||
fn stroke(&mut self, network: &mut MockNetwork) {
|
||||
let live_nodes: Vec<NodeId> = sorted(self.session().registry().node_instances.keys().copied());
|
||||
let Some(&id) = pick(network, &live_nodes) else { return };
|
||||
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") {
|
||||
@@ -417,11 +293,10 @@ 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 };
|
||||
if self.stage_ops(ops).is_err() {
|
||||
return;
|
||||
}
|
||||
let Ok(hot_ops) = self.target.session.stage_computed_ops(ops) else { return };
|
||||
self.replica.broadcast_hot_ops(&hot_ops).expect("broadcast");
|
||||
self.end_interaction();
|
||||
count(&TOTAL_REDONE_RETRACTIONS, 1);
|
||||
TOTAL_REDONE_RETRACTIONS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Drop every held byte outside the GC root set. `needed` is what present peers name and lack.
|
||||
@@ -432,7 +307,7 @@ impl Peer {
|
||||
self.target.collected_while_needed.extend(dropped);
|
||||
let before = self.target.resources.len();
|
||||
self.target.resources.retain(|hash, _| roots.contains(hash));
|
||||
count(&TOTAL_COLLECTED, before - self.target.resources.len());
|
||||
TOTAL_COLLECTED.fetch_add(before - self.target.resources.len(), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Every hash this peer's registry, history, hot log or retracted steps name, gathered independently of the GC
|
||||
@@ -519,19 +394,6 @@ fn random_value(network: &mut MockNetwork) -> Value {
|
||||
Value::from(serde_json::json!(network.random_below(100)))
|
||||
}
|
||||
|
||||
/// A value large enough to become a blob. The pool is small, so peers sometimes stage the same value at once.
|
||||
fn large_value(network: &mut MockNetwork) -> Value {
|
||||
Value::Str(format!("{}{}", "x".repeat(BLOB_THRESHOLD), network.random_below(64)))
|
||||
}
|
||||
|
||||
/// A literal input value. One in three is 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),
|
||||
@@ -569,16 +431,6 @@ 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 of them arrive as deltas
|
||||
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;
|
||||
@@ -588,7 +440,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_input_value(network),
|
||||
value: random_value(network),
|
||||
exposed: false,
|
||||
},
|
||||
};
|
||||
@@ -762,15 +614,7 @@ fn quiesce(network: &mut MockNetwork, peers: &mut [Peer]) -> usize {
|
||||
panic!("the room never went idle");
|
||||
}
|
||||
|
||||
/// The main kind of step in a run.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Workload {
|
||||
Mixed,
|
||||
/// Half the steps are strokes, like live drawing.
|
||||
Strokes,
|
||||
}
|
||||
|
||||
fn simulate(seed: u64, guest_count: usize, steps: usize, workload: Workload) -> (MockNetwork, Vec<Peer>) {
|
||||
fn simulate(seed: u64, guest_count: usize, steps: usize) -> (MockNetwork, Vec<Peer>) {
|
||||
let mut network = MockNetwork::new(seed);
|
||||
let mut peers = open_room(&mut network, guest_count, seed);
|
||||
|
||||
@@ -780,11 +624,7 @@ fn simulate(seed: u64, guest_count: usize, steps: usize, workload: Workload) ->
|
||||
continue;
|
||||
}
|
||||
|
||||
let action = match workload {
|
||||
Workload::Strokes if network.random_below(2) == 0 => 14,
|
||||
_ => network.random_below(18),
|
||||
};
|
||||
match action {
|
||||
match network.random_below(18) {
|
||||
// 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);
|
||||
@@ -802,7 +642,6 @@ fn simulate(seed: u64, guest_count: usize, steps: usize, workload: Workload) ->
|
||||
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();
|
||||
@@ -1024,14 +863,7 @@ 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()
|
||||
.chain(peer.target.blobs.keys().map(|hash| hash.0))
|
||||
})
|
||||
.flat_map(|(_, peer)| peer.target.resources.keys().chain(&peer.target.collected_while_needed).copied())
|
||||
.collect();
|
||||
|
||||
for (index, peer) in present() {
|
||||
@@ -1054,36 +886,14 @@ fn assert_converged(seed: u64, peers: &[Peer]) {
|
||||
|
||||
#[test]
|
||||
fn peers_converge_under_random_interleavings() {
|
||||
run_corpus(Workload::Mixed, 5000);
|
||||
// The generator's ops are guarded on registry state, so a change can quietly stop producing them.
|
||||
assert!(TOTAL_NODES.get() > 0, "the corpus produced no nodes");
|
||||
assert!(TOTAL_WIRED.get() > 0, "the corpus produced no node-to-node inputs");
|
||||
assert!(TOTAL_EXPORTS.get() > 0, "the corpus set no network exports");
|
||||
assert!(TOTAL_INPUT_ATTRIBUTES.get() > 0, "the corpus wrote no input-slot attributes");
|
||||
assert!(TOTAL_SOURCES.get() > 0, "the corpus never stacked a second source on a resource");
|
||||
assert!(TOTAL_COLLECTED.get() > 0, "garbage collection never dropped a resource");
|
||||
assert!(TOTAL_REDONE_RETRACTIONS.get() > 0, "the corpus never redid a step taken back");
|
||||
assert!(TOTAL_BLOBS.get() > 0, "the corpus staged no blobs");
|
||||
}
|
||||
let seeds = std::env::var("SIM_SEEDS").ok().and_then(|value| value.parse::<u64>().ok()).unwrap_or(5000);
|
||||
|
||||
/// Mostly strokes. Blobs chain, reach peers as deltas and are fetched in full by peers that lack a base.
|
||||
#[test]
|
||||
fn blobs_reach_every_peer_under_strokes() {
|
||||
run_corpus(Workload::Strokes, 10_000);
|
||||
assert!(TOTAL_BLOB_DELTAS.get() > 0, "no blob arrived as a delta against one already held");
|
||||
assert!(TOTAL_BLOB_FETCHES.get() > 0, "no blob was fetched in full for a missing base");
|
||||
}
|
||||
|
||||
/// Run `SIM_SEEDS` seeds (or `default_seeds`) and check that each one converges.
|
||||
/// `SIM_KEEP_GOING` runs every seed and lists all failures. This tells one bug from several.
|
||||
fn run_corpus(workload: Workload, default_seeds: u64) {
|
||||
let seeds = std::env::var("SIM_SEEDS").ok().and_then(|value| value.parse::<u64>().ok()).unwrap_or(default_seeds);
|
||||
// Runs every seed and lists the failures, to tell one bug from several.
|
||||
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, workload);
|
||||
let (_, peers) = simulate(seed, 1 + (seed % 3) as usize, 200);
|
||||
count_coverage(peers[expect_host(seed, &peers)].session().retired_registry());
|
||||
assert_converged(seed, &peers);
|
||||
};
|
||||
@@ -1094,17 +904,25 @@ fn run_corpus(workload: Workload, default_seeds: u64) {
|
||||
}
|
||||
}
|
||||
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) {
|
||||
let inputs = || registry.node_instances.values().flat_map(|node| node.inputs());
|
||||
count(&TOTAL_NODES, registry.node_instances.len());
|
||||
count(&TOTAL_WIRED, inputs().filter(|slot| matches!(slot.input, NodeInput::Node { .. })).count());
|
||||
count(&TOTAL_INPUT_ATTRIBUTES, inputs().filter(|slot| !slot.attributes.is_empty()).count());
|
||||
TOTAL_NODES.fetch_add(registry.node_instances.len(), Ordering::Relaxed);
|
||||
TOTAL_WIRED.fetch_add(inputs().filter(|slot| matches!(slot.input, NodeInput::Node { .. })).count(), Ordering::Relaxed);
|
||||
TOTAL_INPUT_ATTRIBUTES.fetch_add(inputs().filter(|slot| !slot.attributes.is_empty()).count(), Ordering::Relaxed);
|
||||
let exports = registry.networks.values().flat_map(|network| &network.exports).filter(|slot| slot.target.is_some()).count();
|
||||
count(&TOTAL_EXPORTS, exports);
|
||||
TOTAL_EXPORTS.fetch_add(exports, Ordering::Relaxed);
|
||||
// A second source can only come from `AddSource`.
|
||||
count(&TOTAL_SOURCES, registry.resources.values().filter(|entry| entry.sources.len() > 1).count());
|
||||
TOTAL_SOURCES.fetch_add(registry.resources.values().filter(|entry| entry.sources.len() > 1).count(), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// A rejoining guest keeps its `PeerId` but restarts its broadcast sequence, which the room must follow
|
||||
@@ -1136,8 +954,7 @@ 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 workload = if std::env::var_os("STROKES").is_some() { Workload::Strokes } else { Workload::Mixed };
|
||||
let (_, peers) = simulate(seed, guests, 200, workload);
|
||||
let (_, peers) = simulate(seed, guests, 200);
|
||||
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());
|
||||
@@ -1214,7 +1031,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, Workload::Mixed).1).collect::<Vec<_>>();
|
||||
let run = |seeds: u64| (0..seeds).map(|seed| simulate(seed, 1 + (seed % 3) as usize, 200).1).collect::<Vec<_>>();
|
||||
|
||||
let (first, second) = (run(100), run(100));
|
||||
|
||||
|
||||
@@ -208,7 +208,8 @@ pub const COLOR_OVERLAY_BLACK_75: &str = "#000000bf";
|
||||
|
||||
// DOCUMENT
|
||||
pub const FILE_EXTENSION: &str = "graphite";
|
||||
/// Extension of documents saved before the `.gdd` container took the `.graphite` extension. Still opened and imported.
|
||||
/// New document container format. Save writes a `.gdd` with the legacy `.graphite` embedded as a fallback
|
||||
/// during the dual-write soak; `.graphite` stays a supported open/import input.
|
||||
pub const GDD_FILE_EXTENSION: &str = "gdd";
|
||||
pub const DEFAULT_DOCUMENT_NAME: &str = "Untitled Document";
|
||||
pub const MAX_UNDO_HISTORY_LEN: usize = 100; // TODO: Add this to user preferences
|
||||
|
||||
@@ -306,12 +306,13 @@ impl Dispatcher {
|
||||
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.workspace.panel_layout.focus_document;
|
||||
let layout = &self.message_handlers.portfolio_message_handler.workspace.panel_layout;
|
||||
menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data);
|
||||
menu_bar_message_handler.collaboration_panel_open = layout.is_panel_present(PanelType::Collaboration);
|
||||
menu_bar_message_handler.session_panel_open = layout.is_panel_present(PanelType::Session);
|
||||
menu_bar_message_handler.history_panel_open = layout.is_panel_present(PanelType::History);
|
||||
menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers);
|
||||
menu_bar_message_handler.inspector_open = layout.is_panel_present(PanelType::Inspector);
|
||||
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
|
||||
menu_bar_message_handler.reset_node_definitions_on_open = self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open;
|
||||
menu_bar_message_handler.show_storage_preferences = self.message_handlers.preferences_message_handler.show_storage_preferences;
|
||||
|
||||
if let Some(document) = self
|
||||
.message_handlers
|
||||
|
||||
@@ -8,6 +8,7 @@ use crate::messages::portfolio::document::utility_types::network_interface;
|
||||
use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::common_functionality::utility_functions::name_layer_action;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use graph_craft::application_io::resource::{DataSource, ResourceHash};
|
||||
use graph_craft::document::NodeId;
|
||||
@@ -166,6 +167,12 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
return;
|
||||
}
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
let nodes = deleted_with_children.len() + chain_nodes.len();
|
||||
responses.add(match (layers.len() == nodes, nodes) {
|
||||
(true, _) => name_layer_action("Cut", nodes),
|
||||
(false, 1) => DocumentMessage::NameInteraction { action: "Cut a node".into() },
|
||||
(false, count) => DocumentMessage::NameInteraction { action: format!("Cut {count} nodes") },
|
||||
});
|
||||
if !deleted_with_children.is_empty() {
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
node_ids: deleted_with_children,
|
||||
@@ -377,6 +384,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
|
||||
let mut added_nodes = false;
|
||||
|
||||
let pasted = entries.len();
|
||||
for entry in entries.into_iter().rev() {
|
||||
let new_ids: HashMap<_, _> = entry.nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
|
||||
let Some(&root_id) = new_ids.get(&NodeId(0)) else {
|
||||
@@ -388,6 +396,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
if !added_nodes {
|
||||
responses.add(DocumentMessage::DeselectAllLayers);
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(name_layer_action("Pasted", pasted));
|
||||
added_nodes = true;
|
||||
}
|
||||
|
||||
|
||||
+50
-3
@@ -303,11 +303,35 @@ impl PreferencesDialogMessageHandler {
|
||||
// =========
|
||||
// DOCUMENTS
|
||||
// =========
|
||||
{
|
||||
// Soak-only `.gdd` storage options, hidden unless enabled from the developer debug menu.
|
||||
if preferences.show_storage_preferences {
|
||||
let header = vec![TextLabel::new("Documents").italic(true).widget_instance()];
|
||||
|
||||
let save_as_gdd_description = "
|
||||
Save documents in the new .gdd container format (with the legacy .graphite file embedded as a recovery fallback) instead of a plain .graphite file. The .gdd format is still being validated, so this is opt-in for now.\n\
|
||||
\n\
|
||||
*Default: Off.*
|
||||
"
|
||||
.trim();
|
||||
let save_as_gdd_checkbox_id = CheckboxId::new();
|
||||
let save_as_gdd = vec![
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
CheckboxInput::new(preferences.save_as_gdd)
|
||||
.tooltip_label("Save as .gdd")
|
||||
.tooltip_description(save_as_gdd_description)
|
||||
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::SaveAsGdd { enabled: checkbox_input.checked }.into())
|
||||
.for_label(save_as_gdd_checkbox_id)
|
||||
.widget_instance(),
|
||||
TextLabel::new("Save as .gdd")
|
||||
.tooltip_label("Save as .gdd")
|
||||
.tooltip_description(save_as_gdd_description)
|
||||
.for_checkbox(save_as_gdd_checkbox_id)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let save_with_history_description = "
|
||||
Include the document's edit history in saved files.\n\
|
||||
Include the document's edit history in saved files. Only applies with \"Save as .gdd\" enabled.\n\
|
||||
\n\
|
||||
*Default: Off.*
|
||||
"
|
||||
@@ -329,7 +353,30 @@ impl PreferencesDialogMessageHandler {
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
rows.extend_from_slice(&[header, save_with_history]);
|
||||
let validate_description = "
|
||||
Validate every document save, open, and undo by round-tripping it through the .gdd storage format and comparing against the legacy path, logging any mismatch. Useful for debugging the .gdd format during its soak, but the per-edit round-trip has a performance cost.\n\
|
||||
\n\
|
||||
*Default: Off.*
|
||||
"
|
||||
.trim();
|
||||
let validate_checkbox_id = CheckboxId::new();
|
||||
let validate_storage_round_trip = vec![
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
CheckboxInput::new(preferences.validate_storage_round_trip)
|
||||
.tooltip_label("Validate Storage Round-Trip")
|
||||
.tooltip_description(validate_description)
|
||||
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::ValidateStorageRoundTrip { enabled: checkbox_input.checked }.into())
|
||||
.for_label(validate_checkbox_id)
|
||||
.widget_instance(),
|
||||
TextLabel::new("Validate Storage Round-Trip")
|
||||
.tooltip_label("Validate Storage Round-Trip")
|
||||
.tooltip_description(validate_description)
|
||||
.for_checkbox(validate_checkbox_id)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
rows.extend_from_slice(&[header, save_as_gdd, save_with_history, validate_storage_round_trip]);
|
||||
}
|
||||
|
||||
// =============
|
||||
|
||||
@@ -199,6 +199,24 @@ pub enum FrontendMessage {
|
||||
UpdateHistoryPanel {
|
||||
state: crate::messages::portfolio::history::utility_types::HistoryPanelState,
|
||||
},
|
||||
UpdateHistoryGraph {
|
||||
graph: crate::messages::portfolio::history::utility_types::HistoryGraphState,
|
||||
},
|
||||
UpdateHistoryGraphOverlay {
|
||||
open: bool,
|
||||
},
|
||||
/// A History panel step's captured image as an SVG, sent when the GPU is unavailable, which the panel shows wherever a row names `id`.
|
||||
UpdateHistoryThumbnail {
|
||||
id: String,
|
||||
svg: String,
|
||||
},
|
||||
/// A History panel step's captured image as straight RGBA pixels.
|
||||
UpdateHistoryThumbnailPixels {
|
||||
id: String,
|
||||
width: u32,
|
||||
height: u32,
|
||||
pixels: serde_bytes::ByteBuf,
|
||||
},
|
||||
UpdateNodeGraphCursors {
|
||||
cursors: Vec<FrontendRemoteCursor>,
|
||||
},
|
||||
|
||||
@@ -345,6 +345,7 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
|
||||
//
|
||||
// DocumentMessage
|
||||
entry!(DoubleTap(Space); action_dispatch=DocumentMessage::GraphViewOverlayToggle),
|
||||
entry!(KeyDown(KeyH); modifiers=[Alt], action_dispatch=HistoryMessage::GraphOverlayToggle),
|
||||
entry!(KeyDownNoRepeat(Escape); action_dispatch=DocumentMessage::Escape),
|
||||
entry!(KeyDown(Delete); action_dispatch=DocumentMessage::DeleteSelectedLayers),
|
||||
entry!(KeyDown(Backspace); action_dispatch=DocumentMessage::DeleteSelectedLayers),
|
||||
|
||||
@@ -76,7 +76,7 @@ define_layout_target!(
|
||||
NodeGraphControlBar,
|
||||
/// The body of the Inspector containing many collapsable sections.
|
||||
Inspector,
|
||||
CollaborationPanel,
|
||||
SessionPanel,
|
||||
/// The contextual input key/mouse combination shortcuts shown in the status bar at the bottom of the window.
|
||||
StatusBarHints,
|
||||
/// The version information shown in the status bar at the bottom right of the window.
|
||||
|
||||
@@ -21,9 +21,10 @@ pub struct MenuBarMessageHandler {
|
||||
pub has_selection_history: (bool, bool),
|
||||
pub message_logging_verbosity: MessageLoggingVerbosity,
|
||||
pub reset_node_definitions_on_open: bool,
|
||||
pub show_storage_preferences: bool,
|
||||
pub make_path_editable_is_allowed: bool,
|
||||
pub data_panel_open: bool,
|
||||
pub collaboration_panel_open: bool,
|
||||
pub session_panel_open: bool,
|
||||
pub history_panel_open: bool,
|
||||
pub layers_panel_open: bool,
|
||||
pub inspector_open: bool,
|
||||
@@ -60,6 +61,7 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
let message_logging_verbosity_names = self.message_logging_verbosity == MessageLoggingVerbosity::Names;
|
||||
let message_logging_verbosity_contents = self.message_logging_verbosity == MessageLoggingVerbosity::Contents;
|
||||
let reset_node_definitions_on_open = self.reset_node_definitions_on_open;
|
||||
let show_storage_preferences = self.show_storage_preferences;
|
||||
let make_path_editable_is_allowed = self.make_path_editable_is_allowed;
|
||||
|
||||
let about = MenuListEntry::new("About Graphite…")
|
||||
@@ -687,10 +689,10 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleDataPanelOpen))
|
||||
.on_commit(|_| WorkspaceMessage::ToggleDataPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
MenuListEntry::new("Collaboration")
|
||||
.label("Collaboration")
|
||||
.icon(if self.collaboration_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.on_commit(|_| WorkspaceMessage::ToggleCollaborationPanelOpen.into())
|
||||
MenuListEntry::new("Session")
|
||||
.label("Session")
|
||||
.icon(if self.session_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.on_commit(|_| WorkspaceMessage::ToggleSessionPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
MenuListEntry::new("History")
|
||||
.label("History")
|
||||
@@ -738,6 +740,10 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.label("Reset Nodes to Definitions on Open")
|
||||
.icon(if reset_node_definitions_on_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.on_commit(|_| PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen.into()),
|
||||
MenuListEntry::new("Show Storage Preferences")
|
||||
.label("Show Storage Preferences")
|
||||
.icon(if show_storage_preferences { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.on_commit(|_| PreferencesMessage::ToggleShowStoragePreferences.into()),
|
||||
],
|
||||
vec![
|
||||
MenuListEntry::new("Print Trace Logs")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Human-readable pretty-printers for storage test failures: registry-vs-registry and
|
||||
//! runtime-network-vs-runtime-network diffs.
|
||||
//! Human-readable pretty-printers for the dual-write soak's validation checks: registry-vs-registry and
|
||||
//! runtime-network-vs-runtime-network diffs. The callers are gated behind the `validate_storage_round_trip`
|
||||
//! preference, so these ship in release but only run when the soak is turned on.
|
||||
|
||||
use std::fmt::Write;
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
use document_graph_storage::{Declarations, Value};
|
||||
use document_graph_storage::{Declarations, Registry, Value};
|
||||
use graph_craft::application_io::resource::{ResourceHash, ResourceId, ResourceRegistry, ResourceStorage};
|
||||
|
||||
use super::utility_types::network_interface::NodeNetworkInterface;
|
||||
@@ -9,12 +9,19 @@ use super::utility_types::network_interface::editor_delta::{EditorDelta, Staging
|
||||
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, build_interface_from_storage, collect_network_view_settings};
|
||||
use crate::messages::portfolio::history::utility_types::LineChange;
|
||||
|
||||
/// Per-document undo/redo state, kept in the `Gdd` working copy.
|
||||
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
|
||||
/// becoming the authoritative history. Owns the dual-stack bookkeeping push/pop/clear and the cursor's stage/retire/move/verify
|
||||
/// lifecycle, so the handler drives history through one surface rather than three loose fields.
|
||||
///
|
||||
/// Not serialized: a clone shares the working-copy container by `Arc`, so it keeps reading the live working copy.
|
||||
/// Not serialized: the legacy stacks are runtime-only, and a clone shares the working-copy container by
|
||||
/// `Arc`, so it keeps reading the live working copy.
|
||||
#[derive(derivative::Derivative)]
|
||||
#[derivative(Clone, Debug, Default)]
|
||||
pub struct DocumentHistory {
|
||||
/// Stack of document network snapshots for previous history states.
|
||||
legacy_undo_stack: VecDeque<NodeNetworkInterface>,
|
||||
/// Stack of document network snapshots for future history states.
|
||||
legacy_redo_stack: VecDeque<NodeNetworkInterface>,
|
||||
/// The `Gdd` working copy: owns the CRDT `Session` and mirrors edits to disk. `None` until the mount
|
||||
/// future built by `load_document` resolves.
|
||||
#[derivative(Debug = "ignore")]
|
||||
@@ -29,8 +36,8 @@ pub struct DocumentHistory {
|
||||
/// moved without recording it (an upgrade on open), since the recorded batch would then describe only
|
||||
/// part of the distance between the two.
|
||||
needs_whole_document_stage: bool,
|
||||
/// How storage undid each step that redo can bring back, latest last.
|
||||
undo_notes: VecDeque<UndoNote>,
|
||||
/// How storage undid each step on the legacy redo stack, aligned with its top.
|
||||
undo_notes: Vec<UndoNote>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -43,12 +50,57 @@ enum UndoNote {
|
||||
Cursor,
|
||||
}
|
||||
|
||||
/// Why [`DocumentHistory::move_cursor`] produced no interface.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CursorMoveError {
|
||||
/// Nothing to move to, unmounted, or the move itself failed. The cursor did not move.
|
||||
NotMoved,
|
||||
/// The cursor moved but the rebuild from it failed. It stays moved unless the caller reverts it.
|
||||
RebuildFailed,
|
||||
}
|
||||
|
||||
impl DocumentHistory {
|
||||
/// Forget the steps redo could bring back.
|
||||
// ===== Legacy snapshot stacks =====
|
||||
|
||||
/// Push a snapshot onto the undo stack, evicting the oldest entry past the history cap.
|
||||
pub fn push_undo(&mut self, snapshot: NodeNetworkInterface) {
|
||||
Self::push_capped(&mut self.legacy_undo_stack, snapshot);
|
||||
}
|
||||
|
||||
/// Push a snapshot onto the redo stack, evicting the oldest entry past the history cap.
|
||||
pub fn push_redo(&mut self, snapshot: NodeNetworkInterface) {
|
||||
Self::push_capped(&mut self.legacy_redo_stack, snapshot);
|
||||
}
|
||||
|
||||
/// Pop the most recent undo snapshot, or `None` when the stack is empty.
|
||||
pub fn pop_undo(&mut self) -> Option<NodeNetworkInterface> {
|
||||
self.legacy_undo_stack.pop_back()
|
||||
}
|
||||
|
||||
/// Pop the most recent redo snapshot, or `None` when the stack is empty.
|
||||
pub fn pop_redo(&mut self) -> Option<NodeNetworkInterface> {
|
||||
self.legacy_redo_stack.pop_back()
|
||||
}
|
||||
|
||||
/// Drop the most recently pushed undo snapshot (used to cancel a transaction that ended up unmodified).
|
||||
pub fn discard_last_undo(&mut self) {
|
||||
self.legacy_undo_stack.pop_back();
|
||||
}
|
||||
|
||||
/// Clear the redo stack, called when a fresh edit invalidates the redo future.
|
||||
pub fn clear_redo(&mut self) {
|
||||
self.legacy_redo_stack.clear();
|
||||
self.undo_notes.clear();
|
||||
}
|
||||
|
||||
/// Add the resources referenced by every snapshot in both history stacks into `resources`, so
|
||||
/// history-only resources stay alive for legacy undo/redo.
|
||||
pub fn collect_used_resources(&self, resources: &mut HashSet<ResourceId>) {
|
||||
for interface in self.legacy_undo_stack.iter().chain(&self.legacy_redo_stack) {
|
||||
interface.collect_used_resources(resources);
|
||||
}
|
||||
}
|
||||
|
||||
// ===== Gdd working-copy cursor =====
|
||||
|
||||
/// The `Gdd` working copy, `None` until the mount future resolves.
|
||||
@@ -85,84 +137,75 @@ impl DocumentHistory {
|
||||
}
|
||||
}
|
||||
|
||||
/// Undoes the latest step in storage, so it can be redone. Returns whether a step was undone.
|
||||
pub fn undo(&mut self, in_session: bool) -> bool {
|
||||
let Some(note) = self.undo_step(in_session) else { return false };
|
||||
|
||||
self.undo_notes.push_back(note);
|
||||
if self.undo_notes.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
|
||||
self.undo_notes.pop_front();
|
||||
/// Undoes the latest step in storage alone. Returns whether storage undid it.
|
||||
pub fn undo_in_storage(&mut self, in_session: bool) -> bool {
|
||||
if self.legacy_undo_stack.is_empty() {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Undoes the latest step in storage without a way to redo it. Returns whether a step was undone.
|
||||
pub fn discard_step(&mut self, in_session: bool) -> bool {
|
||||
let Some(note) = self.undo_step(in_session) else { return false };
|
||||
|
||||
if matches!(note, UndoNote::Cursor)
|
||||
&& let Some(storage) = self.storage.as_mut()
|
||||
&& let Err(error) = storage.forget_latest_undo()
|
||||
{
|
||||
log::error!("Forgetting the discarded step failed: {error}");
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Takes the latest step back. A hot step is retracted, a retired one is dropped from a session's shared line,
|
||||
/// and otherwise the cursor moves back over it.
|
||||
fn undo_step(&mut self, in_session: bool) -> Option<UndoNote> {
|
||||
// A failed retract may already have taken the step back, so no older step is undone after it
|
||||
let retracted = match self.retract_storage_interaction() {
|
||||
Ok(retracted) => retracted,
|
||||
Err(error) => {
|
||||
log::error!("Taking the storage interaction back failed: {error}");
|
||||
return None;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
if let Some(ops) = retracted {
|
||||
return Some(UndoNote::Retracted(ops));
|
||||
let note = if let Some(ops) = retracted {
|
||||
UndoNote::Retracted(ops)
|
||||
} else if in_session && let Some(rev) = self.undo_retired_step() {
|
||||
UndoNote::Dropped(rev)
|
||||
} else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if let Some(snapshot) = self.pop_undo() {
|
||||
self.push_redo(snapshot);
|
||||
}
|
||||
// A session's history is shared, so its cursor never moves
|
||||
if in_session {
|
||||
return self.undo_retired_step().map(UndoNote::Dropped);
|
||||
}
|
||||
self.move_cursor(true).then_some(UndoNote::Cursor)
|
||||
self.note_undo(note);
|
||||
true
|
||||
}
|
||||
|
||||
/// Brings back the latest undone step. Returns whether it was redone.
|
||||
pub fn redo(&mut self) -> bool {
|
||||
let Some(note) = self.undo_notes.pop_back() else { return false };
|
||||
/// Reverses [`undo_in_storage`](Self::undo_in_storage). Returns whether the next redo step was undone there.
|
||||
pub fn redo_in_storage(&mut self) -> bool {
|
||||
if self.legacy_redo_stack.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let reachable = self.storage.as_ref().is_some_and(|storage| storage.can_change_line());
|
||||
let Some(note) = self
|
||||
.undo_notes
|
||||
.pop_if(|note| matches!(note, UndoNote::Retracted(_)) || (reachable && matches!(note, UndoNote::Dropped(_))))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let line_reachable = self.storage.as_ref().is_some_and(|storage| storage.can_change_line());
|
||||
let redone = match ¬e {
|
||||
UndoNote::Retracted(ops) => self.restage_ops(ops.clone()),
|
||||
UndoNote::Dropped(rev) => line_reachable && self.redo_retired_step(*rev),
|
||||
UndoNote::Cursor => self.move_cursor(false),
|
||||
UndoNote::Dropped(rev) => self.redo_retired_step(*rev),
|
||||
UndoNote::Cursor => true,
|
||||
};
|
||||
if !redone {
|
||||
self.undo_notes.push_back(note);
|
||||
// The note stays paired with its redo snapshot
|
||||
self.undo_notes.push(note);
|
||||
return false;
|
||||
}
|
||||
redone
|
||||
if let Some(snapshot) = self.pop_redo() {
|
||||
self.push_undo(snapshot);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Move the cursor along the retired interaction chain, flushing any open interaction first. Returns whether it moved.
|
||||
fn move_cursor(&mut self, undo: bool) -> bool {
|
||||
self.retire_storage_interaction();
|
||||
let Some(storage) = self.storage.as_mut() else { return false };
|
||||
pub fn note_cursor_undo(&mut self) {
|
||||
self.note_undo(UndoNote::Cursor);
|
||||
}
|
||||
|
||||
let moved = if undo {
|
||||
if !storage.can_undo() {
|
||||
return false;
|
||||
}
|
||||
storage.undo()
|
||||
} else {
|
||||
if !storage.can_redo() {
|
||||
return false;
|
||||
}
|
||||
storage.redo()
|
||||
};
|
||||
moved.inspect_err(|error| log::error!("Storage undo/redo cursor move failed: {error}")).is_ok()
|
||||
pub fn forget_undo_note(&mut self) {
|
||||
self.undo_notes.pop();
|
||||
}
|
||||
|
||||
fn note_undo(&mut self, note: UndoNote) {
|
||||
self.undo_notes.push(note);
|
||||
let evicted = self.undo_notes.len().saturating_sub(self.legacy_redo_stack.len());
|
||||
self.undo_notes.drain(..evicted);
|
||||
}
|
||||
|
||||
fn retract_storage_interaction(&mut self) -> Result<Option<Vec<document_graph_storage::RegistryDelta>>, document_format::Error> {
|
||||
@@ -206,6 +249,13 @@ impl DocumentHistory {
|
||||
result.inspect_err(|error| log::error!("Changing the history line with {change:?} failed: {error}")).is_ok()
|
||||
}
|
||||
|
||||
/// Forgets the legacy snapshots once the head has moved off their line.
|
||||
pub fn clear_legacy(&mut self) {
|
||||
self.legacy_undo_stack.clear();
|
||||
self.legacy_redo_stack.clear();
|
||||
self.undo_notes.clear();
|
||||
}
|
||||
|
||||
pub fn retire_storage_interaction(&mut self) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if let Err(error) = storage.retire_pending_interaction() {
|
||||
@@ -270,7 +320,8 @@ impl DocumentHistory {
|
||||
|
||||
/// Stages what the store recorded since the last drain.
|
||||
///
|
||||
/// This and the whole-document conversion produce the same registry for the same edit. They differ in
|
||||
/// This and the whole-document conversion produce the same registry for the same edit, which
|
||||
/// `verify_round_trip` checks when the `validate_storage_round_trip` preference is on. They differ in
|
||||
/// what they cost and in what they can miss: a conversion sees every change however it was made,
|
||||
/// while this sees only what went through the store, so a write that bypasses it is not persisted.
|
||||
fn stage_recorded(
|
||||
@@ -310,13 +361,39 @@ impl DocumentHistory {
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the `Gdd` undo/redo cursor along the retired interaction chain, flushing any open interaction
|
||||
/// first, and rebuild the interface from the rewound registry using the declaration cache.
|
||||
pub fn move_cursor(&mut self, undo: bool) -> Result<NodeNetworkInterface, CursorMoveError> {
|
||||
self.retire_storage_interaction();
|
||||
|
||||
let storage = self.storage.as_mut().ok_or(CursorMoveError::NotMoved)?;
|
||||
|
||||
let moved = if undo {
|
||||
if !storage.can_undo() {
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
}
|
||||
storage.undo().map(|_| ())
|
||||
} else {
|
||||
if !storage.can_redo() {
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
}
|
||||
storage.redo().map(|_| ())
|
||||
};
|
||||
if let Err(error) = moved {
|
||||
log::error!("Storage undo/redo cursor move failed: {error}");
|
||||
return Err(CursorMoveError::NotMoved);
|
||||
}
|
||||
|
||||
self.rebuild_interface().ok_or(CursorMoveError::RebuildFailed)
|
||||
}
|
||||
|
||||
/// Build a new interface from the working registry and cached declarations. `None` when it doesn't convert.
|
||||
pub fn rebuild_interface(&self) -> Option<NodeNetworkInterface> {
|
||||
let storage = self.storage.as_ref()?;
|
||||
|
||||
storage
|
||||
.registry()
|
||||
.to_runtime_with_full_metadata(&self.declarations, storage.blobs())
|
||||
.to_runtime_with_full_metadata(&self.declarations)
|
||||
.map_err(|error| error.to_string())
|
||||
.and_then(|(network, node_entries, network_entries)| build_interface_from_storage(network, node_entries, network_entries).map_err(|error| error.to_string()))
|
||||
.inspect_err(|error| log::error!("Storage interface rebuild failed: {error}"))
|
||||
@@ -362,4 +439,105 @@ impl DocumentHistory {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Step the cursor back the other way, undoing a [`move_cursor`](Self::move_cursor) in the `undo`
|
||||
/// direction whose rebuild failed.
|
||||
pub fn revert_cursor(&mut self, undo: bool) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
|
||||
let reverted = if undo { storage.redo() } else { storage.undo() };
|
||||
if let Err(error) = reverted {
|
||||
log::error!("Storage undo/redo cursor revert failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
// Soak round-trip verification (runtime-gated by `validate_storage_round_trip`)
|
||||
// These log drift rather than panicking, since the soak can run in release where a crash is
|
||||
// unacceptable; tests still fail loud via the `#[cfg(test)]` panics.
|
||||
|
||||
/// Soak check: the stored registry should equal a fresh `from_runtime`, and a `to_runtime` of it should
|
||||
/// equal the original network.
|
||||
pub fn verify_round_trip(&self, interface: &NodeNetworkInterface, registry: &ResourceRegistry) {
|
||||
use super::diff_networks;
|
||||
use super::document_diff::diff_registries;
|
||||
|
||||
let Some(storage) = &self.storage else { return };
|
||||
let peer = storage.session().peer();
|
||||
|
||||
let network = interface.document_network();
|
||||
let metadata_view = StorageMetadataView::new(interface);
|
||||
|
||||
let conversion = match Registry::convert_from_runtime(network, &metadata_view, registry, peer) {
|
||||
Ok(conversion) => conversion,
|
||||
Err(error) => {
|
||||
log::error!("storage round-trip: from_runtime failed: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let target = &conversion.registry;
|
||||
let declarations = &conversion.declarations;
|
||||
|
||||
let stored = storage.registry();
|
||||
if !stored.value_equal(target) {
|
||||
log::error!("storage round-trip: registry value drift after commit\n{}", diff_registries(stored, target));
|
||||
#[cfg(test)]
|
||||
panic!("storage round-trip: registry value drift after commit");
|
||||
}
|
||||
if !stored.order_consistent(target) {
|
||||
log::error!("storage round-trip: timestamp order inconsistent between stored and target");
|
||||
#[cfg(test)]
|
||||
panic!("storage round-trip: timestamp order inconsistent between stored and target");
|
||||
}
|
||||
|
||||
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(declarations) {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
log::error!("storage round-trip: to_runtime failed: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
if &round_tripped != network {
|
||||
log::error!("storage round-trip: network drift after to_runtime\n{}", diff_networks(network, &round_tripped));
|
||||
#[cfg(test)]
|
||||
panic!("storage round-trip: network drift after to_runtime");
|
||||
}
|
||||
}
|
||||
|
||||
/// Soak check: after a cursor move, the cursor's registry should equal a fresh `from_runtime` of the
|
||||
/// current (legacy-restored) interface. `current_resources` are the resources the live network
|
||||
/// references; history-only resources the cursor dropped are expected, not drift.
|
||||
pub fn verify_cursor_matches_runtime(&self, interface: &NodeNetworkInterface, registry: &ResourceRegistry, current_resources: &HashSet<ResourceId>) {
|
||||
use super::document_diff::diff_registries;
|
||||
|
||||
let Some(storage) = &self.storage else { return };
|
||||
let peer = storage.session().peer();
|
||||
|
||||
let network = interface.document_network();
|
||||
let metadata_view = StorageMetadataView::new(interface);
|
||||
|
||||
let Ok(mut conversion) = Registry::convert_from_runtime(network, &metadata_view, registry, peer) else {
|
||||
log::error!("undo/redo shadow: from_runtime failed");
|
||||
return;
|
||||
};
|
||||
|
||||
let stored = storage.registry();
|
||||
|
||||
// The cursor reverts the interaction's `AddResource` while the runtime keeps the resource alive for
|
||||
// legacy redo, so a history-only resource the cursor dropped is expected. Drop those before comparing.
|
||||
conversion.registry.resources.retain(|id, _| stored.resources.contains_key(id) || current_resources.contains(id));
|
||||
|
||||
if !stored.value_equal(&conversion.registry) {
|
||||
log::error!(
|
||||
"undo/redo shadow: cursor registry diverged from the restored interface\n{}",
|
||||
diff_registries(stored, &conversion.registry)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_capped(stack: &mut VecDeque<NodeNetworkInterface>, snapshot: NodeNetworkInterface) {
|
||||
stack.push_back(snapshot);
|
||||
if stack.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
|
||||
stack.pop_front();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -131,6 +131,10 @@ pub enum DocumentMessage {
|
||||
PasteNodes {
|
||||
nodes: Vec<(NodeId, NodeTemplate)>,
|
||||
},
|
||||
/// Names the open interaction for the History panel, such as after the transaction a tool starts.
|
||||
NameInteraction {
|
||||
action: String,
|
||||
},
|
||||
MoveSelectedLayersToGroup {
|
||||
parent: LayerNodeIdentifier,
|
||||
},
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use super::DocumentHistory;
|
||||
use super::document_diff::diff_networks;
|
||||
use super::node_graph::{document_node_definitions, node_inspector};
|
||||
use super::utility_types::error::EditorError;
|
||||
use super::utility_types::layers_in_view::LayersInView;
|
||||
use super::utility_types::misc::{ANGLE_STEP_MAX, ANGLE_STEP_MIN, GroupFolderType, SNAPPING_OPTION_GROUPS, SnappingState};
|
||||
use super::utility_types::network_interface::{self, NodeNetworkInterface, TransactionStatus};
|
||||
use super::utility_types::nodes::{CollapsedLayers, LayerStructureEntry, SelectedNodes};
|
||||
use super::{CursorMoveError, DocumentHistory};
|
||||
use crate::application::{Environment, GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
|
||||
use crate::consts::{
|
||||
ASYMPTOTIC_EFFECT, BLEND_COUNT_PER_LAYER, COLOR_OVERLAY_GRAY, CURVATURE_COMB_DEFAULT_SCALE, CURVATURE_COMB_MAX_SCALE, CURVATURE_COMB_MIN_SCALE, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION,
|
||||
@@ -178,7 +179,7 @@ pub struct DocumentMessageHandler {
|
||||
pub(crate) container: Option<AnyContainer>,
|
||||
/// Peer changes not yet applied, held until their declarations are cached.
|
||||
#[serde(skip)]
|
||||
pub(crate) pending_remote: document_format::RemoteChanges,
|
||||
pub(crate) pending_remote: document_format::network::RemoteChanges,
|
||||
/// Hash of the document snapshot that was most recently saved to disk by the user.
|
||||
#[serde(skip)]
|
||||
saved_hash: Option<u64>,
|
||||
@@ -469,17 +470,17 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.chain_node_range_selection_reference = None;
|
||||
}
|
||||
DocumentMessage::DocumentHistoryBackward => {
|
||||
self.stage_edits_outside_transaction(&resource_storage.resources_mut());
|
||||
self.undo_with_history(document_id, responses);
|
||||
self.resolve_unresolved_resources(document_id, responses);
|
||||
}
|
||||
DocumentMessage::DocumentHistoryForward => {
|
||||
self.redo_with_history(document_id, responses);
|
||||
self.resolve_unresolved_resources(document_id, responses);
|
||||
self.stage_edits_outside_transaction(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
|
||||
self.undo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses)
|
||||
}
|
||||
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
|
||||
DocumentMessage::ChangeHistoryLine { rev, change } => {
|
||||
self.change_history_line(document_id, rev, change, &resource_storage.resources_mut(), responses);
|
||||
self.resolve_unresolved_resources(document_id, responses);
|
||||
self.change_history_line(document_id, rev, change, &resource_storage.resources_mut(), preferences.validate_storage_round_trip, responses)
|
||||
}
|
||||
DocumentMessage::NameInteraction { action } => {
|
||||
if let Some(storage) = self.history.storage_mut() {
|
||||
storage.name_interaction(&action);
|
||||
}
|
||||
}
|
||||
DocumentMessage::DocumentStructureChanged => {
|
||||
if layers_panel_open {
|
||||
@@ -1048,6 +1049,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let layer_id = LayerNodeIdentifier::new_unchecked(layer_node_id);
|
||||
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
responses.add(DocumentMessage::NameInteraction { action: "Added an image".into() });
|
||||
|
||||
let layer = graph_modification_utils::new_image_layer(data, layer_node_id, layer_parent, responses);
|
||||
|
||||
@@ -1109,6 +1111,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let layer_id = LayerNodeIdentifier::new_unchecked(layer_node_id);
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(DocumentMessage::NameInteraction { action: "Added an SVG".into() });
|
||||
|
||||
let layer = graph_modification_utils::new_svg_layer(svg, transform, !place_at_origin, layer_node_id, layer_parent, responses);
|
||||
|
||||
@@ -1260,15 +1263,16 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::SaveDocument | DocumentMessage::SaveDocumentAs => {
|
||||
responses.add(PortfolioMessage::AutoSaveActiveDocument);
|
||||
|
||||
// Save as a `.gdd` container or a plain legacy `.graphite`, per the editor preference.
|
||||
let save_as_gdd = preferences.save_as_gdd;
|
||||
let include_history = preferences.save_with_history;
|
||||
let extension = if save_as_gdd { GDD_FILE_EXTENSION } else { FILE_EXTENSION };
|
||||
let name = format!("{}.{}", self.name.clone(), extension);
|
||||
|
||||
// Saved as a `.gdd` container under the `.graphite` extension
|
||||
let name = format!("{}.{FILE_EXTENSION}", self.name.clone());
|
||||
|
||||
// A document opened from a `.gdd` file is saved back under the `.graphite` extension
|
||||
// Keep the path's extension in sync with the chosen format so bytes and filename agree.
|
||||
let path = match message {
|
||||
DocumentMessage::SaveDocumentAs => None,
|
||||
_ => self.path.clone().map(|path| path.with_extension(FILE_EXTENSION)),
|
||||
_ => self.path.clone().map(|path| path.with_extension(extension)),
|
||||
};
|
||||
if path.is_some() || environment.is_web() {
|
||||
responses.add(DocumentMessage::MarkAsSaved);
|
||||
@@ -1282,19 +1286,20 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let export_load_handle = resource_storage.resources();
|
||||
|
||||
responses.add(async move {
|
||||
document.resources.collect_garbage(document.used_resources().as_ref());
|
||||
document.resources.collect_garbage(document.used_resources(false).as_ref());
|
||||
document.resources.embed_resources(resources_load_handle).await;
|
||||
|
||||
// Legacy .graphite blob with resources embedded inline, so it is self-contained and also
|
||||
// serves as the .gdd recovery fallback.
|
||||
let legacy_document = document.serialize_document().into_bytes();
|
||||
|
||||
// Export the working copy with the legacy blob embedded, falling back to the bare
|
||||
// A .gdd exports the working copy with the legacy blob embedded, falling back to the bare
|
||||
// blob when there is no working copy or the export fails.
|
||||
let content = match document.history.storage() {
|
||||
Some(storage) => storage
|
||||
let content = match (save_as_gdd, document.history.storage()) {
|
||||
(false, _) => legacy_document,
|
||||
(true, Some(storage)) => storage
|
||||
.export_to_bytes(
|
||||
document_format::ExportFormat::Zip,
|
||||
document_format::ExportFormat::Xz,
|
||||
document_format::ExportOptions {
|
||||
include_history,
|
||||
..Default::default()
|
||||
@@ -1307,7 +1312,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
log::error!("Save: building .gdd export failed, falling back to legacy .graphite: {error}");
|
||||
legacy_document
|
||||
}),
|
||||
None => {
|
||||
(true, None) => {
|
||||
log::warn!("Save: working copy not mounted yet, saving legacy .graphite only");
|
||||
legacy_document
|
||||
}
|
||||
@@ -1320,7 +1325,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
folder,
|
||||
filters: vec![FileFilter {
|
||||
name: "Graphite Document".into(),
|
||||
extensions: vec![FILE_EXTENSION.into()],
|
||||
extensions: vec![extension.into()],
|
||||
mime_types: Vec::new(),
|
||||
}],
|
||||
content: content.into(),
|
||||
@@ -1674,10 +1679,11 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
// Note: A transaction should never be started in a scope that mutates the network interface, since it will only be run after that scope ends.
|
||||
DocumentMessage::StartTransaction => {
|
||||
self.stage_edits_outside_transaction(&resource_storage.resources_mut());
|
||||
self.stage_edits_outside_transaction(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
|
||||
self.end_storage_interaction();
|
||||
|
||||
self.network_interface.start_transaction();
|
||||
self.history.push_undo(self.network_interface.clone());
|
||||
// Push the UpdateOpenDocumentsList message to the bus in order to update the save status of the open documents
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
@@ -1693,6 +1699,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
},
|
||||
DocumentMessage::CancelTransaction => {
|
||||
self.network_interface.finish_transaction();
|
||||
self.history.discard_last_undo();
|
||||
}
|
||||
DocumentMessage::CommitTransaction => {
|
||||
if self.network_interface.transaction_status() == TransactionStatus::Finished {
|
||||
@@ -1701,7 +1708,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.network_interface.finish_transaction();
|
||||
self.history.clear_redo();
|
||||
|
||||
self.commit_storage_snapshot(&resource_storage.resources_mut());
|
||||
self.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
|
||||
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
@@ -1719,7 +1726,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
return;
|
||||
}
|
||||
|
||||
self.abort_steps(document_id, undo_count, &resource_storage.resources_mut(), responses);
|
||||
for _ in 0..undo_count {
|
||||
self.undo(viewport, responses);
|
||||
}
|
||||
|
||||
self.network_interface.finish_transaction();
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
@@ -2434,6 +2443,10 @@ impl DocumentMessageHandler {
|
||||
self.history.storage()
|
||||
}
|
||||
|
||||
pub fn declarations(&self) -> &document_graph_storage::Declarations {
|
||||
self.history.declarations()
|
||||
}
|
||||
|
||||
/// Mutable access to the `Gdd` working copy.
|
||||
pub fn storage_mut(&mut self) -> Option<&mut document_format::GddV1> {
|
||||
self.history.storage_mut()
|
||||
@@ -2465,7 +2478,7 @@ impl DocumentMessageHandler {
|
||||
/// The batch boundary: everything the interface recorded since the last one is this commit's batch.
|
||||
/// Draining happens whether or not a working copy is mounted, so the buffer cannot grow across a
|
||||
/// session that never mounts one.
|
||||
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage) {
|
||||
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
|
||||
self.network_interface.settle_definitions();
|
||||
let deltas = self.network_interface.take_deltas();
|
||||
if self.history.storage().is_none() {
|
||||
@@ -2474,13 +2487,18 @@ impl DocumentMessageHandler {
|
||||
|
||||
let view_settings = self.storage_view_settings();
|
||||
self.history.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, byte_store);
|
||||
|
||||
// The interface lags the registry until peer changes are applied
|
||||
if validate && self.pending_remote.is_empty() {
|
||||
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
|
||||
}
|
||||
}
|
||||
|
||||
/// Stages edits made after a transaction finished, such as those queued behind an `AddTransaction`, whose commit runs
|
||||
/// first. They belong to the undo step that just ended, so they must reach storage before it closes.
|
||||
fn stage_edits_outside_transaction(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage) {
|
||||
fn stage_edits_outside_transaction(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
|
||||
if self.network_interface.transaction_status() == TransactionStatus::Finished && self.network_interface.has_deltas() {
|
||||
self.commit_storage_snapshot(byte_store);
|
||||
self.commit_storage_snapshot(byte_store, validate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2527,42 +2545,32 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the `Gdd` undo/redo cursor, swap in the interface rebuilt from it, and autosave so the legacy
|
||||
/// document matches the cursor. `had_oracle` records whether the legacy snapshot already applied, so the
|
||||
/// rebuild can be compared against it.
|
||||
fn drive_storage_undo_redo(&mut self, document_id: DocumentId, had_oracle: bool, undo: bool, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
match self.history.move_cursor(undo) {
|
||||
Ok(rebuilt) => {
|
||||
self.apply_gdd_cursor_rebuild(rebuilt, had_oracle, validate, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
|
||||
}
|
||||
Err(CursorMoveError::NotMoved) => {}
|
||||
// Without the legacy snapshot the interface stayed put, so the cursor has to follow it back.
|
||||
Err(CursorMoveError::RebuildFailed) => {
|
||||
if !had_oracle {
|
||||
self.history.revert_cursor(undo);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuild the resource registry from storage, or keep it on failure. `Resource` inputs resolve through it.
|
||||
fn refresh_resource_registry(&mut self) {
|
||||
let Some(storage) = self.history.storage() else { return };
|
||||
|
||||
let mut resource_registry = match storage.registry().to_resource_registry() {
|
||||
Ok(resource_registry) => resource_registry,
|
||||
Err(error) => {
|
||||
log::error!("Failed to rebuild the resource registry from storage: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// Preserve completed resolutions across undo and redo
|
||||
let stored_resources = &storage.registry().resources;
|
||||
for resolved in self.resources.registry.resolved() {
|
||||
let Some(&hash) = resolved.hash else { continue };
|
||||
|
||||
match resource_registry.info(&resolved.id) {
|
||||
// Storage has its own hash, or a peer changed where the resource comes from
|
||||
Some(stored) if stored.hash.is_some() || stored.sources != resolved.sources => continue,
|
||||
Some(_) => {}
|
||||
// Kept for a redo of the undone step that added it
|
||||
None if !stored_resources.contains_key(&resolved.id) => resolved.sources.iter().for_each(|source| resource_registry.push_source_back(&resolved.id, source.clone())),
|
||||
// Storage holds it with neither a hash nor sources
|
||||
None => continue,
|
||||
}
|
||||
resource_registry.resolve(&resolved.id, hash);
|
||||
}
|
||||
|
||||
self.resources.registry = resource_registry;
|
||||
}
|
||||
|
||||
/// Queues resolving the resources that history left without a hash, as applying a peer's changes does.
|
||||
fn resolve_unresolved_resources(&self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
|
||||
if self.resources.registry.unresolved().next().is_some() {
|
||||
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
|
||||
match storage.registry().to_resource_registry() {
|
||||
Ok(resource_registry) => self.resources.registry = resource_registry,
|
||||
Err(error) => log::error!("Failed to rebuild the resource registry from storage: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2585,10 +2593,7 @@ impl DocumentMessageHandler {
|
||||
&& let Some(gdd) = self.history.storage()
|
||||
{
|
||||
let peer = gdd.session().peer();
|
||||
match self
|
||||
.network_interface
|
||||
.reconcile_remote(gdd.registry(), self.history.declarations(), gdd.blobs(), &changes.touched, peer)
|
||||
{
|
||||
match self.network_interface.reconcile_remote(gdd.registry(), self.history.declarations(), &changes.touched, peer) {
|
||||
Ok(reconciled) => {
|
||||
self.finish_remote_reconcile(reconciled, changes.touched.resources, responses);
|
||||
return true;
|
||||
@@ -2604,7 +2609,7 @@ impl DocumentMessageHandler {
|
||||
|
||||
match self.history.rebuild_interface() {
|
||||
Some(rebuilt) => {
|
||||
self.apply_gdd_cursor_rebuild(rebuilt, responses);
|
||||
self.apply_gdd_cursor_rebuild(rebuilt, false, false, responses);
|
||||
true
|
||||
}
|
||||
None => {
|
||||
@@ -2647,11 +2652,15 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
/// Swap in the interface rebuilt from the `Gdd` cursor. Always overwrites the interface.
|
||||
fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, responses: &mut VecDeque<Message>) {
|
||||
fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
rebuilt.copy_all_transient_view_state(&self.network_interface);
|
||||
std::mem::swap(&mut rebuilt.resolved_types, &mut self.network_interface.resolved_types);
|
||||
rebuilt.load_structure();
|
||||
|
||||
if validate && had_oracle {
|
||||
self.compare_rebuild_against_legacy(&rebuilt);
|
||||
}
|
||||
|
||||
self.network_interface = rebuilt;
|
||||
self.pending_remote = Default::default();
|
||||
if let Some(gdd) = self.history.storage_mut() {
|
||||
@@ -2659,6 +2668,11 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
self.refresh_resource_registry();
|
||||
|
||||
if validate {
|
||||
let current_resources: std::collections::HashSet<_> = self.used_resources(false).iter().copied().collect();
|
||||
self.history.verify_cursor_matches_runtime(&self.network_interface, &self.resources.registry, ¤t_resources);
|
||||
}
|
||||
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
|
||||
@@ -2666,6 +2680,17 @@ impl DocumentMessageHandler {
|
||||
responses.add(NodeGraphMessage::SendWires);
|
||||
}
|
||||
|
||||
/// Check if the rebuilt network equals the legacy-restored one. Logs drift (panics in tests).
|
||||
fn compare_rebuild_against_legacy(&self, rebuilt: &NodeNetworkInterface) {
|
||||
let legacy = self.network_interface.document_network();
|
||||
let candidate = rebuilt.document_network();
|
||||
if candidate != legacy {
|
||||
log::error!("undo/redo rebuild diverged from the legacy snapshot\n{}", diff_networks(legacy, candidate));
|
||||
#[cfg(test)]
|
||||
panic!("undo/redo rebuild diverged from the legacy snapshot")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn serialize_document(&self) -> String {
|
||||
let val = serde_json::to_string(self);
|
||||
// We fully expect the serialization to succeed
|
||||
@@ -2962,67 +2987,46 @@ impl DocumentMessageHandler {
|
||||
paths
|
||||
}
|
||||
|
||||
pub fn undo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
|
||||
// Settled before storage moves, so the glide's offsets don't outlive the step
|
||||
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
// The storage path skips `undo`, which settles a glide before the snapshot moves
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
|
||||
// The legacy snapshot predates peers' writes, so follow only what storage changed
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
if self.history.undo(self.is_in_session()) {
|
||||
if self.history.undo_in_storage(self.is_in_session()) {
|
||||
self.follow_storage_changes(stored_name, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn redo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
if self.history.redo() {
|
||||
self.follow_storage_changes(stored_name, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes back the open transaction along with the `undo_count - 1` steps before it, leaving nothing to redo.
|
||||
fn abort_steps(&mut self, document_id: DocumentId, undo_count: usize, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) {
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
|
||||
let open_transaction_has_edits = self.network_interface.transaction_status() == TransactionStatus::Modified;
|
||||
if open_transaction_has_edits {
|
||||
// Staged so they are taken back with the steps before them
|
||||
self.commit_storage_snapshot(byte_store);
|
||||
}
|
||||
let steps = if open_transaction_has_edits { undo_count } else { undo_count.saturating_sub(1) };
|
||||
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
let in_session = self.is_in_session();
|
||||
let discarded = (0..steps).take_while(|_| self.history.discard_step(in_session)).count();
|
||||
if discarded == 0 {
|
||||
// A session's history is shared, so no legacy snapshot may be installed
|
||||
if self.is_in_session() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Staging the open transaction's edits made storage's own redo unreachable
|
||||
if open_transaction_has_edits {
|
||||
self.history.clear_redo();
|
||||
}
|
||||
self.follow_storage_changes(stored_name, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
|
||||
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
|
||||
self.history.push_redo(previous_network);
|
||||
self.history.note_cursor_undo();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
self.drive_storage_undo_redo(document_id, legacy_applied, true, validate, responses);
|
||||
}
|
||||
|
||||
/// Makes a History panel change in storage and drops the steps redo could bring back, which are off the head's line.
|
||||
fn change_history_line(&mut self, document_id: DocumentId, rev: Rev, change: LineChange, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) {
|
||||
/// Makes a History panel change in storage and drops the legacy snapshots, which are off the head's line.
|
||||
fn change_history_line(&mut self, document_id: DocumentId, rev: Rev, change: LineChange, byte_store: &dyn ResourceStorage, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
}
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
responses.add(EventMessage::ToolAbort);
|
||||
self.stage_edits_outside_transaction(byte_store);
|
||||
self.stage_edits_outside_transaction(byte_store, validate);
|
||||
self.history.retire_storage_interaction();
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
if !self.history.change_line(rev, change) {
|
||||
return;
|
||||
}
|
||||
self.history.clear_redo();
|
||||
self.history.clear_legacy();
|
||||
self.follow_storage_changes(stored_name, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
@@ -3045,6 +3049,78 @@ impl DocumentMessageHandler {
|
||||
self.storage().is_some_and(|gdd| gdd.role().is_some())
|
||||
}
|
||||
|
||||
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
|
||||
fn install_history_snapshot(&mut self, mut network_interface: NodeNetworkInterface, viewport: &ViewportMessageHandler) -> NodeNetworkInterface {
|
||||
// Set the previous network navigation metadata to the current navigation metadata
|
||||
network_interface.copy_all_navigation_metadata(&self.network_interface);
|
||||
std::mem::swap(&mut network_interface.resolved_types, &mut self.network_interface.resolved_types);
|
||||
|
||||
// Update the metadata transform based on document PTZ
|
||||
let transform = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
|
||||
network_interface.set_document_to_viewport_transform(transform);
|
||||
|
||||
// Ensure document structure is loaded so that updating the selected nodes has the correct metadata
|
||||
network_interface.load_structure();
|
||||
|
||||
std::mem::replace(&mut self.network_interface, network_interface)
|
||||
}
|
||||
|
||||
pub fn undo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
|
||||
// If there is no history return and don't broadcast SelectionChanged
|
||||
let network_interface = self.history.pop_undo()?;
|
||||
// Settled first, so the interface stored for redo keeps none of the offsets of a glide underway
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
let previous_network = self.install_history_snapshot(network_interface, viewport);
|
||||
|
||||
// Push the UpdateOpenDocumentsList message to the bus in order to update the save status of the open documents
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
|
||||
|
||||
// TODO: Remove once the footprint is used to load the imports/export distances from the edge
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
|
||||
Some(previous_network)
|
||||
}
|
||||
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
if self.history.redo_in_storage() {
|
||||
self.follow_storage_changes(stored_name, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
|
||||
return;
|
||||
}
|
||||
if self.is_in_session() {
|
||||
return;
|
||||
}
|
||||
|
||||
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
|
||||
self.history.push_undo(previous_network);
|
||||
self.history.forget_undo_note();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
self.drive_storage_undo_redo(document_id, legacy_applied, false, validate, responses);
|
||||
}
|
||||
|
||||
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
|
||||
// If there is no history return and don't broadcast SelectionChanged
|
||||
let network_interface = self.history.pop_redo()?;
|
||||
// Settled first, as when undoing
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
let previous_network = self.install_history_snapshot(network_interface, viewport);
|
||||
|
||||
// Push the UpdateOpenDocumentsList message to the bus in order to update the save status of the open documents
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
responses.add(NodeGraphMessage::SendWires);
|
||||
Some(previous_network)
|
||||
}
|
||||
|
||||
pub fn current_hash(&self) -> u64 {
|
||||
self.network_interface.document_network().current_hash()
|
||||
}
|
||||
@@ -3783,7 +3859,7 @@ impl DocumentMessageHandler {
|
||||
]
|
||||
}
|
||||
|
||||
pub fn update_document_widgets(&self, responses: &mut VecDeque<Message>, animation_is_playing: bool, time: Duration) {
|
||||
pub fn update_document_widgets(&self, responses: &mut VecDeque<Message>, animation_is_playing: bool, time: Duration, history_graph_open: bool) {
|
||||
let mut widgets = vec![
|
||||
IconButton::new("PlaybackToStart", 24)
|
||||
.tooltip_label("Restart Animation")
|
||||
@@ -3868,6 +3944,14 @@ impl DocumentMessageHandler {
|
||||
|
||||
widgets.extend([
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextButton::new("History")
|
||||
.icon("HistoryUndo")
|
||||
.tooltip_label(if history_graph_open { "Hide the history graph" } else { "Show the history graph" })
|
||||
.tooltip_description("Every step and branch of the document's history, drawn over the viewport.")
|
||||
.tooltip_shortcut(action_shortcut!(HistoryMessageDiscriminant::GraphOverlayToggle))
|
||||
.on_update(|_| HistoryMessage::GraphOverlayToggle.into())
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextButton::new("Node Graph")
|
||||
.icon(if self.graph_view_overlay_open { "GraphViewOpen" } else { "GraphViewClosed" })
|
||||
.hover_icon(if self.graph_view_overlay_open { "GraphViewClosed" } else { "GraphViewOpen" })
|
||||
@@ -4255,7 +4339,7 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
pub fn garbage_collect_resources(&mut self) {
|
||||
let used_resources = self.used_resources();
|
||||
let used_resources = self.used_resources(true);
|
||||
self.resources.collect_garbage(&used_resources);
|
||||
}
|
||||
|
||||
@@ -4263,10 +4347,12 @@ impl DocumentMessageHandler {
|
||||
self.history.resource_gc_roots()
|
||||
}
|
||||
|
||||
/// The resources the current network references.
|
||||
pub fn used_resources(&self) -> Box<[ResourceId]> {
|
||||
pub fn used_resources(&self, include_history: bool) -> Box<[ResourceId]> {
|
||||
let mut resources = HashSet::new();
|
||||
self.network_interface.collect_used_resources(&mut resources);
|
||||
if include_history {
|
||||
self.history.collect_used_resources(&mut resources);
|
||||
}
|
||||
resources.into_iter().collect::<Vec<_>>().into_boxed_slice()
|
||||
}
|
||||
}
|
||||
@@ -4610,31 +4696,6 @@ mod document_message_handler_tests {
|
||||
use crate::messages::portfolio::document::utility_types::misc::GridType;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn deleting_the_bottom_layer_leaves_the_layer_above_it_the_empty_stack_value() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.draw_rect(200., 0., 300., 100.).await;
|
||||
|
||||
let [top, bottom] = editor.active_document().metadata().all_layers().collect::<Vec<_>>()[..] else {
|
||||
panic!("there should be two layers")
|
||||
};
|
||||
let stack_bottom = |editor: &EditorTestUtils, layer: LayerNodeIdentifier| {
|
||||
editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.input_from_connector(&InputConnector::node_at_index(layer.to_node(), 0), &[])
|
||||
.cloned()
|
||||
};
|
||||
let empty_stack = stack_bottom(&editor, bottom);
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![bottom.to_node()] }).await;
|
||||
editor.handle_message(DocumentMessage::DeleteSelectedLayers).await;
|
||||
|
||||
assert_eq!(stack_bottom(&editor, top), empty_stack);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_gradient_bakes_round_trip_through_serialization() {
|
||||
let document = DocumentMessageHandler {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
#[cfg(test)]
|
||||
pub(crate) mod document_diff;
|
||||
mod document_history;
|
||||
mod document_message;
|
||||
@@ -15,7 +14,8 @@ pub mod overlays;
|
||||
pub mod resource;
|
||||
pub mod utility_types;
|
||||
|
||||
pub(crate) use document_history::DocumentHistory;
|
||||
pub(crate) use document_diff::diff_networks;
|
||||
pub(crate) use document_history::{CursorMoveError, DocumentHistory};
|
||||
#[doc(inline)]
|
||||
pub use document_message::{DocumentMessage, DocumentMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
|
||||
@@ -1448,13 +1448,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
Ok(vec![choices])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"vec2_uv".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false)])
|
||||
}),
|
||||
);
|
||||
map
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
|
||||
use crate::messages::tool::common_functionality::edit_target::{EditTarget, ResolvedEditTarget};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
|
||||
use crate::messages::tool::common_functionality::utility_functions::make_path_editable_is_allowed;
|
||||
use crate::messages::tool::common_functionality::utility_functions::{make_path_editable_is_allowed, name_layer_action};
|
||||
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
|
||||
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
|
||||
use crate::messages::viewport::Position;
|
||||
@@ -450,10 +450,18 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
return;
|
||||
};
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
node_ids: selected_nodes.selected_nodes().cloned().collect::<Vec<_>>(),
|
||||
delete_children,
|
||||
});
|
||||
let node_ids: Vec<NodeId> = selected_nodes.selected_nodes().cloned().collect();
|
||||
let layers = node_ids.iter().filter(|node_id| network_interface.is_layer(node_id, selection_network_path)).count();
|
||||
if !node_ids.is_empty() {
|
||||
responses.add(match (layers == node_ids.len(), node_ids.len()) {
|
||||
(true, _) => name_layer_action("Deleted", layers),
|
||||
(false, 1) => DocumentMessage::NameInteraction { action: "Deleted a node".into() },
|
||||
(false, count) => DocumentMessage::NameInteraction {
|
||||
action: format!("Deleted {count} nodes"),
|
||||
},
|
||||
});
|
||||
}
|
||||
responses.add(NodeGraphMessage::DeleteNodes { node_ids, delete_children });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
const TEMPLATE_DIRECTORY: &str = "../node-graph/compiler-spike/workloads/templates";
|
||||
|
||||
/// Draws three rectangle layers with the Rectangle tool and saves the document as the compiler spike's layer template.
|
||||
/// Run with `cargo test -p graphite-editor export_compiler_spike_templates -- --ignored`, then rerun the spike's workload export.
|
||||
#[tokio::test]
|
||||
#[ignore]
|
||||
async fn export_compiler_spike_templates() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
for i in 0..3 {
|
||||
let offset = i as f64 * 20.;
|
||||
editor.draw_rect(offset, offset, offset + 10., offset + 10.).await;
|
||||
}
|
||||
|
||||
std::fs::create_dir_all(TEMPLATE_DIRECTORY).unwrap();
|
||||
std::fs::write(format!("{TEMPLATE_DIRECTORY}/rectangle-layers.graphite"), editor.active_document().serialize_document()).unwrap();
|
||||
}
|
||||
@@ -4,7 +4,6 @@ use crate::messages::frontend::utility_types::PersistedState;
|
||||
use crate::messages::portfolio::document_storage_io::document_key;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::test_utils::EditorTestUtils;
|
||||
use document_container::archive::ArchiveFormat;
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
|
||||
fn dispatch(editor: &mut EditorTestUtils, message: impl Into<Message>) -> Vec<FrontendMessage> {
|
||||
@@ -119,22 +118,20 @@ async fn legacy_only_container_gets_storage() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn saving_writes_a_zip_archive_with_the_graphite_extension() {
|
||||
async fn legacy_save_format_still_keeps_a_working_copy() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
let id = new_document(&mut editor, "Saved");
|
||||
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled: false });
|
||||
let id = new_document(&mut editor, "Legacy");
|
||||
let container = container(&editor, id).await;
|
||||
assert!(editor.active_document().storage().is_some(), "every document gets a working copy, whatever the save format");
|
||||
assert!(container.exists("manifest.json").await);
|
||||
|
||||
let saved = dispatch(&mut editor, DocumentMessage::SaveDocumentAs);
|
||||
let (name, content) = saved
|
||||
.iter()
|
||||
.find_map(|message| match message {
|
||||
FrontendMessage::TriggerSaveDocument { name, content, .. } => Some((name.clone(), content.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the save is sent to the frontend");
|
||||
assert_eq!(name, "Saved.graphite");
|
||||
assert_eq!(ArchiveFormat::detect(&content), Some(ArchiveFormat::Zip));
|
||||
let name = saved.iter().find_map(|message| match message {
|
||||
FrontendMessage::TriggerSaveDocument { name, .. } => Some(name.clone()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(name.as_deref(), Some("Legacy.graphite"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -205,6 +202,20 @@ async fn closing_removes_the_stored_document() {
|
||||
assert!(portfolio(&editor).persisted_state_snapshot().documents.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn storage_preference_keeps_the_working_copy() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
let id = new_document(&mut editor, "Toggle");
|
||||
let container = container(&editor, id).await;
|
||||
assert!(editor.active_document().storage().is_some());
|
||||
assert!(container.exists("legacy.graphite").await);
|
||||
|
||||
for enabled in [false, true] {
|
||||
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled });
|
||||
assert!(editor.active_document().storage().is_some(), "the preference only picks the save format");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unreadable_document_is_reported_and_kept_until_discarded() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -38,10 +38,9 @@ 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, &blobs).expect("to_runtime_with_full_metadata failed");
|
||||
let (_converted_network, entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).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();
|
||||
@@ -168,9 +167,8 @@ 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, &blobs).expect("to_runtime_with_full_metadata failed");
|
||||
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).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);
|
||||
@@ -285,9 +283,8 @@ 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, &blobs).expect("to_runtime_with_full_metadata failed");
|
||||
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).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");
|
||||
|
||||
@@ -386,7 +383,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, &conversion.blob_bytes).expect("to_runtime failed");
|
||||
let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime failed");
|
||||
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
|
||||
|
||||
let rebuilt_metadata = rebuilt.network_metadata(&[]).expect("the rebuilt document network should resolve");
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
//!
|
||||
//! Shared fixtures live in [`test_support`].
|
||||
|
||||
mod compiler_spike_templates;
|
||||
mod lifecycle_tests;
|
||||
mod metadata_tests;
|
||||
mod round_trip_tests;
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
//! End-to-end storage round-trip tests: drive real edits through the editor, push the document
|
||||
//! through a fresh in-memory `Gdd` (stage → retire → persist), reopen from the same container, and
|
||||
//! assert the reopened document matches. Exercises the full persistence pipeline (conversion,
|
||||
//! postcard codecs, hot-op retirement, file layout, replay-on-open).
|
||||
//! postcard codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
|
||||
//! `verify_storage_round_trip` only checks in-process without an actual save/reopen.
|
||||
|
||||
use crate::messages::resource_storage::ResourcesHandle;
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{NodeMetadataSource, PeerId, UserId, to_value};
|
||||
use graph_craft::application_io::resource::{DataSource, HashMapResourceStorage, ResourceHash, ResourceId};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::test_support::{RoundTrip, node_locations, node_paths, round_trip_through_gdd};
|
||||
@@ -170,7 +171,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, reopened.blobs()).expect("to_runtime");
|
||||
let (rebuilt_network, node_entries, network_entries) = reopened.registry().to_runtime_with_full_metadata(&declarations).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.
|
||||
@@ -184,7 +185,7 @@ async fn edit_after_open_commits_cleanly() {
|
||||
// Mirror the live sequence via the real `commit_storage_snapshot`: initial commit after open, then a
|
||||
// deletion, then commit again. Deletion (not addition) is the trigger, since it emits a `RemoveNode`
|
||||
// whose retire/reverse is where "Target node does not exist" surfaced live.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("at least one layer");
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
@@ -333,7 +334,7 @@ async fn live_undo_shadows_storage_cursor() {
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
// Capture the loaded state as the base interaction, then make a real edit (fires CommitTransaction).
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
let before_edit = editor.active_document().network_interface.document_network().clone();
|
||||
editor.draw_ellipse(50., 50., 150., 150.).await;
|
||||
let after_edit = editor.active_document().network_interface.document_network().clone();
|
||||
@@ -451,7 +452,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, reopened.blobs()).expect("to_runtime");
|
||||
let (rebuilt_network, node_entries, network_entries) = reopened.registry().to_runtime_with_full_metadata(&declarations).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);
|
||||
@@ -474,7 +475,7 @@ async fn live_undo_new_document_draw_rect() {
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
// Mount-time snapshot: capture the new-document graph as the base interaction.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
|
||||
let before_rect = editor.active_document().network_interface.document_network().clone();
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
@@ -561,7 +562,7 @@ async fn undo_image_paste_resources_subset_of_runtime() {
|
||||
editor.new_document().await;
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
|
||||
editor.handle_message(paste_named_image()).await;
|
||||
|
||||
@@ -572,7 +573,7 @@ async fn undo_image_paste_resources_subset_of_runtime() {
|
||||
let stored: std::collections::BTreeSet<_> = storage.registry().resources.keys().copied().collect();
|
||||
|
||||
// Every resource the restored network still references must be in the cursor.
|
||||
let current: std::collections::BTreeSet<_> = document.used_resources().iter().copied().collect();
|
||||
let current: std::collections::BTreeSet<_> = document.used_resources(false).iter().copied().collect();
|
||||
assert!(
|
||||
current.is_subset(&stored),
|
||||
"cursor is missing a resource the restored network references: current={current:?} stored={stored:?}"
|
||||
@@ -593,7 +594,7 @@ async fn undo_twice_steps_cursor_two_interactions() {
|
||||
editor.new_document().await;
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
let base = editor.active_document().network_interface.document_network().clone();
|
||||
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
@@ -614,7 +615,7 @@ async fn undo_twice_steps_cursor_two_interactions() {
|
||||
// cached for redo though its node is gone, so a naive snapshot would re-detect it as a new `AddResource`
|
||||
// and retire a phantom interaction, knocking the cursor out of lockstep. Scoping the snapshot to
|
||||
// network-referenced resources must keep this a no-op.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
|
||||
// Second undo: removes the rectangle, back to the loaded base. The cursor must step a second interaction
|
||||
// and land on the base, not one short.
|
||||
@@ -633,7 +634,7 @@ async fn undo_twice_steps_cursor_two_interactions() {
|
||||
}
|
||||
|
||||
/// Assert the `Gdd` cursor's stored registry matches a fresh `from_runtime` of the current interface (node
|
||||
/// set, network set, per-network export wiring).
|
||||
/// set, network set, per-network export wiring), mirroring the live `verify_cursor_matches_runtime` check.
|
||||
/// The runtime's resource set may be a superset (it keeps undone resources alive for redo), but every
|
||||
/// resource the current network references must be present.
|
||||
fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
|
||||
@@ -669,15 +670,15 @@ async fn pasted_image_resource_survives_inserting_a_node() {
|
||||
editor.new_document().await;
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
|
||||
editor.handle_message(paste_named_image()).await;
|
||||
editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER)).await;
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
|
||||
let document = editor.active_document();
|
||||
let stored: std::collections::BTreeSet<_> = document.storage().expect("storage mounted").registry().resources.keys().copied().collect();
|
||||
let used: std::collections::BTreeSet<_> = document.used_resources().iter().copied().collect();
|
||||
let used: std::collections::BTreeSet<_> = document.used_resources(false).iter().copied().collect();
|
||||
assert!(used.is_subset(&stored), "storage lost a resource the network references: used={used:?} stored={stored:?}");
|
||||
}
|
||||
|
||||
@@ -688,117 +689,14 @@ async fn pasted_image_resource_survives_storage_mounting_after_the_paste() {
|
||||
|
||||
editor.handle_message(paste_named_image()).await;
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
|
||||
let document = editor.active_document();
|
||||
let stored: std::collections::BTreeSet<_> = document.storage().expect("storage mounted").registry().resources.keys().copied().collect();
|
||||
let used: std::collections::BTreeSet<_> = document.used_resources().iter().copied().collect();
|
||||
let used: std::collections::BTreeSet<_> = document.used_resources(false).iter().copied().collect();
|
||||
assert!(used.is_subset(&stored), "storage lost a resource the network references: used={used:?} stored={stored:?}");
|
||||
}
|
||||
|
||||
/// Pastes an image and points it at a resource from `source` that is staged before it resolves, then resolves it, giving the resource and its hash.
|
||||
async fn image_resource_resolved_after_staging(editor: &mut EditorTestUtils, source: DataSource) -> (ResourceId, ResourceHash) {
|
||||
use graph_craft::document::DocumentNodeImplementation;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::raster_nodes::std_nodes::image;
|
||||
|
||||
editor.new_document().await;
|
||||
let byte_store = mount_in_memory_storage(editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.handle_message(paste_named_image()).await;
|
||||
|
||||
// Point the image at a resource that is still being fetched, so its entry is staged without a hash
|
||||
let image_node_id = editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.document_network()
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == image::IDENTIFIER))
|
||||
.map(|(id, _)| *id)
|
||||
.expect("the pasted image should be an Image node");
|
||||
let resource_id = ResourceId::new();
|
||||
editor.active_document_mut().resources.registry.push_source_back(&resource_id, source.clone());
|
||||
editor.dispatch(DocumentMessage::StartTransaction);
|
||||
editor.dispatch(NodeGraphMessage::SetInputValue {
|
||||
node_id: image_node_id,
|
||||
input_index: image::ResourceInput::INDEX,
|
||||
value: TaggedValue::Resource(resource_id).into(),
|
||||
});
|
||||
editor.dispatch(DocumentMessage::CommitTransaction);
|
||||
let stored = editor
|
||||
.active_document()
|
||||
.storage()
|
||||
.expect("storage mounted")
|
||||
.registry()
|
||||
.resources
|
||||
.get(&resource_id)
|
||||
.map(|entry| entry.hash);
|
||||
assert_eq!(stored, Some(None), "storage should hold the resource without its hash");
|
||||
|
||||
// The fetch finishes, which caches a font's hash for a later resolve
|
||||
let data: Arc<[u8]> = Image::new(2, 2, Color::BLACK).to_png().into();
|
||||
let hash = ResourceHash::from(data.as_ref());
|
||||
let document_id = editor.portfolio_message_handler().active_document_id.expect("a document is open");
|
||||
editor.dispatch(ResourceStorageMessage::Store { data });
|
||||
editor.dispatch(PortfolioMessage::DocumentPassMessage {
|
||||
document_id,
|
||||
message: ResourceMessage::Resolved { resource_id, source, hash }.into(),
|
||||
});
|
||||
|
||||
(resource_id, hash)
|
||||
}
|
||||
|
||||
/// Undo and redo keep the hash of a resource resolved after its entry was staged.
|
||||
#[tokio::test]
|
||||
async fn resource_resolved_after_staging_stays_resolved_through_undo_and_redo() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
// An embedded source can't be fetched again, so only the runtime's resolution keeps it resolved
|
||||
let (resource_id, hash) = image_resource_resolved_after_staging(&mut editor, DataSource::Embedded).await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
// Undo and redo the rectangle, then the step that set the resource
|
||||
for (message, step) in [
|
||||
(DocumentMessage::Undo, "undoing the rectangle"),
|
||||
(DocumentMessage::Redo, "redoing the rectangle"),
|
||||
(DocumentMessage::Undo, "undoing the rectangle again"),
|
||||
(DocumentMessage::Undo, "undoing the resource change"),
|
||||
(DocumentMessage::Redo, "redoing the resource change"),
|
||||
] {
|
||||
editor.dispatch(message);
|
||||
let document = editor.active_document();
|
||||
let registry = &document.resources.registry;
|
||||
assert!(registry.unresolved().next().is_none(), "{step} left a resource unresolved, which stops rendering");
|
||||
assert!(document.used_resources().iter().all(|id| registry.hash(id).is_some()), "{step} left a used resource without its hash");
|
||||
}
|
||||
assert_eq!(editor.active_document().resources.registry.hash(&resource_id), Some(hash));
|
||||
}
|
||||
|
||||
/// A resource that history leaves without its hash is resolved again.
|
||||
#[tokio::test]
|
||||
async fn resource_left_unresolved_by_history_is_resolved_again() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
// A font resolves again from its cached hash, without a download
|
||||
let font = DataSource::Font {
|
||||
family: "Test Family".into(),
|
||||
style: Some("Regular (400)".into()),
|
||||
};
|
||||
let (resource_id, hash) = image_resource_resolved_after_staging(&mut editor, font).await;
|
||||
|
||||
// No snapshot uses the resource once its step is undone, so collection drops the runtime's resolution
|
||||
editor.dispatch(DocumentMessage::Undo);
|
||||
editor.active_document_mut().garbage_collect_resources();
|
||||
assert!(
|
||||
editor.active_document().resources.registry.info(&resource_id).is_none(),
|
||||
"garbage collection should drop the undone step's resource"
|
||||
);
|
||||
|
||||
editor.dispatch(DocumentMessage::Redo);
|
||||
let registry = &editor.active_document().resources.registry;
|
||||
assert_eq!(registry.hash(&resource_id), Some(hash), "redoing the step should resolve its resource again");
|
||||
assert!(registry.unresolved().next().is_none(), "redoing the step left a resource unresolved, which stops rendering");
|
||||
}
|
||||
|
||||
/// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real
|
||||
/// autosave path) runs against it. Returns the byte store the document's resources resolve through.
|
||||
fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> ResourcesHandle {
|
||||
@@ -830,7 +728,7 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
|
||||
// First autosave: captures the loaded document. `verify_storage_round_trip` panics on drift.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
let history_after_open = editor.active_document().storage().unwrap().session().history().count();
|
||||
|
||||
// Snapshot the network, then make a real modification.
|
||||
@@ -839,7 +737,7 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
|
||||
let after_edit = editor.active_document().network_interface.document_network().clone();
|
||||
assert_ne!(before_edit, after_edit, "drawing a rectangle should change the document network");
|
||||
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
editor.active_document_mut().retire_storage_interaction();
|
||||
let history_after_edit = editor.active_document().storage().unwrap().session().history().count();
|
||||
assert!(
|
||||
@@ -853,7 +751,7 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
|
||||
assert_eq!(after_undo, before_edit, "undo should restore the pre-edit network");
|
||||
|
||||
// Autosaving the undone state still round-trips cleanly (no drift panic).
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
}
|
||||
|
||||
/// Manual edits ride a saved document as a folded `VectorModification`, so opening the artworks carrying the most
|
||||
@@ -1080,13 +978,13 @@ async fn undoing_a_hot_step_takes_it_back_and_redo_stages_it_again() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
editor.active_document_mut().retire_storage_interaction();
|
||||
let history_base = editor.active_document().storage().unwrap().session().history().count();
|
||||
let before_edit = editor.active_document().network_interface.document_network().clone();
|
||||
|
||||
editor.draw_rect(64., 64., 192., 192.).await;
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
let after_edit = editor.active_document().network_interface.document_network().clone();
|
||||
assert_ne!(after_edit, before_edit);
|
||||
assert!(!editor.active_document().storage().unwrap().session().hot_log().is_empty(), "the step is hot");
|
||||
@@ -1096,7 +994,7 @@ async fn undoing_a_hot_step_takes_it_back_and_redo_stages_it_again() {
|
||||
let storage = editor.active_document().storage().unwrap();
|
||||
assert!(storage.session().hot_log().is_empty(), "the step was taken back, not retired: {:?}", storage.session().hot_log());
|
||||
assert_eq!(storage.session().history().count(), history_base, "nothing entered history");
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
// The step held for redo keeps its declaration bytes from collection
|
||||
let storage = editor.active_document().storage().unwrap();
|
||||
assert!(
|
||||
@@ -1109,46 +1007,5 @@ async fn undoing_a_hot_step_takes_it_back_and_redo_stages_it_again() {
|
||||
let storage = editor.active_document().storage().unwrap();
|
||||
assert!(!storage.session().hot_log().is_empty(), "the redone step is staged afresh");
|
||||
assert_eq!(storage.session().history().count(), history_base);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
}
|
||||
|
||||
/// Draws three ellipses, undoes all of them, redoes them and one more, then undoes once. `retire` retires each
|
||||
/// drawing first, so the steps undo through the cursor rather than by retraction.
|
||||
async fn redone_steps_undo_one_at_a_time(retire: bool) {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
|
||||
for offset in [0., 200., 400.] {
|
||||
editor.draw_ellipse(offset, 0., offset + 100., 100.).await;
|
||||
if retire {
|
||||
editor.active_document_mut().retire_storage_interaction();
|
||||
}
|
||||
}
|
||||
let layer_count = |editor: &EditorTestUtils| editor.active_document().metadata().all_layers().count();
|
||||
assert_eq!(layer_count(&editor), 3);
|
||||
|
||||
for expected in [2, 1, 0] {
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(layer_count(&editor), expected, "undoing down to {expected} ellipses");
|
||||
}
|
||||
for expected in [1, 2, 3, 3] {
|
||||
editor.handle_message(DocumentMessage::Redo).await;
|
||||
assert_eq!(layer_count(&editor), expected, "redoing up to {expected} ellipses");
|
||||
}
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(layer_count(&editor), 2, "undo takes back only the last redone ellipse");
|
||||
assert_cursor_matches_runtime(editor.active_document(), "after undoing a redone step");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn redone_hot_steps_undo_one_at_a_time() {
|
||||
redone_steps_undo_one_at_a_time(false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn redone_retired_steps_undo_one_at_a_time() {
|
||||
redone_steps_undo_one_at_a_time(true).await;
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
}
|
||||
@@ -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, reopened.blobs()).expect("to_runtime_with_full_metadata");
|
||||
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).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();
|
||||
|
||||
|
||||
+8
-59
@@ -6,7 +6,6 @@ use crate::consts::{GRID_SIZE, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction};
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -43,6 +42,9 @@ fn new_artboard_message(id: NodeId) -> GraphOperationMessage {
|
||||
async fn invariants_hold_through_basic_editing_flow() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
// This test covers the interface's structural invariants. The storage dual-write is out of its scope and asserted by the storage round-trip tests.
|
||||
editor.editor.handle_message(PreferencesMessage::ValidateStorageRoundTrip { enabled: false });
|
||||
|
||||
editor.new_document().await;
|
||||
assert_invariants(&editor, "after opening a new document");
|
||||
|
||||
@@ -1176,6 +1178,8 @@ fn fed_inputs(editor: &EditorTestUtils, output_connector: &OutputConnector, netw
|
||||
async fn dragging_a_dot_out_of_an_import_takes_over_the_wires_the_import_fed() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
// TODO: Remove once staging the recorded edits stores a node wired to an import inside a subgraph as it is, instead of drifting from it
|
||||
editor.handle_message(PreferencesMessage::ValidateStorageRoundTrip { enabled: false }).await;
|
||||
|
||||
let merge = editor.create_node_by_name_at(merge_definition(), 0, 0).await;
|
||||
let path = vec![merge];
|
||||
@@ -2992,6 +2996,9 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire
|
||||
|
||||
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
|
||||
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
|
||||
// TODO: Remove once staging the recorded edits stores a node wired to an import inside a subgraph as it is, instead of drifting from it
|
||||
editor.handle_message(PreferencesMessage::ValidateStorageRoundTrip { enabled: false }).await;
|
||||
|
||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
|
||||
editor.handle_message(NodeGraphMessage::AddImport).await;
|
||||
@@ -3644,61 +3651,3 @@ async fn dropping_a_map_node_onto_a_wire_keeps_its_wired_mapped_input() {
|
||||
);
|
||||
assert_eq!(network_interface.document_network().nodes.len(), node_count);
|
||||
}
|
||||
|
||||
/// Pairs of layers in the root network whose boxes in the graph, which span their chains, intersect.
|
||||
fn overlapping_layers(editor: &EditorTestUtils) -> Vec<(LayerNodeIdentifier, LayerNodeIdentifier)> {
|
||||
let document = editor.active_document();
|
||||
let layers: Vec<_> = document.metadata().all_layers().collect();
|
||||
let bounds = |layer: LayerNodeIdentifier| document.network_interface.node_bounding_box(&layer.to_node(), &[]).expect("a layer should have a box in the graph");
|
||||
|
||||
let mut overlapping = Vec::new();
|
||||
for (index, &first) in layers.iter().enumerate() {
|
||||
for &second in &layers[index + 1..] {
|
||||
let ([first_min, first_max], [second_min, second_max]) = (bounds(first), bounds(second));
|
||||
if first_min.cmplt(second_max).all() && second_min.cmplt(first_max).all() {
|
||||
overlapping.push((first, second));
|
||||
}
|
||||
}
|
||||
}
|
||||
overlapping
|
||||
}
|
||||
|
||||
async fn group_selected_layers(editor: &mut EditorTestUtils) {
|
||||
editor
|
||||
.handle_message(DocumentMessage::GroupSelectedLayers {
|
||||
group_folder_type: GroupFolderType::Layer,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn grouping_the_top_layer_leaves_no_layers_overlapping_in_the_graph() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.draw_rect(50., 50., 150., 150.).await;
|
||||
|
||||
group_selected_layers(&mut editor).await;
|
||||
|
||||
assert_eq!(overlapping_layers(&editor), Vec::new());
|
||||
assert_invariants(&editor, "after grouping the top layer");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn grouping_a_group_moves_the_layer_below_it_past_all_of_its_contents() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.draw_rect(50., 50., 150., 150.).await;
|
||||
let bottom = editor.active_document().metadata().all_layers().last().expect("the bottom rectangle should be a layer");
|
||||
editor.draw_rect(100., 100., 200., 200.).await;
|
||||
editor.handle_message(DocumentMessage::SelectAllLayers).await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesRemove { nodes: vec![bottom.to_node()] }).await;
|
||||
group_selected_layers(&mut editor).await;
|
||||
assert_eq!(overlapping_layers(&editor), Vec::new(), "grouping the top two layers should leave none overlapping");
|
||||
|
||||
group_selected_layers(&mut editor).await;
|
||||
|
||||
assert_eq!(overlapping_layers(&editor), Vec::new());
|
||||
assert_invariants(&editor, "after grouping a group");
|
||||
}
|
||||
+2
-2
@@ -717,7 +717,7 @@ async fn assert_remote_reconcile_reproduces(edit: impl FnOnce(&mut EditorTestUti
|
||||
}
|
||||
peer.stage_computed_ops(constructed.ops).expect("the peer applies the batch");
|
||||
|
||||
mirror.reconcile_remote(peer.registry(), &declarations, &baseline.blob_bytes, &touched, PEER).expect("reconcile");
|
||||
mirror.reconcile_remote(peer.registry(), &declarations, &touched, PEER).expect("reconcile");
|
||||
|
||||
let edited = &editor.active_document().network_interface;
|
||||
assert!(
|
||||
@@ -898,7 +898,7 @@ async fn reconciling_an_untouched_node_changes_nothing() {
|
||||
let reconciled = editor
|
||||
.active_document_mut()
|
||||
.network_interface
|
||||
.reconcile_remote(&baseline.registry, &baseline.declarations, &baseline.blob_bytes, &touched, PEER)
|
||||
.reconcile_remote(&baseline.registry, &baseline.declarations, &touched, PEER)
|
||||
.expect("reconcile");
|
||||
|
||||
assert!(reconciled.networks.is_empty(), "nothing differed, so nothing should have been applied: {:?}", reconciled.networks);
|
||||
|
||||
@@ -1085,82 +1085,10 @@ impl NodeNetworkInterface {
|
||||
self.take_over_outward_wires(layer.to_node(), network_path);
|
||||
}
|
||||
self.unload_upstream_node_click_targets(vec![layer.to_node()], network_path);
|
||||
self.push_stacks_below_ancestors_past_their_content(layer.to_node(), network_path);
|
||||
|
||||
self.remove_orphaned_dots(network_path);
|
||||
}
|
||||
|
||||
/// Moves the layers stacked below each layer that `layer` is nested within down past that layer's grown content.
|
||||
fn push_stacks_below_ancestors_past_their_content(&mut self, layer: NodeId, network_path: &[NodeId]) {
|
||||
let mut visited = HashSet::new();
|
||||
let mut ancestor = self.content_parent(layer, network_path, &mut visited);
|
||||
while let Some(parent) = ancestor {
|
||||
let stack_below = self
|
||||
.input_from_connector(&InputConnector::primary_input(parent), network_path)
|
||||
.and_then(NodeInput::as_node)
|
||||
.filter(|stack_below| self.is_layer(stack_below, network_path));
|
||||
if let (Some(stack_below), Some(parent_position)) = (stack_below, self.position(&parent, network_path))
|
||||
&& let Some(stack_below_position) = self.position(&stack_below, network_path)
|
||||
{
|
||||
let content_bottom_row = self
|
||||
.upstream_nodes_below_layer(&parent, network_path)
|
||||
.iter()
|
||||
.filter_map(|node_id| self.stacked_box_rows(node_id, network_path))
|
||||
.map(|(_, bottom)| bottom)
|
||||
.fold(parent_position.y + STACK_VERTICAL_GAP, i32::max);
|
||||
if content_bottom_row > stack_below_position.y {
|
||||
self.shift_stack_down(stack_below, content_bottom_row - stack_below_position.y, network_path);
|
||||
}
|
||||
}
|
||||
ancestor = self.content_parent(parent, network_path, &mut visited);
|
||||
}
|
||||
}
|
||||
|
||||
/// Shifts a stack of layers down by `rows`, along with the absolutely positioned content they own, which would otherwise stay behind.
|
||||
fn shift_stack_down(&mut self, stack_top: NodeId, rows: i32, network_path: &[NodeId]) {
|
||||
let stack = self
|
||||
.upstream_flow_back_from_nodes(vec![stack_top], network_path, FlowType::PrimaryFlow)
|
||||
.take_while(|node_id| self.is_layer(node_id, network_path))
|
||||
.collect::<Vec<_>>();
|
||||
let absolute_content = stack
|
||||
.iter()
|
||||
.flat_map(|layer| self.upstream_nodes_below_layer(layer, network_path))
|
||||
.filter(|node_id| self.is_absolute(node_id, network_path))
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
self.shift_node(&stack_top, IVec2::new(0, rows), network_path);
|
||||
for node_id in absolute_content {
|
||||
self.shift_node(&node_id, IVec2::new(0, rows), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer whose content holds the stack `layer` is part of, reached through any chain nodes feeding that layer.
|
||||
/// `visited` stops the walk on a cyclic graph, which concurrent edits can produce.
|
||||
fn content_parent(&self, layer: NodeId, network_path: &[NodeId], visited: &mut HashSet<NodeId>) -> Option<NodeId> {
|
||||
let mut current = layer;
|
||||
while visited.insert(current) {
|
||||
let consumers = self.with_outward_wires(network_path, |outward_wires| outward_wires.get(&OutputConnector::primary_output(current)).cloned())??;
|
||||
|
||||
let mut layer_stacked_upon = None;
|
||||
for consumer in consumers {
|
||||
let Some(consumer_node) = consumer.node_id() else { continue };
|
||||
if !self.is_layer(&consumer_node, network_path) {
|
||||
if self.is_chain(&consumer_node, network_path) {
|
||||
return self.downstream_layer_for_chain_node(&consumer_node, network_path);
|
||||
}
|
||||
} else if consumer.input_index() == 0 {
|
||||
layer_stacked_upon = Some(consumer_node);
|
||||
} else {
|
||||
return Some(consumer_node);
|
||||
}
|
||||
}
|
||||
current = layer_stacked_upon?;
|
||||
}
|
||||
|
||||
log::error!("Cycle reached while finding the content parent of layer {layer}");
|
||||
None
|
||||
}
|
||||
|
||||
/// Shifts `upstream_node_id` and everything stacked below it down until a layer needing
|
||||
/// `height_above` rows above it and `height_below` below fits between it and `post_layer_position`.
|
||||
///
|
||||
|
||||
+2
-10
@@ -3,7 +3,6 @@
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
use document_graph_storage::blob::BlobBytes;
|
||||
use document_graph_storage::to_runtime::ConversionError;
|
||||
use document_graph_storage::{Declarations, NetworkId as StorageNetworkId, NodeId as StorageNodeId, Registry, RuntimeProjection, Touched};
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkId, NetworkLocation, NodeId, NodeInput, NodeNetwork};
|
||||
@@ -46,15 +45,8 @@ type StorageIndex = HashMap<StorageNodeId, (NetworkLocation, NodeId)>;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
/// Applies what the registry holds differently for the touched entities. Can fail part-way, and a retry is safe.
|
||||
pub(crate) fn reconcile_remote(
|
||||
&mut self,
|
||||
registry: &Registry,
|
||||
declarations: &Declarations,
|
||||
blobs: &BlobBytes,
|
||||
touched: &Touched,
|
||||
peer: document_graph_storage::PeerId,
|
||||
) -> Result<Reconciled, ReconcileError> {
|
||||
let projection = registry.runtime_projection(declarations, blobs);
|
||||
pub(crate) fn reconcile_remote(&mut self, registry: &Registry, declarations: &Declarations, touched: &Touched, peer: document_graph_storage::PeerId) -> Result<Reconciled, ReconcileError> {
|
||||
let projection = registry.runtime_projection(declarations);
|
||||
let index = self.pin_storage_identities(peer);
|
||||
let mut reconciled = Reconciled::default();
|
||||
|
||||
|
||||
+1
-17
@@ -10,7 +10,6 @@ use interpreted_executor::dynamic_executor::{NodeTypes, ResolvedDocumentNodeType
|
||||
use interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
|
||||
@@ -329,10 +328,8 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
|
||||
// A List-typed default drops to its Item counterpart (when that has a default value and the connector accepts rank 0),
|
||||
// since a stored Item default can promote back onto a List connector but a stored List default can never return to rank 0.
|
||||
// An input whose definition defaults to a list keeps the empty list, since promoting an Item default would leave it a placeholder element.
|
||||
// since a stored Item default can promote back onto a List connector but a stored List default can never return to rank 0
|
||||
if let Some(element) = guaranteed_type.nested_type().list_element()
|
||||
&& !self.definition_defaults_to_list(input_connector, network_path)
|
||||
&& let Some(item_type) = self
|
||||
.potential_valid_input_types(input_connector, network_path)
|
||||
.into_iter()
|
||||
@@ -345,19 +342,6 @@ impl NodeNetworkInterface {
|
||||
TaggedValue::from_type_or_none(&guaranteed_type)
|
||||
}
|
||||
|
||||
/// Whether the definition of the node owning this input gives it a list as its default value.
|
||||
fn definition_defaults_to_list(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> bool {
|
||||
let InputConnector::Node { node_id, input_index } = input_connector else { return false };
|
||||
let Some(definition) = self.reference(node_id, network_path).as_ref().and_then(resolve_document_node_type) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
matches!(
|
||||
definition.node_template.inputs.get(*input_index),
|
||||
Some(NodeInput::Value { tagged_value, .. }) if matches!(tagged_value.ty().nested_type(), Type::List(_))
|
||||
)
|
||||
}
|
||||
|
||||
/// A list of all valid input types for this specific node.
|
||||
pub fn potential_valid_input_types(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Vec<Type> {
|
||||
let InputConnector::Node { node_id, input_index } = input_connector else {
|
||||
|
||||
@@ -357,7 +357,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, gdd.blobs()) {
|
||||
let (network, node_entries, network_entries) = match gdd.registry().to_runtime_with_full_metadata(&declarations) {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
log::error!("Opening document {document_id:?}: failed to convert registry to runtime: {error}");
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
//! Tints what a step changed onto a close-up of the document, colored by how the layer under each changed pixel changed.
|
||||
|
||||
use super::utility_types::Pixels;
|
||||
use glam::{DVec2, UVec2};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Change {
|
||||
Added,
|
||||
Removed,
|
||||
Changed,
|
||||
}
|
||||
|
||||
/// Where a layer's change shows, in document coordinates.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ChangedArea {
|
||||
pub change: Change,
|
||||
pub bounds: [DVec2; 2],
|
||||
}
|
||||
|
||||
/// How far apart two premultiplied channels must be for a pixel to count as changed, out of 255.
|
||||
const THRESHOLD: u8 = 16;
|
||||
/// How much of a tint's color covers a changed pixel.
|
||||
const TINT_STRENGTH: f32 = 0.6;
|
||||
/// How opaque unchanged pixels stay, so the tints stand out.
|
||||
const UNCHANGED_OPACITY: f32 = 0.35;
|
||||
|
||||
fn tint_color(change: Change) -> [u8; 3] {
|
||||
match change {
|
||||
Change::Added => [64, 200, 96],
|
||||
Change::Removed => [232, 64, 64],
|
||||
Change::Changed => [240, 176, 32],
|
||||
}
|
||||
}
|
||||
|
||||
/// The close-up `after` of `frame` with each pixel that differs from `before`, the whole document before the step
|
||||
/// showing `before_frame`, tinted by the change of the area it falls in. A pixel that lost coverage shows as it was.
|
||||
pub fn tint_changes(after: &Pixels, frame: [DVec2; 2], before: &Pixels, before_frame: [DVec2; 2], areas: &[ChangedArea]) -> Pixels {
|
||||
let size = after.size;
|
||||
let mut rgba = Vec::with_capacity(after.rgba.len());
|
||||
for y in 0..size.y {
|
||||
for x in 0..size.x {
|
||||
let point = frame[0] + (DVec2::new(x as f64, y as f64) + 0.5) / size.as_dvec2() * (frame[1] - frame[0]);
|
||||
let now = pixel(after, UVec2::new(x, y));
|
||||
let then = sample(before, before_frame, point);
|
||||
let shown = if differs(now, then) {
|
||||
let lost = now[3] < then[3];
|
||||
tint(if lost { then } else { now }, change_at(areas, point, lost))
|
||||
} else {
|
||||
[now[0], now[1], now[2], (now[3] as f32 * UNCHANGED_OPACITY) as u8]
|
||||
};
|
||||
rgba.extend_from_slice(&shown);
|
||||
}
|
||||
}
|
||||
Pixels { size, rgba }
|
||||
}
|
||||
|
||||
/// The area around every change, with a margin, at the thumbnails' aspect ratio. None when nothing changed.
|
||||
pub fn close_up(areas: &[ChangedArea]) -> Option<[DVec2; 2]> {
|
||||
/// The thumbnails' width over their height.
|
||||
const ASPECT_RATIO: f64 = 1.5;
|
||||
|
||||
let [min, max] = areas.iter().map(|area| area.bounds).reduce(|a, b| [a[0].min(b[0]), a[1].max(b[1])])?;
|
||||
let margin = ((max - min) * 0.15).max(DVec2::splat(4.));
|
||||
let (min, max) = (min - margin, max + margin);
|
||||
|
||||
let size = max - min;
|
||||
let size = if size.x >= size.y * ASPECT_RATIO {
|
||||
DVec2::new(size.x, size.x / ASPECT_RATIO)
|
||||
} else {
|
||||
DVec2::new(size.y * ASPECT_RATIO, size.y)
|
||||
};
|
||||
let center = (min + max) / 2.;
|
||||
Some([center - size / 2., center + size / 2.])
|
||||
}
|
||||
|
||||
/// The change of the areas holding `point`, preferring a removal where the pixel lost coverage and an addition elsewhere.
|
||||
fn change_at(areas: &[ChangedArea], point: DVec2, lost: bool) -> Change {
|
||||
let holding = |change: Change| areas.iter().any(|area| area.change == change && contains(area.bounds, point));
|
||||
let order = match lost {
|
||||
true => [Change::Removed, Change::Changed, Change::Added],
|
||||
false => [Change::Added, Change::Changed, Change::Removed],
|
||||
};
|
||||
order.into_iter().find(|&change| holding(change)).unwrap_or(Change::Changed)
|
||||
}
|
||||
|
||||
fn contains(bounds: [DVec2; 2], point: DVec2) -> bool {
|
||||
point.cmpge(bounds[0]).all() && point.cmple(bounds[1]).all()
|
||||
}
|
||||
|
||||
fn pixel(pixels: &Pixels, at: UVec2) -> [u8; 4] {
|
||||
let index = (at.y * pixels.size.x + at.x) as usize * 4;
|
||||
pixels.rgba.get(index..index + 4).and_then(|pixel| pixel.try_into().ok()).unwrap_or([0; 4])
|
||||
}
|
||||
|
||||
/// The pixel of `pixels`, which shows `frame`, at a document point, transparent outside it.
|
||||
fn sample(pixels: &Pixels, frame: [DVec2; 2], point: DVec2) -> [u8; 4] {
|
||||
let at = (point - frame[0]) / (frame[1] - frame[0]) * pixels.size.as_dvec2();
|
||||
if at.cmplt(DVec2::ZERO).any() || at.cmpge(pixels.size.as_dvec2()).any() {
|
||||
return [0; 4];
|
||||
}
|
||||
pixel(pixels, at.as_uvec2())
|
||||
}
|
||||
|
||||
fn differs(a: [u8; 4], b: [u8; 4]) -> bool {
|
||||
let premultiplied = |pixel: [u8; 4]| pixel.map(|channel| (channel as u16 * pixel[3] as u16 / 255) as u8);
|
||||
let (a, b) = (premultiplied(a), premultiplied(b));
|
||||
a.iter().zip(&b).any(|(a, b)| a.abs_diff(*b) > THRESHOLD) || a[3].abs_diff(b[3]) > THRESHOLD
|
||||
}
|
||||
|
||||
fn tint(pixel: [u8; 4], change: Change) -> [u8; 4] {
|
||||
let color = tint_color(change);
|
||||
let mix = |channel: u8, tint: u8| (channel as f32 + (tint as f32 - channel as f32) * TINT_STRENGTH) as u8;
|
||||
[mix(pixel[0], color[0]), mix(pixel[1], color[1]), mix(pixel[2], color[2]), pixel[3]]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const FRAME: [DVec2; 2] = [DVec2::ZERO, DVec2::new(4., 2.)];
|
||||
const CLEAR: [u8; 4] = [0; 4];
|
||||
const WHITE: [u8; 4] = [255; 4];
|
||||
|
||||
/// A 4×2 image of the given pixels, row by row.
|
||||
fn image(pixels: [[u8; 4]; 8]) -> Pixels {
|
||||
Pixels {
|
||||
size: UVec2::new(4, 2),
|
||||
rgba: pixels.concat(),
|
||||
}
|
||||
}
|
||||
|
||||
fn left_half(change: Change) -> ChangedArea {
|
||||
ChangedArea {
|
||||
change,
|
||||
bounds: [DVec2::ZERO, DVec2::new(2., 2.)],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_stayed_fades_and_what_came_is_tinted_as_added() {
|
||||
let before = image([CLEAR; 8]);
|
||||
let after = image([WHITE, WHITE, CLEAR, CLEAR, WHITE, WHITE, CLEAR, CLEAR]);
|
||||
let tinted = tint_changes(&after, FRAME, &before, FRAME, &[left_half(Change::Added)]);
|
||||
|
||||
assert_eq!(pixel(&tinted, UVec2::new(0, 0)), tint(WHITE, Change::Added));
|
||||
assert_eq!(pixel(&tinted, UVec2::new(3, 1))[3], 0, "transparent pixels that stayed stay transparent");
|
||||
|
||||
let unchanged = tint_changes(&after, FRAME, &after, FRAME, &[]);
|
||||
assert_eq!(pixel(&unchanged, UVec2::new(0, 0))[3], (255. * UNCHANGED_OPACITY) as u8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_went_shows_as_it_was_tinted_as_removed() {
|
||||
let before = image([WHITE, WHITE, CLEAR, CLEAR, WHITE, WHITE, CLEAR, CLEAR]);
|
||||
let after = image([CLEAR; 8]);
|
||||
let tinted = tint_changes(&after, FRAME, &before, FRAME, &[left_half(Change::Removed)]);
|
||||
|
||||
let removed = pixel(&tinted, UVec2::new(1, 1));
|
||||
assert_eq!(removed, tint(WHITE, Change::Removed));
|
||||
assert_eq!(removed[3], 255, "a removed pixel keeps the coverage it had");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moved_layer_is_tinted_as_changed_where_it_was_and_where_it_is() {
|
||||
let before = image([WHITE, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR]);
|
||||
let after = image([CLEAR, WHITE, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR]);
|
||||
let tinted = tint_changes(&after, FRAME, &before, FRAME, &[left_half(Change::Changed)]);
|
||||
|
||||
assert_eq!(pixel(&tinted, UVec2::new(0, 0)), tint(WHITE, Change::Changed), "where it was");
|
||||
assert_eq!(pixel(&tinted, UVec2::new(1, 0)), tint(WHITE, Change::Changed), "where it is");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_close_up_samples_the_whole_document_before_at_its_own_scale() {
|
||||
// The before image shows twice the area, so its left pixel column covers the close-up's left two
|
||||
let before = image([WHITE, CLEAR, CLEAR, CLEAR, WHITE, CLEAR, CLEAR, CLEAR]);
|
||||
let before_frame = [DVec2::ZERO, DVec2::new(8., 4.)];
|
||||
let after = image([WHITE, WHITE, CLEAR, CLEAR, WHITE, WHITE, CLEAR, CLEAR]);
|
||||
let tinted = tint_changes(&after, FRAME, &before, before_frame, &[]);
|
||||
|
||||
assert_eq!(pixel(&tinted, UVec2::new(1, 0))[3], (255. * UNCHANGED_OPACITY) as u8, "still covered, so unchanged");
|
||||
assert_eq!(pixel(&tinted, UVec2::new(2, 0))[3], 0);
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,39 @@ use crate::messages::prelude::*;
|
||||
pub enum HistoryMessage {
|
||||
Refresh,
|
||||
Tick,
|
||||
Expand { id: String, expanded: bool },
|
||||
Expand {
|
||||
id: String,
|
||||
expanded: bool,
|
||||
},
|
||||
LoadMore,
|
||||
GoBack { id: String },
|
||||
RemoveStep { id: String },
|
||||
BringBack { id: String },
|
||||
Follow { id: Option<String> },
|
||||
Rename { id: String, label: String },
|
||||
Tag { id: String, tag: String, on: bool },
|
||||
GoBack {
|
||||
id: String,
|
||||
},
|
||||
RemoveStep {
|
||||
id: String,
|
||||
},
|
||||
BringBack {
|
||||
id: String,
|
||||
},
|
||||
Follow {
|
||||
id: Option<String>,
|
||||
},
|
||||
Rename {
|
||||
id: String,
|
||||
label: String,
|
||||
},
|
||||
Tag {
|
||||
id: String,
|
||||
tag: String,
|
||||
on: bool,
|
||||
},
|
||||
GraphOverlay {
|
||||
open: bool,
|
||||
},
|
||||
GraphOverlayToggle,
|
||||
Captured {
|
||||
document_id: DocumentId,
|
||||
step: document_graph_storage::TimeStamp,
|
||||
capture: Option<Box<super::utility_types::DocumentCapture>>,
|
||||
},
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,3 +1,4 @@
|
||||
mod changes;
|
||||
mod history_message;
|
||||
mod history_message_handler;
|
||||
pub mod utility_types;
|
||||
|
||||
@@ -1,5 +1,36 @@
|
||||
//! What the History panel shows, as the frontend receives it, and the changes it asks of the head's line.
|
||||
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// The document as rendered once a step is done, for the History panel to show and compare.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct DocumentCapture {
|
||||
/// The whole document.
|
||||
pub image: CaptureImage,
|
||||
/// The document area `image` shows.
|
||||
pub frame: [DVec2; 2],
|
||||
/// The area asked for in detail, and its image.
|
||||
pub detail: Option<([DVec2; 2], CaptureImage)>,
|
||||
/// The proto node giving each layer's own content, whose ID changes with that content.
|
||||
pub layer_sources: HashMap<NodeId, NodeId>,
|
||||
}
|
||||
|
||||
/// A capture rendered like the layer thumbnails: pixels from Vello, or an SVG for the frontend to draw when the GPU is unavailable.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum CaptureImage {
|
||||
Pixels(Pixels),
|
||||
Svg(String),
|
||||
}
|
||||
|
||||
/// Straight RGBA pixels, row by row.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Pixels {
|
||||
pub size: glam::UVec2,
|
||||
pub rgba: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum LineChange {
|
||||
/// Moves the shared head to an earlier interaction and keeps the later steps as a branch.
|
||||
@@ -19,8 +50,8 @@ pub struct HistoryPanelState {
|
||||
pub progress: Vec<HistoryProgressRow>,
|
||||
pub more: bool,
|
||||
pub following: Option<String>,
|
||||
/// In a session, a head move affects everyone.
|
||||
pub session: bool,
|
||||
/// Others are connected, so authors, whether work is in history yet and head moves concern them too.
|
||||
pub collaborating: bool,
|
||||
}
|
||||
|
||||
/// One interaction, a run of deltas that undo takes back together.
|
||||
@@ -48,6 +79,17 @@ pub struct HistoryRow {
|
||||
pub head: bool,
|
||||
pub expanded: bool,
|
||||
pub details: Vec<HistoryDeltaRow>,
|
||||
/// How the document looked once this step was done, if the panel was open to capture it.
|
||||
pub thumbnail: Option<HistoryThumbnail>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryThumbnail {
|
||||
/// The ID the frontend received the whole document's image under.
|
||||
pub whole: String,
|
||||
/// The ID of a close-up of what the step changed, tinted by how, when the step before was captured too.
|
||||
pub detail: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -63,10 +105,42 @@ pub struct HistoryDeltaRow {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub author: String,
|
||||
pub color: String,
|
||||
pub mine: bool,
|
||||
pub time: Option<f64>,
|
||||
}
|
||||
|
||||
/// Every step in history as a tree on first parents, for the history graph drawn over the viewport.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryGraphState {
|
||||
pub nodes: Vec<HistoryGraphNode>,
|
||||
/// The widest column plus one.
|
||||
pub width: f64,
|
||||
/// The deepest step's depth plus one.
|
||||
pub depth: usize,
|
||||
}
|
||||
|
||||
/// One interaction, placed in the tree.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryGraphNode {
|
||||
/// The rev closing the interaction, in decimal.
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
/// The column, in step widths from the left. A parent sits centred over its children.
|
||||
pub x: f64,
|
||||
/// Steps from the root.
|
||||
pub depth: usize,
|
||||
pub parent: Option<String>,
|
||||
/// Steps joined into this one by a merge.
|
||||
pub merged: Vec<String>,
|
||||
pub head: bool,
|
||||
pub undone: bool,
|
||||
/// Off the head's line and not undone.
|
||||
pub abandoned: bool,
|
||||
pub thumbnail: Option<HistoryThumbnail>,
|
||||
}
|
||||
|
||||
/// A person with unretired work in the room's hot log.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
@@ -79,4 +153,5 @@ pub struct HistoryProgressRow {
|
||||
pub ops: usize,
|
||||
/// Still being made, not closed and waiting.
|
||||
pub open: bool,
|
||||
pub thumbnail: Option<HistoryThumbnail>,
|
||||
}
|
||||
@@ -144,6 +144,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
documents: &mut self.documents,
|
||||
active_document_id: self.active_document_id,
|
||||
panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::History) && !self.workspace.panel_layout.focus_document,
|
||||
executor: &self.executor,
|
||||
};
|
||||
self.history.process_message(message, responses, context);
|
||||
}
|
||||
@@ -269,7 +270,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
|
||||
match container.write_non_blocking(legacy_path(), document.serialize_document().as_bytes()) {
|
||||
Ok(()) => {
|
||||
document.commit_storage_snapshot(&resource_storage.resources_mut());
|
||||
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
|
||||
document.set_auto_save_state(true);
|
||||
}
|
||||
Err(error) => {
|
||||
@@ -1141,7 +1142,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
}
|
||||
PortfolioMessage::UpdateDocumentWidgets => {
|
||||
if let Some(document) = self.active_document() {
|
||||
document.update_document_widgets(responses, animation.is_playing(), timing_information.animation_time);
|
||||
document.update_document_widgets(responses, animation.is_playing(), timing_information.animation_time, self.history.graph_open());
|
||||
}
|
||||
}
|
||||
PortfolioMessage::UpdateOpenDocumentsList => {
|
||||
@@ -1176,6 +1177,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
PrevDocument,
|
||||
));
|
||||
common.extend(actions!(IngestMessageDiscriminant; Import));
|
||||
common.extend(self.history.actions());
|
||||
}
|
||||
|
||||
common
|
||||
@@ -1344,7 +1346,7 @@ impl PortfolioMessageHandler {
|
||||
let resources = resource_storage.resources_mut();
|
||||
document.set_storage(*gdd, declarations, resources.storage());
|
||||
document.require_whole_document_stage();
|
||||
document.commit_storage_snapshot(&resources);
|
||||
document.commit_storage_snapshot(&resources, preferences.validate_storage_round_trip);
|
||||
document.retire_storage_interaction();
|
||||
}
|
||||
None => {
|
||||
|
||||
@@ -13,7 +13,7 @@ pub enum SyncMessage {
|
||||
Leave,
|
||||
/// Host the active document as a new session with its own link. The others stay in the old room.
|
||||
Fork,
|
||||
/// Send the Collaboration panel's layout.
|
||||
/// Send the Session panel's layout.
|
||||
RefreshPanel,
|
||||
/// Apply what peers sent, once per frame.
|
||||
Poll,
|
||||
|
||||
@@ -171,10 +171,10 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
|
||||
refresh_session_views(responses);
|
||||
}
|
||||
SyncMessage::RefreshPanel => {
|
||||
let layout = collaboration_panel_layout(documents, active_document_id, preferences);
|
||||
let layout = session_panel_layout(documents, active_document_id, preferences);
|
||||
responses.add(LayoutMessage::SendLayout {
|
||||
layout,
|
||||
layout_target: LayoutTarget::CollaborationPanel,
|
||||
layout_target: LayoutTarget::SessionPanel,
|
||||
});
|
||||
}
|
||||
SyncMessage::Poll => {
|
||||
@@ -226,7 +226,7 @@ impl SyncMessageHandler {
|
||||
fn host(&mut self, document_id: DocumentId, gdd: &mut GddV1, preferences: &PreferencesMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let Some(token) = self.connect_document(document_id, gdd, preferences, responses) else { return };
|
||||
responses.add(FrontendMessage::TriggerSessionLinkCopy { token: token.to_string() });
|
||||
responses.add(WorkspaceMessage::FocusPanel { panel_type: PanelType::Collaboration });
|
||||
responses.add(WorkspaceMessage::FocusPanel { panel_type: PanelType::Session });
|
||||
}
|
||||
|
||||
fn connect_document(&mut self, document_id: DocumentId, gdd: &mut GddV1, preferences: &PreferencesMessageHandler, responses: &mut VecDeque<Message>) -> Option<SessionToken> {
|
||||
@@ -534,7 +534,7 @@ fn refresh_session_views(responses: &mut VecDeque<Message>) {
|
||||
responses.add(SyncMessage::RefreshPanel);
|
||||
}
|
||||
|
||||
fn collaboration_panel_layout(documents: &HashMap<DocumentId, DocumentMessageHandler>, active_document_id: Option<DocumentId>, preferences: &PreferencesMessageHandler) -> Layout {
|
||||
fn session_panel_layout(documents: &HashMap<DocumentId, DocumentMessageHandler>, active_document_id: Option<DocumentId>, preferences: &PreferencesMessageHandler) -> Layout {
|
||||
let heading = |text: &str| LayoutGroup::row(vec![TextLabel::new(text).bold(true).widget_instance()]);
|
||||
let note = |text: &str| LayoutGroup::row(vec![TextLabel::new(text).multiline(true).widget_instance()]);
|
||||
let user_name = preferences.user_name.as_str();
|
||||
|
||||
@@ -12,7 +12,7 @@ pub enum PanelType {
|
||||
#[serde(alias = "Properties")]
|
||||
Inspector,
|
||||
Data,
|
||||
Collaboration,
|
||||
Session,
|
||||
History,
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ impl From<String> for PanelType {
|
||||
"Layers" => PanelType::Layers,
|
||||
"Inspector" | "Properties" => PanelType::Inspector,
|
||||
"Data" => PanelType::Data,
|
||||
"Collaboration" => PanelType::Collaboration,
|
||||
"Session" => PanelType::Session,
|
||||
"History" => PanelType::History,
|
||||
_ => panic!("Unknown panel type: {value}"),
|
||||
}
|
||||
@@ -33,7 +33,7 @@ impl From<String> for PanelType {
|
||||
|
||||
impl PanelType {
|
||||
pub fn non_document_panels() -> &'static [PanelType] {
|
||||
&[PanelType::Layers, PanelType::Inspector, PanelType::Data, PanelType::Collaboration, PanelType::History]
|
||||
&[PanelType::Layers, PanelType::Inspector, PanelType::Data, PanelType::Session, PanelType::History]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -305,10 +305,10 @@ impl WorkspacePanelLayout {
|
||||
/// - Data: below the document in the left column (root child 0)
|
||||
/// - Inspector: top of the right column (root child 1)
|
||||
/// - Layers: bottom of the right column (root child 1)
|
||||
/// - Collaboration, History: a tab beside the Inspector or Layers, otherwise placed like that panel
|
||||
/// - Session, History: a tab beside the Inspector or Layers, otherwise placed like that panel
|
||||
fn restore_panel_to_default_position(&mut self, panel_type: PanelType) {
|
||||
let beside = match panel_type {
|
||||
PanelType::Collaboration => Some(PanelType::Inspector),
|
||||
PanelType::Session => Some(PanelType::Inspector),
|
||||
PanelType::History => Some(PanelType::Layers),
|
||||
_ => None,
|
||||
};
|
||||
@@ -334,9 +334,9 @@ impl WorkspacePanelLayout {
|
||||
|
||||
// Determine which root child column to insert into and at which position
|
||||
let (root_child_index, insert_at_end) = match panel_type {
|
||||
PanelType::Data => (0, true), // Left column, after document
|
||||
PanelType::Inspector | PanelType::Collaboration => (1, false), // Right column, at top
|
||||
PanelType::Layers | PanelType::History => (1, true), // Right column, at bottom
|
||||
PanelType::Data => (0, true), // Left column, after document
|
||||
PanelType::Inspector | PanelType::Session => (1, false), // Right column, at top
|
||||
PanelType::Layers | PanelType::History => (1, true), // Right column, at bottom
|
||||
_ => (1, true),
|
||||
};
|
||||
|
||||
@@ -421,7 +421,7 @@ impl Default for WorkspacePanelLayout {
|
||||
subdivision: PanelLayoutSubdivision::PanelGroup {
|
||||
id: PanelGroupId(1),
|
||||
state: PanelGroupState {
|
||||
tabs: vec![PanelType::Inspector],
|
||||
tabs: vec![PanelType::Inspector, PanelType::Session],
|
||||
active_tab_index: 0,
|
||||
},
|
||||
},
|
||||
|
||||
Loaded 100 of 203 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user