You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opendal.apache.org by xu...@apache.org on 2026/10/26 07:37:46 UTC
(opendal-yinyang) 03/06: feat: add a read-only Linux FUSE mount frontend
This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch xuanwo/linux-fuse-foundation
in repository https://gitbox.apache.org/repos/asf/opendal-yinyang.git
commit 49253d272311760cd294d33a97891123b9775618
Author: Xuanwo <gi...@xuanwo.io>
AuthorDate: Mon Oct 26 15:26:38 2026 +0800
feat: add a read-only Linux FUSE mount frontend
Mount a Managed read-only volume in the foreground with
`yy --volume CONFIG mount MOUNTPOINT`. The volume must select
`frontend = "fuse"` and `read_only = true`; the frontend then uses
`fuser` 0.17 only on Linux and keeps every other platform build free of
FUSE dependencies.
The adapter implements the shared Mount contract directly: lookups pin
one authority observation, inode numbers are deterministic from NodeId
with root fixed at 1, kernel lookup counts are tracked per inode,
open/release map to independent references on the node's staged version,
direct I/O bypasses the page cache, and a clean release reclaims the
staged node so the next open re-observes the remote revision. Open
handles report their staged length through fstat, so content and
metadata cannot disagree when the remote side changes. Directory
handles pin a single snapshot revision and serve stable ordinal readdir
offsets.
The read-only frontend refuses to mount a staging database that still
contains unpublished, frozen, conflicted or failed handles instead of
exposing locally staged bytes as a remote snapshot. All remote-capable
callbacks dispatch onto the Tokio runtime with owned request values and
move replies into the tasks; fuser guarantees one reply per request and
replies EIO to dropped unanswered replies. SIGINT/SIGTERM unmount the
session cleanly. FUSE_INTERRUPT is explicitly not cancellation: the
binding answers ENOSYS and the kernel ignores it, so interrupted
syscalls do not stop in-flight remote work.
Co-authored-by: Chojan Shang <ps...@apache.org>
---
Cargo.lock | 202 +++++++++++++
Cargo.toml | 6 +-
src/file_cli.rs | 13 +-
src/fuse/attrs.rs | 88 ++++++
src/fuse/frontend.rs | 830 +++++++++++++++++++++++++++++++++++++++++++++++++++
src/fuse/inode.rs | 198 ++++++++++++
src/fuse/mod.rs | 186 ++++++++++++
src/lib.rs | 2 +
src/main.rs | 7 +-
9 files changed, 1529 insertions(+), 3 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 8ced4f9..2c47845 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -80,6 +80,12 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
[[package]]
name = "aws-lc-rs"
version = "1.18.1"
@@ -525,6 +531,26 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
+[[package]]
+name = "fuser"
+version = "0.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "80a5eca878900c2e39e9e52fd797954b7fc39eeefc8558257114bfea6a698fcf"
+dependencies = [
+ "bitflags 2.13.2",
+ "libc",
+ "log",
+ "memchr",
+ "nix",
+ "num_enum",
+ "page_size",
+ "parking_lot",
+ "pkg-config",
+ "ref-cast",
+ "smallvec",
+ "zerocopy",
+]
+
[[package]]
name = "futures"
version = "0.3.34"
@@ -1075,6 +1101,15 @@ version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
+[[package]]
+name = "lock_api"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+dependencies = [
+ "scopeguard",
+]
+
[[package]]
name = "log"
version = "0.4.34"
@@ -1113,6 +1148,15 @@ version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+[[package]]
+name = "memoffset"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+dependencies = [
+ "autocfg",
+]
+
[[package]]
name = "mio"
version = "1.2.3"
@@ -1124,6 +1168,41 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "nix"
+version = "0.30.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6"
+dependencies = [
+ "bitflags 2.13.2",
+ "cfg-if",
+ "cfg_aliases",
+ "libc",
+ "memoffset",
+]
+
+[[package]]
+name = "num_enum"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"
+dependencies = [
+ "num_enum_derive",
+ "rustversion",
+]
+
+[[package]]
+name = "num_enum_derive"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"
+dependencies = [
+ "proc-macro-crate",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "once_cell"
version = "1.21.4"
@@ -1224,6 +1303,39 @@ dependencies = [
"hashbrown 0.14.5",
]
+[[package]]
+name = "page_size"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da"
+dependencies = [
+ "libc",
+ "winapi",
+]
+
+[[package]]
+name = "parking_lot"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-link",
+]
+
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -1392,6 +1504,35 @@ dependencies = [
"rand_core",
]
+[[package]]
+name = "redox_syscall"
+version = "0.5.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
+[[package]]
+name = "ref-cast"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"
+dependencies = [
+ "ref-cast-impl",
+]
+
+[[package]]
+name = "ref-cast-impl"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
+]
+
[[package]]
name = "reqsign-aws-core"
version = "3.1.1"
@@ -1669,6 +1810,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
[[package]]
name = "security-framework"
version = "3.7.0"
@@ -1781,6 +1928,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+[[package]]
+name = "signal-hook-registry"
+version = "1.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
+dependencies = [
+ "errno",
+ "libc",
+]
+
[[package]]
name = "simd_cesu8"
version = "1.2.0"
@@ -1962,6 +2119,7 @@ dependencies = [
"libc",
"mio",
"pin-project-lite",
+ "signal-hook-registry",
"socket2",
"tokio-macros",
"windows-sys 0.61.2",
@@ -2313,6 +2471,22 @@ dependencies = [
"libc",
]
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
[[package]]
name = "winapi-util"
version = "0.1.11"
@@ -2322,6 +2496,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
[[package]]
name = "windows-link"
version = "0.2.1"
@@ -2440,6 +2620,8 @@ dependencies = [
"blake3",
"borsh",
"clap",
+ "fuser",
+ "nix",
"opendal",
"rusqlite",
"serde",
@@ -2502,6 +2684,26 @@ dependencies = [
"synstructure",
]
+[[package]]
+name = "zerocopy"
+version = "0.8.63"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.63"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "zerofrom"
version = "0.1.8"
diff --git a/Cargo.toml b/Cargo.toml
index 31cfe71..3c864f2 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -43,10 +43,14 @@ rusqlite = { version = "0.40.2", default-features = false, features = ["bundled"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tempfile = "3"
-tokio = { workspace = true, features = ["fs", "macros", "rt-multi-thread", "sync"] }
+tokio = { workspace = true, features = ["fs", "macros", "rt-multi-thread", "signal", "sync"] }
uuid.workspace = true
yinyang-core = { path = "crates/core" }
+[target.'cfg(target_os = "linux")'.dependencies]
+fuser = "0.17.0"
+nix = { version = "0.30.0", features = ["user"] }
+
[workspace]
members = [".", "crates/core", "crates/native", "xtask"]
resolver = "3"
diff --git a/src/file_cli.rs b/src/file_cli.rs
index faa7cf3..e4785fc 100644
--- a/src/file_cli.rs
+++ b/src/file_cli.rs
@@ -178,8 +178,19 @@ pub async fn run(path: &Path, command: Command) -> Result<(), Box<dyn std::error
);
return Ok(());
}
+ if let Command::Mount { mountpoint } = command {
+ #[cfg(target_os = "linux")]
+ {
+ return yinyang::fuse::run(config, operator, token, mountpoint).await;
+ }
+ #[cfg(not(target_os = "linux"))]
+ {
+ let _ = (operator, token, mountpoint);
+ return Err("the fuse frontend is implemented only on Linux".into());
+ }
+ }
let Command::File { command } = command else {
- return Err("with --volume use file, capabilities, receipt, or status; initialize object storage with yy create or service storage with yy serve".into());
+ return Err("with --volume use mount, file, capabilities, receipt, or status; initialize object storage with yy create or service storage with yy serve".into());
};
let volume = Volume::open(config, operator, token).await?;
let runtime = volume.runtime();
diff --git a/src/fuse/attrs.rs b/src/fuse/attrs.rs
new file mode 100644
index 0000000..67489f6
--- /dev/null
+++ b/src/fuse/attrs.rs
@@ -0,0 +1,88 @@
+// 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.
+
+//! Synthesized FUSE attributes for the YinYang metadata model.
+
+use fuser::{FileAttr, FileType};
+use std::time::{Duration, SystemTime};
+use yinyang_core::Revision;
+
+/// Short kernel attribute lifetime. This frontend re-observes the authority
+/// on demand; a one-second window keeps `stat` churn low without pretending
+/// that a longer-lived kernel cache is a coherent remote snapshot.
+pub const ATTR_TTL: Duration = Duration::from_secs(1);
+
+/// Directory size reported to `stat`; the core stores no directory payload.
+pub const DIRECTORY_SIZE: u64 = 4096;
+
+/// Fixed offset makes revision-derived stamps readable without claiming that
+/// they are wall-clock times.
+const STAMP_EPOCH: u64 = 1_600_000_000;
+
+/// Build attributes for an immutable observation. `size` must come from the
+/// same version as `revision`; handles and snapshots both satisfy that rule.
+pub fn attribute(
+ ino: fuser::INodeNo,
+ directory: bool,
+ executable: bool,
+ size: u64,
+ revision: Revision,
+) -> FileAttr {
+ let (uid, gid) = mount_owner();
+ let stamp = SystemTime::UNIX_EPOCH
+ + Duration::from_secs(
+ STAMP_EPOCH
+ + u64::from_be_bytes(
+ revision.to_bytes()[..8]
+ .try_into()
+ .expect("revision sequence prefix"),
+ ),
+ );
+ let perm = if directory {
+ 0o555
+ } else if executable {
+ 0o555
+ } else {
+ 0o444
+ };
+ FileAttr {
+ ino,
+ size,
+ blocks: size.div_ceil(512),
+ atime: stamp,
+ mtime: stamp,
+ ctime: stamp,
+ crtime: stamp,
+ kind: if directory {
+ FileType::Directory
+ } else {
+ FileType::RegularFile
+ },
+ perm,
+ nlink: if directory { 2 } else { 1 },
+ uid,
+ gid,
+ rdev: 0,
+ blksize: 4096,
+ flags: 0,
+ }
+}
+
+fn mount_owner() -> (u32, u32) {
+ use nix::unistd::{getegid, geteuid};
+ (geteuid().as_raw(), getegid().as_raw())
+}
diff --git a/src/fuse/frontend.rs b/src/fuse/frontend.rs
new file mode 100644
index 0000000..6d42417
--- /dev/null
+++ b/src/fuse/frontend.rs
@@ -0,0 +1,830 @@
+// 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.
+
+//! Read-only Linux FUSE frontend over the shared Mount staging contract.
+//!
+//! `fuser` owns the FUSE device, session loop and reply wire encoding; this
+//! module implements only the filesystem callbacks. Every callback that can
+//! perform remote I/O dispatches onto the process Tokio runtime and moves its
+//! reply into the task, so one reply is sent per request and no adapter-wide
+//! lock is held across an authority or staging await. Input buffers borrowed
+//! from the request are converted to owned values before the dispatch, and
+//! the low-level binding replies EIO if a task drops an unanswered reply.
+//!
+//! Files pin the node's shared staged version. `fstat` on an open handle uses
+//! that staged record's length, and reads return staged bytes, so an old
+//! descriptor never mixes a newer remote length with older content. `release`
+//! reclaims a clean shared node, which makes the next open observe the
+//! current remote revision without rebasing live handles. Directory handles
+//! pin one `Snapshot` revision; readdir offsets are stable ordinal positions
+//! over pages of that pinned listing.
+//!
+//! The binding replies ENOSYS to FUSE_INTERRUPT, which the kernel ignores;
+//! an interrupted syscall therefore does not cancel in-flight remote work.
+//! Each operation still replies exactly once, and unmounting the session
+//! aborts remaining tasks whose dropped replies surface as EIO.
+
+use super::attrs::{ATTR_TTL, DIRECTORY_SIZE, attribute};
+use super::inode::{CachedInfo, InodeTable, ROOT_INODE};
+use crate::mount::{Mount, MountFile};
+use fuser::{
+ AccessFlags, BsdFileFlags, FileAttr, FileHandle, FileType, Filesystem, FopenFlags, Generation,
+ INodeNo, InitFlags, KernelConfig, LockOwner, OpenAccMode, OpenFlags, ReplyAttr, ReplyData,
+ ReplyDirectory, ReplyEmpty, ReplyEntry, ReplyOpen, ReplyStatfs, ReplyWrite, ReplyXattr,
+ Request, TimeOrNow, WriteFlags,
+};
+use std::collections::BTreeMap;
+use std::future::Future;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::SystemTime;
+use tokio::runtime::Handle;
+use tokio::sync::Mutex as AsyncMutex;
+use yinyang_core::{NodeId, ScanToken, Snapshot};
+
+/// Entries fetched per pinned directory scan.
+const READDIR_PAGE: usize = 512;
+
+pub(super) struct Inner {
+ mount: Mount,
+ inodes: Mutex<InodeTable>,
+ files: Mutex<BTreeMap<u64, Arc<OpenFile>>>,
+ dirs: Mutex<BTreeMap<u64, Arc<AsyncMutex<DirCursor>>>>,
+ next_handle: AtomicU64,
+ runtime: Handle,
+}
+
+/// One kernel open maps to one reference on the node's shared staged version.
+struct OpenFile {
+ node: NodeId,
+ file: MountFile,
+}
+
+#[derive(Clone)]
+struct DirItem {
+ ino: INodeNo,
+ kind: FileType,
+ name: String,
+}
+
+/// A pinned directory enumeration. Cursor state is serialized per open handle;
+/// no mount-wide lock spans the page scans or per-entry metadata reads.
+struct DirCursor {
+ snapshot: Snapshot,
+ ino: INodeNo,
+ directory: NodeId,
+ parent_ino: INodeNo,
+ entries: Vec<DirItem>,
+ token: Option<ScanToken>,
+ complete: bool,
+}
+
+impl Inner {
+ pub(super) fn new(mount: Mount, runtime: Handle) -> Self {
+ let root = mount.authority().root();
+ Self {
+ mount,
+ inodes: Mutex::new(InodeTable::new(root)),
+ files: Mutex::new(BTreeMap::new()),
+ dirs: Mutex::new(BTreeMap::new()),
+ next_handle: AtomicU64::new(0),
+ runtime,
+ }
+ }
+
+ fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {
+ self.runtime.spawn(future);
+ }
+
+ fn next_handle(&self) -> u64 {
+ self.next_handle.fetch_add(1, Ordering::Relaxed) + 1
+ }
+
+ fn inode_for(&self, id: NodeId, info: Option<CachedInfo>) -> Result<INodeNo, fuser::Errno> {
+ let mut inodes = guard(&self.inodes);
+ if let Some(info) = info {
+ inodes.cache(id, info);
+ }
+ inodes.inode(id).map_err(|_| fuser::Errno::EIO)
+ }
+
+ fn node(&self, ino: INodeNo) -> Option<NodeId> {
+ guard(&self.inodes).node(ino)
+ }
+
+ fn remember_lookup(&self, ino: INodeNo) {
+ guard(&self.inodes).remember_lookup(ino);
+ }
+
+ fn forget(&self, ino: INodeNo, count: u64) {
+ guard(&self.inodes).forget(ino, count);
+ }
+
+ fn open_file(&self, fh: FileHandle) -> Option<Arc<OpenFile>> {
+ guard(&self.files).get(&fh.0).cloned()
+ }
+
+ fn dir_cursor(&self, fh: FileHandle) -> Option<Arc<AsyncMutex<DirCursor>>> {
+ guard(&self.dirs).get(&fh.0).cloned()
+ }
+
+ async fn observe(&self) -> Result<Snapshot, fuser::Errno> {
+ self.mount
+ .authority()
+ .observe_latest()
+ .await
+ .map_err(|e| core_errno(&e))
+ }
+
+ /// Attributes and size from one pinned observation.
+ async fn snapshot_attr(
+ &self,
+ snapshot: &Snapshot,
+ id: NodeId,
+ ) -> Result<FileAttr, fuser::Errno> {
+ let node = snapshot
+ .node(id)
+ .await
+ .map_err(|e| core_errno(&e))?
+ .ok_or(fuser::Errno::ENOENT)?;
+ let info = CachedInfo {
+ directory: node.is_directory(),
+ executable: node.executable(),
+ generation: node.generation(),
+ };
+ let ino = self.inode_for(id, Some(info))?;
+ let size = match node.kind() {
+ yinyang_core::NodeKind::File(content) => content.content_id().length(),
+ yinyang_core::NodeKind::Directory { .. } => DIRECTORY_SIZE,
+ };
+ Ok(attribute(
+ ino,
+ info.directory,
+ info.executable,
+ size,
+ snapshot.revision(),
+ ))
+ }
+
+ /// Attributes for an open handle: the staged length is authoritative so
+ /// `fstat` and read bytes describe the same pinned version.
+ async fn handle_attr(&self, open: &OpenFile) -> Result<FileAttr, fuser::Errno> {
+ let status = open.file.status().await.map_err(|e| runtime_errno(&e))?;
+ let cached = guard(&self.inodes).cached(open.node);
+ let ino = self.inode_for(open.node, None)?;
+ Ok(attribute(
+ ino,
+ cached.is_some_and(|info| info.directory),
+ cached.is_some_and(|info| info.executable),
+ status.length,
+ status.remote_revision,
+ ))
+ }
+
+ async fn lookup(&self, parent: INodeNo, name: String, reply: ReplyEntry) {
+ let Some(parent_id) = self.node(parent) else {
+ return reply.error(fuser::Errno::ESTALE);
+ };
+ let snapshot = match self.observe().await {
+ Ok(snapshot) => snapshot,
+ Err(errno) => return reply.error(errno),
+ };
+ let entry = match snapshot.lookup(parent_id, &name).await {
+ Ok(Some(entry)) => entry,
+ Ok(None) => return reply.error(fuser::Errno::ENOENT),
+ Err(error) => return reply.error(core_errno(&error)),
+ };
+ match self.snapshot_attr(&snapshot, entry.node_id).await {
+ Ok(attr) => {
+ self.remember_lookup(attr.ino);
+ reply.entry(&ATTR_TTL, &attr, Generation(0));
+ }
+ Err(errno) => reply.error(errno),
+ }
+ }
+
+ async fn getattr(&self, ino: INodeNo, fh: Option<FileHandle>, reply: ReplyAttr) {
+ if let Some(fh) = fh
+ && let Some(open) = self.open_file(fh)
+ {
+ return match self.handle_attr(&open).await {
+ Ok(attr) => reply.attr(&ATTR_TTL, &attr),
+ Err(errno) => reply.error(errno),
+ };
+ }
+ let Some(id) = self.node(ino) else {
+ return reply.error(fuser::Errno::ESTALE);
+ };
+ let snapshot = match self.observe().await {
+ Ok(snapshot) => snapshot,
+ Err(errno) => return reply.error(errno),
+ };
+ match self.snapshot_attr(&snapshot, id).await {
+ Ok(attr) => reply.attr(&ATTR_TTL, &attr),
+ Err(errno) => reply.error(errno),
+ }
+ }
+
+ async fn open(&self, ino: INodeNo, flags: OpenFlags, reply: ReplyOpen) {
+ if flags.acc_mode() != OpenAccMode::O_RDONLY {
+ return reply.error(fuser::Errno::EROFS);
+ }
+ let Some(id) = self.node(ino) else {
+ return reply.error(fuser::Errno::ESTALE);
+ };
+ if guard(&self.inodes)
+ .cached(id)
+ .is_some_and(|info| info.directory)
+ {
+ return reply.error(fuser::Errno::EISDIR);
+ }
+ match self.mount.open_node(id, false).await {
+ Ok(file) => {
+ let fh = self.next_handle();
+ guard(&self.files).insert(fh, Arc::new(OpenFile { node: id, file }));
+ reply.opened(FileHandle(fh), FopenFlags::FOPEN_DIRECT_IO);
+ }
+ Err(error) => reply.error(runtime_errno(&error)),
+ }
+ }
+
+ async fn read(&self, fh: FileHandle, offset: u64, size: u32, reply: ReplyData) {
+ let Some(open) = self.open_file(fh) else {
+ return reply.error(fuser::Errno::EBADF);
+ };
+ match open.file.read(offset, size as usize).await {
+ Ok(bytes) => reply.data(&bytes),
+ Err(error) => reply.error(runtime_errno(&error)),
+ }
+ }
+
+ async fn release(&self, ino: INodeNo, fh: FileHandle, reply: ReplyEmpty) {
+ let Some(removed) = guard(&self.files).remove(&fh.0) else {
+ return reply.ok();
+ };
+ let node = removed.node;
+ drop(removed);
+ // Reclaim only the last clean reference so the next open materializes
+ // the current remote revision. A busy result means an interrupted read
+ // still shares the node; that pinned version stays coherent and is
+ // reclaimed once a later release is the final reference.
+ if let Err(error) = self.mount.reclaim(node).await
+ && error.kind() != crate::runtime::ErrorKind::Busy
+ {
+ eprintln!("yy: fuse release cleanup inode {ino}: {error}");
+ }
+ reply.ok();
+ }
+
+ async fn opendir(&self, ino: INodeNo, reply: ReplyOpen) {
+ let Some(id) = self.node(ino) else {
+ return reply.error(fuser::Errno::ESTALE);
+ };
+ let snapshot = match self.observe().await {
+ Ok(snapshot) => snapshot,
+ Err(errno) => return reply.error(errno),
+ };
+ let node = match snapshot.node(id).await {
+ Ok(Some(node)) => node,
+ Ok(None) => return reply.error(fuser::Errno::ENOENT),
+ Err(error) => return reply.error(core_errno(&error)),
+ };
+ if !node.is_directory() {
+ return reply.error(fuser::Errno::ENOTDIR);
+ }
+ let parent_ino = match node.link() {
+ Some(link) => match self.inode_for(link.parent, None) {
+ Ok(ino) => ino,
+ Err(errno) => return reply.error(errno),
+ },
+ // The root's "." and ".." both denote itself.
+ None => ROOT_INODE,
+ };
+ guard(&self.inodes).cache(
+ id,
+ CachedInfo {
+ directory: true,
+ executable: false,
+ generation: node.generation(),
+ },
+ );
+ let fh = self.next_handle();
+ let cursor = Arc::new(AsyncMutex::new(DirCursor {
+ snapshot,
+ ino,
+ directory: id,
+ parent_ino,
+ entries: Vec::new(),
+ token: None,
+ complete: false,
+ }));
+ guard(&self.dirs).insert(fh, cursor);
+ reply.opened(FileHandle(fh), FopenFlags::empty());
+ }
+
+ async fn readdir(&self, fh: FileHandle, offset: u64, mut reply: ReplyDirectory) {
+ let Some(handle) = self.dir_cursor(fh) else {
+ return reply.error(fuser::Errno::EBADF);
+ };
+ let mut cursor = handle.lock().await;
+ if offset == 0 {
+ cursor.entries.clear();
+ cursor.token = None;
+ cursor.complete = false;
+ }
+ let mut index = offset as usize;
+ let mut added = false;
+ loop {
+ if index == 0 {
+ if reply.add(cursor.ino, 1, FileType::Directory, ".") {
+ break;
+ }
+ added = true;
+ index = 1;
+ continue;
+ }
+ if index == 1 {
+ if reply.add(cursor.parent_ino, 2, FileType::Directory, "..") {
+ break;
+ }
+ added = true;
+ index = 2;
+ continue;
+ }
+ let local = index - 2;
+ if local >= cursor.entries.len() {
+ if cursor.complete {
+ break;
+ }
+ let before = cursor.entries.len();
+ if let Err(errno) = self.load_page(&mut cursor).await {
+ // Verified entries stay visible; a mid-stream failure
+ // resumes from the committed offset on the next call.
+ if added || cursor.entries.len() > before {
+ break;
+ }
+ return reply.error(errno);
+ }
+ continue;
+ }
+ let item = cursor.entries[local].clone();
+ if reply.add(item.ino, index as u64 + 1, item.kind, &item.name) {
+ break;
+ }
+ added = true;
+ index += 1;
+ }
+ reply.ok();
+ }
+
+ async fn releasedir(&self, fh: FileHandle, reply: ReplyEmpty) {
+ guard(&self.dirs).remove(&fh.0);
+ reply.ok();
+ }
+
+ async fn load_page(&self, cursor: &mut DirCursor) -> Result<(), fuser::Errno> {
+ let page = cursor
+ .snapshot
+ .scan(cursor.directory, cursor.token.as_ref(), READDIR_PAGE)
+ .await
+ .map_err(|e| core_errno(&e))?;
+ cursor.token = page.next;
+ cursor.complete = cursor.token.is_none();
+ for entry in page.entries {
+ let (ino, kind) = self.resolve_entry(&cursor.snapshot, entry.node_id).await?;
+ cursor.entries.push(DirItem {
+ ino,
+ kind,
+ name: entry.name,
+ });
+ }
+ Ok(())
+ }
+
+ async fn resolve_entry(
+ &self,
+ snapshot: &Snapshot,
+ id: NodeId,
+ ) -> Result<(INodeNo, FileType), fuser::Errno> {
+ if let Some(info) = guard(&self.inodes).cached(id) {
+ let ino = self.inode_for(id, None)?;
+ return Ok((ino, entry_kind(info.directory)));
+ }
+ let node = snapshot
+ .node(id)
+ .await
+ .map_err(|e| core_errno(&e))?
+ .ok_or(fuser::Errno::EIO)?;
+ let info = CachedInfo {
+ directory: node.is_directory(),
+ executable: node.executable(),
+ generation: node.generation(),
+ };
+ let ino = self.inode_for(id, Some(info))?;
+ Ok((ino, entry_kind(info.directory)))
+ }
+}
+
+fn entry_kind(directory: bool) -> FileType {
+ if directory {
+ FileType::Directory
+ } else {
+ FileType::RegularFile
+ }
+}
+
+fn guard<T>(lock: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
+ lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
+}
+
+fn runtime_errno(error: &crate::runtime::Error) -> fuser::Errno {
+ use crate::runtime::ErrorKind;
+ match error.kind() {
+ ErrorKind::NotFound => fuser::Errno::ENOENT,
+ ErrorKind::AlreadyExists => fuser::Errno::EEXIST,
+ ErrorKind::NotDirectory => fuser::Errno::ENOTDIR,
+ ErrorKind::IsDirectory => fuser::Errno::EISDIR,
+ ErrorKind::NotEmpty => fuser::Errno::ENOTEMPTY,
+ ErrorKind::ReadOnly => fuser::Errno::EROFS,
+ ErrorKind::PermissionDenied => fuser::Errno::EACCES,
+ ErrorKind::Busy | ErrorKind::Frozen => fuser::Errno::EBUSY,
+ ErrorKind::TooLarge => fuser::Errno::EFBIG,
+ ErrorKind::NoSpace => fuser::Errno::ENOSPC,
+ ErrorKind::Invalid | ErrorKind::InvalidName => fuser::Errno::EINVAL,
+ ErrorKind::Unsupported => fuser::Errno::ENOSYS,
+ ErrorKind::Closed
+ | ErrorKind::Conflict
+ | ErrorKind::Retryable
+ | ErrorKind::Unknown
+ | ErrorKind::Corrupt
+ | ErrorKind::Storage
+ | ErrorKind::Io
+ | ErrorKind::Unclassified => fuser::Errno::EIO,
+ }
+}
+
+fn core_errno(error: &yinyang_core::Error) -> fuser::Errno {
+ use yinyang_core::ErrorKind;
+ match error.kind() {
+ ErrorKind::NotFound => fuser::Errno::ENOENT,
+ ErrorKind::AlreadyExists => fuser::Errno::EEXIST,
+ ErrorKind::NotDirectory => fuser::Errno::ENOTDIR,
+ ErrorKind::IsDirectory => fuser::Errno::EISDIR,
+ ErrorKind::NotEmpty => fuser::Errno::ENOTEMPTY,
+ ErrorKind::PermissionDenied => fuser::Errno::EACCES,
+ ErrorKind::Invalid | ErrorKind::InvalidName => fuser::Errno::EINVAL,
+ ErrorKind::Unsupported => fuser::Errno::ENOSYS,
+ ErrorKind::Corrupt | ErrorKind::Storage | ErrorKind::Io => fuser::Errno::EIO,
+ }
+}
+
+/// The filesystem object handed to the fuser session.
+pub(super) struct FuseFrontend {
+ pub(super) inner: Arc<Inner>,
+}
+
+impl Filesystem for FuseFrontend {
+ fn init(&mut self, _req: &Request, config: &mut KernelConfig) -> std::io::Result<()> {
+ // FILE_OPS makes the kernel carry the open handle on getattr, which
+ // lets fstat report the staged version; PARALLEL_DIROPS admits
+ // concurrent lookup/readdir, which the adapter already supports.
+ let _ = config.add_capabilities(InitFlags::FUSE_FILE_OPS | InitFlags::FUSE_PARALLEL_DIROPS);
+ let _ = config.set_time_granularity(std::time::Duration::from_secs(1));
+ Ok(())
+ }
+
+ fn destroy(&mut self) {}
+
+ fn lookup(&self, _req: &Request, parent: INodeNo, name: &std::ffi::OsStr, reply: ReplyEntry) {
+ let Some(name) = name.to_str() else {
+ return reply.error(fuser::Errno::EINVAL);
+ };
+ let name = name.to_owned();
+ let inner = self.inner.clone();
+ self.inner
+ .spawn(async move { inner.lookup(parent, name, reply).await });
+ }
+
+ fn getattr(&self, _req: &Request, ino: INodeNo, fh: Option<FileHandle>, reply: ReplyAttr) {
+ let inner = self.inner.clone();
+ self.inner
+ .spawn(async move { inner.getattr(ino, fh, reply).await });
+ }
+
+ fn setattr(
+ &self,
+ _req: &Request,
+ _ino: INodeNo,
+ _mode: Option<u32>,
+ _uid: Option<u32>,
+ _gid: Option<u32>,
+ _size: Option<u64>,
+ _atime: Option<TimeOrNow>,
+ _mtime: Option<TimeOrNow>,
+ _ctime: Option<SystemTime>,
+ _fh: Option<FileHandle>,
+ _crtime: Option<SystemTime>,
+ _chgtime: Option<SystemTime>,
+ _bkuptime: Option<SystemTime>,
+ _flags: Option<BsdFileFlags>,
+ reply: ReplyAttr,
+ ) {
+ reply.error(fuser::Errno::EROFS);
+ }
+
+ fn readlink(&self, _req: &Request, _ino: INodeNo, reply: ReplyData) {
+ reply.error(fuser::Errno::EINVAL);
+ }
+
+ fn mknod(
+ &self,
+ _req: &Request,
+ _parent: INodeNo,
+ _name: &std::ffi::OsStr,
+ _mode: u32,
+ _umask: u32,
+ _rdev: u32,
+ reply: ReplyEntry,
+ ) {
+ reply.error(fuser::Errno::EROFS);
+ }
+
+ fn mkdir(
+ &self,
+ _req: &Request,
+ _parent: INodeNo,
+ _name: &std::ffi::OsStr,
+ _mode: u32,
+ _umask: u32,
+ reply: ReplyEntry,
+ ) {
+ reply.error(fuser::Errno::EROFS);
+ }
+
+ fn unlink(&self, _req: &Request, _parent: INodeNo, _name: &std::ffi::OsStr, reply: ReplyEmpty) {
+ reply.error(fuser::Errno::EROFS);
+ }
+
+ fn rmdir(&self, _req: &Request, _parent: INodeNo, _name: &std::ffi::OsStr, reply: ReplyEmpty) {
+ reply.error(fuser::Errno::EROFS);
+ }
+
+ fn symlink(
+ &self,
+ _req: &Request,
+ _parent: INodeNo,
+ _link_name: &std::ffi::OsStr,
+ _target: &std::path::Path,
+ reply: ReplyEntry,
+ ) {
+ reply.error(fuser::Errno::EROFS);
+ }
+
+ fn rename(
+ &self,
+ _req: &Request,
+ _parent: INodeNo,
+ _name: &std::ffi::OsStr,
+ _newparent: INodeNo,
+ _newname: &std::ffi::OsStr,
+ _flags: fuser::RenameFlags,
+ reply: ReplyEmpty,
+ ) {
+ reply.error(fuser::Errno::EROFS);
+ }
+
+ fn link(
+ &self,
+ _req: &Request,
+ _ino: INodeNo,
+ _newparent: INodeNo,
+ _newname: &std::ffi::OsStr,
+ reply: ReplyEntry,
+ ) {
+ reply.error(fuser::Errno::EROFS);
+ }
+
+ fn open(&self, _req: &Request, ino: INodeNo, flags: OpenFlags, reply: ReplyOpen) {
+ let inner = self.inner.clone();
+ self.inner
+ .spawn(async move { inner.open(ino, flags, reply).await });
+ }
+
+ fn read(
+ &self,
+ _req: &Request,
+ _ino: INodeNo,
+ fh: FileHandle,
+ offset: u64,
+ size: u32,
+ _flags: OpenFlags,
+ _lock_owner: Option<LockOwner>,
+ reply: ReplyData,
+ ) {
+ let inner = self.inner.clone();
+ self.inner
+ .spawn(async move { inner.read(fh, offset, size, reply).await });
+ }
+
+ fn write(
+ &self,
+ _req: &Request,
+ _ino: INodeNo,
+ _fh: FileHandle,
+ _offset: u64,
+ _data: &[u8],
+ _write_flags: WriteFlags,
+ _flags: OpenFlags,
+ _lock_owner: Option<LockOwner>,
+ reply: ReplyWrite,
+ ) {
+ reply.error(fuser::Errno::EROFS);
+ }
+
+ fn flush(
+ &self,
+ _req: &Request,
+ _ino: INodeNo,
+ _fh: FileHandle,
+ _lock_owner: LockOwner,
+ reply: ReplyEmpty,
+ ) {
+ reply.ok();
+ }
+
+ fn fsync(
+ &self,
+ _req: &Request,
+ _ino: INodeNo,
+ _fh: FileHandle,
+ _datasync: bool,
+ reply: ReplyEmpty,
+ ) {
+ reply.ok();
+ }
+
+ fn opendir(&self, _req: &Request, ino: INodeNo, _flags: OpenFlags, reply: ReplyOpen) {
+ let inner = self.inner.clone();
+ self.inner
+ .spawn(async move { inner.opendir(ino, reply).await });
+ }
+
+ fn readdir(
+ &self,
+ _req: &Request,
+ _ino: INodeNo,
+ fh: FileHandle,
+ offset: u64,
+ reply: ReplyDirectory,
+ ) {
+ let inner = self.inner.clone();
+ self.inner
+ .spawn(async move { inner.readdir(fh, offset, reply).await });
+ }
+
+ fn releasedir(
+ &self,
+ _req: &Request,
+ _ino: INodeNo,
+ fh: FileHandle,
+ _flags: OpenFlags,
+ reply: ReplyEmpty,
+ ) {
+ let inner = self.inner.clone();
+ self.inner
+ .spawn(async move { inner.releasedir(fh, reply).await });
+ }
+
+ fn fsyncdir(
+ &self,
+ _req: &Request,
+ _ino: INodeNo,
+ _fh: FileHandle,
+ _datasync: bool,
+ reply: ReplyEmpty,
+ ) {
+ reply.ok();
+ }
+
+ fn statfs(&self, _req: &Request, _ino: INodeNo, reply: ReplyStatfs) {
+ // No local capacity claim is implied by a remote snapshot.
+ reply.statfs(0, 0, 0, 0, 0, 4096, 255, 0);
+ }
+
+ fn setxattr(
+ &self,
+ _req: &Request,
+ _ino: INodeNo,
+ _name: &std::ffi::OsStr,
+ _value: &[u8],
+ _flags: i32,
+ _position: u32,
+ reply: ReplyEmpty,
+ ) {
+ reply.error(fuser::Errno::EROFS);
+ }
+
+ fn getxattr(
+ &self,
+ _req: &Request,
+ _ino: INodeNo,
+ _name: &std::ffi::OsStr,
+ _size: u32,
+ reply: ReplyXattr,
+ ) {
+ reply.error(fuser::Errno::EOPNOTSUPP);
+ }
+
+ fn listxattr(&self, _req: &Request, _ino: INodeNo, _size: u32, reply: ReplyXattr) {
+ reply.error(fuser::Errno::EOPNOTSUPP);
+ }
+
+ fn removexattr(
+ &self,
+ _req: &Request,
+ _ino: INodeNo,
+ _name: &std::ffi::OsStr,
+ reply: ReplyEmpty,
+ ) {
+ reply.error(fuser::Errno::EROFS);
+ }
+
+ fn access(&self, _req: &Request, _ino: INodeNo, mask: AccessFlags, reply: ReplyEmpty) {
+ if mask.contains(AccessFlags::W_OK) {
+ reply.error(fuser::Errno::EROFS);
+ } else {
+ reply.ok();
+ }
+ }
+
+ fn create(
+ &self,
+ _req: &Request,
+ _parent: INodeNo,
+ _name: &std::ffi::OsStr,
+ _mode: u32,
+ _umask: u32,
+ _flags: i32,
+ reply: fuser::ReplyCreate,
+ ) {
+ reply.error(fuser::Errno::EROFS);
+ }
+
+ fn forget(&self, _req: &Request, ino: INodeNo, nlookup: u64) {
+ self.inner.forget(ino, nlookup);
+ }
+
+ fn release(
+ &self,
+ _req: &Request,
+ ino: INodeNo,
+ fh: FileHandle,
+ _flags: OpenFlags,
+ _lock_owner: Option<LockOwner>,
+ _flush: bool,
+ reply: ReplyEmpty,
+ ) {
+ let inner = self.inner.clone();
+ self.inner
+ .spawn(async move { inner.release(ino, fh, reply).await });
+ }
+
+ fn fallocate(
+ &self,
+ _req: &Request,
+ _ino: INodeNo,
+ _fh: FileHandle,
+ _offset: u64,
+ _length: u64,
+ _mode: i32,
+ reply: ReplyEmpty,
+ ) {
+ reply.error(fuser::Errno::EROFS);
+ }
+
+ fn lseek(
+ &self,
+ _req: &Request,
+ _ino: INodeNo,
+ _fh: FileHandle,
+ _offset: i64,
+ _whence: i32,
+ reply: fuser::ReplyLseek,
+ ) {
+ reply.error(fuser::Errno::ENOSYS);
+ }
+}
diff --git a/src/fuse/inode.rs b/src/fuse/inode.rs
new file mode 100644
index 0000000..9ef397b
--- /dev/null
+++ b/src/fuse/inode.rs
@@ -0,0 +1,198 @@
+// 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.
+
+//! Volume-lifetime numeric inode mapping for the Linux FUSE boundary.
+//!
+//! Inode numbers are deterministic functions of the core [`NodeId`], so they
+//! are stable across mounts and restarts. The root is always 1. Identities
+//! with a colliding derivation are rejected instead of aliased; collisions
+//! are astronomically unlikely for 128-bit node identities.
+//!
+//! The map and the cached kind/executable observations live for the whole
+//! mount, mirroring the macOS prototype's identity-map lifetime. Lookup
+//! counters still track kernel references so a later layer can evict entries
+//! without changing the deterministic inode numbers. This module holds no
+//! lock while touching the authority or runtime.
+
+use std::collections::BTreeMap;
+use yinyang_core::NodeId;
+
+/// The FUSE inode reserved for the volume root.
+pub const ROOT_INODE: u64 = 1;
+
+/// Domain separation keeps the derivation independent of content hashes.
+const INODE_DOMAIN: &[u8] = b"yinyang fuse inode v1";
+
+/// Kind-adjacent metadata observed from an authority snapshot.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct CachedInfo {
+ pub directory: bool,
+ pub executable: bool,
+ pub generation: u64,
+}
+
+/// Stable NodeId <-> inode mapping with kernel lookup counters.
+pub struct InodeTable {
+ root: NodeId,
+ by_inode: BTreeMap<u64, NodeId>,
+ by_node: BTreeMap<NodeId, u64>,
+ lookups: BTreeMap<u64, u64>,
+ info: BTreeMap<NodeId, CachedInfo>,
+}
+
+impl InodeTable {
+ pub fn new(root: NodeId) -> Self {
+ Self {
+ root,
+ by_inode: [(ROOT_INODE, root)].into_iter().collect(),
+ by_node: [(root, ROOT_INODE)].into_iter().collect(),
+ lookups: BTreeMap::new(),
+ info: BTreeMap::new(),
+ }
+ }
+
+ /// Resolve or allocate the deterministic inode for a node identity.
+ pub fn inode(&mut self, id: NodeId) -> Result<u64, &'static str> {
+ if let Some(inode) = self.by_node.get(&id) {
+ return Ok(*inode);
+ }
+ let inode = derive(id)?;
+ if let Some(existing) = self.by_inode.get(&inode) {
+ return Err(if *existing == id {
+ "inode already mapped to another identity"
+ } else {
+ "inode collision"
+ });
+ }
+ self.by_inode.insert(inode, id);
+ self.by_node.insert(id, inode);
+ Ok(inode)
+ }
+
+ /// Resolve an inode number to a node identity.
+ pub fn node(&self, inode: u64) -> Option<NodeId> {
+ self.by_inode.get(&inode).copied()
+ }
+
+ /// Remember one successful kernel lookup for an inode.
+ pub fn remember_lookup(&mut self, inode: u64) {
+ let count = self.lookups.entry(inode).or_default().saturating_add(1);
+ self.lookups.insert(inode, count);
+ }
+
+ /// Forget `count` lookups. Mappings are retained for the mount lifetime.
+ pub fn forget(&mut self, inode: u64, count: u64) {
+ let Some(remaining) = self.lookups.get_mut(&inode) else {
+ return;
+ };
+ *remaining = remaining.saturating_sub(count);
+ if *remaining == 0 {
+ self.lookups.remove(&inode);
+ }
+ }
+
+ pub fn lookup_count(&self, inode: u64) -> u64 {
+ self.lookups.get(&inode).copied().unwrap_or(0)
+ }
+
+ /// Cache kind-adjacent metadata observed from a snapshot.
+ pub fn cache(&mut self, id: NodeId, info: CachedInfo) {
+ self.info.insert(id, info);
+ }
+
+ pub fn cached(&self, id: NodeId) -> Option<CachedInfo> {
+ self.info.get(&id).copied()
+ }
+
+ pub fn root(&self) -> NodeId {
+ self.root
+ }
+}
+
+fn derive(id: NodeId) -> Result<u64, &'static str> {
+ let mut hasher = blake3::Hasher::new();
+ hasher.update(INODE_DOMAIN);
+ hasher.update(id.as_bytes());
+ let hash = hasher.finalize();
+ let mut bytes = [0u8; 8];
+ bytes.copy_from_slice(&hash.as_bytes()[..8]);
+ let inode = u64::from_be_bytes(bytes);
+ if inode <= ROOT_INODE {
+ return Err("derived inode collides with the root mapping");
+ }
+ Ok(inode)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn root_is_always_inode_one() {
+ let root = NodeId::generate();
+ let mut table = InodeTable::new(root);
+ assert_eq!(table.inode(root).unwrap(), ROOT_INODE);
+ assert_eq!(table.node(ROOT_INODE), Some(root));
+ }
+
+ #[test]
+ fn derivation_is_stable_and_unique() {
+ let root = NodeId::generate();
+ let mut table = InodeTable::new(root);
+ let ids: Vec<NodeId> = (0..512).map(|_| NodeId::generate()).collect();
+ let first: Vec<u64> = ids.iter().map(|id| table.inode(*id).unwrap()).collect();
+ let mut second = InodeTable::new(root);
+ let repeated: Vec<u64> = ids.iter().map(|id| second.inode(*id).unwrap()).collect();
+ assert_eq!(first, repeated);
+ for (index, inode) in first.iter().enumerate() {
+ assert_ne!(*inode, ROOT_INODE);
+ assert_eq!(second.node(*inode), Some(ids[index]));
+ assert!(!first[..index].contains(inode));
+ }
+ }
+
+ #[test]
+ fn lookup_counters_are_saturating() {
+ let root = NodeId::generate();
+ let mut table = InodeTable::new(root);
+ let id = NodeId::generate();
+ let inode = table.inode(id).unwrap();
+ table.remember_lookup(inode);
+ table.remember_lookup(inode);
+ assert_eq!(table.lookup_count(inode), 2);
+ table.forget(inode, 1);
+ assert_eq!(table.lookup_count(inode), 1);
+ table.forget(inode, 100);
+ assert_eq!(table.lookup_count(inode), 0);
+ assert_eq!(table.node(inode), Some(id));
+ }
+
+ #[test]
+ fn cached_kind_tracks_observations() {
+ let root = NodeId::generate();
+ let mut table = InodeTable::new(root);
+ let id = NodeId::generate();
+ assert_eq!(table.cached(id), None);
+ let info = CachedInfo {
+ directory: false,
+ executable: true,
+ generation: 3,
+ };
+ table.cache(id, info);
+ assert_eq!(table.cached(id), Some(info));
+ }
+}
diff --git a/src/fuse/mod.rs b/src/fuse/mod.rs
new file mode 100644
index 0000000..e4ef3e6
--- /dev/null
+++ b/src/fuse/mod.rs
@@ -0,0 +1,186 @@
+// 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.
+
+//! Linux FUSE mount frontend for Managed read-only volumes.
+//!
+//! The CLI form is `yy --volume CONFIG mount MOUNTPOINT`; the process stays in
+//! the foreground until unmounted. The volume must declare `frontend = "fuse"`
+//! and `read_only = true`; the shared admission rules in
+//! [`crate::volume`] reject every other combination before an authority
+//! connection or staging lease is created.
+//!
+//! Startup takes the staging lease through [`crate::mount::Mount`] and then
+//! refuses to serve a staging database that still holds unpublished, frozen,
+//! conflicted or failed handles: a read-only snapshot view must never surface
+//! those locally staged bytes as if they were remote. Clean observations are
+//! disposable and are reclaimed by the existing Mount recovery.
+//!
+//! The session mounts as `fuse.yinyang` and runs in the foreground. SIGINT and
+//! SIGTERM unmount the session and finish the process; dropping the session
+//! otherwise unmounts as well.
+//!
+//! See `specs/linux-fuse.md` for the full read-only contract.
+
+mod attrs;
+mod frontend;
+mod inode;
+
+use crate::mount::Mount;
+use crate::volume::{Volume, VolumeConfig};
+use fuser::{Config, MountOption, Session, SessionACL};
+use std::path::PathBuf;
+use std::sync::Arc;
+
+/// Mount a validated read-only FUSE volume in the foreground.
+///
+/// `staging` must already be resolved to an absolute path by the CLI.
+pub async fn run(
+ config: VolumeConfig,
+ operator: opendal::Operator,
+ token: Option<String>,
+ mountpoint: PathBuf,
+) -> Result<(), Box<dyn std::error::Error>> {
+ let authority = Volume::connect(&config, operator, token).await?;
+ let mount = Mount::open(authority, &config.staging, true).await?;
+ reject_unpublished_staging(&mount).await?;
+ let snapshot = mount.authority().observe_latest().await?;
+ let root = mount.authority().root();
+ let root_node = snapshot.node(root).await?;
+ if !root_node.is_some_and(|node| node.is_directory()) {
+ return Err(std::io::Error::other(
+ "remote filesystem root is unavailable or not a directory",
+ )
+ .into());
+ }
+ let inner = Arc::new(frontend::Inner::new(
+ mount,
+ tokio::runtime::Handle::current(),
+ ));
+ let filesystem = frontend::FuseFrontend { inner };
+ let mut options = Config::default();
+ options.mount_options = vec![
+ MountOption::RO,
+ MountOption::FSName(format!("yinyang-{}", config.name)),
+ MountOption::Subtype("yinyang".into()),
+ ];
+ options.acl = SessionACL::Owner;
+ let session = Session::new(filesystem, &mountpoint, &options)?;
+ println!(
+ "yy: mounted {} read-only at {} (fuse.yinyang)",
+ config.name,
+ mountpoint.display()
+ );
+ let background = session.spawn()?;
+ shutdown_signal().await;
+ background.umount_and_join()?;
+ println!("yy: unmounted {}", mountpoint.display());
+ Ok(())
+}
+
+/// A read-only snapshot must never expose staged bytes that were not
+/// published. The staging lease is already held, so the check cannot race
+/// another client, and refusing startup changes no remote state.
+async fn reject_unpublished_staging(mount: &Mount) -> Result<(), Box<dyn std::error::Error>> {
+ let status = mount.status().await?;
+ if let Some(handle) = status
+ .handles
+ .iter()
+ .find(|handle| handle.pending || handle.frozen || handle.conflict || handle.error.is_some())
+ {
+ return Err(std::io::Error::other(format!(
+ "staging contains handle {} with unpublished, frozen, conflicted or failed state; \
+ a read-only FUSE mount will not expose it; publish or acknowledge it with the \
+ library frontend before mounting",
+ handle.id
+ ))
+ .into());
+ }
+ Ok(())
+}
+
+/// Wait for SIGINT or SIGTERM, the two signals a foreground mount operator uses
+/// to tear the session down cleanly.
+async fn shutdown_signal() {
+ use tokio::signal::unix::{SignalKind, signal};
+ let mut terminate = match signal(SignalKind::terminate()) {
+ Ok(signal) => signal,
+ Err(_) => {
+ let _ = tokio::signal::ctrl_c().await;
+ return;
+ }
+ };
+ tokio::select! {
+ _ = tokio::signal::ctrl_c() => {}
+ _ = terminate.recv() => {}
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::reject_unpublished_staging;
+ use crate::core::{BackendProfile, Fs};
+ use crate::mount::Mount;
+ use crate::runtime::Runtime;
+ use crate::support;
+ use std::sync::Arc;
+ use yinyang_core::Authority;
+
+ #[tokio::test]
+ async fn read_only_mount_refuses_unpublished_staging() {
+ let temp = tempfile::tempdir().unwrap();
+ let backend = support::TestBackend::default();
+ Fs::create(backend.operator(), BackendProfile::Minio)
+ .await
+ .unwrap();
+ let authority: Arc<dyn Authority> = Arc::new(
+ Fs::open(backend.operator(), BackendProfile::Minio)
+ .await
+ .unwrap(),
+ );
+ let staging = temp.path().join("staging");
+ let runtime = Runtime::open(authority.clone(), &staging).await.unwrap();
+ runtime
+ .create_file(runtime.authority().root(), "dirty")
+ .await
+ .unwrap();
+ let mut handle = runtime.open_file("dirty", true).await.unwrap();
+ handle.write(0, b"unpublished").await.unwrap();
+ drop(handle);
+ drop(runtime);
+ let mount = Mount::open(authority, &staging, true).await.unwrap();
+ let error = reject_unpublished_staging(&mount).await.unwrap_err();
+ assert!(error.to_string().contains("unpublished"));
+ }
+
+ #[tokio::test]
+ async fn read_only_mount_accepts_clean_staging() {
+ let temp = tempfile::tempdir().unwrap();
+ let backend = support::TestBackend::default();
+ Fs::create(backend.operator(), BackendProfile::Minio)
+ .await
+ .unwrap();
+ let authority: Arc<dyn Authority> = Arc::new(
+ Fs::open(backend.operator(), BackendProfile::Minio)
+ .await
+ .unwrap(),
+ );
+ let mount = Mount::open(authority, temp.path().join("staging"), true)
+ .await
+ .unwrap();
+ reject_unpublished_staging(&mount).await.unwrap();
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
index aa12db0..e68fec3 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -20,6 +20,8 @@
//! One-shot publication and restoration of local directories on a Managed filesystem.
mod directory;
+#[cfg(target_os = "linux")]
+pub mod fuse;
pub mod mount;
pub mod runtime;
pub mod sync;
diff --git a/src/main.rs b/src/main.rs
index dc3ba17..1650a71 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -37,6 +37,8 @@ struct Cli {
enum Command {
/// Inspect each capability layer and its effective intersection.
Capabilities,
+ /// Mount a read-only Managed volume through the Linux FUSE frontend.
+ Mount { mountpoint: PathBuf },
/// Operate recoverable file handles (requires --volume).
File {
#[command(subcommand)]
@@ -83,7 +85,10 @@ async fn run(cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
if let Some(path) = &cli.volume {
return file_cli::run(path, cli.command).await;
}
- if matches!(cli.command, Command::File { .. } | Command::Capabilities) {
+ if matches!(
+ cli.command,
+ Command::File { .. } | Command::Capabilities | Command::Mount { .. }
+ ) {
return Err("this command requires --volume CONFIG.json".into());
}
let profile = match std::env::var("YINYANG_STORAGE_PROFILE").as_deref() {