Compare commits

...
38 Commits
Author SHA1 Message Date
nvrl ea29a260b0 Merge pull request #180 from narrrl/fix/echo-false-conflict
fix(fuse): read a write based on a landed create's placeholder as the create's revision
2026-11-27 19:31:10 +01:00
nvrl 8e9816919d Merge pull request #184 from narrrl/feat/sync-root-reducer
feat(sync): run a root reducer per mirror folder alongside the engine
2026-11-27 19:30:48 +01:00
nvrl 90e9c0de26 Merge branch 'feat/sync-local-dirty' into feat/sync-root-reducer
# Conflicts:
#	crates/pdfs-fuse/src/mount.rs
#	crates/pdfs-sync/src/mirror/host.rs
2026-11-27 19:27:09 +01:00
nvrl 61e0eefe3a Merge branch 'feat/sync-enforce-evidence' into feat/sync-local-dirty
# Conflicts:
#	crates/pdfs-fuse/src/mount.rs
#	crates/pdfs-sync/src/mirror/host.rs
2026-11-27 19:26:48 +01:00
nvrl 7862fc9195 Merge branch 'feat/sync-delete-window' into feat/sync-enforce-evidence 2026-11-27 19:26:18 +01:00
nvrl 1c900f47bc Merge branch 'feat/sync-typed-absence' into feat/sync-delete-window 2026-11-27 19:26:17 +01:00
nvrl a9adbf96ef Merge remote-tracking branch 'origin/main' into feat/sync-typed-absence
# Conflicts:
#	docs/ARCHITECTURE.md
2026-11-27 19:26:00 +01:00
nvrl bcdf78c44d Merge pull request #177 from narrrl/fix/eacces-evidence
fix(fuse): log which authority refused a change
2026-11-27 19:23:58 +01:00
nvrl 413be9d961 feat(sync): run a root reducer per mirror folder alongside the engine
One pure state machine per mirror folder says how far the engine can
trust what it has seen: discovering, following, auditing after a doubt
(a watcher error, an overflowed queue, a gap in Drive's event stream, a
restart or a suspension), suspended, draining for on-demand, or handed
off. The passes, the watcher, the event stream and pause feed it inputs;
step() takes no time and does no I/O, so an input sequence replays
exactly.

Nothing acts on the state yet. The engine logs each transition as
'sync: root state', so it can be compared with what the engine did
before a pass relies on it.
2026-11-27 19:20:35 +01:00
nvrl 0fd8dda0d5 feat(sync): keep a local dirty set from the watcher, checked against the walk
The filesystem watcher now marks each path an event names, per mirror
folder (LocalDirty, in memory). A pass claims the marks before it plans
and retires them once it applied everything it found; marks made while
it ran stay for the next pass. A claim is trusted when the folder's
watch was live since the last pass claimed: a watcher error, an
overflowed queue or a restart breaks that.

For now the set is only checked. Each pass still walks the whole
folder, and counts in its trace the claimed marks, whether the claim
was trusted, and the changes it found on disk that a trusted claim did
not cover. Once that stays at zero, a trusted claim can stand in for
the local walk.
2026-11-27 19:14:35 +01:00
nvrl 4f542ae4d6 feat(sync): do not make a deletion the evidence does not back
The shadow check from the typed absence change counted deletions not
backed by proof of absence and acted on nothing. A deletion it flags is
now left out of the pass: it is logged, counted in the trace and failed
as a step, and the baseline row stays, so the next pass plans it again.
A regression in the filters then keeps a file on both sides instead of
deleting it, and a simulation that expects the deletion sees the file
still there.
2026-11-27 19:03:57 +01:00
nvrl fb77dbda6a feat(sync,store): add up a mirror folder's deletions across passes
The wipe guards see one pass. A tree lost a little at a time, by a
failing disk or a script, passes them once per pass, and the passes
between delete the rest in batches.

Each mirror folder now keeps a deletion window (schema 50): when it
began, the most paths the folder tracked since, and the deletions made
since on either side. A pass whose planned deletions would bring the
window to nine tenths of the folder is refused. The plan is recorded
before anything is deleted and settled to what was actually deleted
when the pass ends. A window lasts a day, and changing or removing the
folder drops it.
2026-11-27 19:01:07 +01:00
nvrl ef5f832b0f fix(fuse): read a write based on a landed create's placeholder as the create's revision
A write released while its file's create landed could keep the
placeholder's base, a local mtime and no revision id: the release takes
its handle out of the tree before it queues, so neither the rebase of
open handles nor the rebase of queued writes reached it. The drain then
compared mtimes, Drive had stamped the create a second later, and the
write went up as a conflict copy of the file's own create (B304).

Landing a create now remembers the placeholder's stamp with the revision
the create sealed, and the drain reads a revision-less base with that
stamp as that revision.
2026-11-27 18:56:13 +01:00
nvrl 91fe76dbe1 Merge pull request #176 from narrrl/feat/sched-cold-listing
feat(sched,fuse): list a cold folder once, through admission
2026-11-27 18:38:33 +01:00
nvrl 1b64c37519 test(sync): the evidence classifies what the old filters kept 2026-11-27 18:27:31 +01:00
nvrl e74a36c57e feat(sync): make absence a typed fact, and check deletions against it
Step 4 of the 4.0 plan starts with typed absence. A path missing from a
walk was read through three separate filters (`Unscanned`, `RemoteGaps`
and the ignore rules), each applied where a pass read the walks. The new
`evidence` module answers one question per side instead: the path is
present, proven absent, excluded by rule, or unknown, with why
(unreadable, vanished, unread, under a short listing or under a failed
listing).

The mirror pass now classifies a path only when both sides are known,
which is the same set the old filters let through. Every deletion the
mirror pass and the push pass plan is checked against the evidence once
more in shadow mode: a deletion of a path not proven gone on the side it
is based on is logged and counted as `unproven deletions` in the pass
trace. The check acts on nothing; it should stay at zero, and makes a
regression in the filters visible before it can cost data.
2026-11-27 18:23:02 +01:00
nvrl 7e8417b135 fix(fuse): log which authority refused a change
Two simulation runs failed with an EACCES on a create or mkdir that
should have been allowed (three-clients seed 3 on #176, lan seed 4 on
#171). Neither reproduces locally, and the daemon log said nothing about
the refusal. Both admission points now log a warning when they refuse:
the tree's access for a node that is read-only, or, for a check by uid,
the persisted access and every resident mount's access. The next
occurrence in CI leaves the evidence in the simulation's daemon log.
2026-11-27 18:01:15 +01:00
nvrl 4ff217c721 Merge branch 'feat/sched-observe' into feat/sched-cold-listing 2026-11-27 17:25:03 +01:00
nvrl 620c3fd10f Merge branch 'feat/sched-admission' into feat/sched-observe 2026-11-27 17:24:56 +01:00
nvrl 6bcef1281d Merge remote-tracking branch 'origin/main' into feat/sched-admission
# Conflicts:
#	docs/ARCHITECTURE.md
2026-11-27 17:22:39 +01:00
nvrl b9f18180fe feat(sched,fuse): list a cold folder once, through admission
The second item of the scheduler's delivery order moves one cold
metadata path behind admission. Listing a folder the mount has not listed
yet now asks the daemon's admission first, as a `listing` step, so
`pdfs diagnostics` counts cold listings with the mirror steps.

The admission becomes `Classes`, a limit of its own per class: mirror
steps keep 8, cold listings get 32, above what the mount lists at once
today, so a lookup never waits behind a mirror upload and rarely waits at
all.

Callers that find the same folder unlisted at once used to ask Drive each,
and all but the first threw the answer away. They now share one listing
through a single flight: the first lists the folder, the others wait for
it and take what it published. A follower whose leader failed lists the
folder itself, so every caller still gets its own answer, and a leader
that panics still lets its followers go. A shared folder's refresh stays
out of the flight, since its generation check settles races of its own.
2026-11-27 17:21:50 +01:00
nvrl 70259b5163 feat(sched,sync,cli): report what the admission is doing
The first item of the scheduler's delivery order is to measure before any
policy changes. An admission now reports its load per class of step: how
many run, how many wait, how long the oldest has waited, and the total and
longest wait so far. Bounded meters this with counters that are updated
when a step asks, is admitted and drops its permit; a step that stops
waiting leaves the line without counting.

`pdfs diagnostics` prints the load, and each sync pass trace records the
time its steps spent waiting for admission as `admission wait`, apart from
the time they spent on the network. The control protocol gains
`Diagnostics::admission`, which defaults to empty for an older daemon.
2026-11-27 16:27:38 +01:00
nvrl c1718b13a7 Merge pull request #173 from narrrl/refactor/vfs-headless
feat(vfs,fuse): a headless adapter, and conformance scenarios run through it and FUSE
2026-11-27 16:12:27 +01:00
nvrl acf3bd40a5 feat(sched,sync): admit mirror steps through an Admission port
Start of step 6. The new pdfs-sched crate holds the admission port: a
service describes each step of background work as a Step (its class and
root), waits for a Permit from an Admission, and gives the capacity back
by dropping it. Bounded admits a fixed number of steps at once.

The mirror engine now asks SyncParts::admission before every upload,
download and folder creation of a pass, instead of building a semaphore
per batch. The daemon supplies Bounded with the old limit of 8
(SYNC_CONCURRENCY). Passes run one at a time and a batch waits for all
its steps, so the behaviour is unchanged. An account-wide controller can
replace the policy later without the engine changing.
2026-11-27 16:11:10 +01:00
nvrl e90979eb05 Merge pull request #172 from narrrl/fix/withdrawn-create-ghost
fix(fuse): take a withdrawn create's node out of listings already made (B303)
2026-11-27 15:50:07 +01:00
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 62cc85cb06 feat(vfs,fuse): a headless adapter, and conformance scenarios run through it and FUSE
Slice 3 of step 5. pdfs_vfs::headless::Headless serves the open-file
and namespace services by path, with no kernel and no Drive. Its host
queues every create in the real store, as the daemon does offline, and
keeps what each close committed in memory. It does itself what the
kernel does before calling the FUSE adapter: path resolution one name
at a time, refusing a taken name on mkdir, and opening an existing file
on create.

pdfs_vfs::conformance (test-support) holds an Adapter trait and ten
scenarios: a file written, resized, synced, closed and reopened; partial
overwrites; reads while open; holes past a grow; create over a file;
folder listings; renames that move and replace; the renames and removals
POSIX refuses; and an unlinked open file. They run through the headless
adapter in pdfs-vfs's unit tests, and through a FUSE mount over the fake
Drive, online and offline, in two new simulations. Both adapters see the
same outcomes.
2026-11-27 15:08:39 +01:00
nvrl 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 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
51 changed files with 6476 additions and 742 deletions

No files matched your search

Generated
+10
View File
@@ -3727,6 +3727,7 @@ dependencies = [
"parking_lot 0.13.0",
"pdfs-core",
"pdfs-drive",
"pdfs-sched",
"pdfs-store",
"pdfs-sync",
"pdfs-vfs",
@@ -3770,6 +3771,14 @@ dependencies = [
"webkit6",
]
[[package]]
name = "pdfs-sched"
version = "3.10.0"
dependencies = [
"parking_lot 0.13.0",
"tokio",
]
[[package]]
name = "pdfs-store"
version = "3.10.0"
@@ -3794,6 +3803,7 @@ dependencies = [
"parking_lot 0.13.0",
"pdfs-core",
"pdfs-drive",
"pdfs-sched",
"pdfs-store",
"proton-drive-rs",
"sha1 0.11.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-vfs", "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-sched", "crates/pdfs-vfs", "crates/pdfs-fuse", "crates/pdfs-daemon", "crates/pdfs-cli", "crates/pdfs-gui"]
[workspace.package]
version = "3.10.0"
@@ -28,6 +28,7 @@ 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-sched = { path = "crates/pdfs-sched" }
pdfs-fuse = { path = "crates/pdfs-fuse" }
pdfs-daemon = { path = "crates/pdfs-daemon" }
+68
View File
@@ -270,6 +270,34 @@ pub(super) fn sync_engine_line(sync: &pdfs_core::control::SyncEngineState) -> St
line
}
/// One class of background step in `pdfs diagnostics`: `mirror: 8 running,
/// 3 waiting (oldest 2s); 120 admitted, waited 14s in total, 950ms at most`.
pub(super) fn admission_line(load: &pdfs_core::control::AdmissionLoad) -> String {
let mut line = format!(
"{}: {} running, {} waiting",
load.class, load.running, load.waiting
);
if let Some(ms) = load.oldest_wait_ms {
line.push_str(&format!(" (oldest {})", wait_ms(ms)));
}
line.push_str(&format!(
"; {} admitted, waited {} in total, {} at most",
load.admitted,
wait_ms(load.waited_ms),
wait_ms(load.longest_wait_ms),
));
line
}
/// A wait, in ms below a second, where most admission waits fall.
fn wait_ms(ms: u64) -> String {
if ms < 1000 {
format!("{ms}ms")
} else {
human_secs(ms / 1000)
}
}
pub(super) fn cmd_diagnostics() -> Result<()> {
let response = control_request(CtlRequest::Diagnostics)?;
if emit_json(&response)? {
@@ -346,6 +374,12 @@ pub(super) fn cmd_diagnostics() -> Result<()> {
);
}
}
if !d.admission.is_empty() {
println!("admission of background steps:");
for load in &d.admission {
println!(" {}", admission_line(load));
}
}
if !d.drive_calls.is_empty() {
println!("calls to Drive since start:");
for call in &d.drive_calls {
@@ -480,3 +514,37 @@ pub(super) fn cmd_cache_inspect(deep: bool) -> Result<()> {
other => bail!("unexpected response: {other:?}"),
}
}
#[cfg(test)]
mod tests {
use pdfs_core::control::AdmissionLoad;
use super::admission_line;
#[test]
fn an_admission_line_says_who_waits_and_for_how_long() {
let load = AdmissionLoad {
class: "mirror".into(),
running: 8,
waiting: 3,
oldest_wait_ms: Some(2_400),
admitted: 120,
waited_ms: 14_000,
longest_wait_ms: 950,
};
assert_eq!(
admission_line(&load),
"mirror: 8 running, 3 waiting (oldest 2s); 120 admitted, waited 14s in total, 950ms at most"
);
let idle = AdmissionLoad {
oldest_wait_ms: None,
waiting: 0,
running: 0,
..load
};
assert_eq!(
admission_line(&idle),
"mirror: 0 running, 0 waiting; 120 admitted, waited 14s in total, 950ms at most"
);
}
}
+25
View File
@@ -2382,6 +2382,31 @@ pub struct Diagnostics {
/// folder pin, oldest first. Empty from a daemon that predates the field.
#[serde(default)]
pub jobs: Vec<ServiceState>,
/// What the admission of background work is doing, per class of step.
/// Empty from a daemon that predates the field.
#[serde(default)]
pub admission: Vec<AdmissionLoad>,
}
/// One class of background step in the daemon's admission, in
/// [`Diagnostics::admission`]. Steps waiting here have not reached the
/// network yet, so a stall with steps waiting and none running is in the
/// daemon, not at Proton.
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct AdmissionLoad {
/// The class of step, such as `mirror`.
pub class: String,
/// Steps admitted and still running.
pub running: usize,
/// Steps waiting to be admitted.
pub waiting: usize,
/// How long the step that has waited longest has waited so far, in ms.
pub oldest_wait_ms: Option<u64>,
/// Steps admitted since start.
pub admitted: u64,
/// The time those steps spent waiting, in total and at most, in ms.
pub waited_ms: u64,
pub longest_wait_ms: u64,
}
/// One long-lived daemon thread, in [`Diagnostics::services`], or one
+1
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-sched.workspace = true
pdfs-vfs.workspace = true
pdfs-store.workspace = true
zip.workspace = true
+7 -1
View File
@@ -3,6 +3,7 @@
use super::*;
use crate::shutdown::Shutdown;
use pdfs_core::error::session_revoked;
use pdfs_sync::root::{Doubt, RootInput};
/// Drop `uid` from one mount's tree and tell that mount's kernel session the
/// entry is gone. Shared by the trash and delete paths, which differ only in
@@ -148,7 +149,12 @@ fn apply_event(core: &Core, event: &DriveEvent, dirty: &mut DirtyParents) -> pdf
core.db.sync_remote_changed(&node_uid.to_string(), None)
}
// What changed went by unseen: every pass walks Drive whole again.
DriveEvent::ContinuityLost { .. } => core.db.sync_walks_clear_all().map(|()| Vec::new()),
DriveEvent::ContinuityLost { .. } => {
core.sync
.roots
.input_all(RootInput::Doubted(Doubt::EventGap));
core.db.sync_walks_clear_all().map(|()| Vec::new())
}
_ => Ok(Vec::new()),
};
match marked {
+22 -1
View File
@@ -18,7 +18,9 @@ use std::sync::{Arc, LazyLock};
use std::time::{Duration, Instant};
use parking_lot::Mutex;
use pdfs_core::control::{Diagnostics, DriveCallStat, InflightRequest, ServiceState, WorkerState};
use pdfs_core::control::{
AdmissionLoad, Diagnostics, DriveCallStat, InflightRequest, ServiceState, WorkerState,
};
use pdfs_core::lifecycle::ServiceBoard;
@@ -198,6 +200,21 @@ impl Core {
longest_ms: u64::try_from(stat.longest.as_millis()).unwrap_or(u64::MAX),
})
.collect(),
admission: self
.sync
.admission
.load()
.into_iter()
.map(|load| AdmissionLoad {
class: load.class.name().to_owned(),
running: load.running,
waiting: load.waiting,
oldest_wait_ms: load.oldest_wait.map(millis),
admitted: load.admitted,
waited_ms: millis(load.waited),
longest_wait_ms: millis(load.longest_wait),
})
.collect(),
}
}
@@ -221,6 +238,10 @@ impl Core {
}
}
fn millis(took: Duration) -> u64 {
u64::try_from(took.as_millis()).unwrap_or(u64::MAX)
}
/// Run `probe` on a thread of its own and wait up to `deadline` for it.
///
/// `None` when it did not answer in time, or when the previous probe sharing
+56
View File
@@ -80,6 +80,13 @@ pub(crate) struct DrainState {
/// The node an upload has just put on Drive, from when the drain lets go
/// of its blob until the tree has the node (`docs/BUGS.md` B170).
pub(crate) landed: Arc<Mutex<HashMap<NodeUid, Node>>>,
/// A landed create's placeholder stamp, by the uid Drive gave it, with the
/// revision the create sealed. A write released while the create landed
/// can be based on the placeholder: a local mtime and no revision id. Its
/// bytes are the ones the create sent, so the drain reads that base as the
/// sealed revision ([`placeholder_base`]). Dropped once a later upload of
/// the file lands.
pub(crate) placeholders: Arc<Mutex<HashMap<NodeUid, Baseline>>>,
/// How long this node's last upload actually took, in milliseconds, with
/// the time it was measured for eviction. Feeds
/// [`Core::revision_debounce`]: a file that takes 30 seconds to send needs
@@ -110,6 +117,7 @@ impl DrainState {
unadopted: Arc::new(Mutex::new(HashMap::new())),
sealed_unread: Arc::new(Mutex::new(HashMap::new())),
landed: Arc::new(Mutex::new(HashMap::new())),
placeholders: Arc::new(Mutex::new(HashMap::new())),
upload_times: Arc::new(Mutex::new(HashMap::new())),
upload_cancel: Arc::new(Mutex::new(HashMap::new())),
landing_uploads: Arc::new(AtomicU64::new(0)),
@@ -421,6 +429,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.
@@ -870,6 +882,29 @@ fn revision_changed(base: &Baseline, node: &Node) -> Option<String> {
})
}
/// `base` as the revision it was made against, for [`revision_changed`].
///
/// A base with no revision id whose stamp is a landed create's placeholder
/// (`placeholder`) was taken from that placeholder by a write released while
/// the create landed: the release had taken its handle out of the tree, so the
/// rebase onto the landed node missed it, and it queued after the queued writes
/// were rebased. The placeholder's bytes are the ones the create sent, so the
/// base is the revision the create sealed. Compared by its local mtime instead,
/// the write was a conflict copy of the file's own create whenever the server
/// stamped the create a second later than the placeholder.
fn placeholder_base(base: &Baseline, placeholder: Option<&Baseline>) -> Baseline {
match placeholder {
Some(created)
if base.revision_id.is_none()
&& created.mtime == base.mtime
&& created.size == base.size =>
{
created.clone()
}
_ => base.clone(),
}
}
/// Whether a queued write that found the remote moved on ([`revision_changed`]
/// fired) is nonetheless a single-writer self-supersede rather than a foreign
/// conflict — the remote sits at a revision this daemon sealed itself, so
@@ -1804,6 +1839,27 @@ mod tests {
assert!(revision_changed(&base, &remote).is_some());
}
/// A write released while its file's create landed keeps the
/// placeholder's base: the local mtime, a second before the server's
/// stamp, and no revision id.
#[test]
fn a_write_based_on_a_landed_create_placeholder_is_not_a_conflict() {
let placeholder = baseline(1_795_799_834, 28, None);
let created = baseline(1_795_799_834, 28, Some("rev-create"));
let landed = file_node(1_795_799_835, 28, Some("rev-create"));
assert!(revision_changed(&placeholder, &landed).is_some());
let base = placeholder_base(&placeholder, Some(&created));
assert_eq!(revision_changed(&base, &landed), None);
// Another device writing over the create is still a conflict.
let edited = file_node(1_795_799_835, 28, Some("theirs"));
assert!(revision_changed(&base, &edited).is_some());
// A base with a revision of its own, or another stamp, is left alone.
let other = baseline(1_795_799_830, 28, None);
assert_eq!(placeholder_base(&other, Some(&created)), other);
let revised = baseline(1_795_799_834, 28, Some("older"));
assert_eq!(placeholder_base(&revised, Some(&created)), revised);
}
/// The reported shape (docs/BUGS.md B113): a downloader creates a file
/// through the mount, and the file is moved before its write drains. The
/// move re-stamps the node's mtime on the server (1790955809 -> 1790956593),
+27
View File
@@ -651,6 +651,9 @@ impl Core {
// B123).
let remote = node.clone();
self.stamp_pending_sizes(std::slice::from_mut(&mut node));
// The placeholder as the tree has it, before the landed node replaces
// it: the base of a write that opened over it (`placeholder_base`).
let mut placeholder = None;
// The rows and queued ops already follow the node: `retire_create`
// moved its row to the real uid, and ops find it by local id.
@@ -673,6 +676,11 @@ impl Core {
node.parent_uid = e.node.parent_uid.clone();
}
st.write_through(node.clone());
if let Some(e) = st.entries.get(&ino)
&& node_revision_id(&e.node).is_none()
{
placeholder.get_or_insert((e.node.modification_time, node_size(&e.node)));
}
let mut landed = node.clone();
st.keep_open_write_size(ino, &mut landed);
if let Some(e) = st.entries.get_mut(&ino) {
@@ -719,6 +727,25 @@ impl Core {
{
warn!(%real, error = %e, "persisting our sealed revision failed");
}
// A release that took its handle out of the tree before the rebase
// below and queues after `rebaseline_pending` is caught by neither,
// and an incomplete write does not chain onto our own revision. Its
// base is the placeholder, whose bytes the create sent.
if let Some((mtime, size)) = placeholder
&& mtime != remote.modification_time
&& size == node_size(&remote)
&& let Some(rev) = node_revision_id(&remote)
{
self.drain.placeholders.lock().insert(
real.clone(),
Baseline {
mtime,
size,
hash: None,
revision_id: Some(rev),
},
);
}
self.rebase_open_writes(real, &remote);
// A write carried over from the create was made against no revision at
// all; the one just created is what it now replaces.
+4
View File
@@ -116,6 +116,8 @@ impl Core {
if node.trashed {
return Ok(Some("the file was trashed remotely".into()));
}
let placeholder = self.drain.placeholders.lock().get(uid).cloned();
let base = &placeholder_base(base, placeholder.as_ref());
let Some(reason) = revision_changed(base, &node) else {
return Ok(None);
};
@@ -511,6 +513,8 @@ impl Core {
if fetched.is_ok() {
self.drain.sealed_unread.lock().remove(uid);
}
// This upload went after any write based on the create's placeholder.
self.drain.placeholders.lock().remove(uid);
let node = match fetched {
Ok(Some(node)) => node,
// Trashed or deleted under us: the tree will hear it from the event
+18 -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)
@@ -61,12 +61,28 @@ impl Core {
if let Err(e) = self.db.clear_own_sealed_rev(&uid.to_string()) {
debug!(%uid, error = %e, "clearing the sealed-revision record failed");
}
self.drain.placeholders.lock().remove(&uid);
self.invalidate_trash();
self.log_activity(ActivityKind::Trash, &name, "trashed", true);
info!(%uid, name, "pending trash landed");
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 +207,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,
+48 -629
View File
@@ -2,6 +2,7 @@
use super::*;
use pdfs_vfs::files::Files;
use pdfs_vfs::namespace::{Namespace, Renamed};
use pdfs_vfs::open::{DirListing, dir_page};
impl Filesystem for ProtonFs {
@@ -938,6 +939,7 @@ pub struct ProtonFs {
core: Core,
/// The open-file service, shared with every other mount of the daemon.
files: Arc<Files<Core>>,
namespace: Arc<Namespace<Core>>,
uid: u32,
gid: u32,
/// The tree inode of this session's root, which the kernel knows as
@@ -990,6 +992,7 @@ impl ProtonFs {
let (uid, gid) = unsafe { (libc::geteuid(), libc::getegid()) };
Self {
files: core.files(),
namespace: core.namespace(),
core,
uid,
gid,
@@ -1170,254 +1173,46 @@ impl ProtonFs {
/// The body of [`Filesystem::create`], run off the dispatch loop.
fn serve_create(&self, parent: u64, name: &str, reply: ReplyCreate) {
if let Err(error) = self.core.require_writable(parent) {
reply.error(error);
return;
match self.namespace.create(parent, name) {
Ok(made) => {
let attr = self.attr(made.ino, &made.node, made.access);
reply.created(
&TTL,
&attr,
Generation(0),
FileHandle(made.fh),
FopenFlags::empty(),
);
}
Err(error) => reply.error(namespace_errno(error)),
}
if let Err(e) = self.core.ensure_children(parent) {
// The parent was looked up a moment ago, so ENOENT here means it
// left the tree in between. Log it: the caller only sees "no such
// file" on a create.
if e == Errno::ENOENT {
warn!(parent, name, "create: the parent folder is no longer known");
}
reply.error(e);
return;
}
let parent_uid = {
let st = self.core.state();
match st.entries.get(&parent) {
Some(e) => e.uid.clone(),
None => {
warn!(
parent,
name, "create: the parent folder left the tree during its listing"
);
reply.error(Errno::ENOENT);
return;
}
}
};
// A transient scratch name — a browser's in-flight `*.crdownload`, an
// editor's `*.swp` — is kept purely local and *parked*: no remote node is
// minted and its bytes never upload while it wears that name. The app
// renames the finished file to its real name, and that rename un-parks the
// create so only the completed file reaches Drive. Minting an empty remote
// node here instead is what let a stalled+resumed download fork a
// `(sync-conflict)` copy (docs/BUGS.md B70).
let transient = is_transient_name(name);
// Offline the server cannot mint a uid, so invent one and queue the
// create. The file is real to the caller either way; only its identity is
// provisional until the drain.
//
// A parent that is itself still queued forces the same path even when we
// are online: the API has no folder to put this in yet.
//
// A create that set out online and lost the network on the way lands in
// the queue too, so a Wi-Fi drop costs the caller a wait, never an EIO.
let minted = if !transient && self.core.sends_inline() && !is_local_uid(&parent_uid) {
if let Err(error) = self.core.require_uid_writable(&parent_uid) {
reply.error(error);
return;
}
// Create an empty file on the remote so it has a real uid immediately;
// written bytes are buffered and sealed as a new revision on close.
match self.core.block_on_bounded(self.core.drive.upload_file(
&parent_uid,
name,
media_type_for(name),
b"",
)) {
// A file that exists remotely but could not be read back is
// queued, and the queued create finds it by name and adopts it.
Ok(new_uid) => self.core.fetch_minted_node(&new_uid, name),
Err(e) if self.core.lost_link(&e, "create") => None,
Err(e) => {
error!(%parent_uid, name, error = %e, "create file failed");
reply.error(Errno::EIO);
return;
}
}
} else {
None
};
let node = match minted {
Some(node) => node,
None => match self
.core
.queue_local_node(&parent_uid, name, false, transient)
{
Ok(n) => n,
Err(e) => {
reply.error(e);
return;
}
},
};
let (file, path) = match self.core.cache.create_scratch() {
Ok(x) => x,
Err(e) => {
error!(uid = %node.uid, error = %e, "create scratch file failed");
reply.error(Errno::EIO);
return;
}
};
let mut st = self.core.state();
let ino = st.intern(parent, node.clone());
if let Some(entry) = st.entries.get_mut(&ino) {
entry.open_count = entry.open_count.saturating_add(1);
}
if let Some(kids) = st.children.get_mut(&parent)
&& !kids.contains(&ino)
{
kids.push(ino);
}
let fh = st
.open
.open_writer(ino, || WriteHandle::created(ino, &node, file, path));
let entry = st.entries.get(&ino).unwrap();
let attr = self.attr(ino, &entry.node, entry.access);
drop(st);
self.core.flush_access_changes();
reply.created(
&TTL,
&attr,
Generation(0),
FileHandle(fh),
FopenFlags::empty(),
);
}
/// The body of [`Filesystem::mkdir`], run off the dispatch loop.
fn serve_mkdir(&self, parent: u64, name: &str, reply: ReplyEntry) {
if let Err(error) = self.core.require_writable(parent) {
reply.error(error);
return;
}
if let Err(e) = self.core.ensure_children(parent) {
reply.error(e);
return;
}
let parent_uid = {
let st = self.core.state();
match st.entries.get(&parent) {
Some(e) => e.uid.clone(),
None => {
reply.error(Errno::ENOENT);
return;
}
match self.namespace.mkdir(parent, name) {
Ok(made) => {
let attr = self.attr(made.ino, &made.node, made.access);
reply.entry(&TTL, &attr, Generation(0));
}
};
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.ok();
// As in `create`: offline — or under a parent that is itself still
// queued — the folder becomes a placeholder that the drain turns into a
// real one.
// Losing the network on the way queues it the same way.
let minted = if self.core.sends_inline() && !is_local_uid(&parent_uid) {
if let Err(error) = self.core.require_uid_writable(&parent_uid) {
reply.error(error);
return;
}
match self
.core
.block_on_bounded(self.core.drive.create_folder(&parent_uid, name, now))
{
Ok(new_uid) => self.core.fetch_minted_node(&new_uid, name),
Err(e) if self.core.lost_link(&e, "mkdir") => None,
Err(e) => {
error!(%parent_uid, name, error = %e, "create folder failed");
reply.error(Errno::EIO);
return;
}
}
} else {
None
};
let node = match minted {
Some(node) => node,
None => match self.core.queue_local_node(&parent_uid, name, true, false) {
Ok(n) => n,
Err(e) => {
reply.error(e);
return;
}
},
};
let mut st = self.core.state();
let local = is_local_uid(&node.uid);
let uid = node.uid.clone();
let ino = st.intern(parent, node);
if let Some(kids) = st.children.get_mut(&parent)
&& !kids.contains(&ino)
{
kids.push(ino);
Err(error) => reply.error(namespace_errno(error)),
}
// A folder that exists only here has nothing to enumerate, and asking the
// API to enumerate a `local~` uid would 404. Record it as fully listed and
// empty, which it is, so reads stay offline-clean across a restart too.
if local {
st.children.insert(ino, Vec::new());
st.record_listed(uid);
}
let entry = st.entries.get(&ino).unwrap();
let attr = self.attr(ino, &entry.node, entry.access);
drop(st);
self.core.flush_access_changes();
reply.entry(&TTL, &attr, Generation(0));
}
/// The body of [`Filesystem::unlink`], run off the dispatch loop.
fn serve_unlink(&self, parent: u64, name_str: &str, reply: ReplyEmpty) {
if let Err(error) = self.core.require_writable(parent) {
reply.error(error);
return;
fn serve_unlink(&self, parent: u64, name: &str, reply: ReplyEmpty) {
match self.namespace.unlink(parent, name) {
Ok(()) => reply.ok(),
Err(error) => reply.error(namespace_errno(error)),
}
if let Ok((ino, _)) = self.core.lookup_child(parent, name_str) {
let st = self.core.state();
if let Some(entry) = st.entries.get(&ino)
&& entry.node.is_folder()
{
reply.error(Errno::EISDIR);
return;
}
}
self.trash_child(parent, name_str, reply);
}
/// The body of [`Filesystem::rmdir`], run off the dispatch loop.
fn serve_rmdir(&self, parent: u64, name_str: &str, reply: ReplyEmpty) {
if let Err(error) = self.core.require_writable(parent) {
reply.error(error);
return;
fn serve_rmdir(&self, parent: u64, name: &str, reply: ReplyEmpty) {
match self.namespace.rmdir(parent, name) {
Ok(()) => reply.ok(),
Err(error) => reply.error(namespace_errno(error)),
}
if let Ok((ino, _)) = self.core.lookup_child(parent, name_str) {
{
let st = self.core.state();
if st
.entries
.get(&ino)
.is_some_and(|entry| !entry.node.is_folder())
{
reply.error(Errno::ENOTDIR);
return;
}
}
// A missing cached listing says "unknown", not "empty". Proton's
// trash call is recursive, so enumerate before applying rmdir's
// POSIX emptiness rule.
if let Err(e) = self.core.ensure_children(ino) {
reply.error(e);
return;
}
if self.core.state().has_children(ino) {
reply.error(Errno::ENOTEMPTY);
return;
}
}
self.trash_child(parent, name_str, reply);
}
/// The body of [`Filesystem::rename`], run off the dispatch loop.
@@ -1430,302 +1225,33 @@ impl ProtonFs {
flags: RenameFlags,
reply: ReplyEmpty,
) {
if let Err(error) = self
.core
.require_writable(parent)
.and_then(|()| self.core.require_writable(newparent))
let flags = pdfs_vfs::namespace::RenameFlags {
no_replace: flags.contains(RenameFlags::RENAME_NOREPLACE),
exchange: flags.contains(RenameFlags::RENAME_EXCHANGE),
};
match self
.namespace
.rename(parent, name, newparent, newname, flags)
{
reply.error(error);
return;
}
let (ino, mut uid) = match self.core.lookup_child(parent, name) {
Ok(x) => x,
Err(e) => {
reply.error(e);
return;
}
};
// Ancestor cycle check: moving a directory into itself or one of its descendants is forbidden by POSIX (EINVAL).
{
let st = self.core.state();
if let Some(entry) = st.entries.get(&ino)
&& entry.node.is_folder()
&& st.is_ancestor_of(ino, newparent)
{
reply.error(Errno::EINVAL);
return;
}
}
// The destination has to be listed either way: the queued path pushes
// the node into that listing, and the online one drops it to force a
// re-enumeration.
if newparent != parent
&& let Err(e) = self.core.ensure_children(newparent)
{
reply.error(e);
return;
}
let (old_parent_uid, new_parent_uid) = {
let st = self.core.state();
match (st.entries.get(&parent), st.entries.get(&newparent)) {
(Some(old), Some(new)) => (old.uid.clone(), new.uid.clone()),
_ => {
reply.error(Errno::ENOENT);
return;
}
}
};
// `rename(2)` replaces an existing destination; Proton has no replacing
// rename, so the victim has to be removed first and the operation stops
// being atomic. Without this the 422 surfaced as a blanket EIO and every
// write-to-temp-then-rename tool — rsync, atomic editor saves — failed
// at the very end of its transfer (`docs/BUGS.md` B13).
//
// `RENAME_EXCHANGE` has no Proton primitive and cannot be emulated
// without a window in which one of the two names does not exist.
if flags.contains(RenameFlags::RENAME_EXCHANGE) {
reply.error(Errno::EINVAL);
return;
}
let victim = match self.core.lookup_child(newparent, newname) {
// Renaming a node onto its own name is a no-op, never a self-replace.
Ok((_, vuid)) if vuid == uid => None,
Ok(x) => Some(x),
// Nothing to replace: the overwhelmingly common case.
Err(e) if e.code() == libc::ENOENT => None,
Err(e) => {
reply.error(e);
return;
}
};
let replacement_authorized = if let Some((victim_ino, victim_uid)) = &victim {
if flags.contains(RenameFlags::RENAME_NOREPLACE) {
reply.error(Errno::EEXIST);
return;
}
// POSIX requires both ends to agree on being a directory, and the
// check has to happen before anything is trashed: getting it wrong
// turns a refusal into the destruction of the destination.
let (src_dir, dst_dir) = {
let st = self.core.state();
let is_dir = |i: &u64| {
st.entries
.get(i)
.map(|e| matches!(e.node.kind, NodeKind::Folder))
};
match (is_dir(&ino), is_dir(victim_ino)) {
(Some(a), Some(b)) => (a, b),
_ => {
reply.error(Errno::ENOENT);
return;
Ok(Renamed::Done) => reply.ok(),
Ok(Renamed::Queued) => {
// Answer first: the kernel updates its cache while it
// processes the answer, and an invalidation sent before it
// would be overwritten, leaving an empty destination listing.
reply.ok();
if let Some(notifier) = self.core.session.notifier.get() {
let _ = notifier.inval_entry(parent, OsStr::new(name));
let _ = notifier.inval_entry(newparent, OsStr::new(newname));
let _ = notifier.inval_inode(parent);
if newparent != parent {
let _ = notifier.inval_inode(newparent);
}
}
};
// Replacing a directory means trashing it, and Proton trashes a
// folder with its whole subtree — so the destination's emptiness has
// to be known before the decision is made.
let dst_empty = if dst_dir {
if let Err(e) = self.core.ensure_children(*victim_ino) {
reply.error(e);
return;
}
self.core
.state
.lock()
.children
.get(victim_ino)
.is_none_or(|kids| kids.is_empty())
} else {
true
};
if let Err(e) = check_replaceable(src_dir, dst_dir, dst_empty) {
reply.error(e);
return;
}
if let Err(error) = require_rename_access(
|authority| self.core.require_uid_writable(authority),
&uid,
&old_parent_uid,
&new_parent_uid,
) {
reply.error(error);
return;
}
if let Err(e) = self.core.remove_replaced(*victim_ino, victim_uid, newname) {
reply.error(e);
return;
}
true
} else {
false
};
// A node whose own creation is still queued has no server-side identity
// to rename: the queued op *is* the node, so rewriting its target is the
// whole rename. Nothing reaches the API, which is why this works offline.
// A create that lands meanwhile leaves no op to rewrite; the node is
// then renamed by the uid Drive gave it (docs/BUGS.md B142).
if is_local_uid(&uid) {
match self.core.db.rewrite_op_target(
&uid.to_string(),
&new_parent_uid.to_string(),
newname,
) {
Ok(true) => {
self.core
.state()
.rename_in_place(ino, newparent, &new_parent_uid, newname);
// A create that failed on its old name is due again.
self.core.wake_drain();
// Finalize: a transient scratch file (its create parked, bytes
// held back) renamed to a finished name is the moment the
// completed file is meant to reach Drive. Un-park the create so
// the drain uploads it once (docs/BUGS.md B70). Renaming to
// another transient name leaves it parked.
if is_transient_name(name) && !is_transient_name(newname) {
match self.core.db.set_create_hold(&uid.to_string(), false) {
Ok(_) => {
self.core.wake_drain();
debug!(%uid, newname, "un-parked a finalized transient create");
}
Err(e) => {
warn!(%uid, error = %e, "un-parking a finalized transient create failed")
}
}
}
debug!(%uid, newname, "renamed a node whose create is still queued");
reply.ok();
return;
}
Ok(false) => match self.core.landed_row_uid(ino) {
Some(real) => {
debug!(local = %uid, %real, newname, "create landed under a rename");
uid = real;
}
None => {
warn!(%uid, name, newname, "queued create vanished under a rename");
self.core
.restore_replaced(victim.as_ref(), &new_parent_uid, newname);
reply.error(Errno::EBUSY);
return;
}
},
Err(e) => {
error!(%uid, error = %e, "rewriting a queued create's target failed");
self.core
.restore_replaced(victim.as_ref(), &new_parent_uid, newname);
reply.error(Errno::EIO);
return;
}
}
Err(error) => reply.error(namespace_errno(error)),
}
// Offline, or into a folder that does not exist remotely yet: queue the
// rename rather than 404 or fail. Online moves into a real parent still
// take the synchronous path, so a genuine API refusal (permissions, a
// name clash) surfaces to the caller instead of becoming a queued op
// that can only ever conflict.
// The queued rename, as a closure: the network going away under the
// synchronous path below lands here too, with whatever half already
// reached Drive. The op records the end state, so the drain finishes
// the rest.
let queue_it = |reply: ReplyEmpty| {
let queued = if replacement_authorized {
self.core.queue_rename_authorized(
ino,
&uid,
&old_parent_uid,
newparent,
&new_parent_uid,
newname,
)
} else {
self.core.queue_rename(
ino,
&uid,
&old_parent_uid,
newparent,
&new_parent_uid,
newname,
)
};
match queued {
Ok(()) => {
// Send the rename response first. Kernel-side rename cache
// updates happen while processing that response; notifying
// before it lets those updates overwrite our invalidation
// and retain an empty destination readdir page.
reply.ok();
if let Some(notifier) = self.core.session.notifier.get() {
let _ = notifier.inval_entry(parent, OsStr::new(&name));
let _ = notifier.inval_entry(newparent, OsStr::new(&newname));
let _ = notifier.inval_inode(parent);
if newparent != parent {
let _ = notifier.inval_inode(newparent);
}
}
}
Err(e) => {
self.core
.restore_replaced(victim.as_ref(), &new_parent_uid, newname);
reply.error(e);
}
}
};
if rename_needs_queue(
self.core.sends_inline(),
is_local_uid(&new_parent_uid),
newparent != parent,
newname != name,
) {
queue_it(reply);
return;
}
// A failure past this point has already trashed any node the rename was
// replacing, so put it back rather than leaving the caller with neither
// the source moved nor the destination intact.
if let Err(error) = require_rename_access(
|authority| self.core.require_uid_writable(authority),
&uid,
&old_parent_uid,
&new_parent_uid,
) {
self.core
.restore_replaced(victim.as_ref(), &new_parent_uid, newname);
reply.error(error);
return;
}
// A move that also renames is one request, so the name only has to be
// free in the destination, and the reply never stands for half of it.
let renamed = if newparent != parent {
let target = (newname != name).then_some(newname);
self.core.move_rename_remote(&uid, &new_parent_uid, target)
} else if newname != name {
self.core.rename_remote(&uid, newname)
} else {
Ok(())
};
if let Err(e) = renamed {
if self.core.lost_link(&e, "rename") {
queue_it(reply);
return;
}
error!(%uid, error = %e, "rename failed");
self.core
.restore_replaced(victim.as_ref(), &new_parent_uid, newname);
reply.error(Errno::EIO);
return;
}
// Through the guard, so the database has both folders unlisted before
// the reply. The next lookup rebuilds a folder still marked listed from
// the database, which did not have the move yet (docs/BUGS.md B135).
self.core
.state()
.relocate(ino, parent, newparent, &new_parent_uid, newname);
reply.ok();
}
/// Expose a file's server-side thumbnail/preview as an extended attribute, so
/// a previewing client can fetch it without downloading the whole file. The
/// bytes are fetched on demand and cached; absence yields `ENODATA`.
/// Answer with an inode's current attributes, or `ENOENT` if it went away
/// while the caller was doing something slower.
fn reply_attr(&self, ino: u64, reply: ReplyAttr) {
@@ -1738,113 +1264,6 @@ impl ProtonFs {
None => reply.error(Errno::ENOENT),
}
}
fn trash_child(&self, parent: u64, name: &str, reply: ReplyEmpty) {
if let Err(error) = self.core.require_writable(parent) {
reply.error(error);
return;
}
let (ino, mut uid) = match self.core.lookup_child(parent, name) {
Ok(x) => x,
Err(e) => {
reply.error(e);
return;
}
};
let open_now = self
.core
.state
.lock()
.entries
.get(&ino)
.is_some_and(|e| e.open_count > 0);
// A node the server has never heard of cannot be trashed there; deleting
// it just means its queued creation is no longer wanted. This works
// offline, which the remote path below cannot.
if is_local_uid(&uid) {
let dropped = if open_now {
self.core.withdraw_queued_ops(&uid)
} else {
self.core.discard_queued_ops(&uid)
};
if let Err(error) = dropped {
reply.error(error);
return;
}
self.core.state().forget_or_unlink(&uid);
// A create that landed before the ops were dropped left none: Drive
// has the node, and the tree had not taken its uid yet. It is
// trashed there like any other (docs/BUGS.md B173).
match self.core.landed_row_uid(ino) {
Some(real) => {
debug!(local = %uid, %real, name, "create landed under a delete");
uid = real;
}
None => {
debug!(%uid, name, "deleted a node that had not been created remotely yet");
reply.ok();
return;
}
}
}
// Queue a folder trash while Drive still holds children that were moved
// out locally. The drain waits for those moves before sending it.
let queue_it = |reply: ReplyEmpty| match self.core.queue_trash(&uid, name, open_now) {
Ok(()) => reply.ok(),
Err(e) => reply.error(e),
};
if !self.core.sends_inline() {
return queue_it(reply);
}
match self.core.has_pending_moves_out_of(&uid) {
Ok(false) => {}
Ok(true) => return queue_it(reply),
Err(error) => return reply.error(error),
}
if let Err(e) = self.core.require_uid_writable(&uid) {
reply.error(e);
return;
}
if let Err(e) = self
.core
.block_on_bounded(self.core.drive.trash_nodes(std::slice::from_ref(&uid)))
.and_then(batch::into_unit)
{
if self.core.lost_link(&e, "trash") {
queue_it(reply);
return;
}
error!(%uid, error = %e, "trash failed");
self.core
.log_activity(ActivityKind::Trash, name, e.to_string(), false);
reply.error(Errno::EIO);
return;
}
// Only remove the namespace entry after Drive accepted the mutation.
// Otherwise an EIO response still made the path disappear locally.
self.core.writes.hide(&uid);
self.core.state().forget_or_unlink(&uid);
if open_now {
// The open handle keeps the staged bytes; the drain must not send
// them to a node that is already in the trash (docs/BUGS.md B106).
if let Err(error) = self.core.withdraw_queued_ops(&uid) {
warn!(%uid, ?error, "remote trash landed but queued-op cleanup failed");
}
} else {
if let Err(error) = self.core.discard_queued_ops(&uid) {
warn!(%uid, ?error, "remote trash landed but queued-op cleanup failed");
}
self.core.cache.evict(&uid);
self.core.evict_reader(&uid);
}
self.core.invalidate_trash();
// Every other trash site records itself; this one did not, which made a
// file found in the trash impossible to attribute after the fact — the
// activity log was the only record and it showed nothing (`docs/BUGS.md` B2).
self.core
.log_activity(ActivityKind::Trash, name, "trashed from the mount", true);
reply.ok();
}
}
impl ProtonFs {
+269 -61
View File
@@ -361,15 +361,6 @@ fn fuse_name(name: &OsStr) -> Result<String, Errno> {
})
}
/// Whether a `rename` may replace an existing destination, as an errno.
fn check_replaceable(src_dir: bool, dst_dir: bool, dst_empty: bool) -> Result<(), Errno> {
pdfs_vfs::names::check_replaceable(src_dir, dst_dir, dst_empty).map_err(|error| match error {
pdfs_vfs::names::ReplaceError::IsDirectory => Errno::EISDIR,
pdfs_vfs::names::ReplaceError::NotDirectory => Errno::ENOTDIR,
pdfs_vfs::names::ReplaceError::NotEmpty => Errno::ENOTEMPTY,
})
}
/// The errno the kernel gets for an operation the open-file service refused.
fn file_errno(error: pdfs_vfs::files::FileError<Errno>) -> Errno {
use pdfs_vfs::files::FileError;
@@ -437,6 +428,203 @@ impl pdfs_vfs::files::FilesHost for Core {
}
}
/// The errno the kernel gets for a namespace change the service refused.
fn namespace_errno(error: pdfs_vfs::namespace::NamespaceError<Errno>) -> Errno {
use pdfs_vfs::namespace::NamespaceError;
match error {
NamespaceError::NotFound => Errno::ENOENT,
NamespaceError::IsDirectory => Errno::EISDIR,
NamespaceError::NotDirectory => Errno::ENOTDIR,
NamespaceError::NotEmpty => Errno::ENOTEMPTY,
NamespaceError::InvalidArgument => Errno::EINVAL,
NamespaceError::Exists => Errno::EEXIST,
NamespaceError::Busy => Errno::EBUSY,
NamespaceError::Io => Errno::EIO,
NamespaceError::Host(errno) => errno,
}
}
impl pdfs_vfs::namespace::NamespaceHost for Core {
type Error = Errno;
fn require_writable(&self, ino: u64) -> Result<(), Errno> {
Core::require_writable(self, ino)
}
fn require_uid_writable(&self, uid: &NodeUid) -> Result<(), Errno> {
Core::require_uid_writable(self, uid)
}
fn ensure_children(&self, ino: u64) -> Result<(), Errno> {
Core::ensure_children(self, ino)
}
fn lookup_child(&self, parent: u64, name: &str) -> Result<Option<(u64, NodeUid)>, Errno> {
match Core::lookup_child(self, parent, name) {
Ok(found) => Ok(Some(found)),
Err(e) if e == Errno::ENOENT => Ok(None),
Err(e) => Err(e),
}
}
fn sends_inline(&self) -> bool {
Core::sends_inline(self)
}
fn mint(&self, parent_uid: &NodeUid, name: &str, folder: bool) -> Result<Option<Node>, Errno> {
// A file starts empty on Drive so it has a real uid at once; what is
// written into it is sealed as a new revision on close.
let minted = if folder {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.ok();
self.block_on_bounded(self.drive.create_folder(parent_uid, name, now))
} else {
self.block_on_bounded(self.drive.upload_file(
parent_uid,
name,
media_type_for(name),
b"",
))
};
let what = if folder { "mkdir" } else { "create" };
match minted {
Ok(new_uid) => Ok(self.fetch_minted_node(&new_uid, name)),
Err(e) if self.lost_link(&e, what) => Ok(None),
Err(e) => {
error!(%parent_uid, name, error = %e, "{what} failed on Drive");
Err(Errno::EIO)
}
}
}
fn queue_create(
&self,
parent_uid: &NodeUid,
name: &str,
folder: bool,
parked: bool,
) -> Result<Node, Errno> {
self.queue_local_node(parent_uid, name, folder, parked)
}
fn access_changed(&self) {
self.flush_access_changes();
}
fn drop_queued(&self, uid: &NodeUid, keep_staged: bool) -> Result<(), Errno> {
if keep_staged {
self.withdraw_queued_ops(uid)
} else {
self.discard_queued_ops(uid)
}
}
fn landed_uid(&self, ino: u64) -> Option<NodeUid> {
self.landed_row_uid(ino)
}
fn has_pending_moves_out_of(&self, uid: &NodeUid) -> Result<bool, Errno> {
Core::has_pending_moves_out_of(self, uid)
}
fn queue_trash(&self, uid: &NodeUid, name: &str, open: bool) -> Result<(), Errno> {
Core::queue_trash(self, uid, name, open)
}
fn trash_remote(&self, uid: &NodeUid, name: &str) -> Result<bool, Errno> {
match self
.block_on_bounded(self.drive.trash_nodes(std::slice::from_ref(uid)))
.and_then(batch::into_unit)
{
Ok(()) => Ok(true),
Err(e) if self.lost_link(&e, "trash") => Ok(false),
Err(e) => {
error!(%uid, error = %e, "trash failed");
self.log_activity(ActivityKind::Trash, name, e.to_string(), false);
Err(Errno::EIO)
}
}
}
fn remove_replaced(&self, ino: u64, uid: &NodeUid, name: &str) -> Result<(), Errno> {
Core::remove_replaced(self, ino, uid, name)
}
fn restore_replaced(&self, victim: Option<&(u64, NodeUid)>, parent: &NodeUid, name: &str) {
Core::restore_replaced(self, victim, parent, name);
}
fn queue_rename(
&self,
ino: u64,
uid: &NodeUid,
old_parent_uid: &NodeUid,
new_parent_ino: u64,
new_parent_uid: &NodeUid,
new_name: &str,
authorized: bool,
) -> Result<(), Errno> {
if authorized {
self.queue_rename_authorized(
ino,
uid,
old_parent_uid,
new_parent_ino,
new_parent_uid,
new_name,
)
} else {
Core::queue_rename(
self,
ino,
uid,
old_parent_uid,
new_parent_ino,
new_parent_uid,
new_name,
)
}
}
fn rename_remote(
&self,
uid: &NodeUid,
new_parent: Option<&NodeUid>,
new_name: Option<&str>,
) -> Result<bool, Errno> {
let renamed = match (new_parent, new_name) {
(Some(parent), name) => self.move_rename_remote(uid, parent, name),
(None, Some(name)) => Core::rename_remote(self, uid, name),
(None, None) => Ok(()),
};
match renamed {
Ok(()) => Ok(true),
Err(e) if self.lost_link(&e, "rename") => Ok(false),
Err(e) => {
error!(%uid, error = %e, "rename failed");
Err(Errno::EIO)
}
}
}
fn wake_drain(&self) {
Core::wake_drain(self);
}
fn trashed(&self, uid: &NodeUid, name: &str, open: bool) {
if !open {
self.evict_reader(uid);
}
self.invalidate_trash();
// Every other trash site records itself; this one did not, which made a
// file found in the trash impossible to attribute after the fact — the
// activity log was the only record and it showed nothing (`docs/BUGS.md` B2).
self.log_activity(ActivityKind::Trash, name, "trashed from the mount", true);
}
}
impl Core {
/// The open-file service over this daemon's tree, cache and write-back.
fn files(&self) -> Arc<pdfs_vfs::files::Files<Core>> {
@@ -448,6 +636,17 @@ impl Core {
self.clone(),
))
}
/// The namespace service over this daemon's tree, cache and write-back.
fn namespace(&self) -> Arc<pdfs_vfs::namespace::Namespace<Core>> {
Arc::new(pdfs_vfs::namespace::Namespace::new(
self.state.clone(),
self.db.clone(),
self.cache.clone(),
self.writes.clone(),
self.clone(),
))
}
}
/// The errno the kernel gets for a node the tree refused.
@@ -733,6 +932,9 @@ struct Core {
/// Set while a diagnostics report's database probe is still out, so a
/// database that does not answer costs one stuck thread, not one per report.
pending_probe: Arc<AtomicBool>,
/// Cold listings in flight, by folder, so callers that find the same
/// folder unlisted at once share one listing ([`Core::list_children`]).
listing_flights: Arc<pdfs_sched::flights::Flights<NodeUid>>,
/// Secondary FUSE sessions for `ondemand` sync folders, keyed by sync-folder
/// id. Each is a `ProtonFs` rooted at the folder's remote
/// node, mounted over its local path, sharing this Core's client/cache/db and
@@ -998,7 +1200,21 @@ impl Core {
}
fn require_writable(&self, ino: u64) -> Result<(), Errno> {
self.state().require_writable(ino).map_err(node_errno)
let st = self.state();
st.require_writable(ino).map_err(|error| {
// A refusal of a node the mount owns has no cause the user can
// see, so it says which node and what access the tree holds.
if matches!(error, pdfs_vfs::tree::NodeError::NotWritable) {
let entry = st.entries.get(&ino);
warn!(
ino,
uid = ?entry.map(|e| &e.uid),
access = ?entry.map(|e| e.access),
"refused a change: the tree holds the node read-only"
);
}
node_errno(error)
})
}
/// Mutation admission point. Persisted and every resident authority must
@@ -1018,7 +1234,14 @@ impl Core {
// The drain, which replays intent recorded long ago, is the one
// caller that has to tell the two apart — see
// [`Core::uid_write_authority`].
WriteAuthority::Denied | WriteAuthority::Unknown => Err(Errno::EACCES),
refused @ (WriteAuthority::Denied | WriteAuthority::Unknown) => {
// Which authority refused, so a refusal nobody expected
// leaves evidence: the persisted row, or a resident mount.
let persisted = self.db.effective_node_access(uid);
let live: Vec<Access> = self.state().access_by_uid(uid).into_iter().collect();
warn!(%uid, ?refused, ?persisted, ?live, "refused a change: the node is not writable");
Err(Errno::EACCES)
}
}
}
@@ -1824,20 +2047,6 @@ fn count_noun(n: usize, one: &str, many: &str) -> String {
format!("{n} {}", if n == 1 { one } else { many })
}
/// Whether a rename must be represented as a durable desired end state.
/// Local-first, offline, or into a not-yet-uploaded directory, the API is not
/// called in the syscall. Only remote-to-remote renames sent inline
/// ([`Core::sends_inline`]) stay synchronous, so a successful kernel reply means
/// the remote namespace has already reached the same end state.
fn rename_needs_queue(
inline: bool,
destination_is_local: bool,
_parent_changed: bool,
_name_changed: bool,
) -> bool {
!inline || destination_is_local
}
/// Bytes rendered with a binary unit and one decimal place (e.g. `"1.2 GB"`),
/// for the activity log. Uses 1024-based steps but the shorter SI labels.
fn human_bytes(bytes: u64) -> String {
@@ -1962,9 +2171,9 @@ mod tests {
copy_pending_for_truncate, fuse_name, is_stale_mount, node_visible, off_the_runtime,
orphan_past_retention, prepare_shared_roots, preserve_on_access_denied,
publish_virtual_root_in_listing, reconcile_virtual_root_in_listing,
release_can_discard_unlinked, release_must_retain_queued_trash, rename_needs_queue,
require_node_parent_access, require_rename_access, resolve_anywhere_with,
shared_with_me_uid, uid_write_authority, virtual_node,
release_can_discard_unlinked, release_must_retain_queued_trash, require_node_parent_access,
require_rename_access, resolve_anywhere_with, shared_with_me_uid, uid_write_authority,
virtual_node,
};
use super::{Db, WriteAuthority};
use std::time::Duration;
@@ -2948,20 +3157,6 @@ mod tests {
assert_ne!(pending.meta.authored, vec![(0, pending.meta.len)]);
}
#[test]
fn online_combined_cross_directory_rename_stays_synchronous() {
assert!(!rename_needs_queue(true, false, true, true));
assert!(rename_needs_queue(false, false, false, true));
assert!(rename_needs_queue(true, true, true, false));
}
#[test]
fn one_step_online_namespace_changes_stay_synchronous() {
assert!(!rename_needs_queue(true, false, false, true));
assert!(!rename_needs_queue(true, false, true, false));
assert!(!rename_needs_queue(true, false, false, false));
}
#[test]
fn fuse_names_enforce_linux_component_limits() {
use std::ffi::OsStr;
@@ -3294,24 +3489,26 @@ mod tests {
assert_before(function, "cancel_upload", mutation);
}
let filesystem = include_str!("filesystem.rs");
for signature in ["fn serve_unlink(", "fn serve_rmdir("] {
let function = function_source(filesystem, signature);
let namespace = include_str!("../../pdfs-vfs/src/namespace.rs");
for signature in ["pub fn unlink(", "pub fn rmdir("] {
let function = function_source(namespace, signature);
assert_before(function, "require_writable", "lookup_child");
}
let rename = function_source(filesystem, "fn serve_rename(");
assert_before(rename, "require_rename_access", "remove_replaced");
assert_before(rename, "remove_replaced", "queue_rename_authorized");
for (signature, gate, remote_call) in [
("fn serve_create(", "require_uid_writable", "upload_file"),
("fn serve_mkdir(", "require_uid_writable", "create_folder"),
("fn trash_child(", "require_uid_writable", "trash_nodes"),
("fn serve_rename(", "require_rename_access", "rename_remote"),
("fn make(", "require_uid_writable", ".mint("),
("fn trash_child(", "require_uid_writable", ".trash_remote("),
] {
let function = function_source(filesystem, signature);
let function = function_source(namespace, signature);
assert_before(function, gate, remote_call);
}
let rename = function_source(namespace, "pub fn rename(");
assert_before(rename, "self.authorize_replace(", "remove_replaced");
assert_before(rename, "remove_replaced", "self.host.queue_rename(");
assert_before(rename, "self.require_rename_access(", ".rename_remote(");
let authorize = function_source(namespace, "fn authorize_replace(");
assert_before(authorize, "check_replaceable", "require_rename_access");
assert_before(authorize, "require_rename_access", "ReplaceJournal::begin");
let control_mkdir = function_source(source, "fn create_folder(");
assert_before(
control_mkdir,
@@ -3664,12 +3861,20 @@ mod tests {
assert_before(withdraw, "self.pending_blob(uid)", "release_dropped_below");
assert!(!withdraw.contains("self.writes.pending.lock().remove(uid)"));
let filesystem = include_str!("filesystem.rs");
let trash = function_source(filesystem, "fn trash_child(");
let namespace = include_str!("../../pdfs-vfs/src/namespace.rs");
let trash = function_source(namespace, "fn trash_child(");
assert_eq!(
trash.matches("self.core.withdraw_queued_ops(&uid)").count(),
trash
.matches("self.host.drop_queued(&uid, open_now)")
.count(),
2
);
let drop_queued = function_source(CORE_SOURCE, "fn drop_queued(");
assert_before(
drop_queued,
"if keep_staged",
"self.withdraw_queued_ops(uid)",
);
let release = function_source(CORE_SOURCE, "fn discard_unlinked(");
assert_before(
release,
@@ -3690,10 +3895,13 @@ mod tests {
// Through the raw lock, the move stayed in the state's outbox, and the
// next lookup rebuilt the destination from a database without it
// (B135).
let rename: String = function_source(include_str!("filesystem.rs"), "fn serve_rename(")
.split_whitespace()
.collect();
assert!(rename.contains("self.core.state().relocate("));
let rename: String = function_source(
include_str!("../../pdfs-vfs/src/namespace.rs"),
"pub fn rename(",
)
.split_whitespace()
.collect();
assert!(rename.contains("self.state().relocate("));
assert!(!rename.contains(".lock().relocate("));
}
+36
View File
@@ -3,6 +3,16 @@
use super::*;
/// How many folders the mount lists on Drive at once, in the daemon's
/// admission ([`pdfs_sched::Class::Listing`]).
///
/// Above what the mount's workers ([`workers::FUSE_WORKERS`]) and a burst
/// of commands list at once, so for now the admission counts cold listings
/// in `pdfs diagnostics` and rarely makes one wait. A lookup must not queue
/// behind a pin walking a large tree; a lower limit waits for a policy that
/// tells the two apart.
pub(crate) const COLD_LISTINGS: usize = 32;
impl Core {
/// Whether [`Core::ensure_children`] would answer for `ino` without
/// touching the network. Lets a handler decide between answering inline
@@ -265,6 +275,22 @@ impl Core {
if !self.is_online() {
return self.adopt_stale_listing(ino, &folder_uid, cached, primary_root);
}
// Single flight: callers that find the folder unlisted at the same
// time share one listing. Each used to ask Drive itself, and all but
// the first threw the answer away. A follower waits for the leader and
// takes what it published; when the leader failed, the follower lists
// the folder itself, so each caller still gets its own answer. A
// shared folder's refresh is left out: its generation check answers a
// caller EAGAIN on its own.
let _lead = if foreign {
None
} else {
match self.listing_flights.join(&folder_uid) {
Some(lead) => Some(lead),
None if self.state().children.contains_key(&ino) => return Ok(()),
None => None,
}
};
let refresh_generation =
refresh_foreign.then(|| self.shared.shared_generation.load(Ordering::SeqCst));
@@ -274,6 +300,15 @@ impl Core {
let queued_before = (!foreign)
.then(|| self.db.queued_children(&folder_uid).ok())
.flatten();
// Asking Drive waits for the daemon's admission of cold listings,
// which counts it in `pdfs diagnostics`. The permit covers the two
// calls to Drive and goes before the listing is published.
let admitted = self
.rt
.block_on(self.sync.admission.admit(pdfs_sched::Step {
class: pdfs_sched::Class::Listing,
root: 0,
}));
let uids = match self
.rt
.block_on(self.drive.enumerate_folder_children_node_uids(&folder_uid))
@@ -306,6 +341,7 @@ impl Core {
return Err(Errno::EIO);
}
};
drop(admitted);
// Drive shows none of what is still queued for the folder (B132).
// A shared folder's listing is published as Drive has it.
if !foreign {
+10
View File
@@ -520,6 +520,12 @@ pub(crate) fn mount_with(
unscanned: Arc::default(),
abandon: Arc::default(),
events_read_at: Arc::new(AtomicI64::new(0)),
local_dirty: Arc::default(),
roots: Arc::default(),
admission: Arc::new(pdfs_sched::Classes::new(|class| match class {
pdfs_sched::Class::Mirror => sync::SYNC_CONCURRENCY,
pdfs_sched::Class::Listing => super::listing::COLD_LISTINGS,
})),
};
let state = Arc::new(Ranked::new(
Rank::State,
@@ -571,6 +577,7 @@ pub(crate) fn mount_with(
events,
indexing: Arc::new(AtomicBool::new(false)),
pending_probe: Arc::default(),
listing_flights: Arc::default(),
mounts: Arc::new(Mutex::new(SecondaryMountRegistry::default())),
states: Arc::new(StateRegistry::default()),
};
@@ -582,6 +589,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.
+128
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
@@ -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 —
+130
View File
@@ -0,0 +1,130 @@
//! The mounted-files conformance scenarios (`pdfs_vfs::conformance`) run
//! through the FUSE adapter: a daemon mounted over the fake Drive, driven with
//! ordinary file system calls. The headless adapter runs the same scenarios
//! in `pdfs-vfs`, and both have to see the same outcomes.
use std::fs::{File, OpenOptions};
use std::os::unix::fs::FileExt;
use std::path::PathBuf;
use pdfs_vfs::conformance::Adapter;
use pdfs_vfs::headless::Failure;
/// A mount, addressed by paths relative to its root.
pub(crate) struct Mounted(pub(crate) PathBuf);
fn failure(error: std::io::Error) -> Failure {
error
.raw_os_error()
.map_or(Failure::Io, Failure::from_errno)
}
impl Adapter for Mounted {
type Fd = File;
fn create(&self, path: &str) -> Result<File, Failure> {
File::create(self.0.join(path)).map_err(failure)
}
fn open_write(&self, path: &str) -> Result<File, Failure> {
OpenOptions::new()
.write(true)
.open(self.0.join(path))
.map_err(failure)
}
fn write(&self, fd: &File, offset: u64, data: &[u8]) -> Result<(), Failure> {
fd.write_all_at(data, offset).map_err(failure)
}
fn set_len(&self, fd: &File, size: u64) -> Result<(), Failure> {
fd.set_len(size).map_err(failure)
}
fn fsync(&self, fd: &File) -> Result<(), Failure> {
fd.sync_all().map_err(failure)
}
fn close(&self, fd: File) -> Result<(), Failure> {
// `close(2)`'s own error is the flush's, which `File` drops; flush
// first so a failure is seen.
fd.sync_data().map_err(failure)?;
drop(fd);
Ok(())
}
fn read(&self, path: &str) -> Result<Vec<u8>, Failure> {
std::fs::read(self.0.join(path)).map_err(failure)
}
fn mkdir(&self, path: &str) -> Result<(), Failure> {
std::fs::create_dir(self.0.join(path)).map_err(failure)
}
fn unlink(&self, path: &str) -> Result<(), Failure> {
std::fs::remove_file(self.0.join(path)).map_err(failure)
}
fn rmdir(&self, path: &str) -> Result<(), Failure> {
std::fs::remove_dir(self.0.join(path)).map_err(failure)
}
fn rename(&self, from: &str, to: &str) -> Result<(), Failure> {
std::fs::rename(self.0.join(from), self.0.join(to)).map_err(failure)
}
fn list(&self, path: &str) -> Result<Vec<String>, Failure> {
let mut names = std::fs::read_dir(self.0.join(path))
.map_err(failure)?
.map(|entry| {
entry
.map(|entry| entry.file_name().to_string_lossy().into_owned())
.map_err(failure)
})
.collect::<Result<Vec<_>, _>>()?;
names.sort();
Ok(names)
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::*;
use crate::mount::MountOutcome;
use crate::sim::daemon::{Daemon, scratch, wait_until};
use crate::sim::fake_drive::{FakeDrive, Faults};
fn run_through_a_mount(label: &str, online: bool) {
let drive = FakeDrive::new();
let dir = scratch(label);
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
daemon.client.set_online(online);
let mount = Mounted(daemon.mountpoint.clone());
mount.mkdir("conformance").unwrap();
let failed = pdfs_vfs::conformance::run(&mount, "conformance");
daemon.client.set_online(true);
// Whatever the scenarios queued drains before the daemon stops, so the
// stop does not race an upload.
let drained = wait_until(Duration::from_secs(60), || {
daemon.pending().is_ok_and(|items| items.is_empty())
});
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
assert!(failed.is_empty(), "{failed:#?}");
assert!(drained, "the queue did not drain");
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn the_mount_passes_every_conformance_scenario_online() {
run_through_a_mount("conformance-online", true);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn the_mount_passes_every_conformance_scenario_offline() {
run_through_a_mount("conformance-offline", false);
}
}
+317
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]
@@ -538,6 +539,81 @@ mod tests {
assert!(uploads.count >= 1);
}
/// How often the daemon has asked Drive for the children of a folder.
fn children_listed(daemon: &Daemon) -> u64 {
let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics)
else {
panic!("no diagnostics");
};
diagnostics
.drive_calls
.iter()
.find(|stat| stat.call == "enumerate_folder_children_node_uids")
.map_or(0, |stat| stat.count)
}
fn listing_load(daemon: &Daemon) -> control::AdmissionLoad {
let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics)
else {
panic!("no diagnostics");
};
diagnostics
.admission
.into_iter()
.find(|load| load.class == "listing")
.expect("the admission reports cold listings")
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn callers_that_find_a_folder_unlisted_at_once_share_one_listing() {
// Each caller used to ask Drive for the folder itself, and all but
// the first threw the answer away. Now the first lists it, through
// the daemon's admission, and the others wait for that listing.
let drive = FakeDrive::new();
let cold = drive.device().mkdir("cold");
for name in ["a.txt", "b.txt", "c.txt"] {
drive
.device()
.write(&format!("cold/{name}"), name.as_bytes());
}
let dir = scratch("cold-listing-flight");
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
let listed = |daemon: &Daemon| match daemon.request(&Request::ListDir {
path: "cold".into(),
}) {
Ok(Response::Entries { entries }) => {
let mut names: Vec<String> = entries.into_iter().map(|e| e.name).collect();
names.sort();
names
}
other => panic!("listing cold: {other:?}"),
};
// The mount root is listed first, so the only listing held is cold's.
let _ = std::fs::read_dir(&daemon.mountpoint).unwrap().count();
let before = children_listed(&daemon);
let held = daemon.client.hold_next_children_of(&cold);
std::thread::scope(|scope| {
let callers: Vec<_> = (0..4).map(|_| scope.spawn(|| listed(&daemon))).collect();
assert!(wait_until(Duration::from_secs(10), || held.reached()));
// Give the others time to find the folder unlisted too.
std::thread::sleep(Duration::from_millis(500));
let load = listing_load(&daemon);
assert_eq!((load.running, load.waiting), (1, 0), "{load:?}");
drop(held);
for caller in callers {
assert_eq!(caller.join().unwrap(), ["a.txt", "b.txt", "c.txt"]);
}
});
assert_eq!(children_listed(&daemon) - before, 1);
let load = listing_load(&daemon);
assert_eq!(load.running, 0, "{load:?}");
assert!(load.admitted >= 1, "{load:?}");
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_daemon_on_the_fake_drive_syncs_both_ways() {
@@ -1887,6 +1963,58 @@ mod tests {
.map_or(0, |c| c.value)
}
/// What the watcher reports covers every change a pass then finds on
/// disk: an edit, a new folder with a file in it, a deletion, and a folder
/// moved in from outside with a folder and a file in it (`local_dirty`).
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn the_local_dirty_set_covers_what_the_walk_finds() {
let drive = FakeDrive::new();
let dir = scratch("local-dirty");
let (daemon, folder, _client) =
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
// From the pass after this one, the watch has been live since the
// last claim.
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
let settled = quiet_pass(&daemon, folder).expect("a quiet pass is traced");
assert_eq!(counted(&settled, "local dirty untrusted"), 0, "{settled}");
let local = dir.join("local");
let outside = dir.join("outside");
std::fs::create_dir_all(outside.join("deep")).unwrap();
std::fs::write(outside.join("deep").join("x.txt"), b"moved in").unwrap();
std::fs::write(local.join("a.txt"), b"edited").unwrap();
std::fs::create_dir(local.join("new")).unwrap();
std::fs::write(local.join("new").join("c.txt"), b"three").unwrap();
std::fs::remove_file(local.join("b.txt")).unwrap();
std::fs::rename(&outside, local.join("moved")).unwrap();
assert!(wait_until(Duration::from_secs(60), || {
drive.lookup("mirrored/new/c.txt").is_some()
&& drive.lookup("mirrored/moved/deep/x.txt").is_some()
&& drive.lookup("mirrored/b.txt").is_none()
}));
let after = quiet_pass(&daemon, folder).expect("a quiet pass is traced");
assert_eq!(counted(&after, "local dirty untrusted"), 0, "{after}");
let logged = take_logged();
let missed: Vec<&String> = logged
.iter()
.filter(|line| line.contains("local dirty set missed"))
.collect();
assert!(missed.is_empty(), "{missed:?}");
// The first pass took the folder from discovery to following, and
// nothing since put it in doubt (`root`).
let roots: Vec<&String> = logged
.iter()
.filter(|line| line.contains("sync: root state"))
.collect();
assert!(
roots.len() == 1 && roots[0].contains("to=following"),
"{roots:?}"
);
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_mirror_pass_reports_where_its_time_went() {
@@ -1903,6 +2031,9 @@ mod tests {
let first = traced_pass(&daemon, folder, |t| calls(t, "upload") > 0)
.expect("the first pass is traced");
assert_eq!(calls(&first, "upload"), 3);
// Each upload waited for the daemon's admission first, and the time
// in line is its own entry, apart from the time on the network.
assert_eq!(calls(&first, "admission wait"), 3, "{first}");
assert_eq!(counted(&first, "local entries"), 3);
assert!(counted(&first, "remote folders") >= 1);
for phase in ["baseline", "local walk", "remote walk", "apply"] {
@@ -1916,6 +2047,17 @@ mod tests {
.iter()
.any(|line| line.contains("sync: pass trace"))
);
let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics)
else {
panic!("no diagnostics");
};
let mirror = diagnostics
.admission
.iter()
.find(|load| load.class == "mirror")
.expect("the admission reports mirror steps");
assert!(mirror.admitted >= 3, "{mirror:?}");
assert_eq!((mirror.running, mirror.waiting), (0, 0), "{mirror:?}");
// Drive does not list a node it has just made at once, so the read
// back after an upload has no revision id to record. The next pass
@@ -2874,6 +3016,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 +4759,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
View File
@@ -1,6 +1,7 @@
//! The simulation tests of `docs/TESTING.md`: a fake Drive with
//! the faults the real one has, and the tools to drive daemons against it.
pub(crate) mod conformance;
pub(crate) mod daemon;
pub(crate) use pdfs_drive::sim::fake_drive;
pub(crate) mod model;
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "pdfs-sched"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
rust-version.workspace = true
repository.workspace = true
homepage.workspace = true
description = "Admission of background work for the Proton Drive Linux client"
[dependencies]
tokio.workspace = true
parking_lot.workspace = true
+154
View File
@@ -0,0 +1,154 @@
//! Single flight: one caller does a piece of work, the others asking for the
//! same thing at the same time wait for it.
//!
//! The first caller for a key leads and gets a [`Lead`]; it does the work and
//! drops the lead when done, whether it succeeded, failed or panicked. A
//! caller that finds a lead out for its key follows: [`Flights::join`] blocks
//! until that lead is dropped and returns `None`. The follower then looks
//! again at what the leader left behind; when the leader failed it does the
//! work itself, so every caller still gets an answer of its own.
//!
//! The wait is a blocking one, for the threads that serve the mount. A
//! follower must hold nothing its leader needs.
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::Arc;
use parking_lot::{Condvar, Mutex};
/// The work in flight, by key.
pub struct Flights<K: Eq + Hash + Clone> {
out: Mutex<HashMap<K, Arc<Flight>>>,
}
/// One piece of work in flight, which its followers wait on.
#[derive(Default)]
struct Flight {
landed: Mutex<bool>,
wake: Condvar,
}
/// The right and the duty to do the work for one key. Dropping it lets the
/// followers go.
pub struct Lead<'a, K: Eq + Hash + Clone> {
flights: &'a Flights<K>,
key: K,
flight: Arc<Flight>,
}
impl<K: Eq + Hash + Clone> Default for Flights<K> {
fn default() -> Self {
Self {
out: Mutex::new(HashMap::new()),
}
}
}
impl<K: Eq + Hash + Clone> Flights<K> {
/// Lead the work for `key`, or, when another caller leads it already,
/// wait until that caller is done and return `None`.
pub fn join(&self, key: &K) -> Option<Lead<'_, K>> {
let flight = {
let mut out = self.out.lock();
match out.get(key) {
Some(flight) => flight.clone(),
None => {
let flight = Arc::new(Flight::default());
out.insert(key.clone(), flight.clone());
return Some(Lead {
flights: self,
key: key.clone(),
flight,
});
}
}
};
let mut landed = flight.landed.lock();
while !*landed {
flight.wake.wait(&mut landed);
}
None
}
/// How many keys have work in flight.
pub fn len(&self) -> usize {
self.out.lock().len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<K: Eq + Hash + Clone> Drop for Lead<'_, K> {
fn drop(&mut self) {
// Out of the map first, so a caller that comes after the followers
// wake leads anew rather than following a flight that has landed.
self.flights.out.lock().remove(&self.key);
*self.flight.landed.lock() = true;
self.flight.wake.notify_all();
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
use std::time::Duration;
use super::*;
#[test]
fn callers_that_ask_at_once_share_one_flight() {
let flights = Arc::new(Flights::<u32>::default());
let worked = Arc::new(AtomicUsize::new(0));
let lead = flights.join(&7).expect("the first caller leads");
let followers: Vec<_> = (0..4)
.map(|_| {
let (flights, worked) = (flights.clone(), worked.clone());
thread::spawn(move || {
if flights.join(&7).is_some() {
worked.fetch_add(1, Ordering::SeqCst);
}
})
})
.collect();
thread::sleep(Duration::from_millis(30));
assert!(followers.iter().all(|f| !f.is_finished()));
drop(lead);
for follower in followers {
follower.join().unwrap();
}
assert_eq!(worked.load(Ordering::SeqCst), 0);
assert!(flights.is_empty());
}
#[test]
fn different_keys_do_not_wait_for_each_other() {
let flights = Flights::<u32>::default();
let _a = flights.join(&1).expect("leads 1");
let _b = flights.join(&2).expect("leads 2");
assert_eq!(flights.len(), 2);
}
#[test]
fn a_leader_that_panics_still_lets_its_followers_go() {
let flights = Arc::new(Flights::<u32>::default());
let (led, lead_now) = std::sync::mpsc::channel();
let leader = {
let flights = flights.clone();
thread::spawn(move || {
let _lead = flights.join(&3).expect("leads");
led.send(()).unwrap();
thread::sleep(Duration::from_millis(20));
panic!("the work failed");
})
};
lead_now.recv().unwrap();
assert!(flights.join(&3).is_none());
assert!(leader.join().is_err());
// The next caller leads again.
assert!(flights.join(&3).is_some());
}
}
+466
View File
@@ -0,0 +1,466 @@
//! Admission: when a runnable step of background work may start.
//!
//! Step 6 of the 4.0 plan in `docs/ARCHITECTURE.md` gives the daemon one
//! account-wide admission policy for mirrors, reads and writeback
//! (`SCHEDULER_AND_WORKERS.md`). This crate is its port. A service describes
//! each step it is about to run as a [`Step`] and waits for a [`Permit`]
//! from an [`Admission`]; dropping the permit gives the capacity back.
//!
//! The sync engine is the first caller: every upload, download and folder
//! creation of a mirror pass is admitted here. [`Bounded`] is the policy the
//! daemon supplies for now, a fixed number of steps at once, which is what the
//! engine did on its own before. An account-wide controller that weighs
//! mirrors against mounted reads and the drain plugs in behind the same trait
//! later, without the engine changing.
//!
//! [`flights`] holds the single flight that lets callers asking for the same
//! thing at once share one piece of work.
//!
//! An admission decides only; it runs no step and does no I/O. It does say
//! what it is doing: [`Admission::load`] reports, per class, how many steps
//! run, how many wait and for how long, so a stall report can tell a step
//! waiting in line from one already on the network.
pub mod flights;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, Instant};
use parking_lot::Mutex;
use tokio::sync::Semaphore;
/// The kind of work a step is, which a policy weighs against the others.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Class {
/// One effect of a mirror pass: an upload, a download, or a folder made
/// on Drive.
Mirror,
/// Listing a folder on Drive that the mount has not listed yet, for a
/// lookup, a `readdir` or a command that resolves a path.
Listing,
}
impl Class {
/// Every class, in the order a report lists them.
pub const ALL: [Class; 2] = [Class::Mirror, Class::Listing];
/// The class's name in diagnostics.
pub fn name(self) -> &'static str {
match self {
Class::Mirror => "mirror",
Class::Listing => "listing",
}
}
}
/// A step that is ready to run and asks to be admitted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Step {
pub class: Class,
/// The root the step works for, such as the id of a synced folder, so a
/// policy can be fair across roots. `0` for work of the mount itself.
pub root: i64,
}
/// The capacity a step was admitted with. Dropping it gives the capacity
/// back.
pub struct Permit {
_held: Box<dyn Send + Sync>,
}
impl Permit {
/// A permit that holds `capacity` until it is dropped.
pub fn new(capacity: impl Send + Sync + 'static) -> Self {
Self {
_held: Box::new(capacity),
}
}
}
/// The future an admission answers with: it resolves once the step may run.
pub type Admitting<'a> = Pin<Box<dyn Future<Output = Permit> + Send + 'a>>;
/// What an admission is doing for one class of step, in [`Admission::load`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Load {
pub class: Class,
/// Steps admitted and still holding their permit.
pub running: usize,
/// Steps that asked and have not been admitted yet.
pub waiting: usize,
/// How long the step that has waited longest has waited so far.
pub oldest_wait: Option<Duration>,
/// Steps admitted since the policy was made.
pub admitted: u64,
/// The time those steps spent waiting, in total and at most.
pub waited: Duration,
pub longest_wait: Duration,
}
/// A policy that decides when a step may start.
pub trait Admission: Send + Sync {
/// Wait until `step` may run, and return the capacity it runs with.
fn admit(&self, step: Step) -> Admitting<'_>;
/// What the policy is doing now, one entry per class it has seen. It must
/// answer without waiting on a step, so a stall report can ask it while
/// every step is stuck.
fn load(&self) -> Vec<Load> {
Vec::new()
}
}
/// The counters behind [`Load`], for one class.
#[derive(Default)]
struct Counters {
running: usize,
/// When each waiting step asked, by ticket.
waiting: Vec<(u64, Instant)>,
admitted: u64,
waited: Duration,
longest_wait: Duration,
}
/// The counters of every class, shared by a policy and the permits and
/// pending admissions it handed out. Each lock is held for a few field
/// updates and never across an await.
#[derive(Default)]
struct Meter {
classes: Mutex<[Counters; Class::ALL.len()]>,
next_ticket: std::sync::atomic::AtomicU64,
}
impl Meter {
fn ask(self: &Arc<Self>, class: Class) -> Asking {
let ticket = self
.next_ticket
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let asked = Instant::now();
self.classes.lock()[class as usize]
.waiting
.push((ticket, asked));
Asking {
meter: self.clone(),
class,
ticket,
asked,
admitted: false,
}
}
fn load(&self) -> Vec<Load> {
let now = Instant::now();
let classes = self.classes.lock();
Class::ALL
.iter()
.map(|class| {
let c = &classes[*class as usize];
Load {
class: *class,
running: c.running,
waiting: c.waiting.len(),
oldest_wait: c
.waiting
.iter()
.map(|(_, asked)| now.saturating_duration_since(*asked))
.max(),
admitted: c.admitted,
waited: c.waited,
longest_wait: c.longest_wait,
}
})
.collect()
}
}
/// A step that has asked and not been admitted yet. Dropped unadmitted, as
/// when the caller gives up waiting, it leaves the queue without counting.
struct Asking {
meter: Arc<Meter>,
class: Class,
ticket: u64,
asked: Instant,
admitted: bool,
}
impl Asking {
/// The step was admitted: it stops waiting and starts running.
fn admitted(mut self) -> Running {
let waited = self.asked.elapsed();
{
let mut classes = self.meter.classes.lock();
let c = &mut classes[self.class as usize];
c.waiting.retain(|(t, _)| *t != self.ticket);
c.running += 1;
c.admitted += 1;
c.waited += waited;
c.longest_wait = c.longest_wait.max(waited);
}
self.admitted = true;
Running {
meter: self.meter.clone(),
class: self.class,
}
}
}
impl Drop for Asking {
fn drop(&mut self) {
if !self.admitted {
self.meter.classes.lock()[self.class as usize]
.waiting
.retain(|(t, _)| *t != self.ticket);
}
}
}
/// A step that runs; dropping it counts the step as done.
struct Running {
meter: Arc<Meter>,
class: Class,
}
impl Drop for Running {
fn drop(&mut self) {
let mut classes = self.meter.classes.lock();
let c = &mut classes[self.class as usize];
c.running = c.running.saturating_sub(1);
}
}
/// At most a fixed number of steps at once, whatever their class or root,
/// admitted in the order they asked.
pub struct Bounded {
slots: Arc<Semaphore>,
meter: Arc<Meter>,
}
impl Bounded {
/// A policy that runs at most `limit` steps at once. `limit` must be at
/// least 1.
pub fn new(limit: usize) -> Self {
assert!(limit > 0, "an admission that admits nothing never finishes");
Self {
slots: Arc::new(Semaphore::new(limit)),
meter: Arc::default(),
}
}
/// How many more steps could start now.
pub fn available(&self) -> usize {
self.slots.available_permits()
}
}
impl Admission for Bounded {
fn admit(&self, step: Step) -> Admitting<'_> {
let slots = self.slots.clone();
let asking = self.meter.ask(step.class);
Box::pin(async move {
// The semaphore is never closed, so the acquire cannot fail.
let slot = slots.acquire_owned().await.expect("semaphore never closed");
// A tuple drops its fields in order: the step stops counting as
// running before its slot goes back, so
// a report never shows more running than the limit.
Permit::new((asking.admitted(), slot))
})
}
fn load(&self) -> Vec<Load> {
self.meter.load()
}
}
/// A limit of its own for each class: steps of one class never wait for
/// steps of another. Within a class, steps are admitted in the order they
/// asked.
pub struct Classes {
slots: [Arc<Semaphore>; Class::ALL.len()],
meter: Arc<Meter>,
}
impl Classes {
/// A policy with the limit `limit(class)` for each class. Every limit must
/// be at least 1.
pub fn new(limit: impl Fn(Class) -> usize) -> Self {
Self {
slots: Class::ALL.map(|class| {
let n = limit(class);
assert!(n > 0, "an admission that admits nothing never finishes");
Arc::new(Semaphore::new(n))
}),
meter: Arc::default(),
}
}
/// How many more steps of `class` could start now.
pub fn available(&self, class: Class) -> usize {
self.slots[class as usize].available_permits()
}
}
impl Admission for Classes {
fn admit(&self, step: Step) -> Admitting<'_> {
let slots = self.slots[step.class as usize].clone();
let asking = self.meter.ask(step.class);
Box::pin(async move {
// The semaphore is never closed, so the acquire cannot fail.
let slot = slots.acquire_owned().await.expect("semaphore never closed");
Permit::new((asking.admitted(), slot))
})
}
fn load(&self) -> Vec<Load> {
self.meter.load()
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use super::*;
fn step(root: i64) -> Step {
Step {
class: Class::Mirror,
root,
}
}
#[test]
fn a_bounded_admission_never_runs_more_than_its_limit() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(4)
.enable_time()
.build()
.unwrap();
let admission = Arc::new(Bounded::new(3));
let running = Arc::new(AtomicUsize::new(0));
let peak = Arc::new(AtomicUsize::new(0));
rt.block_on(async {
let mut set = tokio::task::JoinSet::new();
for root in 0..20 {
let (admission, running, peak) = (admission.clone(), running.clone(), peak.clone());
set.spawn(async move {
let _permit = admission.admit(step(root)).await;
let now = running.fetch_add(1, Ordering::SeqCst) + 1;
peak.fetch_max(now, Ordering::SeqCst);
tokio::time::sleep(Duration::from_millis(5)).await;
running.fetch_sub(1, Ordering::SeqCst);
});
}
while set.join_next().await.is_some() {}
});
assert_eq!(peak.load(Ordering::SeqCst), 3);
assert_eq!(admission.available(), 3);
}
#[test]
fn dropping_a_permit_gives_its_capacity_back() {
let rt = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
let admission = Bounded::new(1);
rt.block_on(async {
let first = admission.admit(step(1)).await;
assert_eq!(admission.available(), 0);
drop(first);
assert_eq!(admission.available(), 1);
let _second = admission.admit(step(2)).await;
assert_eq!(admission.available(), 0);
});
}
#[test]
fn the_load_counts_running_and_waiting_steps() {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.unwrap();
let admission = Bounded::new(1);
rt.block_on(async {
let first = admission.admit(step(1)).await;
let mut second = admission.admit(step(2));
// Polled once, the second step is in line behind the first.
assert!(
tokio::time::timeout(Duration::from_millis(20), &mut second)
.await
.is_err()
);
let load = &admission.load()[0];
assert_eq!((load.running, load.waiting, load.admitted), (1, 1, 1));
assert!(load.oldest_wait.unwrap() >= Duration::from_millis(20));
drop(first);
let second = second.await;
let load = &admission.load()[0];
assert_eq!((load.running, load.waiting, load.admitted), (1, 0, 2));
assert_eq!(load.oldest_wait, None);
assert!(load.longest_wait >= Duration::from_millis(20));
assert!(load.waited >= load.longest_wait);
drop(second);
assert_eq!(admission.load()[0].running, 0);
});
}
#[test]
fn a_step_that_stops_waiting_leaves_the_line() {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.unwrap();
let admission = Bounded::new(1);
rt.block_on(async {
let _first = admission.admit(step(1)).await;
let gave_up =
tokio::time::timeout(Duration::from_millis(5), admission.admit(step(2))).await;
assert!(gave_up.is_err());
let load = &admission.load()[0];
assert_eq!((load.running, load.waiting, load.admitted), (1, 0, 1));
});
}
#[test]
fn a_class_at_its_limit_does_not_hold_up_another() {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.unwrap();
let admission = Classes::new(|class| match class {
Class::Mirror => 1,
Class::Listing => 2,
});
rt.block_on(async {
let _mirror = admission.admit(step(1)).await;
let blocked = tokio::time::timeout(Duration::from_millis(5), admission.admit(step(1)));
assert!(blocked.await.is_err());
let listing = Step {
class: Class::Listing,
root: 0,
};
let _a = admission.admit(listing).await;
let _b = admission.admit(listing).await;
assert_eq!(admission.available(Class::Listing), 0);
let load = admission.load();
assert_eq!(load[Class::Mirror as usize].running, 1);
assert_eq!(load[Class::Listing as usize].running, 2);
});
}
#[test]
#[should_panic(expected = "admits nothing")]
fn a_class_limit_of_nothing_is_refused() {
let _ = Classes::new(|class| usize::from(class == Class::Mirror));
}
#[test]
#[should_panic(expected = "admits nothing")]
fn a_bounded_admission_of_nothing_is_refused() {
let _ = Bounded::new(0);
}
}
+39 -1
View File
@@ -11,7 +11,7 @@ use super::Db;
use pdfs_core::Result;
/// Current schema version. Bump on every forward migration added below.
pub(super) const SCHEMA_VERSION: i64 = 49;
pub(super) const SCHEMA_VERSION: i64 = 50;
impl Db {
pub(super) fn migrate(&self) -> Result<()> {
@@ -543,6 +543,16 @@ impl Db {
tx.execute_batch(MIGRATION_V49)?;
}
}
if current < 50 {
let has_folders: bool = tx.query_row(
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'sync_folder'",
[],
|row| row.get::<_, i64>(0).map(|n| n > 0),
)?;
if has_folders {
tx.execute_batch(MIGRATION_V50)?;
}
}
tx.execute(
"INSERT INTO sync_state (key, value) VALUES ('schema_version', ?1)
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
@@ -1547,6 +1557,34 @@ ALTER TABLE sync_walk ADD COLUMN complete INTEGER NOT NULL DEFAULT 0;
ALTER TABLE sync_walk ADD COLUMN seq INTEGER NOT NULL DEFAULT 0;
";
/// Schema v50: the deletions a mirror folder made lately, so the wipe guard
/// sees a tree lost a little at a time, and not only one lost in a single pass
/// (`docs/SYNC_ENGINE.md`).
///
/// One row a folder: when the window began, how many paths the folder
/// tracked then, and how many deletions it has made since. A change to what
/// the folder is, or its removal, drops the row, as it drops the saved walk.
const MIGRATION_V50: &str = "
CREATE TABLE IF NOT EXISTS sync_delete_window (
folder_id INTEGER PRIMARY KEY,
started_at INTEGER NOT NULL,
reference INTEGER NOT NULL,
deleted INTEGER NOT NULL
);
DROP TRIGGER IF EXISTS sync_delete_window_drop_on_folder_update;
DROP TRIGGER IF EXISTS sync_delete_window_drop_on_folder_delete;
CREATE TRIGGER sync_delete_window_drop_on_folder_update
AFTER UPDATE OF local_path, remote_uid, mode ON sync_folder
BEGIN
DELETE FROM sync_delete_window WHERE folder_id = OLD.id;
END;
CREATE TRIGGER sync_delete_window_drop_on_folder_delete
AFTER DELETE ON sync_folder
BEGIN
DELETE FROM sync_delete_window WHERE folder_id = OLD.id;
END;
";
/// See [`MIGRATION_V49_COLUMNS`].
const MIGRATION_V49: &str = "
CREATE TABLE IF NOT EXISTS sync_remote_dirty (
+31 -1
View File
@@ -44,6 +44,7 @@ mod nodes;
mod ops;
mod photos;
mod pins;
mod replace;
mod share_access;
mod state;
mod sync;
@@ -63,7 +64,10 @@ pub use ops::{
};
pub use photos::{StoredPhoto, StoredPlace, THUMB_HAVE, THUMB_NONE, THUMB_UNKNOWN, TimelineRow};
pub use pins::PinRow;
pub use sync::{SavedWalk, SavedWalkDir, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
pub use replace::ReplaceIntent;
pub use sync::{
DeleteWindow, SavedWalk, SavedWalkDir, SavedWalkItem, StoredSyncEntry, StoredSyncFolder,
};
pub use trash::StoredTrash;
/// Size the WAL is truncated back to after a checkpoint. Comfortably above the
@@ -108,6 +112,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 +302,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 +393,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 +418,7 @@ impl Db {
conn: Ranked::new(Rank::DbWriter, conn),
readers: None,
_single_writer: None,
run: next_run(),
};
db.migrate()?;
Ok(db)
@@ -429,6 +440,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)
}
}
+48
View File
@@ -7,6 +7,18 @@ use super::Db;
use pdfs_core::Result;
use std::collections::HashMap;
/// The deletions a mirror folder has made since a window began, which the
/// wipe guard adds to a pass's own before it lets that pass delete anything.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DeleteWindow {
/// When the window began, in seconds since the epoch.
pub started_at: i64,
/// The most paths the folder has tracked since then.
pub reference: u64,
/// The deletions made since then, on either side.
pub deleted: u64,
}
/// What a mirror pass has walked of Drive, saved so a pass cut short
/// resumes the walk instead of listing every folder again (B294), and so a
/// finished walk serves as the next pass's picture of Drive.
@@ -780,6 +792,42 @@ impl Db {
Ok(())
}
/// The deletion window of a mirror folder, if one is open.
pub fn sync_delete_window(&self, folder_id: i64) -> Result<Option<DeleteWindow>> {
let conn = self.read()?;
conn.query_row(
"SELECT started_at, reference, deleted FROM sync_delete_window WHERE folder_id = ?1",
params![folder_id],
|row| {
Ok(DeleteWindow {
started_at: row.get(0)?,
reference: row.get::<_, i64>(1)?.max(0) as u64,
deleted: row.get::<_, i64>(2)?.max(0) as u64,
})
},
)
.optional()
.map_err(Into::into)
}
/// Record the deletion window of a mirror folder.
pub fn sync_delete_window_set(&self, folder_id: i64, window: &DeleteWindow) -> Result<()> {
let conn = self.conn.lock();
conn.execute(
"INSERT INTO sync_delete_window (folder_id, started_at, reference, deleted)
VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(folder_id) DO UPDATE SET started_at = excluded.started_at,
reference = excluded.reference, deleted = excluded.deleted",
params![
folder_id,
window.started_at,
i64::try_from(window.reference).unwrap_or(i64::MAX),
i64::try_from(window.deleted).unwrap_or(i64::MAX)
],
)?;
Ok(())
}
/// Drop the entire baseline for a folder. Used when flipping ondemand→mirror:
/// the local tree was evicted, so the old baseline is stale and would make the
/// next reconcile mistake "locally deleted" for "must re-download". Clearing it
+71
View File
@@ -8381,3 +8381,74 @@ 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());
}
/// A folder's deletion window outlives the pass that opened it, and goes with
/// the folder: a change to what the folder is starts the count again.
#[test]
fn a_deletion_window_is_kept_per_folder_until_the_folder_changes() {
let db = Db::open_in_memory().unwrap();
let id = db.sync_folder_add("/home/me/Docs", "v~root", "s").unwrap();
let other = db
.sync_folder_add("/home/me/Other", "v~other", "s")
.unwrap();
assert_eq!(db.sync_delete_window(id).unwrap(), None);
let window = DeleteWindow {
started_at: 100,
reference: 40,
deleted: 12,
};
db.sync_delete_window_set(id, &window).unwrap();
db.sync_delete_window_set(other, &window).unwrap();
assert_eq!(db.sync_delete_window(id).unwrap(), Some(window));
let more = DeleteWindow {
deleted: 20,
..window
};
db.sync_delete_window_set(id, &more).unwrap();
assert_eq!(db.sync_delete_window(id).unwrap(), Some(more));
db.sync_folder_set_mode(id, "ondemand").unwrap();
assert_eq!(db.sync_delete_window(id).unwrap(), None);
assert_eq!(db.sync_delete_window(other).unwrap(), Some(window));
db.sync_folder_remove(other).unwrap();
assert_eq!(db.sync_delete_window(other).unwrap(), None);
}
+1
View File
@@ -10,6 +10,7 @@ homepage.workspace = true
description = "The mirror engine's planner and pass model for the Proton Drive Linux client"
[dependencies]
pdfs-sched.workspace = true
pdfs-core.workspace = true
pdfs-drive.workspace = true
pdfs-store.workspace = true
+410
View File
@@ -0,0 +1,410 @@
//! What a pass knows about a path on each side, as a typed fact.
//!
//! A path missing from a walk is not proof that it is gone. The local scan
//! leaves out what it cannot read, the remote walk what would not decrypt or
//! list, and the ignore rules what the user excluded. Before this module each
//! of those was a filter of its own ([`Unscanned`], [`RemoteGaps`],
//! [`IgnoreRules`]), applied at each place that read the walks. Here they
//! answer one question per side, [`Presence`]: the path is there, it is
//! proven absent, it is excluded by rule, or nothing is known of it and why.
//!
//! Only [`Presence::Absent`] may lead to a deletion. A pass classifies a path
//! only when both sides are known ([`Evidence::classifiable`]), and every
//! deletion it plans is checked against the evidence again
//! ([`Evidence::unproven_deletion`]). A deletion the evidence does not
//! support is not made: it is logged, counted in the pass trace and failed,
//! so a regression in the filters keeps files instead of costing them.
use std::collections::HashMap;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use crate::planner::{HasKind, RemoteGaps, Unscanned};
use pdfs_core::syncignore::IgnoreRules;
/// What a pass knows about one path on one side.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Presence {
/// The walk returned it.
Present,
/// The walk read the folder it would be in, completely, and it was not
/// there.
Absent,
/// The ignore rules exclude it, so the walks do not look at it.
Excluded,
/// The walk could not tell.
Unknown(Unknown),
}
/// Why a walk could not tell whether a path is there.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Unknown {
/// Here: the path, or a folder above it, cannot be read.
Unreadable,
/// Here: the path, or a folder above it, vanished while the scan looked
/// at it. The next pass sees it settled.
Vanished,
/// On Drive: the path is listed, but what the pass needs of it could not
/// be read.
Unread,
/// On Drive: the listing of the deepest folder above it named nodes that
/// did not come back, so it may be one of them.
ShortListing,
/// On Drive: the listing of the deepest folder above it failed.
Unlisted,
}
impl Presence {
/// Whether the side is known: there, or proven gone.
pub fn is_known(self) -> bool {
matches!(self, Presence::Present | Presence::Absent)
}
}
/// Which side a deletion acts on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Side {
/// The local copy is deleted, because the path is gone from Drive.
Local,
/// The copy on Drive is trashed, because the path is gone here.
Remote,
}
/// The evidence of one pass: both walks and what each could not read.
pub struct Evidence<'a, L, R> {
pub rules: &'a IgnoreRules,
pub local: &'a HashMap<String, L>,
pub unscanned: &'a Unscanned,
/// `None` for a pass that does not walk Drive, such as the push pass
/// before a switch to on-demand. Every remote path is then unknown.
pub remote: Option<RemoteEvidence<'a, R>>,
}
/// The remote half of [`Evidence`].
pub struct RemoteEvidence<'a, R> {
pub entries: &'a HashMap<String, R>,
pub dirs: &'a HashMap<String, NodeUid>,
pub gaps: &'a RemoteGaps,
}
impl<L: HasKind, R: HasKind> Evidence<'_, L, R> {
/// Whether the ignore rules exclude `rel`. A path neither walk returned
/// has no kind, so it is tested as both: erring towards "excluded" only
/// leaves a path alone, never deletes it.
pub fn excluded(&self, rel: &str) -> bool {
if self.rules.is_empty() {
return false;
}
let kind = self.local.get(rel).map(HasKind::is_dir).or_else(|| {
self.remote
.as_ref()
.and_then(|remote| remote.entries.get(rel))
.map(HasKind::is_dir)
});
match kind {
Some(is_dir) => self.rules.is_ignored(rel, is_dir),
None => self.rules.is_ignored(rel, false) || self.rules.is_ignored(rel, true),
}
}
/// What the local walk says of `rel`.
pub fn local(&self, rel: &str) -> Presence {
if self.excluded(rel) {
return Presence::Excluded;
}
// Not even a path the scan returned is known when a folder above it
// could not be read: a pass leaves the whole subtree alone (B196).
if let Some(why) = self.unscanned.why(rel) {
return Presence::Unknown(why);
}
if self.local.contains_key(rel) {
Presence::Present
} else {
Presence::Absent
}
}
/// What the remote walk says of `rel`.
pub fn remote(&self, rel: &str) -> Presence {
if self.excluded(rel) {
return Presence::Excluded;
}
let Some(remote) = &self.remote else {
return Presence::Unknown(Unknown::Unlisted);
};
if remote.entries.contains_key(rel) {
return Presence::Present;
}
match remote.gaps.why(rel, remote.entries, remote.dirs) {
Some(why) => Presence::Unknown(why),
None => Presence::Absent,
}
}
/// Whether a pass may classify `rel`: neither side excluded, and both
/// known. A path under a folder the local scan could not read is left out
/// even when Drive has it, since a download has nowhere to be written.
pub fn classifiable(&self, rel: &str) -> bool {
self.local(rel).is_known() && self.remote(rel).is_known()
}
/// What the evidence says of the side a deletion of `rel` is based on,
/// when that is not proof of absence. A deletion of the local copy needs
/// `rel` proven gone from Drive, and a trash on Drive needs it proven
/// gone here.
pub fn unproven_deletion(&self, rel: &str, side: Side) -> Option<Presence> {
let basis = match side {
Side::Local => self.remote(rel),
Side::Remote => self.local(rel),
};
(basis != Presence::Absent).then_some(basis)
}
}
#[cfg(test)]
mod tests {
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
use super::*;
fn none() -> IgnoreRules {
IgnoreRules::load(std::path::Path::new("/nonexistent-sync-root"), &[])
}
struct Item(bool);
impl HasKind for Item {
fn is_dir(&self) -> bool {
self.0
}
}
fn map(paths: &[(&str, bool)]) -> HashMap<String, Item> {
paths
.iter()
.map(|(rel, dir)| (rel.to_string(), Item(*dir)))
.collect()
}
fn dirs(paths: &[&str]) -> HashMap<String, NodeUid> {
paths
.iter()
.map(|rel| {
(
rel.to_string(),
NodeUid::new(VolumeId::from("v"), LinkId::from(*rel)),
)
})
.collect()
}
#[test]
fn a_path_missing_from_a_complete_walk_is_absent() {
let rules = none();
let local = map(&[("a.txt", false)]);
let remote = map(&[("a.txt", false), ("b.txt", false)]);
let remote_dirs = dirs(&[""]);
let (unscanned, gaps) = (Unscanned::default(), RemoteGaps::default());
let evidence = Evidence {
rules: &rules,
local: &local,
unscanned: &unscanned,
remote: Some(RemoteEvidence {
entries: &remote,
dirs: &remote_dirs,
gaps: &gaps,
}),
};
assert_eq!(evidence.local("a.txt"), Presence::Present);
assert_eq!(evidence.local("b.txt"), Presence::Absent);
assert_eq!(evidence.remote("c.txt"), Presence::Absent);
assert!(evidence.classifiable("b.txt"));
assert_eq!(evidence.unproven_deletion("b.txt", Side::Remote), None);
assert_eq!(
evidence.unproven_deletion("a.txt", Side::Remote),
Some(Presence::Present)
);
}
#[test]
fn what_a_walk_could_not_read_is_unknown_never_absent() {
let rules = none();
let local = map(&[("locked", true)]);
let mut unscanned = Unscanned::default();
unscanned.unreadable("locked".into(), "permission denied");
unscanned.vanished("tmp".into());
let remote = map(&[("docs", true), ("docs/a.txt", false), ("pics", true)]);
let remote_dirs = dirs(&["", "docs", "pics"]);
let mut gaps = RemoteGaps::default();
gaps.short_listing("docs");
gaps.unlisted("pics");
gaps.unread("odd.bin".into());
let evidence = Evidence {
rules: &rules,
local: &local,
unscanned: &unscanned,
remote: Some(RemoteEvidence {
entries: &remote,
dirs: &remote_dirs,
gaps: &gaps,
}),
};
assert_eq!(
evidence.local("locked"),
Presence::Unknown(Unknown::Unreadable)
);
assert_eq!(
evidence.local("locked/deep/x.txt"),
Presence::Unknown(Unknown::Unreadable)
);
assert_eq!(
evidence.local("tmp/y"),
Presence::Unknown(Unknown::Vanished)
);
assert_eq!(
evidence.remote("docs/b.txt"),
Presence::Unknown(Unknown::ShortListing)
);
assert_eq!(evidence.remote("docs/a.txt"), Presence::Present);
assert_eq!(
evidence.remote("pics/2019/x.jpg"),
Presence::Unknown(Unknown::Unlisted)
);
assert_eq!(
evidence.remote("odd.bin"),
Presence::Unknown(Unknown::Unread)
);
assert_eq!(evidence.remote("top.txt"), Presence::Absent);
assert!(!evidence.classifiable("locked/deep/x.txt"));
assert!(!evidence.classifiable("docs/b.txt"));
assert_eq!(
evidence.unproven_deletion("locked/deep/x.txt", Side::Remote),
Some(Presence::Unknown(Unknown::Unreadable))
);
assert_eq!(
evidence.unproven_deletion("docs/b.txt", Side::Local),
Some(Presence::Unknown(Unknown::ShortListing))
);
}
#[test]
fn an_ignored_path_is_excluded_on_both_sides() {
let rules =
IgnoreRules::with_folder_text(std::path::Path::new("/r"), &[], "*.tmp\nbuild/\n");
let local = map(&[("a.tmp", false), ("build", true)]);
let remote: HashMap<String, Item> = HashMap::new();
let (unscanned, remote_dirs, gaps) =
(Unscanned::default(), dirs(&[""]), RemoteGaps::default());
let evidence = Evidence {
rules: &rules,
local: &local,
unscanned: &unscanned,
remote: Some(RemoteEvidence {
entries: &remote,
dirs: &remote_dirs,
gaps: &gaps,
}),
};
assert_eq!(evidence.local("a.tmp"), Presence::Excluded);
assert_eq!(evidence.remote("a.tmp"), Presence::Excluded);
assert_eq!(evidence.local("build"), Presence::Excluded);
// Neither walk returned it, so it is tested as a folder too.
assert_eq!(evidence.remote("build"), Presence::Excluded);
assert!(!evidence.classifiable("a.tmp"));
assert_eq!(
evidence.unproven_deletion("a.tmp", Side::Remote),
Some(Presence::Excluded)
);
}
/// The paths a pass classifies are the ones the separate filters let
/// through before: the ignore rules on the union of the walks, then
/// `Unscanned::covers` and `RemoteGaps::hides`.
#[test]
fn classifiable_paths_are_the_ones_the_old_filters_kept() {
let rules =
IgnoreRules::with_folder_text(std::path::Path::new("/r"), &[], "*.tmp\ncache/\n");
let local = map(&[
("a.txt", false),
("b.tmp", false),
("cache", true),
("locked", true),
("docs", true),
("docs/new.txt", false),
]);
let remote = map(&[
("a.txt", false),
("docs", true),
("docs/kept.txt", false),
("pics", true),
("remote-only.txt", false),
]);
let baseline: HashMap<String, Item> = map(&[
("a.txt", false),
("gone-here.txt", false),
("docs/lost.txt", false),
("pics/2019/x.jpg", false),
("locked/inner.txt", false),
("old.tmp", false),
("cache", true),
]);
let mut unscanned = Unscanned::default();
unscanned.unreadable("locked".into(), "permission denied");
let remote_dirs = dirs(&["", "docs", "pics"]);
let mut gaps = RemoteGaps::default();
gaps.short_listing("docs");
gaps.unlisted("pics");
let evidence = Evidence {
rules: &rules,
local: &local,
unscanned: &unscanned,
remote: Some(RemoteEvidence {
entries: &remote,
dirs: &remote_dirs,
gaps: &gaps,
}),
};
let mut old = crate::planner::classification_order(&local, &remote, &baseline, &rules);
old.retain(|rel| !unscanned.covers(rel) && !gaps.hides(rel, &remote, &remote_dirs));
let mut new = crate::planner::classification_order(
&local,
&remote,
&baseline,
&IgnoreRules::load(std::path::Path::new("/nonexistent-sync-root"), &[]),
);
new.retain(|rel| evidence.classifiable(rel));
old.sort();
new.sort();
assert_eq!(old, new);
// Left out: ignored paths, everything under the unreadable folder,
// what may hide under the short and the failed listing.
assert_eq!(
old,
[
"a.txt",
"docs",
"docs/kept.txt",
"gone-here.txt",
"pics",
"remote-only.txt"
]
);
}
#[test]
fn a_pass_that_does_not_walk_drive_knows_nothing_there() {
let rules = none();
let local = map(&[]);
let unscanned = Unscanned::default();
let evidence: Evidence<'_, Item, Item> = Evidence {
rules: &rules,
local: &local,
unscanned: &unscanned,
remote: None,
};
assert_eq!(evidence.local("gone.txt"), Presence::Absent);
assert!(!evidence.remote("gone.txt").is_known());
assert!(!evidence.classifiable("gone.txt"));
assert_eq!(evidence.unproven_deletion("gone.txt", Side::Remote), None);
}
}
+4 -1
View File
@@ -16,14 +16,17 @@ use std::time::{Duration, Instant, SystemTime};
use pdfs_core::control::ActivityKind;
use pdfs_core::syncignore::IgnoreRules;
use pdfs_store::db::StoredSyncEntry;
use pdfs_store::db::{DeleteWindow, StoredSyncEntry};
use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{Node, NodeKind};
pub mod evidence;
pub mod local_dirty;
pub mod mirror;
pub mod model;
pub mod naming;
pub mod planner;
pub mod root;
pub mod store;
pub mod trace;
+285
View File
@@ -0,0 +1,285 @@
//! The local dirty set: where a mirror folder changed on disk since a pass
//! last looked, as the filesystem watcher reports it (`docs/SYNC_ENGINE.md`).
//!
//! The watcher marks each path an event names. A pass claims every mark made
//! so far and, once it has applied what it found, retires them. Marks made
//! while it ran are newer than its claim and stay for the next pass.
//!
//! A claim is only as good as the watch behind it. It is *trusted* when the
//! folder's watch has been live since before the last pass claimed: then
//! every change since that pass was reported. A watch that failed, a watcher
//! error, an overflowed queue or a restart breaks that, and the next pass has
//! nothing to trust until a pass claims again with the watch live throughout.
//!
//! For now the set is checked, not used: a pass still walks the whole folder,
//! and counts the changes it finds that a trusted claim did not cover. Once
//! those stay at zero, a trusted claim can stand in for the walk.
use std::collections::{HashMap, HashSet};
use parking_lot::Mutex;
/// The dirty marks of every mirror folder, by folder id.
#[derive(Default)]
pub struct LocalDirty {
inner: Mutex<Dirty>,
}
#[derive(Default)]
struct Dirty {
/// The newest generation, across every folder: of a mark, or of a watch
/// coming up.
generation: u64,
folders: HashMap<i64, Marks>,
}
impl Dirty {
/// The next generation. A watch that comes up, or comes back after an
/// overflow, takes one of its own, so it is always later than the last
/// claim, even when no mark was made in between.
fn tick(&mut self) -> u64 {
self.generation += 1;
self.generation
}
}
#[derive(Default)]
struct Marks {
/// Folders whose direct children changed, with the generation of the
/// newest mark on each.
shallow: HashMap<String, u64>,
/// Paths that changed in full, with whatever is below them: a file
/// written, or a folder that appeared with its contents.
deep: HashMap<String, u64>,
/// The generation from which the watch has reported every change, or
/// `None` while the folder is not watched.
live_since: Option<u64>,
/// The generation the last pass claimed through.
claimed: Option<u64>,
}
/// The marks a pass claimed: what the watcher reported up to `through`.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Claim {
pub through: u64,
/// Whether the watch was live since before the last claim, so the marks
/// cover every change since.
pub trusted: bool,
shallow: HashSet<String>,
deep: HashSet<String>,
}
impl Claim {
/// Whether a change to `rel` was reported: its folder's children
/// changed, or it or a folder above it changed in full.
pub fn covers(&self, rel: &str) -> bool {
if self.shallow.contains(parent(rel)) {
return true;
}
let mut at = rel;
loop {
if self.deep.contains(at) {
return true;
}
if at.is_empty() {
return false;
}
at = parent(at);
}
}
/// How many marks the claim holds.
pub fn len(&self) -> usize {
self.shallow.len() + self.deep.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl LocalDirty {
/// The watch on `folder` is in place: every change from now on is
/// reported.
pub fn watched(&self, folder: i64) {
let mut d = self.inner.lock();
let now = d.tick();
let marks = d.folders.entry(folder).or_default();
if marks.live_since.is_none() {
marks.live_since = Some(now);
}
}
/// The watch on `folder` is gone, or never came up.
pub fn unwatched(&self, folder: i64) {
if let Some(marks) = self.inner.lock().folders.get_mut(&folder) {
marks.live_since = None;
}
}
/// The watcher lost events it cannot name: an error, or an overflowed
/// queue. No folder's marks can be trusted until it is watched again.
pub fn lost(&self) {
for marks in self.inner.lock().folders.values_mut() {
marks.live_since = None;
}
}
/// The watcher's queue overflowed: the changes in it are lost, but the
/// watches stand, so every folder still watched reports changes again
/// from now on.
pub fn overflowed(&self) {
let mut d = self.inner.lock();
let now = d.tick();
for marks in d.folders.values_mut() {
if marks.live_since.is_some() {
marks.live_since = Some(now);
}
}
}
/// Note a change the watcher reported at `rel` in `folder`.
pub fn mark(&self, folder: i64, rel: &str) {
let mut d = self.inner.lock();
let generation = d.tick();
let marks = d.folders.entry(folder).or_default();
marks.deep.insert(rel.to_string(), generation);
marks.shallow.insert(parent(rel).to_string(), generation);
}
/// Claim every mark of `folder` made so far, for a pass about to look.
pub fn claim(&self, folder: i64) -> Claim {
let mut d = self.inner.lock();
let through = d.generation;
let marks = d.folders.entry(folder).or_default();
Claim {
through,
trusted: matches!(
(marks.live_since, marks.claimed),
(Some(live), Some(claimed)) if live <= claimed
),
shallow: marks.shallow.keys().cloned().collect(),
deep: marks.deep.keys().cloned().collect(),
}
}
/// A pass that claimed `claim` has looked. With `applied`, it applied
/// everything it found, and the marks it claimed are retired; without,
/// they stay for the next pass to claim again. Either way the next claim
/// is measured from this one.
pub fn looked(&self, folder: i64, claim: &Claim, applied: bool) {
let mut d = self.inner.lock();
let marks = d.folders.entry(folder).or_default();
if applied {
marks.shallow.retain(|_, g| *g > claim.through);
marks.deep.retain(|_, g| *g > claim.through);
}
marks.claimed = Some(claim.through);
}
/// Forget a folder that is no longer synced.
pub fn forget(&self, folder: i64) {
self.inner.lock().folders.remove(&folder);
}
}
/// The folder `rel` is in; the root's is the root.
fn parent(rel: &str) -> &str {
rel.rfind('/').map_or("", |i| &rel[..i])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_claim_covers_a_change_and_its_siblings_folder_but_not_cousins() {
let dirty = LocalDirty::default();
dirty.mark(1, "docs/a.txt");
let claim = dirty.claim(1);
assert!(claim.covers("docs/a.txt"));
// A file made or deleted next to it shows in the same folder.
assert!(claim.covers("docs/b.txt"));
assert!(!claim.covers("other/c.txt"));
assert!(!claim.covers("docs/sub/d.txt"));
assert!(!claim.covers("top.txt"));
}
#[test]
fn a_folder_moved_in_covers_everything_below_it() {
let dirty = LocalDirty::default();
dirty.mark(1, "photos/2024");
let claim = dirty.claim(1);
assert!(claim.covers("photos/2024/jan/1.jpg"));
assert!(claim.covers("photos/other"));
assert!(!claim.covers("music/x.mp3"));
}
#[test]
fn a_claim_is_trusted_only_with_the_watch_live_since_the_last_one() {
let dirty = LocalDirty::default();
dirty.watched(1);
// The first pass after the watch came up has nothing to measure from.
let first = dirty.claim(1);
assert!(!first.trusted);
dirty.looked(1, &first, true);
assert!(dirty.claim(1).trusted);
// Events lost: the next claim is not trusted, nor the one after the
// watch comes back, until a pass has claimed with it live.
dirty.lost();
let lost = dirty.claim(1);
assert!(!lost.trusted);
dirty.looked(1, &lost, true);
dirty.watched(1);
dirty.mark(1, "a.txt");
let back = dirty.claim(1);
assert!(!back.trusted, "watched again after the last claim");
dirty.looked(1, &back, true);
assert!(dirty.claim(1).trusted);
}
#[test]
fn marks_made_during_a_pass_stay_for_the_next_one() {
let dirty = LocalDirty::default();
dirty.mark(1, "a.txt");
let claim = dirty.claim(1);
dirty.mark(1, "b/c.txt");
dirty.looked(1, &claim, true);
let next = dirty.claim(1);
assert!(!next.covers("a.txt"));
assert!(next.covers("b/c.txt"));
}
#[test]
fn a_pass_that_did_not_apply_everything_keeps_its_marks() {
let dirty = LocalDirty::default();
dirty.mark(1, "a.txt");
let claim = dirty.claim(1);
dirty.looked(1, &claim, false);
assert!(dirty.claim(1).covers("a.txt"));
}
#[test]
fn an_overflow_breaks_trust_until_a_pass_claims_again() {
let dirty = LocalDirty::default();
dirty.watched(1);
let first = dirty.claim(1);
dirty.looked(1, &first, true);
dirty.mark(1, "a.txt");
dirty.overflowed();
let lost = dirty.claim(1);
assert!(!lost.trusted);
dirty.looked(1, &lost, true);
assert!(dirty.claim(1).trusted);
}
#[test]
fn folders_keep_their_own_marks() {
let dirty = LocalDirty::default();
dirty.mark(1, "a.txt");
assert!(dirty.claim(2).is_empty());
dirty.forget(1);
assert!(dirty.claim(1).is_empty());
}
}
+306 -6
View File
@@ -38,13 +38,17 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
use sha1::{Digest as _, Sha1};
use tracing::{debug, info, warn};
use crate::evidence::{Evidence, RemoteEvidence, Side};
use crate::local_dirty::Claim;
use crate::planner::HasKind;
use crate::root::{RootInput, Suspension};
use pdfs_core::batch;
use pdfs_core::control::{ActivityKind, TransferDirection};
use pdfs_core::syncignore::IgnoreRules;
use pdfs_core::timestamp::now_secs;
use pdfs_core::transfers::{CountingWriter, OwnedCountingReader};
use pdfs_drive::parse_uid;
use pdfs_store::db::{SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
use pdfs_store::db::{DeleteWindow, SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
mod apply;
mod engine;
@@ -78,10 +82,10 @@ use planner::conflict_path_as;
#[cfg(test)]
use planner::filter_baseline;
use planner::{
FilePlan, RemoteGaps, Unscanned, classification_order, guard_local_wipe, guard_remote_wipe,
join_rel, local_deletions, parent_rel, plan_file, rel_to_path, remote_sig,
remote_subtree_changed, revision_confirms_baseline, revision_moved, tracked_baseline,
unchanged_remote_size,
FilePlan, RemoteGaps, Unscanned, classification_order, delete_window, guard_delete_window,
guard_local_wipe, guard_remote_wipe, join_rel, local_deletions, parent_rel, plan_file,
planned_deletions, rel_to_path, remote_sig, remote_subtree_changed, revision_confirms_baseline,
revision_moved, tracked_baseline, unchanged_remote_size,
};
use trace::{Call, Count, Phase};
@@ -98,15 +102,21 @@ impl Syncer {
pub fn reconcile_folder(&self, folder: &StoredSyncFolder) {
// A paused folder skips the settle too: a queued switch to on-demand
// evicts the local tree, which is only safe after a pass uploaded it.
self.roots.begin(folder.id, folder.last_sync != 0);
if self.sync_folder_paused(folder.id) {
debug!(id = folder.id, "sync: folder paused, skipping reconcile");
self.roots
.input(folder.id, RootInput::Suspended(Suspension::Paused));
return;
}
self.roots.input(folder.id, RootInput::Resumed);
// `ondemand` folders are live FUSE mounts, not mirrored, so there is nothing
// to reconcile — but one may still carry a queued switch back to `mirror`,
// so the settle below is not skipped with it.
if folder.mode == "mirror" {
self.reconcile_pass(folder);
} else {
self.roots.input(folder.id, RootInput::HandedOff);
}
self.settle_pending_mode(folder.id);
}
@@ -147,8 +157,18 @@ impl Syncer {
let _ = self
.store
.sync_folder_set_state(folder.id, "error", now_secs());
self.roots
.input(folder.id, RootInput::Suspended(Suspension::RootMissing));
return;
}
self.roots.input(
folder.id,
if push_only {
RootInput::HandoffQueued
} else {
RootInput::Mirrored
},
);
let _ = self
.store
@@ -209,6 +229,9 @@ impl Syncer {
let progress = self.progress.lock().get(&folder.id).cloned();
self.progress_end(folder.id);
self.log_trace(folder, &result, started.elapsed());
if result.is_ok() && !push_only {
self.roots.input(folder.id, RootInput::Covered);
}
match result {
Ok(outcome) => {
// A folder only reaches `idle` when every path applied cleanly —
@@ -352,6 +375,35 @@ impl Syncer {
}
}
/// Whether the pass must not make a deletion it planned: the evidence does
/// not prove the path gone on the side the deletion is based on. Such a
/// deletion is logged, counted in the trace and as a failed step, and left
/// out; its baseline row stays, so the next pass plans it again.
///
/// The filters before the plan keep such a path out of it, so this
/// should never fire. When it does, a file stays on both sides rather than
/// going on the strength of a walk that never saw it.
fn refuses_deletion<L: HasKind, R: HasKind>(
&self,
evidence: &Evidence<'_, L, R>,
rel: &str,
side: Side,
outcome: &mut Outcome,
) -> bool {
let Some(basis) = evidence.unproven_deletion(rel, side) else {
return false;
};
warn!(
rel,
?side,
?basis,
"sync: not deleting a path whose absence is not proven"
);
self.trace_count(Count::UnprovenDeletions, 1);
outcome.failed(&format!("{rel}: not deleted, its absence is not proven"));
true
}
/// Add `took` to a stage of the running pass's trace.
fn trace_phase(&self, phase: Phase, took: Duration) {
self.engine.trace(|t| t.phase(phase, took));
@@ -474,6 +526,15 @@ impl Syncer {
self.trace_count(Count::LocalEntries, local.len());
// See `push_pass`: the guard must not count excluded paths as lost.
guard_local_wipe(&tracked_baseline(&baseline, rules, &unscanned), &local)?;
// What the watcher reported since the last pass, checked against what
// the walk found (`local_dirty`).
let claim = self.local_dirty.claim(folder_id);
self.check_local_dirty(
folder_id,
&claim,
&tracked_baseline(&baseline, rules, &unscanned),
&local,
);
let mut remote: HashMap<String, RemoteItem> = HashMap::new();
let mut remote_dirs: HashMap<String, NodeUid> = HashMap::new();
@@ -501,7 +562,19 @@ impl Syncer {
// ignored one, and a remote path under it has nowhere to be written.
// The same holds for a path the remote walk could not read: missing
// from it, it would read as deleted on Drive (B212).
order.retain(|rel| !unscanned.covers(rel) && !gaps.hides(rel, &remote, &remote_dirs));
// Only a path both walks know about is classified (`evidence`).
order.retain(|rel| {
pass_evidence(rules, &local, &unscanned, &remote, &remote_dirs, &gaps).classifiable(rel)
});
// The deletions this pass plans, added to those the folder made
// lately: a tree lost a little at a time passes the guards above one
// pass at a time.
let window = self.claim_deletions(
folder_id,
tracked_baseline(&baseline, rules, &unscanned).len(),
planned_deletions(&order, &local, &remote, &baseline),
)?;
let mut unscanned_report = unscanned.report();
unscanned_report.extend(gaps.report());
@@ -587,6 +660,14 @@ impl Syncer {
}
(true, false) => {
// In baseline, gone remotely → the remote side deleted it.
if self.refuses_deletion(
&pass_evidence(rules, &local, &unscanned, &remote, &remote_dirs, &gaps),
rel,
Side::Local,
&mut outcome,
) {
continue;
}
delete_local_dirs.push(rel.clone());
}
(false, true) if !in_base => {
@@ -601,6 +682,14 @@ impl Syncer {
}
(false, true) => {
// In baseline, gone locally → the local side deleted it.
if self.refuses_deletion(
&pass_evidence(rules, &local, &unscanned, &remote, &remote_dirs, &gaps),
rel,
Side::Remote,
&mut outcome,
) {
continue;
}
delete_remote_dirs.push((rel.clone(), remote[rel].uid.clone()));
}
(false, false) => {
@@ -691,6 +780,14 @@ impl Syncer {
}
},
FilePlan::DeleteLocal => {
if self.refuses_deletion(
&pass_evidence(rules, &local, &unscanned, &remote, &remote_dirs, &gaps),
rel,
Side::Local,
&mut outcome,
) {
continue;
}
let path = local_root.join(rel_to_path(rel));
// The plan comes from a scan taken before the remote walk,
// which can take minutes. An edit saved since then is not
@@ -717,6 +814,14 @@ impl Syncer {
outcome.deleted += 1;
}
FilePlan::DeleteRemote => {
if self.refuses_deletion(
&pass_evidence(rules, &local, &unscanned, &remote, &remote_dirs, &gaps),
rel,
Side::Remote,
&mut outcome,
) {
continue;
}
let remote = r.expect("remote deletion requires a remote file");
let step = Instant::now();
let trashed = self
@@ -852,13 +957,155 @@ impl Syncer {
outcome.deleted += 1;
}
self.trace_phase(Phase::Cleanup, cleanup.elapsed());
self.settle_deletions(folder_id, window, outcome.deleted);
// A change the pass could not apply stays dirty for the next one.
self.local_dirty.looked(
folder_id,
&claim,
outcome.errors == 0 && outcome.deferred == 0,
);
Ok(outcome)
}
/// Count the claimed marks of the local dirty set, and, when the claim is
/// trusted, the local changes the walk found that it did not cover. Acts
/// on nothing: the walk is still what the pass plans from.
fn check_local_dirty(
&self,
folder_id: i64,
claim: &Claim,
tracked: &HashMap<String, &StoredSyncEntry>,
local: &HashMap<String, LocalItem>,
) {
self.trace_count(Count::LocalDirty, claim.len());
if !claim.trusted {
self.trace_count(Count::LocalUntrusted, 1);
return;
}
let missed = missed_local(claim, tracked, local);
if missed.is_empty() {
return;
}
for rel in &missed {
debug!(
id = folder_id,
rel, "sync: a local change the watcher did not report"
);
}
info!(
id = folder_id,
missed = missed.len(),
first = %missed[0],
"sync: the local dirty set missed changes the walk found"
);
self.trace_count(Count::MissedLocal, missed.len());
}
/// Open or continue the folder's deletion window for a pass that plans
/// `planned` deletions, and refuse the pass when they would make the
/// window a wipe ([`guard_delete_window`]). `tracked` is how many paths
/// the folder tracks now.
///
/// The window is recorded before anything is deleted, as if every planned
/// deletion will succeed: a pass cut short then leaves the window counting
/// at least what it deleted. Returns the window as it was before this
/// pass, for [`settle_deletions`](Self::settle_deletions).
fn claim_deletions(
&self,
folder_id: i64,
tracked: usize,
planned: usize,
) -> Result<Option<DeleteWindow>, String> {
let open = self
.store
.sync_delete_window(folder_id)
.map_err(|e| format!("load the deletion window: {e:?}"))?;
let window = delete_window(open, tracked, now_secs());
guard_delete_window(&window, planned)?;
if planned == 0 {
return Ok(None);
}
let claimed = DeleteWindow {
deleted: window.deleted + planned as u64,
..window
};
self.store
.sync_delete_window_set(folder_id, &claimed)
.map_err(|e| format!("record the deletion window: {e:?}"))?;
Ok(Some(window))
}
/// Count what a finished pass actually deleted in the window
/// [`claim_deletions`](Self::claim_deletions) opened, in place of what it
/// planned to: a deletion that failed is tried again by the next pass and
/// would otherwise count twice.
fn settle_deletions(&self, folder_id: i64, window: Option<DeleteWindow>, deleted: usize) {
let Some(window) = window else {
return;
};
let settled = DeleteWindow {
deleted: window.deleted + deleted as u64,
..window
};
if let Err(e) = self.store.sync_delete_window_set(folder_id, &settled) {
debug!(id = folder_id, error = ?e, "sync: cannot settle the deletion window");
}
}
}
/// The local changes the walk found since the baseline that `claim` does not
/// cover: paths new on disk, files whose size or mtime moved, and tracked
/// paths gone. Sorted, for a stable log.
fn missed_local(
claim: &Claim,
tracked: &HashMap<String, &StoredSyncEntry>,
local: &HashMap<String, LocalItem>,
) -> Vec<String> {
let changed = local.iter().filter_map(|(rel, item)| {
let moved = match tracked.get(rel) {
None => true,
Some(base) => {
!item.is_dir && (base.local_mtime != item.mtime || base.local_size != item.size)
}
};
moved.then_some(rel)
});
let gone = tracked.keys().filter(|rel| !local.contains_key(*rel));
let mut missed: Vec<String> = changed
.chain(gone)
.filter(|rel| !claim.covers(rel))
.cloned()
.collect();
missed.sort();
missed
}
/// A [`Read`] that hashes what an upload reads through it, so the digest Drive
/// reports afterwards can be compared with what was sent.
/// The evidence of a mirror pass, built where it is asked so it borrows the
/// walks only for the question: `remote_dirs` gains the folders the pass
/// creates between questions.
fn pass_evidence<'a>(
rules: &'a IgnoreRules,
local: &'a HashMap<String, LocalItem>,
unscanned: &'a Unscanned,
remote: &'a HashMap<String, RemoteItem>,
remote_dirs: &'a HashMap<String, NodeUid>,
gaps: &'a RemoteGaps,
) -> Evidence<'a, LocalItem, RemoteItem> {
Evidence {
rules,
local,
unscanned,
remote: Some(RemoteEvidence {
entries: remote,
dirs: remote_dirs,
gaps,
}),
}
}
struct Sha1Tap<R> {
inner: R,
hasher: Arc<Mutex<Sha1>>,
@@ -1661,6 +1908,59 @@ mod tests {
)])
}
/// A walk's changes that a claim of the local dirty set did not cover:
/// one next to a reported change is covered, the rest are missed.
#[test]
fn missed_local_lists_the_changes_a_claim_does_not_cover() {
use crate::local_dirty::LocalDirty;
let row = |rel: &str, mtime: i64| StoredSyncEntry {
rel_path: rel.to_string(),
remote_uid: Some("v~l".into()),
local_mtime: mtime,
local_size: 1,
local_mtime_ns: None,
remote_rev: None,
remote_hash: None,
remote_revision_id: None,
};
let rows: HashMap<String, StoredSyncEntry> = [
("docs", 0),
("docs/a.txt", 1),
("same.txt", 1),
("top.txt", 1),
("old/x.txt", 1),
]
.into_iter()
.map(|(rel, mtime)| (rel.to_string(), row(rel, mtime)))
.collect();
let tracked: HashMap<String, &StoredSyncEntry> =
rows.iter().map(|(k, v)| (k.clone(), v)).collect();
let item = |is_dir: bool, mtime: i64| LocalItem {
mtime_ns: None,
is_dir,
mtime,
size: 1,
open_for_write: false,
};
let local: HashMap<String, LocalItem> = [
("docs", item(true, 9)),
("docs/a.txt", item(false, 2)),
("docs/new.txt", item(false, 1)),
("same.txt", item(false, 1)),
("top.txt", item(false, 2)),
]
.into_iter()
.map(|(rel, item)| (rel.to_string(), item))
.collect();
let dirty = LocalDirty::default();
dirty.mark(1, "docs/a.txt");
let claim = dirty.claim(1);
assert_eq!(
missed_local(&claim, &tracked, &local),
vec!["old/x.txt".to_string(), "top.txt".to_string()]
);
}
#[test]
fn an_unchanged_mtime_reuses_the_recorded_size() {
// The whole point: this file's node key never gets unlocked.
+11 -5
View File
@@ -41,8 +41,8 @@ impl Syncer {
.map_err(|e| format!("baseline dir {rel}: {e:?}"))
}
/// Run a batch of queued [`Pending`] ops concurrently (bounded by
/// [`SYNC_CONCURRENCY`]) and fold their results back into the reconcile's
/// Run a batch of queued [`Pending`] ops concurrently, each once the
/// engine's admission lets it start, and fold their results back into the reconcile's
/// shared state on the engine thread: created folders are registered in
/// `remote_dirs` (so deeper paths resolve their parent), and what each op did
/// is tallied into `outcome`. Driven by `block_on` from the (non-runtime) sync
@@ -67,14 +67,20 @@ impl Syncer {
let core = self.clone();
let root = local_root.to_path_buf();
let results = self.rt.block_on(async move {
let sem = Arc::new(tokio::sync::Semaphore::new(SYNC_CONCURRENCY));
let mut set = tokio::task::JoinSet::new();
for op in batch {
let core = core.clone();
let sem = sem.clone();
let root = root.clone();
set.spawn(async move {
let _permit = sem.acquire_owned().await.expect("semaphore not closed");
let asked = Instant::now();
let _permit = core
.admission
.admit(pdfs_sched::Step {
class: pdfs_sched::Class::Mirror,
root: folder_id,
})
.await;
core.trace_call(Call::Admission, asked.elapsed());
// An op still waiting for its turn when the stop comes is
// not started; the ones already sending finish.
if core.shutdown.is_stopping() {
+48 -3
View File
@@ -10,6 +10,8 @@ use std::collections::BTreeMap;
use super::trace::PassTrace;
use super::*;
use crate::local_dirty::LocalDirty;
use crate::root::{Doubt, RootInput};
/// How long the watcher must go quiet before a burst counts as finished.
///
@@ -30,7 +32,7 @@ const POLL_INTERVAL: Duration = Duration::from_secs(120);
/// How many uploads/downloads/folder-creations a reconcile runs at once. The
/// per-item work is a network round-trip, so a folder with thousands of files is
/// unusable done one-at-a-time; this bounds concurrency like the bulk-upload
/// engine does.
/// engine does. The daemon's admission (`SyncParts::admission`) enforces it.
pub const SYNC_CONCURRENCY: usize = 8;
/// How long after a failed watch the engine tries the watches again. Each try
/// walks the folder's whole tree, so not on every burst.
@@ -246,21 +248,33 @@ pub fn run(core: Syncer, rx: Receiver<SyncMsg>) {
let tx_events = core.tx.clone();
let watched_events = watched.clone();
let dirty = core.local_dirty.clone();
let roots = core.roots.clone();
let handler = move |res: notify::Result<notify::Event>| {
let event = match res {
Ok(event) => event,
// Running out of inotify watches for a new subfolder, say: that
// subfolder's changes are then found by the poll only (B262).
// Nothing says which, so no folder's dirty set is whole now.
Err(e) => {
warn!(error = %e, "sync: filesystem watcher error");
dirty.lost();
roots.input_all(RootInput::Doubted(Doubt::WatchLost));
return;
}
};
if event.need_rescan() {
dirty.overflowed();
roots.input_all(RootInput::Doubted(Doubt::Overflow));
}
// Ignore pure metadata/access noise; content changes are what matter.
if matches!(event.kind, notify::EventKind::Access(_)) {
return;
}
let msg = event_target(&watched_events.lock(), &event.paths);
let watched = watched_events.lock();
mark_dirty(&dirty, &watched, &event.paths);
let msg = event_target(&watched, &event.paths);
drop(watched);
let _ = tx_events.send(msg);
};
// The local walk skips symlinks, so following them here would only watch
@@ -513,6 +527,28 @@ pub(super) fn event_target(watched: &[(PathBuf, i64)], paths: &[PathBuf]) -> Syn
}
}
/// Mark each of `paths` in the local dirty set of the folder it is in.
pub(super) fn mark_dirty(dirty: &LocalDirty, watched: &[(PathBuf, i64)], paths: &[PathBuf]) {
for path in paths {
let Some((root, id)) = watched
.iter()
.filter(|(root, _)| path.starts_with(root))
.max_by_key(|(root, _)| root.components().count())
else {
continue;
};
let Ok(rel) = path.strip_prefix(root) else {
continue;
};
// The walk leaves out a name that is not UTF-8, so there is nothing
// to mark for one.
let parts: Option<Vec<&str>> = rel.components().map(|c| c.as_os_str().to_str()).collect();
if let Some(parts) = parts {
dirty.mark(*id, &parts.join("/"));
}
}
}
/// Bring the filesystem watches in line with the current mirror-folder set:
/// watch newly-added folders, drop removed ones. Returns whether a folder is
/// left unwatched because its watch failed.
@@ -537,9 +573,14 @@ fn rewatch(
}
};
let mut have = watched.lock().clone();
let before = have.clone();
// Drop watches no longer wanted.
for path in keep_wanted(&mut have, &want) {
let _ = watcher.unwatch(&path);
if let Some((_, id)) = before.iter().find(|(p, _)| *p == path) {
core.local_dirty.forget(*id);
core.roots.forget(*id);
}
}
// Add newly wanted watches.
let mut failed = false;
@@ -548,8 +589,12 @@ fn rewatch(
continue;
}
match watcher.watch(path, RecursiveMode::Recursive) {
Ok(()) => have.push((path.clone(), *id)),
Ok(()) => {
have.push((path.clone(), *id));
core.local_dirty.watched(*id);
}
Err(e) => {
core.local_dirty.unwatched(*id);
// A recursive watch that fails partway keeps the watches it had
// added. Their events would match no folder and run a pass over
// every one, and they hold watches the next folder needs (B262).
+8
View File
@@ -86,6 +86,14 @@ pub struct SyncParts {
/// first read. A pass trusts the feed's dirty folders only while it is
/// being read.
pub events_read_at: Arc<AtomicI64>,
/// Where each mirror folder changed on disk since a pass last looked,
/// as the filesystem watcher reports it.
pub local_dirty: Arc<crate::local_dirty::LocalDirty>,
/// What each mirror folder's sync knows about its coverage (`root`).
pub roots: Arc<crate::root::Roots>,
/// When each step of a pass may start: its uploads, downloads and folder
/// creations.
pub admission: Arc<dyn pdfs_sched::Admission>,
}
impl SyncParts {
+10
View File
@@ -308,6 +308,16 @@ impl Syncer {
}
return Ok(outcome);
}
let evidence: Evidence<'_, LocalItem, RemoteItem> = Evidence {
rules,
local: &local,
unscanned: &unscanned,
remote: None,
};
let deletions: Vec<String> = deletions
.into_iter()
.filter(|rel| !self.refuses_deletion(&evidence, rel, Side::Remote, &mut outcome))
.collect();
let mut trashed: Vec<String> = Vec::new();
for rel in &deletions {
if trashed
+251 -14
View File
@@ -102,7 +102,8 @@ pub fn filter_baseline<'a, B>(
/// stopping every other file in the tree from syncing (B196).
#[derive(Default)]
pub struct Unscanned {
covered: HashSet<String>,
/// Each left-out path, with why it was left out.
covered: HashMap<String, crate::evidence::Unknown>,
/// The subset worth telling the user about, with why: an entry that only
/// vanished mid-scan is not, since the next pass sees it settled.
unreadable: Vec<String>,
@@ -111,29 +112,37 @@ pub struct Unscanned {
impl Unscanned {
/// Leave out `rel`, which vanished while the scan looked at it.
pub fn vanished(&mut self, rel: String) {
self.covered.insert(rel);
// An unreadable path stays unreadable: that is the reason the user
// is told about.
self.covered
.entry(rel)
.or_insert(crate::evidence::Unknown::Vanished);
}
/// Leave out `rel`, which cannot be read for `reason`.
pub fn unreadable(&mut self, rel: String, reason: &str) {
self.unreadable.push(format!("{rel} ({reason})"));
self.covered.insert(rel);
self.covered
.insert(rel, crate::evidence::Unknown::Unreadable);
}
/// Whether `rel` is a left-out path or lies under one.
pub fn covers(&self, rel: &str) -> bool {
self.why(rel).is_some()
}
/// Why `rel` was left out, when it is a left-out path or lies under one.
/// The nearest left-out path above it decides.
pub fn why(&self, rel: &str) -> Option<crate::evidence::Unknown> {
if self.covered.is_empty() {
return false;
return None;
}
let mut at = rel;
loop {
if self.covered.contains(at) {
return true;
}
match at.rfind('/') {
Some(i) => at = &at[..i],
None => return false,
if let Some(why) = self.covered.get(at) {
return Some(*why);
}
at = &at[..at.rfind('/')?];
}
}
@@ -250,6 +259,84 @@ pub fn guard_remote_wipe<B, R>(
Ok(())
}
/// How long the deletions a folder makes add up in one window, before a
/// new window starts from the folder as it then is.
pub const DELETE_WINDOW_SECS: i64 = 24 * 60 * 60;
/// The window a pass's deletions count in: the one `open`, or a new one from
/// `now` when none is open or it has run out. `tracked` is how many paths the
/// folder tracks now.
///
/// The reference grows with what is added during the window, so a folder that
/// gains files and then loses them is measured against what it held at its
/// largest. It never shrinks: a tree lost a little at a time is measured
/// against the tree it was, which is the point.
pub fn delete_window(open: Option<DeleteWindow>, tracked: usize, now: i64) -> DeleteWindow {
let tracked = tracked as u64;
match open {
Some(w) if (w.started_at..w.started_at + DELETE_WINDOW_SECS).contains(&now) => {
DeleteWindow {
reference: w.reference.max(tracked + w.deleted),
..w
}
}
_ => DeleteWindow {
started_at: now,
reference: tracked,
deleted: 0,
},
}
}
/// Refuse a pass whose `planned` deletions, added to those the folder made
/// since its `window` began, would make the window a wipe
/// ([`looks_like_a_wipe`]).
///
/// The per-pass guards see one pass. A tree lost a little at a time, by a
/// failing disk or a script, passes each of them in turn, and the passes
/// between delete the rest of the tree in batches (`docs/SYNC_ENGINE.md`).
/// Measured against the whole folder, a user emptying one large subfolder of
/// a healthy tree still passes.
pub fn guard_delete_window(window: &DeleteWindow, planned: usize) -> Result<(), String> {
let deleted = window.deleted.saturating_add(planned as u64);
if planned > 0 && looks_like_a_wipe(deleted as usize, window.reference as usize) {
return Err(format!(
"{deleted} of {} synced paths would be deleted within a day; refusing to \
delete more. If deleted on purpose, remove the folder from sync; to \
upload them again, sync the folder from scratch.",
window.reference
));
}
Ok(())
}
/// How many of `order` a mirror pass will delete, on either side: the files
/// [`plan_file`] deletes, and the folders gone from one side that the
/// baseline still has.
pub fn planned_deletions(
order: &[String],
local: &HashMap<String, LocalItem>,
remote: &HashMap<String, RemoteItem>,
baseline: &HashMap<String, StoredSyncEntry>,
) -> usize {
order
.iter()
.filter(|rel| {
let (l, r) = (local.get(*rel), remote.get(*rel));
let in_base = baseline.get(*rel);
// As the pass tells a folder: a folder gone from both sides only
// loses its baseline row.
if l.map(|x| x.is_dir).or(r.map(|x| x.is_dir)).unwrap_or(false) {
return in_base.is_some() && l.is_some() != r.is_some();
}
matches!(
plan_file(l, r, in_base),
FilePlan::DeleteLocal | FilePlan::DeleteRemote
)
})
.count()
}
/// What a remote walk saw but could not read: a node the SDK left out because
/// it would not decrypt, or a file whose size could not be read.
///
@@ -305,21 +392,37 @@ impl RemoteGaps {
remote: &HashMap<String, R>,
remote_dirs: &HashMap<String, NodeUid>,
) -> bool {
self.why(rel, remote, remote_dirs).is_some()
}
/// Why `rel` may be missing from `remote` only because the walk could not
/// read it, or `None` when its absence is real. A path the walk returned
/// is never hidden.
pub fn why<R>(
&self,
rel: &str,
remote: &HashMap<String, R>,
remote_dirs: &HashMap<String, NodeUid>,
) -> Option<crate::evidence::Unknown> {
use crate::evidence::Unknown;
if self.is_empty() || remote.contains_key(rel) {
return false;
return None;
}
if self.unread.contains(rel) {
return true;
return Some(Unknown::Unread);
}
// The deepest folder the walk did list decides: under a short listing,
// anything not returned may be one of the nodes it could not read.
let mut at = parent_rel(rel);
loop {
if remote_dirs.contains_key(at) {
return self.short.contains(at) || self.unlisted.contains(at);
if self.unlisted.contains(at) {
return Some(Unknown::Unlisted);
}
return self.short.contains(at).then_some(Unknown::ShortListing);
}
if at.is_empty() {
return false;
return None;
}
at = parent_rel(at);
}
@@ -1019,3 +1122,137 @@ mod file_plan_tests {
assert_eq!(remote_subtree_changed("x", &remote_tree, &base), None);
}
}
#[cfg(test)]
mod delete_window_tests {
use super::*;
const NOW: i64 = 1_800_000_000;
fn window(started_at: i64, reference: u64, deleted: u64) -> DeleteWindow {
DeleteWindow {
started_at,
reference,
deleted,
}
}
#[test]
fn a_window_opens_from_the_folder_as_it_is_and_runs_out_after_a_day() {
assert_eq!(delete_window(None, 100, NOW), window(NOW, 100, 0));
let open = window(NOW, 100, 30);
assert_eq!(delete_window(Some(open), 70, NOW + 60), open);
let later = NOW + DELETE_WINDOW_SECS;
assert_eq!(delete_window(Some(open), 70, later), window(later, 70, 0));
// A clock that went back does not keep a window open for ever.
assert_eq!(
delete_window(Some(open), 70, NOW - 1),
window(NOW - 1, 70, 0)
);
}
#[test]
fn what_a_folder_gains_in_a_window_raises_its_reference() {
// 30 deleted and 50 added since: the folder has held 150 paths.
let open = window(NOW, 100, 30);
assert_eq!(delete_window(Some(open), 120, NOW + 1).reference, 150);
}
/// The case the per-pass guard cannot see: a tree lost ten paths a pass.
/// Each pass alone deletes a small share of what is left, until the very
/// last; counted together the window stops them at nine tenths.
#[test]
fn a_tree_lost_a_little_each_pass_is_stopped_at_nine_tenths() {
let mut open = None;
let mut tracked = 100usize;
let mut passes = 0;
loop {
let w = delete_window(open, tracked, NOW + passes);
if guard_delete_window(&w, 10).is_err() {
break;
}
assert!(
!looks_like_a_wipe(10, tracked),
"the per-pass guard let it through"
);
open = Some(DeleteWindow {
deleted: w.deleted + 10,
..w
});
tracked -= 10;
passes += 1;
}
assert_eq!(
passes, 8,
"80 deleted, the pass that makes it 90 is refused"
);
}
#[test]
fn emptying_one_large_subfolder_of_a_healthy_tree_passes() {
let w = delete_window(None, 1000, NOW);
assert!(guard_delete_window(&w, 600).is_ok());
let w = window(NOW, 1000, 600);
assert!(guard_delete_window(&w, 250).is_ok());
}
#[test]
fn a_pass_with_nothing_to_delete_is_never_refused() {
assert!(guard_delete_window(&window(NOW, 100, 95), 0).is_ok());
assert!(guard_delete_window(&window(NOW, 100, 95), 1).is_err());
}
#[test]
fn planned_deletions_counts_both_sides_and_folders() {
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
let item = |is_dir| LocalItem {
mtime_ns: None,
is_dir,
mtime: 1,
size: 1,
open_for_write: false,
};
let node = |is_dir| RemoteItem {
uid: NodeUid::new(VolumeId::from("v"), LinkId::from("l")),
is_dir,
mtime: 1,
size: 1,
revision: None,
sha1: None,
};
let row = |rel: &str| StoredSyncEntry {
rel_path: rel.into(),
remote_uid: Some("v~l".into()),
local_mtime: 1,
local_mtime_ns: None,
local_size: 1,
remote_rev: Some("1".into()),
remote_hash: Some("1".into()),
remote_revision_id: None,
};
// Gone remotely, gone locally, a folder gone remotely, one on both
// sides, a new local file, and a folder gone from both sides.
let local: HashMap<String, LocalItem> = [
("a.txt", item(false)),
("d", item(true)),
("kept", item(false)),
("new.txt", item(false)),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect();
let remote: HashMap<String, RemoteItem> = [("b.txt", node(false)), ("kept", node(false))]
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect();
let baseline: HashMap<String, StoredSyncEntry> = ["a.txt", "b.txt", "d", "kept", "gone"]
.into_iter()
.map(|rel| (rel.to_string(), row(rel)))
.collect();
let order: Vec<String> = ["a.txt", "b.txt", "d", "kept", "new.txt", "gone"]
.into_iter()
.map(String::from)
.collect();
assert_eq!(planned_deletions(&order, &local, &remote, &baseline), 3);
}
}
+256
View File
@@ -0,0 +1,256 @@
//! The root reducer: what a mirror folder's sync knows about its coverage,
//! as one state machine per folder (`docs/SYNC_ENGINE.md`).
//!
//! [`step`] is pure: it takes the state and one input and returns the next
//! state. Time, the watcher, the event stream and the passes stay outside, as
//! inputs, so a sequence of inputs replays exactly.
//!
//! The states say how far the engine can trust what it has seen:
//!
//! - **Discovering**: no pass over the folder has finished yet.
//! - **Following**: a pass covered the whole folder, and nothing since says a
//! change could have gone unreported.
//! - **Auditing**: something did (a lost watch, an overflowed queue, a gap in
//! Drive's event stream, a restart, a suspension). Only a pass over the
//! whole folder brings it back to Following.
//! - **Suspended**: the folder cannot be synced for now: its local root is
//! missing, or sync is paused.
//! - **Draining**: a switch to on-demand is queued; passes only push.
//! - **HandedOff**: the folder is on-demand.
//!
//! For now the reducer is run alongside the engine and acted on by nothing:
//! every pass still covers the whole folder. Its transitions are logged, so
//! they can be compared with what the engine did before anything relies on
//! them.
use std::collections::HashMap;
use std::fmt;
use parking_lot::Mutex;
use tracing::info;
/// Why a folder's coverage is in doubt.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Doubt {
/// The daemon started: nothing was watched while it was down.
Restart,
/// The filesystem watcher reported an error.
WatchLost,
/// The watcher's event queue overflowed.
Overflow,
/// Drive's event stream lost changes.
EventGap,
/// The folder was suspended, and nothing was followed meanwhile.
Suspension,
}
/// Why a folder is not synced for now.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Suspension {
RootMissing,
Paused,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RootState {
Discovering,
Following,
Auditing(Doubt),
Suspended(Suspension),
Draining,
HandedOff,
}
/// Something that happened to a folder, as the reducer takes it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RootInput {
/// A pass over the whole folder finished.
Covered,
/// A change may have gone unreported.
Doubted(Doubt),
/// The folder cannot be synced for now.
Suspended(Suspension),
/// Sync is no longer paused. A missing root is only found again by a
/// pass that covers it.
Resumed,
/// A switch to on-demand is queued.
HandoffQueued,
/// The folder is on-demand.
HandedOff,
/// The folder is a mirror again after being on-demand.
Mirrored,
}
/// The state after `input`.
pub fn step(state: RootState, input: RootInput) -> RootState {
use RootState as S;
match (state, input) {
// An on-demand folder is not synced: only going back to a mirror
// changes it, and that is a first sync over again.
(S::HandedOff, RootInput::Mirrored) => S::Discovering,
(S::HandedOff, _) => S::HandedOff,
(S::Draining, RootInput::HandedOff) => S::HandedOff,
// A switch called off: a mirror again, which followed nothing while
// it pushed.
(S::Draining, RootInput::Mirrored) => S::Auditing(Doubt::Suspension),
(S::Draining, _) => S::Draining,
(_, RootInput::HandoffQueued) => S::Draining,
(_, RootInput::HandedOff) => S::HandedOff,
(S::Suspended(_), RootInput::Covered) => S::Following,
(S::Suspended(Suspension::Paused), RootInput::Resumed) => S::Auditing(Doubt::Suspension),
(S::Suspended(_), RootInput::Suspended(why)) => S::Suspended(why),
(S::Suspended(why), _) => S::Suspended(why),
(_, RootInput::Suspended(why)) => S::Suspended(why),
(_, RootInput::Covered) => S::Following,
(S::Following, RootInput::Doubted(why)) => S::Auditing(why),
// A first sync and an audit cover everything anyway; the first doubt
// is the one to report.
(state, _) => state,
}
}
impl fmt::Display for RootState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RootState::Discovering => f.write_str("discovering"),
RootState::Following => f.write_str("following"),
RootState::Auditing(why) => write!(f, "auditing ({why:?})"),
RootState::Suspended(why) => write!(f, "suspended ({why:?})"),
RootState::Draining => f.write_str("draining"),
RootState::HandedOff => f.write_str("handed off"),
}
}
}
/// The root state of every mirror folder the engine has seen, by id.
#[derive(Default)]
pub struct Roots {
states: Mutex<HashMap<i64, RootState>>,
}
impl Roots {
/// Start following `folder`, unless it already is: from discovery for a
/// folder never synced, and otherwise from an audit, since nothing
/// watched it while the daemon was down.
pub fn begin(&self, folder: i64, synced_before: bool) {
self.states
.lock()
.entry(folder)
.or_insert(if synced_before {
RootState::Auditing(Doubt::Restart)
} else {
RootState::Discovering
});
}
/// Feed `input` to `folder`'s reducer, and log the transition it makes.
/// A folder not begun yet is left alone: its first pass begins it.
pub fn input(&self, folder: i64, input: RootInput) {
let mut states = self.states.lock();
let Some(state) = states.get_mut(&folder) else {
return;
};
let next = step(*state, input);
if next != *state {
info!(id = folder, from = %state, to = %next, ?input, "sync: root state");
*state = next;
}
}
/// Feed `input` to every folder's reducer.
pub fn input_all(&self, input: RootInput) {
let folders: Vec<i64> = self.states.lock().keys().copied().collect();
for folder in folders {
self.input(folder, input);
}
}
/// The state of `folder`, if the engine has begun it.
pub fn state(&self, folder: i64) -> Option<RootState> {
self.states.lock().get(&folder).copied()
}
/// Forget a folder that is no longer synced.
pub fn forget(&self, folder: i64) {
self.states.lock().remove(&folder);
}
}
#[cfg(test)]
mod tests {
use super::*;
use RootInput as I;
use RootState as S;
fn run(from: RootState, inputs: &[RootInput]) -> RootState {
inputs.iter().fold(from, |state, input| step(state, *input))
}
#[test]
fn a_first_sync_follows_once_a_pass_covers_the_folder() {
assert_eq!(run(S::Discovering, &[I::Covered]), S::Following);
// A doubt during discovery changes nothing: the pass covers it all.
assert_eq!(
run(S::Discovering, &[I::Doubted(Doubt::Overflow)]),
S::Discovering
);
}
#[test]
fn a_doubt_takes_a_followed_folder_to_an_audit_until_a_pass_covers_it() {
let audit = run(
S::Following,
&[I::Doubted(Doubt::WatchLost), I::Doubted(Doubt::EventGap)],
);
assert_eq!(
audit,
S::Auditing(Doubt::WatchLost),
"the first doubt stays"
);
assert_eq!(step(audit, I::Covered), S::Following);
}
#[test]
fn a_suspension_ends_in_an_audit_or_a_pass() {
let paused = run(S::Following, &[I::Suspended(Suspension::Paused)]);
assert_eq!(paused, S::Suspended(Suspension::Paused));
assert_eq!(step(paused, I::Doubted(Doubt::Overflow)), paused);
assert_eq!(step(paused, I::Resumed), S::Auditing(Doubt::Suspension));
let missing = run(S::Following, &[I::Suspended(Suspension::RootMissing)]);
assert_eq!(step(missing, I::Resumed), missing);
assert_eq!(step(missing, I::Covered), S::Following);
}
#[test]
fn a_handoff_drains_then_stays_until_the_folder_is_a_mirror_again() {
let draining = step(S::Following, I::HandoffQueued);
assert_eq!(draining, S::Draining);
assert_eq!(step(draining, I::Covered), S::Draining);
let off = step(draining, I::HandedOff);
assert_eq!(off, S::HandedOff);
assert_eq!(step(off, I::Covered), S::HandedOff);
assert_eq!(step(off, I::Mirrored), S::Discovering);
assert_eq!(
step(draining, I::Mirrored),
S::Auditing(Doubt::Suspension),
"a switch called off"
);
}
#[test]
fn roots_begin_once_and_feed_every_folder() {
let roots = Roots::default();
roots.input(1, I::Covered);
assert_eq!(roots.state(1), None, "not begun");
roots.begin(1, false);
roots.begin(2, true);
assert_eq!(roots.state(2), Some(S::Auditing(Doubt::Restart)));
roots.input_all(I::Covered);
roots.begin(1, false);
assert_eq!(roots.state(1), Some(S::Following), "begun only once");
roots.input_all(I::Doubted(Doubt::EventGap));
assert_eq!(roots.state(2), Some(S::Auditing(Doubt::EventGap)));
roots.forget(2);
assert_eq!(roots.state(2), None);
}
}
+19 -3
View File
@@ -1,7 +1,8 @@
//! The port through which the mirror engine reads and writes its own tables.
//!
//! The engine keeps three things in the database: the synced folders, the
//! per-file baseline of each, and the saved walk of Drive with its dirty marks.
//! The engine keeps four things in the database: the synced folders, the
//! per-file baseline of each, the saved walk of Drive with its dirty marks,
//! and the deletions each folder made lately.
//! [`SyncStore`] is exactly the calls a pass makes on them, so the engine does
//! not depend on the whole database, and a test can give it a store of its own.
//!
@@ -11,7 +12,9 @@
use std::collections::HashMap;
use pdfs_core::Result;
use pdfs_store::db::{Db, SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
use pdfs_store::db::{
Db, DeleteWindow, SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder,
};
/// The sync tables, as the mirror engine uses them.
pub trait SyncStore: Send + Sync {
@@ -70,6 +73,13 @@ pub trait SyncStore: Send + Sync {
fn sync_remote_dirty_consume(&self, folder_id: i64, seq: i64) -> Result<()>;
/// Mark folders to list on Drive again.
fn sync_remote_mark(&self, folder_id: i64, dirs: &[String]) -> Result<()>;
// The deletions made lately, for the wipe guard.
/// The folder's deletion window, if one is open.
fn sync_delete_window(&self, folder_id: i64) -> Result<Option<DeleteWindow>>;
/// Record the folder's deletion window.
fn sync_delete_window_set(&self, folder_id: i64, window: &DeleteWindow) -> Result<()>;
}
impl SyncStore for Db {
@@ -138,6 +148,12 @@ impl SyncStore for Db {
fn sync_remote_mark(&self, folder_id: i64, dirs: &[String]) -> Result<()> {
Db::sync_remote_mark(self, folder_id, dirs)
}
fn sync_delete_window(&self, folder_id: i64) -> Result<Option<DeleteWindow>> {
Db::sync_delete_window(self, folder_id)
}
fn sync_delete_window_set(&self, folder_id: i64, window: &DeleteWindow) -> Result<()> {
Db::sync_delete_window_set(self, folder_id, window)
}
}
#[cfg(test)]
+28 -2
View File
@@ -58,6 +58,10 @@ impl Phase {
/// A kind of call to Drive, or of work applied for one path.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Call {
/// Waiting for the daemon's admission before an upload, download or
/// folder creation could start. Time here is time in line, not on the
/// network.
Admission,
/// The child uids of one folder.
ListChildren,
/// Names and kinds of one folder's children, without unlocking file keys.
@@ -76,7 +80,8 @@ pub enum Call {
}
impl Call {
const ALL: [Call; 10] = [
const ALL: [Call; 11] = [
Call::Admission,
Call::ListChildren,
Call::ReadNodes,
Call::ReadNodesFull,
@@ -91,6 +96,7 @@ impl Call {
fn name(self) -> &'static str {
match self {
Call::Admission => "admission wait",
Call::ListChildren => "list children",
Call::ReadNodes => "read nodes",
Call::ReadNodesFull => "read nodes full",
@@ -127,10 +133,22 @@ pub enum Count {
Reused,
/// Folders on Drive marked as changed since the last pass listed them.
Dirty,
/// Deletions the pass planned that the evidence does not back, and so
/// did not make: the path was not proven gone on the side the deletion is
/// based on. Should stay zero; see `evidence`.
UnprovenDeletions,
/// Marks of the local dirty set the pass claimed.
LocalDirty,
/// One when the pass's claim of the local dirty set was not trusted: the
/// watch was not live throughout since the last pass claimed.
LocalUntrusted,
/// Local changes the pass found that a trusted claim of the local dirty
/// set did not cover. Should stay zero; see `local_dirty`.
MissedLocal,
}
impl Count {
const ALL: [Count; 9] = [
const ALL: [Count; 13] = [
Count::LocalEntries,
Count::RemoteFolders,
Count::Nodes,
@@ -140,6 +158,10 @@ impl Count {
Count::Resumed,
Count::Reused,
Count::Dirty,
Count::UnprovenDeletions,
Count::LocalDirty,
Count::LocalUntrusted,
Count::MissedLocal,
];
fn name(self) -> &'static str {
@@ -153,6 +175,10 @@ impl Count {
Count::Resumed => "resumed",
Count::Reused => "reused",
Count::Dirty => "dirty folders",
Count::UnprovenDeletions => "unproven deletions",
Count::LocalDirty => "local dirty",
Count::LocalUntrusted => "local dirty untrusted",
Count::MissedLocal => "missed local changes",
}
}
}
+330
View File
@@ -0,0 +1,330 @@
//! Scenarios every adapter of the mounted-files service has to pass the same
//! way: what a file holds after it is written, resized, synced, closed and
//! opened again, and what create, mkdir, unlink, rmdir and rename do with
//! names.
//!
//! [`run`] takes an [`Adapter`] and a folder to work in. The headless adapter
//! runs them in this crate's tests; `pdfs-fuse` runs them through a mount. A
//! scenario reports what it saw instead of panicking, so one run lists every
//! difference.
use crate::headless::{Failure, Fd, Headless};
/// File and folder operations by path, relative to the adapter's root.
pub trait Adapter {
/// A file open for writing.
type Fd;
/// Create the file, or empty it when it exists, and open it for writing.
fn create(&self, path: &str) -> Result<Self::Fd, Failure>;
fn open_write(&self, path: &str) -> Result<Self::Fd, Failure>;
fn write(&self, fd: &Self::Fd, offset: u64, data: &[u8]) -> Result<(), Failure>;
fn set_len(&self, fd: &Self::Fd, size: u64) -> Result<(), Failure>;
fn fsync(&self, fd: &Self::Fd) -> Result<(), Failure>;
fn close(&self, fd: Self::Fd) -> Result<(), Failure>;
/// The whole content of the file.
fn read(&self, path: &str) -> Result<Vec<u8>, Failure>;
fn mkdir(&self, path: &str) -> Result<(), Failure>;
fn unlink(&self, path: &str) -> Result<(), Failure>;
fn rmdir(&self, path: &str) -> Result<(), Failure>;
fn rename(&self, from: &str, to: &str) -> Result<(), Failure>;
/// The names in the folder, sorted.
fn list(&self, path: &str) -> Result<Vec<String>, Failure>;
}
impl Adapter for Headless {
type Fd = Fd;
fn create(&self, path: &str) -> Result<Fd, Failure> {
Headless::create(self, path)
}
fn open_write(&self, path: &str) -> Result<Fd, Failure> {
Headless::open_write(self, path)
}
fn write(&self, fd: &Fd, offset: u64, data: &[u8]) -> Result<(), Failure> {
Headless::write(self, fd, offset, data)
}
fn set_len(&self, fd: &Fd, size: u64) -> Result<(), Failure> {
Headless::set_len(self, fd, size)
}
fn fsync(&self, fd: &Fd) -> Result<(), Failure> {
Headless::fsync(self, fd)
}
fn close(&self, fd: Fd) -> Result<(), Failure> {
Headless::close(self, fd)
}
fn read(&self, path: &str) -> Result<Vec<u8>, Failure> {
Headless::read(self, path)
}
fn mkdir(&self, path: &str) -> Result<(), Failure> {
Headless::mkdir(self, path)
}
fn unlink(&self, path: &str) -> Result<(), Failure> {
Headless::unlink(self, path)
}
fn rmdir(&self, path: &str) -> Result<(), Failure> {
Headless::rmdir(self, path)
}
fn rename(&self, from: &str, to: &str) -> Result<(), Failure> {
Headless::rename(self, from, to)
}
fn list(&self, path: &str) -> Result<Vec<String>, Failure> {
Headless::list(self, path)
}
}
/// What a scenario saw that it should not have.
pub type Outcome = Result<(), String>;
/// A scenario, run in a folder of its own.
pub type Scenario<A> = fn(&A, &Dir) -> Outcome;
/// The folder a scenario works in.
pub struct Dir(String);
impl Dir {
/// The path of `name` in this folder.
pub fn at(&self, name: &str) -> String {
format!("{}/{name}", self.0)
}
pub fn path(&self) -> &str {
&self.0
}
}
/// Every scenario, by name.
pub fn scenarios<A: Adapter>() -> Vec<(&'static str, Scenario<A>)> {
vec![
("a_reopened_file_has_what_was_written", reopened_file::<A>),
("a_partial_overwrite_keeps_the_rest", partial_overwrite::<A>),
("a_read_while_open_sees_the_writes", read_while_open::<A>),
(
"a_hole_past_a_grow_reads_as_zeros",
hole_reads_as_zeros::<A>,
),
("a_create_over_a_file_empties_it", create_empties::<A>),
("folders_list_their_children", folders_list::<A>),
("a_rename_moves_and_replaces", rename_replaces::<A>),
("a_rename_refuses_what_posix_refuses", rename_refusals::<A>),
("removing_follows_posix", remove_rules::<A>),
(
"an_unlinked_open_file_does_not_come_back",
unlinked_open::<A>,
),
]
}
/// Run every scenario in its own folder under `base`, which must exist. The
/// result names each scenario that failed and why.
pub fn run<A: Adapter>(adapter: &A, base: &str) -> Vec<(&'static str, String)> {
let mut failed = Vec::new();
for (name, scenario) in scenarios::<A>() {
let dir = Dir(format!("{base}/{name}"));
let outcome = adapter
.mkdir(dir.path())
.map_err(|e| format!("mkdir {}: {e:?}", dir.path()))
.and_then(|()| scenario(adapter, &dir));
if let Err(why) = outcome {
failed.push((name, why));
}
}
failed
}
/// `Err` naming `what` unless `got` is `want`.
fn expect<T: PartialEq + std::fmt::Debug>(what: &str, got: T, want: T) -> Outcome {
if got == want {
Ok(())
} else {
Err(format!("{what}: got {got:?}, want {want:?}"))
}
}
/// The `Ok` of `result`, or `Err` naming `what`.
fn ok<T>(what: &str, result: Result<T, Failure>) -> Result<T, String> {
result.map_err(|e| format!("{what}: {e:?}"))
}
fn write_file<A: Adapter>(a: &A, path: &str, bytes: &[u8]) -> Outcome {
let fd = ok(&format!("create {path}"), a.create(path))?;
ok(&format!("write {path}"), a.write(&fd, 0, bytes))?;
ok(&format!("close {path}"), a.close(fd))
}
/// Written, resized, synced, closed and opened again: the bytes are what the
/// handle left, and a second handle adds to them.
fn reopened_file<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.txt");
let fd = ok("create", a.create(&f))?;
ok("write", a.write(&fd, 0, b"hello world"))?;
ok("set_len", a.set_len(&fd, 5))?;
ok("fsync", a.fsync(&fd))?;
ok("close", a.close(fd))?;
expect("after close", a.read(&f), Ok(b"hello".to_vec()))?;
let fd = ok("reopen", a.open_write(&f))?;
ok("append", a.write(&fd, 5, b" again"))?;
ok("close again", a.close(fd))?;
expect("after reopen", a.read(&f), Ok(b"hello again".to_vec()))
}
fn partial_overwrite<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.txt");
write_file(a, &f, b"abcdef")?;
let fd = ok("reopen", a.open_write(&f))?;
ok("overwrite", a.write(&fd, 2, b"XY"))?;
ok("close", a.close(fd))?;
expect("content", a.read(&f), Ok(b"abXYef".to_vec()))
}
fn read_while_open<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.txt");
let fd = ok("create", a.create(&f))?;
ok("write", a.write(&fd, 0, b"draft"))?;
let seen = a.read(&f);
ok("close", a.close(fd))?;
expect("while open", seen, Ok(b"draft".to_vec()))
}
fn hole_reads_as_zeros<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.bin");
let fd = ok("create", a.create(&f))?;
ok("write", a.write(&fd, 0, b"ab"))?;
ok("grow", a.set_len(&fd, 4))?;
ok("write past the end", a.write(&fd, 6, b"z"))?;
ok("close", a.close(fd))?;
expect("content", a.read(&f), Ok(b"ab\0\0\0\0z".to_vec()))
}
fn create_empties<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.txt");
write_file(a, &f, b"old content")?;
write_file(a, &f, b"new")?;
expect("content", a.read(&f), Ok(b"new".to_vec()))
}
fn folders_list<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let sub = d.at("sub");
ok("mkdir", a.mkdir(&sub))?;
expect("mkdir again", a.mkdir(&sub), Err(Failure::Exists))?;
write_file(a, &format!("{sub}/b.txt"), b"b")?;
write_file(a, &format!("{sub}/a.txt"), b"a")?;
expect(
"listing",
a.list(&sub),
Ok(vec!["a.txt".to_owned(), "b.txt".to_owned()]),
)?;
expect(
"parent listing",
a.list(d.path()),
Ok(vec!["sub".to_owned()]),
)?;
expect(
"mkdir under a file",
a.mkdir(&format!("{sub}/a.txt/x")),
Err(Failure::NotDirectory),
)
}
fn rename_replaces<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let (from, to) = (d.at("a.txt"), d.at("b.txt"));
write_file(a, &from, b"A")?;
write_file(a, &to, b"B")?;
ok("rename over", a.rename(&from, &to))?;
expect("destination", a.read(&to), Ok(b"A".to_vec()))?;
expect("source", a.read(&from), Err(Failure::NotFound))?;
ok("mkdir", a.mkdir(&d.at("sub")))?;
ok("move", a.rename(&to, &d.at("sub/c.txt")))?;
expect("moved", a.read(&d.at("sub/c.txt")), Ok(b"A".to_vec()))?;
expect("listing", a.list(d.path()), Ok(vec!["sub".to_owned()]))
}
fn rename_refusals<A: Adapter>(a: &A, d: &Dir) -> Outcome {
ok("mkdir", a.mkdir(&d.at("dir")))?;
ok("mkdir inner", a.mkdir(&d.at("dir/inner")))?;
ok("mkdir full", a.mkdir(&d.at("full")))?;
write_file(a, &d.at("full/x"), b"x")?;
write_file(a, &d.at("f.txt"), b"f")?;
expect(
"folder into itself",
a.rename(&d.at("dir"), &d.at("dir/inner/dir")),
Err(Failure::InvalidArgument),
)?;
expect(
"file over folder",
a.rename(&d.at("f.txt"), &d.at("dir")),
Err(Failure::IsDirectory),
)?;
expect(
"folder over file",
a.rename(&d.at("dir"), &d.at("f.txt")),
Err(Failure::NotDirectory),
)?;
expect(
"folder over a full folder",
a.rename(&d.at("dir"), &d.at("full")),
Err(Failure::NotEmpty),
)?;
expect(
"missing source",
a.rename(&d.at("nothing"), &d.at("g.txt")),
Err(Failure::NotFound),
)?;
expect("file kept", a.read(&d.at("f.txt")), Ok(b"f".to_vec()))?;
expect("full kept", a.list(&d.at("full")), Ok(vec!["x".to_owned()]))
}
fn remove_rules<A: Adapter>(a: &A, d: &Dir) -> Outcome {
ok("mkdir", a.mkdir(&d.at("dir")))?;
write_file(a, &d.at("dir/f"), b"f")?;
expect(
"unlink a folder",
a.unlink(&d.at("dir")),
Err(Failure::IsDirectory),
)?;
expect(
"rmdir a file",
a.rmdir(&d.at("dir/f")),
Err(Failure::NotDirectory),
)?;
expect(
"rmdir a full folder",
a.rmdir(&d.at("dir")),
Err(Failure::NotEmpty),
)?;
expect(
"unlink nothing",
a.unlink(&d.at("nothing")),
Err(Failure::NotFound),
)?;
ok("unlink", a.unlink(&d.at("dir/f")))?;
ok("rmdir", a.rmdir(&d.at("dir")))?;
expect("listing", a.list(d.path()), Ok(Vec::new()))
}
fn unlinked_open<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.txt");
let fd = ok("create", a.create(&f))?;
ok("write", a.write(&fd, 0, b"doomed"))?;
ok("unlink", a.unlink(&f))?;
ok("write after unlink", a.write(&fd, 6, b" still"))?;
ok("close", a.close(fd))?;
expect("read", a.read(&f), Err(Failure::NotFound))?;
expect("listing", a.list(d.path()), Ok(Vec::new()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_headless_adapter_passes_every_scenario() {
let dir = std::env::temp_dir().join(format!("pdfs-headless-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let headless = Headless::open(&dir).unwrap();
headless.mkdir("conformance").unwrap();
let failed = run(&headless, "conformance");
let _ = std::fs::remove_dir_all(&dir);
assert!(failed.is_empty(), "{failed:#?}");
}
}
+629
View File
@@ -0,0 +1,629 @@
//! A second adapter over the mounted-files service, with no kernel: files and
//! folders addressed by path, served by [`Files`] and [`Namespace`].
//!
//! It exists to show what the service needs from an adapter, and that nothing
//! of FUSE is left in it. The Linux FUSE adapter in `pdfs-fuse` answers the
//! kernel with what the services return; this one answers a caller with
//! [`Failure`]. The conformance scenarios (`conformance`, with the
//! `test-support` feature) run through both and expect the same outcomes.
//!
//! [`Headless`] has no Drive. Its host queues every create in the real store
//! as the daemon does offline, and nothing drains the queue. The bytes a
//! closed file committed are kept in memory, as the content of its next
//! revision would be.
//!
//! What the kernel does before it calls the FUSE adapter, this adapter does
//! itself: it resolves a path one name at a time, refuses to make a name that
//! is taken, and opens an existing file when asked to create it. The services
//! leave those checks to the adapter.
use std::collections::HashMap;
use std::fs::File;
use std::path::Path;
use std::sync::Arc;
use parking_lot::Mutex;
use pdfs_core::lockrank::{Rank, Ranked};
use pdfs_store::cache::ContentCache;
use pdfs_store::db::{Db, LOCAL_VOLUME, OP_CREATE, OP_MKDIR, PARK_UNTIL, PendingOp};
use proton_drive_rs::Node;
use proton_drive_rs::proton_sdk::ids::{LinkId, NodeUid, VolumeId};
use crate::files::{FileError, Files, FilesHost};
use crate::ids::is_local_uid;
use crate::namespace::{Namespace, NamespaceError, NamespaceHost, RenameFlags};
use crate::nodes::local_node;
use crate::open::{Intervals, ReadFailure, WriteHandle, assemble_open_read};
use crate::tree::{NodeError, State, StateGuard};
use crate::writes::WriteState;
/// Why the headless adapter refused or failed an operation. The FUSE adapter
/// answers each with the errno named here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Failure {
/// `ENOENT`: no such file or folder.
NotFound,
/// `EEXIST`: the name is taken.
Exists,
/// `EISDIR`: a folder where a file was needed.
IsDirectory,
/// `ENOTDIR`: a file where a folder was needed.
NotDirectory,
/// `ENOTEMPTY`: the folder has children.
NotEmpty,
/// `EINVAL`: an operation that cannot be done, such as moving a folder
/// into itself.
InvalidArgument,
/// `EACCES`: the node may not be changed.
Denied,
/// `EBUSY`: try again.
Busy,
/// `EBADF`: no file is open under this handle.
BadHandle,
/// `ENOSPC`: the local disk is full.
NoSpace,
/// `EOPNOTSUPP`: the operation is not supported.
Unsupported,
/// `EIO`: something failed underneath.
Io,
}
impl Failure {
/// The failure an OS error stands for, as the FUSE adapter answers it.
pub fn from_errno(errno: i32) -> Self {
match errno {
libc::ENOENT => Failure::NotFound,
libc::EEXIST => Failure::Exists,
libc::EISDIR => Failure::IsDirectory,
libc::ENOTDIR => Failure::NotDirectory,
libc::ENOTEMPTY => Failure::NotEmpty,
libc::EINVAL => Failure::InvalidArgument,
libc::EACCES | libc::EPERM => Failure::Denied,
libc::EBUSY => Failure::Busy,
libc::EBADF => Failure::BadHandle,
libc::ENOSPC | libc::EDQUOT => Failure::NoSpace,
libc::EOPNOTSUPP => Failure::Unsupported,
_ => Failure::Io,
}
}
}
/// What the headless host fails with.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostError {
NotFound,
Denied,
Io,
}
impl From<HostError> for Failure {
fn from(error: HostError) -> Self {
match error {
HostError::NotFound => Failure::NotFound,
HostError::Denied => Failure::Denied,
HostError::Io => Failure::Io,
}
}
}
impl From<FileError<HostError>> for Failure {
fn from(error: FileError<HostError>) -> Self {
match error {
FileError::NotFound => Failure::NotFound,
FileError::IsDirectory => Failure::IsDirectory,
FileError::Denied => Failure::Denied,
FileError::BadHandle => Failure::BadHandle,
FileError::NoSpace | FileError::QuotaExceeded => Failure::NoSpace,
FileError::Unsupported => Failure::Unsupported,
FileError::Io | FileError::Storage(_) => Failure::Io,
FileError::Host(error) => error.into(),
}
}
}
impl From<NamespaceError<HostError>> for Failure {
fn from(error: NamespaceError<HostError>) -> Self {
match error {
NamespaceError::NotFound => Failure::NotFound,
NamespaceError::IsDirectory => Failure::IsDirectory,
NamespaceError::NotDirectory => Failure::NotDirectory,
NamespaceError::NotEmpty => Failure::NotEmpty,
NamespaceError::InvalidArgument => Failure::InvalidArgument,
NamespaceError::Exists => Failure::Exists,
NamespaceError::Busy => Failure::Busy,
NamespaceError::Io => Failure::Io,
NamespaceError::Host(error) => error.into(),
}
}
}
fn node_failure(error: NodeError) -> HostError {
match error {
NodeError::NotFound => HostError::NotFound,
NodeError::NotWritable => HostError::Denied,
}
}
/// A file open for writing through the headless adapter.
#[derive(Debug)]
pub struct Fd {
ino: u64,
fh: u64,
}
struct Inner {
state: Arc<Ranked<State>>,
db: Arc<Db>,
cache: Arc<ContentCache>,
/// What each file's last close committed: the content its next revision
/// would upload.
content: Mutex<HashMap<NodeUid, Vec<u8>>>,
}
/// The host of the headless adapter: offline, with the real store.
#[derive(Clone)]
struct LocalHost(Arc<Inner>);
impl LocalHost {
fn state(&self) -> StateGuard<'_> {
StateGuard::new(self.0.state.lock(), &self.0.db)
}
fn base(&self, uid: &NodeUid) -> Vec<u8> {
self.0.content.lock().get(uid).cloned().unwrap_or_default()
}
fn drop_ops(&self, uid: &NodeUid) -> Result<(), HostError> {
self.0
.db
.delete_ops_for_uid(&uid.to_string())
.map(drop)
.map_err(|_| HostError::Io)
}
}
/// The bytes `[0, len)` of a file open for writing: what it wrote from
/// `file`, the rest from `base`.
fn assemble(file: &File, len: u64, written: &Intervals, base: &[u8]) -> Result<Vec<u8>, HostError> {
let base_len = base.len() as u64;
let read = assemble_open_read::<()>(file, len, base_len, written, 0, len, |offset, n| {
Ok(Some(base[offset as usize..(offset + n) as usize].to_vec()))
});
match read {
Ok(Some(bytes)) => Ok(bytes),
Ok(None) | Err(ReadFailure::Base(())) | Err(ReadFailure::Scratch(_)) => Err(HostError::Io),
}
}
impl FilesHost for LocalHost {
type Error = HostError;
fn settle_size(&self, _ino: u64, _uid: &NodeUid) -> Option<u64> {
None
}
fn fill_gaps(
&self,
uid: &NodeUid,
file: &File,
len: u64,
_base_mtime: i64,
_base_size: u64,
written: &Intervals,
) -> Result<(), HostError> {
use std::os::unix::fs::FileExt;
let base = self.base(uid);
file.set_len(len).map_err(|_| HostError::Io)?;
for (start, end, authored) in written.segments(0, len) {
let end = end.min(base.len() as u64);
if !authored && start < end {
file.write_all_at(&base[start as usize..end as usize], start)
.map_err(|_| HostError::Io)?;
}
}
Ok(())
}
fn landed(&self, _uid: &NodeUid) -> Option<Node> {
None
}
fn commit(&self, handle: &mut WriteHandle) -> Result<(), HostError> {
let committed = if handle.dirty {
let base = self.base(&handle.uid);
Some(assemble(&handle.file, handle.len, &handle.written, &base)?)
} else {
None
};
self.0.cache.clear_scratch_durable(&handle.path);
let _ = std::fs::remove_file(&handle.path);
if let Some(bytes) = committed {
self.0.content.lock().insert(handle.uid.clone(), bytes);
}
Ok(())
}
fn discard_unlinked(&self, uid: &NodeUid) {
self.0.content.lock().remove(uid);
let _ = self.drop_ops(uid);
}
}
impl NamespaceHost for LocalHost {
type Error = HostError;
fn require_writable(&self, ino: u64) -> Result<(), HostError> {
self.0
.state
.lock()
.require_writable(ino)
.map_err(node_failure)
}
fn require_uid_writable(&self, uid: &NodeUid) -> Result<(), HostError> {
let st = self.0.state.lock();
match st.by_uid.get(uid) {
Some(&ino) => st.require_writable(ino).map_err(node_failure),
None => Err(HostError::Denied),
}
}
fn ensure_children(&self, _ino: u64) -> Result<(), HostError> {
// Every folder is made here and listed from the start.
Ok(())
}
fn lookup_child(&self, parent: u64, name: &str) -> Result<Option<(u64, NodeUid)>, HostError> {
let st = self.0.state.lock();
Ok(st
.children
.get(&parent)
.into_iter()
.flatten()
.filter_map(|ino| st.entries.get(ino).map(|entry| (*ino, entry)))
.find(|(_, entry)| entry.node.name == name)
.map(|(ino, entry)| (ino, entry.uid.clone())))
}
fn sends_inline(&self) -> bool {
false
}
fn mint(
&self,
_parent: &NodeUid,
_name: &str,
_folder: bool,
) -> Result<Option<Node>, HostError> {
Ok(None)
}
fn queue_create(
&self,
parent_uid: &NodeUid,
name: &str,
folder: bool,
parked: bool,
) -> Result<Node, HostError> {
let now = now_secs();
let lid = self
.0
.db
.add_local_row(&parent_uid.to_string(), name, folder, now)
.map_err(|_| HostError::Io)?;
let uid = NodeUid::new(VolumeId::from(LOCAL_VOLUME), LinkId::from(lid.to_string()));
let op = PendingOp {
id: 0,
kind: if folder { OP_MKDIR } else { OP_CREATE }.to_string(),
uid: uid.to_string(),
parent_uid: Some(parent_uid.to_string()),
name: Some(name.to_owned()),
blob_path: None,
meta_json: None,
created_at: now * 1000,
attempts: 0,
last_error: None,
next_attempt_at: if parked { PARK_UNTIL } else { 0 },
};
self.0.db.enqueue_op(&op).map_err(|_| HostError::Io)?;
Ok(local_node(uid, parent_uid.clone(), name.to_owned(), folder))
}
fn access_changed(&self) {}
fn drop_queued(&self, uid: &NodeUid, _keep_staged: bool) -> Result<(), HostError> {
self.drop_ops(uid)
}
fn landed_uid(&self, _ino: u64) -> Option<NodeUid> {
None
}
fn has_pending_moves_out_of(&self, _uid: &NodeUid) -> Result<bool, HostError> {
Ok(false)
}
fn queue_trash(&self, uid: &NodeUid, _name: &str, open: bool) -> Result<(), HostError> {
// Only the root is not made here, and it cannot be removed.
self.state().forget_or_unlink(uid);
if !open {
self.0.content.lock().remove(uid);
}
Ok(())
}
fn trash_remote(&self, _uid: &NodeUid, _name: &str) -> Result<bool, HostError> {
Ok(false)
}
fn remove_replaced(&self, _ino: u64, uid: &NodeUid, _name: &str) -> Result<(), HostError> {
let open = {
let st = self.0.state.lock();
st.by_uid
.get(uid)
.and_then(|ino| st.entries.get(ino))
.is_some_and(|entry| entry.open_count > 0)
};
if is_local_uid(uid) {
self.drop_ops(uid)?;
}
self.state().forget_or_unlink(uid);
if !open {
self.0.content.lock().remove(uid);
}
Ok(())
}
fn restore_replaced(&self, _victim: Option<&(u64, NodeUid)>, _parent: &NodeUid, _name: &str) {}
fn queue_rename(
&self,
ino: u64,
_uid: &NodeUid,
_old_parent_uid: &NodeUid,
new_parent_ino: u64,
new_parent_uid: &NodeUid,
new_name: &str,
_authorized: bool,
) -> Result<(), HostError> {
self.state()
.rename_in_place(ino, new_parent_ino, new_parent_uid, new_name);
Ok(())
}
fn rename_remote(
&self,
_uid: &NodeUid,
_new_parent: Option<&NodeUid>,
_new_name: Option<&str>,
) -> Result<bool, HostError> {
Ok(false)
}
fn wake_drain(&self) {}
fn trashed(&self, _uid: &NodeUid, _name: &str, _open: bool) {}
}
fn now_secs() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i64)
}
/// The mounted-files service of one root, served by path.
pub struct Headless {
host: LocalHost,
files: Files<LocalHost>,
namespace: Namespace<LocalHost>,
root: u64,
}
impl Headless {
/// A new, empty root, with its store and cache in `dir`.
pub fn open(dir: &Path) -> std::io::Result<Self> {
let other = |e: &dyn std::fmt::Display| std::io::Error::other(e.to_string());
std::fs::create_dir_all(dir)?;
let db = Arc::new(Db::open(&dir.join("cache.db")).map_err(|e| other(&e))?);
let cache = Arc::new(
ContentCache::open(dir.join("content"), dir.join("pins"), 0, db.clone())
.map_err(|e| other(&e))?,
);
let state = Arc::new(Ranked::new(
Rank::State,
State::new(db.clone(), HashMap::new()),
));
let root_uid = NodeUid::new(VolumeId::from("headless"), LinkId::from("root"));
let root = {
let mut st = StateGuard::new(state.lock(), &db);
let ino = st.install_root(local_node(root_uid.clone(), root_uid, String::new(), true));
st.children.insert(ino, Vec::new());
ino
};
let host = LocalHost(Arc::new(Inner {
state: state.clone(),
db: db.clone(),
cache: cache.clone(),
content: Mutex::default(),
}));
let writes = WriteState::default();
Ok(Headless {
files: Files::new(
state.clone(),
db.clone(),
cache.clone(),
writes.clone(),
host.clone(),
),
namespace: Namespace::new(state, db, cache, writes, host.clone()),
host,
root,
})
}
/// The inode at `path`, resolved one name at a time from the root.
fn resolve(&self, path: &str) -> Result<u64, Failure> {
let mut ino = self.root;
for name in components(path) {
if !self.is_folder(ino)? {
return Err(Failure::NotDirectory);
}
ino = self
.host
.lookup_child(ino, name)?
.ok_or(Failure::NotFound)?
.0;
}
Ok(ino)
}
/// The folder `path` names a child of, and the child's name.
fn split<'p>(&self, path: &'p str) -> Result<(u64, &'p str), Failure> {
let mut names: Vec<&str> = components(path).collect();
let name = names.pop().ok_or(Failure::InvalidArgument)?;
let parent = self.resolve(&names.join("/"))?;
if !self.is_folder(parent)? {
return Err(Failure::NotDirectory);
}
Ok((parent, name))
}
fn is_folder(&self, ino: u64) -> Result<bool, Failure> {
self.host
.0
.state
.lock()
.entries
.get(&ino)
.map(|entry| entry.node.is_folder())
.ok_or(Failure::NotFound)
}
fn child(&self, parent: u64, name: &str) -> Result<Option<u64>, Failure> {
Ok(self.host.lookup_child(parent, name)?.map(|(ino, _)| ino))
}
/// Create the file at `path`, or empty it when it exists, and open it for
/// writing, as `open(O_CREAT | O_TRUNC)` does.
pub fn create(&self, path: &str) -> Result<Fd, Failure> {
let (parent, name) = self.split(path)?;
if let Some(ino) = self.child(parent, name)? {
let fd = self.open_ino(ino)?;
self.set_len(&fd, 0)?;
return Ok(fd);
}
let made = self.namespace.create(parent, name)?;
Ok(Fd {
ino: made.ino,
fh: made.fh,
})
}
/// Open the file at `path` for writing.
pub fn open_write(&self, path: &str) -> Result<Fd, Failure> {
let ino = self.resolve(path)?;
self.open_ino(ino)
}
fn open_ino(&self, ino: u64) -> Result<Fd, Failure> {
let fh = self.files.open(ino, true)?;
Ok(Fd { ino, fh })
}
pub fn write(&self, fd: &Fd, offset: u64, data: &[u8]) -> Result<(), Failure> {
Ok(self.files.write(fd.ino, fd.fh, offset, data)?)
}
pub fn set_len(&self, fd: &Fd, size: u64) -> Result<(), Failure> {
match self.files.resize(fd.ino, size)? {
true => Ok(()),
false => Err(Failure::BadHandle),
}
}
pub fn fsync(&self, fd: &Fd) -> Result<(), Failure> {
Ok(self.files.fsync(fd.fh)?)
}
pub fn close(&self, fd: Fd) -> Result<(), Failure> {
Ok(self.files.release(fd.ino, fd.fh)?)
}
/// The whole content of the file at `path`: what a handle open on it
/// holds, or else what its last close committed.
pub fn read(&self, path: &str) -> Result<Vec<u8>, Failure> {
let ino = self.resolve(path)?;
let (uid, size, view) = {
let st = self.host.0.state.lock();
let entry = st.entries.get(&ino).ok_or(Failure::NotFound)?;
if entry.node.is_folder() {
return Err(Failure::IsDirectory);
}
(
entry.uid.clone(),
pdfs_drive::node_size(&entry.node),
st.open.writer(ino).map(WriteHandle::read_view),
)
};
let base = self.host.base(&uid);
match view {
Some(view) => Ok(assemble(&view.file, view.len, &view.written, &base)?),
None => {
let mut bytes = base;
bytes.resize(size as usize, 0);
Ok(bytes)
}
}
}
pub fn mkdir(&self, path: &str) -> Result<(), Failure> {
let (parent, name) = self.split(path)?;
if self.child(parent, name)?.is_some() {
return Err(Failure::Exists);
}
self.namespace.mkdir(parent, name)?;
Ok(())
}
pub fn unlink(&self, path: &str) -> Result<(), Failure> {
let (parent, name) = self.split(path)?;
Ok(self.namespace.unlink(parent, name)?)
}
pub fn rmdir(&self, path: &str) -> Result<(), Failure> {
let (parent, name) = self.split(path)?;
Ok(self.namespace.rmdir(parent, name)?)
}
pub fn rename(&self, from: &str, to: &str) -> Result<(), Failure> {
let (parent, name) = self.split(from)?;
let (new_parent, new_name) = self.split(to)?;
self.child(parent, name)?.ok_or(Failure::NotFound)?;
self.namespace
.rename(parent, name, new_parent, new_name, RenameFlags::default())?;
Ok(())
}
/// The names in the folder at `path`, sorted.
pub fn list(&self, path: &str) -> Result<Vec<String>, Failure> {
let ino = self.resolve(path)?;
if !self.is_folder(ino)? {
return Err(Failure::NotDirectory);
}
let st = self.host.0.state.lock();
let mut names: Vec<String> = st
.children
.get(&ino)
.into_iter()
.flatten()
.filter_map(|kid| st.entries.get(kid).map(|entry| entry.node.name.clone()))
.collect();
names.sort();
Ok(names)
}
}
fn components(path: &str) -> impl Iterator<Item = &str> {
path.split('/')
.filter(|name| !name.is_empty() && *name != ".")
}
+12 -1
View File
@@ -12,11 +12,22 @@
//! authored, the released write that waits for its upload, and directory
//! handles; what the mount accepted but has not sent to Drive yet
//! ([`writes`]); the POSIX rules on names and on what a rename may replace
//! ([`names`]); and which nodes a folder lists ([`nodes`]).
//! ([`names`]); which nodes a folder lists ([`nodes`]); and two services
//! behind host ports: the open files from open to close ([`files`]), and
//! create, mkdir, unlink, rmdir and rename ([`namespace`]).
//!
//! A second adapter, [`headless`], serves the same services by path with no
//! kernel and no Drive. The scenarios in `conformance` (with the
//! `test-support` feature) run through it here and through a FUSE mount in
//! `pdfs-fuse`, and both have to see the same outcomes.
#[cfg(any(test, feature = "test-support"))]
pub mod conformance;
pub mod files;
pub mod headless;
pub mod ids;
pub mod names;
pub mod namespace;
pub mod nodes;
pub mod open;
pub mod tree;
File diff suppressed because it is too large. Load diff
+60 -5
View File
@@ -50,8 +50,9 @@ graph TD
| [`pdfs-core`](../crates/pdfs-core) | Authentication and keyring (`auth`), configuration and directories (`config`), the control protocol (`control`), search scoring, ignore rules, Google Takeout parsing, the machine profile, the transfer registry (`transfers`) and the shutdown signal (`shutdown`) |
| [`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-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, what each walk proves about a path (`evidence`), 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-sched`](../crates/pdfs-sched) | The admission port: a service describes each step of background work it is about to run (`Step`: its class and its root) and waits for a `Permit` from an `Admission`. `Bounded` admits a fixed number at once. The mirror engine admits every upload, download and folder creation of a pass through it |
| [`pdfs-vfs`](../crates/pdfs-vfs) | The mounted-files service, with no kernel adapter: the tree (`tree`: nodes, stable inodes, per-mount roots), the reserved inodes (`ids`), the open files (`open`: write handles and their authored ranges, released writes waiting for upload, directory handles, `fallocate` rules), the open-file service (`files`: open, write, resize, fsync and close, behind the `FilesHost` port), the namespace service (`namespace`: create, mkdir, unlink, rmdir and rename behind the `NamespaceHost` port, and the settling of a cut-off replacing rename), a headless adapter that serves both by path (`headless`) and the scenarios every adapter has to pass (`conformance`), and what the mount accepted but has not sent yet (`writes`: queued revisions, nodes removed here, echoes of our own changes). Errors are typed; the FUSE adapter maps them to errno |
| [`pdfs-fuse`](../crates/pdfs-fuse) | The daemon: FUSE handlers (`filesystem`), finding nodes (`resolve`), folder listings and file sizes (`listing`, `sizes`), reads (`reads`), queueing and the drain (`enqueue`, `queue`, `drain`, `upload`), calls sent straight to Drive (`remote`), requests by path (`requests`), startup recovery (`recovery`), pins, search, trash, the shared tree (`shared`), the link state (`link`), remote events (`background`), the daemon's side of the sync engine (`sync`, which implements `SyncHost`), moves between locations (`relocate`), control handlers (`control`), push events (`events`), photos, sharing, devices, the supervisor, and the simulation tests (`sim/`) |
| [`pdfs-daemon`](../crates/pdfs-daemon) | The daemon's composition root: waits for a session, opens the database and the content cache, resumes the session and mounts, then remounts or retries with a backoff and records each failure |
| [`pdfs-cli`](../crates/pdfs-cli) | The `pdfs` binary. `pdfs daemon` runs `pdfs_daemon::run` in-process; every other command is a control-socket client |
@@ -342,8 +343,23 @@ A filesystem watcher (`notify`) and a remote poll every 120 s feed a debounced p
Safety rules:
- **Absence is a typed fact** (`pdfs_sync::evidence`). For each path and side, a pass knows
that it is there (`Present`), that the walk read the folder it would be in completely and it
was not there (`Absent`), that the ignore rules exclude it (`Excluded`), or that the walk could
not tell, and why (`Unknown`: unreadable or vanished here; unread, under a short listing or
under a failed listing on Drive). Only a path known on both sides is classified, and only
`Absent` backs a deletion. Every deletion a pass plans is checked against the evidence once
more, and one it does not back is not made: the pass logs it, counts it as `unproven
deletions` in its trace and fails the step, and the next pass plans it again. The count
should stay at zero.
- **Wipe guard.** A pass in which every previously synced file has vanished locally is refused
instead of trashing the whole folder on Drive. It applies to any non-empty baseline.
- **Deletion window.** The wipe guard sees one pass. A tree lost a little at a time passes it once
per pass, so each folder also counts the deletions it made in the last day, on either side, in
`sync_delete_window` (schema 50). A mirror pass whose deletions would bring that count to nine
tenths of what the folder tracked is refused (`guard_delete_window`). A user emptying one large
subfolder of a healthy tree stays under it. A pass records its plan before it deletes and what
it actually deleted once it ends. Changing or removing the folder drops the window.
- **Open for writing.** Files that some process holds open for writing (`/proc/*/fd`,
`open_for_write_set`) are left out of the pass and picked up after they are closed.
- **Ignore rules.** `.pdfsignore` (or `.protonignore`) at the folder root plus `ignore_patterns`
@@ -721,6 +737,7 @@ apps pdfs-cli, pdfs-gui talk to the daemon over the co
daemon pdfs-daemon builds the services, supervisor, diagnostics, control server
adapters pdfs-fuse (Linux FUSE), pdfs-local (watch, scan, place), pdfs-drive (SDK adapter, fake Drive)
services pdfs-sync (mirrors), pdfs-vfs (mounted files: objects, handles, generations), photos, ...
pdfs-sched (admission: which step of background work may start)
base pdfs-store (SQLite, migrations), pdfs-core (config, protocol, ids, errors)
```
@@ -860,9 +877,47 @@ base, writes, resizes and `fallocate`, flush, the fsync barrier and the release.
handle counts its changes in a generation, and an fsync holds the handle's barrier from reading
it to writing its sidecar, so overlapping fsyncs record in order (B301). What the service needs
from Drive and the upload queue goes through `files::FilesHost`, which `Core` implements; the
FUSE callbacks keep the inode translation, the choice of thread and the reply. What still sits in
`pdfs-fuse` around the tree is the code that fills it (listings, sizes, the drain), the read
path, and the namespace operations (create, mkdir, rename, unlink).
FUSE callbacks keep the inode translation, the choice of thread and the reply.
The namespace service, `namespace::Namespace`, serves create, mkdir, unlink, rmdir and rename: whether a
new node is made on Drive at once or queued, the parked create of a transient name, the POSIX
checks on what `unlink`, `rmdir` and a replacing rename may remove, the order of a trash (Drive
first, then the tree), and the replace journal written before a rename removes its destination. Drive calls, the queue and the access rules go through `namespace::NamespaceHost`, which
`Core` implements. The module also holds the rules that settle a replacing rename a stop cut off
(B302). What still sits in `pdfs-fuse` around the tree is the code that fills it (listings,
sizes, the drain) and the read path.
A second adapter, `headless::Headless`, serves both services by path, with no kernel and no
Drive: its host queues every create in the store as the daemon does offline. It does itself what
the kernel does before it calls the FUSE adapter: it resolves a path one name at a time, refuses
a name that is taken, and opens a file it is asked to create when one exists. The scenarios in
`pdfs_vfs::conformance` (written, resized, synced, closed and reopened files; folders; renames
and removals with their POSIX refusals; an unlinked open file) run through it in `pdfs-vfs` and
through a FUSE mount, online and offline, in `pdfs-fuse`'s simulations, and both see the same
outcomes. `cargo tree -p pdfs-vfs` still shows no kernel or GUI crate.
Step 6 has started. `pdfs-sched` holds the admission port: an `Admission` decides when a `Step`
may start, and its `Permit` gives the capacity back when dropped. The mirror engine asks it
before every upload, download and folder creation of a pass, through `SyncParts::admission`,
instead of a semaphore of its own. The daemon supplies `Bounded` with the engine's old limit of
8 (`SYNC_CONCURRENCY`); passes run one at a time, so the behaviour is the one from before. An
account-wide controller that weighs mirror steps against mounted reads and the drain plugs in
behind the same trait.
An admission also reports its load (`Admission::load`): per class of step, how many run, how
many wait, how long the oldest has waited, and the total and longest wait so far. `pdfs
diagnostics` prints it, and each pass trace counts the time its steps spent in line
(`admission wait`) apart from the time they spent on the network. This is the first item of the
scheduler's delivery order: measure before any policy changes.
The second item moves one cold path behind admission: a folder the mount has not listed yet. The
daemon's admission is now `Classes`, a limit of its own per class of step, so mirror steps (8) and
cold listings (32, above what the mount lists at once today) never wait for each other. Callers
that find the same folder unlisted at once share one listing through a single flight
(`pdfs_sched::flights`): the first lists it, the others wait and take what it published, and a
follower whose leader failed lists the folder itself, so each caller still gets its own answer.
A shared folder's refresh stays out of the flight, since its generation check settles races of
its own.
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
+101
View File
@@ -108,6 +108,9 @@ a live account since.
| Entry | Title |
|---|---|
| [B304](#b304--a-write-released-while-its-files-create-lands-is-kept-as-a-conflict-copy) | A write released while its file's create lands is kept as a conflict copy |
| [B303](#b303--a-file-made-where-a-withdrawn-create-was-listed-refuses-every-write) | A file made where a withdrawn create was listed refuses every write |
| [B302](#b302--a-stop-during-a-replacing-rename-leaves-the-replaced-file-in-the-trash) | A stop during a replacing rename leaves the replaced file in the trash |
| [B301](#b301--two-overlapping-fsyncs-can-leave-the-older-ones-record-on-disk) | Two overlapping fsyncs can leave the older one's record on disk |
| [B300](#b300--a-read-during-a-release-can-be-served-the-revision-the-write-replaced) | A read during a release can be served the revision the write replaced |
| [B299](#b299--a-synced-folder-in-the-trash-blocks-attaching-any-other-folder) | A synced folder in the trash blocks attaching any other folder |
@@ -404,6 +407,104 @@ a live account since.
Newest first.
### B304 — A write released while its file's create lands is kept as a conflict copy
**Status:** Fixed (unverified)
**Found:** 2026-11-27, from a CI failure of the `one_client_with_stale_hashes_and_reordered_echoes`
simulation (seed 5): the queues did not drain in time, and Drive held a conflict copy of `e.md`.
The daemon log said "the remote revision changed under the queued write (expected 28 bytes at
mtime 1795799834, found 28 at 1795799835)".
**Where:** `Core::adopt_real_uid` in `crates/pdfs-fuse/src/drain/create.rs` and
`Core::revision_conflict` in `crates/pdfs-fuse/src/drain/revision.rs`
**Repro:** Make a file with some content, and let its create reach Drive in a later second than
the file was made locally. As the create lands, write part of the file and close it. Rare: the
close has to fall in a window of a few milliseconds.
**Cause.** The write opened over the create's placeholder, whose base is the local mtime and no
revision id. Landing the create rebases the handles open on the file and the writes queued for
it onto the node Drive made. A release takes its handle out of the tree before it queues the
write, so a release that started before the rebase and queued after it was caught by neither.
The drain then had no revision id to compare and fell back to the mtime, which Drive had stamped
a second later. The write was not complete, so the check that chains a write onto a revision this
daemon sealed did not apply either, and the write went up as a conflict copy of the file's own
create.
**Fix.** Landing a create remembers the placeholder's mtime and size with the revision the create
sealed. A base with no revision id and that stamp is read as that revision: its bytes are the ones
the create sent. The record goes once a later upload of the file lands, or the file is trashed.
**Verified:** `a_write_based_on_a_landed_create_placeholder_is_not_a_conflict` checks the
comparison. The race itself is not reproduced on demand; 40 local replays of the seed passed.
### 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)
+8 -2
View File
@@ -11,8 +11,9 @@ scratch (user data in `staging/` and `recovery/` is never touched by this).
## [Unreleased]
Schema: **49**. New tables save a mirror folder's walk of Proton Drive (48). A finished walk is
kept, with a list of the folders that changed on Proton Drive since (49).
Schema: **50**. New tables save a mirror folder's walk of Proton Drive (48). A finished walk is
kept, with a list of the folders that changed on Proton Drive since (49). Each mirror folder
counts the deletions it made in the last day (50).
### Added
- **`pdfs diagnostics` says which of the daemon's background services are running.** If one
@@ -44,6 +45,11 @@ kept, with a list of the folders that changed on Proton Drive since (49).
any more.
### Changed
- **Deletions in a mirror folder add up across passes.** A sync pass already refuses to delete
nearly every file of a folder at once. Now a folder lost a little at a time is stopped too:
once nine in ten of its synced files would have been deleted within a day, on either side,
the pass is refused and the folder shows the error. Emptying one large subfolder of a healthy
folder still goes through.
- **A sync pass over a large folder picks up where a restart stopped it.** A pass lists the
folder on Proton Drive before it changes anything, and on a folder of hundreds of thousands
of files that takes hours. A restart used to throw the listing away, so a large enough folder
+1 -1
View File
@@ -218,7 +218,7 @@ commands are for scripts and for cases where the mount is not available.
| Command | Description |
|---|---|
| `pdfs diagnose` | Check the installation and print a report. Works without the service. When the service does not answer, also asks Proton which of your keys open. Exits non-zero if a check fails. |
| `pdfs diagnostics` | What a running service is doing now: worker threads, queues, requests in flight, memory, and where each synced folder's last pass spent its time. For a service that has stopped answering, or a synced folder that never finishes. |
| `pdfs diagnostics` | What a running service is doing now: worker threads, queues, requests in flight, memory, how many background steps run and wait, and where each synced folder's last pass spent its time. For a service that has stopped answering, or a synced folder that never finishes. |
| `pdfs cache inspect [--deep]` | Database size, reclaimable space, row counts, cache use against the limit. `--deep` also runs SQLite's integrity check (slow). |
| `pdfs cache vacuum` | Compact the database. Needs free space for a second copy of it while it runs. |
| `pdfs cache clear` | Delete cached file content. Files kept available offline stay. |
+3 -1
View File
@@ -183,7 +183,9 @@ This section is for the curious and for anyone debugging a restore.
ones become conflict copies, as described above.
- **The wipe guard.** A sync pass in which every previously synced file has vanished locally is
refused instead of being mirrored to Proton Drive as a mass deletion. A folder that was emptied
by accident therefore does not empty the backup.
by accident therefore does not empty the backup. Deletions made over several passes add up:
once nine in ten of a folder's synced paths would have gone within a day, further deletions
are refused too.
- **The profile format.** Each profile carries a `version` field. A client refuses a profile
written by a newer, incompatible client instead of applying part of it.
+33 -1
View File
@@ -131,6 +131,11 @@ would refuse a user who empties one large folder on purpose. Left out, they woul
listing or an unmounted disk delete one subtree at a time. Both need a round-level guard
before planning can be split up.
That guard is the deletion window (`guard_delete_window`): a folder counts the deletions it made
in the last day against the most paths it tracked in that time, and refuses a pass that would
bring the count to nine tenths. It already covers a tree lost over several whole passes. Split
planning would add each step's deletions to the same count.
What is built:
- **Schema 48:** `sync_walk` (root, start time), `sync_walk_dir` (each folder found:
@@ -198,6 +203,26 @@ that grows into hours: it is network-bound, while the local walk only reads the
What a quiet pass still costs: loading the baseline and the picture from the database, and the
local walk. The local dirty set removes the local walk.
## Root reducer as built
The states above are first built as a check. `pdfs_sync::root` holds one reducer per mirror
folder. `step(state, input)` is pure: the passes, the watcher, the event stream and pause are
inputs, so a sequence of inputs replays exactly.
| State | Meaning |
|---|---|
| Discovering | No pass over the folder has finished yet. |
| Following | A pass covered the whole folder, and nothing since says a change went unreported. |
| Auditing | A doubt arrived: a watcher error, an overflowed queue, a gap in Drive's event stream, a restart or a suspension. Only a pass over the whole folder ends it. |
| Suspended | The local root is missing, or the folder is paused. |
| Draining | A switch to on-demand is queued, and passes only push. |
| HandedOff | The folder is on-demand. Going back to a mirror starts discovery again. |
Nothing acts on the state yet: every pass still covers the whole folder, so a finished pass
always returns the folder to Following. The engine logs each transition as `sync: root state`,
so the reducer can be compared with what the engine did. Once a Following folder plans from its
dirty sets alone, the state decides which passes must walk everything.
## Plan of work (separate PRs)
1. **Frontier checkpoint.**
@@ -205,7 +230,14 @@ local walk. The local dirty set removes the local walk.
- Left: per-subtree apply, once a round-level guard exists. A resumable local walk matters
less now that the local walk is the only full walk left, and is cheap next to Drive.
2. **Remote dirty set.** Done, described above.
3. **Local dirty set.** `SyncMsg::Dirty`, the `sync_dirty` table, overflow leading to FullCheck.
3. **Local dirty set.**
- Done, as a check: the watcher marks each path an event names in `LocalDirty` (in memory).
A pass claims the marks, and retires them once it applied everything it found. A claim is
trusted when the watch was live since the last pass claimed; a watcher error, an overflow or
a restart breaks that. Each pass still walks the whole folder, and counts the changes it
found that a trusted claim did not cover (`missed local changes` in the trace).
- Left: once that count stays at zero, a trusted claim stands in for the local walk, and
only the marked folders are read.
4. **Step scheduler.** Replace `run_burst` and the per-pass lock with steps and priorities.
5. **Drop the 120 s poll** for the daily audit, once 2 and 3 have run for a release with the
poll still on, and traces show the dirty sets catch everything the poll finds.
+17
View File
@@ -298,12 +298,29 @@ What the parts mean:
recorded. A high count here on a folder that has not changed is the slow case from B294. Each
pass records what it read, so the count falls on the next pass even if this one is cut short.
- **`slowest listing`** names the folder on Proton Drive that took longest to list.
- **`admission wait`** is the time uploads, downloads and folder creations spent waiting for
their turn before they started. The service runs at most 8 of them at once. A large
`admission wait` next to a small `upload` total means the work queued inside the service and
did not wait on Proton Drive. The `admission of background steps` lines in `pdfs diagnostics`
show how many steps run and wait right now, and how long the oldest one has waited.
- **`reused`** and **`dirty folders`:** once a pass has listed the whole folder on Proton Drive,
later passes start from that listing (`reused` paths) and list only the folders Proton Drive
reported a change in (`dirty folders`). A pass with no `reused` count listed everything. That
happens on the first pass, once a day, and after the daemon lost track of Proton Drive's
changes. **`resumed`** counts the paths a pass took from a listing that a restart cut short.
- **`unproven deletions`** counts deletions a pass planned for a path it had not proven gone,
and so did not make. It should never appear. If it does, the folder shows an error, the path
stays on both sides, and the journal has a `sync: not deleting a path whose absence is not
proven` line for each one; please report it with those lines.
- **`local dirty`** counts the places on disk the filesystem watcher reported changed since the
last pass. **`local dirty untrusted`** is 1 when the watch was not live the whole time since
then: after a start, a watch that failed, or an overflowed event queue. **`missed local
changes`** counts changes the pass found on disk that a trusted watch did not report. It
should stay at zero; the journal then has a `sync: the local dirty set missed changes the walk
found` line naming the first one. For now these only check the watcher: every pass still
walks the whole folder.
Please include these lines when you report a slow folder.
### Files named `(sync-conflict …)` appeared