mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 15:53:26 -10:00
Stage what the store recorded instead of converting and diffing the whole document
This commit is contained in:
1 parent
3394695fb9
commit
305cd02332
7 files changed
+282
-118
No files matched your search
@@ -76,6 +76,29 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
|
||||
/// the whole document and diffing it against the working registry.
|
||||
///
|
||||
/// Otherwise identical to [`stage_runtime_snapshot`](Self::stage_runtime_snapshot): each op becomes a
|
||||
/// hot frame, and the proto-node declaration bytes go to the byte store.
|
||||
#[cfg(feature = "conversion")]
|
||||
pub fn stage_constructed_ops(
|
||||
&mut self,
|
||||
ops: Vec<document_graph_storage::RegistryDelta>,
|
||||
declaration_bytes: &document_graph_storage::from_runtime::DeclarationBytes,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<(), Error> {
|
||||
let hot_ops = self.session.stage_computed_ops(ops)?;
|
||||
|
||||
for hot_op in &hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
for bytes in declaration_bytes.values() {
|
||||
byte_store.store(bytes);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retire every pending hot op into durable history as a single interaction (marking the batch's last
|
||||
/// delta as the interaction boundary), then re-snapshot the registry. One interaction is one undo unit,
|
||||
/// so the caller invokes this at each undo-step boundary and before any undo/redo. A no-op when there
|
||||
|
||||
@@ -5,6 +5,7 @@ use document_graph_storage::Registry;
|
||||
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry, ResourceStorage};
|
||||
|
||||
use super::utility_types::network_interface::NodeNetworkInterface;
|
||||
use super::utility_types::network_interface::editor_delta::{EditorDelta, construct_batch};
|
||||
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, collect_network_view_settings};
|
||||
|
||||
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
|
||||
@@ -101,6 +102,7 @@ impl DocumentHistory {
|
||||
/// round-trip check, off by default for its perf cost.
|
||||
pub fn stage_snapshot(
|
||||
&mut self,
|
||||
deltas: &[EditorDelta],
|
||||
interface: &NodeNetworkInterface,
|
||||
registry: &ResourceRegistry,
|
||||
view_settings: BTreeMap<String, serde_json::Value>,
|
||||
@@ -109,21 +111,68 @@ impl DocumentHistory {
|
||||
) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
|
||||
let network = interface.document_network();
|
||||
let metadata_view = StorageMetadataView::new(interface);
|
||||
|
||||
let network_view_settings = storage
|
||||
.network_ids(network, &metadata_view)
|
||||
.ok()
|
||||
.map(|network_ids| collect_network_view_settings(interface, &network_ids));
|
||||
|
||||
// Stage without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo
|
||||
// step, so the deltas accumulate as hot ops and coalesce at the next undo-step boundary.
|
||||
if let Err(error) = storage.stage_runtime_snapshot(network, &metadata_view, registry, byte_store) {
|
||||
// A working copy that does not hold the document yet has no baseline for a batch of changes to
|
||||
// apply to, so the first commit writes the whole document and every later one stages only what
|
||||
// the store recorded. Reading that from the working copy rather than from the caller means a path
|
||||
// that mounts storage and then commits does not have to know which of the two it is.
|
||||
let staged = match storage.registry().node_instances.is_empty() {
|
||||
true => Self::stage_whole_document(storage, interface, registry, byte_store),
|
||||
// An autosave with nothing edited since the last commit still persists the view state below.
|
||||
false if deltas.is_empty() => Ok(()),
|
||||
false => Self::stage_recorded(storage, deltas, interface, registry, byte_store),
|
||||
};
|
||||
if let Err(error) = staged {
|
||||
log::error!("Storage snapshot staging failed: {error}");
|
||||
return;
|
||||
}
|
||||
|
||||
self.persist_view_state(interface, view_settings, legacy_document);
|
||||
}
|
||||
|
||||
/// Converts the whole document and stages the difference from what the working copy holds.
|
||||
///
|
||||
/// Stages without retiring: a tool drag fires several `CommitTransaction`s but is one legacy undo
|
||||
/// step, so the ops accumulate in the hot log and coalesce at the next undo-step boundary.
|
||||
fn stage_whole_document(storage: &mut document_format::GddV1, interface: &NodeNetworkInterface, registry: &ResourceRegistry, byte_store: &dyn ResourceStorage) -> Result<(), String> {
|
||||
let metadata_view = StorageMetadataView::new(interface);
|
||||
storage
|
||||
.stage_runtime_snapshot(interface.document_network(), &metadata_view, registry, byte_store)
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
/// Stages what the store recorded since the last drain.
|
||||
///
|
||||
/// This and the whole-document conversion produce the same registry for the same edit, which
|
||||
/// `verify_round_trip` checks when the `validate_storage_round_trip` preference is on. They differ in
|
||||
/// 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(
|
||||
storage: &mut document_format::GddV1,
|
||||
deltas: &[EditorDelta],
|
||||
interface: &NodeNetworkInterface,
|
||||
registry: &ResourceRegistry,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<(), String> {
|
||||
let peer = storage.session().peer();
|
||||
let metadata_view = StorageMetadataView::new(interface);
|
||||
let constructed = construct_batch(deltas, storage.registry(), registry, &metadata_view, peer).map_err(|error| error.to_string())?;
|
||||
|
||||
storage
|
||||
.stage_constructed_ops(constructed.ops, &constructed.declaration_bytes, byte_store)
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
/// The parts of a commit that are not the graph: the per-peer view settings, and the legacy bytes the
|
||||
/// dual-write soak validates the new format against. Both staging paths persist them; they differ
|
||||
/// only in how the graph ops are derived.
|
||||
fn persist_view_state(&mut self, interface: &NodeNetworkInterface, view_settings: BTreeMap<String, serde_json::Value>, legacy_document: &str) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
|
||||
let network_view_settings = storage
|
||||
.network_ids(interface.document_network(), &StorageMetadataView::new(interface))
|
||||
.ok()
|
||||
.map(|network_ids| collect_network_view_settings(interface, &network_ids));
|
||||
|
||||
if let Err(error) = storage.set_view_settings(view_settings) {
|
||||
log::error!("Persisting view settings failed: {error}");
|
||||
}
|
||||
@@ -134,8 +183,6 @@ impl DocumentHistory {
|
||||
log::error!("Persisting per-network view settings failed: {error}");
|
||||
}
|
||||
|
||||
// Dual-write soak: embed the legacy `.graphite` bytes so the new format
|
||||
// can be validated against (and recovered from) the old one on open.
|
||||
if let Err(error) = storage.store_legacy_document(legacy_document.as_bytes()) {
|
||||
log::error!("Embedding legacy document into working copy failed: {error}");
|
||||
}
|
||||
|
||||
@@ -2026,19 +2026,30 @@ impl DocumentMessageHandler {
|
||||
self.history.retire_storage_interaction();
|
||||
}
|
||||
|
||||
/// Stages the runtime network into the `Gdd` working copy.
|
||||
/// Stages what the store recorded since the last commit into the `Gdd` working copy.
|
||||
///
|
||||
/// The batch boundary: everything the interface recorded since the last one is this commit's batch.
|
||||
/// Draining happens whether or not a working copy is mounted, so the buffer cannot grow across a
|
||||
/// session that never mounts one.
|
||||
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::DocumentSettings;
|
||||
|
||||
// The batch boundary for the store's emitted deltas. Staging still converts the whole document and
|
||||
// diffs it, so the deltas are dropped here rather than consumed; draining unconditionally keeps the
|
||||
// buffer from growing across a session that never mounts storage.
|
||||
let _emitted = self.network_interface.take_deltas();
|
||||
|
||||
let deltas = self.network_interface.take_deltas();
|
||||
if self.history.storage().is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
let (view_settings, legacy_document) = self.storage_side_channels();
|
||||
self.history
|
||||
.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, legacy_document.as_str(), byte_store);
|
||||
|
||||
if validate {
|
||||
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-peer view settings and legacy bytes that ride along with either kind of staging.
|
||||
fn storage_side_channels(&self) -> (std::collections::BTreeMap<String, serde_json::Value>, String) {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::DocumentSettings;
|
||||
|
||||
let view_settings = DocumentSettings {
|
||||
document_ptz: &self.document_ptz,
|
||||
render_mode: &self.render_mode,
|
||||
@@ -2049,14 +2060,7 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
.to_view_map();
|
||||
|
||||
let legacy_document = self.serialize_document();
|
||||
|
||||
self.history
|
||||
.stage_snapshot(&self.network_interface, &self.resources.registry, view_settings, legacy_document.as_str(), byte_store);
|
||||
|
||||
if validate {
|
||||
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
|
||||
}
|
||||
(view_settings, self.serialize_document())
|
||||
}
|
||||
|
||||
/// Restore `view_settings` map into the document.
|
||||
|
||||
+103
-80
@@ -104,36 +104,20 @@ pub fn construct_batch(
|
||||
) -> Result<ConstructedOps, ConversionError> {
|
||||
let identities = IdentitiesOnly(metadata);
|
||||
let resolver = PathResolver::new(Some(&identities), peer);
|
||||
let nodes_by_network = NodesByNetwork::new(working);
|
||||
let mut batch = BatchRegistry::new(working);
|
||||
let mut ops = Vec::new();
|
||||
let mut declaration_bytes = DeclarationBytes::new();
|
||||
let mut batch_removed_nodes = Vec::new();
|
||||
let mut batch_added_resources = HashSet::new();
|
||||
|
||||
// In delta order, so each delta reads what the ones before it did. Removals accumulate as they are
|
||||
// met rather than being gathered up front, since a removal can name a node an earlier delta added.
|
||||
for delta in deltas {
|
||||
if let EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id } | RuntimeDelta::ReplaceNode { network_path, node_id, .. }) = delta {
|
||||
let (removed_nodes, _) = removal_closure(resolver.node_id(network_path, *node_id), working, &nodes_by_network);
|
||||
batch_removed_nodes.extend(removed_nodes);
|
||||
}
|
||||
delta.construct(resources, peer, &identities, &resolver, &mut batch, &mut batch_removed_nodes, &mut ops, &mut declaration_bytes)?;
|
||||
}
|
||||
|
||||
batch_removed_nodes.sort();
|
||||
batch_removed_nodes.dedup();
|
||||
|
||||
for delta in deltas {
|
||||
delta.construct(
|
||||
working,
|
||||
resources,
|
||||
peer,
|
||||
&identities,
|
||||
&resolver,
|
||||
&nodes_by_network,
|
||||
&mut batch_added_resources,
|
||||
&mut ops,
|
||||
&mut declaration_bytes,
|
||||
)?;
|
||||
}
|
||||
|
||||
construct_resource_removals(&batch_removed_nodes, working, &mut ops);
|
||||
construct_resource_removals(&batch_removed_nodes, &batch, &mut ops);
|
||||
Ok(ConstructedOps { ops, declaration_bytes })
|
||||
}
|
||||
|
||||
@@ -141,28 +125,27 @@ impl EditorDelta {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn construct(
|
||||
&self,
|
||||
working: &Registry,
|
||||
resources: &ResourceRegistry,
|
||||
peer: document_graph_storage::PeerId,
|
||||
identities: &dyn NodeMetadataSource,
|
||||
resolver: &PathResolver,
|
||||
nodes_by_network: &NodesByNetwork,
|
||||
batch_added_resources: &mut HashSet<ResourceId>,
|
||||
batch: &mut BatchRegistry,
|
||||
batch_removed_nodes: &mut Vec<document_graph_storage::NodeId>,
|
||||
ops: &mut Vec<RegistryDelta>,
|
||||
declaration_bytes: &mut DeclarationBytes,
|
||||
) -> Result<(), ConversionError> {
|
||||
match self {
|
||||
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, node }) => {
|
||||
construct_structural_additions(network_path, *node_id, node, working, resources, identities, peer, batch_added_resources, ops, declaration_bytes)?;
|
||||
construct_structural_additions(network_path, *node_id, node, batch, resources, identities, peer, ops, declaration_bytes)?;
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
|
||||
construct_removals(resolver.node_id(network_path, *node_id), working, nodes_by_network, ops);
|
||||
construct_structural_additions(network_path, *node_id, node, working, resources, identities, peer, batch_added_resources, ops, declaration_bytes)?;
|
||||
construct_removals(resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
|
||||
construct_structural_additions(network_path, *node_id, node, batch, resources, identities, peer, ops, declaration_bytes)?;
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id }) => {
|
||||
construct_removals(resolver.node_id(network_path, *node_id), working, nodes_by_network, ops);
|
||||
construct_removals(resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::SetVisibility { network_path, node_id, visible }) => {
|
||||
@@ -215,7 +198,7 @@ impl EditorDelta {
|
||||
}
|
||||
|
||||
EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata } => {
|
||||
construct_metadata_snapshot(network_path, *node_id, metadata, working, resolver, ops)?;
|
||||
construct_metadata_snapshot(network_path, *node_id, metadata, batch, resolver, ops)?;
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::SetInputs { network_path, node_id, inputs }) => {
|
||||
@@ -250,7 +233,7 @@ impl EditorDelta {
|
||||
} => {
|
||||
let global_id = resolver.node_id(network_path, *node_id);
|
||||
let source = InputMetadataSource(input_metadata);
|
||||
let working_node = working.node_instances.get(&global_id);
|
||||
let working_node = batch.node(global_id);
|
||||
|
||||
// An insert shifts every later slot, so the array is asserted whole: a `ui::` key the slot
|
||||
// no longer carries is cleared rather than left behind at its old index.
|
||||
@@ -359,11 +342,10 @@ fn construct_structural_additions(
|
||||
network_path: &[NodeId],
|
||||
node_id: NodeId,
|
||||
node: &graph_craft::document::DocumentNode,
|
||||
working: &Registry,
|
||||
batch: &mut BatchRegistry,
|
||||
resources: &ResourceRegistry,
|
||||
identities: &dyn NodeMetadataSource,
|
||||
peer: document_graph_storage::PeerId,
|
||||
batch_added_resources: &mut HashSet<ResourceId>,
|
||||
ops: &mut Vec<RegistryDelta>,
|
||||
declaration_bytes: &mut DeclarationBytes,
|
||||
) -> Result<(), ConversionError> {
|
||||
@@ -378,29 +360,37 @@ fn construct_structural_additions(
|
||||
ops.push(RegistryDelta::AddNetwork { id: *id, network: network.clone() });
|
||||
}
|
||||
|
||||
// Recorded as well as emitted, so a later delta in this batch that reads one of these nodes back
|
||||
// finds it rather than looking only at the registry the batch started from.
|
||||
let mut nodes: Vec<_> = scratch.node_instances.iter().collect();
|
||||
nodes.sort_by_key(|(id, _)| **id);
|
||||
for (id, node) in nodes {
|
||||
ops.push(RegistryDelta::AddNode { id: *id, node: node.clone() });
|
||||
let added: Vec<_> = nodes.into_iter().map(|(id, node)| (*id, node.clone())).collect();
|
||||
for (id, node) in added {
|
||||
ops.push(RegistryDelta::AddNode { id, node: node.clone() });
|
||||
batch.record_addition(id, node);
|
||||
}
|
||||
|
||||
let mut new_resources: Vec<_> = scratch.resources.iter().filter(|(id, _)| !working.resources.contains_key(id)).collect();
|
||||
new_resources.sort_by_key(|(id, _)| **id);
|
||||
let mut new_resources: Vec<_> = scratch
|
||||
.resources
|
||||
.iter()
|
||||
.filter(|(id, _)| !batch.working.resources.contains_key(id))
|
||||
.map(|(id, entry)| (*id, entry.clone()))
|
||||
.collect();
|
||||
new_resources.sort_by_key(|(id, _)| *id);
|
||||
for (id, entry) in new_resources {
|
||||
if batch_added_resources.insert(*id) {
|
||||
ops.push(RegistryDelta::AddResource { id: *id, entry: entry.clone() });
|
||||
if batch.record_resource(id, entry.clone()) {
|
||||
ops.push(RegistryDelta::AddResource { id, entry });
|
||||
}
|
||||
}
|
||||
let mut tagged: Vec<ResourceId> = scratch.node_instances.values().flat_map(node_value_resource_refs).collect();
|
||||
tagged.sort();
|
||||
tagged.dedup();
|
||||
for id in tagged {
|
||||
if !working.resources.contains_key(&id)
|
||||
if batch.resource(id).is_none()
|
||||
&& !scratch.resources.contains_key(&id)
|
||||
&& !batch_added_resources.contains(&id)
|
||||
&& let Some(entry) = convert_resource_entry(resources, id, peer)?
|
||||
{
|
||||
batch_added_resources.insert(id);
|
||||
batch.record_resource(id, entry.clone());
|
||||
ops.push(RegistryDelta::AddResource { id, entry });
|
||||
}
|
||||
}
|
||||
@@ -412,7 +402,7 @@ fn construct_metadata_snapshot(
|
||||
network_path: &[NodeId],
|
||||
node_id: NodeId,
|
||||
metadata: &DocumentNodePersistentMetadata,
|
||||
working: &Registry,
|
||||
batch: &BatchRegistry,
|
||||
resolver: &PathResolver,
|
||||
ops: &mut Vec<RegistryDelta>,
|
||||
) -> Result<(), ConversionError> {
|
||||
@@ -425,7 +415,7 @@ fn construct_metadata_snapshot(
|
||||
let mut pending = vec![(network_path.to_vec(), node_id, metadata)];
|
||||
while let Some((path, id, node_metadata)) = pending.pop() {
|
||||
let global_id = resolver.node_id(&path, id);
|
||||
let working_node = working.node_instances.get(&global_id);
|
||||
let working_node = batch.node(global_id);
|
||||
|
||||
let mut encoded = Attributes::new();
|
||||
encode_node_ui_attributes(&mut encoded, &source, &path, id, TimeStamp::ORIGIN)?;
|
||||
@@ -452,7 +442,8 @@ fn construct_metadata_snapshot(
|
||||
let network_id = resolver.network_id(&nested_path);
|
||||
|
||||
let target = network_metadata.persistent_metadata.reference.clone().map(serde_json::Value::String);
|
||||
let current = working
|
||||
let current = batch
|
||||
.working
|
||||
.networks
|
||||
.get(&network_id)
|
||||
.and_then(|network| network.attributes.get(node_attr::ui::REFERENCE))
|
||||
@@ -505,33 +496,33 @@ fn ui_attribute_writes(current: Option<&Attributes>, encoded: &Attributes) -> Ve
|
||||
deltas
|
||||
}
|
||||
|
||||
fn construct_removals(node_id: document_graph_storage::NodeId, working: &Registry, nodes_by_network: &NodesByNetwork, ops: &mut Vec<RegistryDelta>) {
|
||||
let (mut removed_nodes, mut removed_networks) = removal_closure(node_id, working, nodes_by_network);
|
||||
/// Emits the removal of a node and everything nested under it, recording what was removed so the
|
||||
/// batch's resource liveness accounts for all of it at the end.
|
||||
fn construct_removals(node_id: document_graph_storage::NodeId, batch: &BatchRegistry, batch_removed_nodes: &mut Vec<document_graph_storage::NodeId>, ops: &mut Vec<RegistryDelta>) {
|
||||
let (mut removed_nodes, mut removed_networks) = removal_closure(node_id, batch);
|
||||
|
||||
removed_nodes.sort();
|
||||
removed_networks.sort();
|
||||
for id in &removed_nodes {
|
||||
ops.push(RegistryDelta::RemoveNode {
|
||||
id: *id,
|
||||
snapshot: working.node_instances[id].clone(),
|
||||
});
|
||||
let Some(snapshot) = batch.node(*id) else { continue };
|
||||
ops.push(RegistryDelta::RemoveNode { id: *id, snapshot: snapshot.clone() });
|
||||
}
|
||||
for id in &removed_networks {
|
||||
ops.push(RegistryDelta::RemoveNetwork {
|
||||
id: *id,
|
||||
snapshot: working.networks[id].clone(),
|
||||
});
|
||||
let Some(snapshot) = batch.working.networks.get(id) else { continue };
|
||||
ops.push(RegistryDelta::RemoveNetwork { id: *id, snapshot: snapshot.clone() });
|
||||
}
|
||||
|
||||
batch_removed_nodes.extend(removed_nodes);
|
||||
}
|
||||
|
||||
/// Emits removals for resources referenced only by the batch's removed nodes, checked after every
|
||||
/// removal is known.
|
||||
fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::NodeId], working: &Registry, ops: &mut Vec<RegistryDelta>) {
|
||||
fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::NodeId], batch: &BatchRegistry, ops: &mut Vec<RegistryDelta>) {
|
||||
let removed_node_set: HashSet<_> = batch_removed_nodes.iter().copied().collect();
|
||||
let mut candidates: Vec<ResourceId> = batch_removed_nodes
|
||||
.iter()
|
||||
.flat_map(|id| {
|
||||
let node = &working.node_instances[id];
|
||||
.filter_map(|id| batch.node(*id))
|
||||
.flat_map(|node| {
|
||||
let declaration = match node.implementation() {
|
||||
Implementation::ProtoNode(declaration) => Some(*declaration),
|
||||
Implementation::Network(_) => None,
|
||||
@@ -547,7 +538,7 @@ fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::No
|
||||
|
||||
// Gathered in one pass so each candidate is a lookup rather than another scan of the whole registry
|
||||
let mut still_referenced: HashSet<ResourceId> = HashSet::new();
|
||||
for (id, node) in &working.node_instances {
|
||||
for (id, node) in batch.working.node_instances.iter().chain(&batch.added) {
|
||||
if removed_node_set.contains(id) {
|
||||
continue;
|
||||
}
|
||||
@@ -556,13 +547,13 @@ fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::No
|
||||
}
|
||||
still_referenced.extend(node_value_resource_refs(node));
|
||||
}
|
||||
for network in working.networks.values() {
|
||||
for network in batch.working.networks.values() {
|
||||
still_referenced.extend(network.exports.iter().filter_map(|slot| slot.target.as_ref().and_then(value_resource_ref)));
|
||||
}
|
||||
|
||||
for candidate in candidates {
|
||||
if !still_referenced.contains(&candidate)
|
||||
&& let Some(entry) = working.resources.get(&candidate)
|
||||
&& let Some(entry) = batch.resource(candidate)
|
||||
{
|
||||
ops.push(RegistryDelta::RemoveResource {
|
||||
id: candidate,
|
||||
@@ -572,46 +563,78 @@ fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::No
|
||||
}
|
||||
}
|
||||
|
||||
/// The nodes of each network, grouped once. A removal closure then walks only the subtree it removes,
|
||||
/// instead of rescanning every node in the document for each nested network it meets.
|
||||
struct NodesByNetwork(HashMap<document_graph_storage::NetworkId, Vec<document_graph_storage::NodeId>>);
|
||||
/// The registry a delta is constructed against: what the batch started from, plus the nodes deltas
|
||||
/// earlier in the same batch have added.
|
||||
///
|
||||
/// A delta that reads a node back cannot read only the starting registry. A node added and removed
|
||||
/// within one batch is not in it, and a later delta that rebuilds a node would rebuild the version
|
||||
/// that predates the batch. Additions are tracked rather than the whole registry copied, so the cost
|
||||
/// is the size of the batch rather than of the document.
|
||||
///
|
||||
/// Nodes are also indexed by network, so a removal closure walks only the subtree it removes instead
|
||||
/// of rescanning every node for each nested network it meets.
|
||||
struct BatchRegistry<'a> {
|
||||
working: &'a Registry,
|
||||
added: HashMap<document_graph_storage::NodeId, document_graph_storage::Node>,
|
||||
added_resources: HashMap<ResourceId, document_graph_storage::ResourceEntry>,
|
||||
by_network: HashMap<document_graph_storage::NetworkId, Vec<document_graph_storage::NodeId>>,
|
||||
}
|
||||
|
||||
impl NodesByNetwork {
|
||||
fn new(working: &Registry) -> Self {
|
||||
impl<'a> BatchRegistry<'a> {
|
||||
fn new(working: &'a Registry) -> Self {
|
||||
let mut by_network: HashMap<_, Vec<_>> = HashMap::new();
|
||||
for (id, node) in &working.node_instances {
|
||||
by_network.entry(node.network()).or_default().push(*id);
|
||||
}
|
||||
Self(by_network)
|
||||
Self {
|
||||
working,
|
||||
added: HashMap::new(),
|
||||
added_resources: HashMap::new(),
|
||||
by_network,
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a node an earlier delta in this batch added, so a later one can read it back.
|
||||
fn record_addition(&mut self, id: document_graph_storage::NodeId, node: document_graph_storage::Node) {
|
||||
self.by_network.entry(node.network()).or_default().push(id);
|
||||
self.added.insert(id, node);
|
||||
}
|
||||
|
||||
/// Records a resource this batch added. Returns whether it is new to the batch, so the caller emits
|
||||
/// one addition for a resource several nodes reference.
|
||||
fn record_resource(&mut self, id: ResourceId, entry: document_graph_storage::ResourceEntry) -> bool {
|
||||
self.added_resources.insert(id, entry).is_none()
|
||||
}
|
||||
|
||||
fn node(&self, id: document_graph_storage::NodeId) -> Option<&document_graph_storage::Node> {
|
||||
self.added.get(&id).or_else(|| self.working.node_instances.get(&id))
|
||||
}
|
||||
|
||||
fn resource(&self, id: ResourceId) -> Option<&document_graph_storage::ResourceEntry> {
|
||||
self.added_resources.get(&id).or_else(|| self.working.resources.get(&id))
|
||||
}
|
||||
|
||||
fn children(&self, network_id: document_graph_storage::NetworkId) -> &[document_graph_storage::NodeId] {
|
||||
self.0.get(&network_id).map_or(&[], Vec::as_slice)
|
||||
self.by_network.get(&network_id).map_or(&[], Vec::as_slice)
|
||||
}
|
||||
}
|
||||
|
||||
/// The node together with everything nested under it, and the networks that nesting owns.
|
||||
fn removal_closure(node_id: document_graph_storage::NodeId, working: &Registry, nodes_by_network: &NodesByNetwork) -> (Vec<document_graph_storage::NodeId>, Vec<document_graph_storage::NetworkId>) {
|
||||
fn removal_closure(node_id: document_graph_storage::NodeId, batch: &BatchRegistry) -> (Vec<document_graph_storage::NodeId>, Vec<document_graph_storage::NetworkId>) {
|
||||
let mut nodes = Vec::new();
|
||||
let mut networks = Vec::new();
|
||||
collect_removal_closure(node_id, working, nodes_by_network, &mut nodes, &mut networks);
|
||||
collect_removal_closure(node_id, batch, &mut nodes, &mut networks);
|
||||
(nodes, networks)
|
||||
}
|
||||
|
||||
fn collect_removal_closure(
|
||||
node_id: document_graph_storage::NodeId,
|
||||
working: &Registry,
|
||||
nodes_by_network: &NodesByNetwork,
|
||||
nodes: &mut Vec<document_graph_storage::NodeId>,
|
||||
networks: &mut Vec<document_graph_storage::NetworkId>,
|
||||
) {
|
||||
let Some(node) = working.node_instances.get(&node_id) else { return };
|
||||
fn collect_removal_closure(node_id: document_graph_storage::NodeId, batch: &BatchRegistry, nodes: &mut Vec<document_graph_storage::NodeId>, networks: &mut Vec<document_graph_storage::NetworkId>) {
|
||||
let Some(node) = batch.node(node_id) else { return };
|
||||
nodes.push(node_id);
|
||||
|
||||
if let &Implementation::Network(network_id) = node.implementation() {
|
||||
networks.push(network_id);
|
||||
for &child_id in nodes_by_network.children(network_id) {
|
||||
collect_removal_closure(child_id, working, nodes_by_network, nodes, networks);
|
||||
for &child_id in batch.children(network_id) {
|
||||
collect_removal_closure(child_id, batch, nodes, networks);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+24
@@ -470,6 +470,30 @@ async fn replaying_a_node_insertion_reproduces_the_interface() {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// A node added and removed inside one batch is never in the registry the batch started from, so the
|
||||
/// removal has nothing to look up there. The pair has to cancel out rather than leaving the addition
|
||||
/// staged on its own.
|
||||
#[tokio::test]
|
||||
async fn a_node_added_and_removed_in_one_batch_leaves_nothing_behind() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let working = convert(&editor);
|
||||
editor.active_document_mut().network_interface.discard_deltas();
|
||||
|
||||
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
|
||||
.expect("rectangle definition")
|
||||
.default_node_template();
|
||||
let node_id = NodeId(0xDE17A);
|
||||
editor.active_document_mut().network_interface.insert_node(node_id, template, &[]);
|
||||
editor.active_document_mut().network_interface.delete_nodes(vec![node_id], true, &[]);
|
||||
|
||||
let emitted = editor.active_document_mut().network_interface.take_deltas();
|
||||
let constructed = construct(&editor, &emitted, &working);
|
||||
let diffed = compute_deltas(&working, &convert(&editor));
|
||||
assert_same_stored_effect(&working, constructed, diffed, "add then remove in one batch");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn removing_a_nested_network_node_matches_the_diff() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -87,20 +87,19 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
pub fn vector_modify(&mut self, node_id: &NodeId, modification_type: VectorModificationType) {
|
||||
let Some(node) = self.network_graph_mut(&[]).and_then(|network| network.nodes.get_mut(node_id)) else {
|
||||
log::error!("Could not get node in vector_modification");
|
||||
return;
|
||||
};
|
||||
{
|
||||
let mut value = node.inputs.get_mut(1).and_then(|input| input.as_value_mut());
|
||||
let Some(TaggedValue::VectorModification(modification)) = value.as_deref_mut() else {
|
||||
let mut modified = false;
|
||||
self.edit_input_value(&InputConnector::node_at_index(*node_id, 1), &[], |value| {
|
||||
let TaggedValue::VectorModification(modification) = value else {
|
||||
log::error!("Path node {node_id} does not have a modification input");
|
||||
return;
|
||||
};
|
||||
|
||||
modification.modify(&modification_type);
|
||||
modified = true;
|
||||
});
|
||||
|
||||
if modified {
|
||||
self.transaction_modified();
|
||||
}
|
||||
self.transaction_modified();
|
||||
}
|
||||
|
||||
/// Inserts a new export at insert index. If the insert index is -1 it is inserted at the end. The output_name is used by the encapsulating node.
|
||||
|
||||
@@ -677,6 +677,50 @@ impl NodeNetworkInterface {
|
||||
Some(previous)
|
||||
}
|
||||
|
||||
/// Edits the value at `connector` in place, recording the value the edit leaves behind.
|
||||
///
|
||||
/// For a change expressed as an operation on the existing value rather than as a replacement of it.
|
||||
/// Reading the value out, editing it, and writing it back would copy it twice; the recorded delta
|
||||
/// still carries the whole result, since the storage op is a whole-value write.
|
||||
pub(crate) fn edit_input_value(&mut self, connector: &InputConnector, network_path: &[NodeId], edit: impl FnOnce(&mut TaggedValue)) -> bool {
|
||||
let Some(network) = self.network_graph_mut(network_path) else {
|
||||
log::error!("Could not get nested network in edit_input_value");
|
||||
return false;
|
||||
};
|
||||
|
||||
let slot = match connector {
|
||||
InputConnector::Node { node_id, input_index } => network.nodes.get_mut(node_id).and_then(|node| node.inputs.get_mut(*input_index)),
|
||||
InputConnector::Export(export_index) => network.exports.get_mut(*export_index),
|
||||
};
|
||||
let Some(slot) = slot else {
|
||||
log::error!("Could not get input {connector:?} in edit_input_value");
|
||||
return false;
|
||||
};
|
||||
let Some(mut value) = slot.as_value_mut() else {
|
||||
log::error!("Input {connector:?} is not a value in edit_input_value");
|
||||
return false;
|
||||
};
|
||||
|
||||
edit(&mut value);
|
||||
drop(value);
|
||||
|
||||
let input = slot.clone();
|
||||
self.deltas.push(EditorDelta::Graph(match connector {
|
||||
InputConnector::Node { node_id, input_index } => RuntimeDelta::SetInput {
|
||||
network_path: network_path.to_vec(),
|
||||
node_id: *node_id,
|
||||
input_index: *input_index,
|
||||
input,
|
||||
},
|
||||
InputConnector::Export(export_index) => RuntimeDelta::SetExport {
|
||||
network_path: network_path.to_vec(),
|
||||
export_index: *export_index,
|
||||
input: Some(input),
|
||||
},
|
||||
}));
|
||||
true
|
||||
}
|
||||
|
||||
/// Inserts a node and its metadata, returning the entry it replaced.
|
||||
pub(crate) fn insert_node_entry(&mut self, locator: NodeLocator, template: NodeTemplate) -> Option<NodeTemplate> {
|
||||
if !self.network_pair_exists(locator.network_path) {
|
||||
|
||||
Reference in new issue
Block a user