diff --git a/document/format/src/lib.rs b/document/format/src/lib.rs index b30701e981..0fa45b1fd3 100644 --- a/document/format/src/lib.rs +++ b/document/format/src/lib.rs @@ -20,7 +20,7 @@ use document_graph_storage::{CommitError, NodeMetadataSource}; use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session}; #[cfg(feature = "conversion")] use graphene_resource::LoadResource; -use graphene_resource::ResourceHash; +use graphene_resource::{ResourceHash, ResourceStorage}; pub mod codec; pub mod error; @@ -86,8 +86,24 @@ pub struct Gdd { /// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer /// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network. pub(crate) network_view_settings: std::collections::BTreeMap>, + /// Where this document's resource bytes live. `None` means the working copy's own content-addressed + /// store, which is what a standalone handle uses. The editor points this at its application-wide + /// cache, the single store resources are kept in there. + pub(crate) byte_store: Option>, #[cfg(feature = "network")] pub(crate) network: Option, + #[cfg(feature = "network")] + pub(crate) pending_persist: PendingPersist, +} + +/// Whole-file rewrites the sync path defers to the end of a poll, so one batch of remote packets costs +/// one rewrite of each file rather than one per packet. +#[cfg(feature = "network")] +#[derive(Debug, Default, Clone, Copy)] +pub(crate) struct PendingPersist { + pub(crate) history: bool, + pub(crate) hot_log: bool, + pub(crate) snapshot: bool, } impl Clone for Gdd { @@ -99,8 +115,11 @@ impl Clone for Gdd { manifest: self.manifest.clone(), view_settings: self.view_settings.clone(), network_view_settings: self.network_view_settings.clone(), + byte_store: self.byte_store.clone(), #[cfg(feature = "network")] network: None, + #[cfg(feature = "network")] + pending_persist: PendingPersist::default(), } } } @@ -187,8 +206,11 @@ impl Gdd { manifest, view_settings: session_state.view_settings, network_view_settings: session_state.network_view_settings, + byte_store: None, #[cfg(feature = "network")] network: None, + #[cfg(feature = "network")] + pending_persist: PendingPersist::default(), }) } @@ -211,8 +233,11 @@ impl Gdd { manifest, view_settings: std::collections::BTreeMap::new(), network_view_settings: std::collections::BTreeMap::new(), + byte_store: None, #[cfg(feature = "network")] network: None, + #[cfg(feature = "network")] + pending_persist: PendingPersist::default(), }) } } diff --git a/document/format/src/network.rs b/document/format/src/network.rs index 9cb28364a8..b33e6301f9 100644 --- a/document/format/src/network.rs +++ b/document/format/src/network.rs @@ -5,13 +5,12 @@ use std::collections::HashSet; -use document_container::AsyncContainer; use document_graph_storage::{Delta, HotOp, PeerId, Registry, ResourceHash, Rev, Session, TimeStamp, UserId}; use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, Transport}; -use crate::Gdd; use crate::error::Error; use crate::layout::Layout; +use crate::{Gdd, PendingPersist}; impl Gdd { pub fn share(&mut self, transport: impl Transport + 'static, user: UserId) { @@ -88,10 +87,11 @@ impl SyncTarget for Gdd { fn load(&mut self, registry: Registry, history: Vec, head: Option) -> Result<(), TargetError> { self.session.load(registry, history, head)?; - self.rewrite_history()?; - self.rewrite_hot_log()?; - self.persist_registry_snapshot()?; - self.persist_session_state()?; + self.pending_persist = PendingPersist { + history: true, + hot_log: true, + snapshot: true, + }; Ok(()) } @@ -105,25 +105,34 @@ impl SyncTarget for Gdd { fn merge_remote(&mut self, deltas: Vec, retires: &[TimeStamp]) -> Result<(), TargetError> { self.session.merge_remote(deltas, retires)?; - self.rewrite_history()?; - if !retires.is_empty() { + self.pending_persist.history = true; + self.pending_persist.hot_log |= !retires.is_empty(); + self.pending_persist.snapshot = true; + Ok(()) + } + + fn flush(&mut self) -> Result<(), TargetError> { + let pending = std::mem::take(&mut self.pending_persist); + + if pending.history { + self.rewrite_history()?; + } + if pending.hot_log { self.rewrite_hot_log()?; } - self.persist_registry_snapshot()?; - self.persist_session_state()?; + if pending.snapshot { + self.persist_registry_snapshot()?; + self.persist_session_state()?; + } Ok(()) } fn missing_resources(&self) -> HashSet { - self.session - .all_referenced_resource_hashes() - .into_iter() - .filter(|hash| !self.working.exists_non_blocking(&self.layout.resource_path(hash))) - .collect() + self.unstored_resources().into_iter().collect() } - fn store_resource(&mut self, hash: ResourceHash, bytes: Vec) -> Result<(), TargetError> { - self.working.write_non_blocking(&self.layout.resource_path(&hash), &bytes)?; + fn store_resource(&mut self, _hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> { + self.hold_resource(bytes)?; Ok(()) } } diff --git a/document/format/src/persist.rs b/document/format/src/persist.rs index 5f0f00daf8..455adc3175 100644 --- a/document/format/src/persist.rs +++ b/document/format/src/persist.rs @@ -65,15 +65,10 @@ impl Gdd { 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) and into the working copy itself, so the - // document stays self-contained for peers and exports. Content-addressed, so re-storing + // the working-copy container for standalone export). Content-addressed, so re-storing // identical bytes on every commit is an idempotent no-op. - for (hash, bytes) in &conversion.declaration_bytes { + for bytes in conversion.declaration_bytes.values() { byte_store.store(bytes); - let path = self.layout.resource_path(hash); - if !self.working.exists_non_blocking(&path) { - self.working.write_non_blocking(&path, bytes)?; - } } Ok(conversion.declarations) } diff --git a/document/format/src/resource.rs b/document/format/src/resource.rs index 357416de41..81c58be354 100644 --- a/document/format/src/resource.rs +++ b/document/format/src/resource.rs @@ -91,6 +91,36 @@ impl Gdd { { ResourceProxy(self.working.clone(), self.layout.clone()) } + + /// Point resource lookups at an external store instead of the working copy, for an embedder that + /// already keeps one cache for every open document. + pub fn set_byte_store(&mut self, byte_store: Arc) { + self.byte_store = Some(byte_store); + } + + /// Whether this document's resource bytes are on hand, in whichever store backs it. + pub fn holds_resource(&self, hash: &ResourceHash) -> bool { + match &self.byte_store { + Some(byte_store) => byte_store.contains(hash), + None => self.working.exists_non_blocking(&self.layout.resource_path(hash)), + } + } + + /// Put resource bytes into whichever store backs this document. + pub fn hold_resource(&self, bytes: &[u8]) -> Result<(), ContainerError> { + match &self.byte_store { + Some(byte_store) => { + byte_store.store(bytes); + Ok(()) + } + None => self.working.write_non_blocking(&self.layout.resource_path(&ResourceHash::from(bytes)), bytes), + } + } + + /// Resources the registry or its history names whose bytes are not on hand. + pub fn unstored_resources(&self) -> Vec { + self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.holds_resource(hash)).collect() + } } impl LoadResource for Gdd { diff --git a/document/peer-transport/src/replica.rs b/document/peer-transport/src/replica.rs index b4bb1fd24c..b7b4e70194 100644 --- a/document/peer-transport/src/replica.rs +++ b/document/peer-transport/src/replica.rs @@ -2,7 +2,7 @@ use crate::packet::{Broadcast, BroadcastBody, PacketError, Role, SyncPacket, Syn use crate::target::{SyncTarget, TargetError}; use crate::transport::{Transport, TransportEvent, TransportPeerId}; use document_graph_storage::{Delta, HotOp, PeerId, ResourceHash, TimeStamp, UserId}; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; pub enum Event { PeerJoined { @@ -16,7 +16,10 @@ pub enum Event { Synced, /// Remote ops changed the target. Changed, - ResourceReceived(ResourceHash), + ResourceReceived { + hash: ResourceHash, + bytes: Vec, + }, /// The target couldn't serve this synchronously; answer with `send_resource`. ResourceRequested { from: TransportPeerId, @@ -63,6 +66,10 @@ pub struct Replica { seq: u64, delivered: HashMap, held: Vec<(PeerId, Broadcast)>, + /// Resources asked for and not yet received, so a standing request is not resent every poll. + requested_resources: HashSet, + /// Whether the target's resource references may have moved since they were last examined. + resources_stale: bool, } impl Replica { @@ -85,6 +92,8 @@ impl Replica { seq: 0, delivered: HashMap::new(), held: Vec::new(), + requested_resources: HashSet::new(), + resources_stale: false, } } @@ -130,13 +139,6 @@ impl Replica { self.delivered.iter().map(|(&peer, &seq)| (peer, seq)).chain([(self.peer, self.seq)]).collect() } - pub fn request_resources(&mut self, hashes: Vec) -> Result<(), PacketError> { - if hashes.is_empty() { - return Ok(()); - } - self.transport.broadcast(&SyncPacket::ResourceRequest(hashes)) - } - pub fn send_resource(&mut self, to: TransportPeerId, hash: ResourceHash, bytes: Vec) -> Result<(), PacketError> { self.transport.send(to, &SyncPacket::Resource { hash, bytes }) } @@ -155,6 +157,9 @@ impl Replica { if let Some(remote) = self.peers.remove(&transport_peer) { events.push(Event::PeerLeft { peer: remote.peer }); } + // A peer that left may have been the one still owing bytes, so let the rest be asked again. + self.requested_resources.clear(); + self.resources_stale = true; Ok(()) } TransportEvent::Packet(transport_peer, packet) => self.handle_packet(transport_peer, packet, target, &mut events), @@ -169,9 +174,34 @@ impl Replica { } } + if let Err(error) = target.flush() { + log::error!("Sync error: {error}"); + } + if let Err(error) = self.request_missing_resources(target) { + log::error!("Sync error: {error}"); + } + events } + /// Ask the room for referenced bytes nobody here has yet. Runs after every batch of packets rather + /// than once at sync, since an op delivered later can reference a resource this peer has never seen. + /// Only the hashes without a standing request go out, so a slow transfer is not re-requested. + fn request_missing_resources(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> { + if !self.resources_stale { + return Ok(()); + } + self.resources_stale = false; + + let missing: Vec = target.missing_resources().into_iter().filter(|hash| !self.requested_resources.contains(hash)).collect(); + if missing.is_empty() { + return Ok(()); + } + + self.requested_resources.extend(missing.iter().copied()); + self.transport.broadcast(&SyncPacket::ResourceRequest(missing)) + } + fn send_hello(&mut self, transport_peer: TransportPeerId) -> Result<(), ReplicaError> { let hello = SyncPacket::Hello { peer: self.peer, @@ -189,6 +219,9 @@ impl Replica { self.peers.insert(from, RemotePeer { peer, user, role }); self.observe_delivered(peer, seq); events.push(Event::PeerJoined { peer, user }); + // A fresh peer may hold bytes nobody else here could serve. + self.requested_resources.clear(); + self.resources_stale = true; if role == Role::Host && !self.is_synced() { self.transport.send(from, &SyncPacket::SyncRequest { known_revs: target.known_revs() })?; @@ -219,6 +252,7 @@ impl Replica { None => target.merge_remote(sync.deltas, &[])?, } target.apply_remote_hot_ops(sync.hot_log)?; + self.resources_stale = true; // Broadcasts the host had delivered before answering are already reflected in the snapshot. for (peer, seq) in sync.seen { @@ -235,7 +269,6 @@ impl Replica { retires: Vec::new(), })?; } - self.transport.send(from, &SyncPacket::ResourceRequest(target.missing_resources().into_iter().collect()))?; events.push(Event::Synced); } @@ -262,8 +295,9 @@ impl Replica { log::warn!("Resource from {from} does not match its hash; dropping"); return Ok(()); } - target.store_resource(hash, bytes)?; - events.push(Event::ResourceReceived(hash)); + target.store_resource(hash, &bytes)?; + self.requested_resources.remove(&hash); + events.push(Event::ResourceReceived { hash, bytes }); } } @@ -288,6 +322,7 @@ impl Replica { BroadcastBody::HotOps(ops) => target.apply_remote_hot_ops(ops)?, BroadcastBody::Deltas { deltas, retires } => target.merge_remote(deltas, &retires)?, } + self.resources_stale = true; events.push(Event::Changed); } Ok(()) diff --git a/document/peer-transport/src/target.rs b/document/peer-transport/src/target.rs index 5e647b0aff..92c2c84f50 100644 --- a/document/peer-transport/src/target.rs +++ b/document/peer-transport/src/target.rs @@ -18,6 +18,11 @@ pub trait SyncTarget { /// Must be idempotent on structural ops: a buffered op may already be reflected by the sync. fn apply_remote_hot_ops(&mut self, ops: Vec) -> Result<(), TargetError>; fn merge_remote(&mut self, deltas: Vec, retires: &[TimeStamp]) -> Result<(), TargetError>; + /// Make everything applied since the last flush durable. Called once per [`Replica::poll`](crate::Replica::poll), + /// so a target that rewrites whole files can do it once for a batch rather than once per packet. + fn flush(&mut self) -> Result<(), TargetError> { + Ok(()) + } /// Referenced resources whose bytes are not available locally. fn missing_resources(&self) -> HashSet { @@ -28,7 +33,7 @@ pub trait SyncTarget { let _ = hash; None } - fn store_resource(&mut self, hash: ResourceHash, bytes: Vec) -> Result<(), TargetError> { + fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> { let _ = (hash, bytes); Ok(()) } diff --git a/editor/src/messages/portfolio/document/document_message_handler.rs b/editor/src/messages/portfolio/document/document_message_handler.rs index 7af85efcc2..97a7b109f4 100644 --- a/editor/src/messages/portfolio/document/document_message_handler.rs +++ b/editor/src/messages/portfolio/document/document_message_handler.rs @@ -34,7 +34,7 @@ use crate::messages::tool::utility_types::ToolType; use crate::node_graph_executor::NodeGraphExecutor; use document_graph_storage::Declarations; use glam::{DAffine2, DVec2}; -use graph_craft::application_io::resource::ResourceId; +use graph_craft::application_io::resource::{ResourceId, ResourceStorage}; use graph_craft::application_io::wgpu_available; use graph_craft::document::value::TaggedValue; use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork}; @@ -1814,7 +1814,14 @@ impl MessageHandler> for DocumentMes impl DocumentMessageHandler { /// Build a document handler from a `.gdd` working copy. - pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, declarations: Declarations, name: String, path: Option) -> Self { + pub fn from_storage( + interface: NodeNetworkInterface, + storage: document_format::GddV1, + declarations: Declarations, + byte_store: Arc, + name: String, + path: Option, + ) -> Self { let mut document = Self { network_interface: interface, name, @@ -1823,11 +1830,7 @@ impl DocumentMessageHandler { }; document.apply_stored_document_settings(storage.view_settings()); - match storage.registry().to_resource_registry() { - Ok(resource_registry) => document.resources.registry = resource_registry, - Err(error) => log::error!("Opening .gdd: failed to rebuild resource registry: {error}"), - } - document.history.set_storage(storage, declarations); + document.set_storage(storage, declarations, byte_store); document } @@ -2023,8 +2026,10 @@ impl DocumentMessageHandler { } /// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references. - pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) { + pub fn set_storage(&mut self, mut storage: document_format::GddV1, declarations: Declarations, byte_store: Arc) { + storage.set_byte_store(byte_store); self.history.set_storage(storage, declarations); + self.refresh_resource_registry(); } /// Retire the pending staged hot ops into durable Gdd history as one undo unit. @@ -2103,6 +2108,18 @@ impl DocumentMessageHandler { } } + /// Rebuild the runtime resource registry from storage, which holds each resource's id, content hash + /// and sources. The preprocessor resolves a node's `Resource` input through it, so an interface + /// swapped in from storage needs it refreshed alongside. Keeps the current registry on failure. + fn refresh_resource_registry(&mut self) { + let Some(storage) = self.history.storage() else { return }; + + 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}"), + } + } + /// Swap in an interface rebuilt from the registry a peer's changes left behind. pub(crate) fn apply_remote_changes(&mut self, responses: &mut VecDeque) { let Some(rebuilt) = self.history.rebuild_interface() else { return }; @@ -2129,6 +2146,7 @@ impl DocumentMessageHandler { if let Some(gdd) = self.history.storage_mut() { gdd.mark_runtime_current(); } + self.refresh_resource_registry(); if validate { let current_resources: std::collections::HashSet<_> = self.used_resources(false).iter().copied().collect(); diff --git a/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs b/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs index 5c6e85a597..0e1a4c1e07 100644 --- a/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs +++ b/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs @@ -4,11 +4,13 @@ //! MessagePack 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}; use graph_craft::application_io::resource::HashMapResourceStorage; +use std::sync::Arc; use super::test_support::{RoundTrip, node_paths, round_trip_through_gdd}; use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler; @@ -156,7 +158,7 @@ async fn edit_after_open_commits_cleanly() { // Persist the document into a fresh Gdd and reopen it, then build a runtime document from the // reopened registry: the editor's .gdd-open path. - let byte_store = HashMapResourceStorage::new(); + let byte_store = ResourcesHandle::new(Arc::new(HashMapResourceStorage::new())); let source = editor.active_document(); let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into()) .await @@ -176,7 +178,7 @@ async fn edit_after_open_commits_cleanly() { { let document = editor.active_document_mut(); document.network_interface = rebuilt; - document.set_storage(reopened, declarations); + document.set_storage(reopened, declarations, byte_store.storage()); document.finalize_storage_load(); } @@ -674,12 +676,13 @@ fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) { /// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real /// autosave path) runs against it. Returns the byte store the document's resources resolve through. -async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourceStorage { +async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> ResourcesHandle { let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0x5EED, "test".into(), "test".into()) .await .expect("create_in"); - editor.active_document_mut().set_storage(gdd, Default::default()); - HashMapResourceStorage::new() + let byte_store = ResourcesHandle::new(Arc::new(HashMapResourceStorage::new())); + editor.active_document_mut().set_storage(gdd, Default::default(), byte_store.storage()); + byte_store } /// Open a real demo artwork, mount storage, edit it, and trigger autosave. The autosave runs diff --git a/editor/src/messages/portfolio/document_storage_io.rs b/editor/src/messages/portfolio/document_storage_io.rs index d68d65c883..5793b6898b 100644 --- a/editor/src/messages/portfolio/document_storage_io.rs +++ b/editor/src/messages/portfolio/document_storage_io.rs @@ -90,7 +90,7 @@ pub(super) async fn open_gdd_document( /// Core of the `.gdd` open: archive -> working copy -> `Gdd` -> runtime interface. The registry build is /// authoritative; the embedded legacy blob is the soak oracle and the fallback if the build fails. /// Returns `None` only if neither the build nor the legacy fallback worked. -async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8], store_handle: &impl ResourceStorage, document_id: DocumentId, validate: bool) -> Option { +async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8], store_handle: &ResourcesHandle, document_id: DocumentId, validate: bool) -> Option { let (container, _exists) = match build_per_document_container(path).await { Ok(result) => result, Err(error) => { @@ -164,7 +164,7 @@ async fn build_document_from_gdd(path: Option<&std::path::Path>, content: &[u8], ); } } - return Some(DocumentMessageHandler::from_storage(interface, gdd, declarations, String::new(), None)); + return Some(DocumentMessageHandler::from_storage(interface, gdd, declarations, store_handle.storage(), String::new(), None)); } log::warn!("Opening .gdd for {document_id:?}: registry build failed, falling back to embedded legacy document"); diff --git a/editor/src/messages/portfolio/portfolio_message_handler.rs b/editor/src/messages/portfolio/portfolio_message_handler.rs index d881096b8e..5507a1ea75 100644 --- a/editor/src/messages/portfolio/portfolio_message_handler.rs +++ b/editor/src/messages/portfolio/portfolio_message_handler.rs @@ -327,7 +327,7 @@ impl MessageHandler> for Portfolio log::error!("DocumentStorageMounted for {document_id:?} arrived without its payload"); return; }; - document.set_storage(gdd, declarations); + document.set_storage(gdd, declarations, resource_storage.resources_mut().storage()); if !reopened { document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip); document.retire_storage_interaction(); diff --git a/editor/src/messages/portfolio/sync/sync_message.rs b/editor/src/messages/portfolio/sync/sync_message.rs index a9dd5faff4..f2743770bb 100644 --- a/editor/src/messages/portfolio/sync/sync_message.rs +++ b/editor/src/messages/portfolio/sync/sync_message.rs @@ -24,6 +24,4 @@ pub enum SyncMessage { hash: ResourceHash, bytes: Vec, }, - /// A resource received from a peer was copied into the byte store. - ResourceStored { document_id: DocumentId, hash: ResourceHash, bytes: Vec }, } diff --git a/editor/src/messages/portfolio/sync/sync_message_handler.rs b/editor/src/messages/portfolio/sync/sync_message_handler.rs index 3e18dd4d2c..705a4899e3 100644 --- a/editor/src/messages/portfolio/sync/sync_message_handler.rs +++ b/editor/src/messages/portfolio/sync/sync_message_handler.rs @@ -4,7 +4,7 @@ use crate::messages::portfolio::document::utility_types::network_interface::Tran use crate::messages::prelude::*; use crate::messages::resource_storage::ResourcesHandle; use document_graph_storage::UserId; -use graph_craft::application_io::resource::{LoadResource, ResourceStorage}; +use graph_craft::application_io::resource::LoadResource; use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, Room, SessionToken, SyncTarget}; use std::collections::HashSet; @@ -23,8 +23,6 @@ pub struct SyncMessageHandler { polling: bool, /// Documents whose registry changed remotely since their interface was last rebuilt. dirty: HashSet, - /// Received resources still being copied into the app cache, per document. - storing: HashMap, blocked_reason: HashMap, } @@ -110,7 +108,6 @@ impl MessageHandler> for SyncMessageHandler } let events = gdd.poll_peers(); - let proxy = gdd.resource_proxy(); for event in events { match event { Event::Synced | Event::Changed => { @@ -119,12 +116,13 @@ impl MessageHandler> for SyncMessageHandler } Event::ResourceRequested { from, hash } => { log::debug!("Peer asked for resource {hash}"); - responses.add(load_resource_future(document_id, from, hash, proxy.clone(), resources.clone())); + responses.add(load_resource_future(document_id, from, hash, resources.clone())); } - Event::ResourceReceived(hash) => { - log::debug!("Received resource {hash}"); - *self.storing.entry(document_id).or_default() += 1; - responses.add(store_resource_future(document_id, hash, proxy.clone(), resources.clone())); + // The replica already put the bytes in the byte store; only the decoded form is missing. + Event::ResourceReceived { hash, bytes } => { + log::debug!("Received resource {hash} ({} bytes)", bytes.len()); + document.cache_declaration_bytes(hash, &bytes); + self.dirty.insert(document_id); } Event::PeerJoined { .. } | Event::PeerLeft { .. } => responses.add(PortfolioMessage::UpdateOpenDocumentsList), } @@ -139,11 +137,10 @@ impl MessageHandler> for SyncMessageHandler continue; }; let Some(gdd) = document.storage() else { continue }; - let storing = self.storing.get(&document_id).copied().unwrap_or(0); let missing = SyncTarget::missing_resources(gdd).len(); let transaction = document.network_interface.transaction_status(); - if storing > 0 || missing > 0 || transaction != TransactionStatus::Finished { - let reason = format!("storing {storing} missing {missing} transaction {transaction:?}"); + if missing > 0 || transaction != TransactionStatus::Finished { + let reason = format!("missing {missing} transaction {transaction:?}"); if self.blocked_reason.get(&document_id) != Some(&reason) { log::debug!("Sync rebuild for {document_id:?} waiting: {reason}"); self.blocked_reason.insert(document_id, reason); @@ -154,6 +151,8 @@ impl MessageHandler> for SyncMessageHandler self.dirty.remove(&document_id); document.apply_remote_changes(responses); + // The swapped-in registry names resources this peer may still have to fetch or resolve. + responses.add(PortfolioMessage::ResolveDocumentResources { document_id }); } } SyncMessage::ResourceLoaded { document_id, to, hash, bytes } => { @@ -165,15 +164,6 @@ impl MessageHandler> for SyncMessageHandler log::warn!("Failed to send resource {hash} to a peer: {error}"); } } - SyncMessage::ResourceStored { document_id, hash, bytes } => { - if let Some(count) = self.storing.get_mut(&document_id) { - *count = count.saturating_sub(1); - } - if let Some(document) = documents.get_mut(&document_id) { - document.cache_declaration_bytes(hash, &bytes); - } - self.dirty.insert(document_id); - } } } @@ -203,21 +193,9 @@ fn driver_future(document_id: DocumentId, driver: peer_transport::MessageLoopFut future.into() } -/// The working copy is checked before the app cache: it is the document's own store, which another tab -/// sharing the cache can't garbage-collect from under it. -fn load_resource_future( - document_id: DocumentId, - to: peer_transport::TransportPeerId, - hash: graph_craft::application_io::resource::ResourceHash, - proxy: document_format::ResourceProxy, - resources: ResourcesHandle, -) -> Message { +fn load_resource_future(document_id: DocumentId, to: peer_transport::TransportPeerId, hash: graph_craft::application_io::resource::ResourceHash, resources: ResourcesHandle) -> Message { let future = async move { - let resource = match proxy.load(hash).await { - Some(resource) => Some(resource), - None => resources.load(hash).await, - }; - match resource { + match resources.load(hash).await { Some(resource) => Message::Portfolio(PortfolioMessage::Sync(SyncMessage::ResourceLoaded { document_id, to, @@ -233,28 +211,6 @@ fn load_resource_future( future.into() } -fn store_resource_future( - document_id: DocumentId, - hash: graph_craft::application_io::resource::ResourceHash, - proxy: document_format::ResourceProxy, - resources: ResourcesHandle, -) -> Message { - let future = async move { - let bytes = match proxy.load(hash).await { - Some(resource) => { - resources.store(resource.as_ref()); - resource.as_ref().to_vec() - } - None => { - log::warn!("Received resource {hash} is missing from the working copy"); - Vec::new() - } - }; - Message::Portfolio(PortfolioMessage::Sync(SyncMessage::ResourceStored { document_id, hash, bytes })) - }; - future.into() -} - fn random_token_bytes() -> [u8; 16] { let mut bytes = [0; 16]; bytes[..8].copy_from_slice(&generate_uuid().to_le_bytes()); diff --git a/editor/src/messages/resource_storage/resource_storage_message_handler.rs b/editor/src/messages/resource_storage/resource_storage_message_handler.rs index 26001fb948..4ffdd9dfff 100644 --- a/editor/src/messages/resource_storage/resource_storage_message_handler.rs +++ b/editor/src/messages/resource_storage/resource_storage_message_handler.rs @@ -7,6 +7,17 @@ pub struct ResourcesHandle { inner: Arc, } +impl ResourcesHandle { + pub fn new(inner: Arc) -> Self { + Self { inner } + } + + /// The shared store behind this handle, for a consumer that needs to keep it alive itself. + pub fn storage(&self) -> Arc { + self.inner.clone() + } +} + impl LoadResource for ResourcesHandle { fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> { self.inner.load(hash) diff --git a/node-graph/graphene-cli/src/repl.rs b/node-graph/graphene-cli/src/repl.rs index 15fba33fac..70d5ee88ab 100644 --- a/node-graph/graphene-cli/src/repl.rs +++ b/node-graph/graphene-cli/src/repl.rs @@ -17,7 +17,7 @@ pub fn report(event: &Event) { Event::PeerLeft { peer } => println!("peer {peer:?} left"), Event::Synced => println!("synced"), Event::Changed => println!("document changed"), - Event::ResourceReceived(hash) => println!("received resource {hash}"), + Event::ResourceReceived { hash, bytes } => println!("received resource {hash} ({} bytes)", bytes.len()), Event::ResourceRequested { hash, .. } => println!("peer asked for resource {hash}"), } } diff --git a/node-graph/graphene-cli/src/watch.rs b/node-graph/graphene-cli/src/watch.rs index f31b7873ae..fec69617e9 100644 --- a/node-graph/graphene-cli/src/watch.rs +++ b/node-graph/graphene-cli/src/watch.rs @@ -170,7 +170,7 @@ impl ApplicationHandler for Viewer { fn new_events(&mut self, event_loop: &dyn ActiveEventLoop, _cause: StartCause) { for event in self.runtime.block_on(self.live.poll()) { - if matches!(event, Event::Synced | Event::Changed | Event::ResourceReceived(_)) { + if matches!(event, Event::Synced | Event::Changed | Event::ResourceReceived { .. }) { self.dirty = true; } }