mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-27 19:52:14 +01:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3f6f0b155 | ||
|
|
4e96ae8c61 | ||
|
|
bba74b5e65 | ||
|
|
fd0fb66448 | ||
|
|
7d963b3dd7 | ||
|
|
b7af8ae6c2 | ||
|
|
5647b8e684 | ||
|
|
b6ce90fcd5 | ||
|
|
7adcdd250f | ||
|
|
7614ed6731 | ||
|
|
006b6f6926 | ||
|
|
c44c1bccb5 |
No files matched your search
@@ -421,6 +421,10 @@ impl Core {
|
||||
// Cheap and a no-op when empty.
|
||||
self.cache.flush_touches();
|
||||
self.recovery().recover_fsynced_writes();
|
||||
// One a stop cut off that waited for Drive.
|
||||
if online {
|
||||
self.recovery().settle_replaces();
|
||||
}
|
||||
// Parked rows are invisible to `claim_next_due_op`, so
|
||||
// an idle queue is exactly when a park that has outlived
|
||||
// its writer has to be noticed.
|
||||
|
||||
@@ -19,7 +19,7 @@ impl Core {
|
||||
if is_local_uid_str(&op.uid) {
|
||||
match self.withdrawn_twin(op)? {
|
||||
Some(twin) => {
|
||||
self.writes.hide(&twin);
|
||||
self.withdraw_landed(&twin);
|
||||
match self
|
||||
.block_on_bounded(self.drive.trash_nodes(std::slice::from_ref(&twin)))
|
||||
.and_then(batch::into_unit)
|
||||
@@ -67,6 +67,21 @@ impl Core {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Take a node a withdrawn create made on Drive out of every listing.
|
||||
///
|
||||
/// Hiding keeps it out of listings from now on, not out of one taken while
|
||||
/// Drive listed it and the drain still waited for the answer. A file made
|
||||
/// under the name then opened the node being trashed, and every write to
|
||||
/// it was refused with EACCES (`docs/BUGS.md` B303).
|
||||
fn withdraw_landed(&self, uid: &NodeUid) {
|
||||
self.writes.hide(uid);
|
||||
self.for_each_mount(|st, notify| {
|
||||
if let Some((parent, name)) = st.forget_or_unlink(uid) {
|
||||
notify.inval_entry(parent, name);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Remove a trash op that landed, and the blob of a create it withdrew.
|
||||
pub(crate) fn retire_trash_op(
|
||||
&self,
|
||||
@@ -191,7 +206,7 @@ impl Core {
|
||||
real: &NodeUid,
|
||||
name: &str,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
self.writes.hide(real);
|
||||
self.withdraw_landed(real);
|
||||
self.note_self_change(real);
|
||||
let trash = PendingOp {
|
||||
id: trash,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use super::*;
|
||||
use pdfs_vfs::files::Files;
|
||||
use pdfs_vfs::namespace::{Namespace, Renamed};
|
||||
use pdfs_vfs::open::{DirListing, dir_page};
|
||||
|
||||
impl Filesystem for ProtonFs {
|
||||
@@ -938,6 +939,7 @@ pub struct ProtonFs {
|
||||
core: Core,
|
||||
/// The open-file service, shared with every other mount of the daemon.
|
||||
files: Arc<Files<Core>>,
|
||||
namespace: Arc<Namespace<Core>>,
|
||||
uid: u32,
|
||||
gid: u32,
|
||||
/// The tree inode of this session's root, which the kernel knows as
|
||||
@@ -990,6 +992,7 @@ impl ProtonFs {
|
||||
let (uid, gid) = unsafe { (libc::geteuid(), libc::getegid()) };
|
||||
Self {
|
||||
files: core.files(),
|
||||
namespace: core.namespace(),
|
||||
core,
|
||||
uid,
|
||||
gid,
|
||||
@@ -1170,254 +1173,46 @@ impl ProtonFs {
|
||||
|
||||
/// The body of [`Filesystem::create`], run off the dispatch loop.
|
||||
fn serve_create(&self, parent: u64, name: &str, reply: ReplyCreate) {
|
||||
if let Err(error) = self.core.require_writable(parent) {
|
||||
reply.error(error);
|
||||
return;
|
||||
match self.namespace.create(parent, name) {
|
||||
Ok(made) => {
|
||||
let attr = self.attr(made.ino, &made.node, made.access);
|
||||
reply.created(
|
||||
&TTL,
|
||||
&attr,
|
||||
Generation(0),
|
||||
FileHandle(made.fh),
|
||||
FopenFlags::empty(),
|
||||
);
|
||||
}
|
||||
Err(error) => reply.error(namespace_errno(error)),
|
||||
}
|
||||
if let Err(e) = self.core.ensure_children(parent) {
|
||||
// The parent was looked up a moment ago, so ENOENT here means it
|
||||
// left the tree in between. Log it: the caller only sees "no such
|
||||
// file" on a create.
|
||||
if e == Errno::ENOENT {
|
||||
warn!(parent, name, "create: the parent folder is no longer known");
|
||||
}
|
||||
reply.error(e);
|
||||
return;
|
||||
}
|
||||
let parent_uid = {
|
||||
let st = self.core.state();
|
||||
match st.entries.get(&parent) {
|
||||
Some(e) => e.uid.clone(),
|
||||
None => {
|
||||
warn!(
|
||||
parent,
|
||||
name, "create: the parent folder left the tree during its listing"
|
||||
);
|
||||
reply.error(Errno::ENOENT);
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
// A transient scratch name — a browser's in-flight `*.crdownload`, an
|
||||
// editor's `*.swp` — is kept purely local and *parked*: no remote node is
|
||||
// minted and its bytes never upload while it wears that name. The app
|
||||
// renames the finished file to its real name, and that rename un-parks the
|
||||
// create so only the completed file reaches Drive. Minting an empty remote
|
||||
// node here instead is what let a stalled+resumed download fork a
|
||||
// `(sync-conflict)` copy (docs/BUGS.md B70).
|
||||
let transient = is_transient_name(name);
|
||||
// Offline the server cannot mint a uid, so invent one and queue the
|
||||
// create. The file is real to the caller either way; only its identity is
|
||||
// provisional until the drain.
|
||||
//
|
||||
// A parent that is itself still queued forces the same path even when we
|
||||
// are online: the API has no folder to put this in yet.
|
||||
//
|
||||
// A create that set out online and lost the network on the way lands in
|
||||
// the queue too, so a Wi-Fi drop costs the caller a wait, never an EIO.
|
||||
let minted = if !transient && self.core.sends_inline() && !is_local_uid(&parent_uid) {
|
||||
if let Err(error) = self.core.require_uid_writable(&parent_uid) {
|
||||
reply.error(error);
|
||||
return;
|
||||
}
|
||||
// Create an empty file on the remote so it has a real uid immediately;
|
||||
// written bytes are buffered and sealed as a new revision on close.
|
||||
match self.core.block_on_bounded(self.core.drive.upload_file(
|
||||
&parent_uid,
|
||||
name,
|
||||
media_type_for(name),
|
||||
b"",
|
||||
)) {
|
||||
// A file that exists remotely but could not be read back is
|
||||
// queued, and the queued create finds it by name and adopts it.
|
||||
Ok(new_uid) => self.core.fetch_minted_node(&new_uid, name),
|
||||
Err(e) if self.core.lost_link(&e, "create") => None,
|
||||
Err(e) => {
|
||||
error!(%parent_uid, name, error = %e, "create file failed");
|
||||
reply.error(Errno::EIO);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let node = match minted {
|
||||
Some(node) => node,
|
||||
None => match self
|
||||
.core
|
||||
.queue_local_node(&parent_uid, name, false, transient)
|
||||
{
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
reply.error(e);
|
||||
return;
|
||||
}
|
||||
},
|
||||
};
|
||||
let (file, path) = match self.core.cache.create_scratch() {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
error!(uid = %node.uid, error = %e, "create scratch file failed");
|
||||
reply.error(Errno::EIO);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut st = self.core.state();
|
||||
let ino = st.intern(parent, node.clone());
|
||||
if let Some(entry) = st.entries.get_mut(&ino) {
|
||||
entry.open_count = entry.open_count.saturating_add(1);
|
||||
}
|
||||
if let Some(kids) = st.children.get_mut(&parent)
|
||||
&& !kids.contains(&ino)
|
||||
{
|
||||
kids.push(ino);
|
||||
}
|
||||
let fh = st
|
||||
.open
|
||||
.open_writer(ino, || WriteHandle::created(ino, &node, file, path));
|
||||
let entry = st.entries.get(&ino).unwrap();
|
||||
let attr = self.attr(ino, &entry.node, entry.access);
|
||||
drop(st);
|
||||
self.core.flush_access_changes();
|
||||
reply.created(
|
||||
&TTL,
|
||||
&attr,
|
||||
Generation(0),
|
||||
FileHandle(fh),
|
||||
FopenFlags::empty(),
|
||||
);
|
||||
}
|
||||
|
||||
/// The body of [`Filesystem::mkdir`], run off the dispatch loop.
|
||||
fn serve_mkdir(&self, parent: u64, name: &str, reply: ReplyEntry) {
|
||||
if let Err(error) = self.core.require_writable(parent) {
|
||||
reply.error(error);
|
||||
return;
|
||||
}
|
||||
if let Err(e) = self.core.ensure_children(parent) {
|
||||
reply.error(e);
|
||||
return;
|
||||
}
|
||||
let parent_uid = {
|
||||
let st = self.core.state();
|
||||
match st.entries.get(&parent) {
|
||||
Some(e) => e.uid.clone(),
|
||||
None => {
|
||||
reply.error(Errno::ENOENT);
|
||||
return;
|
||||
}
|
||||
match self.namespace.mkdir(parent, name) {
|
||||
Ok(made) => {
|
||||
let attr = self.attr(made.ino, &made.node, made.access);
|
||||
reply.entry(&TTL, &attr, Generation(0));
|
||||
}
|
||||
};
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.ok();
|
||||
// As in `create`: offline — or under a parent that is itself still
|
||||
// queued — the folder becomes a placeholder that the drain turns into a
|
||||
// real one.
|
||||
// Losing the network on the way queues it the same way.
|
||||
let minted = if self.core.sends_inline() && !is_local_uid(&parent_uid) {
|
||||
if let Err(error) = self.core.require_uid_writable(&parent_uid) {
|
||||
reply.error(error);
|
||||
return;
|
||||
}
|
||||
match self
|
||||
.core
|
||||
.block_on_bounded(self.core.drive.create_folder(&parent_uid, name, now))
|
||||
{
|
||||
Ok(new_uid) => self.core.fetch_minted_node(&new_uid, name),
|
||||
Err(e) if self.core.lost_link(&e, "mkdir") => None,
|
||||
Err(e) => {
|
||||
error!(%parent_uid, name, error = %e, "create folder failed");
|
||||
reply.error(Errno::EIO);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let node = match minted {
|
||||
Some(node) => node,
|
||||
None => match self.core.queue_local_node(&parent_uid, name, true, false) {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
reply.error(e);
|
||||
return;
|
||||
}
|
||||
},
|
||||
};
|
||||
let mut st = self.core.state();
|
||||
let local = is_local_uid(&node.uid);
|
||||
let uid = node.uid.clone();
|
||||
let ino = st.intern(parent, node);
|
||||
if let Some(kids) = st.children.get_mut(&parent)
|
||||
&& !kids.contains(&ino)
|
||||
{
|
||||
kids.push(ino);
|
||||
Err(error) => reply.error(namespace_errno(error)),
|
||||
}
|
||||
// A folder that exists only here has nothing to enumerate, and asking the
|
||||
// API to enumerate a `local~` uid would 404. Record it as fully listed and
|
||||
// empty, which it is, so reads stay offline-clean across a restart too.
|
||||
if local {
|
||||
st.children.insert(ino, Vec::new());
|
||||
st.record_listed(uid);
|
||||
}
|
||||
let entry = st.entries.get(&ino).unwrap();
|
||||
let attr = self.attr(ino, &entry.node, entry.access);
|
||||
drop(st);
|
||||
self.core.flush_access_changes();
|
||||
reply.entry(&TTL, &attr, Generation(0));
|
||||
}
|
||||
|
||||
/// The body of [`Filesystem::unlink`], run off the dispatch loop.
|
||||
fn serve_unlink(&self, parent: u64, name_str: &str, reply: ReplyEmpty) {
|
||||
if let Err(error) = self.core.require_writable(parent) {
|
||||
reply.error(error);
|
||||
return;
|
||||
fn serve_unlink(&self, parent: u64, name: &str, reply: ReplyEmpty) {
|
||||
match self.namespace.unlink(parent, name) {
|
||||
Ok(()) => reply.ok(),
|
||||
Err(error) => reply.error(namespace_errno(error)),
|
||||
}
|
||||
if let Ok((ino, _)) = self.core.lookup_child(parent, name_str) {
|
||||
let st = self.core.state();
|
||||
if let Some(entry) = st.entries.get(&ino)
|
||||
&& entry.node.is_folder()
|
||||
{
|
||||
reply.error(Errno::EISDIR);
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.trash_child(parent, name_str, reply);
|
||||
}
|
||||
|
||||
/// The body of [`Filesystem::rmdir`], run off the dispatch loop.
|
||||
fn serve_rmdir(&self, parent: u64, name_str: &str, reply: ReplyEmpty) {
|
||||
if let Err(error) = self.core.require_writable(parent) {
|
||||
reply.error(error);
|
||||
return;
|
||||
fn serve_rmdir(&self, parent: u64, name: &str, reply: ReplyEmpty) {
|
||||
match self.namespace.rmdir(parent, name) {
|
||||
Ok(()) => reply.ok(),
|
||||
Err(error) => reply.error(namespace_errno(error)),
|
||||
}
|
||||
if let Ok((ino, _)) = self.core.lookup_child(parent, name_str) {
|
||||
{
|
||||
let st = self.core.state();
|
||||
if st
|
||||
.entries
|
||||
.get(&ino)
|
||||
.is_some_and(|entry| !entry.node.is_folder())
|
||||
{
|
||||
reply.error(Errno::ENOTDIR);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// A missing cached listing says "unknown", not "empty". Proton's
|
||||
// trash call is recursive, so enumerate before applying rmdir's
|
||||
// POSIX emptiness rule.
|
||||
if let Err(e) = self.core.ensure_children(ino) {
|
||||
reply.error(e);
|
||||
return;
|
||||
}
|
||||
if self.core.state().has_children(ino) {
|
||||
reply.error(Errno::ENOTEMPTY);
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.trash_child(parent, name_str, reply);
|
||||
}
|
||||
|
||||
/// The body of [`Filesystem::rename`], run off the dispatch loop.
|
||||
@@ -1430,302 +1225,33 @@ 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;
|
||||
}
|
||||
};
|
||||
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;
|
||||
}
|
||||
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();
|
||||
}
|
||||
|
||||
/// Expose a file's server-side thumbnail/preview as an extended attribute, so
|
||||
/// a previewing client can fetch it without downloading the whole file. The
|
||||
/// bytes are fetched on demand and cached; absence yields `ENODATA`.
|
||||
/// Answer with an inode's current attributes, or `ENOENT` if it went away
|
||||
/// while the caller was doing something slower.
|
||||
fn reply_attr(&self, ino: u64, reply: ReplyAttr) {
|
||||
@@ -1738,113 +1264,6 @@ impl ProtonFs {
|
||||
None => reply.error(Errno::ENOENT),
|
||||
}
|
||||
}
|
||||
|
||||
fn trash_child(&self, parent: u64, name: &str, reply: ReplyEmpty) {
|
||||
if let Err(error) = self.core.require_writable(parent) {
|
||||
reply.error(error);
|
||||
return;
|
||||
}
|
||||
let (ino, mut uid) = match self.core.lookup_child(parent, name) {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
reply.error(e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let open_now = self
|
||||
.core
|
||||
.state
|
||||
.lock()
|
||||
.entries
|
||||
.get(&ino)
|
||||
.is_some_and(|e| e.open_count > 0);
|
||||
// A node the server has never heard of cannot be trashed there; deleting
|
||||
// it just means its queued creation is no longer wanted. This works
|
||||
// offline, which the remote path below cannot.
|
||||
if is_local_uid(&uid) {
|
||||
let dropped = if open_now {
|
||||
self.core.withdraw_queued_ops(&uid)
|
||||
} else {
|
||||
self.core.discard_queued_ops(&uid)
|
||||
};
|
||||
if let Err(error) = dropped {
|
||||
reply.error(error);
|
||||
return;
|
||||
}
|
||||
self.core.state().forget_or_unlink(&uid);
|
||||
// A create that landed before the ops were dropped left none: Drive
|
||||
// has the node, and the tree had not taken its uid yet. It is
|
||||
// trashed there like any other (docs/BUGS.md B173).
|
||||
match self.core.landed_row_uid(ino) {
|
||||
Some(real) => {
|
||||
debug!(local = %uid, %real, name, "create landed under a delete");
|
||||
uid = real;
|
||||
}
|
||||
None => {
|
||||
debug!(%uid, name, "deleted a node that had not been created remotely yet");
|
||||
reply.ok();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Queue a folder trash while Drive still holds children that were moved
|
||||
// out locally. The drain waits for those moves before sending it.
|
||||
let queue_it = |reply: ReplyEmpty| match self.core.queue_trash(&uid, name, open_now) {
|
||||
Ok(()) => reply.ok(),
|
||||
Err(e) => reply.error(e),
|
||||
};
|
||||
if !self.core.sends_inline() {
|
||||
return queue_it(reply);
|
||||
}
|
||||
match self.core.has_pending_moves_out_of(&uid) {
|
||||
Ok(false) => {}
|
||||
Ok(true) => return queue_it(reply),
|
||||
Err(error) => return reply.error(error),
|
||||
}
|
||||
if let Err(e) = self.core.require_uid_writable(&uid) {
|
||||
reply.error(e);
|
||||
return;
|
||||
}
|
||||
if let Err(e) = self
|
||||
.core
|
||||
.block_on_bounded(self.core.drive.trash_nodes(std::slice::from_ref(&uid)))
|
||||
.and_then(batch::into_unit)
|
||||
{
|
||||
if self.core.lost_link(&e, "trash") {
|
||||
queue_it(reply);
|
||||
return;
|
||||
}
|
||||
error!(%uid, error = %e, "trash failed");
|
||||
self.core
|
||||
.log_activity(ActivityKind::Trash, name, e.to_string(), false);
|
||||
reply.error(Errno::EIO);
|
||||
return;
|
||||
}
|
||||
// Only remove the namespace entry after Drive accepted the mutation.
|
||||
// Otherwise an EIO response still made the path disappear locally.
|
||||
self.core.writes.hide(&uid);
|
||||
self.core.state().forget_or_unlink(&uid);
|
||||
if open_now {
|
||||
// The open handle keeps the staged bytes; the drain must not send
|
||||
// them to a node that is already in the trash (docs/BUGS.md B106).
|
||||
if let Err(error) = self.core.withdraw_queued_ops(&uid) {
|
||||
warn!(%uid, ?error, "remote trash landed but queued-op cleanup failed");
|
||||
}
|
||||
} else {
|
||||
if let Err(error) = self.core.discard_queued_ops(&uid) {
|
||||
warn!(%uid, ?error, "remote trash landed but queued-op cleanup failed");
|
||||
}
|
||||
self.core.cache.evict(&uid);
|
||||
self.core.evict_reader(&uid);
|
||||
}
|
||||
self.core.invalidate_trash();
|
||||
// Every other trash site records itself; this one did not, which made a
|
||||
// file found in the trash impossible to attribute after the fact — the
|
||||
// activity log was the only record and it showed nothing (`docs/BUGS.md` B2).
|
||||
self.core
|
||||
.log_activity(ActivityKind::Trash, name, "trashed from the mount", true);
|
||||
reply.ok();
|
||||
}
|
||||
}
|
||||
|
||||
impl ProtonFs {
|
||||
|
||||
+243
-59
@@ -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;
|
||||
@@ -437,6 +428,203 @@ impl pdfs_vfs::files::FilesHost for Core {
|
||||
}
|
||||
}
|
||||
|
||||
/// The errno the kernel gets for a namespace change the service refused.
|
||||
fn namespace_errno(error: pdfs_vfs::namespace::NamespaceError<Errno>) -> Errno {
|
||||
use pdfs_vfs::namespace::NamespaceError;
|
||||
match error {
|
||||
NamespaceError::NotFound => Errno::ENOENT,
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
impl pdfs_vfs::namespace::NamespaceHost for Core {
|
||||
type Error = Errno;
|
||||
|
||||
fn require_writable(&self, ino: u64) -> Result<(), Errno> {
|
||||
Core::require_writable(self, ino)
|
||||
}
|
||||
|
||||
fn require_uid_writable(&self, uid: &NodeUid) -> Result<(), Errno> {
|
||||
Core::require_uid_writable(self, uid)
|
||||
}
|
||||
|
||||
fn ensure_children(&self, ino: u64) -> Result<(), Errno> {
|
||||
Core::ensure_children(self, ino)
|
||||
}
|
||||
|
||||
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 {
|
||||
Core::sends_inline(self)
|
||||
}
|
||||
|
||||
fn mint(&self, parent_uid: &NodeUid, name: &str, folder: bool) -> Result<Option<Node>, Errno> {
|
||||
// A file starts empty on Drive so it has a real uid at once; what is
|
||||
// written into it is sealed as a new revision on close.
|
||||
let minted = if folder {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.ok();
|
||||
self.block_on_bounded(self.drive.create_folder(parent_uid, name, now))
|
||||
} else {
|
||||
self.block_on_bounded(self.drive.upload_file(
|
||||
parent_uid,
|
||||
name,
|
||||
media_type_for(name),
|
||||
b"",
|
||||
))
|
||||
};
|
||||
let what = if folder { "mkdir" } else { "create" };
|
||||
match minted {
|
||||
Ok(new_uid) => Ok(self.fetch_minted_node(&new_uid, name)),
|
||||
Err(e) if self.lost_link(&e, what) => Ok(None),
|
||||
Err(e) => {
|
||||
error!(%parent_uid, name, error = %e, "{what} failed on Drive");
|
||||
Err(Errno::EIO)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn queue_create(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
folder: bool,
|
||||
parked: bool,
|
||||
) -> Result<Node, Errno> {
|
||||
self.queue_local_node(parent_uid, name, folder, parked)
|
||||
}
|
||||
|
||||
fn access_changed(&self) {
|
||||
self.flush_access_changes();
|
||||
}
|
||||
|
||||
fn drop_queued(&self, uid: &NodeUid, keep_staged: bool) -> Result<(), Errno> {
|
||||
if keep_staged {
|
||||
self.withdraw_queued_ops(uid)
|
||||
} else {
|
||||
self.discard_queued_ops(uid)
|
||||
}
|
||||
}
|
||||
|
||||
fn landed_uid(&self, ino: u64) -> Option<NodeUid> {
|
||||
self.landed_row_uid(ino)
|
||||
}
|
||||
|
||||
fn has_pending_moves_out_of(&self, uid: &NodeUid) -> Result<bool, Errno> {
|
||||
Core::has_pending_moves_out_of(self, uid)
|
||||
}
|
||||
|
||||
fn queue_trash(&self, uid: &NodeUid, name: &str, open: bool) -> Result<(), Errno> {
|
||||
Core::queue_trash(self, uid, name, open)
|
||||
}
|
||||
|
||||
fn trash_remote(&self, uid: &NodeUid, name: &str) -> Result<bool, Errno> {
|
||||
match self
|
||||
.block_on_bounded(self.drive.trash_nodes(std::slice::from_ref(uid)))
|
||||
.and_then(batch::into_unit)
|
||||
{
|
||||
Ok(()) => Ok(true),
|
||||
Err(e) if self.lost_link(&e, "trash") => Ok(false),
|
||||
Err(e) => {
|
||||
error!(%uid, error = %e, "trash failed");
|
||||
self.log_activity(ActivityKind::Trash, name, e.to_string(), false);
|
||||
Err(Errno::EIO)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
self.invalidate_trash();
|
||||
// Every other trash site records itself; this one did not, which made a
|
||||
// file found in the trash impossible to attribute after the fact — the
|
||||
// activity log was the only record and it showed nothing (`docs/BUGS.md` B2).
|
||||
self.log_activity(ActivityKind::Trash, name, "trashed from the mount", true);
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// The open-file service over this daemon's tree, cache and write-back.
|
||||
fn files(&self) -> Arc<pdfs_vfs::files::Files<Core>> {
|
||||
@@ -448,6 +636,17 @@ impl Core {
|
||||
self.clone(),
|
||||
))
|
||||
}
|
||||
|
||||
/// The namespace service over this daemon's tree, cache and write-back.
|
||||
fn namespace(&self) -> Arc<pdfs_vfs::namespace::Namespace<Core>> {
|
||||
Arc::new(pdfs_vfs::namespace::Namespace::new(
|
||||
self.state.clone(),
|
||||
self.db.clone(),
|
||||
self.cache.clone(),
|
||||
self.writes.clone(),
|
||||
self.clone(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// The errno the kernel gets for a node the tree refused.
|
||||
@@ -1824,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 {
|
||||
@@ -1962,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;
|
||||
@@ -2948,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;
|
||||
@@ -3294,24 +3465,26 @@ mod tests {
|
||||
assert_before(function, "cancel_upload", mutation);
|
||||
}
|
||||
|
||||
let filesystem = include_str!("filesystem.rs");
|
||||
for signature in ["fn serve_unlink(", "fn serve_rmdir("] {
|
||||
let function = function_source(filesystem, signature);
|
||||
let namespace = include_str!("../../pdfs-vfs/src/namespace.rs");
|
||||
for signature in ["pub fn unlink(", "pub fn rmdir("] {
|
||||
let function = function_source(namespace, signature);
|
||||
assert_before(function, "require_writable", "lookup_child");
|
||||
}
|
||||
|
||||
let rename = function_source(filesystem, "fn serve_rename(");
|
||||
assert_before(rename, "require_rename_access", "remove_replaced");
|
||||
assert_before(rename, "remove_replaced", "queue_rename_authorized");
|
||||
for (signature, gate, remote_call) in [
|
||||
("fn serve_create(", "require_uid_writable", "upload_file"),
|
||||
("fn serve_mkdir(", "require_uid_writable", "create_folder"),
|
||||
("fn trash_child(", "require_uid_writable", "trash_nodes"),
|
||||
("fn serve_rename(", "require_rename_access", "rename_remote"),
|
||||
("fn make(", "require_uid_writable", ".mint("),
|
||||
("fn trash_child(", "require_uid_writable", ".trash_remote("),
|
||||
] {
|
||||
let function = function_source(filesystem, signature);
|
||||
let function = function_source(namespace, signature);
|
||||
assert_before(function, gate, remote_call);
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -3664,12 +3837,20 @@ mod tests {
|
||||
assert_before(withdraw, "self.pending_blob(uid)", "release_dropped_below");
|
||||
assert!(!withdraw.contains("self.writes.pending.lock().remove(uid)"));
|
||||
|
||||
let filesystem = include_str!("filesystem.rs");
|
||||
let trash = function_source(filesystem, "fn trash_child(");
|
||||
let namespace = include_str!("../../pdfs-vfs/src/namespace.rs");
|
||||
let trash = function_source(namespace, "fn trash_child(");
|
||||
assert_eq!(
|
||||
trash.matches("self.core.withdraw_queued_ops(&uid)").count(),
|
||||
trash
|
||||
.matches("self.host.drop_queued(&uid, open_now)")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
let drop_queued = function_source(CORE_SOURCE, "fn drop_queued(");
|
||||
assert_before(
|
||||
drop_queued,
|
||||
"if keep_staged",
|
||||
"self.withdraw_queued_ops(uid)",
|
||||
);
|
||||
let release = function_source(CORE_SOURCE, "fn discard_unlinked(");
|
||||
assert_before(
|
||||
release,
|
||||
@@ -3690,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("));
|
||||
}
|
||||
|
||||
|
||||
@@ -582,6 +582,9 @@ pub(crate) fn mount_with(
|
||||
// Writes queued by a previous run (or left behind by a crash) are still owed
|
||||
// an upload, and reads must be served from their staged blobs until they land.
|
||||
core.recovery().hydrate_pending();
|
||||
// A replacing rename a stop cut off: its victim comes back, or its end
|
||||
// state stands. After `hydrate_pending`, which hides queued trashes.
|
||||
core.recovery().settle_replaces();
|
||||
// Then the writes that were fsynced but never closed, which the cache moved
|
||||
// aside at open. After `hydrate_pending`, so a recovered partial write can
|
||||
// see an already-queued write to the same node.
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! recovering writes that were fsynced but not queued when the daemon stopped.
|
||||
|
||||
use super::*;
|
||||
use pdfs_vfs::namespace::{ReplaceOutcome, settle_from_drive, settle_from_queue};
|
||||
|
||||
impl Core {
|
||||
/// Rehydrate the in-memory `State` maps from the DB on mount, so a cold
|
||||
@@ -117,12 +118,48 @@ pub(crate) trait RecoveryHost: Send + Sync {
|
||||
/// Queue a write recovered from a blob fsynced before a stop, as if its
|
||||
/// handle had just been released.
|
||||
fn queue_recovered(&self, uid: &NodeUid, blob: &Path, meta: StagedWrite) -> Result<(), Errno>;
|
||||
|
||||
/// Drive's node `uid`: `None` when Drive cannot be asked now, and
|
||||
/// `Some(None)` when it does not have the node.
|
||||
fn remote_node(&self, uid: &NodeUid) -> Option<Option<Node>>;
|
||||
|
||||
/// Drop the queued trash of a replaced node whose rename was never
|
||||
/// queued, so it stays where it is.
|
||||
fn withdraw_victim_trash(&self, uid: &NodeUid) -> Result<(), Errno>;
|
||||
|
||||
/// Bring a replaced node back out of Drive's trash. Best effort; a failure
|
||||
/// is logged and recorded in the activity log.
|
||||
fn restore_victim(&self, uid: &NodeUid, parent: &NodeUid, name: &str);
|
||||
}
|
||||
|
||||
impl RecoveryHost for Core {
|
||||
fn queue_recovered(&self, uid: &NodeUid, blob: &Path, meta: StagedWrite) -> Result<(), Errno> {
|
||||
self.enqueue_staged_write(uid, 0, blob, meta)
|
||||
}
|
||||
|
||||
fn remote_node(&self, uid: &NodeUid) -> Option<Option<Node>> {
|
||||
if !self.is_online() {
|
||||
return None;
|
||||
}
|
||||
match self.block_on_bounded(self.drive.enumerate_nodes(std::slice::from_ref(uid))) {
|
||||
Ok(nodes) => Some(nodes.into_iter().find(|node| node.uid == *uid)),
|
||||
Err(error) if is_gone(&error) => Some(None),
|
||||
Err(error) => {
|
||||
self.lost_link(&error, "settle a replacing rename");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn withdraw_victim_trash(&self, uid: &NodeUid) -> Result<(), Errno> {
|
||||
self.discard_queued_ops(uid)?;
|
||||
self.writes.unhide(uid);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn restore_victim(&self, uid: &NodeUid, parent: &NodeUid, name: &str) {
|
||||
self.restore_replaced(Some(&(0, uid.clone())), parent, name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuilds the queue from the database and the staging area after a
|
||||
@@ -136,6 +173,97 @@ pub(crate) struct Recovery {
|
||||
}
|
||||
|
||||
impl Recovery {
|
||||
/// Settle the replacing renames an earlier run started and did not end
|
||||
/// (`docs/BUGS.md` B302): forget the ones that reached their end state,
|
||||
/// and put the victim back where the rename did not happen. One that needs
|
||||
/// Drive while Drive cannot be asked stays for a later pass.
|
||||
///
|
||||
/// Runs at mount, after [`hydrate_pending`](Self::hydrate_pending), and on
|
||||
/// the drain's idle passes. The journal holds only this run's own renames
|
||||
/// apart from cut-off ones, and those are left alone, so the idle pass
|
||||
/// never undoes a rename in progress.
|
||||
pub(crate) fn settle_replaces(&self) {
|
||||
let intents = match self.db.open_replaces() {
|
||||
Ok(intents) if intents.is_empty() => return,
|
||||
Ok(intents) => intents,
|
||||
Err(error) => {
|
||||
warn!(%error, "reading cut-off replacing renames failed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let ops = match self.db.pending_ops() {
|
||||
Ok(ops) => ops,
|
||||
Err(error) => {
|
||||
warn!(%error, "reading the queue to settle replacing renames failed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
for intent in intents {
|
||||
let (Some(source), Some(victim), Some(parent)) = (
|
||||
parse_node_uid(&intent.source_uid),
|
||||
parse_node_uid(&intent.victim_uid),
|
||||
parse_node_uid(&intent.new_parent_uid),
|
||||
) else {
|
||||
warn!(source = %intent.source_uid, "dropping a replace intent with an unparseable uid");
|
||||
let _ = self.db.end_replace(&intent.source_uid);
|
||||
continue;
|
||||
};
|
||||
// The source's end state is queued when one of its ops puts it at
|
||||
// the new name: a rename, or the create a queued node's rename
|
||||
// rewrote.
|
||||
let rename_queued = ops.iter().any(|op| {
|
||||
op.uid == intent.source_uid
|
||||
&& [OP_RENAME, OP_CREATE, OP_MKDIR].contains(&op.kind.as_str())
|
||||
&& op.parent_uid.as_deref() == Some(intent.new_parent_uid.as_str())
|
||||
&& op.name.as_deref() == Some(intent.new_name.as_str())
|
||||
});
|
||||
let victim_trash_queued = ops
|
||||
.iter()
|
||||
.any(|op| op.uid == intent.victim_uid && op.kind == OP_TRASH);
|
||||
let outcome = settle_from_queue(rename_queued, victim_trash_queued, is_local_uid(&victim))
|
||||
.unwrap_or_else(|| {
|
||||
if is_local_uid(&source) {
|
||||
// A queued node whose create landed under the rename;
|
||||
// Drive knows it by a uid this entry does not have.
|
||||
warn!(%source, %victim, name = intent.new_name,
|
||||
"cannot settle a replacing rename of a node created here; leaving the replaced node in the trash");
|
||||
return ReplaceOutcome::Done;
|
||||
}
|
||||
let source_node = self.host.remote_node(&source);
|
||||
let victim_node = match source_node {
|
||||
Some(_) => self.host.remote_node(&victim),
|
||||
None => None,
|
||||
};
|
||||
settle_from_drive(
|
||||
&parent,
|
||||
&intent.new_name,
|
||||
source_node.as_ref().map(Option::as_ref),
|
||||
victim_node.as_ref().map(Option::as_ref),
|
||||
)
|
||||
});
|
||||
match outcome {
|
||||
ReplaceOutcome::Wait => continue,
|
||||
ReplaceOutcome::Done => {
|
||||
info!(%source, name = intent.new_name, "a replacing rename cut off by a stop had finished");
|
||||
}
|
||||
ReplaceOutcome::WithdrawVictimTrash => {
|
||||
if let Err(error) = self.host.withdraw_victim_trash(&victim) {
|
||||
warn!(%victim, ?error, "withdrawing a replaced node's queued trash failed; trying again later");
|
||||
continue;
|
||||
}
|
||||
info!(%victim, name = intent.new_name, "kept a node a cut-off rename was replacing");
|
||||
}
|
||||
ReplaceOutcome::RestoreVictim => {
|
||||
self.host.restore_victim(&victim, &parent, &intent.new_name);
|
||||
info!(%victim, name = intent.new_name, "restored a node a cut-off rename had replaced");
|
||||
}
|
||||
}
|
||||
if let Err(error) = self.db.end_replace(&intent.source_uid) {
|
||||
warn!(%source, %error, "ending a settled replace intent failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuild the in-memory pending map from the `pending_op` table on mount.
|
||||
///
|
||||
/// A queued write survives a restart — that is the point of persisting it —
|
||||
|
||||
@@ -479,6 +479,7 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::sim::fake_drive::{Entry, FakeDrive, Faults};
|
||||
use pdfs_core::control::{RefreshScope, SyncIssue};
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
@@ -2874,6 +2875,67 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_listing_taken_while_a_withdrawn_create_lands_does_not_keep_it() {
|
||||
// A file deleted while its create was on the wire. Drive made the node
|
||||
// and listed it before the drain had its answer, and a refresh then put
|
||||
// it in the tree. The drain hid it and trashed it, but the entry stayed:
|
||||
// a new file made under the name opened the trashed node, and every
|
||||
// write and rename of it was refused with EACCES (B303).
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("withdrawn-create-listed");
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
|
||||
let mnt = daemon.mountpoint.clone();
|
||||
let file = |bytes: &[u8]| Some(Entry::File(Arc::new(bytes.to_vec())));
|
||||
|
||||
let held = daemon.client.hold_reply_to_next_create();
|
||||
daemon.write_new(&mnt.join("d"), b"first").unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || held.reached()));
|
||||
std::fs::remove_file(mnt.join("d")).unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
drive.tree().get("d").cloned() == file(b"first")
|
||||
}));
|
||||
// Past the listing lag, so the refresh finds the node Drive made.
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
let refresh = Request::Refresh {
|
||||
scope: RefreshScope::Dir {
|
||||
path: mnt.to_string_lossy().into_owned(),
|
||||
},
|
||||
};
|
||||
assert!(matches!(daemon.request(&refresh), Ok(Response::Ok { .. })));
|
||||
let _ = std::fs::read_dir(&mnt).unwrap().count();
|
||||
drop(held);
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(30), || {
|
||||
daemon.pending().is_ok_and(|items| items.is_empty())
|
||||
&& !drive.tree().contains_key("d")
|
||||
}),
|
||||
"{:?} {:?}",
|
||||
daemon.pending(),
|
||||
drive.tree()
|
||||
);
|
||||
assert!(
|
||||
!mnt.join("d").exists(),
|
||||
"the trashed create is still listed"
|
||||
);
|
||||
|
||||
std::fs::write(mnt.join("d"), b"second").unwrap();
|
||||
std::fs::rename(mnt.join("d"), mnt.join("c.bin")).unwrap();
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(30), || {
|
||||
daemon.pending().is_ok_and(|items| items.is_empty())
|
||||
&& drive.tree().get("c.bin").cloned() == file(b"second")
|
||||
}),
|
||||
"{:?} {:?}",
|
||||
daemon.pending(),
|
||||
drive.tree()
|
||||
);
|
||||
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_file_made_under_the_name_of_a_create_on_the_wire_waits_for_it() {
|
||||
@@ -4556,4 +4618,118 @@ mod tests {
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The state a stop leaves between the two steps of a replacing rename
|
||||
/// sent to Drive inline: the replaced file in the trash, the source under
|
||||
/// its old name, and the journal entry. The next start puts the replaced
|
||||
/// file back (B302).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
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();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
let tree = drive.tree();
|
||||
tree.contains_key("report.odt") && tree.contains_key("report.odt.tmp")
|
||||
}));
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
|
||||
let victim = drive.lookup("report.odt").unwrap();
|
||||
let source = drive.lookup("report.odt.tmp").unwrap();
|
||||
cut_off_replace(&dir, &source, &victim, &drive.root(), "report.odt");
|
||||
drive.device().trash("report.odt");
|
||||
|
||||
// Without the listing lag: a lagging read shows the trash made just
|
||||
// above as not done yet, and a restart quicker than the lag then left
|
||||
// the file in the trash as never removed. A real stop comes long
|
||||
// after its own trash.
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::none())).unwrap();
|
||||
assert!(
|
||||
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: {:?}\n{}",
|
||||
drive.tree(),
|
||||
take_logged().join("\n")
|
||||
);
|
||||
assert!(drive.tree().contains_key("report.odt.tmp"));
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
std::fs::read(daemon.mountpoint.join("report.odt")).is_ok_and(|b| b == b"old")
|
||||
}));
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let db = Db::open(&dir.join("pdfs.db")).unwrap();
|
||||
assert!(db.open_replaces().unwrap().is_empty());
|
||||
drop(db);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The state a stop leaves between the two steps of a queued replacing
|
||||
/// rename: the replaced file's trash queued, the rename not. The next
|
||||
/// start drops the queued trash, so the file is never trashed (B302).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_replace_cut_off_after_queueing_its_trash_keeps_the_replaced_file() {
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("replace-cut-queue");
|
||||
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();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
let tree = drive.tree();
|
||||
tree.contains_key("report.odt") && tree.contains_key("report.odt.tmp")
|
||||
}));
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
|
||||
let victim = drive.lookup("report.odt").unwrap();
|
||||
let source = drive.lookup("report.odt.tmp").unwrap();
|
||||
cut_off_replace(&dir, &source, &victim, &drive.root(), "report.odt");
|
||||
let db = Db::open(&dir.join("pdfs.db")).unwrap();
|
||||
db.replace_ops_with_trash(&victim.to_string(), "report.odt", 1)
|
||||
.unwrap();
|
||||
drop(db);
|
||||
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
std::fs::read(daemon.mountpoint.join("report.odt")).is_ok_and(|b| b == b"old")
|
||||
}));
|
||||
// Long enough for the drain to have sent a trash it still held.
|
||||
std::thread::sleep(Duration::from_secs(3));
|
||||
assert!(
|
||||
drive.tree().contains_key("report.odt"),
|
||||
"the replaced file stayed: {:?}",
|
||||
drive.tree()
|
||||
);
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let db = Db::open(&dir.join("pdfs.db")).unwrap();
|
||||
assert!(db.open_replaces().unwrap().is_empty());
|
||||
assert!(!db.has_pending_op(&victim.to_string(), "trash").unwrap());
|
||||
drop(db);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Write the journal entry of a replacing rename, as an earlier run would
|
||||
/// have before it removed the victim.
|
||||
fn cut_off_replace(
|
||||
dir: &Path,
|
||||
source: &NodeUid,
|
||||
victim: &NodeUid,
|
||||
parent: &NodeUid,
|
||||
name: &str,
|
||||
) {
|
||||
let db = Db::open(&dir.join("pdfs.db")).unwrap();
|
||||
db.begin_replace(&pdfs_store::db::ReplaceIntent {
|
||||
source_uid: source.to_string(),
|
||||
victim_uid: victim.to_string(),
|
||||
new_parent_uid: parent.to_string(),
|
||||
new_name: name.to_owned(),
|
||||
started_ms: 1,
|
||||
run: 0,
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,7 @@ mod nodes;
|
||||
mod ops;
|
||||
mod photos;
|
||||
mod pins;
|
||||
mod replace;
|
||||
mod share_access;
|
||||
mod state;
|
||||
mod sync;
|
||||
@@ -63,6 +64,7 @@ pub use ops::{
|
||||
};
|
||||
pub use photos::{StoredPhoto, StoredPlace, THUMB_HAVE, THUMB_NONE, THUMB_UNKNOWN, TimelineRow};
|
||||
pub use pins::PinRow;
|
||||
pub use replace::ReplaceIntent;
|
||||
pub use sync::{SavedWalk, SavedWalkDir, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
|
||||
pub use trash::StoredTrash;
|
||||
|
||||
@@ -108,6 +110,10 @@ pub struct Db {
|
||||
/// to be owned here rather than by `open`'s stack frame. `None` for
|
||||
/// in-memory databases, which nothing else can reach.
|
||||
_single_writer: Option<File>,
|
||||
/// Tells this opening of the database from earlier ones, so that journal
|
||||
/// entries a previous run left behind can be told from this run's own
|
||||
/// (see `replace`).
|
||||
run: u64,
|
||||
}
|
||||
|
||||
/// Idle read-only connections, opened on demand and kept for reuse.
|
||||
@@ -294,6 +300,7 @@ impl Db {
|
||||
idle: Mutex::new(Vec::new()),
|
||||
}),
|
||||
_single_writer: single_writer,
|
||||
run: next_run(),
|
||||
};
|
||||
// A drain claim names a worker thread in the process that took it, and
|
||||
// the single-writer lock above says that process is not running. Any
|
||||
@@ -384,6 +391,7 @@ impl Db {
|
||||
conn: Ranked::new(Rank::DbWriter, conn),
|
||||
readers: None,
|
||||
_single_writer: None,
|
||||
run: next_run(),
|
||||
};
|
||||
db.migrate()?;
|
||||
Ok(db.into_conn())
|
||||
@@ -408,6 +416,7 @@ impl Db {
|
||||
conn: Ranked::new(Rank::DbWriter, conn),
|
||||
readers: None,
|
||||
_single_writer: None,
|
||||
run: next_run(),
|
||||
};
|
||||
db.migrate()?;
|
||||
Ok(db)
|
||||
@@ -429,6 +438,25 @@ fn is_in_memory(path: &Path) -> bool {
|
||||
p == ":memory:" || p.is_empty()
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static LAST: AtomicU64 = AtomicU64::new(0);
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos() as u64)
|
||||
.unwrap_or(0);
|
||||
let mut last = LAST.load(Ordering::Relaxed);
|
||||
loop {
|
||||
let next = now.max(last + 1);
|
||||
match LAST.compare_exchange_weak(last, next, Ordering::Relaxed, Ordering::Relaxed) {
|
||||
Ok(_) => return next,
|
||||
Err(seen) => last = seen,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! The journal of replacing renames.
|
||||
//!
|
||||
//! Drive has no rename that replaces its destination, so a `rename(2)` over an
|
||||
//! existing name removes the node there first and renames the source second.
|
||||
//! A stop between the two leaves the destination in Drive's trash and the
|
||||
//! source under its old name: neither the old state nor the new one. An entry
|
||||
//! here is written before the first step and removed after the last, so the
|
||||
//! next start finds every replace that was cut off and settles it
|
||||
//! (`docs/BUGS.md` B302).
|
||||
//!
|
||||
//! Kept in `sync_state` under [`REPLACE_PREFIX`], so the schema does not
|
||||
//! change.
|
||||
|
||||
use rusqlite::params;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::Db;
|
||||
use pdfs_core::Result;
|
||||
|
||||
/// The `sync_state` key prefix of a journal entry. The rest of the key is the
|
||||
/// source's uid.
|
||||
const REPLACE_PREFIX: &str = "replace:";
|
||||
|
||||
/// A replacing rename that has started: `source` is to be renamed to
|
||||
/// `new_name` in `new_parent`, over `victim`. Uids are in their `Display`
|
||||
/// form.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ReplaceIntent {
|
||||
pub source_uid: String,
|
||||
pub victim_uid: String,
|
||||
pub new_parent_uid: String,
|
||||
pub new_name: String,
|
||||
/// When the rename started, in milliseconds since the epoch.
|
||||
pub started_ms: i64,
|
||||
/// The opening of the database the rename started under. Set by
|
||||
/// [`Db::begin_replace`].
|
||||
#[serde(default)]
|
||||
pub run: u64,
|
||||
}
|
||||
|
||||
impl ReplaceIntent {
|
||||
fn run_is(&self, run: u64) -> bool {
|
||||
self.run == run
|
||||
}
|
||||
}
|
||||
|
||||
impl Db {
|
||||
/// Record that a replacing rename is about to remove its victim. Committed
|
||||
/// with a synced WAL before it returns, as the queue's own rows are: the
|
||||
/// removal that follows may reach Drive at once.
|
||||
pub fn begin_replace(&self, intent: &ReplaceIntent) -> Result<()> {
|
||||
let intent = ReplaceIntent {
|
||||
run: self.run,
|
||||
..intent.clone()
|
||||
};
|
||||
let value = serde_json::to_string(&intent)?;
|
||||
let conn = self.durable()?;
|
||||
conn.execute(
|
||||
"INSERT INTO sync_state (key, value) VALUES (?1, ?2)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||
params![format!("{REPLACE_PREFIX}{}", intent.source_uid), value],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Forget the replacing rename of `source_uid`: it finished, failed and
|
||||
/// was undone, or was settled after a restart.
|
||||
pub fn end_replace(&self, source_uid: &str) -> Result<()> {
|
||||
self.conn.lock().execute(
|
||||
"DELETE FROM sync_state WHERE key = ?1",
|
||||
params![format!("{REPLACE_PREFIX}{source_uid}")],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every replacing rename an earlier run started and did not end. This
|
||||
/// run's own are in progress, and are not returned. An entry that cannot
|
||||
/// be read is dropped, with a warning: it cannot be settled.
|
||||
pub fn open_replaces(&self) -> Result<Vec<ReplaceIntent>> {
|
||||
let rows: Vec<(String, String)> = {
|
||||
let conn = self.read()?;
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT key, value FROM sync_state WHERE key >= ?1 AND key < ?2 ORDER BY key",
|
||||
)?;
|
||||
stmt.query_map(params![REPLACE_PREFIX, "replace;"], |row| {
|
||||
Ok((row.get(0)?, row.get(1)?))
|
||||
})?
|
||||
.collect::<rusqlite::Result<_>>()?
|
||||
};
|
||||
let mut out = Vec::with_capacity(rows.len());
|
||||
for (key, value) in rows {
|
||||
match serde_json::from_str::<ReplaceIntent>(&value) {
|
||||
Ok(intent) if intent.run_is(self.run) => {}
|
||||
Ok(intent) => out.push(intent),
|
||||
Err(error) => {
|
||||
tracing::warn!(key, %error, "dropping an unreadable replace intent");
|
||||
self.conn
|
||||
.lock()
|
||||
.execute("DELETE FROM sync_state WHERE key = ?1", params![key])?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
@@ -8381,3 +8381,42 @@ fn a_read_without_a_reader_connection_fails_instead_of_waiting_on_the_writer() {
|
||||
"the read must fail, not queue behind the writer"
|
||||
);
|
||||
}
|
||||
|
||||
/// A replacing rename's journal entry outlives the run that wrote it, and is
|
||||
/// gone once ended; other `sync_state` keys are not taken for entries.
|
||||
#[test]
|
||||
fn a_replace_intent_is_kept_until_it_ends() {
|
||||
let db = Db::open_in_memory().unwrap();
|
||||
let intent = ReplaceIntent {
|
||||
source_uid: "vol~src".into(),
|
||||
victim_uid: "vol~victim".into(),
|
||||
new_parent_uid: "vol~dir".into(),
|
||||
new_name: "report.odt".into(),
|
||||
started_ms: 7,
|
||||
run: 0,
|
||||
};
|
||||
db.begin_replace(&intent).unwrap();
|
||||
db.with_conn(|conn| {
|
||||
conn.execute(
|
||||
"INSERT INTO sync_state (key, value) VALUES ('replacement', 'x'), ('replace;', 'y')",
|
||||
[],
|
||||
)?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// This run's own replace is in progress, not cut off.
|
||||
assert!(db.open_replaces().unwrap().is_empty());
|
||||
db.with_conn(|conn| {
|
||||
conn.execute(
|
||||
"UPDATE sync_state SET value = json_set(value, '$.run', 1) WHERE key = 'replace:vol~src'",
|
||||
[],
|
||||
)?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let open = db.open_replaces().unwrap();
|
||||
assert_eq!(open.len(), 1);
|
||||
assert_eq!(open[0].victim_uid, intent.victim_uid);
|
||||
db.end_replace("vol~src").unwrap();
|
||||
assert!(db.open_replaces().unwrap().is_empty());
|
||||
}
|
||||
@@ -12,11 +12,14 @@
|
||||
//! authored, the released write that waits for its upload, and directory
|
||||
//! handles; what the mount accepted but has not sent to Drive yet
|
||||
//! ([`writes`]); the POSIX rules on names and on what a rename may replace
|
||||
//! ([`names`]); and which nodes a folder lists ([`nodes`]).
|
||||
//! ([`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, rmdir and rename ([`namespace`]).
|
||||
|
||||
pub mod files;
|
||||
pub mod ids;
|
||||
pub mod names;
|
||||
pub mod namespace;
|
||||
pub mod nodes;
|
||||
pub mod open;
|
||||
pub mod tree;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+10
-4
@@ -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), 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), 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 |
|
||||
@@ -860,9 +860,15 @@ base, writes, resizes and `fallocate`, flush, the fsync barrier and the release.
|
||||
handle counts its changes in a generation, and an fsync holds the handle's barrier from reading
|
||||
it to writing its sidecar, so overlapping fsyncs record in order (B301). What the service needs
|
||||
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. What still sits in
|
||||
`pdfs-fuse` around the tree is the code that fills it (listings, sizes, the drain), the read
|
||||
path, and the namespace operations (create, mkdir, rename, unlink).
|
||||
FUSE callbacks keep the inode translation, the choice of thread and the reply.
|
||||
|
||||
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`, `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) and the read path.
|
||||
|
||||
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
|
||||
|
||||
@@ -108,6 +108,8 @@ a live account since.
|
||||
|
||||
| Entry | Title |
|
||||
|---|---|
|
||||
| [B303](#b303--a-file-made-where-a-withdrawn-create-was-listed-refuses-every-write) | A file made where a withdrawn create was listed refuses every write |
|
||||
| [B302](#b302--a-stop-during-a-replacing-rename-leaves-the-replaced-file-in-the-trash) | A stop during a replacing rename leaves the replaced file in the trash |
|
||||
| [B301](#b301--two-overlapping-fsyncs-can-leave-the-older-ones-record-on-disk) | Two overlapping fsyncs can leave the older one's record on disk |
|
||||
| [B300](#b300--a-read-during-a-release-can-be-served-the-revision-the-write-replaced) | A read during a release can be served the revision the write replaced |
|
||||
| [B299](#b299--a-synced-folder-in-the-trash-blocks-attaching-any-other-folder) | A synced folder in the trash blocks attaching any other folder |
|
||||
@@ -404,6 +406,74 @@ a live account since.
|
||||
|
||||
Newest first.
|
||||
|
||||
### B303 — A file made where a withdrawn create was listed refuses every write
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
**Found:** 2026-11-27, from a CI failure of the `one_client_on_a_slow_link` simulation (seed 3):
|
||||
`rename y/d -> y/c.bin` answered EACCES, and the daemon log had two "access changed before the
|
||||
write could be queued" errors for the node.
|
||||
**Where:** `Core::trash_withdrawn_create` and `Core::drain_trash` in
|
||||
`crates/pdfs-fuse/src/drain/trash.rs`
|
||||
|
||||
**Repro:** Make a file and delete it while its create is on the wire, on a slow link. Drive makes
|
||||
the node and lists it before the drain has the answer. Refresh the folder in that window. Once the
|
||||
drain has trashed the node, make a file under the same name, write to it and rename it. The write
|
||||
is kept in staging with "access changed before the write could be queued", and the rename fails
|
||||
with EACCES.
|
||||
|
||||
**Cause.** The drain hid the node Drive made, so later listings left it out, but it did not take
|
||||
it out of a listing already in the tree. The refresh had put the node there under the deleted
|
||||
file's name. A new file under that name opened the existing entry, which was the node being
|
||||
trashed. Once the trash landed its row was gone, the node had no write authority, and every
|
||||
write and rename of it was refused.
|
||||
|
||||
**Fix.** `Core::withdraw_landed` hides the node and also removes it from every mount, and drops
|
||||
the kernel's entry for its name. Both places that trash a withdrawn create's node call it.
|
||||
|
||||
**Verified:** `a_listing_taken_while_a_withdrawn_create_lands_does_not_keep_it` holds the answer to
|
||||
a create, deletes the file, refreshes the folder, then lets the answer through. It fails without
|
||||
the fix and passes with it.
|
||||
### B302 — A stop during a replacing rename leaves the replaced file in the trash
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
**Found:** 2026-11-27, from the review of the mounted filesystem in `FUSE.md`, while moving the
|
||||
namespace operations toward `pdfs-vfs` (step 5 of `docs/ARCHITECTURE.md`). It was not seen in a
|
||||
run.
|
||||
**Where:** `serve_rename` and `ReplaceJournal` in `crates/pdfs-fuse/src/filesystem.rs`;
|
||||
`Recovery::settle_replaces` in `crates/pdfs-fuse/src/recovery.rs`; `Db::begin_replace` in
|
||||
`crates/pdfs-store/src/db/replace.rs`; the settle rules in `crates/pdfs-vfs/src/namespace.rs`
|
||||
|
||||
**Repro:** Save a file with an editor that writes a temporary file and renames it over the
|
||||
original. Stop the daemon (a crash, a power loss or a `kill -9`) after the original has gone to the
|
||||
trash and before the rename. Online, the original is in Drive's trash and the new content is under
|
||||
the temporary name. With local-first or offline, the queue holds the original's trash and no rename,
|
||||
so the next start sends the trash. Either way, the file is gone from its name.
|
||||
|
||||
**Cause.** Drive has no rename that replaces its destination, so `rename(2)` over an existing name
|
||||
removes the destination first and renames the source second (B13). A failure between the two steps
|
||||
puts the destination back (`restore_replaced`), but a stop between them left nothing to say that a
|
||||
rename was half done.
|
||||
|
||||
**Fix.** A replacing rename writes a journal entry before it removes the destination, with a synced
|
||||
commit, and removes the entry when it returns, whichever way it returns. The entry lives in
|
||||
`sync_state`, so the schema does not change. On the next start, and on the drain's idle passes
|
||||
while Drive could not be asked, each entry from an earlier run is settled:
|
||||
- the source's rename, or the create it rewrote, is queued: the rename stands;
|
||||
- the destination's trash is queued and the rename is not: the queued trash is dropped;
|
||||
- otherwise Drive is asked. If the source has its new name, the rename stands. If the destination is
|
||||
in the trash, it is restored. If the destination never got there, nothing is undone.
|
||||
|
||||
Entries are tagged with the opening of the database that wrote them, so a rename in progress is
|
||||
never settled under it. A source created here whose create landed under the rename is known to Drive
|
||||
by a uid the entry does not have; it is logged and left as it is.
|
||||
|
||||
**Verified:** `a_replace_cut_off_after_its_trash_brings_the_replaced_file_back` and
|
||||
`a_replace_cut_off_after_queueing_its_trash_keeps_the_replaced_file` start a daemon on the state a
|
||||
stop leaves, and fail without the settle. They write that state directly; no test stops a daemon in
|
||||
the middle of a rename.
|
||||
|
||||
---
|
||||
|
||||
### B301 — Two overlapping fsyncs can leave the older one's record on disk
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
|
||||
Reference in new issue
Block a user