mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-30 04:22:14 +01:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7af8ae6c2 | ||
|
|
7adcdd250f | ||
|
|
006b6f6926 |
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.
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use super::*;
|
||||
use pdfs_vfs::files::Files;
|
||||
use pdfs_vfs::namespace::Namespace;
|
||||
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.
|
||||
@@ -1498,6 +1293,9 @@ impl ProtonFs {
|
||||
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);
|
||||
@@ -1551,6 +1349,14 @@ impl ProtonFs {
|
||||
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;
|
||||
@@ -1723,9 +1529,6 @@ impl ProtonFs {
|
||||
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 +1541,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 {
|
||||
@@ -1925,3 +1621,42 @@ 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+159
-15
@@ -437,6 +437,131 @@ 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::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<(u64, NodeUid), Errno> {
|
||||
Core::lookup_child(self, parent, name)
|
||||
}
|
||||
|
||||
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 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 +573,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.
|
||||
@@ -3294,24 +3430,24 @@ 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");
|
||||
}
|
||||
for (signature, gate, remote_call) in [
|
||||
("fn make(", "require_uid_writable", ".mint("),
|
||||
("fn trash_child(", "require_uid_writable", ".trash_remote("),
|
||||
] {
|
||||
let function = function_source(namespace, signature);
|
||||
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");
|
||||
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"),
|
||||
] {
|
||||
let function = function_source(filesystem, signature);
|
||||
assert_before(function, gate, remote_call);
|
||||
}
|
||||
assert_before(rename, "require_rename_access", "rename_remote");
|
||||
let control_mkdir = function_source(source, "fn create_folder(");
|
||||
assert_before(
|
||||
control_mkdir,
|
||||
@@ -3664,12 +3800,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,
|
||||
|
||||
@@ -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]
|
||||
@@ -4556,4 +4557,115 @@ 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");
|
||||
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: {:?}",
|
||||
drive.tree()
|
||||
);
|
||||
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)
|
||||
@@ -448,6 +457,25 @@ fn is_in_memory(path: &Path) -> bool {
|
||||
/// 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 {
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn acquire_single_writer_lock(path: &Path) -> Result<Option<File>> {
|
||||
if is_in_memory(path) {
|
||||
return Ok(None);
|
||||
|
||||
@@ -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 and rmdir ([`namespace`]).
|
||||
|
||||
pub mod files;
|
||||
pub mod ids;
|
||||
pub mod names;
|
||||
pub mod namespace;
|
||||
pub mod nodes;
|
||||
pub mod open;
|
||||
pub mod tree;
|
||||
|
||||
@@ -0,0 +1,896 @@
|
||||
//! The namespace service: create, mkdir, unlink and rmdir, and the rules for
|
||||
//! a replacing rename.
|
||||
//!
|
||||
//! [`Namespace`] does what the FUSE adapter in `pdfs-fuse` used to do inside
|
||||
//! its callbacks, and returns [`NamespaceError`] for the adapter to answer
|
||||
//! with. What it needs from Drive and from the upload queue goes through
|
||||
//! [`NamespaceHost`].
|
||||
//!
|
||||
//! The rules settle a replacing rename that a stop cut off, on the next start
|
||||
//! (`docs/BUGS.md` B302). The journal entry is
|
||||
//! [`pdfs_store::db::ReplaceIntent`].
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
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 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::open::WriteHandle;
|
||||
use crate::tree::{State, StateGuard};
|
||||
use crate::writes::WriteState;
|
||||
|
||||
/// What to do with a replacing rename a previous run started and did not end.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ReplaceOutcome {
|
||||
/// It reached its end state, or nothing is left to undo: forget it.
|
||||
Done,
|
||||
/// The victim's trash is still queued but the rename never was: drop the
|
||||
/// queued trash, so the victim stays where it is.
|
||||
WithdrawVictimTrash,
|
||||
/// The rename did not happen and the victim is in Drive's trash: restore
|
||||
/// it.
|
||||
RestoreVictim,
|
||||
/// Drive cannot be asked now: try again later.
|
||||
Wait,
|
||||
}
|
||||
|
||||
/// What the queue says about a cut-off replace: whether the source's rename
|
||||
/// was queued, and whether the victim's trash is.
|
||||
///
|
||||
/// Answers without Drive where it can, which is every case the queued path
|
||||
/// left: a queued rename carries the end state and the drain finishes it, and
|
||||
/// a queued trash without a queued rename means the stop came between the two.
|
||||
/// A victim whose own create was still queued had nothing on Drive to restore.
|
||||
pub fn settle_from_queue(
|
||||
rename_queued: bool,
|
||||
victim_trash_queued: bool,
|
||||
victim_local: bool,
|
||||
) -> Option<ReplaceOutcome> {
|
||||
if rename_queued {
|
||||
return Some(ReplaceOutcome::Done);
|
||||
}
|
||||
if victim_trash_queued {
|
||||
return Some(ReplaceOutcome::WithdrawVictimTrash);
|
||||
}
|
||||
if victim_local {
|
||||
return Some(ReplaceOutcome::Done);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// What Drive says about a cut-off replace that went to Drive inline.
|
||||
///
|
||||
/// `source` and `victim` are `None` when Drive could not be asked, and
|
||||
/// `Some(None)` when it does not have the node. The rename happened when the
|
||||
/// source sits at the new name; then the victim's removal was meant. Otherwise
|
||||
/// the victim comes back if it is in the trash, and is left alone if it never
|
||||
/// got there.
|
||||
pub fn settle_from_drive(
|
||||
new_parent: &NodeUid,
|
||||
new_name: &str,
|
||||
source: Option<Option<&Node>>,
|
||||
victim: Option<Option<&Node>>,
|
||||
) -> ReplaceOutcome {
|
||||
let Some(source) = source else {
|
||||
return ReplaceOutcome::Wait;
|
||||
};
|
||||
let renamed = source.is_some_and(|node| {
|
||||
!node.trashed && node.parent_uid.as_ref() == Some(new_parent) && node.name == new_name
|
||||
});
|
||||
if renamed {
|
||||
return ReplaceOutcome::Done;
|
||||
}
|
||||
match victim {
|
||||
None => ReplaceOutcome::Wait,
|
||||
Some(Some(node)) if node.trashed => ReplaceOutcome::RestoreVictim,
|
||||
Some(_) => ReplaceOutcome::Done,
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the namespace service refused or failed an operation.
|
||||
///
|
||||
/// `E` is the host's own error ([`NamespaceHost::Error`]), passed through
|
||||
/// unchanged.
|
||||
#[derive(Debug)]
|
||||
pub enum NamespaceError<E> {
|
||||
/// The parent folder is not in the tree.
|
||||
NotFound,
|
||||
/// `unlink` named a folder.
|
||||
IsDirectory,
|
||||
/// `rmdir` named a file.
|
||||
NotDirectory,
|
||||
/// `rmdir` named a folder that still has children.
|
||||
NotEmpty,
|
||||
/// Something failed that the service already logged: the scratch file of
|
||||
/// a new file.
|
||||
Io,
|
||||
/// The host failed, with its own error.
|
||||
Host(E),
|
||||
}
|
||||
|
||||
impl<E> From<E> for NamespaceError<E> {
|
||||
fn from(error: E) -> Self {
|
||||
NamespaceError::Host(error)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the namespace service needs from the rest of the daemon: the access
|
||||
/// rules, the listing of a folder, Drive, and the upload queue.
|
||||
pub trait NamespaceHost {
|
||||
/// The error the host fails with.
|
||||
type Error: std::fmt::Debug;
|
||||
|
||||
/// Refuse a change under `ino` that its access does not allow.
|
||||
fn require_writable(&self, ino: u64) -> Result<(), Self::Error>;
|
||||
|
||||
/// Refuse a change to `uid` on Drive that its access does not allow.
|
||||
fn require_uid_writable(&self, uid: &NodeUid) -> Result<(), Self::Error>;
|
||||
|
||||
/// 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>;
|
||||
|
||||
/// Whether a change goes to Drive now rather than into the queue.
|
||||
fn sends_inline(&self) -> bool;
|
||||
|
||||
/// Create an empty file, or a folder when `folder`, named `name` under
|
||||
/// `parent_uid` on Drive, and return its node. `None` asks for the create
|
||||
/// to be queued instead: the link went down on the way, or Drive made the
|
||||
/// node but it could not be read back, which the queued create adopts by
|
||||
/// name.
|
||||
fn mint(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
folder: bool,
|
||||
) -> Result<Option<Node>, Self::Error>;
|
||||
|
||||
/// Queue the create of `name` under `parent_uid` and return the node it is
|
||||
/// known by until the drain sends it. A `parked` create waits for a rename
|
||||
/// to a real name before it is sent.
|
||||
fn queue_create(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
folder: bool,
|
||||
parked: bool,
|
||||
) -> Result<Node, Self::Error>;
|
||||
|
||||
/// Publish the access changes the tree recorded.
|
||||
fn access_changed(&self);
|
||||
|
||||
/// Drop the queued operations of `uid`. `keep_staged` keeps the bytes an
|
||||
/// open handle still writes into.
|
||||
fn drop_queued(&self, uid: &NodeUid, keep_staged: bool) -> Result<(), Self::Error>;
|
||||
|
||||
/// The uid the queued create of `ino` landed as, when it landed before its
|
||||
/// queued operations were dropped.
|
||||
fn landed_uid(&self, ino: u64) -> Option<NodeUid>;
|
||||
|
||||
/// Whether Drive still holds children that were moved out of `uid` here
|
||||
/// and not sent yet.
|
||||
fn has_pending_moves_out_of(&self, uid: &NodeUid) -> Result<bool, Self::Error>;
|
||||
|
||||
/// Queue the trash of `uid`. `open` keeps the bytes an open handle still
|
||||
/// writes into.
|
||||
fn queue_trash(&self, uid: &NodeUid, name: &str, open: bool) -> Result<(), Self::Error>;
|
||||
|
||||
/// Trash `uid` on Drive. `Ok(false)` asks for the trash to be queued
|
||||
/// 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>;
|
||||
|
||||
/// 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
|
||||
/// still work.
|
||||
fn trashed(&self, uid: &NodeUid, name: &str, open: bool);
|
||||
}
|
||||
|
||||
/// A node the namespace service made, as the tree holds it once made.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Made {
|
||||
pub ino: u64,
|
||||
/// The write handle a new file is open under; 0 for a folder.
|
||||
pub fh: u64,
|
||||
pub node: Node,
|
||||
pub access: Access,
|
||||
}
|
||||
|
||||
/// The namespace service of one daemon, shared by every mount: create,
|
||||
/// mkdir, unlink and rmdir.
|
||||
pub struct Namespace<H> {
|
||||
state: Arc<Ranked<State>>,
|
||||
db: Arc<Db>,
|
||||
cache: Arc<ContentCache>,
|
||||
writes: WriteState,
|
||||
host: H,
|
||||
}
|
||||
|
||||
impl<H: NamespaceHost> Namespace<H> {
|
||||
pub fn new(
|
||||
state: Arc<Ranked<State>>,
|
||||
db: Arc<Db>,
|
||||
cache: Arc<ContentCache>,
|
||||
writes: WriteState,
|
||||
host: H,
|
||||
) -> Self {
|
||||
Self {
|
||||
state,
|
||||
db,
|
||||
cache,
|
||||
writes,
|
||||
host,
|
||||
}
|
||||
}
|
||||
|
||||
fn state(&self) -> StateGuard<'_> {
|
||||
StateGuard::new(self.state.lock(), &self.db)
|
||||
}
|
||||
|
||||
/// The uid of folder `parent`, after its children are in the tree.
|
||||
fn listed_parent(&self, parent: u64, what: &str) -> Result<NodeUid, NamespaceError<H::Error>> {
|
||||
self.host.require_writable(parent)?;
|
||||
if let Err(error) = self.host.ensure_children(parent) {
|
||||
// The parent was looked up a moment ago, so a failure here often
|
||||
// means it left the tree in between. Log it: the caller only sees
|
||||
// "no such file" on a create.
|
||||
warn!(
|
||||
parent,
|
||||
what,
|
||||
?error,
|
||||
"the parent folder could not be listed"
|
||||
);
|
||||
return Err(NamespaceError::Host(error));
|
||||
}
|
||||
match self.state.lock().entries.get(&parent) {
|
||||
Some(entry) => Ok(entry.uid.clone()),
|
||||
None => {
|
||||
warn!(
|
||||
parent,
|
||||
what, "the parent folder left the tree during its listing"
|
||||
);
|
||||
Err(NamespaceError::NotFound)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mint `name` under `parent_uid` on Drive when changes go there now and
|
||||
/// the parent exists there, or queue its create otherwise.
|
||||
///
|
||||
/// Offline the server cannot mint a uid, so the queue invents one. A
|
||||
/// parent that is itself still queued forces the same path even 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 error.
|
||||
fn make(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
folder: bool,
|
||||
parked: bool,
|
||||
) -> Result<Node, NamespaceError<H::Error>> {
|
||||
if !parked && self.host.sends_inline() && !is_local_uid(parent_uid) {
|
||||
self.host.require_uid_writable(parent_uid)?;
|
||||
if let Some(node) = self.host.mint(parent_uid, name, folder)? {
|
||||
return Ok(node);
|
||||
}
|
||||
}
|
||||
Ok(self.host.queue_create(parent_uid, name, folder, parked)?)
|
||||
}
|
||||
|
||||
/// Create the file `name` in folder `parent` and open it for writing.
|
||||
/// Returns the file and its write handle.
|
||||
///
|
||||
/// A transient scratch name, such as a browser's in-flight `*.crdownload`
|
||||
/// or an editor's `*.swp`, is kept local and parked: no remote node is
|
||||
/// minted and its bytes never upload while it has that name. The rename
|
||||
/// to the real name un-parks the create, so only the finished file reaches
|
||||
/// Drive. Minting an empty remote node here instead let a stalled and
|
||||
/// resumed download fork a conflict copy (`docs/BUGS.md` B70).
|
||||
pub fn create(&self, parent: u64, name: &str) -> Result<Made, NamespaceError<H::Error>> {
|
||||
let parent_uid = self.listed_parent(parent, "create")?;
|
||||
let node = self.make(&parent_uid, name, false, is_transient_name(name))?;
|
||||
let (file, path) = self.cache.create_scratch().map_err(|e| {
|
||||
error!(uid = %node.uid, error = %e, "create scratch file failed");
|
||||
NamespaceError::Io
|
||||
})?;
|
||||
let mut st = self.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 made = made(&st, ino, fh);
|
||||
drop(st);
|
||||
self.host.access_changed();
|
||||
made
|
||||
}
|
||||
|
||||
/// Create the folder `name` in folder `parent`.
|
||||
pub fn mkdir(&self, parent: u64, name: &str) -> Result<Made, NamespaceError<H::Error>> {
|
||||
let parent_uid = self.listed_parent(parent, "mkdir")?;
|
||||
let node = self.make(&parent_uid, name, true, false)?;
|
||||
let mut st = self.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);
|
||||
}
|
||||
// A folder that exists only here has nothing to enumerate, and asking
|
||||
// the API to enumerate a `local~` uid would fail. Record it as fully
|
||||
// listed and empty, which it is, so reads stay offline across a
|
||||
// restart too.
|
||||
if local {
|
||||
st.children.insert(ino, Vec::new());
|
||||
st.record_listed(uid);
|
||||
}
|
||||
let made = made(&st, ino, 0);
|
||||
drop(st);
|
||||
self.host.access_changed();
|
||||
made
|
||||
}
|
||||
|
||||
/// 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)
|
||||
&& self
|
||||
.state
|
||||
.lock()
|
||||
.entries
|
||||
.get(&ino)
|
||||
.is_some_and(|entry| entry.node.is_folder())
|
||||
{
|
||||
return Err(NamespaceError::IsDirectory);
|
||||
}
|
||||
self.trash_child(parent, name)
|
||||
}
|
||||
|
||||
/// 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 self
|
||||
.state
|
||||
.lock()
|
||||
.entries
|
||||
.get(&ino)
|
||||
.is_some_and(|entry| !entry.node.is_folder())
|
||||
{
|
||||
return Err(NamespaceError::NotDirectory);
|
||||
}
|
||||
// A missing cached listing says "unknown", not "empty". Proton's
|
||||
// trash call is recursive, so enumerate before applying rmdir's
|
||||
// POSIX emptiness rule.
|
||||
self.host.ensure_children(ino)?;
|
||||
if self.state.lock().has_children(ino) {
|
||||
return Err(NamespaceError::NotEmpty);
|
||||
}
|
||||
}
|
||||
self.trash_child(parent, name)
|
||||
}
|
||||
|
||||
/// 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 open_now = self
|
||||
.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) {
|
||||
self.host.drop_queued(&uid, open_now)?;
|
||||
self.state().forget_or_unlink(&uid);
|
||||
// A create that landed before the operations 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.host.landed_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");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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 = !self.host.sends_inline() || self.host.has_pending_moves_out_of(&uid)?;
|
||||
if queue {
|
||||
return Ok(self.host.queue_trash(&uid, name, open_now)?);
|
||||
}
|
||||
self.host.require_uid_writable(&uid)?;
|
||||
if !self.host.trash_remote(&uid, name)? {
|
||||
return Ok(self.host.queue_trash(&uid, name, open_now)?);
|
||||
}
|
||||
// Only remove the entry after Drive accepted the trash. Otherwise an
|
||||
// error answer still made the path disappear here.
|
||||
self.writes.hide(&uid);
|
||||
self.state().forget_or_unlink(&uid);
|
||||
// An open handle keeps its staged bytes, and the drain must not send
|
||||
// them to a node that is already in the trash (`docs/BUGS.md` B106).
|
||||
if let Err(error) = self.host.drop_queued(&uid, open_now) {
|
||||
warn!(%uid, ?error, "remote trash landed but queued-op cleanup failed");
|
||||
}
|
||||
if !open_now {
|
||||
self.cache.evict(&uid);
|
||||
}
|
||||
self.host.trashed(&uid, name, open_now);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// What the tree holds for `ino`, read under the same lock that made it, so
|
||||
/// the answer cannot see a later unlink.
|
||||
fn made<E>(st: &State, ino: u64, fh: u64) -> Result<Made, NamespaceError<E>> {
|
||||
let entry = st.entries.get(&ino).ok_or(NamespaceError::NotFound)?;
|
||||
Ok(Made {
|
||||
ino,
|
||||
fh,
|
||||
node: entry.node.clone(),
|
||||
access: entry.access,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn uid(link: &str) -> NodeUid {
|
||||
NodeUid::new(VolumeId::from("vol"), LinkId::from(link))
|
||||
}
|
||||
|
||||
fn node(link: &str, parent: &str, name: &str, trashed: bool) -> Node {
|
||||
let mut node = crate::nodes::local_node(uid(link), uid(parent), name.to_owned(), false);
|
||||
node.trashed = trashed;
|
||||
node
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_queue_settles_what_the_queued_path_left() {
|
||||
use ReplaceOutcome::*;
|
||||
assert_eq!(settle_from_queue(true, true, false), Some(Done));
|
||||
assert_eq!(
|
||||
settle_from_queue(false, true, false),
|
||||
Some(WithdrawVictimTrash)
|
||||
);
|
||||
assert_eq!(settle_from_queue(false, false, true), Some(Done));
|
||||
assert_eq!(settle_from_queue(false, false, false), None);
|
||||
}
|
||||
|
||||
/// The stop came after the victim went to the trash and before the
|
||||
/// source was renamed: the victim comes back.
|
||||
#[test]
|
||||
fn a_trashed_victim_comes_back_when_the_rename_did_not_happen() {
|
||||
let source = node("src", "dir", "report.odt.tmp", false);
|
||||
let victim = node("old", "dir", "report.odt", true);
|
||||
assert_eq!(
|
||||
settle_from_drive(
|
||||
&uid("dir"),
|
||||
"report.odt",
|
||||
Some(Some(&source)),
|
||||
Some(Some(&victim))
|
||||
),
|
||||
ReplaceOutcome::RestoreVictim
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_rename_keeps_its_victim_in_the_trash() {
|
||||
let source = node("src", "dir", "report.odt", false);
|
||||
let victim = node("old", "dir", "report.odt", true);
|
||||
assert_eq!(
|
||||
settle_from_drive(
|
||||
&uid("dir"),
|
||||
"report.odt",
|
||||
Some(Some(&source)),
|
||||
Some(Some(&victim))
|
||||
),
|
||||
ReplaceOutcome::Done
|
||||
);
|
||||
}
|
||||
|
||||
/// The stop came before the victim was removed: nothing to undo.
|
||||
#[test]
|
||||
fn a_victim_never_trashed_is_left_alone() {
|
||||
let source = node("src", "dir", "report.odt.tmp", false);
|
||||
let victim = node("old", "dir", "report.odt", false);
|
||||
assert_eq!(
|
||||
settle_from_drive(
|
||||
&uid("dir"),
|
||||
"report.odt",
|
||||
Some(Some(&source)),
|
||||
Some(Some(&victim))
|
||||
),
|
||||
ReplaceOutcome::Done
|
||||
);
|
||||
assert_eq!(
|
||||
settle_from_drive(&uid("dir"), "report.odt", Some(Some(&source)), Some(None)),
|
||||
ReplaceOutcome::Done
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_drive_it_waits() {
|
||||
let source = node("src", "dir", "report.odt.tmp", false);
|
||||
assert_eq!(
|
||||
settle_from_drive(&uid("dir"), "report.odt", None, None),
|
||||
ReplaceOutcome::Wait
|
||||
);
|
||||
assert_eq!(
|
||||
settle_from_drive(&uid("dir"), "report.odt", Some(Some(&source)), None),
|
||||
ReplaceOutcome::Wait
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod service_tests {
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::lockrank::Rank;
|
||||
use pdfs_store::db::LOCAL_VOLUME;
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
|
||||
|
||||
use super::*;
|
||||
use crate::nodes::local_node;
|
||||
|
||||
/// A unique temp directory removed on drop; avoids a dev-dependency.
|
||||
struct TempDir(PathBuf);
|
||||
impl TempDir {
|
||||
fn new() -> Self {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static N: AtomicU64 = AtomicU64::new(0);
|
||||
let p = std::env::temp_dir().join(format!(
|
||||
"pdfs-namespace-{}-{}",
|
||||
std::process::id(),
|
||||
N.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
std::fs::create_dir_all(&p).unwrap();
|
||||
TempDir(p)
|
||||
}
|
||||
}
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn uid(link: &str) -> NodeUid {
|
||||
NodeUid::new(VolumeId::from("vol"), LinkId::from(link))
|
||||
}
|
||||
|
||||
fn local_uid(link: &str) -> NodeUid {
|
||||
NodeUid::new(VolumeId::from(LOCAL_VOLUME), LinkId::from(link))
|
||||
}
|
||||
|
||||
/// A host that records what it was asked to do. `inline` says whether
|
||||
/// changes go to Drive now; `link_up` whether Drive answers when asked.
|
||||
struct Recorder {
|
||||
state: Arc<Ranked<State>>,
|
||||
inline: bool,
|
||||
link_up: bool,
|
||||
calls: Mutex<Vec<String>>,
|
||||
}
|
||||
|
||||
impl Recorder {
|
||||
fn record(&self, call: String) {
|
||||
self.calls.lock().push(call);
|
||||
}
|
||||
}
|
||||
|
||||
impl NamespaceHost for &'static Recorder {
|
||||
type Error = &'static str;
|
||||
|
||||
fn require_writable(&self, _ino: u64) -> Result<(), &'static str> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_uid_writable(&self, _uid: &NodeUid) -> Result<(), &'static str> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_children(&self, _ino: u64) -> Result<(), &'static str> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn lookup_child(&self, parent: u64, name: &str) -> Result<(u64, NodeUid), &'static str> {
|
||||
let st = self.state.lock();
|
||||
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")
|
||||
}
|
||||
|
||||
fn sends_inline(&self) -> bool {
|
||||
self.inline
|
||||
}
|
||||
|
||||
fn mint(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
folder: bool,
|
||||
) -> Result<Option<Node>, &'static str> {
|
||||
self.record(format!("mint {name}"));
|
||||
Ok(self.link_up.then(|| {
|
||||
local_node(
|
||||
uid(&format!("minted-{name}")),
|
||||
parent_uid.clone(),
|
||||
name.to_owned(),
|
||||
folder,
|
||||
)
|
||||
}))
|
||||
}
|
||||
|
||||
fn queue_create(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
folder: bool,
|
||||
parked: bool,
|
||||
) -> Result<Node, &'static str> {
|
||||
self.record(format!("queue create {name} parked={parked}"));
|
||||
Ok(local_node(
|
||||
local_uid(&format!("queued-{name}")),
|
||||
parent_uid.clone(),
|
||||
name.to_owned(),
|
||||
folder,
|
||||
))
|
||||
}
|
||||
|
||||
fn access_changed(&self) {}
|
||||
|
||||
fn drop_queued(&self, uid: &NodeUid, keep_staged: bool) -> Result<(), &'static str> {
|
||||
self.record(format!("drop queued {uid} keep_staged={keep_staged}"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn landed_uid(&self, _ino: u64) -> Option<NodeUid> {
|
||||
None
|
||||
}
|
||||
|
||||
fn has_pending_moves_out_of(&self, _uid: &NodeUid) -> Result<bool, &'static str> {
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn queue_trash(&self, uid: &NodeUid, _name: &str, open: bool) -> Result<(), &'static str> {
|
||||
self.record(format!("queue trash {uid} open={open}"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn trash_remote(&self, uid: &NodeUid, _name: &str) -> Result<bool, &'static str> {
|
||||
self.record(format!("trash {uid}"));
|
||||
Ok(self.link_up)
|
||||
}
|
||||
|
||||
fn trashed(&self, uid: &NodeUid, _name: &str, open: bool) {
|
||||
self.record(format!("trashed {uid} open={open}"));
|
||||
}
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
namespace: Namespace<&'static Recorder>,
|
||||
host: &'static Recorder,
|
||||
state: Arc<Ranked<State>>,
|
||||
db: Arc<Db>,
|
||||
/// The folder the tests work in.
|
||||
dir: u64,
|
||||
_dir: TempDir,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new(inline: bool, link_up: bool) -> Self {
|
||||
let tmp = TempDir::new();
|
||||
let db = Arc::new(Db::open(&tmp.0.join("cache.db")).unwrap());
|
||||
let cache = Arc::new(
|
||||
ContentCache::open(tmp.0.join("content"), tmp.0.join("pins"), 0, db.clone())
|
||||
.unwrap(),
|
||||
);
|
||||
let state = Arc::new(Ranked::new(
|
||||
Rank::State,
|
||||
State::new(db.clone(), HashMap::new()),
|
||||
));
|
||||
let host: &'static Recorder = Box::leak(Box::new(Recorder {
|
||||
state: state.clone(),
|
||||
inline,
|
||||
link_up,
|
||||
calls: Mutex::default(),
|
||||
}));
|
||||
let dir = {
|
||||
let mut st = StateGuard::new(state.lock(), &db);
|
||||
let node = local_node(uid("dir"), uid("root"), "dir".to_owned(), true);
|
||||
let ino = st.intern(0, node);
|
||||
st.entries.get_mut(&ino).unwrap().access = Access::Owner;
|
||||
st.children.insert(ino, Vec::new());
|
||||
ino
|
||||
};
|
||||
let namespace = Namespace::new(
|
||||
state.clone(),
|
||||
db.clone(),
|
||||
cache,
|
||||
WriteState::default(),
|
||||
host,
|
||||
);
|
||||
Fixture {
|
||||
namespace,
|
||||
host,
|
||||
state,
|
||||
db,
|
||||
dir,
|
||||
_dir: tmp,
|
||||
}
|
||||
}
|
||||
|
||||
fn calls(&self) -> Vec<String> {
|
||||
std::mem::take(&mut *self.host.calls.lock())
|
||||
}
|
||||
|
||||
fn listed(&self, name: &str) -> bool {
|
||||
self.host.lookup_child(self.dir, name).is_ok()
|
||||
}
|
||||
|
||||
fn state(&self) -> StateGuard<'_> {
|
||||
StateGuard::new(self.state.lock(), &self.db)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_online_create_mints_the_file_and_opens_it_for_writing() {
|
||||
let fx = Fixture::new(true, true);
|
||||
let made = fx.namespace.create(fx.dir, "a.txt").unwrap();
|
||||
assert_eq!(fx.calls(), ["mint a.txt"]);
|
||||
assert_eq!(made.node.uid, uid("minted-a.txt"));
|
||||
assert!(made.fh > 0);
|
||||
assert!(fx.listed("a.txt"));
|
||||
let st = fx.state();
|
||||
assert_eq!(st.entries[&made.ino].open_count, 1);
|
||||
assert!(st.open.writer(made.ino).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_create_that_loses_the_link_is_queued() {
|
||||
let fx = Fixture::new(true, false);
|
||||
let made = fx.namespace.create(fx.dir, "a.txt").unwrap();
|
||||
assert_eq!(
|
||||
fx.calls(),
|
||||
["mint a.txt", "queue create a.txt parked=false"]
|
||||
);
|
||||
assert!(is_local_uid(&made.node.uid));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transient_name_is_parked_and_never_minted() {
|
||||
let fx = Fixture::new(true, true);
|
||||
fx.namespace.create(fx.dir, "song.mp3.crdownload").unwrap();
|
||||
assert_eq!(fx.calls(), ["queue create song.mp3.crdownload parked=true"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_offline_mkdir_is_queued_and_listed_empty() {
|
||||
let fx = Fixture::new(false, true);
|
||||
let made = fx.namespace.mkdir(fx.dir, "sub").unwrap();
|
||||
assert_eq!(fx.calls(), ["queue create sub parked=false"]);
|
||||
assert_eq!(made.fh, 0);
|
||||
assert_eq!(fx.state().children.get(&made.ino), Some(&Vec::new()));
|
||||
// Written through when the guard drops: a restart lists it from the
|
||||
// database without asking Drive.
|
||||
let listed = fx.db.children_if_listed(&made.node.uid).unwrap();
|
||||
assert!(listed.is_some_and(|kids| kids.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlink_and_rmdir_keep_to_their_kind_of_node() {
|
||||
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;
|
||||
fx.namespace.create(sub, "inner.txt").unwrap();
|
||||
fx.calls();
|
||||
|
||||
assert!(matches!(
|
||||
fx.namespace.unlink(fx.dir, "sub"),
|
||||
Err(NamespaceError::IsDirectory)
|
||||
));
|
||||
assert!(matches!(
|
||||
fx.namespace.rmdir(fx.dir, "a.txt"),
|
||||
Err(NamespaceError::NotDirectory)
|
||||
));
|
||||
assert!(matches!(
|
||||
fx.namespace.rmdir(fx.dir, "sub"),
|
||||
Err(NamespaceError::NotEmpty)
|
||||
));
|
||||
assert!(fx.calls().is_empty());
|
||||
assert!(fx.listed("sub") && fx.listed("a.txt"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_file_trashed_on_drive_keeps_its_bytes() {
|
||||
let fx = Fixture::new(true, true);
|
||||
let made = fx.namespace.create(fx.dir, "a.txt").unwrap();
|
||||
fx.calls();
|
||||
fx.namespace.unlink(fx.dir, "a.txt").unwrap();
|
||||
let uid = made.node.uid;
|
||||
assert_eq!(
|
||||
fx.calls(),
|
||||
[
|
||||
format!("trash {uid}"),
|
||||
format!("drop queued {uid} keep_staged=true"),
|
||||
format!("trashed {uid} open=true"),
|
||||
]
|
||||
);
|
||||
assert!(!fx.listed("a.txt"));
|
||||
assert!(fx.state().entries[&made.ino].unlinked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trash_that_loses_the_link_is_queued_and_keeps_the_entry_until_then() {
|
||||
let fx = Fixture::new(true, false);
|
||||
let on_drive = uid("on-drive");
|
||||
let ino = {
|
||||
let node = local_node(on_drive.clone(), uid("dir"), "b.txt".to_owned(), false);
|
||||
let mut st = fx.state();
|
||||
let ino = st.intern(fx.dir, node);
|
||||
st.children.get_mut(&fx.dir).unwrap().push(ino);
|
||||
ino
|
||||
};
|
||||
fx.namespace.unlink(fx.dir, "b.txt").unwrap();
|
||||
assert_eq!(
|
||||
fx.calls(),
|
||||
[
|
||||
format!("trash {on_drive}"),
|
||||
format!("queue trash {on_drive} open=false"),
|
||||
]
|
||||
);
|
||||
// The queued trash hides it; the service does not drop it ahead.
|
||||
assert!(fx.state().entries.contains_key(&ino));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_queued_create_drops_it_without_a_trash() {
|
||||
let fx = Fixture::new(false, false);
|
||||
let made = fx.namespace.create(fx.dir, "a.txt").unwrap();
|
||||
fx.state().entries.get_mut(&made.ino).unwrap().open_count = 0;
|
||||
fx.calls();
|
||||
fx.namespace.unlink(fx.dir, "a.txt").unwrap();
|
||||
let uid = made.node.uid;
|
||||
assert_eq!(fx.calls(), [format!("drop queued {uid} keep_staged=false")]);
|
||||
assert!(!fx.listed("a.txt"));
|
||||
}
|
||||
}
|
||||
+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 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-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 and rmdir: 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
|
||||
`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.
|
||||
|
||||
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,7 @@ a live account since.
|
||||
|
||||
| Entry | Title |
|
||||
|---|---|
|
||||
| [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 +405,47 @@ a live account since.
|
||||
|
||||
Newest first.
|
||||
|
||||
### 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