Compare commits

...
Author SHA1 Message Date
nvrl 62cc85cb06 feat(vfs,fuse): a headless adapter, and conformance scenarios run through it and FUSE
Slice 3 of step 5. pdfs_vfs::headless::Headless serves the open-file
and namespace services by path, with no kernel and no Drive. Its host
queues every create in the real store, as the daemon does offline, and
keeps what each close committed in memory. It does itself what the
kernel does before calling the FUSE adapter: path resolution one name
at a time, refusing a taken name on mkdir, and opening an existing file
on create.

pdfs_vfs::conformance (test-support) holds an Adapter trait and ten
scenarios: a file written, resized, synced, closed and reopened; partial
overwrites; reads while open; holes past a grow; create over a file;
folder listings; renames that move and replace; the renames and removals
POSIX refuses; and an unlinked open file. They run through the headless
adapter in pdfs-vfs's unit tests, and through a FUSE mount over the fake
Drive, online and offline, in two new simulations. Both adapters see the
same outcomes.
2026-11-27 15:08:39 +01:00
nvrl 7d963b3dd7 Merge branch 'refactor/vfs-namespace' into refactor/vfs-rename 2026-11-27 14:09:58 +01:00
nvrl 5647b8e684 test(sim,store): print the daemon log when the B302 restore simulation fails
It failed once in CI with only the Drive tree to go on, and does not
reproduce locally. Also put next_run's doc comment back above it: it had
split acquire_single_writer_lock from its own.
2026-11-27 13:47:58 +01:00
nvrl b6ce90fcd5 refactor(vfs,fuse): rename through the namespace service
Namespace::rename now holds what serve_rename did: the cycle and
exchange checks, the replace checks and access gate, the B302 journal
around the victim's removal, the rewrite of a queued create's target
(B142, B70), the choice between the queue and Drive, and the restore of
the victim on failure. Drive calls, the queue and the victim's removal
and restore go through new NamespaceHost methods. The FUSE callback
maps the flags, answers, and drops the kernel's stale entries after a
queued rename.

NamespaceHost::lookup_child now returns None for a missing child, so
the service can tell an absent destination from a failed lookup.
2026-11-27 13:31:29 +01:00
11 changed files with 1909 additions and 433 deletions

No files matched your search

+21 -337
View File
@@ -2,7 +2,7 @@
use super::*;
use pdfs_vfs::files::Files;
use pdfs_vfs::namespace::Namespace;
use pdfs_vfs::namespace::{Namespace, Renamed};
use pdfs_vfs::open::{DirListing, dir_page};
impl Filesystem for ProtonFs {
@@ -1225,308 +1225,31 @@ impl ProtonFs {
flags: RenameFlags,
reply: ReplyEmpty,
) {
if let Err(error) = self
.core
.require_writable(parent)
.and_then(|()| self.core.require_writable(newparent))
let flags = pdfs_vfs::namespace::RenameFlags {
no_replace: flags.contains(RenameFlags::RENAME_NOREPLACE),
exchange: flags.contains(RenameFlags::RENAME_EXCHANGE),
};
match self
.namespace
.rename(parent, name, newparent, newname, flags)
{
reply.error(error);
return;
}
let (ino, mut uid) = match self.core.lookup_child(parent, name) {
Ok(x) => x,
Err(e) => {
reply.error(e);
return;
}
};
// Ancestor cycle check: moving a directory into itself or one of its descendants is forbidden by POSIX (EINVAL).
{
let st = self.core.state();
if let Some(entry) = st.entries.get(&ino)
&& entry.node.is_folder()
&& st.is_ancestor_of(ino, newparent)
{
reply.error(Errno::EINVAL);
return;
}
}
// The destination has to be listed either way: the queued path pushes
// the node into that listing, and the online one drops it to force a
// re-enumeration.
if newparent != parent
&& let Err(e) = self.core.ensure_children(newparent)
{
reply.error(e);
return;
}
let (old_parent_uid, new_parent_uid) = {
let st = self.core.state();
match (st.entries.get(&parent), st.entries.get(&newparent)) {
(Some(old), Some(new)) => (old.uid.clone(), new.uid.clone()),
_ => {
reply.error(Errno::ENOENT);
return;
}
}
};
// `rename(2)` replaces an existing destination; Proton has no replacing
// rename, so the victim has to be removed first and the operation stops
// being atomic. Without this the 422 surfaced as a blanket EIO and every
// write-to-temp-then-rename tool — rsync, atomic editor saves — failed
// at the very end of its transfer (`docs/BUGS.md` B13).
//
// `RENAME_EXCHANGE` has no Proton primitive and cannot be emulated
// without a window in which one of the two names does not exist.
if flags.contains(RenameFlags::RENAME_EXCHANGE) {
reply.error(Errno::EINVAL);
return;
}
let victim = match self.core.lookup_child(newparent, newname) {
// Renaming a node onto its own name is a no-op, never a self-replace.
Ok((_, vuid)) if vuid == uid => None,
Ok(x) => Some(x),
// Nothing to replace: the overwhelmingly common case.
Err(e) if e.code() == libc::ENOENT => None,
Err(e) => {
reply.error(e);
return;
}
};
// Written before the victim is removed and ended when this returns, so
// a stop in between is settled on the next start (`docs/BUGS.md` B302).
let mut _journal: Option<ReplaceJournal> = None;
let replacement_authorized = if let Some((victim_ino, victim_uid)) = &victim {
if flags.contains(RenameFlags::RENAME_NOREPLACE) {
reply.error(Errno::EEXIST);
return;
}
// POSIX requires both ends to agree on being a directory, and the
// check has to happen before anything is trashed: getting it wrong
// turns a refusal into the destruction of the destination.
let (src_dir, dst_dir) = {
let st = self.core.state();
let is_dir = |i: &u64| {
st.entries
.get(i)
.map(|e| matches!(e.node.kind, NodeKind::Folder))
};
match (is_dir(&ino), is_dir(victim_ino)) {
(Some(a), Some(b)) => (a, b),
_ => {
reply.error(Errno::ENOENT);
return;
Ok(Renamed::Done) => reply.ok(),
Ok(Renamed::Queued) => {
// Answer first: the kernel updates its cache while it
// processes the answer, and an invalidation sent before it
// would be overwritten, leaving an empty destination listing.
reply.ok();
if let Some(notifier) = self.core.session.notifier.get() {
let _ = notifier.inval_entry(parent, OsStr::new(name));
let _ = notifier.inval_entry(newparent, OsStr::new(newname));
let _ = notifier.inval_inode(parent);
if newparent != parent {
let _ = notifier.inval_inode(newparent);
}
}
};
// Replacing a directory means trashing it, and Proton trashes a
// folder with its whole subtree — so the destination's emptiness has
// to be known before the decision is made.
let dst_empty = if dst_dir {
if let Err(e) = self.core.ensure_children(*victim_ino) {
reply.error(e);
return;
}
self.core
.state
.lock()
.children
.get(victim_ino)
.is_none_or(|kids| kids.is_empty())
} else {
true
};
if let Err(e) = check_replaceable(src_dir, dst_dir, dst_empty) {
reply.error(e);
return;
}
if let Err(error) = require_rename_access(
|authority| self.core.require_uid_writable(authority),
&uid,
&old_parent_uid,
&new_parent_uid,
) {
reply.error(error);
return;
}
match ReplaceJournal::begin(&self.core.db, &uid, victim_uid, &new_parent_uid, newname) {
Ok(journal) => _journal = Some(journal),
Err(error) => {
error!(%uid, %error, "recording a replacing rename failed; refusing it");
reply.error(Errno::EIO);
return;
}
}
if let Err(e) = self.core.remove_replaced(*victim_ino, victim_uid, newname) {
reply.error(e);
return;
}
true
} else {
false
};
// A node whose own creation is still queued has no server-side identity
// to rename: the queued op *is* the node, so rewriting its target is the
// whole rename. Nothing reaches the API, which is why this works offline.
// A create that lands meanwhile leaves no op to rewrite; the node is
// then renamed by the uid Drive gave it (docs/BUGS.md B142).
if is_local_uid(&uid) {
match self.core.db.rewrite_op_target(
&uid.to_string(),
&new_parent_uid.to_string(),
newname,
) {
Ok(true) => {
self.core
.state()
.rename_in_place(ino, newparent, &new_parent_uid, newname);
// A create that failed on its old name is due again.
self.core.wake_drain();
// Finalize: a transient scratch file (its create parked, bytes
// held back) renamed to a finished name is the moment the
// completed file is meant to reach Drive. Un-park the create so
// the drain uploads it once (docs/BUGS.md B70). Renaming to
// another transient name leaves it parked.
if is_transient_name(name) && !is_transient_name(newname) {
match self.core.db.set_create_hold(&uid.to_string(), false) {
Ok(_) => {
self.core.wake_drain();
debug!(%uid, newname, "un-parked a finalized transient create");
}
Err(e) => {
warn!(%uid, error = %e, "un-parking a finalized transient create failed")
}
}
}
debug!(%uid, newname, "renamed a node whose create is still queued");
reply.ok();
return;
}
Ok(false) => match self.core.landed_row_uid(ino) {
Some(real) => {
debug!(local = %uid, %real, newname, "create landed under a rename");
uid = real;
}
None => {
warn!(%uid, name, newname, "queued create vanished under a rename");
self.core
.restore_replaced(victim.as_ref(), &new_parent_uid, newname);
reply.error(Errno::EBUSY);
return;
}
},
Err(e) => {
error!(%uid, error = %e, "rewriting a queued create's target failed");
self.core
.restore_replaced(victim.as_ref(), &new_parent_uid, newname);
reply.error(Errno::EIO);
return;
}
}
Err(error) => reply.error(namespace_errno(error)),
}
// Offline, or into a folder that does not exist remotely yet: queue the
// rename rather than 404 or fail. Online moves into a real parent still
// take the synchronous path, so a genuine API refusal (permissions, a
// name clash) surfaces to the caller instead of becoming a queued op
// that can only ever conflict.
// The queued rename, as a closure: the network going away under the
// synchronous path below lands here too, with whatever half already
// reached Drive. The op records the end state, so the drain finishes
// the rest.
let queue_it = |reply: ReplyEmpty| {
let queued = if replacement_authorized {
self.core.queue_rename_authorized(
ino,
&uid,
&old_parent_uid,
newparent,
&new_parent_uid,
newname,
)
} else {
self.core.queue_rename(
ino,
&uid,
&old_parent_uid,
newparent,
&new_parent_uid,
newname,
)
};
match queued {
Ok(()) => {
// Send the rename response first. Kernel-side rename cache
// updates happen while processing that response; notifying
// before it lets those updates overwrite our invalidation
// and retain an empty destination readdir page.
reply.ok();
if let Some(notifier) = self.core.session.notifier.get() {
let _ = notifier.inval_entry(parent, OsStr::new(&name));
let _ = notifier.inval_entry(newparent, OsStr::new(&newname));
let _ = notifier.inval_inode(parent);
if newparent != parent {
let _ = notifier.inval_inode(newparent);
}
}
}
Err(e) => {
self.core
.restore_replaced(victim.as_ref(), &new_parent_uid, newname);
reply.error(e);
}
}
};
if rename_needs_queue(
self.core.sends_inline(),
is_local_uid(&new_parent_uid),
newparent != parent,
newname != name,
) {
queue_it(reply);
return;
}
// A failure past this point has already trashed any node the rename was
// replacing, so put it back rather than leaving the caller with neither
// the source moved nor the destination intact.
if let Err(error) = require_rename_access(
|authority| self.core.require_uid_writable(authority),
&uid,
&old_parent_uid,
&new_parent_uid,
) {
self.core
.restore_replaced(victim.as_ref(), &new_parent_uid, newname);
reply.error(error);
return;
}
// A move that also renames is one request, so the name only has to be
// free in the destination, and the reply never stands for half of it.
let renamed = if newparent != parent {
let target = (newname != name).then_some(newname);
self.core.move_rename_remote(&uid, &new_parent_uid, target)
} else if newname != name {
self.core.rename_remote(&uid, newname)
} else {
Ok(())
};
if let Err(e) = renamed {
if self.core.lost_link(&e, "rename") {
queue_it(reply);
return;
}
error!(%uid, error = %e, "rename failed");
self.core
.restore_replaced(victim.as_ref(), &new_parent_uid, newname);
reply.error(Errno::EIO);
return;
}
// Through the guard, so the database has both folders unlisted before
// the reply. The next lookup rebuilds a folder still marked listed from
// the database, which did not have the move yet (docs/BUGS.md B135).
self.core
.state()
.relocate(ino, parent, newparent, &new_parent_uid, newname);
reply.ok();
}
/// Answer with an inode's current attributes, or `ENOENT` if it went away
@@ -1621,42 +1344,3 @@ impl ProtonFs {
}
}
}
/// A replacing rename's journal entry, ended when the rename returns, however
/// it returns. Only a stop leaves it behind, and that is what it is for.
struct ReplaceJournal {
db: Arc<Db>,
source: String,
}
impl ReplaceJournal {
fn begin(
db: &Arc<Db>,
source: &NodeUid,
victim: &NodeUid,
new_parent: &NodeUid,
new_name: &str,
) -> pdfs_core::Result<Self> {
let source = source.to_string();
db.begin_replace(&pdfs_store::db::ReplaceIntent {
source_uid: source.clone(),
victim_uid: victim.to_string(),
new_parent_uid: new_parent.to_string(),
new_name: new_name.to_owned(),
started_ms: now_millis(),
run: 0,
})?;
Ok(Self {
db: db.clone(),
source,
})
}
}
impl Drop for ReplaceJournal {
fn drop(&mut self) {
if let Err(error) = self.db.end_replace(&self.source) {
warn!(source = %self.source, %error, "ending a replacing rename's journal entry failed");
}
}
}
+91 -51
View File
@@ -361,15 +361,6 @@ fn fuse_name(name: &OsStr) -> Result<String, Errno> {
})
}
/// Whether a `rename` may replace an existing destination, as an errno.
fn check_replaceable(src_dir: bool, dst_dir: bool, dst_empty: bool) -> Result<(), Errno> {
pdfs_vfs::names::check_replaceable(src_dir, dst_dir, dst_empty).map_err(|error| match error {
pdfs_vfs::names::ReplaceError::IsDirectory => Errno::EISDIR,
pdfs_vfs::names::ReplaceError::NotDirectory => Errno::ENOTDIR,
pdfs_vfs::names::ReplaceError::NotEmpty => Errno::ENOTEMPTY,
})
}
/// The errno the kernel gets for an operation the open-file service refused.
fn file_errno(error: pdfs_vfs::files::FileError<Errno>) -> Errno {
use pdfs_vfs::files::FileError;
@@ -445,6 +436,9 @@ fn namespace_errno(error: pdfs_vfs::namespace::NamespaceError<Errno>) -> Errno {
NamespaceError::IsDirectory => Errno::EISDIR,
NamespaceError::NotDirectory => Errno::ENOTDIR,
NamespaceError::NotEmpty => Errno::ENOTEMPTY,
NamespaceError::InvalidArgument => Errno::EINVAL,
NamespaceError::Exists => Errno::EEXIST,
NamespaceError::Busy => Errno::EBUSY,
NamespaceError::Io => Errno::EIO,
NamespaceError::Host(errno) => errno,
}
@@ -465,8 +459,12 @@ impl pdfs_vfs::namespace::NamespaceHost for Core {
Core::ensure_children(self, ino)
}
fn lookup_child(&self, parent: u64, name: &str) -> Result<(u64, NodeUid), Errno> {
Core::lookup_child(self, parent, name)
fn lookup_child(&self, parent: u64, name: &str) -> Result<Option<(u64, NodeUid)>, Errno> {
match Core::lookup_child(self, parent, name) {
Ok(found) => Ok(Some(found)),
Err(e) if e == Errno::ENOENT => Ok(None),
Err(e) => Err(e),
}
}
fn sends_inline(&self) -> bool {
@@ -550,6 +548,71 @@ impl pdfs_vfs::namespace::NamespaceHost for Core {
}
}
fn remove_replaced(&self, ino: u64, uid: &NodeUid, name: &str) -> Result<(), Errno> {
Core::remove_replaced(self, ino, uid, name)
}
fn restore_replaced(&self, victim: Option<&(u64, NodeUid)>, parent: &NodeUid, name: &str) {
Core::restore_replaced(self, victim, parent, name);
}
fn queue_rename(
&self,
ino: u64,
uid: &NodeUid,
old_parent_uid: &NodeUid,
new_parent_ino: u64,
new_parent_uid: &NodeUid,
new_name: &str,
authorized: bool,
) -> Result<(), Errno> {
if authorized {
self.queue_rename_authorized(
ino,
uid,
old_parent_uid,
new_parent_ino,
new_parent_uid,
new_name,
)
} else {
Core::queue_rename(
self,
ino,
uid,
old_parent_uid,
new_parent_ino,
new_parent_uid,
new_name,
)
}
}
fn rename_remote(
&self,
uid: &NodeUid,
new_parent: Option<&NodeUid>,
new_name: Option<&str>,
) -> Result<bool, Errno> {
let renamed = match (new_parent, new_name) {
(Some(parent), name) => self.move_rename_remote(uid, parent, name),
(None, Some(name)) => Core::rename_remote(self, uid, name),
(None, None) => Ok(()),
};
match renamed {
Ok(()) => Ok(true),
Err(e) if self.lost_link(&e, "rename") => Ok(false),
Err(e) => {
error!(%uid, error = %e, "rename failed");
Err(Errno::EIO)
}
}
}
fn wake_drain(&self) {
Core::wake_drain(self);
}
fn trashed(&self, uid: &NodeUid, name: &str, open: bool) {
if !open {
self.evict_reader(uid);
@@ -1960,20 +2023,6 @@ fn count_noun(n: usize, one: &str, many: &str) -> String {
format!("{n} {}", if n == 1 { one } else { many })
}
/// Whether a rename must be represented as a durable desired end state.
/// Local-first, offline, or into a not-yet-uploaded directory, the API is not
/// called in the syscall. Only remote-to-remote renames sent inline
/// ([`Core::sends_inline`]) stay synchronous, so a successful kernel reply means
/// the remote namespace has already reached the same end state.
fn rename_needs_queue(
inline: bool,
destination_is_local: bool,
_parent_changed: bool,
_name_changed: bool,
) -> bool {
!inline || destination_is_local
}
/// Bytes rendered with a binary unit and one decimal place (e.g. `"1.2 GB"`),
/// for the activity log. Uses 1024-based steps but the shorter SI labels.
fn human_bytes(bytes: u64) -> String {
@@ -2098,9 +2147,9 @@ mod tests {
copy_pending_for_truncate, fuse_name, is_stale_mount, node_visible, off_the_runtime,
orphan_past_retention, prepare_shared_roots, preserve_on_access_denied,
publish_virtual_root_in_listing, reconcile_virtual_root_in_listing,
release_can_discard_unlinked, release_must_retain_queued_trash, rename_needs_queue,
require_node_parent_access, require_rename_access, resolve_anywhere_with,
shared_with_me_uid, uid_write_authority, virtual_node,
release_can_discard_unlinked, release_must_retain_queued_trash, require_node_parent_access,
require_rename_access, resolve_anywhere_with, shared_with_me_uid, uid_write_authority,
virtual_node,
};
use super::{Db, WriteAuthority};
use std::time::Duration;
@@ -3084,20 +3133,6 @@ mod tests {
assert_ne!(pending.meta.authored, vec![(0, pending.meta.len)]);
}
#[test]
fn online_combined_cross_directory_rename_stays_synchronous() {
assert!(!rename_needs_queue(true, false, true, true));
assert!(rename_needs_queue(false, false, false, true));
assert!(rename_needs_queue(true, true, true, false));
}
#[test]
fn one_step_online_namespace_changes_stay_synchronous() {
assert!(!rename_needs_queue(true, false, false, true));
assert!(!rename_needs_queue(true, false, true, false));
assert!(!rename_needs_queue(true, false, false, false));
}
#[test]
fn fuse_names_enforce_linux_component_limits() {
use std::ffi::OsStr;
@@ -3443,11 +3478,13 @@ mod tests {
assert_before(function, gate, remote_call);
}
let filesystem = include_str!("filesystem.rs");
let rename = function_source(filesystem, "fn serve_rename(");
assert_before(rename, "require_rename_access", "remove_replaced");
assert_before(rename, "remove_replaced", "queue_rename_authorized");
assert_before(rename, "require_rename_access", "rename_remote");
let rename = function_source(namespace, "pub fn rename(");
assert_before(rename, "self.authorize_replace(", "remove_replaced");
assert_before(rename, "remove_replaced", "self.host.queue_rename(");
assert_before(rename, "self.require_rename_access(", ".rename_remote(");
let authorize = function_source(namespace, "fn authorize_replace(");
assert_before(authorize, "check_replaceable", "require_rename_access");
assert_before(authorize, "require_rename_access", "ReplaceJournal::begin");
let control_mkdir = function_source(source, "fn create_folder(");
assert_before(
control_mkdir,
@@ -3834,10 +3871,13 @@ mod tests {
// Through the raw lock, the move stayed in the state's outbox, and the
// next lookup rebuilt the destination from a database without it
// (B135).
let rename: String = function_source(include_str!("filesystem.rs"), "fn serve_rename(")
.split_whitespace()
.collect();
assert!(rename.contains("self.core.state().relocate("));
let rename: String = function_source(
include_str!("../../pdfs-vfs/src/namespace.rs"),
"pub fn rename(",
)
.split_whitespace()
.collect();
assert!(rename.contains("self.state().relocate("));
assert!(!rename.contains(".lock().relocate("));
}
+130
View File
@@ -0,0 +1,130 @@
//! The mounted-files conformance scenarios (`pdfs_vfs::conformance`) run
//! through the FUSE adapter: a daemon mounted over the fake Drive, driven with
//! ordinary file system calls. The headless adapter runs the same scenarios
//! in `pdfs-vfs`, and both have to see the same outcomes.
use std::fs::{File, OpenOptions};
use std::os::unix::fs::FileExt;
use std::path::PathBuf;
use pdfs_vfs::conformance::Adapter;
use pdfs_vfs::headless::Failure;
/// A mount, addressed by paths relative to its root.
pub(crate) struct Mounted(pub(crate) PathBuf);
fn failure(error: std::io::Error) -> Failure {
error
.raw_os_error()
.map_or(Failure::Io, Failure::from_errno)
}
impl Adapter for Mounted {
type Fd = File;
fn create(&self, path: &str) -> Result<File, Failure> {
File::create(self.0.join(path)).map_err(failure)
}
fn open_write(&self, path: &str) -> Result<File, Failure> {
OpenOptions::new()
.write(true)
.open(self.0.join(path))
.map_err(failure)
}
fn write(&self, fd: &File, offset: u64, data: &[u8]) -> Result<(), Failure> {
fd.write_all_at(data, offset).map_err(failure)
}
fn set_len(&self, fd: &File, size: u64) -> Result<(), Failure> {
fd.set_len(size).map_err(failure)
}
fn fsync(&self, fd: &File) -> Result<(), Failure> {
fd.sync_all().map_err(failure)
}
fn close(&self, fd: File) -> Result<(), Failure> {
// `close(2)`'s own error is the flush's, which `File` drops; flush
// first so a failure is seen.
fd.sync_data().map_err(failure)?;
drop(fd);
Ok(())
}
fn read(&self, path: &str) -> Result<Vec<u8>, Failure> {
std::fs::read(self.0.join(path)).map_err(failure)
}
fn mkdir(&self, path: &str) -> Result<(), Failure> {
std::fs::create_dir(self.0.join(path)).map_err(failure)
}
fn unlink(&self, path: &str) -> Result<(), Failure> {
std::fs::remove_file(self.0.join(path)).map_err(failure)
}
fn rmdir(&self, path: &str) -> Result<(), Failure> {
std::fs::remove_dir(self.0.join(path)).map_err(failure)
}
fn rename(&self, from: &str, to: &str) -> Result<(), Failure> {
std::fs::rename(self.0.join(from), self.0.join(to)).map_err(failure)
}
fn list(&self, path: &str) -> Result<Vec<String>, Failure> {
let mut names = std::fs::read_dir(self.0.join(path))
.map_err(failure)?
.map(|entry| {
entry
.map(|entry| entry.file_name().to_string_lossy().into_owned())
.map_err(failure)
})
.collect::<Result<Vec<_>, _>>()?;
names.sort();
Ok(names)
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::*;
use crate::mount::MountOutcome;
use crate::sim::daemon::{Daemon, scratch, wait_until};
use crate::sim::fake_drive::{FakeDrive, Faults};
fn run_through_a_mount(label: &str, online: bool) {
let drive = FakeDrive::new();
let dir = scratch(label);
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
daemon.client.set_online(online);
let mount = Mounted(daemon.mountpoint.clone());
mount.mkdir("conformance").unwrap();
let failed = pdfs_vfs::conformance::run(&mount, "conformance");
daemon.client.set_online(true);
// Whatever the scenarios queued drains before the daemon stops, so the
// stop does not race an upload.
let drained = wait_until(Duration::from_secs(60), || {
daemon.pending().is_ok_and(|items| items.is_empty())
});
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
assert!(failed.is_empty(), "{failed:#?}");
assert!(drained, "the queue did not drain");
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn the_mount_passes_every_conformance_scenario_online() {
run_through_a_mount("conformance-online", true);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn the_mount_passes_every_conformance_scenario_offline() {
run_through_a_mount("conformance-offline", false);
}
}
+5 -2
View File
@@ -4567,6 +4567,8 @@ mod tests {
fn a_replace_cut_off_after_its_trash_brings_the_replaced_file_back() {
let drive = FakeDrive::new();
let dir = scratch("replace-cut-trash");
// Only this test's daemons in the log a failure prints.
take_logged();
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
std::fs::write(daemon.mountpoint.join("report.odt"), b"old").unwrap();
std::fs::write(daemon.mountpoint.join("report.odt.tmp"), b"new").unwrap();
@@ -4590,8 +4592,9 @@ mod tests {
wait_until(Duration::from_secs(30), || {
drive.tree().get("report.odt") == Some(&Entry::File(Arc::new(b"old".to_vec())))
}),
"the replaced file came back: {:?}",
drive.tree()
"the replaced file came back: {:?}\n{}",
drive.tree(),
take_logged().join("\n")
);
assert!(drive.tree().contains_key("report.odt.tmp"));
assert!(wait_until(Duration::from_secs(30), || {
+1
View File
@@ -1,6 +1,7 @@
//! The simulation tests of `docs/TESTING.md`: a fake Drive with
//! the faults the real one has, and the tools to drive daemons against it.
pub(crate) mod conformance;
pub(crate) mod daemon;
pub(crate) use pdfs_drive::sim::fake_drive;
pub(crate) mod model;
+19 -19
View File
@@ -438,25 +438,6 @@ fn is_in_memory(path: &Path) -> bool {
p == ":memory:" || p.is_empty()
}
/// Take the single-instance write lock for the database at `path`.
///
/// The daemon is the only writer by design — the front-ends go through the
/// control socket — but nothing stopped a hand-run `pdfs mount` from starting
/// alongside the systemd unit, at which point two processes own the same inode
/// space, the same content cache, and the same drain queue. SQLite's own
/// locking makes each *statement* safe and does nothing about that.
///
/// `flock` on a sibling `.lock` file rather than on the database itself:
/// SQLite uses POSIX record locks, so the two never interact, and a lock file
/// left behind carries no state — the lock lives in the kernel and dies with
/// the process, however it exits.
///
/// A refusal is retried for [`LOCK_RETRY`] before it counts as another
/// daemon. A child this process spawns holds a copy of every descriptor from
/// its fork until its exec closes them, and `flock` belongs to the open file,
/// not the descriptor. So a lock the process has just let go of can stay held
/// for that moment, and a reopen right after a drop is refused
/// (`docs/BUGS.md` B290).
/// A value no other opening of a database has used: the time in nanoseconds,
/// made unique within this process by a counter.
fn next_run() -> u64 {
@@ -476,6 +457,25 @@ fn next_run() -> u64 {
}
}
/// Take the single-instance write lock for the database at `path`.
///
/// The daemon is the only writer by design — the front-ends go through the
/// control socket — but nothing stopped a hand-run `pdfs mount` from starting
/// alongside the systemd unit, at which point two processes own the same inode
/// space, the same content cache, and the same drain queue. SQLite's own
/// locking makes each *statement* safe and does nothing about that.
///
/// `flock` on a sibling `.lock` file rather than on the database itself:
/// SQLite uses POSIX record locks, so the two never interact, and a lock file
/// left behind carries no state — the lock lives in the kernel and dies with
/// the process, however it exits.
///
/// A refusal is retried for [`LOCK_RETRY`] before it counts as another
/// daemon. A child this process spawns holds a copy of every descriptor from
/// its fork until its exec closes them, and `flock` belongs to the open file,
/// not the descriptor. So a lock the process has just let go of can stay held
/// for that moment, and a reopen right after a drop is refused
/// (`docs/BUGS.md` B290).
fn acquire_single_writer_lock(path: &Path) -> Result<Option<File>> {
if is_in_memory(path) {
return Ok(None);
+330
View File
@@ -0,0 +1,330 @@
//! Scenarios every adapter of the mounted-files service has to pass the same
//! way: what a file holds after it is written, resized, synced, closed and
//! opened again, and what create, mkdir, unlink, rmdir and rename do with
//! names.
//!
//! [`run`] takes an [`Adapter`] and a folder to work in. The headless adapter
//! runs them in this crate's tests; `pdfs-fuse` runs them through a mount. A
//! scenario reports what it saw instead of panicking, so one run lists every
//! difference.
use crate::headless::{Failure, Fd, Headless};
/// File and folder operations by path, relative to the adapter's root.
pub trait Adapter {
/// A file open for writing.
type Fd;
/// Create the file, or empty it when it exists, and open it for writing.
fn create(&self, path: &str) -> Result<Self::Fd, Failure>;
fn open_write(&self, path: &str) -> Result<Self::Fd, Failure>;
fn write(&self, fd: &Self::Fd, offset: u64, data: &[u8]) -> Result<(), Failure>;
fn set_len(&self, fd: &Self::Fd, size: u64) -> Result<(), Failure>;
fn fsync(&self, fd: &Self::Fd) -> Result<(), Failure>;
fn close(&self, fd: Self::Fd) -> Result<(), Failure>;
/// The whole content of the file.
fn read(&self, path: &str) -> Result<Vec<u8>, Failure>;
fn mkdir(&self, path: &str) -> Result<(), Failure>;
fn unlink(&self, path: &str) -> Result<(), Failure>;
fn rmdir(&self, path: &str) -> Result<(), Failure>;
fn rename(&self, from: &str, to: &str) -> Result<(), Failure>;
/// The names in the folder, sorted.
fn list(&self, path: &str) -> Result<Vec<String>, Failure>;
}
impl Adapter for Headless {
type Fd = Fd;
fn create(&self, path: &str) -> Result<Fd, Failure> {
Headless::create(self, path)
}
fn open_write(&self, path: &str) -> Result<Fd, Failure> {
Headless::open_write(self, path)
}
fn write(&self, fd: &Fd, offset: u64, data: &[u8]) -> Result<(), Failure> {
Headless::write(self, fd, offset, data)
}
fn set_len(&self, fd: &Fd, size: u64) -> Result<(), Failure> {
Headless::set_len(self, fd, size)
}
fn fsync(&self, fd: &Fd) -> Result<(), Failure> {
Headless::fsync(self, fd)
}
fn close(&self, fd: Fd) -> Result<(), Failure> {
Headless::close(self, fd)
}
fn read(&self, path: &str) -> Result<Vec<u8>, Failure> {
Headless::read(self, path)
}
fn mkdir(&self, path: &str) -> Result<(), Failure> {
Headless::mkdir(self, path)
}
fn unlink(&self, path: &str) -> Result<(), Failure> {
Headless::unlink(self, path)
}
fn rmdir(&self, path: &str) -> Result<(), Failure> {
Headless::rmdir(self, path)
}
fn rename(&self, from: &str, to: &str) -> Result<(), Failure> {
Headless::rename(self, from, to)
}
fn list(&self, path: &str) -> Result<Vec<String>, Failure> {
Headless::list(self, path)
}
}
/// What a scenario saw that it should not have.
pub type Outcome = Result<(), String>;
/// A scenario, run in a folder of its own.
pub type Scenario<A> = fn(&A, &Dir) -> Outcome;
/// The folder a scenario works in.
pub struct Dir(String);
impl Dir {
/// The path of `name` in this folder.
pub fn at(&self, name: &str) -> String {
format!("{}/{name}", self.0)
}
pub fn path(&self) -> &str {
&self.0
}
}
/// Every scenario, by name.
pub fn scenarios<A: Adapter>() -> Vec<(&'static str, Scenario<A>)> {
vec![
("a_reopened_file_has_what_was_written", reopened_file::<A>),
("a_partial_overwrite_keeps_the_rest", partial_overwrite::<A>),
("a_read_while_open_sees_the_writes", read_while_open::<A>),
(
"a_hole_past_a_grow_reads_as_zeros",
hole_reads_as_zeros::<A>,
),
("a_create_over_a_file_empties_it", create_empties::<A>),
("folders_list_their_children", folders_list::<A>),
("a_rename_moves_and_replaces", rename_replaces::<A>),
("a_rename_refuses_what_posix_refuses", rename_refusals::<A>),
("removing_follows_posix", remove_rules::<A>),
(
"an_unlinked_open_file_does_not_come_back",
unlinked_open::<A>,
),
]
}
/// Run every scenario in its own folder under `base`, which must exist. The
/// result names each scenario that failed and why.
pub fn run<A: Adapter>(adapter: &A, base: &str) -> Vec<(&'static str, String)> {
let mut failed = Vec::new();
for (name, scenario) in scenarios::<A>() {
let dir = Dir(format!("{base}/{name}"));
let outcome = adapter
.mkdir(dir.path())
.map_err(|e| format!("mkdir {}: {e:?}", dir.path()))
.and_then(|()| scenario(adapter, &dir));
if let Err(why) = outcome {
failed.push((name, why));
}
}
failed
}
/// `Err` naming `what` unless `got` is `want`.
fn expect<T: PartialEq + std::fmt::Debug>(what: &str, got: T, want: T) -> Outcome {
if got == want {
Ok(())
} else {
Err(format!("{what}: got {got:?}, want {want:?}"))
}
}
/// The `Ok` of `result`, or `Err` naming `what`.
fn ok<T>(what: &str, result: Result<T, Failure>) -> Result<T, String> {
result.map_err(|e| format!("{what}: {e:?}"))
}
fn write_file<A: Adapter>(a: &A, path: &str, bytes: &[u8]) -> Outcome {
let fd = ok(&format!("create {path}"), a.create(path))?;
ok(&format!("write {path}"), a.write(&fd, 0, bytes))?;
ok(&format!("close {path}"), a.close(fd))
}
/// Written, resized, synced, closed and opened again: the bytes are what the
/// handle left, and a second handle adds to them.
fn reopened_file<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.txt");
let fd = ok("create", a.create(&f))?;
ok("write", a.write(&fd, 0, b"hello world"))?;
ok("set_len", a.set_len(&fd, 5))?;
ok("fsync", a.fsync(&fd))?;
ok("close", a.close(fd))?;
expect("after close", a.read(&f), Ok(b"hello".to_vec()))?;
let fd = ok("reopen", a.open_write(&f))?;
ok("append", a.write(&fd, 5, b" again"))?;
ok("close again", a.close(fd))?;
expect("after reopen", a.read(&f), Ok(b"hello again".to_vec()))
}
fn partial_overwrite<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.txt");
write_file(a, &f, b"abcdef")?;
let fd = ok("reopen", a.open_write(&f))?;
ok("overwrite", a.write(&fd, 2, b"XY"))?;
ok("close", a.close(fd))?;
expect("content", a.read(&f), Ok(b"abXYef".to_vec()))
}
fn read_while_open<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.txt");
let fd = ok("create", a.create(&f))?;
ok("write", a.write(&fd, 0, b"draft"))?;
let seen = a.read(&f);
ok("close", a.close(fd))?;
expect("while open", seen, Ok(b"draft".to_vec()))
}
fn hole_reads_as_zeros<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.bin");
let fd = ok("create", a.create(&f))?;
ok("write", a.write(&fd, 0, b"ab"))?;
ok("grow", a.set_len(&fd, 4))?;
ok("write past the end", a.write(&fd, 6, b"z"))?;
ok("close", a.close(fd))?;
expect("content", a.read(&f), Ok(b"ab\0\0\0\0z".to_vec()))
}
fn create_empties<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.txt");
write_file(a, &f, b"old content")?;
write_file(a, &f, b"new")?;
expect("content", a.read(&f), Ok(b"new".to_vec()))
}
fn folders_list<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let sub = d.at("sub");
ok("mkdir", a.mkdir(&sub))?;
expect("mkdir again", a.mkdir(&sub), Err(Failure::Exists))?;
write_file(a, &format!("{sub}/b.txt"), b"b")?;
write_file(a, &format!("{sub}/a.txt"), b"a")?;
expect(
"listing",
a.list(&sub),
Ok(vec!["a.txt".to_owned(), "b.txt".to_owned()]),
)?;
expect(
"parent listing",
a.list(d.path()),
Ok(vec!["sub".to_owned()]),
)?;
expect(
"mkdir under a file",
a.mkdir(&format!("{sub}/a.txt/x")),
Err(Failure::NotDirectory),
)
}
fn rename_replaces<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let (from, to) = (d.at("a.txt"), d.at("b.txt"));
write_file(a, &from, b"A")?;
write_file(a, &to, b"B")?;
ok("rename over", a.rename(&from, &to))?;
expect("destination", a.read(&to), Ok(b"A".to_vec()))?;
expect("source", a.read(&from), Err(Failure::NotFound))?;
ok("mkdir", a.mkdir(&d.at("sub")))?;
ok("move", a.rename(&to, &d.at("sub/c.txt")))?;
expect("moved", a.read(&d.at("sub/c.txt")), Ok(b"A".to_vec()))?;
expect("listing", a.list(d.path()), Ok(vec!["sub".to_owned()]))
}
fn rename_refusals<A: Adapter>(a: &A, d: &Dir) -> Outcome {
ok("mkdir", a.mkdir(&d.at("dir")))?;
ok("mkdir inner", a.mkdir(&d.at("dir/inner")))?;
ok("mkdir full", a.mkdir(&d.at("full")))?;
write_file(a, &d.at("full/x"), b"x")?;
write_file(a, &d.at("f.txt"), b"f")?;
expect(
"folder into itself",
a.rename(&d.at("dir"), &d.at("dir/inner/dir")),
Err(Failure::InvalidArgument),
)?;
expect(
"file over folder",
a.rename(&d.at("f.txt"), &d.at("dir")),
Err(Failure::IsDirectory),
)?;
expect(
"folder over file",
a.rename(&d.at("dir"), &d.at("f.txt")),
Err(Failure::NotDirectory),
)?;
expect(
"folder over a full folder",
a.rename(&d.at("dir"), &d.at("full")),
Err(Failure::NotEmpty),
)?;
expect(
"missing source",
a.rename(&d.at("nothing"), &d.at("g.txt")),
Err(Failure::NotFound),
)?;
expect("file kept", a.read(&d.at("f.txt")), Ok(b"f".to_vec()))?;
expect("full kept", a.list(&d.at("full")), Ok(vec!["x".to_owned()]))
}
fn remove_rules<A: Adapter>(a: &A, d: &Dir) -> Outcome {
ok("mkdir", a.mkdir(&d.at("dir")))?;
write_file(a, &d.at("dir/f"), b"f")?;
expect(
"unlink a folder",
a.unlink(&d.at("dir")),
Err(Failure::IsDirectory),
)?;
expect(
"rmdir a file",
a.rmdir(&d.at("dir/f")),
Err(Failure::NotDirectory),
)?;
expect(
"rmdir a full folder",
a.rmdir(&d.at("dir")),
Err(Failure::NotEmpty),
)?;
expect(
"unlink nothing",
a.unlink(&d.at("nothing")),
Err(Failure::NotFound),
)?;
ok("unlink", a.unlink(&d.at("dir/f")))?;
ok("rmdir", a.rmdir(&d.at("dir")))?;
expect("listing", a.list(d.path()), Ok(Vec::new()))
}
fn unlinked_open<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.txt");
let fd = ok("create", a.create(&f))?;
ok("write", a.write(&fd, 0, b"doomed"))?;
ok("unlink", a.unlink(&f))?;
ok("write after unlink", a.write(&fd, 6, b" still"))?;
ok("close", a.close(fd))?;
expect("read", a.read(&f), Err(Failure::NotFound))?;
expect("listing", a.list(d.path()), Ok(Vec::new()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_headless_adapter_passes_every_scenario() {
let dir = std::env::temp_dir().join(format!("pdfs-headless-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let headless = Headless::open(&dir).unwrap();
headless.mkdir("conformance").unwrap();
let failed = run(&headless, "conformance");
let _ = std::fs::remove_dir_all(&dir);
assert!(failed.is_empty(), "{failed:#?}");
}
}
+629
View File
@@ -0,0 +1,629 @@
//! A second adapter over the mounted-files service, with no kernel: files and
//! folders addressed by path, served by [`Files`] and [`Namespace`].
//!
//! It exists to show what the service needs from an adapter, and that nothing
//! of FUSE is left in it. The Linux FUSE adapter in `pdfs-fuse` answers the
//! kernel with what the services return; this one answers a caller with
//! [`Failure`]. The conformance scenarios (`conformance`, with the
//! `test-support` feature) run through both and expect the same outcomes.
//!
//! [`Headless`] has no Drive. Its host queues every create in the real store
//! as the daemon does offline, and nothing drains the queue. The bytes a
//! closed file committed are kept in memory, as the content of its next
//! revision would be.
//!
//! What the kernel does before it calls the FUSE adapter, this adapter does
//! itself: it resolves a path one name at a time, refuses to make a name that
//! is taken, and opens an existing file when asked to create it. The services
//! leave those checks to the adapter.
use std::collections::HashMap;
use std::fs::File;
use std::path::Path;
use std::sync::Arc;
use parking_lot::Mutex;
use pdfs_core::lockrank::{Rank, Ranked};
use pdfs_store::cache::ContentCache;
use pdfs_store::db::{Db, LOCAL_VOLUME, OP_CREATE, OP_MKDIR, PARK_UNTIL, PendingOp};
use proton_drive_rs::Node;
use proton_drive_rs::proton_sdk::ids::{LinkId, NodeUid, VolumeId};
use crate::files::{FileError, Files, FilesHost};
use crate::ids::is_local_uid;
use crate::namespace::{Namespace, NamespaceError, NamespaceHost, RenameFlags};
use crate::nodes::local_node;
use crate::open::{Intervals, ReadFailure, WriteHandle, assemble_open_read};
use crate::tree::{NodeError, State, StateGuard};
use crate::writes::WriteState;
/// Why the headless adapter refused or failed an operation. The FUSE adapter
/// answers each with the errno named here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Failure {
/// `ENOENT`: no such file or folder.
NotFound,
/// `EEXIST`: the name is taken.
Exists,
/// `EISDIR`: a folder where a file was needed.
IsDirectory,
/// `ENOTDIR`: a file where a folder was needed.
NotDirectory,
/// `ENOTEMPTY`: the folder has children.
NotEmpty,
/// `EINVAL`: an operation that cannot be done, such as moving a folder
/// into itself.
InvalidArgument,
/// `EACCES`: the node may not be changed.
Denied,
/// `EBUSY`: try again.
Busy,
/// `EBADF`: no file is open under this handle.
BadHandle,
/// `ENOSPC`: the local disk is full.
NoSpace,
/// `EOPNOTSUPP`: the operation is not supported.
Unsupported,
/// `EIO`: something failed underneath.
Io,
}
impl Failure {
/// The failure an OS error stands for, as the FUSE adapter answers it.
pub fn from_errno(errno: i32) -> Self {
match errno {
libc::ENOENT => Failure::NotFound,
libc::EEXIST => Failure::Exists,
libc::EISDIR => Failure::IsDirectory,
libc::ENOTDIR => Failure::NotDirectory,
libc::ENOTEMPTY => Failure::NotEmpty,
libc::EINVAL => Failure::InvalidArgument,
libc::EACCES | libc::EPERM => Failure::Denied,
libc::EBUSY => Failure::Busy,
libc::EBADF => Failure::BadHandle,
libc::ENOSPC | libc::EDQUOT => Failure::NoSpace,
libc::EOPNOTSUPP => Failure::Unsupported,
_ => Failure::Io,
}
}
}
/// What the headless host fails with.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostError {
NotFound,
Denied,
Io,
}
impl From<HostError> for Failure {
fn from(error: HostError) -> Self {
match error {
HostError::NotFound => Failure::NotFound,
HostError::Denied => Failure::Denied,
HostError::Io => Failure::Io,
}
}
}
impl From<FileError<HostError>> for Failure {
fn from(error: FileError<HostError>) -> Self {
match error {
FileError::NotFound => Failure::NotFound,
FileError::IsDirectory => Failure::IsDirectory,
FileError::Denied => Failure::Denied,
FileError::BadHandle => Failure::BadHandle,
FileError::NoSpace | FileError::QuotaExceeded => Failure::NoSpace,
FileError::Unsupported => Failure::Unsupported,
FileError::Io | FileError::Storage(_) => Failure::Io,
FileError::Host(error) => error.into(),
}
}
}
impl From<NamespaceError<HostError>> for Failure {
fn from(error: NamespaceError<HostError>) -> Self {
match error {
NamespaceError::NotFound => Failure::NotFound,
NamespaceError::IsDirectory => Failure::IsDirectory,
NamespaceError::NotDirectory => Failure::NotDirectory,
NamespaceError::NotEmpty => Failure::NotEmpty,
NamespaceError::InvalidArgument => Failure::InvalidArgument,
NamespaceError::Exists => Failure::Exists,
NamespaceError::Busy => Failure::Busy,
NamespaceError::Io => Failure::Io,
NamespaceError::Host(error) => error.into(),
}
}
}
fn node_failure(error: NodeError) -> HostError {
match error {
NodeError::NotFound => HostError::NotFound,
NodeError::NotWritable => HostError::Denied,
}
}
/// A file open for writing through the headless adapter.
#[derive(Debug)]
pub struct Fd {
ino: u64,
fh: u64,
}
struct Inner {
state: Arc<Ranked<State>>,
db: Arc<Db>,
cache: Arc<ContentCache>,
/// What each file's last close committed: the content its next revision
/// would upload.
content: Mutex<HashMap<NodeUid, Vec<u8>>>,
}
/// The host of the headless adapter: offline, with the real store.
#[derive(Clone)]
struct LocalHost(Arc<Inner>);
impl LocalHost {
fn state(&self) -> StateGuard<'_> {
StateGuard::new(self.0.state.lock(), &self.0.db)
}
fn base(&self, uid: &NodeUid) -> Vec<u8> {
self.0.content.lock().get(uid).cloned().unwrap_or_default()
}
fn drop_ops(&self, uid: &NodeUid) -> Result<(), HostError> {
self.0
.db
.delete_ops_for_uid(&uid.to_string())
.map(drop)
.map_err(|_| HostError::Io)
}
}
/// The bytes `[0, len)` of a file open for writing: what it wrote from
/// `file`, the rest from `base`.
fn assemble(file: &File, len: u64, written: &Intervals, base: &[u8]) -> Result<Vec<u8>, HostError> {
let base_len = base.len() as u64;
let read = assemble_open_read::<()>(file, len, base_len, written, 0, len, |offset, n| {
Ok(Some(base[offset as usize..(offset + n) as usize].to_vec()))
});
match read {
Ok(Some(bytes)) => Ok(bytes),
Ok(None) | Err(ReadFailure::Base(())) | Err(ReadFailure::Scratch(_)) => Err(HostError::Io),
}
}
impl FilesHost for LocalHost {
type Error = HostError;
fn settle_size(&self, _ino: u64, _uid: &NodeUid) -> Option<u64> {
None
}
fn fill_gaps(
&self,
uid: &NodeUid,
file: &File,
len: u64,
_base_mtime: i64,
_base_size: u64,
written: &Intervals,
) -> Result<(), HostError> {
use std::os::unix::fs::FileExt;
let base = self.base(uid);
file.set_len(len).map_err(|_| HostError::Io)?;
for (start, end, authored) in written.segments(0, len) {
let end = end.min(base.len() as u64);
if !authored && start < end {
file.write_all_at(&base[start as usize..end as usize], start)
.map_err(|_| HostError::Io)?;
}
}
Ok(())
}
fn landed(&self, _uid: &NodeUid) -> Option<Node> {
None
}
fn commit(&self, handle: &mut WriteHandle) -> Result<(), HostError> {
let committed = if handle.dirty {
let base = self.base(&handle.uid);
Some(assemble(&handle.file, handle.len, &handle.written, &base)?)
} else {
None
};
self.0.cache.clear_scratch_durable(&handle.path);
let _ = std::fs::remove_file(&handle.path);
if let Some(bytes) = committed {
self.0.content.lock().insert(handle.uid.clone(), bytes);
}
Ok(())
}
fn discard_unlinked(&self, uid: &NodeUid) {
self.0.content.lock().remove(uid);
let _ = self.drop_ops(uid);
}
}
impl NamespaceHost for LocalHost {
type Error = HostError;
fn require_writable(&self, ino: u64) -> Result<(), HostError> {
self.0
.state
.lock()
.require_writable(ino)
.map_err(node_failure)
}
fn require_uid_writable(&self, uid: &NodeUid) -> Result<(), HostError> {
let st = self.0.state.lock();
match st.by_uid.get(uid) {
Some(&ino) => st.require_writable(ino).map_err(node_failure),
None => Err(HostError::Denied),
}
}
fn ensure_children(&self, _ino: u64) -> Result<(), HostError> {
// Every folder is made here and listed from the start.
Ok(())
}
fn lookup_child(&self, parent: u64, name: &str) -> Result<Option<(u64, NodeUid)>, HostError> {
let st = self.0.state.lock();
Ok(st
.children
.get(&parent)
.into_iter()
.flatten()
.filter_map(|ino| st.entries.get(ino).map(|entry| (*ino, entry)))
.find(|(_, entry)| entry.node.name == name)
.map(|(ino, entry)| (ino, entry.uid.clone())))
}
fn sends_inline(&self) -> bool {
false
}
fn mint(
&self,
_parent: &NodeUid,
_name: &str,
_folder: bool,
) -> Result<Option<Node>, HostError> {
Ok(None)
}
fn queue_create(
&self,
parent_uid: &NodeUid,
name: &str,
folder: bool,
parked: bool,
) -> Result<Node, HostError> {
let now = now_secs();
let lid = self
.0
.db
.add_local_row(&parent_uid.to_string(), name, folder, now)
.map_err(|_| HostError::Io)?;
let uid = NodeUid::new(VolumeId::from(LOCAL_VOLUME), LinkId::from(lid.to_string()));
let op = PendingOp {
id: 0,
kind: if folder { OP_MKDIR } else { OP_CREATE }.to_string(),
uid: uid.to_string(),
parent_uid: Some(parent_uid.to_string()),
name: Some(name.to_owned()),
blob_path: None,
meta_json: None,
created_at: now * 1000,
attempts: 0,
last_error: None,
next_attempt_at: if parked { PARK_UNTIL } else { 0 },
};
self.0.db.enqueue_op(&op).map_err(|_| HostError::Io)?;
Ok(local_node(uid, parent_uid.clone(), name.to_owned(), folder))
}
fn access_changed(&self) {}
fn drop_queued(&self, uid: &NodeUid, _keep_staged: bool) -> Result<(), HostError> {
self.drop_ops(uid)
}
fn landed_uid(&self, _ino: u64) -> Option<NodeUid> {
None
}
fn has_pending_moves_out_of(&self, _uid: &NodeUid) -> Result<bool, HostError> {
Ok(false)
}
fn queue_trash(&self, uid: &NodeUid, _name: &str, open: bool) -> Result<(), HostError> {
// Only the root is not made here, and it cannot be removed.
self.state().forget_or_unlink(uid);
if !open {
self.0.content.lock().remove(uid);
}
Ok(())
}
fn trash_remote(&self, _uid: &NodeUid, _name: &str) -> Result<bool, HostError> {
Ok(false)
}
fn remove_replaced(&self, _ino: u64, uid: &NodeUid, _name: &str) -> Result<(), HostError> {
let open = {
let st = self.0.state.lock();
st.by_uid
.get(uid)
.and_then(|ino| st.entries.get(ino))
.is_some_and(|entry| entry.open_count > 0)
};
if is_local_uid(uid) {
self.drop_ops(uid)?;
}
self.state().forget_or_unlink(uid);
if !open {
self.0.content.lock().remove(uid);
}
Ok(())
}
fn restore_replaced(&self, _victim: Option<&(u64, NodeUid)>, _parent: &NodeUid, _name: &str) {}
fn queue_rename(
&self,
ino: u64,
_uid: &NodeUid,
_old_parent_uid: &NodeUid,
new_parent_ino: u64,
new_parent_uid: &NodeUid,
new_name: &str,
_authorized: bool,
) -> Result<(), HostError> {
self.state()
.rename_in_place(ino, new_parent_ino, new_parent_uid, new_name);
Ok(())
}
fn rename_remote(
&self,
_uid: &NodeUid,
_new_parent: Option<&NodeUid>,
_new_name: Option<&str>,
) -> Result<bool, HostError> {
Ok(false)
}
fn wake_drain(&self) {}
fn trashed(&self, _uid: &NodeUid, _name: &str, _open: bool) {}
}
fn now_secs() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i64)
}
/// The mounted-files service of one root, served by path.
pub struct Headless {
host: LocalHost,
files: Files<LocalHost>,
namespace: Namespace<LocalHost>,
root: u64,
}
impl Headless {
/// A new, empty root, with its store and cache in `dir`.
pub fn open(dir: &Path) -> std::io::Result<Self> {
let other = |e: &dyn std::fmt::Display| std::io::Error::other(e.to_string());
std::fs::create_dir_all(dir)?;
let db = Arc::new(Db::open(&dir.join("cache.db")).map_err(|e| other(&e))?);
let cache = Arc::new(
ContentCache::open(dir.join("content"), dir.join("pins"), 0, db.clone())
.map_err(|e| other(&e))?,
);
let state = Arc::new(Ranked::new(
Rank::State,
State::new(db.clone(), HashMap::new()),
));
let root_uid = NodeUid::new(VolumeId::from("headless"), LinkId::from("root"));
let root = {
let mut st = StateGuard::new(state.lock(), &db);
let ino = st.install_root(local_node(root_uid.clone(), root_uid, String::new(), true));
st.children.insert(ino, Vec::new());
ino
};
let host = LocalHost(Arc::new(Inner {
state: state.clone(),
db: db.clone(),
cache: cache.clone(),
content: Mutex::default(),
}));
let writes = WriteState::default();
Ok(Headless {
files: Files::new(
state.clone(),
db.clone(),
cache.clone(),
writes.clone(),
host.clone(),
),
namespace: Namespace::new(state, db, cache, writes, host.clone()),
host,
root,
})
}
/// The inode at `path`, resolved one name at a time from the root.
fn resolve(&self, path: &str) -> Result<u64, Failure> {
let mut ino = self.root;
for name in components(path) {
if !self.is_folder(ino)? {
return Err(Failure::NotDirectory);
}
ino = self
.host
.lookup_child(ino, name)?
.ok_or(Failure::NotFound)?
.0;
}
Ok(ino)
}
/// The folder `path` names a child of, and the child's name.
fn split<'p>(&self, path: &'p str) -> Result<(u64, &'p str), Failure> {
let mut names: Vec<&str> = components(path).collect();
let name = names.pop().ok_or(Failure::InvalidArgument)?;
let parent = self.resolve(&names.join("/"))?;
if !self.is_folder(parent)? {
return Err(Failure::NotDirectory);
}
Ok((parent, name))
}
fn is_folder(&self, ino: u64) -> Result<bool, Failure> {
self.host
.0
.state
.lock()
.entries
.get(&ino)
.map(|entry| entry.node.is_folder())
.ok_or(Failure::NotFound)
}
fn child(&self, parent: u64, name: &str) -> Result<Option<u64>, Failure> {
Ok(self.host.lookup_child(parent, name)?.map(|(ino, _)| ino))
}
/// Create the file at `path`, or empty it when it exists, and open it for
/// writing, as `open(O_CREAT | O_TRUNC)` does.
pub fn create(&self, path: &str) -> Result<Fd, Failure> {
let (parent, name) = self.split(path)?;
if let Some(ino) = self.child(parent, name)? {
let fd = self.open_ino(ino)?;
self.set_len(&fd, 0)?;
return Ok(fd);
}
let made = self.namespace.create(parent, name)?;
Ok(Fd {
ino: made.ino,
fh: made.fh,
})
}
/// Open the file at `path` for writing.
pub fn open_write(&self, path: &str) -> Result<Fd, Failure> {
let ino = self.resolve(path)?;
self.open_ino(ino)
}
fn open_ino(&self, ino: u64) -> Result<Fd, Failure> {
let fh = self.files.open(ino, true)?;
Ok(Fd { ino, fh })
}
pub fn write(&self, fd: &Fd, offset: u64, data: &[u8]) -> Result<(), Failure> {
Ok(self.files.write(fd.ino, fd.fh, offset, data)?)
}
pub fn set_len(&self, fd: &Fd, size: u64) -> Result<(), Failure> {
match self.files.resize(fd.ino, size)? {
true => Ok(()),
false => Err(Failure::BadHandle),
}
}
pub fn fsync(&self, fd: &Fd) -> Result<(), Failure> {
Ok(self.files.fsync(fd.fh)?)
}
pub fn close(&self, fd: Fd) -> Result<(), Failure> {
Ok(self.files.release(fd.ino, fd.fh)?)
}
/// The whole content of the file at `path`: what a handle open on it
/// holds, or else what its last close committed.
pub fn read(&self, path: &str) -> Result<Vec<u8>, Failure> {
let ino = self.resolve(path)?;
let (uid, size, view) = {
let st = self.host.0.state.lock();
let entry = st.entries.get(&ino).ok_or(Failure::NotFound)?;
if entry.node.is_folder() {
return Err(Failure::IsDirectory);
}
(
entry.uid.clone(),
pdfs_drive::node_size(&entry.node),
st.open.writer(ino).map(WriteHandle::read_view),
)
};
let base = self.host.base(&uid);
match view {
Some(view) => Ok(assemble(&view.file, view.len, &view.written, &base)?),
None => {
let mut bytes = base;
bytes.resize(size as usize, 0);
Ok(bytes)
}
}
}
pub fn mkdir(&self, path: &str) -> Result<(), Failure> {
let (parent, name) = self.split(path)?;
if self.child(parent, name)?.is_some() {
return Err(Failure::Exists);
}
self.namespace.mkdir(parent, name)?;
Ok(())
}
pub fn unlink(&self, path: &str) -> Result<(), Failure> {
let (parent, name) = self.split(path)?;
Ok(self.namespace.unlink(parent, name)?)
}
pub fn rmdir(&self, path: &str) -> Result<(), Failure> {
let (parent, name) = self.split(path)?;
Ok(self.namespace.rmdir(parent, name)?)
}
pub fn rename(&self, from: &str, to: &str) -> Result<(), Failure> {
let (parent, name) = self.split(from)?;
let (new_parent, new_name) = self.split(to)?;
self.child(parent, name)?.ok_or(Failure::NotFound)?;
self.namespace
.rename(parent, name, new_parent, new_name, RenameFlags::default())?;
Ok(())
}
/// The names in the folder at `path`, sorted.
pub fn list(&self, path: &str) -> Result<Vec<String>, Failure> {
let ino = self.resolve(path)?;
if !self.is_folder(ino)? {
return Err(Failure::NotDirectory);
}
let st = self.host.0.state.lock();
let mut names: Vec<String> = st
.children
.get(&ino)
.into_iter()
.flatten()
.filter_map(|kid| st.entries.get(kid).map(|entry| entry.node.name.clone()))
.collect();
names.sort();
Ok(names)
}
}
fn components(path: &str) -> impl Iterator<Item = &str> {
path.split('/')
.filter(|name| !name.is_empty() && *name != ".")
}
+9 -1
View File
@@ -14,9 +14,17 @@
//! ([`writes`]); the POSIX rules on names and on what a rename may replace
//! ([`names`]); which nodes a folder lists ([`nodes`]); and two services
//! behind host ports: the open files from open to close ([`files`]), and
//! create, mkdir, unlink and rmdir ([`namespace`]).
//! create, mkdir, unlink, rmdir and rename ([`namespace`]).
//!
//! A second adapter, [`headless`], serves the same services by path with no
//! kernel and no Drive. The scenarios in `conformance` (with the
//! `test-support` feature) run through it here and through a FUSE mount in
//! `pdfs-fuse`, and both have to see the same outcomes.
#[cfg(any(test, feature = "test-support"))]
pub mod conformance;
pub mod files;
pub mod headless;
pub mod ids;
pub mod names;
pub mod namespace;
+660 -18
View File
@@ -16,12 +16,13 @@ use pdfs_core::Access;
use pdfs_core::lockrank::Ranked;
use pdfs_core::syncignore::is_transient_name;
use pdfs_store::cache::ContentCache;
use pdfs_store::db::Db;
use pdfs_store::db::{Db, ReplaceIntent};
use proton_drive_rs::Node;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::{debug, error, warn};
use crate::ids::is_local_uid;
use crate::names::{ReplaceError, check_replaceable};
use crate::open::WriteHandle;
use crate::tree::{State, StateGuard};
use crate::writes::WriteState;
@@ -100,16 +101,25 @@ pub fn settle_from_drive(
/// unchanged.
#[derive(Debug)]
pub enum NamespaceError<E> {
/// The parent folder is not in the tree.
/// The node or its folder is not in the tree.
NotFound,
/// `unlink` named a folder.
/// `unlink` named a folder, or a rename would put a file over one.
IsDirectory,
/// `rmdir` named a file.
/// `rmdir` named a file, or a rename would put a folder over one.
NotDirectory,
/// `rmdir` named a folder that still has children.
/// `rmdir` named a folder that still has children, or a rename would
/// replace one.
NotEmpty,
/// A rename that cannot be done: a folder into its own subtree, or an
/// exchange of two names.
InvalidArgument,
/// A rename that may not replace found its destination taken.
Exists,
/// The queued create of a node went away under its rename: try again.
Busy,
/// Something failed that the service already logged: the scratch file of
/// a new file.
/// a new file, the journal of a replacing rename, or the queued create a
/// rename rewrites.
Io,
/// The host failed, with its own error.
Host(E),
@@ -136,8 +146,9 @@ pub trait NamespaceHost {
/// Make sure the tree holds the children of folder `ino`.
fn ensure_children(&self, ino: u64) -> Result<(), Self::Error>;
/// The child `name` of folder `parent`, as its inode and uid.
fn lookup_child(&self, parent: u64, name: &str) -> Result<(u64, NodeUid), Self::Error>;
/// The child `name` of folder `parent`, as its inode and uid, or `None`
/// when the folder has no such child.
fn lookup_child(&self, parent: u64, name: &str) -> Result<Option<(u64, NodeUid)>, Self::Error>;
/// Whether a change goes to Drive now rather than into the queue.
fn sends_inline(&self) -> bool;
@@ -188,6 +199,42 @@ pub trait NamespaceHost {
/// instead, as the link went down on the way. The host logs a failure.
fn trash_remote(&self, uid: &NodeUid, name: &str) -> Result<bool, Self::Error>;
/// Remove the node `uid` that a rename to `name` replaces: trash it on
/// Drive or queue its trash.
fn remove_replaced(&self, ino: u64, uid: &NodeUid, name: &str) -> Result<(), Self::Error>;
/// Put back the node a failed rename to `name` under `parent` removed.
fn restore_replaced(&self, victim: Option<&(u64, NodeUid)>, parent: &NodeUid, name: &str);
/// Queue the rename of `uid` to `new_name` under `new_parent_uid`.
/// `authorized` says the access to replace a destination was already
/// checked.
#[allow(clippy::too_many_arguments)]
fn queue_rename(
&self,
ino: u64,
uid: &NodeUid,
old_parent_uid: &NodeUid,
new_parent_ino: u64,
new_parent_uid: &NodeUid,
new_name: &str,
authorized: bool,
) -> Result<(), Self::Error>;
/// Move `uid` to `new_parent` and rename it to `new_name` on Drive, in
/// one request; `None` leaves that part as it is. `Ok(false)` asks for
/// the rename to be queued instead, as the link went down on the way. The
/// host logs a failure.
fn rename_remote(
&self,
uid: &NodeUid,
new_parent: Option<&NodeUid>,
new_name: Option<&str>,
) -> Result<bool, Self::Error>;
/// Let the drain look at the queue again.
fn wake_drain(&self);
/// Drive accepted the trash of `uid`, and its queued operations and
/// cached bytes are gone: forget what else the host keeps of it and record
/// the trash. `open` means a handle still has it open, and reads of it
@@ -205,8 +252,79 @@ pub struct Made {
pub access: Access,
}
/// How a rename treats an existing destination.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RenameFlags {
/// Fail with [`NamespaceError::Exists`] instead of replacing it.
pub no_replace: bool,
/// Swap the two names, which Drive cannot do.
pub exchange: bool,
}
/// How a rename ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Renamed {
/// Drive has the new name, or nothing on Drive had to change.
Done,
/// The rename is queued. The kernel's cached entries for both names are
/// stale: drop them after the answer, since the kernel updates its cache
/// while it processes the answer and would overwrite an earlier
/// invalidation.
Queued,
}
/// Whether a rename is queued rather than sent now. Local-first, offline, or
/// into a folder not created on Drive yet, the API is not called in the
/// syscall. Only renames between nodes Drive has, sent inline, stay
/// synchronous, so a successful answer means Drive already has the end state.
pub fn rename_needs_queue(inline: bool, destination_is_local: bool) -> bool {
!inline || destination_is_local
}
/// A replacing rename's journal entry, ended when the rename returns, however
/// it returns. Only a stop leaves it behind, and that is what it is for.
struct ReplaceJournal {
db: Arc<Db>,
source: String,
}
impl ReplaceJournal {
fn begin(
db: &Arc<Db>,
source: &NodeUid,
victim: &NodeUid,
new_parent: &NodeUid,
new_name: &str,
) -> pdfs_core::Result<Self> {
let source = source.to_string();
let started_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64);
db.begin_replace(&ReplaceIntent {
source_uid: source.clone(),
victim_uid: victim.to_string(),
new_parent_uid: new_parent.to_string(),
new_name: new_name.to_owned(),
started_ms,
run: 0,
})?;
Ok(Self {
db: db.clone(),
source,
})
}
}
impl Drop for ReplaceJournal {
fn drop(&mut self) {
if let Err(error) = self.db.end_replace(&self.source) {
warn!(source = %self.source, %error, "ending a replacing rename's journal entry failed");
}
}
}
/// The namespace service of one daemon, shared by every mount: create,
/// mkdir, unlink and rmdir.
/// mkdir, unlink, rmdir and rename.
pub struct Namespace<H> {
state: Arc<Ranked<State>>,
db: Arc<Db>,
@@ -352,7 +470,7 @@ impl<H: NamespaceHost> Namespace<H> {
/// Remove the file `name` from folder `parent`.
pub fn unlink(&self, parent: u64, name: &str) -> Result<(), NamespaceError<H::Error>> {
self.host.require_writable(parent)?;
if let Ok((ino, _)) = self.host.lookup_child(parent, name)
if let Ok(Some((ino, _))) = self.host.lookup_child(parent, name)
&& self
.state
.lock()
@@ -368,7 +486,7 @@ impl<H: NamespaceHost> Namespace<H> {
/// Remove the empty folder `name` from folder `parent`.
pub fn rmdir(&self, parent: u64, name: &str) -> Result<(), NamespaceError<H::Error>> {
self.host.require_writable(parent)?;
if let Ok((ino, _)) = self.host.lookup_child(parent, name) {
if let Ok(Some((ino, _))) = self.host.lookup_child(parent, name) {
if self
.state
.lock()
@@ -389,11 +507,265 @@ impl<H: NamespaceHost> Namespace<H> {
self.trash_child(parent, name)
}
/// Rename the child `name` of folder `parent` to `newname` in folder
/// `newparent`.
///
/// `rename(2)` replaces an existing destination. Drive has no replacing
/// rename, so the victim is removed first and the operation stops being
/// atomic. Without that, Drive's refusal surfaced as an error and every
/// write-to-temp-then-rename tool (rsync, atomic editor saves) failed at
/// the very end of its transfer (`docs/BUGS.md` B13). A journal entry
/// written before the victim is removed, and ended when this returns,
/// lets a stop in between be settled on the next start (B302).
pub fn rename(
&self,
parent: u64,
name: &str,
newparent: u64,
newname: &str,
flags: RenameFlags,
) -> Result<Renamed, NamespaceError<H::Error>> {
self.host.require_writable(parent)?;
self.host.require_writable(newparent)?;
let (ino, mut uid) = self
.host
.lookup_child(parent, name)?
.ok_or(NamespaceError::NotFound)?;
// Moving a folder into itself or one of its descendants is forbidden
// by POSIX.
{
let st = self.state.lock();
if st.entries.get(&ino).is_some_and(|e| e.node.is_folder())
&& st.is_ancestor_of(ino, newparent)
{
return Err(NamespaceError::InvalidArgument);
}
}
// The destination has to be listed either way: the queued path pushes
// the node into that listing, and the online one drops it to force a
// re-enumeration.
if newparent != parent {
self.host.ensure_children(newparent)?;
}
let (old_parent_uid, new_parent_uid) = {
let st = self.state.lock();
match (st.entries.get(&parent), st.entries.get(&newparent)) {
(Some(old), Some(new)) => (old.uid.clone(), new.uid.clone()),
_ => return Err(NamespaceError::NotFound),
}
};
// `RENAME_EXCHANGE` has no Drive primitive and cannot be emulated
// without a window in which one of the two names does not exist.
if flags.exchange {
return Err(NamespaceError::InvalidArgument);
}
let victim = match self.host.lookup_child(newparent, newname)? {
// Renaming a node onto its own name is a no-op, never a
// self-replace.
Some((_, victim_uid)) if victim_uid == uid => None,
found => found,
};
let _journal = match &victim {
Some((victim_ino, victim_uid)) => {
if flags.no_replace {
return Err(NamespaceError::Exists);
}
let journal = self.authorize_replace(
ino,
&uid,
*victim_ino,
victim_uid,
&old_parent_uid,
&new_parent_uid,
newname,
)?;
self.host
.remove_replaced(*victim_ino, victim_uid, newname)?;
Some(journal)
}
None => None,
};
let replacing = victim.is_some();
let restore = || {
self.host
.restore_replaced(victim.as_ref(), &new_parent_uid, newname)
};
// A node whose own creation is still queued has no identity on Drive
// to rename: the queued operation is the node, so rewriting its target
// is the whole rename. Nothing reaches the API, which is why this
// works offline. A create that lands meanwhile leaves no operation to
// rewrite; the node is then renamed by the uid Drive gave it
// (`docs/BUGS.md` B142).
if is_local_uid(&uid) {
match self
.db
.rewrite_op_target(&uid.to_string(), &new_parent_uid.to_string(), newname)
{
Ok(true) => {
self.state()
.rename_in_place(ino, newparent, &new_parent_uid, newname);
// A create that failed on its old name is due again.
self.host.wake_drain();
// A transient scratch file (its create parked, bytes held
// back) renamed to a finished name is the moment the file
// is meant to reach Drive: un-park the create so the drain
// uploads it once (`docs/BUGS.md` B70). Renaming to another
// transient name leaves it parked.
if is_transient_name(name) && !is_transient_name(newname) {
match self.db.set_create_hold(&uid.to_string(), false) {
Ok(_) => {
self.host.wake_drain();
debug!(%uid, newname, "un-parked a finalized transient create");
}
Err(e) => {
warn!(%uid, error = %e, "un-parking a finalized transient create failed")
}
}
}
debug!(%uid, newname, "renamed a node whose create is still queued");
return Ok(Renamed::Done);
}
Ok(false) => match self.host.landed_uid(ino) {
Some(real) => {
debug!(local = %uid, %real, newname, "create landed under a rename");
uid = real;
}
None => {
warn!(%uid, name, newname, "queued create vanished under a rename");
restore();
return Err(NamespaceError::Busy);
}
},
Err(e) => {
error!(%uid, error = %e, "rewriting a queued create's target failed");
restore();
return Err(NamespaceError::Io);
}
}
}
// Offline, or into a folder that does not exist on Drive yet, the
// rename is queued. The network going away under the inline path
// lands there too, with whatever half already reached Drive: the
// queued operation records the end state, so the drain finishes the
// rest.
let queue = || match self.host.queue_rename(
ino,
&uid,
&old_parent_uid,
newparent,
&new_parent_uid,
newname,
replacing,
) {
Ok(()) => Ok(Renamed::Queued),
Err(error) => {
restore();
Err(NamespaceError::Host(error))
}
};
if rename_needs_queue(self.host.sends_inline(), is_local_uid(&new_parent_uid)) {
return queue();
}
// A failure past this point has already trashed any node the rename
// was replacing, so put it back rather than leaving the caller with
// neither the source moved nor the destination intact.
if let Err(error) = self.require_rename_access(&uid, &old_parent_uid, &new_parent_uid) {
restore();
return Err(error);
}
// A move that also renames is one request, so the name only has to be
// free in the destination, and the answer never stands for half of
// it.
let to_parent = (newparent != parent).then_some(&new_parent_uid);
let to_name = (newname != name).then_some(newname);
match self.host.rename_remote(&uid, to_parent, to_name) {
Ok(true) => {}
Ok(false) => return queue(),
Err(error) => {
restore();
return Err(NamespaceError::Host(error));
}
}
// Through the guard, so the database has both folders unlisted before
// the answer. The next lookup rebuilds a folder still marked listed
// from the database, which did not have the move yet
// (`docs/BUGS.md` B135).
self.state()
.relocate(ino, parent, newparent, &new_parent_uid, newname);
Ok(Renamed::Done)
}
/// Check that `uid` may replace the victim, and record the replace in the
/// journal. Nothing is removed yet.
#[allow(clippy::too_many_arguments)]
fn authorize_replace(
&self,
ino: u64,
uid: &NodeUid,
victim_ino: u64,
victim_uid: &NodeUid,
old_parent_uid: &NodeUid,
new_parent_uid: &NodeUid,
newname: &str,
) -> Result<ReplaceJournal, NamespaceError<H::Error>> {
// POSIX requires both ends to agree on being a directory, and the
// check has to happen before anything is trashed: getting it wrong
// turns a refusal into the destruction of the destination.
let (src_dir, dst_dir) = {
let st = self.state.lock();
let is_dir = |i: u64| st.entries.get(&i).map(|e| e.node.is_folder());
match (is_dir(ino), is_dir(victim_ino)) {
(Some(a), Some(b)) => (a, b),
_ => return Err(NamespaceError::NotFound),
}
};
// Replacing a folder means trashing it, and Drive trashes a folder
// with its whole subtree, so the destination's emptiness has to be
// known before the decision is made.
let dst_empty = if dst_dir {
self.host.ensure_children(victim_ino)?;
self.state
.lock()
.children
.get(&victim_ino)
.is_none_or(|kids| kids.is_empty())
} else {
true
};
check_replaceable(src_dir, dst_dir, dst_empty).map_err(|error| match error {
ReplaceError::IsDirectory => NamespaceError::IsDirectory,
ReplaceError::NotDirectory => NamespaceError::NotDirectory,
ReplaceError::NotEmpty => NamespaceError::NotEmpty,
})?;
self.require_rename_access(uid, old_parent_uid, new_parent_uid)?;
ReplaceJournal::begin(&self.db, uid, victim_uid, new_parent_uid, newname).map_err(|error| {
error!(%uid, %error, "recording a replacing rename failed; refusing it");
NamespaceError::Io
})
}
/// A rename changes the node and both of its folders on Drive, so all
/// three have to allow it.
fn require_rename_access(
&self,
uid: &NodeUid,
old_parent_uid: &NodeUid,
new_parent_uid: &NodeUid,
) -> Result<(), NamespaceError<H::Error>> {
for authority in [uid, old_parent_uid, new_parent_uid] {
self.host.require_uid_writable(authority)?;
}
Ok(())
}
/// Trash the child `name` of folder `parent`, on Drive or through the
/// queue.
fn trash_child(&self, parent: u64, name: &str) -> Result<(), NamespaceError<H::Error>> {
self.host.require_writable(parent)?;
let (ino, mut uid) = self.host.lookup_child(parent, name)?;
let (ino, mut uid) = self
.host
.lookup_child(parent, name)?
.ok_or(NamespaceError::NotFound)?;
let open_now = self
.state
.lock()
@@ -600,8 +972,11 @@ mod service_tests {
/// changes go to Drive now; `link_up` whether Drive answers when asked.
struct Recorder {
state: Arc<Ranked<State>>,
db: Arc<Db>,
inline: bool,
link_up: bool,
/// Drive refuses a rename outright.
refuse_rename: bool,
calls: Mutex<Vec<String>>,
}
@@ -626,16 +1001,20 @@ mod service_tests {
Ok(())
}
fn lookup_child(&self, parent: u64, name: &str) -> Result<(u64, NodeUid), &'static str> {
fn lookup_child(
&self,
parent: u64,
name: &str,
) -> Result<Option<(u64, NodeUid)>, &'static str> {
let st = self.state.lock();
st.children
Ok(st
.children
.get(&parent)
.into_iter()
.flatten()
.filter_map(|ino| st.entries.get(ino).map(|entry| (*ino, entry)))
.find(|(_, entry)| entry.node.name == name)
.map(|(ino, entry)| (ino, entry.uid.clone()))
.ok_or("no such child")
.map(|(ino, entry)| (ino, entry.uid.clone())))
}
fn sends_inline(&self) -> bool {
@@ -703,6 +1082,71 @@ mod service_tests {
fn trashed(&self, uid: &NodeUid, _name: &str, open: bool) {
self.record(format!("trashed {uid} open={open}"));
}
fn remove_replaced(
&self,
ino: u64,
uid: &NodeUid,
_name: &str,
) -> Result<(), &'static str> {
// The tests replace with the node "a": its journal entry has to be
// on disk before anything is removed.
let journaled = self
.db
.state_str(&format!("replace:{}", self::uid("a")))
.unwrap()
.is_some();
self.record(format!("remove replaced {uid} journaled={journaled}"));
let _ = ino;
StateGuard::new(self.state.lock(), &self.db).forget_or_unlink(uid);
Ok(())
}
fn restore_replaced(
&self,
victim: Option<&(u64, NodeUid)>,
_parent: &NodeUid,
_name: &str,
) {
if let Some((_, uid)) = victim {
self.record(format!("restore {uid}"));
}
}
fn queue_rename(
&self,
_ino: u64,
uid: &NodeUid,
_old_parent_uid: &NodeUid,
_new_parent_ino: u64,
_new_parent_uid: &NodeUid,
new_name: &str,
authorized: bool,
) -> Result<(), &'static str> {
self.record(format!(
"queue rename {uid} to {new_name} authorized={authorized}"
));
Ok(())
}
fn rename_remote(
&self,
uid: &NodeUid,
new_parent: Option<&NodeUid>,
new_name: Option<&str>,
) -> Result<bool, &'static str> {
self.record(format!(
"rename {uid} parent={} name={}",
new_parent.map_or("-".to_owned(), |p| p.to_string()),
new_name.unwrap_or("-")
));
if self.refuse_rename {
return Err("refused");
}
Ok(self.link_up)
}
fn wake_drain(&self) {}
}
struct Fixture {
@@ -717,6 +1161,10 @@ mod service_tests {
impl Fixture {
fn new(inline: bool, link_up: bool) -> Self {
Self::with(inline, link_up, false)
}
fn with(inline: bool, link_up: bool, refuse_rename: bool) -> Self {
let tmp = TempDir::new();
let db = Arc::new(Db::open(&tmp.0.join("cache.db")).unwrap());
let cache = Arc::new(
@@ -729,8 +1177,10 @@ mod service_tests {
));
let host: &'static Recorder = Box::leak(Box::new(Recorder {
state: state.clone(),
db: db.clone(),
inline,
link_up,
refuse_rename,
calls: Mutex::default(),
}));
let dir = {
@@ -763,7 +1213,24 @@ mod service_tests {
}
fn listed(&self, name: &str) -> bool {
self.host.lookup_child(self.dir, name).is_ok()
self.child(self.dir, name).is_some()
}
fn child(&self, parent: u64, name: &str) -> Option<(u64, NodeUid)> {
self.host.lookup_child(parent, name).unwrap()
}
/// Put a node Drive has into folder `parent`, and return its inode.
fn put(&self, parent: u64, link: &str, folder: bool) -> u64 {
let parent_uid = self.state.lock().entries[&parent].uid.clone();
let node = local_node(uid(link), parent_uid, link.to_owned(), folder);
let mut st = self.state();
let ino = st.intern(parent, node);
st.children.get_mut(&parent).unwrap().push(ino);
if folder {
st.children.insert(ino, Vec::new());
}
ino
}
fn state(&self) -> StateGuard<'_> {
@@ -820,7 +1287,7 @@ mod service_tests {
let fx = Fixture::new(true, true);
fx.namespace.mkdir(fx.dir, "sub").unwrap();
fx.namespace.create(fx.dir, "a.txt").unwrap();
let sub = fx.host.lookup_child(fx.dir, "sub").unwrap().0;
let sub = fx.child(fx.dir, "sub").unwrap().0;
fx.namespace.create(sub, "inner.txt").unwrap();
fx.calls();
@@ -893,4 +1360,179 @@ mod service_tests {
assert_eq!(fx.calls(), [format!("drop queued {uid} keep_staged=false")]);
assert!(!fx.listed("a.txt"));
}
#[test]
fn an_online_move_is_one_request_and_moves_the_entry() {
let fx = Fixture::new(true, true);
let sub = fx.put(fx.dir, "sub", true);
let a = fx.put(fx.dir, "a", false);
let renamed = fx
.namespace
.rename(fx.dir, "a", sub, "b", RenameFlags::default())
.unwrap();
assert_eq!(renamed, Renamed::Done);
assert_eq!(
fx.calls(),
[format!("rename {} parent={} name=b", uid("a"), uid("sub"))]
);
// Both folders are unlisted so the next lookup asks Drive again
// (`docs/BUGS.md` B135); the entry already has its new place.
assert!(!fx.listed("a"));
let st = fx.state();
assert_eq!(st.entries[&a].parent, sub);
assert_eq!(st.entries[&a].node.name, "b");
}
#[test]
fn an_offline_rename_is_queued() {
let fx = Fixture::new(false, false);
fx.put(fx.dir, "a", false);
let renamed = fx
.namespace
.rename(fx.dir, "a", fx.dir, "b", RenameFlags::default())
.unwrap();
assert_eq!(renamed, Renamed::Queued);
assert_eq!(
fx.calls(),
[format!("queue rename {} to b authorized=false", uid("a"))]
);
}
#[test]
fn a_rename_that_loses_the_link_is_queued() {
let fx = Fixture::new(true, false);
fx.put(fx.dir, "a", false);
let renamed = fx
.namespace
.rename(fx.dir, "a", fx.dir, "b", RenameFlags::default())
.unwrap();
assert_eq!(renamed, Renamed::Queued);
assert_eq!(
fx.calls(),
[
format!("rename {} parent=- name=b", uid("a")),
format!("queue rename {} to b authorized=false", uid("a")),
]
);
}
#[test]
fn a_folder_cannot_move_into_itself() {
let fx = Fixture::new(true, true);
let sub = fx.put(fx.dir, "sub", true);
let inner = fx.put(sub, "inner", true);
assert!(matches!(
fx.namespace
.rename(fx.dir, "sub", inner, "sub", RenameFlags::default()),
Err(NamespaceError::InvalidArgument)
));
assert!(matches!(
fx.namespace.rename(
fx.dir,
"sub",
fx.dir,
"other",
RenameFlags {
exchange: true,
..RenameFlags::default()
}
),
Err(NamespaceError::InvalidArgument)
));
assert!(fx.calls().is_empty());
}
#[test]
fn a_refused_replace_removes_nothing() {
let fx = Fixture::new(true, true);
fx.put(fx.dir, "a", false);
let sub = fx.put(fx.dir, "sub", true);
fx.put(sub, "inner", false);
fx.put(fx.dir, "b", false);
let no_replace = RenameFlags {
no_replace: true,
..RenameFlags::default()
};
assert!(matches!(
fx.namespace.rename(fx.dir, "a", fx.dir, "b", no_replace),
Err(NamespaceError::Exists)
));
assert!(matches!(
fx.namespace
.rename(fx.dir, "a", fx.dir, "sub", RenameFlags::default()),
Err(NamespaceError::IsDirectory)
));
fx.put(fx.dir, "empty", true);
assert!(matches!(
fx.namespace
.rename(fx.dir, "empty", fx.dir, "sub", RenameFlags::default()),
Err(NamespaceError::NotEmpty)
));
assert!(fx.calls().is_empty());
assert!(fx.db.open_replaces().unwrap().is_empty());
}
#[test]
fn a_replace_journals_before_removing_and_ends_the_entry() {
let fx = Fixture::new(true, true);
let a = fx.put(fx.dir, "a", false);
fx.put(fx.dir, "b", false);
let renamed = fx
.namespace
.rename(fx.dir, "a", fx.dir, "b", RenameFlags::default())
.unwrap();
assert_eq!(renamed, Renamed::Done);
assert_eq!(
fx.calls(),
[
format!("remove replaced {} journaled=true", uid("b")),
format!("rename {} parent=- name=b", uid("a")),
]
);
assert_eq!(fx.state().entries[&a].node.name, "b");
// Ended when the rename returned.
assert!(
fx.db
.state_str(&format!("replace:{}", uid("a")))
.unwrap()
.is_none()
);
}
#[test]
fn a_replace_drive_refuses_brings_the_victim_back() {
let fx = Fixture::with(true, true, true);
fx.put(fx.dir, "a", false);
fx.put(fx.dir, "b", false);
assert!(matches!(
fx.namespace
.rename(fx.dir, "a", fx.dir, "b", RenameFlags::default()),
Err(NamespaceError::Host("refused"))
));
assert_eq!(
fx.calls(),
[
format!("remove replaced {} journaled=true", uid("b")),
format!("rename {} parent=- name=b", uid("a")),
format!("restore {}", uid("b")),
]
);
assert!(fx.listed("a"));
}
#[test]
fn a_rename_whose_queued_create_vanished_asks_to_try_again() {
// The recording host keeps no queue in the database, so the create
// this local node stands for is gone, and Drive never landed it.
let fx = Fixture::new(false, false);
fx.namespace.create(fx.dir, "a").unwrap();
fx.calls();
assert!(matches!(
fx.namespace
.rename(fx.dir, "a", fx.dir, "b", RenameFlags::default()),
Err(NamespaceError::Busy)
));
assert!(fx.calls().is_empty());
assert!(fx.listed("a"));
}
}
+14 -5
View File
@@ -51,7 +51,7 @@ graph TD
| [`pdfs-store`](../crates/pdfs-store) | The SQLite schema and queries (`db/`), the content cache (`cache`) |
| [`pdfs-drive`](../crates/pdfs-drive) | The `DriveApi` seam over the SDK, the call counter (`counted`), and `FakeDrive` for the simulations |
| [`pdfs-sync`](../crates/pdfs-sync) | The mirror engine: its passes (`mirror`), split into the walks (`mirror::walk`), applying a plan (`mirror::apply`) and the push pass (`mirror::push`), its engine thread (`mirror::engine`), its reads and writes of the local disk in one module (`mirror::local`), and the parts with no I/O: planner, pass model and pass trace. It owns its state (`SyncParts`), reads and writes its tables only through `SyncStore`, and reaches the daemon only through `SyncHost` |
| [`pdfs-vfs`](../crates/pdfs-vfs) | The mounted-files service, with no kernel adapter: the tree (`tree`: nodes, stable inodes, per-mount roots), the reserved inodes (`ids`), the open files (`open`: write handles and their authored ranges, released writes waiting for upload, directory handles, `fallocate` rules), the open-file service (`files`: open, write, resize, fsync and close, behind the `FilesHost` port), the namespace service (`namespace`: create, mkdir, unlink and rmdir behind the `NamespaceHost` port, and the settling of a cut-off replacing rename), and what the mount accepted but has not sent yet (`writes`: queued revisions, nodes removed here, echoes of our own changes). Errors are typed; the FUSE adapter maps them to errno |
| [`pdfs-vfs`](../crates/pdfs-vfs) | The mounted-files service, with no kernel adapter: the tree (`tree`: nodes, stable inodes, per-mount roots), the reserved inodes (`ids`), the open files (`open`: write handles and their authored ranges, released writes waiting for upload, directory handles, `fallocate` rules), the open-file service (`files`: open, write, resize, fsync and close, behind the `FilesHost` port), the namespace service (`namespace`: create, mkdir, unlink, rmdir and rename behind the `NamespaceHost` port, and the settling of a cut-off replacing rename), a headless adapter that serves both by path (`headless`) and the scenarios every adapter has to pass (`conformance`), and what the mount accepted but has not sent yet (`writes`: queued revisions, nodes removed here, echoes of our own changes). Errors are typed; the FUSE adapter maps them to errno |
| [`pdfs-fuse`](../crates/pdfs-fuse) | The daemon: FUSE handlers (`filesystem`), finding nodes (`resolve`), folder listings and file sizes (`listing`, `sizes`), reads (`reads`), queueing and the drain (`enqueue`, `queue`, `drain`, `upload`), calls sent straight to Drive (`remote`), requests by path (`requests`), startup recovery (`recovery`), pins, search, trash, the shared tree (`shared`), the link state (`link`), remote events (`background`), the daemon's side of the sync engine (`sync`, which implements `SyncHost`), moves between locations (`relocate`), control handlers (`control`), push events (`events`), photos, sharing, devices, the supervisor, and the simulation tests (`sim/`) |
| [`pdfs-daemon`](../crates/pdfs-daemon) | The daemon's composition root: waits for a session, opens the database and the content cache, resumes the session and mounts, then remounts or retries with a backoff and records each failure |
| [`pdfs-cli`](../crates/pdfs-cli) | The `pdfs` binary. `pdfs daemon` runs `pdfs_daemon::run` in-process; every other command is a control-socket client |
@@ -862,13 +862,22 @@ it to writing its sidecar, so overlapping fsyncs record in order (B301). What th
from Drive and the upload queue goes through `files::FilesHost`, which `Core` implements; the
FUSE callbacks keep the inode translation, the choice of thread and the reply.
The namespace service, `namespace::Namespace`, serves create, mkdir, unlink and rmdir: whether a
The namespace service, `namespace::Namespace`, serves create, mkdir, unlink, rmdir and rename: whether a
new node is made on Drive at once or queued, the parked create of a transient name, the POSIX
checks on what `unlink` and `rmdir` may remove, and the order of a trash (Drive first, then the
tree). Drive calls, the queue and the access rules go through `namespace::NamespaceHost`, which
checks on what `unlink`, `rmdir` and a replacing rename may remove, the order of a trash (Drive
first, then the tree), and the replace journal written before a rename removes its destination. Drive calls, the queue and the access rules go through `namespace::NamespaceHost`, which
`Core` implements. The module also holds the rules that settle a replacing rename a stop cut off
(B302). What still sits in `pdfs-fuse` around the tree is the code that fills it (listings,
sizes, the drain), the read path, and rename.
sizes, the drain) and the read path.
A second adapter, `headless::Headless`, serves both services by path, with no kernel and no
Drive: its host queues every create in the store as the daemon does offline. It does itself what
the kernel does before it calls the FUSE adapter: it resolves a path one name at a time, refuses
a name that is taken, and opens a file it is asked to create when one exists. The scenarios in
`pdfs_vfs::conformance` (written, resized, synced, closed and reopened files; folders; renames
and removals with their POSIX refusals; an unlinked open file) run through it in `pdfs-vfs` and
through a FUSE mount, online and offline, in `pdfs-fuse`'s simulations, and both see the same
outcomes. `cargo tree -p pdfs-vfs` still shows no kernel or GUI crate.
Steps 0 to 3 are 4.0.0. Steps 4 to 6 follow in 4.x, one service at a time. Out of scope for
now: an encrypted local vault (full-disk encryption covers a copied disk today), Windows and