mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-28 04:02:13 +01:00
Compare commits
91
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e12c747a0 | ||
|
|
f975d9cf17 | ||
|
|
deb15a3327 | ||
|
|
8c7a0a8a17 | ||
|
|
9533ebcdfc | ||
|
|
ccc679eef5 | ||
|
|
20603205d9 | ||
|
|
d1421a84b1 | ||
|
|
670ec7db31 | ||
|
|
30b20fc444 | ||
|
|
5c6360e6e7 | ||
|
|
42926b71a9 | ||
|
|
21e7c03460 | ||
|
|
9b541899ef | ||
|
|
8a5f3f9ae0 | ||
|
|
d0697b7fcc | ||
|
|
f32e1b2765 | ||
|
|
b43f46e582 | ||
|
|
d3b70f1ee6 | ||
|
|
30b6d27c74 | ||
|
|
d10b28b14f | ||
|
|
c25e17fa9f | ||
|
|
6c21a58acf | ||
|
|
ea29a260b0 | ||
|
|
8e9816919d | ||
|
|
90e9c0de26 | ||
|
|
61e0eefe3a | ||
|
|
7862fc9195 | ||
|
|
1c900f47bc | ||
|
|
a9adbf96ef | ||
|
|
bcdf78c44d | ||
|
|
413be9d961 | ||
|
|
0fd8dda0d5 | ||
|
|
4f542ae4d6 | ||
|
|
fb77dbda6a | ||
|
|
ef5f832b0f | ||
|
|
91fe76dbe1 | ||
|
|
1b64c37519 | ||
|
|
e74a36c57e | ||
|
|
7e8417b135 | ||
|
|
4ff217c721 | ||
|
|
620c3fd10f | ||
|
|
6bcef1281d | ||
|
|
b9f18180fe | ||
|
|
70259b5163 | ||
|
|
c1718b13a7 | ||
|
|
acf3bd40a5 | ||
|
|
e90979eb05 | ||
|
|
d3f6f0b155 | ||
|
|
4e96ae8c61 | ||
|
|
62cc85cb06 | ||
|
|
bba74b5e65 | ||
|
|
fd0fb66448 | ||
|
|
7d963b3dd7 | ||
|
|
b7af8ae6c2 | ||
|
|
5647b8e684 | ||
|
|
b6ce90fcd5 | ||
|
|
7adcdd250f | ||
|
|
7614ed6731 | ||
|
|
006b6f6926 | ||
|
|
251655548a | ||
|
|
59c6740137 | ||
|
|
ae633c2899 | ||
|
|
d14ed56b86 | ||
|
|
a13ca95a83 | ||
|
|
7978a40224 | ||
|
|
c44c1bccb5 | ||
|
|
275f40b24b | ||
|
|
695a810cea | ||
|
|
9dbb4c9950 | ||
|
|
c5884ba638 | ||
|
|
860593b655 | ||
|
|
4dcc2aa04e | ||
|
|
d891e24e96 | ||
|
|
957a7ff391 | ||
|
|
d9881810b7 | ||
|
|
d9dab26e86 | ||
|
|
eae7ce90d2 | ||
|
|
b674f3eb71 | ||
|
|
3a4812baae | ||
|
|
3da45c0bf9 | ||
|
|
dc72991da2 | ||
|
|
bdcabed1ee | ||
|
|
7def9e903b | ||
|
|
bb376d7dc4 | ||
|
|
57e654924a | ||
|
|
e3bc64df54 | ||
|
|
47576a389e | ||
|
|
7ed07e0056 | ||
|
|
be99fffe1b | ||
|
|
89b3fce38d |
No files matched your search
@@ -17,6 +17,9 @@ jobs:
|
||||
|
||||
- name: Install native dependencies
|
||||
run: |
|
||||
# The runner image lists Microsoft's apt repository, which nothing here
|
||||
# needs and which at times answers 403 and fails the update.
|
||||
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
pkg-config \
|
||||
@@ -80,6 +83,9 @@ jobs:
|
||||
|
||||
- name: Install native dependencies
|
||||
run: |
|
||||
# The runner image lists Microsoft's apt repository, which nothing here
|
||||
# needs and which at times answers 403 and fails the update.
|
||||
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
pkg-config \
|
||||
@@ -129,6 +135,9 @@ jobs:
|
||||
|
||||
- name: Install native dependencies
|
||||
run: |
|
||||
# The runner image lists Microsoft's apt repository, which nothing here
|
||||
# needs and which at times answers 403 and fails the update.
|
||||
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
pkg-config \
|
||||
|
||||
@@ -20,6 +20,9 @@ jobs:
|
||||
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
# The runner image lists Microsoft's apt repository, which nothing here
|
||||
# needs and which at times answers 403 and fails the update.
|
||||
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
pkg-config \
|
||||
@@ -75,6 +78,9 @@ jobs:
|
||||
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
# The runner image lists Microsoft's apt repository, which nothing here
|
||||
# needs and which at times answers 403 and fails the update.
|
||||
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
pkg-config \
|
||||
|
||||
Generated
+28
-4
@@ -3727,8 +3727,10 @@ dependencies = [
|
||||
"parking_lot 0.13.0",
|
||||
"pdfs-core",
|
||||
"pdfs-drive",
|
||||
"pdfs-sched",
|
||||
"pdfs-store",
|
||||
"pdfs-sync",
|
||||
"pdfs-vfs",
|
||||
"proton-drive-rs",
|
||||
"proton-gallery-app-rs",
|
||||
"proton-gallery-rs",
|
||||
@@ -3769,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"
|
||||
@@ -3793,6 +3803,7 @@ dependencies = [
|
||||
"parking_lot 0.13.0",
|
||||
"pdfs-core",
|
||||
"pdfs-drive",
|
||||
"pdfs-sched",
|
||||
"pdfs-store",
|
||||
"proton-drive-rs",
|
||||
"sha1 0.11.0",
|
||||
@@ -3800,6 +3811,19 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-vfs"
|
||||
version = "3.10.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"parking_lot 0.13.0",
|
||||
"pdfs-core",
|
||||
"pdfs-drive",
|
||||
"pdfs-store",
|
||||
"proton-drive-rs",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pem-rfc7468"
|
||||
version = "0.7.0"
|
||||
@@ -4047,9 +4071,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "proton-drive-rs"
|
||||
version = "0.12.6"
|
||||
version = "0.12.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b1a71d0e737a9bd6cff07105218e7bef3bddcfd9d6651646d7302cdbba71961"
|
||||
checksum = "11c09c245784d7253072b751e43b1919140fdbc8641c5328a7e2801889c86041"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.23.1",
|
||||
@@ -4167,9 +4191,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "proton-sdk"
|
||||
version = "0.12.6"
|
||||
version = "0.12.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "81edef2b4b174e936a3537793ee901b92dd7c0484eb7fed09ad69432f407f86b"
|
||||
checksum = "7a6ed261fbcabf35abe67ebf8c8aff85b01fc43aef5b298380a6e6f7d3dd31d3"
|
||||
dependencies = [
|
||||
"aes-gcm 0.11.1",
|
||||
"async-trait",
|
||||
|
||||
+5
-3
@@ -1,6 +1,6 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["crates/pdfs-core", "crates/pdfs-store", "crates/pdfs-drive", "crates/pdfs-sync", "crates/pdfs-fuse", "crates/pdfs-daemon", "crates/pdfs-cli", "crates/pdfs-gui"]
|
||||
members = ["crates/pdfs-core", "crates/pdfs-store", "crates/pdfs-drive", "crates/pdfs-sync", "crates/pdfs-sched", "crates/pdfs-vfs", "crates/pdfs-fuse", "crates/pdfs-daemon", "crates/pdfs-cli", "crates/pdfs-gui"]
|
||||
|
||||
[workspace.package]
|
||||
version = "3.10.0"
|
||||
@@ -15,8 +15,8 @@ keywords = ["proton", "drive", "fuse", "sync", "linux"]
|
||||
categories = ["filesystem", "command-line-utilities"]
|
||||
|
||||
[workspace.dependencies]
|
||||
proton-sdk = { version = "0.12.6" }
|
||||
proton-drive-rs = { version = "0.12.6" }
|
||||
proton-sdk = { version = "0.12.8" }
|
||||
proton-drive-rs = { version = "0.12.8" }
|
||||
proton-gallery-app-rs = "0.1.0"
|
||||
proton-gallery-rs = "0.1.5"
|
||||
proton-map-rs = "0.1.0"
|
||||
@@ -27,6 +27,8 @@ pdfs-core = { path = "crates/pdfs-core" }
|
||||
pdfs-store = { path = "crates/pdfs-store" }
|
||||
pdfs-drive = { path = "crates/pdfs-drive" }
|
||||
pdfs-sync = { path = "crates/pdfs-sync" }
|
||||
pdfs-vfs = { path = "crates/pdfs-vfs" }
|
||||
pdfs-sched = { path = "crates/pdfs-sched" }
|
||||
pdfs-fuse = { path = "crates/pdfs-fuse" }
|
||||
pdfs-daemon = { path = "crates/pdfs-daemon" }
|
||||
|
||||
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -278,6 +278,12 @@ pub struct AppConfig {
|
||||
/// the field.
|
||||
#[serde(default)]
|
||||
pub local_first: Option<bool>,
|
||||
/// Send a file small enough, with its thumbnails, to fit 128 KiB in one
|
||||
/// request instead of three or more. `None` means on. `false` uploads
|
||||
/// every file in blocks, the way all files went before. Defaulted for
|
||||
/// configs predating the field.
|
||||
#[serde(default)]
|
||||
pub small_uploads: Option<bool>,
|
||||
/// Ask GitHub once a day whether a newer release is out, and say so in the
|
||||
/// desktop app. Off by default: GitHub then sees the address and version
|
||||
/// asking. Never used where a package manager installs updates (see
|
||||
@@ -1077,6 +1083,7 @@ mod tests {
|
||||
language: Some("de".to_string()),
|
||||
online_map: true,
|
||||
local_first: Some(false),
|
||||
small_uploads: Some(false),
|
||||
update_check: true,
|
||||
update_last_checked: Some(1_760_000_000),
|
||||
update_latest: Some("3.6.0".to_string()),
|
||||
@@ -1096,6 +1103,7 @@ mod tests {
|
||||
assert_eq!(decoded.update_latest.as_deref(), Some("3.6.0"));
|
||||
assert_eq!(decoded.language.as_deref(), Some("de"));
|
||||
assert_eq!(decoded.upload_limit, Some(500_000));
|
||||
assert_eq!(decoded.small_uploads, Some(false));
|
||||
assert_eq!(decoded.download_limit, None);
|
||||
assert_eq!(decoded.files_view, config.files_view);
|
||||
assert_eq!(decoded.photos_view, config.photos_view);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -21,7 +21,10 @@
|
||||
//!
|
||||
//! Work a request starts and does not wait for runs as a one-shot job
|
||||
//! ([`ServiceBoard::spawn_job`] on a thread, [`ServiceBoard::spawn_task_job`]
|
||||
//! on the runtime): listed on the board while it runs, and not joined on stop.
|
||||
//! on the runtime): listed on the board while it runs. A stop closes the
|
||||
//! board to new jobs, aborts the async ones and joins the rest up to the same
|
||||
//! deadline as the services. A job used to be left running, and one still
|
||||
//! waiting on Drive when the runtime went away panicked on its next timer.
|
||||
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
@@ -36,6 +39,32 @@ use crate::shutdown::Shutdown;
|
||||
/// Wakes a thread that blocks somewhere a [`Shutdown::stop`] alone does not reach.
|
||||
pub type Wake = Box<dyn Fn() + Send + Sync>;
|
||||
|
||||
/// A long-lived loop a mount runs on a thread of its own.
|
||||
///
|
||||
/// Each one says in one place what it is called, how a stop reaches it and
|
||||
/// whether the mount can do without it, next to the loop itself. The mount
|
||||
/// starts a list of them with [`Services::start`] instead of spelling out
|
||||
/// each spawn, wake and failure path.
|
||||
pub trait Service: Send + 'static {
|
||||
/// The thread's name, such as `pdfs-sync`.
|
||||
fn name(&self) -> String;
|
||||
|
||||
/// Whether a mount fails when this cannot start. An optional service is
|
||||
/// logged and skipped: the mount works without it, only less well.
|
||||
fn required(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The call that wakes the loop on a stop, for one that blocks where the
|
||||
/// [`Shutdown`] signal does not reach: a condvar, a channel, an `accept`.
|
||||
fn wake(&self) -> Option<Wake> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Run the loop until the [`Shutdown`] signal or the wake ends it.
|
||||
fn run(self: Box<Self>);
|
||||
}
|
||||
|
||||
/// Whether one service thread is still running, for diagnostics.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ServiceHealth {
|
||||
@@ -57,6 +86,28 @@ struct Board {
|
||||
services: Mutex<Vec<Entry>>,
|
||||
jobs: Mutex<Vec<Job>>,
|
||||
next_job: AtomicU64,
|
||||
/// The running jobs' handles, and whether a stop closed the board. One
|
||||
/// lock for both, so a job is either refused or joined by the stop.
|
||||
handles: Mutex<JobHandles>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct JobHandles {
|
||||
closed: bool,
|
||||
running: Vec<Handle>,
|
||||
}
|
||||
|
||||
impl JobHandles {
|
||||
/// Keep `handle`, dropping the handles of jobs that already ended.
|
||||
fn keep(&mut self, handle: Handle) {
|
||||
self.running.retain(|handle| !handle.is_finished());
|
||||
self.running.push(handle);
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a job did not start: the board's mount is stopping.
|
||||
fn closed_error() -> std::io::Error {
|
||||
std::io::Error::other("the mount is stopping; no new jobs start")
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
@@ -106,37 +157,69 @@ impl ServiceBoard {
|
||||
/// folder pin. It shows in [`jobs`](Self::jobs) until it ends, by return
|
||||
/// or by panic.
|
||||
///
|
||||
/// Not joined on stop. A job's work is either safe to cut short (the
|
||||
/// process exits) or bounded by the deadlines of the calls it makes.
|
||||
/// A stop joins it up to its deadline; a job that may run long checks the
|
||||
/// [`Shutdown`] signal. Once a stop has begun, no job starts and this
|
||||
/// returns an error.
|
||||
pub fn spawn_job<F>(&self, name: &str, run: F) -> std::io::Result<()>
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
{
|
||||
let mut handles = self.0.handles.lock();
|
||||
if handles.closed {
|
||||
return Err(closed_error());
|
||||
}
|
||||
let guard = self.add_job(name);
|
||||
std::thread::Builder::new()
|
||||
let handle = std::thread::Builder::new()
|
||||
.name(name.to_owned())
|
||||
.spawn(move || {
|
||||
let _guard = guard;
|
||||
run();
|
||||
})
|
||||
// On an error the closure, and the guard in it, are already
|
||||
// dropped, so the job is off the list.
|
||||
.map(|_| ())
|
||||
})?;
|
||||
// On an error the closure, and the guard in it, are already dropped,
|
||||
// so the job is off the list.
|
||||
handles.keep(Handle::Thread(handle));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start `task` on `rt` as a one-shot job, like [`spawn_job`](Self::spawn_job)
|
||||
/// for work that is async: a refresh a listing starts and does not wait
|
||||
/// for. It shows in [`jobs`](Self::jobs) until it ends, by return, panic
|
||||
/// or the runtime going away.
|
||||
/// or abort. A stop aborts it at its next `.await`; once a stop has begun,
|
||||
/// `task` is dropped without running.
|
||||
pub fn spawn_task_job<F>(&self, rt: &tokio::runtime::Handle, name: &str, task: F)
|
||||
where
|
||||
F: Future<Output = ()> + Send + 'static,
|
||||
{
|
||||
let mut handles = self.0.handles.lock();
|
||||
if handles.closed {
|
||||
tracing::debug!(job = name, "not started: the mount is stopping");
|
||||
return;
|
||||
}
|
||||
let guard = self.add_job(name);
|
||||
rt.spawn(async move {
|
||||
let task = rt.spawn(async move {
|
||||
let _guard = guard;
|
||||
task.await;
|
||||
});
|
||||
handles.keep(Handle::Task {
|
||||
name: name.to_owned(),
|
||||
task,
|
||||
});
|
||||
}
|
||||
|
||||
/// Close the board to new jobs and abort the async ones. The thread jobs
|
||||
/// still running are handed back for [`join`](Handle::join_until).
|
||||
fn close(&self) -> Vec<Handle> {
|
||||
let running = {
|
||||
let mut handles = self.0.handles.lock();
|
||||
handles.closed = true;
|
||||
std::mem::take(&mut handles.running)
|
||||
};
|
||||
for handle in &running {
|
||||
if let Handle::Task { task, .. } = handle {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
running
|
||||
}
|
||||
|
||||
fn add_job(&self, name: &str) -> JobGuard {
|
||||
@@ -184,7 +267,7 @@ impl Drop for Running {
|
||||
}
|
||||
}
|
||||
|
||||
struct Service {
|
||||
struct Started {
|
||||
handle: Handle,
|
||||
wake: Option<Wake>,
|
||||
}
|
||||
@@ -205,12 +288,25 @@ impl Handle {
|
||||
Handle::Task { task, .. } => task.is_finished(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for the thread or task to end, up to `deadline`, and name it if
|
||||
/// it is still running then.
|
||||
fn join_until(self, deadline: Instant) -> Option<String> {
|
||||
while !self.is_finished() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
match self {
|
||||
Handle::Thread(handle) => join_until([handle], deadline).pop(),
|
||||
Handle::Task { name, task } if !task.is_finished() => Some(name),
|
||||
Handle::Task { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The service threads one mount started, and how to stop them.
|
||||
pub struct Services {
|
||||
board: ServiceBoard,
|
||||
started: Vec<Service>,
|
||||
started: Vec<Started>,
|
||||
}
|
||||
|
||||
impl Services {
|
||||
@@ -239,7 +335,7 @@ impl Services {
|
||||
});
|
||||
match spawned {
|
||||
Ok(handle) => {
|
||||
self.started.push(Service {
|
||||
self.started.push(Started {
|
||||
handle: Handle::Thread(handle),
|
||||
wake,
|
||||
});
|
||||
@@ -253,6 +349,21 @@ impl Services {
|
||||
}
|
||||
}
|
||||
|
||||
/// Start `service` on a thread of its own. A required service that cannot
|
||||
/// start returns the error; an optional one is logged and skipped.
|
||||
pub fn start(&mut self, service: Box<dyn Service>) -> std::io::Result<()> {
|
||||
let name = service.name();
|
||||
let required = service.required();
|
||||
let wake = service.wake();
|
||||
match self.spawn(&name, wake, move || service.run()) {
|
||||
Err(error) if !required => {
|
||||
tracing::warn!(service = name, %error, "optional service did not start");
|
||||
Ok(())
|
||||
}
|
||||
started => started,
|
||||
}
|
||||
}
|
||||
|
||||
/// Start `task` on `rt` as a service named `name`. [`stop`](Self::stop)
|
||||
/// aborts it, so it ends at its next `.await`; a task does not need to
|
||||
/// watch the [`Shutdown`] signal itself. Code between two `.await`s runs
|
||||
@@ -266,7 +377,7 @@ impl Services {
|
||||
let _guard = guard;
|
||||
task.await;
|
||||
});
|
||||
self.started.push(Service {
|
||||
self.started.push(Started {
|
||||
handle: Handle::Task {
|
||||
name: name.to_owned(),
|
||||
task,
|
||||
@@ -285,12 +396,15 @@ impl Services {
|
||||
self.started.is_empty()
|
||||
}
|
||||
|
||||
/// Stop every service: signal `shutdown`, wake each thread and abort each
|
||||
/// task in reverse start order, then join them in the same order until
|
||||
/// `deadline`. Returns the names of the services still running at the
|
||||
/// deadline; they are left behind rather than waited for.
|
||||
/// Stop every service and every job: signal `shutdown`, close the board
|
||||
/// to new jobs, wake each thread and abort each task in reverse start
|
||||
/// order. Then join the jobs, which are the services' clients, and the
|
||||
/// services in the same reverse order, all until `deadline`. Returns the
|
||||
/// names of the services and jobs still running at the deadline; they are
|
||||
/// left behind rather than waited for.
|
||||
pub fn stop(self, shutdown: &Shutdown, deadline: Instant) -> Vec<String> {
|
||||
shutdown.stop();
|
||||
let jobs = self.board.close();
|
||||
for service in self.started.iter().rev() {
|
||||
if let Some(wake) = &service.wake {
|
||||
wake();
|
||||
@@ -299,18 +413,13 @@ impl Services {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
let mut running = Vec::new();
|
||||
for service in self.started.into_iter().rev() {
|
||||
while !service.handle.is_finished() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
match service.handle {
|
||||
Handle::Thread(handle) => running.extend(join_until([handle], deadline)),
|
||||
Handle::Task { name, task } if !task.is_finished() => running.push(name),
|
||||
Handle::Task { .. } => {}
|
||||
}
|
||||
}
|
||||
running
|
||||
let jobs = jobs.into_iter().filter_map(|job| job.join_until(deadline));
|
||||
let services = self
|
||||
.started
|
||||
.into_iter()
|
||||
.rev()
|
||||
.filter_map(|service| service.handle.join_until(deadline));
|
||||
jobs.chain(services).collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -531,4 +640,102 @@ mod tests {
|
||||
}
|
||||
assert!(board.jobs().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stop_joins_the_running_jobs_and_names_a_stuck_one() {
|
||||
let board = ServiceBoard::default();
|
||||
let shutdown = Arc::new(Shutdown::default());
|
||||
let services = Services::new(board.clone());
|
||||
let signalled = shutdown.clone();
|
||||
board
|
||||
.spawn_job("pdfs-test-polite", move || {
|
||||
while signalled.sleep(Duration::from_secs(3600)) {}
|
||||
})
|
||||
.unwrap();
|
||||
let (_hold, stuck) = mpsc::channel::<()>();
|
||||
board
|
||||
.spawn_job("pdfs-test-stuck", move || {
|
||||
let _ = stuck.recv();
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let left = services.stop(&shutdown, Instant::now() + Duration::from_millis(300));
|
||||
|
||||
assert_eq!(left, ["pdfs-test-stuck"]);
|
||||
let jobs: Vec<_> = board.jobs().into_iter().map(|job| job.name).collect();
|
||||
assert_eq!(jobs, ["pdfs-test-stuck"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stop_aborts_a_task_job_and_refuses_new_jobs() {
|
||||
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(1)
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let board = ServiceBoard::default();
|
||||
let services = Services::new(board.clone());
|
||||
board.spawn_task_job(rt.handle(), "pdfs-test-poller", async {
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
});
|
||||
|
||||
let left = services.stop(
|
||||
&Shutdown::default(),
|
||||
Instant::now() + Duration::from_secs(5),
|
||||
);
|
||||
|
||||
assert!(left.is_empty(), "still running: {left:?}");
|
||||
assert!(board.jobs().is_empty());
|
||||
assert!(board.spawn_job("pdfs-test-late", || {}).is_err());
|
||||
board.spawn_task_job(rt.handle(), "pdfs-test-late", async {});
|
||||
assert!(board.jobs().is_empty(), "a job started after the stop");
|
||||
}
|
||||
|
||||
struct Waiter {
|
||||
name: &'static str,
|
||||
rx: mpsc::Receiver<()>,
|
||||
tx: mpsc::Sender<()>,
|
||||
}
|
||||
|
||||
impl Service for Waiter {
|
||||
fn name(&self) -> String {
|
||||
self.name.to_owned()
|
||||
}
|
||||
|
||||
fn wake(&self) -> Option<Wake> {
|
||||
let tx = self.tx.clone();
|
||||
Some(Box::new(move || {
|
||||
let _ = tx.send(());
|
||||
}))
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
let _ = self.rx.recv();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_started_service_is_woken_and_joined_by_a_stop() {
|
||||
let board = ServiceBoard::default();
|
||||
let mut services = Services::new(board.clone());
|
||||
let (tx, rx) = mpsc::channel();
|
||||
services
|
||||
.start(Box::new(Waiter {
|
||||
name: "pdfs-test-waiter",
|
||||
rx,
|
||||
tx,
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(board.health()[0].name, "pdfs-test-waiter");
|
||||
|
||||
let left = services.stop(
|
||||
&Shutdown::default(),
|
||||
Instant::now() + Duration::from_secs(5),
|
||||
);
|
||||
|
||||
assert!(left.is_empty(), "still running: {left:?}");
|
||||
assert!(!board.health()[0].running);
|
||||
}
|
||||
}
|
||||
@@ -363,6 +363,19 @@ pub enum Verdict {
|
||||
/// Compiled ignore rules for one synced folder.
|
||||
pub struct IgnoreRules {
|
||||
matcher: Option<Gitignore>,
|
||||
/// A hash of the patterns the rules were built from, so a caller can tell
|
||||
/// whether they changed.
|
||||
source: u64,
|
||||
}
|
||||
|
||||
/// A hash of `globals` and the folder's ignore file, `file` (its name and
|
||||
/// text), in the order [`IgnoreRules::load`] reads them.
|
||||
fn rules_source(globals: &[String], file: Option<(&str, &[u8])>) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
globals.hash(&mut hasher);
|
||||
file.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
impl IgnoreRules {
|
||||
@@ -382,6 +395,7 @@ impl IgnoreRules {
|
||||
}
|
||||
}
|
||||
|
||||
let mut file = None;
|
||||
for name in IGNORE_FILE_NAMES {
|
||||
let path = root.join(name);
|
||||
if !path.is_file() {
|
||||
@@ -390,15 +404,24 @@ impl IgnoreRules {
|
||||
// `add` returns the first parse error but still takes the lines it
|
||||
// could read, so a bad line costs that line and nothing more.
|
||||
let _ = builder.add(&path);
|
||||
file = Some((*name, std::fs::read(&path).unwrap_or_default()));
|
||||
any = true;
|
||||
break;
|
||||
}
|
||||
let source = rules_source(
|
||||
globals,
|
||||
file.as_ref().map(|(name, text)| (*name, text.as_slice())),
|
||||
);
|
||||
|
||||
if !any {
|
||||
return Self { matcher: None };
|
||||
return Self {
|
||||
matcher: None,
|
||||
source,
|
||||
};
|
||||
}
|
||||
Self {
|
||||
matcher: builder.build().ok(),
|
||||
source,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -415,17 +438,32 @@ impl IgnoreRules {
|
||||
for line in text.lines() {
|
||||
any |= builder.add_line(Some(file.clone()), line).is_ok();
|
||||
}
|
||||
let source = rules_source(globals, Some((IGNORE_FILE_NAMES[0], text.as_bytes())));
|
||||
if !any {
|
||||
return Self { matcher: None };
|
||||
return Self {
|
||||
matcher: None,
|
||||
source,
|
||||
};
|
||||
}
|
||||
Self {
|
||||
matcher: builder.build().ok(),
|
||||
source,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rules matching nothing, for callers with no folder context.
|
||||
pub fn empty() -> Self {
|
||||
Self { matcher: None }
|
||||
Self {
|
||||
matcher: None,
|
||||
source: rules_source(&[], None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifies the patterns these rules were built from: rules loaded
|
||||
/// again from the same globals and the same ignore file give the same
|
||||
/// value. Only for comparing within one run of the daemon.
|
||||
pub fn source(&self) -> u64 {
|
||||
self.source
|
||||
}
|
||||
|
||||
/// Whether any rule is loaded. When false, [`is_ignored`](Self::is_ignored)
|
||||
|
||||
@@ -241,6 +241,13 @@ pub fn mount_once(mountpoint: Option<PathBuf>) -> Result<pdfs_fuse::MountOutcome
|
||||
let (client, session) = rt
|
||||
.block_on(auth::resume_client())
|
||||
.context("resume session (run `pdfs login` first)")?;
|
||||
// On unless the config turns it off: the one-request upload for small
|
||||
// files is new, and this lets it be switched off without a new build.
|
||||
let small_uploads = config.small_uploads.unwrap_or(true);
|
||||
if !small_uploads {
|
||||
tracing::info!("small files are uploaded in blocks: small_uploads is off in the config");
|
||||
}
|
||||
let client = client.with_small_file_upload(small_uploads);
|
||||
|
||||
// Token updates are persisted automatically in real-time. The SDK session has
|
||||
// a token refresh callback registered during `resume_client` that writes updated
|
||||
|
||||
@@ -23,7 +23,7 @@ use proton_drive_rs::{
|
||||
Thumbnail, ThumbnailType, TrashedNode,
|
||||
};
|
||||
|
||||
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
|
||||
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead, RevisionUpload};
|
||||
|
||||
/// Every kind of call [`DriveApi`] makes, one per method.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -393,6 +393,30 @@ impl DriveApi for Counted {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn upload_new_revision_over_dyn(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
expected: &str,
|
||||
reader: &mut (dyn Read + Send),
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<RevisionUpload> {
|
||||
// Counted with the other revision uploads: it is one, with its check.
|
||||
self.timed(
|
||||
DriveCall::UploadNewRevision,
|
||||
self.inner.upload_new_revision_over_dyn(
|
||||
file_uid,
|
||||
expected,
|
||||
reader,
|
||||
intended_size,
|
||||
thumbnails,
|
||||
last_modification_time,
|
||||
),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
|
||||
self.timed(DriveCall::OpenRevision, self.inner.open_revision(uid))
|
||||
.await
|
||||
|
||||
@@ -33,6 +33,8 @@ use proton_drive_rs::{
|
||||
NodeMoveItem, ProtonDriveClient, RevisionReader, Thumbnail, ThumbnailType, TrashedNode,
|
||||
};
|
||||
|
||||
pub use proton_drive_rs::{RevisionUpload, SealedUpload};
|
||||
|
||||
pub mod counted;
|
||||
pub mod digest;
|
||||
|
||||
@@ -120,6 +122,18 @@ pub trait DriveApi: Send + Sync {
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<()>;
|
||||
|
||||
/// A new revision of `file_uid`, only over the revision `expected`. See
|
||||
/// [`ProtonDriveClient::upload_new_revision_over`].
|
||||
async fn upload_new_revision_over_dyn(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
expected: &str,
|
||||
reader: &mut (dyn Read + Send),
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<RevisionUpload>;
|
||||
|
||||
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>>;
|
||||
|
||||
/// The file's thumbnail of `thumbnail_type`, or `None` when its revision
|
||||
@@ -287,6 +301,26 @@ impl dyn DriveApi {
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn upload_new_revision_over<R: Read + Send>(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
expected: &str,
|
||||
mut reader: R,
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<RevisionUpload> {
|
||||
self.upload_new_revision_over_dyn(
|
||||
file_uid,
|
||||
expected,
|
||||
&mut reader,
|
||||
intended_size,
|
||||
thumbnails,
|
||||
last_modification_time,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn download_file_to<W: Write + Send>(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
@@ -468,6 +502,27 @@ impl DriveApi for ProtonDriveClient {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn upload_new_revision_over_dyn(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
expected: &str,
|
||||
reader: &mut (dyn Read + Send),
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<RevisionUpload> {
|
||||
ProtonDriveClient::upload_new_revision_over(
|
||||
self,
|
||||
file_uid,
|
||||
expected,
|
||||
reader,
|
||||
intended_size,
|
||||
thumbnails,
|
||||
last_modification_time.and_then(pdfs_core::timestamp::modification_time),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
|
||||
let reader = ProtonDriveClient::open_revision(self, uid).await?;
|
||||
Ok(Arc::new(reader))
|
||||
@@ -599,6 +654,19 @@ pub fn is_network_error(e: &ProtonError) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// A node's plaintext size as far as its listing knows: the claimed size when
|
||||
/// the revision carries one, else the size on storage. Zero for a folder.
|
||||
pub fn node_size(node: &Node) -> u64 {
|
||||
match &node.kind {
|
||||
NodeKind::Folder => 0,
|
||||
NodeKind::File {
|
||||
claimed_size,
|
||||
total_size_on_storage,
|
||||
..
|
||||
} => claimed_size.unwrap_or(*total_size_on_storage).max(0) as u64,
|
||||
}
|
||||
}
|
||||
|
||||
/// The server revision id of a node's active revision, if it is a file that has
|
||||
/// one. The stable identity the drain conflict-checks against (see `Baseline` in pdfs-store).
|
||||
pub fn node_revision_id(node: &Node) -> Option<String> {
|
||||
|
||||
@@ -67,7 +67,7 @@ use proton_drive_rs::{
|
||||
use sha1::{Digest as _, Sha1};
|
||||
|
||||
use super::rng::Rng;
|
||||
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
|
||||
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead, RevisionUpload, SealedUpload};
|
||||
|
||||
/// The volume every fake node lives on.
|
||||
pub const VOLUME: &str = "simvol";
|
||||
@@ -1531,6 +1531,57 @@ impl DriveApi for FakeClient {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn upload_new_revision_over_dyn(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
expected: &str,
|
||||
reader: &mut (dyn Read + Send),
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<RevisionUpload> {
|
||||
// The SDK reads the file's link for its keys and checks the revision
|
||||
// on that read, so it is held, lags and counts like any other read.
|
||||
self.wait_if_held(&self.0.hold, std::slice::from_ref(file_uid))
|
||||
.await;
|
||||
let lag = self.lag();
|
||||
let seen = self
|
||||
.request(false, |server| {
|
||||
Ok(server
|
||||
.visible(file_uid, lag, Instant::now())
|
||||
.map(|remote| (remote.trashed, remote.file.map(|file| file.revision))))
|
||||
})
|
||||
.await?;
|
||||
match seen {
|
||||
None => return Err(api(ResponseCode::DoesNotExist, "file not found")),
|
||||
Some((true, _)) => return Ok(RevisionUpload::Trashed),
|
||||
Some((false, revision)) if revision.as_deref() != Some(expected) => {
|
||||
return Ok(RevisionUpload::Moved);
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
self.upload_new_revision_from_dyn(
|
||||
file_uid,
|
||||
reader,
|
||||
intended_size,
|
||||
thumbnails,
|
||||
last_modification_time,
|
||||
)
|
||||
.await?;
|
||||
let revision_id = self
|
||||
.0
|
||||
.drive
|
||||
.server
|
||||
.lock()
|
||||
.current(file_uid)
|
||||
.and_then(|remote| remote.file.as_ref().map(|file| file.revision.clone()))
|
||||
.unwrap_or_default();
|
||||
Ok(RevisionUpload::Sealed(SealedUpload {
|
||||
node_uid: file_uid.clone(),
|
||||
revision_id,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
|
||||
let file = self
|
||||
.request(false, |server| {
|
||||
|
||||
@@ -13,6 +13,8 @@ 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
|
||||
sha1.workspace = true
|
||||
@@ -41,6 +43,7 @@ notify = "8"
|
||||
parking_lot.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
pdfs-vfs = { workspace = true, features = ["test-support"] }
|
||||
pdfs-drive = { workspace = true, features = ["sim"] }
|
||||
tracing-subscriber.workspace = true
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
@@ -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 {
|
||||
|
||||
@@ -771,15 +771,18 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
|
||||
query,
|
||||
limit,
|
||||
scope,
|
||||
}) => match core.search(&query, clamp_limit(limit), scope.as_deref()) {
|
||||
}) => match core
|
||||
.searcher()
|
||||
.search(&query, clamp_limit(limit), scope.as_deref())
|
||||
{
|
||||
Ok(hits) => CtlResponse::SearchResults { hits },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
Ok(CtlRequest::SearchLocal { query, limit }) => {
|
||||
match core.search_local(&query, clamp_limit(limit)) {
|
||||
match core.searcher().search_local(&query, clamp_limit(limit)) {
|
||||
Ok(hits) => CtlResponse::LocalResults {
|
||||
hits,
|
||||
indexing: core.indexing.load(Ordering::Relaxed),
|
||||
indexing: core.searcher().indexing(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
@@ -788,11 +791,14 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
|
||||
query,
|
||||
limit,
|
||||
filters,
|
||||
}) => match core.search_v2(&query, clamp_limit(limit), &filters) {
|
||||
}) => match core
|
||||
.searcher()
|
||||
.search_v2(&query, clamp_limit(limit), &filters)
|
||||
{
|
||||
Ok((drive_hits, local_hits)) => CtlResponse::SearchResultsV2 {
|
||||
drive_hits,
|
||||
local_hits,
|
||||
local_indexing: core.indexing.load(Ordering::Relaxed),
|
||||
local_indexing: core.searcher().indexing(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
@@ -1104,13 +1110,13 @@ pub(crate) fn run_control_socket(
|
||||
let core = core.clone();
|
||||
let username = username.clone();
|
||||
let mountpoint = mountpoint.clone();
|
||||
if let Err(e) = std::thread::Builder::new()
|
||||
.name("pdfs-control".into())
|
||||
.spawn(move || {
|
||||
let _permit = permit;
|
||||
handle_control_conn(&core, &username, &mountpoint, stream);
|
||||
})
|
||||
{
|
||||
// A job, so a stop joins it; a subscription ends on the
|
||||
// stop's wake (`EventHub::wake_all`).
|
||||
let board = core.services.clone();
|
||||
if let Err(e) = board.spawn_job("pdfs-control-conn", move || {
|
||||
let _permit = permit;
|
||||
handle_control_conn(&core, &username, &mountpoint, stream);
|
||||
}) {
|
||||
warn!(error = %e, "control: spawn handler failed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,12 +130,26 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
},
|
||||
CtlRequest::RemoveSyncFolder { id, delete_remote } => {
|
||||
match core.remove_sync_folder(id, delete_remote) {
|
||||
Ok(()) => {
|
||||
Ok(None) => {
|
||||
core.profile().touch_profile();
|
||||
CtlResponse::Ok {
|
||||
message: "removed synced folder".to_string(),
|
||||
message: if delete_remote {
|
||||
"removed synced folder and moved its folder in Proton Drive to the trash"
|
||||
} else {
|
||||
"removed synced folder"
|
||||
}
|
||||
.to_string(),
|
||||
}
|
||||
}
|
||||
// The folder no longer syncs, but its copy in Proton Drive is
|
||||
// still there. That is not what was asked, so it is an error,
|
||||
// and the message says which half happened.
|
||||
Ok(Some(trash_error)) => {
|
||||
core.profile().touch_profile();
|
||||
CtlResponse::error(CoreError::remote(format!(
|
||||
"stopped syncing the folder, but its folder in Proton Drive was not moved to the trash: {trash_error}"
|
||||
)))
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
// problems found" and "never looked" are both an empty list;
|
||||
// `integrity_running` says a fresh answer is on its way.
|
||||
let (integrity_problems, integrity_checked, integrity_running) = if deep {
|
||||
core.start_or_read_integrity_check()
|
||||
core.maintenance.start_or_read_integrity_check()
|
||||
} else {
|
||||
(Vec::new(), false, false)
|
||||
};
|
||||
@@ -106,7 +106,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
}
|
||||
Err(e) => CtlResponse::error(CoreError::internal(format!("read db stats: {e:?}"))),
|
||||
},
|
||||
CtlRequest::CacheVacuum => match core.start_vacuum() {
|
||||
CtlRequest::CacheVacuum => match core.maintenance.start_vacuum() {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: "compacting the cache database in the background".into(),
|
||||
},
|
||||
|
||||
@@ -765,9 +765,18 @@ impl Core {
|
||||
jobs
|
||||
}
|
||||
|
||||
/// Remove a synced folder from the sync set. `delete_remote` also deletes its
|
||||
/// folder under the device root; otherwise the cloud copy is left in place.
|
||||
pub(crate) fn remove_sync_folder(&self, id: i64, delete_remote: bool) -> CoreResult<()> {
|
||||
/// Remove a synced folder from the sync set. `delete_remote` also moves its
|
||||
/// folder under the device root to the trash; otherwise the cloud copy is
|
||||
/// left in place.
|
||||
///
|
||||
/// The folder is out of the sync set before the trash is asked, so a trash
|
||||
/// that fails does not fail the removal. It comes back as `Some(error)`,
|
||||
/// for the caller to say that the cloud copy is still there.
|
||||
pub(crate) fn remove_sync_folder(
|
||||
&self,
|
||||
id: i64,
|
||||
delete_remote: bool,
|
||||
) -> CoreResult<Option<String>> {
|
||||
let lock = self.sync.lock(id);
|
||||
// A pass holds the lock for as long as it runs, hours on a large
|
||||
// folder. Ask it to stop at its next checkpoint rather than wait it
|
||||
@@ -823,16 +832,24 @@ impl Core {
|
||||
self.clear_sync_folder_paused(id);
|
||||
// Stop watching the folder we just dropped.
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
|
||||
if delete_remote
|
||||
&& let Some(uid) = parse_uid(&folder.remote_uid)
|
||||
&& let Err(e) = self
|
||||
.rt
|
||||
.block_on(self.drive.trash_nodes(&[uid]))
|
||||
.and_then(batch::into_unit)
|
||||
if !delete_remote {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(uid) = parse_uid(&folder.remote_uid) else {
|
||||
warn!(id, remote = %folder.remote_uid, "delete remote device folder: bad uid");
|
||||
return Ok(Some(format!("bad folder id {}", folder.remote_uid)));
|
||||
};
|
||||
match self
|
||||
.rt
|
||||
.block_on(self.drive.trash_nodes(&[uid]))
|
||||
.and_then(batch::into_unit)
|
||||
{
|
||||
warn!(id, error = %e, "delete remote device folder failed");
|
||||
Ok(()) => Ok(None),
|
||||
Err(e) => {
|
||||
warn!(id, error = %e, "delete remote device folder failed");
|
||||
Ok(Some(e.to_string()))
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Trigger a reconcile: one folder by id, or every folder when `id` is `None`.
|
||||
|
||||
@@ -18,7 +18,11 @@ 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;
|
||||
|
||||
use super::Core;
|
||||
|
||||
@@ -196,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(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,18 +226,28 @@ impl Core {
|
||||
/// is not started until the first one has returned.
|
||||
fn pending_ops_quickly(&self) -> Option<u64> {
|
||||
let db = self.db.clone();
|
||||
probe_once(&self.pending_probe, PENDING_COUNT_DEADLINE, move || {
|
||||
let counts = db.pending_op_counts().ok()?;
|
||||
Some(counts.uploads.max(0) as u64 + counts.changes.max(0) as u64)
|
||||
})
|
||||
probe_once(
|
||||
&self.services,
|
||||
&self.pending_probe,
|
||||
PENDING_COUNT_DEADLINE,
|
||||
move || {
|
||||
let counts = db.pending_op_counts().ok()?;
|
||||
Some(counts.uploads.max(0) as u64 + counts.changes.max(0) as u64)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
/// `busy` has not returned yet: then no new thread is started at all.
|
||||
fn probe_once<T: Send + 'static>(
|
||||
board: &ServiceBoard,
|
||||
busy: &Arc<AtomicBool>,
|
||||
deadline: Duration,
|
||||
probe: impl FnOnce() -> Option<T> + Send + 'static,
|
||||
@@ -228,13 +257,11 @@ fn probe_once<T: Send + 'static>(
|
||||
}
|
||||
let done = Arc::clone(busy);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("pdfs-diagnostics".into())
|
||||
.spawn(move || {
|
||||
let answer = probe();
|
||||
done.store(false, Ordering::Release);
|
||||
let _ = tx.send(answer);
|
||||
});
|
||||
let spawned = board.spawn_job("pdfs-diagnostics", move || {
|
||||
let answer = probe();
|
||||
done.store(false, Ordering::Release);
|
||||
let _ = tx.send(answer);
|
||||
});
|
||||
if spawned.is_err() {
|
||||
busy.store(false, Ordering::Release);
|
||||
return None;
|
||||
@@ -310,11 +337,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_stuck_probe_is_not_started_again() {
|
||||
let board = ServiceBoard::default();
|
||||
let busy = Arc::new(AtomicBool::new(false));
|
||||
let (release, wait) = std::sync::mpsc::channel::<()>();
|
||||
let short = Duration::from_millis(50);
|
||||
|
||||
let stuck = probe_once(&busy, short, move || {
|
||||
let stuck = probe_once(&board, &busy, short, move || {
|
||||
let _ = wait.recv();
|
||||
Some(1)
|
||||
});
|
||||
@@ -322,7 +350,7 @@ mod tests {
|
||||
|
||||
let started = Arc::new(AtomicBool::new(false));
|
||||
let flag = Arc::clone(&started);
|
||||
let second = probe_once(&busy, short, move || {
|
||||
let second = probe_once(&board, &busy, short, move || {
|
||||
flag.store(true, Ordering::SeqCst);
|
||||
Some(2)
|
||||
});
|
||||
@@ -339,7 +367,7 @@ mod tests {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert_eq!(
|
||||
probe_once(&busy, Duration::from_secs(10), || Some(3)),
|
||||
probe_once(&board, &busy, Duration::from_secs(10), || Some(3)),
|
||||
Some(3)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -42,7 +42,6 @@ use tracing::{debug, error, info, warn};
|
||||
|
||||
use super::link::{self, is_network_error};
|
||||
use super::photos::sha1_of;
|
||||
use super::state::{Intervals, PendingRevision};
|
||||
use super::transfers::CountingReader;
|
||||
use super::{
|
||||
Core, DRAIN_BACKOFF_MAX, DRAIN_BACKOFF_MIN, DRAIN_IDLE_POLL, DRAIN_REVISION_DEBOUNCE,
|
||||
@@ -50,6 +49,7 @@ use super::{
|
||||
is_already_exists, is_gone, is_local_uid_str, media_type_for, node_revision_id, node_size,
|
||||
now_millis, now_secs, parse_node_uid,
|
||||
};
|
||||
use pdfs_vfs::open::{Intervals, PendingRevision};
|
||||
use proton_drive_rs::proton_sdk::api::ResponseCode;
|
||||
use proton_drive_rs::proton_sdk::error::ProtonError;
|
||||
|
||||
@@ -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)),
|
||||
@@ -420,7 +428,11 @@ impl Core {
|
||||
// touches get written (`ContentCache::flush_touches`).
|
||||
// Cheap and a no-op when empty.
|
||||
self.cache.flush_touches();
|
||||
self.recover_fsynced_writes();
|
||||
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
|
||||
@@ -1135,9 +1170,9 @@ fn placed_in(st: &crate::state::State, uid: &NodeUid) -> Option<(String, Option<
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::state::WriteHandle;
|
||||
use pdfs_core::Access;
|
||||
use pdfs_store::db::Db;
|
||||
use pdfs_vfs::open::WriteHandle;
|
||||
use proton_drive_rs::NodeKind;
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
|
||||
use std::cell::Cell;
|
||||
@@ -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),
|
||||
|
||||
@@ -564,7 +564,7 @@ impl Core {
|
||||
}
|
||||
}
|
||||
}
|
||||
for aw in st.active_writes.values_mut() {
|
||||
for aw in st.open.writers_mut() {
|
||||
if aw.uid == *local {
|
||||
aw.uid = real.clone();
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
@@ -647,7 +651,7 @@ impl Core {
|
||||
/// daemon has just put there itself (`WriteHandle::rebase_onto`).
|
||||
pub(crate) fn rebase_open_writes(&self, uid: &NodeUid, node: &Node) {
|
||||
self.for_each_state(|st| {
|
||||
for aw in st.active_writes.values_mut() {
|
||||
for aw in st.open.writers_mut() {
|
||||
if aw.uid == *uid {
|
||||
aw.rebase_onto(node);
|
||||
debug!(%uid, mtime = aw.base_mtime, size = aw.base_size,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -19,59 +19,3 @@ impl Core {
|
||||
self.writes.take_echo(uid, now_millis())
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a change this daemon made stays recognisable as its own. Generous
|
||||
/// against a feed that can lag, but finite: past it, an event for the node is
|
||||
/// applied like any other. See [`writes::WriteState`].
|
||||
pub(super) const SELF_CHANGE_TTL_MS: i64 = 120_000;
|
||||
|
||||
/// A remote change this daemon made, awaiting its echo from the event feed.
|
||||
pub(super) struct SelfChange {
|
||||
/// When we made it, in the same epoch millis as [`now_millis`].
|
||||
at_ms: i64,
|
||||
/// Echoes not yet seen. More than one because a single file can be created
|
||||
/// and then have a revision uploaded, and the feed reports both.
|
||||
echoes: u32,
|
||||
}
|
||||
|
||||
/// Record one remote change this daemon made. Split from [`Core`] so the
|
||||
/// expiry and echo-counting rules can be tested against a clock the test owns.
|
||||
pub(super) fn note_self_change(
|
||||
changes: &mut HashMap<NodeUid, SelfChange>,
|
||||
uid: &NodeUid,
|
||||
now_ms: i64,
|
||||
) {
|
||||
// Echoes that never arrived — a node trashed before its event came round, a
|
||||
// feed that skipped it — would otherwise accumulate for the life of the
|
||||
// daemon. Pruning on write keeps the map the size of the recent queue.
|
||||
changes.retain(|_, c| now_ms - c.at_ms < SELF_CHANGE_TTL_MS);
|
||||
let change = changes.entry(uid.clone()).or_insert(SelfChange {
|
||||
at_ms: now_ms,
|
||||
echoes: 0,
|
||||
});
|
||||
change.at_ms = now_ms;
|
||||
change.echoes += 1;
|
||||
}
|
||||
|
||||
/// Claim one echo, per [`Core::take_self_change`].
|
||||
pub(super) fn take_self_change(
|
||||
changes: &mut HashMap<NodeUid, SelfChange>,
|
||||
uid: &NodeUid,
|
||||
now_ms: i64,
|
||||
) -> bool {
|
||||
let Some(change) = changes.get_mut(uid) else {
|
||||
return false;
|
||||
};
|
||||
// Too old to attribute: the feed is far enough behind that this is as likely
|
||||
// to be someone else's change as ours, and guessing wrong here costs the user
|
||||
// a stale file.
|
||||
if now_ms - change.at_ms >= SELF_CHANGE_TTL_MS {
|
||||
changes.remove(uid);
|
||||
return false;
|
||||
}
|
||||
change.echoes -= 1;
|
||||
if change.echoes == 0 {
|
||||
changes.remove(uid);
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -15,12 +15,12 @@ impl Core {
|
||||
pub(crate) fn queue_unreleased_writes(&self) {
|
||||
let handles: Vec<(WriteHandle, bool)> = {
|
||||
let mut st = self.state();
|
||||
st.handles.clear();
|
||||
let inos: Vec<u64> = st.active_writes.keys().copied().collect();
|
||||
inos.into_iter()
|
||||
.filter_map(|ino| {
|
||||
let unlinked = st.entries.get(&ino).is_some_and(|e| e.unlinked);
|
||||
st.active_writes.remove(&ino).map(|h| (h, unlinked))
|
||||
let writers = st.open.take_all();
|
||||
writers
|
||||
.into_iter()
|
||||
.map(|h| {
|
||||
let unlinked = st.entries.get(&h.ino).is_some_and(|e| e.unlinked);
|
||||
(h, unlinked)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
@@ -201,18 +201,8 @@ impl Core {
|
||||
base_size: u64,
|
||||
base_revision_id: Option<String>,
|
||||
) -> Option<Baseline> {
|
||||
if is_local_uid(uid) {
|
||||
return None;
|
||||
}
|
||||
match self.writes.pending.lock().get(uid) {
|
||||
Some(p) => p.meta.based_on.clone(),
|
||||
None => Some(Baseline {
|
||||
mtime: base_mtime,
|
||||
size: base_size,
|
||||
hash: None,
|
||||
revision_id: base_revision_id,
|
||||
}),
|
||||
}
|
||||
self.writes
|
||||
.baseline(uid, base_mtime, base_size, base_revision_id)
|
||||
}
|
||||
|
||||
/// Move a file holding a node's intended new content into staging and queue
|
||||
|
||||
@@ -116,6 +116,14 @@ impl EventHub {
|
||||
.retain(|other| !Arc::ptr_eq(other, mailbox));
|
||||
}
|
||||
|
||||
/// Wake every subscription waiting on its mailbox, so it sees a stop
|
||||
/// now rather than at its next heartbeat.
|
||||
pub(crate) fn wake_all(&self) {
|
||||
for mailbox in self.mailboxes.lock().iter() {
|
||||
mailbox.ready.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
fn has_subscribers(&self) -> bool {
|
||||
!self.mailboxes.lock().is_empty()
|
||||
}
|
||||
|
||||
+93
-1311
File diff suppressed because it is too large.
Load diff
@@ -14,6 +14,8 @@ use pdfs_core::control::{
|
||||
GalleryAction, GalleryAlbum, GalleryFolder, GalleryPlace, PhotoItem, PhotoKind, Response,
|
||||
};
|
||||
use pdfs_core::{CoreError, CoreResult};
|
||||
use pdfs_store::db::Db;
|
||||
use proton_drive_rs::ProtonDriveClient;
|
||||
use proton_drive_rs::proton_sdk::session::ProtonApiSession;
|
||||
use proton_gallery_app_rs::{App, View};
|
||||
use proton_gallery_rs::CancellationToken;
|
||||
@@ -32,6 +34,9 @@ pub(super) struct Gallery {
|
||||
refresh: Notify,
|
||||
access: AtomicU64,
|
||||
video: video::Server,
|
||||
client: ProtonDriveClient,
|
||||
events: Arc<super::events::EventHub>,
|
||||
db: Arc<Db>,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Eq)]
|
||||
@@ -50,8 +55,17 @@ impl Visibility {
|
||||
}
|
||||
|
||||
impl Gallery {
|
||||
pub(super) fn new(root: PathBuf, session: ProtonApiSession) -> Self {
|
||||
pub(super) fn new(
|
||||
root: PathBuf,
|
||||
session: ProtonApiSession,
|
||||
client: ProtonDriveClient,
|
||||
events: Arc<super::events::EventHub>,
|
||||
db: Arc<Db>,
|
||||
) -> Self {
|
||||
Self {
|
||||
client,
|
||||
events,
|
||||
db,
|
||||
root,
|
||||
session,
|
||||
cancel: CancellationToken::new(),
|
||||
@@ -69,13 +83,13 @@ impl Gallery {
|
||||
self.video.close_all();
|
||||
}
|
||||
|
||||
async fn app(&self, core: &Core) -> CoreResult<&App> {
|
||||
async fn app(&self) -> CoreResult<&App> {
|
||||
self.app
|
||||
.get_or_try_init(|| async {
|
||||
App::open_hosted(
|
||||
self.root.clone(),
|
||||
self.session.clone(),
|
||||
core.client.clone(),
|
||||
self.client.clone(),
|
||||
self.cancel.child_token(),
|
||||
)
|
||||
.await
|
||||
@@ -84,12 +98,7 @@ impl Gallery {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn ensure_visibility(
|
||||
&self,
|
||||
core: &Core,
|
||||
app: &App,
|
||||
force: bool,
|
||||
) -> CoreResult<Arc<Visibility>> {
|
||||
async fn ensure_visibility(&self, app: &App, force: bool) -> CoreResult<Arc<Visibility>> {
|
||||
if self.cancel.is_cancelled() {
|
||||
return Err(CoreError::remote("The Gallery session expired"));
|
||||
}
|
||||
@@ -111,7 +120,7 @@ impl Gallery {
|
||||
.await
|
||||
.map_err(gallery_error)?
|
||||
{
|
||||
self.publish_visibility(core, self.read_visibility(core, app).await?);
|
||||
self.publish_visibility(self.read_visibility(app).await?);
|
||||
}
|
||||
let started = Instant::now();
|
||||
let result = tokio::select! {
|
||||
@@ -119,7 +128,7 @@ impl Gallery {
|
||||
_ = self.cancel.cancelled() => Err(CoreError::remote("The Gallery session expired")),
|
||||
result = tokio::time::timeout(Duration::from_secs(20), async {
|
||||
app.refresh_gallery_configuration(false).await.map_err(gallery_error)?;
|
||||
self.read_visibility(core, app).await
|
||||
self.read_visibility(app).await
|
||||
}) => result.unwrap_or_else(|_| Err(CoreError::remote("Gallery visibility check timed out"))),
|
||||
};
|
||||
tracing::debug!(
|
||||
@@ -129,7 +138,7 @@ impl Gallery {
|
||||
);
|
||||
*checked = Some(Instant::now());
|
||||
if let Ok(visibility) = result {
|
||||
self.publish_visibility(core, visibility.clone());
|
||||
self.publish_visibility(visibility.clone());
|
||||
return Ok(visibility);
|
||||
}
|
||||
if !force && let Some(visibility) = self.snapshot() {
|
||||
@@ -145,18 +154,18 @@ impl Gallery {
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn publish_visibility(&self, core: &Core, visibility: Arc<Visibility>) {
|
||||
fn publish_visibility(&self, visibility: Arc<Visibility>) {
|
||||
let mut snapshot = self.visibility.write().unwrap_or_else(|e| e.into_inner());
|
||||
if snapshot.as_ref() != Some(&visibility) {
|
||||
*snapshot = Some(visibility);
|
||||
drop(snapshot);
|
||||
self.video.close_all();
|
||||
core.events
|
||||
self.events
|
||||
.publish(&[pdfs_core::control::Topic::GalleryVisibilitySynced]);
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_visibility(&self, core: &Core, app: &App) -> CoreResult<Arc<Visibility>> {
|
||||
async fn read_visibility(&self, app: &App) -> CoreResult<Arc<Visibility>> {
|
||||
let account = self.account()?;
|
||||
let mut visibility = Visibility::default();
|
||||
for (volume, node) in app
|
||||
@@ -170,7 +179,7 @@ impl Gallery {
|
||||
.insert(NodeUid::new(volume.into(), node.into()).to_string());
|
||||
}
|
||||
visibility.media.extend(
|
||||
core.db
|
||||
self.db
|
||||
.photo_group_members_for(&visibility.media)
|
||||
.map_err(CoreError::from)?,
|
||||
);
|
||||
@@ -328,7 +337,7 @@ impl Gallery {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn poll(self: Arc<Self>, core: Core) {
|
||||
pub(super) async fn poll(self: Arc<Self>) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
@@ -336,9 +345,8 @@ impl Gallery {
|
||||
_ = self.refresh.notified() => {},
|
||||
_ = tokio::time::sleep(Duration::from_secs(60)) => {}
|
||||
}
|
||||
if let Ok(Ok(app)) = tokio::time::timeout(Duration::from_secs(5), self.app(&core)).await
|
||||
{
|
||||
let _ = self.ensure_visibility(&core, app, false).await;
|
||||
if let Ok(Ok(app)) = tokio::time::timeout(Duration::from_secs(5), self.app()).await {
|
||||
let _ = self.ensure_visibility(app, false).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -422,8 +430,8 @@ impl Core {
|
||||
}
|
||||
let gallery = self.gallery_host()?;
|
||||
self.rt.block_on(async {
|
||||
let app = gallery.app(self).await?;
|
||||
gallery.ensure_visibility(self, app, false).await
|
||||
let app = gallery.app().await?;
|
||||
gallery.ensure_visibility(app, false).await
|
||||
})
|
||||
}
|
||||
|
||||
@@ -475,9 +483,9 @@ impl Core {
|
||||
other => other,
|
||||
};
|
||||
self.rt.block_on(async {
|
||||
let app = gallery.app(self).await?;
|
||||
let app = gallery.app().await?;
|
||||
gallery
|
||||
.ensure_visibility(self, app, matches!(action, GalleryAction::Refresh))
|
||||
.ensure_visibility(app, matches!(action, GalleryAction::Refresh))
|
||||
.await?;
|
||||
match action {
|
||||
GalleryAction::AuthenticateHidden | GalleryAction::Lock => unreachable!(),
|
||||
@@ -517,14 +525,14 @@ impl Core {
|
||||
app.add_drive_folder(uid(&node)?)
|
||||
.await
|
||||
.map_err(gallery_error)?;
|
||||
gallery.ensure_visibility(self, app, true).await?;
|
||||
gallery.ensure_visibility(app, true).await?;
|
||||
Ok(done())
|
||||
}
|
||||
GalleryAction::Remove { gallery: id } => {
|
||||
app.forget_drive_gallery(SourceId::new(id).map_err(gallery_error)?)
|
||||
.await
|
||||
.map_err(gallery_error)?;
|
||||
gallery.ensure_visibility(self, app, true).await?;
|
||||
gallery.ensure_visibility(app, true).await?;
|
||||
Ok(done())
|
||||
}
|
||||
GalleryAction::Refresh => {
|
||||
@@ -535,7 +543,7 @@ impl Core {
|
||||
);
|
||||
app.scan_drive_folder(root).await.map_err(gallery_error)?;
|
||||
}
|
||||
gallery.ensure_visibility(self, app, true).await?;
|
||||
gallery.ensure_visibility(app, true).await?;
|
||||
Ok(done())
|
||||
}
|
||||
GalleryAction::Cover { album, uid: node } => {
|
||||
@@ -565,7 +573,7 @@ impl Core {
|
||||
.set_album_settings_at(Some(root), id, settings)
|
||||
.await
|
||||
.map_err(gallery_error)?;
|
||||
gallery.ensure_visibility(self, app, true).await?;
|
||||
gallery.ensure_visibility(app, true).await?;
|
||||
Ok(done())
|
||||
}
|
||||
}
|
||||
@@ -576,8 +584,8 @@ impl Core {
|
||||
let gallery = self.gallery_host()?;
|
||||
let uid = uid(node)?;
|
||||
self.rt.block_on(async {
|
||||
let app = gallery.app(self).await?;
|
||||
let visibility = gallery.ensure_visibility(self, app, false).await?;
|
||||
let app = gallery.app().await?;
|
||||
let visibility = gallery.ensure_visibility(app, false).await?;
|
||||
let access = if private {
|
||||
Some(gallery.private_access()?)
|
||||
} else {
|
||||
@@ -605,7 +613,7 @@ impl Core {
|
||||
let access = gallery.private_access()?;
|
||||
let asset = gallery.asset(&uid(node)?)?;
|
||||
self.rt.block_on(async {
|
||||
let app = gallery.app(self).await?;
|
||||
let app = gallery.app().await?;
|
||||
let bytes = tokio::time::timeout(Duration::from_secs(30), async {
|
||||
if let Some(bytes) = app.preview(&asset).await? {
|
||||
Ok(bytes)
|
||||
@@ -633,8 +641,8 @@ impl Core {
|
||||
let gallery = self.gallery_host()?;
|
||||
let asset = gallery.asset(&uid(node)?)?;
|
||||
self.rt.block_on(async {
|
||||
let app = gallery.app(self).await?;
|
||||
let visibility = gallery.ensure_visibility(self, app, false).await?;
|
||||
let app = gallery.app().await?;
|
||||
let visibility = gallery.ensure_visibility(app, false).await?;
|
||||
let access = if private {
|
||||
Some(gallery.private_access()?)
|
||||
} else {
|
||||
|
||||
@@ -15,11 +15,10 @@
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::time::Duration;
|
||||
|
||||
use pdfs_store::db::PendingCounts;
|
||||
use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_store::db::{Db, PendingCounts};
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use super::Core;
|
||||
|
||||
/// How often the queue is looked at.
|
||||
const CHECK_EVERY: Duration = Duration::from_secs(5);
|
||||
|
||||
@@ -29,11 +28,10 @@ fn sendable(counts: &PendingCounts) -> i64 {
|
||||
}
|
||||
|
||||
/// Run until the daemon stops, holding the inhibitor while changes wait.
|
||||
pub(crate) fn run(core: Core) {
|
||||
pub(crate) fn run(db: &Db, shutdown: &Shutdown) {
|
||||
let mut held: Option<Child> = None;
|
||||
loop {
|
||||
let waiting = core
|
||||
.db
|
||||
let waiting = db
|
||||
.pending_op_counts()
|
||||
.map(|counts| sendable(&counts))
|
||||
.unwrap_or(0);
|
||||
@@ -52,7 +50,7 @@ pub(crate) fn run(core: Core) {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if !core.shutdown.sleep(CHECK_EVERY) {
|
||||
if !shutdown.sleep(CHECK_EVERY) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,16 @@ use proton_drive_rs::NodeKind;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use fuser::Errno;
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::CoreResult;
|
||||
use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_store::cache::ContentCache;
|
||||
|
||||
use super::link::Link;
|
||||
use super::transfers::TransferRegistry;
|
||||
use super::{Core, is_local_uid, node_size, parse_uid};
|
||||
|
||||
/// How often the keeper looks for work.
|
||||
@@ -59,32 +69,76 @@ pub(crate) struct KeptFile {
|
||||
pub(crate) size: u64,
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// Have the keeper check every pin.
|
||||
pub(crate) fn recheck_all_pins(&self) {
|
||||
self.pin_work.lock().all = true;
|
||||
/// What the pin keeper needs from the tree.
|
||||
pub(crate) trait KeeperHost: Send + Sync {
|
||||
/// Where `uid` is in the tree: its inode, its parent's, and whether it is
|
||||
/// a folder.
|
||||
fn locate(&self, uid: &NodeUid) -> Option<(u64, u64, bool)>;
|
||||
/// Every file under the folder at `ino`, listing what is not listed yet.
|
||||
fn pin_subtree_files(&self, ino: u64) -> CoreResult<Vec<u64>>;
|
||||
/// List the folder at `ino` again if its listing was dropped.
|
||||
fn ensure_children(&self, ino: u64) -> Result<(), Errno>;
|
||||
/// The file at `ino`, as a pin keeps it. See [`Core::kept_file`].
|
||||
fn kept_file(&self, ino: u64) -> Option<KeptFile>;
|
||||
/// Download a pinned file and keep it.
|
||||
fn fetch_pinned(&self, uid: &NodeUid, name: &str, mtime: i64, size: u64) -> CoreResult<()>;
|
||||
}
|
||||
|
||||
impl KeeperHost for Core {
|
||||
fn locate(&self, uid: &NodeUid) -> Option<(u64, u64, bool)> {
|
||||
let st = self.state();
|
||||
st.by_uid.get(uid).and_then(|&ino| {
|
||||
let e = st.entries.get(&ino)?;
|
||||
Some((ino, e.parent, e.node.is_folder()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Have the keeper check the pinned file or folder `uid`.
|
||||
pub(crate) fn recheck_pinned(&self, uid: &NodeUid) {
|
||||
self.pin_work.lock().nodes.insert(uid.clone());
|
||||
fn pin_subtree_files(&self, ino: u64) -> CoreResult<Vec<u64>> {
|
||||
Core::pin_subtree_files(self, ino)
|
||||
}
|
||||
|
||||
fn ensure_children(&self, ino: u64) -> Result<(), Errno> {
|
||||
Core::ensure_children(self, ino)
|
||||
}
|
||||
|
||||
fn kept_file(&self, ino: u64) -> Option<KeptFile> {
|
||||
Core::kept_file(self, ino)
|
||||
}
|
||||
|
||||
fn fetch_pinned(&self, uid: &NodeUid, name: &str, mtime: i64, size: u64) -> CoreResult<()> {
|
||||
Core::fetch_pinned(self, uid, name, mtime, size)
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks pins again and downloads what is missing or stale (the module
|
||||
/// documentation says when). Holds the content cache, the transfer list, the
|
||||
/// link, the stop signal and the queue of work; it reaches the tree through
|
||||
/// [`KeeperHost`].
|
||||
pub(crate) struct PinKeeper {
|
||||
cache: Arc<ContentCache>,
|
||||
transfers: Arc<TransferRegistry>,
|
||||
link: Arc<Link>,
|
||||
shutdown: Arc<Shutdown>,
|
||||
work: Arc<Mutex<PinWork>>,
|
||||
host: Arc<dyn KeeperHost>,
|
||||
}
|
||||
|
||||
impl PinKeeper {
|
||||
/// The keeper's loop, until the daemon stops. Starts with a check of every
|
||||
/// pin, which catches up on whatever changed while the daemon was down.
|
||||
///
|
||||
/// Work that failed waits out a backoff of its own. New work does not wait
|
||||
/// for it, so a file that keeps failing does not hold up the next change.
|
||||
pub(crate) fn run_pin_keeper(&self) {
|
||||
self.recheck_all_pins();
|
||||
pub(crate) fn run(&self) {
|
||||
self.work.lock().all = true;
|
||||
let mut backlog = PinWork::default();
|
||||
let mut backlog_due = Instant::now();
|
||||
let mut retry = RETRY_FIRST;
|
||||
while self.shutdown.sleep(KEEPER_TICK) {
|
||||
if !self.is_online() {
|
||||
if !self.link.is_online() {
|
||||
continue;
|
||||
}
|
||||
let mut work = std::mem::take(&mut *self.pin_work.lock());
|
||||
let mut work = std::mem::take(&mut *self.work.lock());
|
||||
let retrying = !backlog.is_empty() && Instant::now() >= backlog_due;
|
||||
if retrying {
|
||||
work.merge(std::mem::take(&mut backlog));
|
||||
@@ -128,19 +182,13 @@ impl Core {
|
||||
if !self.cache.is_pinned(&uid) {
|
||||
continue;
|
||||
}
|
||||
let found = {
|
||||
let st = self.state();
|
||||
st.by_uid.get(&uid).and_then(|&ino| {
|
||||
let e = st.entries.get(&ino)?;
|
||||
Some((ino, e.parent, e.node.is_folder()))
|
||||
})
|
||||
};
|
||||
let found = self.host.locate(&uid);
|
||||
let Some((ino, parent, is_folder)) = found else {
|
||||
debug!(%uid, "pin keeper: pinned node is not in the tree");
|
||||
continue;
|
||||
};
|
||||
if is_folder {
|
||||
match self.pin_subtree_files(ino) {
|
||||
match self.host.pin_subtree_files(ino) {
|
||||
Ok(inos) => files.extend(inos.into_iter().filter(|i| seen.insert(*i))),
|
||||
Err(e) => {
|
||||
warn!(%uid, error = %e, "pin keeper: listing a kept folder failed");
|
||||
@@ -154,7 +202,7 @@ impl Core {
|
||||
// now, which is what the cached copy is checked against.
|
||||
if !work.all
|
||||
&& parent != ino
|
||||
&& let Err(e) = self.ensure_children(parent)
|
||||
&& let Err(e) = self.host.ensure_children(parent)
|
||||
{
|
||||
warn!(%uid, error = ?e, "pin keeper: listing a kept file's folder failed");
|
||||
failed.nodes.insert(uid);
|
||||
@@ -167,7 +215,7 @@ impl Core {
|
||||
|
||||
let stale: Vec<KeptFile> = files
|
||||
.into_iter()
|
||||
.filter_map(|ino| self.kept_file(ino))
|
||||
.filter_map(|ino| self.host.kept_file(ino))
|
||||
.filter(|f| !self.cache.is_cached(&f.uid, f.mtime, f.size))
|
||||
.collect();
|
||||
if stale.is_empty() {
|
||||
@@ -186,7 +234,10 @@ impl Core {
|
||||
continue;
|
||||
}
|
||||
job.detail(file.name.clone());
|
||||
match self.fetch_pinned(&file.uid, &file.name, file.mtime, file.size) {
|
||||
match self
|
||||
.host
|
||||
.fetch_pinned(&file.uid, &file.name, file.mtime, file.size)
|
||||
{
|
||||
Ok(()) => fetched += 1,
|
||||
Err(e) => {
|
||||
warn!(uid = %file.uid, error = %e, "pin keeper: download failed");
|
||||
@@ -203,6 +254,30 @@ impl Core {
|
||||
);
|
||||
failed
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// The pin keeper, with this daemon as its host.
|
||||
pub(crate) fn pin_keeper(&self) -> PinKeeper {
|
||||
PinKeeper {
|
||||
cache: self.cache.clone(),
|
||||
transfers: self.transfers.clone(),
|
||||
link: self.link.clone(),
|
||||
shutdown: self.shutdown.clone(),
|
||||
work: self.pin_work.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Have the keeper check every pin.
|
||||
pub(crate) fn recheck_all_pins(&self) {
|
||||
self.pin_work.lock().all = true;
|
||||
}
|
||||
|
||||
/// Have the keeper check the pinned file or folder `uid`.
|
||||
pub(crate) fn recheck_pinned(&self, uid: &NodeUid) {
|
||||
self.pin_work.lock().nodes.insert(uid.clone());
|
||||
}
|
||||
|
||||
/// The file at `ino`, as a pin keeps it. `None` for a folder, a file this
|
||||
/// daemon still owes an upload for, or a file whose real size cannot be
|
||||
|
||||
+389
-771
File diff suppressed because it is too large.
Load diff
+171
-82
@@ -18,6 +18,11 @@ use proton_drive_rs::proton_sdk::api::ResponseCode;
|
||||
use proton_drive_rs::proton_sdk::error::{ProtonApiError, ProtonError};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_drive::DriveApi;
|
||||
|
||||
use crate::{Core, ONLINE_PROBE_MAX, ONLINE_PROBE_MIN};
|
||||
|
||||
/// How long a remote call a FUSE handler is waiting on may take before the link
|
||||
@@ -88,6 +93,75 @@ impl Link {
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the mount currently believes Proton is reachable.
|
||||
pub(crate) fn is_online(&self) -> bool {
|
||||
self.online.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Whether Proton refused the session itself, so the mount stays offline
|
||||
/// until the user signs in again.
|
||||
pub(crate) fn session_expired(&self) -> bool {
|
||||
self.session_expired.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Flip the mount offline and wake the probe. Only the first caller of an
|
||||
/// outage logs it; the rest are the same outage.
|
||||
pub(crate) fn go_offline(&self, what: &str, error: &dyn std::fmt::Display) {
|
||||
let mut lost_at = self.lost_at.lock();
|
||||
if self.online.swap(false, Ordering::Relaxed) {
|
||||
*lost_at = Some(Instant::now());
|
||||
warn!(during = what, %error,
|
||||
"lost the connection to Proton; queueing changes until it returns");
|
||||
self.changed.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Flip the mount back online and wake everything waiting for it.
|
||||
fn go_online(&self) {
|
||||
let mut lost_at = self.lost_at.lock();
|
||||
self.online.store(true, Ordering::Relaxed);
|
||||
match lost_at.take() {
|
||||
Some(since) => {
|
||||
info!(
|
||||
offline_secs = since.elapsed().as_secs(),
|
||||
"connection to Proton is back"
|
||||
)
|
||||
}
|
||||
None => info!("back online"),
|
||||
}
|
||||
self.changed.notify_all();
|
||||
}
|
||||
|
||||
/// Wait up to `budget` for the link to come back. Returns whether it is up.
|
||||
pub(crate) fn wait_online(&self, budget: Duration, shutdown: &Shutdown) -> bool {
|
||||
let deadline = Instant::now() + budget;
|
||||
let mut lost_at = self.lost_at.lock();
|
||||
while !self.is_online() {
|
||||
if shutdown.is_stopping() || self.changed.wait_until(&mut lost_at, deadline).timed_out()
|
||||
{
|
||||
return self.is_online();
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Wait while the link is up. Returns `false` if the daemon is stopping.
|
||||
fn wait_offline(&self, shutdown: &Shutdown) -> bool {
|
||||
let mut lost_at = self.lost_at.lock();
|
||||
while self.is_online() {
|
||||
if shutdown.is_stopping() {
|
||||
return false;
|
||||
}
|
||||
self.changed.wait_for(&mut lost_at, IDLE_CHECK);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// When the current outage began, if the link is down.
|
||||
fn lost_at(&self) -> Option<Instant> {
|
||||
*self.lost_at.lock()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) use pdfs_drive::is_network_error;
|
||||
@@ -160,7 +234,7 @@ fn next_probe_delay(delay: Duration, outage: Duration) -> Duration {
|
||||
impl Core {
|
||||
/// Whether the mount currently believes Proton is reachable.
|
||||
pub(crate) fn is_online(&self) -> bool {
|
||||
self.link.online.load(Ordering::Relaxed)
|
||||
self.link.is_online()
|
||||
}
|
||||
|
||||
/// Whether a namespace change through the mount goes to Drive inside the
|
||||
@@ -195,7 +269,7 @@ impl Core {
|
||||
/// Whether Proton refused the session itself, so nothing reaches it until
|
||||
/// the user signs in again.
|
||||
pub(crate) fn session_expired(&self) -> bool {
|
||||
self.link.session_expired.load(Ordering::Relaxed)
|
||||
self.link.session_expired()
|
||||
}
|
||||
|
||||
/// Report a failed remote call. Returns whether it failed for want of a
|
||||
@@ -239,65 +313,14 @@ impl Core {
|
||||
self.mark_offline(what, error);
|
||||
}
|
||||
|
||||
/// Flip the mount offline and wake the probe. Only the first caller of an
|
||||
/// outage logs it; the rest are the same outage.
|
||||
/// Flip the mount offline and wake the probe. See [`Link::go_offline`].
|
||||
pub(crate) fn mark_offline(&self, what: &str, error: &dyn std::fmt::Display) {
|
||||
let mut lost_at = self.link.lost_at.lock();
|
||||
if self.link.online.swap(false, Ordering::Relaxed) {
|
||||
*lost_at = Some(Instant::now());
|
||||
warn!(during = what, %error,
|
||||
"lost the connection to Proton; queueing changes until it returns");
|
||||
self.link.changed.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Flip the mount back online, wake everything waiting for it, and let the
|
||||
/// queue drain.
|
||||
fn mark_online(&self) {
|
||||
{
|
||||
let mut lost_at = self.link.lost_at.lock();
|
||||
self.link.online.store(true, Ordering::Relaxed);
|
||||
match lost_at.take() {
|
||||
Some(since) => {
|
||||
info!(
|
||||
offline_secs = since.elapsed().as_secs(),
|
||||
"connection to Proton is back"
|
||||
)
|
||||
}
|
||||
None => info!("back online"),
|
||||
}
|
||||
self.link.changed.notify_all();
|
||||
}
|
||||
self.relist_offline_listings();
|
||||
// Anything written while offline is queued and waiting on exactly this,
|
||||
// including ops that failed on the way down and are sitting out a
|
||||
// backoff sized for a server that keeps refusing. Ops Drive refused
|
||||
// keep theirs: the link was not why.
|
||||
if let Err(e) = self.db.retry_unrefused_ops_now(crate::now_millis()) {
|
||||
warn!(error = %e, "moving backed-off ops up after a reconnect failed");
|
||||
}
|
||||
self.wake_drain();
|
||||
// Downloads for pins failed while the link was down, and the events
|
||||
// that would have named the files are behind us (`docs/BUGS.md` B282).
|
||||
self.recheck_all_pins();
|
||||
self.link.go_offline(what, error);
|
||||
}
|
||||
|
||||
/// Wait up to `budget` for the link to come back. Returns whether it is up.
|
||||
pub(crate) fn wait_online(&self, budget: Duration) -> bool {
|
||||
let deadline = Instant::now() + budget;
|
||||
let mut lost_at = self.link.lost_at.lock();
|
||||
while !self.is_online() {
|
||||
if self.shutdown.is_stopping()
|
||||
|| self
|
||||
.link
|
||||
.changed
|
||||
.wait_until(&mut lost_at, deadline)
|
||||
.timed_out()
|
||||
{
|
||||
return self.is_online();
|
||||
}
|
||||
}
|
||||
true
|
||||
self.link.wait_online(budget, &self.shutdown)
|
||||
}
|
||||
|
||||
/// Wait out `interval` before a background poll of Proton, and while the
|
||||
@@ -318,29 +341,103 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
/// The online probe, with this daemon as its host.
|
||||
pub(crate) fn online_probe(&self) -> OnlineProbe {
|
||||
OnlineProbe {
|
||||
link: self.link.clone(),
|
||||
drive: self.drive.clone(),
|
||||
rt: self.rt.clone(),
|
||||
shutdown: self.shutdown.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The link is back: let everything that waited on it go. Anything
|
||||
/// written while offline is queued and waiting on exactly this, including
|
||||
/// ops that failed on the way down and are sitting out a backoff sized
|
||||
/// for a server that keeps refusing. Ops Drive refused keep theirs: the
|
||||
/// link was not why.
|
||||
fn after_reconnect(&self) {
|
||||
self.relist_offline_listings();
|
||||
if let Err(e) = self.db.retry_unrefused_ops_now(crate::now_millis()) {
|
||||
warn!(error = %e, "moving backed-off ops up after a reconnect failed");
|
||||
}
|
||||
self.wake_drain();
|
||||
// Downloads for pins failed while the link was down, and the events
|
||||
// that would have named the files are behind us (`docs/BUGS.md` B282).
|
||||
self.recheck_all_pins();
|
||||
}
|
||||
}
|
||||
|
||||
/// What the online probe needs from the rest of the daemon.
|
||||
pub(crate) trait LinkHost: Send + Sync {
|
||||
/// Drive answered with the My Files root: store it in the tree and the
|
||||
/// database before the mount goes online.
|
||||
fn refresh_root(&self, root: &proton_drive_rs::Node);
|
||||
/// The mount is online again: relist, retry and refetch what waited.
|
||||
fn reconnected(&self);
|
||||
/// Proton refused the session.
|
||||
fn session_refused(&self, what: &str, error: &ProtonError);
|
||||
/// Repair the primary root's share id, which an offline start could not.
|
||||
fn repair_share_id(&self);
|
||||
}
|
||||
|
||||
impl LinkHost for Core {
|
||||
fn refresh_root(&self, root: &proton_drive_rs::Node) {
|
||||
{
|
||||
let root_ino = self.root_ino();
|
||||
let mut st = self.state();
|
||||
if let Some(e) = st.entries.get_mut(&root_ino) {
|
||||
e.node = root.clone();
|
||||
}
|
||||
}
|
||||
if let Err(e) = self.db.upsert_node(root) {
|
||||
warn!(error = %e, "refresh root after reconnect failed");
|
||||
}
|
||||
}
|
||||
|
||||
fn reconnected(&self) {
|
||||
self.after_reconnect();
|
||||
}
|
||||
|
||||
fn session_refused(&self, what: &str, error: &ProtonError) {
|
||||
self.mark_session_expired(what, error);
|
||||
}
|
||||
|
||||
fn repair_share_id(&self) {
|
||||
self.repair_primary_share_id(&self.primary_root_uid);
|
||||
}
|
||||
}
|
||||
|
||||
/// Watches the link for the life of the mount and probes it back while it is
|
||||
/// down. Holds the link, Drive, the runtime and the stop signal; it reaches
|
||||
/// the tree and the queue through [`LinkHost`].
|
||||
pub(crate) struct OnlineProbe {
|
||||
link: Arc<Link>,
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
shutdown: Arc<Shutdown>,
|
||||
host: Arc<dyn LinkHost>,
|
||||
}
|
||||
|
||||
impl OnlineProbe {
|
||||
/// Watch the link for the life of the mount: sleep while it is up, and
|
||||
/// probe it back while it is down.
|
||||
///
|
||||
/// A mount that started from the cache is down from the first moment; one
|
||||
/// that started online goes down when [`Core::mark_offline`] says so.
|
||||
pub(crate) fn run_online_probe(&self) {
|
||||
/// that started online goes down when [`Link::go_offline`] says so.
|
||||
pub(crate) fn run(&self) {
|
||||
// Only an offline start never had a chance to repair its share id.
|
||||
let mut repair_share_id = !self.is_online();
|
||||
let mut repair_share_id = !self.link.is_online();
|
||||
loop {
|
||||
{
|
||||
let mut lost_at = self.link.lost_at.lock();
|
||||
while self.is_online() {
|
||||
if self.shutdown.is_stopping() {
|
||||
return;
|
||||
}
|
||||
self.link.changed.wait_for(&mut lost_at, IDLE_CHECK);
|
||||
}
|
||||
if !self.link.wait_offline(&self.shutdown) {
|
||||
return;
|
||||
}
|
||||
if !self.probe_until_online() {
|
||||
return;
|
||||
}
|
||||
if std::mem::take(&mut repair_share_id) {
|
||||
self.repair_primary_share_id(&self.primary_root_uid);
|
||||
self.host.repair_share_id();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -351,7 +448,7 @@ impl Core {
|
||||
/// A refused session is not probed: every probe would be refused the same
|
||||
/// way, forever (issue #35). The thread waits for the stop instead.
|
||||
fn probe_until_online(&self) -> bool {
|
||||
let started = self.link.lost_at.lock().unwrap_or_else(Instant::now);
|
||||
let started = self.link.lost_at().unwrap_or_else(Instant::now);
|
||||
let mut delay = if started.elapsed() < YOUNG_OUTAGE {
|
||||
PROBE_AFTER_DROP
|
||||
} else {
|
||||
@@ -361,7 +458,7 @@ impl Core {
|
||||
if !self.shutdown.sleep(delay) {
|
||||
return false;
|
||||
}
|
||||
if self.session_expired() {
|
||||
if self.link.session_expired() {
|
||||
delay = ONLINE_PROBE_MAX;
|
||||
continue;
|
||||
}
|
||||
@@ -373,20 +470,12 @@ impl Core {
|
||||
});
|
||||
match probe {
|
||||
Ok(root) => {
|
||||
{
|
||||
let root_ino = self.root_ino();
|
||||
let mut st = self.state();
|
||||
if let Some(e) = st.entries.get_mut(&root_ino) {
|
||||
e.node = root.clone();
|
||||
}
|
||||
}
|
||||
if let Err(e) = self.db.upsert_node(&root) {
|
||||
warn!(error = %e, "refresh root after reconnect failed");
|
||||
}
|
||||
self.mark_online();
|
||||
self.host.refresh_root(&root);
|
||||
self.link.go_online();
|
||||
self.host.reconnected();
|
||||
return true;
|
||||
}
|
||||
Err(e) if session_revoked(&e) => self.mark_session_expired("online probe", &e),
|
||||
Err(e) if session_revoked(&e) => self.host.session_refused("online probe", &e),
|
||||
Err(e) => {
|
||||
debug!(error = %e, ?delay, "online probe failed; still offline");
|
||||
delay = next_probe_delay(delay, started.elapsed());
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -3,7 +3,31 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Core {
|
||||
/// Runs `VACUUM` and the deep integrity check as jobs, one at a time, and
|
||||
/// keeps the last check's findings. Holds the database, the transfer list for
|
||||
/// the job's entry, and the board the job runs on.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Maintenance {
|
||||
db: Arc<Db>,
|
||||
transfers: Arc<TransferRegistry>,
|
||||
services: pdfs_core::lifecycle::ServiceBoard,
|
||||
state: Arc<Mutex<MaintenanceState>>,
|
||||
}
|
||||
|
||||
impl Maintenance {
|
||||
pub(crate) fn new(
|
||||
db: Arc<Db>,
|
||||
transfers: Arc<TransferRegistry>,
|
||||
services: pdfs_core::lifecycle::ServiceBoard,
|
||||
) -> Self {
|
||||
Self {
|
||||
db,
|
||||
transfers,
|
||||
services,
|
||||
state: Arc::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a background `VACUUM`, or refuse because maintenance is already
|
||||
/// running.
|
||||
///
|
||||
@@ -11,9 +35,9 @@ impl Core {
|
||||
/// request. The outcome is a log line and a job that disappears from
|
||||
/// `GetQueueStatus` when it is done — a vacuum has nothing to report that a
|
||||
/// follow-up `CacheInspect` cannot show.
|
||||
pub(super) fn start_vacuum(&self) -> CoreResult<()> {
|
||||
pub(crate) fn start_vacuum(&self) -> CoreResult<()> {
|
||||
{
|
||||
let mut m = self.maintenance.lock();
|
||||
let mut m = self.state.lock();
|
||||
if m.running {
|
||||
return Err(CoreError::conflict(
|
||||
"database maintenance is already running",
|
||||
@@ -21,12 +45,12 @@ impl Core {
|
||||
}
|
||||
m.running = true;
|
||||
}
|
||||
let core = self.clone();
|
||||
let this = self.clone();
|
||||
if let Err(error) = self.services.spawn_job("pdfs-vacuum", move || {
|
||||
let job = core.transfers.begin_job("Compacting the cache database");
|
||||
let job = this.transfers.begin_job("Compacting the cache database");
|
||||
job.detail("Rewriting the database file");
|
||||
let started = Instant::now();
|
||||
match core.db.vacuum() {
|
||||
match this.db.vacuum() {
|
||||
Ok(outcome) => info!(
|
||||
freed_bytes = outcome.freed_bytes(),
|
||||
before_bytes = outcome.before_bytes,
|
||||
@@ -37,7 +61,7 @@ impl Core {
|
||||
),
|
||||
Err(e) => warn!(error = %e, "vacuum failed"),
|
||||
}
|
||||
core.maintenance.lock().running = false;
|
||||
this.state.lock().running = false;
|
||||
}) {
|
||||
tracing::warn!(%error, "could not start pdfs-vacuum");
|
||||
}
|
||||
@@ -51,8 +75,8 @@ impl Core {
|
||||
/// `(_, false, true)` and the answer lands on a later one — the check reads
|
||||
/// every page of the database under the connection mutex, so the choice is
|
||||
/// between answering late and freezing the mount until it finishes.
|
||||
pub(super) fn start_or_read_integrity_check(&self) -> (Vec<String>, bool, bool) {
|
||||
let mut m = self.maintenance.lock();
|
||||
pub(crate) fn start_or_read_integrity_check(&self) -> (Vec<String>, bool, bool) {
|
||||
let mut m = self.state.lock();
|
||||
if let Some(problems) = m.integrity.clone() {
|
||||
return (problems, true, m.running);
|
||||
}
|
||||
@@ -62,13 +86,13 @@ impl Core {
|
||||
m.running = true;
|
||||
drop(m);
|
||||
|
||||
let core = self.clone();
|
||||
let this = self.clone();
|
||||
if let Err(error) = self.services.spawn_job("pdfs-integrity-check", move || {
|
||||
let job = core
|
||||
let job = this
|
||||
.transfers
|
||||
.begin_background_job("Checking the cache database");
|
||||
job.detail("Verifying every page");
|
||||
let problems = match core.db.integrity_check() {
|
||||
let problems = match this.db.integrity_check() {
|
||||
Ok(problems) => problems,
|
||||
Err(e) => vec![format!("integrity check failed: {e:?}")],
|
||||
};
|
||||
@@ -77,7 +101,7 @@ impl Core {
|
||||
} else {
|
||||
warn!(problems = problems.len(), "cache database integrity check");
|
||||
}
|
||||
let mut m = core.maintenance.lock();
|
||||
let mut m = this.state.lock();
|
||||
m.integrity = Some(problems);
|
||||
m.running = false;
|
||||
}) {
|
||||
@@ -94,7 +118,7 @@ impl Core {
|
||||
/// gain from overlapping them — and the result of a check outlives the request
|
||||
/// that asked for it, because the request is answered before the check finishes.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Maintenance {
|
||||
struct MaintenanceState {
|
||||
/// A vacuum or integrity check is running right now.
|
||||
running: bool,
|
||||
/// Findings of the most recent completed deep check. `None` means none has
|
||||
|
||||
+103
-138
@@ -1,7 +1,7 @@
|
||||
//! Mount lifecycle and background-service orchestration.
|
||||
|
||||
use super::*;
|
||||
use pdfs_core::lifecycle::{ServiceBoard, Services, Wake};
|
||||
use pdfs_core::lifecycle::{Service, ServiceBoard, Services};
|
||||
|
||||
/// Why a [`mount`] call returned. Lets the daemon decide whether to exit (clean
|
||||
/// shutdown) or remount (the mount went away under it).
|
||||
@@ -490,12 +490,21 @@ pub(crate) fn mount_with(
|
||||
let (sync_tx, sync_rx) = std::sync::mpsc::channel::<sync::SyncMsg>();
|
||||
|
||||
let pause = pause::SyncPause::load(db.clone());
|
||||
let events: Arc<events::EventHub> = Arc::default();
|
||||
let gallery_dir = control_socket.with_file_name("gallery-catalog");
|
||||
let gallery =
|
||||
gallery_session.map(|session| Arc::new(super::gallery::Gallery::new(gallery_dir, session)));
|
||||
let gallery = gallery_session.map(|session| {
|
||||
Arc::new(super::gallery::Gallery::new(
|
||||
gallery_dir,
|
||||
session,
|
||||
client.clone(),
|
||||
events.clone(),
|
||||
db.clone(),
|
||||
))
|
||||
});
|
||||
let cache = Arc::new(cache);
|
||||
let shutdown = Arc::new(crate::shutdown::Shutdown::default());
|
||||
let transfers = TransferRegistry::new();
|
||||
let services = ServiceBoard::default();
|
||||
let sync = sync::SyncParts {
|
||||
store: db.clone(),
|
||||
drive: drive.clone(),
|
||||
@@ -511,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,
|
||||
@@ -530,7 +545,11 @@ pub(crate) fn mount_with(
|
||||
client,
|
||||
gallery,
|
||||
rt: rt.clone(),
|
||||
maintenance: Arc::new(Mutex::new(Default::default())),
|
||||
maintenance: super::maintenance::Maintenance::new(
|
||||
db.clone(),
|
||||
transfers.clone(),
|
||||
services.clone(),
|
||||
),
|
||||
primary_root_uid: root.uid.clone(),
|
||||
state: state.clone(),
|
||||
cache,
|
||||
@@ -550,14 +569,15 @@ pub(crate) fn mount_with(
|
||||
writes: super::writes::WriteState::new(),
|
||||
session: super::session::SessionCells::new(),
|
||||
shutdown,
|
||||
services: ServiceBoard::default(),
|
||||
services: services.clone(),
|
||||
photo_jobs: super::photos::PhotoJobs::new(),
|
||||
local_first,
|
||||
transfers,
|
||||
sync,
|
||||
events: Arc::new(Default::default()),
|
||||
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()),
|
||||
};
|
||||
@@ -568,14 +588,17 @@ 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.hydrate_pending();
|
||||
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.
|
||||
core.recover_fsynced_writes();
|
||||
core.recovery().recover_fsynced_writes();
|
||||
// And finally the staged blobs neither of those accounts for: bytes a
|
||||
// failed release left behind with nothing pointing at them.
|
||||
core.reconcile_staging();
|
||||
core.recovery().reconcile_staging();
|
||||
// Several drain workers over one queue. One thread meant a single large
|
||||
// upload held every queued rename, trash and small write behind it for as
|
||||
// long as it ran; the claim column (`Db::claim_next_due_op`) keeps the
|
||||
@@ -587,93 +610,49 @@ pub(crate) fn mount_with(
|
||||
// in-process remount into a second generation of drain workers, sync engines
|
||||
// and sweeps all operating on a mount that no longer exists (`docs/BUGS.md` B44).
|
||||
let mut workers = Services::new(core.services.clone());
|
||||
for worker in 0..DRAIN_WORKERS {
|
||||
let drain_core = core.clone();
|
||||
// The drain workers wait on their own condvar, which a stop has to
|
||||
// notify; one notify wakes them all.
|
||||
let wake: Option<Wake> = (worker == 0).then(|| {
|
||||
let core = core.clone();
|
||||
Box::new(move || core.wake_drain()) as Wake
|
||||
});
|
||||
let spawned = workers.spawn(&format!("pdfs-drain-{worker}"), wake, move || {
|
||||
drain_core.run_pending_drain(worker == 0)
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
let mut list: Vec<Box<dyn Service>> = Vec::new();
|
||||
for index in 0..DRAIN_WORKERS {
|
||||
list.push(Box::new(services::DrainWorker {
|
||||
core: core.clone(),
|
||||
index,
|
||||
}));
|
||||
}
|
||||
|
||||
// Start the folder-sync engine. It watches every mirror folder, polls the
|
||||
// remotes, and reconciles on its own thread — never in front of a FUSE call.
|
||||
// It waits on its channel, so a stop sends it `Stop`.
|
||||
{
|
||||
let syncer = core.syncer();
|
||||
let tx = core.sync.tx.clone();
|
||||
let wake: Wake = Box::new(move || {
|
||||
let _ = tx.send(sync::SyncMsg::Stop);
|
||||
});
|
||||
if let Err(error) =
|
||||
workers.spawn("pdfs-sync", Some(wake), move || sync::run(syncer, sync_rx))
|
||||
{
|
||||
warn!(%error, "failed to start sync engine");
|
||||
}
|
||||
}
|
||||
// A timed pause persisted by an earlier run still has to end on time.
|
||||
if let Some(until) = core.pause.deadline() {
|
||||
core.arm_pause_timer(until);
|
||||
}
|
||||
|
||||
// Reconcile leftover `(sync-conflict …)` copies: drop the ones that turned
|
||||
// out identical to the live file, surface the ones that genuinely diverge.
|
||||
// Its own thread — it enumerates and trashes, and must never block a FUSE call.
|
||||
list.push(Box::new(services::SyncEngine {
|
||||
syncer: core.syncer(),
|
||||
tx: core.sync.tx.clone(),
|
||||
rx: sync_rx,
|
||||
}));
|
||||
// `Off` skips the thread entirely rather than starting an idle one, so the
|
||||
// setting is verifiable from the outside (`ls /proc/<pid>/task/*/comm`).
|
||||
if sweep_mode == SweepMode::Off {
|
||||
info!("conflict sweep disabled by configuration");
|
||||
} else {
|
||||
info!(mode = ?sweep_mode, "conflict sweep enabled");
|
||||
let sweep_core = core.clone();
|
||||
let spawned = workers.spawn("pdfs-conflict-sweep", None, move || {
|
||||
sweep_core.run_conflict_sweep_loop()
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
list.push(Box::new(services::ConflictSweep(core.sweeper())));
|
||||
}
|
||||
|
||||
// Watch the link for the life of the mount: a mount from the cache waits for
|
||||
// the network to come back, and an online one can lose it at any moment and
|
||||
// must notice it coming back just the same.
|
||||
{
|
||||
let probe_core = core.clone();
|
||||
let spawned = workers.spawn("pdfs-online-probe", None, move || {
|
||||
probe_core.run_online_probe()
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
}
|
||||
|
||||
// Keep pinned files on this computer through changes made elsewhere, and
|
||||
// fetch the ones a failed or missed download left out (`docs/BUGS.md`
|
||||
// B282). Its own thread: a check lists folders and downloads files.
|
||||
{
|
||||
let keeper_core = core.clone();
|
||||
let spawned = workers.spawn("pdfs-pin-keeper", None, move || {
|
||||
keeper_core.run_pin_keeper()
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
}
|
||||
|
||||
// Keep the launcher prompt's "This computer" index fresh. Its own thread:
|
||||
// the walk is I/O-heavy and must never sit in front of a FUSE callback.
|
||||
list.push(Box::new(services::OnlineProbe(core.online_probe())));
|
||||
list.push(Box::new(services::PinKeeper(core.pin_keeper())));
|
||||
if matches!(host, Host::Daemon) {
|
||||
if let Some(gallery) = &core.gallery {
|
||||
workers.spawn_task(&rt, "pdfs-gallery", gallery.clone().poll(core.clone()));
|
||||
}
|
||||
let db = core.db.clone();
|
||||
let indexing = core.indexing.clone();
|
||||
let transfers = core.transfers.clone();
|
||||
let mountpoint = mountpoint.to_path_buf();
|
||||
let shutdown = core.shutdown.clone();
|
||||
let spawned = workers.spawn("pdfs-localindex", None, move || {
|
||||
run_local_index(db, indexing, transfers, mountpoint, shutdown)
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
list.push(Box::new(services::LocalIndex {
|
||||
db: core.db.clone(),
|
||||
indexing: core.indexing.clone(),
|
||||
transfers: core.transfers.clone(),
|
||||
mountpoint: mountpoint.to_path_buf(),
|
||||
shutdown: core.shutdown.clone(),
|
||||
}));
|
||||
}
|
||||
for service in list {
|
||||
let started = workers.start(service);
|
||||
keep_or_abandon(&core, control_socket, &mut workers, started)?;
|
||||
}
|
||||
if matches!(host, Host::Daemon)
|
||||
&& let Some(gallery) = &core.gallery
|
||||
{
|
||||
workers.spawn_task(&rt, "pdfs-gallery", gallery.clone().poll());
|
||||
}
|
||||
// A timed pause persisted by an earlier run still has to end on time.
|
||||
if let Some(until) = core.pause.deadline() {
|
||||
core.arm_pause_timer(until);
|
||||
}
|
||||
|
||||
// Bind the control socket before the FUSE session takes over the thread. A
|
||||
@@ -713,23 +692,14 @@ pub(crate) fn mount_with(
|
||||
// mid-transfer can abort it rather than block `join` (see `abort_fuse_connection`).
|
||||
let main_conn = fuse_connection_id(mountpoint);
|
||||
{
|
||||
let control_core = core.clone();
|
||||
let username = username.clone();
|
||||
let mountpoint = mountpoint.to_path_buf();
|
||||
// The listener blocks in `accept`, which only returns when a connection
|
||||
// arrives, so a stop connects to it. Connect while the socket still
|
||||
// exists, which is the point of the poke, then unlink it so nothing else
|
||||
// can arrive behind it. The listener checks the stop flag after every
|
||||
// accept, so a connection that races the unlink cannot put it back to
|
||||
// sleep.
|
||||
let socket = control_socket.to_path_buf();
|
||||
let wake: Wake = Box::new(move || {
|
||||
let _ = std::os::unix::net::UnixStream::connect(&socket);
|
||||
let _ = std::fs::remove_file(&socket);
|
||||
});
|
||||
match workers.spawn("pdfs-control", Some(wake), move || {
|
||||
run_control_socket(control_core, username, mountpoint, listener)
|
||||
}) {
|
||||
let control = services::ControlListener {
|
||||
core: core.clone(),
|
||||
username: username.clone(),
|
||||
mountpoint: mountpoint.to_path_buf(),
|
||||
listener,
|
||||
socket: control_socket.to_path_buf(),
|
||||
};
|
||||
match workers.start(Box::new(control)) {
|
||||
Ok(()) => {}
|
||||
Err(error) => {
|
||||
// A failure here abandons the mount, so the background threads
|
||||
@@ -751,34 +721,19 @@ pub(crate) fn mount_with(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Publishes what changes without one place to publish it from (status,
|
||||
// transfers, sync progress) to the front-ends subscribed on that socket.
|
||||
{
|
||||
let sampler_core = core.clone();
|
||||
let username = username.clone();
|
||||
let mountpoint = mountpoint.to_path_buf();
|
||||
if let Err(error) = workers.spawn("pdfs-events", None, move || {
|
||||
events::run_event_sampler(sampler_core, username, mountpoint)
|
||||
}) {
|
||||
// Not fatal: front-ends still get every published change, only
|
||||
// not the sampled ones.
|
||||
warn!(error = %error, "could not start the event sampler");
|
||||
}
|
||||
}
|
||||
// The supervisor watches the pool and answers the systemd watchdog. Started
|
||||
// after the listener, because its liveness probe is a round trip over that
|
||||
// socket.
|
||||
{
|
||||
let supervisor_core = core.clone();
|
||||
let socket = control_socket.to_path_buf();
|
||||
if let Err(error) = workers.spawn("pdfs-supervisor", None, move || {
|
||||
supervisor::run(supervisor_core, socket)
|
||||
}) {
|
||||
// Not fatal: the mount works without a supervisor, it just goes back
|
||||
// to being undiagnosable if it wedges.
|
||||
warn!(error = %error, "could not start the daemon supervisor");
|
||||
}
|
||||
}
|
||||
// The supervisor's liveness probe is a round trip over the control socket,
|
||||
// so it starts after the listener. Both are optional.
|
||||
let sampler = services::EventSampler {
|
||||
core: core.clone(),
|
||||
username: username.clone(),
|
||||
mountpoint: mountpoint.to_path_buf(),
|
||||
};
|
||||
let watchdog = services::Supervisor {
|
||||
core: core.clone(),
|
||||
socket: control_socket.to_path_buf(),
|
||||
};
|
||||
start_late(&mut workers, Box::new(sampler));
|
||||
start_late(&mut workers, Box::new(watchdog));
|
||||
// The mount is live and the control socket answers: this is the moment the
|
||||
// unit is actually usable, which is what `Type=notify` reports. Whatever
|
||||
// failure an earlier attempt recorded for the front ends is over.
|
||||
@@ -831,12 +786,13 @@ pub(crate) fn mount_with(
|
||||
// Hold off a shutdown while changes exist only here (B66). Only the real
|
||||
// daemon: a simulation's queue is not the user's data.
|
||||
if matches!(host, Host::Daemon) {
|
||||
let inhibit_core = core.clone();
|
||||
if let Err(error) = workers.spawn("pdfs-inhibit", None, move || {
|
||||
crate::inhibit::run(inhibit_core)
|
||||
}) {
|
||||
warn!(%error, "start the shutdown inhibitor failed");
|
||||
}
|
||||
start_late(
|
||||
&mut workers,
|
||||
Box::new(services::Inhibitor {
|
||||
db: core.db.clone(),
|
||||
shutdown: core.shutdown.clone(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Stop signals (SIGTERM from `systemctl --user stop`, SIGINT from Ctrl-C)
|
||||
@@ -985,6 +941,15 @@ fn abandon_workers(core: &Core, control_socket: &Path, workers: Services) {
|
||||
halt_workers(core, control_socket, workers);
|
||||
}
|
||||
|
||||
/// Start a service once the session is live. Past that point a failure no
|
||||
/// longer abandons the mount, so even a required one is only logged.
|
||||
fn start_late(workers: &mut Services, service: Box<dyn Service>) {
|
||||
let name = service.name();
|
||||
if let Err(error) = workers.start(service) {
|
||||
warn!(service = name, %error, "service did not start");
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep a worker the mount just spawned, or, if the spawn failed, stop the
|
||||
/// ones already running and hand the error back.
|
||||
fn keep_or_abandon(
|
||||
|
||||
@@ -709,12 +709,32 @@ fn run_bounded(mut command: Command, timeout: Duration) -> Result<Vec<u8>, ToolE
|
||||
let _ = child.wait();
|
||||
return Err(ToolError::Unavailable);
|
||||
};
|
||||
let reader = std::thread::spawn(move || {
|
||||
let mut output = Vec::new();
|
||||
stdout.read_to_end(&mut output).map(|_| output)
|
||||
});
|
||||
// Scoped, so the reader cannot outlive the call even when the child
|
||||
// overruns and is killed.
|
||||
std::thread::scope(|scope| {
|
||||
let reader = scope.spawn(move || {
|
||||
let mut output = Vec::new();
|
||||
stdout.read_to_end(&mut output).map(|_| output)
|
||||
});
|
||||
let status = wait_bounded(&mut child, timeout);
|
||||
let output = reader
|
||||
.join()
|
||||
.ok()
|
||||
.and_then(Result::ok)
|
||||
.ok_or(ToolError::Unavailable)?;
|
||||
match status {
|
||||
Some(true) => Ok(output),
|
||||
Some(false) => Err(ToolError::Failed),
|
||||
None => Err(ToolError::Unavailable),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Wait for `child` to exit, up to `timeout`, killing it past that. `None`
|
||||
/// when it overran or could not be waited for.
|
||||
fn wait_bounded(child: &mut std::process::Child, timeout: Duration) -> Option<bool> {
|
||||
let started = Instant::now();
|
||||
let status = loop {
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break Some(status.success()),
|
||||
Ok(None) if started.elapsed() < timeout => {
|
||||
@@ -726,16 +746,6 @@ fn run_bounded(mut command: Command, timeout: Duration) -> Result<Vec<u8>, ToolE
|
||||
break None;
|
||||
}
|
||||
}
|
||||
};
|
||||
let output = reader
|
||||
.join()
|
||||
.ok()
|
||||
.and_then(Result::ok)
|
||||
.ok_or(ToolError::Unavailable)?;
|
||||
match status {
|
||||
Some(true) => Ok(output),
|
||||
Some(false) => Err(ToolError::Failed),
|
||||
None => Err(ToolError::Unavailable),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+20
-103
@@ -1,6 +1,7 @@
|
||||
//! Revision-reader cache and streamed range-read subsystem.
|
||||
|
||||
use super::*;
|
||||
use pdfs_vfs::open::{ReadFailure, assemble_open_read};
|
||||
|
||||
/// A read of an unpinned video at least this large streams *without* persisting
|
||||
/// its blocks to the on-disk cache. Playing a 2 GB film would otherwise pour it
|
||||
@@ -1049,10 +1050,11 @@ impl Core {
|
||||
offset: u64,
|
||||
size: u64,
|
||||
) -> Result<Vec<u8>, Errno> {
|
||||
let read = assemble_open_read(file, len, uid, base_size, written, offset, size, |s, n| {
|
||||
let read = assemble_open_read(file, len, base_size, written, offset, size, |s, n| {
|
||||
self.read_range(uid, base_mtime, base_size, s, n, true)
|
||||
.map(Some)
|
||||
})?;
|
||||
})
|
||||
.map_err(|failure| open_read_errno(uid, failure))?;
|
||||
Ok(read.unwrap_or_default())
|
||||
}
|
||||
|
||||
@@ -1075,9 +1077,10 @@ impl Core {
|
||||
offset: u64,
|
||||
size: u64,
|
||||
) -> Result<Option<Vec<u8>>, Errno> {
|
||||
assemble_open_read(file, len, uid, base_size, written, offset, size, |s, n| {
|
||||
assemble_open_read(file, len, base_size, written, offset, size, |s, n| {
|
||||
Ok(self.cached_range(uid, base_mtime, base_size, s, n))
|
||||
})
|
||||
.map_err(|failure| open_read_errno(uid, failure))
|
||||
}
|
||||
|
||||
/// Bytes `[offset, offset + size)` of file `ino` as `read` would serve
|
||||
@@ -1094,16 +1097,12 @@ impl Core {
|
||||
offset: u64,
|
||||
size: u64,
|
||||
) -> Result<Option<Vec<u8>>, Errno> {
|
||||
let handle = self.state().active_writes.get(&ino).map(|h| {
|
||||
(
|
||||
h.file.clone(),
|
||||
h.len,
|
||||
h.uid.clone(),
|
||||
h.base_mtime,
|
||||
h.base_size,
|
||||
h.written.clone(),
|
||||
)
|
||||
});
|
||||
// A writer still open, or one whose release is still queueing it.
|
||||
let handle = self
|
||||
.state()
|
||||
.open
|
||||
.reader(ino)
|
||||
.map(|v| (v.file, v.len, v.uid, v.base_mtime, v.base_size, v.written));
|
||||
if let Some((file, len, uid, base_mtime, base_size, written)) = handle {
|
||||
return self.serve_open_read_local(
|
||||
&file, len, &uid, base_mtime, base_size, &written, offset, size,
|
||||
@@ -1305,47 +1304,16 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes `[offset, offset + size)` of a file open for writing: authored
|
||||
/// ranges from its scratch `file`, the rest from its base through `base`,
|
||||
/// and zeros past the base. `Ok(None)` when `base` says it cannot answer.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn assemble_open_read(
|
||||
file: &File,
|
||||
len: u64,
|
||||
uid: &NodeUid,
|
||||
base_size: u64,
|
||||
written: &Intervals,
|
||||
offset: u64,
|
||||
size: u64,
|
||||
mut base: impl FnMut(u64, u64) -> Result<Option<Vec<u8>>, Errno>,
|
||||
) -> Result<Option<Vec<u8>>, Errno> {
|
||||
if offset >= len || size == 0 {
|
||||
return Ok(Some(Vec::new()));
|
||||
}
|
||||
let end = offset.saturating_add(size).min(len);
|
||||
let mut out = Vec::with_capacity((end - offset) as usize);
|
||||
for (s, e, authored) in written.segments(offset, end) {
|
||||
if authored {
|
||||
let mut buf = vec![0u8; (e - s) as usize];
|
||||
file.read_exact_at(&mut buf, s).map_err(|err| {
|
||||
warn!(%uid, error = %err, "scratch read failed");
|
||||
Errno::EIO
|
||||
})?;
|
||||
out.extend_from_slice(&buf);
|
||||
} else {
|
||||
let bend = e.min(base_size);
|
||||
if s < bend {
|
||||
match base(s, bend - s)? {
|
||||
Some(bytes) => out.extend_from_slice(&bytes),
|
||||
None => return Ok(None),
|
||||
}
|
||||
}
|
||||
// Anything past the base is a hole: zero-fill.
|
||||
let zeros = e.saturating_sub(s.max(base_size));
|
||||
out.resize(out.len() + zeros as usize, 0);
|
||||
/// The errno for a read of an open file that failed: the base's own, or
|
||||
/// `EIO` for the scratch file.
|
||||
fn open_read_errno(uid: &NodeUid, failure: ReadFailure<Errno>) -> Errno {
|
||||
match failure {
|
||||
ReadFailure::Base(errno) => errno,
|
||||
ReadFailure::Scratch(error) => {
|
||||
warn!(%uid, %error, "scratch read failed");
|
||||
Errno::EIO
|
||||
}
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1500,54 +1468,3 @@ mod prefetch_tests {
|
||||
assert!(prefetch.streams.lock().len() <= MAX_PREFETCH_STREAMS + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod open_read_tests {
|
||||
use super::*;
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
|
||||
|
||||
fn scratch(bytes: &[u8]) -> (File, PathBuf) {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"pdfs-open-read-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
let mut file = File::options()
|
||||
.create_new(true)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.unwrap();
|
||||
file.write_all(bytes).unwrap();
|
||||
(file, path)
|
||||
}
|
||||
|
||||
/// The dispatch loop answers from what is on this machine and says so
|
||||
/// when the base would have to be downloaded, for a worker to do it
|
||||
/// (`docs/BUGS.md` B227).
|
||||
#[test]
|
||||
fn a_read_needing_the_base_says_so_instead_of_fetching() {
|
||||
let uid = NodeUid::new(VolumeId::from("v"), LinkId::from("f"));
|
||||
let (file, path) = scratch(b"ABCDEFGH");
|
||||
let mut written = Intervals::default();
|
||||
written.add(0, 4);
|
||||
|
||||
let authored = assemble_open_read(&file, 8, &uid, 8, &written, 0, 4, |_, _| {
|
||||
panic!("an authored range never asks the base")
|
||||
});
|
||||
assert_eq!(authored.unwrap().as_deref(), Some(&b"ABCD"[..]));
|
||||
|
||||
let missing = assemble_open_read(&file, 8, &uid, 8, &written, 2, 6, |_, _| Ok(None));
|
||||
assert_eq!(missing.unwrap(), None);
|
||||
|
||||
let base = assemble_open_read(&file, 10, &uid, 8, &written, 2, 8, |s, n| {
|
||||
assert_eq!((s, n), (4, 4));
|
||||
Ok(Some(b"efgh".to_vec()))
|
||||
});
|
||||
assert_eq!(base.unwrap().as_deref(), Some(&b"CDefgh\0\0"[..]));
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! recovering writes that were fsynced but not queued when the daemon stopped.
|
||||
|
||||
use super::*;
|
||||
use pdfs_vfs::namespace::{ReplaceOutcome, settle_from_drive, settle_from_queue};
|
||||
|
||||
impl Core {
|
||||
/// Rehydrate the in-memory `State` maps from the DB on mount, so a cold
|
||||
@@ -96,11 +97,173 @@ impl Core {
|
||||
st.hydrate_access();
|
||||
|
||||
// Pass 3: rebuild child listings for fully-enumerated folders.
|
||||
let listings = listed_children(&st.entries, listed_dirs);
|
||||
let listings = crate::state::listed_children(&st.entries, listed_dirs);
|
||||
st.children.extend(listings);
|
||||
info!(nodes = st.entries.len(), "hydrated metadata cache from db");
|
||||
}
|
||||
|
||||
/// Startup recovery of the queue, with this daemon as its host.
|
||||
pub(crate) fn recovery(&self) -> Recovery {
|
||||
Recovery {
|
||||
db: self.db.clone(),
|
||||
cache: self.cache.clone(),
|
||||
writes: self.writes.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What recovery needs from the rest of the daemon.
|
||||
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
|
||||
/// restart. Holds the database, the content cache and the write-back's state;
|
||||
/// queueing a recovered write goes through [`RecoveryHost`].
|
||||
pub(crate) struct Recovery {
|
||||
db: Arc<Db>,
|
||||
cache: Arc<ContentCache>,
|
||||
writes: writes::WriteState,
|
||||
host: Arc<dyn RecoveryHost>,
|
||||
}
|
||||
|
||||
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 —
|
||||
@@ -109,7 +272,7 @@ impl Core {
|
||||
///
|
||||
/// A row whose blob has gone missing is dropped: there is nothing left to
|
||||
/// upload, and keeping it would fail forever.
|
||||
pub(super) fn hydrate_pending(&self) {
|
||||
pub(crate) fn hydrate_pending(&self) {
|
||||
let ops = match self.db.pending_ops() {
|
||||
Ok(ops) => ops,
|
||||
Err(e) => {
|
||||
@@ -182,7 +345,7 @@ impl Core {
|
||||
/// `local~` placeholder whose create is gone) is left in place and named in
|
||||
/// the log: unexplained bytes are never evidence that user data is
|
||||
/// disposable.
|
||||
pub(super) fn reconcile_staging(&self) {
|
||||
pub(crate) fn reconcile_staging(&self) {
|
||||
let staged = self.cache.staged_writes();
|
||||
if staged.is_empty() {
|
||||
return;
|
||||
@@ -314,7 +477,7 @@ impl Core {
|
||||
/// Failure is per-write and never fatal: a node that no longer exists, or an
|
||||
/// op that cannot be queued, leaves its blob in `recovery/` for the next run
|
||||
/// (and for a human) instead of taking the mount down.
|
||||
pub(super) fn recover_fsynced_writes(&self) {
|
||||
pub(crate) fn recover_fsynced_writes(&self) {
|
||||
let recovered = self.cache.recovered_writes();
|
||||
if recovered.is_empty() {
|
||||
return;
|
||||
@@ -338,7 +501,7 @@ impl Core {
|
||||
// size, and nothing is interned this early — `hydrate` reads the
|
||||
// size back off `pending` when the node is first looked up, so 0
|
||||
// (no such inode) is correct rather than merely tolerable.
|
||||
match self.enqueue_staged_write(&uid, 0, &blob, meta) {
|
||||
match self.host.queue_recovered(&uid, &blob, meta) {
|
||||
Ok(()) => {
|
||||
self.cache.discard_recovered(&blob);
|
||||
queued += 1;
|
||||
@@ -371,7 +534,7 @@ impl Core {
|
||||
/// content is unrecoverable and nothing will ever mint it a real uid, so
|
||||
/// leaving the row would strand a file in the tree that can be listed but
|
||||
/// never read and never uploaded.
|
||||
pub(super) fn drop_unrecoverable_op(&self, op: &PendingOp, uid: &NodeUid) {
|
||||
fn drop_unrecoverable_op(&self, op: &PendingOp, uid: &NodeUid) {
|
||||
let _ = self.db.delete_op(op.id);
|
||||
if is_local_uid(uid) {
|
||||
error!(%uid, name = op.name.as_deref().unwrap_or("?"),
|
||||
|
||||
@@ -453,11 +453,7 @@ impl Core {
|
||||
// longer has that uid, so the move went ahead under an open write.
|
||||
let mut writing = false;
|
||||
self.for_each_state(|st| {
|
||||
writing = st
|
||||
.active_writes
|
||||
.keys()
|
||||
.chain(&st.releasing)
|
||||
.any(|&open| ino_is_under(st, open, ino));
|
||||
writing = st.open.owed(false).any(|open| ino_is_under(st, open, ino));
|
||||
});
|
||||
Ok(writing)
|
||||
}
|
||||
|
||||
@@ -485,11 +485,8 @@ impl Core {
|
||||
// Unsaved writes, or a release still queueing them, to the file or,
|
||||
// for a folder, to any file below it.
|
||||
let unsaved = st
|
||||
.active_writes
|
||||
.iter()
|
||||
.filter(|(_, w)| w.dirty)
|
||||
.map(|(&open, _)| open)
|
||||
.chain(st.releasing.iter().copied())
|
||||
.open
|
||||
.owed(true)
|
||||
.any(|open| relocate::ino_is_under(&st, open, ino));
|
||||
(entry.node.name.clone(), entry.node.is_folder(), unsaved)
|
||||
};
|
||||
|
||||
@@ -2,7 +2,49 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Search over the database's node and home indexes. Holds the database, the
|
||||
/// content cache (to say whether a hit is on this computer), the on-demand
|
||||
/// mounts (to say which folders a hit can be opened through) and the home
|
||||
/// indexer's busy flag.
|
||||
pub(crate) struct Search {
|
||||
db: Arc<Db>,
|
||||
cache: Arc<ContentCache>,
|
||||
mounts: Arc<Mutex<mount::SecondaryMountRegistry<SecondaryMount>>>,
|
||||
indexing: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// Search, over this daemon's indexes.
|
||||
pub(crate) fn searcher(&self) -> Search {
|
||||
Search {
|
||||
db: self.db.clone(),
|
||||
cache: self.cache.clone(),
|
||||
mounts: self.mounts.clone(),
|
||||
indexing: self.indexing.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// See [`Search::roots`].
|
||||
pub(super) fn search_roots(&self) -> SearchRoots {
|
||||
self.searcher().roots()
|
||||
}
|
||||
}
|
||||
|
||||
impl Search {
|
||||
/// Whether the home indexer is walking right now.
|
||||
pub(crate) fn indexing(&self) -> bool {
|
||||
self.indexing.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The pinned uids, expanded through pinned folders, as one query.
|
||||
fn pinned_set(&self) -> HashSet<String> {
|
||||
self.db
|
||||
.pinned_uids()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The local locations a search result can be opened through, resolved once
|
||||
/// per search rather than once per hit.
|
||||
///
|
||||
@@ -14,7 +56,7 @@ impl Core {
|
||||
/// This used to be a per-hit call that re-read the sync-folder list and ran
|
||||
/// an ancestor walk per folder, against a candidate pool of up to a
|
||||
/// thousand: the whole cost of a keystroke was in here.
|
||||
pub(super) fn search_roots(&self) -> SearchRoots {
|
||||
pub(super) fn roots(&self) -> SearchRoots {
|
||||
let live_mounts = self.mounts.lock();
|
||||
let folders = self.db.sync_folder_list().unwrap_or_default();
|
||||
SearchRoots {
|
||||
@@ -43,7 +85,7 @@ impl Core {
|
||||
.db
|
||||
.search_in(query, limit, scope)
|
||||
.map_err(|e| CoreError::from_api(&e, "search"))?;
|
||||
let roots = self.search_roots();
|
||||
let roots = self.roots();
|
||||
let pinned = self.pinned_set();
|
||||
Ok(hits
|
||||
.into_iter()
|
||||
@@ -105,7 +147,7 @@ impl Core {
|
||||
// SQLite boundary to `limit` would recreate the old empty-filter bug.
|
||||
let candidate_limit = limit.saturating_mul(10).clamp(100, 1_000);
|
||||
let mut drive_hits = if filters.sources.contains(&SearchSource::Drive) {
|
||||
let roots = self.search_roots();
|
||||
let roots = self.roots();
|
||||
let pinned = self.pinned_set();
|
||||
self.db
|
||||
.search_candidates(query, candidate_limit)
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
//! The long-lived loops a mount runs, each as a [`Service`].
|
||||
//!
|
||||
//! Each type here names its thread, says how a stop reaches it and whether the
|
||||
//! mount can do without it. `mount.rs` builds the list and starts it with
|
||||
//! [`Services::start`](pdfs_core::lifecycle::Services::start); a stop wakes and
|
||||
//! joins them in reverse order.
|
||||
|
||||
use std::os::unix::net::UnixListener;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use pdfs_core::lifecycle::{Service, Wake};
|
||||
use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_store::db::Db;
|
||||
|
||||
use super::Core;
|
||||
use super::background::run_local_index;
|
||||
use super::control::run_control_socket;
|
||||
use super::events::{EventHub, run_event_sampler};
|
||||
use super::sync;
|
||||
use super::transfers::TransferRegistry;
|
||||
|
||||
/// One of the threads that send queued changes to Drive. The drain workers wait
|
||||
/// on one condvar, which a stop has to notify; one notify wakes them all, so
|
||||
/// only the first worker carries the wake.
|
||||
pub(crate) struct DrainWorker {
|
||||
pub(crate) core: Core,
|
||||
pub(crate) index: usize,
|
||||
}
|
||||
|
||||
impl Service for DrainWorker {
|
||||
fn name(&self) -> String {
|
||||
format!("pdfs-drain-{}", self.index)
|
||||
}
|
||||
|
||||
fn wake(&self) -> Option<Wake> {
|
||||
let core = self.core.clone();
|
||||
(self.index == 0).then(|| Box::new(move || core.wake_drain()) as Wake)
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
self.core.run_pending_drain(self.index == 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder-sync engine. It watches every mirror folder, polls the remotes and
|
||||
/// reconciles on its own thread, never in front of a FUSE call. It waits on its
|
||||
/// channel, so a stop sends it `Stop`.
|
||||
///
|
||||
/// Optional: the mount still serves files without it.
|
||||
pub(crate) struct SyncEngine {
|
||||
pub(crate) syncer: sync::Syncer,
|
||||
pub(crate) tx: std::sync::mpsc::Sender<sync::SyncMsg>,
|
||||
pub(crate) rx: std::sync::mpsc::Receiver<sync::SyncMsg>,
|
||||
}
|
||||
|
||||
impl Service for SyncEngine {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-sync".to_owned()
|
||||
}
|
||||
|
||||
fn required(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn wake(&self) -> Option<Wake> {
|
||||
let tx = self.tx.clone();
|
||||
Some(Box::new(move || {
|
||||
let _ = tx.send(sync::SyncMsg::Stop);
|
||||
}))
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
let Self { syncer, rx, .. } = *self;
|
||||
sync::run(syncer, rx);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconciles leftover `(sync-conflict …)` copies: drops the ones that turned
|
||||
/// out identical to the live file and surfaces the ones that differ. It
|
||||
/// enumerates and trashes, so it must never block a FUSE call.
|
||||
pub(crate) struct ConflictSweep(pub(crate) super::sweep::Sweeper);
|
||||
|
||||
impl Service for ConflictSweep {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-conflict-sweep".to_owned()
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
self.0.run();
|
||||
}
|
||||
}
|
||||
|
||||
/// Watches the link for the life of the mount: a mount from the cache waits
|
||||
/// for the network to come back, and an online one can lose it at any moment.
|
||||
pub(crate) struct OnlineProbe(pub(crate) super::link::OnlineProbe);
|
||||
|
||||
impl Service for OnlineProbe {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-online-probe".to_owned()
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
self.0.run();
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps pinned files on this computer through changes made elsewhere, and
|
||||
/// fetches the ones a failed or missed download left out (`docs/BUGS.md`
|
||||
/// B282). A check lists folders and downloads files.
|
||||
pub(crate) struct PinKeeper(pub(crate) super::keeper::PinKeeper);
|
||||
|
||||
impl Service for PinKeeper {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-pin-keeper".to_owned()
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
self.0.run();
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps the launcher prompt's "This computer" index fresh. The walk is
|
||||
/// I/O-heavy and must never sit in front of a FUSE callback.
|
||||
pub(crate) struct LocalIndex {
|
||||
pub(crate) db: Arc<Db>,
|
||||
pub(crate) indexing: Arc<AtomicBool>,
|
||||
pub(crate) transfers: Arc<TransferRegistry>,
|
||||
pub(crate) mountpoint: PathBuf,
|
||||
pub(crate) shutdown: Arc<Shutdown>,
|
||||
}
|
||||
|
||||
impl Service for LocalIndex {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-localindex".to_owned()
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
let Self {
|
||||
db,
|
||||
indexing,
|
||||
transfers,
|
||||
mountpoint,
|
||||
shutdown,
|
||||
} = *self;
|
||||
run_local_index(db, indexing, transfers, mountpoint, shutdown);
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers the control socket, one job per connection.
|
||||
///
|
||||
/// The listener blocks in `accept`, which only returns when a connection
|
||||
/// arrives, so a stop connects to it. It connects while the socket still
|
||||
/// exists, which is the point of the poke, then unlinks it so nothing else can
|
||||
/// arrive behind it. The listener checks the stop flag after every accept, so
|
||||
/// a connection that races the unlink cannot put it back to sleep. The
|
||||
/// connections it handed off are jobs, which a stop joins; a subscription
|
||||
/// among them waits on its mailbox, so the wake rings every mailbox too.
|
||||
pub(crate) struct ControlListener {
|
||||
pub(crate) core: Core,
|
||||
pub(crate) username: String,
|
||||
pub(crate) mountpoint: PathBuf,
|
||||
pub(crate) listener: UnixListener,
|
||||
pub(crate) socket: PathBuf,
|
||||
}
|
||||
|
||||
impl Service for ControlListener {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-control".to_owned()
|
||||
}
|
||||
|
||||
fn wake(&self) -> Option<Wake> {
|
||||
let socket = self.socket.clone();
|
||||
let events: Arc<EventHub> = self.core.events.clone();
|
||||
Some(Box::new(move || {
|
||||
let _ = std::os::unix::net::UnixStream::connect(&socket);
|
||||
let _ = std::fs::remove_file(&socket);
|
||||
events.wake_all();
|
||||
}))
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
let Self {
|
||||
core,
|
||||
username,
|
||||
mountpoint,
|
||||
listener,
|
||||
..
|
||||
} = *self;
|
||||
run_control_socket(core, username, mountpoint, listener);
|
||||
}
|
||||
}
|
||||
|
||||
/// Publishes what changes without one place to publish it from (status,
|
||||
/// transfers, sync progress) to the front ends subscribed on the control
|
||||
/// socket.
|
||||
///
|
||||
/// Optional: front ends still get every published change, only not the
|
||||
/// sampled ones.
|
||||
pub(crate) struct EventSampler {
|
||||
pub(crate) core: Core,
|
||||
pub(crate) username: String,
|
||||
pub(crate) mountpoint: PathBuf,
|
||||
}
|
||||
|
||||
impl Service for EventSampler {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-events".to_owned()
|
||||
}
|
||||
|
||||
fn required(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
run_event_sampler(self.core, self.username, self.mountpoint);
|
||||
}
|
||||
}
|
||||
|
||||
/// Watches the worker pool and answers the systemd watchdog. Its liveness
|
||||
/// probe is a round trip over the control socket, so it starts after the
|
||||
/// listener.
|
||||
///
|
||||
/// Optional: the mount works without it, only it is no longer diagnosable if
|
||||
/// it wedges.
|
||||
pub(crate) struct Supervisor {
|
||||
pub(crate) core: Core,
|
||||
pub(crate) socket: PathBuf,
|
||||
}
|
||||
|
||||
impl Service for Supervisor {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-supervisor".to_owned()
|
||||
}
|
||||
|
||||
fn required(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
super::supervisor::run(self.core, self.socket);
|
||||
}
|
||||
}
|
||||
|
||||
/// Holds off a shutdown while changes exist only here (B66).
|
||||
///
|
||||
/// Optional: without it a shutdown is not delayed, and queued changes go out
|
||||
/// on the next start.
|
||||
pub(crate) struct Inhibitor {
|
||||
pub(crate) db: Arc<Db>,
|
||||
pub(crate) shutdown: Arc<Shutdown>,
|
||||
}
|
||||
|
||||
impl Service for Inhibitor {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-inhibit".to_owned()
|
||||
}
|
||||
|
||||
fn required(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
super::inhibit::run(&self.db, &self.shutdown);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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() {
|
||||
@@ -883,10 +959,16 @@ mod tests {
|
||||
|
||||
daemon.client.set_online(false);
|
||||
std::fs::write(daemon.mountpoint.join("f.txt"), b"0123456789").unwrap();
|
||||
// Usually the drain meets the outage first. Another caller (the event
|
||||
// poll, a sync pass) can meet it first and take the mount offline,
|
||||
// and then the drain claims nothing and the write has no failed
|
||||
// attempt to wait out. Both must end with the write going out soon
|
||||
// after the link returns.
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
daemon
|
||||
.pending()
|
||||
.is_ok_and(|items| items.iter().any(|item| item.attempts > 0))
|
||||
|| daemon.online().is_ok_and(|online| !online)
|
||||
}));
|
||||
// The drain records the failure just before it takes the mount
|
||||
// offline. Left online, only the event poll would, much later.
|
||||
@@ -1881,6 +1963,250 @@ mod tests {
|
||||
.map_or(0, |c| c.value)
|
||||
}
|
||||
|
||||
/// Once the watch has been live for a pass, a pass reads again only what
|
||||
/// the watcher reported, and that is enough to find every change: 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 a_trusted_local_dirty_set_stands_in_for_the_walk() {
|
||||
// The log is shared by every test in the process: drop what earlier
|
||||
// tests left in it, so only this daemon's lines are counted.
|
||||
take_logged();
|
||||
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}");
|
||||
assert!(counted(&settled, "local reused") > 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}");
|
||||
// Still taken from the last pass's walk: none of the passes since
|
||||
// changed anything on disk, so each kept its walk for the next.
|
||||
assert!(counted(&after, "local reused") > 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);
|
||||
}
|
||||
|
||||
/// A sync root moved away and made again in its place is a new folder
|
||||
/// on disk, which the old watch does not see. The engine watches it again
|
||||
/// once it is back, and walks it once more after, so a file written in
|
||||
/// it as the watch was set up still reaches Drive without waiting for the
|
||||
/// poll (`root`).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_root_made_again_is_watched_again() {
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("root-again");
|
||||
let (daemon, folder, _client) =
|
||||
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let local = dir.join("local");
|
||||
let away = dir.join("away");
|
||||
std::fs::rename(&local, &away).unwrap();
|
||||
let _ = daemon.request(&Request::SyncNow { id: Some(folder) });
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
take_logged()
|
||||
.iter()
|
||||
.any(|line| line.contains("to=suspended (RootMissing)"))
|
||||
}));
|
||||
// A new folder in the old one's place, with the same files.
|
||||
std::fs::create_dir(&local).unwrap();
|
||||
for name in ["a.txt", "b.txt"] {
|
||||
std::fs::copy(away.join(name), local.join(name)).unwrap();
|
||||
}
|
||||
let _ = daemon.request(&Request::SyncNow { id: Some(folder) });
|
||||
// The pass that finds it back walks it in full, and the watches are
|
||||
// set up again after it.
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
take_logged().iter().any(|line| {
|
||||
line.contains("from=suspended (RootMissing)") && line.contains("to=following")
|
||||
})
|
||||
}));
|
||||
// Written as that pass ends, which may be before the watch is set up
|
||||
// again: the event is then lost, and only the pass the new watch
|
||||
// brings about finds the file. Nothing else asks for one, and the
|
||||
// poll is two minutes off.
|
||||
std::fs::write(local.join("c.txt"), b"three").unwrap();
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(60), || drive
|
||||
.lookup("mirrored/c.txt")
|
||||
.is_some()),
|
||||
"a file written in the root made again reaches Drive"
|
||||
);
|
||||
assert!(drive.lookup("mirrored/a.txt").is_some());
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A sync root replaced between two passes is never seen missing, and
|
||||
/// the watch stays on the folder moved away. The pass sees the root is
|
||||
/// another folder, and the engine watches the new one (`root`).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_root_replaced_between_passes_is_watched_again() {
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("root-replaced");
|
||||
let (daemon, folder, _client) =
|
||||
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let local = dir.join("local");
|
||||
let away = dir.join("away");
|
||||
std::fs::rename(&local, &away).unwrap();
|
||||
std::fs::create_dir(&local).unwrap();
|
||||
for name in ["a.txt", "b.txt"] {
|
||||
std::fs::copy(away.join(name), local.join(name)).unwrap();
|
||||
}
|
||||
take_logged();
|
||||
let _ = daemon.request(&Request::SyncNow { id: Some(folder) });
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
take_logged()
|
||||
.iter()
|
||||
.any(|line| line.contains("the folder's root was replaced"))
|
||||
}));
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
std::fs::write(local.join("c.txt"), b"three").unwrap();
|
||||
// Only the watch can bring this pass about: the poll is two minutes
|
||||
// off.
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(60), || drive
|
||||
.lookup("mirrored/c.txt")
|
||||
.is_some()),
|
||||
"a file written in the root put in place reaches Drive"
|
||||
);
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An effect a daemon sent and never heard back from is `unsure` at the
|
||||
/// next start. One the folder still needs is sent again, and settles; one
|
||||
/// it no longer needs is settled by the first pass that looks (`effect`).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn an_effect_left_unsure_by_a_stop_is_sent_again_or_settled() {
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("unsure-effect");
|
||||
let (daemon, folder, client) = start_mirror(&drive, &dir, &[("a.txt", b"one")]);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
// What a daemon killed while it sent two uploads leaves: one landed
|
||||
// (a.txt is on Drive), the other never went out.
|
||||
let sent = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as i64
|
||||
- 10;
|
||||
let db = reopen(&dir);
|
||||
db.sync_intent_issue(folder, "a.txt", "upload", sent)
|
||||
.unwrap();
|
||||
db.sync_intent_issue(folder, "new.txt", "upload", sent)
|
||||
.unwrap();
|
||||
drop(db);
|
||||
std::fs::write(dir.join("local").join("new.txt"), b"new").unwrap();
|
||||
take_logged();
|
||||
let daemon = Daemon::start(&dir, client).unwrap();
|
||||
assert!(wait_until(Duration::from_secs(60), || drive
|
||||
.lookup("mirrored/new.txt")
|
||||
.is_some()));
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let logged = take_logged();
|
||||
let has = |text: &str| logged.iter().any(|line| line.contains(text));
|
||||
assert!(
|
||||
has("effects=2") && has("did not hear back from"),
|
||||
"{logged:#?}"
|
||||
);
|
||||
assert!(
|
||||
has("sending again an effect a stopped daemon may have made"),
|
||||
"{logged:#?}"
|
||||
);
|
||||
assert!(
|
||||
has("an effect a stopped daemon may have made is no longer needed"),
|
||||
"{logged:#?}"
|
||||
);
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
assert!(
|
||||
reopen(&dir).sync_intents(Some(folder)).unwrap().is_empty(),
|
||||
"every intent settled"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A restart owes the disk a walk in full, since nothing watched it
|
||||
/// meanwhile, and owes Drive nothing: its event stream resumes from the
|
||||
/// cursor (`root`).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_restart_walks_the_disk_in_full_and_not_drive() {
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("restart-owes");
|
||||
let (daemon, folder, _client) =
|
||||
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
take_logged();
|
||||
let daemon = daemon.restart().unwrap();
|
||||
let quiet = quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let logged = take_logged();
|
||||
let roots: Vec<&String> = logged
|
||||
.iter()
|
||||
.filter(|line| line.contains("sync: root state"))
|
||||
.collect();
|
||||
assert!(
|
||||
roots.len() == 1
|
||||
&& roots[0].contains("from=auditing (local: Restart)")
|
||||
&& roots[0].contains("to=following")
|
||||
&& roots[0].contains("Covered { local: true, remote: false }"),
|
||||
"{roots:?}"
|
||||
);
|
||||
assert!(
|
||||
!logged
|
||||
.iter()
|
||||
.any(|line| line.contains("the root state asks for a walk of all of Drive")),
|
||||
"a restart owes Drive nothing"
|
||||
);
|
||||
assert!(counted(&quiet, "reused") > 0, "{quiet}");
|
||||
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() {
|
||||
@@ -1897,6 +2223,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"] {
|
||||
@@ -1910,6 +2239,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
|
||||
@@ -2150,6 +2490,70 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_mirror_create_whose_reply_was_lost_is_adopted_after_a_restart_and_its_edit_lands() {
|
||||
// Drive made the file, but the answer never came back, and the daemon
|
||||
// stopped before it tried again. While it was stopped the file was
|
||||
// written again. A one-request small upload makes this the common way
|
||||
// a create goes unanswered: it leaves a whole file, never a draft. The
|
||||
// start must find that file, take it as this one, and put the newer
|
||||
// bytes on it: one file, no conflict copy.
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("mirror-lost-create-restart");
|
||||
let (daemon, folder, client) = start_mirror(&drive, &dir, &[("a.txt", b"one")]);
|
||||
let local = dir.join("local");
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
|
||||
client.lose_reply_to_next_create();
|
||||
std::fs::write(local.join("new.txt"), b"first").unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
on_drive(&drive, "mirrored/new.txt").is_some_and(|bytes| bytes == b"first")
|
||||
}));
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
|
||||
std::fs::write(local.join("new.txt"), b"second, written while stopped").unwrap();
|
||||
let daemon = Daemon::start(&dir, client).unwrap();
|
||||
let landed = wait_until(Duration::from_secs(60), || {
|
||||
on_drive(&drive, "mirrored/new.txt")
|
||||
.is_some_and(|bytes| bytes == b"second, written while stopped")
|
||||
});
|
||||
let logged = take_logged();
|
||||
assert!(
|
||||
landed,
|
||||
"{:#?}\n{:#?}",
|
||||
drive.tree(),
|
||||
logged
|
||||
.iter()
|
||||
.filter(|l| l.contains("sync") || l.contains("new"))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
|
||||
assert!(conflict_copies(&local, "new").is_empty());
|
||||
let tree = drive.tree();
|
||||
assert!(
|
||||
!tree.keys().any(|k| k.contains("sync-conflict")),
|
||||
"{tree:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
tree.keys().filter(|k| k.contains("new")).count(),
|
||||
1,
|
||||
"{tree:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(local.join("new.txt")).unwrap(),
|
||||
b"second, written while stopped"
|
||||
);
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
assert!(
|
||||
reopen(&dir).sync_intents(Some(folder)).unwrap().is_empty(),
|
||||
"every intent settled"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_revision_made_during_a_mirror_download_still_arrives() {
|
||||
@@ -2868,6 +3272,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() {
|
||||
@@ -4020,6 +4485,57 @@ mod tests {
|
||||
id
|
||||
}
|
||||
|
||||
/// Stop syncing with "Also delete from Proton Drive" on, while Drive cannot
|
||||
/// be reached. The folder stops syncing, but its copy in Proton Drive
|
||||
/// stays. The reply was a plain success, so the app said "Stopped syncing
|
||||
/// folder" and nothing told the user the cloud copy was still there.
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn stopping_sync_says_so_when_its_drive_folder_could_not_be_deleted() {
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("stop-sync-delete-offline");
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
|
||||
let local = dir.join("docs");
|
||||
let id = sync_folder(&daemon, &local, "mirror");
|
||||
std::fs::write(local.join("keep.txt"), b"keep").unwrap();
|
||||
daemon.request(&Request::SyncNow { id: Some(id) }).unwrap();
|
||||
let on_drive = || {
|
||||
drive.tree().iter().any(|(path, entry)| {
|
||||
path.ends_with("docs/keep.txt") && *entry == Entry::File(Arc::new(b"keep".to_vec()))
|
||||
})
|
||||
};
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(30), || on_drive()
|
||||
&& listed_folder(&daemon, id).is_some_and(|f| f.state == "idle")),
|
||||
"the folder synced: {:?}",
|
||||
listed_folder(&daemon, id)
|
||||
);
|
||||
|
||||
daemon.client.set_online(false);
|
||||
let error = daemon
|
||||
.request(&Request::RemoveSyncFolder {
|
||||
id,
|
||||
delete_remote: true,
|
||||
})
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
daemon.client.set_online(true);
|
||||
|
||||
assert!(
|
||||
error.contains("stopped syncing the folder")
|
||||
&& error.contains("was not moved to the trash"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(
|
||||
listed_folder(&daemon, id).is_none(),
|
||||
"the folder still syncs"
|
||||
);
|
||||
assert!(on_drive(), "the copy in Proton Drive is gone after all");
|
||||
assert_eq!(std::fs::read(local.join("keep.txt")).unwrap(), b"keep");
|
||||
daemon.stop().unwrap();
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_move_out_of_an_on_demand_folder_refuses_a_file_still_open_for_writing() {
|
||||
@@ -4550,4 +5066,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,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;
|
||||
|
||||
@@ -165,9 +165,9 @@ impl Core {
|
||||
return;
|
||||
}
|
||||
let queue = self.sizes.size_waiters.clone();
|
||||
if let Err(error) = std::thread::Builder::new()
|
||||
.name("pdfs-size-waiters".into())
|
||||
.spawn(move || queue.serve())
|
||||
if let Err(error) = self
|
||||
.services
|
||||
.spawn_job("pdfs-size-waiters", move || queue.serve())
|
||||
{
|
||||
// Without a thread nothing would ever answer these. A provisional
|
||||
// size is wrong; a `stat` that never returns wedges the caller.
|
||||
@@ -190,6 +190,11 @@ impl Core {
|
||||
let (mut key, mut uids, mut slot) = (key, uids, slot);
|
||||
loop {
|
||||
for chunk in uids.chunks(SIZE_UPGRADE_CHUNK) {
|
||||
// A stop joins this job; the rest of the folder can wait for
|
||||
// the next mount, which lists it afresh.
|
||||
if self.shutdown.is_stopping() {
|
||||
break;
|
||||
}
|
||||
let result =
|
||||
self.block_on_within(BATCH_CALL_TIMEOUT, self.drive.enumerate_nodes(chunk));
|
||||
self.apply_size_upgrade(key, result);
|
||||
@@ -327,7 +332,7 @@ impl Core {
|
||||
};
|
||||
changed.push(ino);
|
||||
// An open write handle is ahead of the server too (B109).
|
||||
if st.active_writes.contains_key(&ino) {
|
||||
if st.open.is_writing(ino) {
|
||||
continue;
|
||||
}
|
||||
let NodeKind::File { claimed_size, .. } = &node.kind else {
|
||||
|
||||
+117
-43
@@ -30,6 +30,10 @@ use pdfs_core::control::ActivityKind;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_drive::DriveApi;
|
||||
use pdfs_store::db::Db;
|
||||
|
||||
use super::{Core, node_content_sha1, node_revision_id, node_size};
|
||||
|
||||
/// What the conflict sweep may do, and the copies it already checked this
|
||||
@@ -44,7 +48,7 @@ pub(crate) struct SweepState {
|
||||
/// Conflict copies the sweep has already checked against the activity log
|
||||
/// this run, so each pass does not ask the database again. The log itself
|
||||
/// is what keeps a copy from being flagged again after a restart. See
|
||||
/// [`Core::run_conflict_sweep_loop`] and `docs/BUGS.md` B99.
|
||||
/// [`Sweeper::run`] and `docs/BUGS.md` B99.
|
||||
pub(crate) conflict_notified: Arc<Mutex<HashSet<NodeUid>>>,
|
||||
}
|
||||
|
||||
@@ -107,17 +111,113 @@ pub(crate) fn conflict_base_name(name: &str) -> Option<String> {
|
||||
Some(base)
|
||||
}
|
||||
|
||||
/// What the conflict sweep needs from the rest of the daemon: the tree of
|
||||
/// every mount and the activity feed.
|
||||
pub(crate) trait SweepHost: Send + Sync {
|
||||
/// Whether `uid` is on this account's own volume, or a virtual node.
|
||||
fn is_own_or_virtual(&self, uid: &NodeUid) -> bool;
|
||||
/// Whether the mount believes Drive is reachable.
|
||||
fn is_online(&self) -> bool;
|
||||
/// Whether a node is being written or held open in any mount.
|
||||
fn is_busy(&self, uid: &NodeUid) -> bool;
|
||||
/// For one pass: whether the conflict listing can show a copy.
|
||||
fn conflict_locator(&self) -> Box<dyn Fn(&NodeUid) -> bool + '_>;
|
||||
/// Unhook a node Drive no longer has from every mount, and drop its
|
||||
/// cached content and open readers.
|
||||
fn forget(&self, uid: &NodeUid);
|
||||
fn log_activity(&self, kind: ActivityKind, target: &str, detail: String, ok: bool);
|
||||
}
|
||||
|
||||
impl SweepHost for Core {
|
||||
fn is_own_or_virtual(&self, uid: &NodeUid) -> bool {
|
||||
Core::is_own_or_virtual(self, uid)
|
||||
}
|
||||
|
||||
fn is_online(&self) -> bool {
|
||||
Core::is_online(self)
|
||||
}
|
||||
|
||||
fn is_busy(&self, uid: &NodeUid) -> bool {
|
||||
Core::is_busy(self, uid)
|
||||
}
|
||||
|
||||
fn conflict_locator(&self) -> Box<dyn Fn(&NodeUid) -> bool + '_> {
|
||||
let roots = Core::search_roots(self);
|
||||
Box::new(move |uid| self.conflict_path(&roots, uid).is_some())
|
||||
}
|
||||
|
||||
fn forget(&self, uid: &NodeUid) {
|
||||
// Leaving a conflict copy hooked up in the tree keeps a node we have
|
||||
// just trashed remotely visible and readable in whichever mount shows
|
||||
// it (`docs/BUGS.md` B74).
|
||||
self.for_each_state(|st| {
|
||||
st.forget_or_unlink(uid);
|
||||
});
|
||||
self.cache.evict(uid);
|
||||
self.evict_reader(uid);
|
||||
}
|
||||
|
||||
fn log_activity(&self, kind: ActivityKind, target: &str, detail: String, ok: bool) {
|
||||
Core::log_activity(self, kind, target, detail, ok);
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// The conflict sweep, with this daemon as its host.
|
||||
pub(crate) fn sweeper(&self) -> Sweeper {
|
||||
Sweeper {
|
||||
drive: self.drive.clone(),
|
||||
rt: self.rt.clone(),
|
||||
db: self.db.clone(),
|
||||
shutdown: self.shutdown.clone(),
|
||||
state: self.sweep.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a node has a write in flight or a file handle open against it.
|
||||
/// Read-only opens use fh 0 and are not tracked, so this is specifically the
|
||||
/// writer/holder check.
|
||||
/// Asked across **every** mount. The sweep runs on the primary Core but
|
||||
/// trashes nodes anywhere in the tree, and a file open inside a sync folder
|
||||
/// is tracked in that fork's `State` — so consulting `self.state` alone
|
||||
/// answered "idle" for every such file and let the sweep delete one with a
|
||||
/// writer attached (`docs/BUGS.md` B74). Busy anywhere means busy.
|
||||
pub(crate) fn is_busy(&self, uid: &NodeUid) -> bool {
|
||||
let mut busy = false;
|
||||
self.for_each_state(|st| {
|
||||
let Some(&ino) = st.by_uid.get(uid) else {
|
||||
return;
|
||||
};
|
||||
busy |= st.open.is_busy(ino);
|
||||
});
|
||||
busy
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconciles leftover conflict copies (the module documentation says how).
|
||||
/// Holds Drive, the runtime, the database, the stop signal and its own state;
|
||||
/// it reaches the mounts through [`SweepHost`].
|
||||
pub(crate) struct Sweeper {
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
db: Arc<Db>,
|
||||
shutdown: Arc<Shutdown>,
|
||||
state: SweepState,
|
||||
host: Arc<dyn SweepHost>,
|
||||
}
|
||||
|
||||
impl Sweeper {
|
||||
/// Sweep for stale conflict copies forever, on its own thread. See the module
|
||||
/// docs for the identical/divergent policy.
|
||||
pub(crate) fn run_conflict_sweep_loop(&self) {
|
||||
pub(crate) fn run(&self) {
|
||||
// Both waits are interruptible, so teardown does not have to sit out a
|
||||
// five-minute interval to join this thread (`docs/BUGS.md` B44).
|
||||
if !self.shutdown.sleep(CONFLICT_SWEEP_WARMUP) {
|
||||
return;
|
||||
}
|
||||
loop {
|
||||
self.sweep_conflicts_once();
|
||||
self.sweep_once();
|
||||
if !self.shutdown.sleep(CONFLICT_SWEEP_INTERVAL) {
|
||||
return;
|
||||
}
|
||||
@@ -125,7 +225,7 @@ impl Core {
|
||||
}
|
||||
|
||||
/// One sweep pass over every node the daemon currently knows.
|
||||
fn sweep_conflicts_once(&self) {
|
||||
fn sweep_once(&self) {
|
||||
let stored = match self.db.load_all() {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
@@ -136,7 +236,7 @@ impl Core {
|
||||
let nodes: Vec<_> = stored
|
||||
.into_iter()
|
||||
.map(|stored| stored.node)
|
||||
.filter(|node| self.is_own_or_virtual(&node.uid))
|
||||
.filter(|node| self.host.is_own_or_virtual(&node.uid))
|
||||
.collect();
|
||||
|
||||
// Index live (non-trashed) files by (parent, name) for sibling lookup.
|
||||
@@ -153,8 +253,8 @@ impl Core {
|
||||
by_parent_name.insert((parent, node.name.as_str()), node);
|
||||
}
|
||||
|
||||
let roots = self.search_roots();
|
||||
let online = self.is_online();
|
||||
let listed = self.host.conflict_locator();
|
||||
let online = self.host.is_online();
|
||||
for node in &nodes {
|
||||
if node.trashed || node.is_folder() {
|
||||
continue;
|
||||
@@ -169,7 +269,7 @@ impl Core {
|
||||
.unwrap_or_default();
|
||||
let sibling = by_parent_name.get(&(parent, base.as_str())).copied();
|
||||
|
||||
match decide(node, sibling, &base, self.sweep.sweep_mode) {
|
||||
match decide(node, sibling, &base, self.state.sweep_mode) {
|
||||
SweepAction::Remove => {
|
||||
// Only while online — the remote trash is the point. Offline,
|
||||
// it waits for a later pass.
|
||||
@@ -181,7 +281,7 @@ impl Core {
|
||||
// would sit in the feed as "resolved" with no way to act on
|
||||
// it (`docs/BUGS.md` B99).
|
||||
SweepAction::Flag(detail) => {
|
||||
if self.conflict_path(&roots, &node.uid).is_some() {
|
||||
if listed(&node.uid) {
|
||||
self.flag_conflict(&node.uid, &node.name, detail);
|
||||
} else {
|
||||
debug!(uid = %node.uid, name = %node.name, "conflict sweep: copy is outside every location; not flagged");
|
||||
@@ -219,12 +319,7 @@ impl Core {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Leaving a conflict copy hooked up in the tree keeps a node we have
|
||||
// just trashed remotely visible and readable in whichever mount shows
|
||||
// it (`docs/BUGS.md` B74).
|
||||
self.for_each_state(|st| {
|
||||
st.forget_or_unlink(uid);
|
||||
});
|
||||
self.host.forget(uid);
|
||||
// Deliberately *not* `discard_queued_ops`: `duplicate_still_removable`
|
||||
// proved the queue empty before the trash above, but that proof is stale
|
||||
// the moment `trash_nodes` goes to the network. A `close(2)` landing in
|
||||
@@ -232,14 +327,12 @@ impl Core {
|
||||
// blob holding the only copy of them. Leaving the op queued is the
|
||||
// non-destructive outcome: the drain re-reads the node, sees it trashed,
|
||||
// and `revision_conflict` routes it to `keep_as_conflict_copy`.
|
||||
self.cache.evict(uid);
|
||||
self.evict_reader(uid);
|
||||
if let Err(e) = self.db.delete_node(uid) {
|
||||
warn!(%uid, error = ?e, "conflict sweep: db delete after trash failed");
|
||||
}
|
||||
self.invalidate_trash();
|
||||
self.sweep.conflict_notified.lock().remove(uid);
|
||||
self.log_activity(
|
||||
super::trash::invalidate_trash(&self.db);
|
||||
self.state.conflict_notified.lock().remove(uid);
|
||||
self.host.log_activity(
|
||||
ActivityKind::Trash,
|
||||
name,
|
||||
format!("auto-removed duplicate of {base}"),
|
||||
@@ -273,7 +366,7 @@ impl Core {
|
||||
|
||||
// Someone is writing to it, or holds it open. Trashing now would pull the
|
||||
// node out from under a live handle.
|
||||
if self.is_busy(uid) {
|
||||
if self.host.is_busy(uid) {
|
||||
debug!(%uid, name, "conflict sweep: skipping duplicate that is open or being written");
|
||||
return false;
|
||||
}
|
||||
@@ -306,32 +399,12 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a node has a write in flight or a file handle open against it.
|
||||
/// Read-only opens use fh 0 and are not tracked, so this is specifically the
|
||||
/// writer/holder check.
|
||||
/// Asked across **every** mount. The sweep runs on the primary Core but
|
||||
/// trashes nodes anywhere in the tree, and a file open inside a sync folder
|
||||
/// is tracked in that fork's `State` — so consulting `self.state` alone
|
||||
/// answered "idle" for every such file and let the sweep delete one with a
|
||||
/// writer attached (`docs/BUGS.md` B74). Busy anywhere means busy.
|
||||
pub(crate) fn is_busy(&self, uid: &NodeUid) -> bool {
|
||||
let mut busy = false;
|
||||
self.for_each_state(|st| {
|
||||
let Some(&ino) = st.by_uid.get(uid) else {
|
||||
return;
|
||||
};
|
||||
busy |=
|
||||
st.active_writes.contains_key(&ino) || st.handles.values().any(|&held| held == ino);
|
||||
});
|
||||
busy
|
||||
}
|
||||
|
||||
/// Surface a conflict copy that needs the user's attention, once. The
|
||||
/// in-memory set spares the database each pass; the activity log itself is
|
||||
/// what keeps a restart from logging the same copy again (`docs/BUGS.md`
|
||||
/// B99). A copy's name carries its own timestamp, so the name identifies it.
|
||||
fn flag_conflict(&self, uid: &NodeUid, name: &str, detail: String) {
|
||||
if !self.sweep.conflict_notified.lock().insert(uid.clone()) {
|
||||
if !self.state.conflict_notified.lock().insert(uid.clone()) {
|
||||
return;
|
||||
}
|
||||
match self.db.activity_has(ActivityKind::Conflict, name) {
|
||||
@@ -342,7 +415,8 @@ impl Core {
|
||||
Err(e) => warn!(%uid, name, error = ?e, "conflict sweep: activity check failed"),
|
||||
}
|
||||
debug!(%uid, name, detail, "conflict sweep: flagged divergent conflict copy");
|
||||
self.log_activity(ActivityKind::Conflict, name, detail, false);
|
||||
self.host
|
||||
.log_activity(ActivityKind::Conflict, name, detail, false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -685,6 +685,6 @@ pub(super) fn expand_restore(
|
||||
|
||||
/// Mark the stored trash listing stale, so the next listing waits for a
|
||||
/// fresh one.
|
||||
fn invalidate_trash(db: &Db) {
|
||||
pub(crate) fn invalidate_trash(db: &Db) {
|
||||
let _ = db.clear_state(TRASH_SYNCED_MS);
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use std::time::{Duration, Instant};
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, NodeUid, VolumeId};
|
||||
use proton_drive_rs::{Node, NodeKind};
|
||||
|
||||
pub(crate) const VIRTUAL_VOLUME: &str = "virtual";
|
||||
pub(crate) use pdfs_vfs::ids::{VIRTUAL_VOLUME, is_virtual_uid};
|
||||
pub(crate) const SHARED_WITH_ME_LINK: &str = "sharedwithme";
|
||||
pub(crate) const SHARED_WITH_ME_BASE: &str = "Shared with me";
|
||||
const MAX_COMPONENT_BYTES: usize = 255;
|
||||
@@ -18,10 +18,6 @@ pub(crate) fn shared_with_me_uid() -> NodeUid {
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn is_virtual_uid(uid: &NodeUid) -> bool {
|
||||
uid.volume_id.as_str() == VIRTUAL_VOLUME
|
||||
}
|
||||
|
||||
pub(crate) fn is_own_or_virtual_uid(uid: &NodeUid, own_volume: &VolumeId) -> bool {
|
||||
uid.volume_id == *own_volume || is_virtual_uid(uid)
|
||||
}
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
//! What the mount accepted and has not yet sent to Drive (`WriteState`).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The write-back's state: writes accepted from the kernel and not yet sent,
|
||||
/// nodes removed here that a stale listing may still return, and the changes
|
||||
/// this daemon made that Drive's event feed will echo back.
|
||||
///
|
||||
/// The drain, the queue and recovery own it. Everything else, the read path,
|
||||
/// listings, the pin keeper and the event feed, asks through the methods
|
||||
/// below instead of taking its locks.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct WriteState {
|
||||
/// Writes accepted from the kernel but not yet uploaded, keyed by node.
|
||||
/// The in-memory face of the `pending_op` table, from
|
||||
/// which it is rebuilt on mount.
|
||||
///
|
||||
/// Two things read it: [`Core::read_range`], because until the op drains the
|
||||
/// staged blob *is* the file's content and the remote still holds the old
|
||||
/// revision; and the drain worker, which performs the uploads.
|
||||
pub(crate) pending: Arc<Mutex<HashMap<NodeUid, PendingRevision>>>,
|
||||
/// Nodes removed through this daemon which a briefly stale remote listing
|
||||
/// may still return. Uids are not reused; an explicit restore clears one.
|
||||
hidden: Arc<Mutex<HashSet<NodeUid>>>,
|
||||
/// Nodes this daemon changed on the remote itself, and how many echoes of
|
||||
/// those changes the event feed still owes us.
|
||||
///
|
||||
/// The feed replays our own writes back at us seconds later, and a
|
||||
/// `NodeUpdated` carries no revision id — nothing in it distinguishes "another
|
||||
/// device changed this file" from "you changed this file". Treating the echo
|
||||
/// as foreign is not free: it evicts the content blob we just uploaded, so the
|
||||
/// next read re-downloads a revision the API may not be serving yet. That is
|
||||
/// how a SQLite database written on the mount came back `malformed`, and how a
|
||||
/// mount doing bulk uploads spent its time re-fetching its own bytes.
|
||||
///
|
||||
/// So the first event for a node we changed ourselves, within
|
||||
/// [`SELF_CHANGE_TTL_MS`], is consumed rather than applied: the tree already
|
||||
/// holds what that event describes, because [`Core::refresh_after_upload`] put
|
||||
/// it there. Anything beyond that applies normally, which bounds the staleness
|
||||
/// a genuine remote change can suffer to one event.
|
||||
///
|
||||
/// Shared across forks like `pending`: the drain that records the change and
|
||||
/// the event task that consumes the echo are both per-daemon.
|
||||
self_changes: Arc<Mutex<HashMap<NodeUid, echoes::SelfChange>>>,
|
||||
}
|
||||
|
||||
impl WriteState {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
pending: Arc::new(Mutex::new(HashMap::new())),
|
||||
hidden: Arc::new(Mutex::new(HashSet::new())),
|
||||
self_changes: Arc::new(Mutex::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The write queued for `uid`, if any: its staged blob is the file's
|
||||
/// content until the drain sends it.
|
||||
pub(crate) fn queued(&self, uid: &NodeUid) -> Option<PendingRevision> {
|
||||
self.pending.lock().get(uid).cloned()
|
||||
}
|
||||
|
||||
/// Whether a write for `uid` is queued and not yet sent. A remote change
|
||||
/// to such a node is not applied over it.
|
||||
pub(crate) fn is_queued(&self, uid: &NodeUid) -> bool {
|
||||
self.pending.lock().contains_key(uid)
|
||||
}
|
||||
|
||||
/// The size the queued write for `uid` gives the file, if one is queued.
|
||||
pub(crate) fn queued_len(&self, uid: &NodeUid) -> Option<u64> {
|
||||
self.pending.lock().get(uid).map(|queued| queued.meta.len)
|
||||
}
|
||||
|
||||
/// The size each queued write gives its file. Empty when nothing is
|
||||
/// queued.
|
||||
pub(crate) fn queued_sizes(&self) -> HashMap<NodeUid, u64> {
|
||||
self.pending
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|(uid, queued)| (uid.clone(), queued.meta.len))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The nodes removed here that a listing must leave out, even if Drive
|
||||
/// still returns them.
|
||||
pub(crate) fn hidden(&self) -> HashSet<NodeUid> {
|
||||
self.hidden.lock().clone()
|
||||
}
|
||||
|
||||
/// Leave `uid` out of listings from now on: it was removed here.
|
||||
pub(crate) fn hide(&self, uid: &NodeUid) {
|
||||
self.hidden.lock().insert(uid.clone());
|
||||
}
|
||||
|
||||
/// List `uid` again: it was restored or put back.
|
||||
pub(crate) fn unhide(&self, uid: &NodeUid) {
|
||||
self.hidden.lock().remove(uid);
|
||||
}
|
||||
|
||||
/// Record that this daemon just changed `uid` on Drive, so the event
|
||||
/// feed's echo of the change is recognised (see [`echoes`]).
|
||||
pub(crate) fn note_echo(&self, uid: &NodeUid, now_ms: i64) {
|
||||
echoes::note_self_change(&mut self.self_changes.lock(), uid, now_ms);
|
||||
}
|
||||
|
||||
/// Claim one outstanding echo for `uid`: whether the event being applied
|
||||
/// is one this daemon caused.
|
||||
pub(crate) fn take_echo(&self, uid: &NodeUid, now_ms: i64) -> bool {
|
||||
echoes::take_self_change(&mut self.self_changes.lock(), uid, now_ms)
|
||||
}
|
||||
}
|
||||
@@ -1007,20 +1007,54 @@ pub(crate) fn prompt_remove_sync_folder(
|
||||
dialog.set_response_appearance("remove", adw::ResponseAppearance::Destructive);
|
||||
dialog.set_default_response(Some("cancel"));
|
||||
dialog.set_close_response("cancel");
|
||||
let ui = ui.clone();
|
||||
dialog.connect_response(None, move |_, resp| {
|
||||
if resp == "remove" {
|
||||
run_devices_mutation(
|
||||
&ui,
|
||||
Request::RemoveSyncFolder {
|
||||
id,
|
||||
delete_remote: !attached && delete_remote.is_active(),
|
||||
// With the switch on, the button does more than stop syncing, so it says
|
||||
// so: the heading, the button and the outcome all name the deletion.
|
||||
delete_remote.connect_active_notify({
|
||||
let dialog = dialog.clone();
|
||||
move |row| {
|
||||
let deleting = row.is_active();
|
||||
dialog.set_heading(Some(&if deleting {
|
||||
gettext("Stop Syncing and Delete Folder?")
|
||||
} else {
|
||||
gettext("Stop Syncing Folder?")
|
||||
}));
|
||||
dialog.set_response_label(
|
||||
"remove",
|
||||
&if deleting {
|
||||
gettext("Stop Syncing and Delete")
|
||||
} else {
|
||||
gettext("Stop Syncing")
|
||||
},
|
||||
&gettext("Stopped syncing folder"),
|
||||
&gettext("Couldn't stop syncing the folder"),
|
||||
);
|
||||
}
|
||||
});
|
||||
let ui = ui.clone();
|
||||
dialog.connect_response(None, move |_, resp| {
|
||||
if resp != "remove" {
|
||||
return;
|
||||
}
|
||||
let deleting = !attached && delete_remote.is_active();
|
||||
let (done, failed) = if deleting {
|
||||
(
|
||||
gettext("Stopped syncing and moved the folder in Proton Drive to the trash"),
|
||||
gettext("Couldn't stop syncing and delete the folder"),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
gettext("Stopped syncing folder"),
|
||||
gettext("Couldn't stop syncing the folder"),
|
||||
)
|
||||
};
|
||||
run_devices_mutation(
|
||||
&ui,
|
||||
Request::RemoveSyncFolder {
|
||||
id,
|
||||
delete_remote: deleting,
|
||||
},
|
||||
&done,
|
||||
&failed,
|
||||
);
|
||||
});
|
||||
dialog.present(win.as_ref());
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 = 52;
|
||||
|
||||
impl Db {
|
||||
pub(super) fn migrate(&self) -> Result<()> {
|
||||
@@ -543,6 +543,41 @@ 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)?;
|
||||
}
|
||||
}
|
||||
if current < 51 {
|
||||
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_V51)?;
|
||||
}
|
||||
}
|
||||
if current < 52 {
|
||||
let has_intents: bool = tx.query_row(
|
||||
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'sync_intent'",
|
||||
[],
|
||||
|row| row.get::<_, i64>(0).map(|n| n > 0),
|
||||
)?;
|
||||
let has_column: bool = tx.query_row(
|
||||
"SELECT COUNT(*) FROM pragma_table_info('sync_intent') WHERE name = 'sent_sha1s'",
|
||||
[],
|
||||
|row| row.get::<_, i64>(0).map(|n| n > 0),
|
||||
)?;
|
||||
if has_intents && !has_column {
|
||||
tx.execute_batch(MIGRATION_V52)?;
|
||||
}
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT INTO sync_state (key, value) VALUES ('schema_version', ?1)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||
@@ -1547,6 +1582,73 @@ 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;
|
||||
";
|
||||
|
||||
/// Schema v51: an intent for each effect a mirror pass sends, written before
|
||||
/// it is sent and removed once its result is in (`docs/SYNC_ENGINE.md`).
|
||||
///
|
||||
/// One row a folder, path and kind of effect. A row left `issued` was sent by
|
||||
/// a daemon that stopped before it heard back: the effect may or may not have
|
||||
/// happened. A change to what the folder is, or its removal, drops its rows.
|
||||
const MIGRATION_V51: &str = "
|
||||
CREATE TABLE IF NOT EXISTS sync_intent (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
folder_id INTEGER NOT NULL,
|
||||
rel_path TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
attempts INTEGER NOT NULL,
|
||||
issued_at INTEGER NOT NULL,
|
||||
last_error TEXT,
|
||||
UNIQUE (folder_id, rel_path, kind)
|
||||
);
|
||||
DROP TRIGGER IF EXISTS sync_intent_drop_on_folder_update;
|
||||
DROP TRIGGER IF EXISTS sync_intent_drop_on_folder_delete;
|
||||
CREATE TRIGGER sync_intent_drop_on_folder_update
|
||||
AFTER UPDATE OF local_path, remote_uid, mode ON sync_folder
|
||||
BEGIN
|
||||
DELETE FROM sync_intent WHERE folder_id = OLD.id;
|
||||
END;
|
||||
CREATE TRIGGER sync_intent_drop_on_folder_delete
|
||||
AFTER DELETE ON sync_folder
|
||||
BEGIN
|
||||
DELETE FROM sync_intent WHERE folder_id = OLD.id;
|
||||
END;
|
||||
";
|
||||
|
||||
/// v52: the SHA-1s of the bytes each unsettled mirror upload sent, space
|
||||
/// separated. A reply that never came may hide an upload that landed, and its
|
||||
/// digest is how a later pass knows the file on Drive for its own.
|
||||
const MIGRATION_V52: &str = "
|
||||
ALTER TABLE sync_intent ADD COLUMN sent_sha1s TEXT;
|
||||
";
|
||||
|
||||
/// See [`MIGRATION_V49_COLUMNS`].
|
||||
const MIGRATION_V49: &str = "
|
||||
CREATE TABLE IF NOT EXISTS sync_remote_dirty (
|
||||
|
||||
@@ -44,6 +44,7 @@ mod nodes;
|
||||
mod ops;
|
||||
mod photos;
|
||||
mod pins;
|
||||
mod replace;
|
||||
mod share_access;
|
||||
mod state;
|
||||
mod sync;
|
||||
@@ -63,7 +64,11 @@ 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, StoredIntent, StoredSyncEntry,
|
||||
StoredSyncFolder,
|
||||
};
|
||||
pub use trash::StoredTrash;
|
||||
|
||||
/// Size the WAL is truncated back to after a checkpoint. Comfortably above the
|
||||
@@ -108,6 +113,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 +303,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 +394,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 +419,7 @@ impl Db {
|
||||
conn: Ranked::new(Rank::DbWriter, conn),
|
||||
readers: None,
|
||||
_single_writer: None,
|
||||
run: next_run(),
|
||||
};
|
||||
db.migrate()?;
|
||||
Ok(db)
|
||||
@@ -429,6 +441,25 @@ fn is_in_memory(path: &Path) -> bool {
|
||||
p == ":memory:" || p.is_empty()
|
||||
}
|
||||
|
||||
/// A value no other opening of a database has used: the time in nanoseconds,
|
||||
/// made unique within this process by a counter.
|
||||
fn next_run() -> u64 {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static LAST: AtomicU64 = AtomicU64::new(0);
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos() as u64)
|
||||
.unwrap_or(0);
|
||||
let mut last = LAST.load(Ordering::Relaxed);
|
||||
loop {
|
||||
let next = now.max(last + 1);
|
||||
match LAST.compare_exchange_weak(last, next, Ordering::Relaxed, Ordering::Relaxed) {
|
||||
Ok(_) => return next,
|
||||
Err(seen) => last = seen,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the single-instance write lock for the database at `path`.
|
||||
///
|
||||
/// The daemon is the only writer by design — the front-ends go through the
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! The journal of replacing renames.
|
||||
//!
|
||||
//! Drive has no rename that replaces its destination, so a `rename(2)` over an
|
||||
//! existing name removes the node there first and renames the source second.
|
||||
//! A stop between the two leaves the destination in Drive's trash and the
|
||||
//! source under its old name: neither the old state nor the new one. An entry
|
||||
//! here is written before the first step and removed after the last, so the
|
||||
//! next start finds every replace that was cut off and settles it
|
||||
//! (`docs/BUGS.md` B302).
|
||||
//!
|
||||
//! Kept in `sync_state` under [`REPLACE_PREFIX`], so the schema does not
|
||||
//! change.
|
||||
|
||||
use rusqlite::params;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::Db;
|
||||
use pdfs_core::Result;
|
||||
|
||||
/// The `sync_state` key prefix of a journal entry. The rest of the key is the
|
||||
/// source's uid.
|
||||
const REPLACE_PREFIX: &str = "replace:";
|
||||
|
||||
/// A replacing rename that has started: `source` is to be renamed to
|
||||
/// `new_name` in `new_parent`, over `victim`. Uids are in their `Display`
|
||||
/// form.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ReplaceIntent {
|
||||
pub source_uid: String,
|
||||
pub victim_uid: String,
|
||||
pub new_parent_uid: String,
|
||||
pub new_name: String,
|
||||
/// When the rename started, in milliseconds since the epoch.
|
||||
pub started_ms: i64,
|
||||
/// The opening of the database the rename started under. Set by
|
||||
/// [`Db::begin_replace`].
|
||||
#[serde(default)]
|
||||
pub run: u64,
|
||||
}
|
||||
|
||||
impl ReplaceIntent {
|
||||
fn run_is(&self, run: u64) -> bool {
|
||||
self.run == run
|
||||
}
|
||||
}
|
||||
|
||||
impl Db {
|
||||
/// Record that a replacing rename is about to remove its victim. Committed
|
||||
/// with a synced WAL before it returns, as the queue's own rows are: the
|
||||
/// removal that follows may reach Drive at once.
|
||||
pub fn begin_replace(&self, intent: &ReplaceIntent) -> Result<()> {
|
||||
let intent = ReplaceIntent {
|
||||
run: self.run,
|
||||
..intent.clone()
|
||||
};
|
||||
let value = serde_json::to_string(&intent)?;
|
||||
let conn = self.durable()?;
|
||||
conn.execute(
|
||||
"INSERT INTO sync_state (key, value) VALUES (?1, ?2)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||
params![format!("{REPLACE_PREFIX}{}", intent.source_uid), value],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Forget the replacing rename of `source_uid`: it finished, failed and
|
||||
/// was undone, or was settled after a restart.
|
||||
pub fn end_replace(&self, source_uid: &str) -> Result<()> {
|
||||
self.conn.lock().execute(
|
||||
"DELETE FROM sync_state WHERE key = ?1",
|
||||
params![format!("{REPLACE_PREFIX}{source_uid}")],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every replacing rename an earlier run started and did not end. This
|
||||
/// run's own are in progress, and are not returned. An entry that cannot
|
||||
/// be read is dropped, with a warning: it cannot be settled.
|
||||
pub fn open_replaces(&self) -> Result<Vec<ReplaceIntent>> {
|
||||
let rows: Vec<(String, String)> = {
|
||||
let conn = self.read()?;
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT key, value FROM sync_state WHERE key >= ?1 AND key < ?2 ORDER BY key",
|
||||
)?;
|
||||
stmt.query_map(params![REPLACE_PREFIX, "replace;"], |row| {
|
||||
Ok((row.get(0)?, row.get(1)?))
|
||||
})?
|
||||
.collect::<rusqlite::Result<_>>()?
|
||||
};
|
||||
let mut out = Vec::with_capacity(rows.len());
|
||||
for (key, value) in rows {
|
||||
match serde_json::from_str::<ReplaceIntent>(&value) {
|
||||
Ok(intent) if intent.run_is(self.run) => {}
|
||||
Ok(intent) => out.push(intent),
|
||||
Err(error) => {
|
||||
tracing::warn!(key, %error, "dropping an unreadable replace intent");
|
||||
self.conn
|
||||
.lock()
|
||||
.execute("DELETE FROM sync_state WHERE key = ?1", params![key])?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,38 @@ 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,
|
||||
}
|
||||
|
||||
/// An effect a mirror pass sent, or is about to send, and has not settled.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StoredIntent {
|
||||
pub id: i64,
|
||||
pub folder_id: i64,
|
||||
pub rel_path: String,
|
||||
/// What the effect does, such as `upload` or `download`.
|
||||
pub kind: String,
|
||||
/// Where it stands, as the effect reducer names it.
|
||||
pub state: String,
|
||||
/// How many times it was sent, this time included.
|
||||
pub attempts: u32,
|
||||
/// When it was last sent, in seconds since the epoch.
|
||||
pub issued_at: i64,
|
||||
pub last_error: Option<String>,
|
||||
/// For an upload: the SHA-1s of the bytes its attempts streamed without
|
||||
/// hearing a success back, lowercase. One of them may have landed.
|
||||
pub sent_sha1s: Vec<String>,
|
||||
}
|
||||
|
||||
/// 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 +812,175 @@ 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(())
|
||||
}
|
||||
|
||||
/// Record that an effect is about to be sent: a new intent in state
|
||||
/// `issued`, or the one already there for the same folder, path and kind,
|
||||
/// sent once more. Returns the intent as it is now, and the state it was
|
||||
/// in before, if there was one.
|
||||
pub fn sync_intent_issue(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel_path: &str,
|
||||
kind: &str,
|
||||
now: i64,
|
||||
) -> Result<(StoredIntent, Option<String>)> {
|
||||
let mut conn = self.conn.lock();
|
||||
let tx = conn.transaction()?;
|
||||
let before: Option<String> = tx
|
||||
.query_row(
|
||||
"SELECT state FROM sync_intent WHERE folder_id = ?1 AND rel_path = ?2 AND kind = ?3",
|
||||
params![folder_id, rel_path, kind],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
tx.execute(
|
||||
"INSERT INTO sync_intent (folder_id, rel_path, kind, state, attempts, issued_at)
|
||||
VALUES (?1, ?2, ?3, 'issued', 1, ?4)
|
||||
ON CONFLICT(folder_id, rel_path, kind) DO UPDATE SET state = 'issued',
|
||||
attempts = attempts + 1, issued_at = excluded.issued_at",
|
||||
params![folder_id, rel_path, kind, now],
|
||||
)?;
|
||||
let intent = tx.query_row(
|
||||
&format!(
|
||||
"SELECT {INTENT_COLUMNS} FROM sync_intent
|
||||
WHERE folder_id = ?1 AND rel_path = ?2 AND kind = ?3"
|
||||
),
|
||||
params![folder_id, rel_path, kind],
|
||||
intent_row,
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok((intent, before))
|
||||
}
|
||||
|
||||
/// Settle an intent whose effect is done: the row goes.
|
||||
pub fn sync_intent_settle(&self, id: i64) -> Result<()> {
|
||||
let conn = self.conn.lock();
|
||||
conn.execute("DELETE FROM sync_intent WHERE id = ?1", params![id])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Move an intent to `state`, with the error that put it there.
|
||||
pub fn sync_intent_set(&self, id: i64, state: &str, error: Option<&str>) -> Result<()> {
|
||||
let conn = self.conn.lock();
|
||||
conn.execute(
|
||||
"UPDATE sync_intent SET state = ?2, last_error = ?3 WHERE id = ?1",
|
||||
params![id, state, error],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Note that the upload `kind` of `rel_path` streamed bytes with SHA-1
|
||||
/// `sha1` and heard no success back. Nothing happens without an intent for
|
||||
/// it. A digest already noted is not added again.
|
||||
pub fn sync_intent_sent(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel_path: &str,
|
||||
kind: &str,
|
||||
sha1: &str,
|
||||
) -> Result<()> {
|
||||
let sha1 = sha1.to_ascii_lowercase();
|
||||
let conn = self.conn.lock();
|
||||
conn.execute(
|
||||
"UPDATE sync_intent SET sent_sha1s = CASE
|
||||
WHEN sent_sha1s IS NULL OR sent_sha1s = '' THEN ?4
|
||||
WHEN instr(' ' || sent_sha1s || ' ', ' ' || ?4 || ' ') > 0 THEN sent_sha1s
|
||||
ELSE sent_sha1s || ' ' || ?4 END
|
||||
WHERE folder_id = ?1 AND rel_path = ?2 AND kind = ?3",
|
||||
params![folder_id, rel_path, kind, sha1],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every intent not settled, oldest first; only `folder_id`'s when given.
|
||||
pub fn sync_intents(&self, folder_id: Option<i64>) -> Result<Vec<StoredIntent>> {
|
||||
let conn = self.read()?;
|
||||
let mut stmt = conn.prepare(&format!(
|
||||
"SELECT {INTENT_COLUMNS} FROM sync_intent
|
||||
WHERE ?1 IS NULL OR folder_id = ?1 ORDER BY id"
|
||||
))?;
|
||||
let rows = stmt
|
||||
.query_map(params![folder_id], intent_row)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// Move every intent in state `from` to `to`, across all folders.
|
||||
/// Returns how many moved.
|
||||
pub fn sync_intents_move(&self, from: &str, to: &str) -> Result<usize> {
|
||||
let conn = self.conn.lock();
|
||||
Ok(conn.execute(
|
||||
"UPDATE sync_intent SET state = ?2 WHERE state = ?1",
|
||||
params![from, to],
|
||||
)?)
|
||||
}
|
||||
|
||||
/// Settle the intents of `folder_id` in one of `states` that were last
|
||||
/// sent before `before`: a pass that started after them looked at their
|
||||
/// paths and did not send them again. Returns the intents settled.
|
||||
pub fn sync_intents_settle_before(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
states: &[&str],
|
||||
before: i64,
|
||||
) -> Result<Vec<StoredIntent>> {
|
||||
let mut conn = self.conn.lock();
|
||||
let tx = conn.transaction()?;
|
||||
let mut settled = Vec::new();
|
||||
{
|
||||
let mut stmt = tx.prepare(&format!(
|
||||
"SELECT {INTENT_COLUMNS} FROM sync_intent
|
||||
WHERE folder_id = ?1 AND issued_at < ?2 ORDER BY id"
|
||||
))?;
|
||||
for row in stmt.query_map(params![folder_id, before], intent_row)? {
|
||||
let row = row?;
|
||||
if states.contains(&row.state.as_str()) {
|
||||
settled.push(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
for intent in &settled {
|
||||
tx.execute("DELETE FROM sync_intent WHERE id = ?1", params![intent.id])?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(settled)
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -794,6 +995,26 @@ impl Db {
|
||||
}
|
||||
}
|
||||
|
||||
const INTENT_COLUMNS: &str =
|
||||
"id, folder_id, rel_path, kind, state, attempts, issued_at, last_error, sent_sha1s";
|
||||
|
||||
fn intent_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoredIntent> {
|
||||
Ok(StoredIntent {
|
||||
id: row.get(0)?,
|
||||
folder_id: row.get(1)?,
|
||||
rel_path: row.get(2)?,
|
||||
kind: row.get(3)?,
|
||||
state: row.get(4)?,
|
||||
attempts: u32::try_from(row.get::<_, i64>(5)?).unwrap_or(u32::MAX),
|
||||
issued_at: row.get(6)?,
|
||||
last_error: row.get(7)?,
|
||||
sent_sha1s: row
|
||||
.get::<_, Option<String>>(8)?
|
||||
.map(|s| s.split_whitespace().map(str::to_owned).collect())
|
||||
.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn clear_walk(tx: &rusqlite::Transaction<'_>, folder_id: i64) -> Result<()> {
|
||||
for table in [
|
||||
"sync_walk",
|
||||
|
||||
@@ -8381,3 +8381,149 @@ 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);
|
||||
}
|
||||
|
||||
/// An intent is one row per folder, path and kind: sent again, it counts the
|
||||
/// attempt and says what state it was left in. It goes once settled, and with
|
||||
/// the folder.
|
||||
#[test]
|
||||
fn an_upload_notes_each_digest_it_sent_once() {
|
||||
let db = Db::open_in_memory().unwrap();
|
||||
let id = db.sync_folder_add("/home/me/Docs", "v~root", "s").unwrap();
|
||||
// Nothing to note without an intent.
|
||||
db.sync_intent_sent(id, "a.txt", "upload", "AA").unwrap();
|
||||
assert!(db.sync_intents(Some(id)).unwrap().is_empty());
|
||||
|
||||
db.sync_intent_issue(id, "a.txt", "upload", 10).unwrap();
|
||||
db.sync_intent_sent(id, "a.txt", "upload", "AA").unwrap();
|
||||
db.sync_intent_sent(id, "a.txt", "upload", "aa").unwrap();
|
||||
// Sent again with other bytes: both may have landed.
|
||||
db.sync_intent_issue(id, "a.txt", "upload", 20).unwrap();
|
||||
db.sync_intent_sent(id, "a.txt", "upload", "bb").unwrap();
|
||||
// Another kind of the same path keeps its own.
|
||||
db.sync_intent_issue(id, "a.txt", "upload-revision", 21)
|
||||
.unwrap();
|
||||
let intents = db.sync_intents(Some(id)).unwrap();
|
||||
let upload = intents.iter().find(|i| i.kind == "upload").unwrap();
|
||||
assert_eq!(upload.sent_sha1s, ["aa", "bb"]);
|
||||
let revision = intents
|
||||
.iter()
|
||||
.find(|i| i.kind == "upload-revision")
|
||||
.unwrap();
|
||||
assert!(revision.sent_sha1s.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_effect_intent_is_kept_until_it_is_settled_or_its_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();
|
||||
let (first, before) = db.sync_intent_issue(id, "a.txt", "upload", 10).unwrap();
|
||||
assert_eq!(before, None);
|
||||
assert_eq!((first.state.as_str(), first.attempts), ("issued", 1));
|
||||
db.sync_intent_set(first.id, "retry", Some("timed out"))
|
||||
.unwrap();
|
||||
let (again, before) = db.sync_intent_issue(id, "a.txt", "upload", 20).unwrap();
|
||||
assert_eq!(before.as_deref(), Some("retry"));
|
||||
assert_eq!(again.id, first.id, "the same intent");
|
||||
assert_eq!((again.attempts, again.issued_at), (2, 20));
|
||||
assert_eq!(again.last_error.as_deref(), Some("timed out"));
|
||||
let (download, _) = db.sync_intent_issue(id, "a.txt", "download", 21).unwrap();
|
||||
db.sync_intent_issue(other, "b.txt", "upload", 5).unwrap();
|
||||
assert_eq!(db.sync_intents(Some(id)).unwrap().len(), 2);
|
||||
assert_eq!(db.sync_intents(None).unwrap().len(), 3);
|
||||
|
||||
db.sync_intent_settle(download.id).unwrap();
|
||||
assert_eq!(db.sync_intents(Some(id)).unwrap().len(), 1);
|
||||
|
||||
// A start finds what a stopped daemon left sent.
|
||||
assert_eq!(db.sync_intents_move("issued", "unsure").unwrap(), 2);
|
||||
assert_eq!(db.sync_intents_move("issued", "unsure").unwrap(), 0);
|
||||
// A pass that began after an intent was sent settles it.
|
||||
let settled = db
|
||||
.sync_intents_settle_before(other, &["unsure"], 6)
|
||||
.unwrap();
|
||||
assert_eq!(settled.len(), 1);
|
||||
assert!(db.sync_intents(Some(other)).unwrap().is_empty());
|
||||
assert!(
|
||||
db.sync_intents_settle_before(id, &["unsure"], 20)
|
||||
.unwrap()
|
||||
.is_empty(),
|
||||
"sent at 20, not before"
|
||||
);
|
||||
|
||||
db.sync_folder_set_mode(id, "ondemand").unwrap();
|
||||
assert!(db.sync_intents(Some(id)).unwrap().is_empty());
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
//! The effect reducer: where one effect a mirror pass sends stands, from the
|
||||
//! moment it is about to be sent until its result is in
|
||||
//! (`docs/SYNC_ENGINE.md`).
|
||||
//!
|
||||
//! An effect is an upload, a download, a folder made on Drive, and the other
|
||||
//! [`Pending`](crate::model::Pending) ops. Before one is sent, an intent for it
|
||||
//! is written to the database (`sync_intent`); when its result is in, the
|
||||
//! intent is settled or kept with the failure. An intent still `issued` when
|
||||
//! the daemon starts was sent by a daemon that stopped before it heard back,
|
||||
//! so the effect may or may not have happened: it is `unsure`.
|
||||
//!
|
||||
//! [`step`] is pure, as the root reducer is: the I/O results, the restart and
|
||||
//! the pass that looks again are inputs.
|
||||
//!
|
||||
//! For now the intents are kept in shadow: they record and log what happens,
|
||||
//! and nothing reads them to decide what to send. The apply step's own checks
|
||||
//! (a create that may have landed is looked up before it is sent again, B266;
|
||||
//! a download checks the disk before it replaces a file, B39) still do that.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// Failures in a row after which an effect is reported as blocked.
|
||||
pub const BLOCKED_AFTER: u32 = 5;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EffectState {
|
||||
/// Sent, or about to be; no result yet.
|
||||
Issued,
|
||||
/// Found issued at a start: the daemon stopped before the result came,
|
||||
/// so the effect may or may not have happened.
|
||||
Unsure,
|
||||
/// It failed, and a later pass may send it again.
|
||||
Retry,
|
||||
/// It failed [`BLOCKED_AFTER`] times in a row.
|
||||
Blocked,
|
||||
/// Its result is in. The intent goes.
|
||||
Settled,
|
||||
}
|
||||
|
||||
impl EffectState {
|
||||
/// The name the database keeps.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
EffectState::Issued => "issued",
|
||||
EffectState::Unsure => "unsure",
|
||||
EffectState::Retry => "retry",
|
||||
EffectState::Blocked => "blocked",
|
||||
EffectState::Settled => "settled",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_name(name: &str) -> Option<EffectState> {
|
||||
Some(match name {
|
||||
"issued" => EffectState::Issued,
|
||||
"unsure" => EffectState::Unsure,
|
||||
"retry" => EffectState::Retry,
|
||||
"blocked" => EffectState::Blocked,
|
||||
"settled" => EffectState::Settled,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for EffectState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.name())
|
||||
}
|
||||
}
|
||||
|
||||
/// Something that happened to an effect.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EffectInput {
|
||||
/// It is sent (again); `attempts` counts this one.
|
||||
Issued { attempts: u32 },
|
||||
/// It did what it was sent to do.
|
||||
Succeeded,
|
||||
/// It failed.
|
||||
Failed,
|
||||
/// The daemon started.
|
||||
Restarted,
|
||||
/// A pass that began after it was sent looked at its path and did not
|
||||
/// send it again: what it was for has changed, or is done.
|
||||
Superseded,
|
||||
}
|
||||
|
||||
/// The state after `input`.
|
||||
pub fn step(state: EffectState, input: EffectInput) -> EffectState {
|
||||
use EffectState as S;
|
||||
match (state, input) {
|
||||
(S::Settled, _) => S::Settled,
|
||||
(_, EffectInput::Issued { .. }) => S::Issued,
|
||||
(_, EffectInput::Succeeded | EffectInput::Superseded) => S::Settled,
|
||||
(S::Issued, EffectInput::Restarted) => S::Unsure,
|
||||
(state, EffectInput::Restarted) => state,
|
||||
(_, EffectInput::Failed) => S::Retry,
|
||||
}
|
||||
}
|
||||
|
||||
/// The state after a failure on the `attempts`th send. Counts are kept
|
||||
/// outside [`step`], with the intent.
|
||||
pub fn failed(attempts: u32) -> EffectState {
|
||||
if attempts >= BLOCKED_AFTER {
|
||||
EffectState::Blocked
|
||||
} else {
|
||||
step(EffectState::Issued, EffectInput::Failed)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use EffectInput as I;
|
||||
use EffectState as S;
|
||||
|
||||
#[test]
|
||||
fn an_effect_settles_once_it_succeeds() {
|
||||
let sent = step(S::Retry, I::Issued { attempts: 2 });
|
||||
assert_eq!(sent, S::Issued);
|
||||
assert_eq!(step(sent, I::Succeeded), S::Settled);
|
||||
assert_eq!(step(S::Settled, I::Failed), S::Settled, "settled stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_effect_sent_before_a_stop_is_unsure_after_the_start() {
|
||||
assert_eq!(step(S::Issued, I::Restarted), S::Unsure);
|
||||
// Only one that was sent: a failure is known, and stays one.
|
||||
assert_eq!(step(S::Retry, I::Restarted), S::Retry);
|
||||
assert_eq!(step(S::Blocked, I::Restarted), S::Blocked);
|
||||
// Sent again, or found needless by a later pass.
|
||||
assert_eq!(step(S::Unsure, I::Issued { attempts: 2 }), S::Issued);
|
||||
assert_eq!(step(S::Unsure, I::Superseded), S::Settled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_effect_that_keeps_failing_is_blocked() {
|
||||
assert_eq!(failed(1), S::Retry);
|
||||
assert_eq!(failed(BLOCKED_AFTER - 1), S::Retry);
|
||||
assert_eq!(failed(BLOCKED_AFTER), S::Blocked);
|
||||
assert_eq!(step(S::Blocked, I::Superseded), S::Settled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_state_reads_back_by_its_name() {
|
||||
for state in [S::Issued, S::Unsure, S::Retry, S::Blocked, S::Settled] {
|
||||
assert_eq!(EffectState::from_name(state.name()), Some(state));
|
||||
}
|
||||
assert_eq!(EffectState::from_name("planned"), None);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -16,14 +16,18 @@ 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 effect;
|
||||
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;
|
||||
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
//! 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.
|
||||
//!
|
||||
//! A trusted claim stands in for most of the local walk. The set keeps the
|
||||
//! last walk of each folder ([`LocalWalk`]), and a pass with a trusted claim
|
||||
//! reads again only what the claim covers and takes the rest from that walk.
|
||||
//! A walk is only kept after a pass that changed nothing on disk itself, and
|
||||
//! a full walk still runs now and then: it checks the set, counting the
|
||||
//! changes it finds that a trusted claim did not cover.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::time::Instant;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
|
||||
use crate::model::LocalItem;
|
||||
|
||||
/// 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>,
|
||||
/// What the last pass found on disk, when it may stand in for a walk.
|
||||
walk: Option<LocalWalk>,
|
||||
/// The folder's root as it was when it was watched, as device and
|
||||
/// inode. A watch follows the folder it was set on, so a root moved away
|
||||
/// and made again is another folder the watch does not see.
|
||||
root: Option<RootId>,
|
||||
}
|
||||
|
||||
/// A folder on disk, as device and inode.
|
||||
pub type RootId = (u64, u64);
|
||||
|
||||
/// The identity of the folder at `path`, if there is one.
|
||||
pub fn root_id(path: &std::path::Path) -> Option<RootId> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
std::fs::metadata(path)
|
||||
.ok()
|
||||
.filter(|meta| meta.is_dir())
|
||||
.map(|meta| (meta.dev(), meta.ino()))
|
||||
}
|
||||
|
||||
/// What a pass found on disk, kept for the next pass to start from.
|
||||
pub struct LocalWalk {
|
||||
/// Every path the walk found, as a walk returns them.
|
||||
pub items: HashMap<String, LocalItem>,
|
||||
/// [`IgnoreRules::source`](pdfs_core::syncignore::IgnoreRules::source)
|
||||
/// of the rules it was walked with: other rules would have found other
|
||||
/// paths.
|
||||
pub rules: u64,
|
||||
/// When the folder was last walked in full.
|
||||
pub walked_at: Instant,
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// The folders whose direct children changed.
|
||||
pub fn shallow(&self) -> impl Iterator<Item = &str> {
|
||||
self.shallow.iter().map(String::as_str)
|
||||
}
|
||||
|
||||
/// The paths that changed with whatever is below them.
|
||||
pub fn deep(&self) -> impl Iterator<Item = &str> {
|
||||
self.deep.iter().map(String::as_str)
|
||||
}
|
||||
|
||||
/// 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, set on the root `root`: every
|
||||
/// change from now on is reported.
|
||||
pub fn watched(&self, folder: i64, root: Option<RootId>) {
|
||||
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);
|
||||
}
|
||||
marks.root = root;
|
||||
}
|
||||
|
||||
/// The root `folder`'s watch was last set on.
|
||||
pub fn watched_root(&self, folder: i64) -> Option<RootId> {
|
||||
self.inner.lock().folders.get(&folder)?.root
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
|
||||
/// Take the walk the last pass kept for `folder`. Taken, not read: a pass
|
||||
/// that does not keep a walk again leaves the next one nothing to start
|
||||
/// from.
|
||||
pub fn take_walk(&self, folder: i64) -> Option<LocalWalk> {
|
||||
self.inner
|
||||
.lock()
|
||||
.folders
|
||||
.get_mut(&folder)
|
||||
.and_then(|marks| marks.walk.take())
|
||||
}
|
||||
|
||||
/// Keep what a pass found on disk for the next pass on `folder`.
|
||||
pub fn keep_walk(&self, folder: i64, walk: LocalWalk) {
|
||||
self.inner.lock().folders.entry(folder).or_default().walk = Some(walk);
|
||||
}
|
||||
|
||||
/// 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, None);
|
||||
// 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, None);
|
||||
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, None);
|
||||
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());
|
||||
}
|
||||
}
|
||||
+589
-15
@@ -38,13 +38,20 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use sha1::{Digest as _, Sha1};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use crate::effect::{self, EffectState};
|
||||
use crate::evidence::{Evidence, RemoteEvidence, Side};
|
||||
use crate::local_dirty::{Claim, LocalWalk, root_id};
|
||||
use crate::planner::HasKind;
|
||||
use crate::root::{Doubt, Phase as RootPhase, 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, StoredIntent, StoredSyncEntry, StoredSyncFolder,
|
||||
};
|
||||
|
||||
mod apply;
|
||||
mod engine;
|
||||
@@ -78,10 +85,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 +105,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 +160,49 @@ impl Syncer {
|
||||
let _ = self
|
||||
.store
|
||||
.sync_folder_set_state(folder.id, "error", now_secs());
|
||||
self.roots
|
||||
.input(folder.id, RootInput::Suspended(Suspension::RootMissing));
|
||||
// A root removed takes its watch with it, and one made again in
|
||||
// its place is not watched until the watches are set up again.
|
||||
// Until then the disk is walked in full.
|
||||
self.local_dirty.unwatched(folder.id);
|
||||
self.roots
|
||||
.input(folder.id, RootInput::Doubted(Doubt::WatchLost));
|
||||
let _ = self.tx.send(SyncMsg::Rewatch);
|
||||
return;
|
||||
}
|
||||
// Back after it was missing: watch it again. This pass walks the disk
|
||||
// in full, as the root state owes it.
|
||||
if self
|
||||
.roots
|
||||
.state(folder.id)
|
||||
.is_some_and(|state| state.phase == RootPhase::Suspended(Suspension::RootMissing))
|
||||
{
|
||||
let _ = self.tx.send(SyncMsg::Rewatch);
|
||||
}
|
||||
// Moved away and made again between two passes, or before the engine
|
||||
// got to drop the old watch: the watch is on a folder that is no
|
||||
// longer the root, and reports nothing of this one.
|
||||
if let Some(watched) = self.local_dirty.watched_root(folder.id)
|
||||
&& root_id(&local_root).is_some_and(|now| now != watched)
|
||||
{
|
||||
info!(
|
||||
id = folder.id,
|
||||
"sync: the folder's root was replaced; watching it again"
|
||||
);
|
||||
self.local_dirty.unwatched(folder.id);
|
||||
self.roots
|
||||
.input(folder.id, RootInput::Doubted(Doubt::WatchLost));
|
||||
let _ = self.tx.send(SyncMsg::Rewatch);
|
||||
}
|
||||
self.roots.input(
|
||||
folder.id,
|
||||
if push_only {
|
||||
RootInput::HandoffQueued
|
||||
} else {
|
||||
RootInput::Mirrored
|
||||
},
|
||||
);
|
||||
|
||||
let _ = self
|
||||
.store
|
||||
@@ -209,6 +263,13 @@ impl Syncer {
|
||||
let progress = self.progress.lock().get(&folder.id).cloned();
|
||||
self.progress_end(folder.id);
|
||||
self.log_trace(folder, &result, started.elapsed());
|
||||
if let Ok(outcome) = &result
|
||||
&& !push_only
|
||||
{
|
||||
let (local, remote) = outcome.walked_in_full;
|
||||
self.roots
|
||||
.input(folder.id, RootInput::Covered { local, remote });
|
||||
}
|
||||
match result {
|
||||
Ok(outcome) => {
|
||||
// A folder only reaches `idle` when every path applied cleanly —
|
||||
@@ -352,6 +413,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));
|
||||
@@ -445,6 +535,9 @@ impl Syncer {
|
||||
remote_root: &NodeUid,
|
||||
rules: &IgnoreRules,
|
||||
) -> Result<Outcome, PassAbort> {
|
||||
// Intents sent before this moment that the pass does not send again
|
||||
// are settled at its end (`effect`).
|
||||
let pass_began = now_secs();
|
||||
// Loaded before the walks: the remote one uses it to tell which files are
|
||||
// unchanged and so can skip decrypting their claimed size, and its size is
|
||||
// the only estimate available of how much this pass has to check — the walks
|
||||
@@ -460,20 +553,74 @@ impl Syncer {
|
||||
|
||||
let mut local: HashMap<String, LocalItem> = HashMap::new();
|
||||
let mut unscanned = Unscanned::default();
|
||||
// What the watcher reported since the last pass (`local_dirty`).
|
||||
// Claimed before the walk: a change made while it runs is newer than
|
||||
// the claim, and stays marked for the next pass.
|
||||
let claim = self.local_dirty.claim(folder_id);
|
||||
// What the root state says this pass must walk in full (`root`).
|
||||
let owed = self.roots.owed(folder_id);
|
||||
// The last pass's walk, when the claim can bring it up to date: the
|
||||
// watch was live since that pass claimed, the ignore rules are the
|
||||
// same, the folder was walked in full lately, and the root state owes
|
||||
// the disk nothing.
|
||||
let kept = self.local_dirty.take_walk(folder_id).filter(|kept| {
|
||||
claim.trusted
|
||||
&& kept.rules == rules.source()
|
||||
&& kept.walked_at.elapsed() < LOCAL_AUDIT_INTERVAL
|
||||
});
|
||||
let kept = match (kept, owed.local) {
|
||||
(Some(_), Some(doubt)) => {
|
||||
info!(
|
||||
id = folder_id,
|
||||
?doubt,
|
||||
"sync: the root state asks for a walk of the whole disk"
|
||||
);
|
||||
None
|
||||
}
|
||||
(kept, _) => kept,
|
||||
};
|
||||
let step = Instant::now();
|
||||
let writing = open_for_write_set(local_root);
|
||||
self.walk_local(
|
||||
folder_id,
|
||||
local_root,
|
||||
rules,
|
||||
&writing,
|
||||
&mut local,
|
||||
&mut unscanned,
|
||||
)?;
|
||||
let (walked_at, walked_in_full) = match kept {
|
||||
Some(kept) => {
|
||||
local = kept.items;
|
||||
self.trace_count(Count::LocalReused, local.len());
|
||||
// What is taken from the kept walk counts as scanned at once.
|
||||
self.progress_scanned_many(folder_id, local.len());
|
||||
rewalk_local_tree(
|
||||
local_root,
|
||||
rules,
|
||||
&writing,
|
||||
&claim,
|
||||
&mut local,
|
||||
&mut unscanned,
|
||||
&mut |rel| self.progress_scanned(folder_id, base_name(rel)),
|
||||
)?;
|
||||
(kept.walked_at, false)
|
||||
}
|
||||
None => {
|
||||
self.walk_local(
|
||||
folder_id,
|
||||
local_root,
|
||||
rules,
|
||||
&writing,
|
||||
&mut local,
|
||||
&mut unscanned,
|
||||
)?;
|
||||
(step, true)
|
||||
}
|
||||
};
|
||||
self.trace_phase(Phase::LocalWalk, step.elapsed());
|
||||
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)?;
|
||||
self.check_local_dirty(
|
||||
folder_id,
|
||||
&claim,
|
||||
walked_in_full,
|
||||
&tracked_baseline(&baseline, rules, &unscanned),
|
||||
&local,
|
||||
);
|
||||
|
||||
let mut remote: HashMap<String, RemoteItem> = HashMap::new();
|
||||
let mut remote_dirs: HashMap<String, NodeUid> = HashMap::new();
|
||||
@@ -489,11 +636,12 @@ impl Syncer {
|
||||
gaps: &mut gaps,
|
||||
},
|
||||
&baseline,
|
||||
owed.remote.is_none(),
|
||||
);
|
||||
// Timed even when cut short: a walk that never ends is the case the
|
||||
// trace exists for.
|
||||
self.trace_phase(Phase::RemoteWalk, step.elapsed());
|
||||
walked?;
|
||||
let remote_in_full = walked?;
|
||||
guard_remote_wipe(&tracked_baseline(&baseline, rules, &unscanned), &remote)?;
|
||||
|
||||
let mut order = classification_order(&local, &remote, &baseline, rules);
|
||||
@@ -501,12 +649,25 @@ 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());
|
||||
let mut outcome = Outcome {
|
||||
unscanned: unscanned_report,
|
||||
walked_in_full: (walked_in_full, remote_in_full),
|
||||
..Default::default()
|
||||
};
|
||||
// Folders to delete, collected here and removed deepest-first at the end
|
||||
@@ -587,10 +748,19 @@ 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 => {
|
||||
// New remote folder → create locally (cheap, inline).
|
||||
outcome.local_changes += 1;
|
||||
if let Err(e) = std::fs::create_dir_all(local_root.join(rel_to_path(rel)))
|
||||
.map_err(|e| format!("mkdir {rel}: {e}"))
|
||||
.and_then(|()| self.baseline_dir(folder_id, rel, &remote[rel].uid))
|
||||
@@ -601,6 +771,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) => {
|
||||
@@ -674,6 +852,18 @@ impl Syncer {
|
||||
}
|
||||
FilePlan::Conflict => {
|
||||
let remote = r.expect("conflict requires a remote file");
|
||||
if self.landed_unanswered(folder_id, rel, remote.sha1.as_deref()) {
|
||||
info!(
|
||||
rel,
|
||||
"sync: the file on Drive is an upload of ours that went unanswered; sending the newer local bytes as a revision of it"
|
||||
);
|
||||
batch.push(Pending::UploadRevision {
|
||||
rel: rel.clone(),
|
||||
uid: remote.uid.clone(),
|
||||
seen: RemoteSeen::from(remote),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
batch.push(Pending::Conflict {
|
||||
rel: rel.clone(),
|
||||
uid: remote.uid.clone(),
|
||||
@@ -691,6 +881,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
|
||||
@@ -701,6 +899,7 @@ impl Syncer {
|
||||
outcome.deferred += 1;
|
||||
continue;
|
||||
}
|
||||
outcome.local_changes += 1;
|
||||
if let Err(e) = removed_locally(std::fs::remove_file(&path)) {
|
||||
warn!(rel, error = %e, "sync: remove local file failed");
|
||||
self.log_activity(
|
||||
@@ -717,6 +916,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
|
||||
@@ -772,6 +979,7 @@ impl Syncer {
|
||||
.sync_entries(folder_id)
|
||||
.map_err(|e| format!("reload baseline: {e:?}"))?;
|
||||
for removal in remove_local_dirs(local_root, delete_local_dirs, &mut current) {
|
||||
outcome.local_changes += 1;
|
||||
match removal {
|
||||
DirRemoval::Removed(rel) => {
|
||||
let _ = self.store.sync_entry_remove(folder_id, &rel);
|
||||
@@ -852,13 +1060,184 @@ impl Syncer {
|
||||
outcome.deleted += 1;
|
||||
}
|
||||
self.trace_phase(Phase::Cleanup, cleanup.elapsed());
|
||||
self.settle_deletions(folder_id, window, outcome.deleted);
|
||||
// Every path was looked at and planned: what an earlier pass left
|
||||
// unsettled and this one did not send again is no longer owed.
|
||||
if outcome.unscanned.is_empty() && outcome.deferred == 0 {
|
||||
self.supersede_intents(folder_id, pass_began);
|
||||
}
|
||||
// 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,
|
||||
);
|
||||
// The walk is kept for the next pass only when the pass changed
|
||||
// nothing on disk itself and could read everything. A change of its
|
||||
// own is marked only once the watcher reports it, which may come
|
||||
// after the next pass claims, and a path left out has to be looked
|
||||
// at again anyway.
|
||||
if outcome.local_changes == 0
|
||||
&& outcome.errors == 0
|
||||
&& outcome.deferred == 0
|
||||
&& unscanned.is_empty()
|
||||
{
|
||||
self.local_dirty.keep_walk(
|
||||
folder_id,
|
||||
LocalWalk {
|
||||
items: local,
|
||||
rules: rules.source(),
|
||||
walked_at,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Count the claimed marks of the local dirty set, and, after a walk of
|
||||
/// the whole folder with a trusted claim, the local changes the walk
|
||||
/// found that the claim did not cover. Those are changes a pass that
|
||||
/// trusted the claim would have missed until the next full walk.
|
||||
fn check_local_dirty(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
claim: &Claim,
|
||||
walked_in_full: bool,
|
||||
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;
|
||||
}
|
||||
if !walked_in_full {
|
||||
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>>,
|
||||
@@ -943,6 +1322,11 @@ fn dir_row(rel: &str, uid: &NodeUid) -> StoredSyncEntry {
|
||||
/// stream marked dirty; this full walk catches what the stream may have missed.
|
||||
const AUDIT_INTERVAL: Duration = Duration::from_secs(24 * 3600);
|
||||
|
||||
/// How long a pass may bring the last local walk up to date from the local
|
||||
/// dirty set before it walks the whole folder again. The full walk is what
|
||||
/// checks the set: it counts what the set missed.
|
||||
const LOCAL_AUDIT_INTERVAL: Duration = Duration::from_secs(3600);
|
||||
|
||||
/// How lately Drive's event stream must have been read for a pass to rely on
|
||||
/// it. A few polls' worth.
|
||||
const EVENTS_FRESH: Duration = Duration::from_secs(3 * crate::EVENT_POLL_INTERVAL.as_secs());
|
||||
@@ -1661,6 +2045,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.
|
||||
@@ -2568,4 +3005,141 @@ mod tests {
|
||||
o.deferred = 1;
|
||||
assert!(!o.is_empty());
|
||||
}
|
||||
|
||||
/// What a walk found, comparable: kind, mtime and size by path.
|
||||
fn shape(items: &HashMap<String, LocalItem>) -> Vec<(String, bool, i64, i64)> {
|
||||
let mut shape: Vec<_> = items
|
||||
.iter()
|
||||
.map(|(rel, item)| (rel.clone(), item.is_dir, item.mtime, item.size))
|
||||
.collect();
|
||||
shape.sort();
|
||||
shape
|
||||
}
|
||||
|
||||
/// Bring `kept` up to date with what `dirty` marked for folder 1.
|
||||
fn rewalk(
|
||||
root: &Path,
|
||||
rules: &IgnoreRules,
|
||||
dirty: &crate::local_dirty::LocalDirty,
|
||||
kept: &mut HashMap<String, LocalItem>,
|
||||
) -> Unscanned {
|
||||
let mut unscanned = Unscanned::default();
|
||||
rewalk_local_tree(
|
||||
root,
|
||||
rules,
|
||||
&HashSet::new(),
|
||||
&dirty.claim(1),
|
||||
kept,
|
||||
&mut unscanned,
|
||||
&mut no_progress(),
|
||||
)
|
||||
.unwrap();
|
||||
unscanned
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rewalk_of_the_marked_paths_finds_what_a_full_walk_finds() {
|
||||
let root = sync_test_dir("rewalk");
|
||||
std::fs::create_dir_all(root.join("docs/old")).unwrap();
|
||||
std::fs::create_dir_all(root.join("quiet/deep")).unwrap();
|
||||
std::fs::write(root.join("docs/a.txt"), b"a").unwrap();
|
||||
std::fs::write(root.join("docs/b.txt"), b"b").unwrap();
|
||||
std::fs::write(root.join("docs/old/x.txt"), b"x").unwrap();
|
||||
std::fs::write(root.join("quiet/deep/q.txt"), b"q").unwrap();
|
||||
let (mut kept, _) = scan(&root).unwrap();
|
||||
|
||||
// Each kind of change, marked as the watcher reports it.
|
||||
let dirty = crate::local_dirty::LocalDirty::default();
|
||||
std::fs::write(root.join("docs/a.txt"), b"edited, and longer").unwrap();
|
||||
dirty.mark(1, "docs/a.txt");
|
||||
std::fs::remove_file(root.join("docs/b.txt")).unwrap();
|
||||
dirty.mark(1, "docs/b.txt");
|
||||
std::fs::write(root.join("docs/new.txt"), b"new").unwrap();
|
||||
dirty.mark(1, "docs/new.txt");
|
||||
std::fs::remove_dir_all(root.join("docs/old")).unwrap();
|
||||
dirty.mark(1, "docs/old");
|
||||
// A folder moved in: one event, for the folder only.
|
||||
let outside = sync_test_dir("rewalk-outside");
|
||||
std::fs::create_dir_all(outside.join("moved/sub")).unwrap();
|
||||
std::fs::write(outside.join("moved/sub/m.txt"), b"m").unwrap();
|
||||
std::fs::rename(outside.join("moved"), root.join("moved")).unwrap();
|
||||
dirty.mark(1, "moved");
|
||||
|
||||
let unscanned = rewalk(&root, &rules_for(&[]), &dirty, &mut kept);
|
||||
assert!(unscanned.is_empty());
|
||||
let (full, _) = scan(&root).unwrap();
|
||||
assert_eq!(shape(&kept), shape(&full));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let _ = std::fs::remove_dir_all(&outside);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rewalk_takes_what_nothing_marked_from_the_kept_walk() {
|
||||
let root = sync_test_dir("rewalk-kept");
|
||||
std::fs::create_dir_all(root.join("quiet")).unwrap();
|
||||
std::fs::write(root.join("quiet/q.txt"), b"q").unwrap();
|
||||
let (mut kept, _) = scan(&root).unwrap();
|
||||
// Changed with no mark: the rewalk does not look, which is why only
|
||||
// a trusted claim may stand in for the walk.
|
||||
std::fs::write(root.join("quiet/q.txt"), b"changed unseen").unwrap();
|
||||
let before = shape(&kept);
|
||||
rewalk(
|
||||
&root,
|
||||
&rules_for(&[]),
|
||||
&crate::local_dirty::LocalDirty::default(),
|
||||
&mut kept,
|
||||
);
|
||||
assert_eq!(shape(&kept), before);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rewalk_leaves_ignored_folders_out_and_walks_from_a_known_folder() {
|
||||
let root = sync_test_dir("rewalk-ignored");
|
||||
let rules = rules_for(&["build/"]);
|
||||
let (mut kept, _) = scan(&root).unwrap();
|
||||
let dirty = crate::local_dirty::LocalDirty::default();
|
||||
std::fs::create_dir_all(root.join("build/out")).unwrap();
|
||||
std::fs::write(root.join("build/out/o.bin"), b"o").unwrap();
|
||||
dirty.mark(1, "build/out/o.bin");
|
||||
// A file in a folder whose own mark never came.
|
||||
std::fs::create_dir_all(root.join("src/mod")).unwrap();
|
||||
std::fs::write(root.join("src/mod/s.rs"), b"s").unwrap();
|
||||
dirty.mark(1, "src/mod/s.rs");
|
||||
rewalk(&root, &rules, &dirty, &mut kept);
|
||||
let found: Vec<String> = shape(&kept).into_iter().map(|(rel, ..)| rel).collect();
|
||||
assert_eq!(found, ["src", "src/mod", "src/mod/s.rs"]);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rewalk_reads_again_a_file_that_was_open_for_writing() {
|
||||
let root = sync_test_dir("rewalk-open");
|
||||
std::fs::write(root.join("log.txt"), b"one").unwrap();
|
||||
let (mut kept, _) = scan(&root).unwrap();
|
||||
kept.get_mut("log.txt").unwrap().open_for_write = true;
|
||||
std::fs::write(root.join("log.txt"), b"one and two").unwrap();
|
||||
rewalk(
|
||||
&root,
|
||||
&rules_for(&[]),
|
||||
&crate::local_dirty::LocalDirty::default(),
|
||||
&mut kept,
|
||||
);
|
||||
let item = &kept["log.txt"];
|
||||
assert_eq!(item.size, 11);
|
||||
assert!(!item.open_for_write, "closed now");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mark_on_the_root_walks_everything() {
|
||||
let root = sync_test_dir("rewalk-root");
|
||||
let (mut kept, _) = scan(&root).unwrap();
|
||||
std::fs::write(root.join("top.txt"), b"t").unwrap();
|
||||
let dirty = crate::local_dirty::LocalDirty::default();
|
||||
dirty.mark(1, "");
|
||||
rewalk(&root, &rules_for(&[]), &dirty, &mut kept);
|
||||
assert!(kept.contains_key("top.txt"));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -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() {
|
||||
@@ -128,6 +134,146 @@ impl Syncer {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write the intent of `op` before it is sent (`effect`). In shadow: a
|
||||
/// failure to write it is logged, and the op is sent anyway.
|
||||
fn issue_intent(&self, folder_id: i64, op: &Pending) -> Option<StoredIntent> {
|
||||
let (intent, before) = match self.store.sync_intent_issue(
|
||||
folder_id,
|
||||
op.rel(),
|
||||
op.intent(),
|
||||
now_secs(),
|
||||
) {
|
||||
Ok(issued) => issued,
|
||||
Err(e) => {
|
||||
debug!(id = folder_id, rel = op.rel(), error = ?e, "sync: cannot record an intent");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
match before.as_deref().and_then(EffectState::from_name) {
|
||||
// Sent by a daemon that stopped before it heard back. The apply
|
||||
// step's own checks tell whether it landed (B266, B39).
|
||||
Some(EffectState::Unsure) => {
|
||||
self.trace_count(Count::UnsureResent, 1);
|
||||
info!(
|
||||
id = folder_id,
|
||||
rel = op.rel(),
|
||||
kind = op.intent(),
|
||||
attempts = intent.attempts,
|
||||
"sync: sending again an effect a stopped daemon may have made"
|
||||
);
|
||||
}
|
||||
Some(EffectState::Retry | EffectState::Blocked) => {
|
||||
self.trace_count(Count::Retried, 1);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Some(intent)
|
||||
}
|
||||
|
||||
/// Settle or keep `intent` by how its op ended.
|
||||
fn settle_intent(&self, intent: &StoredIntent, op: &Pending, result: &Result<Applied, String>) {
|
||||
let written = match result {
|
||||
Ok(_) => self.store.sync_intent_settle(intent.id),
|
||||
Err(e) => {
|
||||
let state = effect::failed(intent.attempts);
|
||||
if state == EffectState::Blocked && intent.state != EffectState::Blocked.name() {
|
||||
warn!(
|
||||
id = intent.folder_id,
|
||||
rel = op.rel(),
|
||||
kind = op.intent(),
|
||||
attempts = intent.attempts,
|
||||
error = %e,
|
||||
"sync: an effect keeps failing"
|
||||
);
|
||||
}
|
||||
self.store.sync_intent_set(intent.id, state.name(), Some(e))
|
||||
}
|
||||
};
|
||||
if let Err(e) = written {
|
||||
debug!(id = intent.folder_id, rel = op.rel(), error = ?e, "sync: cannot settle an intent");
|
||||
}
|
||||
}
|
||||
|
||||
/// Note that an upload of `rel` streamed bytes with SHA-1 `sha1` and did
|
||||
/// not hear a success back. They may have landed all the same.
|
||||
fn note_sent(&self, folder_id: i64, rel: &str, kind: &str, sha1: &str) {
|
||||
if let Err(error) = self.store.sync_intent_sent(folder_id, rel, kind, sha1) {
|
||||
debug!(rel, error = ?error, "sync: cannot note what an upload sent");
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the file Drive holds at `rel`, with SHA-1 `remote_sha1`, is one
|
||||
/// of this daemon's own uploads whose answer never came: an upload of
|
||||
/// `rel` not yet settled streamed exactly those bytes.
|
||||
///
|
||||
/// Then the file is ours, not another computer's, and a newer local edit
|
||||
/// is not a conflict with it: it goes up as a revision. A file that only
|
||||
/// happens to hold the same bytes loses nothing by that either.
|
||||
pub(super) fn landed_unanswered(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel: &str,
|
||||
remote_sha1: Option<&str>,
|
||||
) -> bool {
|
||||
let Some(remote_sha1) = remote_sha1 else {
|
||||
return false;
|
||||
};
|
||||
let intents = match self.store.sync_intents(Some(folder_id)) {
|
||||
Ok(intents) => intents,
|
||||
Err(error) => {
|
||||
debug!(rel, error = ?error, "sync: cannot read the effect intents");
|
||||
return false;
|
||||
}
|
||||
};
|
||||
intents.iter().any(|intent| {
|
||||
intent.rel_path == rel
|
||||
&& matches!(intent.kind.as_str(), "upload" | "upload-revision")
|
||||
&& intent
|
||||
.sent_sha1s
|
||||
.iter()
|
||||
.any(|sent| sent.eq_ignore_ascii_case(remote_sha1))
|
||||
})
|
||||
}
|
||||
|
||||
/// Settle the intents of `folder_id` that a pass begun at `began` did
|
||||
/// not send again, though it looked at every path: what they were for has
|
||||
/// changed, or is done.
|
||||
pub(super) fn supersede_intents(&self, folder_id: i64, began: i64) {
|
||||
let states = [
|
||||
EffectState::Unsure.name(),
|
||||
EffectState::Retry.name(),
|
||||
EffectState::Blocked.name(),
|
||||
];
|
||||
match self
|
||||
.store
|
||||
.sync_intents_settle_before(folder_id, &states, began)
|
||||
{
|
||||
Ok(settled) => {
|
||||
self.trace_count(Count::Superseded, settled.len());
|
||||
for intent in settled {
|
||||
let level_info = intent.state == EffectState::Unsure.name();
|
||||
if level_info {
|
||||
info!(
|
||||
id = folder_id,
|
||||
rel = %intent.rel_path,
|
||||
kind = %intent.kind,
|
||||
"sync: an effect a stopped daemon may have made is no longer needed"
|
||||
);
|
||||
} else {
|
||||
debug!(
|
||||
id = folder_id,
|
||||
rel = %intent.rel_path,
|
||||
kind = %intent.kind,
|
||||
state = %intent.state,
|
||||
"sync: an effect is no longer needed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => debug!(id = folder_id, error = ?e, "sync: cannot settle intents"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a removal of `folder_id` is waiting for its running pass.
|
||||
pub(super) fn pass_abandoned(&self, folder_id: i64) -> bool {
|
||||
self.abandon.lock().contains(&folder_id)
|
||||
@@ -144,9 +290,13 @@ impl Syncer {
|
||||
op: Pending,
|
||||
) -> Result<Applied, String> {
|
||||
self.progress_started(folder_id, base_name(op.rel()));
|
||||
let intent = self.issue_intent(folder_id, &op);
|
||||
let step = Instant::now();
|
||||
let result = self.apply_one(folder_id, local_root, &op).await;
|
||||
self.trace_call(op.call(), step.elapsed());
|
||||
if let Some(intent) = intent {
|
||||
self.settle_intent(&intent, &op, &result);
|
||||
}
|
||||
self.progress_finished(folder_id);
|
||||
let name = base_name(op.rel());
|
||||
match &result {
|
||||
@@ -214,6 +364,15 @@ impl Syncer {
|
||||
return Ok(Applied::Vanished);
|
||||
}
|
||||
if !digest.eq_ignore_ascii_case(sha1) {
|
||||
if self.landed_unanswered(folder_id, rel, Some(sha1)) {
|
||||
info!(
|
||||
rel,
|
||||
"sync: the file on Drive is an upload of ours that went unanswered; sending the newer local bytes as a revision of it"
|
||||
);
|
||||
return self
|
||||
.upload_revision(folder_id, local_root, rel, uid, remote)
|
||||
.await;
|
||||
}
|
||||
info!(
|
||||
rel,
|
||||
"sync: same size as on Drive but different content; keeping a conflict copy"
|
||||
@@ -335,8 +494,14 @@ impl Syncer {
|
||||
Some(mtime),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| format!("upload {rel}: {e}"))?;
|
||||
.await;
|
||||
let uid = match uid {
|
||||
Ok(uid) => uid,
|
||||
Err(e) => {
|
||||
self.note_sent(folder_id, rel, "upload", &sent.digest());
|
||||
return Err(format!("upload {rel}: {e}"));
|
||||
}
|
||||
};
|
||||
// The parent has gained a child that no cached listing of it knows
|
||||
// about. Without this, a folder later switched to on-demand serves a
|
||||
// snapshot that predates this upload (B86).
|
||||
@@ -356,9 +521,13 @@ impl Syncer {
|
||||
/// folder may have committed a revision since, and uploading over it would
|
||||
/// leave that edit only in the revision history. So Drive is asked first,
|
||||
/// and a file that moved on is left for the next pass, which keeps the
|
||||
/// local edit as a conflict copy (B249). A revision committed between this
|
||||
/// check and the upload's own draft is not caught here; the read-back after
|
||||
/// the upload catches one committed after it.
|
||||
/// local edit as a conflict copy (B249). A revision committed after the
|
||||
/// upload is caught by the read-back.
|
||||
///
|
||||
/// When the pass knows the revision id, the check rides on the read of the
|
||||
/// file the upload makes for its keys (`upload_new_revision_over`), and the
|
||||
/// revision is created over that id, so Drive refuses one committed in
|
||||
/// between. A baseline without an id still reads the node first.
|
||||
pub(super) async fn upload_revision(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
@@ -371,22 +540,16 @@ impl Syncer {
|
||||
let Some(file) = open_to_upload(&path, rel)? else {
|
||||
return Ok(Applied::Vanished);
|
||||
};
|
||||
let current = self
|
||||
.drive
|
||||
.enumerate_nodes(std::slice::from_ref(uid))
|
||||
.await
|
||||
.map_err(|e| format!("check {rel} on Drive: {e}"))?;
|
||||
match current.first() {
|
||||
Some(node) if !node.trashed && seen.still_current(node) => {}
|
||||
Some(node) if !node.trashed => {
|
||||
return Err(format!(
|
||||
"{rel} changed on Drive since this pass looked; it is compared again on the next pass"
|
||||
));
|
||||
}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"{rel} is no longer on Drive where this pass saw it; it is compared again on the next pass"
|
||||
));
|
||||
if seen.revision.is_none() {
|
||||
let current = self
|
||||
.drive
|
||||
.enumerate_nodes(std::slice::from_ref(uid))
|
||||
.await
|
||||
.map_err(|e| format!("check {rel} on Drive: {e}"))?;
|
||||
match current.first() {
|
||||
Some(node) if !node.trashed && seen.still_current(node) => {}
|
||||
Some(node) if !node.trashed => return Err(moved_on_drive(rel)),
|
||||
_ => return Err(gone_from_drive(rel)),
|
||||
}
|
||||
}
|
||||
let meta = file.metadata().map_err(|e| format!("stat {rel}: {e}"))?;
|
||||
@@ -404,10 +567,28 @@ impl Syncer {
|
||||
meta.len(),
|
||||
),
|
||||
));
|
||||
self.drive
|
||||
.upload_new_revision_from(uid, reader, meta.len() as i64, thumbnails, Some(mtime))
|
||||
.await
|
||||
.map_err(|e| format!("upload revision {rel}: {e}"))?;
|
||||
let size = meta.len() as i64;
|
||||
let uploaded = match seen.revision.as_deref() {
|
||||
Some(expected) => self
|
||||
.drive
|
||||
.upload_new_revision_over(uid, expected, reader, size, thumbnails, Some(mtime))
|
||||
.await
|
||||
.map(Some),
|
||||
None => self
|
||||
.drive
|
||||
.upload_new_revision_from(uid, reader, size, thumbnails, Some(mtime))
|
||||
.await
|
||||
.map(|()| None),
|
||||
};
|
||||
match uploaded {
|
||||
Ok(None | Some(pdfs_drive::RevisionUpload::Sealed(_))) => {}
|
||||
Ok(Some(pdfs_drive::RevisionUpload::Moved)) => return Err(moved_on_drive(rel)),
|
||||
Ok(Some(pdfs_drive::RevisionUpload::Trashed)) => return Err(gone_from_drive(rel)),
|
||||
Err(e) => {
|
||||
self.note_sent(folder_id, rel, "upload-revision", &sent.digest());
|
||||
return Err(format!("upload revision {rel}: {e}"));
|
||||
}
|
||||
}
|
||||
warn_if_torn(rel, &path, streamed);
|
||||
let remote = self
|
||||
.landed_as_sent(rel, uid, &sent.digest(), streamed)
|
||||
@@ -576,3 +757,16 @@ impl Syncer {
|
||||
.map_err(|e| format!("baseline {rel}: {e:?}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a revision was not sent: Drive's file moved on since the pass looked.
|
||||
fn moved_on_drive(rel: &str) -> String {
|
||||
format!("{rel} changed on Drive since this pass looked; it is compared again on the next pass")
|
||||
}
|
||||
|
||||
/// Why a revision was not sent: the file is no longer on Drive where the pass
|
||||
/// saw it.
|
||||
fn gone_from_drive(rel: &str) -> String {
|
||||
format!(
|
||||
"{rel} is no longer on Drive where this pass saw it; it is compared again on the next pass"
|
||||
)
|
||||
}
|
||||
@@ -10,6 +10,8 @@ use std::collections::BTreeMap;
|
||||
|
||||
use super::trace::PassTrace;
|
||||
use super::*;
|
||||
use crate::local_dirty::{LocalDirty, root_id};
|
||||
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.
|
||||
@@ -240,27 +242,52 @@ pub fn run(core: Syncer, rx: Receiver<SyncMsg>) {
|
||||
),
|
||||
Err(e) => warn!(error = ?e, "sync: cannot reset folders left syncing"),
|
||||
}
|
||||
// An effect still `issued` was sent by a daemon that stopped before it
|
||||
// heard back: it may or may not have happened (`effect`).
|
||||
match core.store.sync_intents_move(
|
||||
effect::EffectState::Issued.name(),
|
||||
effect::EffectState::Unsure.name(),
|
||||
) {
|
||||
Ok(0) => {}
|
||||
Ok(n) => info!(
|
||||
effects = n,
|
||||
"sync: effects the last run sent and did not hear back from"
|
||||
),
|
||||
Err(e) => warn!(error = ?e, "sync: cannot read the effects the last run sent"),
|
||||
}
|
||||
// Paths the watcher currently covers, mapped to their folder id, so an event
|
||||
// path can be resolved back to the folder it belongs to.
|
||||
let watched: Arc<Mutex<Vec<(PathBuf, i64)>>> = Arc::new(Mutex::new(Vec::new()));
|
||||
|
||||
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
|
||||
@@ -292,7 +319,7 @@ pub fn run(core: Syncer, rx: Receiver<SyncMsg>) {
|
||||
.ok();
|
||||
}
|
||||
|
||||
let mut unwatched = rewatch(&core, &mut watcher, &watched);
|
||||
let (mut unwatched, _) = rewatch(&core, &mut watcher, &watched);
|
||||
let mut last_rewatch = Instant::now();
|
||||
run_burst(&core, &HashSet::new(), true);
|
||||
|
||||
@@ -313,7 +340,14 @@ pub fn run(core: Syncer, rx: Receiver<SyncMsg>) {
|
||||
do_rewatch = true;
|
||||
}
|
||||
if do_rewatch {
|
||||
unwatched = rewatch(&core, &mut watcher, &watched);
|
||||
let newly;
|
||||
(unwatched, newly) = rewatch(&core, &mut watcher, &watched);
|
||||
// A change made before its folder was watched has no event. A
|
||||
// folder whose root came back was watched only after the pass
|
||||
// that found it walked it, so what was written in between waits
|
||||
// for this pass, which walks it in full: its claim is not trusted
|
||||
// yet.
|
||||
ids.extend(newly);
|
||||
last_rewatch = Instant::now();
|
||||
}
|
||||
run_burst(&core, &ids, all);
|
||||
@@ -513,9 +547,33 @@ 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;
|
||||
};
|
||||
// A name that is not UTF-8 cannot be keyed: the folder that holds
|
||||
// it is marked instead, so the walk of it reports the name it leaves
|
||||
// out.
|
||||
let parts: Vec<&str> = rel
|
||||
.components()
|
||||
.map_while(|c| c.as_os_str().to_str())
|
||||
.collect();
|
||||
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.
|
||||
/// left unwatched because its watch failed, and the folders watched anew.
|
||||
///
|
||||
/// The watch calls run on a copy, outside the lock: the watcher's event
|
||||
/// callback takes the same lock, and a backend that hands a watch request to
|
||||
@@ -524,7 +582,7 @@ fn rewatch(
|
||||
core: &Syncer,
|
||||
watcher: &mut notify::RecommendedWatcher,
|
||||
watched: &Mutex<Vec<(PathBuf, i64)>>,
|
||||
) -> bool {
|
||||
) -> (bool, Vec<i64>) {
|
||||
let want: Vec<(PathBuf, i64)> = match core.store.sync_folder_list() {
|
||||
Ok(f) => f
|
||||
.into_iter()
|
||||
@@ -533,23 +591,48 @@ fn rewatch(
|
||||
.collect(),
|
||||
Err(e) => {
|
||||
warn!(error = ?e, "sync: cannot list folders to watch");
|
||||
return false;
|
||||
return (false, Vec::new());
|
||||
}
|
||||
};
|
||||
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);
|
||||
}
|
||||
}
|
||||
// A root that is gone took its watch with it, and a root made again is
|
||||
// another folder than the one watched: drop the watch, so the root is
|
||||
// watched again below.
|
||||
have.retain(|(path, id)| {
|
||||
let same = core
|
||||
.local_dirty
|
||||
.watched_root(*id)
|
||||
.is_some_and(|root| root_id(path) == Some(root));
|
||||
if !same {
|
||||
let _ = watcher.unwatch(path);
|
||||
core.local_dirty.unwatched(*id);
|
||||
}
|
||||
same
|
||||
});
|
||||
// Add newly wanted watches.
|
||||
let mut failed = false;
|
||||
let mut newly = Vec::new();
|
||||
for (path, id) in &want {
|
||||
if have.iter().any(|(p, _)| p == path) {
|
||||
continue;
|
||||
}
|
||||
match watcher.watch(path, RecursiveMode::Recursive) {
|
||||
Ok(()) => have.push((path.clone(), *id)),
|
||||
Ok(()) => {
|
||||
have.push((path.clone(), *id));
|
||||
core.local_dirty.watched(*id, root_id(path));
|
||||
newly.push(*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).
|
||||
@@ -565,7 +648,7 @@ fn rewatch(
|
||||
}
|
||||
}
|
||||
*watched.lock() = have;
|
||||
failed
|
||||
(failed, newly)
|
||||
}
|
||||
|
||||
/// Keep the watches in `have` that `want` still asks for, and return the paths
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -19,8 +19,9 @@ use tracing::{debug, warn};
|
||||
|
||||
use super::model::{LocalItem, LocalSig, system_mtime, system_mtime_ns};
|
||||
use super::planner::{
|
||||
Unscanned, conflict_path_with_suffix, filter_baseline, join_rel, rel_to_path,
|
||||
Unscanned, conflict_path_with_suffix, filter_baseline, join_rel, parent_rel, rel_to_path,
|
||||
};
|
||||
use crate::local_dirty::Claim;
|
||||
|
||||
/// A local file's identity and content SHA-1, both read from one descriptor,
|
||||
/// or `None` when it is gone. The identity is taken after the hash, so a file
|
||||
@@ -270,90 +271,271 @@ pub(super) fn walk_local_dir(
|
||||
let entries = std::fs::read_dir(dir).map_err(io(format!("read {}", dir.display())))?;
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(io(format!("read entry in {}", dir.display())))?;
|
||||
let path = entry.path();
|
||||
let stripped = path.strip_prefix(root).map_err(|e| {
|
||||
ScanError::Failed(format!(
|
||||
"local path {} escaped sync root {}: {e}",
|
||||
path.display(),
|
||||
root.display()
|
||||
))
|
||||
})?;
|
||||
let Some(rel) = stripped.to_str() else {
|
||||
// Nothing can be keyed by this name: not the baseline, which only
|
||||
// ever held paths this scan produced, and not Drive, whose names are
|
||||
// UTF-8. Leaving it out cannot read as a deletion of anything.
|
||||
warn!(path = %path.display(), "sync: name is not valid UTF-8; leaving it out of the pass");
|
||||
unscanned.unreadable(
|
||||
stripped.to_string_lossy().into_owned(),
|
||||
"name is not valid UTF-8",
|
||||
);
|
||||
continue;
|
||||
};
|
||||
// Ignore our own in-flight download temp files.
|
||||
if rel.contains(".pdfs-tmp-") {
|
||||
walk_local_entry(root, &entry.path(), rules, writing, out, unscanned, scanned)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Collect one entry of the local tree, at `path`, into `out`: a file, or a
|
||||
/// folder with everything under it. What cannot be read goes to `unscanned`,
|
||||
/// as in [`walk_local_tree`].
|
||||
pub(super) fn walk_local_entry(
|
||||
root: &Path,
|
||||
path: &Path,
|
||||
rules: &IgnoreRules,
|
||||
writing: &HashSet<PathBuf>,
|
||||
out: &mut HashMap<String, LocalItem>,
|
||||
unscanned: &mut Unscanned,
|
||||
scanned: &mut dyn FnMut(&str),
|
||||
) -> Result<(), ScanError> {
|
||||
let stripped = path.strip_prefix(root).map_err(|e| {
|
||||
ScanError::Failed(format!(
|
||||
"local path {} escaped sync root {}: {e}",
|
||||
path.display(),
|
||||
root.display()
|
||||
))
|
||||
})?;
|
||||
let Some(rel) = stripped.to_str() else {
|
||||
// Nothing can be keyed by this name: not the baseline, which only
|
||||
// ever held paths this scan produced, and not Drive, whose names are
|
||||
// UTF-8. Leaving it out cannot read as a deletion of anything.
|
||||
warn!(path = %path.display(), "sync: name is not valid UTF-8; leaving it out of the pass");
|
||||
unscanned.unreadable(
|
||||
stripped.to_string_lossy().into_owned(),
|
||||
"name is not valid UTF-8",
|
||||
);
|
||||
return Ok(());
|
||||
};
|
||||
// Ignore our own in-flight download temp files.
|
||||
if rel.contains(".pdfs-tmp-") {
|
||||
return Ok(());
|
||||
}
|
||||
let meta = match std::fs::symlink_metadata(path) {
|
||||
Ok(meta) => meta,
|
||||
// Gone since the listing, or in a folder that lists but does not
|
||||
// allow `stat`. Either way this pass cannot say what it is.
|
||||
Err(error) => {
|
||||
let what = format!("stat {}", path.display());
|
||||
return leave_out(rel, ScanError::Io { what, error }, unscanned);
|
||||
}
|
||||
};
|
||||
// Ignored paths are dropped here as well as from the classification
|
||||
// union — not for correctness (the union filter is what makes this
|
||||
// safe) but so an ignored `node_modules/` is never descended into or
|
||||
// counted against scan progress.
|
||||
if rules.is_ignored(rel, meta.is_dir()) {
|
||||
return Ok(());
|
||||
}
|
||||
if meta.is_dir() {
|
||||
out.insert(
|
||||
rel.to_string(),
|
||||
LocalItem {
|
||||
is_dir: true,
|
||||
mtime: 0,
|
||||
mtime_ns: None,
|
||||
size: 0,
|
||||
open_for_write: false,
|
||||
},
|
||||
);
|
||||
scanned(rel);
|
||||
if let Err(failure) = walk_local_dir(root, path, rules, writing, out, unscanned, scanned) {
|
||||
leave_out(rel, failure, unscanned)?;
|
||||
// What the folder did list before failing goes with it: a
|
||||
// half-read folder is as unknown as an unread one.
|
||||
let prefix = format!("{rel}/");
|
||||
out.retain(|k, _| k != rel && !k.starts_with(&prefix));
|
||||
}
|
||||
} else if meta.is_file() {
|
||||
// Check whether any process holds this file open for writing.
|
||||
// The canonical path is used because /proc/*/fd links resolve
|
||||
// to canonical targets.
|
||||
let ofw = std::fs::canonicalize(path)
|
||||
.map(|canon| writing.contains(&canon))
|
||||
.unwrap_or(false);
|
||||
out.insert(
|
||||
rel.to_string(),
|
||||
LocalItem {
|
||||
is_dir: false,
|
||||
mtime: system_mtime(&meta),
|
||||
mtime_ns: system_mtime_ns(&meta),
|
||||
size: meta.len() as i64,
|
||||
open_for_write: ofw,
|
||||
},
|
||||
);
|
||||
scanned(rel);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Bring `items`, a walk of `root` that an earlier pass kept, up to date with
|
||||
/// what `claim` reports changed since, instead of walking the whole tree:
|
||||
///
|
||||
/// - each folder whose direct children changed is listed again: a child gone
|
||||
/// from it goes with everything under it, a child that is new or no longer
|
||||
/// the same kind is walked, and a subfolder still there keeps what the
|
||||
/// earlier walk found under it;
|
||||
/// - each path that changed in full is walked again, with what is under it;
|
||||
/// - each file that was open for writing is read again, since closing it is
|
||||
/// not a change the watcher reports.
|
||||
///
|
||||
/// Everything else stands as the earlier walk found it. That is only sound
|
||||
/// for a claim that is trusted, of a walk taken before it, with the same
|
||||
/// ignore rules: see `local_dirty`.
|
||||
pub(super) fn rewalk_local_tree(
|
||||
root: &Path,
|
||||
rules: &IgnoreRules,
|
||||
writing: &HashSet<PathBuf>,
|
||||
claim: &Claim,
|
||||
items: &mut HashMap<String, LocalItem>,
|
||||
unscanned: &mut Unscanned,
|
||||
scanned: &mut dyn FnMut(&str),
|
||||
) -> Result<(), String> {
|
||||
let walked = |rel: &str, items: &HashMap<String, LocalItem>| {
|
||||
rel.is_empty() || items.get(rel).is_some_and(|item| item.is_dir)
|
||||
};
|
||||
// A path whose folder the earlier walk did not find (a mark that came
|
||||
// before its folder's, or one in an ignored folder) is walked from the
|
||||
// nearest folder it did find.
|
||||
let anchored = |mut rel: String, items: &HashMap<String, LocalItem>| {
|
||||
while !walked(parent_rel(&rel), items) {
|
||||
rel = parent_rel(&rel).to_string();
|
||||
}
|
||||
rel
|
||||
};
|
||||
// Paths walked again in full.
|
||||
let mut again: Vec<String> = claim
|
||||
.deep()
|
||||
.map(str::to_string)
|
||||
.chain(
|
||||
items
|
||||
.iter()
|
||||
.filter(|(_, item)| item.open_for_write)
|
||||
.map(|(rel, _)| rel.clone()),
|
||||
)
|
||||
.map(|rel| anchored(rel, items))
|
||||
.collect();
|
||||
if again.iter().any(String::is_empty) {
|
||||
items.clear();
|
||||
return walk_local_tree(root, rules, writing, items, unscanned, scanned);
|
||||
}
|
||||
let mut folders: Vec<&str> = claim.shallow().collect();
|
||||
folders.sort_by_key(|dir| (dir.matches('/').count(), *dir));
|
||||
let mut children: HashMap<&str, Vec<String>> =
|
||||
folders.iter().map(|dir| (*dir, Vec::new())).collect();
|
||||
for rel in items.keys() {
|
||||
if let Some(of) = children.get_mut(parent_rel(rel)) {
|
||||
of.push(rel.clone());
|
||||
}
|
||||
}
|
||||
// Subtrees to drop from the earlier walk before walking anything again.
|
||||
let mut dropped: HashSet<String> = again.iter().cloned().collect();
|
||||
for dir in folders {
|
||||
if !walked(dir, items) {
|
||||
// Not a folder the earlier walk found: new, ignored, or no
|
||||
// longer a folder. It is walked in full.
|
||||
let rel = anchored(dir.to_string(), items);
|
||||
dropped.insert(rel.clone());
|
||||
again.push(rel);
|
||||
continue;
|
||||
}
|
||||
let meta = match std::fs::symlink_metadata(&path) {
|
||||
Ok(meta) => meta,
|
||||
// Gone since the listing, or in a folder that lists but does not
|
||||
// allow `stat`. Either way this pass cannot say what it is.
|
||||
let path = root.join(rel_to_path(dir));
|
||||
let listing = std::fs::read_dir(&path).and_then(|entries| {
|
||||
entries
|
||||
.map(|entry| entry.map(|entry| entry.path()))
|
||||
.collect::<std::io::Result<Vec<PathBuf>>>()
|
||||
});
|
||||
let listing = match listing {
|
||||
Ok(listing) => listing,
|
||||
Err(error) if dir.is_empty() => {
|
||||
return Err(format!("read {}: {error}", path.display()));
|
||||
}
|
||||
Err(error) => {
|
||||
let what = format!("stat {}", path.display());
|
||||
leave_out(rel, ScanError::Io { what, error }, unscanned)?;
|
||||
dropped.insert(dir.to_string());
|
||||
if error.kind() != std::io::ErrorKind::NotFound {
|
||||
let what = format!("read {}", path.display());
|
||||
leave_out(dir, ScanError::Io { what, error }, unscanned)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// Ignored paths are dropped here as well as from the classification
|
||||
// union — not for correctness (the union filter is what makes this
|
||||
// safe) but so an ignored `node_modules/` is never descended into or
|
||||
// counted against scan progress.
|
||||
if rules.is_ignored(rel, meta.is_dir()) {
|
||||
continue;
|
||||
let mut present: HashSet<String> = HashSet::with_capacity(listing.len());
|
||||
for child in listing {
|
||||
let Some(rel) = child
|
||||
.strip_prefix(root)
|
||||
.ok()
|
||||
.and_then(|rel| rel.to_str())
|
||||
.map(str::to_string)
|
||||
else {
|
||||
// Walked again, so a name that cannot be keyed is reported
|
||||
// as a full walk reports it.
|
||||
again.push(dir.to_string());
|
||||
dropped.insert(dir.to_string());
|
||||
break;
|
||||
};
|
||||
let still_a_folder = items.get(&rel).is_some_and(|item| item.is_dir)
|
||||
&& std::fs::symlink_metadata(&child).is_ok_and(|meta| meta.is_dir());
|
||||
if !still_a_folder {
|
||||
dropped.insert(rel.clone());
|
||||
again.push(rel.clone());
|
||||
}
|
||||
present.insert(rel);
|
||||
}
|
||||
if meta.is_dir() {
|
||||
out.insert(
|
||||
rel.to_string(),
|
||||
LocalItem {
|
||||
is_dir: true,
|
||||
mtime: 0,
|
||||
mtime_ns: None,
|
||||
size: 0,
|
||||
open_for_write: false,
|
||||
},
|
||||
);
|
||||
scanned(rel);
|
||||
if let Err(failure) =
|
||||
walk_local_dir(root, &path, rules, writing, out, unscanned, scanned)
|
||||
{
|
||||
leave_out(rel, failure, unscanned)?;
|
||||
// What the folder did list before failing goes with it: a
|
||||
// half-read folder is as unknown as an unread one.
|
||||
let prefix = format!("{rel}/");
|
||||
out.retain(|k, _| k != rel && !k.starts_with(&prefix));
|
||||
for rel in &children[dir] {
|
||||
if !present.contains(rel) {
|
||||
dropped.insert(rel.clone());
|
||||
}
|
||||
} else if meta.is_file() {
|
||||
// Check whether any process holds this file open for writing.
|
||||
// The canonical path is used because /proc/*/fd links resolve
|
||||
// to canonical targets.
|
||||
let ofw = std::fs::canonicalize(&path)
|
||||
.map(|canon| writing.contains(&canon))
|
||||
.unwrap_or(false);
|
||||
out.insert(
|
||||
rel.to_string(),
|
||||
LocalItem {
|
||||
is_dir: false,
|
||||
mtime: system_mtime(&meta),
|
||||
mtime_ns: system_mtime_ns(&meta),
|
||||
size: meta.len() as i64,
|
||||
open_for_write: ofw,
|
||||
},
|
||||
);
|
||||
scanned(rel);
|
||||
}
|
||||
}
|
||||
items.retain(|rel, _| !under_any(rel, &dropped));
|
||||
again.sort_by_key(|rel| (rel.matches('/').count(), rel.clone()));
|
||||
again.dedup();
|
||||
let mut walked_again: HashSet<String> = HashSet::new();
|
||||
for rel in again {
|
||||
if under_any(&rel, &walked_again) {
|
||||
continue;
|
||||
}
|
||||
let path = root.join(rel_to_path(&rel));
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Ok(_) => {
|
||||
walk_local_entry(root, &path, rules, writing, items, unscanned, scanned)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
// Gone since it was marked, or its folder is no longer one:
|
||||
// nothing to find.
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
|
||||
) => {}
|
||||
Err(error) => {
|
||||
let what = format!("stat {}", path.display());
|
||||
leave_out(&rel, ScanError::Io { what, error }, unscanned)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
walked_again.insert(rel);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `rel` is one of `roots` or lies under one.
|
||||
fn under_any(rel: &str, roots: &HashSet<String>) -> bool {
|
||||
if roots.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let mut at = rel;
|
||||
loop {
|
||||
if roots.contains(at) {
|
||||
return true;
|
||||
}
|
||||
match at.rfind('/') {
|
||||
Some(i) => at = &at[..i],
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the mirror copy at `rel` holds something Proton Drive does not, or
|
||||
/// `None` when everything under it is on Drive exactly as it is on disk.
|
||||
///
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -79,18 +79,25 @@ impl Syncer {
|
||||
/// folder's baseline changes, so a resumed walk never meets a baseline
|
||||
/// newer than its listings; it is as old as a long walk's first listings
|
||||
/// would be, and the apply step checks each file again before it acts.
|
||||
///
|
||||
/// With `reuse` false, a complete saved walk is not used: the root state
|
||||
/// owes Drive a walk in full. Returns whether the walk covered all of
|
||||
/// Drive's side, rather than only the folders marked dirty.
|
||||
pub(super) fn walk_remote(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
root: &NodeUid,
|
||||
walk: &mut RemoteWalk<'_>,
|
||||
baseline: &HashMap<String, StoredSyncEntry>,
|
||||
) -> Result<(), PassAbort> {
|
||||
reuse: bool,
|
||||
) -> Result<bool, PassAbort> {
|
||||
let WalkStart {
|
||||
mut todo,
|
||||
mut children,
|
||||
dirty_upto,
|
||||
} = self.start_walk(folder_id, root, walk);
|
||||
} = self.start_walk(folder_id, root, walk, reuse);
|
||||
// Started from the saved picture, the walk lists only what changed.
|
||||
let in_full = children.is_none();
|
||||
// Folders to list again next pass: their listing failed or came back
|
||||
// short this time.
|
||||
let mut again: Vec<String> = Vec::new();
|
||||
@@ -221,7 +228,8 @@ impl Syncer {
|
||||
return Err(PassAbort::Stopped);
|
||||
}
|
||||
self.finish_walk(folder_id, dirty_upto, &again)
|
||||
.map_err(|e| PassAbort::from(format!("save the walk of Drive: {e:?}")))
|
||||
.map_err(|e| PassAbort::from(format!("save the walk of Drive: {e:?}")))?;
|
||||
Ok(in_full)
|
||||
}
|
||||
|
||||
/// Keep a walk that reached its end as the next pass's picture of Drive.
|
||||
@@ -264,6 +272,7 @@ impl Syncer {
|
||||
folder_id: i64,
|
||||
root: &NodeUid,
|
||||
walk: &mut RemoteWalk<'_>,
|
||||
reuse: bool,
|
||||
) -> WalkStart {
|
||||
let root_uid = root.to_string();
|
||||
let saved = match self.store.sync_walk_load(folder_id) {
|
||||
@@ -277,9 +286,17 @@ impl Syncer {
|
||||
&& saved.root_uid == root_uid
|
||||
{
|
||||
let age = now_secs().saturating_sub(saved.started);
|
||||
if saved.complete
|
||||
let fresh = saved.complete
|
||||
&& age < AUDIT_INTERVAL.as_secs() as i64
|
||||
&& self.events_trusted(root)
|
||||
&& self.events_trusted(root);
|
||||
if fresh && !reuse {
|
||||
info!(
|
||||
id = folder_id,
|
||||
"sync: the root state asks for a walk of all of Drive"
|
||||
);
|
||||
}
|
||||
if fresh
|
||||
&& reuse
|
||||
&& let Some(start) = self.walk_dirty(folder_id, &saved, walk)
|
||||
{
|
||||
return start;
|
||||
|
||||
@@ -146,6 +146,15 @@ pub struct Outcome {
|
||||
/// The first step that failed in this pass, so the line that ends a pass
|
||||
/// in `error` says why without a search back through the journal.
|
||||
pub first_error: Option<String>,
|
||||
/// Changes the pass made on disk itself: files downloaded, conflict
|
||||
/// copies kept, folders made, and files and folders removed. Not part of
|
||||
/// the summary, which counts them by kind; a pass that made any does not
|
||||
/// keep its walk for the next one (`local_dirty`).
|
||||
pub local_changes: usize,
|
||||
/// Which sides the pass walked in full, rather than bringing the last
|
||||
/// walk up to date from the dirty set: the disk, and Drive. The root
|
||||
/// state counts a side covered only after a walk in full (`root`).
|
||||
pub walked_in_full: (bool, bool),
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
@@ -162,8 +171,14 @@ impl Outcome {
|
||||
match applied {
|
||||
Applied::Dir(..) => self.created += 1,
|
||||
Applied::Uploaded => self.uploaded += 1,
|
||||
Applied::Downloaded => self.downloaded += 1,
|
||||
Applied::Conflict => self.conflicts += 1,
|
||||
Applied::Downloaded => {
|
||||
self.downloaded += 1;
|
||||
self.local_changes += 1;
|
||||
}
|
||||
Applied::Conflict => {
|
||||
self.conflicts += 1;
|
||||
self.local_changes += 1;
|
||||
}
|
||||
Applied::Vanished | Applied::Adopted => {}
|
||||
}
|
||||
}
|
||||
@@ -292,6 +307,19 @@ impl Pending {
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of effect its intent records (`effect`).
|
||||
pub fn intent(&self) -> &'static str {
|
||||
match self {
|
||||
Pending::CreateDir { .. } => "create-folder",
|
||||
Pending::UploadNew { .. } => "upload",
|
||||
Pending::UploadRevision { .. } => "upload-revision",
|
||||
Pending::Download { .. } => "download",
|
||||
Pending::Adopt { .. } => "adopt",
|
||||
Pending::Conflict { .. } => "conflict",
|
||||
Pending::PushConflict { .. } => "push-conflict",
|
||||
}
|
||||
}
|
||||
|
||||
/// The activity line's detail, which distinguishes ops that share a kind.
|
||||
pub fn detail(&self) -> &'static str {
|
||||
match self {
|
||||
|
||||
+256
-14
@@ -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,42 @@ 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 nothing was left out.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.covered.is_empty()
|
||||
}
|
||||
|
||||
/// 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 +264,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 +397,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 +1127,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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
//! 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 phases say how far the engine can trust what it has seen:
|
||||
//!
|
||||
//! - **Discovering**: no pass over the folder has finished yet.
|
||||
//! - **Following**: passes covered the whole folder, and nothing since says a
|
||||
//! change could have gone unreported. A pass may work from the dirty sets.
|
||||
//! - **Auditing**: something did (a lost watch, an overflowed queue, a gap in
|
||||
//! Drive's event stream, a restart). Only a pass that walks the doubted
|
||||
//! side in full 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.
|
||||
//!
|
||||
//! A doubt is about one side. The disk is followed by the watcher and Drive
|
||||
//! by its event stream, and each can fail on its own: a restart misses what
|
||||
//! happened on disk while the daemon was down, but the event stream resumes
|
||||
//! from its cursor. So the state keeps a doubt for each side ([`Owed`]), and
|
||||
//! a pass walks in full only the side that is owed.
|
||||
//!
|
||||
//! A pass asks [`Roots::owed`] before it walks. The checks a pass made
|
||||
//! before the reducer was acted on (a trusted watch, a fresh event stream,
|
||||
//! the audit intervals) still apply on top: the reducer can make a pass walk
|
||||
//! more, never less.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use tracing::info;
|
||||
|
||||
/// Why a side of a folder is in doubt.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Doubt {
|
||||
/// Nothing has walked this side yet.
|
||||
FirstSync,
|
||||
/// The daemon started: nothing watched the disk while it was down.
|
||||
Restart,
|
||||
/// The filesystem watcher reported an error, or the folder's watch is
|
||||
/// gone.
|
||||
WatchLost,
|
||||
/// The watcher's event queue overflowed.
|
||||
Overflow,
|
||||
/// Drive's event stream lost changes.
|
||||
EventGap,
|
||||
/// The folder only pushed for a while, which drops its picture of Drive.
|
||||
Pushed,
|
||||
}
|
||||
|
||||
impl Doubt {
|
||||
/// Whether this doubt is about the disk, and whether about Drive.
|
||||
fn sides(self) -> (bool, bool) {
|
||||
match self {
|
||||
Doubt::FirstSync => (true, true),
|
||||
Doubt::Restart | Doubt::WatchLost | Doubt::Overflow => (true, false),
|
||||
Doubt::EventGap | Doubt::Pushed => (false, true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a pass owes a folder: the sides it must walk in full, each with the
|
||||
/// first doubt that made it so.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Owed {
|
||||
pub local: Option<Doubt>,
|
||||
pub remote: Option<Doubt>,
|
||||
}
|
||||
|
||||
impl Owed {
|
||||
/// Both sides, for a folder nothing has walked.
|
||||
pub const ALL: Owed = Owed {
|
||||
local: Some(Doubt::FirstSync),
|
||||
remote: Some(Doubt::FirstSync),
|
||||
};
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.local.is_none() && self.remote.is_none()
|
||||
}
|
||||
|
||||
/// Add `doubt` to the sides it is about. The first doubt on a side
|
||||
/// stays: it is the one to report.
|
||||
fn doubt(self, doubt: Doubt) -> Owed {
|
||||
let (local, remote) = doubt.sides();
|
||||
Owed {
|
||||
local: self.local.or(local.then_some(doubt)),
|
||||
remote: self.remote.or(remote.then_some(doubt)),
|
||||
}
|
||||
}
|
||||
|
||||
/// What is left once a pass walked the sides given in full.
|
||||
fn cover(self, local: bool, remote: bool) -> Owed {
|
||||
Owed {
|
||||
local: self.local.filter(|_| !local),
|
||||
remote: self.remote.filter(|_| !remote),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Owed {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match (self.local, self.remote) {
|
||||
(None, None) => f.write_str("nothing"),
|
||||
(Some(l), None) => write!(f, "local: {l:?}"),
|
||||
(None, Some(r)) => write!(f, "remote: {r:?}"),
|
||||
(Some(l), Some(r)) => write!(f, "local: {l:?}, remote: {r:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 Phase {
|
||||
Discovering,
|
||||
Following,
|
||||
Auditing,
|
||||
Suspended(Suspension),
|
||||
Draining,
|
||||
HandedOff,
|
||||
}
|
||||
|
||||
/// A folder's state: its phase, and what a pass owes it. Following owes
|
||||
/// nothing and Auditing owes something; a suspended folder keeps what it is
|
||||
/// owed for when it comes back.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct RootState {
|
||||
pub phase: Phase,
|
||||
pub owed: Owed,
|
||||
}
|
||||
|
||||
impl RootState {
|
||||
/// A folder no pass has walked.
|
||||
pub const NEW: RootState = RootState {
|
||||
phase: Phase::Discovering,
|
||||
owed: Owed::ALL,
|
||||
};
|
||||
|
||||
/// A folder synced before the daemon started: what happened on disk
|
||||
/// meanwhile went unwatched. Drive's event stream resumes from its
|
||||
/// cursor, and reports a gap when it cannot.
|
||||
pub const RESTARTED: RootState = RootState {
|
||||
phase: Phase::Auditing,
|
||||
owed: Owed {
|
||||
local: Some(Doubt::Restart),
|
||||
remote: None,
|
||||
},
|
||||
};
|
||||
|
||||
/// Following once nothing is owed. Otherwise a folder still discovering
|
||||
/// stays so, and any other is audited.
|
||||
fn settled(phase: Phase, owed: Owed) -> RootState {
|
||||
let phase = match phase {
|
||||
_ if owed.is_empty() => Phase::Following,
|
||||
Phase::Discovering => Phase::Discovering,
|
||||
_ => Phase::Auditing,
|
||||
};
|
||||
RootState { phase, owed }
|
||||
}
|
||||
}
|
||||
|
||||
/// Something that happened to a folder, as the reducer takes it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RootInput {
|
||||
/// A pass finished. It walked the disk in full when `local`, and Drive
|
||||
/// when `remote`; otherwise it worked from that side's dirty set.
|
||||
Covered { local: bool, remote: bool },
|
||||
/// A change may have gone unreported.
|
||||
Doubted(Doubt),
|
||||
/// The folder cannot be synced for now.
|
||||
Suspended(Suspension),
|
||||
/// Sync is no longer paused. The watcher and the event stream kept
|
||||
/// running meanwhile, so the folder owes what it owed before. 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 Phase as P;
|
||||
let RootState { phase, owed } = state;
|
||||
let with = |phase| RootState { phase, owed };
|
||||
match (phase, input) {
|
||||
// An on-demand folder is not synced: only going back to a mirror
|
||||
// changes it, and that is a first sync over again.
|
||||
(P::HandedOff, RootInput::Mirrored) => RootState::NEW,
|
||||
(P::HandedOff, _) => state,
|
||||
(P::Draining, RootInput::HandedOff) => with(P::HandedOff),
|
||||
// A switch called off: a mirror again. The push passes dropped the
|
||||
// picture of Drive; the disk stayed watched.
|
||||
(P::Draining, RootInput::Mirrored) => {
|
||||
RootState::settled(P::Auditing, owed.doubt(Doubt::Pushed))
|
||||
}
|
||||
(P::Draining, _) => state,
|
||||
(_, RootInput::HandoffQueued) => with(P::Draining),
|
||||
(_, RootInput::HandedOff) => with(P::HandedOff),
|
||||
// A suspended folder is still watched, and owes what went wrong
|
||||
// meanwhile when it comes back.
|
||||
(P::Suspended(_), RootInput::Doubted(why)) => RootState {
|
||||
phase,
|
||||
owed: owed.doubt(why),
|
||||
},
|
||||
(P::Suspended(_), RootInput::Covered { local, remote }) => {
|
||||
RootState::settled(P::Auditing, owed.cover(local, remote))
|
||||
}
|
||||
(P::Suspended(Suspension::Paused), RootInput::Resumed) => {
|
||||
RootState::settled(P::Auditing, owed)
|
||||
}
|
||||
(P::Suspended(_), RootInput::Suspended(why)) => with(P::Suspended(why)),
|
||||
(P::Suspended(_), _) => state,
|
||||
(_, RootInput::Suspended(why)) => with(P::Suspended(why)),
|
||||
(_, RootInput::Doubted(why)) => RootState::settled(phase, owed.doubt(why)),
|
||||
(_, RootInput::Covered { local, remote }) => {
|
||||
RootState::settled(phase, owed.cover(local, remote))
|
||||
}
|
||||
(_, RootInput::Resumed | RootInput::Mirrored) => state,
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RootState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self.phase {
|
||||
Phase::Discovering => f.write_str("discovering")?,
|
||||
Phase::Following => f.write_str("following")?,
|
||||
Phase::Auditing => f.write_str("auditing")?,
|
||||
Phase::Suspended(why) => write!(f, "suspended ({why:?})")?,
|
||||
Phase::Draining => f.write_str("draining")?,
|
||||
Phase::HandedOff => f.write_str("handed off")?,
|
||||
}
|
||||
if !self.owed.is_empty() && self.phase != Phase::Discovering {
|
||||
write!(f, " ({})", self.owed)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 of the disk, 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::RESTARTED
|
||||
} else {
|
||||
RootState::NEW
|
||||
});
|
||||
}
|
||||
|
||||
/// 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()
|
||||
}
|
||||
|
||||
/// What a pass over `folder` must walk in full. A folder not begun is
|
||||
/// owed everything.
|
||||
pub fn owed(&self, folder: i64) -> Owed {
|
||||
self.state(folder).map_or(Owed::ALL, |state| state.owed)
|
||||
}
|
||||
|
||||
/// 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 Phase as P;
|
||||
use RootInput as I;
|
||||
|
||||
fn run(from: RootState, inputs: &[RootInput]) -> RootState {
|
||||
inputs.iter().fold(from, |state, input| step(state, *input))
|
||||
}
|
||||
|
||||
const BOTH: RootInput = I::Covered {
|
||||
local: true,
|
||||
remote: true,
|
||||
};
|
||||
const NEITHER: RootInput = I::Covered {
|
||||
local: false,
|
||||
remote: false,
|
||||
};
|
||||
const LOCAL: RootInput = I::Covered {
|
||||
local: true,
|
||||
remote: false,
|
||||
};
|
||||
const REMOTE: RootInput = I::Covered {
|
||||
local: false,
|
||||
remote: true,
|
||||
};
|
||||
const FOLLOWING: RootState = RootState {
|
||||
phase: P::Following,
|
||||
owed: Owed {
|
||||
local: None,
|
||||
remote: None,
|
||||
},
|
||||
};
|
||||
|
||||
fn auditing(local: Option<Doubt>, remote: Option<Doubt>) -> RootState {
|
||||
RootState {
|
||||
phase: P::Auditing,
|
||||
owed: Owed { local, remote },
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_first_sync_follows_once_a_pass_walks_both_sides() {
|
||||
assert_eq!(run(RootState::NEW, &[BOTH]), FOLLOWING);
|
||||
let half = run(RootState::NEW, &[LOCAL]);
|
||||
assert_eq!(half.phase, P::Discovering);
|
||||
assert_eq!(half.owed.remote, Some(Doubt::FirstSync));
|
||||
assert_eq!(step(half, REMOTE), FOLLOWING);
|
||||
// A doubt during discovery changes nothing: the pass walks it all.
|
||||
assert_eq!(
|
||||
run(RootState::NEW, &[I::Doubted(Doubt::Overflow)]),
|
||||
RootState::NEW
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pass_from_the_dirty_sets_keeps_a_followed_folder_following() {
|
||||
assert_eq!(run(FOLLOWING, &[NEITHER, NEITHER]), FOLLOWING);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_doubt_is_owed_on_its_side_until_a_pass_walks_that_side() {
|
||||
let audit = run(
|
||||
FOLLOWING,
|
||||
&[
|
||||
I::Doubted(Doubt::WatchLost),
|
||||
I::Doubted(Doubt::Overflow),
|
||||
I::Doubted(Doubt::EventGap),
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
audit,
|
||||
auditing(Some(Doubt::WatchLost), Some(Doubt::EventGap)),
|
||||
"the first doubt on each side stays"
|
||||
);
|
||||
let local_done = step(audit, LOCAL);
|
||||
assert_eq!(local_done, auditing(None, Some(Doubt::EventGap)));
|
||||
assert_eq!(step(local_done, NEITHER), local_done);
|
||||
assert_eq!(step(local_done, REMOTE), FOLLOWING);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restart_owes_the_disk_and_not_drive() {
|
||||
assert_eq!(RootState::RESTARTED, auditing(Some(Doubt::Restart), None));
|
||||
assert_eq!(step(RootState::RESTARTED, LOCAL), FOLLOWING);
|
||||
assert_eq!(step(RootState::RESTARTED, REMOTE), RootState::RESTARTED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_suspension_keeps_what_is_owed_and_what_goes_wrong_meanwhile() {
|
||||
let paused = step(FOLLOWING, I::Suspended(Suspension::Paused));
|
||||
assert_eq!(paused.phase, P::Suspended(Suspension::Paused));
|
||||
assert_eq!(
|
||||
step(paused, I::Resumed),
|
||||
FOLLOWING,
|
||||
"nothing went unwatched"
|
||||
);
|
||||
let overflowed = step(paused, I::Doubted(Doubt::Overflow));
|
||||
assert_eq!(overflowed.phase, P::Suspended(Suspension::Paused));
|
||||
assert_eq!(
|
||||
step(overflowed, I::Resumed),
|
||||
auditing(Some(Doubt::Overflow), None)
|
||||
);
|
||||
let missing = step(FOLLOWING, I::Suspended(Suspension::RootMissing));
|
||||
assert_eq!(step(missing, I::Resumed), missing);
|
||||
assert_eq!(step(missing, NEITHER), FOLLOWING);
|
||||
let lost = run(
|
||||
FOLLOWING,
|
||||
&[
|
||||
I::Suspended(Suspension::RootMissing),
|
||||
I::Doubted(Doubt::WatchLost),
|
||||
],
|
||||
);
|
||||
assert_eq!(step(lost, LOCAL), FOLLOWING);
|
||||
// Paused during discovery: still owed everything after.
|
||||
let paused_new = run(
|
||||
RootState::NEW,
|
||||
&[I::Suspended(Suspension::Paused), I::Resumed],
|
||||
);
|
||||
assert_eq!(paused_new.owed, Owed::ALL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_handoff_drains_then_stays_until_the_folder_is_a_mirror_again() {
|
||||
let draining = step(FOLLOWING, I::HandoffQueued);
|
||||
assert_eq!(draining.phase, P::Draining);
|
||||
assert_eq!(step(draining, BOTH), draining);
|
||||
let off = step(draining, I::HandedOff);
|
||||
assert_eq!(off.phase, P::HandedOff);
|
||||
assert_eq!(step(off, BOTH), off);
|
||||
assert_eq!(step(off, I::Mirrored), RootState::NEW);
|
||||
assert_eq!(
|
||||
step(draining, I::Mirrored),
|
||||
auditing(None, Some(Doubt::Pushed)),
|
||||
"a switch called off walks Drive again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roots_begin_once_and_feed_every_folder() {
|
||||
let roots = Roots::default();
|
||||
roots.input(1, BOTH);
|
||||
assert_eq!(roots.state(1), None, "not begun");
|
||||
assert_eq!(roots.owed(1), Owed::ALL);
|
||||
roots.begin(1, false);
|
||||
roots.begin(2, true);
|
||||
assert_eq!(roots.state(2), Some(RootState::RESTARTED));
|
||||
roots.input_all(BOTH);
|
||||
roots.begin(1, false);
|
||||
assert_eq!(roots.state(1), Some(FOLLOWING), "begun only once");
|
||||
roots.input_all(I::Doubted(Doubt::EventGap));
|
||||
assert_eq!(
|
||||
roots.owed(2),
|
||||
Owed {
|
||||
local: None,
|
||||
remote: Some(Doubt::EventGap)
|
||||
}
|
||||
);
|
||||
roots.forget(2);
|
||||
assert_eq!(roots.state(2), None);
|
||||
}
|
||||
}
|
||||
@@ -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, StoredIntent, StoredSyncEntry, StoredSyncFolder,
|
||||
};
|
||||
|
||||
/// The sync tables, as the mirror engine uses them.
|
||||
pub trait SyncStore: Send + Sync {
|
||||
@@ -70,6 +73,50 @@ 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<()>;
|
||||
|
||||
// The intent of each effect sent (`effect`).
|
||||
|
||||
/// Record that an effect is about to be sent; returns the intent and the
|
||||
/// state it was in before, if any.
|
||||
fn sync_intent_issue(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel_path: &str,
|
||||
kind: &str,
|
||||
now: i64,
|
||||
) -> Result<(StoredIntent, Option<String>)>;
|
||||
/// Drop a settled intent.
|
||||
fn sync_intent_settle(&self, id: i64) -> Result<()>;
|
||||
/// Move an intent to `state`, with the error that put it there.
|
||||
fn sync_intent_set(&self, id: i64, state: &str, error: Option<&str>) -> Result<()>;
|
||||
/// Note that upload `kind` of `rel_path` streamed bytes with SHA-1 `sha1`
|
||||
/// and heard no success back.
|
||||
fn sync_intent_sent(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel_path: &str,
|
||||
kind: &str,
|
||||
sha1: &str,
|
||||
) -> Result<()>;
|
||||
/// Every intent not settled; only `folder_id`'s when given.
|
||||
fn sync_intents(&self, folder_id: Option<i64>) -> Result<Vec<StoredIntent>>;
|
||||
/// Move every intent in state `from` to `to`.
|
||||
fn sync_intents_move(&self, from: &str, to: &str) -> Result<usize>;
|
||||
/// Settle the intents of `folder_id` in one of `states` last sent before
|
||||
/// `before`.
|
||||
fn sync_intents_settle_before(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
states: &[&str],
|
||||
before: i64,
|
||||
) -> Result<Vec<StoredIntent>>;
|
||||
}
|
||||
|
||||
impl SyncStore for Db {
|
||||
@@ -138,6 +185,50 @@ 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)
|
||||
}
|
||||
fn sync_intent_issue(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel_path: &str,
|
||||
kind: &str,
|
||||
now: i64,
|
||||
) -> Result<(StoredIntent, Option<String>)> {
|
||||
Db::sync_intent_issue(self, folder_id, rel_path, kind, now)
|
||||
}
|
||||
fn sync_intent_settle(&self, id: i64) -> Result<()> {
|
||||
Db::sync_intent_settle(self, id)
|
||||
}
|
||||
fn sync_intent_set(&self, id: i64, state: &str, error: Option<&str>) -> Result<()> {
|
||||
Db::sync_intent_set(self, id, state, error)
|
||||
}
|
||||
fn sync_intent_sent(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel_path: &str,
|
||||
kind: &str,
|
||||
sha1: &str,
|
||||
) -> Result<()> {
|
||||
Db::sync_intent_sent(self, folder_id, rel_path, kind, sha1)
|
||||
}
|
||||
fn sync_intents(&self, folder_id: Option<i64>) -> Result<Vec<StoredIntent>> {
|
||||
Db::sync_intents(self, folder_id)
|
||||
}
|
||||
fn sync_intents_move(&self, from: &str, to: &str) -> Result<usize> {
|
||||
Db::sync_intents_move(self, from, to)
|
||||
}
|
||||
fn sync_intents_settle_before(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
states: &[&str],
|
||||
before: i64,
|
||||
) -> Result<Vec<StoredIntent>> {
|
||||
Db::sync_intents_settle_before(self, folder_id, states, before)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -200,5 +291,20 @@ mod tests {
|
||||
);
|
||||
store.sync_remote_dirty_consume(id, dirty[0].0).unwrap();
|
||||
assert!(store.sync_remote_dirty(id).unwrap().is_empty());
|
||||
|
||||
let (intent, _) = store.sync_intent_issue(id, "a.txt", "upload", 1).unwrap();
|
||||
store.sync_intent_set(intent.id, "retry", None).unwrap();
|
||||
assert_eq!(store.sync_intents(Some(id)).unwrap()[0].state, "retry");
|
||||
assert_eq!(store.sync_intents_move("retry", "blocked").unwrap(), 1);
|
||||
assert_eq!(
|
||||
store
|
||||
.sync_intents_settle_before(id, &["blocked"], 2)
|
||||
.unwrap()
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
let (intent, _) = store.sync_intent_issue(id, "a.txt", "upload", 3).unwrap();
|
||||
store.sync_intent_settle(intent.id).unwrap();
|
||||
assert!(store.sync_intents(None).unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -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,33 @@ 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,
|
||||
/// Paths on disk taken from the last pass's walk, which a trusted claim
|
||||
/// of the local dirty set keeps up to date, instead of walked again.
|
||||
LocalReused,
|
||||
/// Effects sent again that a stopped daemon had sent and not heard back
|
||||
/// from: each may have happened already (`effect`).
|
||||
UnsureResent,
|
||||
/// Effects sent again after they failed.
|
||||
Retried,
|
||||
/// Unsettled effects of earlier passes that this pass looked at and no
|
||||
/// longer sent.
|
||||
Superseded,
|
||||
}
|
||||
|
||||
impl Count {
|
||||
const ALL: [Count; 9] = [
|
||||
const ALL: [Count; 17] = [
|
||||
Count::LocalEntries,
|
||||
Count::RemoteFolders,
|
||||
Count::Nodes,
|
||||
@@ -140,6 +169,14 @@ impl Count {
|
||||
Count::Resumed,
|
||||
Count::Reused,
|
||||
Count::Dirty,
|
||||
Count::UnprovenDeletions,
|
||||
Count::LocalDirty,
|
||||
Count::LocalUntrusted,
|
||||
Count::MissedLocal,
|
||||
Count::LocalReused,
|
||||
Count::UnsureResent,
|
||||
Count::Retried,
|
||||
Count::Superseded,
|
||||
];
|
||||
|
||||
fn name(self) -> &'static str {
|
||||
@@ -153,6 +190,14 @@ 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",
|
||||
Count::LocalReused => "local reused",
|
||||
Count::UnsureResent => "unsure resent",
|
||||
Count::Retried => "retried",
|
||||
Count::Superseded => "superseded",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "pdfs-vfs"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
description = "The mounted-files service of the Proton Drive Linux client, without a kernel adapter"
|
||||
|
||||
[features]
|
||||
# Helpers that let other crates' tests build and inspect a tree.
|
||||
test-support = []
|
||||
|
||||
[dependencies]
|
||||
pdfs-core.workspace = true
|
||||
pdfs-drive.workspace = true
|
||||
pdfs-store.workspace = true
|
||||
proton-drive-rs.workspace = true
|
||||
libc.workspace = true
|
||||
parking_lot.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
@@ -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:#?}");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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 != ".")
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//! Inode numbers the tree reserves, and the volume of nodes that only exist
|
||||
//! here.
|
||||
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
|
||||
/// The root inode of every session. Each session calls its own root 1.
|
||||
pub const ROOT_INO: u64 = 1;
|
||||
|
||||
/// Parent inode for a persisted node whose parent row is missing from the
|
||||
/// database. No folder carries this inode, so such a node is listed by nobody
|
||||
/// and stays inert until a live enumeration re-parents it.
|
||||
pub const ORPHAN_INO: u64 = 0;
|
||||
|
||||
/// The volume id of the folders this client makes up, such as "Shared with
|
||||
/// me". No such volume exists on Drive.
|
||||
pub const VIRTUAL_VOLUME: &str = "virtual";
|
||||
|
||||
/// Whether `uid` names a folder this client made up rather than a Drive node.
|
||||
pub fn is_virtual_uid(uid: &NodeUid) -> bool {
|
||||
uid.volume_id.as_str() == VIRTUAL_VOLUME
|
||||
}
|
||||
|
||||
/// Whether this node exists only on this machine, so far. Such a uid is
|
||||
/// meaningless to the API and must never be sent to it.
|
||||
pub fn is_local_uid(uid: &NodeUid) -> bool {
|
||||
uid.volume_id.as_str() == pdfs_store::db::LOCAL_VOLUME
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
//! The mounted-files service: what a file open through a mount is, and what
|
||||
//! happens to its bytes between `open` and `close`.
|
||||
//!
|
||||
//! Step 5 of the 4.0 plan in `docs/ARCHITECTURE.md` moves the mount's
|
||||
//! state here, slice by slice, so that it can be built and tested without a
|
||||
//! kernel. Nothing in this crate knows about `fuser` or errno: the FUSE
|
||||
//! adapter in `pdfs-fuse` maps the typed errors at the boundary.
|
||||
//!
|
||||
//! So far it holds the tree ([`tree`]): the nodes a mount shows, their
|
||||
//! stable inode numbers, and the per-mount roots; and the open files
|
||||
//! ([`open`]): the scratch file a handle writes into, which bytes of it are
|
||||
//! authored, the released write that waits for its upload, and directory
|
||||
//! handles; what the mount accepted but has not sent to Drive yet
|
||||
//! ([`writes`]); the POSIX rules on names and on what a rename may replace
|
||||
//! ([`names`]); which nodes a folder lists ([`nodes`]); and two services
|
||||
//! behind host ports: the open files from open to close ([`files`]), and
|
||||
//! create, mkdir, unlink, rmdir and rename ([`namespace`]).
|
||||
//!
|
||||
//! 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;
|
||||
pub mod writes;
|
||||
@@ -0,0 +1,110 @@
|
||||
//! The POSIX rules on names and on what a rename may replace.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
/// Why a pathname component cannot name a node.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum NameError {
|
||||
/// Longer than `NAME_MAX` (255 bytes).
|
||||
TooLong,
|
||||
/// Empty, `.` or `..`.
|
||||
Reserved,
|
||||
/// Not UTF-8, which Drive requires.
|
||||
NotUtf8,
|
||||
}
|
||||
|
||||
/// Why a rename may not replace its destination.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ReplaceError {
|
||||
/// A file would replace a directory.
|
||||
IsDirectory,
|
||||
/// A directory would replace a file.
|
||||
NotDirectory,
|
||||
/// The directory to replace is not empty.
|
||||
NotEmpty,
|
||||
}
|
||||
|
||||
/// Convert one kernel pathname component into the UTF-8 name accepted by Drive.
|
||||
/// Linux filesystems conventionally cap a component at `NAME_MAX` (255 bytes),
|
||||
/// but the FUSE kernel path can pass a longer component through to userspace.
|
||||
pub fn component(name: &OsStr) -> Result<String, NameError> {
|
||||
let bytes = name.as_bytes();
|
||||
if bytes.len() > 255 {
|
||||
return Err(NameError::TooLong);
|
||||
}
|
||||
if bytes.is_empty() || bytes == b"." || bytes == b".." {
|
||||
return Err(NameError::Reserved);
|
||||
}
|
||||
name.to_str().map(str::to_owned).ok_or(NameError::NotUtf8)
|
||||
}
|
||||
|
||||
/// Whether a `rename` may replace an existing destination, per POSIX.
|
||||
///
|
||||
/// Split out from the handler because it is the part that is pure and the part
|
||||
/// that is dangerous: every `Err` here is a refusal that happens *before*
|
||||
/// anything is trashed, and getting one wrong turns a refusal into the
|
||||
/// destruction of the destination (`docs/BUGS.md` B13).
|
||||
///
|
||||
/// `dst_empty` is only meaningful when `dst_dir`; pass `true` otherwise.
|
||||
pub fn check_replaceable(
|
||||
src_dir: bool,
|
||||
dst_dir: bool,
|
||||
dst_empty: bool,
|
||||
) -> Result<(), ReplaceError> {
|
||||
match (src_dir, dst_dir) {
|
||||
// A non-directory may not replace a directory, or vice versa.
|
||||
(false, true) => Err(ReplaceError::IsDirectory),
|
||||
(true, false) => Err(ReplaceError::NotDirectory),
|
||||
// Proton trashes a folder with its whole subtree, so replacing a
|
||||
// non-empty one would silently take its contents with it. POSIX says
|
||||
// ENOTEMPTY, which is also the safe answer.
|
||||
(true, true) if !dst_empty => Err(ReplaceError::NotEmpty),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod replace_tests {
|
||||
use super::{ReplaceError, check_replaceable};
|
||||
|
||||
/// The case that motivated all of this: rsync renaming its temp file over
|
||||
/// the real one. Two plain files, and it has to be allowed — refusing is
|
||||
/// what made every rsync transfer fail at the last step (`docs/BUGS.md` B13).
|
||||
#[test]
|
||||
fn a_file_may_replace_a_file() {
|
||||
assert!(check_replaceable(false, false, true).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_directory_may_be_replaced_by_a_directory() {
|
||||
assert!(check_replaceable(true, true, true).is_ok());
|
||||
}
|
||||
|
||||
/// Proton trashes a folder with its whole subtree, so allowing this would
|
||||
/// discard every file under the destination without ever naming them.
|
||||
#[test]
|
||||
fn a_non_empty_directory_is_never_replaced() {
|
||||
let e = check_replaceable(true, true, false).expect_err("must refuse");
|
||||
assert_eq!(e, ReplaceError::NotEmpty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_two_ends_must_agree_on_being_a_directory() {
|
||||
assert_eq!(
|
||||
check_replaceable(false, true, true).expect_err("a file may not replace a directory"),
|
||||
ReplaceError::IsDirectory
|
||||
);
|
||||
assert_eq!(
|
||||
check_replaceable(true, false, true).expect_err("a directory may not replace a file"),
|
||||
ReplaceError::NotDirectory
|
||||
);
|
||||
}
|
||||
|
||||
/// `dst_empty` describes a directory; it must not leak into the file case,
|
||||
/// where callers pass `true` by convention.
|
||||
#[test]
|
||||
fn emptiness_is_ignored_when_the_destination_is_a_file() {
|
||||
assert!(check_replaceable(false, false, false).is_ok());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,193 @@
|
||||
//! Rules about the nodes a mount lists that need neither the kernel nor Drive:
|
||||
//! which of them a folder shows, how queued changes lie over a listing, and
|
||||
//! what a node made here looks like before Drive has seen it.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use pdfs_core::timestamp::now_secs;
|
||||
use pdfs_drive::{media_type_for, remote_name_is_safe};
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use proton_drive_rs::{Node, NodeKind};
|
||||
use tracing::warn;
|
||||
|
||||
/// Fabricate the node the server would have returned, for a `create`/`mkdir`
|
||||
/// that could not reach it. Everything the kernel asks about a fresh node —
|
||||
/// name, kind, size, times — is knowable locally; the uid is the only invention,
|
||||
/// and the drain replaces it with the real one.
|
||||
pub fn local_node(uid: NodeUid, parent_uid: NodeUid, name: String, is_dir: bool) -> Node {
|
||||
let now = now_secs();
|
||||
Node {
|
||||
uid,
|
||||
parent_uid: Some(parent_uid),
|
||||
kind: if is_dir {
|
||||
NodeKind::Folder
|
||||
} else {
|
||||
NodeKind::File {
|
||||
media_type: media_type_for(&name).to_string(),
|
||||
total_size_on_storage: 0,
|
||||
// No revision has been sealed: nothing has been uploaded yet.
|
||||
active_revision_state: None,
|
||||
active_revision_id: None,
|
||||
content_sha1: None,
|
||||
claimed_size: Some(0),
|
||||
claimed_modification_time: None,
|
||||
}
|
||||
},
|
||||
name,
|
||||
creation_time: now,
|
||||
modification_time: now,
|
||||
trashed: false,
|
||||
is_shared: false,
|
||||
is_shared_publicly: false,
|
||||
signature_email: None,
|
||||
membership: None,
|
||||
// A locally fabricated node is on the main volume, never a photo/album.
|
||||
photo: None,
|
||||
album: None,
|
||||
// Nothing signed it: it has never been near the crypto layer.
|
||||
verification: Default::default(),
|
||||
direct_role: None,
|
||||
share_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `node` is a file Drive lists without an active revision, as it does
|
||||
/// one whose create has not been committed.
|
||||
pub fn is_unrevised(node: &Node) -> bool {
|
||||
matches!(
|
||||
node.kind,
|
||||
NodeKind::File {
|
||||
active_revision_id: None,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/// The plaintext size, in bytes, that a node reports.
|
||||
/// Overwrite each file node's `claimed_size` with the optimistic size of its
|
||||
/// queued write, where it has one. Folders and nodes with nothing queued are
|
||||
/// left alone. See [`Core::stamp_pending_sizes`] for why this exists.
|
||||
pub fn apply_pending_sizes(nodes: &mut [Node], sizes: &HashMap<NodeUid, u64>) {
|
||||
for node in nodes {
|
||||
if let Some(&len) = sizes.get(&node.uid)
|
||||
&& let NodeKind::File { claimed_size, .. } = &mut node.kind
|
||||
{
|
||||
*claimed_size = Some(len as i64);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn node_visible(node: &Node, folder_uid: &NodeUid, hidden: &HashSet<NodeUid>) -> bool {
|
||||
if !remote_name_is_safe(&node.name) {
|
||||
warn!(uid = %node.uid, "a remote name cannot be a local file name; leaving it out");
|
||||
return false;
|
||||
}
|
||||
!node.trashed && node.uid != *folder_uid && !hidden.contains(&node.uid)
|
||||
}
|
||||
|
||||
/// Lay what is queued for a folder over Drive's listing of it, from
|
||||
/// `Db::queued_children`: a node a queued rename moved away is dropped, and a
|
||||
/// node a queued create, mkdir or rename put there is listed as the DB has it.
|
||||
///
|
||||
/// That node holds its name here: a create Drive already has but whose answer
|
||||
/// is still on its way, or which the drain is still reading back, is listed by
|
||||
/// Drive under its new uid and by the queue under its stand-in. Both were
|
||||
/// listed, and a 128-file folder listed 129 (`docs/BUGS.md` B164).
|
||||
pub fn overlay_queued(nodes: &mut Vec<Node>, queued: Vec<Node>, gone: &HashSet<String>) {
|
||||
let here: HashSet<String> = queued.iter().map(|node| node.uid.to_string()).collect();
|
||||
let names: HashSet<&str> = queued.iter().map(|node| node.name.as_str()).collect();
|
||||
nodes.retain(|node| {
|
||||
let uid = node.uid.to_string();
|
||||
!gone.contains(&uid) && !here.contains(&uid) && !names.contains(node.name.as_str())
|
||||
});
|
||||
nodes.extend(queued);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod pending_size_tests {
|
||||
use super::{Node, NodeKind, NodeUid, apply_pending_sizes};
|
||||
use pdfs_drive::node_size;
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn uid(link: &str) -> NodeUid {
|
||||
NodeUid::new(VolumeId::from("vol"), LinkId::from(link))
|
||||
}
|
||||
|
||||
fn file(link: &str, claimed: i64) -> Node {
|
||||
Node {
|
||||
uid: uid(link),
|
||||
parent_uid: Some(uid("parent")),
|
||||
kind: NodeKind::File {
|
||||
media_type: "text/plain".into(),
|
||||
total_size_on_storage: 0,
|
||||
active_revision_state: None,
|
||||
active_revision_id: None,
|
||||
content_sha1: None,
|
||||
claimed_size: Some(claimed),
|
||||
claimed_modification_time: None,
|
||||
},
|
||||
name: link.into(),
|
||||
creation_time: 100,
|
||||
modification_time: 100,
|
||||
trashed: false,
|
||||
is_shared: false,
|
||||
is_shared_publicly: false,
|
||||
signature_email: None,
|
||||
membership: None,
|
||||
photo: None,
|
||||
album: None,
|
||||
verification: Default::default(),
|
||||
direct_role: None,
|
||||
share_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn folder(link: &str) -> Node {
|
||||
Node {
|
||||
kind: NodeKind::Folder,
|
||||
..file(link, 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// B11: a re-enumeration mid-write must not revert the size to the
|
||||
/// server's. A file that stats as 0 gets no `read` from the kernel at all,
|
||||
/// so the staged blob is never served and the file reads as empty.
|
||||
#[test]
|
||||
fn a_queued_write_keeps_its_optimistic_size_through_a_re_enumeration() {
|
||||
let mut nodes = vec![file("queued", 0), file("settled", 4096)];
|
||||
let sizes = HashMap::from([(uid("queued"), 3)]);
|
||||
|
||||
apply_pending_sizes(&mut nodes, &sizes);
|
||||
|
||||
assert_eq!(
|
||||
node_size(&nodes[0]),
|
||||
3,
|
||||
"the remote's pre-write size must not win over the queued write's"
|
||||
);
|
||||
assert_eq!(
|
||||
node_size(&nodes[1]),
|
||||
4096,
|
||||
"a file with nothing queued keeps the size the server reported"
|
||||
);
|
||||
}
|
||||
|
||||
/// The map is keyed by uid and says nothing about kind; a folder that
|
||||
/// somehow collides must not grow a `claimed_size`.
|
||||
#[test]
|
||||
fn folders_are_left_alone() {
|
||||
let mut nodes = vec![folder("dir")];
|
||||
apply_pending_sizes(&mut nodes, &HashMap::from([(uid("dir"), 999)]));
|
||||
assert!(matches!(nodes[0].kind, NodeKind::Folder));
|
||||
assert_eq!(node_size(&nodes[0]), 0);
|
||||
}
|
||||
|
||||
/// The common case: nothing queued, nothing touched.
|
||||
#[test]
|
||||
fn an_empty_pending_map_changes_nothing() {
|
||||
let mut nodes = vec![file("a", 10), file("b", 20)];
|
||||
apply_pending_sizes(&mut nodes, &HashMap::new());
|
||||
assert_eq!(node_size(&nodes[0]), 10);
|
||||
assert_eq!(node_size(&nodes[1]), 20);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,268 @@
|
||||
//! What the mount accepted and has not yet sent to Drive (`WriteState`).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
|
||||
use pdfs_store::cache::Baseline;
|
||||
|
||||
use crate::ids::is_local_uid;
|
||||
use crate::open::PendingRevision;
|
||||
|
||||
/// The write-back's state: writes accepted from the kernel and not yet sent,
|
||||
/// nodes removed here that a stale listing may still return, and the changes
|
||||
/// this daemon made that Drive's event feed will echo back.
|
||||
///
|
||||
/// The drain, the queue and recovery own it. Everything else, the read path,
|
||||
/// listings, the pin keeper and the event feed, asks through the methods
|
||||
/// below instead of taking its locks.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct WriteState {
|
||||
/// Writes accepted from the kernel but not yet uploaded, keyed by node.
|
||||
/// The in-memory face of the `pending_op` table, from
|
||||
/// which it is rebuilt on mount.
|
||||
///
|
||||
/// Two things read it: [`Core::read_range`], because until the op drains the
|
||||
/// staged blob *is* the file's content and the remote still holds the old
|
||||
/// revision; and the drain worker, which performs the uploads.
|
||||
pub pending: Arc<Mutex<HashMap<NodeUid, PendingRevision>>>,
|
||||
/// Nodes removed through this daemon which a briefly stale remote listing
|
||||
/// may still return. Uids are not reused; an explicit restore clears one.
|
||||
hidden: Arc<Mutex<HashSet<NodeUid>>>,
|
||||
/// Nodes this daemon changed on the remote itself, and how many echoes of
|
||||
/// those changes the event feed still owes us.
|
||||
///
|
||||
/// The feed replays our own writes back at us seconds later, and a
|
||||
/// `NodeUpdated` carries no revision id — nothing in it distinguishes "another
|
||||
/// device changed this file" from "you changed this file". Treating the echo
|
||||
/// as foreign is not free: it evicts the content blob we just uploaded, so the
|
||||
/// next read re-downloads a revision the API may not be serving yet. That is
|
||||
/// how a SQLite database written on the mount came back `malformed`, and how a
|
||||
/// mount doing bulk uploads spent its time re-fetching its own bytes.
|
||||
///
|
||||
/// So the first event for a node we changed ourselves, within
|
||||
/// [`SELF_CHANGE_TTL_MS`], is consumed rather than applied: the tree already
|
||||
/// holds what that event describes, because [`Core::refresh_after_upload`] put
|
||||
/// it there. Anything beyond that applies normally, which bounds the staleness
|
||||
/// a genuine remote change can suffer to one event.
|
||||
///
|
||||
/// Shared across forks like `pending`: the drain that records the change and
|
||||
/// the event task that consumes the echo are both per-daemon.
|
||||
self_changes: Arc<Mutex<HashMap<NodeUid, SelfChange>>>,
|
||||
}
|
||||
|
||||
impl WriteState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
pending: Arc::new(Mutex::new(HashMap::new())),
|
||||
hidden: Arc::new(Mutex::new(HashSet::new())),
|
||||
self_changes: Arc::new(Mutex::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The write queued for `uid`, if any: its staged blob is the file's
|
||||
/// content until the drain sends it.
|
||||
pub fn queued(&self, uid: &NodeUid) -> Option<PendingRevision> {
|
||||
self.pending.lock().get(uid).cloned()
|
||||
}
|
||||
|
||||
/// The remote revision a write to `uid` was made against, for the
|
||||
/// conflict check: the queued write's own base while one is queued, and
|
||||
/// otherwise the base the handle started from. `None` for a node that has
|
||||
/// never existed remotely: there is no revision to conflict with until its
|
||||
/// create drains.
|
||||
pub fn baseline(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
base_mtime: i64,
|
||||
base_size: u64,
|
||||
base_revision_id: Option<String>,
|
||||
) -> Option<Baseline> {
|
||||
if is_local_uid(uid) {
|
||||
return None;
|
||||
}
|
||||
match self.pending.lock().get(uid) {
|
||||
Some(p) => p.meta.based_on.clone(),
|
||||
None => Some(Baseline {
|
||||
mtime: base_mtime,
|
||||
size: base_size,
|
||||
hash: None,
|
||||
revision_id: base_revision_id,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a write for `uid` is queued and not yet sent. A remote change
|
||||
/// to such a node is not applied over it.
|
||||
pub fn is_queued(&self, uid: &NodeUid) -> bool {
|
||||
self.pending.lock().contains_key(uid)
|
||||
}
|
||||
|
||||
/// The size the queued write for `uid` gives the file, if one is queued.
|
||||
pub fn queued_len(&self, uid: &NodeUid) -> Option<u64> {
|
||||
self.pending.lock().get(uid).map(|queued| queued.meta.len)
|
||||
}
|
||||
|
||||
/// The size each queued write gives its file. Empty when nothing is
|
||||
/// queued.
|
||||
pub fn queued_sizes(&self) -> HashMap<NodeUid, u64> {
|
||||
self.pending
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|(uid, queued)| (uid.clone(), queued.meta.len))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The nodes removed here that a listing must leave out, even if Drive
|
||||
/// still returns them.
|
||||
pub fn hidden(&self) -> HashSet<NodeUid> {
|
||||
self.hidden.lock().clone()
|
||||
}
|
||||
|
||||
/// Leave `uid` out of listings from now on: it was removed here.
|
||||
pub fn hide(&self, uid: &NodeUid) {
|
||||
self.hidden.lock().insert(uid.clone());
|
||||
}
|
||||
|
||||
/// List `uid` again: it was restored or put back.
|
||||
pub fn unhide(&self, uid: &NodeUid) {
|
||||
self.hidden.lock().remove(uid);
|
||||
}
|
||||
|
||||
/// Record that this daemon just changed `uid` on Drive, so the event
|
||||
/// feed's echo of the change is recognised (see [`echoes`]).
|
||||
pub fn note_echo(&self, uid: &NodeUid, now_ms: i64) {
|
||||
note_self_change(&mut self.self_changes.lock(), uid, now_ms);
|
||||
}
|
||||
|
||||
/// Claim one outstanding echo for `uid`: whether the event being applied
|
||||
/// is one this daemon caused.
|
||||
pub fn take_echo(&self, uid: &NodeUid, now_ms: i64) -> bool {
|
||||
take_self_change(&mut self.self_changes.lock(), uid, now_ms)
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a change this daemon made stays recognisable as its own. Generous
|
||||
/// against a feed that can lag, but finite: past it, an event for the node is
|
||||
/// applied like any other. See [`writes::WriteState`].
|
||||
pub(crate) const SELF_CHANGE_TTL_MS: i64 = 120_000;
|
||||
|
||||
/// A remote change this daemon made, awaiting its echo from the event feed.
|
||||
pub(crate) struct SelfChange {
|
||||
/// When we made it, in the same epoch millis as [`now_millis`].
|
||||
at_ms: i64,
|
||||
/// Echoes not yet seen. More than one because a single file can be created
|
||||
/// and then have a revision uploaded, and the feed reports both.
|
||||
echoes: u32,
|
||||
}
|
||||
|
||||
/// Record one remote change this daemon made. Split from [`Core`] so the
|
||||
/// expiry and echo-counting rules can be tested against a clock the test owns.
|
||||
pub(crate) fn note_self_change(
|
||||
changes: &mut HashMap<NodeUid, SelfChange>,
|
||||
uid: &NodeUid,
|
||||
now_ms: i64,
|
||||
) {
|
||||
// Echoes that never arrived — a node trashed before its event came round, a
|
||||
// feed that skipped it — would otherwise accumulate for the life of the
|
||||
// daemon. Pruning on write keeps the map the size of the recent queue.
|
||||
changes.retain(|_, c| now_ms - c.at_ms < SELF_CHANGE_TTL_MS);
|
||||
let change = changes.entry(uid.clone()).or_insert(SelfChange {
|
||||
at_ms: now_ms,
|
||||
echoes: 0,
|
||||
});
|
||||
change.at_ms = now_ms;
|
||||
change.echoes += 1;
|
||||
}
|
||||
|
||||
/// Claim one echo, per [`Core::take_self_change`].
|
||||
pub(crate) fn take_self_change(
|
||||
changes: &mut HashMap<NodeUid, SelfChange>,
|
||||
uid: &NodeUid,
|
||||
now_ms: i64,
|
||||
) -> bool {
|
||||
let Some(change) = changes.get_mut(uid) else {
|
||||
return false;
|
||||
};
|
||||
// Too old to attribute: the feed is far enough behind that this is as likely
|
||||
// to be someone else's change as ours, and guessing wrong here costs the user
|
||||
// a stale file.
|
||||
if now_ms - change.at_ms >= SELF_CHANGE_TTL_MS {
|
||||
changes.remove(uid);
|
||||
return false;
|
||||
}
|
||||
change.echoes -= 1;
|
||||
if change.echoes == 0 {
|
||||
changes.remove(uid);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
|
||||
|
||||
/// An event feed carries no revision id, so the only thing that tells a
|
||||
/// remote change apart from the echo of one this daemon just made is this
|
||||
/// bookkeeping. Getting it wrong is expensive in both directions: too eager
|
||||
/// and we evict the bytes we uploaded and re-download them from an API that
|
||||
/// may still be serving the previous revision (a SQLite file on the mount
|
||||
/// read back `malformed`); too generous and a real change from another device
|
||||
/// is ignored.
|
||||
#[test]
|
||||
fn a_self_change_is_claimed_once_and_expires() {
|
||||
let mut changes = HashMap::new();
|
||||
let uid = NodeUid::new(VolumeId::from("vol"), LinkId::from("link"));
|
||||
let other = NodeUid::new(VolumeId::from("vol"), LinkId::from("other"));
|
||||
let t0 = 1_000_000;
|
||||
|
||||
assert!(
|
||||
!take_self_change(&mut changes, &uid, t0),
|
||||
"a node we never touched is never ours"
|
||||
);
|
||||
|
||||
note_self_change(&mut changes, &uid, t0);
|
||||
assert!(
|
||||
take_self_change(&mut changes, &uid, t0 + 5_000),
|
||||
"the echo of our own change is claimed"
|
||||
);
|
||||
assert!(
|
||||
!take_self_change(&mut changes, &uid, t0 + 6_000),
|
||||
"and only once, so a later foreign change still applies"
|
||||
);
|
||||
|
||||
// A create followed by a revision upload is two changes to one node, and
|
||||
// the feed reports both.
|
||||
note_self_change(&mut changes, &uid, t0);
|
||||
note_self_change(&mut changes, &uid, t0);
|
||||
assert!(take_self_change(&mut changes, &uid, t0 + 1));
|
||||
assert!(take_self_change(&mut changes, &uid, t0 + 2));
|
||||
assert!(!take_self_change(&mut changes, &uid, t0 + 3));
|
||||
|
||||
// Past the window the attribution is a guess, and a wrong guess leaves
|
||||
// the user looking at a stale file.
|
||||
note_self_change(&mut changes, &uid, t0);
|
||||
assert!(!take_self_change(
|
||||
&mut changes,
|
||||
&uid,
|
||||
t0 + SELF_CHANGE_TTL_MS
|
||||
));
|
||||
assert!(
|
||||
!changes.contains_key(&uid),
|
||||
"an expired change is dropped, not left to be re-tested"
|
||||
);
|
||||
|
||||
// An echo that never arrives must not accumulate for the life of the
|
||||
// daemon; the next recorded change prunes it.
|
||||
note_self_change(&mut changes, &uid, t0);
|
||||
note_self_change(&mut changes, &other, t0 + SELF_CHANGE_TTL_MS);
|
||||
assert_eq!(
|
||||
changes.len(),
|
||||
1,
|
||||
"recording a change prunes the ones whose echo never came"
|
||||
);
|
||||
}
|
||||
}
|
||||
+147
-11
@@ -50,8 +50,10 @@ 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-fuse`](../crates/pdfs-fuse) | The daemon: FUSE handlers (`filesystem`), the tree (`state`), finding nodes (`resolve`), folder listings and file sizes (`listing`, `sizes`), reads (`reads`), queueing and the drain (`enqueue`, `queue`, `drain`, `upload`), calls sent straight to Drive (`remote`), requests by path (`requests`), startup recovery (`recovery`), pins, search, trash, the shared tree (`shared`), the link state (`link`), remote events (`background`), the daemon's side of the sync engine (`sync`, which implements `SyncHost`), moves between locations (`relocate`), control handlers (`control`), push events (`events`), photos, sharing, devices, the supervisor, and the simulation tests (`sim/`) |
|
||||
| [`pdfs-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 |
|
||||
| [`pdfs-gui`](../crates/pdfs-gui) | `pdfs-app`, `pdfs-tray` and `pdfs-prompt`. Pages in `src/app/pages/`, widgets in `src/app/widgets/`, CSS and icons in `resources/` |
|
||||
@@ -341,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`
|
||||
@@ -479,10 +496,14 @@ both with `pdfs_core::search::relevance_score`, so the prompt can merge them int
|
||||
| Smaller helpers | `pdfs-localindex` (home index for search), `pdfs-pause` (ends a timed pause), `pdfs-similar` (similar photos, on request), `pdfs-diagnostics` |
|
||||
|
||||
Long-running loops wait on one shared `Shutdown` signal instead of sleeping, so a stop joins them
|
||||
instead of leaving them behind (`docs/BUGS.md` B44). The mount starts its long-lived threads
|
||||
through `pdfs_core::lifecycle::Services`. Each one is started with its name and, if it blocks where
|
||||
the signal does not reach, the call that wakes it: the drain's condvar, the sync engine's `Stop`
|
||||
message, a connection to the control socket. A stop signals, wakes and joins them in reverse start
|
||||
instead of leaving them behind (`docs/BUGS.md` B44). Each long-lived thread is a
|
||||
`pdfs_core::lifecycle::Service`, defined in `pdfs-fuse/src/services.rs`. A service says what its
|
||||
thread is called, whether the mount can run without it, and, if it blocks where the signal does
|
||||
not reach, the call that wakes it: the drain's condvar, the sync engine's `Stop` message, a
|
||||
connection to the control socket. The mount builds the list and starts it through
|
||||
`Services::start`. A required service that cannot start fails the mount attempt, which is retried;
|
||||
an optional one (the sync engine, the event sampler, the supervisor, the inhibitor) is logged and
|
||||
skipped. A stop signals, wakes and joins them in reverse start
|
||||
order, up to one 10-second deadline, and names any that are still running at the end. A
|
||||
service can also be an async task on the runtime (`Services::spawn_task`): the event streams and
|
||||
the gallery refresh. A stop aborts such a task at its next `.await` and waits for it to end. These
|
||||
@@ -496,7 +517,10 @@ re-date, a profile backup, a size upgrade) runs as a one-shot job:
|
||||
`ServiceBoard::spawn_job` starts it on a named thread and lists it until it ends. `pdfs
|
||||
diagnostics` shows the jobs running and how long each has run. Async work of the same kind (the
|
||||
trash, timeline and album refreshes a listing starts) goes through `ServiceBoard::spawn_task_job`
|
||||
and is listed the same way. Jobs are not joined on stop.
|
||||
and is listed the same way. Each control connection is a job too. A stop closes the board to new
|
||||
jobs, aborts the async ones and joins the thread jobs before the services, up to the same
|
||||
deadline. A long job checks the `Shutdown` signal between steps. Jobs used to be left running, and
|
||||
one still waiting on Drive when the runtime went away panicked on its next timer.
|
||||
|
||||
---
|
||||
|
||||
@@ -713,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)
|
||||
```
|
||||
|
||||
@@ -764,8 +789,9 @@ State that several owners share sits behind a narrow interface of its own:
|
||||
- `session::SessionCells` holds what belongs to one mount's FUSE session: whether it is the
|
||||
primary mount, its root inode, its kernel channel and whether it is up. An on-demand fork gets
|
||||
fresh cells from `SessionCells::fork`, and shares the rest of `Core`.
|
||||
- `link::Link` holds whether Drive answers, next to when the link went down. Code reads it through
|
||||
`Core::is_online`.
|
||||
- `link::Link` holds whether Drive answers, next to when the link went down, and is the only
|
||||
code that changes it: it flips the flag, logs the outage and wakes whoever waits. Code reads it
|
||||
through `Core::is_online`.
|
||||
|
||||
Some areas are services of their own rather than methods on `Core`. `sharing::Sharing` holds
|
||||
only the handles it calls (the client, Drive, the content cache, the transfer list and a read of
|
||||
@@ -799,14 +825,124 @@ folders and on-demand mounts are still methods on `Core`.
|
||||
machines wrote, to offer their folders for restore. It needs nothing from the filesystem, so it
|
||||
has no host. Turning the offered folders into synced folders stays on `Core`.
|
||||
|
||||
`maintenance::Maintenance` runs `VACUUM` and the deep integrity check as jobs, one at a time, and
|
||||
keeps the last check's findings.
|
||||
|
||||
`search::Search` answers searches over the node and home indexes. It holds the database, the
|
||||
content cache, the on-demand mounts and the home indexer's busy flag.
|
||||
|
||||
`recovery::Recovery` rebuilds the queue after a restart: the pending map, the staging area and
|
||||
writes fsynced before the stop. Its `RecoveryHost` port queues a recovered write. Rebuilding the
|
||||
tree stays on `Core`.
|
||||
|
||||
The mount's background loops are services of their own too, each started from the list in
|
||||
`services.rs`:
|
||||
|
||||
- `link::OnlineProbe` probes the link back while it is down. Its `LinkHost` port stores the root
|
||||
Drive answered with, lets what waited on the link go (relisting, retrying backed-off ops,
|
||||
waking the drain, rechecking pins), reports a refused session and repairs the root's share id.
|
||||
- `sweep::Sweeper` is the conflict sweep. Its `SweepHost` port asks whether a node is the
|
||||
account's own, whether the mount is online, whether a node is busy in any mount and whether
|
||||
the conflict listing can show a copy; it unhooks a trashed copy from every mount and adds
|
||||
activity entries.
|
||||
- `keeper::PinKeeper` keeps pinned files current. Its `KeeperHost` port finds a node in the tree,
|
||||
lists kept folders, describes a file as a pin keeps it and downloads it.
|
||||
- The inhibitor takes only the database and the stop signal.
|
||||
|
||||
The drain workers, the control listener, the event sampler and the supervisor still take a whole
|
||||
`Core`. The drain is the write-back, which is part of the mounted-files service (step 5); the
|
||||
other three answer front ends with reports drawn from every area.
|
||||
|
||||
The control socket answers each area's requests in a module of its own under `control/`:
|
||||
sharing, Photos, synced folders and devices, revisions, and the trash and cache. Each module
|
||||
exports a pattern macro naming its requests, and the main match hands them over in one arm, so
|
||||
the compiler still checks that every request has an answer. A module turns a path or a uid into a
|
||||
node once, then asks the service.
|
||||
|
||||
What is left in `Core` is the tree, the database, the cache and the Drive client, which most
|
||||
owners use, plus single fields that belong to one module each.
|
||||
What is left in `Core` is the mounted-files side: the tree and its per-mount state, reads,
|
||||
queued writes and the drain, listings and sizes, path requests, and the registry of on-demand
|
||||
mounts. Step 5 turns that into the `pdfs-vfs` service. `Core` also implements the services'
|
||||
host ports and builds each service on demand, which moves to `pdfs-daemon` once the services no
|
||||
longer need the tree.
|
||||
|
||||
Step 5 has started. `pdfs-vfs` holds the tree (`tree::State`: every node a mount shows, its
|
||||
stable inode, the roots of each session) and the open files (`open::OpenFiles`: write handles by
|
||||
inode and by handle number, the inodes being released, and directory handles with their frozen
|
||||
listings). A write goes through `stage_write`, which reports a full disk as a typed error; the
|
||||
tree refuses a write to a read-only node with `NodeError`; the FUSE adapter maps both to errno.
|
||||
The crate depends on no kernel or GUI crate; `cargo tree -p pdfs-vfs` shows neither.
|
||||
|
||||
The open-file service, `files::Files`, serves a file from open to close: the write open and its
|
||||
base, writes, resizes and `fallocate`, flush, the fsync barrier and the release. Each write
|
||||
handle counts its changes in a generation, and an fsync holds the handle's barrier from reading
|
||||
it to writing its sidecar, so overlapping fsyncs record in order (B301). What the service needs
|
||||
from Drive and the upload queue goes through `files::FilesHost`, which `Core` implements; the
|
||||
FUSE callbacks keep the inode translation, the choice of thread and the reply.
|
||||
|
||||
The namespace service, `namespace::Namespace`, serves create, mkdir, unlink, rmdir and rename: whether a
|
||||
new node is made on Drive at once or queued, the parked create of a transient name, the POSIX
|
||||
checks on what `unlink`, `rmdir` and a replacing rename may remove, the order of a trash (Drive
|
||||
first, then the tree), and the replace journal written before a rename removes its destination. Drive calls, the queue and the access rules go through `namespace::NamespaceHost`, which
|
||||
`Core` implements. The module also holds the rules that settle a replacing rename a stop cut off
|
||||
(B302). What still sits in `pdfs-fuse` around the tree is the code that fills it (listings,
|
||||
sizes, the drain) and the read path.
|
||||
|
||||
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.
|
||||
|
||||
Step 4 has started, inside `pdfs-sync`:
|
||||
|
||||
- **Typed absence.** `evidence` says, for each path a walk touched, what the walk proved about it:
|
||||
present, absent, excluded by the ignore rules, or unknown, with the reason: a folder that could
|
||||
not be read, a path that vanished during the scan, or a Drive listing that failed or came back
|
||||
short. The mirror pass and the push pass both ask it, and a deletion without
|
||||
proof that the path is gone is not made: it is logged and counted, and the next pass plans it
|
||||
again.
|
||||
- **A delete guard over time.** Each mirror folder counts its deletions over the last day
|
||||
(`sync_delete_window`), on either side. A pass that would bring the count to nine in ten of
|
||||
what the folder held is refused, so a wipe spread over several passes is caught as one.
|
||||
- **The local dirty set.** `local_dirty::LocalDirty` holds where each folder changed on disk since
|
||||
a pass last looked, as the watcher reports it, and whether the watch was live throughout. A pass
|
||||
still walks the whole folder and counts the changes the set did not cover.
|
||||
- **The root reducer.** `root::Roots` holds one state machine per folder (discovering, following,
|
||||
auditing, suspended, draining, handed off) that says how far the engine can trust what it has
|
||||
seen. Its transitions are logged; nothing acts on them yet.
|
||||
|
||||
Where step 3 stopped: `Core` no longer holds raw state, only the handles of the parts that own it,
|
||||
and the areas that are services of their own build from those handles. Taking `Core` apart
|
||||
further would change how hundreds of call sites reach the tree without changing who owns what, so
|
||||
the mounted-files side stays in `Core` until step 5 moves it out. The inner crates still see the
|
||||
SDK's id and node types (`NodeUid`, `Node`), which come with the whole `proton-sdk` crate; a
|
||||
crate in the SDK with only those types is the way out, and comes with an SDK release.
|
||||
|
||||
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
|
||||
|
||||
+192
-1
@@ -108,6 +108,12 @@ a live account since.
|
||||
|
||||
| Entry | Title |
|
||||
|---|---|
|
||||
| [B305](#b305--a-mirrored-file-whose-upload-went-unanswered-gets-a-conflict-copy-of-its-own-edit) | A mirrored file whose upload went unanswered gets a conflict copy of its own edit |
|
||||
| [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 |
|
||||
| [B298](#b298--a-synced-folder-edit-whose-upload-lost-its-answer-is-kept-as-a-conflict-copy-of-itself) | A synced-folder edit whose upload lost its answer is kept as a conflict copy of itself |
|
||||
| [B297](#b297--the-simulations-fail-and-hang-when-run-in-parallel-and-nothing-stops-that) | The simulations fail and hang when run in parallel, and nothing stops that |
|
||||
@@ -402,6 +408,191 @@ a live account since.
|
||||
|
||||
Newest first.
|
||||
|
||||
### B305 — A mirrored file whose upload went unanswered gets a conflict copy of its own edit
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
**Found:** 2026-11-27, writing the simulation for the case the effect reducer is meant to handle
|
||||
(`FURTHER_IMPROVEMENTS.md`): a create accepted by Drive, the reply lost, a restart, and a newer
|
||||
local edit. The simulation failed on the first run. Drive held `new.txt` with the first bytes and
|
||||
`new (sync-conflict …).txt` with the edit.
|
||||
**Where:** the `FilePlan::Conflict` arm of the plan in `crates/pdfs-sync/src/mirror.rs`, and
|
||||
`Pending::Adopt` in `crates/pdfs-sync/src/mirror/apply.rs`
|
||||
|
||||
**Repro:** In a mirror folder, write a new file. Lose the answer to its upload after Drive has
|
||||
made the file. Stop the daemon, write the file again, and start the daemon.
|
||||
|
||||
**Cause.** The upload failed as far as the daemon knew, so no baseline was recorded. The next pass
|
||||
found the path on both sides with no baseline and different bytes, which is what two computers
|
||||
writing one new file look like, so it kept the local copy as a conflict copy. The edit itself is
|
||||
not lost. The one-request small upload makes this ending of a lost reply the usual one: it
|
||||
leaves a whole file, never a draft for the next attempt to replace.
|
||||
|
||||
**Fix.** An upload that hears no success back notes the SHA-1 of the bytes it streamed in its
|
||||
effect intent (`sent_sha1s`, schema 52). Before keeping a conflict copy, the plan checks the
|
||||
intents. If Drive's file holds exactly bytes an unsettled upload of that path sent, the file is
|
||||
this daemon's own. The local bytes then go up as a revision of it. A first-sync adopt of a
|
||||
same-size file with other bytes does the same. A file that holds those bytes by chance loses
|
||||
nothing either: they are what this computer sent.
|
||||
|
||||
**Verified:** `a_mirror_create_whose_reply_was_lost_is_adopted_after_a_restart_and_its_edit_lands`
|
||||
fails without the fix and passes with it. `an_upload_notes_each_digest_it_sent_once` covers the
|
||||
store.
|
||||
|
||||
### 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)
|
||||
**Found:** 2026-11-27, from the review of the mounted filesystem in `FUSE.md`, while moving the
|
||||
fsync into `pdfs-vfs` (step 5 of `docs/ARCHITECTURE.md`). It was not seen in a run.
|
||||
**Where:** `Files::fsync` in `crates/pdfs-vfs/src/files.rs`; `WriteHandle::generation` and
|
||||
`WriteHandle::barrier` in `crates/pdfs-vfs/src/open.rs`
|
||||
|
||||
**Repro:** Write a file and call `fsync` from two threads on the same open file, with a write in
|
||||
between. Each fsync runs on a worker. If the first one finishes after the second, its record of the
|
||||
file goes to disk last. Kill the daemon before the file is closed. The restart recovers the file
|
||||
as the first fsync saw it and loses the bytes the second one had made durable.
|
||||
|
||||
**Cause.** An fsync copied what the handle held (length, written ranges, base), synced the scratch
|
||||
file and then wrote that copy as the sidecar a restart recovers from. Nothing ordered two of these
|
||||
on the same file, so the copy that was written last was not always the newest.
|
||||
|
||||
**Fix.** Each write handle counts its changes in `generation` and carries a `barrier` lock. An
|
||||
fsync takes the barrier before it reads the handle and holds it until the sidecar is written, so a
|
||||
later fsync records at least what an earlier one did. The barrier also keeps the generation last
|
||||
made durable, and an fsync with nothing new since then skips the sidecar.
|
||||
|
||||
**Verified:** `an_fsync_records_what_the_file_holds_when_its_turn_comes` holds the barrier, writes
|
||||
while an fsync waits for it, and checks that a restart recovers the later bytes. No test drives
|
||||
this through a mount.
|
||||
|
||||
---
|
||||
|
||||
### B300 — A read during a release can be served the revision the write replaced
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
**Found:** 2026-11-27, by reading the code while moving the open files into `pdfs-vfs` (step 5 of
|
||||
`docs/ARCHITECTURE.md`). It was not seen in a run.
|
||||
**Where:** `OpenFiles::release` and `OpenFiles::reader` in `crates/pdfs-vfs/src/open.rs`;
|
||||
`Core::read_local` in `crates/pdfs-fuse/src/reads.rs` and the `read` callback in
|
||||
`crates/pdfs-fuse/src/filesystem.rs`
|
||||
|
||||
**Repro:** Keep one read-only handle open on a file, and read through it from a second thread.
|
||||
Write the file through another handle and close it. A read that lands after the release took the
|
||||
write state out of the open files, but before the release queued the new revision, finds neither
|
||||
of them, and is answered with the revision on Drive from before the write.
|
||||
|
||||
**Cause.** The release removed the writer first and queued the revision second. Each read looks for
|
||||
an open writer, then for a queued revision, then goes to the cache or Drive. The release runs on the
|
||||
dispatch loop, so an `open` and `read` issued after `close(2)` are served after it. A read already
|
||||
running on a worker, through a handle opened earlier, is not ordered that way.
|
||||
|
||||
**Fix.** A release now keeps a read view of the writer (its scratch file, length, base and written
|
||||
ranges) until the revision is queued. `OpenFiles::reader` answers from the open writer, or from that
|
||||
view, and both read paths ask it first. The view was already kept in one form, as the set of inodes
|
||||
being released, which only the check for unsaved changes looked at.
|
||||
|
||||
**Verified:** `the_last_release_hands_back_the_write_and_marks_it_releasing` checks that a read finds
|
||||
the write until `finish_release`. No test drives the race through a mount.
|
||||
|
||||
---
|
||||
|
||||
### B299 — A synced folder in the trash blocks attaching any other folder
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
@@ -6004,7 +6195,7 @@ since Sep 20, 13:13 · Resolved`. `find` showed all six copies still on disk, in
|
||||
journal showed the daemon mounting at 17:29:33, and the entries were stamped 17:30. That is the
|
||||
sweep's 30-second warmup.
|
||||
|
||||
**Where:** `crates/pdfs-fuse/src/sweep.rs` (`flag_conflict`, `sweep_conflicts_once`),
|
||||
**Where:** `crates/pdfs-fuse/src/sweep.rs` (`flag_conflict`, `Sweeper::sweep_once`),
|
||||
`crates/pdfs-fuse/src/conflicts.rs` (`list_conflicts`), `crates/pdfs-fuse/src/control.rs`
|
||||
(`ResolveConflict`).
|
||||
|
||||
|
||||
+41
-2
@@ -11,10 +11,21 @@ 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: **52**. 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). Each upload, download or folder a mirror pass
|
||||
sends is recorded until its result is in (51), and an upload that heard no answer keeps the
|
||||
digest of what it sent (52).
|
||||
|
||||
### Added
|
||||
- **Small files go up to Proton Drive in one request.** A file whose encrypted size is under
|
||||
128 KiB, and a new revision of one, is now sent in a single request instead of a draft, its
|
||||
block and a commit. This covers synced folders and the drive mount. On a test account, a first
|
||||
sync of 200 small files ran 58% faster, and 50 edits of them 97% faster. Larger files go up in
|
||||
blocks as before. `proton-sdk` and `proton-drive-rs` are now 0.12.7.
|
||||
- **`small_uploads` in `config.json` turns off the one-request upload for small files.** It is
|
||||
on by default. Set it to `false` to send every file as a draft, its blocks and a commit, as
|
||||
before. The service reads it at start. See [Configuration](CONFIGURATION.md#small_uploads).
|
||||
- **`pdfs diagnostics` says which of the daemon's background services are running.** If one
|
||||
ends while the drive is mounted, for example the sync engine after a crash, the journal says
|
||||
so once, by name, instead of saying nothing until a restart. It also lists the jobs running
|
||||
@@ -44,6 +55,22 @@ kept, with a list of the folders that changed on Proton Drive since (49).
|
||||
any more.
|
||||
|
||||
### Changed
|
||||
- **An upload into a folder and an edit of a synced file make fewer requests.** The key that
|
||||
hashes a folder's file names is now read once per folder, not once per upload. A synced
|
||||
folder no longer reads a file again before it sends an edit. It checks that nobody else
|
||||
changed the file through the read the upload already makes, and it still sends nothing over
|
||||
a revision it has not seen. `proton-sdk` and `proton-drive-rs` are now 0.12.8.
|
||||
- **A sync pass over a quiet folder no longer reads the whole folder on disk.** While the
|
||||
filesystem watcher has been running without a break, a pass reads again only the folders and
|
||||
files it reported changed, and takes the rest from the pass before. The whole folder is still
|
||||
read at least once an hour, after a start, after a pass that downloaded or removed files, and
|
||||
whenever the watcher may have lost a change. `pdfs diagnostics` shows how many paths a pass
|
||||
took over as `local reused`.
|
||||
- **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
|
||||
@@ -59,6 +86,18 @@ kept, with a list of the folders that changed on Proton Drive since (49).
|
||||
first pass, and whenever the change feed lost track (#53).
|
||||
|
||||
### Fixed
|
||||
- **Stopping a sync with "Also delete from Proton Drive" says that it deletes, and says so when
|
||||
the deletion failed.** With the switch on, the dialog now reads "Stop Syncing and Delete
|
||||
Folder?" and its button "Stop Syncing and Delete". If the folder stopped syncing but its folder
|
||||
in Proton Drive could not be moved to the trash, for example while offline, the app and
|
||||
`pdfs sync rm --delete-remote` now report an error that says so. Before, they reported plain
|
||||
success, and the copy in Proton Drive stayed without a word.
|
||||
- **A mirrored file whose upload went unanswered no longer gets a conflict copy of its own
|
||||
edit.** Proton Drive can make a file and lose the answer. If the file was then written again
|
||||
before the next sync, for example while the daemon was stopped, that sync saw two different
|
||||
files under one name. It kept this computer's newer edit as a conflict copy next to its own
|
||||
first upload. Now an upload that hears no answer keeps the digest of the bytes it sent. When
|
||||
Proton Drive holds exactly those bytes, the newer edit goes up as a new version of that file.
|
||||
- **A stop ends the loops that follow Proton Drive's change feed before the daemon exits.**
|
||||
The loops that read the Drive and photos event streams, and the gallery refresh, kept
|
||||
running after every other service had stopped, and could still write to the database while
|
||||
|
||||
+1
-1
@@ -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. |
|
||||
|
||||
@@ -88,6 +88,7 @@ fix it.
|
||||
| `device_uid` | string | none | Computers → Continue This Backup Here… or Sync With This Computer… | The computer this machine syncs into. Unset means "match by hostname" |
|
||||
| `conflict_sweep` | `off` / `report` / `enforce` | `report` | Sync → Conflict Copies | See [`conflict_sweep`](#conflict_sweep) |
|
||||
| `local_first` | bool | `true` | — | See [`local_first`](#local_first) |
|
||||
| `small_uploads` | bool | `true` | — | See [`small_uploads`](#small_uploads) |
|
||||
| `language` | gettext code | system | General → Appearance | Language of the app, tray and prompt, such as `de` or `pt_BR` |
|
||||
| `proton_theme` | bool | follow system | General → Appearance | Proton's colours instead of the system theme |
|
||||
| `online_map` | bool | `false` | General → Appearance | Street map for Places from OpenFreeMap |
|
||||
@@ -145,6 +146,16 @@ call returns at once. The change goes to Drive from the queue, the same way it d
|
||||
Set it to `false` to have these calls wait for Drive again, as before 3.0.0. The switch is there
|
||||
for one release, in case the queued path misbehaves for you; please report it if it does.
|
||||
|
||||
### `small_uploads`
|
||||
|
||||
A file that fits in 128 KiB with its thumbnails goes to Proton Drive in one request. A larger one
|
||||
goes as a draft, its blocks, and a commit, which takes three requests or more. Most synced files
|
||||
are small, so this is what decides how fast a folder of many small files syncs.
|
||||
|
||||
Set it to `false` to upload every file in blocks again. The setting is read when the service
|
||||
starts. The journal says `small files are uploaded in blocks` while it is off. Please report it if
|
||||
you need to turn it off.
|
||||
|
||||
### `open_with`
|
||||
|
||||
Decides how files picked in the search launcher or the app are opened. Rules are tried in order;
|
||||
|
||||
+3
-1
@@ -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.
|
||||
|
||||
|
||||
+144
-3
@@ -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:
|
||||
@@ -195,8 +200,120 @@ that grows into hours: it is network-bound, while the local walk only reads the
|
||||
`a_pass_lists_only_the_folders_changed_on_drive` (sim: an edit, a new folder with a folder
|
||||
in it, and a deletion arrive, and a folder nothing changed in is never listed).
|
||||
|
||||
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.
|
||||
What a quiet pass still costs: loading the baseline and the picture from the database. The local
|
||||
dirty set takes the place of the local walk, as described below.
|
||||
|
||||
## Root reducer as built
|
||||
|
||||
`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.
|
||||
|
||||
| Phase | Meaning |
|
||||
|---|---|
|
||||
| Discovering | No pass over the folder has finished yet. |
|
||||
| Following | Passes covered the whole folder, and nothing since says a change went unreported. |
|
||||
| Auditing | A doubt arrived, and the side it is about has not been walked in full since. |
|
||||
| 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. |
|
||||
|
||||
A doubt is about one side, since the disk and Drive are followed by different things that fail
|
||||
on their own. The state keeps, for each side, the first doubt not yet answered (`Owed`):
|
||||
|
||||
| Doubt | Side | Where it comes from |
|
||||
|---|---|---|
|
||||
| FirstSync | both | A folder no pass has walked, or one that is a mirror again. |
|
||||
| Restart | disk | The daemon started: nothing watched the disk while it was down. Drive's event stream resumes from its cursor. |
|
||||
| WatchLost | disk | A watcher error, or a root that went missing and took its watch with it. |
|
||||
| Overflow | disk | The watcher's queue overflowed. |
|
||||
| EventGap | Drive | The event stream reported `ContinuityLost`. |
|
||||
| Pushed | Drive | A switch to on-demand was called off; the push passes dropped the picture of Drive. |
|
||||
|
||||
A pause owes nothing by itself: the watcher and the event stream keep running for a paused
|
||||
folder. A doubt that arrives while a folder is suspended is kept for when it comes back.
|
||||
|
||||
**Acted on:** a pass asks the state what it owes before it walks. A side that is owed is walked
|
||||
in full: the disk without the kept walk, and Drive without the saved picture (a walk an earlier
|
||||
pass cut short still resumes). The pass reports which sides it walked in full
|
||||
(`Outcome::walked_in_full`), and only those answer a doubt. A pass from the dirty sets keeps a
|
||||
Following folder Following.
|
||||
|
||||
The checks a pass made before (a trusted claim, a fresh event stream, the audit intervals) still
|
||||
apply on top: the state can make a pass walk more, never less. Today each doubt also breaks one
|
||||
of those checks, so the state adds no full walks except after a missing root. When the state is
|
||||
what forces a walk, the journal says `the root state asks for a walk of the whole disk` or `of
|
||||
all of Drive`.
|
||||
|
||||
A watch follows the folder it was set on, so a root moved away and made again is another folder
|
||||
that the old watch does not see. The engine keeps the root's device and inode with each watch.
|
||||
A pass that finds the root missing, or finds a root with another inode, drops the folder's trust
|
||||
in its claims and asks for the watches to be set up again. Setting them up drops any watch whose
|
||||
root is gone or replaced and watches the new one. Then it runs a pass over each folder it watched
|
||||
anew, since a file written before the watch was in place has no event. Until a watch is back,
|
||||
the disk is walked in full.
|
||||
|
||||
**Tests:** the `root::tests` unit tests (a doubt per side, a restart, a suspension, a handoff),
|
||||
`a_restart_walks_the_disk_in_full_and_not_drive` (sim: the first pass after a restart walks the
|
||||
disk and reuses the picture of Drive), and `a_root_made_again_is_watched_again` and
|
||||
`a_root_replaced_between_passes_is_watched_again` (sims: a file written in a root moved away and
|
||||
made again reaches Drive within a minute; the second fails without the inode check).
|
||||
|
||||
## Effect intents as built
|
||||
|
||||
The second reducer, `pdfs_sync::effect`, follows one effect a mirror pass sends: a folder made on
|
||||
Drive, an upload, a new revision, a download, an adopted file or a conflict copy (the `Pending`
|
||||
ops). Before an op is sent, its intent is written to `sync_intent` (schema 51): one row per
|
||||
folder, path and kind, with the number of attempts and the time it was last sent. Its result
|
||||
decides what happens next:
|
||||
|
||||
| State | Meaning |
|
||||
|---|---|
|
||||
| issued | Sent, or about to be; no result yet. |
|
||||
| unsure | Found `issued` at a start: the daemon stopped before the result came, so the effect may or may not have happened. |
|
||||
| retry | It failed, and a later pass may send it again. |
|
||||
| blocked | It failed five times in a row. The journal says `sync: an effect keeps failing` once. |
|
||||
| settled | Its result is in. The row goes. |
|
||||
|
||||
- A start moves every `issued` row to `unsure`, and says how many in the journal.
|
||||
- An op sent again keeps its row and counts the attempt. When the row was `unsure`, the journal
|
||||
says `sync: sending again an effect a stopped daemon may have made`.
|
||||
- A pass that looked at every path (none unscanned or deferred) settles the rows from before it
|
||||
began that it did not send again: what they were for has changed, or is done. An `unsure` one
|
||||
is logged at info.
|
||||
- A change to what the folder is, or its removal, drops its rows.
|
||||
|
||||
The intents decide one thing so far: whether a file on Drive is an upload of this daemon's
|
||||
that went unanswered.
|
||||
- An upload that does not hear a success back notes the SHA-1 of the bytes it streamed in its
|
||||
intent (`sent_sha1s`, schema 52). Each attempt adds its digest.
|
||||
- When a later pass would keep a conflict copy, it checks the intent first. The path may be new
|
||||
on both sides, or changed on both sides since the baseline. If Drive's file holds exactly
|
||||
bytes an unsettled upload of that path sent, the file is ours. The newer local bytes then go up
|
||||
as a revision of it, with no conflict copy. The same holds for a first-sync adopt of a
|
||||
same-size file whose bytes differ.
|
||||
- This is the usual end of a lost reply to a one-request small upload. Such an upload leaves a
|
||||
whole file, never a draft. If the file was written again before the next pass, for example
|
||||
while the daemon was stopped, the next pass used to see two different files and fork a
|
||||
conflict copy of this computer's own edit.
|
||||
- A file that only happens to hold the same bytes loses nothing either: its content is what
|
||||
this computer sent.
|
||||
- A daemon killed in the middle of an upload notes no digest, so that case still ends in a
|
||||
conflict copy when the file is edited before the next pass. It is kept, and nothing is lost.
|
||||
|
||||
Otherwise nothing reads the intents to decide what to send. The apply step's own checks still
|
||||
decide whether an effect that may have landed is sent again (B266 for a create, B39 for a
|
||||
download). Deletions on either side are not recorded yet. Trace counts: `unsure resent`,
|
||||
`retried`, `superseded`.
|
||||
|
||||
**Tests:**
|
||||
- the `effect::tests` unit tests;
|
||||
- DB: `an_effect_intent_is_kept_until_it_is_settled_or_its_folder_changes`, and
|
||||
`an_upload_notes_each_digest_it_sent_once`;
|
||||
- sim `an_effect_left_unsure_by_a_stop_is_sent_again_or_settled`: of two uploads a stopped daemon
|
||||
left unsure, the one still needed is sent again and the other is settled;
|
||||
- sim `a_mirror_create_whose_reply_was_lost_is_adopted_after_a_restart_and_its_edit_lands`:
|
||||
Drive makes the file and the answer is lost, then the daemon stops and the file is written
|
||||
again. After the start there is one file, holding the newer bytes, and no conflict copy.
|
||||
|
||||
## Plan of work (separate PRs)
|
||||
|
||||
@@ -205,7 +322,31 @@ 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:
|
||||
- The watcher marks each path an event names in `LocalDirty` (in memory): the path, with
|
||||
what is under it, and the folder it is in. A pass claims the marks before it looks at the
|
||||
disk, so a change made while it looks stays marked for the next pass, 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.
|
||||
- A pass keeps what it found on disk (`LocalWalk`) for the next one, unless it changed the
|
||||
disk itself (a download, a conflict copy, a folder made or removed), failed a step, deferred
|
||||
a file or could not read a path. Its own changes are marked only once the watcher reports
|
||||
them, which may come after the next pass claims, so that pass walks in full instead.
|
||||
- The next pass with a trusted claim, the same ignore rules (`IgnoreRules::source`) and a
|
||||
full walk less than an hour old starts from the kept walk (`local reused` in the trace).
|
||||
It lists each marked folder again, walks each marked path again with what is under it, and
|
||||
reads again each file that was open for writing. Everything else is taken as it was.
|
||||
- A full walk with a trusted claim still counts the changes the claim did not cover
|
||||
(`missed local changes`). It runs at least once an hour, and after anything that breaks
|
||||
the trust.
|
||||
- A mark that was missed delays a change until the next full walk. It cannot lose one: a
|
||||
download and a local deletion check the file on disk against what the pass planned from
|
||||
before they act, and a path missing from the kept walk is one a walk found gone.
|
||||
- **Tests:** the `rewalk` unit tests in `mirror.rs` (each kind of change, ignored folders, a
|
||||
mark that came before its folder's, a file that was open for writing), and
|
||||
`a_trusted_local_dirty_set_stands_in_for_the_walk` (sim: an edit, a new folder, a deletion
|
||||
and a folder moved in reach Drive through reused walks; it fails with the watcher's marks
|
||||
switched off).
|
||||
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.
|
||||
|
||||
+26
-3
@@ -307,9 +307,32 @@ instance's keyring entry so the next run does not sign in again; `--logout` forg
|
||||
Proton asks for a CAPTCHA, sign in once by hand with `PDFS_INSTANCE=bench pdfs login`.
|
||||
|
||||
The script refuses a `pdfs` built without `PDFS_INSTANCE`, which would act on your own account.
|
||||
A new folder's first sync uploads about one small file every four seconds, so with a 500-file
|
||||
tree the edit is timed about 35 minutes in. A run that is cut short leaves its folder behind; the
|
||||
next run removes it.
|
||||
A new folder's first sync uploads about two small files a second (eight at a time), so with a
|
||||
500-file tree the edit is timed a few minutes in. A run that is cut short leaves its folder behind;
|
||||
the next run removes it.
|
||||
|
||||
### The small-file benchmark
|
||||
|
||||
`--scenario small` times many small files instead, the case that the API's one-request small
|
||||
upload is for. For each tree size (200 by default) it makes files of `--small-size` random bytes
|
||||
(4096 by default), plus `--images` noise PNGs that get thumbnails (10 by default). It then:
|
||||
|
||||
- times the first sync, until every file is uploaded and the folder is quiet
|
||||
- rewrites `--edits` of the files at once (50 by default) and times until all are uploaded again
|
||||
|
||||
For each phase it reports wall time, files per second, the daemon's CPU time, and the requests
|
||||
the daemon sent. The requests are API calls by method, plus storage uploads. It counts them from
|
||||
the SDK's telemetry: the daemon runs with `RUST_LOG=info,pgp=error,proton_sdk::telemetry=debug`,
|
||||
and its log goes to the work directory. If the SDK tags each request with its endpoint, the JSON
|
||||
output also counts requests per endpoint.
|
||||
|
||||
```bash
|
||||
scripts/live-bench.py --account-env path/to/.env --pdfs target/release/pdfs --scenario small \
|
||||
--json small.json
|
||||
```
|
||||
|
||||
Wall time varies by 2x between runs against the live service. Compare medians of three runs,
|
||||
and treat the request counts as the stable measure.
|
||||
|
||||
## Before a release
|
||||
|
||||
|
||||
@@ -298,12 +298,41 @@ 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. **`local reused`** counts the paths on disk a pass took from
|
||||
the last pass's walk instead of walking the folder again: it then read only what the watcher
|
||||
reported. A pass with no `local reused` count walked the whole folder. That happens on the
|
||||
first pass, at least once an hour, after the pass before it changed files on disk itself,
|
||||
and after anything that breaks trust in the watch. Only those passes count `missed local
|
||||
changes`.
|
||||
A `sync: root state` line in the journal says when a folder's state changes, for example
|
||||
`from=following to=auditing (local: Overflow)`: the side named is walked in full by the next
|
||||
pass, which takes the folder back to `following`.
|
||||
**`unsure resent`** counts effects sent again that a daemon stopped before it heard back
|
||||
from; the apply step checks whether each already landed before it sends it. **`retried`**
|
||||
counts effects sent again after a failure, and **`superseded`** counts unsettled effects of
|
||||
earlier passes that were no longer needed. A `sync: an effect keeps failing` line names an
|
||||
upload, download or folder that failed five times in a row.
|
||||
|
||||
Please include these lines when you report a slow folder.
|
||||
|
||||
### Files named `(sync-conflict …)` appeared
|
||||
|
||||
+426
-403
File diff suppressed because it is too large.
Load diff
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user