From 722b87413436342152b5c1400925fb845e55e5fb Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 16:03:51 +0100 Subject: [PATCH] feat(sync): fetch the records of changes, and snapshots as they're read `Sync` shares records with a remote. This is its fetching side for changes: `fetch_changes` asks the remote what it holds of some changes, by id, and fetches the records this node lacks, with those they refer to, recursively (a revision's base and dependencies, a statement's subject and the statements it supersedes or promotes), then the records of the changes the revisions fetched belong to, so every change this node learns of comes whole. It flags the changes that diverged. Answers that stop short are asked for again from where they stopped. Snapshots don't come with records: `Sync::need` fetches one when something reads it, skipping what snapshots this node holds whole hold at the same path. A fetch publishes trees before what they hold, so a snapshot being fetched is marked durably in `fetching/`, synced with the batch, and `Store::holds` doesn't take a marked one for whole: fetching it again completes it. `Sync::repair` fetches a snapshot whole again, for one that lacks trees its root names. `Dependencies` now tells the records an object refers to from its content, since only records come with a fetch. --- AGENTS.md | 2 + apps/origin-src/src/lib.rs | 1 + apps/origin-src/src/remote.rs | 2 +- apps/origin-src/src/service.rs | 83 +++++-- apps/origin-src/src/store/mod.rs | 45 +++- apps/origin-src/src/sync.rs | 396 +++++++++++++++++++++++++++++++ apps/origin-src/src/tree.rs | 90 ++++++- 7 files changed, 584 insertions(+), 35 deletions(-) create mode 100644 apps/origin-src/src/sync.rs diff --git a/AGENTS.md b/AGENTS.md index 278bc0eb..bbb2226d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,6 +20,8 @@ review bots read and write at the same time, written in Rust. server. `OriginService` (`service.rs`) is the one API over a repository: the HTTP routes (`http.rs`) and the command line's commands that the API offers only translate into its calls, so neither duplicates the other. + `sync.rs` shares records with a remote (`remote.rs`), which answers the + same calls over the SDK or, for a local path, in-process. - `tools/xtask`: development tasks, run with `cargo xtask`, such as timing origin against git (`just bench-git`). diff --git a/apps/origin-src/src/lib.rs b/apps/origin-src/src/lib.rs index 130a07f7..092361e6 100644 --- a/apps/origin-src/src/lib.rs +++ b/apps/origin-src/src/lib.rs @@ -20,6 +20,7 @@ pub mod remote; pub mod server; pub mod service; pub mod store; +pub mod sync; pub mod targets; pub mod tree; pub mod workspace; diff --git a/apps/origin-src/src/remote.rs b/apps/origin-src/src/remote.rs index 1003eac6..e9abffb9 100644 --- a/apps/origin-src/src/remote.rs +++ b/apps/origin-src/src/remote.rs @@ -3,7 +3,7 @@ //! A remote is a server over HTTP, `http://host[:port]/`, or a //! repository on a local path: a server's repository, or a working copy's. //! A local one is served by an in-process [`OriginService`] run by this -//! node, so both answer the same calls, and syncing never +//! node, so both answer the same calls, and [`sync`](crate::sync) never //! tells them apart. Calls block: an HTTP remote runs the SDK on a runtime //! of its own. diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index 533e731f..2ef5e623 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -107,6 +107,15 @@ impl OriginService { } } + /// The service, answering fetches in parts of at most `limit` bytes. + #[cfg(test)] + pub(crate) fn with_pack_limit(self, limit: usize) -> Self { + Self { + pack_limit: limit, + ..self + } + } + /// The service, with `index`, just read, as its index. #[must_use] pub fn with_index(self, index: Index) -> Self { @@ -382,7 +391,7 @@ impl OriginService { let decoded = object .decode() .map_err(|source| ServiceError::Malformed { id, source })?; - for (needed, kind) in Dependencies::of(&decoded) { + for (needed, kind) in Dependencies::of(&decoded).all() { match held.get(&needed) { Some(&held) if held != Some(kind) => { return Err(ServiceError::WrongKind { id, needed, kind }); @@ -719,37 +728,50 @@ impl OriginService { } /// What an object needs the repository to have for it to be usable, as -/// [`OriginService::put_records`] lists, and the kind each must be. A +/// [`OriginService::put_records`] lists, and the kind each must be: the +/// records it refers to, and the content, snapshots and blobs. A /// revision's predecessors and a statement's payload are history and /// details: the repository may lack them, and retention may have dropped a -/// payload. -struct Dependencies; +/// payload. An acceptance needs nothing here: its chain brings what it +/// refers to. +#[derive(Debug, Default)] +pub(crate) struct Dependencies { + /// Revisions, statements and acceptances. + pub records: Vec<(ObjectId, ObjectKind)>, + /// Trees and blobs. + pub content: Vec<(ObjectId, ObjectKind)>, +} impl Dependencies { - fn of(object: &Object) -> Vec<(ObjectId, ObjectKind)> { + pub(crate) fn of(object: &Object) -> Self { match object { - Object::Blob(_) | Object::Acceptance(_) => Vec::new(), - Object::Tree(tree) => tree - .iter() - .map(|(_, entry)| (entry.id, entry.kind.object_kind())) - .collect(), + Object::Blob(_) | Object::Acceptance(_) => Self::default(), + Object::Tree(tree) => Self { + records: Vec::new(), + content: tree + .iter() + .map(|(_, entry)| (entry.id, entry.kind.object_kind())) + .collect(), + }, Object::Revision(revision) => { let base = match revision.base { Base::Acceptance(id) => (id.into(), ObjectKind::Acceptance), Base::Revision(id) => (id.into(), ObjectKind::Revision), }; - let mut needed = vec![ - (revision.snapshot.into(), ObjectKind::Tree), - (revision.description.into(), ObjectKind::Blob), - base, - ]; - needed.extend( + let mut records = vec![base]; + records.extend( revision .deps .iter() .map(|&id| (id.into(), ObjectKind::Revision)), ); - needed + Self { + records, + content: vec![ + (revision.snapshot.into(), ObjectKind::Tree), + (revision.description.into(), ObjectKind::Blob), + ], + } } Object::Statement(statement) => Self::of_statement(statement), } @@ -757,16 +779,25 @@ impl Dependencies { /// What a statement needs: its subject, and the statements it /// supersedes or promotes. - fn of_statement(statement: &Statement) -> Vec<(ObjectId, ObjectKind)> { + pub(crate) fn of_statement(statement: &Statement) -> Self { + let mut dependencies = Self::default(); let subject = (statement.subject.into(), statement.subject.kind()); - [Some(subject)] - .into_iter() - .chain( - [statement.supersedes, statement.promoted_from] - .map(|id| id.map(|id| (id.into(), ObjectKind::Statement))), - ) - .flatten() - .collect() + match statement.subject { + RecordId::Snapshot(_) => dependencies.content.push(subject), + _ => dependencies.records.push(subject), + } + dependencies.records.extend( + [statement.supersedes, statement.promoted_from] + .into_iter() + .flatten() + .map(|id| (id.into(), ObjectKind::Statement)), + ); + dependencies + } + + /// Every object needed, and the kind it must be. + pub(crate) fn all(&self) -> impl Iterator { + self.records.iter().chain(&self.content).copied() } } diff --git a/apps/origin-src/src/store/mod.rs b/apps/origin-src/src/store/mod.rs index 405aec97..48259051 100644 --- a/apps/origin-src/src/store/mod.rs +++ b/apps/origin-src/src/store/mod.rs @@ -247,9 +247,7 @@ impl Store

{ /// failure may not be durable. pub fn write_all(&self, objects: &[EncodedObject]) -> Result { let batch = self.batch(); - let written = Self::on_every_core(objects, |chunk| batch.write_all(chunk)) - .into_iter() - .sum::>()?; + let written = batch.stage_all(objects)?; batch.commit()?; Ok(written) } @@ -327,6 +325,24 @@ impl Store

{ Ok(self.path(id).exists() || self.find_packed(id)?.is_some()) } + /// Those of `ids` the store has, in order. + /// + /// # Errors + /// + /// Fails like [`Store::contains`]. + pub fn present + Copy>( + &self, + ids: impl IntoIterator, + ) -> Result, StoreError> { + let mut present = Vec::new(); + for id in ids { + if self.contains(id.into())? { + present.push(id); + } + } + Ok(present) + } + /// When this node stored the object: when its loose file was written, /// which packing it keeps. /// @@ -675,11 +691,26 @@ impl Batch<'_, P> { Ok(self.store.packs.find(id).is_some()) } - /// Stages each of `objects` in turn, returning how many were new. - fn write_all(&self, objects: &[EncodedObject]) -> Result { - objects.iter().try_fold(0, |written, object| { - Ok(written + usize::from(self.write(object)?)) + /// Makes `path`, a file or a directory written in place, durable before + /// anything the batch stages is published. + pub(crate) fn sync_first(&self, path: impl Into) { + self.write.sync_with(path); + } + + /// Stages `objects` from every core, returning how many were new, as + /// [`Store::write_all`] does. + /// + /// # Errors + /// + /// Fails like [`Batch::write`]. + pub fn stage_all(&self, objects: &[EncodedObject]) -> Result { + Store::

::on_every_core(objects, |chunk| { + chunk.iter().try_fold(0, |written, object| { + Ok(written + usize::from(self.write(object)?)) + }) }) + .into_iter() + .sum() } /// Publishes every object staged, durably, and logs the new records in diff --git a/apps/origin-src/src/sync.rs b/apps/origin-src/src/sync.rs new file mode 100644 index 00000000..72b2e124 --- /dev/null +++ b/apps/origin-src/src/sync.rs @@ -0,0 +1,396 @@ +//! Sync: sharing records with a [remote](crate::remote). +//! +//! - **Fetching** the records of changes compares them with the remote's, +//! by id, and fetches those missing, with the records they refer to, and +//! the records of the changes those belong to. +//! - Snapshots don't come with records: [`Sync::need`] fetches one when +//! something reads it, such as a checkout. A snapshot is marked while it's +//! fetched ([`Store::fetching`]), so one whose fetch was interrupted is +//! fetched again rather than taken for whole. +//! +//! Transfers are bounded: a fetch's answers stop at +//! [`Pack::LIMIT`](origin_shared::pack::Pack::LIMIT), with the rest asked +//! for again (see [`Part`]). + +use std::collections::{BTreeSet, HashMap, HashSet}; +use std::mem; + +use origin_platform::Native; +use origin_shared::api::{FetchRecords, FetchSnapshot, InventoryRequest}; +use origin_shared::object::DecodeError; +use origin_shared::pack::Part; +use origin_shared::{ + ChangeId, EncodedObject, ObjectId, ObjectKind, Principal, PrincipalName, Revision, TreeId, +}; + +use crate::annotations::Annotations; +use crate::remote::{Remote, RemoteError}; +use crate::service::Dependencies; +use crate::store::{Batch, Store, StoreError}; + +/// A store, and the remote it syncs with. +pub struct Sync<'a> { + store: &'a Store, + remote: &'a Remote, + /// This node, which flags the divergence fetched revisions reveal. + node: Principal, +} + +/// What fetching records did. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Fetched { + /// The revisions fetched. + pub revisions: usize, + /// The statements fetched. + pub statements: usize, +} + +impl<'a> Sync<'a> { + /// Syncs `store` with `remote`, as the node `node`. + pub fn new(store: &'a Store, remote: &'a Remote, node: PrincipalName) -> Self { + Self { + store, + remote, + node: Principal::Node(node), + } + } + + /// Fetches the records of `changes` the remote has and this node + /// doesn't: their revisions and the statements about them, with the + /// records they refer to, and then the records of the changes the + /// revisions fetched belong to, so every change this node learns of + /// comes whole. Flags the changes that diverged. + /// + /// # Errors + /// + /// Fails if the remote or the store fails. + pub fn fetch_changes(&self, changes: &[ChangeId]) -> Result { + let mut fetched = Fetched::default(); + let mut asked: HashSet = changes.iter().copied().collect(); + let mut next: Vec = asked.iter().copied().collect(); + let mut revised = BTreeSet::new(); + // Objects found stored stay until what refers to them is written. + let _held = self.store.hold_objects()?; + while !next.is_empty() { + let inventories = self.remote.inventory(&InventoryRequest { + changes: mem::take(&mut next), + })?; + let ids = inventories.iter().flat_map(|inventory| { + let revisions = inventory.revisions.iter().map(|&id| ObjectId::from(id)); + revisions.chain(inventory.statements.iter().map(|&id| id.into())) + }); + let held = self.store.batch(); + let records = self.closure(&held, ids, &HashSet::new())?; + held.commit()?; + for change in Self::revised(&records)? { + fetched.revisions += 1; + revised.insert(change); + if asked.insert(change) { + next.push(change); + } + } + fetched.statements += records + .iter() + .filter(|record| record.kind().ok() == Some(ObjectKind::Statement)) + .count(); + if !records.is_empty() { + self.store.write_all(&records)?; + } + } + if !revised.is_empty() { + let annotations = Annotations::open(self.store)?; + for change in revised { + annotations.flag_divergence(change, self.node.clone())?; + } + } + Ok(fetched) + } + + /// The change of each revision of `records`, one for each. + fn revised(records: &[EncodedObject]) -> Result, SyncError> { + let mut changes = Vec::new(); + for record in records { + if record.kind().ok() == Some(ObjectKind::Revision) { + let revision: Revision = + record.decode_as().map_err(|source| SyncError::Malformed { + id: record.id(), + source, + })?; + changes.push(revision.change); + } + } + Ok(changes) + } + + /// Fetches the records `ids` names that this node lacks, other than + /// those of `skip`, with the records they refer to, recursively: a + /// revision's base and dependencies, a statement's subject and the + /// statements it supersedes or promotes, but not their snapshots. Each + /// comes with the blob it carries. Those this node has are made durable + /// by `held`, which must commit before anything refers to them. + fn closure( + &self, + held: &Batch<'_, Native>, + ids: impl IntoIterator, + skip: &HashSet, + ) -> Result, SyncError> { + let mut seen = HashSet::new(); + let mut wanted = Vec::new(); + let mut want = |id: ObjectId, wanted: &mut Vec| { + if !skip.contains(&id) && !held.depend(id)? && seen.insert(id) { + wanted.push(id); + } + Ok::<_, StoreError>(()) + }; + for id in ids { + want(id, &mut wanted)?; + } + let mut objects = Vec::new(); + while !wanted.is_empty() { + let mut request = FetchRecords { + ids: mem::take(&mut wanted), + }; + while !request.ids.is_empty() { + let Part { pack, more } = self.remote.records(&request)?; + // A part that stops short holds the records up to the last + // it has: the rest come from asking again. + let rest = if more { + let position: HashMap = request + .ids + .iter() + .enumerate() + .map(|(position, &id)| (id, position)) + .collect(); + let last = pack + .objects + .iter() + .filter_map(|object| position.get(&object.id())) + .max(); + last.map_or_else(Vec::new, |&last| request.ids.split_off(last + 1)) + } else { + Vec::new() + }; + for object in pack.objects { + if matches!( + object.kind(), + Ok(ObjectKind::Revision | ObjectKind::Statement) + ) { + let decoded = object.decode().map_err(|source| SyncError::Malformed { + id: object.id(), + source, + })?; + for (id, _) in Dependencies::of(&decoded).records { + want(id, &mut wanted)?; + } + } + objects.push(object); + } + request.ids = rest; + } + } + Ok(objects) + } + + /// Fetches the trees and blobs of `snapshot`, unless the store holds it + /// whole, skipping what the snapshots `have`, which it holds whole, + /// hold at the same path. Returns whether it fetched. + /// + /// # Errors + /// + /// Fails if the remote doesn't have the snapshot, or the remote or the + /// store fails. + pub fn need(&self, snapshot: TreeId, have: &[TreeId]) -> Result { + if self.store.holds(snapshot)? { + return Ok(false); + } + let request = FetchSnapshot { + snapshot, + have: self.store.held_whole(have.iter().copied())?, + paths: Vec::new(), + skip: 0, + }; + self.fetch_parts(request, Some(snapshot))?; + Ok(true) + } + + /// Fetches `snapshot` whole again, whatever the store holds: what the + /// store lacks of a snapshot it has the root of, which reading it + /// found. + /// + /// # Errors + /// + /// Fails like [`Sync::need`]. + pub fn repair(&self, snapshot: TreeId) -> Result<(), SyncError> { + let request = FetchSnapshot { + snapshot, + have: Vec::new(), + paths: Vec::new(), + skip: 0, + }; + self.fetch_parts(request, Some(snapshot)) + } + + /// Fetches what `request` asks for, part after part, in one batch. With + /// `whole`, the snapshot it fetches whole, which is marked until the + /// batch is durable. + fn fetch_parts( + &self, + mut request: FetchSnapshot, + whole: Option, + ) -> Result<(), SyncError> { + // Objects found stored stay until the trees referring to them are. + let _held = self.store.hold_objects()?; + let batch = self.store.batch(); + let fetching = whole + .map(|snapshot| self.store.fetching(snapshot, &batch)) + .transpose()?; + loop { + let Part { pack, more } = self.remote.snapshot(&request)?; + batch.stage_all(&pack.objects)?; + if !more || pack.objects.is_empty() { + break; + } + request.skip += pack.objects.len() as u64; + } + batch.commit()?; + if let Some(fetching) = fetching { + fetching.done()?; + } + Ok(()) + } +} + +/// A failure to sync with a remote. +#[derive(Debug, thiserror::Error)] +pub enum SyncError { + /// The remote sent an object that doesn't decode. + #[error("the remote sent a malformed object {id}")] + Malformed { + /// The object. + id: ObjectId, + /// What is wrong. + source: DecodeError, + }, + /// The remote failed. + #[error(transparent)] + Remote(#[from] RemoteError), + /// Objects cannot be read or written. + #[error(transparent)] + Store(#[from] StoreError), +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use origin_platform::Native; + use origin_shared::pack::Pack; + use origin_shared::{NodeKey, RepoPath}; + + use super::*; + use crate::queue::tests::{Repo, ci_test}; + use crate::service::{Node, OriginService}; + use crate::tree::Snapshots; + use crate::tree::tests::build; + + const MAIN_RULES: &str = "[targets.main]\nauthority = \"node:queue\"\n"; + + /// A node's own repository, empty, syncing with the queue's repository + /// of `server` in-process. + struct Client { + _dir: tempfile::TempDir, + store: Store, + remote: Remote, + } + + impl Client { + fn new(server: &Repo) -> Self { + Self::answered_in_parts(server, Pack::LIMIT) + } + + /// A client of a server answering in parts of `limit` bytes. + fn answered_in_parts(server: &Repo, limit: usize) -> Self { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path().join(".origin"), Native::default()); + store.init().unwrap(); + let node = Node { + name: "queue".parse().unwrap(), + key: Arc::new(NodeKey::from_bytes(&[7; 32])), + }; + let service = OriginService::new(server.store.clone(), node).with_pack_limit(limit); + let remote = Remote::Local(Box::new(service)); + Self { + _dir: dir, + store, + remote, + } + } + + fn sync(&self) -> Sync<'_> { + Sync::new(&self.store, &self.remote, "laptop".parse().unwrap()) + } + } + + #[test] + fn fetches_the_records_of_changes() { + let server = Repo::new(MAIN_RULES); + let first = server.change_on_main(1, &[("a", "a")]); + let annotations = server.annotations(); + annotations.issue(&ci_test(first, "node:ci"), None).unwrap(); + let client = Client::new(&server); + + let fetched = client + .sync() + .fetch_changes(&[ChangeId::from_bytes([1; 16])]) + .unwrap(); + assert_eq!( + fetched, + Fetched { + revisions: 1, + statements: 1 + } + ); + assert!(client.store.contains(first.into()).unwrap()); + let again = client + .sync() + .fetch_changes(&[ChangeId::from_bytes([1; 16])]) + .unwrap(); + assert_eq!(again, Fetched::default()); + } + + #[test] + fn interrupted_snapshot_fetches_are_fetched_again() { + let server = Repo::new(MAIN_RULES); + let revision = server.change_on_main(1, &[("src/a", "a")]); + let client = Client::new(&server); + client + .sync() + .fetch_changes(&[ChangeId::from_bytes([1; 16])]) + .unwrap(); + let snapshot = client.store.get(revision).unwrap().snapshot; + let empty = build(&client.store, &[]); + + // A fetch cut short once the root was published, not what it holds. + let batch = client.store.batch(); + let fetching = client.store.fetching(snapshot, &batch).unwrap(); + batch + .stage_all(&[server.store.read(snapshot.into()).unwrap()]) + .unwrap(); + batch.commit().unwrap(); + drop(fetching); + assert!(!client.store.holds(snapshot).unwrap()); + assert!(client.sync().need(snapshot, &[]).unwrap(), "fetched again"); + assert!(client.store.holds(snapshot).unwrap()); + assert_eq!(client.store.diff(empty, snapshot).unwrap().len(), 1); + + // One that lacks a tree, unmarked, is repaired whole. + let src = Snapshots::new(&client.store) + .entry_at(snapshot, &RepoPath::new("src").unwrap()) + .unwrap() + .unwrap(); + client.store.remove(&[src.id]).unwrap(); + assert!(client.store.diff(empty, snapshot).is_err()); + client.sync().repair(snapshot).unwrap(); + assert_eq!(client.store.diff(empty, snapshot).unwrap().len(), 1); + } +} diff --git a/apps/origin-src/src/tree.rs b/apps/origin-src/src/tree.rs index 87699f55..7ea9d1f4 100644 --- a/apps/origin-src/src/tree.rs +++ b/apps/origin-src/src/tree.rs @@ -2,6 +2,9 @@ use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; +use std::fs::{self, File}; +use std::io; +use std::path::PathBuf; use origin_platform::Platform; use origin_shared::{ @@ -10,7 +13,7 @@ use origin_shared::{ }; use crate::conflict::{Conflicted, Conflicts}; -use crate::store::{Store, StoreError}; +use crate::store::{Batch, Store, StoreError}; /// A file that differs between two trees. #[derive(Clone, Debug, PartialEq, Eq)] @@ -433,6 +436,91 @@ impl Store

{ } } +/// A snapshot being fetched, marked durably in the store's `fetching/`, so +/// an interrupted fetch, which published trees before what they hold, is +/// never taken for a whole snapshot: see [`Store::holds`]. Dropping it +/// without [`Fetching::done`] leaves the mark, and fetching the snapshot +/// again completes it. +#[derive(Debug)] +pub struct Fetching { + path: PathBuf, +} + +impl Fetching { + /// Removes the mark, once everything fetched is durable. A crash that + /// loses the removal only fetches the snapshot again. + /// + /// # Errors + /// + /// Fails if the mark cannot be removed. + pub fn done(self) -> Result<(), StoreError> { + match fs::remove_file(&self.path) { + Err(error) if error.kind() != io::ErrorKind::NotFound => { + Err(StoreError::io(&self.path, error)) + } + _ => Ok(()), + } + } +} + +impl Store

{ + /// The directory marking the snapshots being fetched. + const FETCHING: &str = "fetching"; + + fn fetching_path(&self, snapshot: TreeId) -> PathBuf { + self.root().join(Self::FETCHING).join(snapshot.to_hex()) + } + + /// Whether the store holds `snapshot` whole: its root, and no fetch of + /// it that didn't finish (see [`Fetching`]). + /// + /// # Errors + /// + /// Fails like [`Store::contains`]. + pub fn holds(&self, snapshot: TreeId) -> Result { + Ok(self.contains(snapshot.into())? && !self.fetching_path(snapshot).exists()) + } + + /// Those of `snapshots` the store [holds](Store::holds) whole, in + /// order. + /// + /// # Errors + /// + /// Fails like [`Store::contains`]. + pub fn held_whole( + &self, + snapshots: impl IntoIterator, + ) -> Result, StoreError> { + let mut held = Vec::new(); + for snapshot in snapshots { + if self.holds(snapshot)? { + held.push(snapshot); + } + } + Ok(held) + } + + /// Marks `snapshot` as being fetched, durably before anything `batch` + /// stages is published, at no sync of its own: the batch syncs the mark + /// with what it stages. + /// + /// # Errors + /// + /// Fails if the mark, or the directory holding it, cannot be created. + pub fn fetching(&self, snapshot: TreeId, batch: &Batch<'_, P>) -> Result { + let dir = self.root().join(Self::FETCHING); + if !dir.is_dir() { + fs::create_dir_all(&dir).map_err(|source| StoreError::io(&dir, source))?; + self.sync_dir(self.root())?; + } + let path = dir.join(snapshot.to_hex()); + File::create(&path).map_err(|source| StoreError::io(&path, source))?; + batch.sync_first(&path); + batch.sync_first(dir); + Ok(Fetching { path }) + } +} + /// An object of a snapshot, and where it is: [`Store::added`] lists them. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Placed {