Compare commits

...
Author SHA1 Message Date
nvrl cb6e0e3228 feat(core,fuse): stop the event-stream loops with the mount's other services
The loops that follow the Drive and photos event streams, and the gallery
refresh, were bare tasks on the runtime. A stop ended every thread and left
them running until the process exited, still able to write to the database.

`Services::spawn_task` starts an async task as a service: it shows on the
service board, and a stop aborts it at its next `.await` and waits for it
up to the shared deadline. `ServiceBoard::spawn_task_job` lists the trash,
timeline and album refreshes a listing starts as jobs, and the My Files
share-id repair runs as a job too.

The sims now fail a run whose stops leave a service running.
2026-11-26 18:47:16 +01:00
nvrl a627542c20 Merge pull request #161 from narrrl/refactor/mirror-split
refactor(sync), feat(core,fuse): split mirror.rs; run request work as named jobs
2026-11-26 17:27:38 +01:00
nvrl 58fa3b5953 Merge pull request #160 from narrrl/refactor/cli-split
refactor(cli,fuse): split the CLI's main.rs, the drain and photos by area
2026-11-26 17:01:19 +01:00
nvrl 633e268a7b Merge pull request #159 from narrrl/feat/pdfs-daemon
feat(daemon): add pdfs-daemon, the daemon's composition root
2026-11-26 17:01:07 +01:00
nvrl afbf88aa2d feat(core,fuse): run a request's background work as a named job on the service board
Work a request starts and does not wait for ran on a bare thread::spawn:
unnamed, invisible to diagnostics, and a panic if the thread could not
be started. ServiceBoard::spawn_job starts it on a named thread and
lists it until it ends, by return or by panic.

Twelve sites move to it: the profile backup, the upload, add and restore
of synced folders from the control socket, re-dating, VACUUM, the deep
integrity check, the Google Photos import, the timed pause, a folder
pin, the similar-photo pass, and size upgrades. A job that cannot be
started is logged by name instead of panicking the handler.

pdfs diagnostics gets a jobs field (serde default) and prints the jobs
running with their age. Jobs are not joined on stop, as before.
2026-11-26 16:45:43 +01:00
nvrl e93e2a3ef9 refactor(sync): split mirror.rs into the walks, applying a plan and the push pass
mirror.rs keeps a pass from end to end (reconcile_folder, reconcile_pass,
do_reconcile), the trace, the helpers the parts share, and the tests.
Syncer's methods move, unchanged, into:

- mirror/walk.rs: walking the local tree and Drive's folders, resuming
  a saved walk, walking only the changed folders, listing one (8)
- mirror/apply.rs: applying a plan in batches, uploads, downloads, and
  the baseline each one leaves (12)
- mirror/push.rs: the push pass (1)

No behaviour changes.
2026-11-26 16:39:57 +01:00
nvrl 66c67b5a08 refactor(fuse): split photos.rs into the thumbnail and timeline requests
photos.rs keeps the image, RAW and video decoding, the decode budget,
PhotoJobs and the tests. Core's methods move, unchanged, into:

- photos/thumbs.rs: generating and uploading missing thumbnails, file
  thumbnails, folder covers, the recursive build (19 methods)
- photos/timeline.rs: the timeline, favorites, duplicates and similar
  shots, places, on this day, groups, trashing photos (21 methods)

Two doc links in drain/revision.rs point at crate:: instead of super::.
No behaviour changes.
2026-11-26 16:34:34 +01:00
nvrl d32f287763 Merge pull request #158 from narrrl/refactor/lib-split
refactor(fuse): split Core's methods by area out of lib.rs into ten modules
2026-11-26 16:31:24 +01:00
nvrl 27860688ab refactor(fuse): split the drain by op kind into drain/{create,rename,trash,revision}.rs
drain.rs keeps the workers, the claim and dispatch of an op, the access
deferral, the helpers several op kinds share, and the tests. The Core
methods that drain one kind of op move, unchanged, into submodules:

- create.rs: creates and mkdirs, twins left by an unanswered attempt,
  adopting the real uid (16 methods)
- rename.rs: renames and moves (3)
- trash.rs: trashes, and withdrawing a create that never landed (5)
- revision.rs: uploads, the conflict check, placing what landed, the
  revision debounce (13)

The source-order tests read the drain through DRAIN_SOURCE. No behaviour
changes.
2026-11-26 16:29:02 +01:00
nvrl 307bbac96c refactor(cli): split main.rs by command area into seven modules
main.rs keeps the command definitions, main's dispatch and the helpers
every area uses (control_request, ok_or_bail, path_arg, the formatters).
The commands move, unchanged, into:

- account.rs: login, unlock, lock, logout
- files.rs: mount, pins, ls, search, rename, move, copy, du, rm,
  versions, trash, mkdir, upload, refresh
- photos.rs: timeline, favorites, albums, the Google Photos import,
  re-dating
- sharing.rs: share, members, roles, public links, shared items,
  invitations, bookmarks, leave
- status.rs: status, locations, devices, diagnostics, cache
- sync.rs: sync, conflicts, the sync queue, issues, export, restore,
  limits, ignore rules, health
- diagnose.rs: pdfs diagnose and its report, with its tests

main.rs goes from 4,842 lines to 1,620. No behaviour changes.
2026-11-26 16:25:28 +01:00
nvrl 191a9cfe82 feat(daemon): add pdfs-daemon, the daemon's composition root
The daemon's run loop moves out of pdfs-cli into a new crate. run waits
for a stored session, then opens the database and the content cache,
resumes the session on a runtime of its own, and mounts. It remounts
after an external unmount, and retries a failed mount with a backoff,
recording each failure. pdfs daemon and pdfs mount call into it.

Moved unchanged, with their nine tests: login_poll_delay,
wait_for_session, not_empty_cause, mount_retry_schedule,
mount_retry_delay, mount_once and release_runtime. cmd_daemon becomes
pdfs_daemon::run.

The services the mount starts are still built in pdfs-fuse. Moving their
construction here is the next part of step 3.
2026-11-26 16:20:51 +01:00
nvrl 04fb485e9f Merge pull request #157 from narrrl/refactor/core-groups
refactor(fuse): move five more Core groups, with their code, out of lib.rs
2026-11-26 16:12:03 +01:00
43 changed files with 9409 additions and 8819 deletions

No files matched your search

Generated
+13
View File
@@ -3640,6 +3640,7 @@ dependencies = [
"clap",
"clap_complete",
"pdfs-core",
"pdfs-daemon",
"pdfs-fuse",
"pdfs-store",
"rpassword",
@@ -3680,6 +3681,18 @@ dependencies = [
"zeroize",
]
[[package]]
name = "pdfs-daemon"
version = "3.10.0"
dependencies = [
"anyhow",
"pdfs-core",
"pdfs-fuse",
"pdfs-store",
"tokio",
"tracing",
]
[[package]]
name = "pdfs-drive"
version = "3.10.0"
+2 -1
View File
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["crates/pdfs-core", "crates/pdfs-store", "crates/pdfs-drive", "crates/pdfs-sync", "crates/pdfs-fuse", "crates/pdfs-cli", "crates/pdfs-gui"]
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"]
[workspace.package]
version = "3.10.0"
@@ -28,6 +28,7 @@ pdfs-store = { path = "crates/pdfs-store" }
pdfs-drive = { path = "crates/pdfs-drive" }
pdfs-sync = { path = "crates/pdfs-sync" }
pdfs-fuse = { path = "crates/pdfs-fuse" }
pdfs-daemon = { path = "crates/pdfs-daemon" }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "fs", "io-util", "time", "signal"] }
serde = { version = "1", features = ["derive"] }
+1
View File
@@ -17,6 +17,7 @@ path = "src/main.rs"
pdfs-core.workspace = true
pdfs-store.workspace = true
pdfs-fuse.workspace = true
pdfs-daemon.workspace = true
tokio.workspace = true
anyhow.workspace = true
tracing.workspace = true
+187
View File
@@ -0,0 +1,187 @@
//! The account: login, unlock, lock and logout.
use super::*;
/// Read a line from stdin with a prompt (echoed).
pub(super) fn prompt_line(label: &str) -> Result<String> {
print!("{label}: ");
std::io::stdout().flush()?;
let mut line = String::new();
std::io::stdin().read_line(&mut line)?;
Ok(line.trim().to_owned())
}
pub(super) fn cmd_login(username: Option<String>, remember: bool) -> Result<()> {
let username = match username {
Some(u) => u,
None => prompt_line("Proton email")?,
};
let password = rpassword::prompt_password("Password: ").context("read password")?;
// The 2FA prompt fires lazily — only if the account actually requires it.
let get_totp = || -> pdfs_core::Result<String> {
prompt_line("2FA code").map_err(|e| pdfs_core::Error::Other(format!("read 2FA code: {e}")))
};
// Only a two-password account is ever asked for this.
let get_mailbox = |attempt: u32| prompt_mailbox(attempt, remember);
// Proton may ask for a CAPTCHA first, usually on a VPN. The CLI has no
// browser engine, so the user solves the page in their own browser and says
// when they are done; the retry then carries the challenge token.
let get_hv = |hv: pdfs_core::proton_sdk::api::HumanVerification| {
println!(
"Proton is asking for a CAPTCHA before it will accept this sign-in.\n\
Open this page in your browser and complete it:\n\n {}\n",
auth::browser_verification_url(&hv)
);
prompt_line("Press Enter once the page says you are verified")
.map_err(|e| pdfs_core::Error::Other(format!("read verification answer: {e}")))?;
Ok(auth::browser_verified(&hv))
};
let rt = tokio::runtime::Runtime::new()?;
rt.block_on(auth::login_interactive(
&username,
&password,
get_totp,
get_mailbox,
get_hv,
))
.map_err(login_failure)?;
// A daemon that is already up is parked in `wait_for_session`, sleeping
// between keyring checks; restart it so the mount appears now instead of
// whenever the next poll fires. Only when it is already active — `pdfs
// login` deliberately does not enable the unit the way the GUI does, so a
// headless user driving `pdfs daemon` by hand keeps that setup.
if service::is_active() {
service::restart();
}
println!("Logged in as {username}. Session stored in the system keyring.");
report_key_state();
Ok(())
}
pub(super) fn login_failure(error: pdfs_core::Error) -> anyhow::Error {
if matches!(&error, pdfs_core::Error::Proton(e) if pdfs_core::error::sign_in_blocked(e)) {
// The SDK logs the response code at debug level. Its server text
// would give contradictory instructions in the displayed cause chain.
anyhow::anyhow!(
"Proton declined this sign-in (code 2028). Wait before trying again. If it persists, try signing in on the web and mention code 2028 when contacting Proton support."
)
} else {
anyhow::Error::new(error).context("login failed")
}
}
/// Ask for the mailbox password of a two-password account, without echo.
pub(super) fn prompt_mailbox(attempt: u32, remember: bool) -> pdfs_core::Result<auth::Mailbox> {
if attempt == 0 {
eprintln!("This account has a separate mailbox password.");
} else {
eprintln!("That mailbox password did not unlock the account. Try again.");
}
let password = rpassword::prompt_password("Mailbox password: ")
.map_err(|e| pdfs_core::Error::Other(format!("read mailbox password: {e}")))?;
Ok(auth::Mailbox {
password: zeroize::Zeroizing::new(password),
remember,
})
}
/// Say where the account's keys are held, and what that means for the next login.
pub(super) fn report_key_state() {
match auth::key_state() {
Ok(auth::KeyState::Session) => println!(
"Unlocked for this login session only. After you log out or reboot, run `pdfs unlock`."
),
Ok(auth::KeyState::Locked) => println!("The account is locked. Run `pdfs unlock`."),
_ => {}
}
}
pub(super) fn cmd_unlock(remember: bool) -> Result<()> {
auth::load().context("not logged in (run `pdfs login` first)")?;
let rt = tokio::runtime::Runtime::new()?;
// Bounded like the login prompt: three wrong answers end the command.
let mut attempt = 0;
loop {
let mailbox = prompt_mailbox(attempt, remember)?;
match rt.block_on(auth::unlock(&mailbox.password, remember)) {
Ok(()) => break,
Err(pdfs_core::Error::WrongMailboxPassword) if attempt < 2 => attempt += 1,
Err(e) => return Err(anyhow::Error::new(e).context("unlock failed")),
}
}
// A daemon parked on the locked account would otherwise notice on its next
// poll; restarting it makes the mount appear now, as after `pdfs login`.
if service::is_active() {
service::restart();
}
println!("Unlocked.");
report_key_state();
Ok(())
}
pub(super) fn cmd_lock(forget: bool) -> Result<()> {
auth::lock(forget)?;
println!(
"Locked. {}",
if forget {
"Unlock removed from memory and keyring."
} else {
"Run `pdfs unlock` to unlock again."
}
);
// The running daemon keeps its keys until it restarts; say so, since
// "locked" would otherwise suggest the mount stopped.
if service::is_active() {
println!(
"The running daemon keeps its keys until it restarts: `systemctl --user restart proton-drive`."
);
}
Ok(())
}
/// `stored`, `session` or `locked`: where the account's keys are held.
pub(super) fn key_state_name() -> &'static str {
match auth::key_state() {
Ok(auth::KeyState::Stored) => "stored",
Ok(auth::KeyState::Session) => "session",
_ => "locked",
}
}
pub(super) fn cmd_logout(yes: bool) -> Result<()> {
// Queued changes stay staged on this computer and are sent after the next
// sign-in, but until then they exist nowhere else. Without a running
// daemon there is no count to show.
if !yes
&& let Ok(CtlResponse::Status {
pending_uploads,
pending_changes,
parked_uploads,
..
}) = control_request(CtlRequest::Status)
{
let queued = pending_uploads + pending_changes + parked_uploads;
if queued > 0 {
println!(
"{queued} change(s) are not on Proton Drive yet. They stay on this computer and are \
sent after you sign in again. Run `pdfs sync flush` first to send them now."
);
confirm("Sign out anyway?")?;
}
}
if auth::logout()? {
println!("Signed out: the session is ended on Proton and cleared here.");
} else {
println!(
"Stored session cleared. Proton could not be reached to end the session; \
it stays valid until it expires or is signed out in your account's security settings."
);
}
Ok(())
}
+538
View File
@@ -0,0 +1,538 @@
//! `pdfs diagnose`: checks of this computer that need no running daemon.
use super::*;
#[derive(Default)]
pub(super) struct DiagnoseReport {
warnings: usize,
failures: usize,
}
impl DiagnoseReport {
pub(super) fn finding(&mut self, level: DiagnoseLevel, label: &str, detail: impl AsRef<str>) {
let mark = match level {
DiagnoseLevel::Ok => "ok ",
DiagnoseLevel::Warn => {
self.warnings += 1;
"WARN"
}
DiagnoseLevel::Fail => {
self.failures += 1;
"FAIL"
}
};
let detail = detail.as_ref();
if detail.is_empty() {
println!("[{mark}] {label}");
} else {
println!("[{mark}] {label}: {detail}");
}
}
pub(super) fn check(&mut self, label: &str, ok: bool, detail: impl AsRef<str>) {
self.finding(
if ok {
DiagnoseLevel::Ok
} else {
DiagnoseLevel::Fail
},
label,
detail,
);
}
}
#[derive(Clone, Copy)]
pub(super) enum DiagnoseLevel {
Ok,
Warn,
Fail,
}
pub(super) fn executable_on_path(name: &str) -> bool {
std::env::var_os("PATH").is_some_and(|paths| {
std::env::split_paths(&paths)
.any(|dir| std::fs::metadata(dir.join(name)).is_ok_and(|m| m.is_file()))
})
}
/// Create, sync, and remove a new file without ever replacing an existing one.
pub(super) fn writable_probe(dir: &Path) -> std::io::Result<()> {
let name = format!(".pdfs-diagnose-probe-{}", std::process::id());
let path = dir.join(name);
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)?;
let result = (|| {
file.write_all(b"probe")?;
file.sync_all()
})();
drop(file);
let remove = std::fs::remove_file(path);
result.and(remove)
}
/// Self-check the installation, reporting each finding and exiting non-zero if
/// any check failed.
///
/// Every check is written to work with no daemon running, because that is the
/// situation a user runs this in. A missing daemon is reported as a finding,
/// not an error that aborts the rest of the report.
pub(super) fn cmd_diagnose() -> Result<()> {
let mut report = DiagnoseReport::default();
let dirs = AppDirs::new().context("resolve application directories")?;
let config = dirs.load_config();
println!("Paths");
let state = dirs.state_dir();
report.check(
" state dir",
state.is_dir(),
format!("{}", state.display()),
);
let cache_dir = dirs.cache_dir();
report.check(
" cache dir",
cache_dir.is_dir(),
format!("{}", cache_dir.display()),
);
// Writability is checked by actually writing: permission bits do not
// account for a full disk, a read-only remount, or an immutable flag.
match writable_probe(&state) {
Ok(()) => report.finding(
DiagnoseLevel::Ok,
" state dir writable",
"write and fsync succeeded",
),
Err(e) => report.finding(DiagnoseLevel::Fail, " state dir writable", e.to_string()),
}
let db_path = dirs.db_path();
if db_path.exists() {
let db_size = std::fs::metadata(&db_path).map(|m| m.len()).unwrap_or(0);
report.check(
" database",
db_path.is_file(),
format!("{} ({})", db_path.display(), human_bytes(db_size)),
);
} else {
// The daemon creates it on its first start, which waits for a sign-in,
// so a fresh install has none yet (issue #39 read this as the fault).
report.finding(
DiagnoseLevel::Warn,
" database",
format!(
"{} not created yet (the daemon creates it on first start)",
db_path.display()
),
);
}
println!("\nFUSE");
let fuse = Path::new("/dev/fuse");
report.check(" /dev/fuse", fuse.exists(), fuse.display().to_string());
let has_fusermount = executable_on_path("fusermount3") || executable_on_path("fusermount");
report.check(
" unmount helper",
has_fusermount,
"fusermount3 or fusermount on PATH",
);
println!("\nAccount");
let mut keys_unlocked = false;
match pdfs_core::auth::load() {
Ok(session) => {
report.finding(DiagnoseLevel::Ok, " keyring session", session.username);
let key_state = key_state_name();
keys_unlocked = key_state != "locked";
match key_state {
"locked" => report.finding(
DiagnoseLevel::Fail,
" account keys",
"locked — run `pdfs unlock` (the daemon waits for it)",
),
"session" => report.finding(
DiagnoseLevel::Ok,
" account keys",
"unlocked for this login session",
),
_ => report.finding(DiagnoseLevel::Ok, " account keys", "stored in the keyring"),
}
}
Err(e) => {
// A locked keyring and an absent login look the same from here, so
// the detail carries the distinction rather than the verdict.
report.finding(DiagnoseLevel::Fail, " keyring session", format!("{e}"));
}
}
println!("\nDaemon");
let socket = dirs.control_socket();
let socket_exists = socket.exists();
let socket_kind_ok =
std::fs::symlink_metadata(&socket).is_ok_and(|m| m.file_type().is_socket());
// A stale socket file with no listener is the common failure, so the reply
// is what decides this rather than the file's existence.
let status = control_request(CtlRequest::Status);
report.finding(
if socket_exists && !socket_kind_ok {
DiagnoseLevel::Fail
} else if socket_exists && status.is_ok() {
DiagnoseLevel::Ok
} else {
DiagnoseLevel::Warn
},
" control socket",
if socket_exists && socket_kind_ok && status.is_err() {
format!("{} (left over; nothing listens on it)", socket.display())
} else {
socket.display().to_string()
},
);
let mut daemon_responding = false;
match status {
Ok(CtlResponse::Status {
mountpoint,
online,
session_expired,
tokens_unsaved,
pending_uploads,
pending_changes,
failing_ops,
failing_error,
staged_bytes,
staged_oldest_secs,
paused,
paused_until,
version,
..
}) => {
daemon_responding = true;
report.finding(DiagnoseLevel::Ok, " daemon responding", "");
if daemon_outdated(&version) {
report.finding(
DiagnoseLevel::Warn,
" daemon version",
outdated_daemon_note(&version),
);
}
let live_type = pdfs_core::mountpoint::mounted_fs_type(Path::new(&mountpoint));
let is_fuse = live_type
.as_deref()
.is_some_and(|kind| kind.starts_with("fuse"));
report.finding(
if is_fuse {
DiagnoseLevel::Ok
} else {
DiagnoseLevel::Fail
},
" active mount",
live_type.map_or_else(
|| format!("{mountpoint} is not mounted"),
|kind| format!("{mountpoint} ({kind})"),
),
);
// The keyring check above read the blob, which still holds the
// tokens the daemon could not replace.
if tokens_unsaved {
report.finding(
DiagnoseLevel::Warn,
" session tokens",
"the keyring refuses the refreshed ones; unlock it, or a reboot needs `pdfs login`",
);
}
// A refused session reads as offline too, but no connection will
// bring it back, and the keyring check above cannot tell.
if session_expired {
report.finding(
DiagnoseLevel::Fail,
" session",
"Proton refused it (expired or revoked) — run `pdfs login`",
);
} else {
report.finding(
if online {
DiagnoseLevel::Ok
} else {
DiagnoseLevel::Warn
},
" network",
if online {
"online"
} else {
"offline; cached data remains available"
},
);
}
let pending = pending_uploads + pending_changes;
report.finding(
if pending == 0 {
DiagnoseLevel::Ok
} else {
DiagnoseLevel::Warn
},
" queued writes",
if pending == 0 {
"none".to_string()
} else {
format!("{pending} waiting to upload")
},
);
// The rest of the daemon's state that the report used to drop:
// writes that keep failing, a pause, a folder in error. Each of
// them stops changes from reaching Drive while everything above
// reads as fine (`docs/BUGS.md` B268).
for (level, check, detail) in sync_health(
failing_ops,
failing_error.as_deref(),
staged_bytes,
staged_oldest_secs,
paused,
paused_until.map(|until| until - unix_now()),
) {
report.finding(level, check, detail);
}
if let Ok(CtlResponse::SyncFolders { items }) =
control_request(CtlRequest::ListSyncFolders)
{
for (level, check, detail) in folder_health(&items) {
report.finding(level, &check, detail);
}
}
match await_integrity_check() {
Ok(CtlResponse::CacheReport {
integrity_problems,
integrity_checked: true,
..
}) if integrity_problems.is_empty() => report.finding(
DiagnoseLevel::Ok,
" database integrity",
"SQLite integrity_check passed",
),
Ok(CtlResponse::CacheReport {
integrity_checked: false,
..
}) => report.finding(
DiagnoseLevel::Warn,
" database integrity",
"still checking — run `pdfs cache inspect --deep` for the result",
),
Ok(CtlResponse::CacheReport {
integrity_problems, ..
}) => report.finding(
DiagnoseLevel::Fail,
" database integrity",
format!(
"{} problem(s): {}",
integrity_problems.len(),
integrity_problems.join("; ")
),
),
Ok(other) => report.finding(
DiagnoseLevel::Fail,
" database integrity",
format!("unexpected: {other:?}"),
),
Err(e) => report.finding(
DiagnoseLevel::Fail,
" database integrity",
format!("check failed: {e:#}"),
),
}
}
Ok(other) => {
report.finding(
DiagnoseLevel::Fail,
" daemon responding",
format!("unexpected: {other:?}"),
);
}
Err(e) => {
// Not a failure of the installation: a stopped daemon is a normal
// state, and the rest of the report is still worth printing.
report.finding(
DiagnoseLevel::Warn,
" daemon responding",
format!("stopped or unreachable: {e:#}"),
);
match pdfs_core::mountfail::read(&dirs.state_dir()) {
// A daemon whose mount keeps failing never opens the socket,
// so this is the only place its reason shows (B263).
Some(failure) => report.finding(
DiagnoseLevel::Fail,
" mount",
format!(
"failing for {}, {} attempt(s): {}",
human_secs(unix_now().saturating_sub(failure.since).max(0) as u64),
failure.attempts,
if failure.awaiting_keys {
format!("{} — after recovering your account keys, restart proton-drive.service", failure.error)
} else {
failure.error
}
),
),
None => println!(
" (start it with `systemctl --user start proton-drive.service`)"
),
}
}
}
let mountpoint = dirs.resolved_mountpoint(&config);
report.finding(
if mountpoint.is_dir() {
DiagnoseLevel::Ok
} else {
DiagnoseLevel::Warn
},
" configured mountpoint",
mountpoint.display().to_string(),
);
// The daemon opens its control socket only once My Files is mounted, so a
// daemon that answers has the keys it needs. One that does not may be stuck
// on a key that does not open (#40); only then is Proton asked.
if keys_unlocked && !daemon_responding {
println!("\nKeys");
diagnose_keys(&mut report);
}
if report.failures == 0 {
if report.warnings == 0 {
println!("\nNo problems found.");
} else {
println!(
"\nNo critical problems found; {} warning(s) need attention.",
report.warnings
);
}
Ok(())
} else {
bail!(
"{} check(s) failed and {} warning(s) were reported; see above",
report.failures,
report.warnings
)
}
}
/// Ask Proton which account and address keys open, and which of them the My
/// Files share needs. The findings hold key IDs and no secrets.
pub(super) fn diagnose_keys(report: &mut DiagnoseReport) {
use pdfs_core::keycheck::{self, Level};
let checked = tokio::runtime::Runtime::new()
.map_err(anyhow::Error::from)
.and_then(|rt| {
rt.block_on(async {
tokio::time::timeout(std::time::Duration::from_secs(30), keycheck::run())
.await
.map_err(|_| anyhow!("Proton did not answer within 30 seconds"))?
.map_err(anyhow::Error::from)
})
});
let (keys, share) = match checked {
Ok(checked) => checked,
Err(e) => {
report.finding(DiagnoseLevel::Warn, " key check", format!("{e:#}"));
return;
}
};
let findings = keycheck::findings(&keys, &share);
let any_failed = findings.iter().any(|f| f.level != Level::Ok);
for finding in findings {
let level = match finding.level {
Level::Ok => DiagnoseLevel::Ok,
Level::Warn => DiagnoseLevel::Warn,
Level::Fail => DiagnoseLevel::Fail,
};
report.finding(level, &format!(" {}", finding.label), finding.detail);
}
if any_failed {
println!(" (key IDs are not secret; include this section when you report it)");
}
}
#[cfg(test)]
mod diagnose_tests {
use super::*;
/// A healthy queue says nothing; writes that keep failing, an old unsent
/// write and a pause each say so (`docs/BUGS.md` B268).
#[test]
fn a_stuck_queue_or_a_pause_is_reported() {
assert!(sync_health(0, None, 0, 0, false, None).is_empty());
assert!(sync_health(0, None, 4096, STAGED_STALE_SECS - 1, false, None).is_empty());
let checks: Vec<&str> = sync_health(
2,
Some("upload a.txt: quota"),
4096,
STAGED_STALE_SECS,
true,
Some(600),
)
.into_iter()
.map(|(level, check, _)| {
assert!(matches!(level, DiagnoseLevel::Warn));
check.trim()
})
.collect();
assert_eq!(checks, ["failing writes", "oldest unsent write", "sync"]);
}
/// Issue #53: a folder that would not sync, and `diagnose` found nothing.
#[test]
fn a_synced_folder_in_error_is_reported() {
let folder = |id: i64, state: &str| pdfs_core::control::SyncFolderInfo {
kind: "device".into(),
id,
local_path: format!("/home/u/f{id}"),
remote_uid: "vol~link".into(),
mode: "mirror".into(),
state: state.into(),
last_sync: 0,
pending_mode: None,
progress: None,
paused: false,
};
let findings =
folder_health(&[folder(1, "idle"), folder(2, "error"), folder(3, "syncing")]);
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].1.trim(), "synced folder [2]");
assert!(findings[0].2.starts_with("/home/u/f2: sync error"));
}
#[test]
fn finding_severity_is_counted_centrally() {
let mut report = DiagnoseReport::default();
report.finding(DiagnoseLevel::Ok, "ok", "");
report.finding(DiagnoseLevel::Warn, "warn", "");
report.finding(DiagnoseLevel::Fail, "fail", "");
assert_eq!(report.warnings, 1);
assert_eq!(report.failures, 1);
}
#[test]
fn writable_probe_never_replaces_an_existing_file() {
let dir = std::env::temp_dir().join(format!(
"pdfs-diagnose-test-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
std::fs::create_dir_all(&dir).unwrap();
let collision = dir.join(format!(".pdfs-diagnose-probe-{}", std::process::id()));
std::fs::write(&collision, b"keep me").unwrap();
assert_eq!(
writable_probe(&dir).unwrap_err().kind(),
std::io::ErrorKind::AlreadyExists
);
assert_eq!(std::fs::read(&collision).unwrap(), b"keep me");
std::fs::remove_file(collision).unwrap();
std::fs::remove_dir(dir).unwrap();
}
}
+474
View File
@@ -0,0 +1,474 @@
//! Files on the drive: mount, pins, listing, search, moves and copies,
//! versions, trash, new folders and uploads.
use super::*;
pub(super) fn cmd_versions(action: VersionCmd) -> Result<()> {
match action {
VersionCmd::List { path } => {
let response = control_request(CtlRequest::ListRevisions {
path: path_arg(&path)?,
})?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Revisions { items } if items.is_empty() => {
println!("No versions.");
}
CtlResponse::Revisions { items } => {
for r in items {
// The claimed plaintext size is what the user recognises;
// the storage size is ciphertext and always larger.
let size = r
.claimed_size
.filter(|size| *size >= 0)
.unwrap_or(r.size_on_storage)
.max(0) as u64;
let mark = if r.is_active { "*" } else { " " };
let by = r
.signed_by
.map(|email| format!(" {email}"))
.unwrap_or_default();
println!(
"{mark} {:<20} {:>10} {}{by}",
r.id,
human_bytes(size),
format_epoch(r.created),
);
}
println!("(* = current)");
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
VersionCmd::Restore { path, id } => {
ok_or_bail(control_request(CtlRequest::RestoreRevision {
path: path_arg(&path)?,
revision_id: id,
})?)
}
VersionCmd::Save { path, id, dest } => {
// The daemon writes the file, so it needs a path that means the same
// thing in its process as in this one.
let dest = std::path::absolute(&dest)
.with_context(|| format!("resolve {}", dest.display()))?;
ok_or_bail(control_request(CtlRequest::SaveRevisionAs {
path: path_arg(&path)?,
revision_id: id,
dest: dest.to_string_lossy().into_owned(),
})?)
}
VersionCmd::Rm { path, id } => ok_or_bail(control_request(CtlRequest::DeleteRevision {
path: path_arg(&path)?,
revision_id: id,
})?),
}
}
pub(super) fn cmd_mount(mountpoint: Option<PathBuf>) -> Result<()> {
pdfs_daemon::mount_once(mountpoint)?;
Ok(())
}
pub(super) fn cmd_pin(path: PathBuf) -> Result<()> {
match control_request(CtlRequest::Pin {
path: path_arg(&path)?,
})? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_unpin(path: PathBuf) -> Result<()> {
match control_request(CtlRequest::Unpin {
path: path_arg(&path)?,
})? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_transfers() -> Result<()> {
use pdfs_core::control::TransferDirection;
let response = control_request(CtlRequest::GetQueueStatus)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Transfers { items, jobs } if items.is_empty() && jobs.is_empty() => {
println!("Nothing in progress.")
}
CtlResponse::Transfers { items, jobs } => {
// Jobs first: they are the context for the transfers under them ("of
// 40 files", "still scanning") rather than a separate list.
for j in jobs {
let count = if j.total > 0 {
format!("{} of {}", j.done, j.total)
} else {
"—".to_string()
};
let detail = if j.detail.is_empty() {
String::new()
} else {
format!(" — {}", j.detail)
};
println!("… {:>9} {}{detail}", count, j.title);
}
for t in items {
let arrow = match t.direction {
TransferDirection::Download => "↓",
TransferDirection::Upload => "↑",
};
let pct = if t.bytes_total > 0 {
format!(
"{:.0}%",
100.0 * t.bytes_completed as f64 / t.bytes_total as f64
)
} else {
"—".to_string()
};
let speed = t.speed_bytes_sec as f64 / 1_048_576.0;
println!(
"{arrow} {:>4} {:>8} / {:>8} {speed:>6.2} MiB/s {}",
pct, t.bytes_completed, t.bytes_total, t.name
);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_pins() -> Result<()> {
let response = control_request(CtlRequest::ListPins)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Pins { pins } if pins.is_empty() => println!("No pinned files."),
CtlResponse::Pins { pins } => {
for p in pins {
println!("{}", p.path);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_ls(path: Option<PathBuf>) -> Result<()> {
let path = match path {
Some(p) => path_arg(&p)?,
None => String::new(),
};
let response = control_request(CtlRequest::ListDir { path })?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Entries { entries } if entries.is_empty() => println!("(empty)"),
CtlResponse::Entries { entries } => {
for e in entries {
let kind = if e.is_dir { "d" } else { "-" };
let pin = if e.pinned { "*" } else { " " };
println!("{kind}{pin} {:>12} {} [{}]", e.size, e.name, e.uid);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_search(query: String, limit: usize, scope: Option<PathBuf>) -> Result<()> {
let scope = scope.map(|p| path_arg(&p)).transpose()?;
match control_request(CtlRequest::Search {
query,
limit,
scope,
})? {
CtlResponse::SearchResults { hits } if hits.is_empty() => println!("(no matches)"),
CtlResponse::SearchResults { hits } => {
for h in hits {
let kind = if h.is_dir { "d" } else { "-" };
let pin = if h.pinned { "*" } else { " " };
println!("{kind}{pin} {:>12} {}", h.size, h.path);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_rename(path: PathBuf, new_name: String) -> Result<()> {
match control_request(CtlRequest::Rename {
path: path_arg(&path)?,
new_name,
})? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// Move each of `sources` into `new_parent`, one request each. A refusal names
/// its source and the rest still move; the command fails if any did not.
pub(super) fn cmd_move(sources: Vec<PathBuf>, new_parent: PathBuf) -> Result<()> {
let new_parent = path_arg(&new_parent)?;
let mut failed = 0;
for source in &sources {
let outcome = path_arg(source).and_then(|path| {
match control_request(CtlRequest::Move {
path,
new_parent: new_parent.clone(),
})? {
CtlResponse::Ok { message } => Ok(message),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
});
match outcome {
Ok(message) => println!("{message}"),
Err(e) if sources.len() == 1 => return Err(e),
Err(e) => {
eprintln!("{}: {e:#}", source.display());
failed += 1;
}
}
}
if failed > 0 {
bail!("{failed} of {} could not be moved", sources.len());
}
Ok(())
}
pub(super) fn cmd_copy(sources: Vec<PathBuf>, new_parent: PathBuf) -> Result<()> {
let new_parent = path_arg(&new_parent)?;
let mut failed = 0;
for source in &sources {
let outcome = path_arg(source).and_then(|path| {
match control_request(CtlRequest::Copy {
path,
new_parent: new_parent.clone(),
})? {
CtlResponse::Ok { message } => Ok(message),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
});
match outcome {
Ok(message) => println!("{message}"),
Err(e) if sources.len() == 1 => return Err(e),
Err(e) => {
eprintln!("{}: {e:#}", source.display());
failed += 1;
}
}
}
if failed > 0 {
bail!("{failed} of {} could not be copied", sources.len());
}
Ok(())
}
pub(super) fn cmd_du(path: PathBuf) -> Result<()> {
let response = control_request(CtlRequest::FolderSize {
path: path_arg(&path)?,
})?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::FolderSize { size, items } => {
let noun = if items == 1 { "item" } else { "items" };
println!(
"{} in {items} {noun} (on Proton Drive, trash included)",
human_bytes(size)
);
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_rm(path: PathBuf) -> Result<()> {
match control_request(CtlRequest::Delete {
path: path_arg(&path)?,
})? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_trash(by_folder: bool, folder: Option<String>) -> Result<()> {
let request = match folder {
Some(uid) => CtlRequest::ListTrashedFolder { uid },
None => CtlRequest::ListTrash,
};
let response = control_request(request)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Entries { entries } if entries.is_empty() => println!("(nothing here)"),
CtlResponse::Entries { entries } if by_folder => {
let mut groups: BTreeMap<String, Vec<&pdfs_core::control::DirEntry>> = BTreeMap::new();
for e in entries.iter().filter(|e| e.trashed_parent.is_none()) {
let folder = match e.trashed_from.as_deref() {
None => "(unknown folder)".to_string(),
Some("") => "/".to_string(),
Some(path) => format!("/{path}"),
};
groups.entry(folder).or_default().push(e);
}
for (folder, items) in groups {
println!("{folder} ({} item(s))", items.len());
for e in items {
print_trashed(e, " ");
}
}
}
CtlResponse::Entries { entries } => {
for e in &entries {
print_trashed(e, "");
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn print_trashed(e: &pdfs_core::control::DirEntry, indent: &str) {
let kind = if e.is_dir { "d" } else { "-" };
println!("{indent}{kind} {:>12} {} [{}]", e.size, e.name, e.uid);
}
pub(super) fn cmd_restore(uids: Vec<String>) -> Result<()> {
match control_request(CtlRequest::Restore { uids })? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_delete_forever(uids: Vec<String>) -> Result<()> {
confirm(&format!(
"Permanently delete {} item(s)? This cannot be undone.",
uids.len()
))?;
match control_request(CtlRequest::DeleteForever { uids })? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_empty_trash() -> Result<()> {
confirm("Permanently delete everything in the trash? This cannot be undone.")?;
match control_request(CtlRequest::EmptyTrash)? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// Drop a cached listing. `trash` and `photos` name those two listings; anything
/// else is read as a folder path, so a folder actually called "trash" is still
/// reachable as `./trash`.
pub(super) fn cmd_refresh(target: Option<String>, full: bool) -> Result<()> {
let scope = match target.as_deref() {
Some("trash") => RefreshScope::Trash,
Some("photos") => RefreshScope::Photos { full },
path => RefreshScope::Dir {
path: path.unwrap_or("").to_string(),
},
};
let photos = matches!(scope, RefreshScope::Photos { .. });
match control_request(CtlRequest::Refresh { scope })? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
if photos {
wait_for_photos_refresh()?;
}
Ok(())
}
/// How often [`wait_for_photos_refresh`] asks the daemon whether the timeline
/// refresh it started is done.
pub(super) const PHOTOS_REFRESH_POLL: std::time::Duration = std::time::Duration::from_secs(2);
/// Block until the daemon's timeline refresh has finished.
///
/// The daemon answers `Refresh { Photos }` as soon as the refresh is running,
/// because re-reading a large library takes minutes and a control reply may not.
/// `pdfs refresh photos` means "the timeline is up to date when I return", so
/// the waiting happens here, where no socket read bound applies.
pub(super) fn wait_for_photos_refresh() -> Result<()> {
loop {
std::thread::sleep(PHOTOS_REFRESH_POLL);
match control_request(CtlRequest::PhotosRefreshStatus)? {
CtlResponse::PhotosRefresh { running: true } => continue,
CtlResponse::PhotosRefresh { running: false } => {
println!("refreshed");
return Ok(());
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
}
}
pub(super) fn cmd_mkdir(parent: PathBuf, name: String) -> Result<()> {
match control_request(CtlRequest::CreateFolder {
parent: path_arg(&parent)?,
name,
})? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_upload(sources: Vec<PathBuf>, parent: PathBuf) -> Result<()> {
// The daemon reads the sources off its own (local) filesystem, so send it
// absolute, canonicalized paths.
let mut abs = Vec::with_capacity(sources.len());
for src in &sources {
let p = std::fs::canonicalize(src).with_context(|| format!("resolve {}", src.display()))?;
abs.push(
p.to_str()
.ok_or_else(|| anyhow!("path is not valid UTF-8: {}", p.display()))?
.to_owned(),
);
}
match control_request(CtlRequest::UploadPaths {
parent: path_arg(&parent)?,
sources: abs,
})? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
File diff suppressed because it is too large. Load diff
+470
View File
@@ -0,0 +1,470 @@
//! Photos: the timeline, favorites, albums, the Google Photos import and
//! re-dating.
use super::*;
pub(super) fn cmd_photos(limit: usize, offset: usize, favorites: bool) -> Result<()> {
match control_request(CtlRequest::PhotosTimeline {
offset,
limit,
kind: None,
range: None,
favorites,
not_in_album: false,
})? {
CtlResponse::Photos {
available: false, ..
} => {
println!("This account has no photos volume.")
}
CtlResponse::Photos { items, .. } if items.is_empty() => println!("No photos."),
CtlResponse::Photos { items, .. } => print_photo_page(items)?,
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// Print one page of photos as `capture-time uid thumbnail-path`.
///
/// A timeline or album reply only carries thumbnails already in the cache, so
/// the rest of the page's are pulled in one batch rather than left blank.
pub(super) fn cmd_favorite(uid: String, remove: bool) -> Result<()> {
ok_or_bail(control_request(CtlRequest::SetPhotoFavorite {
uid,
favorite: !remove,
})?)
}
pub(super) fn print_photo_page(items: Vec<pdfs_core::control::PhotoItem>) -> Result<()> {
let uids: Vec<String> = items.iter().map(|p| p.uid.clone()).collect();
let thumbs: HashMap<String, Option<String>> =
match control_request(CtlRequest::PhotoThumbs { uids })? {
CtlResponse::Thumbs { items } => items.into_iter().map(|t| (t.uid, t.path)).collect(),
_ => HashMap::new(),
};
for p in items {
let thumb = thumbs
.get(&p.uid)
.and_then(|p| p.as_deref())
.or(p.thumb_path.as_deref())
.unwrap_or("(no thumbnail)");
let fav = if p.favorite { "*" } else { " " };
println!("{fav} {} {} {thumb}", p.capture_time, p.uid);
}
Ok(())
}
pub(super) fn cmd_albums() -> Result<()> {
match control_request(CtlRequest::PhotoAlbums)? {
CtlResponse::Albums {
available: false, ..
} => println!("This account has no photos volume."),
CtlResponse::Albums { items, .. } if items.is_empty() => println!("No albums."),
CtlResponse::Albums { items, .. } => {
for album in items {
let shared = if album.shared {
" (shared with me)"
} else {
""
};
println!(
"{:>6} {} {}{shared}",
album.photo_count, album.uid, album.name
);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_new_album(name: String) -> Result<()> {
match control_request(CtlRequest::CreateAlbum { name })? {
CtlResponse::AlbumCreated { uid } => println!("{uid}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// Send an album add or remove and report it per photo; any failed photo
/// fails the command.
pub(super) fn cmd_album_change(request: CtlRequest, verb: &str) -> Result<()> {
match control_request(request)? {
CtlResponse::AlbumChanged { changed, failed } => {
println!("{} {verb}", photo_count(changed.len()));
for failure in &failed {
eprintln!("{}: {}", failure.uid, failure.message);
}
if !failed.is_empty() {
bail!("{} failed", photo_count(failed.len()));
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn photo_count(n: usize) -> String {
if n == 1 {
"1 photo".to_string()
} else {
format!("{n} photos")
}
}
pub(super) fn cmd_import_google_photos(
archives: Vec<PathBuf>,
dry_run: bool,
resume: bool,
wait: bool,
) -> Result<()> {
let request = if resume {
CtlRequest::ResumeImport
} else {
// The daemon opens the archives itself off the shared filesystem, so it
// gets absolute paths — the same arrangement `pdfs upload` uses.
let mut absolute = Vec::with_capacity(archives.len());
for archive in &archives {
let path = std::fs::canonicalize(archive)
.with_context(|| format!("resolve {}", archive.display()))?;
absolute.push(
path.to_str()
.ok_or_else(|| anyhow!("path is not valid UTF-8: {}", path.display()))?
.to_owned(),
);
}
CtlRequest::ImportTakeout {
archives: absolute,
dry_run,
}
};
match control_request(request)? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
if !wait {
println!("Run `pdfs import-status` to follow it.");
return Ok(());
}
// Poll rather than stream: the control protocol is request/response, and an
// import runs for hours — a held-open socket would be the only long-lived
// connection the daemon has. A line is printed when the step changes and
// every few percent of it, not on every poll.
let mut last_line = String::new();
let mut last_printed = std::time::Instant::now();
loop {
std::thread::sleep(std::time::Duration::from_secs(2));
match control_request(CtlRequest::ImportStatus)? {
CtlResponse::ImportStatus {
running: true,
progress,
..
} => {
let line = progress.as_ref().map(progress_line).unwrap_or_default();
let step_changed = line.split(':').next() != last_line.split(':').next();
if !line.is_empty()
&& line != last_line
&& (step_changed || last_printed.elapsed().as_secs() >= 30)
{
println!("{line}");
last_line = line;
last_printed = std::time::Instant::now();
}
}
CtlResponse::ImportStatus {
summary, resumable, ..
} => {
print_import_summary(summary.as_ref(), &resumable);
return import_outcome(summary.as_ref());
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
}
}
/// One line saying where a running import is.
pub(super) fn progress_line(progress: &pdfs_core::control::ImportProgress) -> String {
use pdfs_core::control::ImportPhase;
let step = match progress.phase {
ImportPhase::Scanning => "Reading archives",
ImportPhase::Checking => "Checking for photos already on Proton",
ImportPhase::Uploading => "Uploading",
ImportPhase::Albums => "Filing photos into albums",
};
match (progress.total, &progress.current) {
(0, _) => format!("{step}…"),
(total, Some(name)) => format!("{step}: {} of {total} ({name})", progress.done),
(total, None) => format!("{step}: {} of {total}", progress.done),
}
}
/// How an import `--wait` followed ended, as the exit status: an error unless
/// it did everything it set out to do, so a script can tell.
pub(super) fn import_outcome(summary: Option<&pdfs_core::control::ImportSummary>) -> Result<()> {
let Some(summary) = summary else {
bail!("the import ended without a result; the service may have restarted");
};
if let Some(error) = &summary.error {
bail!("the import failed: {error}");
}
if summary.interrupted {
bail!("the import was interrupted; run `pdfs import-google-photos --resume` to continue");
}
if summary.cancelled {
bail!("the import was cancelled");
}
if summary.failed > 0 || !summary.unreadable_archives.is_empty() {
bail!(
"the import finished, but {} photo(s) and {} archive(s) failed",
summary.failed,
summary.unreadable_archives.len()
);
}
Ok(())
}
pub(super) fn cmd_redate_photos(
dry_run: bool,
limit: Option<usize>,
from: Option<String>,
to: Option<String>,
wait: bool,
) -> Result<()> {
let range = match (from.as_deref(), to.as_deref()) {
(None, None) => None,
(from, to) => Some((
from.map(parse_day).transpose()?.unwrap_or(i64::MIN),
to.map(parse_day).transpose()?.unwrap_or(i64::MAX),
)),
};
match control_request(CtlRequest::RedatePhotos {
dry_run,
limit,
range,
})? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
if !wait {
println!("Run `pdfs redate-status` to follow it.");
return Ok(());
}
// Polled for the same reason the import is: request/response protocol, and a
// run over a whole library is a download plus an upload per photo.
loop {
std::thread::sleep(std::time::Duration::from_secs(2));
match control_request(CtlRequest::RedateStatus)? {
CtlResponse::RedateStatus { running: true, .. } => continue,
CtlResponse::RedateStatus { summary, .. } => {
print_redate_summary(summary.as_ref());
return finished_run(
"the re-date",
summary.map(|s| (s.failed, s.cancelled, s.error)),
);
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
}
}
/// How a run `--wait` followed ended, as the exit status: an error when it
/// failed, was cancelled, or left photos failed, so a script can tell.
/// `outcome` is `(failed, cancelled, error)`; `None` when the daemon has no
/// result, which happens when it restarted during the run.
pub(super) fn finished_run(
what: &str,
outcome: Option<(usize, bool, Option<String>)>,
) -> Result<()> {
match outcome {
None => bail!("{what} ended without a result; the service may have restarted"),
Some((_, _, Some(error))) => bail!("{what} failed: {error}"),
Some((_, true, None)) => bail!("{what} was cancelled"),
Some((failed, false, None)) if failed > 0 => {
bail!("{what} finished, but {failed} photo(s) failed")
}
Some(_) => Ok(()),
}
}
/// A `YYYY-MM-DD` day as epoch seconds at UTC midnight. Reuses the Takeout
/// scanner's date reader, which already accepts exactly this spelling.
pub(super) fn parse_day(day: &str) -> Result<i64> {
pdfs_core::takeout::capture_time_from_name(day)
.ok_or_else(|| anyhow!("not a date (expected YYYY-MM-DD): {day}"))
}
pub(super) fn cmd_redate_status() -> Result<()> {
match control_request(CtlRequest::RedateStatus)? {
CtlResponse::RedateStatus { running, summary } => {
if running {
println!("Re-date running. `pdfs transfers` shows its progress.");
}
print_redate_summary(summary.as_ref());
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_cancel_redate() -> Result<()> {
match control_request(CtlRequest::CancelRedate)? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn print_redate_summary(summary: Option<&pdfs_core::control::RedateSummary>) {
let Some(summary) = summary else {
println!("No re-date has run yet.");
return;
};
if let Some(error) = &summary.error {
println!("Failed : {error}");
return;
}
println!("Photos examined : {}", summary.examined);
println!("Mis-dated : {}", summary.candidates);
if summary.dry_run {
println!("(dry run — nothing was uploaded or trashed)");
} else {
println!("Re-dated : {}", summary.redated);
if summary.album_links > 0 {
println!("Albums refiled : {}", summary.album_links);
}
if summary.failed > 0 {
println!("Failed : {}", summary.failed);
}
if summary.bytes > 0 {
println!("Uploaded bytes : {}", summary.bytes);
}
}
for (name, stored, wanted) in &summary.samples {
// Epoch seconds, as `pdfs photos` prints capture times.
println!(" {name}: {stored} -> {wanted}");
}
if summary.candidates > summary.samples.len() {
println!(
" … and {} more",
summary.candidates - summary.samples.len()
);
}
if summary.cancelled {
println!("Run was cancelled before it finished.");
}
}
pub(super) fn cmd_import_status() -> Result<()> {
match control_request(CtlRequest::ImportStatus)? {
CtlResponse::ImportStatus {
running,
summary,
progress,
resumable,
} => {
if running {
match progress.as_ref() {
Some(progress) => println!("Import running. {}", progress_line(progress)),
None => println!("Import running."),
}
}
print_import_summary(summary.as_ref(), &resumable);
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_cancel_import() -> Result<()> {
match control_request(CtlRequest::CancelImport)? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn print_import_summary(
summary: Option<&pdfs_core::control::ImportSummary>,
resumable: &[String],
) {
let Some(summary) = summary else {
println!("No import has run yet.");
return;
};
if summary.dry_run {
println!("Scan only; nothing was uploaded.");
}
if let Some(error) = &summary.error {
println!("Stopped by : {error}");
}
println!("Photos in export : {}", summary.found);
if summary.dry_run {
println!("Would upload : {}", summary.to_upload);
println!("Bytes to upload : {}", summary.to_upload_bytes);
} else {
println!("Uploaded : {}", summary.uploaded);
}
println!("Already on Proton: {}", summary.duplicates);
if summary.live_photos > 0 {
println!("Live photos : {}", summary.live_photos);
}
if summary.skipped_trashed > 0 {
println!("Skipped (trash) : {}", summary.skipped_trashed);
}
if summary.albums_created > 0 || summary.album_links > 0 {
println!(
"Albums : {} created, {} photos filed",
summary.albums_created, summary.album_links
);
}
if summary.failed > 0 {
println!("Failed : {}", summary.failed);
}
for archive in &summary.unreadable_archives {
println!("Unreadable : {archive}");
}
if summary.bytes > 0 {
println!("Uploaded bytes : {}", summary.bytes);
}
if summary.interrupted {
println!("The service stopped before the import finished.");
} else if summary.cancelled {
println!("Import was cancelled before it finished.");
}
if !resumable.is_empty() {
println!("Run `pdfs import-google-photos --resume` to continue it.");
}
}
pub(super) fn cmd_album(uid: String, limit: usize, offset: usize) -> Result<()> {
match control_request(CtlRequest::AlbumPhotos { uid, offset, limit })? {
CtlResponse::Photos { items, .. } if items.is_empty() => println!("No photos."),
CtlResponse::Photos { items, .. } => print_photo_page(items)?,
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_open_photo(uid: String) -> Result<()> {
match control_request(CtlRequest::OpenPhoto { uid })? {
CtlResponse::FilePath { path } => println!("{path}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
+389
View File
@@ -0,0 +1,389 @@
//! Sharing: members and roles, public links, what is shared with you,
//! invitations and bookmarks.
use super::*;
pub(super) fn cmd_members(path: PathBuf) -> Result<()> {
let response = control_request(CtlRequest::ListShare {
path: path_arg(&path)?,
})?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Share { entries, link } => {
if entries.is_empty() {
println!("No members or pending invitations.");
}
for e in entries {
let kind = match e.kind {
ShareEntryKind::Member => "member",
ShareEntryKind::ProtonInvite => "invited (proton)",
ShareEntryKind::ExternalInvite => "invited (external)",
};
println!("{:<18} {:<8} {} [{}]", kind, e.role, e.email, e.id);
}
match link {
Some(l) => {
let url = l.url.as_deref().unwrap_or("(url hidden)");
let pw = if l.has_password { " +password" } else { "" };
let expiry = l
.expires
.map(|at| format!(", expires {}", format_epoch_utc(at)))
.unwrap_or_default();
println!("public link ({}{pw}{expiry}): {url} [{}]", l.role, l.id);
}
None => println!("public link: none"),
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_share_role(
path: PathBuf,
id: String,
kind: ShareKindArg,
role: String,
) -> Result<()> {
ok_or_bail(control_request(CtlRequest::UpdateShareRole {
path: path_arg(&path)?,
id,
kind: kind.to_kind(),
role,
})?)
}
pub(super) fn cmd_unshare(
path: PathBuf,
id: Option<String>,
kind: Option<ShareKindArg>,
) -> Result<()> {
let path = path_arg(&path)?;
let request = match (id, kind) {
(Some(id), Some(kind)) => CtlRequest::RemoveShareEntry {
path,
id,
kind: kind.to_kind(),
},
_ => CtlRequest::StopSharing { path },
};
ok_or_bail(control_request(request)?)
}
pub(super) fn cmd_public_link(action: PublicLinkCmd) -> Result<()> {
match action {
PublicLinkCmd::Create {
path,
role,
password,
expires,
} => match control_request(CtlRequest::CreatePublicLink {
path: path_arg(&path)?,
role,
password,
expires,
})? {
response if emit_json(&response)? => {}
CtlResponse::PublicLink { link } => {
println!("{}", link.url.as_deref().unwrap_or("(no url returned)"));
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
},
PublicLinkCmd::Update {
path,
id,
role,
password,
no_password,
expires,
no_expiry,
} => match control_request(CtlRequest::UpdatePublicLink {
path: path_arg(&path)?,
id,
role,
password: link_change(password, no_password),
expires: link_change(expires, no_expiry),
})? {
response if emit_json(&response)? => {}
CtlResponse::PublicLink { link } => {
println!("{}", link.url.as_deref().unwrap_or("(no url returned)"));
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
},
PublicLinkCmd::Remove { path, id } => {
ok_or_bail(control_request(CtlRequest::RemovePublicLink {
path: path_arg(&path)?,
id,
})?)?
}
}
Ok(())
}
/// A `--x VALUE` / `--no-x` flag pair as one link option change.
pub(super) fn link_change<T>(value: Option<T>, remove: bool) -> LinkChange<T> {
match (value, remove) {
(Some(value), _) => LinkChange::Set(value),
(None, true) => LinkChange::Remove,
(None, false) => LinkChange::Keep,
}
}
pub(super) fn cmd_shared() -> Result<()> {
match control_request(CtlRequest::ListSharedByMe)? {
CtlResponse::SharedByMe { items } if items.is_empty() => {
println!("You haven't shared anything.")
}
CtlResponse::SharedByMe { items } => {
for it in items {
let kind = if it.is_dir { "d" } else { "-" };
let mut tags = Vec::new();
if it.member_count > 0 {
tags.push(format!("{} member(s)", it.member_count));
}
if it.invite_count > 0 {
tags.push(format!("{} pending", it.invite_count));
}
if let Some(link) = &it.link {
tags.push(match &link.url {
Some(url) => format!("link: {url}"),
None => "link".to_string(),
});
}
let tags = if tags.is_empty() {
String::new()
} else {
format!(" ({})", tags.join(", "))
};
println!("{kind} {}{tags} [{}]", it.name, it.uid);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// List what is shared with me, or — given a folder uid — that folder's
/// children. Shared items have no path in the mount, so a uid is the only handle
/// there is: every row prints one, and it is what the next level down (or
/// `shared-get`) is addressed with.
pub(super) fn cmd_shared_with_me(uid: Option<String>) -> Result<()> {
let request = match uid {
Some(uid) => CtlRequest::ListSharedFolder { uid },
None => CtlRequest::ListSharedWithMe,
};
let response = control_request(request)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Entries { entries } if entries.is_empty() => {
println!("Nothing shared with you.")
}
CtlResponse::Entries { entries } => {
for e in entries {
let kind = if e.is_dir { "d" } else { "-" };
// My role decides whether this is writable at all, so it is
// printed whenever the API reported one; an empty role prints
// nothing rather than a guess.
let role = if e.role.is_empty() {
String::new()
} else {
format!(" ({})", e.role)
};
println!("{kind} {:>12} {}{role} [{}]", e.size, e.name, e.uid);
if let Some(line) = shared_by_line(&e) {
println!("{:>15}{line}", "");
}
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// Who shared an entry with me, and when, as a line printed under it — `None`
/// when the invitation said nothing (owned content, or a node inside a shared
/// folder rather than its root). An inviter whose signature did not verify is
/// said to be claimed, not stated: the name may be forged.
pub(super) fn shared_by_line(entry: &pdfs_core::control::DirEntry) -> Option<String> {
if entry.shared_by.is_empty() {
return None;
}
let mut line = format!("shared by {}", entry.shared_by);
if entry.shared_at > 0 {
line.push_str(&format!(" at {}", format_epoch_utc(entry.shared_at)));
}
if entry.shared_by_unverified {
line.push_str(" WARNING: invitation signature did not verify; the sender may be forged");
}
Some(line)
}
/// Download a file shared with me. The daemon puts the plaintext in its content
/// cache and replies with that path; with a `dest` we copy it out, so the caller
/// gets a file it owns rather than one the cache may later evict.
pub(super) fn cmd_shared_get(uid: String, dest: Option<PathBuf>) -> Result<()> {
let path = match control_request(CtlRequest::OpenSharedFile { uid })? {
CtlResponse::FilePath { path } => PathBuf::from(path),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
};
match dest {
Some(dest) => {
std::fs::copy(&path, &dest).with_context(|| format!("writing {}", dest.display()))?;
println!("{}", dest.display());
}
None => println!("{}", path.display()),
}
Ok(())
}
pub(super) fn cmd_quota() -> Result<()> {
let response = control_request(CtlRequest::AccountQuota)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::AccountQuota {
max_space,
used_space,
} => {
let used = used_space.max(0) as u64;
if max_space > 0 {
let total = max_space as u64;
let pct = (used as f64 / total as f64 * 100.0).round() as u64;
println!(
"{} of {} used ({pct}%)",
human_bytes(used),
human_bytes(total)
);
} else {
println!("{} used", human_bytes(used));
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_activity(limit: usize) -> Result<()> {
let response = control_request(CtlRequest::ListActivity { limit })?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Activity { items } if items.is_empty() => println!("No recent activity."),
CtlResponse::Activity { items } => {
for a in items {
let when = format_epoch(a.time);
let verb = activity_verb(a.kind);
let mark = if a.ok { " " } else { "!" };
let detail = if a.detail.is_empty() {
String::new()
} else {
format!(" {}", a.detail)
};
println!("{mark} {when} {verb:<8} {}{detail}", a.target);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// A short verb for an activity kind, for the CLI's one-line-per-event feed.
pub(super) fn activity_verb(kind: pdfs_core::control::ActivityKind) -> &'static str {
use pdfs_core::control::ActivityKind::*;
match kind {
Upload => "upload",
Download => "download",
Sync => "sync",
Rename => "rename",
Move => "move",
Copy => "copy",
CreateFolder => "mkdir",
Trash => "trash",
Restore => "restore",
DeleteForever => "delete",
EmptyTrash => "empty",
Share => "share",
PublicLink => "link",
Unshare => "unshare",
Conflict => "conflict",
}
}
/// The `synced:` column of `sync list` and `devices list`: when the last pass
/// finished, or `never`. The daemon reports 0 for a folder that never synced.
pub(super) fn last_synced(secs: Option<i64>) -> String {
match secs {
Some(secs) if secs > 0 => format_epoch(secs),
_ => "never".to_string(),
}
}
pub(super) fn cmd_leave(uid: String) -> Result<()> {
ok_or_bail(control_request(CtlRequest::LeaveShared { uid })?)
}
pub(super) fn cmd_invitations(action: InvitationCmd) -> Result<()> {
match action {
InvitationCmd::List => match control_request(CtlRequest::ListInvitations)? {
CtlResponse::Invitations { items } if items.is_empty() => {
println!("No pending invitations.")
}
CtlResponse::Invitations { items } => {
for i in items {
let kind = if i.is_dir { "folder" } else { "file" };
let name = i.name.as_deref().unwrap_or("(name hidden)");
println!("{} shared {kind} \"{name}\" [{}]", i.inviter_email, i.id);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
},
InvitationCmd::Accept { id } => {
ok_or_bail(control_request(CtlRequest::AcceptInvitation { id })?)?
}
InvitationCmd::Reject { id } => {
ok_or_bail(control_request(CtlRequest::RejectInvitation { id })?)?
}
}
Ok(())
}
pub(super) fn cmd_bookmarks(action: BookmarkCmd) -> Result<()> {
match action {
BookmarkCmd::List => match control_request(CtlRequest::ListBookmarks)? {
CtlResponse::Bookmarks { items } if items.is_empty() => println!("No bookmarks."),
CtlResponse::Bookmarks { items } => {
for b in items {
let name = b.name.as_deref().unwrap_or("(name hidden)");
println!("{name} {} [{}]", b.url, b.token);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
},
BookmarkCmd::Add { url, password } => {
ok_or_bail(control_request(CtlRequest::CreateBookmark {
url,
password,
})?)?
}
BookmarkCmd::Rm { token } => {
ok_or_bail(control_request(CtlRequest::DeleteBookmark { token })?)?
}
}
Ok(())
}
+482
View File
@@ -0,0 +1,482 @@
//! What the daemon reports: status, locations, devices, diagnostics and the
//! content cache.
use super::*;
pub(super) fn cmd_devices(action: DeviceCmd) -> Result<()> {
match action {
DeviceCmd::List => {
let response = control_request(CtlRequest::ListDevices)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Devices { items } if items.is_empty() => println!("No devices."),
CtlResponse::Devices { items } => {
for d in items {
let sync = last_synced(d.last_sync);
let tag = match (d.adopted, d.this_device) {
(true, _) => " *adopted*",
(false, true) => " *this machine*",
_ => "",
};
println!(
"{} {} (synced: {sync}) [{}]{tag}",
d.device_type, d.name, d.uid
);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
}
DeviceCmd::Rename { uid, name } => {
ok_or_bail(control_request(CtlRequest::RenameDevice { uid, name })?)?
}
DeviceCmd::Rm { uid } => ok_or_bail(control_request(CtlRequest::DeleteDevice { uid })?)?,
DeviceCmd::Adopt { uid, clear } => {
if uid.is_none() && !clear {
bail!("give a device uid (see `pdfs devices list`), or --clear");
}
let uid = if clear { None } else { uid };
ok_or_bail(control_request(CtlRequest::AdoptDevice { uid })?)?
}
DeviceCmd::Join { uid, yes } => {
if !yes {
println!(
"This computer syncs into that device alongside it. Its folders are kept\n\
in step on both computers: an edit or a deletion on one reaches the other.\n\
New synced folders here go under that device too. Folders already synced\n\
here stay where they are."
);
confirm("Sync with it?")?;
}
let response = control_request(CtlRequest::AdoptDevice { uid: Some(uid) })?;
// A script gets the one reply and runs `sync restore` itself.
if emit_json(&response)? {
return Ok(());
}
ok_or_bail(response)?;
// The device is this machine's now, so the plain restore offers its
// folders.
cmd_sync_restore(yes, None)?
}
DeviceCmd::Migrate { uid, yes } => {
if !yes {
println!(
"Every folder that device backs up moves into this computer's backup.\n\
The device stays registered, without those folders. Stop Proton Drive\n\
on that computer first, or it sees its folders disappear."
);
confirm("Move them here?")?;
}
let response = control_request(CtlRequest::MigrateDevice { uid })?;
// A script gets the one reply and runs `sync restore` itself.
if emit_json(&response)? {
return Ok(());
}
ok_or_bail(response)?;
// The folders are this device's now, so the plain restore offers them.
cmd_sync_restore(yes, None)?
}
}
Ok(())
}
pub(super) fn cmd_status() -> Result<()> {
// `status` is the one query that merges two sources — the local keyring and
// the daemon — so its JSON is composed here rather than being a daemon reply
// passed through. A script asking for status wants both halves in one
// object, including the "logged in but no daemon" case that has no reply at
// all.
if json_enabled() {
let session = match auth::load() {
Ok(s) => Some(s),
Err(pdfs_core::Error::NotLoggedIn) => None,
Err(e) => return Err(e.into()),
};
let mount = match control_request(CtlRequest::Status) {
Ok(r @ CtlResponse::Status { .. }) => response_payload(&r)?,
_ => serde_json::Value::Null,
};
let out = serde_json::json!({
"logged_in": session.is_some(),
"username": session.as_ref().map(|s| s.username.clone()),
"user_id": session.as_ref().map(|s| s.user_id.clone()),
"scopes": session.as_ref().map(|s| s.scopes.clone()),
"keys": session.as_ref().map(|_| key_state_name()),
"mount": mount,
});
println!("{}", serde_json::to_string_pretty(&out)?);
return Ok(());
}
match auth::load() {
Ok(s) => {
println!("Logged in as {} (user {})", s.username, s.user_id);
println!("Scopes: {}", s.scopes.join(", "));
match key_state_name() {
"locked" => println!("Keys: locked — run `pdfs unlock`"),
"session" => println!("Keys: unlocked for this login session"),
_ => {}
}
}
Err(pdfs_core::Error::NotLoggedIn) => {
println!("Not logged in. Run `pdfs login`.");
return Ok(());
}
Err(e) => return Err(e.into()),
}
// If a mount daemon is running, report live status from its control socket.
match control_request(CtlRequest::Status) {
Ok(CtlResponse::Status {
mountpoint,
pinned,
online,
pending_uploads,
pending_changes,
parked_uploads,
failing_ops,
failing_error,
staged_bytes,
staged_oldest_secs,
paused,
paused_until,
session_expired,
tokens_unsaved,
version,
..
}) => {
let state = match (online, paused) {
_ if session_expired => ", session expired: run `pdfs login`",
(_, true) => ", sync paused",
(false, false) => ", offline",
(true, false) => "",
};
let queued = match pending_summary(pending_uploads, pending_changes) {
Some(s) => format!(", {s}"),
None => String::new(),
};
println!("Mounted at {mountpoint} ({pinned} pinned{state}{queued})");
// Everything below is a queue that is not making progress on its
// own. Printed only when it exists, because in the ordinary case
// there is nothing to say.
if staged_bytes > 0 {
println!(
"Staged {} not yet uploaded (oldest {})",
human_bytes(staged_bytes),
human_age(staged_oldest_secs),
);
}
if let Some(until) = paused_until {
let left = until.saturating_sub(unix_now()).max(0) as u64;
println!("Paused sync resumes in {}", human_age(left.max(1)));
}
if parked_uploads > 0 {
println!("Parked {parked_uploads} upload(s) waiting for a final filename");
}
if failing_ops > 0 {
println!(
"Stuck {failing_ops} queued operation(s) keep failing: {}",
failing_error.as_deref().unwrap_or("no error recorded"),
);
}
if tokens_unsaved {
println!(
"Keyring refuses the refreshed sign-in; unlock it, or a reboot needs `pdfs login`"
);
}
if daemon_outdated(&version) {
println!("Daemon {}", outdated_daemon_note(&version));
}
}
Ok(other) => println!("Mount: unexpected response {other:?}"),
Err(_) => println!("Mount: not running."),
}
Ok(())
}
/// What `pdfs status` and `pdfs diagnose` say about a daemon still running
/// an older release than this CLI.
pub(super) fn outdated_daemon_note(version: &str) -> String {
let running = if version.is_empty() {
"an older release".to_string()
} else {
version.to_string()
};
format!(
"still runs {running}, this is {}; run `systemctl --user restart proton-drive` to finish the update",
env!("CARGO_PKG_VERSION"),
)
}
pub(super) fn cmd_locations() -> Result<()> {
let response = control_request(CtlRequest::ListLocations)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Locations { items } if items.is_empty() => {
println!("No Proton Drive locations.");
}
CtlResponse::Locations { items } => {
for location in items {
let kind = match &location.kind {
MountKind::MyFiles => "My Files".to_string(),
MountKind::Device { sync_folder_id } => {
format!("Device folder {sync_folder_id}")
}
MountKind::Attached { sync_folder_id } => {
format!("My files mirror {sync_folder_id}")
}
MountKind::Shared { .. } => "Shared folder".to_string(),
};
let mode = match location.pending_mode {
Some(pending) => format!("{} -> {pending}", location.mode),
None => location.mode.to_string(),
};
let mounted = if location.mounted {
"mounted"
} else {
"not mounted"
};
println!(
"{kind}: {} ({mode}, {}, {}, {mounted})",
location.local_path, location.access, location.state
);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// The sync engine's line in `pdfs diagnostics`: whether it runs, and which
/// folder's pass it is on.
pub(super) fn sync_engine_line(sync: &pdfs_core::control::SyncEngineState) -> String {
let mut line = match (sync.running, sync.pass_folder) {
(false, _) => "STOPPED; synced folders do not sync until the daemon restarts".to_string(),
(true, None) => "idle".to_string(),
(true, Some(folder)) => format!(
"pass on folder {folder} for {}, last progress {} ago",
human_secs(sync.pass_age_secs),
human_secs(sync.pass_idle_secs),
),
};
if sync.panics > 0 {
line.push_str(&format!("; {} pass(es) panicked", sync.panics));
}
line
}
pub(super) fn cmd_diagnostics() -> Result<()> {
let response = control_request(CtlRequest::Diagnostics)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Diagnostics { diagnostics: d } => {
println!(
"uptime {} rss {} pending ops {}",
human_secs(d.uptime_secs),
human_bytes(d.rss_bytes),
d.pending_ops
.map_or_else(|| "unknown (database busy)".to_owned(), |n| n.to_string()),
);
println!(
"control handlers {}/{}",
d.control_handlers, d.control_handler_limit,
);
println!(
"queued: meta {} (done {}), transfer {} (done {})",
d.meta_queued, d.meta_completed, d.transfer_queued, d.transfer_completed,
);
println!("workers:");
for worker in &d.workers {
let what = if worker.busy {
worker.label.as_str()
} else {
"idle"
};
println!(
" {:<20} {:<12} {}",
worker.name,
what,
human_secs(worker.age_secs)
);
}
if !d.services.is_empty() {
let ended: Vec<&str> = d
.services
.iter()
.filter(|service| !service.running)
.map(|service| service.name.as_str())
.collect();
if ended.is_empty() {
println!("services: {} running", d.services.len());
} else {
println!(
"services: {} running, ended: {}",
d.services.len() - ended.len(),
ended.join(", ")
);
}
}
if !d.jobs.is_empty() {
let jobs: Vec<String> = d
.jobs
.iter()
.map(|job| format!("{} ({})", job.name, human_secs(job.age_secs)))
.collect();
println!("jobs: {}", jobs.join(", "));
}
if let Some(sync) = &d.sync {
println!("sync engine: {}", sync_engine_line(sync));
for trace in &sync.traces {
let how = if trace.ended.is_empty() {
"running"
} else {
trace.ended.as_str()
};
println!(
" folder {} pass ({how}, {}): {trace}",
trace.folder_id,
human_secs(trace.elapsed_ms / 1000),
);
}
}
if !d.drive_calls.is_empty() {
println!("calls to Drive since start:");
for call in &d.drive_calls {
println!(
" {:<38} {:>7} calls {:>5} failed {:>9} ms total {:>7} ms longest",
call.call, call.count, call.errors, call.total_ms, call.longest_ms,
);
}
}
if d.inflight.is_empty() {
println!("in-flight requests: none");
} else {
println!("in-flight requests (oldest first):");
for request in &d.inflight {
println!(" {:<20} {}", request.kind, human_secs(request.age_secs));
}
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_cache(action: CacheCmd) -> Result<()> {
match action {
CacheCmd::Inspect { deep } => cmd_cache_inspect(deep),
CacheCmd::Vacuum => match control_request(CtlRequest::CacheVacuum)? {
CtlResponse::Ok { message } => {
println!("{message}");
Ok(())
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
},
CacheCmd::Clear => match control_request(CtlRequest::PurgeCache)? {
CtlResponse::Ok { message } => {
println!("{message}");
Ok(())
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
},
}
}
/// Ask for a deep integrity check and wait for it to finish.
///
/// The daemon answers the request immediately and runs the check on a thread —
/// it holds the single database connection for as long as it takes, which would
/// otherwise stall the mount — so a caller that needs the verdict polls for it.
/// `pdfs doctor` is that caller: it is a diagnostic the user is watching, so
/// waiting is right, and the bound is generous enough for a large database
/// without hanging forever if the daemon never finishes.
pub(super) fn await_integrity_check() -> Result<CtlResponse> {
const POLL: std::time::Duration = std::time::Duration::from_secs(1);
const GIVE_UP_AFTER: std::time::Duration = std::time::Duration::from_secs(120);
let started = std::time::Instant::now();
loop {
let response = control_request(CtlRequest::CacheInspect { deep: true })?;
match &response {
CtlResponse::CacheReport {
integrity_running: true,
integrity_checked: false,
..
} if started.elapsed() < GIVE_UP_AFTER => std::thread::sleep(POLL),
_ => return Ok(response),
}
}
}
pub(super) fn cmd_cache_inspect(deep: bool) -> Result<()> {
let response = control_request(CtlRequest::CacheInspect { deep })?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::CacheReport {
schema_version,
db_bytes,
db_reclaimable_bytes,
tables,
cache_used,
cache_budget,
integrity_problems,
integrity_checked,
integrity_running,
} => {
println!(
"Database schema v{schema_version}, {}",
human_bytes(db_bytes)
);
if db_reclaimable_bytes > 0 {
println!(
" {} reclaimable — run `pdfs cache vacuum`",
human_bytes(db_reclaimable_bytes)
);
}
let budget = if cache_budget == 0 {
"unlimited".to_string()
} else {
human_bytes(cache_budget)
};
println!("Content {} cached of {budget}", human_bytes(cache_used));
println!("\nRows");
for (name, count) in tables {
println!(" {name:<16} {count:>10}");
}
if integrity_checked {
if integrity_problems.is_empty() {
println!("\nIntegrity ok");
} else {
println!("\nIntegrity {} problem(s):", integrity_problems.len());
for problem in integrity_problems {
println!(" {problem}");
}
}
} else if integrity_running {
// The daemon runs the check on a thread rather than holding its
// only database connection for the length of it, so the answer
// belongs to a later request.
println!("\nIntegrity checking in the background — run this again for the result");
} else {
println!("\nIntegrity not checked (pass --deep)");
}
Ok(())
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
}
+780
View File
@@ -0,0 +1,780 @@
//! `pdfs sync`: synced folders, their queue, issues, limits and ignore rules,
//! and `pdfs conflicts`.
use super::*;
pub(super) fn cmd_sync(action: SyncCmd) -> Result<()> {
match action {
SyncCmd::Add { path } => {
let abs = std::fs::canonicalize(&path)
.with_context(|| format!("resolve {}", path.display()))?;
let local_path = abs
.to_str()
.ok_or_else(|| anyhow!("path is not valid UTF-8"))?
.to_string();
ok_or_bail(control_request(CtlRequest::AddSyncFolder { local_path })?)?
}
SyncCmd::Attach { path, to } => {
let abs = std::fs::canonicalize(&path)
.with_context(|| format!("resolve {}", path.display()))?;
let local_path = abs
.to_str()
.ok_or_else(|| anyhow!("path is not valid UTF-8"))?
.to_owned();
let remote_path = to
.to_str()
.ok_or_else(|| anyhow!("remote path is not valid UTF-8"))?
.to_owned();
ok_or_bail(control_request(CtlRequest::AttachSyncFolder {
local_path,
remote_path,
})?)?
}
SyncCmd::List => {
let response = control_request(CtlRequest::ListSyncFolders)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::SyncFolders { items } if items.is_empty() => {
println!("No synced folders.")
}
CtlResponse::SyncFolders { items } => {
for f in items {
let sync = last_synced(Some(f.last_sync));
// A queued switch is reported as the mode the folder is moving
// to, so `sync list` never reads as if the request was dropped.
let mode = match &f.pending_mode {
Some(pending) => format!("{} → {pending}", f.mode),
None => f.mode.clone(),
};
let mode = match f.paused {
true => format!("{mode}, paused"),
false => mode,
};
println!(
"[{}] {} ({mode}, {}, synced: {sync})",
f.id, f.local_path, f.state
);
// A pass in flight says what it is doing, indented under it.
if let Some(p) = &f.progress {
match p.phase {
SyncPhase::Scanning if p.total == 0 && p.done == 0 => {
println!(" scanning…")
}
// A first pass has no estimate yet; the count alone
// shows a long first scan is moving.
SyncPhase::Scanning if p.total == 0 => {
println!(" scanning: {} checked", p.done)
}
SyncPhase::Scanning => {
println!(
" scanning: {} of {}",
p.done,
p.total.max(p.done)
)
}
SyncPhase::Applying => println!(
" {} of {} {}",
p.done + 1,
p.total.max(p.done + 1),
p.current
),
}
}
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
}
SyncCmd::Rm { id, delete_remote } => {
ok_or_bail(control_request(CtlRequest::RemoveSyncFolder {
id,
delete_remote,
})?)?
}
SyncCmd::Now { id } => ok_or_bail(control_request(CtlRequest::SyncNow { id })?)?,
SyncCmd::Reset { id } => ok_or_bail(control_request(CtlRequest::ResetSyncFolder { id })?)?,
SyncCmd::Pause {
folder: Some(id), ..
} => ok_or_bail(control_request(CtlRequest::SetSyncFolderPaused {
id,
paused: true,
})?)?,
SyncCmd::Resume { folder: Some(id) } => {
ok_or_bail(control_request(CtlRequest::SetSyncFolderPaused {
id,
paused: false,
})?)?
}
SyncCmd::Pause {
duration,
folder: None,
} => {
let until = duration.map(|secs| unix_now().saturating_add(secs as i64));
ok_or_bail(control_request(CtlRequest::SetSyncPaused {
paused: true,
until,
})?)?
}
SyncCmd::Queue => return cmd_sync_queue(),
SyncCmd::Flush { timeout } => return cmd_sync_flush(timeout),
SyncCmd::Issues => return cmd_sync_issues(),
SyncCmd::Export { id, dest } => return cmd_sync_export(id, &dest),
SyncCmd::Limit { up, down } => return cmd_sync_limit(up, down),
SyncCmd::Ignore { action } => return cmd_sync_ignore(action),
SyncCmd::Discard { id, yes } => {
if !yes {
confirm(&format!(
"Discard queued change {id} and undo it here? Content not exported is lost."
))?;
}
ok_or_bail(control_request(CtlRequest::DiscardPendingOp { id })?)?
}
SyncCmd::Retry { id } => ok_or_bail(control_request(CtlRequest::RetryPendingOp { id })?)?,
SyncCmd::Resume { folder: None } => {
ok_or_bail(control_request(CtlRequest::SetSyncPaused {
paused: false,
until: None,
})?)?
}
SyncCmd::Mode { id, mode } => {
ok_or_bail(control_request(CtlRequest::SetSyncFolderMode { id, mode })?)?
}
SyncCmd::Restore { yes, device } => return cmd_sync_restore(yes, device),
}
Ok(())
}
/// `pdfs conflicts`: list conflict copies, or resolve one.
pub(super) fn cmd_conflicts(action: Option<ConflictCmd>) -> Result<()> {
if let Some(ConflictCmd::Resolve { path, keep, name }) = action {
let keep = match keep.as_str() {
"original" => ConflictKeep::Original,
"copy" => ConflictKeep::Copy,
_ => ConflictKeep::Both {
name: name.unwrap_or_default(),
},
};
let path = path_arg(&path)?;
return ok_or_bail(control_request(CtlRequest::ResolveConflict { path, keep })?);
}
let response = control_request(CtlRequest::ListConflicts)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Conflicts { items } if items.is_empty() => println!("No conflicts."),
CtlResponse::Conflicts { items } => {
for c in items {
println!("{}", c.path);
let verdict = match (c.original_exists, c.identical) {
(false, _) => "original is gone".to_string(),
(true, true) => format!("identical to {}", c.original_path),
(true, false) => format!(
"differs from {} ({} vs {})",
c.original_path,
human_bytes(c.size),
human_bytes(c.original_size.unwrap_or_default()),
),
};
println!(" {verdict}");
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// `pdfs sync queue`: what has not reached Proton Drive yet, and why.
pub(super) fn cmd_sync_queue() -> Result<()> {
let response = control_request(CtlRequest::ListPendingOps)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::PendingOps { items } if items.is_empty() => {
println!("Nothing queued: everything is on Proton Drive.");
}
CtlResponse::PendingOps { items } => {
let now = unix_now();
for op in items {
let state = match (op.parked, op.next_attempt_at) {
(true, _) => "waiting for its final name".to_string(),
(false, Some(at)) if at > now => {
format!("next try in {}", human_age((at - now) as u64))
}
(false, _) => "due now".to_string(),
};
println!("[{}] {} {} ({state})", op.id, op.kind, op.path);
if let Some(issue) = op.issue {
println!(" needs attention: {}", issue_text(issue));
}
if let Some(error) = &op.last_error {
println!(" failed {} time(s): {error}", op.attempts);
}
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// `pdfs sync flush`: wait for the queue to drain.
///
/// Failed changes are retried at once rather than after their backoff. The
/// wait ends early, with exit code 3, when everything left is waiting on the
/// user: refused by Drive, failing again and again, or a temporary file
/// waiting for its final name. Paused or offline, it keeps waiting and says
/// why.
pub(super) fn cmd_sync_flush(timeout: Option<u64>) -> Result<()> {
const POLL: std::time::Duration = std::time::Duration::from_secs(1);
let deadline =
timeout.map(|secs| std::time::Instant::now() + std::time::Duration::from_secs(secs));
ok_or_bail(control_request(CtlRequest::RetryPendingOp { id: None })?)?;
let mut last_line = String::new();
loop {
let items = match control_request(CtlRequest::ListPendingOps)? {
CtlResponse::PendingOps { items } => items,
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
};
let waiting = items
.iter()
.filter(|op| !op.parked && !op.failing && op.issue.is_none())
.count();
if items.is_empty() {
finish_line(&last_line);
println!("Everything is on Proton Drive.");
return Ok(());
}
if waiting == 0 {
finish_line(&last_line);
eprintln!(
"{} queued change(s) need you before they can be sent. See `pdfs sync issues`.",
items.len()
);
std::process::exit(3);
}
let reason = match control_request(CtlRequest::Status)? {
CtlResponse::Status { paused: true, .. } => " (sync is paused; `pdfs sync resume`)",
CtlResponse::Status { online: false, .. } => " (offline; waiting for Proton Drive)",
_ => "",
};
let line = format!("{waiting} change(s) left to send{reason}");
if line != last_line {
if !last_line.is_empty() {
print!("\r\x1b[2K");
}
print!("{line}");
last_line = line;
}
if deadline.is_some_and(|deadline| std::time::Instant::now() >= deadline) {
finish_line(&last_line);
eprintln!("Timed out with {waiting} change(s) still queued.");
std::process::exit(4);
}
std::thread::sleep(POLL);
}
}
/// End a progress line so the next message starts on its own.
pub(super) fn finish_line(last_line: &str) {
if !last_line.is_empty() {
println!();
}
}
/// `pdfs sync issues`: the queued changes that need the user, and what to do.
pub(super) fn cmd_sync_issues() -> Result<()> {
let response = control_request(CtlRequest::ListPendingOps)?;
let items = match response {
CtlResponse::PendingOps { items } => items,
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
};
let issues: Vec<_> = items.into_iter().filter(|op| op.failing).collect();
if json_enabled() {
println!("{}", serde_json::to_string_pretty(&issues)?);
return Ok(());
}
if issues.is_empty() {
println!("No sync issues.");
return Ok(());
}
for op in issues {
println!("[{}] {} {}", op.id, op.kind, op.path);
match op.issue {
Some(issue) => println!(" {}", issue_text(issue)),
None => println!(" keeps failing; it is retried."),
}
if let Some(error) = &op.last_error {
println!(" last error: {error}");
}
if op.exportable {
println!(
" save a copy: pdfs sync export {} <file or folder>",
op.id
);
}
}
Ok(())
}
/// What a sync issue means, and what the user can do about it.
pub(super) fn issue_text(issue: SyncIssue) -> &'static str {
match issue {
SyncIssue::Quota => {
"Proton Drive storage is full. Free up space or upgrade; the change is retried."
}
SyncIssue::Access => {
"you can no longer change this on Proton Drive, for example because a share was \
revoked. Save a copy to keep the content."
}
SyncIssue::Trashed => "restore the item or folder from Trash, then retry the move.",
SyncIssue::Missing => {
"the file or its folder is gone from Proton Drive. Save a copy to keep the content."
}
SyncIssue::Limit => {
"the folder holds too many items or is nested too deep. Move the file to another \
folder."
}
SyncIssue::Rejected => {
"Proton Drive rejected the change, for example the name. Rename the file."
}
SyncIssue::Unknown => "Proton Drive refused the change.",
}
}
/// `pdfs sync export`: save a queued upload's content. A folder as `dest`
/// gets the file under its own name.
pub(super) fn cmd_sync_export(id: i64, dest: &Path) -> Result<()> {
let mut dest =
std::path::absolute(dest).with_context(|| format!("resolving {}", dest.display()))?;
if dest.is_dir() {
let items = match control_request(CtlRequest::ListPendingOps)? {
CtlResponse::PendingOps { items } => items,
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
};
let Some(op) = items.iter().find(|op| op.id == id) else {
bail!("no queued change {id}; see `pdfs sync queue`");
};
let name = Path::new(&op.path)
.file_name()
.with_context(|| format!("{} has no file name", op.path))?;
dest.push(name);
}
ok_or_bail(control_request(CtlRequest::ExportPendingOp {
id,
dest: dest.display().to_string(),
})?)
}
/// `pdfs sync restore`: list what this machine's device holds, confirm where
/// each folder should land, then hand the mapping to the daemon.
///
/// The daemon only ever *proposes* local paths — a path recorded by another
/// machine may name a home directory that does not exist here — so the default
/// flow is propose-and-confirm. `--yes` accepts the proposals for scripting.
pub(super) fn cmd_sync_restore(yes: bool, device: Option<String>) -> Result<()> {
let response = control_request(match &device {
Some(device) => CtlRequest::ListDeviceRestorableFolders {
device: device.clone(),
},
None => CtlRequest::ListRestorableFolders,
})?;
if emit_json(&response)? {
return Ok(());
}
let items = match response {
CtlResponse::RestorableFolders { items } => items,
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
};
let candidates: Vec<_> = items.into_iter().filter(|f| !f.already_synced).collect();
if candidates.is_empty() {
println!("Nothing to restore: this device has no folders that aren't already synced here.");
return Ok(());
}
let mut chosen: Vec<CtlRestoreItem> = Vec::new();
for f in candidates {
if yes {
println!("{} -> {} [{}]", f.name, f.local_path, f.mode);
chosen.push(CtlRestoreItem {
remote_uid: f.remote_uid,
local_path: f.local_path,
mode: f.mode,
});
continue;
}
// Empty answer takes the proposal, `n` skips, anything else is read as
// the path to use instead — the three things a user wants here.
let answer = prompt_line(&format!(
"{} [{}] -> {} (Enter to accept, 'n' to skip, or a path)",
f.name, f.mode, f.local_path
))?;
match answer.as_str() {
"n" | "N" => continue,
"" => chosen.push(CtlRestoreItem {
remote_uid: f.remote_uid,
local_path: f.local_path,
mode: f.mode,
}),
path => chosen.push(CtlRestoreItem {
remote_uid: f.remote_uid,
local_path: expand_tilde(path),
mode: f.mode,
}),
}
}
if chosen.is_empty() {
println!("Nothing selected.");
return Ok(());
}
ok_or_bail(control_request(match device {
Some(device) => CtlRequest::RestoreDeviceFolders {
device,
items: chosen,
},
None => CtlRequest::RestoreSyncFolders { items: chosen },
})?)?;
// The daemon acks before it works, so the outcome, and any folder it had
// to skip, only shows up later.
println!("Run `pdfs activity` to see which folders were restored.");
Ok(())
}
/// Expand a leading `~` in a hand-typed path. The daemon requires an absolute
/// path, and a shell is not always the one doing the typing here.
pub(super) fn expand_tilde(path: &str) -> String {
match path.strip_prefix("~/") {
Some(rest) => match std::env::var_os("HOME") {
Some(home) => PathBuf::from(home)
.join(rest)
.to_string_lossy()
.into_owned(),
None => path.to_string(),
},
None => path.to_string(),
}
}
pub(super) fn cmd_share(
path: PathBuf,
emails: Vec<String>,
role: String,
message: Option<String>,
) -> Result<()> {
ok_or_bail(control_request(CtlRequest::ShareNode {
path: path_arg(&path)?,
emails,
role,
message,
})?)
}
/// Format an age in seconds for a report line, coarsely — the point of the
/// number is whether it is minutes or weeks.
/// Parse a `sync pause --for` duration: a whole number followed by `m`, `h` or
/// `d`. Returns seconds.
pub(super) fn parse_pause_duration(text: &str) -> Result<u64, String> {
let text = text.trim();
let split = text.char_indices().last().map_or(0, |(at, _)| at);
let (number, unit) = text.split_at(split);
let per_unit: u64 = match unit {
"m" => 60,
"h" => 3600,
"d" => 86_400,
_ => return Err("use a number followed by m, h or d, e.g. 30m".to_string()),
};
match number.parse::<u64>() {
Ok(n) if n > 0 => Ok(n.saturating_mul(per_unit)),
_ => Err("use a positive whole number, e.g. 30m".to_string()),
}
}
/// Read a bytes-per-second rate: a whole number with an optional `K`, `M` or
/// `G` suffix in the same binary units `human_bytes` prints.
pub(super) fn parse_rate(text: &str) -> Result<u64, String> {
let text = text.trim();
let (number, scale) = match text.char_indices().last() {
Some((at, 'K' | 'k')) => (&text[..at], 1024),
Some((at, 'M' | 'm')) => (&text[..at], 1_048_576),
Some((at, 'G' | 'g')) => (&text[..at], 1_073_741_824),
_ => (text, 1),
};
number
.parse::<u64>()
.map(|n| n.saturating_mul(scale))
.map_err(|_| "use a whole number with an optional K, M or G, e.g. 2M".to_string())
}
pub(super) fn human_rate(rate: u64) -> String {
if rate == 0 {
"unlimited".to_string()
} else {
format!("{}/s", human_bytes(rate))
}
}
/// `pdfs sync limit`: set the bandwidth caps, keeping whichever one is not
/// given, or print both when neither is.
pub(super) fn cmd_sync_limit(up: Option<u64>, down: Option<u64>) -> Result<()> {
let config = AppDirs::new()?.load_config();
let upload = up.or(config.upload_limit).unwrap_or(0);
let download = down.or(config.download_limit).unwrap_or(0);
if up.is_none() && down.is_none() {
println!("Upload {}", human_rate(upload));
println!("Download {}", human_rate(download));
return Ok(());
}
ok_or_bail(control_request(CtlRequest::SetBandwidthLimits {
upload,
download,
})?)
}
pub(super) fn cmd_sync_ignore(action: IgnoreCmd) -> Result<()> {
use pdfs_core::syncignore::{
DEFAULT_IGNORE_PATTERNS, FolderRules, IgnoreRules, RuleSource, Verdict, add_folder_pattern,
check_pattern, remove_folder_pattern,
};
let dirs = AppDirs::new()?;
let change = |edit: &dyn Fn(&mut Vec<String>)| -> Result<()> {
dirs.change_ignore_patterns(edit)?;
// The next pass picks the change up anyway; this only hurries it.
let _ = control_request(CtlRequest::SyncNow { id: None });
Ok(())
};
let valid = |pattern: &str| -> Result<String> {
let pattern = pattern.trim();
if pattern.is_empty() || pattern.starts_with('#') {
bail!("not a pattern: `{pattern}`");
}
check_pattern(pattern).map_err(|e| anyhow!("not a valid pattern: {e}"))?;
Ok(pattern.to_string())
};
match action {
IgnoreCmd::List { folder: None } => {
let config = dirs.load_config();
let list = config.resolved_ignore_patterns();
if list.is_empty() {
println!("No patterns: every file is synced.");
}
for pattern in list {
if DEFAULT_IGNORE_PATTERNS.contains(&pattern.as_str()) {
println!("{pattern} (built in)");
} else {
println!("{pattern}");
}
}
}
IgnoreCmd::List {
folder: Some(folder),
} => {
let (_, root) = mirror_folder_of(&folder)?;
let rules = FolderRules::read(&root)?;
let patterns = rules.patterns();
if patterns.is_empty() {
println!(
"{} has no own patterns; the ones for all synced folders apply.",
root.display()
);
}
for pattern in patterns {
println!("{pattern}");
}
}
IgnoreCmd::Add {
pattern,
folder: None,
} => {
let pattern = valid(&pattern)?;
change(&|list| {
if !list.contains(&pattern) {
list.push(pattern.clone());
}
})?;
}
IgnoreCmd::Add {
pattern,
folder: Some(folder),
} => {
let pattern = valid(&pattern)?;
let (id, root) = mirror_folder_of(&folder)?;
if add_folder_pattern(&root, &pattern)? {
let _ = control_request(CtlRequest::SyncNow { id: Some(id) });
} else {
println!("`{pattern}` is already in {}/.pdfsignore.", root.display());
}
}
IgnoreCmd::Remove {
pattern,
folder: None,
} => {
let pattern = pattern.trim().to_string();
let list = dirs.load_config().resolved_ignore_patterns();
if !list.contains(&pattern) {
bail!("`{pattern}` is not in the list; see `pdfs sync ignore list`");
}
change(&|list| list.retain(|p| *p != pattern))?;
}
IgnoreCmd::Remove {
pattern,
folder: Some(folder),
} => {
let (id, root) = mirror_folder_of(&folder)?;
if !remove_folder_pattern(&root, &pattern)? {
bail!(
"`{}` is not among the own patterns of {}; see `pdfs sync ignore list --folder {}`",
pattern.trim(),
root.display(),
root.display()
);
}
let _ = control_request(CtlRequest::SyncNow { id: Some(id) });
}
IgnoreCmd::Reset => change(&|list| {
*list = DEFAULT_IGNORE_PATTERNS
.iter()
.map(|p| (*p).to_string())
.collect()
})?,
IgnoreCmd::Check { path } => {
let path = std::path::absolute(&path)?;
let folder = synced_folder_of(&path)?;
if folder.mode != "mirror" {
println!(
"{} is online only; patterns apply only to folders kept on this computer.",
folder.local_path
);
return Ok(());
}
let root = PathBuf::from(&folder.local_path);
let rel = path.strip_prefix(&root).unwrap_or(&path).to_string_lossy();
let globals = dirs.load_config().resolved_ignore_patterns();
let rules = IgnoreRules::load(&root, &globals);
let source = |source: &RuleSource| match source {
RuleSource::AllFolders => "the patterns for all synced folders".to_string(),
RuleSource::ThisFolder => format!("{}/.pdfsignore", root.display()),
};
match rules.explain(&rel, path.is_dir()) {
Verdict::Synced => println!("Synced: no pattern matches it."),
Verdict::Excluded { pattern, source: s } => {
println!("Not synced: excluded by `{pattern}` in {}.", source(&s))
}
Verdict::Included { pattern, source: s } => {
println!("Synced: `{pattern}` in {} includes it again.", source(&s))
}
}
}
}
Ok(())
}
/// The synced folder holding `path`: the innermost one, as the daemon lists
/// them.
pub(super) fn synced_folder_of(path: &Path) -> Result<SyncFolderInfo> {
let path = std::path::absolute(path)?;
let folders = match control_request(CtlRequest::ListSyncFolders)? {
CtlResponse::SyncFolders { items } => items,
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected reply: {other:?}"),
};
folders
.into_iter()
.filter(|f| path.starts_with(&f.local_path))
.max_by_key(|f| f.local_path.len())
.ok_or_else(|| anyhow!("{} is not in a synced folder", path.display()))
}
/// The id and root of the synced folder kept on this computer that holds
/// `path`. Own patterns mean nothing to an online-only folder.
pub(super) fn mirror_folder_of(path: &Path) -> Result<(i64, PathBuf)> {
let folder = synced_folder_of(path)?;
if folder.mode != "mirror" {
bail!(
"{} is online only; patterns apply only to folders kept on this computer",
folder.local_path
);
}
Ok((folder.id, PathBuf::from(folder.local_path)))
}
/// How long the oldest write may wait to upload before `diagnose` calls it
/// out. Under a day it is a slow link or a big file; past it, something is
/// holding the queue.
pub(super) const STAGED_STALE_SECS: u64 = 86_400;
/// `diagnose` findings for the queue and the pause, from the `Status` reply.
/// `paused_for` is how long a timed pause still runs, in seconds.
pub(super) fn sync_health(
failing_ops: u64,
failing_error: Option<&str>,
staged_bytes: u64,
staged_oldest_secs: u64,
paused: bool,
paused_for: Option<i64>,
) -> Vec<(DiagnoseLevel, &'static str, String)> {
let mut findings = Vec::new();
if failing_ops > 0 {
findings.push((
DiagnoseLevel::Warn,
" failing writes",
match failing_error {
Some(error) => format!("{failing_ops} keep failing; the last error: {error}"),
None => format!("{failing_ops} keep failing"),
},
));
}
if staged_bytes > 0 && staged_oldest_secs >= STAGED_STALE_SECS {
findings.push((
DiagnoseLevel::Warn,
" oldest unsent write",
format!(
"{} old, {} only on this computer",
human_secs(staged_oldest_secs),
human_bytes(staged_bytes)
),
));
}
if paused {
findings.push((
DiagnoseLevel::Warn,
" sync",
match paused_for {
Some(left) if left > 0 => {
format!("paused for another {}", human_secs(left as u64))
}
_ => "paused until resumed (`pdfs sync resume`)".to_string(),
},
));
}
findings
}
/// `diagnose` findings for the synced folders that need someone to look.
pub(super) fn folder_health(
folders: &[pdfs_core::control::SyncFolderInfo],
) -> Vec<(DiagnoseLevel, String, String)> {
folders
.iter()
.filter_map(|folder| {
let what = match folder.state.as_str() {
"error" => "sync error; `pdfs sync list` and the activity feed say more",
"conflict" => "conflict copies to look at",
_ => return None,
};
Some((
DiagnoseLevel::Warn,
format!(" synced folder [{}]", folder.id),
format!("{}: {what}", folder.local_path),
))
})
.collect()
}
+6 -1
View File
@@ -2378,9 +2378,14 @@ pub struct Diagnostics {
/// still running. Empty from a daemon that predates the field.
#[serde(default)]
pub services: Vec<ServiceState>,
/// The one-shot jobs running now, such as a cache check, an import or a
/// folder pin, oldest first. Empty from a daemon that predates the field.
#[serde(default)]
pub jobs: Vec<ServiceState>,
}
/// One long-lived daemon thread, in [`Diagnostics::services`].
/// One long-lived daemon thread, in [`Diagnostics::services`], or one
/// one-shot job, in [`Diagnostics::jobs`].
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct ServiceState {
/// The thread's name, such as `pdfs-sync`.
+288 -17
View File
@@ -12,9 +12,20 @@
//! reverse start order: it signals [`Shutdown`], wakes each one, and joins each
//! one up to a shared deadline, naming any that is still running then.
//! [`ServiceBoard`] is the live view of the same threads, for diagnostics.
//!
//! A service can also be an async task on the mount's runtime
//! ([`Services::spawn_task`]), such as the loops that follow Drive's event
//! streams. A stop aborts it at its next `.await` and waits for it to go, up
//! to the same deadline. Such a task used to run until the runtime went
//! away, which on a stop is when the process exits.
//!
//! 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.
use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
@@ -35,10 +46,18 @@ pub struct ServiceHealth {
pub age: Duration,
}
/// The live view of the service threads: which ones were started, and which
/// are still running. Cheap to clone and to read; never blocks on a service.
/// The live view of the service threads, which were started and which are
/// still running, and of the one-shot jobs running now. Cheap to clone and to
/// read; never blocks on a service or a job.
#[derive(Clone, Default)]
pub struct ServiceBoard(Arc<Mutex<Vec<Entry>>>);
pub struct ServiceBoard(Arc<Board>);
#[derive(Default)]
struct Board {
services: Mutex<Vec<Entry>>,
jobs: Mutex<Vec<Job>>,
next_job: AtomicU64,
}
struct Entry {
name: String,
@@ -46,10 +65,17 @@ struct Entry {
running: Arc<AtomicBool>,
}
struct Job {
id: u64,
name: String,
started: Instant,
}
impl ServiceBoard {
/// Every service thread started so far, in start order.
pub fn health(&self) -> Vec<ServiceHealth> {
self.0
.services
.lock()
.iter()
.map(|entry| ServiceHealth {
@@ -60,9 +86,75 @@ impl ServiceBoard {
.collect()
}
/// The one-shot jobs running now, oldest first. A job leaves the list
/// when its thread ends.
pub fn jobs(&self) -> Vec<ServiceHealth> {
self.0
.jobs
.lock()
.iter()
.map(|job| ServiceHealth {
name: job.name.clone(),
running: true,
age: job.started.elapsed(),
})
.collect()
}
/// Start `run` on a thread named `name`, as a one-shot job: a request's
/// work that outlasts the request, such as a cache check, an import or a
/// 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.
pub fn spawn_job<F>(&self, name: &str, run: F) -> std::io::Result<()>
where
F: FnOnce() + Send + 'static,
{
let guard = self.add_job(name);
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(|_| ())
}
/// 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.
pub fn spawn_task_job<F>(&self, rt: &tokio::runtime::Handle, name: &str, task: F)
where
F: Future<Output = ()> + Send + 'static,
{
let guard = self.add_job(name);
rt.spawn(async move {
let _guard = guard;
task.await;
});
}
fn add_job(&self, name: &str) -> JobGuard {
let id = self.0.next_job.fetch_add(1, Ordering::Relaxed);
self.0.jobs.lock().push(Job {
id,
name: name.to_owned(),
started: Instant::now(),
});
JobGuard {
board: self.0.clone(),
id,
}
}
fn add(&self, name: &str) -> Arc<AtomicBool> {
let running = Arc::new(AtomicBool::new(true));
self.0.lock().push(Entry {
self.0.services.lock().push(Entry {
name: name.to_owned(),
started: Instant::now(),
running: running.clone(),
@@ -71,6 +163,18 @@ impl ServiceBoard {
}
}
/// Takes a job off the board when its thread ends, by return or by panic.
struct JobGuard {
board: Arc<Board>,
id: u64,
}
impl Drop for JobGuard {
fn drop(&mut self) {
self.board.jobs.lock().retain(|job| job.id != self.id);
}
}
/// Clears a service's `running` flag when its thread ends, by return or by panic.
struct Running(Arc<AtomicBool>);
@@ -81,10 +185,28 @@ impl Drop for Running {
}
struct Service {
handle: JoinHandle<()>,
handle: Handle,
wake: Option<Wake>,
}
/// A service is a thread, or an async task on the mount's runtime.
enum Handle {
Thread(JoinHandle<()>),
Task {
name: String,
task: tokio::task::JoinHandle<()>,
},
}
impl Handle {
fn is_finished(&self) -> bool {
match self {
Handle::Thread(handle) => handle.is_finished(),
Handle::Task { task, .. } => task.is_finished(),
}
}
}
/// The service threads one mount started, and how to stop them.
pub struct Services {
board: ServiceBoard,
@@ -117,7 +239,10 @@ impl Services {
});
match spawned {
Ok(handle) => {
self.started.push(Service { handle, wake });
self.started.push(Service {
handle: Handle::Thread(handle),
wake,
});
Ok(())
}
Err(error) => {
@@ -128,31 +253,64 @@ impl Services {
}
}
/// How many threads were 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
/// to its end, so a write it makes there is not cut in half.
pub fn spawn_task<F>(&mut self, rt: &tokio::runtime::Handle, name: &str, task: F)
where
F: Future<Output = ()> + Send + 'static,
{
let guard = Running(self.board.add(name));
let task = rt.spawn(async move {
let _guard = guard;
task.await;
});
self.started.push(Service {
handle: Handle::Task {
name: name.to_owned(),
task,
},
wake: None,
});
}
/// How many services were started.
pub fn len(&self) -> usize {
self.started.len()
}
/// Whether no thread was started.
/// Whether no service was started.
pub fn is_empty(&self) -> bool {
self.started.is_empty()
}
/// Stop every thread: signal `shutdown`, wake each thread in reverse start
/// order, then join them in the same order until `deadline`. Returns the
/// names of the threads still running at the deadline; they are left
/// behind rather than waited for.
/// 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.
pub fn stop(self, shutdown: &Shutdown, deadline: Instant) -> Vec<String> {
shutdown.stop();
for service in self.started.iter().rev() {
if let Some(wake) = &service.wake {
wake();
}
if let Handle::Task { task, .. } = &service.handle {
task.abort();
}
}
join_until(
self.started.into_iter().rev().map(|service| service.handle),
deadline,
)
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
}
}
@@ -260,4 +418,117 @@ mod tests {
assert!(left.is_empty());
assert!(!board.health()[0].running);
}
#[test]
fn a_job_shows_while_it_runs_and_leaves_when_it_ends() {
let board = ServiceBoard::default();
let (release, wait) = mpsc::channel::<()>();
let (done_tx, done_rx) = mpsc::channel::<()>();
board
.spawn_job("pdfs-test-job", move || {
let _ = wait.recv();
let _done = done_tx;
})
.unwrap();
let jobs = board.jobs();
assert_eq!(jobs.len(), 1);
assert_eq!(jobs[0].name, "pdfs-test-job");
assert!(board.health().is_empty(), "a job is not a service");
release.send(()).unwrap();
let _ = done_rx.recv_timeout(Duration::from_secs(5));
let deadline = Instant::now() + Duration::from_secs(5);
while !board.jobs().is_empty() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
assert!(board.jobs().is_empty());
}
#[test]
fn a_stop_aborts_a_task_and_shows_it_ended() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
let board = ServiceBoard::default();
let mut services = Services::new(board.clone());
// Never ends on its own and never looks at the shutdown signal.
services.spawn_task(rt.handle(), "poller", async {
loop {
tokio::time::sleep(Duration::from_millis(5)).await;
}
});
assert_eq!(services.len(), 1);
assert!(board.health()[0].running);
let left = services.stop(
&Shutdown::default(),
Instant::now() + Duration::from_secs(5),
);
assert!(left.is_empty(), "still running: {left:?}");
assert!(!board.health()[0].running);
}
#[test]
fn a_task_stuck_between_awaits_is_named_at_the_deadline() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
let mut services = Services::new(ServiceBoard::default());
let (release, wait) = mpsc::channel::<()>();
let (started_tx, started_rx) = mpsc::channel::<()>();
// Blocks its worker thread, so an abort cannot reach it until it yields.
services.spawn_task(rt.handle(), "blocking", async move {
let _ = started_tx.send(());
let _ = wait.recv();
});
started_rx.recv_timeout(Duration::from_secs(5)).unwrap();
let left = services.stop(
&Shutdown::default(),
Instant::now() + Duration::from_millis(100),
);
assert_eq!(left, ["blocking"]);
drop(release);
}
#[test]
fn a_task_job_shows_while_it_runs_and_leaves_when_it_ends() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
let board = ServiceBoard::default();
let (release, wait) = tokio::sync::oneshot::channel::<()>();
board.spawn_task_job(rt.handle(), "pdfs-test-refresh", async move {
let _ = wait.await;
});
let jobs = board.jobs();
assert_eq!(jobs.len(), 1);
assert_eq!(jobs[0].name, "pdfs-test-refresh");
release.send(()).unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
while !board.jobs().is_empty() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
assert!(board.jobs().is_empty());
}
#[test]
fn a_job_that_panics_leaves_the_list() {
let board = ServiceBoard::default();
board.spawn_job("doomed-job", || panic!("boom")).unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
while !board.jobs().is_empty() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
assert!(board.jobs().is_empty());
}
}
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "pdfs-daemon"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
rust-version.workspace = true
repository.workspace = true
homepage.workspace = true
description = "The Proton Drive Linux daemon's composition root: session, mount and restart loop"
[dependencies]
pdfs-core.workspace = true
pdfs-store.workspace = true
pdfs-fuse.workspace = true
tokio.workspace = true
anyhow.workspace = true
tracing.workspace = true
+469
View File
@@ -0,0 +1,469 @@
//! The daemon's composition root.
//!
//! `pdfs daemon` runs [`run`]: it waits for a stored session, opens the
//! database and the content cache, resumes the session on a runtime of its
//! own, and mounts. It keeps the mount alive: a clean stop exits, an
//! external unmount remounts, and a failure is recorded and retried with a
//! backoff. The mount itself, and the services it starts, are `pdfs-fuse`.
//!
//! Step 3 of `docs/ARCHITECTURE.md` moves the building of those services
//! here, one at a time.
use std::path::PathBuf;
use std::sync::Arc;
use anyhow::{Context, Result};
use pdfs_core::auth;
use pdfs_core::config::AppDirs;
use pdfs_store::cache::ContentCache;
use pdfs_store::db::Db;
/// How long to wait before the next login check, after `attempts` checks have
/// already come back [`pdfs_core::Error::NotLoggedIn`].
///
/// Doubles from 3s to a 15s ceiling. The interval is not just a sleep:
/// [`auth::load`] builds a fresh `keyring::Entry` on every call, so each check
/// opens a new D-Bus connection to the Secret Service and negotiates an
/// encrypted session over it. A flat 3s poll meant 28,800 of those a day from a
/// daemon that had nothing to do; the ceiling cuts that by 80%.
///
/// The ceiling stays low because the sleep is also the worst-case login →
/// mount latency for anything that does *not* poke systemd: front-ends restart
/// the unit on login (`service::enable_start`), which interrupts the sleep
/// immediately, but a hand-run `pdfs daemon` has no such wake-up path.
fn login_poll_delay(attempts: u32) -> std::time::Duration {
const BASE_SECS: u64 = 3;
const MAX_SECS: u64 = 15;
// `checked_shl` rather than `<<`: the daemon can sit unauthenticated for
// weeks, and a shift past the width of the type is a panic, not a big number.
let factor = 1u64.checked_shl(attempts).unwrap_or(u64::MAX);
std::time::Duration::from_secs(BASE_SECS.saturating_mul(factor).min(MAX_SECS))
}
/// Block until a session is stored and unlocked, backing off between checks.
///
/// `load` and `sleep` are parameters rather than direct calls so the backoff
/// schedule can be tested without a keyring and without real time passing.
fn wait_for_session<L, S>(mut load: L, mut sleep: S) -> Result<()>
where
L: FnMut() -> std::result::Result<(), pdfs_core::Error>,
S: FnMut(std::time::Duration),
{
let mut attempts: u32 = 0;
loop {
match load() {
Ok(()) => return Ok(()),
Err(pdfs_core::Error::NotLoggedIn) => {
let delay = login_poll_delay(attempts);
// Say it once at INFO. Repeating it every interval buried the
// journal in tens of thousands of identical lines a day.
if attempts == 0 {
tracing::info!("not logged in; waiting for a session…");
} else {
tracing::debug!(delay_secs = delay.as_secs(), "still not logged in");
}
sleep(delay);
attempts = attempts.saturating_add(1);
}
Err(pdfs_core::Error::Locked) => {
let delay = login_poll_delay(attempts);
if attempts == 0 {
tracing::info!("account is locked; waiting for `pdfs unlock`…");
} else {
tracing::debug!(delay_secs = delay.as_secs(), "account still locked");
}
sleep(delay);
attempts = attempts.saturating_add(1);
}
Err(e) => return Err(e.into()),
}
}
}
/// Run the daemon: the auto-mount loop. Waits for a stored login, mounts, and keeps
/// the mount alive: a clean stop (SIGTERM via `systemctl --user stop`) exits 0;
/// an external unmount triggers a remount; errors back off and retry. This is
/// the entry point for the systemd user service.
pub fn run(mountpoint: Option<PathBuf>) -> Result<()> {
let state_dir = AppDirs::new()?.state_dir();
// A failure an earlier daemon recorded is not this one's.
pdfs_core::mountfail::clear(&state_dir);
let mut failure: Option<pdfs_core::mountfail::MountFailure> = None;
loop {
// Wait until a session is stored. The GUI enables this service on login,
// but the service may also start at boot before the user has logged in.
wait_for_session(auth::ready, pdfs_fuse::idle_sleep)?;
let outcome = mount_once(mountpoint.clone());
if outcome.is_ok() {
// The mount came up, so the next failure starts a new run of them.
failure = None;
}
match outcome {
Ok(pdfs_fuse::MountOutcome::Shutdown) => {
tracing::info!("daemon stopping");
return Ok(());
}
Ok(pdfs_fuse::MountOutcome::ResumeStored) => {
tracing::info!("resuming the session stored in the keyring");
}
Ok(pdfs_fuse::MountOutcome::Unmounted) => {
tracing::warn!("mount ended externally; remounting in 2s");
pdfs_fuse::idle_sleep(std::time::Duration::from_secs(2));
}
Err(e) => {
// `{:#}` so the whole anyhow chain lands in the log — the top
// context alone ("mount failed") never says *why*.
let error = format!("{e:#}");
let now = unix_now();
let attempts = failure.as_ref().map_or(1, |f| f.attempts.saturating_add(1));
let delay = mount_retry_schedule(&e, attempts);
match delay {
Some(delay) => tracing::error!(
error,
attempts,
retry_secs = delay.as_secs(),
"mount failed; retrying"
),
None => tracing::error!(
error,
attempts,
"account keys could not open My Files; waiting for service restart"
),
}
let record = pdfs_core::mountfail::MountFailure {
error: error.clone(),
since: failure.as_ref().map_or(now, |f| f.since),
attempts,
next_attempt: now + delay.map_or(0, |delay| delay.as_secs() as i64),
awaiting_keys: delay.is_none(),
not_empty: not_empty_cause(&e),
};
if let Err(e) = pdfs_core::mountfail::record(&state_dir, &record) {
tracing::warn!(error = %e, "could not record the mount failure");
}
pdfs_fuse::notify_status(&format!("Mount failing: {error}"));
failure = Some(record);
// Retry and a successful login restart the service. Keep the
// watchdog alive while parked without contacting Proton.
match delay {
Some(delay) => pdfs_fuse::idle_sleep(delay),
None => return pdfs_fuse::wait_for_restart().context("wait for key recovery"),
}
}
}
}
}
/// The folder in the way, when `error` is a mount refused over a folder that
/// already has files in it. The refusal travels inside an `io::Error`, whose
/// `source` skips the error it wraps, so each link is unwrapped by hand.
fn not_empty_cause(error: &anyhow::Error) -> Option<pdfs_core::mountpoint::NotEmpty> {
error.chain().find_map(|cause| {
cause
.downcast_ref::<pdfs_core::mountpoint::NotEmpty>()
.or_else(|| {
cause
.downcast_ref::<std::io::Error>()?
.get_ref()?
.downcast_ref::<pdfs_core::mountpoint::NotEmpty>()
})
.cloned()
})
}
fn mount_retry_schedule(error: &anyhow::Error, attempts: u32) -> Option<std::time::Duration> {
let root = error.chain().find_map(|cause| {
cause
.downcast_ref::<std::io::Error>()?
.get_ref()?
.downcast_ref::<pdfs_core::mountfail::RootLookup>()
});
if root.is_some_and(|root| root.needs_account_keys()) {
None
} else {
Some(mount_retry_delay(attempts))
}
}
/// How long to wait before mount attempt `attempts + 1`, after `attempts`
/// failures in a row.
///
/// Doubles from 5 s to a 2-minute ceiling. A flat 5 s retry sent about four
/// requests to Proton per attempt, tens of thousands a day from an account
/// whose mount fails on a key, which no retry fixes (`docs/BUGS.md` B263). The
/// ceiling stays at minutes because a cold start without a network fails the
/// same way, and must mount soon after the network returns.
fn mount_retry_delay(attempts: u32) -> std::time::Duration {
const BASE_SECS: u64 = 5;
const MAX_SECS: u64 = 120;
let factor = 1u64
.checked_shl(attempts.saturating_sub(1))
.unwrap_or(u64::MAX);
std::time::Duration::from_secs(BASE_SECS.saturating_mul(factor).min(MAX_SECS))
}
/// One mount run: resume the session, mount, and block until the mount ends
/// (clean shutdown or external unmount). Returns the [`MountOutcome`] so the
/// daemon loop can decide whether to exit or remount.
pub fn mount_once(mountpoint: Option<PathBuf>) -> Result<pdfs_fuse::MountOutcome> {
let dirs = AppDirs::new()?;
dirs.ensure()?;
let config = dirs.load_config();
// An explicit `--mountpoint` wins; otherwise honor the Settings-page choice
// (config), falling back to the default location.
let mountpoint = mountpoint.unwrap_or_else(|| dirs.resolved_mountpoint(&config));
// Hydrating a large account and remounting its folders can outlast the
// unit's watchdog before the supervisor sends its first ping (B279).
pdfs_fuse::stretch_watchdog_for_startup();
pdfs_fuse::prepare_mountpoint(&mountpoint)
.with_context(|| format!("create mountpoint {}", mountpoint.display()))?;
let username = auth::load().map(|s| s.username).unwrap_or_default();
// The daemon owns the unified DB (single writer). Open it here so the content
// cache and the mount share one handle: the cache uses its `cache_entries`
// table as the LRU index, the mount uses it for nodes/search/event cursor.
let db = Arc::new(Db::open(&dirs.db_path()).context("open cache db")?);
let cache = ContentCache::open(
dirs.content_cache_dir(),
dirs.pins_path(),
config.resolved_cache_budget(),
db.clone(),
)
.context("open content cache")?;
let control_socket = dirs.control_socket();
// Multi-threaded runtime: its worker threads keep servicing async SDK calls
// while the main thread is parked inside the blocking FUSE session loop.
let rt = tokio::runtime::Runtime::new()?;
let (client, session) = rt
.block_on(auth::resume_client())
.context("resume session (run `pdfs login` first)")?;
// Token updates are persisted automatically in real-time. The SDK session has
// a token refresh callback registered during `resume_client` that writes updated
// credentials back to the OS keyring immediately upon rotation. This prevents
// the system keyring from holding stale refresh tokens even if the daemon crashes,
// the system is suspended, or the network changes.
let handle = rt.handle().clone();
let result = pdfs_fuse::mount(
client,
handle,
&mountpoint,
cache,
&control_socket,
db,
pdfs_fuse::MountOptions {
username,
gallery_session: Some(session.clone()),
sweep_mode: config.resolved_conflict_sweep(),
upload_limit: config.upload_limit.unwrap_or(0),
download_limit: config.download_limit.unwrap_or(0),
local_first: config.local_first.unwrap_or(true),
},
);
// Last chance for a rotation the keyring refused when it happened. Only
// that: by now the keyring may hold a newer login, the one this stop was
// restarted for, and the tokens of this session would overwrite it.
if let Err(e) = auth::persist(&session) {
tracing::error!(
error = %e,
"could not save the refreshed session tokens; the next start may need `pdfs login`"
);
}
release_runtime(rt, matches!(result, Ok(pdfs_fuse::MountOutcome::Shutdown)));
let outcome = result.context("mount failed")?;
Ok(outcome)
}
/// Let go of a mount's runtime once the mount has ended.
///
/// On a stop the process exits right after, so the runtime is left running
/// for it to end with. Shutting it down first broke every thread the mount
/// does not join, such as a size lookup or a profile backup a request started
/// during the stop: its next call to Drive panicked with "A Tokio 1.x context
/// was found, but it is being shutdown" (`docs/BUGS.md` B276). A mount that
/// is about to be tried again does shut it down, because a new runtime
/// replaces it. Dropping it would wait for every blocking task, however long;
/// a call still stuck on Drive would hold the retry (B165).
fn release_runtime(rt: tokio::runtime::Runtime, exiting: bool) {
if exiting {
std::mem::forget(rt);
} else {
rt.shutdown_timeout(std::time::Duration::from_secs(2));
}
}
fn unix_now() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
#[cfg(test)]
mod release_runtime_tests {
use super::*;
use std::time::Duration;
/// A thread the mount never joined still reaches Drive after a stop. It
/// used to panic on its first timer once the runtime was shut down.
#[test]
fn a_thread_left_running_at_a_stop_can_still_use_the_runtime() {
let rt = tokio::runtime::Runtime::new().unwrap();
let handle = rt.handle().clone();
let (released_tx, released_rx) = std::sync::mpsc::channel();
let straggler = std::thread::spawn(move || {
released_rx.recv().unwrap();
handle.block_on(async {
tokio::time::sleep(Duration::from_millis(1)).await;
7
})
});
release_runtime(rt, true);
released_tx.send(()).unwrap();
assert_eq!(straggler.join().expect("the thread must not panic"), 7);
}
#[test]
fn a_mount_tried_again_shuts_its_runtime_down() {
let rt = tokio::runtime::Runtime::new().unwrap();
let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
rt.spawn(async move {
let _done = done_tx;
std::future::pending::<()>().await;
});
release_runtime(rt, false);
// The task is dropped with the runtime, and its sender with it.
assert_eq!(
done_rx.recv_timeout(Duration::from_secs(5)),
Err(std::sync::mpsc::RecvTimeoutError::Disconnected)
);
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::*;
/// The mount retry backs off from 5 s to a ceiling of minutes, rather than
/// asking Proton every 5 s forever (`docs/BUGS.md` B263).
#[test]
fn a_failing_mount_backs_off_to_a_ceiling() {
let secs: Vec<u64> = (1..=8).map(|n| mount_retry_delay(n).as_secs()).collect();
assert_eq!(secs, [5, 10, 20, 40, 80, 120, 120, 120]);
assert_eq!(mount_retry_delay(u32::MAX).as_secs(), 120);
}
#[test]
fn cold_root_key_failures_wait_for_a_restart() {
use pdfs_core::proton_sdk::{ProtonError, crypto::CryptoError};
for (cause, parked) in [
(ProtonError::KeysLocked, true),
(CryptoError::Decrypt("missing key".into()).into(), true),
(CryptoError::Decrypt("malformed data".into()).into(), false),
(ProtonError::invalid_operation("missing key"), false),
] {
let io = std::io::Error::other(pdfs_core::mountfail::RootLookup(cause));
let error = anyhow::Error::new(io).context("mount failed");
assert_eq!(mount_retry_schedule(&error, 1).is_none(), parked);
}
let io = std::io::Error::from(std::io::ErrorKind::NetworkUnreachable);
assert_eq!(
mount_retry_schedule(&io.into(), 1),
Some(mount_retry_delay(1))
);
}
/// A refusal over a folder with files in it reaches the failure record
/// through the `io::Error` and the context around it (`docs/BUGS.md` B277).
#[test]
fn a_mount_refused_over_files_is_recorded_as_such() {
let found = pdfs_core::mountpoint::NotEmpty {
path: PathBuf::from("/home/you/ProtonDrive"),
entries: vec!["Work".into()],
count: 1,
};
let error =
anyhow::Error::new(std::io::Error::other(found.clone())).context("mount failed");
assert_eq!(not_empty_cause(&error), Some(found));
let other =
anyhow::Error::new(std::io::Error::other("missing key")).context("mount failed");
assert_eq!(not_empty_cause(&other), None);
}
#[test]
fn poll_delay_doubles_then_holds_at_the_ceiling() {
assert_eq!(login_poll_delay(0), Duration::from_secs(3));
assert_eq!(login_poll_delay(1), Duration::from_secs(6));
assert_eq!(login_poll_delay(2), Duration::from_secs(12));
assert_eq!(login_poll_delay(3), Duration::from_secs(15));
assert_eq!(login_poll_delay(4), Duration::from_secs(15));
// A daemon left unauthenticated for weeks reaches attempt counts well
// past the width of the shift; that must cap, not panic.
assert_eq!(login_poll_delay(64), Duration::from_secs(15));
assert_eq!(login_poll_delay(u32::MAX), Duration::from_secs(15));
}
#[test]
fn waiting_for_a_session_stops_hammering_the_keyring() {
let mut checks_left = 20;
let mut slept: Vec<Duration> = Vec::new();
wait_for_session(
|| {
if checks_left == 0 {
Ok(())
} else {
checks_left -= 1;
Err(pdfs_core::Error::NotLoggedIn)
}
},
|delay| slept.push(delay),
)
.unwrap();
assert_eq!(slept.len(), 20, "one wait per failed check");
assert!(
slept.windows(2).all(|w| w[1] >= w[0]),
"the interval must never shrink: {slept:?}"
);
// The point of the change. Every check is a fresh D-Bus session against
// the Secret Service, so 20 of them must not fit inside a single minute
// the way a flat 3s poll did.
let total: Duration = slept.iter().sum();
assert!(
total >= Duration::from_secs(4 * 60),
"20 checks should span at least 4 minutes, spanned {total:?}"
);
}
#[test]
fn a_locked_account_is_waited_on_until_it_is_unlocked() {
let mut checks = vec![
Ok(()),
Err(pdfs_core::Error::Locked),
Err(pdfs_core::Error::NotLoggedIn),
Err(pdfs_core::Error::Locked),
];
let mut slept = 0;
wait_for_session(|| checks.pop().unwrap(), |_| slept += 1).unwrap();
assert_eq!(slept, 3, "locked and signed-out are both waited out");
}
#[test]
fn a_stored_session_is_not_waited_for_at_all() {
let mut slept = 0;
wait_for_session(|| Ok(()), |_| slept += 1).unwrap();
assert_eq!(slept, 0);
}
}
+17 -15
View File
@@ -140,16 +140,17 @@ impl Core {
return;
}
let core = self.clone();
self.rt.spawn(async move {
let refreshed = core.refresh_albums().await;
core.photo_jobs
.albums_refreshing
.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background album refresh failed"),
}
});
self.services
.spawn_task_job(&self.rt, "pdfs-albums-refresh", async move {
let refreshed = core.refresh_albums().await;
core.photo_jobs
.albums_refreshing
.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background album refresh failed"),
}
});
}
/// A page of one album's photos, newest capture first. The album's contents
@@ -179,11 +180,12 @@ impl Core {
} else if self.listing_stale(&stamp, TIMELINE_TTL) {
let core = self.clone();
let album = album.clone();
self.rt.spawn(async move {
if let Err(e) = core.refresh_album(&album).await {
warn!(%album, error = %e, "background album refresh failed");
}
});
self.services
.spawn_task_job(&self.rt, "pdfs-album-refresh", async move {
if let Err(e) = core.refresh_album(&album).await {
warn!(%album, error = %e, "background album refresh failed");
}
});
}
let page = self
+62 -43
View File
@@ -1291,7 +1291,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
let core = core.clone();
let paths: Vec<PathBuf> = sources.into_iter().map(PathBuf::from).collect();
let n = paths.len();
std::thread::spawn(move || {
if let Err(error) = core.services.clone().spawn_job("pdfs-upload", move || {
let started = Instant::now();
match core.upload_paths(&parent_rel, &paths) {
Ok(stats) => {
@@ -1327,7 +1327,9 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
core.log_activity(ActivityKind::Upload, "bulk upload", &e, false);
}
}
});
}) {
tracing::warn!(%error, "could not start pdfs-upload");
}
CtlResponse::Ok {
message: format!("uploading {n} item(s)"),
}
@@ -1514,29 +1516,35 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
// completion (and any failures) go to the activity log.
let core = core.clone();
let path = PathBuf::from(&local_path);
std::thread::spawn(move || {
let started = Instant::now();
match core.add_sync_folder(&path) {
Ok(folder) => {
core.touch_profile();
let name = Path::new(&folder.local_path)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(&folder.local_path)
.to_string();
core.log_activity(
ActivityKind::Upload,
format!("synced {name}"),
human_duration(started.elapsed()),
folder.state != "error",
);
if let Err(error) = core
.services
.clone()
.spawn_job("pdfs-add-sync-folder", move || {
let started = Instant::now();
match core.add_sync_folder(&path) {
Ok(folder) => {
core.touch_profile();
let name = Path::new(&folder.local_path)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(&folder.local_path)
.to_string();
core.log_activity(
ActivityKind::Upload,
format!("synced {name}"),
human_duration(started.elapsed()),
folder.state != "error",
);
}
Err(e) => {
warn!(error = %e, "add sync folder failed");
core.log_activity(ActivityKind::Upload, "add sync folder", &e, false);
}
}
Err(e) => {
warn!(error = %e, "add sync folder failed");
core.log_activity(ActivityKind::Upload, "add sync folder", &e, false);
}
}
});
})
{
tracing::warn!(%error, "could not start pdfs-add-sync-folder");
}
CtlResponse::Ok {
message: format!("adding {local_path}"),
}
@@ -1682,26 +1690,37 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
// Like AddSyncFolder: each restored folder downloads a whole tree,
// which outlasts the socket timeout. Ack, then work.
let core = core.clone();
std::thread::spawn(move || {
match core.restore_sync_folders(&items, device.as_deref()) {
Ok(outcome) => {
core.touch_profile();
if !outcome.complete() {
warn!(skipped = ?outcome.skipped, "restore skipped folders");
if let Err(error) =
core.services
.clone()
.spawn_job("pdfs-restore-sync-folders", move || {
match core.restore_sync_folders(&items, device.as_deref()) {
Ok(outcome) => {
core.touch_profile();
if !outcome.complete() {
warn!(skipped = ?outcome.skipped, "restore skipped folders");
}
core.log_activity(
ActivityKind::Download,
outcome.summary(),
outcome.skipped.join("; "),
outcome.complete(),
);
}
Err(e) => {
warn!(error = %e, "restore failed");
core.log_activity(
ActivityKind::Download,
"restore folders",
&e,
false,
);
}
}
core.log_activity(
ActivityKind::Download,
outcome.summary(),
outcome.skipped.join("; "),
outcome.complete(),
);
}
Err(e) => {
warn!(error = %e, "restore failed");
core.log_activity(ActivityKind::Download, "restore folders", &e, false);
}
}
});
})
{
tracing::warn!(%error, "could not start pdfs-restore-sync-folders");
}
CtlResponse::Ok {
message: "restoring folders".to_string(),
}
+10
View File
@@ -174,6 +174,16 @@ impl Core {
age_secs: service.age.as_secs(),
})
.collect(),
jobs: self
.services
.jobs()
.into_iter()
.map(|job| ServiceState {
name: job.name,
running: job.running,
age_secs: job.age.as_secs(),
})
.collect(),
drive_calls: self
.drive_calls
.snapshot()
File diff suppressed because it is too large. Load diff
+813
View File
@@ -0,0 +1,813 @@
//! Draining a create or a mkdir: sending it, adopting a twin an unanswered
//! attempt left on Drive, and swapping the placeholder for the real node.
use super::*;
impl Core {
/// Finish adopting the node `op` is for, if its create landed but could
/// not be read back.
///
/// Until it is, the tree has the node as it was made locally, and a write
/// queued over it is based on that rather than on what Drive holds. Sent
/// so, the write found our own create's revision in its way and landed as
/// a conflict copy (`docs/BUGS.md` B143).
pub(crate) fn finish_adoption(&self, op: &PendingOp) -> Result<(), Box<dyn std::error::Error>> {
let Some(real) = parse_node_uid(&op.uid) else {
return Ok(());
};
let local = match self.drain.unadopted.lock().get(&real).cloned() {
Some(local) => local,
// The map does not outlive a restart, which also forgets the
// stand-in: the row is under the real uid by then. A file as it was
// made here has no revision of Drive's (`docs/BUGS.md` B182).
None if op.kind == OP_REVISION && self.never_read_back(&real) => real.clone(),
None => return Ok(()),
};
// A node gone since is the op's to deal with.
if self.fetch_node_remote(&real)?.is_some() {
self.adopt_real_uid(&local, &real, |_| {})?;
}
self.drain.unadopted.lock().remove(&real);
debug!(%local, %real, "adopted a landed create");
Ok(())
}
/// Whether the tree has the file `real` as it was made here: its create
/// landed, but Drive's answer was never read back.
pub(crate) fn never_read_back(&self, real: &NodeUid) -> bool {
let st = self.state();
st.by_uid
.get(real)
.and_then(|ino| st.entries.get(ino))
.is_some_and(|entry| !entry.node.is_folder() && node_revision_id(&entry.node).is_none())
}
/// Make a node that so far exists only on this machine real, and adopt the
/// uid the server gives it.
pub(crate) fn drain_local_node(
&self,
op: &PendingOp,
) -> Result<(), Box<dyn std::error::Error>> {
// Drive holds the name the create is sent with once it lands, whatever
// became of the file meanwhile, until the rename or trash queued
// behind it frees it (`Core::name_is_held`).
if let (Some(parent), Some(name)) = (op.parent_uid.as_deref(), op.name.as_deref())
&& let Some(parent) = parse_node_uid(parent)
{
self.drain
.creating
.lock()
.insert(op.id, (parent, name.to_string()));
}
let created = self.create_local_node(op);
self.drain.creating.lock().remove(&op.id);
created
}
pub(crate) fn create_local_node(
&self,
op: &PendingOp,
) -> Result<(), Box<dyn std::error::Error>> {
let local = parse_node_uid(&op.uid).ok_or("pending op has an unparseable uid")?;
let parent_str = op.parent_uid.as_deref().ok_or("create op has no parent")?;
// `run_pending_drain` will not offer an op whose parent is still a
// placeholder, so reaching here with one is a bug, not a wait.
if is_local_uid_str(parent_str) {
return Err(format!("parent {parent_str} has not been created yet").into());
}
let parent = parse_node_uid(parent_str).ok_or("create op has an unparseable parent")?;
let wanted = op.name.clone().ok_or("create op has no name")?;
if self.db.has_withdrawn_create(parent_str, &wanted)? {
return Err(held_by_queued_change(&wanted));
}
// Someone else may have taken the name while this sat in the queue —
// reachable only because the op waited, which is the whole point of the
// queue. Never overwrite theirs and never drop ours: land under a
// conflict name, exactly as the sync engine does.
//
// Two things can hold the name that are not someone else's file. The
// node a create made before the network dropped its answer is ours: the
// create was queued because nobody heard back, so adopt it. And a node
// whose trash is still queued is about to let go of it.
let mut name = wanted.clone();
let mut home = parent.clone();
let mut sent = (parent_str.to_string(), wanted.clone());
let mut blob_landed = true;
// An earlier attempt, sent before the file was renamed or moved, may
// have made it and lost the answer. That node is ours where it was
// sent, and the rename follows it (`docs/BUGS.md` B184).
let mut real = match self.earlier_twin(op, parent_str, &wanted)? {
Some(EarlierTwin {
parent: was_in,
name: was_named,
twin,
holds_blob,
}) => {
info!(%local, %twin, was_named, wanted, "an earlier attempt landed unanswered under another name; adopting it");
sent = (was_in.to_string(), was_named.clone());
home = was_in;
name = was_named;
blob_landed = holds_blob;
Ok(twin)
}
None => self.create_drained_node(op, &parent, &name),
};
if real.as_ref().is_err_and(|e| is_already_exists(e.as_ref()))
&& let Some((twin, holds_blob)) = self.adoptable_twin(op, &parent, &wanted)?
{
info!(%local, %twin, wanted, "the name is held by our own unanswered create; adopting it");
real = Ok(twin);
blob_landed = holds_blob;
}
if real.as_ref().is_err_and(|e| is_already_exists(e.as_ref()))
&& self.name_is_held(op, Some(&parent), &wanted)?
{
return Err(held_by_queued_change(&wanted));
}
// What held it may have let go since Drive answered (docs/BUGS.md
// B144).
if real.as_ref().is_err_and(|e| is_already_exists(e.as_ref())) {
real = self.create_drained_node(op, &parent, &wanted);
}
if real.as_ref().is_err_and(|e| is_already_exists(e.as_ref())) {
name = conflict_name(&wanted, now_secs());
warn!(%local, wanted, name, "name is taken remotely; creating under a conflict name");
real = self.create_drained_node(op, &parent, &name);
if real.is_ok() {
self.log_activity(
ActivityKind::Upload,
&wanted,
format!("name was taken remotely; created as {name}"),
false,
);
}
}
// The folder this node was created in may have been trashed remotely
// while the op waited, in which case nothing will ever make the op
// succeed as written and retrying it forever wedges the queue behind a
// file that has bytes to save. Re-home it to the root: not where the
// user put it, but it exists, it is visible, and the bytes are intact.
//
// Not for a create a delete withdrew while it was on the wire: the
// folder is most often gone because the user removed it, with this
// file, and the file would come back in the root (`docs/BUGS.md` B168).
if let Some(root) = self.root_uid()
&& real.is_err()
&& !self.db.has_pending_op(&op.uid, OP_TRASH)?
&& self.parent_is_gone(&parent)
{
warn!(%local, name, "parent folder is gone remotely; creating in the root instead");
real = self.create_drained_node(op, &root, &name);
if real.as_ref().is_err_and(|e| is_already_exists(e.as_ref())) {
name = conflict_name(&wanted, now_secs());
real = self.create_drained_node(op, &root, &name);
}
home = root;
if real.is_ok() {
self.log_activity(
ActivityKind::Upload,
&wanted,
format!("its folder was trashed remotely; created in the root as {name}"),
false,
);
}
}
let real = real?;
// Retiring the op makes the ops behind it due: a child created in a new
// folder, a rename made while the create was on the wire. Drive answers
// a create before it lists the node, and those ops sent before then
// found no folder or dropped the rename as gone. Best effort:
// `adopt_real_uid` reads it back again and reports the failure.
let _ = self.read_back(&real);
// Retire the op before touching anything else: if we crash here the node
// exists remotely and the local placeholder is reconciled by the event
// sync, whereas a surviving op would create the file a second time.
// An adopted node made empty has not had a blob this op carries
// uploaded: it goes on as a revision of the node instead.
let uploaded = blob_landed.then_some(op.blob_path.as_deref()).flatten();
let landing = CreateLanding {
local: &local.to_string(),
real: &real.to_string(),
sent: (&sent.0, &sent.1),
landed: (&home.to_string(), &name),
};
// Counted from the op's retirement until the bytes are cached and the
// tree has the real uid, as an upload is. Uncounted, the queue read
// empty while that still ran: a delete in between took an open file
// for closed and dropped what its handle reads, and a script that
// waited for an empty queue read the file before it was cached
// (`docs/BUGS.md` B257).
let _landing = LandingUpload::begin(&self.drain.landing_uploads);
let newer = match self.retire_create(op, uploaded, &landing, &local, &real)? {
CreateRetired::Withdrawn { trash } => {
return self.trash_withdrawn_create(op, trash, &local, &real, &name);
}
retired => matches!(retired, CreateRetired::Newer { .. }),
};
// The uploaded blob is the new file's content, so it becomes the cached
// content, as for a revision. A partial write fills its gaps from it;
// without it the next write open was refused (`docs/BUGS.md` B123).
let landed: Option<StagedWrite> = uploaded
.filter(|_| !newer)
.and(op.meta_json.as_deref())
.and_then(|json| serde_json::from_str(json).ok());
// The op is gone, so the create has landed whatever the read-back
// says. One that fails is finished before anything else is sent for
// the node (`docs/BUGS.md` B143).
if let Err(e) = self.adopt_real_uid(&local, &real, |node| {
if let (Some(blob), Some(meta)) = (uploaded, &landed)
&& node_size(node) == meta.len
&& keeps_landed_upload(self.cache.is_pinned(&real), meta.len, self.cache.budget())
{
let _ =
self.cache
.store_file(&real, node.modification_time, meta.len, Path::new(blob));
}
}) {
warn!(%local, %real, error = %e, "reading back a landed create failed; adopting it later");
self.drain
.unadopted
.lock()
.insert(real.clone(), local.clone());
}
// The feed will report this create back to us; the tree already has it
// under its real uid, so that event is ours to ignore (`Core::self_changes`).
self.note_self_change(&real);
// The uploaded blob is done with either way: a write that replaced it
// while it was on the wire already discarded it when it attached.
if let Some(blob) = uploaded {
self.cache.discard_staged(Path::new(blob));
}
if newer {
info!(%local, %real, name, "a write landed during the create; queued it as a revision");
self.wake_drain();
}
self.log_activity(ActivityKind::Upload, &name, "created", true);
info!(%local, %real, name, kind = %op.kind, "pending create landed");
Ok(())
}
/// Whether `name` is held on Drive by a change of ours that is to free it:
/// a queued trash, a queued rename away from it, or another create on the
/// wire that was sent with it in `parent`, which a rename or trash follows
/// (`Db::finish_create`). The op that wants the name waits for it rather
/// than land under a conflict name.
///
/// A trash is waited for as long as it takes. The rest only for
/// [`NAME_HOLD_ATTEMPTS`]: two files swapping names each hold the name the
/// other wants.
pub(crate) fn name_is_held(
&self,
op: &PendingOp,
parent: Option<&NodeUid>,
name: &str,
) -> Result<bool, Box<dyn std::error::Error>> {
let parent_uid = parent.map(NodeUid::to_string);
if self
.db
.has_pending_trash_named(name, parent_uid.as_deref())?
{
return Ok(true);
}
if op.attempts >= NAME_HOLD_ATTEMPTS {
return Ok(false);
}
let creating = self
.drain
.creating
.lock()
.iter()
.any(|(id, (p, n))| *id != op.id && Some(p) == parent && n == name);
Ok(creating || self.db.has_pending_move_from(name)?)
}
/// Whether a create other than `op` is on the wire under `name`, in any
/// folder.
pub(crate) fn creating_named(&self, op: &PendingOp, name: &str) -> bool {
self.drain
.creating
.lock()
.iter()
.any(|(id, (_, n))| *id != op.id && n == name)
}
/// The node an earlier attempt at create `op` made under a parent or name
/// the op has been moved from since ([`Core::adoptable_twin`]).
pub(super) fn earlier_twin(
&self,
op: &PendingOp,
parent: &str,
name: &str,
) -> Result<Option<EarlierTwin>, Box<dyn std::error::Error>> {
for (was_in, was_named) in self.db.create_targets(op.id)? {
if (was_in.as_str(), was_named.as_str()) == (parent, name) {
continue;
}
let Some(was_in) = parse_node_uid(&was_in) else {
continue;
};
match self.adoptable_twin(op, &was_in, &was_named) {
Ok(Some((twin, holds_blob))) => {
return Ok(Some(EarlierTwin {
parent: was_in,
name: was_named,
twin,
holds_blob,
}));
}
Ok(None) => {}
Err(e) if is_gone(e.as_ref()) => {}
Err(e) => return Err(e),
}
}
Ok(None)
}
/// The node already holding `name` under `parent`, if it is the one an
/// earlier attempt at this op made before its answer was lost, and whether
/// it holds the op's blob already.
///
/// A create that timed out may still have landed; the op was queued because
/// the caller never heard back. Without this, its replay forked a
/// `(sync-conflict)` copy of a file nobody else had touched.
pub(crate) fn adoptable_twin(
&self,
op: &PendingOp,
parent: &NodeUid,
name: &str,
) -> Result<Option<(NodeUid, bool)>, Box<dyn std::error::Error>> {
// A second file queued under the same name, after the first was
// renamed away, finds the first one's node fresh and empty while its
// create is on the wire. Taking it put both files on one node, and the
// first one's rename took the second one's bytes along
// (docs/BUGS.md B147).
let racing = self
.drain
.creating
.lock()
.iter()
.any(|(id, (p, n))| *id != op.id && p == parent && n == name);
if racing {
return Ok(None);
}
let uids = self.block_on_bounded(self.drive.enumerate_folder_children_node_uids(parent))?;
let children = self.block_on_bounded(self.drive.enumerate_nodes_light(&uids))?;
// A node this mount trashed is not one an unanswered create made, even
// while its trash is on the wire or a listing still shows it. Taking a
// folder removed and made again put the new one's contents into the
// old one, and its trash took them along (docs/BUGS.md B162).
let hidden = self.hidden.lock().clone();
let Some(twin) = children
.into_iter()
.find(|node| node.name == name && !node.trashed && !hidden.contains(&node.uid))
else {
return Ok(None);
};
// A node in the tree was answered for, by this mount or by a listing:
// the same race after the first create landed. Without the adoption,
// an unanswered twin forks a conflict copy, which loses nothing.
if self.state().by_uid.contains_key(&twin.uid) {
return Ok(None);
}
// The light listing carries no file size or digest.
let twin = match twin.kind {
NodeKind::Folder => twin,
NodeKind::File { .. } => match self.fetch_node_remote(&twin.uid)? {
Some(node) => node,
None => return Ok(None),
},
};
// A create uploads its bytes in the same call, so the node a lost
// answer leaves holds them (docs/BUGS.md B127): the ones the op holds
// now, or ones a write has replaced since (B156), which still go up.
let current = match op.blob_path.as_deref() {
Some(blob) if node_size(&twin) > 0 => Some(staged_sha1(Path::new(blob))?),
_ => None,
};
let holds_blob = current
.as_deref()
.is_some_and(|sha| holds_bytes(&twin, sha));
let sent = self.create_sent_digests(op.id, current);
Ok(
adoptable(op.kind == OP_MKDIR, &twin, self.first_sent(op), &sent)
.then_some((twin.uid, holds_blob)),
)
}
/// The SHA-1s of the bytes queued create `id` may have made its file with:
/// `current`, those of the blob it holds now, and those each earlier
/// attempt uploaded.
pub(crate) fn create_sent_digests(&self, id: i64, current: Option<String>) -> Vec<String> {
let mut sent = self.db.create_sent(id).unwrap_or_else(|e| {
warn!(id, error = %e, "reading what a queued create sent failed");
Vec::new()
});
sent.extend(current);
sent
}
/// When create `op` first went out, which is the earliest a node its lost
/// answer left can have been made. An op queued offline may wait for days
/// before that; measured from when it was queued, the adoption window let
/// it take a node another device made in the meantime. Ops sent before the
/// time was recorded fall back to when they were queued.
pub(crate) fn first_sent(&self, op: &PendingOp) -> i64 {
match self.db.create_first_sent(op.id) {
Ok(Some(at)) => at.max(op.created_at),
Ok(None) => op.created_at,
Err(e) => {
warn!(id = op.id, error = %e, "reading when a queued create was sent failed");
op.created_at
}
}
}
/// Make one queued `create`/`mkdir` real under a given name, and hand back
/// the API's own error so the caller can tell a name clash from a failure.
///
/// Split out because the conflict path has to run it twice: the second time
/// under a different name.
pub(crate) fn create_drained_node(
&self,
op: &PendingOp,
parent: &NodeUid,
name: &str,
) -> Result<NodeUid, Box<dyn std::error::Error>> {
self.db
.note_create_target(op.id, &parent.to_string(), name, now_millis())?;
match op.kind == OP_MKDIR {
true => Ok(self.block_on_bounded(self.drive.create_folder(
parent,
name,
Some(now_secs()),
))?),
false => self.upload_created_file(op, parent, name),
}
}
/// Upload the bytes a queued create accumulated, if any. A file that was
/// created but never written (`touch`) has no blob and uploads as empty.
pub(crate) fn upload_created_file(
&self,
op: &PendingOp,
parent: &NodeUid,
name: &str,
) -> Result<NodeUid, Box<dyn std::error::Error>> {
let Some(blob) = op.blob_path.as_deref() else {
return Ok(self.block_on_bounded(self.drive.upload_file(
parent,
name,
media_type_for(name),
b"",
))?);
};
let meta: StagedWrite = serde_json::from_str(op.meta_json.as_deref().unwrap_or(""))?;
// An incomplete blob would be authored bytes over zeros, and there is no
// base to repair it from — the file has never existed remotely. Refusing
// to queue that is `queue_revision`'s job, so reaching here means the blob
// is whole.
if !meta.complete {
return Err("queued create holds an incomplete blob".into());
}
// The call may make the file and lose its answer, and the op may hold
// a newer blob by the time it is retried (`Core::adoptable_twin`).
let sha = staged_sha1(Path::new(blob))?;
self.db.note_create_sent(op.id, &sha)?;
let thumbnails = self.upload_thumbnails(Path::new(blob), name);
let guard = self
.transfers
.begin(name, op.uid.clone(), TransferDirection::Upload, meta.len);
let reader = CountingReader::new(File::open(blob)?, &guard);
let uid = self.block_on_within(
link::upload_deadline(meta.len, self.transfers.upload_cap()),
self.drive.upload_file_from(
parent,
name,
media_type_for(name),
reader,
meta.len as i64,
thumbnails,
None,
false,
),
)?;
Ok(uid)
}
/// Retire a landed create's op and move its queued state to the real uid,
/// unless the create was withdrawn while it was on the wire.
///
/// Runs under the `pending` lock, which `Core::enqueue_staged_write` also
/// holds from attaching a blob to a create until it records the pending
/// entry. So a write either attached before this ran and is carried over,
/// or finds the create gone and queues against the real uid itself. The
/// open write handles are repointed right after, for the same reason:
/// a handle released later must not queue against the placeholder.
pub(crate) fn retire_create(
&self,
op: &PendingOp,
uploaded: Option<&str>,
landing: &CreateLanding<'_>,
local: &NodeUid,
real: &NodeUid,
) -> Result<CreateRetired, Box<dyn std::error::Error>> {
let retired = {
let mut pending = self.pending.lock();
let retired = self.db.finish_create(op.id, uploaded, landing, |json| {
let mut meta: StagedWrite = serde_json::from_str(json).ok()?;
meta.uid = landing.real.to_string();
serde_json::to_string(&meta).ok()
})?;
// A withdrawn create's placeholder is the delete's to clean up, and
// an open handle may still read its pending entry.
if let CreateRetired::Withdrawn { .. } = retired {
return Ok(retired);
}
pending.remove(local);
if let CreateRetired::Newer { blob, meta } = &retired {
let meta: StagedWrite = serde_json::from_str(meta)?;
pending.insert(
real.clone(),
PendingRevision {
path: PathBuf::from(blob),
meta,
},
);
}
retired
};
#[cfg(test)]
self.drive.landing(real);
if retired == CreateRetired::Landed
&& let Some(blob) = uploaded
{
self.cache_created(op, local, real, blob);
}
self.for_each_state(|st| {
if let Some(ino) = st.by_uid.remove(local) {
st.by_uid.insert(real.clone(), ino);
// The node too: the next write of it upserts the row by the
// node's uid, and would bring the placeholder row back.
if let Some(e) = st.entries.get_mut(&ino) {
e.uid = real.clone();
e.node.uid = real.clone();
}
// Its children still name the placeholder as their parent, and
// the next write of one would put it back on the row.
for kid in st.children.get(&ino).cloned().unwrap_or_default() {
if let Some(e) = st.entries.get_mut(&kid)
&& e.node.parent_uid.as_ref() == Some(local)
{
e.node.parent_uid = Some(real.clone());
}
}
}
for aw in st.active_writes.values_mut() {
if aw.uid == *local {
aw.uid = real.clone();
}
}
});
Ok(retired)
}
/// Cache a landed create's uploaded `blob` under `real`, keyed as the tree
/// has the file.
///
/// A write handle open on the file is repointed at `real` right after this,
/// and a release fills its gaps from the cache by the size and mtime it
/// opened over. Drive lists the new node a moment after the create, so
/// `adopt_real_uid` caches the bytes only once it can read the node back.
/// A release in between found nothing to fill from, and the next write open
/// was refused (docs/BUGS.md B131).
pub(crate) fn cache_created(
&self,
op: &PendingOp,
local: &NodeUid,
real: &NodeUid,
blob: &str,
) {
let Some(meta) = op
.meta_json
.as_deref()
.and_then(|json| serde_json::from_str::<StagedWrite>(json).ok())
else {
return;
};
let mut mtime = None;
self.for_each_state(|st| {
if let Some(entry) = st.by_uid.get(local).and_then(|ino| st.entries.get(ino)) {
mtime = Some(entry.node.modification_time);
}
});
if let Some(mtime) = mtime
&& keeps_landed_upload(self.cache.is_pinned(real), meta.len, self.cache.budget())
{
let _ = self
.cache
.store_file(real, mtime, meta.len, Path::new(blob));
}
}
/// Swap a placeholder uid for the real one across everything that keyed off
/// it: queued children, the DB, the in-memory tree, and the caches.
///
/// The inode is deliberately kept, so anything already holding the file open
/// keeps working across the drain.
///
/// Applied to the tree every mount shares. A node created inside an
/// on-demand sync folder once lived in that fork's own state, where the
/// primary mount's drain never looked, and stayed on its `local~` uid —
/// an empty file for as long as the daemon ran (`docs/BUGS.md` B74).
///
/// `adopt` sees the node as Drive made it, before anything is rebased onto
/// it.
pub(crate) fn adopt_real_uid(
&self,
local: &NodeUid,
real: &NodeUid,
adopt: impl FnOnce(&Node),
) -> Result<(), Box<dyn std::error::Error>> {
// A rename made while the create was on the wire is queued against the
// real uid (`Db::finish_create`). Until it lands, the tree keeps the
// name and folder the user gave it. Asked before the read-back: a
// rename that lands while Drive answers leaves no op behind, and the
// answer may still have the old name (`docs/BUGS.md` B161).
let real_key = real.to_string();
let renaming = self.db.has_pending_op(&real_key, OP_RENAME)?;
// Drive answers a create before it lists the new node.
let mut node = self
.read_back(real)
.map_err(|e| self.errno_error(e, "fetch node"))?;
// Before open handles are rebased onto the node, so one released in
// between finds what `adopt` keeps (`docs/BUGS.md` B123).
adopt(&node);
// What Drive holds is the base open handles and queued writes are
// rebased onto below. The tree shows a write queued over it, as a
// listing does: a write open sized from the landed node over a shorter
// queued blob left a gap that refused the next open (`docs/BUGS.md`
// B123).
let remote = node.clone();
self.stamp_pending_sizes(std::slice::from_mut(&mut node));
// 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.
self.for_each_state(|st| {
if let Some(ino) = st.by_uid.remove(local) {
st.by_uid.insert(real.clone(), ino);
}
let Some(&ino) = st.by_uid.get(real) else {
st.write_through(node.clone());
return;
};
// Asked again under the lock: `Core::queue_rename` queues its op
// before it renames the entry under this lock. Asked only before,
// a rename made since was overwritten with the name the create was
// sent with, here and in the node row (`docs/BUGS.md` B152).
let renaming =
renaming || matches!(self.db.has_pending_op(&real_key, OP_RENAME), Ok(true));
if renaming && let Some(e) = st.entries.get(&ino) {
node.name = e.node.name.clone();
node.parent_uid = e.node.parent_uid.clone();
}
st.write_through(node.clone());
let mut landed = node.clone();
st.keep_open_write_size(ino, &mut landed);
if let Some(e) = st.entries.get_mut(&ino) {
e.uid = real.clone();
e.node = landed;
}
// Where the op said the node goes and where it actually landed can
// differ — a conflict re-homes it — so the tree follows the parent
// the server reports rather than the one we asked for.
if let Some(parent) = node.parent_uid.clone()
&& let Some(&pino) = st.by_uid.get(&parent)
&& st.entries.get(&ino).is_some_and(|e| e.parent != pino)
{
let old = st.entries.get(&ino).map(|e| e.parent);
if let Some(old) = old
&& let Some(kids) = st.children.get_mut(&old)
{
kids.retain(|&k| k != ino);
}
if let Some(e) = st.entries.get_mut(&ino) {
e.parent = pino;
}
if let Some(kids) = st.children.get_mut(&pino)
&& !kids.contains(&ino)
{
kids.push(ino);
}
}
});
// A handle still open on the placeholder was based on no revision at
// all: a local-clock mtime and no revision id. Released as it is, its
// write would land as a conflict copy of the empty file this create just
// made (`docs/BUGS.md` B113). Rebased before the restamp below, so a
// release that races this is caught there.
//
// A release that took its base before the rebase and queues after the
// restamp is caught by neither. The revision this create sealed is
// ours, as one a revision upload sealed is, so the drain chains that
// write onto it instead of forking a conflict copy (B70 layer B).
if let Some(rev) = node_revision_id(&remote)
&& let Err(e) = self
.db
.set_own_sealed_rev(&real.to_string(), &rev, now_millis())
{
warn!(%real, error = %e, "persisting our sealed revision failed");
}
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.
self.rebaseline_pending(real, &remote);
if node.is_folder() {
// It was recorded as listed while local (it was empty and had nothing
// to enumerate). That still holds: its queued children re-intern under
// the real uid as they drain.
if let Err(e) = self.db.set_listed(real, true) {
warn!(%real, error = %e, "db set_listed(true) failed after remap");
}
}
Ok(())
}
/// Retire parks that are never going to end (docs/BUGS.md B70).
///
/// A parked create waits for one event: the rename from the transient name
/// to the finished one. Nothing else ever un-parks it, and plenty of writers
/// never perform it — an editor unlinks its swap file, a download is
/// abandoned, or the file was always going to be called `index.tmp`. Such a
/// row stayed at [`PARK_UNTIL`] for the life of the database, pinning the
/// only copy of its bytes in `staging/` and counting against the queue.
///
/// Two outcomes, and neither deletes bytes a user can still see:
///
/// * The node is gone from the tree — the file was deleted while its create
/// was parked, so the create is no longer wanted. The op and its blob go,
/// which is what [`Core::discard_queued_ops`] would have done had the
/// delete path reached it.
/// * The node is still there and has been parked past
/// [`PARK_EXPIRY_MS`] with nothing holding it open — the park has outlived
/// the writer it was protecting. Un-park it, and the ordinary drain
/// uploads it like any other create.
///
/// An open node is left alone whatever its age: it is still being written.
pub(crate) fn sweep_parked_creates(&self) {
let parked = match self.db.parked_create_ops() {
Ok(parked) if !parked.is_empty() => parked,
Ok(_) => return,
Err(error) => {
warn!(%error, "reading parked creates failed; skipping the park sweep");
return;
}
};
let now = now_millis();
let (mut released, mut dropped) = (0usize, 0usize);
for op in &parked {
let Some(uid) = parse_node_uid(&op.uid) else {
continue;
};
let name = op.name.as_deref().unwrap_or("?");
let listed = match self.db.node_by_uid(&op.uid) {
Ok(known) => known.is_some(),
// Never infer "deleted" from a failed read: that would discard
// the bytes over a transient database error.
Err(error) => {
debug!(%uid, %error, "cannot tell whether a parked node still exists");
continue;
}
};
match park_verdict(op.created_at, now, self.uid_is_open(&uid), listed) {
ParkVerdict::Keep => continue,
ParkVerdict::Drop => {
if let Err(error) = self.discard_queued_ops(&uid) {
warn!(%uid, name, ?error, "dropping a deleted transient's parked create failed");
continue;
}
dropped += 1;
debug!(%uid, name, "dropped a parked create whose file was deleted");
continue;
}
ParkVerdict::Release => {}
}
match self.db.set_create_hold(&op.uid, false) {
Ok(true) => {
released += 1;
info!(%uid, name, parked_ms = now - op.created_at,
"un-parked a transient create that was never renamed; uploading it");
}
Ok(false) => {}
Err(error) => warn!(%uid, name, %error, "un-parking an expired park failed"),
}
}
if released > 0 || dropped > 0 {
info!(released, dropped, "swept parked creates");
}
if released > 0 {
self.wake_drain();
}
}
}
+203
View File
@@ -0,0 +1,203 @@
//! Draining a rename or a move.
use super::*;
impl Core {
/// Apply a queued rename/move to the remote.
///
/// The op is the desired end state, so the remote's current state decides
/// what actually has to be called: either half may already match (the event
/// sync saw someone else do it, or an earlier attempt got half way through
/// before failing). That also makes the whole thing idempotent, which a
/// retrying queue needs.
pub(crate) fn drain_rename(&self, op: &PendingOp) -> Result<(), Box<dyn std::error::Error>> {
let uid = parse_node_uid(&op.uid).ok_or("rename op has an unparseable uid")?;
let parent_str = op.parent_uid.as_deref().ok_or("rename op has no parent")?;
if is_local_uid_str(parent_str) {
return Err(format!("destination {parent_str} has not been created yet").into());
}
let parent = parse_node_uid(parent_str).ok_or("rename op has an unparseable parent")?;
let name = op.name.clone().ok_or("rename op has no name")?;
// A trashed node can be restored. Only retire the operation if the node
// is gone entirely.
let node = match self.fetch_node_remote(&uid)? {
Some(n) if n.trashed => return Err(TrashedMove(n.name).into()),
Some(n) => n,
None => {
warn!(%uid, name, "renamed node is gone remotely; dropping the rename");
self.db.delete_op(op.id)?;
return Ok(());
}
};
let meta: Option<RenameMeta> = op
.meta_json
.as_deref()
.map(serde_json::from_str)
.transpose()?;
if let Some(meta) = &meta
&& moved_elsewhere(meta, &node, &parent, &name)
{
// Someone moved or renamed it while ours was queued. Ours still
// wins, as the last change does on Drive.
info!(%uid, from = %node.name, to = %name,
"node moved remotely while its rename was queued");
}
let landed = if node.parent_uid.as_ref() == Some(&parent) {
self.drain_rename_in_place(op, &uid, Some(&parent), &node.name, &name)?
} else {
// Move and rename land as one request (`move-multiple` takes a
// target name), so there is no half-applied state between them and
// no window for the requirements to go stale between two calls —
// the race B46 queued this op to get away from.
let target = (node.name != name).then_some(name.as_str());
let try_move = |target| {
self.move_rename_remote(&uid, &parent, target).map_err(
|error| -> Box<dyn std::error::Error> {
if (is_gone(&error) || refusal(&error) == Some(Some(SyncIssue::Access)))
&& let Some(name) = trashed_move_folder(
node.parent_uid.iter().chain(std::iter::once(&parent)),
|uid| self.fetch_node_remote(uid).ok().flatten(),
)
{
return TrashedMove(name).into();
}
error.into()
},
)
};
match try_move(target) {
Ok(()) => name.clone(),
// The destination holds that name already. Landing under a
// *different* name is the non-destructive resolution: it neither
// clobbers their file nor drops ours, and it is visible.
Err(e) if is_already_exists(e.as_ref()) => {
if self.name_is_held(op, Some(&parent), &name)? {
return Err(held_by_queued_change(&name));
}
// What held it may have let go since Drive answered
// (docs/BUGS.md B144).
match try_move(target) {
Ok(()) => name.clone(),
Err(e) if is_already_exists(e.as_ref()) => {
let alt = conflict_name(&name, now_secs());
warn!(%uid, name, alt, "destination already holds that name; using a conflict name");
try_move(Some(&alt))?;
self.adopt_drained_name(&uid, &alt);
self.log_activity(
ActivityKind::Rename,
&name,
format!("destination already had that name; moved as {alt}"),
false,
);
alt
}
Err(e) => return Err(e),
}
}
// The destination folder is gone. Leaving the node in its current
// parent is the honest outcome: it is not where the user asked for
// it, but it exists and it is where it has always been. The name
// the user chose still applies there. Retrying the move could
// only fail again — the folder is not coming back — and would
// wedge the queue.
Err(e) if is_gone(e.as_ref()) => {
warn!(%uid, name, %parent, "move destination is gone; leaving the node where it is");
let landed = match self.drain_rename_in_place(
op,
&uid,
node.parent_uid.as_ref(),
&node.name,
&name,
) {
Ok(landed) => landed,
// The node went with it; nothing is left to rename.
Err(e) if is_gone(e.as_ref()) => node.name.clone(),
Err(e) => return Err(e),
};
self.log_activity(
ActivityKind::Rename,
&landed,
"destination folder no longer exists; the file was left in place"
.to_string(),
false,
);
landed
}
Err(e) => return Err(e),
}
};
self.db.delete_op(op.id)?;
// An op that wanted the name this node let go of waits no longer.
if let Some(from) = meta.and_then(|m| m.original_name)
&& from != landed
{
self.db.wake_ops_waiting_for(&from)?;
self.wake_drain();
}
info!(%uid, name = %landed, "pending rename landed");
Ok(())
}
/// Rename `uid` without moving it, from `current` to `name`, and return the
/// name it landed under. Someone may have taken the name while we were
/// offline; the node then lands under a conflict name instead.
pub(crate) fn drain_rename_in_place(
&self,
op: &PendingOp,
uid: &NodeUid,
parent: Option<&NodeUid>,
current: &str,
name: &str,
) -> Result<String, Box<dyn std::error::Error>> {
if current == name {
return Ok(current.to_string());
}
match self.rename_remote(uid, name) {
Ok(()) => Ok(name.to_string()),
Err(e) if is_already_exists(&e) => {
if self.name_is_held(op, parent, name)? {
return Err(held_by_queued_change(name));
}
// What held it may have let go since Drive answered
// (docs/BUGS.md B144).
match self.rename_remote(uid, name) {
Ok(()) => return Ok(name.to_string()),
Err(e) if is_already_exists(&e) => {}
Err(e) => return Err(e.into()),
}
let alt = conflict_name(name, now_secs());
warn!(%uid, name, alt, "rename target name is taken; using a conflict name");
self.rename_remote(uid, &alt)?;
self.adopt_drained_name(uid, &alt);
self.log_activity(
ActivityKind::Rename,
name,
format!("name was taken remotely; renamed to {alt}"),
false,
);
Ok(alt)
}
Err(e) => Err(e.into()),
}
}
/// Record the name the remote actually gave a node, after a conflict forced
/// it away from the one the user asked for. Best effort: the event sync
/// would correct the tree anyway, but not before the user has looked at it.
pub(crate) fn adopt_drained_name(&self, uid: &NodeUid, name: &str) {
self.for_each_state(|st| {
let Some(&ino) = st.by_uid.get(uid) else {
return;
};
let Some(entry) = st.entries.get_mut(&ino) else {
return;
};
entry.node.name = name.to_string();
let node = entry.node.clone();
if let Err(e) = st.db.upsert_node(&node) {
warn!(%uid, error = %e, "db upsert_node failed after a conflict rename");
}
});
}
}
+702
View File
@@ -0,0 +1,702 @@
//! Draining a revision: the upload, the conflict check before it, and
//! placing what landed in the tree and the cache.
use super::*;
impl Core {
/// How long a freshly queued revision of `uid` should wait before a worker
/// may pick it up.
///
/// [`DRAIN_REVISION_DEBOUNCE`] exists for a tool that preallocates a file
/// and then writes it, where two seconds is the right scale. It is the wrong
/// scale for a large file on a slow link: an editor saving a 200 MB project
/// every ten seconds queues a write, the drain starts sending it, the next
/// save supersedes it mid-flight, and the file never finishes uploading
/// while the user keeps working. Waiting roughly as long as the last upload
/// of *this* node took moves that supersede into the queue, where replacing
/// a row costs nothing.
///
/// Never shorter than the fixed debounce and never longer than
/// [`DRAIN_REVISION_DEBOUNCE_MAX`]: a node whose upload is genuinely slow
/// still has to reach Drive, and a single pathological stall must not park
/// it.
///
/// [`DRAIN_REVISION_DEBOUNCE`]: crate::DRAIN_REVISION_DEBOUNCE
/// [`DRAIN_REVISION_DEBOUNCE_MAX`]: crate::DRAIN_REVISION_DEBOUNCE_MAX
pub(crate) fn revision_debounce(&self, uid: &NodeUid) -> Duration {
let measured = self
.drain
.upload_times
.lock()
.get(&uid.to_string())
.map(|&(ms, _)| Duration::from_millis(ms));
adaptive_debounce(measured)
}
/// Remember how long an upload of `uid` took, for the next write's
/// debounce.
///
/// Only a *completed* upload is a measurement. A cancelled or failed one
/// says how long it ran before it stopped, which is not how long the file
/// takes to send, and feeding that back would let one network fault widen
/// the debounce for good.
pub(crate) fn record_upload_time(&self, uid: &NodeUid, took: Duration) {
let mut times = self.drain.upload_times.lock();
let now = now_millis();
if times.len() >= UPLOAD_TIME_MEMORY
&& !times.contains_key(&uid.to_string())
&& let Some(oldest) = times
.iter()
.min_by_key(|(_, (_, at))| *at)
.map(|(k, _)| k.clone())
{
times.remove(&oldest);
}
times.insert(uid.to_string(), (took.as_millis() as u64, now));
}
/// Register a cancellation flag for an upload of `uid` that is about to
/// start, returning a guard that deregisters it.
///
/// Deregistration is by identity rather than by key: a supersede that
/// arrives just as this upload finishes may already have registered the
/// *next* upload's flag under the same uid, and removing that one would
/// leave the newer upload uncancellable.
pub(super) fn begin_cancellable_upload(&self, uid: &NodeUid) -> UploadCancel {
let flag = Arc::new(AtomicBool::new(false));
self.drain
.upload_cancel
.lock()
.insert(uid.clone(), flag.clone());
UploadCancel {
registry: self.drain.upload_cancel.clone(),
uid: uid.clone(),
flag,
}
}
/// Tell an upload of `uid` that is on the wire to stop, if there is one.
///
/// Called when a newer revision of the file is queued. The upload does not
/// stop instantly — it stops when the SDK next asks its reader for bytes,
/// which for a 4 MiB block is soon enough to matter and late enough to be
/// safe: the staged blob it is reading stays open until it lets go.
pub(crate) fn cancel_upload(&self, uid: &NodeUid) {
if let Some(flag) = self.drain.upload_cancel.lock().get(uid) {
flag.store(true, Ordering::Relaxed);
debug!(%uid, "cancelling a superseded upload");
}
}
/// Why a queued write must not be applied to its node, or `None` when it
/// still can be.
///
/// A queued write is an edit of a specific revision. Time passes before it
/// drains — indefinitely, if that is how long the network is gone — and in
/// that window the node can be rewritten by another device, trashed, or
/// deleted outright. Sending the blob anyway would silently drop whatever
/// happened in between, which is exactly the thing the sync engine refuses
/// to do.
///
/// Only checkable against a recorded baseline: a write staged before
/// [`StagedWrite::based_on`] existed, or one against a node that has never
/// existed remotely, has nothing to compare and is applied as before.
pub(crate) fn revision_conflict(
&self,
uid: &NodeUid,
meta: &StagedWrite,
blob: &Path,
) -> Result<Option<String>, Box<dyn std::error::Error>> {
let Some(ref base) = meta.based_on else {
return Ok(None);
};
let Some(node) = self.fetch_node_remote(uid)? else {
return Ok(Some("the file no longer exists remotely".into()));
};
if node.trashed {
return Ok(Some("the file was trashed remotely".into()));
}
let Some(reason) = revision_changed(base, &node) else {
return Ok(None);
};
// The remote moved on from the baseline — normally a conflict. But if it
// sits at a revision *this daemon* sealed, no other device changed the
// file: it is a single-writer stall→resume (a browser that closed and
// reopened its download fd; B70 layer B). Chain onto it — supersede
// instead of forking — so the finished bytes win the name rather than
// being exiled to a `(sync-conflict)` copy.
let remote_rev = node_revision_id(&node);
// The table, so the answer survives a restart (`own_sealed_rev`).
let own_rev = self
.db
.own_sealed_rev(&uid.to_string(), now_millis())
.unwrap_or_default();
if is_own_self_supersede(meta.complete, remote_rev.as_deref(), own_rev.as_deref()) {
debug!(%uid, ?remote_rev,
"queued write chains onto our own sealed revision; not a conflict");
return Ok(None);
}
// An earlier attempt at this write may have landed with its answer
// lost: the remote then holds these very bytes in a revision we never
// heard of. Forked, the write was a conflict copy of itself
// (docs/BUGS.md B155); sent again, it is a revision of the same bytes.
if meta.complete
&& node_size(&node) == meta.len
&& let NodeKind::File {
content_sha1: Some(remote),
..
} = &node.kind
&& remote.eq_ignore_ascii_case(&staged_sha1(blob)?)
{
debug!(%uid, ?remote_rev, "the remote already holds the queued write; not a conflict");
return Ok(None);
}
// An upload of ours landed and its read-back went unanswered, so its
// revision id was never recorded as ours. The bytes it sent say the
// same: the remote holds them, so no other device wrote since
// (docs/BUGS.md B157).
let sealed = self.drain.sealed_unread.lock().get(uid).cloned();
if meta.complete
&& let Some(sealed) = sealed
&& let NodeKind::File {
content_sha1: Some(remote),
..
} = &node.kind
&& remote.eq_ignore_ascii_case(&sealed)
{
debug!(%uid, ?remote_rev, "queued write chains onto our own unread revision; not a conflict");
return Ok(None);
}
Ok(Some(reason))
}
/// Land a queued write that can no longer be applied to its own node as a
/// *new* file beside it, and retire the op.
///
/// The non-destructive resolution, and the same one the sync engine reaches
/// for: the remote keeps whatever it has, the user keeps their bytes, and
/// the name says which is which.
///
/// An incomplete blob is gap-filled from whatever the node holds *now* —
/// mixing revisions, which is only defensible because the result is
/// explicitly a conflict copy rather than anyone's file. When even that is
/// impossible the op is dropped but the staged bytes are deliberately left
/// on disk: unreachable through the mount, but not destroyed, and the
/// activity log says where they are.
pub(crate) fn keep_as_conflict_copy(
&self,
op: &PendingOp,
blob: &Path,
meta: &StagedWrite,
uid: &NodeUid,
reason: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let place = self.node_place(uid);
let name = place
.as_ref()
.map(|(_, n)| n.clone())
.unwrap_or_else(|| self.node_name(uid));
// A node the tree has forgotten still has bytes worth keeping, so the
// copy falls back to the root rather than being abandoned. So does one
// whose folder went with it: an upload into a folder Drive no longer
// has fails on every retry (B150).
let folder = match place.map(|(p, _)| p) {
Some(p) if self.fetch_node_remote(&p)?.is_some_and(|n| !n.trashed) => Some(p),
_ => None,
};
let Some(parent) = folder.or_else(|| self.root_uid()) else {
return self.abandon_to_staging(op, blob, uid, &name, reason);
};
warn!(%uid, name, reason, "queued write conflicts; keeping a conflict copy");
if !meta.complete {
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(blob)?;
let mut written = Intervals::default();
for &(s, e) in &meta.authored {
written.add(s, e);
}
if let Err(e) = self.fill_gaps(
uid,
&file,
meta.len,
meta.base_mtime,
meta.base_size,
&written,
) {
error!(%uid, name, error = ?e, "cannot complete a conflicted partial write");
return self.abandon_to_staging(op, blob, uid, &name, reason);
}
}
let alt = conflict_name(&name, now_secs());
let thumbnails = self.upload_thumbnails(blob, &alt);
let guard =
self.transfers
.begin(&alt, meta.uid.clone(), TransferDirection::Upload, meta.len);
let reader = CountingReader::new(File::open(blob)?, &guard);
self.block_on_within(
link::upload_deadline(meta.len, self.transfers.upload_cap()),
self.drive.upload_file_from(
&parent,
&alt,
media_type_for(&alt),
reader,
meta.len as i64,
thumbnails,
None,
false,
),
)?;
drop(guard);
self.db.delete_op(op.id)?;
// Dropping the pending entry hands the node back to the remote's truth:
// reads stop coming from the staged blob, and the event sync stops
// skipping it as "ahead of the server". Only if it
// is still *this* write's entry — see [`Core::release_pending`].
self.release_pending(uid, blob);
self.cache.discard_staged(blob);
self.cache.evict(uid);
self.evict_reader(uid);
// The conflict copy is a node the tree has never seen.
self.for_each_state(|st| {
if let Some(&ino) = st.by_uid.get(&parent) {
st.invalidate_listing(ino);
}
});
self.log_activity(
ActivityKind::Upload,
&name,
format!("{reason}; local changes uploaded as {alt}"),
false,
);
self.events.publish(&[
pdfs_core::control::Topic::Files,
pdfs_core::control::Topic::Conflicts,
]);
info!(%uid, name, alt, "queued write landed as a conflict copy");
Ok(())
}
/// Give up on placing a queued write anywhere the mount can see, without
/// destroying it: the op goes (it could only fail forever) but the staged
/// blob deliberately stays on disk, and the activity log says where.
///
/// The last resort of the conflict path, and the same bargain
/// [`Core::stage_orphaned_write`] strikes at the other end: bytes we cannot
/// place are still bytes we do not get to delete.
pub(crate) fn abandon_to_staging(
&self,
op: &PendingOp,
blob: &Path,
uid: &NodeUid,
name: &str,
reason: &str,
) -> Result<(), Box<dyn std::error::Error>> {
error!(%uid, name, reason, staged = %blob.display(),
"cannot place a conflicted write; bytes kept in staging");
self.db.delete_op(op.id)?;
self.release_pending(uid, blob);
self.cache.evict(uid);
self.evict_reader(uid);
self.log_activity(
ActivityKind::Upload,
name,
format!("{reason}; local changes kept at {}", blob.display()),
false,
);
Ok(())
}
/// Upload a staged revision of a file the server already knows about.
pub(crate) fn drain_revision(&self, op: &PendingOp) -> Result<(), Box<dyn std::error::Error>> {
let op_started = Instant::now();
let blob = op
.blob_path
.clone()
.ok_or("pending op has no staged blob")?;
let blob = PathBuf::from(blob);
let mut meta: StagedWrite = serde_json::from_str(op.meta_json.as_deref().unwrap_or(""))?;
let uid = parse_node_uid(&meta.uid).ok_or("staged write has an unparseable uid")?;
if let Some(reason) = self.revision_conflict(&uid, &meta, &blob)? {
// Trashing the file from the mount drops its queued write, but not
// from under a worker already holding it. That worker then finds the
// node trashed — by us — and would upload the withdrawn bytes as a
// conflict copy (a `recovered-…` file in the root when the tree has
// already forgotten the node). A write nobody queues any more is
// not a conflict.
if !self.db.op_exists(op.id)? {
debug!(%uid, reason, "queued write withdrawn while it drained; dropping it");
return Ok(());
}
return self.keep_as_conflict_copy(op, &blob, &meta, &uid, &reason);
}
// An incomplete blob is authored bytes over zeros; the untouched ranges
// have to be filled from the base before it can be sent. This is the case
// the write could not resolve at release time (it was offline), and the
// reason it is safe to do now is that we are not.
if !meta.complete {
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(&blob)?;
let mut written = Intervals::default();
for &(s, e) in &meta.authored {
written.add(s, e);
}
self.fill_gaps(
&uid,
&file,
meta.len,
meta.base_mtime,
meta.base_size,
&written,
)
.map_err(|e| self.errno_error(e, "gap-fill from base failed"))?;
// The blob is whole now. Recorded, so that a retry after a lost
// answer can match these bytes against the server's revision
// (`revision_conflict`) instead of forking a conflict copy of the
// user's own write.
meta.complete = true;
match serde_json::to_string(&meta) {
Ok(json) => {
let path = op.blob_path.as_deref().unwrap_or_default();
if let Err(e) = self.db.update_op_meta_for_blob(op.id, path, &json) {
warn!(%uid, error = %e,
"recording a gap-filled blob as whole failed; \
a lost answer may land it as a conflict copy");
}
}
Err(e) => warn!(%uid, error = %e, "serializing a gap-filled sidecar failed"),
}
}
let name = self.node_name(&uid);
let thumbnails = self.upload_thumbnails(&blob, &name);
let guard =
self.transfers
.begin(&name, meta.uid.clone(), TransferDirection::Upload, meta.len);
// Registered before the first byte moves, so a write that lands while
// this is on the wire can stop it rather than paying for a revision the
// op it queued will immediately replace.
let cancel = self.begin_cancellable_upload(&uid);
// An unlink that withdrew this op before the flag above existed had no
// upload to cancel; the row is the record that it happened.
if !self.db.op_exists(op.id)? {
debug!(%uid, "queued write withdrawn before it went out; dropping it");
return Ok(());
}
let reader = CountingReader::new(File::open(&blob)?, &guard).with_cancel(cancel.flag());
let started = Instant::now();
let sent = self.block_on_within(
link::upload_deadline(meta.len, self.transfers.upload_cap()),
self.drive
.upload_new_revision_from(&uid, reader, meta.len as i64, thumbnails, None),
);
let took = started.elapsed();
if let Err(e) = sent {
if cancel.cancelled() {
// Not a failure, and not this op's row to retire: the write that
// cancelled us deleted it and took ownership of the staged blob
// when it superseded this revision. Leaving the blob alone here
// is the whole point — it is either already unlinked or it
// belongs to the newer op.
info!(%uid, "upload abandoned; a newer write superseded it");
return Ok(());
}
return Err(e.into());
}
drop(cancel);
drop(guard);
// Only a completed upload times how long this file takes to send, which
// is what the next write's debounce is scaled from.
self.record_upload_time(&uid, took);
// Still pending to whoever asks until the bytes are cached below, and
// counted before the op goes so the status never reads empty in between.
// An empty queue is how a script or the app knows a written file reads
// without the network; retiring the op alone left the read-back's round
// trip in which it did not (B119). The op itself has to go first: one
// restored after a crash would re-send a revision this daemon has not
// yet recorded as its own, and come back as a conflict copy.
let _landing = LandingUpload::begin(&self.drain.landing_uploads);
// Retire the op before dropping the blob: a crash between the two leaves
// an orphaned file (harmless), whereas the reverse would leave a queued
// op pointing at nothing.
self.db.delete_op(op.id)?;
self.evict_reader(&uid);
// The staged blob now matches the sealed revision, so it becomes the
// file's cached content, stamped like the revision just read back.
// Reading the file again then needs no network, which an editor or a
// build does at once and a flaky link cannot always give (`docs/BUGS.md`
// B119). Adopted by link, not by value: the blob is the whole file, and
// a video read into a `Vec` here is an OOM. `discard_staged` below drops
// the staging name only — the cache keeps the inode.
self.refresh_after_upload(&uid, &blob, |mtime, size| {
if size == meta.len
&& keeps_landed_upload(self.cache.is_pinned(&uid), meta.len, self.cache.budget())
{
let _ = self.cache.store_file(&uid, mtime, meta.len, &blob);
}
});
self.cache.discard_staged(&blob);
self.log_activity(ActivityKind::Upload, &name, "uploaded", true);
// Both times, so a slow drain shows whether the upload itself or the
// checks and gap-fill around it are where the time goes.
info!(
%uid,
len = meta.len,
upload_ms = took.as_millis() as u64,
total_ms = op_started.elapsed().as_millis() as u64,
"pending upload landed"
);
Ok(())
}
/// Adopt the server's metadata for a node we have just uploaded a revision
/// for.
///
/// [`State::record_pending_write`] deliberately stamps the node with the
/// moment we *accepted* the write, so `ls` reflects it before the upload
/// lands. The server stamps the sealed revision with its own time, and the
/// two differ by however long the upload took. That difference is not
/// cosmetic: [`Core::remote_baseline`] reads this node to build
/// [`StagedWrite::based_on`], and [`Core::revision_conflict`] compares that
/// baseline against the remote — so leaving our optimistic time in place
/// makes the *next* write to this file look like another device changed it
/// underneath us, and diverts it into a conflict copy over nothing.
///
/// A write queued while this upload was on the wire is handled instead by
/// [`Core::rebaseline_pending`]: its optimistic size/mtime must stay on the
/// node (the same reason `apply_event` refuses to overwrite a node with a
/// queued write), but its *baseline* still has to learn about the revision
/// we just sealed. Skipping both, as this used to, is what produced a file
/// that conflicted with itself and left a full-size duplicate behind.
///
/// `blob` is the revision that landed, which stays the pending one until
/// open write handles are rebased off it, and `adopt` gets the mtime and
/// size of the node read back before that, so the uploaded bytes can be
/// cached under its revision first. A handle released in between fills its
/// gaps from one or the other; with the blob let go first and the cache
/// filled last, it found neither, and the next write open was refused
/// (docs/BUGS.md B123). When the node cannot be read back, `adopt` gets
/// the stamp the tree still has, which is the base a write opened next
/// takes: without it the blob went and nothing replaced it (B157). The
/// blob's digest then stands in for the revision id the read-back did
/// not bring, so the next write knows the revision as its own.
///
/// Best effort: a failure here costs a spurious conflict copy on the next
/// write, not this upload, which has already landed. Returns the node as
/// the server now has it, or `None` when it could not be read back.
pub(crate) fn refresh_after_upload(
&self,
uid: &NodeUid,
blob: &Path,
adopt: impl FnOnce(i64, u64),
) -> Option<Node> {
// Asked before the read-back: the op went before it, so a rename queued
// behind the upload can land while Drive answers, and the answer may
// still have the old name (`docs/BUGS.md` B172).
let placed = self.placement(uid);
let renaming = self
.db
.has_pending_op(&uid.to_string(), OP_RENAME)
.unwrap_or(false);
let fetched = self.fetch_node_remote(uid);
if fetched.is_ok() {
self.drain.sealed_unread.lock().remove(uid);
}
let node = match fetched {
Ok(Some(node)) => node,
// Trashed or deleted under us: the tree will hear it from the event
// sync, which is better placed to unhook the inode than we are.
Ok(None) => {
self.release_pending(uid, blob);
return None;
}
Err(e) => {
warn!(%uid, error = %e,
"refreshing metadata after an upload failed; \
the next write to this file may conflict with itself");
match staged_sha1(blob) {
Ok(sha) => {
self.drain.sealed_unread.lock().insert(uid.clone(), sha);
}
Err(_) => {
self.drain.sealed_unread.lock().remove(uid);
}
}
// No newer write took over, so the tree's stamp is this upload's.
if self.pending_blob(uid).as_deref() == Some(blob) {
let mut stamp = None;
self.for_each_state(|st| {
if let Some(entry) = st.by_uid.get(uid).and_then(|ino| st.entries.get(ino))
{
stamp = Some((entry.node.modification_time, node_size(&entry.node)));
}
});
if let Some((mtime, size)) = stamp {
adopt(mtime, size);
}
}
self.release_pending(uid, blob);
return None;
}
};
adopt(node.modification_time, node_size(&node));
// This function's whole job is to bring the tree level with the revision
// we just sealed, so the feed's report of that revision has nothing left
// to tell us. Claimed here rather than at the upload call so it is only
// recorded when the node was actually re-read (`Core::self_changes`).
self.note_self_change(uid);
// Rebase any *open* write handles targeting this node. A handle opened
// before this upload carries a stale base — its `base_mtime`/`base_size`
// name the revision we just replaced. Without this update,
// `remote_baseline` will build a `based_on` from those stale values, the
// drain will compare them against the revision we sealed, and the write
// will be diverted into a conflict copy of itself.
//
// This is the open-handle counterpart of `rebaseline_pending`, which
// covers the same gap for *queued* ops.
{
// Remember it as ours, so a queued write that opened over an earlier
// revision recognises this as a self-supersede rather than a foreign
// change and does not fork (B70 layer B; consulted in
// `revision_conflict`).
if let Some(rev) = node_revision_id(&node) {
// In the table, not in memory: losing it at shutdown reopened
// the fork window B70 layer B closed, for the first drain
// after a restart.
if let Err(e) = self
.db
.set_own_sealed_rev(&uid.to_string(), &rev, now_millis())
{
warn!(%uid, error = %e, "persisting our sealed revision failed");
}
}
// A write open from here until the tree has the node takes it as
// its base: the blob it would have copied is let go of below, and
// the tree's stamp names the revision this one replaced
// (docs/BUGS.md B170).
self.drain.landed.lock().insert(uid.clone(), node.clone());
self.rebase_open_writes(uid, &node);
}
self.release_pending(uid, blob);
#[cfg(test)]
self.drive.landing(uid);
self.place_landed(uid, &node, placed, renaming);
self.drain.landed.lock().remove(uid);
Some(node)
}
/// Put a node whose upload just landed into the tree, unless a newer write
/// is queued for it. `before` is where the tree had the node and
/// `renaming` whether a rename of it was queued, both from before the
/// read-back.
pub(crate) fn place_landed(
&self,
uid: &NodeUid,
node: &Node,
before: Option<(String, Option<NodeUid>)>,
renaming: bool,
) {
// Ordered so that a write queued *during* the fetch above is still
// caught: it took its baseline from the node's optimistic stamp, and
// this overwrites it with the revision the server actually holds.
if self.rebaseline_pending(uid, node) {
return;
}
// A rename queued behind the upload has not reached Drive yet, or
// landed after Drive read the node back, and the tree keeps the name
// and folder the user gave the file, as `adopt_real_uid` does. Taking
// Drive's put the file back under its old name. A rename queued since
// the read-back began has already moved the entry when the tree is
// updated, so a name that changed in between is the user's too
// (docs/BUGS.md B146, B172).
let renaming = renaming
|| self
.db
.has_pending_op(&uid.to_string(), OP_RENAME)
.unwrap_or(false);
self.for_each_state(|st| {
let moved = placed_in(st, uid) != before;
let Some(entry) = st.by_uid.get(uid).and_then(|ino| st.entries.get(ino)) else {
return;
};
let parent = entry.parent;
let mut node = node.clone();
if renaming || moved {
node.name = entry.node.name.clone();
node.parent_uid = entry.node.parent_uid.clone();
}
st.intern(parent, node);
});
}
/// Where the tree has `uid`: its name and parent.
pub(crate) fn placement(&self, uid: &NodeUid) -> Option<(String, Option<NodeUid>)> {
placed_in(&self.state(), uid)
}
/// Rebase every write handle open on `uid` onto `node`, a revision this
/// 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() {
if aw.uid == *uid {
aw.rebase_onto(node);
debug!(%uid, mtime = aw.base_mtime, size = aw.base_size,
"rebased open write handle onto the revision just landed");
}
}
});
}
/// Point a still-queued write at the revision this upload just sealed, and
/// report whether there was one.
///
/// The revision we sent *is* the base the queued write will be applied over,
/// but nothing else says so. [`Core::remote_baseline`] carries a baseline
/// across a supersede because the op it inherits from "is the last one that
/// actually observed the remote" — true only until that op drains. Once it
/// has, the inherited baseline names a revision we replaced ourselves, and
/// [`Core::revision_conflict`] reads that as another device having moved the
/// file. It is a self-conflict, and it is expensive: the whole staged blob
/// is re-uploaded as a second file.
///
/// Both copies of the sidecar are updated — the in-memory one the next
/// `release` inherits from, and the persisted one the drain reloads after a
/// restart. Best effort on the DB half; the in-memory half is what the
/// immediate next write reads.
pub(crate) fn rebaseline_pending(&self, uid: &NodeUid, sealed: &Node) -> bool {
let base = Baseline {
mtime: sealed.modification_time,
size: node_size(sealed),
hash: None,
revision_id: node_revision_id(sealed),
};
let mut pending = self.pending.lock();
let Some(p) = pending.get_mut(uid) else {
return false;
};
p.meta.based_on = Some(base.clone());
match serde_json::to_string(&p.meta) {
Ok(json) => {
if let Err(e) = self.db.update_op_meta(&uid.to_string(), OP_REVISION, &json) {
warn!(%uid, error = %e,
"restamping a queued write's baseline failed; \
it may land as a conflict copy of itself");
}
}
Err(e) => warn!(%uid, error = %e, "serializing a restamped sidecar failed"),
}
debug!(%uid, mtime = base.mtime, size = base.size,
"queued write rebaselined onto the revision just uploaded");
true
}
}
+224
View File
@@ -0,0 +1,224 @@
//! Draining a trash, and withdrawing a create that was removed before it
//! landed.
use super::*;
impl Core {
/// Apply a queued trash to the remote.
///
/// A node that is already gone is a success, not a failure: the outcome the
/// op asked for holds either way, and retrying forever against a node the
/// server has forgotten would wedge the queue.
pub(crate) fn drain_trash(&self, op: &PendingOp) -> Result<(), Box<dyn std::error::Error>> {
let uid = parse_node_uid(&op.uid).ok_or("trash op has an unparseable uid")?;
let name = op.name.clone().unwrap_or_else(|| op.uid.clone());
// The trash a delete left of a create that was sent, on the wire or
// before, and failed (`Db::delete_ops_for_uid`). A create that failed
// may still have made the node and lost only its answer, and the node
// would keep the deleted file's name and bytes (docs/BUGS.md B151).
if is_local_uid_str(&op.uid) {
match self.withdrawn_twin(op)? {
Some(twin) => {
self.hidden.lock().insert(twin.clone());
match self
.block_on_bounded(self.drive.trash_nodes(std::slice::from_ref(&twin)))
.and_then(batch::into_unit)
{
Ok(()) => {}
Err(e) if is_gone(&e) => {}
Err(e) => return Err(e.into()),
}
self.invalidate_trash();
info!(%uid, %twin, name, "a withdrawn create had landed unanswered; trashed it");
}
None => debug!(%uid, name, "withdrawn create never landed; trash op satisfied"),
}
self.retire_trash_op(op, &uid)?;
return Ok(());
}
match self
.block_on_bounded(self.drive.trash_nodes(std::slice::from_ref(&uid)))
.and_then(batch::into_unit)
{
Ok(()) => {}
Err(e) if is_gone(&e) => {
debug!(%uid, name, "node was already gone remotely; trash op satisfied");
}
Err(e) => return Err(e.into()),
}
self.retire_trash_op(op, &uid)?;
// A file trashed while open kept the bytes its handle reads, and a
// final close while the trash was queued left them to this
// (`docs/BUGS.md` B186).
if !self.is_open_anywhere(&uid) {
if let Some(blob) = self.pending_blob(&uid) {
self.release_pending(&uid, &blob);
self.cache.discard_staged(&blob);
}
self.cache.evict(&uid);
self.evict_reader(&uid);
}
if let Err(e) = self.db.clear_own_sealed_rev(&uid.to_string()) {
debug!(%uid, error = %e, "clearing the sealed-revision record failed");
}
self.invalidate_trash();
self.log_activity(ActivityKind::Trash, &name, "trashed", true);
info!(%uid, name, "pending trash landed");
Ok(())
}
/// Remove a trash op that landed, and the blob of a create it withdrew.
pub(crate) fn retire_trash_op(
&self,
op: &PendingOp,
uid: &NodeUid,
) -> Result<(), Box<dyn std::error::Error>> {
if let Some(blob) = self.db.complete_trash_op(op.id, uid)? {
self.cache.discard_staged(Path::new(&blob));
}
Ok(())
}
/// The node a create that a trash withdrew made on Drive although its
/// answer was lost: in the create's folder under its name, or under one
/// an attempt was sent with before a rename (`docs/BUGS.md` B184).
pub(crate) fn withdrawn_twin(
&self,
op: &PendingOp,
) -> Result<Option<NodeUid>, Box<dyn std::error::Error>> {
let mut targets: Vec<(String, String)> = op
.parent_uid
.clone()
.zip(op.name.clone())
.into_iter()
.collect();
for target in self.db.create_targets(op.id)? {
if !targets.contains(&target) {
targets.push(target);
}
}
for (parent, name) in targets {
if is_local_uid_str(&parent) {
continue;
}
let Some(parent) = parse_node_uid(&parent) else {
continue;
};
if let Some(twin) = self.withdrawn_twin_in(op, &parent, &name)? {
return Ok(Some(twin));
}
}
Ok(None)
}
/// The node in `parent` under `name` a withdrawn create made, if it is one
/// the create would have adopted had it been retried ([`adoptable`]). A
/// node with a change of ours queued is one the user is still working on.
pub(crate) fn withdrawn_twin_in(
&self,
op: &PendingOp,
parent: &NodeUid,
name: &str,
) -> Result<Option<NodeUid>, Box<dyn std::error::Error>> {
let uids =
match self.block_on_bounded(self.drive.enumerate_folder_children_node_uids(parent)) {
Ok(uids) => uids,
Err(e) if is_gone(&e) => return Ok(None),
Err(e) => return Err(e.into()),
};
let children = self.block_on_bounded(self.drive.enumerate_nodes_light(&uids))?;
// As for a create's own twin (`Core::adoptable_twin`): a node this
// mount trashed is not one, and a node in the tree was answered for.
// A file of the user's renamed to the name the create was sent under
// was taken for it, and trashed (`docs/BUGS.md` B193).
let hidden = self.hidden.lock().clone();
let Some(twin) = children
.into_iter()
.find(|node| node.name == name && !node.trashed && !hidden.contains(&node.uid))
else {
return Ok(None);
};
if self.state().by_uid.contains_key(&twin.uid) {
return Ok(None);
}
let queued = twin.uid.to_string();
for kind in [OP_RENAME, OP_REVISION, OP_TRASH] {
if self.db.has_pending_op(&queued, kind)? {
return Ok(None);
}
}
let is_dir = match twin.kind {
// A folder made by a create that never answered has nothing in
// it: what was queued inside waited for its uid.
NodeKind::Folder => {
let inside = self
.block_on_bounded(self.drive.enumerate_folder_children_node_uids(&twin.uid))?;
if !inside.is_empty() {
return Ok(None);
}
true
}
NodeKind::File { .. } => false,
};
let twin = match is_dir {
true => twin,
false => match self.fetch_node_remote(&twin.uid)? {
Some(node) => node,
None => return Ok(None),
},
};
// A blob gone from staging matches nothing, and leaves the node be.
let current = match op.blob_path.as_deref() {
Some(blob) if node_size(&twin) > 0 => staged_sha1(Path::new(blob)).ok(),
_ => None,
};
let sent = self.create_sent_digests(op.id, current);
Ok(adoptable(is_dir, &twin, self.first_sent(op), &sent).then_some(twin.uid))
}
/// Trash the node a create made after the file was deleted, or replaced by
/// a rename, while its upload was on the wire (`docs/BUGS.md` B129).
///
/// `Db::finish_create` queued the trash, claimed, in the transaction that
/// found the create gone. It goes out now rather than behind the queue:
/// until it lands the node holds its name on Drive, and a file created
/// there again forks a conflict copy. A failure leaves it queued.
pub(crate) fn trash_withdrawn_create(
&self,
op: &PendingOp,
trash: i64,
local: &NodeUid,
real: &NodeUid,
name: &str,
) -> Result<(), Box<dyn std::error::Error>> {
self.hidden.lock().insert(real.clone());
self.note_self_change(real);
let trash = PendingOp {
id: trash,
kind: OP_TRASH.to_string(),
uid: real.to_string(),
parent_uid: None,
name: Some(name.to_string()),
blob_path: None,
meta_json: None,
created_at: op.created_at,
attempts: 0,
last_error: None,
next_attempt_at: 0,
};
info!(%local, %real, name, "a create landed after its file was deleted; trashing it");
if let Err(e) = self.drain_trash(&trash) {
warn!(%real, name, error = %e, "trashing a withdrawn create failed; queued");
if let Err(e) = self.db.record_op_failure(
trash.id,
&e.to_string(),
now_millis() + DRAIN_BACKOFF_MIN.as_millis() as i64,
) {
error!(%real, error = %e, "recording a drain failure failed");
}
self.release_claim(&trash);
self.wake_drain();
}
Ok(())
}
}
+15 -7
View File
@@ -3859,6 +3859,15 @@ mod tests {
);
}
/// The drain's source: `drain.rs` and the modules it was split into.
const DRAIN_SOURCE: &str = concat!(
include_str!("drain/create.rs"),
include_str!("drain/rename.rs"),
include_str!("drain/revision.rs"),
include_str!("drain/trash.rs"),
include_str!("drain.rs"),
);
/// `Core`'s source: `lib.rs` and the modules its methods were split into.
const CORE_SOURCE: &str = concat!(
include_str!("activity.rs"),
@@ -4147,7 +4156,7 @@ mod tests {
for source in [
CORE_SOURCE,
include_str!("filesystem.rs"),
include_str!("drain.rs"),
DRAIN_SOURCE,
include_str!("relocate.rs"),
] {
assert_eq!(
@@ -4337,7 +4346,7 @@ mod tests {
// A drain worker that claimed the op before it was withdrawn checks
// again before any byte leaves.
let drain = function_source(include_str!("drain.rs"), "pub(crate) fn drain_revision(");
let drain = function_source(DRAIN_SOURCE, "pub(crate) fn drain_revision(");
let upload = &drain[drain.find("begin_cancellable_upload").unwrap()..];
assert_before(upload, "self.db.op_exists(op.id)", "File::open(&blob)");
}
@@ -4358,16 +4367,15 @@ mod tests {
fn a_paused_drain_claims_nothing() {
// A claimed create counts as sent, so trashing its folder kept it as
// a trash, although the paused worker only handed it back (B178).
let worker: String =
function_source(include_str!("drain.rs"), "pub(crate) fn run_pending_drain(")
.split_whitespace()
.collect();
let worker: String = function_source(DRAIN_SOURCE, "pub(crate) fn run_pending_drain(")
.split_whitespace()
.collect();
assert!(worker.contains("(online&&!paused).then(||self.db.claim_next_due_op(now))"));
}
#[test]
fn a_landed_upload_stays_pending_until_its_bytes_are_cached() {
let drain = function_source(include_str!("drain.rs"), "pub(crate) fn drain_revision(");
let drain = function_source(DRAIN_SOURCE, "pub(crate) fn drain_revision(");
assert_before(
drain,
"let _landing = LandingUpload::begin(&self.drain.landing_uploads)",
+8 -4
View File
@@ -22,7 +22,7 @@ impl Core {
m.running = true;
}
let core = self.clone();
std::thread::spawn(move || {
if let Err(error) = self.services.spawn_job("pdfs-vacuum", move || {
let job = core.transfers.begin_job("Compacting the cache database");
job.detail("Rewriting the database file");
let started = Instant::now();
@@ -38,7 +38,9 @@ impl Core {
Err(e) => warn!(error = %e, "vacuum failed"),
}
core.maintenance.lock().running = false;
});
}) {
tracing::warn!(%error, "could not start pdfs-vacuum");
}
Ok(())
}
@@ -61,7 +63,7 @@ impl Core {
drop(m);
let core = self.clone();
std::thread::spawn(move || {
if let Err(error) = self.services.spawn_job("pdfs-integrity-check", move || {
let job = core
.transfers
.begin_background_job("Checking the cache database");
@@ -78,7 +80,9 @@ impl Core {
let mut m = core.maintenance.lock();
m.integrity = Some(problems);
m.running = false;
});
}) {
tracing::warn!(%error, "could not start pdfs-integrity-check");
}
(Vec::new(), false, true)
}
}
+16 -7
View File
@@ -658,7 +658,7 @@ pub(crate) fn mount_with(
// the walk is I/O-heavy and must never sit in front of a FUSE callback.
if matches!(host, Host::Daemon) {
if let Some(gallery) = &core.gallery {
rt.spawn(gallery.clone().poll(core.clone()));
workers.spawn_task(&rt, "pdfs-gallery", gallery.clone().poll(core.clone()));
}
let db = core.db.clone();
let indexing = core.indexing.clone();
@@ -798,19 +798,28 @@ pub(crate) fn mount_with(
}
}
};
rt.spawn(run_event_sync(core.drive.clone(), scope, core.clone()));
// Services rather than bare tasks: a stop aborts them. Before, they ran
// until the runtime went away, which on a stop is when the process exits.
workers.spawn_task(
&rt,
"pdfs-event-sync",
run_event_sync(core.drive.clone(), scope, core.clone()),
);
// The photos volume has its own event stream; without it the gallery only
// learns about a phone-side deletion when the timeline goes stale.
rt.spawn(run_photos_event_sync(core.clone()));
workers.spawn_task(
&rt,
"pdfs-photo-events",
run_photos_event_sync(core.clone()),
);
// Not in a simulation: `client` there reaches no API, and the thread, still
// waiting on it after the stop, held the database a test opens next.
if online && matches!(host, Host::Daemon) {
let repair_core = core.clone();
let root_uid = core.primary_root_uid.clone();
if let Err(error) = std::thread::Builder::new()
.name("pdfs-share-id".into())
.spawn(move || repair_core.repair_primary_share_id(&root_uid))
{
if let Err(error) = core.services.spawn_job("pdfs-share-id", move || {
repair_core.repair_primary_share_id(&root_uid)
}) {
warn!(%error, "start My Files share-id repair failed");
}
}
+15 -17
View File
@@ -182,24 +182,22 @@ impl Core {
pub(crate) fn arm_pause_timer(&self, until: i64) {
let core = self.clone();
let wait = Duration::from_secs(until.saturating_sub(now_secs()).max(0) as u64);
let spawned = std::thread::Builder::new()
.name("pdfs-pause".into())
.spawn(move || {
if !core.shutdown.sleep(wait) {
return;
let spawned = self.services.spawn_job("pdfs-pause", move || {
if !core.shutdown.sleep(wait) {
return;
}
if core
.sync_paused_until
.compare_exchange(until, 0, Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
{
if let Err(error) = core.db.clear_state(PAUSED_UNTIL_KEY) {
warn!(%error, "clearing an expired sync pause failed");
}
if core
.sync_paused_until
.compare_exchange(until, 0, Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
{
if let Err(error) = core.db.clear_state(PAUSED_UNTIL_KEY) {
warn!(%error, "clearing an expired sync pause failed");
}
info!("sync pause ended");
core.resume_sync_work();
}
});
info!("sync pause ended");
core.resume_sync_work();
}
});
if let Err(error) = spawned {
// The drain and the reconcile still read the clock, so the pause
// still ends — just at the next idle poll instead of on time.
File diff suppressed because it is too large. Load diff
+986
View File
@@ -0,0 +1,986 @@
//! Thumbnails: the ones the server lacks, generated here and uploaded; the
//! file-manager thumbnails for ordinary files and folder covers; and the
//! recursive build started from the Files toolbar.
use super::*;
impl Core {
/// [`upload_thumbnails`] for a file about to upload, staging any RAW copy
/// under this cache. Blocking.
pub(crate) fn upload_thumbnails(&self, path: &Path, name: &str) -> Vec<Thumbnail> {
upload_thumbnails(path, name, self.cache.raw_thumbnail_staging_dir())
}
/// [`Core::upload_thumbnails`] on the blocking pool, for async callers.
pub(crate) async fn upload_thumbnails_async(
&self,
path: PathBuf,
name: String,
) -> Vec<Thumbnail> {
let staging_dir = self.cache.raw_thumbnail_staging_dir().to_path_buf();
tokio::task::spawn_blocking(move || upload_thumbnails(&path, &name, &staging_dir))
.await
.unwrap_or_default()
}
/// Thumbnails for `uids`, served from the cache, fetched from the server for
/// whatever is missing, and — for the photos the server has no thumbnail for
/// at all — *generated locally* from the full file (see
/// [`Core::generate_thumbs`]). Requested on demand as tiles scroll into view,
/// so a cold timeline paints immediately and only the photos actually on
/// screen cost a round-trip.
///
/// A photo absent from the persisted timeline is skipped: its capture time is
/// the cache's validity tag, and guessing that would poison the cache.
///
/// A camera raw is served by the JPEG of the same shot when there is one:
/// the two files show one picture, and the JPEG is already decodable in
/// milliseconds where the raw costs a full download and a raw decode. The
/// tile still answers under the uid that was asked for.
pub(crate) fn photo_thumbs(&self, requested: &[NodeUid]) -> Vec<PhotoThumb> {
self.photo_thumbs_with(requested, true)
}
/// [`Core::photo_thumbs`], with local generation only when `generate` is
/// set. Without it, a photo the server has no thumbnail for is left
/// without one rather than downloaded whole.
pub(crate) fn photo_thumbs_with(
&self,
requested: &[NodeUid],
generate: bool,
) -> Vec<PhotoThumb> {
let ttype = ThumbnailType::Thumbnail.as_i32();
// Only a raw can be stood in for, and that is one batched read; the
// per-shot group lookup is then paid for raws alone, not for a page of
// ordinary photos.
let asked: Vec<String> = requested.iter().map(|u| u.to_string()).collect();
let raws: HashSet<String> = self
.db
.photos_by_uid(&asked)
.unwrap_or_default()
.into_iter()
.filter(|photo| photo.kind == PhotoKind::Raw)
.map(|photo| photo.uid)
.collect();
let sources: Vec<NodeUid> = requested
.iter()
.map(|uid| {
if raws.contains(&uid.to_string()) {
self.thumb_source(uid)
} else {
uid.clone()
}
})
.collect();
let uids = &sources;
let keys: Vec<String> = uids.iter().map(|u| u.to_string()).collect();
let mut stored = self.db.photos_by_uid(&keys).unwrap_or_default();
// Album covers and the contents of an album shared with us are not in our
// own timeline, so their capture time — the cache's validity tag — only
// exists on the album rows. Fill in whatever the timeline didn't cover.
{
let have: HashSet<String> = stored.iter().map(|p| p.uid.clone()).collect();
let missing: Vec<String> = keys
.iter()
.filter(|k| !have.contains(*k))
.cloned()
.collect();
stored.extend(self.db.album_photos_by_uid(&missing).unwrap_or_default());
}
let stored = stored;
let tags: HashMap<String, i64> = stored
.iter()
.map(|p| (p.uid.clone(), p.capture_time))
.collect();
let names: HashMap<String, String> = stored
.iter()
.filter_map(|photo| photo.name.clone().map(|name| (photo.uid.clone(), name)))
.collect();
// Ask the server only for photos that are missing a cached thumbnail and
// haven't already been written off as un-thumbnailable.
let want: Vec<NodeUid> = uids
.iter()
.filter(|uid| {
let key = uid.to_string();
stored
.iter()
.find(|p| p.uid == key)
.is_some_and(|p| p.thumb_state != db::THUMB_NONE)
&& tags.get(&key).is_some_and(|&tag| {
self.cache.cached_thumbnail_path(uid, ttype, tag).is_none()
})
})
.cloned()
.collect();
if !want.is_empty() {
let mut missing = want.clone();
match self.rt.block_on(
self.photos()
.enumerate_thumbnails(&want, ThumbnailType::Thumbnail),
) {
Ok(thumbs) => {
for ft in thumbs {
let Some(&tag) = tags.get(&ft.file_uid.to_string()) else {
continue;
};
let Ok(bytes) = ft.result else { continue };
if bytes.is_empty() {
continue;
}
if self
.cache
.store_thumbnail(&ft.file_uid, ttype, tag, &bytes)
.is_ok()
{
missing.retain(|uid| uid != &ft.file_uid);
self.record_thumb(&ft.file_uid, db::THUMB_HAVE, ratio_of(&bytes));
}
}
}
// A failed batch is not a verdict: leave every uid in `missing` so
// the local fallback still gives those tiles an image.
Err(e) => warn!(error = %e, "batch photo thumbnails failed"),
}
// Whatever the server had nothing for gets a thumbnail made from its
// own bytes — this is what fills in camera photos uploaded by clients
// that never generated one. Off the request path: a full-size photo
// takes far longer to fetch than the whole rest of the batch, and the
// thumbnails that *are* ready must not wait behind it.
if generate && !missing.is_empty() {
self.spawn_generate_thumbs(missing, &tags, &names, ThumbJob::Photos);
}
}
let pending = self.photo_jobs.thumb_gen.lock();
requested
.iter()
.zip(uids)
.map(|(asked, source)| PhotoThumb {
uid: asked.to_string(),
path: tags.get(&source.to_string()).and_then(|&tag| {
self.cache
.cached_thumbnail_path(source, ttype, tag)
.map(|p| p.display().to_string())
}),
pending: pending.contains(source),
})
.collect()
}
/// Which file's thumbnail stands for `uid` on a tile.
///
/// Itself, for all but a camera raw that was written next to a JPEG of the
/// same shot. For that one, the JPEG: same picture, already compressed,
/// often carrying a server thumbnail the raw does not have — so the Raw tab
/// costs no raw download and no raw decode. A raw that stands alone keeps
/// its own local generation.
pub(crate) fn thumb_source(&self, uid: &NodeUid) -> NodeUid {
let members = match self.db.photos_group(&uid.to_string()) {
Ok(members) if members.len() > 1 => members,
_ => return uid.clone(),
};
let key = uid.to_string();
if !members
.iter()
.any(|photo| photo.uid == key && photo.kind == PhotoKind::Raw)
{
return uid.clone();
}
members
.iter()
.find(|photo| photo.kind != PhotoKind::Raw)
.and_then(|photo| parse_uid(&photo.uid))
.unwrap_or_else(|| uid.clone())
}
/// Thumbnails for image files shown by the regular file browser, Shared and
/// Trash pages. Unlike [`Core::photo_thumbs`], these nodes need not be in the
/// Photos timeline: the request supplies each file's modification time as
/// the cache validity tag.
pub(crate) fn file_thumbs(
&self,
items: &[FileThumbRequest],
generation: u64,
) -> Option<Vec<PhotoThumb>> {
let current = generation != 0
&& self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation;
if !current {
return None;
}
let ttype = ThumbnailType::Thumbnail.as_i32();
let parsed: Vec<(String, NodeUid, i64)> = items
.iter()
.filter_map(|item| {
parse_uid(&item.uid).map(|uid| (item.uid.clone(), uid, item.modified))
})
.collect();
let tags: HashMap<String, i64> = parsed
.iter()
.map(|(raw, _, modified)| (raw.clone(), *modified))
.collect();
let names: HashMap<String, String> = items
.iter()
.map(|item| (item.uid.clone(), item.name.clone()))
.collect();
// Drive makes no thumbnails itself; a file has one only when its
// uploader attached it, as this client and Proton's apps do. The
// generation step asks for that first, and only makes one from the
// file's content without it.
let mut wanted = Vec::new();
let mut seen = HashSet::new();
for (raw, uid, modified) in &parsed {
if self
.cache
.cached_thumbnail_path(uid, ttype, *modified)
.is_some()
|| self
.photo_jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), *modified)
|| !seen.insert(raw.clone())
{
continue;
}
wanted.push(uid.clone());
}
if !wanted.is_empty() {
self.spawn_generate_thumbs(wanted, &tags, &names, ThumbJob::Files(generation));
}
let pending = self.photo_jobs.thumb_gen.lock();
Some(
items
.iter()
.map(|item| {
let uid = parse_uid(&item.uid);
PhotoThumb {
uid: item.uid.clone(),
path: uid.as_ref().and_then(|uid| {
self.cache
.cached_thumbnail_path(uid, ttype, item.modified)
.map(|path| path.display().to_string())
}),
pending: uid.as_ref().is_some_and(|uid| pending.contains(uid)),
}
})
.collect(),
)
}
/// Reserve the next ordinary-file listing generation. This daemon-owned
/// monotonic value replaces GUI wall-clock seeds, which can move backwards
/// across NTP corrections, suspend, or dual boot.
pub(crate) fn reserve_file_thumb_generation(&self) -> u64 {
let next = |current| if current == u64::MAX { 1 } else { current + 1 };
let previous = self
.photo_jobs
.file_thumb_generation
.try_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
Some(next(current))
})
.expect("generation update always succeeds");
let generation = next(previous);
self.photo_jobs.file_thumb_cancel.notify_waiters();
generation
}
/// Advance the ordinary-file thumbnail generation. Every queued/download in
/// an older listing observes the new value and exits; Photos and explicit
/// recursive builds do not use this generation and continue normally.
pub(crate) fn cancel_file_thumbs(&self, generation: u64) {
let previous = self
.photo_jobs
.file_thumb_generation
.fetch_max(generation, Ordering::SeqCst);
if generation > previous {
self.photo_jobs.file_thumb_cancel.notify_waiters();
}
}
/// Generate the missing thumbnails on the runtime, skipping any photo already
/// being generated. The uids are marked in-flight before the task starts, so
/// the reply this call is about to send already reports them as pending.
pub(super) fn spawn_generate_thumbs(
&self,
uids: Vec<NodeUid>,
tags: &HashMap<String, i64>,
names: &HashMap<String, String>,
job: ThumbJob,
) {
let fresh: Vec<NodeUid> = {
let mut inflight = self.photo_jobs.thumb_gen.lock();
uids.into_iter()
.filter(|uid| inflight.insert(uid.clone()))
.collect()
};
if fresh.is_empty() {
return;
}
let core = self.clone();
let tags = tags.clone();
let names = names.clone();
// `generate_thumbs` blocks on the runtime itself, so it belongs on the
// blocking pool rather than on an async worker.
self.rt.spawn_blocking(move || {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
core.generate_thumbs(&fresh, &tags, &names, job)
}));
let mut inflight = core.photo_jobs.thumb_gen.lock();
for uid in &fresh {
inflight.remove(uid);
}
drop(inflight);
if result.is_err() {
warn!("thumbnail generation worker panicked");
}
});
}
/// Make thumbnails for photos the server has none for: download each full
/// file once, scale it to [`THUMB_EDGE`], and store the result in the thumbnail
/// cache exactly as if the server had served it.
///
/// Bounded by [`THUMB_GEN_CONCURRENCY`] — these are full-size originals, and a
/// screenful of them at once would saturate the link. A photo whose bytes
/// can't be decoded (a codec `image` doesn't speak) is marked
/// [`db::THUMB_NONE`] and never attempted again.
pub(super) fn thumb_job_current(&self, job: ThumbJob) -> bool {
match job {
ThumbJob::Files(generation) => {
self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation
}
ThumbJob::Photos => true,
ThumbJob::Build => !self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst),
}
}
pub(super) fn generate_thumbs(
&self,
uids: &[NodeUid],
tags: &HashMap<String, i64>,
names: &HashMap<String, String>,
job: ThumbJob,
) -> ThumbBatchSummary {
info!(count = uids.len(), "generating local thumbnails");
let results: Vec<(NodeUid, ThumbAttempt)> = self.rt.block_on(async {
let mut out = Vec::with_capacity(uids.len());
for chunk in uids.chunks(THUMB_GEN_CONCURRENCY) {
let mut set = tokio::task::JoinSet::new();
for uid in chunk {
let core = self.clone();
let client = self.client.clone();
let uid = uid.clone();
let name = names.get(&uid.to_string()).cloned().unwrap_or_default();
set.spawn(async move {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
let video = is_video_name(&name);
let audio = is_audio_file_name(&name);
// Without ffmpeg a video can still have its uploader's
// thumbnail, but Photos has asked the server already.
let can_sample = !video || ffmpeg_available();
if !can_sample && matches!(job, ThumbJob::Photos) {
return (uid, ThumbAttempt::Unavailable);
}
// One shared permit pool bounds all thumbnail batches,
// rather than multiplying the limit by every control
// request the GUI happens to have in flight.
let acquire = core.photo_jobs.thumb_gen_budget.clone().acquire_owned();
tokio::pin!(acquire);
let _permit = match job {
ThumbJob::Files(_) => loop {
tokio::select! {
permit = &mut acquire => break permit.ok(),
_ = core.photo_jobs.file_thumb_cancel.notified() => {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
}
},
ThumbJob::Build => loop {
tokio::select! {
permit = &mut acquire => break permit.ok(),
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
}
},
ThumbJob::Photos => acquire.await.ok(),
};
let Some(_permit) = _permit else {
return (uid, ThumbAttempt::Unavailable);
};
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
let download_uid = uid.clone();
let drive = core.drive.clone();
let audio_name = name.clone();
let download = async move {
// Photos asked the server in one batch already. A
// file view's or a build's file may carry a
// thumbnail its uploader made, which costs one
// small download instead of its content.
if !matches!(job, ThumbJob::Photos)
&& let Some(bytes) = drive
.download_thumbnail(&download_uid, ThumbnailType::Thumbnail)
.await?
.filter(|bytes| !bytes.is_empty())
{
return Ok(Fetched::Ready(bytes));
}
if !can_sample {
return Ok(Fetched::Nothing);
}
if video {
let reader = drive.open_revision(&download_uid).await?;
sample_video(reader.as_ref()).await.map(Fetched::Video)
} else if audio {
let reader = drive.open_revision(&download_uid).await?;
sample_audio(reader.as_ref(), &audio_name)
.await
.map(Fetched::Audio)
} else {
client
.download_file(&download_uid)
.await
.map(Fetched::Whole)
}
};
tokio::pin!(download);
let downloaded = match job {
ThumbJob::Files(_) => loop {
tokio::select! {
result = &mut download => break Some(result),
_ = core.photo_jobs.file_thumb_cancel.notified() => {
if !core.thumb_job_current(job) {
break None;
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
break None;
}
}
}
},
ThumbJob::Build => loop {
tokio::select! {
result = &mut download => break Some(result),
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
if !core.thumb_job_current(job) {
break None;
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
break None;
}
}
}
},
ThumbJob::Photos => Some(download.await),
};
let Some(downloaded) = downloaded else {
return (uid, ThumbAttempt::Cancelled);
};
let fetched = match downloaded {
Ok(fetched) => fetched,
Err(e) => {
warn!(%uid, error = %e, "download for a thumbnail failed");
return (uid, ThumbAttempt::Unavailable);
}
};
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
// Decoding + scaling a 20 MP JPEG is CPU-bound and would
// stall the runtime's worker; hand it to the blocking pool.
let staging_dir = core.cache.raw_thumbnail_staging_dir().to_path_buf();
let staging = staging_dir.clone();
let made = tokio::task::spawn_blocking(move || match fetched {
Fetched::Audio(sample) => {
audio_cover_thumbnail(&sample, &name, &staging_dir)
}
Fetched::Video(sample) => video_sample_thumbnail(
&sample,
&name,
&staging_dir,
OsStr::new("ffmpeg"),
FFMPEG_TIMEOUT,
),
Fetched::Whole(bytes) => scale_thumbnail(&bytes, &name, &staging_dir),
Fetched::Nothing => ScaleAttempt::Unavailable,
Fetched::Ready(bytes) => match ratio_of(&bytes) {
Some(ratio) => ScaleAttempt::Made(GeneratedThumb { bytes, ratio }),
None => ScaleAttempt::Undecodable,
},
})
.await
.unwrap_or(ScaleAttempt::Unavailable);
// A song without a picture of its own shows its
// folder's cover.
let made = match made {
ScaleAttempt::Undecodable if audio && core.thumb_job_current(job) => {
core.folder_cover_thumbnail(&uid, staging).await
}
made => made,
};
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
match made {
ScaleAttempt::Made(thumb) => (uid, ThumbAttempt::Made(thumb)),
ScaleAttempt::Undecodable => (uid, ThumbAttempt::Undecodable),
ScaleAttempt::Unavailable => (uid, ThumbAttempt::Unavailable),
}
});
}
while let Some(joined) = set.join_next().await {
if let Ok(result) = joined {
out.push(result);
}
}
}
out
});
let ttype = ThumbnailType::Thumbnail.as_i32();
let mut summary = ThumbBatchSummary::default();
for (uid, attempt) in results {
match attempt {
ThumbAttempt::Made(thumb) => {
let Some(&tag) = tags.get(&uid.to_string()) else {
summary.unavailable += 1;
continue;
};
match self.cache.store_thumbnail(&uid, ttype, tag, &thumb.bytes) {
Ok(()) => {
summary.made += 1;
self.photo_jobs
.thumbnail_misses
.lock()
.forget_local(&(uid.clone(), ttype));
self.record_thumb(&uid, db::THUMB_HAVE, Some(thumb.ratio));
}
Err(e) => {
summary.unavailable += 1;
warn!(%uid, error = %e, "storing generated thumbnail failed");
}
}
}
// The photo's own bytes aren't an image we can read: no thumbnail
// will ever exist for it, so stop trying.
ThumbAttempt::Undecodable => {
summary.undecodable += 1;
if let Some(&tag) = tags.get(&uid.to_string()) {
self.photo_jobs
.thumbnail_misses
.lock()
.remember_local((uid.clone(), ttype), tag);
}
self.record_thumb(&uid, db::THUMB_NONE, None);
}
// The download failed — a dropped connection, an expired link. That
// is not a verdict on the photo: leave its state alone so the next
// scroll past it tries again.
ThumbAttempt::Unavailable => summary.unavailable += 1,
ThumbAttempt::Cancelled => summary.cancelled += 1,
}
}
// A folder on screen whose tiles were given up on, as a recursive
// build's start does to them, fills in without being opened again.
if summary.made > 0 {
self.events.publish(&[Topic::Thumbnails]);
}
summary
}
/// The cover image in the folder of the song `uid`: the best-named one of
/// [`FOLDER_COVER_STEMS`] among its siblings the database knows.
pub(crate) fn folder_cover(&self, uid: &NodeUid) -> Option<proton_drive_rs::Node> {
let node = self.db.node_by_uid(&uid.to_string()).ok()??;
let parent = node.parent_uid?;
let siblings = match self.db.children_if_listed(&parent) {
Ok(Some(children)) => children,
_ => self.db.known_children(&parent).ok()?,
};
siblings
.into_iter()
.filter(|sibling| !sibling.is_folder() && !sibling.trashed)
.filter_map(|sibling| cover_rank(&sibling.name).map(|rank| (rank, sibling)))
.min_by(|(a, x), (b, y)| a.cmp(b).then_with(|| x.name.cmp(&y.name)))
.map(|(_, cover)| cover)
}
/// A thumbnail of the song `uid` made from its folder's cover image: the
/// cover's own cached thumbnail when it has one, else the thumbnail its
/// uploader attached, else the image itself, up to
/// [`FOLDER_COVER_MAX_BYTES`].
///
/// The result is stored under the song, so a cover added to the folder or
/// replaced later shows only once the song changes or the daemon restarts
/// and forgets the songs it found no cover for.
pub(super) async fn folder_cover_thumbnail(
&self,
uid: &NodeUid,
staging_dir: PathBuf,
) -> ScaleAttempt {
let Some(cover) = self.folder_cover(uid) else {
return ScaleAttempt::Undecodable;
};
let ttype = ThumbnailType::Thumbnail;
let cached = self
.cache
.cached_thumbnail_path(&cover.uid, ttype.as_i32(), cover.modification_time)
.and_then(|path| std::fs::read(path).ok());
let ready = match cached {
Some(bytes) => Some(bytes),
None => match self.drive.download_thumbnail(&cover.uid, ttype).await {
Ok(bytes) => bytes.filter(|bytes| !bytes.is_empty()),
Err(e) => {
warn!(cover = %cover.uid, error = %e, "folder cover thumbnail download failed");
return ScaleAttempt::Unavailable;
}
},
};
if let Some(bytes) = ready {
return match ratio_of(&bytes) {
Some(ratio) => ScaleAttempt::Made(GeneratedThumb { bytes, ratio }),
None => ScaleAttempt::Undecodable,
};
}
let read = async {
let reader = self.drive.open_revision(&cover.uid).await?;
if reader.size() > FOLDER_COVER_MAX_BYTES {
return Ok(None);
}
reader.read_at(0, reader.size()).await.map(Some)
};
let bytes = match read.await {
Ok(Some(bytes)) => bytes,
Ok(None) => return ScaleAttempt::Undecodable,
Err(e) => {
warn!(cover = %cover.uid, error = %e, "folder cover download failed");
return ScaleAttempt::Unavailable;
}
};
let name = cover.name;
tokio::task::spawn_blocking(move || scale_thumbnail(&bytes, &name, &staging_dir))
.await
.unwrap_or(ScaleAttempt::Unavailable)
}
pub(crate) fn thumbnail_build_status(&self) -> ThumbnailBuildStatus {
self.photo_jobs.thumbnail_build.lock().clone()
}
/// Start one recursive local-thumbnail build. A request for the same root
/// may attach to it; a different root is rejected explicitly instead of
/// silently pretending the existing job belongs to the caller.
pub(crate) fn start_thumbnail_build(&self, root: PathBuf) -> CoreResult<ThumbnailBuildStatus> {
let path = root.to_string_lossy().into_owned();
let status = {
let mut status = self.photo_jobs.thumbnail_build.lock();
if !thumbnail_build_may_start(&status, &path)? {
return Ok(status.clone());
}
self.photo_jobs
.thumbnail_build_cancelled
.store(false, Ordering::SeqCst);
*status = ThumbnailBuildStatus {
running: true,
scanning: true,
path: path.clone(),
folders_scanned: 0,
images_found: 0,
completed: 0,
failed: 0,
message: None,
};
status.clone()
};
let core = self.clone();
self.rt.spawn_blocking(move || {
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
core.run_thumbnail_build(root)
}))
.is_err()
{
let mut status = core.photo_jobs.thumbnail_build.lock();
status.running = false;
status.scanning = false;
status.message = Some("Thumbnail generation stopped unexpectedly".to_string());
core.photo_jobs
.thumbnail_build_cancelled
.store(false, Ordering::SeqCst);
warn!(path = %status.path, "recursive thumbnail build panicked");
}
});
Ok(status)
}
pub(crate) fn cancel_thumbnail_build(&self) -> ThumbnailBuildStatus {
let (status, cancelled) = {
let status = self.photo_jobs.thumbnail_build.lock();
let cancelled = status.running;
if cancelled {
self.photo_jobs
.thumbnail_build_cancelled
.store(true, Ordering::SeqCst);
}
(status.clone(), cancelled)
};
if cancelled {
self.photo_jobs.thumbnail_build_cancel.notify_waiters();
}
status
}
pub(crate) fn finish_thumbnail_build(&self) {
let mut status = self.photo_jobs.thumbnail_build.lock();
let cancelled = self
.photo_jobs
.thumbnail_build_cancelled
.swap(false, Ordering::SeqCst);
status.running = false;
status.scanning = false;
if cancelled {
status.message = Some("Thumbnail build cancelled".to_string());
}
info!(
path = %status.path,
images = status.images_found,
failed = status.failed,
cancelled,
"recursive thumbnail build finished"
);
}
pub(crate) fn run_thumbnail_build(&self, root: PathBuf) {
let mut folders = vec![root];
let mut images: Vec<(NodeUid, i64, String)> = Vec::new();
let mut seen_folders = HashSet::new();
let mut seen_images = HashSet::new();
while let Some(folder) = folders.pop() {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.finish_thumbnail_build();
return;
}
let listing = self.list_dir(&folder);
{
let mut status = self.photo_jobs.thumbnail_build.lock();
status.folders_scanned += 1;
}
let entries = match listing {
Ok(entries) => entries,
Err(error) => {
let mut status = self.photo_jobs.thumbnail_build.lock();
if status.message.is_none() {
status.message = Some(format!(
"Some folders could not be read ({}: {error})",
folder.display()
));
}
continue;
}
};
let mut found_here = 0_u64;
let mut invalid_here = 0_u64;
for entry in entries {
if entry.is_dir {
if seen_folders.insert(entry.uid) {
folders.push(folder.join(entry.name));
}
} else if is_thumbnail_media_name(&entry.name, Some(entry.size)) {
match parse_uid(&entry.uid) {
Some(uid) if seen_images.insert(uid.clone()) => {
found_here += 1;
images.push((uid, entry.modified, entry.name));
}
Some(_) => {}
None => {
found_here += 1;
invalid_here += 1;
}
}
}
}
let mut status = self.photo_jobs.thumbnail_build.lock();
status.images_found += found_here;
status.completed += invalid_here;
status.failed += invalid_here;
}
self.photo_jobs.thumbnail_build.lock().scanning = false;
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.finish_thumbnail_build();
return;
}
let ttype = ThumbnailType::Thumbnail.as_i32();
let mut todo = Vec::new();
for (uid, modified, name) in images {
if self
.cache
.cached_thumbnail_path(&uid, ttype, modified)
.is_some()
{
self.photo_jobs.thumbnail_build.lock().completed += 1;
} else if self
.photo_jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), modified)
{
let mut status = self.photo_jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
} else {
todo.push((uid, modified, name));
}
}
for chunk in todo.chunks(THUMB_BUILD_CHUNK) {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.finish_thumbnail_build();
return;
}
let mut claimed = Vec::with_capacity(chunk.len());
let mut tags = HashMap::with_capacity(chunk.len());
let mut names = HashMap::with_capacity(chunk.len());
for (uid, modified, name) in chunk {
// A visible tile may have started this image just before the
// toolbar action. Wait for that one bounded job to finish rather
// than downloading the full image twice.
let waiting_since = Instant::now();
loop {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.finish_thumbnail_build();
return;
}
if self
.cache
.cached_thumbnail_path(uid, ttype, *modified)
.is_some()
{
self.photo_jobs.thumbnail_build.lock().completed += 1;
break;
}
if self
.photo_jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), *modified)
{
let mut status = self.photo_jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
break;
}
if self.photo_jobs.thumb_gen.lock().insert(uid.clone()) {
tags.insert(uid.to_string(), *modified);
names.insert(uid.to_string(), name.clone());
claimed.push(uid.clone());
break;
}
if waiting_since.elapsed() >= THUMB_BUILD_CLAIM_TIMEOUT {
let mut status = self.photo_jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
if status.message.is_none() {
status.message = Some(
"Some images stayed busy and were skipped after a timeout".into(),
);
}
break;
}
std::thread::sleep(Duration::from_millis(50));
}
}
if claimed.is_empty() {
continue;
}
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
self.generate_thumbs(&claimed, &tags, &names, ThumbJob::Build)
}));
{
let mut inflight = self.photo_jobs.thumb_gen.lock();
for uid in &claimed {
inflight.remove(uid);
}
}
let mut status = self.photo_jobs.thumbnail_build.lock();
match result {
Ok(summary) => {
status.completed += summary.processed();
status.failed += summary.failed();
}
Err(_) => {
status.completed += claimed.len() as u64;
status.failed += claimed.len() as u64;
status.message = Some("Some thumbnail workers stopped unexpectedly".into());
}
}
}
self.finish_thumbnail_build();
}
/// Persist what a thumbnail attempt learned about a photo, against the
/// timeline and against every album the photo sits in — one attempt, one
/// verdict, wherever the photo is painted.
pub(crate) fn record_thumb(&self, uid: &NodeUid, state: i64, ratio: Option<f64>) {
let key = uid.to_string();
if let Err(e) = self.db.photo_set_thumb(&key, state, ratio) {
warn!(%uid, error = %e, "recording thumbnail state failed");
}
if let Err(e) = self.db.album_photo_set_thumb(&key, state, ratio) {
warn!(%uid, error = %e, "recording album thumbnail state failed");
}
}
}
+636
View File
@@ -0,0 +1,636 @@
//! The photos timeline and what is built on it: favorites, duplicates and
//! similar shots, places, on this day, groups, and trashing photos.
use super::*;
impl Core {
#[allow(clippy::too_many_arguments)]
pub(crate) fn photos_timeline(
&self,
offset: usize,
limit: usize,
kind: Option<PhotoKind>,
range: Option<(i64, i64)>,
favorites: bool,
not_in_album: bool,
excluded: &str,
) -> CoreResult<Option<Vec<PhotoItem>>> {
let count = self.db.photos_count().map_err(CoreError::from)?;
let listed = self
.db
.state_i64(PHOTOS_SYNCED_MS)
.map_err(CoreError::from)?
.is_some();
if !listed {
if count == 0 {
if !self.refresh_timeline_joined()? {
return Ok(None);
}
} else {
self.spawn_timeline_refresh();
}
} else if self
.db
.state_i64(PHOTOS_AVAILABLE)
.map_err(CoreError::from)?
== Some(0)
{
return Ok(None);
}
// The filter is only as good as the album contents on disk, and those
// are fetched lazily, per album opened. Fill in the missing ones before
// the first page; later pages reuse what that fetch stored.
if not_in_album && offset == 0 {
self.ensure_album_contents()?;
}
let page = self
.db
.photos_page_visible(
offset,
limit,
kind,
range,
favorites,
not_in_album,
excluded,
)
.map_err(CoreError::from)?;
Ok(Some(page.into_iter().map(|p| self.photo_item(p)).collect()))
}
/// Project a persisted photo into the wire item the front-end paints: its
/// learned aspect ratio, its thumbnail verdict, and the on-disk path of its
/// thumbnail when one is cached (tagged with the capture time, which is the
/// only revision handle a photo carries).
pub(crate) fn photo_item(&self, photo: StoredPhoto) -> PhotoItem {
let thumb_path = parse_uid(&photo.uid).and_then(|uid| {
self.cache
.cached_thumbnail_path(&uid, ThumbnailType::Thumbnail.as_i32(), photo.capture_time)
.map(|p| p.display().to_string())
});
PhotoItem {
uid: photo.uid,
capture_time: photo.capture_time,
thumb_path,
name: photo.name,
ratio: photo.ratio,
no_thumb: photo.thumb_state == db::THUMB_NONE,
kind: photo.kind,
favorite: photo.favorite,
group_size: photo.group_size as u32,
has_raw: photo.has_raw,
place_id: photo.place_id,
}
}
/// Add or remove Proton's `Favorite` tag on a photo, then record the change
/// locally so the gallery reflects it without waiting for a timeline refresh.
///
/// The SDK reports one outcome per photo rather than failing the call, so the
/// single outcome is unwrapped back into this request's result.
pub(crate) fn set_photo_favorite(&self, uid: &NodeUid, favorite: bool) -> CoreResult<()> {
let photos = self.photos();
let update = PhotoTagsUpdate {
node_uid: uid.clone(),
tags_to_add: if favorite {
vec![PhotoTag::Favorite]
} else {
Vec::new()
},
tags_to_remove: if favorite {
Vec::new()
} else {
vec![PhotoTag::Favorite]
},
};
let outcomes = self
.rt
.block_on(photos.update_photos(std::slice::from_ref(&update)))
.map_err(|e| CoreError::from_api(&e, "update photo tags"))?;
pdfs_core::batch::into_unit(outcomes)
.map_err(|e| CoreError::from_api(&e, "update photo tags"))?;
// The photo event feed replays this write back at us as a bare
// `NodeUpdated`, which is indistinguishable from the same photo being
// favorited on a phone. Claim the echo, or the gallery pays for a
// resolve of a node whose one changed field is already stored below.
self.note_self_change(uid);
self.db
.photos_set_favorite(&uid.to_string(), favorite)
.map_err(CoreError::from)?;
Ok(())
}
/// The timeline's duplicate sets, as wire items (see
/// [`db::Db::photo_duplicates`]).
pub(crate) fn photo_duplicates(&self) -> CoreResult<Vec<Vec<PhotoItem>>> {
let sets = self.db.photo_duplicates().map_err(CoreError::from)?;
Ok(sets
.into_iter()
.map(|set| set.into_iter().map(|p| self.photo_item(p)).collect())
.collect())
}
/// The sets of shots that look alike, as wire items (see
/// [`db::Db::photo_similar`]), how far hashing has got while it runs, and
/// how many shots couldn't be compared once it's done. Starts a hashing
/// pass for the shots not hashed yet unless one is running.
pub(crate) fn photo_similar(
&self,
) -> CoreResult<(Vec<Vec<PhotoItem>>, Option<MappingProgress>, usize)> {
self.spawn_similar_hashing();
let sets = self.db.photo_similar().map_err(CoreError::from)?;
let (done, total) = self.db.similar_progress().map_err(CoreError::from)?;
let hashing = self
.photo_jobs
.similar_hashing
.load(Ordering::SeqCst)
.then_some(MappingProgress { done, total });
let uncompared = if hashing.is_some() { 0 } else { total - done };
let sets = sets
.into_iter()
.map(|set| set.into_iter().map(|p| self.photo_item(p)).collect())
.collect();
Ok((sets, hashing, uncompared))
}
pub(crate) fn spawn_similar_hashing(&self) {
if self.photo_jobs.similar_hashing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
let spawned = self.services.spawn_job("pdfs-similar", move || {
if let Err(e) = core.hash_similar() {
warn!(error = %e, "similar-photo hashing failed");
}
core.photo_jobs
.similar_hashing
.store(false, Ordering::SeqCst);
});
if let Err(e) = spawned {
warn!(error = %e, "could not start similar-photo hashing");
self.photo_jobs
.similar_hashing
.store(false, Ordering::SeqCst);
}
}
/// Hash the look of every shot not hashed yet, a chunk at a time. Only
/// thumbnails the server has are used: a photo without one is skipped
/// rather than downloaded whole, and tried again on the next pass.
pub(crate) fn hash_similar(&self) -> CoreResult<()> {
let mut tried: HashSet<String> = HashSet::new();
loop {
if self.shutdown.is_stopping() {
return Ok(());
}
// Shots tried this pass without a thumbnail are still unhashed and
// come back first, so ask past them.
let chunk: Vec<NodeUid> = self
.db
.photos_unhashed(tried.len() + SIMILAR_CHUNK)
.map_err(CoreError::from)?
.into_iter()
.filter(|photo| tried.insert(photo.uid.clone()))
.take(SIMILAR_CHUNK)
.filter_map(|photo| parse_uid(&photo.uid))
.collect();
if chunk.is_empty() {
return Ok(());
}
let paths: Vec<(String, PathBuf)> = self
.photo_thumbs_with(&chunk, false)
.into_iter()
.filter_map(|thumb| Some((thumb.uid, PathBuf::from(thumb.path?))))
.collect();
for (uid, hash) in similar_hashes(paths) {
self.db
.photo_set_similar_hash(&uid, hash)
.map_err(CoreError::from)?;
}
}
}
/// The towns the photos were taken in, as wire items. A town the bundled
/// table no longer knows (the stored id came from an older table) is left
/// out rather than shown without a name.
pub(crate) fn photo_places(&self, excluded: &str) -> CoreResult<Vec<PlaceInfo>> {
let places = self
.db
.photo_places_visible(excluded)
.map_err(CoreError::from)?;
Ok(places
.into_iter()
.filter_map(|place| {
let city = pdfs_core::places::city(place.id)?;
Some(PlaceInfo {
id: place.id,
name: city.name.to_string(),
country: city.country.to_string(),
latitude: city.latitude,
longitude: city.longitude,
photo_count: place.count,
cover: self.photo_item(place.cover),
})
})
.collect())
}
/// A page of the photos taken in town `id`, as wire items.
pub(crate) fn place_photos(
&self,
id: u32,
offset: usize,
limit: usize,
excluded: &str,
) -> CoreResult<Vec<PhotoItem>> {
let photos = self
.db
.photos_at_place_visible(id, offset, limit, excluded)
.map_err(CoreError::from)?;
Ok(photos.into_iter().map(|p| self.photo_item(p)).collect())
}
/// Every photo taken in town `id` with its own location, as wire items.
pub(crate) fn place_locations(&self, id: u32) -> CoreResult<Vec<PhotoLocation>> {
let photos = self
.db
.photo_locations_at_place(id)
.map_err(CoreError::from)?;
Ok(photos
.into_iter()
.map(|(photo, (latitude, longitude))| PhotoLocation {
photo: self.photo_item(photo),
latitude,
longitude,
})
.collect())
}
/// Photos taken on today's date in earlier years, as wire items. Served
/// from the stored timeline only: the strip is a nicety, not worth a wait
/// on the network, and the timeline's own load keeps that store fresh.
pub(crate) fn photos_on_this_day(
&self,
limit: usize,
excluded: &str,
) -> CoreResult<Vec<PhotoItem>> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i64);
let photos = self
.db
.photos_on_this_day_visible(now, limit, excluded)
.map_err(CoreError::from)?;
Ok(photos.into_iter().map(|p| self.photo_item(p)).collect())
}
/// Every file of one photo's group, in server order, as wire items. A photo
/// the timeline does not hold comes back empty, which the lightbox reads as
/// "nothing to switch between".
pub(crate) fn photo_group(&self, uid: &str) -> CoreResult<Vec<PhotoItem>> {
let members = self.db.photos_group(uid).map_err(CoreError::from)?;
Ok(members
.into_iter()
.map(|photo| self.photo_item(photo))
.collect())
}
/// Every uid asked for, plus the other files of any group they belong to,
/// each once. A uid the timeline does not hold (an album photo on someone
/// else's volume) is passed through unchanged.
pub(crate) fn expand_photo_groups(&self, uids: &[NodeUid]) -> Vec<NodeUid> {
let mut out: Vec<NodeUid> = Vec::with_capacity(uids.len());
let mut seen: HashSet<String> = HashSet::new();
for uid in uids {
let members = self.db.photos_group(&uid.to_string()).unwrap_or_default();
let mut group: Vec<NodeUid> = members
.iter()
.filter_map(|photo| parse_uid(&photo.uid))
.collect();
if group.is_empty() {
group.push(uid.clone());
}
for member in group {
if seen.insert(member.to_string()) {
out.push(member);
}
}
}
out
}
/// Mutation admission for a photo, which [`Core::require_uid_writable`]
/// cannot answer on its own.
///
/// Photos live on the photo volume, and that volume is not part of the FUSE
/// tree: a photo has no `nodes` row, so every authority comes back
/// [`WriteAuthority::Unknown`] and the plain check refuses the whole
/// library. Membership of our own timeline is the authority that does exist
/// here — the timeline is enumerated from our photo share, so a uid in it is
/// ours to trash. Anything else (an album photo on someone else's volume)
/// still fails closed.
pub(crate) fn require_photo_writable(&self, uid: &NodeUid) -> Result<(), fuser::Errno> {
match self.uid_write_authority(uid) {
WriteAuthority::Writable => Ok(()),
WriteAuthority::Denied => Err(fuser::Errno::EACCES),
WriteAuthority::Unknown => {
let key = uid.to_string();
let known = self
.db
.photos_by_uid(std::slice::from_ref(&key))
.map(|rows| !rows.is_empty())
.unwrap_or(false);
if known {
Ok(())
} else {
Err(fuser::Errno::EACCES)
}
}
}
}
/// Trash photos by uid, and forget them locally.
///
/// The gallery is not part of the FUSE mount, so this is the photos-side
/// counterpart of [`Core::delete`]: same destination (Proton trash, so the
/// Trash page can restore them), addressed by uid because that is all a tile
/// has.
///
/// The server answers per node, and so does this: a batch where one photo
/// fails still removes the ones that went, and the caller is told which is
/// which. Only what actually left the server is forgotten locally.
///
/// A photo that is one file of a group takes its whole group with it. The
/// gallery shows a RAW+JPEG shot as one tile, so deleting that tile has to
/// delete the shot — leaving the RAW behind would put the photo back on the
/// Raw tab and nowhere else. `files_only` turns that off, for removing
/// one copy of a shot that is stored twice.
pub(crate) fn trash_photos(
&self,
uids: &[NodeUid],
files_only: bool,
) -> CoreResult<TrashOutcome> {
if uids.is_empty() {
return Ok((Vec::new(), Vec::new()));
}
let expanded;
let uids = if files_only {
uids
} else {
expanded = self.expand_photo_groups(uids);
&expanded
};
for uid in uids {
self.require_photo_writable(uid)
.map_err(|errno| self.errno_error(errno, "trash access"))?;
}
let outcomes = self
.rt
.block_on(self.drive.trash_nodes(uids))
.map_err(|e| CoreError::from_api(&e, "trash"))?;
let (trashed, failed) = pdfs_core::batch::split(outcomes);
let trashed: Vec<String> = trashed.iter().map(|uid| uid.to_string()).collect();
for uid in &trashed {
if let Some(parsed) = parse_uid(uid) {
self.cache.evict(&parsed);
self.evict_reader(&parsed);
}
}
// The timeline is served from the database, so removing the rows is what
// makes the photos disappear now rather than at the next refresh.
if let Err(error) = self.db.photos_delete(&trashed) {
warn!(%error, "trashed photos could not be removed from the timeline");
}
self.invalidate_photos();
self.invalidate_albums();
self.invalidate_trash();
let failed = failed
.into_iter()
.map(|(uid, error)| (uid.to_string(), error.to_string()))
.collect();
Ok((trashed, failed))
}
/// Commit the lightweight listing before resolving pending nodes. The
/// feed generation fences both commits against events received in flight.
pub(crate) async fn refresh_timeline(&self) -> CoreResult<bool> {
let started = Instant::now();
let generation = self
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos();
if self
.db
.state_i64(PHOTOS_SYNCED_MS)
.map_err(CoreError::from)?
.is_none()
{
let available = link::bounded(photos.get_photos_root())
.await
.map_err(|e| CoreError::from_api(&e, "photos root"))?
.is_some();
let items = if available {
link::bounded_by(crate::BATCH_CALL_TIMEOUT, photos.enumerate_timeline())
.await
.map_err(|e| CoreError::from_api(&e, "timeline"))?
.into_iter()
.map(|item| db::TimelineRow::new(item.uid.to_string(), item.capture_time))
.collect()
} else {
Vec::new()
};
if !self
.db
.photos_replace_at(&items, generation, available, now_ms())
.map_err(CoreError::from)?
{
return Err(CoreError::remote(
"Photos changed during the refresh. Try again shortly.",
));
}
if !available {
return Ok(false);
}
} else if self
.db
.state_i64(PHOTOS_AVAILABLE)
.map_err(CoreError::from)?
== Some(0)
{
return Ok(false);
}
let pending = self.db.photos_pending().map_err(CoreError::from)?;
let total = self.db.photos_count().map_err(CoreError::from)?;
let skipped = total.saturating_sub(pending.len());
let mut resolved = 0;
let progress = ProgressGuard(&self.photo_jobs.timeline_progress);
for (index, chunk) in pending.chunks(TIMELINE_ENRICH_CHUNK).enumerate() {
if self.shutdown.is_stopping() {
break;
}
*progress.0.lock() = Some((skipped + index * TIMELINE_ENRICH_CHUNK, total));
let uids: Vec<_> = chunk.iter().filter_map(|uid| parse_uid(uid)).collect();
let nodes = link::bounded(photos.enumerate_nodes(&uids))
.await
.map_err(|e| CoreError::from_api(&e, "read photo metadata"))?;
let rows: Vec<_> = nodes
.into_iter()
.filter_map(|node| {
let NodeKind::File { media_type, .. } = node.kind else {
return None;
};
if node.trashed {
return None;
}
let photo = node.photo.as_ref();
Some(db::TimelineRow {
name: Some(node.name),
media_type: Some(media_type),
favorite: Some(photo.is_some_and(|p| p.tags.contains(&PhotoTag::Favorite))),
content_hash: photo.and_then(|p| p.content_hash.clone()),
location: photo
.and_then(|p| p.location)
.map(|l| (l.latitude, l.longitude)),
main_uid: photo
.and_then(|p| p.main_photo_uid.as_ref())
.map(ToString::to_string),
resolved_at: Some(now_ms()),
..db::TimelineRow::new(node.uid.to_string(), 0)
})
})
.collect();
if !self
.db
.photos_resolve_at(generation, &rows)
.map_err(CoreError::from)?
{
return Err(CoreError::remote(
"Photos changed during the refresh. Try again shortly.",
));
}
resolved += rows.len();
}
info!(
photos = total,
resolved,
wanted = pending.len(),
skipped,
elapsed_ms = started.elapsed().as_millis() as u64,
"photos timeline refreshed"
);
Ok(true)
}
/// Refresh the timeline off the request path, so a stale page is still served
/// at DB speed. At most one refresh runs at a time.
/// Refresh the timeline and wait for it, sharing a refresh already under
/// way instead of starting a second one beside it.
///
/// The first request after an empty cache has nothing to serve until the
/// fetch lands, so it waits. Two such requests (the gallery and its retry,
/// or a background refresh started by an import) used to each fetch the
/// whole library at once, sharing the session's rate limit and taking
/// minutes. Returns whether the account has a photos library.
pub(crate) fn refresh_timeline_joined(&self) -> CoreResult<bool> {
if self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
{
while self.photo_jobs.timeline_refreshing.load(Ordering::SeqCst)
&& !self.shutdown.is_stopping()
{
std::thread::sleep(std::time::Duration::from_millis(200));
}
// A refresh that landed stamped the timeline fresh. One that failed
// did not, and the caller gets this refresh's own error instead of
// an empty timeline.
if self
.db
.state_i64(PHOTOS_SYNCED_MS)
.map_err(CoreError::from)?
.is_some()
|| self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
{
return Ok(self.db.state_i64(PHOTOS_AVAILABLE).ok().flatten() != Some(0));
}
}
let refreshed = self.rt.block_on(self.refresh_timeline());
self.photo_jobs
.timeline_refreshing
.store(false, Ordering::SeqCst);
if refreshed.is_ok() {
self.events.publish(&[Topic::Photos]);
}
refreshed
}
pub(crate) fn spawn_timeline_refresh(&self) {
if self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
{
return;
}
let core = self.clone();
self.services
.spawn_task_job(&self.rt, "pdfs-timeline-refresh", async move {
let refreshed = core.refresh_timeline().await;
core.photo_jobs
.timeline_refreshing
.store(false, Ordering::SeqCst);
// Only a refresh that landed: a front-end re-reading after a failed
// one would find the timeline still stale and start another.
match refreshed {
Ok(_) => core.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background timeline refresh failed"),
}
});
}
/// How far the running timeline refresh has got reading photo metadata, or
/// `None` when no refresh is reading any.
pub(crate) fn timeline_progress(&self) -> Option<MappingProgress> {
self.photo_jobs
.timeline_progress
.lock()
.map(|(done, total)| MappingProgress { done, total })
}
/// Whether a timeline refresh is running. A front-end that asked for one
/// watches this to know when the new timeline is worth re-reading.
pub(crate) fn timeline_refreshing(&self) -> bool {
self.photo_jobs.timeline_refreshing.load(Ordering::SeqCst)
}
/// Download a photo's full content into the content cache, returning its
/// on-disk path (served from cache when a fresh blob already exists).
pub(crate) fn open_photo(&self, uid: &NodeUid) -> CoreResult<PathBuf> {
let photos = self.photos();
let node = self
.rt
.block_on(photos.get_node(uid))
.map_err(|e| CoreError::from_api(&e, "photo node"))?
.ok_or_else(|| CoreError::not_found("photo not found"))?;
let (mtime, size) = (node.modification_time, node_size(&node));
if let Some(p) = self.cache.cached_content_path(uid, mtime, size) {
return Ok(p);
}
let bytes = self
.download_photo_tracked(&photos, uid, &node.name, size)
.map_err(|e| CoreError::from_api(&e, "download photo"))?;
self.cache
.store(uid, mtime, size, &bytes)
.map_err(|e| CoreError::internal(format!("cache store: {e}")))?;
Ok(self.cache.content_path(uid))
}
}
+4 -3
View File
@@ -42,9 +42,10 @@ impl Core {
.map_err(|e| CoreError::from_api(&e, "pin"))?;
let core = self.clone();
let folder = name.clone();
std::thread::Builder::new()
.name("pin-folder".into())
.spawn(move || core.pin_subtree(ino, &uid, &folder))
self.services
.spawn_job("pdfs-pin-folder", move || {
core.pin_subtree(ino, &uid, &folder)
})
.map_err(|e| CoreError::internal(format!("spawn pin: {e}")))?;
return Ok(format!("{name}: downloading its files in the background"));
}
+4 -2
View File
@@ -55,7 +55,7 @@ impl Core {
return;
}
let core = self.clone();
std::thread::spawn(move || {
if let Err(error) = self.services.spawn_job("pdfs-profile-backup", move || {
let (saving, dirty) = save_state();
while dirty.swap(false, Ordering::SeqCst) {
if let Err(e) = core.save_profile() {
@@ -64,7 +64,9 @@ impl Core {
}
}
saving.store(false, Ordering::SeqCst);
});
}) {
tracing::warn!(%error, "could not start pdfs-profile-backup");
}
}
/// Serialize this machine's arrangement and upload it to its own
+4 -2
View File
@@ -288,7 +288,7 @@ impl Core {
}
let core = self.clone();
std::thread::spawn(move || {
if let Err(error) = self.services.spawn_job("pdfs-redate", move || {
let outcome = core.redate_photos(dry_run, limit, range, cancel);
let mut state = REDATE.lock();
state.running = false;
@@ -310,7 +310,9 @@ impl Core {
),
Err(e) => warn!(error = %e, "photo re-date failed"),
}
});
}) {
tracing::warn!(%error, "could not start pdfs-redate");
}
Ok(())
}
}
+14
View File
@@ -140,6 +140,14 @@ pub(crate) fn run(seed: u64, profile: &'static Profile) -> Result<(), String> {
}
}
run.logged.extend(take_logged());
// Every stop, the restarts' included, ends all the services a mount
// started; one left running is a second generation beside the next mount's.
let outcome = outcome.and_then(
|()| match run.logged.iter().find(|line| left_running(line)) {
Some(line) => Err(format!("shutdown: a stop left services running: {line}")),
None => Ok(()),
},
);
match outcome {
Ok(()) => {
let _ = std::fs::remove_dir_all(&dir);
@@ -608,6 +616,12 @@ fn outcome(actual: &Result<Result<(), i32>, String>) -> String {
}
}
/// Whether `line` is the mount's report of services still running at its
/// stop deadline (`mount::halt_workers`).
fn left_running(line: &str) -> bool {
line.starts_with("background workers did not finish in time")
}
/// Run `profile` over the seeds the environment asks for: `PDFS_SIM_SEED`
/// alone, or `PDFS_SIM_SEEDS` of them (default `default_seeds`) from 1.
pub(crate) fn run_seeds(profile: &'static Profile, default_seeds: u64) {
+7 -1
View File
@@ -130,7 +130,13 @@ impl Core {
SizeUpgradeClaim::Start(slot, uids) => {
let core = self.clone();
let worker = slot.clone();
std::thread::spawn(move || core.run_size_upgrade(key, uids, worker));
if let Err(error) = self.services.spawn_job("pdfs-size-upgrade", move || {
core.run_size_upgrade(key, uids, worker)
}) {
// The waiters give up on the slot at their deadline and
// answer with the size they have.
warn!(%error, "could not start a size upgrade");
}
Some(slot)
}
}
+4 -2
View File
@@ -1153,7 +1153,7 @@ impl Core {
}
let core = self.clone();
std::thread::spawn(move || {
if let Err(error) = self.services.spawn_job("pdfs-import", move || {
// The job is dropped only after the final state is stored: the
// job leaving the transfer snapshot is the front-ends' cue to ask
// for the result, which must then be there.
@@ -1186,7 +1186,9 @@ impl Core {
summary.complete(),
);
}
});
}) {
tracing::warn!(%error, "could not start pdfs-import");
}
Ok(())
}
}
+11 -10
View File
@@ -266,16 +266,17 @@ impl Core {
return;
}
let core = self.clone();
self.rt.spawn(async move {
let refreshed = core.refresh_trash().await;
core.trash.trash_refreshing.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Trash]),
Err(e) => warn!(error = %e, "background trash refresh failed"),
}
// After the flag, so a waiter that wakes on this sees it cleared.
core.trash.trash_progress.notify_waiters();
});
self.services
.spawn_task_job(&self.rt, "pdfs-trash-refresh", async move {
let refreshed = core.refresh_trash().await;
core.trash.trash_refreshing.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Trash]),
Err(e) => warn!(error = %e, "background trash refresh failed"),
}
// After the flag, so a waiter that wakes on this sees it cleared.
core.trash.trash_progress.notify_waiters();
});
}
/// Wait for the in-flight trash refresh to make progress, for at most
File diff suppressed because it is too large. Load diff
+578
View File
@@ -0,0 +1,578 @@
//! Applying a pass's plan: uploads, downloads and the other effects, in
//! batches, and the baseline each one leaves behind.
use super::*;
impl Syncer {
/// Store the revision id of each file in one listing whose baseline row has
/// none, when the size the walk just read shows that file unchanged.
///
/// The classification step does the same, but only a pass that gets all the
/// way through the walk reaches it. A large folder whose walk is cut short
/// every time (a restart, a logout) then reads the size of every such file
/// again, one key unlock each, on every pass, and never finishes (B294).
pub(super) fn record_revisions(
&self,
folder_id: i64,
prefix: &str,
nodes: &[Node],
sized: &HashMap<String, (i64, Option<String>)>,
baseline: &HashMap<String, StoredSyncEntry>,
) {
let rows = revisions_to_record(prefix, nodes, sized, baseline);
if rows.is_empty() {
return;
}
match self.store.sync_entries_set_revision(folder_id, &rows) {
Ok(n) => self.trace_count(Count::Revisions, n),
Err(e) => debug!(folder = prefix, error = ?e, "sync: cannot record revision ids"),
}
}
/// Record a folder's baseline row (folders carry no content signature).
pub(super) fn baseline_dir(
&self,
folder_id: i64,
rel: &str,
uid: &NodeUid,
) -> Result<(), String> {
self.store
.sync_entry_upsert(folder_id, &dir_row(rel, uid))
.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
/// 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
/// engine thread, spawning the tasks onto the shared runtime.
///
/// Fails with [`PassAbort::Stopped`] once the daemon is stopping, after the
/// ops already sending have finished.
pub(super) fn flush_batch(
&self,
folder_id: i64,
local_root: &Path,
remote_dirs: &mut HashMap<String, NodeUid>,
batch: Vec<Pending>,
outcome: &mut Outcome,
) -> Result<(), PassAbort> {
if batch.is_empty() {
return Ok(());
}
self.progress_queued(folder_id, batch.len());
self.trace_count(Count::Queued, batch.len());
let applying = Instant::now();
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");
// An op still waiting for its turn when the stop comes is
// not started; the ones already sending finish.
if core.shutdown.is_stopping() {
return None;
}
Some(core.apply_pending(folder_id, &root, op).await)
});
}
let mut out = Vec::new();
let mut join_errors = 0usize;
while let Some(joined) = set.join_next().await {
match joined {
Ok(Some(result)) => out.push(result),
Ok(None) => {}
// The runtime ends with the daemon and cancels what is left.
Err(e) if e.is_cancelled() => {}
Err(e) => {
join_errors += 1;
warn!(error = %e, "sync: task panicked");
}
}
}
(out, join_errors)
});
self.trace_phase(Phase::Apply, applying.elapsed());
let (results, join_errors) = results;
outcome.errors += join_errors;
for result in results {
match result {
Ok(applied) => {
outcome.record(&applied);
if let Applied::Dir(rel, uid) = applied {
remote_dirs.insert(rel, uid);
}
}
Err(e) => {
warn!(error = %e, "sync: step failed; continuing");
outcome.failed(&e);
}
}
}
// The pass goes no further: the next depth's paths may need a folder
// this batch did not get to make, and went on to fail one by one
// (`docs/BUGS.md` B169).
if self.shutdown.is_stopping() {
return Err(PassAbort::Stopped);
}
if self.pass_abandoned(folder_id) {
return Err(PassAbort::Abandoned);
}
Ok(())
}
/// 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)
}
/// Apply one [`Pending`] op (async, so it can run concurrently in a batch),
/// reporting it to the folder's live progress and to the activity feed. Each
/// item logs its own line — the feed is meant to answer "what is it doing",
/// which a pass-level summary alone cannot.
pub(super) async fn apply_pending(
&self,
folder_id: i64,
local_root: &Path,
op: Pending,
) -> Result<Applied, String> {
self.progress_started(folder_id, base_name(op.rel()));
let step = Instant::now();
let result = self.apply_one(folder_id, local_root, &op).await;
self.trace_call(op.call(), step.elapsed());
self.progress_finished(folder_id);
let name = base_name(op.rel());
match &result {
Ok(Applied::Adopted) => {}
Ok(_) => self.log_activity(op.kind(), name, op.detail(), true),
Err(e) => self.log_activity(op.kind(), name, e.clone(), false),
}
result
}
/// The body of one [`Pending`] op, without the progress/activity bookkeeping.
pub(super) async fn apply_one(
&self,
folder_id: i64,
local_root: &Path,
op: &Pending,
) -> Result<Applied, String> {
match op {
Pending::CreateDir { rel, parent } => {
let uid = self
.drive
.create_folder(parent, base_name(rel), Some(now_secs()))
.await
.map_err(|e| format!("create remote folder {rel}: {e}"))?;
// The parent has gained a child that no cached listing of it
// knows about (B86).
self.invalidate_children_of(parent);
self.baseline_dir(folder_id, rel, &uid)?;
Ok(Applied::Dir(rel.clone(), uid))
}
Pending::UploadNew { rel, parent } => {
self.upload_new(folder_id, local_root, rel, parent).await
}
Pending::UploadRevision { rel, uid, seen } => {
self.upload_revision(folder_id, local_root, rel, uid, seen)
.await
}
Pending::Download {
rel,
uid,
seen,
local,
} => {
self.download_file(folder_id, local_root, rel, uid, seen, *local)
.await?;
Ok(Applied::Downloaded)
}
Pending::Adopt {
rel,
uid,
seen: remote,
sha1,
local,
} => {
let path = local_root.join(rel_to_path(rel));
let hashed = tokio::task::spawn_blocking(move || local_sha1(&path))
.await
.map_err(|e| format!("hash {rel}: {e}"))?
.map_err(|e| format!("hash {rel}: {e}"))?;
let Some((seen, digest)) = hashed else {
return Ok(Applied::Vanished);
};
// Edited since the scan: the next pass plans it again.
if !seen.same_content(local) {
return Ok(Applied::Vanished);
}
if !digest.eq_ignore_ascii_case(sha1) {
info!(
rel,
"sync: same size as on Drive but different content; keeping a conflict copy"
);
return self
.take_remote_keeping_local(folder_id, local_root, rel, uid, remote)
.await;
}
self.store
.sync_entry_upsert(
folder_id,
&StoredSyncEntry {
rel_path: rel.clone(),
remote_uid: Some(uid.to_string()),
local_mtime: seen.mtime,
local_mtime_ns: seen.mtime_ns,
local_size: seen.size,
remote_rev: Some(remote.mtime.to_string()),
remote_hash: Some(remote.size.to_string()),
remote_revision_id: remote.revision.clone(),
},
)
.map_err(|e| format!("adopt baseline {rel}: {e:?}"))?;
Ok(Applied::Adopted)
}
Pending::Conflict { rel, uid, seen } => {
self.take_remote_keeping_local(folder_id, local_root, rel, uid, seen)
.await
}
Pending::PushConflict { rel, parent } => {
// The ordinary conflict resolution — rename the local copy aside and
// let the next pass upload it — loses the file here: the folder is
// going on-demand, so "next pass" comes after the local tree has been
// evicted. Push the conflict copy now, while it still exists, and
// leave the remote file holding the original path.
let path = local_root.join(rel_to_path(rel));
let conflict = preserve_conflict_copy(&path, now_secs())
.map_err(|e| format!("set aside conflict copy for {rel}: {e}"))?;
let name = conflict
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.ok_or_else(|| format!("conflict copy for {rel} has no name"))?;
let conflict_rel = join_rel(parent_rel(rel), &name);
self.upload_new(folder_id, local_root, &conflict_rel, parent)
.await?;
info!(rel, "sync: uploaded local changes as a conflict copy");
Ok(Applied::Conflict)
}
}
}
/// Set the local copy aside (it re-uploads as a new file next pass), then
/// take the remote version as the shared truth.
pub(super) async fn take_remote_keeping_local(
&self,
folder_id: i64,
local_root: &Path,
rel: &str,
uid: &NodeUid,
seen: &RemoteSeen,
) -> Result<Applied, String> {
let path = local_root.join(rel_to_path(rel));
if path.exists() {
preserve_conflict_copy(&path, now_secs())
.map_err(|e| format!("set aside conflict copy for {rel}: {e}"))?;
info!(rel, "sync: kept local changes as a conflict copy");
}
// The local copy has just been moved aside, so the state this
// download expects to find at the path is "nothing" — anything
// that appears while it runs is a *new* racing write, and gets
// its own conflict copy rather than being overwritten (B39).
self.download_file(folder_id, local_root, rel, uid, seen, None)
.await?;
Ok(Applied::Conflict)
}
/// Upload a brand-new local file to its remote parent, then record baseline.
pub(super) async fn upload_new(
&self,
folder_id: i64,
local_root: &Path,
rel: &str,
parent: &NodeUid,
) -> Result<Applied, String> {
let path = local_root.join(rel_to_path(rel));
let name = base_name(rel);
let Some(file) = open_to_upload(&path, rel)? else {
return Ok(Applied::Vanished);
};
let meta = file.metadata().map_err(|e| format!("stat {rel}: {e}"))?;
let mtime = system_mtime(&meta);
// Taken from the descriptor being streamed, so it names the content that
// actually goes up rather than whatever is at the path when we finish.
let streamed = LocalSig::from(&meta);
let thumbnails = self
.thumbnails_for_upload(path.clone(), name.to_string())
.await;
// Count the bytes as they are read, so this upload shows up in
// `GetQueueStatus` next to a manual one. The uid isn't known until the
// draft is sealed, so the transfer registers without one.
let (reader, sent) = Sha1Tap::new(OwnedCountingReader::new(
file,
self.transfers
.begin(name, "", TransferDirection::Upload, meta.len()),
));
let uid = self
.drive
// Mirror push: the local file is authoritative. If a prior attempt was
// interrupted mid-upload it left an unsealed draft of this name; recover
// it even across a daemon restart (which rotates our client uid), so the
// folder can reach idle instead of `AlreadyExists`-looping forever.
.upload_file_replacing_draft_from(
parent,
name,
pdfs_drive::media_type_for(name),
reader,
meta.len() as i64,
thumbnails,
Some(mtime),
false,
)
.await
.map_err(|e| 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).
self.invalidate_children_of(parent);
warn_if_torn(rel, &path, streamed);
let remote = self
.landed_as_sent(rel, &uid, &sent.digest(), streamed)
.await?;
self.record_file_baseline(folder_id, rel, Some(streamed), &uid, &remote)?;
Ok(Applied::Uploaded)
}
/// Upload a changed local file as a new revision of an existing remote node.
///
/// The revision supersedes whatever is current on Drive, and the plan comes
/// from a walk that may be minutes old. Another computer syncing the same
/// 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.
pub(super) async fn upload_revision(
&self,
folder_id: i64,
local_root: &Path,
rel: &str,
uid: &NodeUid,
seen: &RemoteSeen,
) -> Result<Applied, String> {
let path = local_root.join(rel_to_path(rel));
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"
));
}
}
let meta = file.metadata().map_err(|e| format!("stat {rel}: {e}"))?;
let mtime = system_mtime(&meta);
let streamed = LocalSig::from(&meta);
let thumbnails = self
.thumbnails_for_upload(path.clone(), base_name(rel).to_string())
.await;
let (reader, sent) = Sha1Tap::new(OwnedCountingReader::new(
file,
self.transfers.begin(
base_name(rel),
uid.to_string(),
TransferDirection::Upload,
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}"))?;
warn_if_torn(rel, &path, streamed);
let remote = self
.landed_as_sent(rel, uid, &sent.digest(), streamed)
.await?;
self.record_file_baseline(folder_id, rel, Some(streamed), uid, &remote)?;
Ok(Applied::Uploaded)
}
/// Download a remote file to its local path (atomically via a temp file),
/// stamp the local mtime to match the remote, then record baseline.
///
/// `expected_local` is the identity planning saw at the destination. The
/// rename below is the destructive step, and the download in between can run
/// for minutes, so the destination is re-examined right before it: a local
/// file that no longer matches the plan is set aside as a conflict copy
/// instead of being replaced (`docs/BUGS.md` B39).
///
/// The baseline records `seen`, the revision the pass planned to download,
/// and not a read of the node afterwards. Another computer may commit a
/// revision while the download runs, and a read-back would record that
/// revision as synced while the disk holds the older one, so its edit would
/// never arrive (B250). If the download did fetch the newer revision, the
/// next pass fetches it once more, which costs a transfer and loses nothing.
pub(super) async fn download_file(
&self,
folder_id: i64,
local_root: &Path,
rel: &str,
uid: &NodeUid,
seen: &RemoteSeen,
expected_local: Option<LocalSig>,
) -> Result<(), String> {
let (mtime, size) = (seen.mtime, seen.size);
let path = local_root.join(rel_to_path(rel));
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| format!("mkdir for {rel}: {e}"))?;
}
let tmp = staging_path(&path);
// A file an on-demand mount already read, say one just moved here from
// it, is in the content cache under the same revision key.
let seeded = size > 0 && self.cache.copy_cached_to(uid, mtime, size as u64, &tmp);
if seeded {
std::fs::File::open(&tmp)
.and_then(|f| f.sync_all())
.map_err(|e| {
let _ = std::fs::remove_file(&tmp);
format!("sync tmp {rel}: {e}")
})?;
debug!(
rel,
"sync: placed from the content cache instead of downloading"
);
} else {
let out = std::fs::File::create(&tmp).map_err(|e| format!("create tmp {rel}: {e}"))?;
// Count the bytes as they land, so the download reports progress like
// an on-demand hydration does.
let guard = self.transfers.begin(
base_name(rel),
uid.to_string(),
TransferDirection::Download,
size.max(0) as u64,
);
let mut out = CountingWriter::new(out, &guard);
self.drive
.download_file_to(uid, &mut out)
.await
.map_err(|e| {
let _ = std::fs::remove_file(&tmp);
format!("download {rel}: {e}")
})?;
let mut out = out.into_inner();
out.flush().map_err(|e| format!("flush tmp {rel}: {e}"))?;
out.sync_all().map_err(|e| format!("sync tmp {rel}: {e}"))?;
}
place_download(&tmp, &path, expected_local, mtime, rel)?;
// Here the file on disk *is* the transferred content: it was published
// by a rename and stamped just above, so its stat is the identity.
self.record_file_baseline(folder_id, rel, local_sig(&path), uid, seen)
}
/// What Drive holds for `uid` after this daemon uploaded content with SHA-1
/// `sent` and identity `streamed` to it, as the baseline should record it.
///
/// Read back so the stored signature is exactly what a walk reports next
/// time. A digest on Drive that is not `sent` means another computer
/// committed a revision right after this upload. Recording that revision
/// as synced would hide it, and the edit here would be lost to it on the
/// next download. So the baseline is left as it was, and the next pass sees
/// both sides changed and keeps a conflict copy (B250).
pub(super) async fn landed_as_sent(
&self,
rel: &str,
uid: &NodeUid,
sent: &str,
streamed: LocalSig,
) -> Result<RemoteSeen, String> {
let node = match self.drive.enumerate_nodes(std::slice::from_ref(uid)).await {
Ok(nodes) => nodes.into_iter().next(),
Err(e) => {
warn!(rel, error = %e, "sync: baseline refetch failed; using local mtime");
None
}
};
let Some(node) = node else {
// Drive does not list a node it has just made at once. The upload
// stamped it with the local modification time, so that and the
// size sent are what a walk reports.
return Ok(RemoteSeen {
mtime: streamed.mtime,
size: streamed.size,
revision: None,
});
};
if let Some(digest) = pdfs_drive::node_content_sha1(&node)
&& !digest.eq_ignore_ascii_case(sent)
{
return Err(format!(
"{rel} was changed on Drive by another client right after this upload; it is compared again on the next pass"
));
}
let (mtime, size) = remote_file_sig(&node);
Ok(RemoteSeen {
mtime,
size,
revision: pdfs_drive::node_revision_id(&node),
})
}
/// Record a file's baseline: the local identity these bytes came from and
/// the remote revision they were synced with. Called after every
/// upload/download so the very next reconcile sees the path as unchanged.
///
/// `local` is the identity the *transferred content* corresponds to, which
/// is not always the file's current stat. An upload streams the live file,
/// so it passes the identity it read the first byte at: if a writer changed
/// the file mid-stream, the remote now holds a torn revision, and recording
/// the pre-upload identity is what makes the next pass see the path as
/// locally changed and upload a whole, clean revision over it. Recording the
/// post-upload stat instead declared the torn revision synchronized and left
/// it as the file's content on Drive (`docs/BUGS.md` B40).
pub(super) fn record_file_baseline(
&self,
folder_id: i64,
rel: &str,
local: Option<LocalSig>,
uid: &NodeUid,
remote: &RemoteSeen,
) -> Result<(), String> {
let Some(local) = local else {
return Err(format!("stat {rel}: no local identity to baseline"));
};
self.store
.sync_entry_upsert(
folder_id,
&StoredSyncEntry {
rel_path: rel.to_string(),
remote_uid: Some(uid.to_string()),
local_mtime: local.mtime,
local_mtime_ns: local.mtime_ns,
local_size: local.size,
remote_rev: Some(remote.mtime.to_string()),
remote_hash: Some(remote.size.to_string()),
remote_revision_id: remote.revision.clone(),
},
)
.map_err(|e| format!("baseline {rel}: {e:?}"))
}
}
+350
View File
@@ -0,0 +1,350 @@
//! The push pass: sending local changes to Drive between full passes.
use super::*;
impl Syncer {
/// Get every local change up to Drive, and nothing else — the pass run for a
/// folder waiting to go on-demand, whose local copy is about to be evicted.
///
/// This exists because a full [`do_reconcile`](Self::do_reconcile) is both too
/// slow and too wasteful to stand between the user and the switch they asked
/// for. It walks the whole remote tree (the minutes-long part of a pass over a
/// large folder) to answer a question the switch makes irrelevant — what the
/// remote side has that we don't — and then downloads those files onto a disk
/// we are about to clear. A push pass answers only "is anything here not on
/// Drive yet?", which the local tree and the baseline already know, so it needs
/// no remote walk at all and finishes in the time the local walk takes.
///
/// The remote is consulted for exactly one thing: the files whose local copy
/// changed. Those, and only those, could be a two-sided edit, so their nodes are
/// fetched (cheaply, in one batch) to check whether the remote moved too. If it
/// did, the local copy goes up under a conflict name rather than overwriting the
/// other side. Everything else — remote edits, remote deletions, remote-only
/// files — is left for the FUSE mount to show live once the switch lands.
///
/// Per-path failures are counted, never fatal, exactly as in `do_reconcile`; a
/// non-zero [`Outcome::errors`] leaves the folder out of `idle`, which keeps the
/// queued switch waiting rather than evicting a file that never made it up.
pub(super) fn push_pass(
&self,
folder_id: i64,
local_root: &Path,
remote_root: &NodeUid,
rules: &IgnoreRules,
) -> Result<Outcome, PassAbort> {
// This pass uploads without walking Drive, so a walk saved by an
// earlier pass would not know what it sent; see `do_reconcile`.
self.store
.sync_walk_clear(folder_id)
.map_err(|e| format!("drop the saved walk: {e:?}"))?;
let step = Instant::now();
let baseline = self
.store
.sync_entries(folder_id)
.map_err(|e| format!("load baseline: {e:?}"))?;
self.trace_phase(Phase::Baseline, step.elapsed());
// Only the local side is walked here, so each baseline path is checked once.
self.progress_scan_total(folder_id, baseline.len());
let mut local: HashMap<String, LocalItem> = HashMap::new();
let mut unscanned = Unscanned::default();
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,
)?;
self.trace_phase(Phase::LocalWalk, step.elapsed());
self.trace_count(Count::LocalEntries, local.len());
// The guard compares against the paths this pass could still see: an
// ignored or unreadable path is absent from `local` by rule or by
// failure, not by loss, and counting those as missing would trip the
// guard on every pass — wedging the folder's sync permanently — the
// moment a rule covers the whole tree.
let tracked = tracked_baseline(&baseline, rules, &unscanned);
// A local copy that is gone in its entirety is not trashed on Drive,
// for the reason `guard_local_wipe` gives. A full pass stops there, but
// this one exists for a switch to on-demand, which needs nothing local
// and leaves Drive as it is: refusing the pass would only keep the
// folder out of `idle`, wedging the switch for good (#46). So the pass
// forgets those paths instead of trashing them, and the mount then
// shows everything Drive still has.
let local_gone = match guard_local_wipe(&tracked, &local) {
Ok(()) => false,
Err(reason) => {
warn!(id = folder_id, %reason, "sync: going on-demand without trashing anything on Drive");
true
}
};
// The remote folder uids come from the baseline instead of a walk: every
// directory this device has synced recorded its uid there when it was
// created or first matched up.
let mut remote_dirs: HashMap<String, NodeUid> = HashMap::new();
remote_dirs.insert(String::new(), remote_root.clone());
for (rel, item) in &local {
if !item.is_dir {
continue;
}
if let Some(uid) = baseline
.get(rel)
.and_then(|e| e.remote_uid.as_deref())
.and_then(parse_uid)
{
remote_dirs.insert(rel.clone(), uid);
}
}
// A local directory the baseline has no uid for is either brand new or one
// whose first pass never finished — and those look identical from here.
// Creating it blindly would duplicate a remote folder we simply haven't
// looked at, so when any exist, the remote folder tree is walked for real.
// It costs one light listing per folder and no file keys, and a folder whose
// baseline is complete — the case this pass is written for — skips it
// entirely and touches the network only for the files it uploads.
if local
.iter()
.any(|(rel, item)| item.is_dir && !remote_dirs.contains_key(rel))
{
self.walk_remote_dirs(folder_id, remote_root, "", &mut remote_dirs)?;
}
// Files whose local copy has moved since the baseline: the only ones with
// anything to push, and the only ones that could be a two-sided edit.
let changed: Vec<&String> = local
.iter()
.filter(|(_, item)| !item.is_dir && !item.open_for_write)
.filter(|(rel, item)| {
baseline
.get(*rel)
.is_none_or(|b| b.local_mtime != item.mtime || b.local_size != item.size)
})
.map(|(rel, _)| rel)
.collect();
// One light batch tells us which of those also changed remotely. A light
// node carries the modification time and the revision id without
// unlocking the node key, and those are what the baseline compares
// against.
let check: Vec<NodeUid> = changed
.iter()
.filter_map(|rel| baseline.get(*rel))
.filter_map(|e| e.remote_uid.as_deref())
.filter_map(parse_uid)
.collect();
let remote_now: HashMap<String, (i64, Option<String>)> = if check.is_empty() {
HashMap::new()
} else {
self.rt
.block_on(self.drive.enumerate_nodes_light(&check))
.map_err(|e| format!("resolve changed nodes: {e}"))?
.into_iter()
.filter(|n| !n.trashed)
.map(|n| {
let revision = pdfs_drive::node_revision_id(&n);
(n.uid.to_string(), (n.modification_time, revision))
})
.collect()
};
let changed: HashSet<&String> = changed.into_iter().collect();
let mut outcome = Outcome {
deferred: local.values().filter(|item| item.open_for_write).count(),
unscanned: unscanned.report(),
..Default::default()
};
let mut order: Vec<&String> = local.keys().collect();
order.sort_by_key(|p| p.matches('/').count());
// Same depth-ascending batching as `do_reconcile`: a folder is created
// remotely before the paths inside it are classified, so their parent uid is
// in `remote_dirs` by the time they need it.
let mut batch: Vec<Pending> = Vec::new();
let mut batch_depth = 0usize;
for rel in order {
let depth = rel.matches('/').count();
if depth > batch_depth {
self.flush_batch(
folder_id,
local_root,
&mut remote_dirs,
std::mem::take(&mut batch),
&mut outcome,
)?;
batch_depth = depth;
}
let item = &local[rel];
if item.is_dir {
// The folder is already on Drive, so only its children carry work —
// but if the walk above is what found it, record the uid now so the
// next pass over this folder needs no walk at all.
if let Some(uid) = remote_dirs.get(rel) {
if baseline
.get(rel)
.and_then(|e| e.remote_uid.as_deref())
.is_none()
&& let Err(e) = self.baseline_dir(folder_id, rel, uid)
{
warn!(rel, error = %e, "sync: folder step failed; continuing");
outcome.failed(&format!("{rel}: {e}"));
}
continue;
}
match remote_dirs.get(parent_rel(rel)) {
Some(parent) => batch.push(Pending::CreateDir {
rel: rel.clone(),
parent: parent.clone(),
}),
None => {
warn!(rel, "sync: no remote parent for folder; continuing");
outcome.failed(&format!("{rel}: no remote parent for folder"));
}
}
continue;
}
if !changed.contains(rel) {
// Local copy matches the baseline, so it is already on Drive.
continue;
}
let base = baseline.get(rel);
let uid = base
.and_then(|e| e.remote_uid.as_deref())
.and_then(parse_uid);
match uid {
// Never uploaded (or the remote node is gone): it goes up as a new file.
None => match remote_dirs.get(parent_rel(rel)) {
Some(parent) => batch.push(Pending::UploadNew {
rel: rel.clone(),
parent: parent.clone(),
}),
None => {
warn!(rel, "sync: no remote parent for file; continuing");
outcome.failed(&format!("{rel}: no remote parent for file"));
}
},
Some(uid) => {
let (remote_moved, seen) = match remote_now.get(&uid.to_string()) {
Some((mtime, revision)) => {
let recorded = base.and_then(remote_sig);
let moved = recorded.is_none_or(|(m, _)| m != *mtime)
|| revision_moved(base, revision.as_deref());
let seen = RemoteSeen {
mtime: *mtime,
size: recorded.map_or(0, |(_, size)| size),
revision: revision.clone(),
};
(moved, seen)
}
// Trashed or unreadable remotely — treat as gone and re-upload
// the local copy as a new file rather than losing it.
None => {
match remote_dirs.get(parent_rel(rel)) {
Some(parent) => batch.push(Pending::UploadNew {
rel: rel.clone(),
parent: parent.clone(),
}),
None => {
warn!(rel, "sync: no remote parent for file; continuing");
outcome.failed(&format!("{rel}: no remote parent for file"));
}
}
continue;
}
};
if remote_moved {
match remote_dirs.get(parent_rel(rel)) {
Some(parent) => batch.push(Pending::PushConflict {
rel: rel.clone(),
parent: parent.clone(),
}),
None => {
warn!(rel, "sync: no remote parent for file; continuing");
outcome.failed(&format!("{rel}: no remote parent for file"));
}
}
} else {
batch.push(Pending::UploadRevision {
rel: rel.clone(),
uid,
seen,
});
}
}
}
}
self.flush_batch(
folder_id,
local_root,
&mut remote_dirs,
std::mem::take(&mut batch),
&mut outcome,
)?;
// Paths the baseline knows that are no longer on disk: the user deleted them
// locally, and the deletion has to reach Drive before the mount starts
// showing the folder's remote contents — otherwise everything they deleted
// comes back the moment the switch lands. Shallowest first, skipping anything
// under a folder already trashed (its children went with it).
let deletions = local_deletions(&tracked, &local);
if local_gone {
// Forgotten instead of trashed. A row left behind would read to
// the switch as a deletion not on Drive yet and withdraw it, and
// to a later full pass as a reason to stop again. Forgotten, a full
// pass downloads the paths again.
let mut forgotten: HashSet<&str> = HashSet::new();
for rel in &deletions {
let mut parent = parent_rel(rel);
while !parent.is_empty() && !forgotten.contains(parent) {
parent = parent_rel(parent);
}
if parent.is_empty() {
let _ = self.store.sync_entries_remove_subtree(folder_id, rel);
forgotten.insert(rel);
}
}
return Ok(outcome);
}
let mut trashed: Vec<String> = Vec::new();
for rel in &deletions {
if trashed
.iter()
.any(|dir| rel.starts_with(&format!("{dir}/")))
{
let _ = self.store.sync_entry_remove(folder_id, rel);
continue;
}
let Some(uid) = baseline[rel].remote_uid.as_deref().and_then(parse_uid) else {
let _ = self.store.sync_entry_remove(folder_id, rel);
continue;
};
if let Err(e) = self
.rt
.block_on(self.drive.trash_nodes(&[uid]))
.and_then(batch::into_unit)
{
warn!(rel, error = %e, "sync: trash remote failed");
self.log_activity(ActivityKind::Trash, base_name(rel), e.to_string(), false);
outcome.failed(&format!("{rel}: {e}"));
continue;
}
trashed.push(rel.clone());
if let Some(parent) = parent_uid_of(rel, &remote_dirs, &baseline) {
self.invalidate_children_of(&parent);
}
let _ = self.store.sync_entry_remove(folder_id, rel);
self.log_activity(
ActivityKind::Trash,
base_name(rel),
"removed on Drive",
true,
);
outcome.deleted += 1;
}
Ok(outcome)
}
}
+553
View File
@@ -0,0 +1,553 @@
//! The walks of a pass: the local tree, Drive's folders (resumable, and only
//! the changed ones when the event feed can be trusted), and listing one.
use super::*;
impl Syncer {
/// Recursively walk a local tree into `out`, keyed by `/`-joined relative
/// path. Symlinks and other special files are skipped, and paths that cannot
/// be read go to `unscanned`. Reports each entry to the pass's scan progress.
pub(super) fn walk_local(
&self,
folder_id: i64,
root: &Path,
rules: &IgnoreRules,
writing: &HashSet<PathBuf>,
out: &mut HashMap<String, LocalItem>,
unscanned: &mut Unscanned,
) -> Result<(), String> {
walk_local_tree(root, rules, writing, out, unscanned, &mut |rel| {
self.progress_scanned(folder_id, base_name(rel))
})
}
/// Map every remote folder under `folder` to its uid by rel path, ignoring
/// files. The cheap half of [`walk_remote`](Self::walk_remote): folders carry no
/// content signature, so a light listing answers this without unlocking a single
/// node key. Used by [`push_pass`](Self::push_pass) to tell a folder it must
/// create from one it just hasn't recorded yet.
pub(super) fn walk_remote_dirs(
&self,
folder_id: i64,
folder: &NodeUid,
prefix: &str,
dirs: &mut HashMap<String, NodeUid>,
) -> Result<(), String> {
let uids = self
.rt
.block_on(self.drive.enumerate_folder_children_node_uids(folder))
.map_err(|e| format!("enumerate {folder}: {e}"))?;
if uids.is_empty() {
return Ok(());
}
let nodes = self
.rt
.block_on(self.drive.enumerate_nodes_light(&uids))
.map_err(|e| format!("resolve nodes: {e}"))?;
for node in nodes {
if node.trashed || !node.is_folder() || !pdfs_drive::remote_name_is_safe(&node.name) {
continue;
}
let rel = join_rel(prefix, &node.name);
self.progress_scanned(folder_id, base_name(&rel));
dirs.insert(rel.clone(), node.uid.clone());
self.walk_remote_dirs(folder_id, &node.uid, &rel, dirs)?;
}
Ok(())
}
/// Walk the remote tree of a mirror folder into `walk`, folder by folder,
/// recording every descendant's relative path, and mapping each subfolder's
/// rel path to its uid in `walk.dirs`.
///
/// A file's size comes from its extended attributes, which only its own node
/// key can decrypt — and unlocking that key costs an S2K derivation (tens of
/// milliseconds) *per file*, which is the bulk of a pass over a large folder.
/// So the walk enumerates cheaply ([`enumerate_nodes_light`]) and only pays
/// for the files whose modification time has moved away from `baseline`: an
/// unchanged mtime means the recorded size still stands.
///
/// [`enumerate_nodes_light`]: proton_drive_rs::ProtonDriveClient::enumerate_nodes_light
///
/// What the walk could not read goes to `walk.gaps`, never silently out of
/// the map: a missing path reads as deleted on Drive.
///
/// Each folder's listing is saved as it comes in. A walk cut short by a
/// stop resumes from what was saved and lists only the folders it had not
/// reached, where it used to start over and, on a folder large enough,
/// never finish (B294). The database drops a saved walk whenever the
/// 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.
pub(super) fn walk_remote(
&self,
folder_id: i64,
root: &NodeUid,
walk: &mut RemoteWalk<'_>,
baseline: &HashMap<String, StoredSyncEntry>,
) -> Result<(), PassAbort> {
let WalkStart {
mut todo,
mut children,
dirty_upto,
} = self.start_walk(folder_id, root, walk);
// Folders to list again next pass: their listing failed or came back
// short this time.
let mut again: Vec<String> = Vec::new();
let mut listed: HashSet<String> = HashSet::new();
while let Some(next) = todo.pop_front() {
// Checked per folder, not per pass: this walk is the long pole on a
// large tree, and a user who asks for on-demand three minutes into
// it should not wait out the rest of a survey of files they want
// deleted. Bailing out here is safe precisely because the walk has
// applied nothing — a *partial* remote map, on the other hand,
// would be read as "the remote deleted everything we haven't
// reached yet", so it must never reach the diff.
if self.shutdown.is_stopping() {
return Err(PassAbort::Stopped);
}
if self.pass_abandoned(folder_id) {
return Err(PassAbort::Abandoned);
}
if self.ondemand_queued(folder_id) {
return Err(PassAbort::Interrupted);
}
// Gone with a folder listed again before it, or listed already.
if walk.dirs.get(&next.prefix) != Some(&next.uid) || !listed.insert(next.prefix.clone())
{
continue;
}
let prefix = next.prefix;
// What an earlier listing could not read is read again now.
walk.gaps.forget(&prefix);
let Some(listing) = self.list_remote(folder_id, &next.uid, &prefix, walk, baseline)?
else {
// What the saved walk holds of it is older than the change
// that marked it: its files are left out of this pass, as a
// folder a full walk could not list is.
if let Some(children) = &children {
for rel in children.of(&prefix) {
if !walk.dirs.contains_key(rel) {
walk.out.remove(rel);
}
}
}
again.push(prefix);
continue;
};
if listing.short || !listing.unread.is_empty() {
again.push(prefix.clone());
}
let mut removed = Vec::new();
let mut kept: HashSet<String> = HashSet::new();
if let Some(children) = &mut children {
// Listed again: what it held before and no longer holds goes,
// with all under it. A folder still there under the same uid
// keeps what was saved under it.
let fresh: HashMap<&str, &RemoteItem> = listing
.items
.iter()
.map(|(rel, item)| (rel.as_str(), item))
.collect();
for old in children.take(&prefix) {
let same_folder = walk.dirs.get(&old).is_some_and(|uid| {
fresh
.get(old.as_str())
.is_some_and(|item| item.is_dir && &item.uid == uid)
});
if same_folder {
kept.insert(old);
} else {
children.remove_subtree(&old, walk, &mut removed);
}
}
children.add(
&prefix,
listing
.items
.iter()
.map(|(rel, _)| rel)
.chain(&listing.unread),
);
}
let mut saved = Vec::with_capacity(listing.items.len() + listing.unread.len());
for (rel, item) in listing.items {
self.progress_scanned(folder_id, base_name(&rel));
saved.push(SavedWalkItem {
rel_path: rel.clone(),
uid: Some(item.uid.to_string()),
is_dir: item.is_dir,
mtime: item.mtime,
size: item.size,
revision: item.revision.clone(),
sha1: item.sha1.clone(),
});
if item.is_dir {
walk.dirs.insert(rel.clone(), item.uid.clone());
if !kept.contains(&rel) {
todo.push_back(WalkNext {
prefix: rel.clone(),
uid: item.uid.clone(),
});
}
}
walk.out.insert(rel, item);
}
for rel in listing.unread {
self.progress_scanned(folder_id, base_name(&rel));
saved.push(SavedWalkItem {
rel_path: rel.clone(),
uid: None,
is_dir: false,
mtime: 0,
size: 0,
revision: None,
sha1: None,
});
walk.gaps.unread(rel);
}
// A walk that cannot be saved still runs; it just starts over if
// it is cut short.
if let Err(e) =
self.store
.sync_walk_record(folder_id, &prefix, listing.short, &saved, &removed)
{
debug!(folder = prefix, error = ?e, "sync: cannot save the walk's progress");
}
}
// A stop that came during the last listing still ends the pass here,
// and the next one resumes a walk with nothing left to list.
if self.shutdown.is_stopping() {
return Err(PassAbort::Stopped);
}
self.finish_walk(folder_id, dirty_upto, &again)
.map_err(|e| PassAbort::from(format!("save the walk of Drive: {e:?}")))
}
/// Keep a walk that reached its end as the next pass's picture of Drive.
/// A walk that listed every folder drops the dirty marks it read past; a
/// walk of the dirty folders only drops the marks it read, up to
/// `dirty_upto`. Either way, the folders in `again` stay dirty, so the
/// next pass lists them again.
pub(super) fn finish_walk(
&self,
folder_id: i64,
dirty_upto: Option<i64>,
again: &[String],
) -> pdfs_core::Result<()> {
if !again.is_empty() {
self.store.sync_remote_mark(folder_id, again)?;
}
match dirty_upto {
Some(seq) => self.store.sync_remote_dirty_consume(folder_id, seq),
None => {
if !self.store.sync_walk_complete(folder_id)? {
debug!(
id = folder_id,
"sync: the walk of Drive was dropped before its end"
);
}
Ok(())
}
}
}
/// Where a walk of Drive starts.
///
/// - A complete walk, kept up to date by the event stream, is loaded into
/// `walk`, and only the folders marked dirty since are listed again.
/// - A walk an earlier pass did not finish is loaded and continues, when
/// it is recent enough.
/// - Otherwise a new walk starts at the root.
pub(super) fn start_walk(
&self,
folder_id: i64,
root: &NodeUid,
walk: &mut RemoteWalk<'_>,
) -> WalkStart {
let root_uid = root.to_string();
let saved = match self.store.sync_walk_load(folder_id) {
Ok(saved) => saved,
Err(e) => {
warn!(id = folder_id, error = ?e, "sync: cannot read the saved walk; starting over");
None
}
};
if let Some(saved) = saved
&& saved.root_uid == root_uid
{
let age = now_secs().saturating_sub(saved.started);
if saved.complete
&& age < AUDIT_INTERVAL.as_secs() as i64
&& self.events_trusted(root)
&& let Some(start) = self.walk_dirty(folder_id, &saved, walk)
{
return start;
}
if !saved.complete
&& age < WALK_MAX_AGE.as_secs() as i64
&& let Some(restored) = restore_walk(&saved, walk)
{
self.progress_scanned_many(folder_id, restored.items);
self.trace_count(Count::Resumed, restored.items);
info!(
id = folder_id,
restored = restored.items,
folders_left = restored.todo.len(),
age_s = age,
"sync: resuming the walk of Drive"
);
return WalkStart {
todo: restored.todo,
children: None,
dirty_upto: None,
};
}
// Loaded into `walk`, and of no use: start from nothing.
walk.out.clear();
walk.dirs.retain(|rel, _| rel.is_empty());
*walk.gaps = RemoteGaps::default();
}
if let Err(e) = self.store.sync_walk_begin(folder_id, &root_uid, now_secs()) {
debug!(id = folder_id, error = ?e, "sync: cannot save the walk's progress");
}
WalkStart {
todo: VecDeque::from([WalkNext {
prefix: String::new(),
uid: root.clone(),
}]),
children: None,
dirty_upto: None,
}
}
/// Start from a complete walk: load it into `walk`, and list again the
/// folders marked dirty since, plus any found since and not listed yet.
/// `None` when it cannot be read back.
pub(super) fn walk_dirty(
&self,
folder_id: i64,
saved: &SavedWalk,
walk: &mut RemoteWalk<'_>,
) -> Option<WalkStart> {
let dirty = match self.store.sync_remote_dirty(folder_id) {
Ok(dirty) => dirty,
Err(e) => {
warn!(id = folder_id, error = ?e, "sync: cannot read what changed on Drive");
return None;
}
};
let restored = restore_walk(saved, walk)?;
let mut todo = restored.todo;
let mut dirs: Vec<&str> = dirty.iter().map(|(_, dir)| dir.as_str()).collect();
dirs.sort_by_key(|dir| (dir.matches('/').count(), *dir));
dirs.dedup();
// Shallowest first: a folder listed again may turn out new or gone,
// and is then listed whole or dropped with what is under it.
for dir in &dirs {
match walk.dirs.get(*dir) {
Some(uid) => todo.push_back(WalkNext {
prefix: dir.to_string(),
uid: uid.clone(),
}),
// Gone from Drive, or new and not listed yet: listing its
// parent, marked too, settles it.
None => debug!(id = folder_id, dir, "sync: a dirty folder is not on Drive"),
}
}
self.progress_scanned_many(folder_id, restored.items);
self.trace_count(Count::Reused, restored.items);
self.trace_count(Count::Dirty, dirs.len());
info!(
id = folder_id,
known = restored.items,
dirty = dirs.len(),
to_list = todo.len(),
"sync: listing only the folders changed on Drive"
);
Some(WalkStart {
todo,
children: Some(restored.children),
dirty_upto: Some(dirty.iter().map(|(seq, _)| *seq).max().unwrap_or(0)),
})
}
/// Whether Drive's event stream for `root` is being followed, so a
/// change on Drive is marked dirty by the time a pass looks. The stream
/// covers the account's own volume only, and must have been read lately.
///
/// Right after a start, the stream has not been read yet: wait a little
/// for it rather than walk all of Drive again.
pub(super) fn events_trusted(&self, root: &NodeUid) -> bool {
if root.volume_id != self.primary_root_uid.volume_id {
return false;
}
let started = Instant::now();
while self.events_read_at.load(Ordering::Relaxed) == 0
&& started.elapsed() < EVENTS_FRESH
&& self.shutdown.sleep(Duration::from_millis(250))
{}
let read_at = self.events_read_at.load(Ordering::Relaxed);
read_at > 0 && now_secs().saturating_sub(read_at) < EVENTS_FRESH.as_secs() as i64
}
/// List one folder on Drive. `None` when the listing failed: that is
/// noted in `walk.gaps`, and the folder is not saved as listed, so a
/// resumed walk asks again. A failure at the root fails the pass.
pub(super) fn list_remote(
&self,
folder_id: i64,
folder: &NodeUid,
prefix: &str,
walk: &mut RemoteWalk<'_>,
baseline: &HashMap<String, StoredSyncEntry>,
) -> Result<Option<Listing>, PassAbort> {
let listing = Instant::now();
let step = Instant::now();
let uids = self
.rt
.block_on(self.drive.enumerate_folder_children_node_uids(folder))
.map_err(|e| format!("enumerate {folder}: {e}"));
self.trace_call(Call::ListChildren, step.elapsed());
self.trace_count(Count::RemoteFolders, 1);
let Some(uids) = unlisted_gap(walk, prefix, uids)? else {
return Ok(None);
};
let mut out = Listing::default();
if uids.is_empty() {
return Ok(Some(out));
}
let step = Instant::now();
let nodes = self
.rt
.block_on(self.drive.enumerate_nodes_light(&uids))
.map_err(|e| format!("resolve nodes: {e}"));
self.trace_call(Call::ReadNodes, step.elapsed());
let Some(nodes) = unlisted_gap(walk, prefix, nodes)? else {
return Ok(None);
};
// The SDK leaves out a node it cannot decrypt, and says so only in its
// log. Its name went with it, so all this can record is the folder.
if nodes.len() < uids.len() {
warn!(
folder = prefix,
listed = uids.len(),
read = nodes.len(),
"sync: some nodes on Drive cannot be read; leaving them out"
);
walk.gaps.short_listing(prefix);
out.short = true;
}
let nodes: Vec<Node> = nodes
.into_iter()
.filter(|node| {
let safe = pdfs_drive::remote_name_is_safe(&node.name);
if !safe {
warn!(folder = prefix, uid = %node.uid, "sync: a name on Drive cannot be a local file name; leaving it out");
}
safe
})
.collect();
// Files whose recorded mtime no longer matches: their size has to be
// read for real, so these are the only node keys worth unlocking.
let stale: Vec<NodeUid> = nodes
.iter()
.filter(|n| !n.trashed && !n.is_folder())
.filter(|n| {
unchanged_remote_size(
baseline,
&join_rel(prefix, &n.name),
n.modification_time,
pdfs_drive::node_revision_id(n).as_deref(),
)
.is_none()
})
.map(|n| n.uid.clone())
.collect();
// The full enumeration also decrypts the content digest, which the
// first sync of a path compares against the local file (B248).
let sized: HashMap<String, (i64, Option<String>)> = if stale.is_empty() {
HashMap::new()
} else {
let step = Instant::now();
let full = self
.rt
.block_on(self.drive.enumerate_nodes(&stale))
.map_err(|e| format!("resolve nodes: {e}"));
self.trace_call(Call::ReadNodesFull, step.elapsed());
self.trace_count(Count::NodesFull, stale.len());
let Some(full) = unlisted_gap(walk, prefix, full)? else {
return Ok(None);
};
full.iter()
.map(|n| {
(
n.uid.to_string(),
(remote_file_sig(n).1, pdfs_drive::node_content_sha1(n)),
)
})
.collect()
};
let stale: HashSet<String> = stale.iter().map(|u| u.to_string()).collect();
self.record_revisions(folder_id, prefix, &nodes, &sized, baseline);
self.trace_count(Count::Nodes, nodes.len());
self.engine.trace(|t| t.listing(prefix, listing.elapsed()));
for node in nodes {
if node.trashed {
continue;
}
let rel = join_rel(prefix, &node.name);
if node.is_folder() {
out.items.push((
rel,
RemoteItem {
uid: node.uid,
is_dir: true,
mtime: 0,
size: 0,
revision: None,
sha1: None,
},
));
continue;
}
let (size, sha1) = if stale.contains(&node.uid.to_string()) {
match sized.get(&node.uid.to_string()) {
Some(sized) => sized.clone(),
// Its size was needed but could not be read (the full
// enumeration skipped it as undecryptable). Leave it out
// rather than record a stale size, and say so: missing,
// it would read as deleted on Drive.
None => {
out.unread.push(rel);
continue;
}
}
} else {
match unchanged_remote_size(
baseline,
&rel,
node.modification_time,
pdfs_drive::node_revision_id(&node).as_deref(),
) {
Some(size) => (size, None),
None => continue,
}
};
out.items.push((
rel,
RemoteItem {
revision: pdfs_drive::node_revision_id(&node),
uid: node.uid,
is_dir: false,
mtime: node.modification_time,
size,
sha1,
},
));
}
Ok(Some(out))
}
}
+22 -6
View File
@@ -50,9 +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 and engine thread (`mirror`), with 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-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-cli`](../crates/pdfs-cli) | The `pdfs` binary. `pdfs daemon` runs the daemon in-process; every other command is a control-socket client |
| [`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/` |
The daemon runs as the systemd user unit `proton-drive.service`. Only the daemon holds the
@@ -468,7 +469,9 @@ both with `pdfs_core::search::relevance_score`, so the prompt can merge them int
| `pdfs-control` | Accepts control connections; at most 64 handlers |
| `pdfs-events` | Publishes status, transfer and topic changes to subscribers |
| `pdfs-sync`, `pdfs-sync-poll` | Mirror passes and the remote poll (§7) |
| Tokio runtime | Remote calls, and the Drive and photos event streams (§6) |
| `pdfs-event-sync`, `pdfs-photo-events` | Async tasks on the Tokio runtime that follow the Drive and photos event streams (§6) |
| `pdfs-gallery` | Async task. Refreshes the gallery's visibility every minute and on request |
| Tokio runtime | Remote calls |
| `pdfs-online-probe` | Probes Drive while offline |
| `pdfs-pin-keeper` | Checks pins once a second for work: every pin at startup, when the link returns and after the event feed loses continuity, and the pins a batch of remote events changed. Downloads files kept offline that are missing or stale; failures retry with a backoff of 30 s to 30 min (`docs/BUGS.md` B282) |
| `pdfs-supervisor` | Logs workers that hold one job for minutes, a queue that stops draining, and control requests that never return; samples memory; pings the systemd watchdog only after a round trip over the control socket succeeds (`WatchdogSec=120`) |
@@ -480,10 +483,21 @@ instead of leaving them behind (`docs/BUGS.md` B44). The mount starts its long-l
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
order, up to one 10-second deadline, and names any that are still running at the end.
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
tasks used to run until the runtime went away, which on a stop is when the process exits.
The sims fail a run whose stops leave a service running.
`pdfs diagnostics` reports what each worker is doing and which services are still running. The
supervisor warns once about a service that ended while the mount runs.
Work a request starts and does not wait for (a cache check, `VACUUM`, an import, a folder pin, a
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.
---
## 10. Threat model: what this client writes to disk in plaintext
@@ -732,11 +746,13 @@ The work goes in steps. Each ships the same behaviour with the simulation tests
| 5 | `pdfs-vfs`: open files, then directories and renames, behind the FUSE adapter |
| 6 | One admission policy for mirrors, reads and writeback |
Step 3 so far: the daemon's long-lived threads start and stop through one `Services` set (§9).
Step 3 so far: the daemon's long-lived threads and async loops start and stop through one
`Services` set (§9).
`Core`'s fields are grouped by owner, each group a struct in the module that owns it:
`photos::PhotoJobs`, `drain::DrainState`, `reads::ReadState`, `sizes::SizeState`,
`trash::TrashState`, `shared::SharedState`, `sharing::QuotaCache` and `sweep::SweepState`.
`Core`'s methods are split by area out of `lib.rs` into their own modules. What is left in `Core`
`Core`'s methods are split by area out of `lib.rs` into their own modules. The daemon's run loop
moved out of `pdfs-cli` into `pdfs-daemon`, which is where the services will be built. What is left in `Core`
is shared by several owners (the tree, the database, the queue's `pending` map) and needs ports
before it can move.
+7 -1
View File
@@ -17,7 +17,9 @@ kept, with a list of the folders that changed on Proton Drive since (49).
### Added
- **`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.
so once, by name, instead of saying nothing until a restart. It also lists the jobs running
in the background, such as a cache check, an import, a folder being pinned or a refresh of
the trash or the photo timeline, and how long each has run.
- **`PDFS_INSTANCE` runs a second client next to your own.** With a name set, the client keeps
its own directories, keyring entry, kernel keys and mountpoint, so a test account can run
alongside the account you use. `scripts/live-bench.py` uses it to time one edit, from the
@@ -57,6 +59,10 @@ 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
- **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
the process exited.
- **A synced folder whose folder on Drive is in the trash no longer blocks attaching another.**
Until it was removed, every `pdfs sync attach` failed with "remote sync folder is in the trash",
whatever folder it named (B299).