Compare commits

..
Author SHA1 Message Date
nvrl d3f6f0b155 Merge branch 'main' into fix/withdrawn-create-ghost 2026-11-27 15:49:56 +01:00
nvrl 4e96ae8c61 Merge pull request #171 from narrrl/refactor/vfs-rename
refactor(vfs,fuse): rename through the namespace service
2026-11-27 15:49:29 +01:00
nvrl bba74b5e65 Merge pull request #170 from narrrl/refactor/vfs-namespace
refactor(vfs,fuse,store): namespace service, and settle a cut-off replacing rename (B302)
2026-11-27 14:39:35 +01:00
nvrl fd0fb66448 fix(fuse): take a withdrawn create's node out of listings already made (B303)
A file deleted while its create was on the wire leaves a node on Drive,
which the drain hides and trashes once it has the answer. Hiding kept the
node out of later listings, but a refresh taken while Drive listed it and
the drain still waited had already put it in the tree under the deleted
file's name. A new file made under that name opened the node being
trashed, and once the trash landed every write and rename of it was
refused with EACCES. Seen as a one_client_on_a_slow_link failure in CI.

Core::withdraw_landed now hides the node, removes it from every mount
and drops the kernel's entry for its name. Both places that trash a
withdrawn create's node use it.
2026-11-27 14:35:50 +01:00
nvrl 7d963b3dd7 Merge branch 'refactor/vfs-namespace' into refactor/vfs-rename 2026-11-27 14:09:58 +01:00
nvrl b7af8ae6c2 test(sim): restore a cut-off replace's victim without a listing lag
The simulation trashes the replaced file on Drive just before the
restart. Under the LAN profile a read shows that trash only after the
50 ms listing lag, so a restart quicker than that read the file as never
trashed and left it there. It failed that way in CI twice. A real stop
comes long after its own trash, so the restart now reads Drive without
the lag.
2026-11-27 14:09:55 +01:00
nvrl 5647b8e684 test(sim,store): print the daemon log when the B302 restore simulation fails
It failed once in CI with only the Drive tree to go on, and does not
reproduce locally. Also put next_run's doc comment back above it: it had
split acquire_single_writer_lock from its own.
2026-11-27 13:47:58 +01:00
nvrl b6ce90fcd5 refactor(vfs,fuse): rename through the namespace service
Namespace::rename now holds what serve_rename did: the cycle and
exchange checks, the replace checks and access gate, the B302 journal
around the victim's removal, the rewrite of a queued create's target
(B142, B70), the choice between the queue and Drive, and the restore of
the victim on failure. Drive calls, the queue and the victim's removal
and restore go through new NamespaceHost methods. The FUSE callback
maps the flags, answers, and drops the kernel's stale entries after a
queued rename.

NamespaceHost::lookup_child now returns None for a missing child, so
the service can tell an absent destination from a failed lookup.
2026-11-27 13:31:29 +01:00
nvrl 7adcdd250f refactor(vfs,fuse): create, mkdir, unlink and rmdir through the namespace service
Namespace in pdfs-vfs now decides whether a new node is minted on Drive
or queued, parks a transient name, applies the unlink and rmdir checks,
and orders a trash: Drive first, then the tree, then the queued ops and
the cache. Drive calls, the queue and the access rules go through the
NamespaceHost port, which Core implements. The FUSE callbacks keep the
inode translation, the worker lane and the reply.

The create and mkdir answers now read the new entry under the lock that
made it, so an unlink racing the reply cannot leave the answer without
an entry. Unit tests cover the paths with a recording host.
2026-11-27 13:15:09 +01:00
nvrl 7614ed6731 Merge pull request #169 from narrrl/refactor/vfs-host
refactor(vfs,fuse): an open-file service behind the FUSE adapter (step 5, slice 1)
2026-11-27 13:02:51 +01:00
nvrl 006b6f6926 fix(fuse,vfs,store): settle a replacing rename a stop cut off (B302)
Drive has no replacing rename, so rename(2) over an existing name
removes the destination first and renames the source second. A stop
between the two left the destination in Drive's trash, or with its
trash queued and no rename, and nothing recorded that a rename was
half done.

A replacing rename now writes a journal entry with a synced commit
before it removes the destination, and ends it when it returns. The
entry lives in sync_state, so the schema does not change, and carries
the opening of the database that wrote it, so a rename in progress is
never settled under it.

At mount, and on the drain's idle passes while online, Recovery
settles each entry from an earlier run with the rules in
pdfs_vfs::namespace: a queued rename stands, a queued trash with no
rename is dropped, and otherwise Drive decides whether the rename
happened or the destination comes back from the trash.
2026-11-27 13:01:15 +01:00
nvrl 251655548a docs: describe the open-file service in ARCHITECTURE.md 2026-11-27 12:40:27 +01:00
nvrl 59c6740137 refactor(vfs,fuse): close a file through the open-file service
Files::release does what the release callback and finish_release did:
retire the handle, and on the last close hand what it wrote to the
upload queue, or drop it when the file was unlinked while open. The
read view a release keeps until the revision is queued (B300) is
retired there too.

FilesHost gains commit, which follows a landed create and queues the
revision, and discard_unlinked, which drops an unlinked file's row,
queued changes and cached bytes once nothing needs them. Core
implements both with the code that was in the callback. The release
still runs on the dispatch loop, for the ordering it gives a read that
follows the close.
2026-11-27 12:39:49 +01:00
nvrl ae633c2899 fix(vfs): order overlapping fsyncs on one file (B301)
An fsync copied what the handle held, synced the scratch file and then
wrote that copy as the sidecar a restart recovers from. Two fsyncs on
the same file ran on different workers with nothing ordering them, so
the one that finished last could leave the older record on disk.

Each write handle now counts its changes in a generation and carries
a barrier. An fsync takes the barrier before it reads the handle and
keeps it until the sidecar is written. An fsync with nothing new since
the last durable generation skips the sidecar.
2026-11-27 12:36:35 +01:00
nvrl d14ed56b86 refactor(vfs,fuse): serve open, write, resize, flush and fsync from pdfs-vfs
The open-file service, pdfs_vfs::files::Files, now does what the FUSE
callbacks did inline for a file open for writing:
- a write open, with its re-check of the queued base (B32, B170, B204);
- staging a write;
- a handle-backed resize and fallocate;
- the flush of a dirty scratch file;
- the fsync barrier and its durability sidecar.

It returns FileError, which the adapter maps to the same errno values as
before. What it needs from Drive and the drain goes through FilesHost,
which Core implements: settling a provisional size, filling gaps from
the remote base, and the node an upload just landed.

remote_baseline becomes WriteState::baseline, and is_local_uid moves to
pdfs_vfs::ids. New tests drive the service with an offline host and no
kernel.
2026-11-27 12:32:28 +01:00
nvrl a13ca95a83 refactor(vfs,fuse): move the tree's kernel-free rules into pdfs-vfs
- merge_over_pending and copy_pending_for_truncate, which fold a queued
  revision into a newer write, move to pdfs_vfs::open with their tests.
- The last release of an unlinked inode becomes State::release_unlinked,
  and listed_children moves to pdfs_vfs::tree.
- Which nodes a folder shows, how queued changes lie over a listing, and
  the node a create makes before Drive has seen it move to pdfs_vfs::nodes.
- The component-name and rename-replace checks move to pdfs_vfs::names
  and return NameError and ReplaceError. The FUSE adapter maps them to
  the same errno values as before.
2026-11-27 12:19:11 +01:00
nvrl 7978a40224 refactor(vfs,fuse): let the tree build a directory's listing
The listing a readdir pages through is built from the tree alone, so it
moves from filesystem.rs to State::listing in pdfs-vfs.
2026-11-27 12:13:34 +01:00
nvrl c44c1bccb5 Merge pull request #168 from narrrl/refactor/vfs-open-files
refactor(vfs,fuse): start pdfs-vfs with the tree and the open files
2026-11-27 10:25:29 +01:00
nvrl 275f40b24b refactor(vfs,fuse): move the read of an open file into pdfs-vfs
A read of a file open for writing takes the written ranges from the
scratch file, asks the base for the rest, and zero-fills past the base.
That assembly moves to `pdfs_vfs::open::assemble_open_read`, with its
test. It is generic over the base's error. A failed scratch read comes
back as `ReadFailure::Scratch`. The read path maps that to `EIO` and logs
it, as before, and passes the base's own errno through.
2026-11-27 02:10:14 +01:00
nvrl 695a810cea refactor(vfs,fuse): move the write-back's state into pdfs-vfs
`WriteState` holds three things:
- the revisions the mount accepted but has not uploaded;
- the nodes removed here that a stale listing may still return;
- the echoes the event feed owes for changes this daemon made.

It moves from `pdfs-fuse/src/writes.rs` to `pdfs_vfs::writes`. The echo
bookkeeping it uses moves with it, together with its test. `pdfs-fuse`
keeps `Core::note_self_change` and `Core::take_self_change`, which stamp
the time and call it.

There is no behaviour change.
2026-11-27 02:06:07 +01:00
nvrl 9dbb4c9950 fix(vfs,fuse): serve a read during a release from the write it is queueing (B300)
A release took the write state out of the open files, then queued the new
revision. A read that ran on a worker in between found neither, and could
be served the revision on Drive from before the write. An `open` and `read`
issued after `close(2)` are ordered behind the release, because both go
through the dispatch loop. A read through a handle opened earlier is not.

`OpenFiles` now keeps a read view of the writer until `finish_release`:
its scratch file, length, base and written ranges. This replaces the set
of releasing inodes. `OpenFiles::reader` answers from an open writer or
from that view, and both read paths ask it first.
2026-11-27 02:01:38 +01:00
nvrl c5884ba638 refactor(vfs,fuse): move the tree into pdfs-vfs
`State` is the tree every mount shows. It holds the nodes by inode, the
stable inode numbers from local ids, each session's root, and the open
files. It moves from `pdfs-fuse/src/state.rs` to `pdfs_vfs::tree`, with its
tests. `pdfs-fuse` keeps its paths through `use pdfs_vfs::tree as state`.

It needed three things from `pdfs-fuse`, and these move to
`pdfs_vfs::ids`:
- the root inode;
- the orphan inode;
- the check for nodes on the made-up virtual volume.

Its one kernel type was the `fuser::Errno` that `require_writable` returned.
That becomes `tree::NodeError`, which the FUSE adapter maps to `ENOENT` or
`EACCES`, as before.

The helpers other crates' tests use to inspect a tree are behind the
`test-support` feature. `pdfs-fuse` enables it for its tests only.

There is no behaviour change.
2026-11-27 01:57:11 +01:00
nvrl 860593b655 refactor(vfs,fuse): move fallocate rules and directory handles into pdfs-vfs
The rules for which `fallocate` modes a write handle can record, and what
each one does to the authored ranges and the length, lived in the FUSE
callback. They are now `pdfs_vfs::open::Fallocate` and
`WriteHandle::record_fallocate`. The callback runs the syscall and records
the result, as before.

Directory handles join `OpenFiles`. The frozen listing an `opendir` takes,
and the paging of a `readdir` through it (`dir_page`), no longer sit on
`State` and in the reply code. File and directory handles now draw from the
same counter in the same table, which was the reason they had to share one.

There is no behaviour change.
2026-11-27 01:52:04 +01:00
nvrl 4dcc2aa04e refactor(vfs,fuse): keep the open files in one table in pdfs-vfs
`State` carried four loose fields for open files:
- the write state by inode;
- the inode behind each handle;
- the inodes being released;
- the next handle number.

Eleven modules read and changed them directly. The release callback did
the reference counting by hand. Finding unsaved changes meant chaining two
of the maps in two places.

`pdfs_vfs::open::OpenFiles` now owns them. It opens a writer and returns
the handle number, looks a writer up by inode or by handle, and says
whether an inode is busy or owes changes. It hands back the write state
on the last release, and marks the inode as releasing until
`finish_release`. One counter still serves file and directory handles.
The FUSE adapter and the rest of `pdfs-fuse` call these methods. There
is no behaviour change.
2026-11-27 01:47:18 +01:00
nvrl d891e24e96 refactor(vfs,fuse): start pdfs-vfs with the open file
Step 5 of the 4.0 plan moves the mounted-files side out of `pdfs-fuse` into
a service that does not know about the kernel. This starts the `pdfs-vfs`
crate with the open file:
- `Intervals`, the ranges of a scratch file written here;
- `WriteHandle`, a file open for writing;
- `PendingRevision`, a released write waiting for its upload.

They move unchanged from `pdfs-fuse/src/state.rs`, with their tests.

Writing the scratch file moves too. `stage_write` reports a full disk as
`WriteError::NoSpace` instead of an `io::Error` the caller has to inspect.
The FUSE adapter maps it to `ENOSPC` and frees cache space, as before.

`node_size` moves to `pdfs-drive`, next to `node_revision_id`, so both
crates use one copy. `pdfs-vfs` depends on neither `fuser` nor GTK.
2026-11-27 01:42:52 +01:00
nvrl 957a7ff391 Merge pull request #167 from narrrl/refactor/joined-workers
refactor(core,fuse): join jobs on stop and run the mount's loops as services
2026-11-27 01:34:57 +01:00
nvrl d9881810b7 Merge pull request #166 from narrrl/refactor/devices-service
refactor(fuse): make the device records and the profile backup services
2026-11-27 01:33:47 +01:00
nvrl 89b3fce38d Merge pull request #163 from narrrl/refactor/write-state
refactor(fuse): put shared write-back, session and link state behind narrow interfaces
2026-11-26 20:15:54 +01:00
37 changed files with 5817 additions and 2782 deletions

No files matched your search

Generated
+14
View File
@@ -3729,6 +3729,7 @@ dependencies = [
"pdfs-drive",
"pdfs-store",
"pdfs-sync",
"pdfs-vfs",
"proton-drive-rs",
"proton-gallery-app-rs",
"proton-gallery-rs",
@@ -3800,6 +3801,19 @@ dependencies = [
"tracing",
]
[[package]]
name = "pdfs-vfs"
version = "3.10.0"
dependencies = [
"libc",
"parking_lot 0.13.0",
"pdfs-core",
"pdfs-drive",
"pdfs-store",
"proton-drive-rs",
"tracing",
]
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
+2 -1
View File
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["crates/pdfs-core", "crates/pdfs-store", "crates/pdfs-drive", "crates/pdfs-sync", "crates/pdfs-fuse", "crates/pdfs-daemon", "crates/pdfs-cli", "crates/pdfs-gui"]
members = ["crates/pdfs-core", "crates/pdfs-store", "crates/pdfs-drive", "crates/pdfs-sync", "crates/pdfs-vfs", "crates/pdfs-fuse", "crates/pdfs-daemon", "crates/pdfs-cli", "crates/pdfs-gui"]
[workspace.package]
version = "3.10.0"
@@ -27,6 +27,7 @@ pdfs-core = { path = "crates/pdfs-core" }
pdfs-store = { path = "crates/pdfs-store" }
pdfs-drive = { path = "crates/pdfs-drive" }
pdfs-sync = { path = "crates/pdfs-sync" }
pdfs-vfs = { path = "crates/pdfs-vfs" }
pdfs-fuse = { path = "crates/pdfs-fuse" }
pdfs-daemon = { path = "crates/pdfs-daemon" }
+13
View File
@@ -599,6 +599,19 @@ pub fn is_network_error(e: &ProtonError) -> bool {
}
}
/// A node's plaintext size as far as its listing knows: the claimed size when
/// the revision carries one, else the size on storage. Zero for a folder.
pub fn node_size(node: &Node) -> u64 {
match &node.kind {
NodeKind::Folder => 0,
NodeKind::File {
claimed_size,
total_size_on_storage,
..
} => claimed_size.unwrap_or(*total_size_on_storage).max(0) as u64,
}
}
/// The server revision id of a node's active revision, if it is a file that has
/// one. The stable identity the drain conflict-checks against (see `Baseline` in pdfs-store).
pub fn node_revision_id(node: &Node) -> Option<String> {
+2
View File
@@ -13,6 +13,7 @@ description = "FUSE on-demand filesystem for Proton Drive"
pdfs-core.workspace = true
pdfs-drive.workspace = true
pdfs-sync.workspace = true
pdfs-vfs.workspace = true
pdfs-store.workspace = true
zip.workspace = true
sha1.workspace = true
@@ -41,6 +42,7 @@ notify = "8"
parking_lot.workspace = true
[dev-dependencies]
pdfs-vfs = { workspace = true, features = ["test-support"] }
pdfs-drive = { workspace = true, features = ["sim"] }
tracing-subscriber.workspace = true
tokio = { workspace = true, features = ["test-util"] }
+6 -2
View File
@@ -42,7 +42,6 @@ use tracing::{debug, error, info, warn};
use super::link::{self, is_network_error};
use super::photos::sha1_of;
use super::state::{Intervals, PendingRevision};
use super::transfers::CountingReader;
use super::{
Core, DRAIN_BACKOFF_MAX, DRAIN_BACKOFF_MIN, DRAIN_IDLE_POLL, DRAIN_REVISION_DEBOUNCE,
@@ -50,6 +49,7 @@ use super::{
is_already_exists, is_gone, is_local_uid_str, media_type_for, node_revision_id, node_size,
now_millis, now_secs, parse_node_uid,
};
use pdfs_vfs::open::{Intervals, PendingRevision};
use proton_drive_rs::proton_sdk::api::ResponseCode;
use proton_drive_rs::proton_sdk::error::ProtonError;
@@ -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.
@@ -1135,9 +1139,9 @@ fn placed_in(st: &crate::state::State, uid: &NodeUid) -> Option<(String, Option<
#[cfg(test)]
mod tests {
use super::*;
use crate::state::WriteHandle;
use pdfs_core::Access;
use pdfs_store::db::Db;
use pdfs_vfs::open::WriteHandle;
use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
use std::cell::Cell;
+1 -1
View File
@@ -564,7 +564,7 @@ impl Core {
}
}
}
for aw in st.active_writes.values_mut() {
for aw in st.open.writers_mut() {
if aw.uid == *local {
aw.uid = real.clone();
}
+1 -1
View File
@@ -647,7 +647,7 @@ impl Core {
/// daemon has just put there itself (`WriteHandle::rebase_onto`).
pub(crate) fn rebase_open_writes(&self, uid: &NodeUid, node: &Node) {
self.for_each_state(|st| {
for aw in st.active_writes.values_mut() {
for aw in st.open.writers_mut() {
if aw.uid == *uid {
aw.rebase_onto(node);
debug!(%uid, mtime = aw.base_mtime, size = aw.base_size,
+17 -2
View File
@@ -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,
-56
View File
@@ -19,59 +19,3 @@ impl Core {
self.writes.take_echo(uid, now_millis())
}
}
/// How long a change this daemon made stays recognisable as its own. Generous
/// against a feed that can lag, but finite: past it, an event for the node is
/// applied like any other. See [`writes::WriteState`].
pub(super) const SELF_CHANGE_TTL_MS: i64 = 120_000;
/// A remote change this daemon made, awaiting its echo from the event feed.
pub(super) struct SelfChange {
/// When we made it, in the same epoch millis as [`now_millis`].
at_ms: i64,
/// Echoes not yet seen. More than one because a single file can be created
/// and then have a revision uploaded, and the feed reports both.
echoes: u32,
}
/// Record one remote change this daemon made. Split from [`Core`] so the
/// expiry and echo-counting rules can be tested against a clock the test owns.
pub(super) fn note_self_change(
changes: &mut HashMap<NodeUid, SelfChange>,
uid: &NodeUid,
now_ms: i64,
) {
// Echoes that never arrived — a node trashed before its event came round, a
// feed that skipped it — would otherwise accumulate for the life of the
// daemon. Pruning on write keeps the map the size of the recent queue.
changes.retain(|_, c| now_ms - c.at_ms < SELF_CHANGE_TTL_MS);
let change = changes.entry(uid.clone()).or_insert(SelfChange {
at_ms: now_ms,
echoes: 0,
});
change.at_ms = now_ms;
change.echoes += 1;
}
/// Claim one echo, per [`Core::take_self_change`].
pub(super) fn take_self_change(
changes: &mut HashMap<NodeUid, SelfChange>,
uid: &NodeUid,
now_ms: i64,
) -> bool {
let Some(change) = changes.get_mut(uid) else {
return false;
};
// Too old to attribute: the feed is far enough behind that this is as likely
// to be someone else's change as ours, and guessing wrong here costs the user
// a stale file.
if now_ms - change.at_ms >= SELF_CHANGE_TTL_MS {
changes.remove(uid);
return false;
}
change.echoes -= 1;
if change.echoes == 0 {
changes.remove(uid);
}
true
}
+8 -18
View File
@@ -15,12 +15,12 @@ impl Core {
pub(crate) fn queue_unreleased_writes(&self) {
let handles: Vec<(WriteHandle, bool)> = {
let mut st = self.state();
st.handles.clear();
let inos: Vec<u64> = st.active_writes.keys().copied().collect();
inos.into_iter()
.filter_map(|ino| {
let unlinked = st.entries.get(&ino).is_some_and(|e| e.unlinked);
st.active_writes.remove(&ino).map(|h| (h, unlinked))
let writers = st.open.take_all();
writers
.into_iter()
.map(|h| {
let unlinked = st.entries.get(&h.ino).is_some_and(|e| e.unlinked);
(h, unlinked)
})
.collect()
};
@@ -201,18 +201,8 @@ impl Core {
base_size: u64,
base_revision_id: Option<String>,
) -> Option<Baseline> {
if is_local_uid(uid) {
return None;
}
match self.writes.pending.lock().get(uid) {
Some(p) => p.meta.based_on.clone(),
None => Some(Baseline {
mtime: base_mtime,
size: base_size,
hash: None,
revision_id: base_revision_id,
}),
}
self.writes
.baseline(uid, base_mtime, base_size, base_revision_id)
}
/// Move a file holding a node's intended new content into staging and queue
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+3
View File
@@ -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.
+20 -103
View File
@@ -1,6 +1,7 @@
//! Revision-reader cache and streamed range-read subsystem.
use super::*;
use pdfs_vfs::open::{ReadFailure, assemble_open_read};
/// A read of an unpinned video at least this large streams *without* persisting
/// its blocks to the on-disk cache. Playing a 2 GB film would otherwise pour it
@@ -1049,10 +1050,11 @@ impl Core {
offset: u64,
size: u64,
) -> Result<Vec<u8>, Errno> {
let read = assemble_open_read(file, len, uid, base_size, written, offset, size, |s, n| {
let read = assemble_open_read(file, len, base_size, written, offset, size, |s, n| {
self.read_range(uid, base_mtime, base_size, s, n, true)
.map(Some)
})?;
})
.map_err(|failure| open_read_errno(uid, failure))?;
Ok(read.unwrap_or_default())
}
@@ -1075,9 +1077,10 @@ impl Core {
offset: u64,
size: u64,
) -> Result<Option<Vec<u8>>, Errno> {
assemble_open_read(file, len, uid, base_size, written, offset, size, |s, n| {
assemble_open_read(file, len, base_size, written, offset, size, |s, n| {
Ok(self.cached_range(uid, base_mtime, base_size, s, n))
})
.map_err(|failure| open_read_errno(uid, failure))
}
/// Bytes `[offset, offset + size)` of file `ino` as `read` would serve
@@ -1094,16 +1097,12 @@ impl Core {
offset: u64,
size: u64,
) -> Result<Option<Vec<u8>>, Errno> {
let handle = self.state().active_writes.get(&ino).map(|h| {
(
h.file.clone(),
h.len,
h.uid.clone(),
h.base_mtime,
h.base_size,
h.written.clone(),
)
});
// A writer still open, or one whose release is still queueing it.
let handle = self
.state()
.open
.reader(ino)
.map(|v| (v.file, v.len, v.uid, v.base_mtime, v.base_size, v.written));
if let Some((file, len, uid, base_mtime, base_size, written)) = handle {
return self.serve_open_read_local(
&file, len, &uid, base_mtime, base_size, &written, offset, size,
@@ -1305,47 +1304,16 @@ impl Core {
}
}
/// The bytes `[offset, offset + size)` of a file open for writing: authored
/// ranges from its scratch `file`, the rest from its base through `base`,
/// and zeros past the base. `Ok(None)` when `base` says it cannot answer.
#[allow(clippy::too_many_arguments)]
fn assemble_open_read(
file: &File,
len: u64,
uid: &NodeUid,
base_size: u64,
written: &Intervals,
offset: u64,
size: u64,
mut base: impl FnMut(u64, u64) -> Result<Option<Vec<u8>>, Errno>,
) -> Result<Option<Vec<u8>>, Errno> {
if offset >= len || size == 0 {
return Ok(Some(Vec::new()));
}
let end = offset.saturating_add(size).min(len);
let mut out = Vec::with_capacity((end - offset) as usize);
for (s, e, authored) in written.segments(offset, end) {
if authored {
let mut buf = vec![0u8; (e - s) as usize];
file.read_exact_at(&mut buf, s).map_err(|err| {
warn!(%uid, error = %err, "scratch read failed");
Errno::EIO
})?;
out.extend_from_slice(&buf);
} else {
let bend = e.min(base_size);
if s < bend {
match base(s, bend - s)? {
Some(bytes) => out.extend_from_slice(&bytes),
None => return Ok(None),
}
}
// Anything past the base is a hole: zero-fill.
let zeros = e.saturating_sub(s.max(base_size));
out.resize(out.len() + zeros as usize, 0);
/// The errno for a read of an open file that failed: the base's own, or
/// `EIO` for the scratch file.
fn open_read_errno(uid: &NodeUid, failure: ReadFailure<Errno>) -> Errno {
match failure {
ReadFailure::Base(errno) => errno,
ReadFailure::Scratch(error) => {
warn!(%uid, %error, "scratch read failed");
Errno::EIO
}
}
Ok(Some(out))
}
#[cfg(test)]
@@ -1500,54 +1468,3 @@ mod prefetch_tests {
assert!(prefetch.streams.lock().len() <= MAX_PREFETCH_STREAMS + 1);
}
}
#[cfg(test)]
mod open_read_tests {
use super::*;
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
fn scratch(bytes: &[u8]) -> (File, PathBuf) {
let path = std::env::temp_dir().join(format!(
"pdfs-open-read-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let mut file = File::options()
.create_new(true)
.read(true)
.write(true)
.open(&path)
.unwrap();
file.write_all(bytes).unwrap();
(file, path)
}
/// The dispatch loop answers from what is on this machine and says so
/// when the base would have to be downloaded, for a worker to do it
/// (`docs/BUGS.md` B227).
#[test]
fn a_read_needing_the_base_says_so_instead_of_fetching() {
let uid = NodeUid::new(VolumeId::from("v"), LinkId::from("f"));
let (file, path) = scratch(b"ABCDEFGH");
let mut written = Intervals::default();
written.add(0, 4);
let authored = assemble_open_read(&file, 8, &uid, 8, &written, 0, 4, |_, _| {
panic!("an authored range never asks the base")
});
assert_eq!(authored.unwrap().as_deref(), Some(&b"ABCD"[..]));
let missing = assemble_open_read(&file, 8, &uid, 8, &written, 2, 6, |_, _| Ok(None));
assert_eq!(missing.unwrap(), None);
let base = assemble_open_read(&file, 10, &uid, 8, &written, 2, 8, |s, n| {
assert_eq!((s, n), (4, 4));
Ok(Some(b"efgh".to_vec()))
});
assert_eq!(base.unwrap().as_deref(), Some(&b"CDefgh\0\0"[..]));
let _ = std::fs::remove_file(path);
}
}
+129 -1
View File
@@ -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
@@ -96,7 +97,7 @@ impl Core {
st.hydrate_access();
// Pass 3: rebuild child listings for fully-enumerated folders.
let listings = listed_children(&st.entries, listed_dirs);
let listings = crate::state::listed_children(&st.entries, listed_dirs);
st.children.extend(listings);
info!(nodes = st.entries.len(), "hydrated metadata cache from db");
}
@@ -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 —
+1 -5
View File
@@ -453,11 +453,7 @@ impl Core {
// longer has that uid, so the move went ahead under an open write.
let mut writing = false;
self.for_each_state(|st| {
writing = st
.active_writes
.keys()
.chain(&st.releasing)
.any(|&open| ino_is_under(st, open, ino));
writing = st.open.owed(false).any(|open| ino_is_under(st, open, ino));
});
Ok(writing)
}
+2 -5
View File
@@ -485,11 +485,8 @@ impl Core {
// Unsaved writes, or a release still queueing them, to the file or,
// for a folder, to any file below it.
let unsaved = st
.active_writes
.iter()
.filter(|(_, w)| w.dirty)
.map(|(&open, _)| open)
.chain(st.releasing.iter().copied())
.open
.owed(true)
.any(|open| relocate::ino_is_under(&st, open, ino));
(entry.node.name.clone(), entry.node.is_folder(), unsaved)
};
+176
View File
@@ -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();
}
}
+1 -1
View File
@@ -332,7 +332,7 @@ impl Core {
};
changed.push(ino);
// An open write handle is ahead of the server too (B109).
if st.active_writes.contains_key(&ino) {
if st.open.is_writing(ino) {
continue;
}
let NodeKind::File { claimed_size, .. } = &node.kind else {
+1 -2
View File
@@ -189,8 +189,7 @@ impl Core {
let Some(&ino) = st.by_uid.get(uid) else {
return;
};
busy |=
st.active_writes.contains_key(&ino) || st.handles.values().any(|&held| held == ino);
busy |= st.open.is_busy(ino);
});
busy
}
+1 -5
View File
@@ -6,7 +6,7 @@ use std::time::{Duration, Instant};
use proton_drive_rs::proton_sdk::ids::{LinkId, NodeUid, VolumeId};
use proton_drive_rs::{Node, NodeKind};
pub(crate) const VIRTUAL_VOLUME: &str = "virtual";
pub(crate) use pdfs_vfs::ids::{VIRTUAL_VOLUME, is_virtual_uid};
pub(crate) const SHARED_WITH_ME_LINK: &str = "sharedwithme";
pub(crate) const SHARED_WITH_ME_BASE: &str = "Shared with me";
const MAX_COMPONENT_BYTES: usize = 255;
@@ -18,10 +18,6 @@ pub(crate) fn shared_with_me_uid() -> NodeUid {
)
}
pub(crate) fn is_virtual_uid(uid: &NodeUid) -> bool {
uid.volume_id.as_str() == VIRTUAL_VOLUME
}
pub(crate) fn is_own_or_virtual_uid(uid: &NodeUid, own_volume: &VolumeId) -> bool {
uid.volume_id == *own_volume || is_virtual_uid(uid)
}
-110
View File
@@ -1,110 +0,0 @@
//! What the mount accepted and has not yet sent to Drive (`WriteState`).
use super::*;
/// The write-back's state: writes accepted from the kernel and not yet sent,
/// nodes removed here that a stale listing may still return, and the changes
/// this daemon made that Drive's event feed will echo back.
///
/// The drain, the queue and recovery own it. Everything else, the read path,
/// listings, the pin keeper and the event feed, asks through the methods
/// below instead of taking its locks.
#[derive(Clone)]
pub(crate) struct WriteState {
/// Writes accepted from the kernel but not yet uploaded, keyed by node.
/// The in-memory face of the `pending_op` table, from
/// which it is rebuilt on mount.
///
/// Two things read it: [`Core::read_range`], because until the op drains the
/// staged blob *is* the file's content and the remote still holds the old
/// revision; and the drain worker, which performs the uploads.
pub(crate) pending: Arc<Mutex<HashMap<NodeUid, PendingRevision>>>,
/// Nodes removed through this daemon which a briefly stale remote listing
/// may still return. Uids are not reused; an explicit restore clears one.
hidden: Arc<Mutex<HashSet<NodeUid>>>,
/// Nodes this daemon changed on the remote itself, and how many echoes of
/// those changes the event feed still owes us.
///
/// The feed replays our own writes back at us seconds later, and a
/// `NodeUpdated` carries no revision id — nothing in it distinguishes "another
/// device changed this file" from "you changed this file". Treating the echo
/// as foreign is not free: it evicts the content blob we just uploaded, so the
/// next read re-downloads a revision the API may not be serving yet. That is
/// how a SQLite database written on the mount came back `malformed`, and how a
/// mount doing bulk uploads spent its time re-fetching its own bytes.
///
/// So the first event for a node we changed ourselves, within
/// [`SELF_CHANGE_TTL_MS`], is consumed rather than applied: the tree already
/// holds what that event describes, because [`Core::refresh_after_upload`] put
/// it there. Anything beyond that applies normally, which bounds the staleness
/// a genuine remote change can suffer to one event.
///
/// Shared across forks like `pending`: the drain that records the change and
/// the event task that consumes the echo are both per-daemon.
self_changes: Arc<Mutex<HashMap<NodeUid, echoes::SelfChange>>>,
}
impl WriteState {
pub(crate) fn new() -> Self {
Self {
pending: Arc::new(Mutex::new(HashMap::new())),
hidden: Arc::new(Mutex::new(HashSet::new())),
self_changes: Arc::new(Mutex::new(HashMap::new())),
}
}
/// The write queued for `uid`, if any: its staged blob is the file's
/// content until the drain sends it.
pub(crate) fn queued(&self, uid: &NodeUid) -> Option<PendingRevision> {
self.pending.lock().get(uid).cloned()
}
/// Whether a write for `uid` is queued and not yet sent. A remote change
/// to such a node is not applied over it.
pub(crate) fn is_queued(&self, uid: &NodeUid) -> bool {
self.pending.lock().contains_key(uid)
}
/// The size the queued write for `uid` gives the file, if one is queued.
pub(crate) fn queued_len(&self, uid: &NodeUid) -> Option<u64> {
self.pending.lock().get(uid).map(|queued| queued.meta.len)
}
/// The size each queued write gives its file. Empty when nothing is
/// queued.
pub(crate) fn queued_sizes(&self) -> HashMap<NodeUid, u64> {
self.pending
.lock()
.iter()
.map(|(uid, queued)| (uid.clone(), queued.meta.len))
.collect()
}
/// The nodes removed here that a listing must leave out, even if Drive
/// still returns them.
pub(crate) fn hidden(&self) -> HashSet<NodeUid> {
self.hidden.lock().clone()
}
/// Leave `uid` out of listings from now on: it was removed here.
pub(crate) fn hide(&self, uid: &NodeUid) {
self.hidden.lock().insert(uid.clone());
}
/// List `uid` again: it was restored or put back.
pub(crate) fn unhide(&self, uid: &NodeUid) {
self.hidden.lock().remove(uid);
}
/// Record that this daemon just changed `uid` on Drive, so the event
/// feed's echo of the change is recognised (see [`echoes`]).
pub(crate) fn note_echo(&self, uid: &NodeUid, now_ms: i64) {
echoes::note_self_change(&mut self.self_changes.lock(), uid, now_ms);
}
/// Claim one outstanding echo for `uid`: whether the event being applied
/// is one this daemon caused.
pub(crate) fn take_echo(&self, uid: &NodeUid, now_ms: i64) -> bool {
echoes::take_self_change(&mut self.self_changes.lock(), uid, now_ms)
}
}
+28
View File
@@ -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
+105
View File
@@ -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)
}
}
+39
View File
@@ -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());
}
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "pdfs-vfs"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
rust-version.workspace = true
repository.workspace = true
homepage.workspace = true
description = "The mounted-files service of the Proton Drive Linux client, without a kernel adapter"
[features]
# Helpers that let other crates' tests build and inspect a tree.
test-support = []
[dependencies]
pdfs-core.workspace = true
pdfs-drive.workspace = true
pdfs-store.workspace = true
proton-drive-rs.workspace = true
libc.workspace = true
parking_lot.workspace = true
tracing.workspace = true
File diff suppressed because it is too large. Load diff
+27
View File
@@ -0,0 +1,27 @@
//! Inode numbers the tree reserves, and the volume of nodes that only exist
//! here.
use proton_drive_rs::proton_sdk::ids::NodeUid;
/// The root inode of every session. Each session calls its own root 1.
pub const ROOT_INO: u64 = 1;
/// Parent inode for a persisted node whose parent row is missing from the
/// database. No folder carries this inode, so such a node is listed by nobody
/// and stays inert until a live enumeration re-parents it.
pub const ORPHAN_INO: u64 = 0;
/// The volume id of the folders this client makes up, such as "Shared with
/// me". No such volume exists on Drive.
pub const VIRTUAL_VOLUME: &str = "virtual";
/// Whether `uid` names a folder this client made up rather than a Drive node.
pub fn is_virtual_uid(uid: &NodeUid) -> bool {
uid.volume_id.as_str() == VIRTUAL_VOLUME
}
/// Whether this node exists only on this machine, so far. Such a uid is
/// meaningless to the API and must never be sent to it.
pub fn is_local_uid(uid: &NodeUid) -> bool {
uid.volume_id.as_str() == pdfs_store::db::LOCAL_VOLUME
}
+26
View File
@@ -0,0 +1,26 @@
//! The mounted-files service: what a file open through a mount is, and what
//! happens to its bytes between `open` and `close`.
//!
//! Step 5 of the 4.0 plan in `docs/ARCHITECTURE.md` moves the mount's
//! state here, slice by slice, so that it can be built and tested without a
//! kernel. Nothing in this crate knows about `fuser` or errno: the FUSE
//! adapter in `pdfs-fuse` maps the typed errors at the boundary.
//!
//! So far it holds the tree ([`tree`]): the nodes a mount shows, their
//! stable inode numbers, and the per-mount roots; and the open files
//! ([`open`]): the scratch file a handle writes into, which bytes of it are
//! 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`]); 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;
pub mod writes;
+110
View File
@@ -0,0 +1,110 @@
//! The POSIX rules on names and on what a rename may replace.
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
/// Why a pathname component cannot name a node.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NameError {
/// Longer than `NAME_MAX` (255 bytes).
TooLong,
/// Empty, `.` or `..`.
Reserved,
/// Not UTF-8, which Drive requires.
NotUtf8,
}
/// Why a rename may not replace its destination.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReplaceError {
/// A file would replace a directory.
IsDirectory,
/// A directory would replace a file.
NotDirectory,
/// The directory to replace is not empty.
NotEmpty,
}
/// Convert one kernel pathname component into the UTF-8 name accepted by Drive.
/// Linux filesystems conventionally cap a component at `NAME_MAX` (255 bytes),
/// but the FUSE kernel path can pass a longer component through to userspace.
pub fn component(name: &OsStr) -> Result<String, NameError> {
let bytes = name.as_bytes();
if bytes.len() > 255 {
return Err(NameError::TooLong);
}
if bytes.is_empty() || bytes == b"." || bytes == b".." {
return Err(NameError::Reserved);
}
name.to_str().map(str::to_owned).ok_or(NameError::NotUtf8)
}
/// Whether a `rename` may replace an existing destination, per POSIX.
///
/// Split out from the handler because it is the part that is pure and the part
/// that is dangerous: every `Err` here is a refusal that happens *before*
/// anything is trashed, and getting one wrong turns a refusal into the
/// destruction of the destination (`docs/BUGS.md` B13).
///
/// `dst_empty` is only meaningful when `dst_dir`; pass `true` otherwise.
pub fn check_replaceable(
src_dir: bool,
dst_dir: bool,
dst_empty: bool,
) -> Result<(), ReplaceError> {
match (src_dir, dst_dir) {
// A non-directory may not replace a directory, or vice versa.
(false, true) => Err(ReplaceError::IsDirectory),
(true, false) => Err(ReplaceError::NotDirectory),
// Proton trashes a folder with its whole subtree, so replacing a
// non-empty one would silently take its contents with it. POSIX says
// ENOTEMPTY, which is also the safe answer.
(true, true) if !dst_empty => Err(ReplaceError::NotEmpty),
_ => Ok(()),
}
}
#[cfg(test)]
mod replace_tests {
use super::{ReplaceError, check_replaceable};
/// The case that motivated all of this: rsync renaming its temp file over
/// the real one. Two plain files, and it has to be allowed — refusing is
/// what made every rsync transfer fail at the last step (`docs/BUGS.md` B13).
#[test]
fn a_file_may_replace_a_file() {
assert!(check_replaceable(false, false, true).is_ok());
}
#[test]
fn an_empty_directory_may_be_replaced_by_a_directory() {
assert!(check_replaceable(true, true, true).is_ok());
}
/// Proton trashes a folder with its whole subtree, so allowing this would
/// discard every file under the destination without ever naming them.
#[test]
fn a_non_empty_directory_is_never_replaced() {
let e = check_replaceable(true, true, false).expect_err("must refuse");
assert_eq!(e, ReplaceError::NotEmpty);
}
#[test]
fn the_two_ends_must_agree_on_being_a_directory() {
assert_eq!(
check_replaceable(false, true, true).expect_err("a file may not replace a directory"),
ReplaceError::IsDirectory
);
assert_eq!(
check_replaceable(true, false, true).expect_err("a directory may not replace a file"),
ReplaceError::NotDirectory
);
}
/// `dst_empty` describes a directory; it must not leak into the file case,
/// where callers pass `true` by convention.
#[test]
fn emptiness_is_ignored_when_the_destination_is_a_file() {
assert!(check_replaceable(false, false, false).is_ok());
}
}
File diff suppressed because it is too large. Load diff
+193
View File
@@ -0,0 +1,193 @@
//! Rules about the nodes a mount lists that need neither the kernel nor Drive:
//! which of them a folder shows, how queued changes lie over a listing, and
//! what a node made here looks like before Drive has seen it.
use std::collections::{HashMap, HashSet};
use pdfs_core::timestamp::now_secs;
use pdfs_drive::{media_type_for, remote_name_is_safe};
use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{Node, NodeKind};
use tracing::warn;
/// Fabricate the node the server would have returned, for a `create`/`mkdir`
/// that could not reach it. Everything the kernel asks about a fresh node —
/// name, kind, size, times — is knowable locally; the uid is the only invention,
/// and the drain replaces it with the real one.
pub fn local_node(uid: NodeUid, parent_uid: NodeUid, name: String, is_dir: bool) -> Node {
let now = now_secs();
Node {
uid,
parent_uid: Some(parent_uid),
kind: if is_dir {
NodeKind::Folder
} else {
NodeKind::File {
media_type: media_type_for(&name).to_string(),
total_size_on_storage: 0,
// No revision has been sealed: nothing has been uploaded yet.
active_revision_state: None,
active_revision_id: None,
content_sha1: None,
claimed_size: Some(0),
claimed_modification_time: None,
}
},
name,
creation_time: now,
modification_time: now,
trashed: false,
is_shared: false,
is_shared_publicly: false,
signature_email: None,
membership: None,
// A locally fabricated node is on the main volume, never a photo/album.
photo: None,
album: None,
// Nothing signed it: it has never been near the crypto layer.
verification: Default::default(),
direct_role: None,
share_id: None,
}
}
/// Whether `node` is a file Drive lists without an active revision, as it does
/// one whose create has not been committed.
pub fn is_unrevised(node: &Node) -> bool {
matches!(
node.kind,
NodeKind::File {
active_revision_id: None,
..
}
)
}
/// The plaintext size, in bytes, that a node reports.
/// Overwrite each file node's `claimed_size` with the optimistic size of its
/// queued write, where it has one. Folders and nodes with nothing queued are
/// left alone. See [`Core::stamp_pending_sizes`] for why this exists.
pub fn apply_pending_sizes(nodes: &mut [Node], sizes: &HashMap<NodeUid, u64>) {
for node in nodes {
if let Some(&len) = sizes.get(&node.uid)
&& let NodeKind::File { claimed_size, .. } = &mut node.kind
{
*claimed_size = Some(len as i64);
}
}
}
pub fn node_visible(node: &Node, folder_uid: &NodeUid, hidden: &HashSet<NodeUid>) -> bool {
if !remote_name_is_safe(&node.name) {
warn!(uid = %node.uid, "a remote name cannot be a local file name; leaving it out");
return false;
}
!node.trashed && node.uid != *folder_uid && !hidden.contains(&node.uid)
}
/// Lay what is queued for a folder over Drive's listing of it, from
/// `Db::queued_children`: a node a queued rename moved away is dropped, and a
/// node a queued create, mkdir or rename put there is listed as the DB has it.
///
/// That node holds its name here: a create Drive already has but whose answer
/// is still on its way, or which the drain is still reading back, is listed by
/// Drive under its new uid and by the queue under its stand-in. Both were
/// listed, and a 128-file folder listed 129 (`docs/BUGS.md` B164).
pub fn overlay_queued(nodes: &mut Vec<Node>, queued: Vec<Node>, gone: &HashSet<String>) {
let here: HashSet<String> = queued.iter().map(|node| node.uid.to_string()).collect();
let names: HashSet<&str> = queued.iter().map(|node| node.name.as_str()).collect();
nodes.retain(|node| {
let uid = node.uid.to_string();
!gone.contains(&uid) && !here.contains(&uid) && !names.contains(node.name.as_str())
});
nodes.extend(queued);
}
#[cfg(test)]
mod pending_size_tests {
use super::{Node, NodeKind, NodeUid, apply_pending_sizes};
use pdfs_drive::node_size;
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
use std::collections::HashMap;
fn uid(link: &str) -> NodeUid {
NodeUid::new(VolumeId::from("vol"), LinkId::from(link))
}
fn file(link: &str, claimed: i64) -> Node {
Node {
uid: uid(link),
parent_uid: Some(uid("parent")),
kind: NodeKind::File {
media_type: "text/plain".into(),
total_size_on_storage: 0,
active_revision_state: None,
active_revision_id: None,
content_sha1: None,
claimed_size: Some(claimed),
claimed_modification_time: None,
},
name: link.into(),
creation_time: 100,
modification_time: 100,
trashed: false,
is_shared: false,
is_shared_publicly: false,
signature_email: None,
membership: None,
photo: None,
album: None,
verification: Default::default(),
direct_role: None,
share_id: None,
}
}
fn folder(link: &str) -> Node {
Node {
kind: NodeKind::Folder,
..file(link, 0)
}
}
/// B11: a re-enumeration mid-write must not revert the size to the
/// server's. A file that stats as 0 gets no `read` from the kernel at all,
/// so the staged blob is never served and the file reads as empty.
#[test]
fn a_queued_write_keeps_its_optimistic_size_through_a_re_enumeration() {
let mut nodes = vec![file("queued", 0), file("settled", 4096)];
let sizes = HashMap::from([(uid("queued"), 3)]);
apply_pending_sizes(&mut nodes, &sizes);
assert_eq!(
node_size(&nodes[0]),
3,
"the remote's pre-write size must not win over the queued write's"
);
assert_eq!(
node_size(&nodes[1]),
4096,
"a file with nothing queued keeps the size the server reported"
);
}
/// The map is keyed by uid and says nothing about kind; a folder that
/// somehow collides must not grow a `claimed_size`.
#[test]
fn folders_are_left_alone() {
let mut nodes = vec![folder("dir")];
apply_pending_sizes(&mut nodes, &HashMap::from([(uid("dir"), 999)]));
assert!(matches!(nodes[0].kind, NodeKind::Folder));
assert_eq!(node_size(&nodes[0]), 0);
}
/// The common case: nothing queued, nothing touched.
#[test]
fn an_empty_pending_map_changes_nothing() {
let mut nodes = vec![file("a", 10), file("b", 20)];
apply_pending_sizes(&mut nodes, &HashMap::new());
assert_eq!(node_size(&nodes[0]), 10);
assert_eq!(node_size(&nodes[1]), 20);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+268
View File
@@ -0,0 +1,268 @@
//! What the mount accepted and has not yet sent to Drive (`WriteState`).
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use parking_lot::Mutex;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use pdfs_store::cache::Baseline;
use crate::ids::is_local_uid;
use crate::open::PendingRevision;
/// The write-back's state: writes accepted from the kernel and not yet sent,
/// nodes removed here that a stale listing may still return, and the changes
/// this daemon made that Drive's event feed will echo back.
///
/// The drain, the queue and recovery own it. Everything else, the read path,
/// listings, the pin keeper and the event feed, asks through the methods
/// below instead of taking its locks.
#[derive(Clone, Default)]
pub struct WriteState {
/// Writes accepted from the kernel but not yet uploaded, keyed by node.
/// The in-memory face of the `pending_op` table, from
/// which it is rebuilt on mount.
///
/// Two things read it: [`Core::read_range`], because until the op drains the
/// staged blob *is* the file's content and the remote still holds the old
/// revision; and the drain worker, which performs the uploads.
pub pending: Arc<Mutex<HashMap<NodeUid, PendingRevision>>>,
/// Nodes removed through this daemon which a briefly stale remote listing
/// may still return. Uids are not reused; an explicit restore clears one.
hidden: Arc<Mutex<HashSet<NodeUid>>>,
/// Nodes this daemon changed on the remote itself, and how many echoes of
/// those changes the event feed still owes us.
///
/// The feed replays our own writes back at us seconds later, and a
/// `NodeUpdated` carries no revision id — nothing in it distinguishes "another
/// device changed this file" from "you changed this file". Treating the echo
/// as foreign is not free: it evicts the content blob we just uploaded, so the
/// next read re-downloads a revision the API may not be serving yet. That is
/// how a SQLite database written on the mount came back `malformed`, and how a
/// mount doing bulk uploads spent its time re-fetching its own bytes.
///
/// So the first event for a node we changed ourselves, within
/// [`SELF_CHANGE_TTL_MS`], is consumed rather than applied: the tree already
/// holds what that event describes, because [`Core::refresh_after_upload`] put
/// it there. Anything beyond that applies normally, which bounds the staleness
/// a genuine remote change can suffer to one event.
///
/// Shared across forks like `pending`: the drain that records the change and
/// the event task that consumes the echo are both per-daemon.
self_changes: Arc<Mutex<HashMap<NodeUid, SelfChange>>>,
}
impl WriteState {
pub fn new() -> Self {
Self {
pending: Arc::new(Mutex::new(HashMap::new())),
hidden: Arc::new(Mutex::new(HashSet::new())),
self_changes: Arc::new(Mutex::new(HashMap::new())),
}
}
/// The write queued for `uid`, if any: its staged blob is the file's
/// content until the drain sends it.
pub fn queued(&self, uid: &NodeUid) -> Option<PendingRevision> {
self.pending.lock().get(uid).cloned()
}
/// The remote revision a write to `uid` was made against, for the
/// conflict check: the queued write's own base while one is queued, and
/// otherwise the base the handle started from. `None` for a node that has
/// never existed remotely: there is no revision to conflict with until its
/// create drains.
pub fn baseline(
&self,
uid: &NodeUid,
base_mtime: i64,
base_size: u64,
base_revision_id: Option<String>,
) -> Option<Baseline> {
if is_local_uid(uid) {
return None;
}
match self.pending.lock().get(uid) {
Some(p) => p.meta.based_on.clone(),
None => Some(Baseline {
mtime: base_mtime,
size: base_size,
hash: None,
revision_id: base_revision_id,
}),
}
}
/// Whether a write for `uid` is queued and not yet sent. A remote change
/// to such a node is not applied over it.
pub fn is_queued(&self, uid: &NodeUid) -> bool {
self.pending.lock().contains_key(uid)
}
/// The size the queued write for `uid` gives the file, if one is queued.
pub fn queued_len(&self, uid: &NodeUid) -> Option<u64> {
self.pending.lock().get(uid).map(|queued| queued.meta.len)
}
/// The size each queued write gives its file. Empty when nothing is
/// queued.
pub fn queued_sizes(&self) -> HashMap<NodeUid, u64> {
self.pending
.lock()
.iter()
.map(|(uid, queued)| (uid.clone(), queued.meta.len))
.collect()
}
/// The nodes removed here that a listing must leave out, even if Drive
/// still returns them.
pub fn hidden(&self) -> HashSet<NodeUid> {
self.hidden.lock().clone()
}
/// Leave `uid` out of listings from now on: it was removed here.
pub fn hide(&self, uid: &NodeUid) {
self.hidden.lock().insert(uid.clone());
}
/// List `uid` again: it was restored or put back.
pub fn unhide(&self, uid: &NodeUid) {
self.hidden.lock().remove(uid);
}
/// Record that this daemon just changed `uid` on Drive, so the event
/// feed's echo of the change is recognised (see [`echoes`]).
pub fn note_echo(&self, uid: &NodeUid, now_ms: i64) {
note_self_change(&mut self.self_changes.lock(), uid, now_ms);
}
/// Claim one outstanding echo for `uid`: whether the event being applied
/// is one this daemon caused.
pub fn take_echo(&self, uid: &NodeUid, now_ms: i64) -> bool {
take_self_change(&mut self.self_changes.lock(), uid, now_ms)
}
}
/// How long a change this daemon made stays recognisable as its own. Generous
/// against a feed that can lag, but finite: past it, an event for the node is
/// applied like any other. See [`writes::WriteState`].
pub(crate) const SELF_CHANGE_TTL_MS: i64 = 120_000;
/// A remote change this daemon made, awaiting its echo from the event feed.
pub(crate) struct SelfChange {
/// When we made it, in the same epoch millis as [`now_millis`].
at_ms: i64,
/// Echoes not yet seen. More than one because a single file can be created
/// and then have a revision uploaded, and the feed reports both.
echoes: u32,
}
/// Record one remote change this daemon made. Split from [`Core`] so the
/// expiry and echo-counting rules can be tested against a clock the test owns.
pub(crate) fn note_self_change(
changes: &mut HashMap<NodeUid, SelfChange>,
uid: &NodeUid,
now_ms: i64,
) {
// Echoes that never arrived — a node trashed before its event came round, a
// feed that skipped it — would otherwise accumulate for the life of the
// daemon. Pruning on write keeps the map the size of the recent queue.
changes.retain(|_, c| now_ms - c.at_ms < SELF_CHANGE_TTL_MS);
let change = changes.entry(uid.clone()).or_insert(SelfChange {
at_ms: now_ms,
echoes: 0,
});
change.at_ms = now_ms;
change.echoes += 1;
}
/// Claim one echo, per [`Core::take_self_change`].
pub(crate) fn take_self_change(
changes: &mut HashMap<NodeUid, SelfChange>,
uid: &NodeUid,
now_ms: i64,
) -> bool {
let Some(change) = changes.get_mut(uid) else {
return false;
};
// Too old to attribute: the feed is far enough behind that this is as likely
// to be someone else's change as ours, and guessing wrong here costs the user
// a stale file.
if now_ms - change.at_ms >= SELF_CHANGE_TTL_MS {
changes.remove(uid);
return false;
}
change.echoes -= 1;
if change.echoes == 0 {
changes.remove(uid);
}
true
}
#[cfg(test)]
mod tests {
use super::*;
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
/// An event feed carries no revision id, so the only thing that tells a
/// remote change apart from the echo of one this daemon just made is this
/// bookkeeping. Getting it wrong is expensive in both directions: too eager
/// and we evict the bytes we uploaded and re-download them from an API that
/// may still be serving the previous revision (a SQLite file on the mount
/// read back `malformed`); too generous and a real change from another device
/// is ignored.
#[test]
fn a_self_change_is_claimed_once_and_expires() {
let mut changes = HashMap::new();
let uid = NodeUid::new(VolumeId::from("vol"), LinkId::from("link"));
let other = NodeUid::new(VolumeId::from("vol"), LinkId::from("other"));
let t0 = 1_000_000;
assert!(
!take_self_change(&mut changes, &uid, t0),
"a node we never touched is never ours"
);
note_self_change(&mut changes, &uid, t0);
assert!(
take_self_change(&mut changes, &uid, t0 + 5_000),
"the echo of our own change is claimed"
);
assert!(
!take_self_change(&mut changes, &uid, t0 + 6_000),
"and only once, so a later foreign change still applies"
);
// A create followed by a revision upload is two changes to one node, and
// the feed reports both.
note_self_change(&mut changes, &uid, t0);
note_self_change(&mut changes, &uid, t0);
assert!(take_self_change(&mut changes, &uid, t0 + 1));
assert!(take_self_change(&mut changes, &uid, t0 + 2));
assert!(!take_self_change(&mut changes, &uid, t0 + 3));
// Past the window the attribution is a guess, and a wrong guess leaves
// the user looking at a stale file.
note_self_change(&mut changes, &uid, t0);
assert!(!take_self_change(
&mut changes,
&uid,
t0 + SELF_CHANGE_TTL_MS
));
assert!(
!changes.contains_key(&uid),
"an expired change is dropped, not left to be re-tested"
);
// An echo that never arrives must not accumulate for the life of the
// daemon; the next recorded change prunes it.
note_self_change(&mut changes, &uid, t0);
note_self_change(&mut changes, &other, t0 + SELF_CHANGE_TTL_MS);
assert_eq!(
changes.len(),
1,
"recording a change prunes the ones whose echo never came"
);
}
}
+24 -1
View File
@@ -51,7 +51,8 @@ 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-fuse`](../crates/pdfs-fuse) | The daemon: FUSE handlers (`filesystem`), the tree (`state`), 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-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 |
| [`pdfs-gui`](../crates/pdfs-gui) | `pdfs-app`, `pdfs-tray` and `pdfs-prompt`. Pages in `src/app/pages/`, widgets in `src/app/widgets/`, CSS and icons in `resources/` |
@@ -847,6 +848,28 @@ mounts. Step 5 turns that into the `pdfs-vfs` service. `Core` also implements th
host ports and builds each service on demand, which moves to `pdfs-daemon` once the services no
longer need the tree.
Step 5 has started. `pdfs-vfs` holds the tree (`tree::State`: every node a mount shows, its
stable inode, the roots of each session) and the open files (`open::OpenFiles`: write handles by
inode and by handle number, the inodes being released, and directory handles with their frozen
listings). A write goes through `stage_write`, which reports a full disk as a typed error; the
tree refuses a write to a read-only node with `NodeError`; the FUSE adapter maps both to errno.
The crate depends on no kernel or GUI crate; `cargo tree -p pdfs-vfs` shows neither.
The open-file service, `files::Files`, serves a file from open to close: the write open and its
base, writes, resizes and `fallocate`, flush, the fsync barrier and the release. Each write
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.
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
macOS adapters, and a separate repository for the sync engine.
+129
View File
@@ -108,6 +108,10 @@ 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 |
| [B298](#b298--a-synced-folder-edit-whose-upload-lost-its-answer-is-kept-as-a-conflict-copy-of-itself) | A synced-folder edit whose upload lost its answer is kept as a conflict copy of itself |
| [B297](#b297--the-simulations-fail-and-hang-when-run-in-parallel-and-nothing-stops-that) | The simulations fail and hang when run in parallel, and nothing stops that |
@@ -402,6 +406,131 @@ 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)
**Found:** 2026-11-27, from the review of the mounted filesystem in `FUSE.md`, while moving the
fsync into `pdfs-vfs` (step 5 of `docs/ARCHITECTURE.md`). It was not seen in a run.
**Where:** `Files::fsync` in `crates/pdfs-vfs/src/files.rs`; `WriteHandle::generation` and
`WriteHandle::barrier` in `crates/pdfs-vfs/src/open.rs`
**Repro:** Write a file and call `fsync` from two threads on the same open file, with a write in
between. Each fsync runs on a worker. If the first one finishes after the second, its record of the
file goes to disk last. Kill the daemon before the file is closed. The restart recovers the file
as the first fsync saw it and loses the bytes the second one had made durable.
**Cause.** An fsync copied what the handle held (length, written ranges, base), synced the scratch
file and then wrote that copy as the sidecar a restart recovers from. Nothing ordered two of these
on the same file, so the copy that was written last was not always the newest.
**Fix.** Each write handle counts its changes in `generation` and carries a `barrier` lock. An
fsync takes the barrier before it reads the handle and holds it until the sidecar is written, so a
later fsync records at least what an earlier one did. The barrier also keeps the generation last
made durable, and an fsync with nothing new since then skips the sidecar.
**Verified:** `an_fsync_records_what_the_file_holds_when_its_turn_comes` holds the barrier, writes
while an fsync waits for it, and checks that a restart recovers the later bytes. No test drives
this through a mount.
---
### B300 — A read during a release can be served the revision the write replaced
**Status:** Fixed (unverified)
**Found:** 2026-11-27, by reading the code while moving the open files into `pdfs-vfs` (step 5 of
`docs/ARCHITECTURE.md`). It was not seen in a run.
**Where:** `OpenFiles::release` and `OpenFiles::reader` in `crates/pdfs-vfs/src/open.rs`;
`Core::read_local` in `crates/pdfs-fuse/src/reads.rs` and the `read` callback in
`crates/pdfs-fuse/src/filesystem.rs`
**Repro:** Keep one read-only handle open on a file, and read through it from a second thread.
Write the file through another handle and close it. A read that lands after the release took the
write state out of the open files, but before the release queued the new revision, finds neither
of them, and is answered with the revision on Drive from before the write.
**Cause.** The release removed the writer first and queued the revision second. Each read looks for
an open writer, then for a queued revision, then goes to the cache or Drive. The release runs on the
dispatch loop, so an `open` and `read` issued after `close(2)` are served after it. A read already
running on a worker, through a handle opened earlier, is not ordered that way.
**Fix.** A release now keeps a read view of the writer (its scratch file, length, base and written
ranges) until the revision is queued. `OpenFiles::reader` answers from the open writer, or from that
view, and both read paths ask it first. The view was already kept in one form, as the set of inodes
being released, which only the check for unsaved changes looked at.
**Verified:** `the_last_release_hands_back_the_write_and_marks_it_releasing` checks that a read finds
the write until `finish_release`. No test drives the race through a mount.
---
### B299 — A synced folder in the trash blocks attaching any other folder
**Status:** Fixed (unverified)