You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opendal.apache.org by ps...@apache.org on 2026/08/27 09:53:35 UTC
(opendal-ofs) branch managed-v0/sync-restore created (now 6197b56)
This is an automated email from the ASF dual-hosted git repository.
PsiACE pushed a change to branch managed-v0/sync-restore
in repository https://gitbox.apache.org/repos/asf/opendal-ofs.git
at 6197b56 feat(sync): restore managed replicas
This branch includes the following new commits:
new da30877 feat(sync): add replica request and state contracts
new 6197b56 feat(sync): restore managed replicas
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(opendal-ofs) 02/02: feat(sync): restore managed replicas
Posted by ps...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
PsiACE pushed a commit to branch managed-v0/sync-restore
in repository https://gitbox.apache.org/repos/asf/opendal-ofs.git
commit 6197b56b40a77101409b7dd7d0e31a517b8ea5f8
Author: PsiACE <ps...@apache.org>
AuthorDate: Thu Aug 27 17:30:45 2026 +0800
feat(sync): restore managed replicas
---
Cargo.lock | 1 +
crates/core/Cargo.toml | 3 +-
crates/core/src/data/file.rs | 8 +
crates/core/src/data/mod.rs | 1 +
crates/core/src/error.rs | 4 +
crates/core/src/sync/engine.rs | 206 +++++++++++++++
crates/core/src/sync/install.rs | 257 +++++++++++++++++++
crates/core/src/sync/mod.rs | 5 +
crates/core/src/sync/replica/fs.rs | 383 ++++++++++++++++++++++++++++
crates/core/src/sync/replica/mod.rs | 1 +
crates/core/src/sync/replica/state_store.rs | 78 +++++-
crates/core/src/sync/segment_install.rs | 182 +++++++++++++
crates/core/src/sync/state.rs | 49 ++++
crates/core/src/sync/transfer.rs | 70 +++++
crates/core/src/volume/open.rs | 55 +++-
15 files changed, 1298 insertions(+), 5 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 4c3e53d..356f95b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1107,6 +1107,7 @@ dependencies = [
"tokio",
"tokio-util",
"uuid",
+ "walkdir",
]
[[package]]
diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml
index 4644867..727a6c1 100644
--- a/crates/core/Cargo.toml
+++ b/crates/core/Cargo.toml
@@ -33,9 +33,10 @@ ofs-managed-format = { path = "../managed-format" }
opendal = "0.57.0"
serde = { version = "1", features = ["derive"] }
tempfile = "3"
-tokio = { version = "1", features = ["io-util"] }
+tokio = { version = "1", features = ["fs", "io-util"] }
tokio-util.workspace = true
uuid = { version = "1", features = ["v4"] }
+walkdir = "2.5"
[dev-dependencies]
opendal = { version = "0.57.0", features = ["services-fs"] }
diff --git a/crates/core/src/data/file.rs b/crates/core/src/data/file.rs
index 0317b29..88b6a95 100644
--- a/crates/core/src/data/file.rs
+++ b/crates/core/src/data/file.rs
@@ -164,6 +164,10 @@ impl<T> RangeBatch<T> {
Ok(())
}
+ pub(crate) const fn locator(&self) -> ObjectLocator {
+ self.locator
+ }
+
pub(crate) fn stream_range(&self) -> Option<Range<u64>> {
self.contiguous.then(|| {
self.items
@@ -174,6 +178,10 @@ impl<T> RangeBatch<T> {
})
}
+ pub(crate) fn into_items(self) -> Vec<RangeBatchItem<T>> {
+ self.items
+ }
+
pub(crate) async fn read(
self,
operator: &Operator,
diff --git a/crates/core/src/data/mod.rs b/crates/core/src/data/mod.rs
index 15d540f..9488c15 100644
--- a/crates/core/src/data/mod.rs
+++ b/crates/core/src/data/mod.rs
@@ -28,6 +28,7 @@ pub(crate) mod write;
pub use codec::{ContentHasher, ExtentCodec, IdentityCodec};
pub use extent::{ExtentRunWriter, compact_file_extents};
+pub(crate) use file::{RangeBatch, RangeBatcher};
pub use file::{ReusableFile, ReusableFileSource, logical_range, restore_file};
pub use lookup::ContentLookup;
pub use partition::{FilePartitioner, WholePartitioner};
diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs
index 0d6cbce..9aa247c 100644
--- a/crates/core/src/error.rs
+++ b/crates/core/src/error.rs
@@ -75,6 +75,10 @@ impl Error {
Self::new(ErrorKind::Conflict, operation, message)
}
+ pub(crate) fn unsupported(operation: &'static str, message: impl Into<String>) -> Self {
+ Self::new(ErrorKind::Unsupported, operation, message)
+ }
+
pub(crate) fn corrupt(operation: &'static str, message: impl Into<String>) -> Self {
Self::new(ErrorKind::Corrupt, operation, message)
}
diff --git a/crates/core/src/sync/engine.rs b/crates/core/src/sync/engine.rs
new file mode 100644
index 0000000..c33e24b
--- /dev/null
+++ b/crates/core/src/sync/engine.rs
@@ -0,0 +1,206 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::path::{Path, PathBuf};
+
+use crate::Error;
+use crate::format::{FileExtentMap, NamespaceRevision};
+use crate::volume::{AccessFamily, CoreAccess, ManagedVolume, Namespace};
+use crate::work::WorkContext;
+
+use super::ReplicaState;
+use super::install::install;
+use super::replica::state_store::ReplicaStateFile;
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct SyncOutcome {
+ pub conflict_paths: Vec<String>,
+ pub published: bool,
+ pub sequence: u64,
+}
+
+impl SyncOutcome {
+ fn restored(revision: NamespaceRevision, published: bool) -> Self {
+ Self {
+ conflict_paths: Vec::new(),
+ published,
+ sequence: revision.cursor().sequence(),
+ }
+ }
+}
+
+pub struct SyncEngine<A: AccessFamily = CoreAccess> {
+ volume: ManagedVolume<A>,
+}
+
+impl<A: AccessFamily> SyncEngine<A> {
+ pub const fn new(volume: ManagedVolume<A>) -> Self {
+ Self { volume }
+ }
+
+ /// Attach an empty local directory to a Managed volume and materialize its
+ /// current namespace. Interrupted installations resume from durable state.
+ pub async fn sync(
+ &self,
+ root: &Path,
+ state_path: &Path,
+ resolve_paths: &[String],
+ ) -> Result<SyncOutcome, Error> {
+ if !resolve_paths.is_empty() {
+ return Err(Error::unsupported(
+ "restore replica",
+ "conflict resolution requires replica convergence",
+ ));
+ }
+ let root = canonical_directory(root)?;
+ let workspace_directory = state_path
+ .parent()
+ .filter(|directory| !directory.as_os_str().is_empty())
+ .unwrap_or_else(|| Path::new("."));
+ let workspace = WorkContext::create_in(self.volume.work_budget(), workspace_directory)?;
+ let (mut state_file, stored) = ReplicaStateFile::open(state_path)?;
+ validate_binding(stored.as_ref(), &root, &self.volume)?;
+
+ let requested = stored.as_ref().map(ReplicaState::resume_revision);
+ let (observed, loaded) = self
+ .volume
+ .observe_with_base_in(&workspace, requested)
+ .await?;
+ if let Some(state) = stored.as_ref()
+ && (state.authority_id() != observed.authority_id()
+ || state.authority_name() != self.volume.authority_name())
+ {
+ return Err(Error::invalid(
+ "restore replica",
+ "replica state belongs to a different namespace authority",
+ ));
+ }
+
+ if let Some(mut state) = stored {
+ let Some((target, published)) = state.installation() else {
+ return Err(Error::unsupported(
+ "synchronize replica",
+ "an attached replica requires convergence",
+ ));
+ };
+ let namespace = if observed.revision() == target {
+ &observed.namespace
+ } else {
+ loaded.as_ref().unwrap_or(&observed.namespace)
+ };
+ return self
+ .install_and_advance(
+ &workspace,
+ &root,
+ &mut state_file,
+ &mut state,
+ namespace,
+ if observed.revision() == target {
+ target
+ } else {
+ observed.revision()
+ },
+ published,
+ )
+ .await;
+ }
+
+ require_empty(&root)?;
+ let mut state = ReplicaState::new(
+ root.clone(),
+ self.volume.id(),
+ observed.authority_id(),
+ self.volume.authority_name().to_owned(),
+ observed.revision(),
+ );
+ self.install_and_advance(
+ &workspace,
+ &root,
+ &mut state_file,
+ &mut state,
+ &observed.namespace,
+ observed.revision(),
+ false,
+ )
+ .await
+ }
+
+ async fn install_and_advance(
+ &self,
+ workspace: &WorkContext,
+ root: &Path,
+ state_file: &mut ReplicaStateFile,
+ state: &mut ReplicaState,
+ namespace: &Namespace<FileExtentMap>,
+ revision: NamespaceRevision,
+ published: bool,
+ ) -> Result<SyncOutcome, Error> {
+ state.begin_install(revision, published);
+ state_file.persist(state)?;
+ install(workspace, root, namespace, &self.volume, None).await?;
+ state.advance(revision);
+ state_file.persist(state)?;
+ Ok(SyncOutcome::restored(revision, published))
+ }
+}
+
+fn canonical_directory(root: &Path) -> Result<PathBuf, Error> {
+ let root = std::fs::canonicalize(root)
+ .map_err(|error| Error::from_io("open replica directory", Some(root), error))?;
+ if !root.is_dir() {
+ return Err(Error::invalid(
+ "restore replica",
+ "replica path is not a directory",
+ ));
+ }
+ Ok(root)
+}
+
+fn validate_binding<A: AccessFamily>(
+ state: Option<&ReplicaState>,
+ root: &Path,
+ volume: &ManagedVolume<A>,
+) -> Result<(), Error> {
+ let Some(state) = state else {
+ return Ok(());
+ };
+ if state.root() != root {
+ return Err(Error::invalid(
+ "restore replica",
+ "replica state belongs to a different local directory",
+ ));
+ }
+ if state.volume_id() != volume.id() {
+ return Err(Error::invalid(
+ "restore replica",
+ "replica state belongs to a different volume",
+ ));
+ }
+ Ok(())
+}
+
+fn require_empty(root: &Path) -> Result<(), Error> {
+ let mut entries = std::fs::read_dir(root)
+ .map_err(|error| Error::from_io("read replica directory", Some(root), error))?;
+ if entries.next().is_some() {
+ return Err(Error::unsupported(
+ "restore replica",
+ "initial publication requires local observation",
+ ));
+ }
+ Ok(())
+}
diff --git a/crates/core/src/sync/install.rs b/crates/core/src/sync/install.rs
new file mode 100644
index 0000000..a43b79f
--- /dev/null
+++ b/crates/core/src/sync/install.rs
@@ -0,0 +1,257 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::cmp::Reverse;
+use std::path::Path;
+
+use crate::Error;
+use crate::filesystem::NamespaceValue;
+use crate::format::FileExtentMap;
+use crate::volume::AccessFamily;
+use crate::volume::{ManagedVolume, Namespace, NamespaceReader};
+use crate::work::{Spool, SpoolReader, WorkContext};
+use futures::TryStreamExt as _;
+use serde::{Deserialize, Serialize};
+
+use super::replica::fs::{DirectoryDurability, StoredPath};
+use super::segment_install::{self, Installation as SegmentInstallation};
+use super::transfer::materialize_file;
+
+pub(crate) async fn install<A: AccessFamily>(
+ workspace: &WorkContext,
+ root: &Path,
+ target: &Namespace<FileExtentMap>,
+ volume: &ManagedVolume<A>,
+ current: Option<&Namespace<FileExtentMap>>,
+) -> Result<(), Error> {
+ let verify_existing = current.is_none();
+ let transfer_concurrency = volume.stream_concurrency();
+ let removals = installation_removals(root, current, target, workspace)?;
+ let mut durability = DirectoryDurability::create(workspace)?;
+ let removals = crate::work::sort(workspace, &removals, |path| Reverse(path.clone()))?;
+ let mut removals = removals.reader()?;
+ while let Some(path) = removals.next()? {
+ let destination = root.join(path.to_path_buf());
+ crate::sync::replica::fs::remove_path(&destination)?;
+ durability.changed_parent(&destination)?;
+ }
+
+ let mut file_installations = workspace.writer("file-installations")?;
+ let mut grouped = workspace.writer("grouped-segment-installations")?;
+ let mut current_reader = current.map(Namespace::reader).transpose()?;
+ let mut current_record = current_reader
+ .as_mut()
+ .map(|reader| reader.next())
+ .transpose()?
+ .flatten();
+ let mut target_reader = target.reader()?;
+ while let Some(record) = target_reader.next()? {
+ while current_record
+ .as_ref()
+ .is_some_and(|current| current.path < record.path)
+ {
+ current_record = current_reader
+ .as_mut()
+ .expect("current record requires a reader")
+ .next()?;
+ }
+ let matching_current = current_record
+ .as_ref()
+ .filter(|current| current.path == record.path);
+ let Some(node) = record.value else {
+ continue;
+ };
+ let destination = root.join(&record.path);
+ let NamespaceValue::RegularFile {
+ version,
+ content,
+ data,
+ } = node.value
+ else {
+ if record.path.is_empty() {
+ continue;
+ }
+ match crate::sync::replica::fs::path_metadata(&destination)? {
+ Some(metadata) if metadata.is_dir() => {}
+ Some(_) => {
+ crate::sync::replica::fs::remove_path(&destination)?;
+ durability.changed_parent(&destination)?;
+ crate::sync::replica::fs::create_directory(&destination, &mut durability)?;
+ }
+ None => {
+ crate::sync::replica::fs::create_directory(&destination, &mut durability)?;
+ }
+ }
+ continue;
+ };
+ if !verify_existing
+ && matching_current.is_some_and(|current| {
+ current.value.as_ref().is_some_and(|current| {
+ current.attributes == node.attributes
+ && current
+ .file()
+ .is_some_and(|(current_version, _, _)| current_version == version)
+ })
+ })
+ {
+ continue;
+ }
+ let executable = node.attributes.executable;
+ let reusable = matching_current.and_then(|current| {
+ current
+ .value
+ .as_ref()
+ .and_then(|current| current.file().map(|(_, _, data)| data.clone()))
+ });
+ if let Some(mapping) = data.inline_file_extent() {
+ if mapping.logical_range.offset != 0
+ || mapping.extent_offset != 0
+ || mapping.logical_range.length != content.length()
+ || mapping.extent.content() != content
+ {
+ return Err(Error::corrupt(
+ "install Managed file",
+ "inline extent does not match its file content",
+ ));
+ }
+ grouped.write(&SegmentInstallation {
+ extent: mapping.extent,
+ destination: StoredPath::from_path(&destination)?,
+ fingerprint: content,
+ executable,
+ })?;
+ } else {
+ file_installations.write(&FileInstallation {
+ destination: StoredPath::from_path(&destination)?,
+ fingerprint: content,
+ content: data.clone(),
+ reusable,
+ executable,
+ })?;
+ }
+ }
+ let installations = file_installations
+ .finish()?
+ .stream()?
+ .map_ok(|file| install_file(volume, file, verify_existing))
+ .try_buffer_unordered(transfer_concurrency);
+ futures::pin_mut!(installations);
+ while let Some(installation) = installations.try_next().await? {
+ if let Some(destination) = installation {
+ durability.changed_parent(&destination)?;
+ }
+ }
+
+ segment_install::install(
+ volume,
+ workspace,
+ &grouped.finish()?,
+ transfer_concurrency,
+ verify_existing,
+ &mut durability,
+ )
+ .await?;
+ durability.sync(workspace)?;
+ Ok(())
+}
+
+#[derive(Deserialize, Serialize)]
+struct FileInstallation {
+ destination: StoredPath,
+ fingerprint: crate::filesystem::ContentRef,
+ content: FileExtentMap,
+ reusable: Option<FileExtentMap>,
+ executable: bool,
+}
+
+async fn install_file<A: AccessFamily>(
+ volume: &ManagedVolume<A>,
+ file: FileInstallation,
+ verify_existing: bool,
+) -> Result<Option<std::path::PathBuf>, Error> {
+ let destination = file.destination.to_path_buf();
+ if verify_existing
+ && crate::sync::replica::fs::file_matches(&destination, file.fingerprint, file.executable)
+ .await?
+ {
+ return Ok(None);
+ }
+ materialize_file(
+ volume,
+ (file.fingerprint, file.content),
+ file.reusable,
+ &destination,
+ file.executable,
+ )
+ .await?;
+ Ok(Some(destination))
+}
+
+fn installation_removals(
+ root: &Path,
+ current: Option<&Namespace<FileExtentMap>>,
+ target: &Namespace<FileExtentMap>,
+ workspace: &WorkContext,
+) -> Result<Spool<StoredPath>, Error> {
+ let mut removed = workspace.writer("removed")?;
+ let current = match current {
+ Some(current) => CurrentPaths::Namespace(current.reader()?),
+ None => {
+ let mut actual = workspace.writer("actual-paths")?;
+ crate::sync::replica::fs::scan_paths(root, &mut actual, &mut removed)?;
+ CurrentPaths::Filesystem(
+ crate::work::sort(workspace, &actual.finish()?, String::clone)?.reader()?,
+ )
+ }
+ };
+ let mut current = current;
+ let mut target = target.reader()?;
+ let mut left = current.next()?;
+ let mut right = target.next()?;
+ while let Some(record) = left.as_ref() {
+ match right.as_ref().map(|target| record.cmp(&target.path)) {
+ None | Some(std::cmp::Ordering::Less) => {
+ if !record.is_empty() {
+ removed.write(&StoredPath::from_path(Path::new(record))?)?;
+ }
+ left = current.next()?;
+ }
+ Some(std::cmp::Ordering::Equal) => {
+ left = current.next()?;
+ right = target.next()?;
+ }
+ Some(std::cmp::Ordering::Greater) => {
+ right = target.next()?;
+ }
+ }
+ }
+ removed.finish()
+}
+
+enum CurrentPaths {
+ Namespace(NamespaceReader<FileExtentMap>),
+ Filesystem(SpoolReader<String>),
+}
+
+impl CurrentPaths {
+ fn next(&mut self) -> Result<Option<String>, Error> {
+ match self {
+ Self::Namespace(reader) => Ok(reader.next()?.map(|record| record.path)),
+ Self::Filesystem(reader) => reader.next(),
+ }
+ }
+}
diff --git a/crates/core/src/sync/mod.rs b/crates/core/src/sync/mod.rs
index efddaab..13a7274 100644
--- a/crates/core/src/sync/mod.rs
+++ b/crates/core/src/sync/mod.rs
@@ -17,10 +17,15 @@
//! Public request and durable replica-state contracts for Managed Sync.
+mod engine;
mod input;
+mod install;
mod replica;
+mod segment_install;
mod state;
+mod transfer;
+pub use engine::{SyncEngine, SyncOutcome};
pub use input::{
ConflictResolution, FileChangeSet, FileChangeSetEntry, LocalChangeHint, SyncRequest,
};
diff --git a/crates/core/src/sync/replica/fs.rs b/crates/core/src/sync/replica/fs.rs
new file mode 100644
index 0000000..9449432
--- /dev/null
+++ b/crates/core/src/sync/replica/fs.rs
@@ -0,0 +1,383 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Native local-filesystem operations used while installing a namespace.
+
+use std::cmp::Reverse;
+#[cfg(any(unix, windows))]
+use std::ffi::OsString;
+use std::fs::File;
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+use tokio::fs::File as AsyncFile;
+use tokio::io::BufReader;
+
+use crate::Error;
+use crate::data::ContentHasher;
+use crate::filesystem::ContentRef;
+use crate::work::{OrderedRead as _, Unique};
+use crate::work::{SpoolWriter, WorkContext};
+
+const IO_BUFFER_BYTES: usize = 256 * 1024;
+
+pub(crate) async fn file_matches(
+ path: &Path,
+ expected: ContentRef,
+ executable: bool,
+) -> Result<bool, Error> {
+ let metadata = match std::fs::symlink_metadata(path) {
+ Ok(metadata) => metadata,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
+ Err(error) => return Err(Error::from_io("inspect replica file", Some(path), error)),
+ };
+ if !supported_regular_file(&metadata) || is_executable(&metadata) != executable {
+ return Ok(false);
+ }
+ if metadata.len() != expected.length() {
+ return Ok(false);
+ }
+ Ok(hash_file(path).await? == expected)
+}
+
+async fn hash_file(path: &Path) -> Result<ContentRef, Error> {
+ let file = AsyncFile::open(path)
+ .await
+ .map_err(|error| Error::from_io("verify local file", Some(path), error))?;
+ let mut content = ContentHasher::default();
+ {
+ let reader = tokio_util::io::InspectReader::new(file, |bytes| content.observe(bytes));
+ let mut reader = BufReader::with_capacity(IO_BUFFER_BYTES, reader);
+ tokio::io::copy_buf(&mut reader, &mut tokio::io::sink())
+ .await
+ .map_err(|error| Error::from_io("verify local file", Some(path), error))?;
+ }
+ content
+ .complete_content()
+ .ok_or_else(|| Error::conflict("verify local file", "local file was not read completely"))
+}
+
+pub(crate) fn entries(root: &Path) -> impl Iterator<Item = Result<walkdir::DirEntry, Error>> + '_ {
+ walkdir::WalkDir::new(root)
+ .min_depth(1)
+ .follow_links(false)
+ .into_iter()
+ .map(|entry| entry.map_err(|error| walk_error("walk replica directory", error)))
+}
+
+fn walk_error(operation: &'static str, error: walkdir::Error) -> Error {
+ let path = error.path().map(Path::to_path_buf);
+ let source = error
+ .into_io_error()
+ .unwrap_or_else(|| std::io::Error::other("directory traversal failed"));
+ Error::from_io(operation, path.as_deref(), source)
+}
+
+/// One same-directory staging file committed by atomic rename.
+struct StagedFile {
+ destination: PathBuf,
+ temporary: tempfile::TempPath,
+ file: Option<AsyncFile>,
+}
+
+impl StagedFile {
+ pub(crate) async fn create(destination: &Path) -> Result<Self, Error> {
+ if path_metadata(destination)?.is_some_and(|metadata| metadata.is_dir()) {
+ remove_replaced_directory(destination)?;
+ }
+ let parent = destination.parent().unwrap_or_else(|| Path::new("."));
+ tokio::fs::create_dir_all(parent)
+ .await
+ .map_err(|error| Error::from_io("create replica directory", Some(parent), error))?;
+ let staging = tempfile::NamedTempFile::new_in(parent)
+ .map_err(|error| Error::from_io("create replica staging file", Some(parent), error))?;
+ let (file, temporary) = staging.into_parts();
+ Ok(Self {
+ destination: destination.to_owned(),
+ temporary,
+ file: Some(AsyncFile::from_std(file)),
+ })
+ }
+
+ async fn commit(mut self, executable: bool) -> Result<(), Error> {
+ drop(self.file.take());
+ tokio::fs::rename(&self.temporary, &self.destination)
+ .await
+ .map_err(|error| {
+ Error::from_io("install replica file", Some(&self.destination), error)
+ })?;
+ if executable {
+ make_executable(&self.destination)?;
+ }
+ Ok(())
+ }
+}
+
+pub(crate) async fn install_file(
+ destination: &Path,
+ executable: bool,
+ write: impl AsyncFnOnce(&mut AsyncFile) -> Result<(), Error>,
+) -> Result<(), Error> {
+ let mut staging = StagedFile::create(destination).await?;
+ write(staging.file.as_mut().expect("staging file is open")).await?;
+ staging.commit(executable).await
+}
+
+pub(crate) fn scan_paths(
+ root: &Path,
+ actual: &mut SpoolWriter<String>,
+ removed: &mut SpoolWriter<StoredPath>,
+) -> Result<(), Error> {
+ for child in entries(root) {
+ let child = child?;
+ let path = child.path();
+ let relative = path
+ .strip_prefix(root)
+ .expect("walked installation path is below its root");
+ match portable_replica_path(relative) {
+ Some(path) => {
+ actual.write(&path)?;
+ }
+ None => {
+ removed.write(&StoredPath::from_path(relative)?)?;
+ }
+ }
+ }
+ Ok(())
+}
+
+fn portable_replica_path(path: &Path) -> Option<String> {
+ let path = path.to_str()?;
+ #[cfg(windows)]
+ let path = path.replace('\\', "/");
+ Some(path.to_owned())
+}
+
+pub(crate) fn create_directory(
+ path: &Path,
+ durability: &mut DirectoryDurability,
+) -> Result<(), Error> {
+ let mut missing = Vec::new();
+ let mut candidate = path;
+ while !candidate.exists() {
+ missing.push(candidate.to_owned());
+ let Some(parent) = candidate.parent() else {
+ break;
+ };
+ candidate = parent;
+ }
+ std::fs::create_dir_all(path)
+ .map_err(|error| Error::from_io("create replica directory", Some(path), error))?;
+ for directory in missing {
+ durability.record(&directory)?;
+ durability.changed_parent(&directory)?;
+ }
+ Ok(())
+}
+
+pub(crate) struct DirectoryDurability {
+ directories: SpoolWriter<StoredPath>,
+}
+
+impl DirectoryDurability {
+ pub(crate) fn create(workspace: &WorkContext) -> Result<Self, Error> {
+ Ok(Self {
+ directories: workspace.writer("durability")?,
+ })
+ }
+
+ fn record(&mut self, path: &Path) -> Result<(), Error> {
+ self.directories.write(&StoredPath::from_path(path)?)?;
+ Ok(())
+ }
+
+ pub(crate) fn changed_parent(&mut self, path: &Path) -> Result<(), Error> {
+ if let Some(parent) = path.parent() {
+ self.record(parent)?;
+ }
+ Ok(())
+ }
+
+ pub(crate) fn sync(self, workspace: &WorkContext) -> Result<(), Error> {
+ let directories = crate::work::sort(workspace, &self.directories.finish()?, |path| {
+ Reverse(path.clone())
+ })?;
+ let mut directories = Unique::new(directories.reader()?, Clone::clone);
+ while let Some(directory) = directories.next()? {
+ let directory = directory.to_path_buf();
+ if path_metadata(&directory)?.is_none_or(|metadata| !metadata.is_dir()) {
+ continue;
+ }
+ File::open(&directory)
+ .and_then(|directory| directory.sync_all())
+ .map_err(|error| {
+ Error::from_io("persist replica directory", Some(&directory), error)
+ })?;
+ }
+ Ok(())
+ }
+}
+
+pub(crate) fn remove_path(path: &Path) -> Result<(), Error> {
+ let Some(metadata) = path_metadata(path)? else {
+ return Ok(());
+ };
+ if metadata.is_dir() {
+ std::fs::remove_dir_all(path)
+ .map_err(|error| Error::from_io("remove replica directory", Some(path), error))
+ } else {
+ std::fs::remove_file(path)
+ .map_err(|error| Error::from_io("remove replica file", Some(path), error))
+ }
+}
+
+pub(crate) fn remove_replaced_directory(path: &Path) -> Result<(), Error> {
+ std::fs::remove_dir_all(path)
+ .map_err(|error| Error::from_io("replace replica directory", Some(path), error))
+}
+
+pub(crate) fn path_metadata(path: &Path) -> Result<Option<std::fs::Metadata>, Error> {
+ match std::fs::symlink_metadata(path) {
+ Ok(metadata) => Ok(Some(metadata)),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(error) => Err(Error::from_io("inspect replica path", Some(path), error)),
+ }
+}
+
+#[cfg(unix)]
+fn supported_regular_file(metadata: &std::fs::Metadata) -> bool {
+ use std::os::unix::fs::MetadataExt as _;
+
+ metadata.is_file() && metadata.nlink() == 1
+}
+
+#[cfg(not(unix))]
+fn supported_regular_file(metadata: &std::fs::Metadata) -> bool {
+ metadata.is_file()
+}
+
+#[cfg(unix)]
+fn is_executable(metadata: &std::fs::Metadata) -> bool {
+ use std::os::unix::fs::PermissionsExt as _;
+
+ metadata.permissions().mode() & 0o111 != 0
+}
+
+#[cfg(not(unix))]
+const fn is_executable(_metadata: &std::fs::Metadata) -> bool {
+ false
+}
+
+#[cfg(unix)]
+pub(crate) fn make_executable(path: &Path) -> Result<(), Error> {
+ use std::os::unix::fs::PermissionsExt as _;
+
+ let mut permissions = std::fs::metadata(path)
+ .map_err(|error| Error::from_io("read replica permissions", Some(path), error))?
+ .permissions();
+ permissions.set_mode(permissions.mode() | 0o111);
+ std::fs::set_permissions(path, permissions)
+ .map_err(|error| Error::from_io("write replica permissions", Some(path), error))
+}
+
+#[cfg(not(unix))]
+pub(crate) fn make_executable(_path: &Path) -> Result<(), Error> {
+ Err(Error::unsupported(
+ "install replica",
+ "Managed Sync executable attributes are not implemented on this platform",
+ ))
+}
+
+#[cfg(unix)]
+#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
+pub(crate) struct StoredPath(Vec<u8>);
+
+#[cfg(unix)]
+impl StoredPath {
+ pub(crate) fn from_path(path: &Path) -> Result<Self, Error> {
+ use std::os::unix::ffi::OsStrExt as _;
+
+ Ok(Self(path.as_os_str().as_bytes().to_vec()))
+ }
+
+ pub(crate) fn to_path_buf(&self) -> PathBuf {
+ use std::os::unix::ffi::OsStringExt as _;
+
+ PathBuf::from(OsString::from_vec(self.0.clone()))
+ }
+
+ pub(crate) const fn memory_bytes(&self) -> usize {
+ self.0.len()
+ }
+}
+
+#[cfg(windows)]
+#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
+pub(crate) struct StoredPath(Vec<u16>);
+
+#[cfg(windows)]
+impl StoredPath {
+ pub(crate) fn from_path(path: &Path) -> Result<Self, Error> {
+ use std::os::windows::ffi::OsStrExt as _;
+
+ Ok(Self(
+ path.as_os_str()
+ .encode_wide()
+ .map(|unit| {
+ if unit == b'\\' as u16 {
+ b'/' as u16
+ } else {
+ unit
+ }
+ })
+ .collect(),
+ ))
+ }
+
+ pub(crate) fn to_path_buf(&self) -> PathBuf {
+ use std::os::windows::ffi::OsStringExt as _;
+
+ PathBuf::from(OsString::from_wide(&self.0))
+ }
+
+ pub(crate) const fn memory_bytes(&self) -> usize {
+ self.0.len().saturating_mul(std::mem::size_of::<u16>())
+ }
+}
+
+#[cfg(not(any(unix, windows)))]
+#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
+pub(crate) struct StoredPath(String);
+
+#[cfg(not(any(unix, windows)))]
+impl StoredPath {
+ pub(crate) fn from_path(path: &Path) -> Result<Self, Error> {
+ path.to_str()
+ .map(|path| Self(path.to_owned()))
+ .ok_or_else(|| {
+ Error::unsupported("record replica path", "platform path is not Unicode")
+ })
+ }
+
+ pub(crate) fn to_path_buf(&self) -> PathBuf {
+ PathBuf::from(&self.0)
+ }
+
+ pub(crate) const fn memory_bytes(&self) -> usize {
+ self.0.len()
+ }
+}
diff --git a/crates/core/src/sync/replica/mod.rs b/crates/core/src/sync/replica/mod.rs
index 22954df..3219e94 100644
--- a/crates/core/src/sync/replica/mod.rs
+++ b/crates/core/src/sync/replica/mod.rs
@@ -15,4 +15,5 @@
// specific language governing permissions and limitations
// under the License.
+pub(crate) mod fs;
pub(super) mod state_store;
diff --git a/crates/core/src/sync/replica/state_store.rs b/crates/core/src/sync/replica/state_store.rs
index bc070e4..71dfe78 100644
--- a/crates/core/src/sync/replica/state_store.rs
+++ b/crates/core/src/sync/replica/state_store.rs
@@ -17,8 +17,9 @@
//! Atomic persistence for the lightweight replica recovery record.
-use std::fs;
-use std::path::Path;
+use std::fs::{self, File};
+use std::io::Write as _;
+use std::path::{Path, PathBuf};
use crate::Error;
use crate::format::RecordCodec;
@@ -27,6 +28,30 @@ use crate::sync::state::ReplicaState;
const STATE_RECORD: RecordCodec = RecordCodec::new(*b"OFSSTA00", 16 * 1024);
+pub(crate) struct ReplicaStateFile {
+ path: PathBuf,
+ exists: bool,
+}
+
+impl ReplicaStateFile {
+ pub(crate) fn open(path: &Path) -> Result<(Self, Option<ReplicaState>), Error> {
+ let state = load(path)?;
+ Ok((
+ Self {
+ path: path.to_owned(),
+ exists: state.is_some(),
+ },
+ state,
+ ))
+ }
+
+ pub(crate) fn persist(&mut self, state: &ReplicaState) -> Result<(), Error> {
+ write(state, &self.path, self.exists)?;
+ self.exists = true;
+ Ok(())
+ }
+}
+
pub(crate) fn load(path: &Path) -> Result<Option<ReplicaState>, Error> {
let bytes = match fs::read(path) {
Ok(bytes) => bytes,
@@ -37,3 +62,52 @@ pub(crate) fn load(path: &Path) -> Result<Option<ReplicaState>, Error> {
state.validate()?;
Ok(Some(state))
}
+
+fn write(state: &ReplicaState, path: &Path, replace: bool) -> Result<(), Error> {
+ state.validate()?;
+ let directory = path
+ .parent()
+ .filter(|parent| !parent.as_os_str().is_empty())
+ .unwrap_or_else(|| Path::new("."));
+ fs::create_dir_all(directory).map_err(|error| {
+ Error::from_io("create replica state directory", Some(directory), error)
+ })?;
+ let bytes = STATE_RECORD.encode(state)?;
+ let mut temporary = tempfile::NamedTempFile::new_in(directory)
+ .map_err(|error| Error::from_io("create replica state", Some(directory), error))?;
+ temporary
+ .write_all(&bytes)
+ .and_then(|()| temporary.as_file().sync_all())
+ .map_err(|error| Error::from_io("persist replica state", Some(path), error))?;
+ let installed = if replace {
+ temporary.persist(path)
+ } else {
+ temporary.persist_noclobber(path)
+ };
+ installed.map_err(|error| {
+ if error.error.kind() == std::io::ErrorKind::AlreadyExists {
+ Error::invalid(
+ "synchronize replica",
+ format!(
+ "cannot attach with an existing replica state: {}",
+ path.display()
+ ),
+ )
+ } else {
+ Error::from_io("install replica state", Some(path), error.error)
+ }
+ })?;
+ sync_parent(directory)
+}
+
+#[cfg(unix)]
+fn sync_parent(directory: &Path) -> Result<(), Error> {
+ File::open(directory)
+ .and_then(|directory| directory.sync_all())
+ .map_err(|error| Error::from_io("persist replica state directory", Some(directory), error))
+}
+
+#[cfg(not(unix))]
+fn sync_parent(_directory: &Path) -> Result<(), Error> {
+ Ok(())
+}
diff --git a/crates/core/src/sync/segment_install.rs b/crates/core/src/sync/segment_install.rs
new file mode 100644
index 0000000..8cdc3c5
--- /dev/null
+++ b/crates/core/src/sync/segment_install.rs
@@ -0,0 +1,182 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use futures::{StreamExt as _, TryStreamExt as _, future};
+use serde::{Deserialize, Serialize};
+
+use crate::Error;
+use crate::data::{RangeBatch, RangeBatcher, RangeReader};
+use crate::filesystem::ContentRef;
+use crate::format::ExtentRef;
+use crate::volume::AccessFamily;
+use crate::volume::ManagedVolume;
+use crate::work::{Spool, SpoolWriter, WorkContext};
+
+use super::replica::fs::{DirectoryDurability, StoredPath};
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub(crate) struct Installation {
+ pub(super) extent: ExtentRef,
+ pub(super) destination: StoredPath,
+ pub(super) fingerprint: ContentRef,
+ pub(super) executable: bool,
+}
+
+impl Installation {
+ fn memory_bytes(&self) -> usize {
+ size_of::<Self>()
+ .saturating_add(self.destination.memory_bytes())
+ .saturating_add(
+ self.extent
+ .decoding_outputs
+ .len()
+ .saturating_mul(size_of::<ContentRef>()),
+ )
+ }
+}
+
+pub(crate) async fn install<A: AccessFamily>(
+ volume: &ManagedVolume<A>,
+ workspace: &WorkContext,
+ pending: &Spool<Installation>,
+ concurrency: usize,
+ authoritative: bool,
+ durability: &mut DirectoryDurability,
+) -> Result<(), Error> {
+ let pending = crate::work::sort(workspace, pending, |file| {
+ (
+ file.extent.stored_range.segment,
+ file.extent.stored_range.offset,
+ )
+ })?;
+ let mut batches = RangeBatcher::new(volume.transfer_window_bytes(), volume.read_gap_bytes());
+ {
+ let installations = pending
+ .stream()?
+ .map(|file| {
+ file.and_then(|file| {
+ let locator = file.extent.stored_range.segment;
+ let start = file.extent.stored_range.offset;
+ let end = start
+ .checked_add(file.extent.stored_range.stored_content.length())
+ .ok_or_else(|| {
+ Error::corrupt("install Managed segment", "file range overflows")
+ })?;
+ let metadata_bytes = file.memory_bytes();
+ batches.push(locator, start..end, metadata_bytes, file)
+ })
+ .transpose()
+ })
+ .filter_map(future::ready)
+ .map_ok(|batch| {
+ let volume = volume.clone();
+ let workspace = workspace.clone();
+ async move { install_batch(&volume, &workspace, batch, authoritative).await }
+ })
+ .try_buffer_unordered(concurrency);
+ futures::pin_mut!(installations);
+ while let Some(installed) = installations.try_next().await? {
+ record_installed(installed, durability)?;
+ }
+ }
+ if let Some(batch) = batches.take() {
+ let installed = install_batch(volume, workspace, batch, authoritative).await?;
+ record_installed(installed, durability)?;
+ }
+ Ok(())
+}
+
+fn record_installed(
+ paths: Spool<StoredPath>,
+ durability: &mut DirectoryDurability,
+) -> Result<(), Error> {
+ let mut paths = paths.reader()?;
+ while let Some(path) = paths.next()? {
+ durability.changed_parent(&path.to_path_buf())?;
+ }
+ Ok(())
+}
+
+async fn install_batch<A: AccessFamily>(
+ volume: &ManagedVolume<A>,
+ workspace: &WorkContext,
+ batch: RangeBatch<Installation>,
+ authoritative: bool,
+) -> Result<Spool<StoredPath>, Error> {
+ let mut installed = workspace.writer("installed-segment-files")?;
+ if !authoritative {
+ install_ranges(volume, batch, &mut installed).await?;
+ return installed.finish();
+ }
+ let locator = batch.locator();
+ let mut selected = RangeBatcher::new(volume.transfer_window_bytes(), volume.read_gap_bytes());
+ for item in batch.into_items() {
+ let file = item.value;
+ if crate::sync::replica::fs::file_matches(
+ &file.destination.to_path_buf(),
+ file.fingerprint,
+ file.executable,
+ )
+ .await?
+ {
+ continue;
+ }
+ let metadata_bytes = file.memory_bytes();
+ if let Some(batch) = selected.push(locator, item.range, metadata_bytes, file)? {
+ install_ranges(volume, batch, &mut installed).await?;
+ }
+ }
+ if let Some(batch) = selected.take() {
+ install_ranges(volume, batch, &mut installed).await?;
+ }
+ installed.finish()
+}
+
+async fn install_ranges<A: AccessFamily>(
+ volume: &ManagedVolume<A>,
+ batch: RangeBatch<Installation>,
+ installed: &mut SpoolWriter<StoredPath>,
+) -> Result<(), Error> {
+ let mut batch = batch
+ .read(volume.operator(), volume.read_gap_bytes())
+ .await?;
+ while let Some((file, reader)) = batch.next() {
+ install_file(volume, reader, &file).await?;
+ installed.write(&file.destination)?;
+ }
+ Ok(())
+}
+
+async fn install_file<A: AccessFamily>(
+ volume: &ManagedVolume<A>,
+ reader: &mut RangeReader,
+ file: &Installation,
+) -> Result<(), Error> {
+ let destination = file.destination.to_path_buf();
+ crate::sync::replica::fs::install_file(&destination, file.executable, async |destination| {
+ volume
+ .read_extent(
+ reader,
+ file.extent.clone(),
+ 0..file.fingerprint.length(),
+ destination,
+ )
+ .await
+ })
+ .await?;
+ Ok(())
+}
diff --git a/crates/core/src/sync/state.rs b/crates/core/src/sync/state.rs
index 227c661..a3ef579 100644
--- a/crates/core/src/sync/state.rs
+++ b/crates/core/src/sync/state.rs
@@ -67,6 +67,26 @@ pub enum SyncPhase {
}
impl ReplicaState {
+ pub(crate) fn new(
+ root: PathBuf,
+ volume_id: VolumeId,
+ authority_id: AuthorityId,
+ authority_name: String,
+ common: NamespaceRevision,
+ ) -> Self {
+ Self {
+ root,
+ volume_id,
+ authority_id,
+ authority_name,
+ common,
+ observed: common,
+ phase: SyncPhase::Clean,
+ conflicts: 0,
+ base_expired: false,
+ }
+ }
+
pub(super) fn validate(&self) -> Result<(), Error> {
if self.observed.cursor().sequence() < self.common.cursor().sequence() {
return Err(Error::invalid(
@@ -129,4 +149,33 @@ impl ReplicaState {
pub const fn base_expired(&self) -> bool {
self.base_expired
}
+
+ pub(crate) const fn installation(&self) -> Option<(NamespaceRevision, bool)> {
+ match self.phase {
+ SyncPhase::Installing { published } => Some((self.observed, published)),
+ _ => None,
+ }
+ }
+
+ pub(crate) const fn resume_revision(&self) -> NamespaceRevision {
+ match self.phase {
+ SyncPhase::Clean => self.common,
+ SyncPhase::Publishing { .. } | SyncPhase::Installing { .. } => self.observed,
+ }
+ }
+
+ pub(crate) fn advance(&mut self, common: NamespaceRevision) {
+ self.common = common;
+ self.observed = common;
+ self.phase = SyncPhase::Clean;
+ self.conflicts = 0;
+ self.base_expired = false;
+ }
+
+ pub(crate) fn begin_install(&mut self, target: NamespaceRevision, published: bool) {
+ self.phase = SyncPhase::Installing { published };
+ self.observed = target;
+ self.conflicts = 0;
+ self.base_expired = false;
+ }
}
diff --git a/crates/core/src/sync/transfer.rs b/crates/core/src/sync/transfer.rs
new file mode 100644
index 0000000..2dbbe36
--- /dev/null
+++ b/crates/core/src/sync/transfer.rs
@@ -0,0 +1,70 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::path::Path;
+
+use tokio::fs::File;
+
+use crate::Error;
+use crate::data::ContentHasher;
+use crate::data::ReusableFile;
+use crate::filesystem::ContentRef;
+use crate::format::FileExtentMap;
+use crate::volume::AccessFamily;
+use crate::volume::ManagedVolume;
+
+pub(super) async fn materialize_file<A: AccessFamily>(
+ volume: &ManagedVolume<A>,
+ content: (ContentRef, FileExtentMap),
+ reusable: Option<FileExtentMap>,
+ destination: &Path,
+ executable: bool,
+) -> Result<(), Error> {
+ let expected = content.0;
+ crate::sync::replica::fs::install_file(destination, executable, async |destination_file| {
+ let mut source = match reusable {
+ Some(reference) => Some((
+ reference,
+ File::open(destination).await.map_err(|error| {
+ Error::from_io("open reusable replica file", Some(destination), error)
+ })?,
+ )),
+ None => None,
+ };
+ let reusable = source.as_mut().map(|(reference, source)| ReusableFile {
+ reference: reference.clone(),
+ source,
+ });
+ let mut materialized = ContentHasher::default();
+ {
+ let mut writer = tokio_util::io::InspectWriter::new(destination_file, |bytes| {
+ materialized.observe(bytes)
+ });
+ volume.read_data(content, .., reusable, &mut writer).await?;
+ }
+ if materialized.content() == expected {
+ Ok(())
+ } else {
+ Err(Error::conflict(
+ "install Managed file",
+ "materialized bytes do not match the target content",
+ ))
+ }
+ })
+ .await
+ .map_err(|error| error.with_context("path", destination.display()))
+}
diff --git a/crates/core/src/volume/open.rs b/crates/core/src/volume/open.rs
index e79fb1f..cf23a47 100644
--- a/crates/core/src/volume/open.rs
+++ b/crates/core/src/volume/open.rs
@@ -18,14 +18,19 @@
//! Create and open a Managed volume from its experimental v0 format.
use std::num::NonZeroUsize;
+use std::ops::RangeBounds;
use opendal::Operator;
+use tokio::io::AsyncWrite;
use crate::Error;
use crate::ErrorKind;
use crate::authority::{AuthorityAccess, AuthorityObservation, DefaultAuthorityAccess};
-use crate::data::{CoreDataAccess, DataAccess, ExtentCodec, FilePartitioner};
-use crate::filesystem::{ChangeCursor, NodeId, VolumeId};
+use crate::data::{
+ CoreDataAccess, DataAccess, ExtentCodec, FilePartitioner, RangeReader, ReusableFile,
+ validate_file_map,
+};
+use crate::filesystem::{ChangeCursor, ContentRef, NodeId, VolumeId};
use crate::format::{
FORMAT_KEY, FORMAT_RECORD, FileDataLayout, FileExtentMap, GcEpoch, NamespaceCommit,
NamespaceRevision, VolumeFormat,
@@ -229,6 +234,13 @@ impl<A: AccessFamily> ManagedVolume<A> {
self.access.data().decoding_count()
}
+ pub(crate) fn transfer_window_bytes(&self) -> usize {
+ self.work_budget
+ .memory_target_bytes()
+ .saturating_div(self.stream_concurrency)
+ .max(1)
+ }
+
/// Create a volume in empty storage, or reopen it when the same layout exists.
pub async fn create(
operator: &Operator,
@@ -456,6 +468,45 @@ impl<A: AccessFamily> ManagedVolume<A> {
)
.await
}
+
+ pub(crate) async fn read_extent(
+ &self,
+ reader: &mut RangeReader,
+ reference: crate::format::ExtentRef,
+ range: std::ops::Range<u64>,
+ destination: &mut (impl AsyncWrite + Send + Unpin),
+ ) -> Result<(), Error> {
+ let destination: &mut (dyn AsyncWrite + Send + Unpin) = destination;
+ self.access
+ .data()
+ .codec()
+ .decode(reader, reference, range, destination)
+ .await
+ }
+
+ pub(crate) async fn read_data<'a>(
+ &'a self,
+ content: (ContentRef, FileExtentMap),
+ range: impl RangeBounds<u64>,
+ reusable: Option<ReusableFile<'a>>,
+ destination: &'a mut (impl AsyncWrite + Send + Unpin),
+ ) -> Result<(), Error> {
+ let (content, reference) = content;
+ validate_file_map(&reference, content, self.file_decoding_count())?;
+ let range = crate::data::logical_range(content.length(), range)?;
+ crate::data::restore_file(
+ self.access.data(),
+ &self.operator,
+ self.read_gap_bytes,
+ self.transfer_window_bytes(),
+ reference,
+ content,
+ range,
+ reusable,
+ destination,
+ )
+ .await
+ }
}
fn require_control_capabilities(operator: &Operator) -> Result<(), Error> {
(opendal-ofs) 01/02: feat(sync): add replica request and state contracts
Posted by ps...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
PsiACE pushed a commit to branch managed-v0/sync-restore
in repository https://gitbox.apache.org/repos/asf/opendal-ofs.git
commit da30877d8fa448964b95ca50efa65a149b8d49a6
Author: PsiACE <ps...@apache.org>
AuthorDate: Thu Aug 27 17:25:33 2026 +0800
feat(sync): add replica request and state contracts
---
crates/core/src/lib.rs | 1 +
crates/core/src/sync/input.rs | 123 +++++++++++++++++++
crates/core/src/{lib.rs => sync/mod.rs} | 27 +++--
crates/core/src/{lib.rs => sync/replica/mod.rs} | 17 +--
.../src/{lib.rs => sync/replica/state_store.rs} | 34 +++---
crates/core/src/sync/state.rs | 132 +++++++++++++++++++++
6 files changed, 291 insertions(+), 43 deletions(-)
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index 20ad07c..f81a414 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -21,6 +21,7 @@ pub mod authority;
pub mod data;
mod error;
pub mod storage;
+pub mod sync;
pub mod volume;
pub(crate) mod work;
diff --git a/crates/core/src/sync/input.rs b/crates/core/src/sync/input.rs
new file mode 100644
index 0000000..e461bad
--- /dev/null
+++ b/crates/core/src/sync/input.rs
@@ -0,0 +1,123 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Sync request, change-set, and hint types.
+
+use crate::Error;
+use crate::filesystem::{ContentRef, validate_portable_path};
+use crate::format::FileRange;
+
+/// Trusted changed ranges for one immutable staged file publication.
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct FileChangeSetEntry {
+ pub(crate) path: String,
+ pub(crate) base: ContentRef,
+ pub(crate) ranges: Vec<FileRange>,
+}
+
+impl FileChangeSetEntry {
+ /// Normalize changed ranges and bind them to the previously observed content.
+ pub fn new(
+ path: impl Into<String>,
+ base: ContentRef,
+ ranges: impl IntoIterator<Item = std::ops::Range<u64>>,
+ ) -> Result<Self, Error> {
+ let path = path.into();
+ validate_portable_path(&path)?;
+ if path.is_empty() {
+ return Err(Error::invalid(
+ "record Managed file mutation",
+ "changed file path is empty",
+ ));
+ }
+ let mut ranges = ranges
+ .into_iter()
+ .map(|range| {
+ let length = range.end.checked_sub(range.start).ok_or_else(|| {
+ Error::invalid("record Managed file mutation", "changed range is invalid")
+ })?;
+ Ok::<_, Error>(FileRange::new(range.start, length)?)
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ ranges.sort_unstable_by_key(|range| range.offset);
+ let mut normalized = Vec::<FileRange>::new();
+ for range in ranges {
+ if let Some(previous) = normalized.last_mut() {
+ let previous_end = previous.end()?;
+ if range.offset <= previous_end {
+ let end = previous_end.max(range.end()?);
+ previous.length = end - previous.offset;
+ continue;
+ }
+ }
+ normalized.push(range);
+ }
+ Ok(Self {
+ path,
+ base,
+ ranges: normalized,
+ })
+ }
+
+ pub fn path(&self) -> &str {
+ &self.path
+ }
+}
+
+/// Complete trusted regular-file change set for one publication.
+#[derive(Clone, Debug, Default)]
+pub struct FileChangeSet {
+ pub(crate) entries: Vec<FileChangeSetEntry>,
+}
+
+impl FileChangeSet {
+ pub fn new(entries: Vec<FileChangeSetEntry>) -> Result<Self, Error> {
+ let mut seen = std::collections::BTreeSet::new();
+ for entry in &entries {
+ if !seen.insert(entry.path.as_str()) {
+ return Err(Error::invalid(
+ "synchronize replica",
+ "one file has more than one mutation input",
+ ));
+ }
+ }
+ Ok(Self { entries })
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.entries.is_empty()
+ }
+}
+
+/// Non-authoritative hint that a path may have changed.
+#[derive(Clone, Debug)]
+pub struct LocalChangeHint {
+ pub path: String,
+}
+
+/// Explicit conflict resolution by publishing the current local path.
+#[derive(Clone, Debug)]
+pub struct ConflictResolution {
+ pub path: String,
+}
+
+/// User-visible sync request assembled by the command layer.
+#[derive(Clone, Debug)]
+pub struct SyncRequest {
+ pub resolve: Vec<String>,
+ pub change_set: Option<FileChangeSet>,
+}
diff --git a/crates/core/src/lib.rs b/crates/core/src/sync/mod.rs
similarity index 62%
copy from crates/core/src/lib.rs
copy to crates/core/src/sync/mod.rs
index 20ad07c..efddaab 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/sync/mod.rs
@@ -15,19 +15,20 @@
// specific language governing permissions and limitations
// under the License.
-//! OpenDAL-backed runtime primitives for the Managed v0 format.
+//! Public request and durable replica-state contracts for Managed Sync.
-pub mod authority;
-pub mod data;
-mod error;
-pub mod storage;
-pub mod volume;
-pub(crate) mod work;
+mod input;
+mod replica;
+mod state;
-pub use error::{Error, ErrorKind, Result};
-pub use ofs_managed_format::v0 as format;
-pub use ofs_managed_format::v0::model as filesystem;
-pub use volume::{
- AccessFamily, CoreAccess, CreateOptions, GcOutcome, ManagedAccess, ManagedObservation,
- ManagedVolume, VolumeRuntime,
+pub use input::{
+ ConflictResolution, FileChangeSet, FileChangeSetEntry, LocalChangeHint, SyncRequest,
};
+pub use state::{PublicationOrigin, ReplicaPhase, ReplicaState};
+
+use crate::Error;
+
+/// Load and validate the lightweight state of one local replica.
+pub fn load_replica_state(path: &std::path::Path) -> Result<Option<ReplicaState>, Error> {
+ replica::state_store::load(path)
+}
diff --git a/crates/core/src/lib.rs b/crates/core/src/sync/replica/mod.rs
similarity index 64%
copy from crates/core/src/lib.rs
copy to crates/core/src/sync/replica/mod.rs
index 20ad07c..22954df 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/sync/replica/mod.rs
@@ -15,19 +15,4 @@
// specific language governing permissions and limitations
// under the License.
-//! OpenDAL-backed runtime primitives for the Managed v0 format.
-
-pub mod authority;
-pub mod data;
-mod error;
-pub mod storage;
-pub mod volume;
-pub(crate) mod work;
-
-pub use error::{Error, ErrorKind, Result};
-pub use ofs_managed_format::v0 as format;
-pub use ofs_managed_format::v0::model as filesystem;
-pub use volume::{
- AccessFamily, CoreAccess, CreateOptions, GcOutcome, ManagedAccess, ManagedObservation,
- ManagedVolume, VolumeRuntime,
-};
+pub(super) mod state_store;
diff --git a/crates/core/src/lib.rs b/crates/core/src/sync/replica/state_store.rs
similarity index 53%
copy from crates/core/src/lib.rs
copy to crates/core/src/sync/replica/state_store.rs
index 20ad07c..bc070e4 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/sync/replica/state_store.rs
@@ -15,19 +15,25 @@
// specific language governing permissions and limitations
// under the License.
-//! OpenDAL-backed runtime primitives for the Managed v0 format.
+//! Atomic persistence for the lightweight replica recovery record.
-pub mod authority;
-pub mod data;
-mod error;
-pub mod storage;
-pub mod volume;
-pub(crate) mod work;
+use std::fs;
+use std::path::Path;
-pub use error::{Error, ErrorKind, Result};
-pub use ofs_managed_format::v0 as format;
-pub use ofs_managed_format::v0::model as filesystem;
-pub use volume::{
- AccessFamily, CoreAccess, CreateOptions, GcOutcome, ManagedAccess, ManagedObservation,
- ManagedVolume, VolumeRuntime,
-};
+use crate::Error;
+use crate::format::RecordCodec;
+
+use crate::sync::state::ReplicaState;
+
+const STATE_RECORD: RecordCodec = RecordCodec::new(*b"OFSSTA00", 16 * 1024);
+
+pub(crate) fn load(path: &Path) -> Result<Option<ReplicaState>, Error> {
+ let bytes = match fs::read(path) {
+ Ok(bytes) => bytes,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => return Err(Error::from_io("read replica state", Some(path), error)),
+ };
+ let state: ReplicaState = STATE_RECORD.decode(&bytes)?;
+ state.validate()?;
+ Ok(Some(state))
+}
diff --git a/crates/core/src/sync/state.rs b/crates/core/src/sync/state.rs
new file mode 100644
index 0000000..227c661
--- /dev/null
+++ b/crates/core/src/sync/state.rs
@@ -0,0 +1,132 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+
+use crate::Error;
+use crate::authority::AuthorityId;
+use crate::filesystem::{ChangeCursor, OperationId, VolumeId};
+use crate::format::{GcEpoch, NamespaceRevision};
+
+/// A recoverable binding between one local replica and its remote namespace.
+///
+/// This record deliberately contains no namespace image or per-path identity map.
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct ReplicaState {
+ root: PathBuf,
+ volume_id: VolumeId,
+ authority_id: AuthorityId,
+ authority_name: String,
+ common: NamespaceRevision,
+ observed: NamespaceRevision,
+ phase: SyncPhase,
+ conflicts: u64,
+ base_expired: bool,
+}
+
+/// Origin of the namespace being installed.
+#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum PublicationOrigin {
+ Local,
+ Remote,
+}
+
+/// Persistent replica execution boundary.
+pub type ReplicaPhase = SyncPhase;
+
+#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum SyncPhase {
+ Clean,
+ Publishing {
+ target: NamespaceRevision,
+ operation_id: OperationId,
+ gc_epoch: GcEpoch,
+ },
+ Installing {
+ published: bool,
+ },
+}
+
+impl ReplicaState {
+ pub(super) fn validate(&self) -> Result<(), Error> {
+ if self.observed.cursor().sequence() < self.common.cursor().sequence() {
+ return Err(Error::invalid(
+ "synchronize replica",
+ "replica remote cursor is behind its common namespace",
+ ));
+ }
+ match self.phase {
+ SyncPhase::Clean => Ok(()),
+ SyncPhase::Publishing { target, .. }
+ if self.observed.cursor().sequence() >= self.common.cursor().sequence()
+ && target.cursor().sequence() == self.observed.cursor().sequence() + 1 =>
+ {
+ Ok(())
+ }
+ SyncPhase::Installing { .. }
+ if self.observed.cursor().sequence() >= self.common.cursor().sequence() =>
+ {
+ Ok(())
+ }
+ _ => Err(Error::corrupt(
+ "read replica state",
+ "replica recovery references are invalid",
+ )),
+ }
+ }
+
+ pub fn root(&self) -> &Path {
+ &self.root
+ }
+
+ pub const fn volume_id(&self) -> VolumeId {
+ self.volume_id
+ }
+
+ pub const fn authority_id(&self) -> AuthorityId {
+ self.authority_id
+ }
+
+ pub fn authority_name(&self) -> &str {
+ &self.authority_name
+ }
+
+ pub const fn common_revision(&self) -> NamespaceRevision {
+ self.common
+ }
+
+ pub const fn remote_cursor(&self) -> ChangeCursor {
+ self.observed.cursor()
+ }
+
+ pub const fn conflict_count(&self) -> u64 {
+ self.conflicts
+ }
+
+ pub const fn has_pending(&self) -> bool {
+ !matches!(self.phase, SyncPhase::Clean)
+ }
+
+ pub const fn base_expired(&self) -> bool {
+ self.base_expired
+ }
+}