mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-28 20:12:14 +01:00
Compare commits
142
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1bd3d1577a | ||
|
|
8ee457cbcf | ||
|
|
d03c96e0c8 | ||
|
|
a0c51d87fb | ||
|
|
cf2632a1b5 | ||
|
|
af033f33a4 | ||
|
|
99f76ba95f | ||
|
|
bb13097604 | ||
|
|
58bbac76aa | ||
|
|
1e041150f3 | ||
|
|
61dcdf3493 | ||
|
|
e3f371eb5d | ||
|
|
bbd4784ccf | ||
|
|
d025e53933 | ||
|
|
65d17fd3a7 | ||
|
|
c747802240 | ||
|
|
d0efbcddeb | ||
|
|
e5f37d8359 | ||
|
|
79d4013b8c | ||
|
|
3a02c56440 | ||
|
|
40484bbbae | ||
|
|
6803571802 | ||
|
|
861af49d22 | ||
|
|
c5f40f63b2 | ||
|
|
7e12c747a0 | ||
|
|
8881c79f15 | ||
|
|
f975d9cf17 | ||
|
|
deb15a3327 | ||
|
|
8c7a0a8a17 | ||
|
|
9533ebcdfc | ||
|
|
ccc679eef5 | ||
|
|
20603205d9 | ||
|
|
d1421a84b1 | ||
|
|
670ec7db31 | ||
|
|
30b20fc444 | ||
|
|
5c6360e6e7 | ||
|
|
42926b71a9 | ||
|
|
21e7c03460 | ||
|
|
9b541899ef | ||
|
|
8a5f3f9ae0 | ||
|
|
d0697b7fcc | ||
|
|
f32e1b2765 | ||
|
|
b43f46e582 | ||
|
|
d3b70f1ee6 | ||
|
|
30b6d27c74 | ||
|
|
d10b28b14f | ||
|
|
c25e17fa9f | ||
|
|
6c21a58acf | ||
|
|
ea29a260b0 | ||
|
|
8e9816919d | ||
|
|
90e9c0de26 | ||
|
|
61e0eefe3a | ||
|
|
7862fc9195 | ||
|
|
1c900f47bc | ||
|
|
a9adbf96ef | ||
|
|
bcdf78c44d | ||
|
|
413be9d961 | ||
|
|
0fd8dda0d5 | ||
|
|
4f542ae4d6 | ||
|
|
fb77dbda6a | ||
|
|
ef5f832b0f | ||
|
|
91fe76dbe1 | ||
|
|
1b64c37519 | ||
|
|
e74a36c57e | ||
|
|
7e8417b135 | ||
|
|
4ff217c721 | ||
|
|
620c3fd10f | ||
|
|
6bcef1281d | ||
|
|
b9f18180fe | ||
|
|
70259b5163 | ||
|
|
c1718b13a7 | ||
|
|
acf3bd40a5 | ||
|
|
e90979eb05 | ||
|
|
d3f6f0b155 | ||
|
|
4e96ae8c61 | ||
|
|
62cc85cb06 | ||
|
|
bba74b5e65 | ||
|
|
fd0fb66448 | ||
|
|
7d963b3dd7 | ||
|
|
b7af8ae6c2 | ||
|
|
5647b8e684 | ||
|
|
b6ce90fcd5 | ||
|
|
7adcdd250f | ||
|
|
7614ed6731 | ||
|
|
006b6f6926 | ||
|
|
251655548a | ||
|
|
59c6740137 | ||
|
|
ae633c2899 | ||
|
|
d14ed56b86 | ||
|
|
a13ca95a83 | ||
|
|
7978a40224 | ||
|
|
c44c1bccb5 | ||
|
|
275f40b24b | ||
|
|
695a810cea | ||
|
|
9dbb4c9950 | ||
|
|
c5884ba638 | ||
|
|
860593b655 | ||
|
|
4dcc2aa04e | ||
|
|
d891e24e96 | ||
|
|
957a7ff391 | ||
|
|
d9881810b7 | ||
|
|
d9dab26e86 | ||
|
|
eae7ce90d2 | ||
|
|
b674f3eb71 | ||
|
|
3a4812baae | ||
|
|
3da45c0bf9 | ||
|
|
dc72991da2 | ||
|
|
bdcabed1ee | ||
|
|
7def9e903b | ||
|
|
bb376d7dc4 | ||
|
|
57e654924a | ||
|
|
e3bc64df54 | ||
|
|
47576a389e | ||
|
|
7ed07e0056 | ||
|
|
be99fffe1b | ||
|
|
96de4a8f46 | ||
|
|
97d9d671d2 | ||
|
|
45e0b60994 | ||
|
|
96248e41e2 | ||
|
|
ee2f28c5cd | ||
|
|
acc251c3d3 | ||
|
|
e855498edf | ||
|
|
54bb2fd10d | ||
|
|
c6806362ae | ||
|
|
89b3fce38d | ||
|
|
7462edc07c | ||
|
|
b9571ad045 | ||
|
|
b210485430 | ||
|
|
24f1f51c2c | ||
|
|
bbaa24e6ce | ||
|
|
cb6e0e3228 | ||
|
|
a627542c20 | ||
|
|
58fa3b5953 | ||
|
|
633e268a7b | ||
|
|
afbf88aa2d | ||
|
|
e93e2a3ef9 | ||
|
|
66c67b5a08 | ||
|
|
d32f287763 | ||
|
|
27860688ab | ||
|
|
307bbac96c | ||
|
|
191a9cfe82 | ||
|
|
04fb485e9f |
No files matched your search
@@ -17,6 +17,9 @@ jobs:
|
||||
|
||||
- name: Install native dependencies
|
||||
run: |
|
||||
# The runner image lists Microsoft's apt repository, which nothing here
|
||||
# needs and which at times answers 403 and fails the update.
|
||||
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
pkg-config \
|
||||
@@ -80,6 +83,9 @@ jobs:
|
||||
|
||||
- name: Install native dependencies
|
||||
run: |
|
||||
# The runner image lists Microsoft's apt repository, which nothing here
|
||||
# needs and which at times answers 403 and fails the update.
|
||||
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
pkg-config \
|
||||
@@ -129,6 +135,9 @@ jobs:
|
||||
|
||||
- name: Install native dependencies
|
||||
run: |
|
||||
# The runner image lists Microsoft's apt repository, which nothing here
|
||||
# needs and which at times answers 403 and fails the update.
|
||||
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
pkg-config \
|
||||
|
||||
@@ -20,6 +20,9 @@ jobs:
|
||||
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
# The runner image lists Microsoft's apt repository, which nothing here
|
||||
# needs and which at times answers 403 and fails the update.
|
||||
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
pkg-config \
|
||||
@@ -75,6 +78,9 @@ jobs:
|
||||
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
# The runner image lists Microsoft's apt repository, which nothing here
|
||||
# needs and which at times answers 403 and fails the update.
|
||||
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
pkg-config \
|
||||
|
||||
Generated
+48
-11
@@ -3634,12 +3634,13 @@ checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-cli"
|
||||
version = "3.10.0"
|
||||
version = "4.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
"clap_complete",
|
||||
"pdfs-core",
|
||||
"pdfs-daemon",
|
||||
"pdfs-fuse",
|
||||
"pdfs-store",
|
||||
"rpassword",
|
||||
@@ -3652,7 +3653,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-core"
|
||||
version = "3.10.0"
|
||||
version = "4.0.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.23.1",
|
||||
@@ -3680,9 +3681,21 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-daemon"
|
||||
version = "4.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"pdfs-core",
|
||||
"pdfs-fuse",
|
||||
"pdfs-store",
|
||||
"tokio",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-drive"
|
||||
version = "3.10.0"
|
||||
version = "4.0.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"futures",
|
||||
@@ -3697,7 +3710,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-fuse"
|
||||
version = "3.10.0"
|
||||
version = "4.0.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.23.1",
|
||||
@@ -3714,8 +3727,10 @@ dependencies = [
|
||||
"parking_lot 0.13.0",
|
||||
"pdfs-core",
|
||||
"pdfs-drive",
|
||||
"pdfs-sched",
|
||||
"pdfs-store",
|
||||
"pdfs-sync",
|
||||
"pdfs-vfs",
|
||||
"proton-drive-rs",
|
||||
"proton-gallery-app-rs",
|
||||
"proton-gallery-rs",
|
||||
@@ -3733,7 +3748,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-gui"
|
||||
version = "3.10.0"
|
||||
version = "4.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-channel",
|
||||
@@ -3756,9 +3771,17 @@ dependencies = [
|
||||
"webkit6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-sched"
|
||||
version = "4.0.0"
|
||||
dependencies = [
|
||||
"parking_lot 0.13.0",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-store"
|
||||
version = "3.10.0"
|
||||
version = "4.0.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"parking_lot 0.13.0",
|
||||
@@ -3774,12 +3797,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-sync"
|
||||
version = "3.10.0"
|
||||
version = "4.0.0"
|
||||
dependencies = [
|
||||
"notify",
|
||||
"parking_lot 0.13.0",
|
||||
"pdfs-core",
|
||||
"pdfs-drive",
|
||||
"pdfs-sched",
|
||||
"pdfs-store",
|
||||
"proton-drive-rs",
|
||||
"sha1 0.11.0",
|
||||
@@ -3787,6 +3811,19 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-vfs"
|
||||
version = "4.0.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"parking_lot 0.13.0",
|
||||
"pdfs-core",
|
||||
"pdfs-drive",
|
||||
"pdfs-store",
|
||||
"proton-drive-rs",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pem-rfc7468"
|
||||
version = "0.7.0"
|
||||
@@ -4034,9 +4071,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "proton-drive-rs"
|
||||
version = "0.12.6"
|
||||
version = "0.12.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b1a71d0e737a9bd6cff07105218e7bef3bddcfd9d6651646d7302cdbba71961"
|
||||
checksum = "11c09c245784d7253072b751e43b1919140fdbc8641c5328a7e2801889c86041"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.23.1",
|
||||
@@ -4154,9 +4191,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "proton-sdk"
|
||||
version = "0.12.6"
|
||||
version = "0.12.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "81edef2b4b174e936a3537793ee901b92dd7c0484eb7fed09ad69432f407f86b"
|
||||
checksum = "7a6ed261fbcabf35abe67ebf8c8aff85b01fc43aef5b298380a6e6f7d3dd31d3"
|
||||
dependencies = [
|
||||
"aes-gcm 0.11.1",
|
||||
"async-trait",
|
||||
|
||||
+7
-4
@@ -1,9 +1,9 @@
|
||||
[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-sched", "crates/pdfs-vfs", "crates/pdfs-fuse", "crates/pdfs-daemon", "crates/pdfs-cli", "crates/pdfs-gui"]
|
||||
|
||||
[workspace.package]
|
||||
version = "3.10.0"
|
||||
version = "4.0.0"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
authors = ["Nils Pukropp <contact@narl.io>"]
|
||||
@@ -15,8 +15,8 @@ keywords = ["proton", "drive", "fuse", "sync", "linux"]
|
||||
categories = ["filesystem", "command-line-utilities"]
|
||||
|
||||
[workspace.dependencies]
|
||||
proton-sdk = { version = "0.12.6" }
|
||||
proton-drive-rs = { version = "0.12.6" }
|
||||
proton-sdk = { version = "0.12.8" }
|
||||
proton-drive-rs = { version = "0.12.8" }
|
||||
proton-gallery-app-rs = "0.1.0"
|
||||
proton-gallery-rs = "0.1.5"
|
||||
proton-map-rs = "0.1.0"
|
||||
@@ -27,7 +27,10 @@ pdfs-core = { path = "crates/pdfs-core" }
|
||||
pdfs-store = { path = "crates/pdfs-store" }
|
||||
pdfs-drive = { path = "crates/pdfs-drive" }
|
||||
pdfs-sync = { path = "crates/pdfs-sync" }
|
||||
pdfs-vfs = { path = "crates/pdfs-vfs" }
|
||||
pdfs-sched = { path = "crates/pdfs-sched" }
|
||||
pdfs-fuse = { path = "crates/pdfs-fuse" }
|
||||
pdfs-daemon = { path = "crates/pdfs-daemon" }
|
||||
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "fs", "io-util", "time", "signal"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
+16
-3712
File diff suppressed because it is too large.
Load diff
@@ -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(())
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -0,0 +1,622 @@
|
||||
//! 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
|
||||
}
|
||||
|
||||
/// One class of background step in `pdfs diagnostics`: `mirror: 8 running,
|
||||
/// 3 waiting (oldest 2s); 120 admitted, waited 14s in total, 950ms at most`.
|
||||
pub(super) fn admission_line(load: &pdfs_core::control::AdmissionLoad) -> String {
|
||||
let mut line = format!(
|
||||
"{}: {} running, {} waiting",
|
||||
load.class, load.running, load.waiting
|
||||
);
|
||||
if let Some(ms) = load.oldest_wait_ms {
|
||||
line.push_str(&format!(" (oldest {})", wait_ms(ms)));
|
||||
}
|
||||
line.push_str(&format!(
|
||||
"; {} admitted, waited {} in total, {} at most",
|
||||
load.admitted,
|
||||
wait_ms(load.waited_ms),
|
||||
wait_ms(load.longest_wait_ms),
|
||||
));
|
||||
line
|
||||
}
|
||||
|
||||
/// One mirror effect not settled yet in `pdfs diagnostics`:
|
||||
/// `folder 3 upload docs/a.txt: retry, sent 2 times, 5m0s ago (timed out)`.
|
||||
pub(super) fn effect_line(intent: &pdfs_core::control::EffectIntent) -> String {
|
||||
let times = if intent.attempts == 1 {
|
||||
"time"
|
||||
} else {
|
||||
"times"
|
||||
};
|
||||
let mut line = format!(
|
||||
"folder {} {} {}: {}, sent {} {times}, {} ago",
|
||||
intent.folder_id,
|
||||
intent.kind,
|
||||
intent.rel_path,
|
||||
intent.state,
|
||||
intent.attempts,
|
||||
human_secs(intent.age_secs),
|
||||
);
|
||||
if let Some(error) = &intent.last_error {
|
||||
line.push_str(&format!(" ({error})"));
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
/// A wait, in ms below a second, where most admission waits fall.
|
||||
fn wait_ms(ms: u64) -> String {
|
||||
if ms < 1000 {
|
||||
format!("{ms}ms")
|
||||
} else {
|
||||
human_secs(ms / 1000)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn cmd_diagnostics() -> Result<()> {
|
||||
let response = control_request(CtlRequest::Diagnostics)?;
|
||||
if emit_json(&response)? {
|
||||
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.admission.is_empty() {
|
||||
println!("admission of background steps:");
|
||||
for load in &d.admission {
|
||||
println!(" {}", admission_line(load));
|
||||
}
|
||||
}
|
||||
if !d.drive_calls.is_empty() {
|
||||
println!("calls to Drive since start:");
|
||||
for call in &d.drive_calls {
|
||||
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.upload_paths.iter().any(|stat| stat.count > 0) {
|
||||
println!("uploads since start, by path:");
|
||||
for stat in &d.upload_paths {
|
||||
println!(
|
||||
" {:<38} {:>7} files {:>5} failed {:>9} ms total {:>7} ms longest",
|
||||
stat.path, stat.count, stat.errors, stat.total_ms, stat.longest_ms,
|
||||
);
|
||||
}
|
||||
}
|
||||
match &d.effects {
|
||||
None => {}
|
||||
Some(effects) if effects.count == 0 => println!("sync effects not settled: none"),
|
||||
Some(effects) => {
|
||||
println!("sync effects not settled: {} (oldest first)", effects.count);
|
||||
for intent in &effects.oldest {
|
||||
println!(" {}", effect_line(intent));
|
||||
}
|
||||
if effects.count > effects.oldest.len() {
|
||||
println!(" and {} more", effects.count - effects.oldest.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
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:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pdfs_core::control::{AdmissionLoad, EffectIntent};
|
||||
|
||||
use super::{admission_line, effect_line};
|
||||
|
||||
#[test]
|
||||
fn an_effect_line_says_what_waits_and_why() {
|
||||
let intent = EffectIntent {
|
||||
folder_id: 3,
|
||||
rel_path: "docs/a.txt".into(),
|
||||
kind: "upload".into(),
|
||||
state: "retry".into(),
|
||||
attempts: 2,
|
||||
age_secs: 300,
|
||||
last_error: Some("timed out".into()),
|
||||
};
|
||||
assert_eq!(
|
||||
effect_line(&intent),
|
||||
"folder 3 upload docs/a.txt: retry, sent 2 times, 5m0s ago (timed out)"
|
||||
);
|
||||
let sent = EffectIntent {
|
||||
state: "issued".into(),
|
||||
attempts: 1,
|
||||
last_error: None,
|
||||
..intent
|
||||
};
|
||||
assert_eq!(
|
||||
effect_line(&sent),
|
||||
"folder 3 upload docs/a.txt: issued, sent 1 time, 5m0s ago"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_admission_line_says_who_waits_and_for_how_long() {
|
||||
let load = AdmissionLoad {
|
||||
class: "mirror".into(),
|
||||
running: 8,
|
||||
waiting: 3,
|
||||
oldest_wait_ms: Some(2_400),
|
||||
admitted: 120,
|
||||
waited_ms: 14_000,
|
||||
longest_wait_ms: 950,
|
||||
};
|
||||
assert_eq!(
|
||||
admission_line(&load),
|
||||
"mirror: 8 running, 3 waiting (oldest 2s); 120 admitted, waited 14s in total, 950ms at most"
|
||||
);
|
||||
let idle = AdmissionLoad {
|
||||
oldest_wait_ms: None,
|
||||
waiting: 0,
|
||||
running: 0,
|
||||
..load
|
||||
};
|
||||
assert_eq!(
|
||||
admission_line(&idle),
|
||||
"mirror: 0 running, 0 waiting; 120 admitted, waited 14s in total, 950ms at most"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -38,7 +38,6 @@ use proton_sdk::error::ProtonError;
|
||||
use proton_sdk::http::Tokens;
|
||||
use proton_sdk::login::{self, LoginError, Step};
|
||||
use proton_sdk::session::{PasswordMode, ProtonApiSession, ResumeParameters};
|
||||
use proton_sdk::telemetry::TracingTelemetry;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
@@ -771,7 +770,7 @@ async fn migrate_legacy(
|
||||
/// default.
|
||||
fn tune(client: ProtonDriveClient, passphrases: &KeyPassphrases) -> ProtonDriveClient {
|
||||
let client = client
|
||||
.with_telemetry(TracingTelemetry::shared())
|
||||
.with_telemetry(crate::uploads::telemetry())
|
||||
.with_small_file_upload(true);
|
||||
match AppDirs::new().and_then(|dirs| crate::sdkcache::SdkCache::shared(&dirs)) {
|
||||
Ok(cache) => {
|
||||
|
||||
@@ -278,6 +278,12 @@ pub struct AppConfig {
|
||||
/// the field.
|
||||
#[serde(default)]
|
||||
pub local_first: Option<bool>,
|
||||
/// Send a file small enough, with its thumbnails, to fit 128 KiB in one
|
||||
/// request instead of three or more. `None` means on. `false` uploads
|
||||
/// every file in blocks, the way all files went before. Defaulted for
|
||||
/// configs predating the field.
|
||||
#[serde(default)]
|
||||
pub small_uploads: Option<bool>,
|
||||
/// Ask GitHub once a day whether a newer release is out, and say so in the
|
||||
/// desktop app. Off by default: GitHub then sees the address and version
|
||||
/// asking. Never used where a package manager installs updates (see
|
||||
@@ -1077,6 +1083,7 @@ mod tests {
|
||||
language: Some("de".to_string()),
|
||||
online_map: true,
|
||||
local_first: Some(false),
|
||||
small_uploads: Some(false),
|
||||
update_check: true,
|
||||
update_last_checked: Some(1_760_000_000),
|
||||
update_latest: Some("3.6.0".to_string()),
|
||||
@@ -1096,6 +1103,7 @@ mod tests {
|
||||
assert_eq!(decoded.update_latest.as_deref(), Some("3.6.0"));
|
||||
assert_eq!(decoded.language.as_deref(), Some("de"));
|
||||
assert_eq!(decoded.upload_limit, Some(500_000));
|
||||
assert_eq!(decoded.small_uploads, Some(false));
|
||||
assert_eq!(decoded.download_limit, None);
|
||||
assert_eq!(decoded.files_view, config.files_view);
|
||||
assert_eq!(decoded.photos_view, config.photos_view);
|
||||
|
||||
@@ -1171,6 +1171,15 @@ pub struct PendingOpInfo {
|
||||
/// Carries file content that [`Request::ExportPendingOp`] can save.
|
||||
#[serde(default)]
|
||||
pub exportable: bool,
|
||||
/// The node the op changes. A discard drops every op queued on the same
|
||||
/// node (see [`Request::DiscardPendingOp`]), so this tells which rows go
|
||||
/// together. Empty from a daemon that predates the field.
|
||||
#[serde(default)]
|
||||
pub node: String,
|
||||
/// The node was made on this computer and Drive has never had it. A
|
||||
/// discard removes it here, rather than putting back what Drive has.
|
||||
#[serde(default)]
|
||||
pub local_only: bool,
|
||||
}
|
||||
|
||||
/// Why Drive refused a queued change (in [`PendingOpInfo`]). The change stays
|
||||
@@ -2374,13 +2383,83 @@ pub struct Diagnostics {
|
||||
/// field.
|
||||
#[serde(default)]
|
||||
pub drive_calls: Vec<DriveCallStat>,
|
||||
/// Uploads since start, by how the SDK sent their content: `small` in one
|
||||
/// request, `blocks` as a draft, its blocks and a commit. Empty from a
|
||||
/// daemon that predates the field.
|
||||
#[serde(default)]
|
||||
pub upload_paths: Vec<UploadPathStat>,
|
||||
/// The daemon's long-lived threads, in start order, and whether each is
|
||||
/// 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>,
|
||||
/// What the admission of background work is doing, per class of step.
|
||||
/// Empty from a daemon that predates the field.
|
||||
#[serde(default)]
|
||||
pub admission: Vec<AdmissionLoad>,
|
||||
/// The mirror effects not settled yet: sent and waiting for an answer,
|
||||
/// left unsure by a stop, or failed. `None` when the database did not
|
||||
/// answer in time, or from a daemon that predates the field.
|
||||
#[serde(default)]
|
||||
pub effects: Option<EffectReport>,
|
||||
}
|
||||
|
||||
/// One long-lived daemon thread, in [`Diagnostics::services`].
|
||||
/// The mirror effects not settled yet, in [`Diagnostics::effects`].
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct EffectReport {
|
||||
/// How many there are.
|
||||
pub count: usize,
|
||||
/// The oldest of them, at most [`EffectReport::SHOWN`].
|
||||
pub oldest: Vec<EffectIntent>,
|
||||
}
|
||||
|
||||
impl EffectReport {
|
||||
/// How many effects a report lists.
|
||||
pub const SHOWN: usize = 20;
|
||||
}
|
||||
|
||||
/// One mirror effect not settled yet, in [`EffectReport::oldest`].
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct EffectIntent {
|
||||
pub folder_id: i64,
|
||||
pub rel_path: String,
|
||||
/// What it does, such as `upload`, `download` or `trash`.
|
||||
pub kind: String,
|
||||
/// `issued`, `unsure`, `retry` or `blocked`.
|
||||
pub state: String,
|
||||
/// How many times it was sent.
|
||||
pub attempts: u32,
|
||||
/// How long ago it was last sent.
|
||||
pub age_secs: u64,
|
||||
pub last_error: Option<String>,
|
||||
}
|
||||
|
||||
/// One class of background step in the daemon's admission, in
|
||||
/// [`Diagnostics::admission`]. Steps waiting here have not reached the
|
||||
/// network yet, so a stall with steps waiting and none running is in the
|
||||
/// daemon, not at Proton.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct AdmissionLoad {
|
||||
/// The class of step, such as `mirror`.
|
||||
pub class: String,
|
||||
/// Steps admitted and still running.
|
||||
pub running: usize,
|
||||
/// Steps waiting to be admitted.
|
||||
pub waiting: usize,
|
||||
/// How long the step that has waited longest has waited so far, in ms.
|
||||
pub oldest_wait_ms: Option<u64>,
|
||||
/// Steps admitted since start.
|
||||
pub admitted: u64,
|
||||
/// The time those steps spent waiting, in total and at most, in ms.
|
||||
pub waited_ms: u64,
|
||||
pub longest_wait_ms: u64,
|
||||
}
|
||||
|
||||
/// One long-lived daemon thread, in [`Diagnostics::services`], or one
|
||||
/// 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`.
|
||||
@@ -2403,6 +2482,17 @@ pub struct DriveCallStat {
|
||||
pub longest_ms: u64,
|
||||
}
|
||||
|
||||
/// Uploads that took one path, in [`Diagnostics::upload_paths`].
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct UploadPathStat {
|
||||
/// `small` or `blocks`.
|
||||
pub path: String,
|
||||
pub count: u64,
|
||||
pub errors: u64,
|
||||
pub total_ms: u64,
|
||||
pub longest_ms: u64,
|
||||
}
|
||||
|
||||
/// What the folder-sync engine is doing, for [`Diagnostics`].
|
||||
///
|
||||
/// The engine is one thread that runs every synced folder's passes in turn.
|
||||
|
||||
@@ -30,6 +30,7 @@ pub mod timestamp;
|
||||
pub mod transfers;
|
||||
pub mod tray;
|
||||
pub mod update;
|
||||
pub mod uploads;
|
||||
|
||||
// Photo logic shared with Proton Gallery through the proton-rs crates.
|
||||
pub use proton_gallery_rs::{exiftime, places, similar, takeout};
|
||||
|
||||
@@ -12,9 +12,23 @@
|
||||
//! 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. A stop closes the
|
||||
//! board to new jobs, aborts the async ones and joins the rest up to the same
|
||||
//! deadline as the services. A job used to be left running, and one still
|
||||
//! waiting on Drive when the runtime went away panicked on its next timer.
|
||||
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -25,6 +39,32 @@ use crate::shutdown::Shutdown;
|
||||
/// Wakes a thread that blocks somewhere a [`Shutdown::stop`] alone does not reach.
|
||||
pub type Wake = Box<dyn Fn() + Send + Sync>;
|
||||
|
||||
/// A long-lived loop a mount runs on a thread of its own.
|
||||
///
|
||||
/// Each one says in one place what it is called, how a stop reaches it and
|
||||
/// whether the mount can do without it, next to the loop itself. The mount
|
||||
/// starts a list of them with [`Services::start`] instead of spelling out
|
||||
/// each spawn, wake and failure path.
|
||||
pub trait Service: Send + 'static {
|
||||
/// The thread's name, such as `pdfs-sync`.
|
||||
fn name(&self) -> String;
|
||||
|
||||
/// Whether a mount fails when this cannot start. An optional service is
|
||||
/// logged and skipped: the mount works without it, only less well.
|
||||
fn required(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The call that wakes the loop on a stop, for one that blocks where the
|
||||
/// [`Shutdown`] signal does not reach: a condvar, a channel, an `accept`.
|
||||
fn wake(&self) -> Option<Wake> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Run the loop until the [`Shutdown`] signal or the wake ends it.
|
||||
fn run(self: Box<Self>);
|
||||
}
|
||||
|
||||
/// Whether one service thread is still running, for diagnostics.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ServiceHealth {
|
||||
@@ -35,10 +75,40 @@ 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,
|
||||
/// The running jobs' handles, and whether a stop closed the board. One
|
||||
/// lock for both, so a job is either refused or joined by the stop.
|
||||
handles: Mutex<JobHandles>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct JobHandles {
|
||||
closed: bool,
|
||||
running: Vec<Handle>,
|
||||
}
|
||||
|
||||
impl JobHandles {
|
||||
/// Keep `handle`, dropping the handles of jobs that already ended.
|
||||
fn keep(&mut self, handle: Handle) {
|
||||
self.running.retain(|handle| !handle.is_finished());
|
||||
self.running.push(handle);
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a job did not start: the board's mount is stopping.
|
||||
fn closed_error() -> std::io::Error {
|
||||
std::io::Error::other("the mount is stopping; no new jobs start")
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
name: String,
|
||||
@@ -46,10 +116,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 +137,107 @@ 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.
|
||||
///
|
||||
/// A stop joins it up to its deadline; a job that may run long checks the
|
||||
/// [`Shutdown`] signal. Once a stop has begun, no job starts and this
|
||||
/// returns an error.
|
||||
pub fn spawn_job<F>(&self, name: &str, run: F) -> std::io::Result<()>
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
{
|
||||
let mut handles = self.0.handles.lock();
|
||||
if handles.closed {
|
||||
return Err(closed_error());
|
||||
}
|
||||
let guard = self.add_job(name);
|
||||
let handle = std::thread::Builder::new()
|
||||
.name(name.to_owned())
|
||||
.spawn(move || {
|
||||
let _guard = guard;
|
||||
run();
|
||||
})?;
|
||||
// On an error the closure, and the guard in it, are already dropped,
|
||||
// so the job is off the list.
|
||||
handles.keep(Handle::Thread(handle));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start `task` on `rt` as a one-shot job, like [`spawn_job`](Self::spawn_job)
|
||||
/// for work that is async: a refresh a listing starts and does not wait
|
||||
/// for. It shows in [`jobs`](Self::jobs) until it ends, by return, panic
|
||||
/// or abort. A stop aborts it at its next `.await`; once a stop has begun,
|
||||
/// `task` is dropped without running.
|
||||
pub fn spawn_task_job<F>(&self, rt: &tokio::runtime::Handle, name: &str, task: F)
|
||||
where
|
||||
F: Future<Output = ()> + Send + 'static,
|
||||
{
|
||||
let mut handles = self.0.handles.lock();
|
||||
if handles.closed {
|
||||
tracing::debug!(job = name, "not started: the mount is stopping");
|
||||
return;
|
||||
}
|
||||
let guard = self.add_job(name);
|
||||
let task = rt.spawn(async move {
|
||||
let _guard = guard;
|
||||
task.await;
|
||||
});
|
||||
handles.keep(Handle::Task {
|
||||
name: name.to_owned(),
|
||||
task,
|
||||
});
|
||||
}
|
||||
|
||||
/// Close the board to new jobs and abort the async ones. The thread jobs
|
||||
/// still running are handed back for [`join`](Handle::join_until).
|
||||
fn close(&self) -> Vec<Handle> {
|
||||
let running = {
|
||||
let mut handles = self.0.handles.lock();
|
||||
handles.closed = true;
|
||||
std::mem::take(&mut handles.running)
|
||||
};
|
||||
for handle in &running {
|
||||
if let Handle::Task { task, .. } = handle {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
running
|
||||
}
|
||||
|
||||
fn add_job(&self, name: &str) -> JobGuard {
|
||||
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 +246,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>);
|
||||
|
||||
@@ -80,15 +267,46 @@ impl Drop for Running {
|
||||
}
|
||||
}
|
||||
|
||||
struct Service {
|
||||
handle: JoinHandle<()>,
|
||||
struct Started {
|
||||
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(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for the thread or task to end, up to `deadline`, and name it if
|
||||
/// it is still running then.
|
||||
fn join_until(self, deadline: Instant) -> Option<String> {
|
||||
while !self.is_finished() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
match self {
|
||||
Handle::Thread(handle) => join_until([handle], deadline).pop(),
|
||||
Handle::Task { name, task } if !task.is_finished() => Some(name),
|
||||
Handle::Task { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The service threads one mount started, and how to stop them.
|
||||
pub struct Services {
|
||||
board: ServiceBoard,
|
||||
started: Vec<Service>,
|
||||
started: Vec<Started>,
|
||||
}
|
||||
|
||||
impl Services {
|
||||
@@ -117,7 +335,10 @@ impl Services {
|
||||
});
|
||||
match spawned {
|
||||
Ok(handle) => {
|
||||
self.started.push(Service { handle, wake });
|
||||
self.started.push(Started {
|
||||
handle: Handle::Thread(handle),
|
||||
wake,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => {
|
||||
@@ -128,31 +349,77 @@ impl Services {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many threads were started.
|
||||
/// Start `service` on a thread of its own. A required service that cannot
|
||||
/// start returns the error; an optional one is logged and skipped.
|
||||
pub fn start(&mut self, service: Box<dyn Service>) -> std::io::Result<()> {
|
||||
let name = service.name();
|
||||
let required = service.required();
|
||||
let wake = service.wake();
|
||||
match self.spawn(&name, wake, move || service.run()) {
|
||||
Err(error) if !required => {
|
||||
tracing::warn!(service = name, %error, "optional service did not start");
|
||||
Ok(())
|
||||
}
|
||||
started => started,
|
||||
}
|
||||
}
|
||||
|
||||
/// Start `task` on `rt` as a service named `name`. [`stop`](Self::stop)
|
||||
/// aborts it, so it ends at its next `.await`; a task does not need to
|
||||
/// watch the [`Shutdown`] signal itself. Code between two `.await`s runs
|
||||
/// 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(Started {
|
||||
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 and every job: signal `shutdown`, close the board
|
||||
/// to new jobs, wake each thread and abort each task in reverse start
|
||||
/// order. Then join the jobs, which are the services' clients, and the
|
||||
/// services in the same reverse order, all until `deadline`. Returns the
|
||||
/// names of the services and jobs still running at the deadline; they are
|
||||
/// left behind rather than waited for.
|
||||
pub fn stop(self, shutdown: &Shutdown, deadline: Instant) -> Vec<String> {
|
||||
shutdown.stop();
|
||||
let jobs = self.board.close();
|
||||
for service in self.started.iter().rev() {
|
||||
if let Some(wake) = &service.wake {
|
||||
wake();
|
||||
}
|
||||
if let Handle::Task { task, .. } = &service.handle {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
join_until(
|
||||
self.started.into_iter().rev().map(|service| service.handle),
|
||||
deadline,
|
||||
)
|
||||
let jobs = jobs.into_iter().filter_map(|job| job.join_until(deadline));
|
||||
let services = self
|
||||
.started
|
||||
.into_iter()
|
||||
.rev()
|
||||
.filter_map(|service| service.handle.join_until(deadline));
|
||||
jobs.chain(services).collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,4 +527,215 @@ 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());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stop_joins_the_running_jobs_and_names_a_stuck_one() {
|
||||
let board = ServiceBoard::default();
|
||||
let shutdown = Arc::new(Shutdown::default());
|
||||
let services = Services::new(board.clone());
|
||||
let signalled = shutdown.clone();
|
||||
board
|
||||
.spawn_job("pdfs-test-polite", move || {
|
||||
while signalled.sleep(Duration::from_secs(3600)) {}
|
||||
})
|
||||
.unwrap();
|
||||
let (_hold, stuck) = mpsc::channel::<()>();
|
||||
board
|
||||
.spawn_job("pdfs-test-stuck", move || {
|
||||
let _ = stuck.recv();
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let left = services.stop(&shutdown, Instant::now() + Duration::from_millis(300));
|
||||
|
||||
assert_eq!(left, ["pdfs-test-stuck"]);
|
||||
let jobs: Vec<_> = board.jobs().into_iter().map(|job| job.name).collect();
|
||||
assert_eq!(jobs, ["pdfs-test-stuck"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stop_aborts_a_task_job_and_refuses_new_jobs() {
|
||||
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(1)
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let board = ServiceBoard::default();
|
||||
let services = Services::new(board.clone());
|
||||
board.spawn_task_job(rt.handle(), "pdfs-test-poller", async {
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
});
|
||||
|
||||
let left = services.stop(
|
||||
&Shutdown::default(),
|
||||
Instant::now() + Duration::from_secs(5),
|
||||
);
|
||||
|
||||
assert!(left.is_empty(), "still running: {left:?}");
|
||||
assert!(board.jobs().is_empty());
|
||||
assert!(board.spawn_job("pdfs-test-late", || {}).is_err());
|
||||
board.spawn_task_job(rt.handle(), "pdfs-test-late", async {});
|
||||
assert!(board.jobs().is_empty(), "a job started after the stop");
|
||||
}
|
||||
|
||||
struct Waiter {
|
||||
name: &'static str,
|
||||
rx: mpsc::Receiver<()>,
|
||||
tx: mpsc::Sender<()>,
|
||||
}
|
||||
|
||||
impl Service for Waiter {
|
||||
fn name(&self) -> String {
|
||||
self.name.to_owned()
|
||||
}
|
||||
|
||||
fn wake(&self) -> Option<Wake> {
|
||||
let tx = self.tx.clone();
|
||||
Some(Box::new(move || {
|
||||
let _ = tx.send(());
|
||||
}))
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
let _ = self.rx.recv();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_started_service_is_woken_and_joined_by_a_stop() {
|
||||
let board = ServiceBoard::default();
|
||||
let mut services = Services::new(board.clone());
|
||||
let (tx, rx) = mpsc::channel();
|
||||
services
|
||||
.start(Box::new(Waiter {
|
||||
name: "pdfs-test-waiter",
|
||||
rx,
|
||||
tx,
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(board.health()[0].name, "pdfs-test-waiter");
|
||||
|
||||
let left = services.stop(
|
||||
&Shutdown::default(),
|
||||
Instant::now() + Duration::from_secs(5),
|
||||
);
|
||||
|
||||
assert!(left.is_empty(), "still running: {left:?}");
|
||||
assert!(!board.health()[0].running);
|
||||
}
|
||||
}
|
||||
@@ -139,6 +139,11 @@ pub struct PromptConfig {
|
||||
/// false for a launcher that advertises support but is themed without them.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub menu_icons: Option<bool>,
|
||||
/// Remember what the search window opens, to list it before a search and
|
||||
/// rank it higher in one. Defaults to true. Off, the history is cleared
|
||||
/// the next time the window opens and nothing more is kept.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub remember_recent: Option<bool>,
|
||||
}
|
||||
|
||||
/// Which front end the prompt presents.
|
||||
@@ -158,6 +163,11 @@ pub enum PromptMode {
|
||||
/// than the GTK prompt's cap because filtering happens launcher-side.
|
||||
pub const DEFAULT_MENU_LIMIT: usize = 50;
|
||||
|
||||
/// The search window's history of what it opened, in the state directory.
|
||||
/// The app deletes it to clear the list; the window reads it again each time
|
||||
/// it opens.
|
||||
pub const PROMPT_HISTORY_FILE: &str = "prompt-history.json";
|
||||
|
||||
impl PromptConfig {
|
||||
pub fn resolved_mode(&self) -> PromptMode {
|
||||
self.mode.unwrap_or_default()
|
||||
@@ -170,6 +180,10 @@ impl PromptConfig {
|
||||
pub fn resolved_menu_icons(&self) -> bool {
|
||||
self.menu_icons.unwrap_or(true)
|
||||
}
|
||||
|
||||
pub fn resolved_remember_recent(&self) -> bool {
|
||||
self.remember_recent.unwrap_or(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// One line offered to the launcher.
|
||||
|
||||
@@ -363,6 +363,19 @@ pub enum Verdict {
|
||||
/// Compiled ignore rules for one synced folder.
|
||||
pub struct IgnoreRules {
|
||||
matcher: Option<Gitignore>,
|
||||
/// A hash of the patterns the rules were built from, so a caller can tell
|
||||
/// whether they changed.
|
||||
source: u64,
|
||||
}
|
||||
|
||||
/// A hash of `globals` and the folder's ignore file, `file` (its name and
|
||||
/// text), in the order [`IgnoreRules::load`] reads them.
|
||||
fn rules_source(globals: &[String], file: Option<(&str, &[u8])>) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
globals.hash(&mut hasher);
|
||||
file.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
impl IgnoreRules {
|
||||
@@ -382,6 +395,7 @@ impl IgnoreRules {
|
||||
}
|
||||
}
|
||||
|
||||
let mut file = None;
|
||||
for name in IGNORE_FILE_NAMES {
|
||||
let path = root.join(name);
|
||||
if !path.is_file() {
|
||||
@@ -390,15 +404,24 @@ impl IgnoreRules {
|
||||
// `add` returns the first parse error but still takes the lines it
|
||||
// could read, so a bad line costs that line and nothing more.
|
||||
let _ = builder.add(&path);
|
||||
file = Some((*name, std::fs::read(&path).unwrap_or_default()));
|
||||
any = true;
|
||||
break;
|
||||
}
|
||||
let source = rules_source(
|
||||
globals,
|
||||
file.as_ref().map(|(name, text)| (*name, text.as_slice())),
|
||||
);
|
||||
|
||||
if !any {
|
||||
return Self { matcher: None };
|
||||
return Self {
|
||||
matcher: None,
|
||||
source,
|
||||
};
|
||||
}
|
||||
Self {
|
||||
matcher: builder.build().ok(),
|
||||
source,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -415,17 +438,32 @@ impl IgnoreRules {
|
||||
for line in text.lines() {
|
||||
any |= builder.add_line(Some(file.clone()), line).is_ok();
|
||||
}
|
||||
let source = rules_source(globals, Some((IGNORE_FILE_NAMES[0], text.as_bytes())));
|
||||
if !any {
|
||||
return Self { matcher: None };
|
||||
return Self {
|
||||
matcher: None,
|
||||
source,
|
||||
};
|
||||
}
|
||||
Self {
|
||||
matcher: builder.build().ok(),
|
||||
source,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rules matching nothing, for callers with no folder context.
|
||||
pub fn empty() -> Self {
|
||||
Self { matcher: None }
|
||||
Self {
|
||||
matcher: None,
|
||||
source: rules_source(&[], None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifies the patterns these rules were built from: rules loaded
|
||||
/// again from the same globals and the same ignore file give the same
|
||||
/// value. Only for comparing within one run of the daemon.
|
||||
pub fn source(&self) -> u64 {
|
||||
self.source
|
||||
}
|
||||
|
||||
/// Whether any rule is loaded. When false, [`is_ignored`](Self::is_ignored)
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
//! How the SDK sent each upload's content, counted from its telemetry.
|
||||
//!
|
||||
//! A file whose encrypted size is under 128 KiB goes up in one request
|
||||
//! (`small`). Any other file goes up as a draft, its blocks and a commit
|
||||
//! (`blocks`). The SDK picks the path inside each upload call and reports it
|
||||
//! only as the `backend` attribute of the `upload_file` and
|
||||
//! `upload_new_revision` timers, so this module counts those events. If the
|
||||
//! share of small uploads drops to zero for small files, the one-request path
|
||||
//! is off or the server refuses it, and `pdfs diagnostics` shows that.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use proton_sdk::telemetry::{Outcome, Telemetry, TelemetryEvent, TracingTelemetry};
|
||||
|
||||
/// The counts of every upload of this process, by path.
|
||||
pub static UPLOAD_PATHS: UploadPaths = UploadPaths::new();
|
||||
|
||||
/// Upload counts for each path.
|
||||
#[derive(Debug)]
|
||||
pub struct UploadPaths {
|
||||
small: PathStat,
|
||||
blocks: PathStat,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PathStat {
|
||||
count: AtomicU64,
|
||||
errors: AtomicU64,
|
||||
total_ms: AtomicU64,
|
||||
longest_ms: AtomicU64,
|
||||
}
|
||||
|
||||
/// One path's counts at one moment.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UploadPathStat {
|
||||
/// `small` or `blocks`.
|
||||
pub path: &'static str,
|
||||
pub count: u64,
|
||||
pub errors: u64,
|
||||
pub total_ms: u64,
|
||||
pub longest_ms: u64,
|
||||
}
|
||||
|
||||
impl PathStat {
|
||||
const fn new() -> Self {
|
||||
Self {
|
||||
count: AtomicU64::new(0),
|
||||
errors: AtomicU64::new(0),
|
||||
total_ms: AtomicU64::new(0),
|
||||
longest_ms: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
fn add(&self, failed: bool, took: Duration) {
|
||||
let ms = u64::try_from(took.as_millis()).unwrap_or(u64::MAX);
|
||||
self.count.fetch_add(1, Ordering::Relaxed);
|
||||
if failed {
|
||||
self.errors.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
self.total_ms.fetch_add(ms, Ordering::Relaxed);
|
||||
self.longest_ms.fetch_max(ms, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn snapshot(&self, path: &'static str) -> UploadPathStat {
|
||||
UploadPathStat {
|
||||
path,
|
||||
count: self.count.load(Ordering::Relaxed),
|
||||
errors: self.errors.load(Ordering::Relaxed),
|
||||
total_ms: self.total_ms.load(Ordering::Relaxed),
|
||||
longest_ms: self.longest_ms.load(Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for UploadPaths {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl UploadPaths {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
small: PathStat::new(),
|
||||
blocks: PathStat::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Count `event` if it is the end of an upload.
|
||||
pub fn record(&self, event: &TelemetryEvent) {
|
||||
if !matches!(event.operation, "upload_file" | "upload_new_revision") {
|
||||
return;
|
||||
}
|
||||
let backend = event
|
||||
.attributes
|
||||
.iter()
|
||||
.find_map(|(key, value)| (*key == "backend").then_some(value.as_str()));
|
||||
let stat = match backend {
|
||||
Some("small") => &self.small,
|
||||
Some("blocks") => &self.blocks,
|
||||
_ => return,
|
||||
};
|
||||
stat.add(event.outcome == Outcome::Failure, event.duration);
|
||||
}
|
||||
|
||||
/// The counts so far, small first.
|
||||
pub fn snapshot(&self) -> [UploadPathStat; 2] {
|
||||
[self.small.snapshot("small"), self.blocks.snapshot("blocks")]
|
||||
}
|
||||
}
|
||||
|
||||
/// The SDK's telemetry sink for this process: every event goes to `tracing`
|
||||
/// as before, and uploads are also counted in [`UPLOAD_PATHS`].
|
||||
pub fn telemetry() -> Arc<dyn Telemetry> {
|
||||
Arc::new(Counting {
|
||||
inner: TracingTelemetry::shared(),
|
||||
})
|
||||
}
|
||||
|
||||
struct Counting {
|
||||
inner: Arc<dyn Telemetry>,
|
||||
}
|
||||
|
||||
impl Telemetry for Counting {
|
||||
fn record(&self, event: &TelemetryEvent) {
|
||||
UPLOAD_PATHS.record(event);
|
||||
self.inner.record(event);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn event(operation: &'static str, backend: &str, outcome: Outcome, ms: u64) -> TelemetryEvent {
|
||||
TelemetryEvent {
|
||||
operation,
|
||||
outcome,
|
||||
duration: Duration::from_millis(ms),
|
||||
attributes: vec![
|
||||
("backend", backend.to_owned()),
|
||||
("aead", "false".to_owned()),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uploads_are_counted_by_the_path_the_sdk_took() {
|
||||
let paths = UploadPaths::new();
|
||||
paths.record(&event("upload_file", "small", Outcome::Success, 300));
|
||||
paths.record(&event(
|
||||
"upload_new_revision",
|
||||
"small",
|
||||
Outcome::Failure,
|
||||
500,
|
||||
));
|
||||
paths.record(&event("upload_file", "blocks", Outcome::Success, 2_000));
|
||||
|
||||
let [small, blocks] = paths.snapshot();
|
||||
assert_eq!(
|
||||
small,
|
||||
UploadPathStat {
|
||||
path: "small",
|
||||
count: 2,
|
||||
errors: 1,
|
||||
total_ms: 800,
|
||||
longest_ms: 500,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
(blocks.count, blocks.errors, blocks.longest_ms),
|
||||
(1, 0, 2_000)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_operations_and_events_without_a_backend_are_not_counted() {
|
||||
let paths = UploadPaths::new();
|
||||
paths.record(&event("http_request", "small", Outcome::Success, 10));
|
||||
paths.record(&TelemetryEvent {
|
||||
operation: "upload_file",
|
||||
outcome: Outcome::Success,
|
||||
duration: Duration::from_millis(10),
|
||||
attributes: Vec::new(),
|
||||
});
|
||||
|
||||
assert!(paths.snapshot().iter().all(|stat| stat.count == 0));
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1,476 @@
|
||||
//! 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)")?;
|
||||
// On unless the config turns it off: the one-request upload for small
|
||||
// files is new, and this lets it be switched off without a new build.
|
||||
let small_uploads = config.small_uploads.unwrap_or(true);
|
||||
if !small_uploads {
|
||||
tracing::info!("small files are uploaded in blocks: small_uploads is off in the config");
|
||||
}
|
||||
let client = client.with_small_file_upload(small_uploads);
|
||||
|
||||
// Token updates are persisted automatically in real-time. The SDK session has
|
||||
// a token refresh callback registered during `resume_client` that writes updated
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ use proton_drive_rs::{
|
||||
Thumbnail, ThumbnailType, TrashedNode,
|
||||
};
|
||||
|
||||
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
|
||||
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead, RevisionUpload};
|
||||
|
||||
/// Every kind of call [`DriveApi`] makes, one per method.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -393,6 +393,30 @@ impl DriveApi for Counted {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn upload_new_revision_over_dyn(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
expected: &str,
|
||||
reader: &mut (dyn Read + Send),
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<RevisionUpload> {
|
||||
// Counted with the other revision uploads: it is one, with its check.
|
||||
self.timed(
|
||||
DriveCall::UploadNewRevision,
|
||||
self.inner.upload_new_revision_over_dyn(
|
||||
file_uid,
|
||||
expected,
|
||||
reader,
|
||||
intended_size,
|
||||
thumbnails,
|
||||
last_modification_time,
|
||||
),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
|
||||
self.timed(DriveCall::OpenRevision, self.inner.open_revision(uid))
|
||||
.await
|
||||
|
||||
@@ -33,6 +33,8 @@ use proton_drive_rs::{
|
||||
NodeMoveItem, ProtonDriveClient, RevisionReader, Thumbnail, ThumbnailType, TrashedNode,
|
||||
};
|
||||
|
||||
pub use proton_drive_rs::{RevisionUpload, SealedUpload};
|
||||
|
||||
pub mod counted;
|
||||
pub mod digest;
|
||||
|
||||
@@ -120,6 +122,18 @@ pub trait DriveApi: Send + Sync {
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<()>;
|
||||
|
||||
/// A new revision of `file_uid`, only over the revision `expected`. See
|
||||
/// [`ProtonDriveClient::upload_new_revision_over`].
|
||||
async fn upload_new_revision_over_dyn(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
expected: &str,
|
||||
reader: &mut (dyn Read + Send),
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<RevisionUpload>;
|
||||
|
||||
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>>;
|
||||
|
||||
/// The file's thumbnail of `thumbnail_type`, or `None` when its revision
|
||||
@@ -287,6 +301,26 @@ impl dyn DriveApi {
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn upload_new_revision_over<R: Read + Send>(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
expected: &str,
|
||||
mut reader: R,
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<RevisionUpload> {
|
||||
self.upload_new_revision_over_dyn(
|
||||
file_uid,
|
||||
expected,
|
||||
&mut reader,
|
||||
intended_size,
|
||||
thumbnails,
|
||||
last_modification_time,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn download_file_to<W: Write + Send>(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
@@ -468,6 +502,27 @@ impl DriveApi for ProtonDriveClient {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn upload_new_revision_over_dyn(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
expected: &str,
|
||||
reader: &mut (dyn Read + Send),
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<RevisionUpload> {
|
||||
ProtonDriveClient::upload_new_revision_over(
|
||||
self,
|
||||
file_uid,
|
||||
expected,
|
||||
reader,
|
||||
intended_size,
|
||||
thumbnails,
|
||||
last_modification_time.and_then(pdfs_core::timestamp::modification_time),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
|
||||
let reader = ProtonDriveClient::open_revision(self, uid).await?;
|
||||
Ok(Arc::new(reader))
|
||||
@@ -599,6 +654,19 @@ pub fn is_network_error(e: &ProtonError) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// A node's plaintext size as far as its listing knows: the claimed size when
|
||||
/// the revision carries one, else the size on storage. Zero for a folder.
|
||||
pub fn node_size(node: &Node) -> u64 {
|
||||
match &node.kind {
|
||||
NodeKind::Folder => 0,
|
||||
NodeKind::File {
|
||||
claimed_size,
|
||||
total_size_on_storage,
|
||||
..
|
||||
} => claimed_size.unwrap_or(*total_size_on_storage).max(0) as u64,
|
||||
}
|
||||
}
|
||||
|
||||
/// The server revision id of a node's active revision, if it is a file that has
|
||||
/// one. The stable identity the drain conflict-checks against (see `Baseline` in pdfs-store).
|
||||
pub fn node_revision_id(node: &Node) -> Option<String> {
|
||||
|
||||
@@ -67,7 +67,7 @@ use proton_drive_rs::{
|
||||
use sha1::{Digest as _, Sha1};
|
||||
|
||||
use super::rng::Rng;
|
||||
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
|
||||
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead, RevisionUpload, SealedUpload};
|
||||
|
||||
/// The volume every fake node lives on.
|
||||
pub const VOLUME: &str = "simvol";
|
||||
@@ -1531,6 +1531,57 @@ impl DriveApi for FakeClient {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn upload_new_revision_over_dyn(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
expected: &str,
|
||||
reader: &mut (dyn Read + Send),
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<RevisionUpload> {
|
||||
// The SDK reads the file's link for its keys and checks the revision
|
||||
// on that read, so it is held, lags and counts like any other read.
|
||||
self.wait_if_held(&self.0.hold, std::slice::from_ref(file_uid))
|
||||
.await;
|
||||
let lag = self.lag();
|
||||
let seen = self
|
||||
.request(false, |server| {
|
||||
Ok(server
|
||||
.visible(file_uid, lag, Instant::now())
|
||||
.map(|remote| (remote.trashed, remote.file.map(|file| file.revision))))
|
||||
})
|
||||
.await?;
|
||||
match seen {
|
||||
None => return Err(api(ResponseCode::DoesNotExist, "file not found")),
|
||||
Some((true, _)) => return Ok(RevisionUpload::Trashed),
|
||||
Some((false, revision)) if revision.as_deref() != Some(expected) => {
|
||||
return Ok(RevisionUpload::Moved);
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
self.upload_new_revision_from_dyn(
|
||||
file_uid,
|
||||
reader,
|
||||
intended_size,
|
||||
thumbnails,
|
||||
last_modification_time,
|
||||
)
|
||||
.await?;
|
||||
let revision_id = self
|
||||
.0
|
||||
.drive
|
||||
.server
|
||||
.lock()
|
||||
.current(file_uid)
|
||||
.and_then(|remote| remote.file.as_ref().map(|file| file.revision.clone()))
|
||||
.unwrap_or_default();
|
||||
Ok(RevisionUpload::Sealed(SealedUpload {
|
||||
node_uid: file_uid.clone(),
|
||||
revision_id,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
|
||||
let file = self
|
||||
.request(false, |server| {
|
||||
|
||||
@@ -13,6 +13,8 @@ description = "FUSE on-demand filesystem for Proton Drive"
|
||||
pdfs-core.workspace = true
|
||||
pdfs-drive.workspace = true
|
||||
pdfs-sync.workspace = true
|
||||
pdfs-sched.workspace = true
|
||||
pdfs-vfs.workspace = true
|
||||
pdfs-store.workspace = true
|
||||
zip.workspace = true
|
||||
sha1.workspace = true
|
||||
@@ -41,6 +43,7 @@ notify = "8"
|
||||
parking_lot.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
pdfs-vfs = { workspace = true, features = ["test-support"] }
|
||||
pdfs-drive = { workspace = true, features = ["sim"] }
|
||||
tracing-subscriber.workspace = true
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
@@ -57,7 +57,7 @@ impl Core {
|
||||
mountpoint: &Path,
|
||||
) -> CoreResult<StoredSyncFolder> {
|
||||
let _registration = super::devices::SYNC_ROOT_REGISTRATION.lock();
|
||||
if !self.primary {
|
||||
if !self.session.primary {
|
||||
return Err(CoreError::invalid("attach must use My files"));
|
||||
}
|
||||
if remote.is_absolute()
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use super::*;
|
||||
use crate::shutdown::Shutdown;
|
||||
use pdfs_core::error::session_revoked;
|
||||
use pdfs_sync::root::{Doubt, RootInput};
|
||||
|
||||
/// Drop `uid` from one mount's tree and tell that mount's kernel session the
|
||||
/// entry is gone. Shared by the trash and delete paths, which differ only in
|
||||
@@ -148,7 +149,12 @@ fn apply_event(core: &Core, event: &DriveEvent, dirty: &mut DirtyParents) -> pdf
|
||||
core.db.sync_remote_changed(&node_uid.to_string(), None)
|
||||
}
|
||||
// What changed went by unseen: every pass walks Drive whole again.
|
||||
DriveEvent::ContinuityLost { .. } => core.db.sync_walks_clear_all().map(|()| Vec::new()),
|
||||
DriveEvent::ContinuityLost { .. } => {
|
||||
core.sync
|
||||
.roots
|
||||
.input_all(RootInput::Doubted(Doubt::EventGap));
|
||||
core.db.sync_walks_clear_all().map(|()| Vec::new())
|
||||
}
|
||||
_ => Ok(Vec::new()),
|
||||
};
|
||||
match marked {
|
||||
@@ -176,7 +182,7 @@ fn apply_event(core: &Core, event: &DriveEvent, dirty: &mut DirtyParents) -> pdf
|
||||
// even for a trash, so an echo we no longer care about does not
|
||||
// linger to suppress a later foreign change.
|
||||
let echo = core.take_self_change(node_uid);
|
||||
let ours = !*is_trashed && (echo || core.pending.lock().contains_key(node_uid));
|
||||
let ours = !*is_trashed && (echo || core.writes.is_queued(node_uid));
|
||||
if ours {
|
||||
debug!(uid = %node_uid, "ignoring remote event for a node with a queued write");
|
||||
}
|
||||
@@ -568,7 +574,7 @@ pub(super) async fn run_event_sync(
|
||||
|
||||
/// Follow the Photos volume and commit changes with its durable event cursor.
|
||||
pub(super) async fn run_photos_event_sync(core: Core) {
|
||||
let photos = core.photos();
|
||||
let photos = core.photos_api();
|
||||
// The photos volume only exists once the user has used Photos at all, and
|
||||
// the daemon may well start before the network does.
|
||||
let scope = loop {
|
||||
@@ -635,7 +641,7 @@ pub(super) async fn run_photos_event_sync(core: Core) {
|
||||
}
|
||||
}
|
||||
if core.db.photos_need_work().unwrap_or(true) {
|
||||
core.spawn_timeline_refresh();
|
||||
core.photos().spawn_timeline_refresh();
|
||||
}
|
||||
core.next_poll(POLL_INTERVAL).await;
|
||||
}
|
||||
|
||||
+64
-1086
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,455 @@
|
||||
//! The control requests about Photos: the timeline, albums, thumbnails, the gallery, and Takeout imports and redating.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The requests [`answer`] serves, as a pattern, so the control socket's match
|
||||
/// hands exactly these over and the compiler still checks that it covers every
|
||||
/// request.
|
||||
macro_rules! request {
|
||||
() => {
|
||||
::pdfs_core::control::Request::PhotosTimeline { .. }
|
||||
| ::pdfs_core::control::Request::PhotoDuplicates
|
||||
| ::pdfs_core::control::Request::PhotoSimilar
|
||||
| ::pdfs_core::control::Request::PhotoPlaces
|
||||
| ::pdfs_core::control::Request::PlacePhotos { .. }
|
||||
| ::pdfs_core::control::Request::PlaceLocations { .. }
|
||||
| ::pdfs_core::control::Request::PhotosOnThisDay { .. }
|
||||
| ::pdfs_core::control::Request::PhotoGroup { .. }
|
||||
| ::pdfs_core::control::Request::SetPhotoFavorite { .. }
|
||||
| ::pdfs_core::control::Request::PhotoAlbums
|
||||
| ::pdfs_core::control::Request::AlbumPhotos { .. }
|
||||
| ::pdfs_core::control::Request::CreateAlbum { .. }
|
||||
| ::pdfs_core::control::Request::RenameAlbum { .. }
|
||||
| ::pdfs_core::control::Request::DeleteAlbum { .. }
|
||||
| ::pdfs_core::control::Request::AddToAlbum { .. }
|
||||
| ::pdfs_core::control::Request::RemoveFromAlbum { .. }
|
||||
| ::pdfs_core::control::Request::PhotoPresence { .. }
|
||||
| ::pdfs_core::control::Request::PhotoMonths { .. }
|
||||
| ::pdfs_core::control::Request::PhotoThumbs { .. }
|
||||
| ::pdfs_core::control::Request::FileThumbs { .. }
|
||||
| ::pdfs_core::control::Request::ReserveFileThumbGeneration
|
||||
| ::pdfs_core::control::Request::CancelFileThumbs { .. }
|
||||
| ::pdfs_core::control::Request::StartThumbnailBuild { .. }
|
||||
| ::pdfs_core::control::Request::CancelThumbnailBuild
|
||||
| ::pdfs_core::control::Request::ThumbnailBuildStatus
|
||||
| ::pdfs_core::control::Request::PhotosRefreshStatus
|
||||
| ::pdfs_core::control::Request::OpenPhoto { .. }
|
||||
| ::pdfs_core::control::Request::DriveGallery { .. }
|
||||
| ::pdfs_core::control::Request::OpenGalleryVideo { .. }
|
||||
| ::pdfs_core::control::Request::OpenGalleryImage { .. }
|
||||
| ::pdfs_core::control::Request::CloseGalleryVideo { .. }
|
||||
| ::pdfs_core::control::Request::GalleryThumbnail { .. }
|
||||
| ::pdfs_core::control::Request::ImportTakeout { .. }
|
||||
| ::pdfs_core::control::Request::ImportStatus
|
||||
| ::pdfs_core::control::Request::ResumeImport
|
||||
| ::pdfs_core::control::Request::CancelImport
|
||||
| ::pdfs_core::control::Request::RedatePhotos { .. }
|
||||
| ::pdfs_core::control::Request::RedateStatus
|
||||
| ::pdfs_core::control::Request::CancelRedate
|
||||
| ::pdfs_core::control::Request::UploadPhoto { .. }
|
||||
};
|
||||
}
|
||||
pub(super) use request;
|
||||
|
||||
/// Answer a request that [`request!`] matches.
|
||||
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
let Ask {
|
||||
core,
|
||||
mountpoint,
|
||||
stream,
|
||||
visibility,
|
||||
excluded,
|
||||
..
|
||||
} = *ask;
|
||||
match request {
|
||||
CtlRequest::PhotosTimeline {
|
||||
offset,
|
||||
limit,
|
||||
kind,
|
||||
range,
|
||||
favorites,
|
||||
not_in_album,
|
||||
} => match core.photos().photos_timeline(
|
||||
offset,
|
||||
clamp_limit(limit),
|
||||
kind,
|
||||
range,
|
||||
favorites,
|
||||
not_in_album,
|
||||
excluded,
|
||||
) {
|
||||
Ok(Some(items)) => CtlResponse::Photos {
|
||||
available: true,
|
||||
items,
|
||||
counts: core.db.photos_counts_visible(excluded).ok(),
|
||||
},
|
||||
Ok(None) => CtlResponse::Photos {
|
||||
available: false,
|
||||
items: Vec::new(),
|
||||
counts: None,
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PhotoDuplicates => match core.photos().photo_duplicates() {
|
||||
Ok(sets) => CtlResponse::PhotoDuplicates { sets },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PhotoSimilar => match core.photos().photo_similar() {
|
||||
Ok((sets, hashing, uncompared)) => CtlResponse::PhotoSimilar {
|
||||
sets,
|
||||
hashing,
|
||||
uncompared,
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PhotoPlaces => match core.photos().photo_places(excluded) {
|
||||
Ok(items) => CtlResponse::Places {
|
||||
items,
|
||||
mapping: core.photos().timeline_progress(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PlacePhotos { id, offset, limit } => {
|
||||
match core
|
||||
.photos()
|
||||
.place_photos(id, offset, clamp_limit(limit), excluded)
|
||||
{
|
||||
Ok(items) => CtlResponse::Photos {
|
||||
available: true,
|
||||
items,
|
||||
counts: None,
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::PlaceLocations { id } => match core.photos().place_locations(id) {
|
||||
Ok(items) => CtlResponse::PhotoLocations { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PhotosOnThisDay { limit } => {
|
||||
match core
|
||||
.photos()
|
||||
.photos_on_this_day(clamp_limit(limit), excluded)
|
||||
{
|
||||
Ok(items) => CtlResponse::Photos {
|
||||
available: true,
|
||||
items,
|
||||
counts: None,
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::PhotoGroup { uid } => match core.photos().photo_group(&uid) {
|
||||
Ok(items) => CtlResponse::Photos {
|
||||
available: true,
|
||||
items,
|
||||
counts: None,
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::SetPhotoFavorite { uid, favorite } => match parse_uid(&uid) {
|
||||
Some(node_uid) => match core.photos().set_photo_favorite(&node_uid, favorite) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: if favorite {
|
||||
"added to favorites".to_string()
|
||||
} else {
|
||||
"removed from favorites".to_string()
|
||||
},
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
None => CtlResponse::error(CoreError::invalid(format!("invalid uid: {uid}"))),
|
||||
},
|
||||
CtlRequest::PhotoAlbums => match core.photos().albums() {
|
||||
Ok(Some(items)) => CtlResponse::Albums {
|
||||
available: true,
|
||||
items,
|
||||
},
|
||||
Ok(None) => CtlResponse::Albums {
|
||||
available: false,
|
||||
items: Vec::new(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::AlbumPhotos { uid, offset, limit } => match parse_uid(&uid) {
|
||||
// An album page is a timeline page as far as the front-end is
|
||||
// concerned, so it comes back in the same reply — with `counts`
|
||||
// unset, which describe the whole timeline rather than this album.
|
||||
Some(album) => match visibility.permits(&uid).and_then(|()| {
|
||||
core.photos()
|
||||
.album_photos(&album, offset, clamp_limit(limit), excluded)
|
||||
}) {
|
||||
Ok(items) => CtlResponse::Photos {
|
||||
available: true,
|
||||
items,
|
||||
counts: None,
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
|
||||
},
|
||||
CtlRequest::CreateAlbum { name } => match core.photos().create_album(&name) {
|
||||
Ok(uid) => CtlResponse::AlbumCreated { uid },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RenameAlbum { uid, name } => match parse_uid(&uid) {
|
||||
Some(album) => match core.photos().rename_album(&album, &name) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: format!("renamed album to {name}"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
|
||||
},
|
||||
CtlRequest::DeleteAlbum { uid, delete_photos } => match parse_uid(&uid) {
|
||||
Some(album) => match core.photos().delete_album(&album, delete_photos) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: "album deleted".to_string(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
|
||||
},
|
||||
CtlRequest::AddToAlbum { uid, photos } => album_change(&uid, &photos, |album, photos| {
|
||||
core.photos().add_to_album(album, photos)
|
||||
}),
|
||||
CtlRequest::RemoveFromAlbum { uid, photos } => {
|
||||
album_change(&uid, &photos, |album, photos| {
|
||||
core.photos().remove_from_album(album, photos)
|
||||
})
|
||||
}
|
||||
CtlRequest::PhotoPresence { uid, album } => match core.cached_gallery_visibility() {
|
||||
Ok(visibility)
|
||||
if visibility.media.contains(&uid)
|
||||
|| album
|
||||
.as_ref()
|
||||
.is_some_and(|uid| visibility.albums.contains(uid)) =>
|
||||
{
|
||||
CtlResponse::PhotoPresence { present: false }
|
||||
}
|
||||
Ok(_) => match core.db.photos_contains(&uid, album.as_deref()) {
|
||||
Ok(present) => CtlResponse::PhotoPresence { present },
|
||||
Err(error) => CtlResponse::error(error.into()),
|
||||
},
|
||||
Err(error) => CtlResponse::error(error),
|
||||
},
|
||||
CtlRequest::PhotoMonths { .. } => unreachable!("handled before visibility requests"),
|
||||
CtlRequest::PhotoThumbs { uids } => {
|
||||
let parsed: Vec<NodeUid> = uids
|
||||
.iter()
|
||||
.filter(|uid| !visibility.media.contains(*uid))
|
||||
.filter_map(|u| parse_uid(u))
|
||||
.collect();
|
||||
CtlResponse::Thumbs {
|
||||
items: core.photos().photo_thumbs(&parsed),
|
||||
}
|
||||
}
|
||||
CtlRequest::FileThumbs { items, generation } => {
|
||||
match core.photos().file_thumbs(&items, generation) {
|
||||
Some(items) => CtlResponse::Thumbs { items },
|
||||
None => CtlResponse::FileThumbsStale,
|
||||
}
|
||||
}
|
||||
CtlRequest::ReserveFileThumbGeneration => CtlResponse::FileThumbGeneration {
|
||||
generation: core.photos().reserve_file_thumb_generation(),
|
||||
},
|
||||
CtlRequest::CancelFileThumbs { generation } => {
|
||||
core.photos().cancel_file_thumbs(generation);
|
||||
CtlResponse::Ok {
|
||||
message: "thumbnail requests cancelled".to_string(),
|
||||
}
|
||||
}
|
||||
CtlRequest::StartThumbnailBuild { path } => match rel_to_mount(mountpoint, &path) {
|
||||
Ok(rel) => match core.photos().start_thumbnail_build(rel) {
|
||||
Ok(status) => CtlResponse::ThumbnailBuild { status },
|
||||
Err(error) => CtlResponse::error(error),
|
||||
},
|
||||
Err(error) => CtlResponse::error(error),
|
||||
},
|
||||
CtlRequest::CancelThumbnailBuild => CtlResponse::ThumbnailBuild {
|
||||
status: core.photos().cancel_thumbnail_build(),
|
||||
},
|
||||
CtlRequest::ThumbnailBuildStatus => CtlResponse::ThumbnailBuild {
|
||||
status: core.photos().thumbnail_build_status(),
|
||||
},
|
||||
CtlRequest::PhotosRefreshStatus => CtlResponse::PhotosRefresh {
|
||||
running: core.photos().timeline_refreshing(),
|
||||
},
|
||||
CtlRequest::OpenPhoto { uid } => match parse_uid(&uid) {
|
||||
Some(u) => match visibility
|
||||
.permits(&uid)
|
||||
.and_then(|()| core.photos().open_photo(&u))
|
||||
{
|
||||
Ok(p) => CtlResponse::FilePath {
|
||||
path: p.display().to_string(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
None => CtlResponse::error(CoreError::invalid(format!("bad uid: {uid}"))),
|
||||
},
|
||||
CtlRequest::DriveGallery {
|
||||
action: pdfs_core::control::GalleryAction::AuthenticateHidden,
|
||||
} => core
|
||||
.authenticate_hidden_gallery(stream)
|
||||
.unwrap_or_else(CtlResponse::error),
|
||||
CtlRequest::DriveGallery { action } => core
|
||||
.drive_gallery(action)
|
||||
.unwrap_or_else(CtlResponse::error),
|
||||
CtlRequest::OpenGalleryVideo { uid, private } => core
|
||||
.open_gallery_video(&uid, private)
|
||||
.unwrap_or_else(CtlResponse::error),
|
||||
CtlRequest::OpenGalleryImage { uid, private: true } => {
|
||||
core.gallery_image(&uid).unwrap_or_else(CtlResponse::error)
|
||||
}
|
||||
CtlRequest::OpenGalleryImage {
|
||||
uid,
|
||||
private: false,
|
||||
} => match visibility
|
||||
.permits(&uid)
|
||||
.and_then(|()| core.sharing.open_shared_file(&uid))
|
||||
{
|
||||
Ok(path) => CtlResponse::FilePath {
|
||||
path: path.display().to_string(),
|
||||
},
|
||||
Err(error) => CtlResponse::error(error),
|
||||
},
|
||||
CtlRequest::CloseGalleryVideo { token } => core
|
||||
.close_gallery_video(&token)
|
||||
.unwrap_or_else(CtlResponse::error),
|
||||
CtlRequest::GalleryThumbnail { uid, private } => core
|
||||
.gallery_thumbnail(&uid, private)
|
||||
.unwrap_or_else(CtlResponse::error),
|
||||
CtlRequest::ImportTakeout { archives, dry_run } => {
|
||||
if archives.is_empty() {
|
||||
CtlResponse::error(CoreError::invalid("no Takeout archives given"))
|
||||
} else {
|
||||
let paths = archives.into_iter().map(PathBuf::from).collect();
|
||||
start_takeout_import(core, paths, dry_run)
|
||||
}
|
||||
}
|
||||
CtlRequest::ImportStatus => {
|
||||
let report = crate::photos::takeout::import_status();
|
||||
CtlResponse::ImportStatus {
|
||||
running: report.running,
|
||||
summary: report.summary,
|
||||
progress: report.progress,
|
||||
resumable: report.resumable,
|
||||
}
|
||||
}
|
||||
CtlRequest::ResumeImport => match crate::photos::takeout::resumable_archives() {
|
||||
None => CtlResponse::error(CoreError::not_found("there is no import to resume")),
|
||||
Some(paths) => start_takeout_import(core, paths, false),
|
||||
},
|
||||
CtlRequest::CancelImport => {
|
||||
if crate::photos::takeout::cancel_import() {
|
||||
CtlResponse::Ok {
|
||||
message: "stopping the import".to_string(),
|
||||
}
|
||||
} else {
|
||||
CtlResponse::error(CoreError::invalid("no import is running"))
|
||||
}
|
||||
}
|
||||
CtlRequest::RedatePhotos {
|
||||
dry_run,
|
||||
limit,
|
||||
range,
|
||||
} => match core.photos().spawn_redate(dry_run, limit, range) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: if dry_run {
|
||||
"checking photo dates".to_string()
|
||||
} else {
|
||||
"fixing photo dates".to_string()
|
||||
},
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RedateStatus => {
|
||||
let (running, summary) = crate::photos::redate::redate_status();
|
||||
CtlResponse::RedateStatus { running, summary }
|
||||
}
|
||||
CtlRequest::CancelRedate => {
|
||||
if crate::photos::redate::cancel_redate() {
|
||||
CtlResponse::Ok {
|
||||
message: "stopping the re-date".to_string(),
|
||||
}
|
||||
} else {
|
||||
CtlResponse::error(CoreError::invalid("no photo re-date is running"))
|
||||
}
|
||||
}
|
||||
CtlRequest::UploadPhoto {
|
||||
name,
|
||||
media_type,
|
||||
source_path,
|
||||
capture_time,
|
||||
} => {
|
||||
// Streamed off disk rather than carried over the socket: see the note
|
||||
// on `Request::UploadPhoto`. The length comes from the same handle the
|
||||
// bytes do, so a file changing size under us cannot make the two
|
||||
// disagree.
|
||||
match std::fs::File::open(&source_path).and_then(|f| f.metadata().map(|m| (f, m.len())))
|
||||
{
|
||||
Err(e) => CtlResponse::error(CoreError::invalid(format!(
|
||||
"cannot read {source_path}: {e}"
|
||||
))),
|
||||
Ok((file, len)) => {
|
||||
let photos = core.photos_api();
|
||||
// Unless the caller knows better: the photo's own EXIF,
|
||||
// then the file's modification time, which a copy resets.
|
||||
let capture_time = capture_time.or_else(|| {
|
||||
let path = Path::new(&source_path);
|
||||
pdfs_core::exiftime::capture_time_of(path).or_else(|| {
|
||||
let modified =
|
||||
std::fs::metadata(path).and_then(|m| m.modified()).ok()?;
|
||||
let since = modified.duration_since(std::time::UNIX_EPOCH).ok()?;
|
||||
Some(since.as_secs() as i64)
|
||||
})
|
||||
});
|
||||
let metadata = proton_drive_rs::PhotoUploadMetadata {
|
||||
capture_time,
|
||||
last_modification_time: capture_time
|
||||
.and_then(pdfs_core::timestamp::modification_time),
|
||||
..Default::default()
|
||||
};
|
||||
let thumbnails = core
|
||||
.photos()
|
||||
.upload_thumbnails(Path::new(&source_path), &name);
|
||||
let guard =
|
||||
core.transfers
|
||||
.begin(name.clone(), "", TransferDirection::Upload, len);
|
||||
let reader = CountingReader::new(std::io::BufReader::new(file), &guard);
|
||||
match core.rt.block_on(photos.upload_photo_from(
|
||||
&name,
|
||||
&media_type,
|
||||
reader,
|
||||
len as i64,
|
||||
thumbnails,
|
||||
metadata,
|
||||
false,
|
||||
)) {
|
||||
Ok(uid) => {
|
||||
// The photo we just uploaded belongs at the head of the
|
||||
// timeline, and the GUI reloads the gallery the moment this
|
||||
// reply lands — so refresh now rather than leaving it to a
|
||||
// background pass that would land just after that reload.
|
||||
core.invalidate_photos();
|
||||
if let Err(e) = core.photos().refresh_timeline_joined() {
|
||||
warn!(error = %e, "timeline refresh after upload failed");
|
||||
}
|
||||
CtlResponse::Ok {
|
||||
message: format!("uploaded photo with uid {uid}"),
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
// The reply goes to the app's toast only; without
|
||||
// this the journal shows a failure and no reason.
|
||||
warn!(error = %e, "photo upload failed");
|
||||
CtlResponse::error(CoreError::from_api(&e, "upload photo failed"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// `control` only hands over what `request!` matches.
|
||||
_ => CtlResponse::error(CoreError::internal("not a photos request".to_string())),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
//! The control requests about a file's earlier revisions: listing, restoring, deleting and saving one as a new file, by path or by uid.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The requests [`answer`] serves, as a pattern, so the control socket's match
|
||||
/// hands exactly these over and the compiler still checks that it covers every
|
||||
/// request.
|
||||
macro_rules! request {
|
||||
() => {
|
||||
::pdfs_core::control::Request::ListRevisions { .. }
|
||||
| ::pdfs_core::control::Request::ListRevisionsByUid { .. }
|
||||
| ::pdfs_core::control::Request::RestoreRevision { .. }
|
||||
| ::pdfs_core::control::Request::RestoreRevisionByUid { .. }
|
||||
| ::pdfs_core::control::Request::DeleteRevision { .. }
|
||||
| ::pdfs_core::control::Request::DeleteRevisionByUid { .. }
|
||||
| ::pdfs_core::control::Request::SaveRevisionAs { .. }
|
||||
| ::pdfs_core::control::Request::SaveRevisionAsByUid { .. }
|
||||
};
|
||||
}
|
||||
pub(super) use request;
|
||||
|
||||
/// The file a request is about, and how the activity feed names it: the file
|
||||
/// name under the mount, or the uid.
|
||||
struct Target {
|
||||
uid: NodeUid,
|
||||
name: String,
|
||||
}
|
||||
|
||||
impl Target {
|
||||
fn path(core: &Core, rel: &Path) -> CoreResult<Self> {
|
||||
let (_ino, uid) = core.resolve(rel)?;
|
||||
let name = rel
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| uid.to_string());
|
||||
Ok(Self { uid, name })
|
||||
}
|
||||
|
||||
fn uid(core: &Core, uid: &str) -> CoreResult<Self> {
|
||||
let uid = core.resolve_anywhere(uid)?;
|
||||
let name = uid.to_string();
|
||||
Ok(Self { uid, name })
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer a request that [`request!`] matches.
|
||||
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
let Ask {
|
||||
core, mountpoint, ..
|
||||
} = *ask;
|
||||
let revisions = core.revisions();
|
||||
let at = |path: &str| rel_to_mount(mountpoint, path);
|
||||
let reply = |result: CoreResult<String>| match result {
|
||||
Ok(message) => CtlResponse::Ok { message },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
};
|
||||
match request {
|
||||
CtlRequest::ListRevisions { path } => {
|
||||
match at(&path).and_then(|rel| Target::path(core, &rel)) {
|
||||
Ok(file) => listed(revisions.list(&file.uid)),
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::ListRevisionsByUid { uid } => match Target::uid(core, &uid) {
|
||||
Ok(file) => listed(revisions.list(&file.uid)),
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RestoreRevision { path, revision_id } => reply(at(&path).and_then(|rel| {
|
||||
let file = Target::path(core, &rel)?;
|
||||
revisions.restore(&file.uid, &revision_id, &file.name)?;
|
||||
// The size and mtime a listing shows describe the revision that
|
||||
// was active a moment ago.
|
||||
core.invalidate_parent_listing(&rel);
|
||||
Ok(format!("restoring version {revision_id} of {path}"))
|
||||
})),
|
||||
CtlRequest::RestoreRevisionByUid { uid, revision_id } => {
|
||||
reply(Target::uid(core, &uid).and_then(|file| {
|
||||
revisions.restore(&file.uid, &revision_id, &file.name)?;
|
||||
Ok(format!("restoring version {revision_id}"))
|
||||
}))
|
||||
}
|
||||
CtlRequest::DeleteRevision { path, revision_id } => reply(at(&path).and_then(|rel| {
|
||||
let file = Target::path(core, &rel)?;
|
||||
revisions.delete(&file.uid, &revision_id, &file.name)?;
|
||||
Ok(format!("deleted version {revision_id} of {path}"))
|
||||
})),
|
||||
CtlRequest::DeleteRevisionByUid { uid, revision_id } => {
|
||||
reply(Target::uid(core, &uid).and_then(|file| {
|
||||
revisions.delete(&file.uid, &revision_id, &file.name)?;
|
||||
Ok(format!("deleted version {revision_id}"))
|
||||
}))
|
||||
}
|
||||
CtlRequest::SaveRevisionAs {
|
||||
path,
|
||||
revision_id,
|
||||
dest,
|
||||
} => reply(at(&path).and_then(|rel| {
|
||||
let file = Target::path(core, &rel)?;
|
||||
let written =
|
||||
revisions.save_as(&file.uid, &revision_id, &file.name, Path::new(&dest))?;
|
||||
Ok(format!("wrote {} to {dest}", human_bytes(written)))
|
||||
})),
|
||||
CtlRequest::SaveRevisionAsByUid {
|
||||
uid,
|
||||
revision_id,
|
||||
dest,
|
||||
} => reply(Target::uid(core, &uid).and_then(|file| {
|
||||
let written =
|
||||
revisions.save_as(&file.uid, &revision_id, &file.name, Path::new(&dest))?;
|
||||
Ok(format!("wrote {} to {dest}", human_bytes(written)))
|
||||
})),
|
||||
// `control` only hands over what `request!` matches.
|
||||
_ => CtlResponse::error(CoreError::internal("not a revisions request".to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
fn listed(result: CoreResult<Vec<pdfs_core::control::RevisionInfo>>) -> CtlResponse {
|
||||
match result {
|
||||
Ok(items) => CtlResponse::Revisions { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
//! The control requests about sharing: who a node is shared with, its public
|
||||
//! link, what others share with this account, invitations and saved links.
|
||||
//!
|
||||
//! Most of them come in two forms, one naming the node by its path under the
|
||||
//! mount and one by its uid. Both are resolved to a uid here, once, and the
|
||||
//! [`Sharing`](crate::sharing::Sharing) service is only ever asked about a
|
||||
//! resolved node.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use pdfs_core::CoreResult;
|
||||
use pdfs_core::control::{ActivityKind, Request as CtlRequest, Response as CtlResponse};
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
|
||||
use super::rel_to_mount;
|
||||
use crate::Core;
|
||||
use crate::sharing::StopSharingOutcome;
|
||||
|
||||
/// The requests [`answer`] serves, as a pattern, so the control socket's
|
||||
/// match hands exactly these over and the compiler still checks that it covers
|
||||
/// every request.
|
||||
macro_rules! request {
|
||||
() => {
|
||||
::pdfs_core::control::Request::ShareNode { .. }
|
||||
| ::pdfs_core::control::Request::ShareNodeByUid { .. }
|
||||
| ::pdfs_core::control::Request::ListShare { .. }
|
||||
| ::pdfs_core::control::Request::ListShareByUid { .. }
|
||||
| ::pdfs_core::control::Request::UpdateShareRole { .. }
|
||||
| ::pdfs_core::control::Request::UpdateShareRoleByUid { .. }
|
||||
| ::pdfs_core::control::Request::RemoveShareEntry { .. }
|
||||
| ::pdfs_core::control::Request::RemoveShareEntryByUid { .. }
|
||||
| ::pdfs_core::control::Request::CreatePublicLink { .. }
|
||||
| ::pdfs_core::control::Request::CreatePublicLinkByUid { .. }
|
||||
| ::pdfs_core::control::Request::UpdatePublicLink { .. }
|
||||
| ::pdfs_core::control::Request::UpdatePublicLinkByUid { .. }
|
||||
| ::pdfs_core::control::Request::RemovePublicLink { .. }
|
||||
| ::pdfs_core::control::Request::RemovePublicLinkByUid { .. }
|
||||
| ::pdfs_core::control::Request::StopSharing { .. }
|
||||
| ::pdfs_core::control::Request::StopSharingByUid { .. }
|
||||
| ::pdfs_core::control::Request::ListSharedWithMe
|
||||
| ::pdfs_core::control::Request::ListSharedFolder { .. }
|
||||
| ::pdfs_core::control::Request::OpenSharedFile { .. }
|
||||
| ::pdfs_core::control::Request::LeaveShared { .. }
|
||||
| ::pdfs_core::control::Request::ListInvitations
|
||||
| ::pdfs_core::control::Request::AcceptInvitation { .. }
|
||||
| ::pdfs_core::control::Request::RejectInvitation { .. }
|
||||
| ::pdfs_core::control::Request::ListBookmarks
|
||||
| ::pdfs_core::control::Request::CreateBookmark { .. }
|
||||
| ::pdfs_core::control::Request::DeleteBookmark { .. }
|
||||
| ::pdfs_core::control::Request::ListSharedByMe
|
||||
};
|
||||
}
|
||||
pub(super) use request;
|
||||
|
||||
/// The node a request is about, and how the activity feed names it: the path
|
||||
/// the user gave, or the uid.
|
||||
struct Target {
|
||||
label: String,
|
||||
/// The node, or why it could not be resolved. A failure is reported
|
||||
/// through the request's own reply, so a share that fails here is logged
|
||||
/// as a failed share, as it was before the split.
|
||||
node: CoreResult<NodeUid>,
|
||||
}
|
||||
|
||||
impl Target {
|
||||
/// A node named by its path. A path outside the mount fails the request
|
||||
/// before it starts, without an activity entry.
|
||||
fn path(core: &Core, mountpoint: &Path, path: String) -> CoreResult<Self> {
|
||||
let rel = rel_to_mount(mountpoint, &path)?;
|
||||
Ok(Self {
|
||||
node: core.resolve(&rel).map(|(_ino, uid)| uid),
|
||||
label: path,
|
||||
})
|
||||
}
|
||||
|
||||
/// A node named by its uid, which one of this daemon's locations, or the
|
||||
/// Photos timeline, must show to be this account's.
|
||||
fn uid(core: &Core, uid: String) -> Self {
|
||||
Self {
|
||||
node: core.resolve_shareable(&uid),
|
||||
label: uid,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer a request that [`request!`] matches.
|
||||
pub(super) fn answer(ask: &super::Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
let (core, mountpoint) = (ask.core, ask.mountpoint);
|
||||
match answer_or_refuse(core, mountpoint, request) {
|
||||
Ok(response) => response,
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn answer_or_refuse(
|
||||
core: &Core,
|
||||
mountpoint: &Path,
|
||||
request: CtlRequest,
|
||||
) -> CoreResult<CtlResponse> {
|
||||
let sharing = &core.sharing;
|
||||
Ok(match request {
|
||||
CtlRequest::ShareNode {
|
||||
path,
|
||||
emails,
|
||||
role,
|
||||
message,
|
||||
} => share_node(
|
||||
core,
|
||||
Target::path(core, mountpoint, path)?,
|
||||
&emails,
|
||||
&role,
|
||||
message,
|
||||
),
|
||||
CtlRequest::ShareNodeByUid {
|
||||
uid,
|
||||
emails,
|
||||
role,
|
||||
message,
|
||||
} => share_node(core, Target::uid(core, uid), &emails, &role, message),
|
||||
CtlRequest::ListShare { path } => list_share(core, Target::path(core, mountpoint, path)?),
|
||||
CtlRequest::ListShareByUid { uid } => list_share(core, Target::uid(core, uid)),
|
||||
CtlRequest::UpdateShareRole {
|
||||
path,
|
||||
id,
|
||||
kind,
|
||||
role,
|
||||
} => {
|
||||
let target = Target::path(core, mountpoint, path)?;
|
||||
target
|
||||
.node
|
||||
.and_then(|uid| sharing.update_share_role(&uid, &id, kind, &role))?;
|
||||
role_updated(&role)
|
||||
}
|
||||
CtlRequest::UpdateShareRoleByUid {
|
||||
uid,
|
||||
id,
|
||||
kind,
|
||||
role,
|
||||
} => {
|
||||
let target = Target::uid(core, uid);
|
||||
target
|
||||
.node
|
||||
.and_then(|uid| sharing.update_share_role(&uid, &id, kind, &role))?;
|
||||
role_updated(&role)
|
||||
}
|
||||
CtlRequest::RemoveShareEntry { path, id, kind } => {
|
||||
let target = Target::path(core, mountpoint, path)?;
|
||||
remove_share_entry(core, target, &id, kind)?
|
||||
}
|
||||
CtlRequest::RemoveShareEntryByUid { uid, id, kind } => {
|
||||
remove_share_entry(core, Target::uid(core, uid), &id, kind)?
|
||||
}
|
||||
CtlRequest::CreatePublicLink {
|
||||
path,
|
||||
role,
|
||||
password,
|
||||
expires,
|
||||
} => {
|
||||
let target = Target::path(core, mountpoint, path)?;
|
||||
create_public_link(core, target, &role, password.as_deref(), expires)
|
||||
}
|
||||
CtlRequest::CreatePublicLinkByUid {
|
||||
uid,
|
||||
role,
|
||||
password,
|
||||
expires,
|
||||
} => create_public_link(
|
||||
core,
|
||||
Target::uid(core, uid),
|
||||
&role,
|
||||
password.as_deref(),
|
||||
expires,
|
||||
),
|
||||
CtlRequest::UpdatePublicLink {
|
||||
path,
|
||||
id,
|
||||
role,
|
||||
password,
|
||||
expires,
|
||||
} => {
|
||||
let uid = Target::path(core, mountpoint, path)?.node?;
|
||||
let link = sharing.update_public_link(&uid, &id, role.as_deref(), password, expires)?;
|
||||
CtlResponse::PublicLink { link }
|
||||
}
|
||||
CtlRequest::UpdatePublicLinkByUid {
|
||||
uid,
|
||||
id,
|
||||
role,
|
||||
password,
|
||||
expires,
|
||||
} => {
|
||||
let uid = Target::uid(core, uid).node?;
|
||||
let link = sharing.update_public_link(&uid, &id, role.as_deref(), password, expires)?;
|
||||
CtlResponse::PublicLink { link }
|
||||
}
|
||||
CtlRequest::RemovePublicLink { path, id } => {
|
||||
remove_public_link(core, Target::path(core, mountpoint, path)?, &id)?
|
||||
}
|
||||
CtlRequest::RemovePublicLinkByUid { uid, id } => {
|
||||
remove_public_link(core, Target::uid(core, uid), &id)?
|
||||
}
|
||||
CtlRequest::StopSharing { path } => {
|
||||
stop_sharing(core, Target::path(core, mountpoint, path)?)
|
||||
}
|
||||
CtlRequest::StopSharingByUid { uid } => stop_sharing(core, Target::uid(core, uid)),
|
||||
CtlRequest::ListSharedWithMe => CtlResponse::Entries {
|
||||
entries: sharing.list_shared_with_me()?,
|
||||
},
|
||||
CtlRequest::ListSharedFolder { uid } => CtlResponse::Entries {
|
||||
entries: sharing.list_shared_folder(&uid)?,
|
||||
},
|
||||
CtlRequest::OpenSharedFile { uid } => CtlResponse::FilePath {
|
||||
path: sharing.open_shared_file(&uid)?.display().to_string(),
|
||||
},
|
||||
CtlRequest::LeaveShared { uid } => {
|
||||
sharing.leave_shared(&uid)?;
|
||||
core.log_activity(ActivityKind::Unshare, "shared item", "left", true);
|
||||
ok("left shared item")
|
||||
}
|
||||
CtlRequest::ListInvitations => CtlResponse::Invitations {
|
||||
items: sharing.list_invitations()?,
|
||||
},
|
||||
CtlRequest::AcceptInvitation { id } => {
|
||||
sharing.accept_invitation(&id)?;
|
||||
ok("invitation accepted")
|
||||
}
|
||||
CtlRequest::RejectInvitation { id } => {
|
||||
sharing.reject_invitation(&id)?;
|
||||
ok("invitation rejected")
|
||||
}
|
||||
CtlRequest::ListBookmarks => CtlResponse::Bookmarks {
|
||||
items: sharing.list_bookmarks()?,
|
||||
},
|
||||
CtlRequest::CreateBookmark { url, password } => {
|
||||
sharing.create_bookmark(&url, password.as_deref())?;
|
||||
ok("bookmark saved")
|
||||
}
|
||||
CtlRequest::DeleteBookmark { token } => {
|
||||
sharing.delete_bookmark(&token)?;
|
||||
ok("bookmark removed")
|
||||
}
|
||||
CtlRequest::ListSharedByMe => CtlResponse::SharedByMe {
|
||||
items: sharing.list_shared_by_me()?,
|
||||
},
|
||||
// `control` only hands over what `request!` matches.
|
||||
_ => CtlResponse::error(pdfs_core::CoreError::internal(
|
||||
"not a sharing request".to_string(),
|
||||
)),
|
||||
})
|
||||
}
|
||||
|
||||
fn ok(message: &str) -> CtlResponse {
|
||||
CtlResponse::Ok {
|
||||
message: message.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn role_updated(role: &str) -> CtlResponse {
|
||||
CtlResponse::Ok {
|
||||
message: format!("role updated to {role}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn share_node(
|
||||
core: &Core,
|
||||
target: Target,
|
||||
emails: &[String],
|
||||
role: &str,
|
||||
message: Option<String>,
|
||||
) -> CtlResponse {
|
||||
let shared = target.node.and_then(|uid| {
|
||||
core.sharing
|
||||
.share_node(&uid, emails, role, message.as_deref())
|
||||
});
|
||||
match shared {
|
||||
Ok((proton, external)) => {
|
||||
core.log_activity(
|
||||
ActivityKind::Share,
|
||||
&target.label,
|
||||
format!("{} recipient(s) as {role}", proton + external),
|
||||
true,
|
||||
);
|
||||
ok(&format!(
|
||||
"invited {proton} Proton and {external} external user(s)"
|
||||
))
|
||||
}
|
||||
Err(e) => {
|
||||
core.log_activity(ActivityKind::Share, &target.label, &e, false);
|
||||
CtlResponse::error(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_share(core: &Core, target: Target) -> CtlResponse {
|
||||
match target.node.and_then(|uid| core.sharing.list_share(&uid)) {
|
||||
Ok((entries, link)) => CtlResponse::Share { entries, link },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_share_entry(
|
||||
core: &Core,
|
||||
target: Target,
|
||||
id: &str,
|
||||
kind: pdfs_core::control::ShareEntryKind,
|
||||
) -> CoreResult<CtlResponse> {
|
||||
target
|
||||
.node
|
||||
.and_then(|uid| core.sharing.remove_share_entry(&uid, id, kind))?;
|
||||
core.log_activity(ActivityKind::Unshare, &target.label, "access removed", true);
|
||||
Ok(ok("removed"))
|
||||
}
|
||||
|
||||
fn create_public_link(
|
||||
core: &Core,
|
||||
target: Target,
|
||||
role: &str,
|
||||
password: Option<&str>,
|
||||
expires: Option<i64>,
|
||||
) -> CtlResponse {
|
||||
let created = target.node.and_then(|uid| {
|
||||
core.sharing
|
||||
.create_public_link(&uid, role, password, expires)
|
||||
});
|
||||
match created {
|
||||
Ok(link) => {
|
||||
core.log_activity(
|
||||
ActivityKind::PublicLink,
|
||||
&target.label,
|
||||
"link created",
|
||||
true,
|
||||
);
|
||||
CtlResponse::PublicLink { link }
|
||||
}
|
||||
Err(e) => {
|
||||
core.log_activity(ActivityKind::PublicLink, &target.label, &e, false);
|
||||
CtlResponse::error(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_public_link(core: &Core, target: Target, id: &str) -> CoreResult<CtlResponse> {
|
||||
target
|
||||
.node
|
||||
.and_then(|uid| core.sharing.remove_public_link(&uid, id))?;
|
||||
core.log_activity(ActivityKind::Unshare, &target.label, "link removed", true);
|
||||
Ok(ok("public link removed"))
|
||||
}
|
||||
|
||||
/// Log a stop-sharing request, and turn a partial removal into an error that
|
||||
/// names what is still shared.
|
||||
fn stop_sharing(core: &Core, target: Target) -> CtlResponse {
|
||||
let result: CoreResult<StopSharingOutcome> =
|
||||
target.node.and_then(|uid| core.sharing.stop_sharing(&uid));
|
||||
match result.map(|outcome| outcome.into_result()) {
|
||||
Ok(Ok(message)) => {
|
||||
core.log_activity(
|
||||
ActivityKind::Unshare,
|
||||
&target.label,
|
||||
"stopped sharing",
|
||||
true,
|
||||
);
|
||||
CtlResponse::Ok { message }
|
||||
}
|
||||
Ok(Err(left)) => {
|
||||
core.log_activity(ActivityKind::Unshare, &target.label, &left, false);
|
||||
CtlResponse::error(pdfs_core::CoreError::remote(left))
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
//! The control requests about synced folders and devices: adding, attaching, switching and removing folders, pausing, conflicts, the pending-change queue, and restoring a device's folders.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The requests [`answer`] serves, as a pattern, so the control socket's match
|
||||
/// hands exactly these over and the compiler still checks that it covers every
|
||||
/// request.
|
||||
macro_rules! request {
|
||||
() => {
|
||||
::pdfs_core::control::Request::ListDevices
|
||||
| ::pdfs_core::control::Request::ListLocations
|
||||
| ::pdfs_core::control::Request::RenameDevice { .. }
|
||||
| ::pdfs_core::control::Request::DeleteDevice { .. }
|
||||
| ::pdfs_core::control::Request::AdoptDevice { .. }
|
||||
| ::pdfs_core::control::Request::MigrateDevice { .. }
|
||||
| ::pdfs_core::control::Request::AddSyncFolder { .. }
|
||||
| ::pdfs_core::control::Request::AttachSyncFolder { .. }
|
||||
| ::pdfs_core::control::Request::ListSyncFolders
|
||||
| ::pdfs_core::control::Request::RemoveSyncFolder { .. }
|
||||
| ::pdfs_core::control::Request::SetSyncFolderMode { .. }
|
||||
| ::pdfs_core::control::Request::SetSyncFolderPaused { .. }
|
||||
| ::pdfs_core::control::Request::ResetSyncFolder { .. }
|
||||
| ::pdfs_core::control::Request::SyncNow { .. }
|
||||
| ::pdfs_core::control::Request::SetSyncPaused { .. }
|
||||
| ::pdfs_core::control::Request::ListConflicts
|
||||
| ::pdfs_core::control::Request::ResolveConflict { .. }
|
||||
| ::pdfs_core::control::Request::ListPendingOps
|
||||
| ::pdfs_core::control::Request::ExportPendingOp { .. }
|
||||
| ::pdfs_core::control::Request::DiscardPendingOp { .. }
|
||||
| ::pdfs_core::control::Request::RetryPendingOp { .. }
|
||||
| ::pdfs_core::control::Request::ListRestorableFolders
|
||||
| ::pdfs_core::control::Request::ListDeviceRestorableFolders { .. }
|
||||
| ::pdfs_core::control::Request::RestoreSyncFolders { .. }
|
||||
| ::pdfs_core::control::Request::RestoreDeviceFolders { .. }
|
||||
};
|
||||
}
|
||||
pub(super) use request;
|
||||
|
||||
/// Answer a request that [`request!`] matches.
|
||||
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
let Ask {
|
||||
core, mountpoint, ..
|
||||
} = *ask;
|
||||
match request {
|
||||
CtlRequest::ListDevices => match core.devices().list_devices() {
|
||||
Ok(items) => CtlResponse::Devices { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListLocations => match core.list_locations() {
|
||||
Ok(items) => CtlResponse::Locations { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RenameDevice { uid, name } => match core.devices().rename_device(&uid, &name) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: format!("renamed device to {name}"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::DeleteDevice { uid } => match core.devices().delete_device(&uid) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: "device deleted".to_string(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::AdoptDevice { uid } => match core.devices().adopt_device(uid.as_deref()) {
|
||||
Ok(message) => CtlResponse::Ok { message },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::MigrateDevice { uid } => match core.devices().migrate_device(&uid) {
|
||||
Ok(message) => CtlResponse::Ok { message },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::AddSyncFolder { local_path } => {
|
||||
// Registering the device and uploading a folder tree far outlasts the
|
||||
// socket read timeout, so ack immediately and work on a background
|
||||
// thread. The folder appears in ListSyncFolders once the row lands;
|
||||
// completion (and any failures) go to the activity log.
|
||||
let core = core.clone();
|
||||
let path = PathBuf::from(&local_path);
|
||||
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.profile().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);
|
||||
}
|
||||
}
|
||||
})
|
||||
{
|
||||
tracing::warn!(%error, "could not start pdfs-add-sync-folder");
|
||||
}
|
||||
CtlResponse::Ok {
|
||||
message: format!("adding {local_path}"),
|
||||
}
|
||||
}
|
||||
CtlRequest::AttachSyncFolder {
|
||||
local_path,
|
||||
remote_path,
|
||||
} => {
|
||||
let result = rel_to_mount(mountpoint, &remote_path).and_then(|remote| {
|
||||
core.attach_sync_folder(Path::new(&local_path), &remote, mountpoint)
|
||||
});
|
||||
match result {
|
||||
Ok(folder) => CtlResponse::Ok {
|
||||
message: format!("sync folder {} attached: {}", folder.id, folder.local_path),
|
||||
},
|
||||
Err(error) => CtlResponse::error(error),
|
||||
}
|
||||
}
|
||||
CtlRequest::ListSyncFolders => match core.list_sync_folders() {
|
||||
Ok(items) => CtlResponse::SyncFolders { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RemoveSyncFolder { id, delete_remote } => {
|
||||
match core.remove_sync_folder(id, delete_remote) {
|
||||
Ok(None) => {
|
||||
core.profile().touch_profile();
|
||||
CtlResponse::Ok {
|
||||
message: if delete_remote {
|
||||
"removed synced folder and moved its folder in Proton Drive to the trash"
|
||||
} else {
|
||||
"removed synced folder"
|
||||
}
|
||||
.to_string(),
|
||||
}
|
||||
}
|
||||
// The folder no longer syncs, but its copy in Proton Drive is
|
||||
// still there. That is not what was asked, so it is an error,
|
||||
// and the message says which half happened.
|
||||
Ok(Some(trash_error)) => {
|
||||
core.profile().touch_profile();
|
||||
CtlResponse::error(CoreError::remote(format!(
|
||||
"stopped syncing the folder, but its folder in Proton Drive was not moved to the trash: {trash_error}"
|
||||
)))
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::SetSyncFolderMode { id, mode } => {
|
||||
match core.request_sync_folder_mode(id, &mode) {
|
||||
Ok(message) => {
|
||||
core.profile().touch_profile();
|
||||
core.log_activity(ActivityKind::Upload, &message, "", true);
|
||||
CtlResponse::Ok { message }
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::SetSyncFolderPaused { id, paused } => {
|
||||
match core.set_sync_folder_paused(id, paused) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: match paused {
|
||||
true => format!("folder {id} paused"),
|
||||
false => format!("folder {id} resumed"),
|
||||
},
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::ResetSyncFolder { id } => match core.reset_sync_folder(id) {
|
||||
Ok(message) => {
|
||||
core.log_activity(ActivityKind::Sync, &message, "", true);
|
||||
CtlResponse::Ok { message }
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::SyncNow { id } => {
|
||||
core.sync_now(id);
|
||||
CtlResponse::Ok {
|
||||
message: match id {
|
||||
Some(id) => format!("reconciling folder {id}"),
|
||||
None => "reconciling all folders".to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
CtlRequest::SetSyncPaused { paused, until } => match core.set_sync_paused(paused, until) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: match (paused, until) {
|
||||
(false, _) => "sync resumed".to_string(),
|
||||
(true, None) => "sync paused until resumed".to_string(),
|
||||
(true, Some(_)) => "sync paused".to_string(),
|
||||
},
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListConflicts => match core.list_conflicts() {
|
||||
Ok(items) => CtlResponse::Conflicts { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ResolveConflict { path, keep } => match route_change(core, mountpoint, &path) {
|
||||
Ok((core, rel)) => match core.resolve_conflict(&rel, &keep) {
|
||||
Ok(message) => CtlResponse::Ok { message },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListPendingOps => match core.pending_op_infos() {
|
||||
Ok(items) => CtlResponse::PendingOps { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ExportPendingOp { id, dest } => {
|
||||
match core.export_pending_op(id, Path::new(&dest)) {
|
||||
Ok(written) => CtlResponse::Ok {
|
||||
message: format!("wrote {} to {dest}", human_bytes(written)),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::DiscardPendingOp { id } => match core.discard_pending_op(id) {
|
||||
Ok(path) => CtlResponse::Ok {
|
||||
message: format!("discarded the queued change to {path}"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RetryPendingOp { id } => match core.retry_pending_ops(id) {
|
||||
Ok(0) if id.is_some() => CtlResponse::Ok {
|
||||
message: "nothing to retry: the operation is already due or waiting for a rename"
|
||||
.to_string(),
|
||||
},
|
||||
Ok(moved) => CtlResponse::Ok {
|
||||
message: format!("retrying {moved} queued operation(s) now"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListRestorableFolders => match core.profile().list_restorable_folders(None) {
|
||||
Ok(items) => CtlResponse::RestorableFolders { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListDeviceRestorableFolders { device } => {
|
||||
match core.profile().list_restorable_folders(Some(&device)) {
|
||||
Ok(items) => CtlResponse::RestorableFolders { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
request @ (CtlRequest::RestoreSyncFolders { .. }
|
||||
| CtlRequest::RestoreDeviceFolders { .. }) => {
|
||||
let (device, items) = match request {
|
||||
CtlRequest::RestoreDeviceFolders { device, items } => (Some(device), items),
|
||||
CtlRequest::RestoreSyncFolders { items } => (None, items),
|
||||
_ => unreachable!("matched above"),
|
||||
};
|
||||
// Like AddSyncFolder: each restored folder downloads a whole tree,
|
||||
// which outlasts the socket timeout. Ack, then work.
|
||||
let core = core.clone();
|
||||
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.profile().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,
|
||||
);
|
||||
}
|
||||
}
|
||||
})
|
||||
{
|
||||
tracing::warn!(%error, "could not start pdfs-restore-sync-folders");
|
||||
}
|
||||
CtlResponse::Ok {
|
||||
message: "restoring folders".to_string(),
|
||||
}
|
||||
}
|
||||
// `control` only hands over what `request!` matches.
|
||||
_ => CtlResponse::error(CoreError::internal("not a sync request".to_string())),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//! The control requests about Drive's trash and the local content cache.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The requests [`answer`] serves, as a pattern, so the control socket's match
|
||||
/// hands exactly these over and the compiler still checks that it covers every
|
||||
/// request.
|
||||
macro_rules! request {
|
||||
() => {
|
||||
::pdfs_core::control::Request::ListTrash
|
||||
| ::pdfs_core::control::Request::ListTrashedFolder { .. }
|
||||
| ::pdfs_core::control::Request::Restore { .. }
|
||||
| ::pdfs_core::control::Request::DeleteForever { .. }
|
||||
| ::pdfs_core::control::Request::EmptyTrash
|
||||
| ::pdfs_core::control::Request::PurgeCache
|
||||
| ::pdfs_core::control::Request::CacheInspect { .. }
|
||||
| ::pdfs_core::control::Request::CacheVacuum
|
||||
| ::pdfs_core::control::Request::SetCacheBudget { .. }
|
||||
};
|
||||
}
|
||||
pub(super) use request;
|
||||
|
||||
/// Answer a request that [`request!`] matches.
|
||||
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
let Ask { core, .. } = *ask;
|
||||
match request {
|
||||
CtlRequest::ListTrash => match core.trash().list_trash() {
|
||||
Ok(entries) => CtlResponse::Entries { entries },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListTrashedFolder { uid } => match core.trash().list_trashed_folder(&uid) {
|
||||
Ok(entries) => CtlResponse::Entries { entries },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::Restore { uids } => match core.trash().restore(&uids) {
|
||||
Ok(n) => {
|
||||
core.log_activity(ActivityKind::Restore, format!("{n} item(s)"), "", true);
|
||||
CtlResponse::Ok {
|
||||
message: format!("restored {n} item(s)"),
|
||||
}
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::DeleteForever { uids } => match core.trash().delete_forever(&uids) {
|
||||
Ok(n) => {
|
||||
core.log_activity(
|
||||
ActivityKind::DeleteForever,
|
||||
format!("{n} item(s)"),
|
||||
"",
|
||||
true,
|
||||
);
|
||||
CtlResponse::Ok {
|
||||
message: format!("permanently deleted {n} item(s)"),
|
||||
}
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::EmptyTrash => match core.trash().empty_trash() {
|
||||
Ok(n) => {
|
||||
let items = if n == 1 {
|
||||
"1 item".to_string()
|
||||
} else {
|
||||
format!("{n} items")
|
||||
};
|
||||
core.log_activity(ActivityKind::EmptyTrash, items.clone(), "", true);
|
||||
CtlResponse::Ok {
|
||||
message: format!("emptied trash ({items})"),
|
||||
}
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PurgeCache => {
|
||||
let freed = core.cache.clear_unpinned();
|
||||
CtlResponse::Ok {
|
||||
message: format!(
|
||||
"purged {:.1} MiB of unpinned cache",
|
||||
freed as f64 / 1_048_576.0
|
||||
),
|
||||
}
|
||||
}
|
||||
CtlRequest::CacheInspect { deep } => match core.db.stats() {
|
||||
Ok(stats) => {
|
||||
// The deep check reads every page — tens of seconds on a real
|
||||
// database, all of it holding the connection every FUSE handler
|
||||
// needs — so it runs on a thread and this request returns
|
||||
// whatever the last completed check found. `integrity_checked`
|
||||
// tells the caller which answer it is holding, since "no
|
||||
// problems found" and "never looked" are both an empty list;
|
||||
// `integrity_running` says a fresh answer is on its way.
|
||||
let (integrity_problems, integrity_checked, integrity_running) = if deep {
|
||||
core.maintenance.start_or_read_integrity_check()
|
||||
} else {
|
||||
(Vec::new(), false, false)
|
||||
};
|
||||
CtlResponse::CacheReport {
|
||||
integrity_running,
|
||||
schema_version: stats.schema_version,
|
||||
db_bytes: stats.total_bytes(),
|
||||
db_reclaimable_bytes: stats.reclaimable_bytes(),
|
||||
tables: stats.tables,
|
||||
cache_used: core.cache.usage(),
|
||||
cache_budget: core.cache.budget(),
|
||||
integrity_problems,
|
||||
integrity_checked,
|
||||
}
|
||||
}
|
||||
Err(e) => CtlResponse::error(CoreError::internal(format!("read db stats: {e:?}"))),
|
||||
},
|
||||
CtlRequest::CacheVacuum => match core.maintenance.start_vacuum() {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: "compacting the cache database in the background".into(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::SetCacheBudget { bytes } => {
|
||||
core.cache.set_budget(bytes);
|
||||
// Persist so the next mount keeps the new cap. Best-effort: a config
|
||||
// write failure is reported but the live cap is already applied.
|
||||
match AppDirs::new()
|
||||
.map(|dirs| dirs.update_config(|cfg| cfg.cache_budget = Some(bytes)))
|
||||
{
|
||||
Ok(Ok(())) => {
|
||||
core.profile().touch_profile();
|
||||
CtlResponse::Ok {
|
||||
message: format!("cache budget set to {bytes} bytes"),
|
||||
}
|
||||
}
|
||||
Ok(Err(e)) => CtlResponse::error(CoreError::internal(format!(
|
||||
"budget applied but config write failed: {e}"
|
||||
))),
|
||||
Err(e) => CtlResponse::error(CoreError::internal(format!(
|
||||
"budget applied but config unavailable: {e}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
// `control` only hands over what `request!` matches.
|
||||
_ => CtlResponse::error(CoreError::internal("not a trash request".to_string())),
|
||||
}
|
||||
}
|
||||
+127
-46
@@ -9,7 +9,6 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::batch;
|
||||
@@ -21,9 +20,9 @@ use pdfs_core::mounts::MountMode;
|
||||
use pdfs_core::profile::PROFILE_DIR_NAME;
|
||||
use pdfs_core::{CoreError, CoreResult};
|
||||
use pdfs_store::db::{StoredDevice, StoredSyncFolder};
|
||||
use proton_drive_rs::proton_sdk::error::ProtonError;
|
||||
use proton_drive_rs::proton_sdk::ids::{DeviceUid, NodeUid};
|
||||
use proton_drive_rs::{DeviceType, Node};
|
||||
use std::sync::OnceLock;
|
||||
use tracing::{info, warn};
|
||||
|
||||
use super::sync::{self, base_name};
|
||||
@@ -148,28 +147,70 @@ fn migrated_name(name: &str, device: &str, taken: &[String]) -> Option<String> {
|
||||
.find(|candidate| free(candidate))
|
||||
}
|
||||
|
||||
impl Core {
|
||||
// ---- devices ----------------------------------------------------------
|
||||
/// This account's devices on Drive, and which one is this computer: listing,
|
||||
/// renaming, deleting, adopting and migrating them, and registering this one.
|
||||
///
|
||||
/// It reaches the rest of the daemon through [`DevicesHost`]. [`Core::devices`]
|
||||
/// builds one on demand with the daemon as its host.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Devices {
|
||||
client: proton_drive_rs::ProtonDriveClient,
|
||||
drive: std::sync::Arc<dyn crate::drive::DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
db: std::sync::Arc<pdfs_store::db::Db>,
|
||||
host: std::sync::Arc<dyn DevicesHost>,
|
||||
}
|
||||
|
||||
/// Unified local-location listing for the control protocol.
|
||||
pub(crate) fn list_locations(&self) -> CoreResult<Vec<MountSpec>> {
|
||||
let progress = self.sync.progress.lock();
|
||||
let mut locations = self
|
||||
.db
|
||||
.mount_list()
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
|
||||
for location in &mut locations {
|
||||
location.mounted = self.states.is_mounted_at(Path::new(&location.local_path));
|
||||
if let MountKind::Device { sync_folder_id } | MountKind::Attached { sync_folder_id } =
|
||||
&location.kind
|
||||
{
|
||||
location.progress = progress.get(sync_folder_id).cloned();
|
||||
location.paused = self.sync_folder_paused(*sync_folder_id);
|
||||
}
|
||||
}
|
||||
Ok(locations)
|
||||
/// What [`Devices`] needs from the rest of the daemon, to migrate a device's
|
||||
/// folders onto this one.
|
||||
pub(crate) trait DevicesHost: Send + Sync {
|
||||
/// Move a node under `parent` on the server, renaming it to `name` if
|
||||
/// given, and update the tree to match.
|
||||
fn move_node(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
parent: &NodeUid,
|
||||
name: Option<&str>,
|
||||
) -> Result<(), ProtonError>;
|
||||
/// Run a sync pass for one synced folder now.
|
||||
fn sync_now(&self, id: Option<i64>);
|
||||
/// Re-enumerate a folder's children on next access.
|
||||
fn invalidate_children_of(&self, parent: &NodeUid);
|
||||
}
|
||||
|
||||
impl DevicesHost for Core {
|
||||
fn move_node(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
parent: &NodeUid,
|
||||
name: Option<&str>,
|
||||
) -> Result<(), ProtonError> {
|
||||
self.move_rename_remote(uid, parent, name)
|
||||
}
|
||||
|
||||
fn sync_now(&self, id: Option<i64>) {
|
||||
Core::sync_now(self, id);
|
||||
}
|
||||
|
||||
fn invalidate_children_of(&self, parent: &NodeUid) {
|
||||
Core::invalidate_children_of(self, parent);
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// The devices service, with this daemon as its host.
|
||||
pub(crate) fn devices(&self) -> Devices {
|
||||
Devices {
|
||||
client: self.client.clone(),
|
||||
drive: self.drive.clone(),
|
||||
rt: self.rt.clone(),
|
||||
db: self.db.clone(),
|
||||
host: std::sync::Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Devices {
|
||||
/// List the account's registered devices, flagging the one *this* machine
|
||||
/// syncs to so a front-end can treat it as more than another computer in the
|
||||
/// list — deleting it takes this machine's synced folders down with it.
|
||||
@@ -356,7 +397,10 @@ impl Core {
|
||||
continue;
|
||||
}
|
||||
let new_name = migrated_name(&node.name, &source.name, &taken);
|
||||
if let Err(e) = self.move_rename_remote(&node.uid, &target_root, new_name.as_deref()) {
|
||||
if let Err(e) = self
|
||||
.host
|
||||
.move_node(&node.uid, &target_root, new_name.as_deref())
|
||||
{
|
||||
warn!(name = %node.name, error = %e, "migrate: could not move folder");
|
||||
failed.push(format!("{}: {e}", node.name));
|
||||
continue;
|
||||
@@ -373,11 +417,11 @@ impl Core {
|
||||
if let Err(e) = self.db.sync_folder_set_share(folder.id, &target.share_id) {
|
||||
warn!(id = folder.id, error = ?e, "migrate: could not re-point sync folder");
|
||||
}
|
||||
self.sync_now(Some(folder.id));
|
||||
self.host.sync_now(Some(folder.id));
|
||||
}
|
||||
}
|
||||
self.invalidate_children_of(&source_root);
|
||||
self.invalidate_children_of(&target_root);
|
||||
self.host.invalidate_children_of(&source_root);
|
||||
self.host.invalidate_children_of(&target_root);
|
||||
|
||||
let mut message = format!("moved {moved} folder(s) from {}", source.name);
|
||||
if !renamed.is_empty() {
|
||||
@@ -397,8 +441,6 @@ impl Core {
|
||||
Ok(message)
|
||||
}
|
||||
|
||||
// ---- device folder sync -------------------------
|
||||
|
||||
/// Auto-register (or recover) this machine as a Proton Drive Device, caching
|
||||
/// it so restarts reuse the same device. Recovery matches an existing remote
|
||||
/// Linux device by name before creating a new one, so a lost local record
|
||||
@@ -505,7 +547,7 @@ impl Core {
|
||||
}
|
||||
|
||||
/// Everything directly under a device root, trashed nodes included.
|
||||
pub(super) fn device_root_nodes(&self, root_uid: &NodeUid) -> CoreResult<Vec<Node>> {
|
||||
pub(crate) fn device_root_nodes(&self, root_uid: &NodeUid) -> CoreResult<Vec<Node>> {
|
||||
let uids = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_folder_children_node_uids(root_uid))
|
||||
@@ -517,6 +559,31 @@ impl Core {
|
||||
.block_on(self.drive.enumerate_nodes(&uids))
|
||||
.map_err(|e| CoreError::from_api(&e, "resolve device root children"))
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
// ---- devices ----------------------------------------------------------
|
||||
|
||||
/// Unified local-location listing for the control protocol.
|
||||
pub(crate) fn list_locations(&self) -> CoreResult<Vec<MountSpec>> {
|
||||
let progress = self.sync.progress.lock();
|
||||
let mut locations = self
|
||||
.db
|
||||
.mount_list()
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
|
||||
for location in &mut locations {
|
||||
location.mounted = self.states.is_mounted_at(Path::new(&location.local_path));
|
||||
if let MountKind::Device { sync_folder_id } | MountKind::Attached { sync_folder_id } =
|
||||
&location.kind
|
||||
{
|
||||
location.progress = progress.get(sync_folder_id).cloned();
|
||||
location.paused = self.sync_folder_paused(*sync_folder_id);
|
||||
}
|
||||
}
|
||||
Ok(locations)
|
||||
}
|
||||
|
||||
// ---- device folder sync -------------------------
|
||||
|
||||
/// Add a local folder to this device's sync set: register the device if
|
||||
/// needed, create a matching folder under the device root, upload the local
|
||||
@@ -570,7 +637,7 @@ impl Core {
|
||||
)));
|
||||
}
|
||||
|
||||
let device = self.ensure_device()?;
|
||||
let device = self.devices().ensure_device()?;
|
||||
let root_uid = parse_uid(&device.root_uid).ok_or_else(|| {
|
||||
CoreError::internal(format!("bad device root uid: {}", device.root_uid))
|
||||
})?;
|
||||
@@ -582,7 +649,7 @@ impl Core {
|
||||
// original, not leave the user with two "Downloads" in their Drive. The
|
||||
// reconcile treats an existing remote tree correctly: unmatched paths read as
|
||||
// a conflict, not as data loss.
|
||||
let remote_root = match self.find_device_child_folder(&root_uid, &name)? {
|
||||
let remote_root = match self.devices().find_device_child_folder(&root_uid, &name)? {
|
||||
Some(uid) => {
|
||||
info!(name, "reusing existing device folder");
|
||||
uid
|
||||
@@ -698,9 +765,18 @@ impl Core {
|
||||
jobs
|
||||
}
|
||||
|
||||
/// Remove a synced folder from the sync set. `delete_remote` also deletes its
|
||||
/// folder under the device root; otherwise the cloud copy is left in place.
|
||||
pub(crate) fn remove_sync_folder(&self, id: i64, delete_remote: bool) -> CoreResult<()> {
|
||||
/// Remove a synced folder from the sync set. `delete_remote` also moves its
|
||||
/// folder under the device root to the trash; otherwise the cloud copy is
|
||||
/// left in place.
|
||||
///
|
||||
/// The folder is out of the sync set before the trash is asked, so a trash
|
||||
/// that fails does not fail the removal. It comes back as `Some(error)`,
|
||||
/// for the caller to say that the cloud copy is still there.
|
||||
pub(crate) fn remove_sync_folder(
|
||||
&self,
|
||||
id: i64,
|
||||
delete_remote: bool,
|
||||
) -> CoreResult<Option<String>> {
|
||||
let lock = self.sync.lock(id);
|
||||
// A pass holds the lock for as long as it runs, hours on a large
|
||||
// folder. Ask it to stop at its next checkpoint rather than wait it
|
||||
@@ -756,16 +832,24 @@ impl Core {
|
||||
self.clear_sync_folder_paused(id);
|
||||
// Stop watching the folder we just dropped.
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
|
||||
if delete_remote
|
||||
&& let Some(uid) = parse_uid(&folder.remote_uid)
|
||||
&& let Err(e) = self
|
||||
.rt
|
||||
.block_on(self.drive.trash_nodes(&[uid]))
|
||||
.and_then(batch::into_unit)
|
||||
if !delete_remote {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(uid) = parse_uid(&folder.remote_uid) else {
|
||||
warn!(id, remote = %folder.remote_uid, "delete remote device folder: bad uid");
|
||||
return Ok(Some(format!("bad folder id {}", folder.remote_uid)));
|
||||
};
|
||||
match self
|
||||
.rt
|
||||
.block_on(self.drive.trash_nodes(&[uid]))
|
||||
.and_then(batch::into_unit)
|
||||
{
|
||||
warn!(id, error = %e, "delete remote device folder failed");
|
||||
Ok(()) => Ok(None),
|
||||
Err(e) => {
|
||||
warn!(id, error = %e, "delete remote device folder failed");
|
||||
Ok(Some(e.to_string()))
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Trigger a reconcile: one folder by id, or every folder when `id` is `None`.
|
||||
@@ -782,10 +866,7 @@ impl Core {
|
||||
/// kernel channel, both filled in when the session is built.
|
||||
pub(crate) fn fork_state(&self) -> Core {
|
||||
let mut fork = self.clone();
|
||||
fork.primary = false;
|
||||
fork.root = Arc::new(OnceLock::new());
|
||||
fork.notifier = Arc::new(OnceLock::new());
|
||||
fork.session_live = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
fork.session = self.session.fork();
|
||||
fork
|
||||
}
|
||||
|
||||
@@ -1173,7 +1254,7 @@ impl Core {
|
||||
root: Node,
|
||||
) -> CoreResult<SecondaryMount> {
|
||||
let core = self.fork_state();
|
||||
let session_live = core.session_live.clone();
|
||||
let session_live = core.session.session_live.clone();
|
||||
// The fork owns this state/path registration. `spawn_session` only
|
||||
// marks it live after FUSE has spawned successfully.
|
||||
core.register_state(local);
|
||||
|
||||
@@ -18,7 +18,14 @@ use std::sync::{Arc, LazyLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::control::{Diagnostics, DriveCallStat, InflightRequest, ServiceState, WorkerState};
|
||||
use pdfs_core::control::{
|
||||
AdmissionLoad, Diagnostics, DriveCallStat, EffectIntent, EffectReport, InflightRequest,
|
||||
ServiceState, UploadPathStat, WorkerState,
|
||||
};
|
||||
|
||||
use pdfs_core::lifecycle::ServiceBoard;
|
||||
use pdfs_core::timestamp::now_secs;
|
||||
use pdfs_store::db::StoredIntent;
|
||||
|
||||
use super::Core;
|
||||
|
||||
@@ -141,6 +148,7 @@ impl Core {
|
||||
})
|
||||
.unwrap_or_default();
|
||||
inflight.sort_by_key(|request| std::cmp::Reverse(request.age_secs));
|
||||
let (pending_ops, effects) = self.database_quickly().unzip();
|
||||
|
||||
Diagnostics {
|
||||
uptime_secs: STARTED.elapsed().as_secs(),
|
||||
@@ -162,7 +170,8 @@ impl Core {
|
||||
inflight,
|
||||
control_handlers: super::control::active_handlers(),
|
||||
control_handler_limit: super::control::handler_limit(),
|
||||
pending_ops: self.pending_ops_quickly(),
|
||||
pending_ops,
|
||||
effects,
|
||||
sync: Some(self.sync.engine.report()),
|
||||
services: self
|
||||
.services
|
||||
@@ -174,6 +183,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()
|
||||
@@ -186,29 +205,89 @@ impl Core {
|
||||
longest_ms: u64::try_from(stat.longest.as_millis()).unwrap_or(u64::MAX),
|
||||
})
|
||||
.collect(),
|
||||
upload_paths: pdfs_core::uploads::UPLOAD_PATHS
|
||||
.snapshot()
|
||||
.into_iter()
|
||||
.map(|stat| UploadPathStat {
|
||||
path: stat.path.to_owned(),
|
||||
count: stat.count,
|
||||
errors: stat.errors,
|
||||
total_ms: stat.total_ms,
|
||||
longest_ms: stat.longest_ms,
|
||||
})
|
||||
.collect(),
|
||||
admission: self
|
||||
.sync
|
||||
.admission
|
||||
.load()
|
||||
.into_iter()
|
||||
.map(|load| AdmissionLoad {
|
||||
class: load.class.name().to_owned(),
|
||||
running: load.running,
|
||||
waiting: load.waiting,
|
||||
oldest_wait_ms: load.oldest_wait.map(millis),
|
||||
admitted: load.admitted,
|
||||
waited_ms: millis(load.waited),
|
||||
longest_wait_ms: millis(load.longest_wait),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Queued mutations, or `None` when the database did not answer within
|
||||
/// [`PENDING_COUNT_DEADLINE`] or an earlier probe is still waiting on it.
|
||||
/// Queued mutations and the mirror effects not settled yet, or `None`
|
||||
/// when the database did not answer within [`DATABASE_DEADLINE`] or an
|
||||
/// earlier probe is still waiting on it.
|
||||
///
|
||||
/// The supervisor asks for a report every tick. One thread per report
|
||||
/// would pile up behind a database that never answers, so a second probe
|
||||
/// is not started until the first one has returned.
|
||||
fn pending_ops_quickly(&self) -> Option<u64> {
|
||||
fn database_quickly(&self) -> Option<(u64, EffectReport)> {
|
||||
let db = self.db.clone();
|
||||
probe_once(&self.pending_probe, PENDING_COUNT_DEADLINE, move || {
|
||||
let counts = db.pending_op_counts().ok()?;
|
||||
Some(counts.uploads.max(0) as u64 + counts.changes.max(0) as u64)
|
||||
})
|
||||
probe_once(
|
||||
&self.services,
|
||||
&self.pending_probe,
|
||||
DATABASE_DEADLINE,
|
||||
move || {
|
||||
let counts = db.pending_op_counts().ok()?;
|
||||
let pending = counts.uploads.max(0) as u64 + counts.changes.max(0) as u64;
|
||||
let intents = db.sync_intents(None).ok()?;
|
||||
Some((pending, effect_report(intents, now_secs())))
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The report of the unsettled `intents`, oldest first, at `now`.
|
||||
fn effect_report(mut intents: Vec<StoredIntent>, now: i64) -> EffectReport {
|
||||
intents.sort_by_key(|intent| (intent.issued_at, intent.id));
|
||||
EffectReport {
|
||||
count: intents.len(),
|
||||
oldest: intents
|
||||
.into_iter()
|
||||
.take(EffectReport::SHOWN)
|
||||
.map(|intent| EffectIntent {
|
||||
folder_id: intent.folder_id,
|
||||
rel_path: intent.rel_path,
|
||||
kind: intent.kind,
|
||||
state: intent.state,
|
||||
attempts: intent.attempts,
|
||||
age_secs: u64::try_from(now - intent.issued_at).unwrap_or(0),
|
||||
last_error: intent.last_error,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn millis(took: Duration) -> u64 {
|
||||
u64::try_from(took.as_millis()).unwrap_or(u64::MAX)
|
||||
}
|
||||
|
||||
/// Run `probe` on a thread of its own and wait up to `deadline` for it.
|
||||
///
|
||||
/// `None` when it did not answer in time, or when the previous probe sharing
|
||||
/// `busy` has not returned yet: then no new thread is started at all.
|
||||
fn probe_once<T: Send + 'static>(
|
||||
board: &ServiceBoard,
|
||||
busy: &Arc<AtomicBool>,
|
||||
deadline: Duration,
|
||||
probe: impl FnOnce() -> Option<T> + Send + 'static,
|
||||
@@ -218,13 +297,11 @@ fn probe_once<T: Send + 'static>(
|
||||
}
|
||||
let done = Arc::clone(busy);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("pdfs-diagnostics".into())
|
||||
.spawn(move || {
|
||||
let answer = probe();
|
||||
done.store(false, Ordering::Release);
|
||||
let _ = tx.send(answer);
|
||||
});
|
||||
let spawned = board.spawn_job("pdfs-diagnostics", move || {
|
||||
let answer = probe();
|
||||
done.store(false, Ordering::Release);
|
||||
let _ = tx.send(answer);
|
||||
});
|
||||
if spawned.is_err() {
|
||||
busy.store(false, Ordering::Release);
|
||||
return None;
|
||||
@@ -233,12 +310,49 @@ fn probe_once<T: Send + 'static>(
|
||||
}
|
||||
|
||||
/// How long the report waits for the database before reporting without it.
|
||||
const PENDING_COUNT_DEADLINE: Duration = Duration::from_millis(500);
|
||||
const DATABASE_DEADLINE: Duration = Duration::from_millis(500);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The report counts every unsettled effect but lists only the oldest,
|
||||
/// so a folder with thousands of failed uploads stays readable.
|
||||
#[test]
|
||||
fn the_effect_report_lists_the_oldest_and_counts_them_all() {
|
||||
let intent = |id: i64, issued_at: i64| StoredIntent {
|
||||
id,
|
||||
folder_id: 1,
|
||||
rel_path: format!("f{id}"),
|
||||
kind: "trash".into(),
|
||||
state: "retry".into(),
|
||||
attempts: 2,
|
||||
issued_at,
|
||||
last_error: Some("offline".into()),
|
||||
sent_sha1s: Vec::new(),
|
||||
};
|
||||
let total = EffectReport::SHOWN as i64 + 5;
|
||||
let intents = (0..total).map(|id| intent(id, 1_000 - id)).collect();
|
||||
let report = effect_report(intents, 1_100);
|
||||
assert_eq!(report.count, total as usize);
|
||||
assert_eq!(report.oldest.len(), EffectReport::SHOWN);
|
||||
let first = &report.oldest[0];
|
||||
assert_eq!(first.rel_path, format!("f{}", total - 1));
|
||||
assert_eq!(first.age_secs, 100 + total as u64 - 1);
|
||||
assert_eq!(first.last_error.as_deref(), Some("offline"));
|
||||
assert!(
|
||||
report
|
||||
.oldest
|
||||
.windows(2)
|
||||
.all(|pair| pair[0].age_secs >= pair[1].age_secs)
|
||||
);
|
||||
// A clock that went back reads as just sent, not as a wrap.
|
||||
assert_eq!(
|
||||
effect_report(vec![intent(1, 2_000)], 1_000).oldest[0].age_secs,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
/// The request name is read off the wire format, so it must match both
|
||||
/// shapes serde produces.
|
||||
#[test]
|
||||
@@ -300,11 +414,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_stuck_probe_is_not_started_again() {
|
||||
let board = ServiceBoard::default();
|
||||
let busy = Arc::new(AtomicBool::new(false));
|
||||
let (release, wait) = std::sync::mpsc::channel::<()>();
|
||||
let short = Duration::from_millis(50);
|
||||
|
||||
let stuck = probe_once(&busy, short, move || {
|
||||
let stuck = probe_once(&board, &busy, short, move || {
|
||||
let _ = wait.recv();
|
||||
Some(1)
|
||||
});
|
||||
@@ -312,7 +427,7 @@ mod tests {
|
||||
|
||||
let started = Arc::new(AtomicBool::new(false));
|
||||
let flag = Arc::clone(&started);
|
||||
let second = probe_once(&busy, short, move || {
|
||||
let second = probe_once(&board, &busy, short, move || {
|
||||
flag.store(true, Ordering::SeqCst);
|
||||
Some(2)
|
||||
});
|
||||
@@ -329,7 +444,7 @@ mod tests {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert_eq!(
|
||||
probe_once(&busy, Duration::from_secs(10), || Some(3)),
|
||||
probe_once(&board, &busy, Duration::from_secs(10), || Some(3)),
|
||||
Some(3)
|
||||
);
|
||||
}
|
||||
|
||||
+67
-1916
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,840 @@
|
||||
//! 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 (`WriteState::note_echo`).
|
||||
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.writes.hidden();
|
||||
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.photos().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.writes.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.open.writers_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 placeholder as the tree has it, before the landed node replaces
|
||||
// it: the base of a write that opened over it (`placeholder_base`).
|
||||
let mut placeholder = None;
|
||||
// The rows and queued ops already follow the node: `retire_create`
|
||||
// moved its row to the real uid, and ops find it by local id.
|
||||
|
||||
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());
|
||||
if let Some(e) = st.entries.get(&ino)
|
||||
&& node_revision_id(&e.node).is_none()
|
||||
{
|
||||
placeholder.get_or_insert((e.node.modification_time, node_size(&e.node)));
|
||||
}
|
||||
let mut landed = node.clone();
|
||||
st.keep_open_write_size(ino, &mut landed);
|
||||
if let Some(e) = st.entries.get_mut(&ino) {
|
||||
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");
|
||||
}
|
||||
// A release that took its handle out of the tree before the rebase
|
||||
// below and queues after `rebaseline_pending` is caught by neither,
|
||||
// and an incomplete write does not chain onto our own revision. Its
|
||||
// base is the placeholder, whose bytes the create sent.
|
||||
if let Some((mtime, size)) = placeholder
|
||||
&& mtime != remote.modification_time
|
||||
&& size == node_size(&remote)
|
||||
&& let Some(rev) = node_revision_id(&remote)
|
||||
{
|
||||
self.drain.placeholders.lock().insert(
|
||||
real.clone(),
|
||||
Baseline {
|
||||
mtime,
|
||||
size,
|
||||
hash: None,
|
||||
revision_id: Some(rev),
|
||||
},
|
||||
);
|
||||
}
|
||||
self.rebase_open_writes(real, &remote);
|
||||
// A write carried over from the create was made against no revision at
|
||||
// all; the one just created is what it now replaces.
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,706 @@
|
||||
//! 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 placeholder = self.drain.placeholders.lock().get(uid).cloned();
|
||||
let base = &placeholder_base(base, placeholder.as_ref());
|
||||
let Some(reason) = revision_changed(base, &node) else {
|
||||
return Ok(None);
|
||||
};
|
||||
// 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.photos().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.photos().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);
|
||||
}
|
||||
// This upload went after any write based on the create's placeholder.
|
||||
self.drain.placeholders.lock().remove(uid);
|
||||
let node = match fetched {
|
||||
Ok(Some(node)) => node,
|
||||
// Trashed or deleted under us: the tree will hear it from the event
|
||||
// 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 (`WriteState::note_echo`).
|
||||
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.open.writers_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.writes.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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
//! 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.withdraw_landed(&twin);
|
||||
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.drain.placeholders.lock().remove(&uid);
|
||||
self.invalidate_trash();
|
||||
self.log_activity(ActivityKind::Trash, &name, "trashed", true);
|
||||
info!(%uid, name, "pending trash landed");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Take a node a withdrawn create made on Drive out of every listing.
|
||||
///
|
||||
/// Hiding keeps it out of listings from now on, not out of one taken while
|
||||
/// Drive listed it and the drain still waited for the answer. A file made
|
||||
/// under the name then opened the node being trashed, and every write to
|
||||
/// it was refused with EACCES (`docs/BUGS.md` B303).
|
||||
fn withdraw_landed(&self, uid: &NodeUid) {
|
||||
self.writes.hide(uid);
|
||||
self.for_each_mount(|st, notify| {
|
||||
if let Some((parent, name)) = st.forget_or_unlink(uid) {
|
||||
notify.inval_entry(parent, name);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Remove a trash op that landed, and the blob of a create it withdrew.
|
||||
pub(crate) fn retire_trash_op(
|
||||
&self,
|
||||
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.writes.hidden();
|
||||
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.withdraw_landed(real);
|
||||
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(())
|
||||
}
|
||||
}
|
||||
@@ -7,71 +7,15 @@ impl Core {
|
||||
/// Record that this daemon just changed `uid` on the remote, so the event
|
||||
/// feed's echo of that change is recognised instead of re-applied. Called
|
||||
/// from the drain once the remote has actually accepted the change and the
|
||||
/// tree has been brought level with it. See [`Core::self_changes`].
|
||||
/// tree has been brought level with it. See [`writes::WriteState`].
|
||||
pub(crate) fn note_self_change(&self, uid: &NodeUid) {
|
||||
note_self_change(&mut self.self_changes.lock(), uid, now_millis());
|
||||
self.writes.note_echo(uid, now_millis());
|
||||
}
|
||||
|
||||
/// Claim one outstanding echo for `uid`, reporting whether this event is one
|
||||
/// this daemon caused. Consuming rather than merely testing is what bounds
|
||||
/// the suppression: the next event for the node applies normally.
|
||||
pub(super) fn take_self_change(&self, uid: &NodeUid) -> bool {
|
||||
take_self_change(&mut self.self_changes.lock(), uid, now_millis())
|
||||
self.writes.take_echo(uid, now_millis())
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a change this daemon made stays recognisable as its own. Generous
|
||||
/// against a feed that can lag, but finite: past it, an event for the node is
|
||||
/// applied like any other. See [`Core::self_changes`].
|
||||
pub(super) const SELF_CHANGE_TTL_MS: i64 = 120_000;
|
||||
|
||||
/// A remote change this daemon made, awaiting its echo from the event feed.
|
||||
pub(super) struct SelfChange {
|
||||
/// When we made it, in the same epoch millis as [`now_millis`].
|
||||
at_ms: i64,
|
||||
/// Echoes not yet seen. More than one because a single file can be created
|
||||
/// and then have a revision uploaded, and the feed reports both.
|
||||
echoes: u32,
|
||||
}
|
||||
|
||||
/// Record one remote change this daemon made. Split from [`Core`] so the
|
||||
/// expiry and echo-counting rules can be tested against a clock the test owns.
|
||||
pub(super) fn note_self_change(
|
||||
changes: &mut HashMap<NodeUid, SelfChange>,
|
||||
uid: &NodeUid,
|
||||
now_ms: i64,
|
||||
) {
|
||||
// Echoes that never arrived — a node trashed before its event came round, a
|
||||
// feed that skipped it — would otherwise accumulate for the life of the
|
||||
// daemon. Pruning on write keeps the map the size of the recent queue.
|
||||
changes.retain(|_, c| now_ms - c.at_ms < SELF_CHANGE_TTL_MS);
|
||||
let change = changes.entry(uid.clone()).or_insert(SelfChange {
|
||||
at_ms: now_ms,
|
||||
echoes: 0,
|
||||
});
|
||||
change.at_ms = now_ms;
|
||||
change.echoes += 1;
|
||||
}
|
||||
|
||||
/// Claim one echo, per [`Core::take_self_change`].
|
||||
pub(super) fn take_self_change(
|
||||
changes: &mut HashMap<NodeUid, SelfChange>,
|
||||
uid: &NodeUid,
|
||||
now_ms: i64,
|
||||
) -> bool {
|
||||
let Some(change) = changes.get_mut(uid) else {
|
||||
return false;
|
||||
};
|
||||
// Too old to attribute: the feed is far enough behind that this is as likely
|
||||
// to be someone else's change as ours, and guessing wrong here costs the user
|
||||
// a stale file.
|
||||
if now_ms - change.at_ms >= SELF_CHANGE_TTL_MS {
|
||||
changes.remove(uid);
|
||||
return false;
|
||||
}
|
||||
change.echoes -= 1;
|
||||
if change.echoes == 0 {
|
||||
changes.remove(uid);
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -15,12 +15,12 @@ impl Core {
|
||||
pub(crate) fn queue_unreleased_writes(&self) {
|
||||
let handles: Vec<(WriteHandle, bool)> = {
|
||||
let mut st = self.state();
|
||||
st.handles.clear();
|
||||
let inos: Vec<u64> = st.active_writes.keys().copied().collect();
|
||||
inos.into_iter()
|
||||
.filter_map(|ino| {
|
||||
let unlinked = st.entries.get(&ino).is_some_and(|e| e.unlinked);
|
||||
st.active_writes.remove(&ino).map(|h| (h, unlinked))
|
||||
let writers = st.open.take_all();
|
||||
writers
|
||||
.into_iter()
|
||||
.map(|h| {
|
||||
let unlinked = st.entries.get(&h.ino).is_some_and(|e| e.unlinked);
|
||||
(h, unlinked)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
@@ -201,18 +201,8 @@ impl Core {
|
||||
base_size: u64,
|
||||
base_revision_id: Option<String>,
|
||||
) -> Option<Baseline> {
|
||||
if is_local_uid(uid) {
|
||||
return None;
|
||||
}
|
||||
match self.pending.lock().get(uid) {
|
||||
Some(p) => p.meta.based_on.clone(),
|
||||
None => Some(Baseline {
|
||||
mtime: base_mtime,
|
||||
size: base_size,
|
||||
hash: None,
|
||||
revision_id: base_revision_id,
|
||||
}),
|
||||
}
|
||||
self.writes
|
||||
.baseline(uid, base_mtime, base_size, base_revision_id)
|
||||
}
|
||||
|
||||
/// Move a file holding a node's intended new content into staging and queue
|
||||
@@ -247,7 +237,7 @@ impl Core {
|
||||
// of exactly the ranges this write did not touch, and what neither wrote
|
||||
// is still the remote content that the earlier write was based on, which
|
||||
// is why the baseline is inherited along with them.
|
||||
let previous = self.pending.lock().get(uid).cloned();
|
||||
let previous = self.writes.queued(uid);
|
||||
if !meta.complete
|
||||
&& let Some(previous) = previous
|
||||
&& let Err(error) = merge_over_pending(&mut meta, src, &previous)
|
||||
@@ -302,7 +292,7 @@ impl Core {
|
||||
// carries it over, or has already finished and this write
|
||||
// queues against the real uid below (`Core::retire_create`).
|
||||
let meta_json = serde_json::to_string(&meta).unwrap_or_default();
|
||||
let mut pending = self.pending.lock();
|
||||
let mut pending = self.writes.pending.lock();
|
||||
let attached = self
|
||||
.db
|
||||
.attach_blob_to_create(&uid.to_string(), &path.to_string_lossy(), &meta_json)
|
||||
@@ -325,7 +315,7 @@ impl Core {
|
||||
debug!(local = %uid, %real, "create landed under an open write; queueing a revision");
|
||||
uid = real;
|
||||
meta.uid = uid.to_string();
|
||||
let previous = self.pending.lock().get(&uid).cloned();
|
||||
let previous = self.writes.queued(&uid);
|
||||
meta.based_on = previous.as_ref().and_then(|p| p.meta.based_on.clone());
|
||||
if !meta.complete
|
||||
&& let Some(previous) = previous
|
||||
@@ -353,7 +343,8 @@ impl Core {
|
||||
error!(%uid, error = %e, "queueing upload failed");
|
||||
Errno::EIO
|
||||
})?;
|
||||
self.pending
|
||||
self.writes
|
||||
.pending
|
||||
.lock()
|
||||
.insert(uid.clone(), PendingRevision { path, meta });
|
||||
superseded
|
||||
@@ -436,7 +427,7 @@ impl Core {
|
||||
// case the remote is *not* our base: the complete staged revision is.
|
||||
// Compose from those local bytes so the truncate can supersede the
|
||||
// queued upload without fetching stale remote content or returning EIO.
|
||||
let pending_base = self.pending.lock().get(&uid).cloned();
|
||||
let pending_base = self.writes.queued(&uid);
|
||||
if pending_base
|
||||
.as_ref()
|
||||
.is_some_and(|pending| !pending.meta.complete)
|
||||
@@ -726,7 +717,7 @@ impl Core {
|
||||
} else {
|
||||
self.release_dropped_ops(uid, blobs);
|
||||
}
|
||||
self.hidden.lock().insert(uid.clone());
|
||||
self.writes.hide(uid);
|
||||
// Withdrawn from the tree, which every mount serves from, so no other
|
||||
// mount goes on serving a file the user just trashed (`docs/BUGS.md`
|
||||
// B74).
|
||||
@@ -786,7 +777,7 @@ impl Core {
|
||||
/// (`docs/BUGS.md` B102), so the entries to forget are found by blob, not
|
||||
/// only by `uid`.
|
||||
pub(super) fn release_dropped_ops(&self, uid: &NodeUid, blobs: Vec<String>) {
|
||||
self.pending.lock().remove(uid);
|
||||
self.writes.pending.lock().remove(uid);
|
||||
self.release_dropped_below(blobs);
|
||||
}
|
||||
|
||||
@@ -794,7 +785,7 @@ impl Core {
|
||||
/// entry.
|
||||
pub(super) fn release_dropped_below(&self, blobs: Vec<String>) {
|
||||
let below: Vec<NodeUid> = {
|
||||
let mut pending = self.pending.lock();
|
||||
let mut pending = self.writes.pending.lock();
|
||||
let below: Vec<NodeUid> = pending
|
||||
.iter()
|
||||
.filter(|(_, p)| blobs.iter().any(|b| p.path == Path::new(b)))
|
||||
|
||||
@@ -116,6 +116,14 @@ impl EventHub {
|
||||
.retain(|other| !Arc::ptr_eq(other, mailbox));
|
||||
}
|
||||
|
||||
/// Wake every subscription waiting on its mailbox, so it sees a stop
|
||||
/// now rather than at its next heartbeat.
|
||||
pub(crate) fn wake_all(&self) {
|
||||
for mailbox in self.mailboxes.lock().iter() {
|
||||
mailbox.ready.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
fn has_subscribers(&self) -> bool {
|
||||
!self.mailboxes.lock().is_empty()
|
||||
}
|
||||
|
||||
+95
-1313
File diff suppressed because it is too large.
Load diff
@@ -14,6 +14,8 @@ use pdfs_core::control::{
|
||||
GalleryAction, GalleryAlbum, GalleryFolder, GalleryPlace, PhotoItem, PhotoKind, Response,
|
||||
};
|
||||
use pdfs_core::{CoreError, CoreResult};
|
||||
use pdfs_store::db::Db;
|
||||
use proton_drive_rs::ProtonDriveClient;
|
||||
use proton_drive_rs::proton_sdk::session::ProtonApiSession;
|
||||
use proton_gallery_app_rs::{App, View};
|
||||
use proton_gallery_rs::CancellationToken;
|
||||
@@ -32,6 +34,9 @@ pub(super) struct Gallery {
|
||||
refresh: Notify,
|
||||
access: AtomicU64,
|
||||
video: video::Server,
|
||||
client: ProtonDriveClient,
|
||||
events: Arc<super::events::EventHub>,
|
||||
db: Arc<Db>,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Eq)]
|
||||
@@ -50,8 +55,17 @@ impl Visibility {
|
||||
}
|
||||
|
||||
impl Gallery {
|
||||
pub(super) fn new(root: PathBuf, session: ProtonApiSession) -> Self {
|
||||
pub(super) fn new(
|
||||
root: PathBuf,
|
||||
session: ProtonApiSession,
|
||||
client: ProtonDriveClient,
|
||||
events: Arc<super::events::EventHub>,
|
||||
db: Arc<Db>,
|
||||
) -> Self {
|
||||
Self {
|
||||
client,
|
||||
events,
|
||||
db,
|
||||
root,
|
||||
session,
|
||||
cancel: CancellationToken::new(),
|
||||
@@ -69,13 +83,13 @@ impl Gallery {
|
||||
self.video.close_all();
|
||||
}
|
||||
|
||||
async fn app(&self, core: &Core) -> CoreResult<&App> {
|
||||
async fn app(&self) -> CoreResult<&App> {
|
||||
self.app
|
||||
.get_or_try_init(|| async {
|
||||
App::open_hosted(
|
||||
self.root.clone(),
|
||||
self.session.clone(),
|
||||
core.client.clone(),
|
||||
self.client.clone(),
|
||||
self.cancel.child_token(),
|
||||
)
|
||||
.await
|
||||
@@ -84,12 +98,7 @@ impl Gallery {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn ensure_visibility(
|
||||
&self,
|
||||
core: &Core,
|
||||
app: &App,
|
||||
force: bool,
|
||||
) -> CoreResult<Arc<Visibility>> {
|
||||
async fn ensure_visibility(&self, app: &App, force: bool) -> CoreResult<Arc<Visibility>> {
|
||||
if self.cancel.is_cancelled() {
|
||||
return Err(CoreError::remote("The Gallery session expired"));
|
||||
}
|
||||
@@ -111,7 +120,7 @@ impl Gallery {
|
||||
.await
|
||||
.map_err(gallery_error)?
|
||||
{
|
||||
self.publish_visibility(core, self.read_visibility(core, app).await?);
|
||||
self.publish_visibility(self.read_visibility(app).await?);
|
||||
}
|
||||
let started = Instant::now();
|
||||
let result = tokio::select! {
|
||||
@@ -119,7 +128,7 @@ impl Gallery {
|
||||
_ = self.cancel.cancelled() => Err(CoreError::remote("The Gallery session expired")),
|
||||
result = tokio::time::timeout(Duration::from_secs(20), async {
|
||||
app.refresh_gallery_configuration(false).await.map_err(gallery_error)?;
|
||||
self.read_visibility(core, app).await
|
||||
self.read_visibility(app).await
|
||||
}) => result.unwrap_or_else(|_| Err(CoreError::remote("Gallery visibility check timed out"))),
|
||||
};
|
||||
tracing::debug!(
|
||||
@@ -129,7 +138,7 @@ impl Gallery {
|
||||
);
|
||||
*checked = Some(Instant::now());
|
||||
if let Ok(visibility) = result {
|
||||
self.publish_visibility(core, visibility.clone());
|
||||
self.publish_visibility(visibility.clone());
|
||||
return Ok(visibility);
|
||||
}
|
||||
if !force && let Some(visibility) = self.snapshot() {
|
||||
@@ -145,18 +154,18 @@ impl Gallery {
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn publish_visibility(&self, core: &Core, visibility: Arc<Visibility>) {
|
||||
fn publish_visibility(&self, visibility: Arc<Visibility>) {
|
||||
let mut snapshot = self.visibility.write().unwrap_or_else(|e| e.into_inner());
|
||||
if snapshot.as_ref() != Some(&visibility) {
|
||||
*snapshot = Some(visibility);
|
||||
drop(snapshot);
|
||||
self.video.close_all();
|
||||
core.events
|
||||
self.events
|
||||
.publish(&[pdfs_core::control::Topic::GalleryVisibilitySynced]);
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_visibility(&self, core: &Core, app: &App) -> CoreResult<Arc<Visibility>> {
|
||||
async fn read_visibility(&self, app: &App) -> CoreResult<Arc<Visibility>> {
|
||||
let account = self.account()?;
|
||||
let mut visibility = Visibility::default();
|
||||
for (volume, node) in app
|
||||
@@ -170,7 +179,7 @@ impl Gallery {
|
||||
.insert(NodeUid::new(volume.into(), node.into()).to_string());
|
||||
}
|
||||
visibility.media.extend(
|
||||
core.db
|
||||
self.db
|
||||
.photo_group_members_for(&visibility.media)
|
||||
.map_err(CoreError::from)?,
|
||||
);
|
||||
@@ -328,7 +337,7 @@ impl Gallery {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn poll(self: Arc<Self>, core: Core) {
|
||||
pub(super) async fn poll(self: Arc<Self>) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
@@ -336,9 +345,8 @@ impl Gallery {
|
||||
_ = self.refresh.notified() => {},
|
||||
_ = tokio::time::sleep(Duration::from_secs(60)) => {}
|
||||
}
|
||||
if let Ok(Ok(app)) = tokio::time::timeout(Duration::from_secs(5), self.app(&core)).await
|
||||
{
|
||||
let _ = self.ensure_visibility(&core, app, false).await;
|
||||
if let Ok(Ok(app)) = tokio::time::timeout(Duration::from_secs(5), self.app()).await {
|
||||
let _ = self.ensure_visibility(app, false).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -422,8 +430,8 @@ impl Core {
|
||||
}
|
||||
let gallery = self.gallery_host()?;
|
||||
self.rt.block_on(async {
|
||||
let app = gallery.app(self).await?;
|
||||
gallery.ensure_visibility(self, app, false).await
|
||||
let app = gallery.app().await?;
|
||||
gallery.ensure_visibility(app, false).await
|
||||
})
|
||||
}
|
||||
|
||||
@@ -475,9 +483,9 @@ impl Core {
|
||||
other => other,
|
||||
};
|
||||
self.rt.block_on(async {
|
||||
let app = gallery.app(self).await?;
|
||||
let app = gallery.app().await?;
|
||||
gallery
|
||||
.ensure_visibility(self, app, matches!(action, GalleryAction::Refresh))
|
||||
.ensure_visibility(app, matches!(action, GalleryAction::Refresh))
|
||||
.await?;
|
||||
match action {
|
||||
GalleryAction::AuthenticateHidden | GalleryAction::Lock => unreachable!(),
|
||||
@@ -517,14 +525,14 @@ impl Core {
|
||||
app.add_drive_folder(uid(&node)?)
|
||||
.await
|
||||
.map_err(gallery_error)?;
|
||||
gallery.ensure_visibility(self, app, true).await?;
|
||||
gallery.ensure_visibility(app, true).await?;
|
||||
Ok(done())
|
||||
}
|
||||
GalleryAction::Remove { gallery: id } => {
|
||||
app.forget_drive_gallery(SourceId::new(id).map_err(gallery_error)?)
|
||||
.await
|
||||
.map_err(gallery_error)?;
|
||||
gallery.ensure_visibility(self, app, true).await?;
|
||||
gallery.ensure_visibility(app, true).await?;
|
||||
Ok(done())
|
||||
}
|
||||
GalleryAction::Refresh => {
|
||||
@@ -535,7 +543,7 @@ impl Core {
|
||||
);
|
||||
app.scan_drive_folder(root).await.map_err(gallery_error)?;
|
||||
}
|
||||
gallery.ensure_visibility(self, app, true).await?;
|
||||
gallery.ensure_visibility(app, true).await?;
|
||||
Ok(done())
|
||||
}
|
||||
GalleryAction::Cover { album, uid: node } => {
|
||||
@@ -565,7 +573,7 @@ impl Core {
|
||||
.set_album_settings_at(Some(root), id, settings)
|
||||
.await
|
||||
.map_err(gallery_error)?;
|
||||
gallery.ensure_visibility(self, app, true).await?;
|
||||
gallery.ensure_visibility(app, true).await?;
|
||||
Ok(done())
|
||||
}
|
||||
}
|
||||
@@ -576,8 +584,8 @@ impl Core {
|
||||
let gallery = self.gallery_host()?;
|
||||
let uid = uid(node)?;
|
||||
self.rt.block_on(async {
|
||||
let app = gallery.app(self).await?;
|
||||
let visibility = gallery.ensure_visibility(self, app, false).await?;
|
||||
let app = gallery.app().await?;
|
||||
let visibility = gallery.ensure_visibility(app, false).await?;
|
||||
let access = if private {
|
||||
Some(gallery.private_access()?)
|
||||
} else {
|
||||
@@ -605,7 +613,7 @@ impl Core {
|
||||
let access = gallery.private_access()?;
|
||||
let asset = gallery.asset(&uid(node)?)?;
|
||||
self.rt.block_on(async {
|
||||
let app = gallery.app(self).await?;
|
||||
let app = gallery.app().await?;
|
||||
let bytes = tokio::time::timeout(Duration::from_secs(30), async {
|
||||
if let Some(bytes) = app.preview(&asset).await? {
|
||||
Ok(bytes)
|
||||
@@ -633,8 +641,8 @@ impl Core {
|
||||
let gallery = self.gallery_host()?;
|
||||
let asset = gallery.asset(&uid(node)?)?;
|
||||
self.rt.block_on(async {
|
||||
let app = gallery.app(self).await?;
|
||||
let visibility = gallery.ensure_visibility(self, app, false).await?;
|
||||
let app = gallery.app().await?;
|
||||
let visibility = gallery.ensure_visibility(app, false).await?;
|
||||
let access = if private {
|
||||
Some(gallery.private_access()?)
|
||||
} else {
|
||||
|
||||
@@ -15,11 +15,10 @@
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::time::Duration;
|
||||
|
||||
use pdfs_store::db::PendingCounts;
|
||||
use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_store::db::{Db, PendingCounts};
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use super::Core;
|
||||
|
||||
/// How often the queue is looked at.
|
||||
const CHECK_EVERY: Duration = Duration::from_secs(5);
|
||||
|
||||
@@ -29,11 +28,10 @@ fn sendable(counts: &PendingCounts) -> i64 {
|
||||
}
|
||||
|
||||
/// Run until the daemon stops, holding the inhibitor while changes wait.
|
||||
pub(crate) fn run(core: Core) {
|
||||
pub(crate) fn run(db: &Db, shutdown: &Shutdown) {
|
||||
let mut held: Option<Child> = None;
|
||||
loop {
|
||||
let waiting = core
|
||||
.db
|
||||
let waiting = db
|
||||
.pending_op_counts()
|
||||
.map(|counts| sendable(&counts))
|
||||
.unwrap_or(0);
|
||||
@@ -52,7 +50,7 @@ pub(crate) fn run(core: Core) {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if !core.shutdown.sleep(CHECK_EVERY) {
|
||||
if !shutdown.sleep(CHECK_EVERY) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,16 @@ use proton_drive_rs::NodeKind;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use fuser::Errno;
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::CoreResult;
|
||||
use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_store::cache::ContentCache;
|
||||
|
||||
use super::link::Link;
|
||||
use super::transfers::TransferRegistry;
|
||||
use super::{Core, is_local_uid, node_size, parse_uid};
|
||||
|
||||
/// How often the keeper looks for work.
|
||||
@@ -59,32 +69,76 @@ pub(crate) struct KeptFile {
|
||||
pub(crate) size: u64,
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// Have the keeper check every pin.
|
||||
pub(crate) fn recheck_all_pins(&self) {
|
||||
self.pin_work.lock().all = true;
|
||||
/// What the pin keeper needs from the tree.
|
||||
pub(crate) trait KeeperHost: Send + Sync {
|
||||
/// Where `uid` is in the tree: its inode, its parent's, and whether it is
|
||||
/// a folder.
|
||||
fn locate(&self, uid: &NodeUid) -> Option<(u64, u64, bool)>;
|
||||
/// Every file under the folder at `ino`, listing what is not listed yet.
|
||||
fn pin_subtree_files(&self, ino: u64) -> CoreResult<Vec<u64>>;
|
||||
/// List the folder at `ino` again if its listing was dropped.
|
||||
fn ensure_children(&self, ino: u64) -> Result<(), Errno>;
|
||||
/// The file at `ino`, as a pin keeps it. See [`Core::kept_file`].
|
||||
fn kept_file(&self, ino: u64) -> Option<KeptFile>;
|
||||
/// Download a pinned file and keep it.
|
||||
fn fetch_pinned(&self, uid: &NodeUid, name: &str, mtime: i64, size: u64) -> CoreResult<()>;
|
||||
}
|
||||
|
||||
impl KeeperHost for Core {
|
||||
fn locate(&self, uid: &NodeUid) -> Option<(u64, u64, bool)> {
|
||||
let st = self.state();
|
||||
st.by_uid.get(uid).and_then(|&ino| {
|
||||
let e = st.entries.get(&ino)?;
|
||||
Some((ino, e.parent, e.node.is_folder()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Have the keeper check the pinned file or folder `uid`.
|
||||
pub(crate) fn recheck_pinned(&self, uid: &NodeUid) {
|
||||
self.pin_work.lock().nodes.insert(uid.clone());
|
||||
fn pin_subtree_files(&self, ino: u64) -> CoreResult<Vec<u64>> {
|
||||
Core::pin_subtree_files(self, ino)
|
||||
}
|
||||
|
||||
fn ensure_children(&self, ino: u64) -> Result<(), Errno> {
|
||||
Core::ensure_children(self, ino)
|
||||
}
|
||||
|
||||
fn kept_file(&self, ino: u64) -> Option<KeptFile> {
|
||||
Core::kept_file(self, ino)
|
||||
}
|
||||
|
||||
fn fetch_pinned(&self, uid: &NodeUid, name: &str, mtime: i64, size: u64) -> CoreResult<()> {
|
||||
Core::fetch_pinned(self, uid, name, mtime, size)
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks pins again and downloads what is missing or stale (the module
|
||||
/// documentation says when). Holds the content cache, the transfer list, the
|
||||
/// link, the stop signal and the queue of work; it reaches the tree through
|
||||
/// [`KeeperHost`].
|
||||
pub(crate) struct PinKeeper {
|
||||
cache: Arc<ContentCache>,
|
||||
transfers: Arc<TransferRegistry>,
|
||||
link: Arc<Link>,
|
||||
shutdown: Arc<Shutdown>,
|
||||
work: Arc<Mutex<PinWork>>,
|
||||
host: Arc<dyn KeeperHost>,
|
||||
}
|
||||
|
||||
impl PinKeeper {
|
||||
/// The keeper's loop, until the daemon stops. Starts with a check of every
|
||||
/// pin, which catches up on whatever changed while the daemon was down.
|
||||
///
|
||||
/// Work that failed waits out a backoff of its own. New work does not wait
|
||||
/// for it, so a file that keeps failing does not hold up the next change.
|
||||
pub(crate) fn run_pin_keeper(&self) {
|
||||
self.recheck_all_pins();
|
||||
pub(crate) fn run(&self) {
|
||||
self.work.lock().all = true;
|
||||
let mut backlog = PinWork::default();
|
||||
let mut backlog_due = Instant::now();
|
||||
let mut retry = RETRY_FIRST;
|
||||
while self.shutdown.sleep(KEEPER_TICK) {
|
||||
if !self.is_online() {
|
||||
if !self.link.is_online() {
|
||||
continue;
|
||||
}
|
||||
let mut work = std::mem::take(&mut *self.pin_work.lock());
|
||||
let mut work = std::mem::take(&mut *self.work.lock());
|
||||
let retrying = !backlog.is_empty() && Instant::now() >= backlog_due;
|
||||
if retrying {
|
||||
work.merge(std::mem::take(&mut backlog));
|
||||
@@ -128,19 +182,13 @@ impl Core {
|
||||
if !self.cache.is_pinned(&uid) {
|
||||
continue;
|
||||
}
|
||||
let found = {
|
||||
let st = self.state();
|
||||
st.by_uid.get(&uid).and_then(|&ino| {
|
||||
let e = st.entries.get(&ino)?;
|
||||
Some((ino, e.parent, e.node.is_folder()))
|
||||
})
|
||||
};
|
||||
let found = self.host.locate(&uid);
|
||||
let Some((ino, parent, is_folder)) = found else {
|
||||
debug!(%uid, "pin keeper: pinned node is not in the tree");
|
||||
continue;
|
||||
};
|
||||
if is_folder {
|
||||
match self.pin_subtree_files(ino) {
|
||||
match self.host.pin_subtree_files(ino) {
|
||||
Ok(inos) => files.extend(inos.into_iter().filter(|i| seen.insert(*i))),
|
||||
Err(e) => {
|
||||
warn!(%uid, error = %e, "pin keeper: listing a kept folder failed");
|
||||
@@ -154,7 +202,7 @@ impl Core {
|
||||
// now, which is what the cached copy is checked against.
|
||||
if !work.all
|
||||
&& parent != ino
|
||||
&& let Err(e) = self.ensure_children(parent)
|
||||
&& let Err(e) = self.host.ensure_children(parent)
|
||||
{
|
||||
warn!(%uid, error = ?e, "pin keeper: listing a kept file's folder failed");
|
||||
failed.nodes.insert(uid);
|
||||
@@ -167,7 +215,7 @@ impl Core {
|
||||
|
||||
let stale: Vec<KeptFile> = files
|
||||
.into_iter()
|
||||
.filter_map(|ino| self.kept_file(ino))
|
||||
.filter_map(|ino| self.host.kept_file(ino))
|
||||
.filter(|f| !self.cache.is_cached(&f.uid, f.mtime, f.size))
|
||||
.collect();
|
||||
if stale.is_empty() {
|
||||
@@ -186,7 +234,10 @@ impl Core {
|
||||
continue;
|
||||
}
|
||||
job.detail(file.name.clone());
|
||||
match self.fetch_pinned(&file.uid, &file.name, file.mtime, file.size) {
|
||||
match self
|
||||
.host
|
||||
.fetch_pinned(&file.uid, &file.name, file.mtime, file.size)
|
||||
{
|
||||
Ok(()) => fetched += 1,
|
||||
Err(e) => {
|
||||
warn!(uid = %file.uid, error = %e, "pin keeper: download failed");
|
||||
@@ -203,6 +254,30 @@ impl Core {
|
||||
);
|
||||
failed
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// The pin keeper, with this daemon as its host.
|
||||
pub(crate) fn pin_keeper(&self) -> PinKeeper {
|
||||
PinKeeper {
|
||||
cache: self.cache.clone(),
|
||||
transfers: self.transfers.clone(),
|
||||
link: self.link.clone(),
|
||||
shutdown: self.shutdown.clone(),
|
||||
work: self.pin_work.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Have the keeper check every pin.
|
||||
pub(crate) fn recheck_all_pins(&self) {
|
||||
self.pin_work.lock().all = true;
|
||||
}
|
||||
|
||||
/// Have the keeper check the pinned file or folder `uid`.
|
||||
pub(crate) fn recheck_pinned(&self, uid: &NodeUid) {
|
||||
self.pin_work.lock().nodes.insert(uid.clone());
|
||||
}
|
||||
|
||||
/// The file at `ino`, as a pin keeps it. `None` for a folder, a file this
|
||||
/// daemon still owes an upload for, or a file whose real size cannot be
|
||||
@@ -231,7 +306,7 @@ impl Core {
|
||||
claimed_size.is_none(),
|
||||
)
|
||||
};
|
||||
if is_local_uid(&uid) || self.pending.lock().contains_key(&uid) {
|
||||
if is_local_uid(&uid) || self.writes.is_queued(&uid) {
|
||||
return None;
|
||||
}
|
||||
let size = match provisional {
|
||||
|
||||
+449
-899
File diff suppressed because it is too large.
Load diff
+180
-85
@@ -18,6 +18,11 @@ use proton_drive_rs::proton_sdk::api::ResponseCode;
|
||||
use proton_drive_rs::proton_sdk::error::{ProtonApiError, ProtonError};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_drive::DriveApi;
|
||||
|
||||
use crate::{Core, ONLINE_PROBE_MAX, ONLINE_PROBE_MIN};
|
||||
|
||||
/// How long a remote call a FUSE handler is waiting on may take before the link
|
||||
@@ -58,6 +63,11 @@ const IDLE_CHECK: Duration = Duration::from_secs(1);
|
||||
/// that fires on every change so waiters need not poll.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Link {
|
||||
/// False while the API is unreachable and we are serving the cached tree.
|
||||
/// Set by the probe thread; read by front-ends through
|
||||
/// `Response::Status` so the UI can say so rather than leaving the user to
|
||||
/// infer it from a wall of EIO.
|
||||
online: AtomicBool,
|
||||
lost_at: Mutex<Option<Instant>>,
|
||||
changed: Condvar,
|
||||
/// Folders listed from the DB alone while offline, to relist once back.
|
||||
@@ -74,14 +84,84 @@ pub(crate) struct Link {
|
||||
}
|
||||
|
||||
impl Link {
|
||||
/// The link of a mount that comes up with Proton refusing its session, or
|
||||
/// not.
|
||||
pub(crate) fn starting(session_expired: bool) -> Self {
|
||||
/// The link of a mount that comes up online or from the cache, with
|
||||
/// Proton refusing its session or not.
|
||||
pub(crate) fn starting(online: bool, session_expired: bool) -> Self {
|
||||
Self {
|
||||
online: AtomicBool::new(online),
|
||||
session_expired: AtomicBool::new(session_expired),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the mount currently believes Proton is reachable.
|
||||
pub(crate) fn is_online(&self) -> bool {
|
||||
self.online.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Whether Proton refused the session itself, so the mount stays offline
|
||||
/// until the user signs in again.
|
||||
pub(crate) fn session_expired(&self) -> bool {
|
||||
self.session_expired.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Flip the mount offline and wake the probe. Only the first caller of an
|
||||
/// outage logs it; the rest are the same outage.
|
||||
pub(crate) fn go_offline(&self, what: &str, error: &dyn std::fmt::Display) {
|
||||
let mut lost_at = self.lost_at.lock();
|
||||
if self.online.swap(false, Ordering::Relaxed) {
|
||||
*lost_at = Some(Instant::now());
|
||||
warn!(during = what, %error,
|
||||
"lost the connection to Proton; queueing changes until it returns");
|
||||
self.changed.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Flip the mount back online and wake everything waiting for it.
|
||||
fn go_online(&self) {
|
||||
let mut lost_at = self.lost_at.lock();
|
||||
self.online.store(true, Ordering::Relaxed);
|
||||
match lost_at.take() {
|
||||
Some(since) => {
|
||||
info!(
|
||||
offline_secs = since.elapsed().as_secs(),
|
||||
"connection to Proton is back"
|
||||
)
|
||||
}
|
||||
None => info!("back online"),
|
||||
}
|
||||
self.changed.notify_all();
|
||||
}
|
||||
|
||||
/// Wait up to `budget` for the link to come back. Returns whether it is up.
|
||||
pub(crate) fn wait_online(&self, budget: Duration, shutdown: &Shutdown) -> bool {
|
||||
let deadline = Instant::now() + budget;
|
||||
let mut lost_at = self.lost_at.lock();
|
||||
while !self.is_online() {
|
||||
if shutdown.is_stopping() || self.changed.wait_until(&mut lost_at, deadline).timed_out()
|
||||
{
|
||||
return self.is_online();
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Wait while the link is up. Returns `false` if the daemon is stopping.
|
||||
fn wait_offline(&self, shutdown: &Shutdown) -> bool {
|
||||
let mut lost_at = self.lost_at.lock();
|
||||
while self.is_online() {
|
||||
if shutdown.is_stopping() {
|
||||
return false;
|
||||
}
|
||||
self.changed.wait_for(&mut lost_at, IDLE_CHECK);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// When the current outage began, if the link is down.
|
||||
fn lost_at(&self) -> Option<Instant> {
|
||||
*self.lost_at.lock()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) use pdfs_drive::is_network_error;
|
||||
@@ -154,7 +234,7 @@ fn next_probe_delay(delay: Duration, outage: Duration) -> Duration {
|
||||
impl Core {
|
||||
/// Whether the mount currently believes Proton is reachable.
|
||||
pub(crate) fn is_online(&self) -> bool {
|
||||
self.online.load(Ordering::Relaxed)
|
||||
self.link.is_online()
|
||||
}
|
||||
|
||||
/// Whether a namespace change through the mount goes to Drive inside the
|
||||
@@ -189,7 +269,7 @@ impl Core {
|
||||
/// Whether Proton refused the session itself, so nothing reaches it until
|
||||
/// the user signs in again.
|
||||
pub(crate) fn session_expired(&self) -> bool {
|
||||
self.link.session_expired.load(Ordering::Relaxed)
|
||||
self.link.session_expired()
|
||||
}
|
||||
|
||||
/// Report a failed remote call. Returns whether it failed for want of a
|
||||
@@ -233,65 +313,14 @@ impl Core {
|
||||
self.mark_offline(what, error);
|
||||
}
|
||||
|
||||
/// Flip the mount offline and wake the probe. Only the first caller of an
|
||||
/// outage logs it; the rest are the same outage.
|
||||
/// Flip the mount offline and wake the probe. See [`Link::go_offline`].
|
||||
pub(crate) fn mark_offline(&self, what: &str, error: &dyn std::fmt::Display) {
|
||||
let mut lost_at = self.link.lost_at.lock();
|
||||
if self.online.swap(false, Ordering::Relaxed) {
|
||||
*lost_at = Some(Instant::now());
|
||||
warn!(during = what, %error,
|
||||
"lost the connection to Proton; queueing changes until it returns");
|
||||
self.link.changed.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Flip the mount back online, wake everything waiting for it, and let the
|
||||
/// queue drain.
|
||||
fn mark_online(&self) {
|
||||
{
|
||||
let mut lost_at = self.link.lost_at.lock();
|
||||
self.online.store(true, Ordering::Relaxed);
|
||||
match lost_at.take() {
|
||||
Some(since) => {
|
||||
info!(
|
||||
offline_secs = since.elapsed().as_secs(),
|
||||
"connection to Proton is back"
|
||||
)
|
||||
}
|
||||
None => info!("back online"),
|
||||
}
|
||||
self.link.changed.notify_all();
|
||||
}
|
||||
self.relist_offline_listings();
|
||||
// Anything written while offline is queued and waiting on exactly this,
|
||||
// including ops that failed on the way down and are sitting out a
|
||||
// backoff sized for a server that keeps refusing. Ops Drive refused
|
||||
// keep theirs: the link was not why.
|
||||
if let Err(e) = self.db.retry_unrefused_ops_now(crate::now_millis()) {
|
||||
warn!(error = %e, "moving backed-off ops up after a reconnect failed");
|
||||
}
|
||||
self.wake_drain();
|
||||
// Downloads for pins failed while the link was down, and the events
|
||||
// that would have named the files are behind us (`docs/BUGS.md` B282).
|
||||
self.recheck_all_pins();
|
||||
self.link.go_offline(what, error);
|
||||
}
|
||||
|
||||
/// Wait up to `budget` for the link to come back. Returns whether it is up.
|
||||
pub(crate) fn wait_online(&self, budget: Duration) -> bool {
|
||||
let deadline = Instant::now() + budget;
|
||||
let mut lost_at = self.link.lost_at.lock();
|
||||
while !self.is_online() {
|
||||
if self.shutdown.is_stopping()
|
||||
|| self
|
||||
.link
|
||||
.changed
|
||||
.wait_until(&mut lost_at, deadline)
|
||||
.timed_out()
|
||||
{
|
||||
return self.is_online();
|
||||
}
|
||||
}
|
||||
true
|
||||
self.link.wait_online(budget, &self.shutdown)
|
||||
}
|
||||
|
||||
/// Wait out `interval` before a background poll of Proton, and while the
|
||||
@@ -312,29 +341,103 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
/// The online probe, with this daemon as its host.
|
||||
pub(crate) fn online_probe(&self) -> OnlineProbe {
|
||||
OnlineProbe {
|
||||
link: self.link.clone(),
|
||||
drive: self.drive.clone(),
|
||||
rt: self.rt.clone(),
|
||||
shutdown: self.shutdown.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The link is back: let everything that waited on it go. Anything
|
||||
/// written while offline is queued and waiting on exactly this, including
|
||||
/// ops that failed on the way down and are sitting out a backoff sized
|
||||
/// for a server that keeps refusing. Ops Drive refused keep theirs: the
|
||||
/// link was not why.
|
||||
fn after_reconnect(&self) {
|
||||
self.relist_offline_listings();
|
||||
if let Err(e) = self.db.retry_unrefused_ops_now(crate::now_millis()) {
|
||||
warn!(error = %e, "moving backed-off ops up after a reconnect failed");
|
||||
}
|
||||
self.wake_drain();
|
||||
// Downloads for pins failed while the link was down, and the events
|
||||
// that would have named the files are behind us (`docs/BUGS.md` B282).
|
||||
self.recheck_all_pins();
|
||||
}
|
||||
}
|
||||
|
||||
/// What the online probe needs from the rest of the daemon.
|
||||
pub(crate) trait LinkHost: Send + Sync {
|
||||
/// Drive answered with the My Files root: store it in the tree and the
|
||||
/// database before the mount goes online.
|
||||
fn refresh_root(&self, root: &proton_drive_rs::Node);
|
||||
/// The mount is online again: relist, retry and refetch what waited.
|
||||
fn reconnected(&self);
|
||||
/// Proton refused the session.
|
||||
fn session_refused(&self, what: &str, error: &ProtonError);
|
||||
/// Repair the primary root's share id, which an offline start could not.
|
||||
fn repair_share_id(&self);
|
||||
}
|
||||
|
||||
impl LinkHost for Core {
|
||||
fn refresh_root(&self, root: &proton_drive_rs::Node) {
|
||||
{
|
||||
let root_ino = self.root_ino();
|
||||
let mut st = self.state();
|
||||
if let Some(e) = st.entries.get_mut(&root_ino) {
|
||||
e.node = root.clone();
|
||||
}
|
||||
}
|
||||
if let Err(e) = self.db.upsert_node(root) {
|
||||
warn!(error = %e, "refresh root after reconnect failed");
|
||||
}
|
||||
}
|
||||
|
||||
fn reconnected(&self) {
|
||||
self.after_reconnect();
|
||||
}
|
||||
|
||||
fn session_refused(&self, what: &str, error: &ProtonError) {
|
||||
self.mark_session_expired(what, error);
|
||||
}
|
||||
|
||||
fn repair_share_id(&self) {
|
||||
self.repair_primary_share_id(&self.primary_root_uid);
|
||||
}
|
||||
}
|
||||
|
||||
/// Watches the link for the life of the mount and probes it back while it is
|
||||
/// down. Holds the link, Drive, the runtime and the stop signal; it reaches
|
||||
/// the tree and the queue through [`LinkHost`].
|
||||
pub(crate) struct OnlineProbe {
|
||||
link: Arc<Link>,
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
shutdown: Arc<Shutdown>,
|
||||
host: Arc<dyn LinkHost>,
|
||||
}
|
||||
|
||||
impl OnlineProbe {
|
||||
/// Watch the link for the life of the mount: sleep while it is up, and
|
||||
/// probe it back while it is down.
|
||||
///
|
||||
/// A mount that started from the cache is down from the first moment; one
|
||||
/// that started online goes down when [`Core::mark_offline`] says so.
|
||||
pub(crate) fn run_online_probe(&self) {
|
||||
/// that started online goes down when [`Link::go_offline`] says so.
|
||||
pub(crate) fn run(&self) {
|
||||
// Only an offline start never had a chance to repair its share id.
|
||||
let mut repair_share_id = !self.is_online();
|
||||
let mut repair_share_id = !self.link.is_online();
|
||||
loop {
|
||||
{
|
||||
let mut lost_at = self.link.lost_at.lock();
|
||||
while self.is_online() {
|
||||
if self.shutdown.is_stopping() {
|
||||
return;
|
||||
}
|
||||
self.link.changed.wait_for(&mut lost_at, IDLE_CHECK);
|
||||
}
|
||||
if !self.link.wait_offline(&self.shutdown) {
|
||||
return;
|
||||
}
|
||||
if !self.probe_until_online() {
|
||||
return;
|
||||
}
|
||||
if std::mem::take(&mut repair_share_id) {
|
||||
self.repair_primary_share_id(&self.primary_root_uid);
|
||||
self.host.repair_share_id();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -345,7 +448,7 @@ impl Core {
|
||||
/// A refused session is not probed: every probe would be refused the same
|
||||
/// way, forever (issue #35). The thread waits for the stop instead.
|
||||
fn probe_until_online(&self) -> bool {
|
||||
let started = self.link.lost_at.lock().unwrap_or_else(Instant::now);
|
||||
let started = self.link.lost_at().unwrap_or_else(Instant::now);
|
||||
let mut delay = if started.elapsed() < YOUNG_OUTAGE {
|
||||
PROBE_AFTER_DROP
|
||||
} else {
|
||||
@@ -355,7 +458,7 @@ impl Core {
|
||||
if !self.shutdown.sleep(delay) {
|
||||
return false;
|
||||
}
|
||||
if self.session_expired() {
|
||||
if self.link.session_expired() {
|
||||
delay = ONLINE_PROBE_MAX;
|
||||
continue;
|
||||
}
|
||||
@@ -367,20 +470,12 @@ impl Core {
|
||||
});
|
||||
match probe {
|
||||
Ok(root) => {
|
||||
{
|
||||
let root_ino = self.root_ino();
|
||||
let mut st = self.state();
|
||||
if let Some(e) = st.entries.get_mut(&root_ino) {
|
||||
e.node = root.clone();
|
||||
}
|
||||
}
|
||||
if let Err(e) = self.db.upsert_node(&root) {
|
||||
warn!(error = %e, "refresh root after reconnect failed");
|
||||
}
|
||||
self.mark_online();
|
||||
self.host.refresh_root(&root);
|
||||
self.link.go_online();
|
||||
self.host.reconnected();
|
||||
return true;
|
||||
}
|
||||
Err(e) if session_revoked(&e) => self.mark_session_expired("online probe", &e),
|
||||
Err(e) if session_revoked(&e) => self.host.session_refused("online probe", &e),
|
||||
Err(e) => {
|
||||
debug!(error = %e, ?delay, "online probe failed; still offline");
|
||||
delay = next_probe_delay(delay, started.elapsed());
|
||||
|
||||
@@ -3,6 +3,16 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
/// How many folders the mount lists on Drive at once, in the daemon's
|
||||
/// admission ([`pdfs_sched::Class::Listing`]).
|
||||
///
|
||||
/// Above what the mount's workers ([`workers::FUSE_WORKERS`]) and a burst
|
||||
/// of commands list at once, so for now the admission counts cold listings
|
||||
/// in `pdfs diagnostics` and rarely makes one wait. A lookup must not queue
|
||||
/// behind a pin walking a large tree; a lower limit waits for a policy that
|
||||
/// tells the two apart.
|
||||
pub(crate) const COLD_LISTINGS: usize = 32;
|
||||
|
||||
impl Core {
|
||||
/// Whether [`Core::ensure_children`] would answer for `ino` without
|
||||
/// touching the network. Lets a handler decide between answering inline
|
||||
@@ -32,10 +42,7 @@ impl Core {
|
||||
None
|
||||
};
|
||||
freshness.is_none_or(|key| {
|
||||
!listing_needs_refresh(
|
||||
self.online.load(Ordering::Relaxed),
|
||||
self.shared_listing_stale(&key),
|
||||
)
|
||||
!listing_needs_refresh(self.is_online(), self.shared_listing_stale(&key))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -58,16 +65,10 @@ impl Core {
|
||||
/// lock: no site in the daemon holds `pending` and `state` at once, and this
|
||||
/// is not the place to become the first.
|
||||
pub(super) fn stamp_pending_sizes(&self, nodes: &mut [Node]) {
|
||||
let sizes: HashMap<NodeUid, u64> = {
|
||||
let pending = self.pending.lock();
|
||||
if pending.is_empty() {
|
||||
return;
|
||||
}
|
||||
pending
|
||||
.iter()
|
||||
.map(|(uid, pr)| (uid.clone(), pr.meta.len))
|
||||
.collect()
|
||||
};
|
||||
let sizes = self.writes.queued_sizes();
|
||||
if sizes.is_empty() {
|
||||
return;
|
||||
}
|
||||
apply_pending_sizes(nodes, &sizes);
|
||||
}
|
||||
|
||||
@@ -167,7 +168,7 @@ impl Core {
|
||||
// Before the lock: a DB row carries the size the server last
|
||||
// sealed, which a queued write is ahead of (B11).
|
||||
self.stamp_pending_sizes(&mut nodes);
|
||||
let hidden = self.hidden.lock().clone();
|
||||
let hidden = self.writes.hidden();
|
||||
let mut st = self.state();
|
||||
if st.children.contains_key(&ino) {
|
||||
return Ok(());
|
||||
@@ -235,14 +236,11 @@ impl Core {
|
||||
}
|
||||
|
||||
let primary_root =
|
||||
is_primary_root_listing(self.primary, &folder_uid, &self.primary_root_uid);
|
||||
is_primary_root_listing(self.session.primary, &folder_uid, &self.primary_root_uid);
|
||||
let foreign = !self.is_own_or_virtual(&folder_uid) && !is_local_uid(&folder_uid);
|
||||
let foreign_key = foreign.then(|| Self::shared_folder_freshness_key(&folder_uid));
|
||||
let refresh_foreign = foreign_key.as_deref().is_some_and(|key| {
|
||||
listing_needs_refresh(
|
||||
self.online.load(Ordering::Relaxed),
|
||||
self.shared_listing_stale(key),
|
||||
)
|
||||
listing_needs_refresh(self.is_online(), self.shared_listing_stale(key))
|
||||
});
|
||||
if cached && !refresh_foreign {
|
||||
if primary_root {
|
||||
@@ -277,6 +275,22 @@ impl Core {
|
||||
if !self.is_online() {
|
||||
return self.adopt_stale_listing(ino, &folder_uid, cached, primary_root);
|
||||
}
|
||||
// Single flight: callers that find the folder unlisted at the same
|
||||
// time share one listing. Each used to ask Drive itself, and all but
|
||||
// the first threw the answer away. A follower waits for the leader and
|
||||
// takes what it published; when the leader failed, the follower lists
|
||||
// the folder itself, so each caller still gets its own answer. A
|
||||
// shared folder's refresh is left out: its generation check answers a
|
||||
// caller EAGAIN on its own.
|
||||
let _lead = if foreign {
|
||||
None
|
||||
} else {
|
||||
match self.listing_flights.join(&folder_uid) {
|
||||
Some(lead) => Some(lead),
|
||||
None if self.state().children.contains_key(&ino) => return Ok(()),
|
||||
None => None,
|
||||
}
|
||||
};
|
||||
|
||||
let refresh_generation =
|
||||
refresh_foreign.then(|| self.shared.shared_generation.load(Ordering::SeqCst));
|
||||
@@ -286,6 +300,15 @@ impl Core {
|
||||
let queued_before = (!foreign)
|
||||
.then(|| self.db.queued_children(&folder_uid).ok())
|
||||
.flatten();
|
||||
// Asking Drive waits for the daemon's admission of cold listings,
|
||||
// which counts it in `pdfs diagnostics`. The permit covers the two
|
||||
// calls to Drive and goes before the listing is published.
|
||||
let admitted = self
|
||||
.rt
|
||||
.block_on(self.sync.admission.admit(pdfs_sched::Step {
|
||||
class: pdfs_sched::Class::Listing,
|
||||
root: 0,
|
||||
}));
|
||||
let uids = match self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_folder_children_node_uids(&folder_uid))
|
||||
@@ -318,6 +341,7 @@ impl Core {
|
||||
return Err(Errno::EIO);
|
||||
}
|
||||
};
|
||||
drop(admitted);
|
||||
// Drive shows none of what is still queued for the folder (B132).
|
||||
// A shared folder's listing is published as Drive has it.
|
||||
if !foreign {
|
||||
@@ -334,7 +358,7 @@ impl Core {
|
||||
// Same as the DB path above: the remote's size for a file with a write
|
||||
// still queued is the pre-write one (B11).
|
||||
self.stamp_pending_sizes(&mut nodes);
|
||||
let hidden = self.hidden.lock().clone();
|
||||
let hidden = self.writes.hidden();
|
||||
let mut filtered_nodes: Vec<Node> = nodes
|
||||
.into_iter()
|
||||
.filter(|node| node_visible(node, &folder_uid, &hidden))
|
||||
@@ -446,11 +470,17 @@ impl Core {
|
||||
///
|
||||
/// Metadata only: a thumbnail path is attached for photos whose thumbnail is
|
||||
/// already cached, and nothing is downloaded here — the front-end pulls the
|
||||
/// thumbnails it actually paints via [`Core::photo_thumbs`].
|
||||
/// thumbnails it actually paints via [`Photos::photo_thumbs`](crate::photos::Photos::photo_thumbs).
|
||||
pub(super) fn listing_stale(&self, key: &str, ttl: Duration) -> bool {
|
||||
match self.db.state_i64(key).ok().flatten() {
|
||||
Some(ms) => now_ms().saturating_sub(ms) >= ttl.as_millis() as i64,
|
||||
None => true,
|
||||
}
|
||||
listing_stale(&self.db, key, ttl)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the listing stamped under `key` is older than `ttl`, or was never
|
||||
/// stamped.
|
||||
pub(crate) fn listing_stale(db: &Db, key: &str, ttl: Duration) -> bool {
|
||||
match db.state_i64(key).ok().flatten() {
|
||||
Some(ms) => now_ms().saturating_sub(ms) >= ttl.as_millis() as i64,
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,31 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Core {
|
||||
/// Runs `VACUUM` and the deep integrity check as jobs, one at a time, and
|
||||
/// keeps the last check's findings. Holds the database, the transfer list for
|
||||
/// the job's entry, and the board the job runs on.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Maintenance {
|
||||
db: Arc<Db>,
|
||||
transfers: Arc<TransferRegistry>,
|
||||
services: pdfs_core::lifecycle::ServiceBoard,
|
||||
state: Arc<Mutex<MaintenanceState>>,
|
||||
}
|
||||
|
||||
impl Maintenance {
|
||||
pub(crate) fn new(
|
||||
db: Arc<Db>,
|
||||
transfers: Arc<TransferRegistry>,
|
||||
services: pdfs_core::lifecycle::ServiceBoard,
|
||||
) -> Self {
|
||||
Self {
|
||||
db,
|
||||
transfers,
|
||||
services,
|
||||
state: Arc::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a background `VACUUM`, or refuse because maintenance is already
|
||||
/// running.
|
||||
///
|
||||
@@ -11,9 +35,9 @@ impl Core {
|
||||
/// request. The outcome is a log line and a job that disappears from
|
||||
/// `GetQueueStatus` when it is done — a vacuum has nothing to report that a
|
||||
/// follow-up `CacheInspect` cannot show.
|
||||
pub(super) fn start_vacuum(&self) -> CoreResult<()> {
|
||||
pub(crate) fn start_vacuum(&self) -> CoreResult<()> {
|
||||
{
|
||||
let mut m = self.maintenance.lock();
|
||||
let mut m = self.state.lock();
|
||||
if m.running {
|
||||
return Err(CoreError::conflict(
|
||||
"database maintenance is already running",
|
||||
@@ -21,12 +45,12 @@ impl Core {
|
||||
}
|
||||
m.running = true;
|
||||
}
|
||||
let core = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
let job = core.transfers.begin_job("Compacting the cache database");
|
||||
let this = self.clone();
|
||||
if let Err(error) = self.services.spawn_job("pdfs-vacuum", move || {
|
||||
let job = this.transfers.begin_job("Compacting the cache database");
|
||||
job.detail("Rewriting the database file");
|
||||
let started = Instant::now();
|
||||
match core.db.vacuum() {
|
||||
match this.db.vacuum() {
|
||||
Ok(outcome) => info!(
|
||||
freed_bytes = outcome.freed_bytes(),
|
||||
before_bytes = outcome.before_bytes,
|
||||
@@ -37,8 +61,10 @@ impl Core {
|
||||
),
|
||||
Err(e) => warn!(error = %e, "vacuum failed"),
|
||||
}
|
||||
core.maintenance.lock().running = false;
|
||||
});
|
||||
this.state.lock().running = false;
|
||||
}) {
|
||||
tracing::warn!(%error, "could not start pdfs-vacuum");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -49,8 +75,8 @@ impl Core {
|
||||
/// `(_, false, true)` and the answer lands on a later one — the check reads
|
||||
/// every page of the database under the connection mutex, so the choice is
|
||||
/// between answering late and freezing the mount until it finishes.
|
||||
pub(super) fn start_or_read_integrity_check(&self) -> (Vec<String>, bool, bool) {
|
||||
let mut m = self.maintenance.lock();
|
||||
pub(crate) fn start_or_read_integrity_check(&self) -> (Vec<String>, bool, bool) {
|
||||
let mut m = self.state.lock();
|
||||
if let Some(problems) = m.integrity.clone() {
|
||||
return (problems, true, m.running);
|
||||
}
|
||||
@@ -60,13 +86,13 @@ impl Core {
|
||||
m.running = true;
|
||||
drop(m);
|
||||
|
||||
let core = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
let job = core
|
||||
let this = self.clone();
|
||||
if let Err(error) = self.services.spawn_job("pdfs-integrity-check", move || {
|
||||
let job = this
|
||||
.transfers
|
||||
.begin_background_job("Checking the cache database");
|
||||
job.detail("Verifying every page");
|
||||
let problems = match core.db.integrity_check() {
|
||||
let problems = match this.db.integrity_check() {
|
||||
Ok(problems) => problems,
|
||||
Err(e) => vec![format!("integrity check failed: {e:?}")],
|
||||
};
|
||||
@@ -75,10 +101,12 @@ impl Core {
|
||||
} else {
|
||||
warn!(problems = problems.len(), "cache database integrity check");
|
||||
}
|
||||
let mut m = core.maintenance.lock();
|
||||
let mut m = this.state.lock();
|
||||
m.integrity = Some(problems);
|
||||
m.running = false;
|
||||
});
|
||||
}) {
|
||||
tracing::warn!(%error, "could not start pdfs-integrity-check");
|
||||
}
|
||||
(Vec::new(), false, true)
|
||||
}
|
||||
}
|
||||
@@ -90,7 +118,7 @@ impl Core {
|
||||
/// gain from overlapping them — and the result of a check outlives the request
|
||||
/// that asked for it, because the request is answered before the check finishes.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Maintenance {
|
||||
struct MaintenanceState {
|
||||
/// A vacuum or integrity check is running right now.
|
||||
running: bool,
|
||||
/// Findings of the most recent completed deep check. `None` means none has
|
||||
|
||||
+147
-168
@@ -1,7 +1,7 @@
|
||||
//! Mount lifecycle and background-service orchestration.
|
||||
|
||||
use super::*;
|
||||
use pdfs_core::lifecycle::{ServiceBoard, Services, Wake};
|
||||
use pdfs_core::lifecycle::{Service, ServiceBoard, Services};
|
||||
|
||||
/// Why a [`mount`] call returned. Lets the daemon decide whether to exit (clean
|
||||
/// shutdown) or remount (the mount went away under it).
|
||||
@@ -351,16 +351,17 @@ pub(super) fn spawn_session(
|
||||
clear_stale_mount(mountpoint);
|
||||
info!(mountpoint = %mountpoint.display(), "mounting Proton Drive location");
|
||||
let fs = ProtonFs::new(core.clone(), root);
|
||||
if core.primary {
|
||||
if core.session.primary {
|
||||
// Only My Files rehydrates the daemon-wide node cache, once. A
|
||||
// secondary mount shares the tree it fills.
|
||||
core.hydrate();
|
||||
}
|
||||
let session = Session::new(fs, mountpoint, &config)?.spawn()?;
|
||||
let _ = core
|
||||
.session
|
||||
.notifier
|
||||
.set(KernelChannel::new(session.notifier(), core.root_ino()));
|
||||
core.session_live.store(true, Ordering::Release);
|
||||
core.session.session_live.store(true, Ordering::Release);
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
@@ -488,13 +489,22 @@ pub(crate) fn mount_with(
|
||||
// handlers can trigger reconciles.
|
||||
let (sync_tx, sync_rx) = std::sync::mpsc::channel::<sync::SyncMsg>();
|
||||
|
||||
let paused_until = pause::load_paused_until(&db);
|
||||
let pause = pause::SyncPause::load(db.clone());
|
||||
let events: Arc<events::EventHub> = Arc::default();
|
||||
let gallery_dir = control_socket.with_file_name("gallery-catalog");
|
||||
let gallery =
|
||||
gallery_session.map(|session| Arc::new(super::gallery::Gallery::new(gallery_dir, session)));
|
||||
let gallery = gallery_session.map(|session| {
|
||||
Arc::new(super::gallery::Gallery::new(
|
||||
gallery_dir,
|
||||
session,
|
||||
client.clone(),
|
||||
events.clone(),
|
||||
db.clone(),
|
||||
))
|
||||
});
|
||||
let cache = Arc::new(cache);
|
||||
let shutdown = Arc::new(crate::shutdown::Shutdown::default());
|
||||
let transfers = TransferRegistry::new();
|
||||
let services = ServiceBoard::default();
|
||||
let sync = sync::SyncParts {
|
||||
store: db.clone(),
|
||||
drive: drive.clone(),
|
||||
@@ -510,49 +520,64 @@ pub(crate) fn mount_with(
|
||||
unscanned: Arc::default(),
|
||||
abandon: Arc::default(),
|
||||
events_read_at: Arc::new(AtomicI64::new(0)),
|
||||
local_dirty: Arc::default(),
|
||||
roots: Arc::default(),
|
||||
admission: Arc::new(pdfs_sched::Classes::new(|class| match class {
|
||||
pdfs_sched::Class::Mirror => sync::SYNC_CONCURRENCY,
|
||||
pdfs_sched::Class::Listing => super::listing::COLD_LISTINGS,
|
||||
})),
|
||||
};
|
||||
let state = Arc::new(Ranked::new(
|
||||
Rank::State,
|
||||
State::new(db.clone(), share_access),
|
||||
));
|
||||
let sharing = super::sharing::Sharing::new(
|
||||
client.clone(),
|
||||
drive.clone(),
|
||||
rt.clone(),
|
||||
cache.clone(),
|
||||
transfers.clone(),
|
||||
state.clone(),
|
||||
);
|
||||
let core = Core {
|
||||
drive,
|
||||
drive_calls,
|
||||
client,
|
||||
gallery,
|
||||
rt: rt.clone(),
|
||||
maintenance: Arc::new(Mutex::new(Default::default())),
|
||||
maintenance: super::maintenance::Maintenance::new(
|
||||
db.clone(),
|
||||
transfers.clone(),
|
||||
services.clone(),
|
||||
),
|
||||
primary_root_uid: root.uid.clone(),
|
||||
primary: true,
|
||||
state: Arc::new(Ranked::new(
|
||||
Rank::State,
|
||||
State::new(db.clone(), share_access),
|
||||
)),
|
||||
root: Arc::new(OnceLock::new()),
|
||||
state: state.clone(),
|
||||
cache,
|
||||
reads: super::reads::ReadState::new(),
|
||||
workers: Arc::new(Workers::new(FUSE_WORKERS)?),
|
||||
db,
|
||||
online: Arc::new(AtomicBool::new(online)),
|
||||
link: Arc::new(link::Link::starting(start == Start::SessionExpired)),
|
||||
sync_paused_until: Arc::new(AtomicI64::new(paused_until)),
|
||||
pending: Arc::new(Mutex::new(HashMap::new())),
|
||||
hidden: Arc::new(Mutex::new(HashSet::new())),
|
||||
link: Arc::new(link::Link::starting(online, start == Start::SessionExpired)),
|
||||
pause,
|
||||
drain: super::drain::DrainState::new(),
|
||||
pin_work: Arc::new(Mutex::new(Default::default())),
|
||||
sizes: super::sizes::SizeState::new(),
|
||||
trash: super::trash::TrashState::new(),
|
||||
trash_jobs: super::trash::TrashState::new(),
|
||||
shared: super::shared::SharedState::new(),
|
||||
quota_cache: super::sharing::QuotaCache::new(),
|
||||
quota: super::quota::QuotaCache::new(),
|
||||
sharing,
|
||||
sweep: super::sweep::SweepState::new(sweep_mode),
|
||||
writes: super::writes::WriteState::new(),
|
||||
session: super::session::SessionCells::new(),
|
||||
shutdown,
|
||||
services: ServiceBoard::default(),
|
||||
services: services.clone(),
|
||||
photo_jobs: super::photos::PhotoJobs::new(),
|
||||
local_first,
|
||||
self_changes: Arc::new(Mutex::new(HashMap::new())),
|
||||
notifier: Arc::new(OnceLock::new()),
|
||||
session_live: Arc::new(AtomicBool::new(false)),
|
||||
transfers,
|
||||
sync,
|
||||
events: Arc::new(Default::default()),
|
||||
events,
|
||||
indexing: Arc::new(AtomicBool::new(false)),
|
||||
pending_probe: Arc::default(),
|
||||
listing_flights: Arc::default(),
|
||||
mounts: Arc::new(Mutex::new(SecondaryMountRegistry::default())),
|
||||
states: Arc::new(StateRegistry::default()),
|
||||
};
|
||||
@@ -563,14 +588,17 @@ pub(crate) fn mount_with(
|
||||
|
||||
// Writes queued by a previous run (or left behind by a crash) are still owed
|
||||
// an upload, and reads must be served from their staged blobs until they land.
|
||||
core.hydrate_pending();
|
||||
core.recovery().hydrate_pending();
|
||||
// A replacing rename a stop cut off: its victim comes back, or its end
|
||||
// state stands. After `hydrate_pending`, which hides queued trashes.
|
||||
core.recovery().settle_replaces();
|
||||
// Then the writes that were fsynced but never closed, which the cache moved
|
||||
// aside at open. After `hydrate_pending`, so a recovered partial write can
|
||||
// see an already-queued write to the same node.
|
||||
core.recover_fsynced_writes();
|
||||
core.recovery().recover_fsynced_writes();
|
||||
// And finally the staged blobs neither of those accounts for: bytes a
|
||||
// failed release left behind with nothing pointing at them.
|
||||
core.reconcile_staging();
|
||||
core.recovery().reconcile_staging();
|
||||
// Several drain workers over one queue. One thread meant a single large
|
||||
// upload held every queued rename, trash and small write behind it for as
|
||||
// long as it ran; the claim column (`Db::claim_next_due_op`) keeps the
|
||||
@@ -582,93 +610,49 @@ pub(crate) fn mount_with(
|
||||
// in-process remount into a second generation of drain workers, sync engines
|
||||
// and sweeps all operating on a mount that no longer exists (`docs/BUGS.md` B44).
|
||||
let mut workers = Services::new(core.services.clone());
|
||||
for worker in 0..DRAIN_WORKERS {
|
||||
let drain_core = core.clone();
|
||||
// The drain workers wait on their own condvar, which a stop has to
|
||||
// notify; one notify wakes them all.
|
||||
let wake: Option<Wake> = (worker == 0).then(|| {
|
||||
let core = core.clone();
|
||||
Box::new(move || core.wake_drain()) as Wake
|
||||
});
|
||||
let spawned = workers.spawn(&format!("pdfs-drain-{worker}"), wake, move || {
|
||||
drain_core.run_pending_drain(worker == 0)
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
let mut list: Vec<Box<dyn Service>> = Vec::new();
|
||||
for index in 0..DRAIN_WORKERS {
|
||||
list.push(Box::new(services::DrainWorker {
|
||||
core: core.clone(),
|
||||
index,
|
||||
}));
|
||||
}
|
||||
|
||||
// Start the folder-sync engine. It watches every mirror folder, polls the
|
||||
// remotes, and reconciles on its own thread — never in front of a FUSE call.
|
||||
// It waits on its channel, so a stop sends it `Stop`.
|
||||
{
|
||||
let syncer = core.syncer();
|
||||
let tx = core.sync.tx.clone();
|
||||
let wake: Wake = Box::new(move || {
|
||||
let _ = tx.send(sync::SyncMsg::Stop);
|
||||
});
|
||||
if let Err(error) =
|
||||
workers.spawn("pdfs-sync", Some(wake), move || sync::run(syncer, sync_rx))
|
||||
{
|
||||
warn!(%error, "failed to start sync engine");
|
||||
}
|
||||
}
|
||||
// A timed pause persisted by an earlier run still has to end on time.
|
||||
if pause::paused_at(paused_until, now_secs()) && paused_until != pause::PAUSED_INDEFINITELY {
|
||||
core.arm_pause_timer(paused_until);
|
||||
}
|
||||
|
||||
// Reconcile leftover `(sync-conflict …)` copies: drop the ones that turned
|
||||
// out identical to the live file, surface the ones that genuinely diverge.
|
||||
// Its own thread — it enumerates and trashes, and must never block a FUSE call.
|
||||
list.push(Box::new(services::SyncEngine {
|
||||
syncer: core.syncer(),
|
||||
tx: core.sync.tx.clone(),
|
||||
rx: sync_rx,
|
||||
}));
|
||||
// `Off` skips the thread entirely rather than starting an idle one, so the
|
||||
// setting is verifiable from the outside (`ls /proc/<pid>/task/*/comm`).
|
||||
if sweep_mode == SweepMode::Off {
|
||||
info!("conflict sweep disabled by configuration");
|
||||
} else {
|
||||
info!(mode = ?sweep_mode, "conflict sweep enabled");
|
||||
let sweep_core = core.clone();
|
||||
let spawned = workers.spawn("pdfs-conflict-sweep", None, move || {
|
||||
sweep_core.run_conflict_sweep_loop()
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
list.push(Box::new(services::ConflictSweep(core.sweeper())));
|
||||
}
|
||||
|
||||
// Watch the link for the life of the mount: a mount from the cache waits for
|
||||
// the network to come back, and an online one can lose it at any moment and
|
||||
// must notice it coming back just the same.
|
||||
{
|
||||
let probe_core = core.clone();
|
||||
let spawned = workers.spawn("pdfs-online-probe", None, move || {
|
||||
probe_core.run_online_probe()
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
}
|
||||
|
||||
// Keep pinned files on this computer through changes made elsewhere, and
|
||||
// fetch the ones a failed or missed download left out (`docs/BUGS.md`
|
||||
// B282). Its own thread: a check lists folders and downloads files.
|
||||
{
|
||||
let keeper_core = core.clone();
|
||||
let spawned = workers.spawn("pdfs-pin-keeper", None, move || {
|
||||
keeper_core.run_pin_keeper()
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
}
|
||||
|
||||
// Keep the launcher prompt's "This computer" index fresh. Its own thread:
|
||||
// the walk is I/O-heavy and must never sit in front of a FUSE callback.
|
||||
list.push(Box::new(services::OnlineProbe(core.online_probe())));
|
||||
list.push(Box::new(services::PinKeeper(core.pin_keeper())));
|
||||
if matches!(host, Host::Daemon) {
|
||||
if let Some(gallery) = &core.gallery {
|
||||
rt.spawn(gallery.clone().poll(core.clone()));
|
||||
}
|
||||
let db = core.db.clone();
|
||||
let indexing = core.indexing.clone();
|
||||
let transfers = core.transfers.clone();
|
||||
let mountpoint = mountpoint.to_path_buf();
|
||||
let shutdown = core.shutdown.clone();
|
||||
let spawned = workers.spawn("pdfs-localindex", None, move || {
|
||||
run_local_index(db, indexing, transfers, mountpoint, shutdown)
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
list.push(Box::new(services::LocalIndex {
|
||||
db: core.db.clone(),
|
||||
indexing: core.indexing.clone(),
|
||||
transfers: core.transfers.clone(),
|
||||
mountpoint: mountpoint.to_path_buf(),
|
||||
shutdown: core.shutdown.clone(),
|
||||
}));
|
||||
}
|
||||
for service in list {
|
||||
let started = workers.start(service);
|
||||
keep_or_abandon(&core, control_socket, &mut workers, started)?;
|
||||
}
|
||||
if matches!(host, Host::Daemon)
|
||||
&& let Some(gallery) = &core.gallery
|
||||
{
|
||||
workers.spawn_task(&rt, "pdfs-gallery", gallery.clone().poll());
|
||||
}
|
||||
// A timed pause persisted by an earlier run still has to end on time.
|
||||
if let Some(until) = core.pause.deadline() {
|
||||
core.arm_pause_timer(until);
|
||||
}
|
||||
|
||||
// Bind the control socket before the FUSE session takes over the thread. A
|
||||
@@ -708,23 +692,14 @@ pub(crate) fn mount_with(
|
||||
// mid-transfer can abort it rather than block `join` (see `abort_fuse_connection`).
|
||||
let main_conn = fuse_connection_id(mountpoint);
|
||||
{
|
||||
let control_core = core.clone();
|
||||
let username = username.clone();
|
||||
let mountpoint = mountpoint.to_path_buf();
|
||||
// The listener blocks in `accept`, which only returns when a connection
|
||||
// arrives, so a stop connects to it. Connect while the socket still
|
||||
// exists, which is the point of the poke, then unlink it so nothing else
|
||||
// can arrive behind it. The listener checks the stop flag after every
|
||||
// accept, so a connection that races the unlink cannot put it back to
|
||||
// sleep.
|
||||
let socket = control_socket.to_path_buf();
|
||||
let wake: Wake = Box::new(move || {
|
||||
let _ = std::os::unix::net::UnixStream::connect(&socket);
|
||||
let _ = std::fs::remove_file(&socket);
|
||||
});
|
||||
match workers.spawn("pdfs-control", Some(wake), move || {
|
||||
run_control_socket(control_core, username, mountpoint, listener)
|
||||
}) {
|
||||
let control = services::ControlListener {
|
||||
core: core.clone(),
|
||||
username: username.clone(),
|
||||
mountpoint: mountpoint.to_path_buf(),
|
||||
listener,
|
||||
socket: control_socket.to_path_buf(),
|
||||
};
|
||||
match workers.start(Box::new(control)) {
|
||||
Ok(()) => {}
|
||||
Err(error) => {
|
||||
// A failure here abandons the mount, so the background threads
|
||||
@@ -736,7 +711,7 @@ pub(crate) fn mount_with(
|
||||
warn!(id, error = %unmount_error, "secondary teardown after control startup failure failed");
|
||||
}
|
||||
}
|
||||
if let Err(unmount_error) = teardown_session(&core.session_live, || {
|
||||
if let Err(unmount_error) = teardown_session(&core.session.session_live, || {
|
||||
umount_session_unblocked(bg, main_conn)
|
||||
}) {
|
||||
warn!(error = %unmount_error, "unmount after control startup failure failed");
|
||||
@@ -746,34 +721,19 @@ pub(crate) fn mount_with(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Publishes what changes without one place to publish it from (status,
|
||||
// transfers, sync progress) to the front-ends subscribed on that socket.
|
||||
{
|
||||
let sampler_core = core.clone();
|
||||
let username = username.clone();
|
||||
let mountpoint = mountpoint.to_path_buf();
|
||||
if let Err(error) = workers.spawn("pdfs-events", None, move || {
|
||||
events::run_event_sampler(sampler_core, username, mountpoint)
|
||||
}) {
|
||||
// Not fatal: front-ends still get every published change, only
|
||||
// not the sampled ones.
|
||||
warn!(error = %error, "could not start the event sampler");
|
||||
}
|
||||
}
|
||||
// The supervisor watches the pool and answers the systemd watchdog. Started
|
||||
// after the listener, because its liveness probe is a round trip over that
|
||||
// socket.
|
||||
{
|
||||
let supervisor_core = core.clone();
|
||||
let socket = control_socket.to_path_buf();
|
||||
if let Err(error) = workers.spawn("pdfs-supervisor", None, move || {
|
||||
supervisor::run(supervisor_core, socket)
|
||||
}) {
|
||||
// Not fatal: the mount works without a supervisor, it just goes back
|
||||
// to being undiagnosable if it wedges.
|
||||
warn!(error = %error, "could not start the daemon supervisor");
|
||||
}
|
||||
}
|
||||
// The supervisor's liveness probe is a round trip over the control socket,
|
||||
// so it starts after the listener. Both are optional.
|
||||
let sampler = services::EventSampler {
|
||||
core: core.clone(),
|
||||
username: username.clone(),
|
||||
mountpoint: mountpoint.to_path_buf(),
|
||||
};
|
||||
let watchdog = services::Supervisor {
|
||||
core: core.clone(),
|
||||
socket: control_socket.to_path_buf(),
|
||||
};
|
||||
start_late(&mut workers, Box::new(sampler));
|
||||
start_late(&mut workers, Box::new(watchdog));
|
||||
// The mount is live and the control socket answers: this is the moment the
|
||||
// unit is actually usable, which is what `Type=notify` reports. Whatever
|
||||
// failure an earlier attempt recorded for the front ends is over.
|
||||
@@ -798,31 +758,41 @@ 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");
|
||||
}
|
||||
}
|
||||
// Hold off a shutdown while changes exist only here (B66). Only the real
|
||||
// daemon: a simulation's queue is not the user's data.
|
||||
if matches!(host, Host::Daemon) {
|
||||
let inhibit_core = core.clone();
|
||||
if let Err(error) = workers.spawn("pdfs-inhibit", None, move || {
|
||||
crate::inhibit::run(inhibit_core)
|
||||
}) {
|
||||
warn!(%error, "start the shutdown inhibitor failed");
|
||||
}
|
||||
start_late(
|
||||
&mut workers,
|
||||
Box::new(services::Inhibitor {
|
||||
db: core.db.clone(),
|
||||
shutdown: core.shutdown.clone(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Stop signals (SIGTERM from `systemctl --user stop`, SIGINT from Ctrl-C)
|
||||
@@ -844,7 +814,7 @@ pub(crate) fn mount_with(
|
||||
Ok(()) => {
|
||||
info!("stop requested; unmounting");
|
||||
core.mounts.lock().close();
|
||||
if let Err(e) = teardown_session(&core.session_live, || {
|
||||
if let Err(e) = teardown_session(&core.session.session_live, || {
|
||||
umount_session_unblocked(bg, main_conn)
|
||||
}) {
|
||||
warn!(error = %e, "umount_and_join failed");
|
||||
@@ -856,7 +826,7 @@ pub(crate) fn mount_with(
|
||||
{
|
||||
info!("unmounting to resume the stored session");
|
||||
core.mounts.lock().close();
|
||||
if let Err(e) = teardown_session(&core.session_live, || {
|
||||
if let Err(e) = teardown_session(&core.session.session_live, || {
|
||||
umount_session_unblocked(bg, main_conn)
|
||||
}) {
|
||||
warn!(error = %e, "umount_and_join failed");
|
||||
@@ -867,7 +837,7 @@ pub(crate) fn mount_with(
|
||||
if bg.guard.is_finished() {
|
||||
info!("mount ended externally");
|
||||
core.mounts.lock().close();
|
||||
if let Err(e) = teardown_session(&core.session_live, || bg.join()) {
|
||||
if let Err(e) = teardown_session(&core.session.session_live, || bg.join()) {
|
||||
warn!(error = %e, "session join failed");
|
||||
}
|
||||
break MountOutcome::Unmounted;
|
||||
@@ -876,7 +846,7 @@ pub(crate) fn mount_with(
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
|
||||
// Signal task gone (failed to install); fall back to join.
|
||||
core.mounts.lock().close();
|
||||
let _ = teardown_session(&core.session_live, || bg.join());
|
||||
let _ = teardown_session(&core.session.session_live, || bg.join());
|
||||
break MountOutcome::Unmounted;
|
||||
}
|
||||
}
|
||||
@@ -971,6 +941,15 @@ fn abandon_workers(core: &Core, control_socket: &Path, workers: Services) {
|
||||
halt_workers(core, control_socket, workers);
|
||||
}
|
||||
|
||||
/// Start a service once the session is live. Past that point a failure no
|
||||
/// longer abandons the mount, so even a required one is only logged.
|
||||
fn start_late(workers: &mut Services, service: Box<dyn Service>) {
|
||||
let name = service.name();
|
||||
if let Err(error) = workers.start(service) {
|
||||
warn!(service = name, %error, "service did not start");
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep a worker the mount just spawned, or, if the spawn failed, stop the
|
||||
/// ones already running and hand the error back.
|
||||
fn keep_or_abandon(
|
||||
|
||||
@@ -51,41 +51,106 @@ fn store_folder_paused(db: &Db, id: i64, paused: bool) -> pdfs_core::Result<()>
|
||||
/// A pause with no end time: it lasts until the user resumes.
|
||||
pub(crate) const PAUSED_INDEFINITELY: i64 = i64::MAX;
|
||||
|
||||
/// The persisted pause, or `0` when there is none (or it cannot be read — a
|
||||
/// broken state row must not keep sync paused forever).
|
||||
pub(crate) fn load_paused_until(db: &Db) -> i64 {
|
||||
match db.state_i64(PAUSED_UNTIL_KEY) {
|
||||
Ok(Some(until)) => until,
|
||||
Ok(None) => 0,
|
||||
Err(error) => {
|
||||
warn!(%error, "reading the sync pause failed; treating sync as running");
|
||||
0
|
||||
/// The global pause: when it ends, in memory and in the database.
|
||||
///
|
||||
/// The value is the Unix second the pause ends, [`PAUSED_INDEFINITELY`] for
|
||||
/// "until resumed", or `0` when sync runs. Only this type reads or writes it;
|
||||
/// the rest of the daemon asks [`Core::sync_paused`].
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct SyncPause {
|
||||
until: Arc<AtomicI64>,
|
||||
db: Arc<Db>,
|
||||
}
|
||||
|
||||
impl SyncPause {
|
||||
/// The persisted pause, or none when there is no row or it cannot be read:
|
||||
/// a broken state row must not keep sync paused forever.
|
||||
pub(crate) fn load(db: Arc<Db>) -> Self {
|
||||
let until = match db.state_i64(PAUSED_UNTIL_KEY) {
|
||||
Ok(Some(until)) => until,
|
||||
Ok(None) => 0,
|
||||
Err(error) => {
|
||||
warn!(%error, "reading the sync pause failed; treating sync as running");
|
||||
0
|
||||
}
|
||||
};
|
||||
Self {
|
||||
until: Arc::new(AtomicI64::new(until)),
|
||||
db,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_paused(&self) -> bool {
|
||||
paused_at(self.until.load(Ordering::Relaxed), now_secs())
|
||||
}
|
||||
|
||||
/// `None` when not paused, `Some(None)` when paused until resumed,
|
||||
/// `Some(Some(t))` when it ends at Unix second `t`.
|
||||
fn status(&self) -> Option<Option<i64>> {
|
||||
let until = self.until.load(Ordering::Relaxed);
|
||||
match paused_at(until, now_secs()) {
|
||||
false => None,
|
||||
true if until == PAUSED_INDEFINITELY => Some(None),
|
||||
true => Some(Some(until)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of a timed pause still in force, which needs a timer.
|
||||
pub(crate) fn deadline(&self) -> Option<i64> {
|
||||
self.status().flatten()
|
||||
}
|
||||
|
||||
/// Persist `value`, then take it. A pause that cannot be saved is not
|
||||
/// taken, so what the user sees never outlives a restart by surprise.
|
||||
fn store(&self, value: i64) -> Result<(), CoreError> {
|
||||
let persisted = match value {
|
||||
0 => self.db.clear_state(PAUSED_UNTIL_KEY),
|
||||
value => self.db.set_state_i64(PAUSED_UNTIL_KEY, value),
|
||||
};
|
||||
if let Err(error) = persisted {
|
||||
return Err(CoreError::internal(format!(
|
||||
"saving the sync pause: {error}"
|
||||
)));
|
||||
}
|
||||
self.until.store(value, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// End the pause that lasts until `until`, if it is still the one in
|
||||
/// force. Returns whether it was: a later pause or resume replaced it
|
||||
/// otherwise, and the timer that asks has nothing to do.
|
||||
fn expire(&self, until: i64) -> bool {
|
||||
if self
|
||||
.until
|
||||
.compare_exchange(until, 0, Ordering::Relaxed, Ordering::Relaxed)
|
||||
.is_err()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let Err(error) = self.db.clear_state(PAUSED_UNTIL_KEY) {
|
||||
warn!(%error, "clearing an expired sync pause failed");
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a pause lasting until `until` is still in force at `now` (both Unix
|
||||
/// seconds). `0` is "not paused".
|
||||
pub(crate) fn paused_at(until: i64, now: i64) -> bool {
|
||||
fn paused_at(until: i64, now: i64) -> bool {
|
||||
until != 0 && now < until
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// True while the user has sync paused.
|
||||
pub(crate) fn sync_paused(&self) -> bool {
|
||||
paused_at(self.sync_paused_until.load(Ordering::Relaxed), now_secs())
|
||||
self.pause.is_paused()
|
||||
}
|
||||
|
||||
/// The pause's end, for status reporting: `None` when not paused,
|
||||
/// `Some(None)` when paused until resumed, `Some(Some(t))` when it ends at
|
||||
/// Unix second `t`.
|
||||
pub(crate) fn sync_pause(&self) -> Option<Option<i64>> {
|
||||
let until = self.sync_paused_until.load(Ordering::Relaxed);
|
||||
match paused_at(until, now_secs()) {
|
||||
false => None,
|
||||
true if until == PAUSED_INDEFINITELY => Some(None),
|
||||
true => Some(Some(until)),
|
||||
}
|
||||
self.pause.status()
|
||||
}
|
||||
|
||||
/// Pause sync until Unix second `until` (`None`: until resumed), or resume
|
||||
@@ -103,16 +168,7 @@ impl Core {
|
||||
}
|
||||
(true, Some(until)) => until,
|
||||
};
|
||||
let persisted = match value {
|
||||
0 => self.db.clear_state(PAUSED_UNTIL_KEY),
|
||||
value => self.db.set_state_i64(PAUSED_UNTIL_KEY, value),
|
||||
};
|
||||
if let Err(error) = persisted {
|
||||
return Err(CoreError::internal(format!(
|
||||
"saving the sync pause: {error}"
|
||||
)));
|
||||
}
|
||||
self.sync_paused_until.store(value, Ordering::Relaxed);
|
||||
self.pause.store(value)?;
|
||||
match value {
|
||||
0 => {
|
||||
info!("sync resumed");
|
||||
@@ -182,24 +238,15 @@ 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;
|
||||
}
|
||||
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();
|
||||
}
|
||||
});
|
||||
let spawned = self.services.spawn_job("pdfs-pause", move || {
|
||||
if !core.shutdown.sleep(wait) {
|
||||
return;
|
||||
}
|
||||
if core.pause.expire(until) {
|
||||
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.
|
||||
|
||||
+138
-1621
File diff suppressed because it is too large.
Load diff
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! Both are persisted projections of what the photos volume reports, refreshed
|
||||
//! on the same stale-while-serving rule as the timeline
|
||||
//! ([`crate::photos`]): a listing already on disk is served immediately and
|
||||
//! ([`super`]): a listing already on disk is served immediately and
|
||||
//! refreshed behind the caller, and only an empty one waits on the network.
|
||||
//!
|
||||
//! An album is a folder node carrying album properties, so it has a name like
|
||||
@@ -23,15 +23,16 @@ use proton_drive_rs::NodeKind;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use tracing::warn;
|
||||
|
||||
use super::{
|
||||
ALBUM_SYNCED_PREFIX, ALBUMS_SYNCED_MS, Core, PHOTOS_AVAILABLE, TIMELINE_ENRICH_CHUNK,
|
||||
TIMELINE_TTL, link, now_ms, parse_uid,
|
||||
use super::Photos;
|
||||
use crate::{
|
||||
ALBUM_SYNCED_PREFIX, ALBUMS_SYNCED_MS, PHOTOS_AVAILABLE, TIMELINE_ENRICH_CHUNK, TIMELINE_TTL,
|
||||
link, listing::listing_stale, now_ms, parse_uid,
|
||||
};
|
||||
|
||||
impl Core {
|
||||
impl Photos {
|
||||
/// The album listing, served from disk and refreshed behind the caller when
|
||||
/// stale. `None` means the account has no photos volume — the same signal
|
||||
/// [`Core::photos_timeline`] gives.
|
||||
/// [`Photos::photos_timeline`] gives.
|
||||
pub(crate) fn albums(&self) -> CoreResult<Option<Vec<AlbumInfo>>> {
|
||||
let count = self.db.albums_count().map_err(CoreError::from)?;
|
||||
if count == 0
|
||||
@@ -44,13 +45,13 @@ impl Core {
|
||||
// Nothing on disk, so this one request waits for the fetch — unless
|
||||
// the account is already known to have no photos volume.
|
||||
let known_empty = self.db.state_i64(PHOTOS_AVAILABLE).ok().flatten() == Some(0);
|
||||
if known_empty && !self.listing_stale(ALBUMS_SYNCED_MS, TIMELINE_TTL) {
|
||||
if known_empty && !listing_stale(&self.db, ALBUMS_SYNCED_MS, TIMELINE_TTL) {
|
||||
return Ok(None);
|
||||
}
|
||||
if !self.rt.block_on(self.refresh_albums())? {
|
||||
return Ok(None);
|
||||
}
|
||||
} else if self.listing_stale(ALBUMS_SYNCED_MS, TIMELINE_TTL) {
|
||||
} else if listing_stale(&self.db, ALBUMS_SYNCED_MS, TIMELINE_TTL) {
|
||||
self.spawn_albums_refresh();
|
||||
}
|
||||
|
||||
@@ -66,7 +67,7 @@ impl Core {
|
||||
.db
|
||||
.photo_projection_generation()
|
||||
.map_err(CoreError::from)?;
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
if link::bounded(photos.get_photos_root())
|
||||
.await
|
||||
.map_err(|e| CoreError::from_api(&e, "photos root"))?
|
||||
@@ -132,24 +133,19 @@ impl Core {
|
||||
|
||||
/// Refresh the album listing off the request path. At most one runs at a time.
|
||||
pub(crate) fn spawn_albums_refresh(&self) {
|
||||
if self
|
||||
.photo_jobs
|
||||
.albums_refreshing
|
||||
.swap(true, Ordering::SeqCst)
|
||||
{
|
||||
if self.jobs.albums_refreshing.swap(true, Ordering::SeqCst) {
|
||||
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"),
|
||||
}
|
||||
});
|
||||
let this = self.clone();
|
||||
self.services
|
||||
.spawn_task_job(&self.rt, "pdfs-albums-refresh", async move {
|
||||
let refreshed = this.refresh_albums().await;
|
||||
this.jobs.albums_refreshing.store(false, Ordering::SeqCst);
|
||||
match refreshed {
|
||||
Ok(_) => this.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
|
||||
@@ -176,14 +172,15 @@ impl Core {
|
||||
.is_none()
|
||||
{
|
||||
self.rt.block_on(self.refresh_album(album))?;
|
||||
} else if self.listing_stale(&stamp, TIMELINE_TTL) {
|
||||
let core = self.clone();
|
||||
} else if listing_stale(&self.db, &stamp, TIMELINE_TTL) {
|
||||
let this = 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) = this.refresh_album(&album).await {
|
||||
warn!(%album, error = %e, "background album refresh failed");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let page = self
|
||||
@@ -233,7 +230,7 @@ impl Core {
|
||||
.db
|
||||
.photo_projection_generation()
|
||||
.map_err(CoreError::from)?;
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
let items = link::bounded(photos.enumerate_album(album))
|
||||
.await
|
||||
.map_err(|e| CoreError::from_api(&e, "album"))?;
|
||||
@@ -283,11 +280,11 @@ impl Core {
|
||||
}
|
||||
|
||||
/// Create an album and return its uid. The listing is refreshed before
|
||||
/// answering, so the next [`Core::albums`] already shows it.
|
||||
/// answering, so the next [`Photos::albums`] already shows it.
|
||||
pub(crate) fn create_album(&self, name: &str) -> CoreResult<String> {
|
||||
let uid = self
|
||||
.rt
|
||||
.block_on(self.photos().create_album(name))
|
||||
.block_on(self.photos_api().create_album(name))
|
||||
.map_err(|e| CoreError::from_api(&e, "create album"))?;
|
||||
self.after_album_change(None);
|
||||
Ok(uid.to_string())
|
||||
@@ -295,7 +292,7 @@ impl Core {
|
||||
|
||||
pub(crate) fn rename_album(&self, album: &NodeUid, name: &str) -> CoreResult<()> {
|
||||
self.rt
|
||||
.block_on(self.photos().rename_album(album, name))
|
||||
.block_on(self.photos_api().rename_album(album, name))
|
||||
.map_err(|e| CoreError::from_api(&e, "rename album"))?;
|
||||
self.after_album_change(None);
|
||||
Ok(())
|
||||
@@ -305,7 +302,7 @@ impl Core {
|
||||
/// which only matters for photos that exist in the album alone.
|
||||
pub(crate) fn delete_album(&self, album: &NodeUid, delete_photos: bool) -> CoreResult<()> {
|
||||
self.rt
|
||||
.block_on(self.photos().delete_album(album, delete_photos))
|
||||
.block_on(self.photos_api().delete_album(album, delete_photos))
|
||||
.map_err(|e| CoreError::from_api(&e, "delete album"))?;
|
||||
let key = album.to_string();
|
||||
if let Err(error) = self.db.photos_delete(&[key]) {
|
||||
@@ -323,7 +320,7 @@ impl Core {
|
||||
) -> CoreResult<AlbumOutcome> {
|
||||
let outcomes = self
|
||||
.rt
|
||||
.block_on(self.photos().add_photos_to_album(album, photos))
|
||||
.block_on(self.photos_api().add_photos_to_album(album, photos))
|
||||
.map_err(|e| CoreError::from_api(&e, "add to album"))?;
|
||||
self.after_album_change(Some(album));
|
||||
Ok(album_outcome(outcomes))
|
||||
@@ -338,7 +335,7 @@ impl Core {
|
||||
) -> CoreResult<AlbumOutcome> {
|
||||
let outcomes = self
|
||||
.rt
|
||||
.block_on(self.photos().remove_photos_from_album(album, photos))
|
||||
.block_on(self.photos_api().remove_photos_from_album(album, photos))
|
||||
.map_err(|e| CoreError::from_api(&e, "remove from album"))?;
|
||||
self.after_album_change(Some(album));
|
||||
Ok(album_outcome(outcomes))
|
||||
@@ -361,7 +358,7 @@ impl Core {
|
||||
}
|
||||
|
||||
/// Drop the album listing's and every album's freshness stamp, so the next
|
||||
/// request re-enumerates. Paired with [`Core::invalidate_photos`] — a change
|
||||
/// request re-enumerates. Paired with [`Core::invalidate_photos`](crate::Core::invalidate_photos) — a change
|
||||
/// to the timeline can just as easily be a change to an album.
|
||||
pub(crate) fn invalidate_albums(&self) {
|
||||
let _ = self.db.clear_state(ALBUMS_SYNCED_MS);
|
||||
@@ -27,7 +27,7 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use proton_drive_rs::{PhotoTag, PhotoTagsUpdate, PhotoUploadMetadata};
|
||||
use tracing::{info, warn};
|
||||
|
||||
use super::Core;
|
||||
use super::Photos;
|
||||
use crate::parse_uid as parse_node_uid;
|
||||
use crate::transfers::CountingReader;
|
||||
|
||||
@@ -84,7 +84,7 @@ struct Candidate {
|
||||
albums: Vec<String>,
|
||||
}
|
||||
|
||||
impl Core {
|
||||
impl Photos {
|
||||
/// Re-date mis-dated photos. Blocking; run on its own thread.
|
||||
///
|
||||
/// `cancel` stops the run at the next photo boundary. A photo is only ever
|
||||
@@ -184,7 +184,7 @@ impl Core {
|
||||
/// trash the original. Every earlier step failing leaves the account exactly
|
||||
/// as it was.
|
||||
fn redate_one(&self, candidate: &Candidate, summary: &mut RedateSummary) -> CoreResult<()> {
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
let path = self.open_photo(&candidate.uid)?;
|
||||
let size = std::fs::metadata(&path)
|
||||
.map_err(|e| CoreError::internal(format!("stat {}: {e}", path.display())))?
|
||||
@@ -227,7 +227,7 @@ impl Core {
|
||||
match self.rt.block_on(photos.update_photos(&[update])) {
|
||||
// As in `set_photo_favorite`: claim our own echo, so the tag we
|
||||
// just set does not come back as a remote change.
|
||||
Ok(_) => self.note_self_change(&new_uid),
|
||||
Ok(_) => self.host.note_self_change(&new_uid),
|
||||
Err(e) => {
|
||||
warn!(name = candidate.name, error = %e, "cannot re-favorite re-dated photo")
|
||||
}
|
||||
@@ -287,9 +287,9 @@ impl Core {
|
||||
state.last = None;
|
||||
}
|
||||
|
||||
let core = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
let outcome = core.redate_photos(dry_run, limit, range, cancel);
|
||||
let this = self.clone();
|
||||
if let Err(error) = self.services.spawn_job("pdfs-redate", move || {
|
||||
let outcome = this.redate_photos(dry_run, limit, range, cancel);
|
||||
let mut state = REDATE.lock();
|
||||
state.running = false;
|
||||
state.cancel = None;
|
||||
@@ -310,7 +310,9 @@ impl Core {
|
||||
),
|
||||
Err(e) => warn!(error = %e, "photo re-date failed"),
|
||||
}
|
||||
});
|
||||
}) {
|
||||
tracing::warn!(%error, "could not start pdfs-redate");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ use tracing::{info, warn};
|
||||
|
||||
pub(crate) use pdfs_drive::digest::sha1_of;
|
||||
|
||||
use super::Core;
|
||||
use super::Photos;
|
||||
use crate::photos::can_make_thumbnail;
|
||||
use crate::transfers::CountingReader;
|
||||
|
||||
@@ -468,7 +468,7 @@ fn read_entry<R>(
|
||||
Ok(sink(&mut file))
|
||||
}
|
||||
|
||||
impl Core {
|
||||
impl Photos {
|
||||
/// Copy archive entry `entry` into the thumbnail staging folder and return
|
||||
/// its path. The caller removes it.
|
||||
fn stage_takeout_entry(
|
||||
@@ -611,7 +611,7 @@ impl Core {
|
||||
));
|
||||
}
|
||||
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
if self
|
||||
.rt
|
||||
.block_on(photos.get_photos_root())
|
||||
@@ -668,7 +668,7 @@ impl Core {
|
||||
report: &Reporter,
|
||||
) -> CoreResult<()> {
|
||||
report.phase(ImportPhase::Checking, 0);
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
let names: Vec<String> = planned.iter().map(|p| p.photo.name.clone()).collect();
|
||||
let collisions = self
|
||||
.rt
|
||||
@@ -919,7 +919,7 @@ impl Core {
|
||||
report.step();
|
||||
match done.result {
|
||||
Ok(uid) => {
|
||||
self.note_self_change(&uid);
|
||||
self.host.note_self_change(&uid);
|
||||
summary.uploaded += 1;
|
||||
summary.bytes += done.photo.size;
|
||||
if done.live {
|
||||
@@ -954,7 +954,7 @@ impl Core {
|
||||
tags: Vec<PhotoTag>,
|
||||
main_uid: Option<NodeUid>,
|
||||
) -> CoreResult<NodeUid> {
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
let guard = self.transfers.begin(
|
||||
photo.name.clone(),
|
||||
"",
|
||||
@@ -1035,7 +1035,7 @@ impl Core {
|
||||
tags_to_remove: Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
if let Err(e) = self.rt.block_on(self.photos().update_photos(&updates)) {
|
||||
if let Err(e) = self.rt.block_on(self.photos_api().update_photos(&updates)) {
|
||||
warn!(error = %e, "marking imported favorites failed");
|
||||
}
|
||||
}
|
||||
@@ -1049,7 +1049,7 @@ impl Core {
|
||||
summary: &mut ImportSummary,
|
||||
report: &Reporter,
|
||||
) -> CoreResult<()> {
|
||||
let photos = self.photos();
|
||||
let photos = self.photos_api();
|
||||
|
||||
// Existing albums by decrypted name, so a second import of the same
|
||||
// export adds to the album it made the first time instead of a twin.
|
||||
@@ -1152,14 +1152,14 @@ impl Core {
|
||||
state.save();
|
||||
}
|
||||
|
||||
let core = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
let this = self.clone();
|
||||
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.
|
||||
let job = core.transfers.begin_job("Importing Google Photos");
|
||||
let job = this.transfers.begin_job("Importing Google Photos");
|
||||
let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
core.import_takeout(&archives, dry_run, &cancel, &job)
|
||||
this.import_takeout(&archives, dry_run, &cancel, &job)
|
||||
}));
|
||||
// A panic must not leave the import marked as running for the
|
||||
// life of the daemon, refusing every later one.
|
||||
@@ -1179,14 +1179,16 @@ impl Core {
|
||||
}
|
||||
drop(job);
|
||||
if !dry_run {
|
||||
core.log_activity(
|
||||
this.host.log_activity(
|
||||
ActivityKind::Upload,
|
||||
"Google Photos import",
|
||||
"Google Photos import".to_string(),
|
||||
activity_line(&summary),
|
||||
summary.complete(),
|
||||
);
|
||||
}
|
||||
});
|
||||
}) {
|
||||
tracing::warn!(%error, "could not start pdfs-import");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,967 @@
|
||||
//! 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 Photos {
|
||||
/// [`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())
|
||||
}
|
||||
|
||||
/// [`Photos::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
|
||||
/// [`Photos::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)
|
||||
}
|
||||
|
||||
/// [`Photos::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_api()
|
||||
.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.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 [`Photos::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.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
|
||||
.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.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
|
||||
.jobs
|
||||
.file_thumb_generation
|
||||
.try_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
|
||||
Some(next(current))
|
||||
})
|
||||
.expect("generation update always succeeds");
|
||||
let generation = next(previous);
|
||||
self.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
|
||||
.jobs
|
||||
.file_thumb_generation
|
||||
.fetch_max(generation, Ordering::SeqCst);
|
||||
if generation > previous {
|
||||
self.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.jobs.thumb_gen.lock();
|
||||
uids.into_iter()
|
||||
.filter(|uid| inflight.insert(uid.clone()))
|
||||
.collect()
|
||||
};
|
||||
if fresh.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let this = 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(|| {
|
||||
this.generate_thumbs(&fresh, &tags, &names, job)
|
||||
}));
|
||||
let mut inflight = this.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.jobs.file_thumb_generation.load(Ordering::SeqCst) == generation
|
||||
}
|
||||
ThumbJob::Photos => true,
|
||||
ThumbJob::Build => !self.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 this = 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 !this.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 = this.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(),
|
||||
_ = this.jobs.file_thumb_cancel.notified() => {
|
||||
if !this.thumb_job_current(job) {
|
||||
return (uid, ThumbAttempt::Cancelled);
|
||||
}
|
||||
}
|
||||
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
|
||||
if !this.thumb_job_current(job) {
|
||||
return (uid, ThumbAttempt::Cancelled);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
ThumbJob::Build => loop {
|
||||
tokio::select! {
|
||||
permit = &mut acquire => break permit.ok(),
|
||||
_ = this.jobs.thumbnail_build_cancel.notified() => {
|
||||
if !this.thumb_job_current(job) {
|
||||
return (uid, ThumbAttempt::Cancelled);
|
||||
}
|
||||
}
|
||||
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
|
||||
if !this.thumb_job_current(job) {
|
||||
return (uid, ThumbAttempt::Cancelled);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
ThumbJob::Photos => acquire.await.ok(),
|
||||
};
|
||||
let Some(_permit) = _permit else {
|
||||
return (uid, ThumbAttempt::Unavailable);
|
||||
};
|
||||
if !this.thumb_job_current(job) {
|
||||
return (uid, ThumbAttempt::Cancelled);
|
||||
}
|
||||
|
||||
let download_uid = uid.clone();
|
||||
let drive = this.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),
|
||||
_ = this.jobs.file_thumb_cancel.notified() => {
|
||||
if !this.thumb_job_current(job) {
|
||||
break None;
|
||||
}
|
||||
}
|
||||
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
|
||||
if !this.thumb_job_current(job) {
|
||||
break None;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
ThumbJob::Build => loop {
|
||||
tokio::select! {
|
||||
result = &mut download => break Some(result),
|
||||
_ = this.jobs.thumbnail_build_cancel.notified() => {
|
||||
if !this.thumb_job_current(job) {
|
||||
break None;
|
||||
}
|
||||
}
|
||||
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
|
||||
if !this.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 !this.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 = this.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 && this.thumb_job_current(job) => {
|
||||
this.folder_cover_thumbnail(&uid, staging).await
|
||||
}
|
||||
made => made,
|
||||
};
|
||||
if !this.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.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.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.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.jobs.thumbnail_build.lock();
|
||||
if !thumbnail_build_may_start(&status, &path)? {
|
||||
return Ok(status.clone());
|
||||
}
|
||||
self.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 this = self.clone();
|
||||
self.rt.spawn_blocking(move || {
|
||||
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
this.run_thumbnail_build(root)
|
||||
}))
|
||||
.is_err()
|
||||
{
|
||||
let mut status = this.jobs.thumbnail_build.lock();
|
||||
status.running = false;
|
||||
status.scanning = false;
|
||||
status.message = Some("Thumbnail generation stopped unexpectedly".to_string());
|
||||
this.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.jobs.thumbnail_build.lock();
|
||||
let cancelled = status.running;
|
||||
if cancelled {
|
||||
self.jobs
|
||||
.thumbnail_build_cancelled
|
||||
.store(true, Ordering::SeqCst);
|
||||
}
|
||||
(status.clone(), cancelled)
|
||||
};
|
||||
if cancelled {
|
||||
self.jobs.thumbnail_build_cancel.notify_waiters();
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
pub(crate) fn finish_thumbnail_build(&self) {
|
||||
let mut status = self.jobs.thumbnail_build.lock();
|
||||
let cancelled = self
|
||||
.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.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
|
||||
self.finish_thumbnail_build();
|
||||
return;
|
||||
}
|
||||
let listing = self.host.list_dir(&folder);
|
||||
{
|
||||
let mut status = self.jobs.thumbnail_build.lock();
|
||||
status.folders_scanned += 1;
|
||||
}
|
||||
let entries = match listing {
|
||||
Ok(entries) => entries,
|
||||
Err(error) => {
|
||||
let mut status = self.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.jobs.thumbnail_build.lock();
|
||||
status.images_found += found_here;
|
||||
status.completed += invalid_here;
|
||||
status.failed += invalid_here;
|
||||
}
|
||||
|
||||
self.jobs.thumbnail_build.lock().scanning = false;
|
||||
if self.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.jobs.thumbnail_build.lock().completed += 1;
|
||||
} else if self
|
||||
.jobs
|
||||
.thumbnail_misses
|
||||
.lock()
|
||||
.local_contains(&(uid.clone(), ttype), modified)
|
||||
{
|
||||
let mut status = self.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.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.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
|
||||
self.finish_thumbnail_build();
|
||||
return;
|
||||
}
|
||||
if self
|
||||
.cache
|
||||
.cached_thumbnail_path(uid, ttype, *modified)
|
||||
.is_some()
|
||||
{
|
||||
self.jobs.thumbnail_build.lock().completed += 1;
|
||||
break;
|
||||
}
|
||||
if self
|
||||
.jobs
|
||||
.thumbnail_misses
|
||||
.lock()
|
||||
.local_contains(&(uid.clone(), ttype), *modified)
|
||||
{
|
||||
let mut status = self.jobs.thumbnail_build.lock();
|
||||
status.completed += 1;
|
||||
status.failed += 1;
|
||||
break;
|
||||
}
|
||||
if self.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.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.jobs.thumb_gen.lock();
|
||||
for uid in &claimed {
|
||||
inflight.remove(uid);
|
||||
}
|
||||
}
|
||||
let mut status = self.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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,523 @@
|
||||
//! 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 Photos {
|
||||
#[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_api();
|
||||
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.host.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
|
||||
.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.jobs.similar_hashing.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
let this = self.clone();
|
||||
let spawned = self.services.spawn_job("pdfs-similar", move || {
|
||||
if let Err(e) = this.hash_similar() {
|
||||
warn!(error = %e, "similar-photo hashing failed");
|
||||
}
|
||||
this.jobs.similar_hashing.store(false, Ordering::SeqCst);
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
warn!(error = %e, "could not start similar-photo hashing");
|
||||
self.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
|
||||
}
|
||||
|
||||
/// 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_api();
|
||||
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.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.jobs.timeline_refreshing.swap(true, Ordering::SeqCst) {
|
||||
while self.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.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.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.jobs.timeline_refreshing.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
let this = self.clone();
|
||||
self.services
|
||||
.spawn_task_job(&self.rt, "pdfs-timeline-refresh", async move {
|
||||
let refreshed = this.refresh_timeline().await;
|
||||
this.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(_) => this.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.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.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_api();
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Trashing photos by uid. This stays on [`Core`] rather than [`Photos`]: it
|
||||
//! checks write authority against the tree, drops open readers and clears the
|
||||
//! trash listing, all of which belong to the filesystem side.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Core {
|
||||
/// 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.photos().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.photos().invalidate_albums();
|
||||
self.invalidate_trash();
|
||||
|
||||
let failed = failed
|
||||
.into_iter()
|
||||
.map(|(uid, error)| (uid.to_string(), error.to_string()))
|
||||
.collect();
|
||||
Ok((trashed, failed))
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
|
||||
+367
-325
@@ -21,8 +21,13 @@ use pdfs_core::{CoreError, CoreResult};
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use tracing::{info, warn};
|
||||
|
||||
use super::devices::Devices;
|
||||
use super::drive::DriveApi;
|
||||
use super::sync;
|
||||
use super::{Core, now_secs, parse_uid, this_hostname};
|
||||
use pdfs_core::lifecycle::ServiceBoard;
|
||||
use pdfs_store::db::Db;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Coalescing flags for background profile saves.
|
||||
///
|
||||
@@ -40,331 +45,32 @@ fn save_state() -> &'static (AtomicBool, AtomicBool) {
|
||||
SAVE_STATE.get_or_init(|| (AtomicBool::new(false), AtomicBool::new(false)))
|
||||
}
|
||||
|
||||
/// The backup of this machine's arrangement on Drive: which folders sync where
|
||||
/// and in which mode. It writes the profile and reads the ones other machines
|
||||
/// wrote, to offer their folders for restore.
|
||||
///
|
||||
/// It needs nothing from the filesystem. [`Core::profile`] builds one on
|
||||
/// demand. A clone shares everything, which is how a save moves onto a
|
||||
/// background job.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ProfileBackup {
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
db: Arc<Db>,
|
||||
services: ServiceBoard,
|
||||
devices: Devices,
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// Note that the arrangement this machine's profile describes has changed,
|
||||
/// and upload a fresh profile in the background.
|
||||
///
|
||||
/// Fire-and-forget by design: callers are mutation paths (add/remove a sync
|
||||
/// folder, switch a mode, pin a node, save settings) whose success does not
|
||||
/// depend on the backup succeeding.
|
||||
pub(crate) fn touch_profile(&self) {
|
||||
let (saving, dirty) = save_state();
|
||||
dirty.store(true, Ordering::SeqCst);
|
||||
// Someone is already uploading; they will see DIRTY and take another lap.
|
||||
if saving.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
/// The profile backup.
|
||||
pub(crate) fn profile(&self) -> ProfileBackup {
|
||||
ProfileBackup {
|
||||
drive: self.drive.clone(),
|
||||
rt: self.rt.clone(),
|
||||
db: self.db.clone(),
|
||||
services: self.services.clone(),
|
||||
devices: self.devices(),
|
||||
}
|
||||
let core = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
let (saving, dirty) = save_state();
|
||||
while dirty.swap(false, Ordering::SeqCst) {
|
||||
if let Err(e) = core.save_profile() {
|
||||
warn!(error = %e.message, "profile backup failed");
|
||||
break;
|
||||
}
|
||||
}
|
||||
saving.store(false, Ordering::SeqCst);
|
||||
});
|
||||
}
|
||||
|
||||
/// Serialize this machine's arrangement and upload it to its own
|
||||
/// `profile-<machine id>.json` inside the device's `.proton-drive-linux`
|
||||
/// folder, replacing any existing one.
|
||||
///
|
||||
/// Each machine writes its own file because several computers may sync
|
||||
/// into one device. They used to share `profile.json`, and each save
|
||||
/// replaced the other computers' folders with its own (B252). That file is
|
||||
/// left as it is, so a client before 3.5.0 still finds it.
|
||||
///
|
||||
/// Does nothing when no device is registered: a machine that has never
|
||||
/// synced a folder has nothing to describe, and registering a device just to
|
||||
/// hold an empty profile would put a stray computer in the user's Drive.
|
||||
pub(crate) fn save_profile(&self) -> CoreResult<()> {
|
||||
let Some(device) = self
|
||||
.db
|
||||
.device_get()
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let root_uid = parse_uid(&device.root_uid).ok_or_else(|| {
|
||||
CoreError::internal(format!("bad device root uid: {}", device.root_uid))
|
||||
})?;
|
||||
|
||||
let machine_id = pdfs_core::config::AppDirs::new()
|
||||
.and_then(|dirs| dirs.machine_id())
|
||||
.map_err(|e| CoreError::internal(format!("machine id: {e}")))?;
|
||||
let file_name = profile_file_name(&machine_id);
|
||||
let profile = self.build_profile(&device.uid, &machine_id)?;
|
||||
let bytes = profile.to_bytes().map_err(CoreError::internal)?;
|
||||
let len = bytes.len() as i64;
|
||||
|
||||
// The device root itself rejects file creation (B78), so the profile
|
||||
// lives one level down, in a folder created on first save.
|
||||
let dir_uid = self.ensure_profile_dir(&root_uid)?;
|
||||
|
||||
// Replace the existing document rather than adding a second file of the
|
||||
// same name: the profile is a single mutable record, and a folder with
|
||||
// `profile.json` and `profile (1).json` in it teaches the restore
|
||||
// nothing about which to trust.
|
||||
let existing = self.find_device_child_file(&dir_uid, &file_name)?;
|
||||
match existing {
|
||||
Some(uid) => self
|
||||
.rt
|
||||
.block_on(self.drive.upload_new_revision_from(
|
||||
&uid,
|
||||
Cursor::new(bytes),
|
||||
len,
|
||||
Vec::new(),
|
||||
Some(now_secs()),
|
||||
))
|
||||
.map(|_| ())
|
||||
.map_err(|e| CoreError::from_api(&e, "upload profile revision"))?,
|
||||
None => {
|
||||
self.rt
|
||||
.block_on(self.drive.upload_file_replacing_draft_from(
|
||||
&dir_uid,
|
||||
&file_name,
|
||||
"application/json",
|
||||
Cursor::new(bytes),
|
||||
len,
|
||||
Vec::new(),
|
||||
Some(now_secs()),
|
||||
false,
|
||||
))
|
||||
.map_err(|e| CoreError::from_api(&e, "upload profile"))?;
|
||||
}
|
||||
}
|
||||
info!(folders = profile.folders.len(), "profile backed up");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Snapshot the local arrangement into a [`Profile`].
|
||||
fn build_profile(&self, device_uid: &str, machine_id: &str) -> CoreResult<Profile> {
|
||||
let folders = profile_folders(
|
||||
self.db
|
||||
.sync_folder_list()
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?,
|
||||
);
|
||||
let pins = self
|
||||
.db
|
||||
.pin_list()
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
|
||||
.into_iter()
|
||||
.map(|row| ProfilePin {
|
||||
uid: row.uid,
|
||||
path: row.path,
|
||||
recursive: row.recursive,
|
||||
})
|
||||
.collect();
|
||||
let cfg = pdfs_core::config::AppDirs::new()
|
||||
.map(|d| d.load_config())
|
||||
.unwrap_or_default();
|
||||
Ok(Profile {
|
||||
version: PROFILE_VERSION,
|
||||
device_uid: device_uid.to_string(),
|
||||
hostname: this_hostname(),
|
||||
machine_id: Some(machine_id.to_string()),
|
||||
saved_at: now_secs(),
|
||||
folders,
|
||||
pins,
|
||||
ignore_patterns: cfg.ignore_patterns,
|
||||
cache_budget: cfg.cache_budget,
|
||||
mountpoint: cfg.mountpoint,
|
||||
})
|
||||
}
|
||||
|
||||
/// An untrashed *file* named `name` directly under `parent_uid`.
|
||||
///
|
||||
/// The sibling of `find_device_child_folder`; kept separate because a folder
|
||||
/// named `profile.json` must not be mistaken for the profile.
|
||||
fn find_device_child_file(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
) -> CoreResult<Option<NodeUid>> {
|
||||
let uids = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_folder_children_node_uids(parent_uid))
|
||||
.map_err(|e| CoreError::from_api(&e, "list device root"))?;
|
||||
if uids.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let nodes = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_nodes(&uids))
|
||||
.map_err(|e| CoreError::from_api(&e, "resolve device root children"))?;
|
||||
Ok(nodes
|
||||
.into_iter()
|
||||
.find(|n| !n.is_folder() && !n.trashed && n.name == name)
|
||||
.map(|n| n.uid))
|
||||
}
|
||||
|
||||
/// The untrashed files directly under `parent_uid` whose name passes
|
||||
/// `keep`.
|
||||
fn device_child_files(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
keep: impl Fn(&str) -> bool,
|
||||
) -> CoreResult<Vec<NodeUid>> {
|
||||
let uids = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_folder_children_node_uids(parent_uid))
|
||||
.map_err(|e| CoreError::from_api(&e, "list device root"))?;
|
||||
if uids.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let nodes = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_nodes(&uids))
|
||||
.map_err(|e| CoreError::from_api(&e, "resolve device root children"))?;
|
||||
Ok(nodes
|
||||
.into_iter()
|
||||
.filter(|n| !n.is_folder() && !n.trashed && keep(&n.name))
|
||||
.map(|n| n.uid)
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The device's `.proton-drive-linux` folder, creating it if this is the
|
||||
/// first save on this device.
|
||||
///
|
||||
/// Reused by stable identity rather than recreated: a second folder of the
|
||||
/// same name would split the profile across two documents, and the restore
|
||||
/// would have no way to tell which is current.
|
||||
fn ensure_profile_dir(&self, root_uid: &NodeUid) -> CoreResult<NodeUid> {
|
||||
if let Some(uid) = self.find_device_child_folder(root_uid, PROFILE_DIR_NAME)? {
|
||||
return Ok(uid);
|
||||
}
|
||||
let uid = self
|
||||
.rt
|
||||
.block_on(
|
||||
self.drive
|
||||
.create_folder(root_uid, PROFILE_DIR_NAME, Some(now_secs())),
|
||||
)
|
||||
.map_err(|e| CoreError::from_api(&e, "create profile folder"))?;
|
||||
info!(name = PROFILE_DIR_NAME, "created device profile folder");
|
||||
Ok(uid)
|
||||
}
|
||||
|
||||
/// Download and parse the profiles of every computer that syncs this
|
||||
/// device.
|
||||
///
|
||||
/// Reads every profile in `.proton-drive-linux/`: one per machine, and the
|
||||
/// shared `profile.json` of clients before 3.5.0. Falls back to the device
|
||||
/// root, where clients before the B78 fix wrote it. The fallback is
|
||||
/// read-only: the next save writes to the folder, and the legacy document
|
||||
/// is left alone rather than trashed, so an older client on another
|
||||
/// machine keeps working. A profile that cannot be read is left out and
|
||||
/// logged; the others still count.
|
||||
fn load_profiles(&self, root_uid: &NodeUid) -> CoreResult<Vec<Profile>> {
|
||||
let mut uids = match self.find_device_child_folder(root_uid, PROFILE_DIR_NAME)? {
|
||||
Some(dir_uid) => self.device_child_files(&dir_uid, is_profile_file_name)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
if uids.is_empty() {
|
||||
uids = self.device_child_files(root_uid, |name| name == PROFILE_FILE_NAME)?;
|
||||
if !uids.is_empty() {
|
||||
info!("reading legacy profile from the device root");
|
||||
}
|
||||
}
|
||||
let mut profiles = Vec::new();
|
||||
for uid in uids {
|
||||
let mut buf: Vec<u8> = Vec::new();
|
||||
let parsed = self
|
||||
.rt
|
||||
.block_on(self.drive.download_file_to(&uid, &mut buf))
|
||||
.map_err(|e| CoreError::from_api(&e, "download profile"))
|
||||
.and_then(|()| Profile::parse(&buf).map_err(CoreError::invalid));
|
||||
match parsed {
|
||||
Ok(profile) => profiles.push(profile),
|
||||
Err(e) => {
|
||||
warn!(%uid, error = %e.message, "could not read a profile; leaving it out")
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(profiles)
|
||||
}
|
||||
|
||||
// ---- restore ----------------------------------------
|
||||
|
||||
/// The folders under a device that could be synced here, each carrying a
|
||||
/// proposed local path. `device` names another registered device by uid;
|
||||
/// `None` is this machine's own.
|
||||
///
|
||||
/// The proposal comes from the profile when one exists and its path is
|
||||
/// usable on this machine, and from `~/<name>` otherwise — a restored
|
||||
/// `/home/other-user/Documents` would be wrong on a machine where that user
|
||||
/// does not exist, and silently creating it would be worse.
|
||||
pub(crate) fn list_restorable_folders(
|
||||
&self,
|
||||
device: Option<&str>,
|
||||
) -> CoreResult<Vec<RestorableFolder>> {
|
||||
let device = self.restore_source(device)?;
|
||||
let root_uid = parse_uid(&device.root_uid).ok_or_else(|| {
|
||||
CoreError::internal(format!("bad device root uid: {}", device.root_uid))
|
||||
})?;
|
||||
|
||||
let profiles = match self.load_profiles(&root_uid) {
|
||||
Ok(p) => p,
|
||||
// A missing or unreadable profile is not fatal: the remote tree
|
||||
// alone is enough to offer a restore, just with plainer defaults.
|
||||
Err(e) => {
|
||||
warn!(error = %e.message, "could not read profiles; proposing defaults");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
let hostname = this_hostname();
|
||||
|
||||
let uids = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_folder_children_node_uids(&root_uid))
|
||||
.map_err(|e| CoreError::from_api(&e, "list device root"))?;
|
||||
let nodes = if uids.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.rt
|
||||
.block_on(self.drive.enumerate_nodes(&uids))
|
||||
.map_err(|e| CoreError::from_api(&e, "resolve device root children"))?
|
||||
};
|
||||
|
||||
// Folders already synced here are not restorable — they are already
|
||||
// restored — but they are still listed, flagged, so the picker can show
|
||||
// the whole device rather than a confusing subset.
|
||||
let existing: Vec<String> = self
|
||||
.db
|
||||
.sync_folder_list()
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
|
||||
.into_iter()
|
||||
.map(|f| f.remote_uid)
|
||||
.collect();
|
||||
|
||||
Ok(nodes
|
||||
.into_iter()
|
||||
// `.proton-drive-linux` holds the profile itself, not user data:
|
||||
// offering it as a restorable folder would sync the bookkeeping
|
||||
// back onto the machine it describes.
|
||||
.filter(|n| n.is_folder() && !n.trashed && n.name != PROFILE_DIR_NAME)
|
||||
// The name becomes a folder under the home folder: one with a `/`
|
||||
// or a `..` in it would put the restore somewhere else.
|
||||
.filter(|n| crate::remote_name_is_safe(&n.name))
|
||||
.map(|n| {
|
||||
let uid = n.uid.to_string();
|
||||
let saved = saved_folder(&profiles, &uid, &hostname);
|
||||
let proposed = saved
|
||||
.map(|f| PathBuf::from(&f.local_path))
|
||||
.filter(|p| path_is_usable_here(p))
|
||||
.unwrap_or_else(|| default_local_path(&n.name));
|
||||
RestorableFolder {
|
||||
already_synced: existing.iter().any(|e| e == &uid),
|
||||
remote_uid: uid,
|
||||
name: n.name,
|
||||
local_path: proposed.to_string_lossy().to_string(),
|
||||
mode: saved
|
||||
.map(|f| f.mode.to_string())
|
||||
.unwrap_or_else(|| "mirror".into()),
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Attach remote device folders to local paths and let the sync engine fill
|
||||
@@ -385,7 +91,7 @@ impl Core {
|
||||
if items.is_empty() {
|
||||
return Err(CoreError::invalid("nothing to restore"));
|
||||
}
|
||||
let device = self.restore_source(device)?;
|
||||
let device = self.devices().restore_source(device)?;
|
||||
let existing = self
|
||||
.db
|
||||
.sync_folder_list()
|
||||
@@ -395,7 +101,7 @@ impl Core {
|
||||
// where destructive device-only operations would otherwise be allowed.
|
||||
let device_root = super::parse_uid(&device.root_uid)
|
||||
.ok_or_else(|| CoreError::internal("invalid device root"))?;
|
||||
let children = self.device_root_nodes(&device_root)?;
|
||||
let children = self.devices().device_root_nodes(&device_root)?;
|
||||
let reserved = crate::devices::sync_root_reserved();
|
||||
let mut roots: Vec<PathBuf> = existing
|
||||
.iter()
|
||||
@@ -478,6 +184,342 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
impl ProfileBackup {
|
||||
/// Note that the arrangement this machine's profile describes has changed,
|
||||
/// and upload a fresh profile in the background.
|
||||
///
|
||||
/// Fire-and-forget by design: callers are mutation paths (add/remove a sync
|
||||
/// folder, switch a mode, pin a node, save settings) whose success does not
|
||||
/// depend on the backup succeeding.
|
||||
pub(crate) fn touch_profile(&self) {
|
||||
let (saving, dirty) = save_state();
|
||||
dirty.store(true, Ordering::SeqCst);
|
||||
// Someone is already uploading; they will see DIRTY and take another lap.
|
||||
if saving.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
let this = self.clone();
|
||||
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) = this.save_profile() {
|
||||
warn!(error = %e.message, "profile backup failed");
|
||||
break;
|
||||
}
|
||||
}
|
||||
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
|
||||
/// `profile-<machine id>.json` inside the device's `.proton-drive-linux`
|
||||
/// folder, replacing any existing one.
|
||||
///
|
||||
/// Each machine writes its own file because several computers may sync
|
||||
/// into one device. They used to share `profile.json`, and each save
|
||||
/// replaced the other computers' folders with its own (B252). That file is
|
||||
/// left as it is, so a client before 3.5.0 still finds it.
|
||||
///
|
||||
/// Does nothing when no device is registered: a machine that has never
|
||||
/// synced a folder has nothing to describe, and registering a device just to
|
||||
/// hold an empty profile would put a stray computer in the user's Drive.
|
||||
pub(crate) fn save_profile(&self) -> CoreResult<()> {
|
||||
let Some(device) = self
|
||||
.db
|
||||
.device_get()
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let root_uid = parse_uid(&device.root_uid).ok_or_else(|| {
|
||||
CoreError::internal(format!("bad device root uid: {}", device.root_uid))
|
||||
})?;
|
||||
|
||||
let machine_id = pdfs_core::config::AppDirs::new()
|
||||
.and_then(|dirs| dirs.machine_id())
|
||||
.map_err(|e| CoreError::internal(format!("machine id: {e}")))?;
|
||||
let file_name = profile_file_name(&machine_id);
|
||||
let profile = self.build_profile(&device.uid, &machine_id)?;
|
||||
let bytes = profile.to_bytes().map_err(CoreError::internal)?;
|
||||
let len = bytes.len() as i64;
|
||||
|
||||
// The device root itself rejects file creation (B78), so the profile
|
||||
// lives one level down, in a folder created on first save.
|
||||
let dir_uid = self.ensure_profile_dir(&root_uid)?;
|
||||
|
||||
// Replace the existing document rather than adding a second file of the
|
||||
// same name: the profile is a single mutable record, and a folder with
|
||||
// `profile.json` and `profile (1).json` in it teaches the restore
|
||||
// nothing about which to trust.
|
||||
let existing = self.find_device_child_file(&dir_uid, &file_name)?;
|
||||
match existing {
|
||||
Some(uid) => self
|
||||
.rt
|
||||
.block_on(self.drive.upload_new_revision_from(
|
||||
&uid,
|
||||
Cursor::new(bytes),
|
||||
len,
|
||||
Vec::new(),
|
||||
Some(now_secs()),
|
||||
))
|
||||
.map(|_| ())
|
||||
.map_err(|e| CoreError::from_api(&e, "upload profile revision"))?,
|
||||
None => {
|
||||
self.rt
|
||||
.block_on(self.drive.upload_file_replacing_draft_from(
|
||||
&dir_uid,
|
||||
&file_name,
|
||||
"application/json",
|
||||
Cursor::new(bytes),
|
||||
len,
|
||||
Vec::new(),
|
||||
Some(now_secs()),
|
||||
false,
|
||||
))
|
||||
.map_err(|e| CoreError::from_api(&e, "upload profile"))?;
|
||||
}
|
||||
}
|
||||
info!(folders = profile.folders.len(), "profile backed up");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Snapshot the local arrangement into a [`Profile`].
|
||||
pub(crate) fn build_profile(&self, device_uid: &str, machine_id: &str) -> CoreResult<Profile> {
|
||||
let folders = profile_folders(
|
||||
self.db
|
||||
.sync_folder_list()
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?,
|
||||
);
|
||||
let pins = self
|
||||
.db
|
||||
.pin_list()
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
|
||||
.into_iter()
|
||||
.map(|row| ProfilePin {
|
||||
uid: row.uid,
|
||||
path: row.path,
|
||||
recursive: row.recursive,
|
||||
})
|
||||
.collect();
|
||||
let cfg = pdfs_core::config::AppDirs::new()
|
||||
.map(|d| d.load_config())
|
||||
.unwrap_or_default();
|
||||
Ok(Profile {
|
||||
version: PROFILE_VERSION,
|
||||
device_uid: device_uid.to_string(),
|
||||
hostname: this_hostname(),
|
||||
machine_id: Some(machine_id.to_string()),
|
||||
saved_at: now_secs(),
|
||||
folders,
|
||||
pins,
|
||||
ignore_patterns: cfg.ignore_patterns,
|
||||
cache_budget: cfg.cache_budget,
|
||||
mountpoint: cfg.mountpoint,
|
||||
})
|
||||
}
|
||||
|
||||
/// An untrashed *file* named `name` directly under `parent_uid`.
|
||||
///
|
||||
/// The sibling of `find_device_child_folder`; kept separate because a folder
|
||||
/// named `profile.json` must not be mistaken for the profile.
|
||||
pub(crate) fn find_device_child_file(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
) -> CoreResult<Option<NodeUid>> {
|
||||
let uids = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_folder_children_node_uids(parent_uid))
|
||||
.map_err(|e| CoreError::from_api(&e, "list device root"))?;
|
||||
if uids.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let nodes = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_nodes(&uids))
|
||||
.map_err(|e| CoreError::from_api(&e, "resolve device root children"))?;
|
||||
Ok(nodes
|
||||
.into_iter()
|
||||
.find(|n| !n.is_folder() && !n.trashed && n.name == name)
|
||||
.map(|n| n.uid))
|
||||
}
|
||||
|
||||
/// The untrashed files directly under `parent_uid` whose name passes
|
||||
/// `keep`.
|
||||
pub(crate) fn device_child_files(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
keep: impl Fn(&str) -> bool,
|
||||
) -> CoreResult<Vec<NodeUid>> {
|
||||
let uids = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_folder_children_node_uids(parent_uid))
|
||||
.map_err(|e| CoreError::from_api(&e, "list device root"))?;
|
||||
if uids.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let nodes = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_nodes(&uids))
|
||||
.map_err(|e| CoreError::from_api(&e, "resolve device root children"))?;
|
||||
Ok(nodes
|
||||
.into_iter()
|
||||
.filter(|n| !n.is_folder() && !n.trashed && keep(&n.name))
|
||||
.map(|n| n.uid)
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The device's `.proton-drive-linux` folder, creating it if this is the
|
||||
/// first save on this device.
|
||||
///
|
||||
/// Reused by stable identity rather than recreated: a second folder of the
|
||||
/// same name would split the profile across two documents, and the restore
|
||||
/// would have no way to tell which is current.
|
||||
pub(crate) fn ensure_profile_dir(&self, root_uid: &NodeUid) -> CoreResult<NodeUid> {
|
||||
if let Some(uid) = self
|
||||
.devices
|
||||
.find_device_child_folder(root_uid, PROFILE_DIR_NAME)?
|
||||
{
|
||||
return Ok(uid);
|
||||
}
|
||||
let uid = self
|
||||
.rt
|
||||
.block_on(
|
||||
self.drive
|
||||
.create_folder(root_uid, PROFILE_DIR_NAME, Some(now_secs())),
|
||||
)
|
||||
.map_err(|e| CoreError::from_api(&e, "create profile folder"))?;
|
||||
info!(name = PROFILE_DIR_NAME, "created device profile folder");
|
||||
Ok(uid)
|
||||
}
|
||||
|
||||
/// Download and parse the profiles of every computer that syncs this
|
||||
/// device.
|
||||
///
|
||||
/// Reads every profile in `.proton-drive-linux/`: one per machine, and the
|
||||
/// shared `profile.json` of clients before 3.5.0. Falls back to the device
|
||||
/// root, where clients before the B78 fix wrote it. The fallback is
|
||||
/// read-only: the next save writes to the folder, and the legacy document
|
||||
/// is left alone rather than trashed, so an older client on another
|
||||
/// machine keeps working. A profile that cannot be read is left out and
|
||||
/// logged; the others still count.
|
||||
pub(crate) fn load_profiles(&self, root_uid: &NodeUid) -> CoreResult<Vec<Profile>> {
|
||||
let mut uids = match self
|
||||
.devices
|
||||
.find_device_child_folder(root_uid, PROFILE_DIR_NAME)?
|
||||
{
|
||||
Some(dir_uid) => self.device_child_files(&dir_uid, is_profile_file_name)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
if uids.is_empty() {
|
||||
uids = self.device_child_files(root_uid, |name| name == PROFILE_FILE_NAME)?;
|
||||
if !uids.is_empty() {
|
||||
info!("reading legacy profile from the device root");
|
||||
}
|
||||
}
|
||||
let mut profiles = Vec::new();
|
||||
for uid in uids {
|
||||
let mut buf: Vec<u8> = Vec::new();
|
||||
let parsed = self
|
||||
.rt
|
||||
.block_on(self.drive.download_file_to(&uid, &mut buf))
|
||||
.map_err(|e| CoreError::from_api(&e, "download profile"))
|
||||
.and_then(|()| Profile::parse(&buf).map_err(CoreError::invalid));
|
||||
match parsed {
|
||||
Ok(profile) => profiles.push(profile),
|
||||
Err(e) => {
|
||||
warn!(%uid, error = %e.message, "could not read a profile; leaving it out")
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(profiles)
|
||||
}
|
||||
|
||||
// ---- restore ----------------------------------------
|
||||
|
||||
/// The folders under a device that could be synced here, each carrying a
|
||||
/// proposed local path. `device` names another registered device by uid;
|
||||
/// `None` is this machine's own.
|
||||
///
|
||||
/// The proposal comes from the profile when one exists and its path is
|
||||
/// usable on this machine, and from `~/<name>` otherwise — a restored
|
||||
/// `/home/other-user/Documents` would be wrong on a machine where that user
|
||||
/// does not exist, and silently creating it would be worse.
|
||||
pub(crate) fn list_restorable_folders(
|
||||
&self,
|
||||
device: Option<&str>,
|
||||
) -> CoreResult<Vec<RestorableFolder>> {
|
||||
let device = self.devices.restore_source(device)?;
|
||||
let root_uid = parse_uid(&device.root_uid).ok_or_else(|| {
|
||||
CoreError::internal(format!("bad device root uid: {}", device.root_uid))
|
||||
})?;
|
||||
|
||||
let profiles = match self.load_profiles(&root_uid) {
|
||||
Ok(p) => p,
|
||||
// A missing or unreadable profile is not fatal: the remote tree
|
||||
// alone is enough to offer a restore, just with plainer defaults.
|
||||
Err(e) => {
|
||||
warn!(error = %e.message, "could not read profiles; proposing defaults");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
let hostname = this_hostname();
|
||||
|
||||
let uids = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_folder_children_node_uids(&root_uid))
|
||||
.map_err(|e| CoreError::from_api(&e, "list device root"))?;
|
||||
let nodes = if uids.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.rt
|
||||
.block_on(self.drive.enumerate_nodes(&uids))
|
||||
.map_err(|e| CoreError::from_api(&e, "resolve device root children"))?
|
||||
};
|
||||
|
||||
// Folders already synced here are not restorable — they are already
|
||||
// restored — but they are still listed, flagged, so the picker can show
|
||||
// the whole device rather than a confusing subset.
|
||||
let existing: Vec<String> = self
|
||||
.db
|
||||
.sync_folder_list()
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
|
||||
.into_iter()
|
||||
.map(|f| f.remote_uid)
|
||||
.collect();
|
||||
|
||||
Ok(nodes
|
||||
.into_iter()
|
||||
// `.proton-drive-linux` holds the profile itself, not user data:
|
||||
// offering it as a restorable folder would sync the bookkeeping
|
||||
// back onto the machine it describes.
|
||||
.filter(|n| n.is_folder() && !n.trashed && n.name != PROFILE_DIR_NAME)
|
||||
// The name becomes a folder under the home folder: one with a `/`
|
||||
// or a `..` in it would put the restore somewhere else.
|
||||
.filter(|n| crate::remote_name_is_safe(&n.name))
|
||||
.map(|n| {
|
||||
let uid = n.uid.to_string();
|
||||
let saved = saved_folder(&profiles, &uid, &hostname);
|
||||
let proposed = saved
|
||||
.map(|f| PathBuf::from(&f.local_path))
|
||||
.filter(|p| path_is_usable_here(p))
|
||||
.unwrap_or_else(|| default_local_path(&n.name));
|
||||
RestorableFolder {
|
||||
already_synced: existing.iter().any(|e| e == &uid),
|
||||
remote_uid: uid,
|
||||
name: n.name,
|
||||
local_path: proposed.to_string_lossy().to_string(),
|
||||
mode: saved
|
||||
.map(|f| f.mode.to_string())
|
||||
.unwrap_or_else(|| "mirror".into()),
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// Only device backups belong in the device's cross-machine profile.
|
||||
fn profile_folders(folders: Vec<pdfs_store::db::StoredSyncFolder>) -> Vec<ProfileFolder> {
|
||||
folders
|
||||
|
||||
@@ -37,6 +37,7 @@ impl Core {
|
||||
.filter(|path| !path.is_empty())
|
||||
.or_else(|| op.name.clone())
|
||||
.unwrap_or_else(|| op.uid.clone());
|
||||
let local_only = parse_node_uid(&op.uid).is_some_and(|uid| is_local_uid(&uid));
|
||||
PendingOpInfo {
|
||||
id: op.id,
|
||||
kind: op.kind,
|
||||
@@ -49,6 +50,8 @@ impl Core {
|
||||
failing: op.attempts >= FAILING_ATTEMPTS || issues.contains_key(&op.id),
|
||||
issue: issues.get(&op.id).map(|issue| SyncIssue::parse(issue)),
|
||||
exportable,
|
||||
node: op.uid,
|
||||
local_only,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
@@ -172,7 +175,7 @@ impl Core {
|
||||
CoreError::conflict(format!("{path} is being sent right now; try again"))
|
||||
})?;
|
||||
self.release_dropped_ops(uid, blobs);
|
||||
self.hidden.lock().remove(uid);
|
||||
self.writes.unhide(uid);
|
||||
match node {
|
||||
Some(node) => self.for_each_mount(|st, notify| {
|
||||
put_back(st, notify, node);
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! The account's storage quota, as `statfs(2)` and the control socket ask
|
||||
//! for it.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::{CoreError, CoreResult};
|
||||
use tracing::debug;
|
||||
|
||||
use super::{Core, QUOTA_TTL};
|
||||
|
||||
/// The last account quota answer, for `statfs(2)`, and whether a refresh
|
||||
/// of it is running.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct QuotaCache {
|
||||
/// Last account quota answer and when it was learned, for `statfs(2)`.
|
||||
///
|
||||
/// `df` and the free-space preflight of every file manager and installer ask
|
||||
/// for this, and the answer costs a round trip — so it is served from here
|
||||
/// for [`QUOTA_TTL`] and refreshed on a worker afterwards. Total account
|
||||
/// storage moves slowly enough that a minute-old number is a better answer
|
||||
/// than either a stall or the zeroes the default implementation returns.
|
||||
last: Arc<Mutex<Option<(std::time::Instant, i64, i64)>>>,
|
||||
/// Set while a `statfs` is refreshing [`QuotaCache::last`], so the others serve
|
||||
/// the last figures instead of each holding a worker on the same request.
|
||||
refreshing: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl QuotaCache {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
last: Arc::new(Mutex::new(None)),
|
||||
refreshing: Arc::new(AtomicBool::new(false)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// Total account storage usage `(max_space, used_space)` in bytes, across all
|
||||
/// Proton products (not Drive-only). A remote round-trip; nothing here is
|
||||
/// cached.
|
||||
pub(crate) fn account_quota(&self) -> CoreResult<(i64, i64)> {
|
||||
let q = self.block_on_bounded(self.drive.quota()).map_err(|e| {
|
||||
self.lost_link(&e, "account quota");
|
||||
CoreError::from_api(&e, "account quota")
|
||||
})?;
|
||||
*self.quota.last.lock() = Some((std::time::Instant::now(), q.max_space, q.used_space));
|
||||
Ok((q.max_space, q.used_space))
|
||||
}
|
||||
|
||||
/// The account quota as `statfs(2)` needs it: cached for [`QUOTA_TTL`],
|
||||
/// refetched after that, and `None` when there is no usable answer at all —
|
||||
/// offline with nothing cached.
|
||||
///
|
||||
/// Never blocks on the network for a *fresh* value when a recent one exists,
|
||||
/// because the callers are `df` and every "is there room?" preflight, and a
|
||||
/// stale byte count is worth more to them than a stalled syscall. Offline,
|
||||
/// the last known figures keep being served rather than degrading to zero.
|
||||
pub(crate) fn account_quota_cached(&self) -> Option<(i64, i64)> {
|
||||
if let Some((at, max_space, used_space)) = *self.quota.last.lock()
|
||||
&& at.elapsed() < QUOTA_TTL
|
||||
{
|
||||
return Some((max_space, used_space));
|
||||
}
|
||||
let last = || self.quota.last.lock().map(|(_, max, used)| (max, used));
|
||||
if !self.is_online()
|
||||
|| self
|
||||
.quota
|
||||
.refreshing
|
||||
.swap(true, std::sync::atomic::Ordering::AcqRel)
|
||||
{
|
||||
return last();
|
||||
}
|
||||
let refreshed = self.account_quota();
|
||||
self.quota
|
||||
.refreshing
|
||||
.store(false, std::sync::atomic::Ordering::Release);
|
||||
match refreshed {
|
||||
Ok(q) => Some(q),
|
||||
Err(error) => {
|
||||
debug!(%error, "account quota refresh failed; serving the last known figures");
|
||||
last()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
-105
@@ -1,6 +1,7 @@
|
||||
//! Revision-reader cache and streamed range-read subsystem.
|
||||
|
||||
use super::*;
|
||||
use pdfs_vfs::open::{ReadFailure, assemble_open_read};
|
||||
|
||||
/// A read of an unpinned video at least this large streams *without* persisting
|
||||
/// its blocks to the on-disk cache. Playing a 2 GB film would otherwise pour it
|
||||
@@ -507,7 +508,7 @@ impl Core {
|
||||
// A queued write has not reached the remote yet, so the remote's current
|
||||
// revision is stale and the staged blob is the truth. Serve from it until
|
||||
// the drain worker lands the upload.
|
||||
if let Some(pending) = self.pending.lock().get(uid).cloned() {
|
||||
if let Some(pending) = self.writes.queued(uid) {
|
||||
return self.read_pending(&pending, offset, len);
|
||||
}
|
||||
// A node created offline and never written has no blob and no remote: it
|
||||
@@ -1049,10 +1050,11 @@ impl Core {
|
||||
offset: u64,
|
||||
size: u64,
|
||||
) -> Result<Vec<u8>, Errno> {
|
||||
let read = assemble_open_read(file, len, uid, base_size, written, offset, size, |s, n| {
|
||||
let read = assemble_open_read(file, len, base_size, written, offset, size, |s, n| {
|
||||
self.read_range(uid, base_mtime, base_size, s, n, true)
|
||||
.map(Some)
|
||||
})?;
|
||||
})
|
||||
.map_err(|failure| open_read_errno(uid, failure))?;
|
||||
Ok(read.unwrap_or_default())
|
||||
}
|
||||
|
||||
@@ -1075,9 +1077,10 @@ impl Core {
|
||||
offset: u64,
|
||||
size: u64,
|
||||
) -> Result<Option<Vec<u8>>, Errno> {
|
||||
assemble_open_read(file, len, uid, base_size, written, offset, size, |s, n| {
|
||||
assemble_open_read(file, len, base_size, written, offset, size, |s, n| {
|
||||
Ok(self.cached_range(uid, base_mtime, base_size, s, n))
|
||||
})
|
||||
.map_err(|failure| open_read_errno(uid, failure))
|
||||
}
|
||||
|
||||
/// Bytes `[offset, offset + size)` of file `ino` as `read` would serve
|
||||
@@ -1094,16 +1097,12 @@ impl Core {
|
||||
offset: u64,
|
||||
size: u64,
|
||||
) -> Result<Option<Vec<u8>>, Errno> {
|
||||
let handle = self.state().active_writes.get(&ino).map(|h| {
|
||||
(
|
||||
h.file.clone(),
|
||||
h.len,
|
||||
h.uid.clone(),
|
||||
h.base_mtime,
|
||||
h.base_size,
|
||||
h.written.clone(),
|
||||
)
|
||||
});
|
||||
// A writer still open, or one whose release is still queueing it.
|
||||
let handle = self
|
||||
.state()
|
||||
.open
|
||||
.reader(ino)
|
||||
.map(|v| (v.file, v.len, v.uid, v.base_mtime, v.base_size, v.written));
|
||||
if let Some((file, len, uid, base_mtime, base_size, written)) = handle {
|
||||
return self.serve_open_read_local(
|
||||
&file, len, &uid, base_mtime, base_size, &written, offset, size,
|
||||
@@ -1132,7 +1131,7 @@ impl Core {
|
||||
true => self.landed_stand_in_uid(&uid).unwrap_or(uid),
|
||||
false => uid,
|
||||
};
|
||||
if let Some(pending) = self.pending.lock().get(&uid).cloned() {
|
||||
if let Some(pending) = self.writes.queued(&uid) {
|
||||
let m = &pending.meta;
|
||||
let file = File::open(&pending.path).map_err(|e| {
|
||||
error!(%uid, path = %pending.path.display(), error = %e, "open staged blob failed");
|
||||
@@ -1305,47 +1304,16 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes `[offset, offset + size)` of a file open for writing: authored
|
||||
/// ranges from its scratch `file`, the rest from its base through `base`,
|
||||
/// and zeros past the base. `Ok(None)` when `base` says it cannot answer.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn assemble_open_read(
|
||||
file: &File,
|
||||
len: u64,
|
||||
uid: &NodeUid,
|
||||
base_size: u64,
|
||||
written: &Intervals,
|
||||
offset: u64,
|
||||
size: u64,
|
||||
mut base: impl FnMut(u64, u64) -> Result<Option<Vec<u8>>, Errno>,
|
||||
) -> Result<Option<Vec<u8>>, Errno> {
|
||||
if offset >= len || size == 0 {
|
||||
return Ok(Some(Vec::new()));
|
||||
}
|
||||
let end = offset.saturating_add(size).min(len);
|
||||
let mut out = Vec::with_capacity((end - offset) as usize);
|
||||
for (s, e, authored) in written.segments(offset, end) {
|
||||
if authored {
|
||||
let mut buf = vec![0u8; (e - s) as usize];
|
||||
file.read_exact_at(&mut buf, s).map_err(|err| {
|
||||
warn!(%uid, error = %err, "scratch read failed");
|
||||
Errno::EIO
|
||||
})?;
|
||||
out.extend_from_slice(&buf);
|
||||
} else {
|
||||
let bend = e.min(base_size);
|
||||
if s < bend {
|
||||
match base(s, bend - s)? {
|
||||
Some(bytes) => out.extend_from_slice(&bytes),
|
||||
None => return Ok(None),
|
||||
}
|
||||
}
|
||||
// Anything past the base is a hole: zero-fill.
|
||||
let zeros = e.saturating_sub(s.max(base_size));
|
||||
out.resize(out.len() + zeros as usize, 0);
|
||||
/// The errno for a read of an open file that failed: the base's own, or
|
||||
/// `EIO` for the scratch file.
|
||||
fn open_read_errno(uid: &NodeUid, failure: ReadFailure<Errno>) -> Errno {
|
||||
match failure {
|
||||
ReadFailure::Base(errno) => errno,
|
||||
ReadFailure::Scratch(error) => {
|
||||
warn!(%uid, %error, "scratch read failed");
|
||||
Errno::EIO
|
||||
}
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1500,54 +1468,3 @@ mod prefetch_tests {
|
||||
assert!(prefetch.streams.lock().len() <= MAX_PREFETCH_STREAMS + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod open_read_tests {
|
||||
use super::*;
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
|
||||
|
||||
fn scratch(bytes: &[u8]) -> (File, PathBuf) {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"pdfs-open-read-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
let mut file = File::options()
|
||||
.create_new(true)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.unwrap();
|
||||
file.write_all(bytes).unwrap();
|
||||
(file, path)
|
||||
}
|
||||
|
||||
/// The dispatch loop answers from what is on this machine and says so
|
||||
/// when the base would have to be downloaded, for a worker to do it
|
||||
/// (`docs/BUGS.md` B227).
|
||||
#[test]
|
||||
fn a_read_needing_the_base_says_so_instead_of_fetching() {
|
||||
let uid = NodeUid::new(VolumeId::from("v"), LinkId::from("f"));
|
||||
let (file, path) = scratch(b"ABCDEFGH");
|
||||
let mut written = Intervals::default();
|
||||
written.add(0, 4);
|
||||
|
||||
let authored = assemble_open_read(&file, 8, &uid, 8, &written, 0, 4, |_, _| {
|
||||
panic!("an authored range never asks the base")
|
||||
});
|
||||
assert_eq!(authored.unwrap().as_deref(), Some(&b"ABCD"[..]));
|
||||
|
||||
let missing = assemble_open_read(&file, 8, &uid, 8, &written, 2, 6, |_, _| Ok(None));
|
||||
assert_eq!(missing.unwrap(), None);
|
||||
|
||||
let base = assemble_open_read(&file, 10, &uid, 8, &written, 2, 8, |s, n| {
|
||||
assert_eq!((s, n), (4, 4));
|
||||
Ok(Some(b"efgh".to_vec()))
|
||||
});
|
||||
assert_eq!(base.unwrap().as_deref(), Some(&b"CDefgh\0\0"[..]));
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! recovering writes that were fsynced but not queued when the daemon stopped.
|
||||
|
||||
use super::*;
|
||||
use pdfs_vfs::namespace::{ReplaceOutcome, settle_from_drive, settle_from_queue};
|
||||
|
||||
impl Core {
|
||||
/// Rehydrate the in-memory `State` maps from the DB on mount, so a cold
|
||||
@@ -28,17 +29,11 @@ impl Core {
|
||||
// lying about the size reads as data loss. `hydrate_pending` ran before
|
||||
// us, so the pending map is populated; snapshot it here rather than hold
|
||||
// both locks at once.
|
||||
let pending_sizes: HashMap<NodeUid, u64> = {
|
||||
let pending = self.pending.lock();
|
||||
pending
|
||||
.iter()
|
||||
.map(|(uid, pr)| (uid.clone(), pr.meta.len))
|
||||
.collect()
|
||||
};
|
||||
let pending_sizes = self.writes.queued_sizes();
|
||||
// `hydrate_pending` runs first and restores queued-trash tombstones.
|
||||
// Their node rows remain persisted as drain-time access authority, but
|
||||
// must not reappear in the mounted namespace after a restart.
|
||||
let hidden = self.hidden.lock().clone();
|
||||
let hidden = self.writes.hidden();
|
||||
let mut st = self.state();
|
||||
|
||||
// Pass 1: give every uid its inode from its local id (the root is
|
||||
@@ -102,11 +97,173 @@ impl Core {
|
||||
st.hydrate_access();
|
||||
|
||||
// Pass 3: rebuild child listings for fully-enumerated folders.
|
||||
let listings = listed_children(&st.entries, listed_dirs);
|
||||
let listings = crate::state::listed_children(&st.entries, listed_dirs);
|
||||
st.children.extend(listings);
|
||||
info!(nodes = st.entries.len(), "hydrated metadata cache from db");
|
||||
}
|
||||
|
||||
/// Startup recovery of the queue, with this daemon as its host.
|
||||
pub(crate) fn recovery(&self) -> Recovery {
|
||||
Recovery {
|
||||
db: self.db.clone(),
|
||||
cache: self.cache.clone(),
|
||||
writes: self.writes.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What recovery needs from the rest of the daemon.
|
||||
pub(crate) trait RecoveryHost: Send + Sync {
|
||||
/// Queue a write recovered from a blob fsynced before a stop, as if its
|
||||
/// handle had just been released.
|
||||
fn queue_recovered(&self, uid: &NodeUid, blob: &Path, meta: StagedWrite) -> Result<(), Errno>;
|
||||
|
||||
/// Drive's node `uid`: `None` when Drive cannot be asked now, and
|
||||
/// `Some(None)` when it does not have the node.
|
||||
fn remote_node(&self, uid: &NodeUid) -> Option<Option<Node>>;
|
||||
|
||||
/// Drop the queued trash of a replaced node whose rename was never
|
||||
/// queued, so it stays where it is.
|
||||
fn withdraw_victim_trash(&self, uid: &NodeUid) -> Result<(), Errno>;
|
||||
|
||||
/// Bring a replaced node back out of Drive's trash. Best effort; a failure
|
||||
/// is logged and recorded in the activity log.
|
||||
fn restore_victim(&self, uid: &NodeUid, parent: &NodeUid, name: &str);
|
||||
}
|
||||
|
||||
impl RecoveryHost for Core {
|
||||
fn queue_recovered(&self, uid: &NodeUid, blob: &Path, meta: StagedWrite) -> Result<(), Errno> {
|
||||
self.enqueue_staged_write(uid, 0, blob, meta)
|
||||
}
|
||||
|
||||
fn remote_node(&self, uid: &NodeUid) -> Option<Option<Node>> {
|
||||
if !self.is_online() {
|
||||
return None;
|
||||
}
|
||||
match self.block_on_bounded(self.drive.enumerate_nodes(std::slice::from_ref(uid))) {
|
||||
Ok(nodes) => Some(nodes.into_iter().find(|node| node.uid == *uid)),
|
||||
Err(error) if is_gone(&error) => Some(None),
|
||||
Err(error) => {
|
||||
self.lost_link(&error, "settle a replacing rename");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn withdraw_victim_trash(&self, uid: &NodeUid) -> Result<(), Errno> {
|
||||
self.discard_queued_ops(uid)?;
|
||||
self.writes.unhide(uid);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn restore_victim(&self, uid: &NodeUid, parent: &NodeUid, name: &str) {
|
||||
self.restore_replaced(Some(&(0, uid.clone())), parent, name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuilds the queue from the database and the staging area after a
|
||||
/// restart. Holds the database, the content cache and the write-back's state;
|
||||
/// queueing a recovered write goes through [`RecoveryHost`].
|
||||
pub(crate) struct Recovery {
|
||||
db: Arc<Db>,
|
||||
cache: Arc<ContentCache>,
|
||||
writes: writes::WriteState,
|
||||
host: Arc<dyn RecoveryHost>,
|
||||
}
|
||||
|
||||
impl Recovery {
|
||||
/// Settle the replacing renames an earlier run started and did not end
|
||||
/// (`docs/BUGS.md` B302): forget the ones that reached their end state,
|
||||
/// and put the victim back where the rename did not happen. One that needs
|
||||
/// Drive while Drive cannot be asked stays for a later pass.
|
||||
///
|
||||
/// Runs at mount, after [`hydrate_pending`](Self::hydrate_pending), and on
|
||||
/// the drain's idle passes. The journal holds only this run's own renames
|
||||
/// apart from cut-off ones, and those are left alone, so the idle pass
|
||||
/// never undoes a rename in progress.
|
||||
pub(crate) fn settle_replaces(&self) {
|
||||
let intents = match self.db.open_replaces() {
|
||||
Ok(intents) if intents.is_empty() => return,
|
||||
Ok(intents) => intents,
|
||||
Err(error) => {
|
||||
warn!(%error, "reading cut-off replacing renames failed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let ops = match self.db.pending_ops() {
|
||||
Ok(ops) => ops,
|
||||
Err(error) => {
|
||||
warn!(%error, "reading the queue to settle replacing renames failed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
for intent in intents {
|
||||
let (Some(source), Some(victim), Some(parent)) = (
|
||||
parse_node_uid(&intent.source_uid),
|
||||
parse_node_uid(&intent.victim_uid),
|
||||
parse_node_uid(&intent.new_parent_uid),
|
||||
) else {
|
||||
warn!(source = %intent.source_uid, "dropping a replace intent with an unparseable uid");
|
||||
let _ = self.db.end_replace(&intent.source_uid);
|
||||
continue;
|
||||
};
|
||||
// The source's end state is queued when one of its ops puts it at
|
||||
// the new name: a rename, or the create a queued node's rename
|
||||
// rewrote.
|
||||
let rename_queued = ops.iter().any(|op| {
|
||||
op.uid == intent.source_uid
|
||||
&& [OP_RENAME, OP_CREATE, OP_MKDIR].contains(&op.kind.as_str())
|
||||
&& op.parent_uid.as_deref() == Some(intent.new_parent_uid.as_str())
|
||||
&& op.name.as_deref() == Some(intent.new_name.as_str())
|
||||
});
|
||||
let victim_trash_queued = ops
|
||||
.iter()
|
||||
.any(|op| op.uid == intent.victim_uid && op.kind == OP_TRASH);
|
||||
let outcome = settle_from_queue(rename_queued, victim_trash_queued, is_local_uid(&victim))
|
||||
.unwrap_or_else(|| {
|
||||
if is_local_uid(&source) {
|
||||
// A queued node whose create landed under the rename;
|
||||
// Drive knows it by a uid this entry does not have.
|
||||
warn!(%source, %victim, name = intent.new_name,
|
||||
"cannot settle a replacing rename of a node created here; leaving the replaced node in the trash");
|
||||
return ReplaceOutcome::Done;
|
||||
}
|
||||
let source_node = self.host.remote_node(&source);
|
||||
let victim_node = match source_node {
|
||||
Some(_) => self.host.remote_node(&victim),
|
||||
None => None,
|
||||
};
|
||||
settle_from_drive(
|
||||
&parent,
|
||||
&intent.new_name,
|
||||
source_node.as_ref().map(Option::as_ref),
|
||||
victim_node.as_ref().map(Option::as_ref),
|
||||
)
|
||||
});
|
||||
match outcome {
|
||||
ReplaceOutcome::Wait => continue,
|
||||
ReplaceOutcome::Done => {
|
||||
info!(%source, name = intent.new_name, "a replacing rename cut off by a stop had finished");
|
||||
}
|
||||
ReplaceOutcome::WithdrawVictimTrash => {
|
||||
if let Err(error) = self.host.withdraw_victim_trash(&victim) {
|
||||
warn!(%victim, ?error, "withdrawing a replaced node's queued trash failed; trying again later");
|
||||
continue;
|
||||
}
|
||||
info!(%victim, name = intent.new_name, "kept a node a cut-off rename was replacing");
|
||||
}
|
||||
ReplaceOutcome::RestoreVictim => {
|
||||
self.host.restore_victim(&victim, &parent, &intent.new_name);
|
||||
info!(%victim, name = intent.new_name, "restored a node a cut-off rename had replaced");
|
||||
}
|
||||
}
|
||||
if let Err(error) = self.db.end_replace(&intent.source_uid) {
|
||||
warn!(%source, %error, "ending a settled replace intent failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuild the in-memory pending map from the `pending_op` table on mount.
|
||||
///
|
||||
/// A queued write survives a restart — that is the point of persisting it —
|
||||
@@ -115,7 +272,7 @@ impl Core {
|
||||
///
|
||||
/// A row whose blob has gone missing is dropped: there is nothing left to
|
||||
/// upload, and keeping it would fail forever.
|
||||
pub(super) fn hydrate_pending(&self) {
|
||||
pub(crate) fn hydrate_pending(&self) {
|
||||
let ops = match self.db.pending_ops() {
|
||||
Ok(ops) => ops,
|
||||
Err(e) => {
|
||||
@@ -123,7 +280,7 @@ impl Core {
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut map = self.pending.lock();
|
||||
let mut map = self.writes.pending.lock();
|
||||
let mut restored = 0usize;
|
||||
for op in ops {
|
||||
let Some(uid) = parse_node_uid(&op.uid) else {
|
||||
@@ -132,7 +289,7 @@ impl Core {
|
||||
continue;
|
||||
};
|
||||
if op.kind == OP_TRASH {
|
||||
self.hidden.lock().insert(uid.clone());
|
||||
self.writes.hide(&uid);
|
||||
}
|
||||
restored += 1;
|
||||
// Only a revision must have a blob. A create carries none until
|
||||
@@ -188,7 +345,7 @@ impl Core {
|
||||
/// `local~` placeholder whose create is gone) is left in place and named in
|
||||
/// the log: unexplained bytes are never evidence that user data is
|
||||
/// disposable.
|
||||
pub(super) fn reconcile_staging(&self) {
|
||||
pub(crate) fn reconcile_staging(&self) {
|
||||
let staged = self.cache.staged_writes();
|
||||
if staged.is_empty() {
|
||||
return;
|
||||
@@ -225,7 +382,7 @@ impl Core {
|
||||
example.get_or_insert_with(|| blob.clone());
|
||||
continue;
|
||||
};
|
||||
if self.pending.lock().contains_key(&uid) {
|
||||
if self.writes.is_queued(&uid) {
|
||||
// A newer write for the same node is queued and carries its own
|
||||
// blob. These bytes are older; keeping them is right, uploading
|
||||
// them over the newer ones is not.
|
||||
@@ -266,7 +423,7 @@ impl Core {
|
||||
if let Some(old) = superseded {
|
||||
self.cache.discard_staged(Path::new(&old));
|
||||
}
|
||||
self.pending.lock().insert(
|
||||
self.writes.pending.lock().insert(
|
||||
uid.clone(),
|
||||
PendingRevision {
|
||||
path: blob.clone(),
|
||||
@@ -320,7 +477,7 @@ impl Core {
|
||||
/// Failure is per-write and never fatal: a node that no longer exists, or an
|
||||
/// op that cannot be queued, leaves its blob in `recovery/` for the next run
|
||||
/// (and for a human) instead of taking the mount down.
|
||||
pub(super) fn recover_fsynced_writes(&self) {
|
||||
pub(crate) fn recover_fsynced_writes(&self) {
|
||||
let recovered = self.cache.recovered_writes();
|
||||
if recovered.is_empty() {
|
||||
return;
|
||||
@@ -336,7 +493,7 @@ impl Core {
|
||||
// now would use the wrong remote base. enqueue_staged_write would abandon it
|
||||
// to staging; keep it in recovery instead so the drain loop can queue it
|
||||
// once the queue clears.
|
||||
if !meta.complete && self.pending.lock().contains_key(&uid) {
|
||||
if !meta.complete && self.writes.is_queued(&uid) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -344,7 +501,7 @@ impl Core {
|
||||
// size, and nothing is interned this early — `hydrate` reads the
|
||||
// size back off `pending` when the node is first looked up, so 0
|
||||
// (no such inode) is correct rather than merely tolerable.
|
||||
match self.enqueue_staged_write(&uid, 0, &blob, meta) {
|
||||
match self.host.queue_recovered(&uid, &blob, meta) {
|
||||
Ok(()) => {
|
||||
self.cache.discard_recovered(&blob);
|
||||
queued += 1;
|
||||
@@ -377,7 +534,7 @@ impl Core {
|
||||
/// content is unrecoverable and nothing will ever mint it a real uid, so
|
||||
/// leaving the row would strand a file in the tree that can be listed but
|
||||
/// never read and never uploaded.
|
||||
pub(super) fn drop_unrecoverable_op(&self, op: &PendingOp, uid: &NodeUid) {
|
||||
fn drop_unrecoverable_op(&self, op: &PendingOp, uid: &NodeUid) {
|
||||
let _ = self.db.delete_op(op.id);
|
||||
if is_local_uid(uid) {
|
||||
error!(%uid, name = op.name.as_deref().unwrap_or("?"),
|
||||
|
||||
@@ -172,7 +172,7 @@ impl Core {
|
||||
rel: dest_rel,
|
||||
},
|
||||
) = (&source, &dest)
|
||||
&& Arc::ptr_eq(&core.root, &dest_core.root)
|
||||
&& Arc::ptr_eq(&core.session.root, &dest_core.session.root)
|
||||
{
|
||||
return core.move_to(rel, dest_rel);
|
||||
}
|
||||
@@ -453,11 +453,7 @@ impl Core {
|
||||
// longer has that uid, so the move went ahead under an open write.
|
||||
let mut writing = false;
|
||||
self.for_each_state(|st| {
|
||||
writing = st
|
||||
.active_writes
|
||||
.keys()
|
||||
.chain(&st.releasing)
|
||||
.any(|&open| ino_is_under(st, open, ino));
|
||||
writing = st.open.owed(false).any(|open| ino_is_under(st, open, ino));
|
||||
});
|
||||
Ok(writing)
|
||||
}
|
||||
|
||||
@@ -485,11 +485,8 @@ impl Core {
|
||||
// Unsaved writes, or a release still queueing them, to the file or,
|
||||
// for a folder, to any file below it.
|
||||
let unsaved = st
|
||||
.active_writes
|
||||
.iter()
|
||||
.filter(|(_, w)| w.dirty)
|
||||
.map(|(&open, _)| open)
|
||||
.chain(st.releasing.iter().copied())
|
||||
.open
|
||||
.owed(true)
|
||||
.any(|open| relocate::ino_is_under(&st, open, ino));
|
||||
(entry.node.name.clone(), entry.node.is_folder(), unsaved)
|
||||
};
|
||||
@@ -693,7 +690,7 @@ impl Core {
|
||||
self.for_each_state(|st| {
|
||||
st.forget_or_unlink(uid);
|
||||
});
|
||||
self.hidden.lock().insert(uid.clone());
|
||||
self.writes.hide(uid);
|
||||
if open_now {
|
||||
if let Err(error) = self.withdraw_queued_ops(uid) {
|
||||
error!(%uid, "remote replacement landed but queued-op cleanup failed");
|
||||
@@ -763,7 +760,7 @@ impl Core {
|
||||
.and_then(batch::into_unit)
|
||||
{
|
||||
Ok(()) => {
|
||||
self.hidden.lock().remove(uid);
|
||||
self.writes.unhide(uid);
|
||||
self.for_each_mount(|st, notify| {
|
||||
if let Some(&ino) = st.by_uid.get(parent) {
|
||||
st.invalidate_listing(ino);
|
||||
|
||||
@@ -133,7 +133,7 @@ impl Core {
|
||||
// These paths walk the tree lazily, so a cold node needs the API.
|
||||
// Offline that surfaces as EIO, which on its own would read to the
|
||||
// user as a broken file rather than a missing network.
|
||||
libc::EIO if !self.online.load(Ordering::Relaxed) => CoreError::offline(),
|
||||
libc::EIO if !self.is_online() => CoreError::offline(),
|
||||
libc::EINVAL => CoreError::invalid(format!("{what}: not a usable path")),
|
||||
libc::ENOSPC => CoreError::new(ErrorKind::Quota, format!("{what}: out of space")),
|
||||
libc::EEXIST => CoreError::conflict(format!("{what}: already exists")),
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
//! file rather than trying to describe the new one. The next read repopulates
|
||||
//! from whatever is live by then.
|
||||
//! - **The active revision cannot be deleted**, and the server — not this code —
|
||||
//! is what enforces that. [`Core::delete_revision_for_uid`] refuses locally
|
||||
//! is what enforces that. [`Revisions::delete`] refuses locally
|
||||
//! too, so the user gets a sentence instead of an API code.
|
||||
|
||||
use std::path::Path;
|
||||
@@ -27,7 +27,12 @@ use proton_drive_rs::Revision;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use tracing::info;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use proton_drive_rs::ProtonDriveClient;
|
||||
|
||||
use super::Core;
|
||||
use crate::drive::DriveApi;
|
||||
|
||||
/// A [`Revision`] as the control protocol reports it.
|
||||
fn revision_info(revision: Revision) -> RevisionInfo {
|
||||
@@ -45,70 +50,37 @@ fn revision_info(revision: Revision) -> RevisionInfo {
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// The version history of the file at mountpoint-relative `rel`.
|
||||
pub(crate) fn list_revisions(&self, rel: &Path) -> CoreResult<Vec<RevisionInfo>> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.list_revisions_for_uid(&uid)
|
||||
}
|
||||
/// A file's revisions on Drive. Every method takes a node already resolved to
|
||||
/// its uid, and the name the activity feed shows for it.
|
||||
///
|
||||
/// It reaches the filesystem through [`RevisionsHost`]. [`Core::revisions`]
|
||||
/// builds one on demand with the daemon as its host.
|
||||
pub(crate) struct Revisions {
|
||||
client: ProtonDriveClient,
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
host: Arc<dyn RevisionsHost>,
|
||||
}
|
||||
|
||||
/// [`Core::list_revisions`] for a node addressed through any daemon location.
|
||||
pub(crate) fn list_revisions_by_uid(&self, uid: &str) -> CoreResult<Vec<RevisionInfo>> {
|
||||
let uid = self.resolve_anywhere(uid)?;
|
||||
self.list_revisions_for_uid(&uid)
|
||||
}
|
||||
/// What [`Revisions`] needs from the filesystem.
|
||||
pub(crate) trait RevisionsHost: Send + Sync {
|
||||
/// Refuse unless this daemon may change the node's content. `what` names
|
||||
/// the operation in the error.
|
||||
fn require_writable(&self, uid: &NodeUid, what: &str) -> CoreResult<()>;
|
||||
/// The node's active revision changed on the server: forget its cached
|
||||
/// content and open readers, and fetch it again if it is kept offline.
|
||||
fn content_replaced(&self, uid: &NodeUid);
|
||||
/// Add an entry to the activity log.
|
||||
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool);
|
||||
}
|
||||
|
||||
fn list_revisions_for_uid(&self, uid: &NodeUid) -> CoreResult<Vec<RevisionInfo>> {
|
||||
let revisions = self
|
||||
.rt
|
||||
.block_on(self.client.enumerate_revisions(uid))
|
||||
.map_err(|e| CoreError::from_api(&e, "list revisions"))?;
|
||||
Ok(revisions.into_iter().map(revision_info).collect())
|
||||
}
|
||||
|
||||
/// Make `revision_id` the current content of the file at `rel`.
|
||||
pub(crate) fn restore_revision(&self, rel: &Path, revision_id: &str) -> CoreResult<()> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
let name = rel
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| uid.to_string());
|
||||
self.restore_revision_for_uid(&uid, revision_id, &name)?;
|
||||
// The size and mtime a listing shows describe the revision that was
|
||||
// active a moment ago.
|
||||
self.invalidate_parent_listing(rel);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`Core::restore_revision`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn restore_revision_by_uid(&self, uid: &str, revision_id: &str) -> CoreResult<()> {
|
||||
let uid = self.resolve_anywhere(uid)?;
|
||||
let name = uid.to_string();
|
||||
self.restore_revision_for_uid(&uid, revision_id, &name)
|
||||
}
|
||||
|
||||
fn restore_revision_for_uid(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
revision_id: &str,
|
||||
name: &str,
|
||||
) -> CoreResult<()> {
|
||||
// Restoring rewrites the file's content: the same authority a write
|
||||
// needs, not the one a read needs.
|
||||
impl RevisionsHost for Core {
|
||||
fn require_writable(&self, uid: &NodeUid, what: &str) -> CoreResult<()> {
|
||||
self.require_uid_writable(uid)
|
||||
.map_err(|error| self.errno_error(error, "restore revision"))?;
|
||||
if let Err(e) = self
|
||||
.rt
|
||||
.block_on(self.client.restore_revision(uid, revision_id))
|
||||
{
|
||||
let error = CoreError::from_api(&e, "restore revision");
|
||||
self.log_activity(ActivityKind::Restore, name, &error, false);
|
||||
return Err(error);
|
||||
}
|
||||
// The active revision is changing behind our back — anything describing
|
||||
// the old one (cached blocks, an open reader, the size in a listing) is
|
||||
// stale from here on, and the server may not have applied the swap yet.
|
||||
.map_err(|error| self.errno_error(error, what))
|
||||
}
|
||||
|
||||
fn content_replaced(&self, uid: &NodeUid) {
|
||||
self.cache.evict(uid);
|
||||
self.evict_reader(uid);
|
||||
// A file kept offline gets the restored content back on disk, and
|
||||
@@ -116,9 +88,58 @@ impl Core {
|
||||
if self.cache.is_pinned(uid) {
|
||||
self.recheck_pinned(uid);
|
||||
}
|
||||
self.log_activity(
|
||||
}
|
||||
|
||||
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool) {
|
||||
Core::log_activity(self, kind, target, detail, ok);
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// The revisions service, with this daemon as its host.
|
||||
pub(crate) fn revisions(&self) -> Revisions {
|
||||
Revisions {
|
||||
client: self.client.clone(),
|
||||
drive: self.drive.clone(),
|
||||
rt: self.rt.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Revisions {
|
||||
pub(crate) fn list(&self, uid: &NodeUid) -> CoreResult<Vec<RevisionInfo>> {
|
||||
let revisions = self
|
||||
.rt
|
||||
.block_on(self.client.enumerate_revisions(uid))
|
||||
.map_err(|e| CoreError::from_api(&e, "list revisions"))?;
|
||||
Ok(revisions.into_iter().map(revision_info).collect())
|
||||
}
|
||||
|
||||
pub(crate) fn restore(&self, uid: &NodeUid, revision_id: &str, name: &str) -> CoreResult<()> {
|
||||
// Restoring rewrites the file's content: the same authority a write
|
||||
// needs, not the one a read needs.
|
||||
self.host.require_writable(uid, "restore revision")?;
|
||||
if let Err(e) = self
|
||||
.rt
|
||||
.block_on(self.client.restore_revision(uid, revision_id))
|
||||
{
|
||||
let error = CoreError::from_api(&e, "restore revision");
|
||||
self.host.log_activity(
|
||||
ActivityKind::Restore,
|
||||
name.to_string(),
|
||||
error.to_string(),
|
||||
false,
|
||||
);
|
||||
return Err(error);
|
||||
}
|
||||
// The active revision is changing behind our back — anything describing
|
||||
// the old one (cached blocks, an open reader, the size in a listing) is
|
||||
// stale from here on, and the server may not have applied the swap yet.
|
||||
self.host.content_replaced(uid);
|
||||
self.host.log_activity(
|
||||
ActivityKind::Restore,
|
||||
name,
|
||||
name.to_string(),
|
||||
format!("restored version {revision_id}"),
|
||||
true,
|
||||
);
|
||||
@@ -126,32 +147,8 @@ impl Core {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Permanently delete `revision_id` from the history of the file at `rel`.
|
||||
pub(crate) fn delete_revision(&self, rel: &Path, revision_id: &str) -> CoreResult<()> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
let name = rel
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| uid.to_string());
|
||||
self.delete_revision_for_uid(&uid, revision_id, &name)
|
||||
}
|
||||
|
||||
/// [`Core::delete_revision`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn delete_revision_by_uid(&self, uid: &str, revision_id: &str) -> CoreResult<()> {
|
||||
let uid = self.resolve_anywhere(uid)?;
|
||||
let name = uid.to_string();
|
||||
self.delete_revision_for_uid(&uid, revision_id, &name)
|
||||
}
|
||||
|
||||
fn delete_revision_for_uid(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
revision_id: &str,
|
||||
name: &str,
|
||||
) -> CoreResult<()> {
|
||||
self.require_uid_writable(uid)
|
||||
.map_err(|error| self.errno_error(error, "delete revision"))?;
|
||||
pub(crate) fn delete(&self, uid: &NodeUid, revision_id: &str, name: &str) -> CoreResult<()> {
|
||||
self.host.require_writable(uid, "delete revision")?;
|
||||
// The server rejects deleting the active revision; saying so here is a
|
||||
// sentence the user can act on instead of an API code, and it costs one
|
||||
// listing the front-end already made to show the version list.
|
||||
@@ -171,9 +168,9 @@ impl Core {
|
||||
self.rt
|
||||
.block_on(self.client.delete_revision(uid, revision_id))
|
||||
.map_err(|e| CoreError::from_api(&e, "delete revision"))?;
|
||||
self.log_activity(
|
||||
self.host.log_activity(
|
||||
ActivityKind::DeleteForever,
|
||||
name,
|
||||
name.to_string(),
|
||||
format!("deleted version {revision_id}"),
|
||||
true,
|
||||
);
|
||||
@@ -181,36 +178,7 @@ impl Core {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write `revision_id` of the file at `rel` to the absolute local path
|
||||
/// `dest`, leaving the file itself untouched.
|
||||
pub(crate) fn save_revision_as(
|
||||
&self,
|
||||
rel: &Path,
|
||||
revision_id: &str,
|
||||
dest: &Path,
|
||||
) -> CoreResult<u64> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
let name = rel
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| uid.to_string());
|
||||
self.save_revision_for_uid(&uid, revision_id, &name, dest)
|
||||
}
|
||||
|
||||
/// [`Core::save_revision_as`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn save_revision_as_by_uid(
|
||||
&self,
|
||||
uid: &str,
|
||||
revision_id: &str,
|
||||
dest: &Path,
|
||||
) -> CoreResult<u64> {
|
||||
let uid = self.resolve_anywhere(uid)?;
|
||||
let name = uid.to_string();
|
||||
self.save_revision_for_uid(&uid, revision_id, &name, dest)
|
||||
}
|
||||
|
||||
fn save_revision_for_uid(
|
||||
pub(crate) fn save_as(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
revision_id: &str,
|
||||
@@ -253,13 +221,18 @@ impl Core {
|
||||
// A half-written file looks like a successful export to every
|
||||
// tool that opens it afterwards.
|
||||
let _ = std::fs::remove_file(dest);
|
||||
self.log_activity(ActivityKind::Download, name, &error, false);
|
||||
self.host.log_activity(
|
||||
ActivityKind::Download,
|
||||
name.to_string(),
|
||||
error.to_string(),
|
||||
false,
|
||||
);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
self.log_activity(
|
||||
self.host.log_activity(
|
||||
ActivityKind::Download,
|
||||
name,
|
||||
name.to_string(),
|
||||
format!("saved version {revision_id} to {}", dest.display()),
|
||||
true,
|
||||
);
|
||||
|
||||
@@ -2,7 +2,49 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Search over the database's node and home indexes. Holds the database, the
|
||||
/// content cache (to say whether a hit is on this computer), the on-demand
|
||||
/// mounts (to say which folders a hit can be opened through) and the home
|
||||
/// indexer's busy flag.
|
||||
pub(crate) struct Search {
|
||||
db: Arc<Db>,
|
||||
cache: Arc<ContentCache>,
|
||||
mounts: Arc<Mutex<mount::SecondaryMountRegistry<SecondaryMount>>>,
|
||||
indexing: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// Search, over this daemon's indexes.
|
||||
pub(crate) fn searcher(&self) -> Search {
|
||||
Search {
|
||||
db: self.db.clone(),
|
||||
cache: self.cache.clone(),
|
||||
mounts: self.mounts.clone(),
|
||||
indexing: self.indexing.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// See [`Search::roots`].
|
||||
pub(super) fn search_roots(&self) -> SearchRoots {
|
||||
self.searcher().roots()
|
||||
}
|
||||
}
|
||||
|
||||
impl Search {
|
||||
/// Whether the home indexer is walking right now.
|
||||
pub(crate) fn indexing(&self) -> bool {
|
||||
self.indexing.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The pinned uids, expanded through pinned folders, as one query.
|
||||
fn pinned_set(&self) -> HashSet<String> {
|
||||
self.db
|
||||
.pinned_uids()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The local locations a search result can be opened through, resolved once
|
||||
/// per search rather than once per hit.
|
||||
///
|
||||
@@ -14,7 +56,7 @@ impl Core {
|
||||
/// This used to be a per-hit call that re-read the sync-folder list and ran
|
||||
/// an ancestor walk per folder, against a candidate pool of up to a
|
||||
/// thousand: the whole cost of a keystroke was in here.
|
||||
pub(super) fn search_roots(&self) -> SearchRoots {
|
||||
pub(super) fn roots(&self) -> SearchRoots {
|
||||
let live_mounts = self.mounts.lock();
|
||||
let folders = self.db.sync_folder_list().unwrap_or_default();
|
||||
SearchRoots {
|
||||
@@ -43,7 +85,7 @@ impl Core {
|
||||
.db
|
||||
.search_in(query, limit, scope)
|
||||
.map_err(|e| CoreError::from_api(&e, "search"))?;
|
||||
let roots = self.search_roots();
|
||||
let roots = self.roots();
|
||||
let pinned = self.pinned_set();
|
||||
Ok(hits
|
||||
.into_iter()
|
||||
@@ -105,7 +147,7 @@ impl Core {
|
||||
// SQLite boundary to `limit` would recreate the old empty-filter bug.
|
||||
let candidate_limit = limit.saturating_mul(10).clamp(100, 1_000);
|
||||
let mut drive_hits = if filters.sources.contains(&SearchSource::Drive) {
|
||||
let roots = self.search_roots();
|
||||
let roots = self.roots();
|
||||
let pinned = self.pinned_set();
|
||||
self.db
|
||||
.search_candidates(query, candidate_limit)
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
//! The long-lived loops a mount runs, each as a [`Service`].
|
||||
//!
|
||||
//! Each type here names its thread, says how a stop reaches it and whether the
|
||||
//! mount can do without it. `mount.rs` builds the list and starts it with
|
||||
//! [`Services::start`](pdfs_core::lifecycle::Services::start); a stop wakes and
|
||||
//! joins them in reverse order.
|
||||
|
||||
use std::os::unix::net::UnixListener;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use pdfs_core::lifecycle::{Service, Wake};
|
||||
use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_store::db::Db;
|
||||
|
||||
use super::Core;
|
||||
use super::background::run_local_index;
|
||||
use super::control::run_control_socket;
|
||||
use super::events::{EventHub, run_event_sampler};
|
||||
use super::sync;
|
||||
use super::transfers::TransferRegistry;
|
||||
|
||||
/// One of the threads that send queued changes to Drive. The drain workers wait
|
||||
/// on one condvar, which a stop has to notify; one notify wakes them all, so
|
||||
/// only the first worker carries the wake.
|
||||
pub(crate) struct DrainWorker {
|
||||
pub(crate) core: Core,
|
||||
pub(crate) index: usize,
|
||||
}
|
||||
|
||||
impl Service for DrainWorker {
|
||||
fn name(&self) -> String {
|
||||
format!("pdfs-drain-{}", self.index)
|
||||
}
|
||||
|
||||
fn wake(&self) -> Option<Wake> {
|
||||
let core = self.core.clone();
|
||||
(self.index == 0).then(|| Box::new(move || core.wake_drain()) as Wake)
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
self.core.run_pending_drain(self.index == 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder-sync engine. It watches every mirror folder, polls the remotes and
|
||||
/// reconciles on its own thread, never in front of a FUSE call. It waits on its
|
||||
/// channel, so a stop sends it `Stop`.
|
||||
///
|
||||
/// Optional: the mount still serves files without it.
|
||||
pub(crate) struct SyncEngine {
|
||||
pub(crate) syncer: sync::Syncer,
|
||||
pub(crate) tx: std::sync::mpsc::Sender<sync::SyncMsg>,
|
||||
pub(crate) rx: std::sync::mpsc::Receiver<sync::SyncMsg>,
|
||||
}
|
||||
|
||||
impl Service for SyncEngine {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-sync".to_owned()
|
||||
}
|
||||
|
||||
fn required(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn wake(&self) -> Option<Wake> {
|
||||
let tx = self.tx.clone();
|
||||
Some(Box::new(move || {
|
||||
let _ = tx.send(sync::SyncMsg::Stop);
|
||||
}))
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
let Self { syncer, rx, .. } = *self;
|
||||
sync::run(syncer, rx);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconciles leftover `(sync-conflict …)` copies: drops the ones that turned
|
||||
/// out identical to the live file and surfaces the ones that differ. It
|
||||
/// enumerates and trashes, so it must never block a FUSE call.
|
||||
pub(crate) struct ConflictSweep(pub(crate) super::sweep::Sweeper);
|
||||
|
||||
impl Service for ConflictSweep {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-conflict-sweep".to_owned()
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
self.0.run();
|
||||
}
|
||||
}
|
||||
|
||||
/// Watches the link for the life of the mount: a mount from the cache waits
|
||||
/// for the network to come back, and an online one can lose it at any moment.
|
||||
pub(crate) struct OnlineProbe(pub(crate) super::link::OnlineProbe);
|
||||
|
||||
impl Service for OnlineProbe {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-online-probe".to_owned()
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
self.0.run();
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps pinned files on this computer through changes made elsewhere, and
|
||||
/// fetches the ones a failed or missed download left out (`docs/BUGS.md`
|
||||
/// B282). A check lists folders and downloads files.
|
||||
pub(crate) struct PinKeeper(pub(crate) super::keeper::PinKeeper);
|
||||
|
||||
impl Service for PinKeeper {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-pin-keeper".to_owned()
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
self.0.run();
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps the launcher prompt's "This computer" index fresh. The walk is
|
||||
/// I/O-heavy and must never sit in front of a FUSE callback.
|
||||
pub(crate) struct LocalIndex {
|
||||
pub(crate) db: Arc<Db>,
|
||||
pub(crate) indexing: Arc<AtomicBool>,
|
||||
pub(crate) transfers: Arc<TransferRegistry>,
|
||||
pub(crate) mountpoint: PathBuf,
|
||||
pub(crate) shutdown: Arc<Shutdown>,
|
||||
}
|
||||
|
||||
impl Service for LocalIndex {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-localindex".to_owned()
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
let Self {
|
||||
db,
|
||||
indexing,
|
||||
transfers,
|
||||
mountpoint,
|
||||
shutdown,
|
||||
} = *self;
|
||||
run_local_index(db, indexing, transfers, mountpoint, shutdown);
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers the control socket, one job per connection.
|
||||
///
|
||||
/// The listener blocks in `accept`, which only returns when a connection
|
||||
/// arrives, so a stop connects to it. It connects while the socket still
|
||||
/// exists, which is the point of the poke, then unlinks it so nothing else can
|
||||
/// arrive behind it. The listener checks the stop flag after every accept, so
|
||||
/// a connection that races the unlink cannot put it back to sleep. The
|
||||
/// connections it handed off are jobs, which a stop joins; a subscription
|
||||
/// among them waits on its mailbox, so the wake rings every mailbox too.
|
||||
pub(crate) struct ControlListener {
|
||||
pub(crate) core: Core,
|
||||
pub(crate) username: String,
|
||||
pub(crate) mountpoint: PathBuf,
|
||||
pub(crate) listener: UnixListener,
|
||||
pub(crate) socket: PathBuf,
|
||||
}
|
||||
|
||||
impl Service for ControlListener {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-control".to_owned()
|
||||
}
|
||||
|
||||
fn wake(&self) -> Option<Wake> {
|
||||
let socket = self.socket.clone();
|
||||
let events: Arc<EventHub> = self.core.events.clone();
|
||||
Some(Box::new(move || {
|
||||
let _ = std::os::unix::net::UnixStream::connect(&socket);
|
||||
let _ = std::fs::remove_file(&socket);
|
||||
events.wake_all();
|
||||
}))
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
let Self {
|
||||
core,
|
||||
username,
|
||||
mountpoint,
|
||||
listener,
|
||||
..
|
||||
} = *self;
|
||||
run_control_socket(core, username, mountpoint, listener);
|
||||
}
|
||||
}
|
||||
|
||||
/// Publishes what changes without one place to publish it from (status,
|
||||
/// transfers, sync progress) to the front ends subscribed on the control
|
||||
/// socket.
|
||||
///
|
||||
/// Optional: front ends still get every published change, only not the
|
||||
/// sampled ones.
|
||||
pub(crate) struct EventSampler {
|
||||
pub(crate) core: Core,
|
||||
pub(crate) username: String,
|
||||
pub(crate) mountpoint: PathBuf,
|
||||
}
|
||||
|
||||
impl Service for EventSampler {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-events".to_owned()
|
||||
}
|
||||
|
||||
fn required(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
run_event_sampler(self.core, self.username, self.mountpoint);
|
||||
}
|
||||
}
|
||||
|
||||
/// Watches the worker pool and answers the systemd watchdog. Its liveness
|
||||
/// probe is a round trip over the control socket, so it starts after the
|
||||
/// listener.
|
||||
///
|
||||
/// Optional: the mount works without it, only it is no longer diagnosable if
|
||||
/// it wedges.
|
||||
pub(crate) struct Supervisor {
|
||||
pub(crate) core: Core,
|
||||
pub(crate) socket: PathBuf,
|
||||
}
|
||||
|
||||
impl Service for Supervisor {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-supervisor".to_owned()
|
||||
}
|
||||
|
||||
fn required(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
super::supervisor::run(self.core, self.socket);
|
||||
}
|
||||
}
|
||||
|
||||
/// Holds off a shutdown while changes exist only here (B66).
|
||||
///
|
||||
/// Optional: without it a shutdown is not delayed, and queued changes go out
|
||||
/// on the next start.
|
||||
pub(crate) struct Inhibitor {
|
||||
pub(crate) db: Arc<Db>,
|
||||
pub(crate) shutdown: Arc<Shutdown>,
|
||||
}
|
||||
|
||||
impl Service for Inhibitor {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-inhibit".to_owned()
|
||||
}
|
||||
|
||||
fn required(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
super::inhibit::run(&self.db, &self.shutdown);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//! The cells that belong to one mount's FUSE session (`SessionCells`).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// What belongs to one mount's FUSE session rather than to the daemon: whether
|
||||
/// it is the primary My Files mount, the tree inode it is rooted at, its
|
||||
/// kernel channel and whether the session is up.
|
||||
///
|
||||
/// Every other part of `Core` is shared between the primary mount and its
|
||||
/// on-demand forks. A fork gets fresh cells from [`SessionCells::fork`].
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct SessionCells {
|
||||
/// False only for a forked on-demand device mount. The synthetic shared
|
||||
/// directory belongs exclusively to the primary My Files mount.
|
||||
pub(crate) primary: bool,
|
||||
/// The tree inode this mount's session is rooted at, set when the session
|
||||
/// is built ([`ProtonFs::new`]). Each fork has its own cell.
|
||||
pub(crate) root: Arc<OnceLock<u64>>,
|
||||
/// This mount's kernel notification channel, for telling the kernel to drop
|
||||
/// metadata it has cached. Set once the session exists — which is *after*
|
||||
/// the `Core` it is built from, hence the cell.
|
||||
///
|
||||
/// Per mount, not per daemon: each session calls its own root inode 1.
|
||||
/// [`Core::fork_state`] gives each fork an empty cell of its own. Work that
|
||||
/// changes the tree for every mount tells every session
|
||||
/// ([`Core::for_each_mount`]).
|
||||
pub(crate) notifier: Arc<OnceLock<KernelChannel>>,
|
||||
/// True only after this mount's FUSE session spawned successfully.
|
||||
/// Registration happens earlier for the primary drain, so registration
|
||||
/// alone cannot answer whether the location is mounted.
|
||||
pub(crate) session_live: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl SessionCells {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
primary: true,
|
||||
root: Arc::new(OnceLock::new()),
|
||||
notifier: Arc::new(OnceLock::new()),
|
||||
session_live: Arc::new(AtomicBool::new(false)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fresh cells for an on-demand fork: not the primary mount, and no root,
|
||||
/// channel or session until the fork's own session is built.
|
||||
pub(crate) fn fork(&self) -> Self {
|
||||
Self {
|
||||
primary: false,
|
||||
..Self::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -122,7 +122,7 @@ impl Core {
|
||||
}
|
||||
|
||||
pub(super) fn ensure_shared_children(&self, ino: u64) -> Result<(), Errno> {
|
||||
let online = self.online.load(Ordering::Relaxed);
|
||||
let online = self.is_online();
|
||||
let resident = self.state().children.contains_key(&ino);
|
||||
match shared_listing_plan(
|
||||
resident,
|
||||
@@ -235,7 +235,7 @@ impl Core {
|
||||
drop(st);
|
||||
self.flush_access_changes();
|
||||
self.mark_shared_refresh_success(SHARED_WITH_ME_SYNCED_MS);
|
||||
if let Some(notifier) = self.notifier.get() {
|
||||
if let Some(notifier) = self.session.notifier.get() {
|
||||
let _ = notifier.inval_inode(ino);
|
||||
}
|
||||
Ok(())
|
||||
|
||||
+70
-267
@@ -2,54 +2,62 @@
|
||||
//! account has received, saved public-link bookmarks, and the reverse view of
|
||||
//! everything this account shares out.
|
||||
//!
|
||||
//! All of it is remote-only state — nothing here touches the inode maps or the
|
||||
//! content cache, so every method is a round-trip wrapped in the crate error
|
||||
//! shape the control socket expects.
|
||||
//! All of it is remote-only state: nothing here changes the tree or the
|
||||
//! content cache's entries for this account's own files, so every method is a
|
||||
//! round trip wrapped in the error shape the control socket expects.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
|
||||
use pdfs_core::control::{
|
||||
BookmarkInfo, DirEntry, InvitationInfo, LinkChange, PublicLinkInfo, ShareEntry, ShareEntryKind,
|
||||
SharedItem,
|
||||
SharedItem, TransferDirection,
|
||||
};
|
||||
use pdfs_core::lockrank::Ranked;
|
||||
use pdfs_core::{CoreError, CoreResult};
|
||||
use tracing::debug;
|
||||
|
||||
use crate::QUOTA_TTL;
|
||||
use pdfs_store::cache::ContentCache;
|
||||
use proton_drive_rs::proton_sdk::crypto::VerificationStatus;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use proton_drive_rs::{MemberRole, NodeKind};
|
||||
use proton_drive_rs::{MemberRole, Node, NodeKind, ProtonDriveClient};
|
||||
use tracing::debug;
|
||||
|
||||
use proton_drive_rs::Node;
|
||||
use super::drive::DriveApi;
|
||||
use super::transfers::{CountingWriter, TransferRegistry};
|
||||
use super::{State, node_size, parse_uid, public_link_info, role_from_str, role_to_str};
|
||||
|
||||
use super::{Core, node_size, parse_uid, public_link_info, role_from_str, role_to_str};
|
||||
|
||||
/// The last account quota answer, for `statfs(2)`, and whether a refresh
|
||||
/// of it is running.
|
||||
/// Sharing as a service of its own: what this account shares and with whom,
|
||||
/// its public links, what others share with it, and its saved links.
|
||||
///
|
||||
/// Every method takes a node already resolved to its uid. Turning a path or a
|
||||
/// wire-format uid into one, and the check that the node is this daemon's to
|
||||
/// share, are the caller's (the control socket's), so this holds only the
|
||||
/// handles it calls: the client, Drive, the content cache and the transfer
|
||||
/// list for opening a shared file, and a read of the tree for paths.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct QuotaCache {
|
||||
/// Last account quota answer and when it was learned, for `statfs(2)`.
|
||||
///
|
||||
/// `df` and the free-space preflight of every file manager and installer ask
|
||||
/// for this, and the answer costs a round trip — so it is served from here
|
||||
/// for [`QUOTA_TTL`] and refreshed on a worker afterwards. Total account
|
||||
/// storage moves slowly enough that a minute-old number is a better answer
|
||||
/// than either a stall or the zeroes the default implementation returns.
|
||||
pub(crate) quota: Arc<Mutex<Option<(std::time::Instant, i64, i64)>>>,
|
||||
/// Set while a `statfs` is refreshing [`Core::quota`], so the others serve
|
||||
/// the last figures instead of each holding a worker on the same request.
|
||||
pub(crate) quota_refreshing: Arc<AtomicBool>,
|
||||
pub(crate) struct Sharing {
|
||||
client: ProtonDriveClient,
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
cache: Arc<ContentCache>,
|
||||
transfers: Arc<TransferRegistry>,
|
||||
state: Arc<Ranked<State>>,
|
||||
}
|
||||
|
||||
impl QuotaCache {
|
||||
pub(crate) fn new() -> Self {
|
||||
impl Sharing {
|
||||
pub(crate) fn new(
|
||||
client: ProtonDriveClient,
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
cache: Arc<ContentCache>,
|
||||
transfers: Arc<TransferRegistry>,
|
||||
state: Arc<Ranked<State>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
quota: Arc::new(Mutex::new(None)),
|
||||
quota_refreshing: Arc::new(AtomicBool::new(false)),
|
||||
client,
|
||||
drive,
|
||||
rt,
|
||||
cache,
|
||||
transfers,
|
||||
state,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,7 +70,7 @@ impl QuotaCache {
|
||||
/// offer path-keyed actions on it. The local-state flags (`pinned`, `cached`)
|
||||
/// stay false: they describe content this account owns a local copy policy for,
|
||||
/// which a share on someone else's volume is not.
|
||||
fn shared_entry_of(core: &Core, n: Node) -> DirEntry {
|
||||
fn shared_entry_of(sharing: &Sharing, n: Node) -> DirEntry {
|
||||
let is_dir = n.is_folder();
|
||||
let size = match &n.kind {
|
||||
NodeKind::File {
|
||||
@@ -99,7 +107,7 @@ fn shared_entry_of(core: &Core, n: Node) -> DirEntry {
|
||||
pinned: false,
|
||||
pinned_by_folder: false,
|
||||
cached: false,
|
||||
path: core.rel_path_for_uid(&n.uid).unwrap_or_default(),
|
||||
path: sharing.rel_path_for_uid(&n.uid).unwrap_or_default(),
|
||||
uid: n.uid.to_string(),
|
||||
role,
|
||||
shared_by,
|
||||
@@ -112,35 +120,12 @@ fn shared_entry_of(core: &Core, n: Node) -> DirEntry {
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
impl Sharing {
|
||||
// ---- sharing a node ---------------------------------------------------
|
||||
|
||||
/// Invite Proton and/or external emails to the node at `rel` at `role`.
|
||||
/// Invite Proton and/or external emails to the node `uid` at `role`.
|
||||
/// Returns `(proton_invited, external_invited)`.
|
||||
pub(crate) fn share_node(
|
||||
&self,
|
||||
rel: &Path,
|
||||
emails: &[String],
|
||||
role: &str,
|
||||
message: Option<&str>,
|
||||
) -> CoreResult<(usize, usize)> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.share_node_for_uid(&uid, emails, role, message)
|
||||
}
|
||||
|
||||
/// [`Core::share_node`] for a node addressed through any daemon location.
|
||||
pub(crate) fn share_node_by_uid(
|
||||
&self,
|
||||
uid: &str,
|
||||
emails: &[String],
|
||||
role: &str,
|
||||
message: Option<&str>,
|
||||
) -> CoreResult<(usize, usize)> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.share_node_for_uid(&uid, emails, role, message)
|
||||
}
|
||||
|
||||
fn share_node_for_uid(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
emails: &[String],
|
||||
@@ -155,25 +140,8 @@ impl Core {
|
||||
.map_err(|e| CoreError::from_api(&e, "share"))
|
||||
}
|
||||
|
||||
/// List the members, pending invitations and public link of the node at `rel`.
|
||||
/// List the members, pending invitations and public link of the node `uid`.
|
||||
pub(crate) fn list_share(
|
||||
&self,
|
||||
rel: &Path,
|
||||
) -> CoreResult<(Vec<ShareEntry>, Option<PublicLinkInfo>)> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.list_share_for_uid(&uid)
|
||||
}
|
||||
|
||||
/// [`Core::list_share`] for a node addressed through any daemon location.
|
||||
pub(crate) fn list_share_by_uid(
|
||||
&self,
|
||||
uid: &str,
|
||||
) -> CoreResult<(Vec<ShareEntry>, Option<PublicLinkInfo>)> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.list_share_for_uid(&uid)
|
||||
}
|
||||
|
||||
fn list_share_for_uid(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
) -> CoreResult<(Vec<ShareEntry>, Option<PublicLinkInfo>)> {
|
||||
@@ -225,32 +193,8 @@ impl Core {
|
||||
}
|
||||
|
||||
/// Change the role of a member or pending Proton invitation on the node at
|
||||
/// `rel`. External invitations have no role-update endpoint.
|
||||
/// `uid`. External invitations have no role-update endpoint.
|
||||
pub(crate) fn update_share_role(
|
||||
&self,
|
||||
rel: &Path,
|
||||
id: &str,
|
||||
kind: ShareEntryKind,
|
||||
role: &str,
|
||||
) -> CoreResult<()> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.update_share_role_for_uid(&uid, id, kind, role)
|
||||
}
|
||||
|
||||
/// [`Core::update_share_role`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn update_share_role_by_uid(
|
||||
&self,
|
||||
uid: &str,
|
||||
id: &str,
|
||||
kind: ShareEntryKind,
|
||||
role: &str,
|
||||
) -> CoreResult<()> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.update_share_role_for_uid(&uid, id, kind, role)
|
||||
}
|
||||
|
||||
fn update_share_role_for_uid(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
id: &str,
|
||||
@@ -290,30 +234,8 @@ impl Core {
|
||||
}
|
||||
|
||||
/// Remove a member, pending Proton invite, or external invite from the node
|
||||
/// at `rel`.
|
||||
/// at `uid`.
|
||||
pub(crate) fn remove_share_entry(
|
||||
&self,
|
||||
rel: &Path,
|
||||
id: &str,
|
||||
kind: ShareEntryKind,
|
||||
) -> CoreResult<()> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.remove_share_entry_for_uid(&uid, id, kind)
|
||||
}
|
||||
|
||||
/// [`Core::remove_share_entry`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn remove_share_entry_by_uid(
|
||||
&self,
|
||||
uid: &str,
|
||||
id: &str,
|
||||
kind: ShareEntryKind,
|
||||
) -> CoreResult<()> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.remove_share_entry_for_uid(&uid, id, kind)
|
||||
}
|
||||
|
||||
fn remove_share_entry_for_uid(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
id: &str,
|
||||
@@ -359,32 +281,8 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a public link on the node at `rel`, returning its info (with URL).
|
||||
/// Create a public link on the node `uid`, returning its info (with URL).
|
||||
pub(crate) fn create_public_link(
|
||||
&self,
|
||||
rel: &Path,
|
||||
role: &str,
|
||||
password: Option<&str>,
|
||||
expires: Option<i64>,
|
||||
) -> CoreResult<PublicLinkInfo> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.create_public_link_for_uid(&uid, role, password, expires)
|
||||
}
|
||||
|
||||
/// [`Core::create_public_link`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn create_public_link_by_uid(
|
||||
&self,
|
||||
uid: &str,
|
||||
role: &str,
|
||||
password: Option<&str>,
|
||||
expires: Option<i64>,
|
||||
) -> CoreResult<PublicLinkInfo> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.create_public_link_for_uid(&uid, role, password, expires)
|
||||
}
|
||||
|
||||
fn create_public_link_for_uid(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
role: &str,
|
||||
@@ -399,36 +297,11 @@ impl Core {
|
||||
Ok(public_link_info(link))
|
||||
}
|
||||
|
||||
/// Change the public link `id` on the node at `rel`, keeping its URL.
|
||||
pub(crate) fn update_public_link(
|
||||
&self,
|
||||
rel: &Path,
|
||||
id: &str,
|
||||
role: Option<&str>,
|
||||
password: LinkChange<String>,
|
||||
expires: LinkChange<i64>,
|
||||
) -> CoreResult<PublicLinkInfo> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.update_public_link_for_uid(&uid, id, role, password, expires)
|
||||
}
|
||||
|
||||
/// [`Core::update_public_link`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn update_public_link_by_uid(
|
||||
&self,
|
||||
uid: &str,
|
||||
id: &str,
|
||||
role: Option<&str>,
|
||||
password: LinkChange<String>,
|
||||
expires: LinkChange<i64>,
|
||||
) -> CoreResult<PublicLinkInfo> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.update_public_link_for_uid(&uid, id, role, password, expires)
|
||||
}
|
||||
|
||||
/// Change the public link `id` on the node `uid`, keeping its URL.
|
||||
///
|
||||
/// The SDK sets all three options on every update, so each `Keep` is
|
||||
/// filled in from the link as it stands.
|
||||
fn update_public_link_for_uid(
|
||||
pub(crate) fn update_public_link(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
id: &str,
|
||||
@@ -482,20 +355,8 @@ impl Core {
|
||||
Ok(public_link_info(link))
|
||||
}
|
||||
|
||||
/// Remove the public link `id` from the node at `rel`.
|
||||
pub(crate) fn remove_public_link(&self, rel: &Path, id: &str) -> CoreResult<()> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.remove_public_link_for_uid(&uid, id)
|
||||
}
|
||||
|
||||
/// [`Core::remove_public_link`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn remove_public_link_by_uid(&self, uid: &str, id: &str) -> CoreResult<()> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.remove_public_link_for_uid(&uid, id)
|
||||
}
|
||||
|
||||
fn remove_public_link_for_uid(&self, uid: &NodeUid, id: &str) -> CoreResult<()> {
|
||||
/// Remove the public link `id` from the node `uid`.
|
||||
pub(crate) fn remove_public_link(&self, uid: &NodeUid, id: &str) -> CoreResult<()> {
|
||||
let link = self
|
||||
.rt
|
||||
.block_on(self.client.get_public_link(uid))
|
||||
@@ -507,25 +368,15 @@ impl Core {
|
||||
.map_err(|e| CoreError::from_api(&e, "remove public link"))
|
||||
}
|
||||
|
||||
/// Stop sharing the node at `rel`: remove its public link, then every
|
||||
/// Stop sharing the node `uid`: remove its public link, then every
|
||||
/// external invitation, Proton invitation and member. The SDK has no call
|
||||
/// that deletes a share outright, so this composes the per-entry ones.
|
||||
pub(crate) fn stop_sharing(&self, rel: &Path) -> CoreResult<StopSharingOutcome> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.stop_sharing_for_uid(&uid)
|
||||
}
|
||||
|
||||
/// [`Core::stop_sharing`] for a node addressed through any daemon location.
|
||||
pub(crate) fn stop_sharing_by_uid(&self, uid: &str) -> CoreResult<StopSharingOutcome> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.stop_sharing_for_uid(&uid)
|
||||
}
|
||||
|
||||
///
|
||||
/// Each step runs even when an earlier one failed, so a single stuck
|
||||
/// member does not leave the public link up. The link goes first: it is the
|
||||
/// widest exposure. Only a failure to list what is there fails the whole
|
||||
/// request; a failed removal is counted in the outcome.
|
||||
fn stop_sharing_for_uid(&self, uid: &NodeUid) -> CoreResult<StopSharingOutcome> {
|
||||
pub(crate) fn stop_sharing(&self, uid: &NodeUid) -> CoreResult<StopSharingOutcome> {
|
||||
let mut outcome = StopSharingOutcome::default();
|
||||
let link = self
|
||||
.rt
|
||||
@@ -637,9 +488,17 @@ impl Core {
|
||||
if let Some(p) = self.cache.cached_content_path(&uid, mtime, size) {
|
||||
return Ok(p);
|
||||
}
|
||||
let bytes = self
|
||||
.download_file_tracked(&uid, &node.name, size)
|
||||
let guard = self.transfers.begin(
|
||||
&node.name,
|
||||
uid.to_string(),
|
||||
TransferDirection::Download,
|
||||
size,
|
||||
);
|
||||
let mut out = CountingWriter::new(Vec::with_capacity(size as usize), &guard);
|
||||
self.rt
|
||||
.block_on(self.drive.download_file_to(&uid, &mut out))
|
||||
.map_err(|e| CoreError::from_api(&e, "download"))?;
|
||||
let bytes = out.into_inner();
|
||||
self.cache
|
||||
.store(&uid, mtime, size, &bytes)
|
||||
.map_err(|e| CoreError::internal(format!("cache store: {e}")))?;
|
||||
@@ -721,62 +580,6 @@ impl Core {
|
||||
.map_err(|e| CoreError::from_api(&e, "delete bookmark"))
|
||||
}
|
||||
|
||||
// ---- account ----------------------------------------------------------
|
||||
|
||||
/// Total account storage usage `(max_space, used_space)` in bytes, across all
|
||||
/// Proton products (not Drive-only). A remote round-trip; nothing here is
|
||||
/// cached.
|
||||
pub(crate) fn account_quota(&self) -> CoreResult<(i64, i64)> {
|
||||
let q = self.block_on_bounded(self.drive.quota()).map_err(|e| {
|
||||
self.lost_link(&e, "account quota");
|
||||
CoreError::from_api(&e, "account quota")
|
||||
})?;
|
||||
*self.quota_cache.quota.lock() =
|
||||
Some((std::time::Instant::now(), q.max_space, q.used_space));
|
||||
Ok((q.max_space, q.used_space))
|
||||
}
|
||||
|
||||
/// The account quota as `statfs(2)` needs it: cached for [`QUOTA_TTL`],
|
||||
/// refetched after that, and `None` when there is no usable answer at all —
|
||||
/// offline with nothing cached.
|
||||
///
|
||||
/// Never blocks on the network for a *fresh* value when a recent one exists,
|
||||
/// because the callers are `df` and every "is there room?" preflight, and a
|
||||
/// stale byte count is worth more to them than a stalled syscall. Offline,
|
||||
/// the last known figures keep being served rather than degrading to zero.
|
||||
pub(crate) fn account_quota_cached(&self) -> Option<(i64, i64)> {
|
||||
if let Some((at, max_space, used_space)) = *self.quota_cache.quota.lock()
|
||||
&& at.elapsed() < QUOTA_TTL
|
||||
{
|
||||
return Some((max_space, used_space));
|
||||
}
|
||||
let last = || {
|
||||
self.quota_cache
|
||||
.quota
|
||||
.lock()
|
||||
.map(|(_, max, used)| (max, used))
|
||||
};
|
||||
if !self.is_online()
|
||||
|| self
|
||||
.quota_cache
|
||||
.quota_refreshing
|
||||
.swap(true, std::sync::atomic::Ordering::AcqRel)
|
||||
{
|
||||
return last();
|
||||
}
|
||||
let refreshed = self.account_quota();
|
||||
self.quota_cache
|
||||
.quota_refreshing
|
||||
.store(false, std::sync::atomic::Ordering::Release);
|
||||
match refreshed {
|
||||
Ok(q) => Some(q),
|
||||
Err(error) => {
|
||||
debug!(%error, "account quota refresh failed; serving the last known figures");
|
||||
last()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- shared by me -----------------------------------------------------
|
||||
|
||||
/// List the nodes I have shared with others, each with a summary of its share
|
||||
@@ -846,15 +649,15 @@ impl Core {
|
||||
/// tree, by walking parent inodes to the root. `None` when the node has never
|
||||
/// been seen through the mount (e.g. shared but not browsed to this session) —
|
||||
/// the caller then leaves the path empty.
|
||||
pub(crate) fn rel_path_for_uid(&self, uid: &NodeUid) -> Option<String> {
|
||||
fn rel_path_for_uid(&self, uid: &NodeUid) -> Option<String> {
|
||||
// Relative to whichever root the node sits under: a node browsed
|
||||
// through a sync folder is under that fork's root, not My Files
|
||||
// (`docs/BUGS.md` B74).
|
||||
walk_to_root(&self.state(), uid)
|
||||
walk_to_root(&self.state.lock(), uid)
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`Core::stop_sharing`] managed to remove.
|
||||
/// What [`Sharing::stop_sharing`] managed to remove.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct StopSharingOutcome {
|
||||
/// Entries removed (the link, invitations and members alike).
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
//! The mounted-files conformance scenarios (`pdfs_vfs::conformance`) run
|
||||
//! through the FUSE adapter: a daemon mounted over the fake Drive, driven with
|
||||
//! ordinary file system calls. The headless adapter runs the same scenarios
|
||||
//! in `pdfs-vfs`, and both have to see the same outcomes.
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::os::unix::fs::FileExt;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use pdfs_vfs::conformance::Adapter;
|
||||
use pdfs_vfs::headless::Failure;
|
||||
|
||||
/// A mount, addressed by paths relative to its root.
|
||||
pub(crate) struct Mounted(pub(crate) PathBuf);
|
||||
|
||||
fn failure(error: std::io::Error) -> Failure {
|
||||
error
|
||||
.raw_os_error()
|
||||
.map_or(Failure::Io, Failure::from_errno)
|
||||
}
|
||||
|
||||
impl Adapter for Mounted {
|
||||
type Fd = File;
|
||||
|
||||
fn create(&self, path: &str) -> Result<File, Failure> {
|
||||
File::create(self.0.join(path)).map_err(failure)
|
||||
}
|
||||
|
||||
fn open_write(&self, path: &str) -> Result<File, Failure> {
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.open(self.0.join(path))
|
||||
.map_err(failure)
|
||||
}
|
||||
|
||||
fn write(&self, fd: &File, offset: u64, data: &[u8]) -> Result<(), Failure> {
|
||||
fd.write_all_at(data, offset).map_err(failure)
|
||||
}
|
||||
|
||||
fn set_len(&self, fd: &File, size: u64) -> Result<(), Failure> {
|
||||
fd.set_len(size).map_err(failure)
|
||||
}
|
||||
|
||||
fn fsync(&self, fd: &File) -> Result<(), Failure> {
|
||||
fd.sync_all().map_err(failure)
|
||||
}
|
||||
|
||||
fn close(&self, fd: File) -> Result<(), Failure> {
|
||||
// `close(2)`'s own error is the flush's, which `File` drops; flush
|
||||
// first so a failure is seen.
|
||||
fd.sync_data().map_err(failure)?;
|
||||
drop(fd);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read(&self, path: &str) -> Result<Vec<u8>, Failure> {
|
||||
std::fs::read(self.0.join(path)).map_err(failure)
|
||||
}
|
||||
|
||||
fn mkdir(&self, path: &str) -> Result<(), Failure> {
|
||||
std::fs::create_dir(self.0.join(path)).map_err(failure)
|
||||
}
|
||||
|
||||
fn unlink(&self, path: &str) -> Result<(), Failure> {
|
||||
std::fs::remove_file(self.0.join(path)).map_err(failure)
|
||||
}
|
||||
|
||||
fn rmdir(&self, path: &str) -> Result<(), Failure> {
|
||||
std::fs::remove_dir(self.0.join(path)).map_err(failure)
|
||||
}
|
||||
|
||||
fn rename(&self, from: &str, to: &str) -> Result<(), Failure> {
|
||||
std::fs::rename(self.0.join(from), self.0.join(to)).map_err(failure)
|
||||
}
|
||||
|
||||
fn list(&self, path: &str) -> Result<Vec<String>, Failure> {
|
||||
let mut names = std::fs::read_dir(self.0.join(path))
|
||||
.map_err(failure)?
|
||||
.map(|entry| {
|
||||
entry
|
||||
.map(|entry| entry.file_name().to_string_lossy().into_owned())
|
||||
.map_err(failure)
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
names.sort();
|
||||
Ok(names)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
|
||||
use super::*;
|
||||
use crate::mount::MountOutcome;
|
||||
use crate::sim::daemon::{Daemon, scratch, wait_until};
|
||||
use crate::sim::fake_drive::{FakeDrive, Faults};
|
||||
|
||||
fn run_through_a_mount(label: &str, online: bool) {
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch(label);
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
|
||||
daemon.client.set_online(online);
|
||||
let mount = Mounted(daemon.mountpoint.clone());
|
||||
mount.mkdir("conformance").unwrap();
|
||||
let failed = pdfs_vfs::conformance::run(&mount, "conformance");
|
||||
daemon.client.set_online(true);
|
||||
// Whatever the scenarios queued drains before the daemon stops, so the
|
||||
// stop does not race an upload.
|
||||
let drained = wait_until(Duration::from_secs(60), || {
|
||||
daemon.pending().is_ok_and(|items| items.is_empty())
|
||||
});
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert!(failed.is_empty(), "{failed:#?}");
|
||||
assert!(drained, "the queue did not drain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn the_mount_passes_every_conformance_scenario_online() {
|
||||
run_through_a_mount("conformance-online", true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn the_mount_passes_every_conformance_scenario_offline() {
|
||||
run_through_a_mount("conformance-offline", false);
|
||||
}
|
||||
}
|
||||
@@ -479,6 +479,7 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::sim::fake_drive::{Entry, FakeDrive, Faults};
|
||||
use pdfs_core::control::{RefreshScope, SyncIssue};
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
@@ -538,6 +539,81 @@ mod tests {
|
||||
assert!(uploads.count >= 1);
|
||||
}
|
||||
|
||||
/// How often the daemon has asked Drive for the children of a folder.
|
||||
fn children_listed(daemon: &Daemon) -> u64 {
|
||||
let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics)
|
||||
else {
|
||||
panic!("no diagnostics");
|
||||
};
|
||||
diagnostics
|
||||
.drive_calls
|
||||
.iter()
|
||||
.find(|stat| stat.call == "enumerate_folder_children_node_uids")
|
||||
.map_or(0, |stat| stat.count)
|
||||
}
|
||||
|
||||
fn listing_load(daemon: &Daemon) -> control::AdmissionLoad {
|
||||
let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics)
|
||||
else {
|
||||
panic!("no diagnostics");
|
||||
};
|
||||
diagnostics
|
||||
.admission
|
||||
.into_iter()
|
||||
.find(|load| load.class == "listing")
|
||||
.expect("the admission reports cold listings")
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn callers_that_find_a_folder_unlisted_at_once_share_one_listing() {
|
||||
// Each caller used to ask Drive for the folder itself, and all but
|
||||
// the first threw the answer away. Now the first lists it, through
|
||||
// the daemon's admission, and the others wait for that listing.
|
||||
let drive = FakeDrive::new();
|
||||
let cold = drive.device().mkdir("cold");
|
||||
for name in ["a.txt", "b.txt", "c.txt"] {
|
||||
drive
|
||||
.device()
|
||||
.write(&format!("cold/{name}"), name.as_bytes());
|
||||
}
|
||||
let dir = scratch("cold-listing-flight");
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
|
||||
let listed = |daemon: &Daemon| match daemon.request(&Request::ListDir {
|
||||
path: "cold".into(),
|
||||
}) {
|
||||
Ok(Response::Entries { entries }) => {
|
||||
let mut names: Vec<String> = entries.into_iter().map(|e| e.name).collect();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
other => panic!("listing cold: {other:?}"),
|
||||
};
|
||||
// The mount root is listed first, so the only listing held is cold's.
|
||||
let _ = std::fs::read_dir(&daemon.mountpoint).unwrap().count();
|
||||
|
||||
let before = children_listed(&daemon);
|
||||
let held = daemon.client.hold_next_children_of(&cold);
|
||||
std::thread::scope(|scope| {
|
||||
let callers: Vec<_> = (0..4).map(|_| scope.spawn(|| listed(&daemon))).collect();
|
||||
assert!(wait_until(Duration::from_secs(10), || held.reached()));
|
||||
// Give the others time to find the folder unlisted too.
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
let load = listing_load(&daemon);
|
||||
assert_eq!((load.running, load.waiting), (1, 0), "{load:?}");
|
||||
drop(held);
|
||||
for caller in callers {
|
||||
assert_eq!(caller.join().unwrap(), ["a.txt", "b.txt", "c.txt"]);
|
||||
}
|
||||
});
|
||||
assert_eq!(children_listed(&daemon) - before, 1);
|
||||
let load = listing_load(&daemon);
|
||||
assert_eq!(load.running, 0, "{load:?}");
|
||||
assert!(load.admitted >= 1, "{load:?}");
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_daemon_on_the_fake_drive_syncs_both_ways() {
|
||||
@@ -883,10 +959,16 @@ mod tests {
|
||||
|
||||
daemon.client.set_online(false);
|
||||
std::fs::write(daemon.mountpoint.join("f.txt"), b"0123456789").unwrap();
|
||||
// Usually the drain meets the outage first. Another caller (the event
|
||||
// poll, a sync pass) can meet it first and take the mount offline,
|
||||
// and then the drain claims nothing and the write has no failed
|
||||
// attempt to wait out. Both must end with the write going out soon
|
||||
// after the link returns.
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
daemon
|
||||
.pending()
|
||||
.is_ok_and(|items| items.iter().any(|item| item.attempts > 0))
|
||||
|| daemon.online().is_ok_and(|online| !online)
|
||||
}));
|
||||
// The drain records the failure just before it takes the mount
|
||||
// offline. Left online, only the event poll would, much later.
|
||||
@@ -1250,6 +1332,33 @@ mod tests {
|
||||
std::fs::remove_file(mnt.join("gone.txt")).unwrap();
|
||||
std::fs::write(mnt.join("new.txt"), b"new").unwrap();
|
||||
std::fs::create_dir(mnt.join("dir")).unwrap();
|
||||
std::fs::rename(mnt.join("edit.txt"), mnt.join("edited.txt")).unwrap();
|
||||
|
||||
// The queue says which changes share a node, so the app can name
|
||||
// every change a discard drops, and which nodes Drive never had.
|
||||
let queued = daemon.pending().unwrap();
|
||||
let on = |name: &str| -> Vec<&PendingOpInfo> {
|
||||
queued.iter().filter(|op| op.path.ends_with(name)).collect()
|
||||
};
|
||||
// By node, not by path: the path an op shows may still be the old
|
||||
// name for a moment after the rename.
|
||||
let edit = queued
|
||||
.iter()
|
||||
.find(|op| op.kind == "revision")
|
||||
.expect("the edit is queued");
|
||||
let same: Vec<&str> = queued
|
||||
.iter()
|
||||
.filter(|op| op.node == edit.node)
|
||||
.map(|op| op.kind.as_str())
|
||||
.collect();
|
||||
assert!(!edit.node.is_empty());
|
||||
assert_eq!(same, ["revision", "rename"], "{queued:?}");
|
||||
assert!(!edit.local_only);
|
||||
assert!(on("new.txt").iter().all(|op| op.local_only), "{queued:?}");
|
||||
assert!(
|
||||
on("moved.txt").iter().all(|op| !op.local_only),
|
||||
"{queued:?}"
|
||||
);
|
||||
|
||||
// Discarding one change drops the others queued on its node.
|
||||
for _ in 0..10 {
|
||||
@@ -1881,6 +1990,308 @@ mod tests {
|
||||
.map_or(0, |c| c.value)
|
||||
}
|
||||
|
||||
/// Once the watch has been live for a pass, a pass reads again only what
|
||||
/// the watcher reported, and that is enough to find every change: an
|
||||
/// edit, a new folder with a file in it, a deletion, and a folder moved in
|
||||
/// from outside with a folder and a file in it (`local_dirty`).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_trusted_local_dirty_set_stands_in_for_the_walk() {
|
||||
// The log is shared by every test in the process: drop what earlier
|
||||
// tests left in it, so only this daemon's lines are counted.
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("local-dirty");
|
||||
let (daemon, folder, _client) =
|
||||
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
|
||||
// From the pass after this one, the watch has been live since the
|
||||
// last claim.
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let settled = quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
assert_eq!(counted(&settled, "local dirty untrusted"), 0, "{settled}");
|
||||
assert!(counted(&settled, "local reused") > 0, "{settled}");
|
||||
|
||||
let local = dir.join("local");
|
||||
let outside = dir.join("outside");
|
||||
std::fs::create_dir_all(outside.join("deep")).unwrap();
|
||||
std::fs::write(outside.join("deep").join("x.txt"), b"moved in").unwrap();
|
||||
std::fs::write(local.join("a.txt"), b"edited").unwrap();
|
||||
std::fs::create_dir(local.join("new")).unwrap();
|
||||
std::fs::write(local.join("new").join("c.txt"), b"three").unwrap();
|
||||
std::fs::remove_file(local.join("b.txt")).unwrap();
|
||||
std::fs::rename(&outside, local.join("moved")).unwrap();
|
||||
assert!(wait_until(Duration::from_secs(60), || {
|
||||
drive.lookup("mirrored/new/c.txt").is_some()
|
||||
&& drive.lookup("mirrored/moved/deep/x.txt").is_some()
|
||||
&& drive.lookup("mirrored/b.txt").is_none()
|
||||
}));
|
||||
let after = quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
assert_eq!(counted(&after, "local dirty untrusted"), 0, "{after}");
|
||||
// Still taken from the last pass's walk: none of the passes since
|
||||
// changed anything on disk, so each kept its walk for the next.
|
||||
assert!(counted(&after, "local reused") > 0, "{after}");
|
||||
let logged = take_logged();
|
||||
let missed: Vec<&String> = logged
|
||||
.iter()
|
||||
.filter(|line| line.contains("local dirty set missed"))
|
||||
.collect();
|
||||
assert!(missed.is_empty(), "{missed:?}");
|
||||
// The first pass took the folder from discovery to following, and
|
||||
// nothing since put it in doubt (`root`).
|
||||
let roots: Vec<&String> = logged
|
||||
.iter()
|
||||
.filter(|line| line.contains("sync: root state"))
|
||||
.collect();
|
||||
assert!(
|
||||
roots.len() == 1 && roots[0].contains("to=following"),
|
||||
"{roots:?}"
|
||||
);
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A sync root moved away and made again in its place is a new folder
|
||||
/// on disk, which the old watch does not see. The engine watches it again
|
||||
/// once it is back, and walks it once more after, so a file written in
|
||||
/// it as the watch was set up still reaches Drive without waiting for the
|
||||
/// poll (`root`).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_root_made_again_is_watched_again() {
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("root-again");
|
||||
let (daemon, folder, _client) =
|
||||
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let local = dir.join("local");
|
||||
let away = dir.join("away");
|
||||
std::fs::rename(&local, &away).unwrap();
|
||||
let _ = daemon.request(&Request::SyncNow { id: Some(folder) });
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
take_logged()
|
||||
.iter()
|
||||
.any(|line| line.contains("to=suspended (RootMissing)"))
|
||||
}));
|
||||
// A new folder in the old one's place, with the same files.
|
||||
std::fs::create_dir(&local).unwrap();
|
||||
for name in ["a.txt", "b.txt"] {
|
||||
std::fs::copy(away.join(name), local.join(name)).unwrap();
|
||||
}
|
||||
let _ = daemon.request(&Request::SyncNow { id: Some(folder) });
|
||||
// The pass that finds it back walks it in full, and the watches are
|
||||
// set up again after it.
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
take_logged().iter().any(|line| {
|
||||
line.contains("from=suspended (RootMissing)") && line.contains("to=following")
|
||||
})
|
||||
}));
|
||||
// Written as that pass ends, which may be before the watch is set up
|
||||
// again: the event is then lost, and only the pass the new watch
|
||||
// brings about finds the file. Nothing else asks for one, and the
|
||||
// poll is two minutes off.
|
||||
std::fs::write(local.join("c.txt"), b"three").unwrap();
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(60), || drive
|
||||
.lookup("mirrored/c.txt")
|
||||
.is_some()),
|
||||
"a file written in the root made again reaches Drive"
|
||||
);
|
||||
assert!(drive.lookup("mirrored/a.txt").is_some());
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A sync root replaced between two passes is never seen missing, and
|
||||
/// the watch stays on the folder moved away. The pass sees the root is
|
||||
/// another folder, and the engine watches the new one (`root`).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_root_replaced_between_passes_is_watched_again() {
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("root-replaced");
|
||||
let (daemon, folder, _client) =
|
||||
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let local = dir.join("local");
|
||||
let away = dir.join("away");
|
||||
std::fs::rename(&local, &away).unwrap();
|
||||
std::fs::create_dir(&local).unwrap();
|
||||
for name in ["a.txt", "b.txt"] {
|
||||
std::fs::copy(away.join(name), local.join(name)).unwrap();
|
||||
}
|
||||
take_logged();
|
||||
let _ = daemon.request(&Request::SyncNow { id: Some(folder) });
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
take_logged()
|
||||
.iter()
|
||||
.any(|line| line.contains("the folder's root was replaced"))
|
||||
}));
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
std::fs::write(local.join("c.txt"), b"three").unwrap();
|
||||
// Only the watch can bring this pass about: the poll is two minutes
|
||||
// off.
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(60), || drive
|
||||
.lookup("mirrored/c.txt")
|
||||
.is_some()),
|
||||
"a file written in the root put in place reaches Drive"
|
||||
);
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An effect a daemon sent and never heard back from is `unsure` at the
|
||||
/// next start. One the folder still needs is sent again, and settles; one
|
||||
/// it no longer needs is settled by the first pass that looks (`effect`).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn an_effect_left_unsure_by_a_stop_is_sent_again_or_settled() {
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("unsure-effect");
|
||||
let (daemon, folder, client) = start_mirror(&drive, &dir, &[("a.txt", b"one")]);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
// What a daemon killed while it sent two uploads leaves: one landed
|
||||
// (a.txt is on Drive), the other never went out.
|
||||
let sent = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as i64
|
||||
- 10;
|
||||
let db = reopen(&dir);
|
||||
db.sync_intent_issue(folder, "a.txt", "upload", sent)
|
||||
.unwrap();
|
||||
db.sync_intent_issue(folder, "new.txt", "upload", sent)
|
||||
.unwrap();
|
||||
drop(db);
|
||||
std::fs::write(dir.join("local").join("new.txt"), b"new").unwrap();
|
||||
take_logged();
|
||||
let daemon = Daemon::start(&dir, client).unwrap();
|
||||
assert!(wait_until(Duration::from_secs(60), || drive
|
||||
.lookup("mirrored/new.txt")
|
||||
.is_some()));
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let logged = take_logged();
|
||||
let has = |text: &str| logged.iter().any(|line| line.contains(text));
|
||||
assert!(
|
||||
has("effects=2") && has("did not hear back from"),
|
||||
"{logged:#?}"
|
||||
);
|
||||
assert!(
|
||||
has("sending again an effect a stopped daemon may have made"),
|
||||
"{logged:#?}"
|
||||
);
|
||||
assert!(
|
||||
has("an effect a stopped daemon may have made is no longer needed"),
|
||||
"{logged:#?}"
|
||||
);
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
assert!(
|
||||
reopen(&dir).sync_intents(Some(folder)).unwrap().is_empty(),
|
||||
"every intent settled"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The mirror effects not settled yet, from `pdfs diagnostics`.
|
||||
fn effects(daemon: &Daemon) -> Vec<control::EffectIntent> {
|
||||
let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics)
|
||||
else {
|
||||
panic!("no diagnostics");
|
||||
};
|
||||
diagnostics.effects.map(|e| e.oldest).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A deletion a mirror pass sends is recorded like any other effect, and
|
||||
/// `pdfs diagnostics` lists it until it lands: a trash on Drive while its
|
||||
/// answer is outstanding, and a removal from disk.
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_deletion_is_an_effect_until_it_lands() {
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("deletion-effect");
|
||||
let (daemon, folder, _client) = start_mirror(
|
||||
&drive,
|
||||
&dir,
|
||||
&[
|
||||
("a.txt", b"one"),
|
||||
("b.txt", b"two"),
|
||||
("c.txt", b"three"),
|
||||
("d.txt", b"four"),
|
||||
],
|
||||
);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let uid = drive.lookup("mirrored/a.txt").unwrap();
|
||||
let held = daemon.client.hold_next_trash(&uid);
|
||||
std::fs::remove_file(dir.join("local").join("a.txt")).unwrap();
|
||||
assert!(wait_until(Duration::from_secs(60), || held.reached()));
|
||||
let listed = effects(&daemon);
|
||||
assert!(
|
||||
listed.iter().any(|e| e.folder_id == folder
|
||||
&& e.rel_path == "a.txt"
|
||||
&& e.kind == "trash"
|
||||
&& e.state == "issued"),
|
||||
"{listed:#?}"
|
||||
);
|
||||
drop(held);
|
||||
assert!(wait_until(Duration::from_secs(60), || {
|
||||
drive.lookup("mirrored/a.txt").is_none() && effects(&daemon).is_empty()
|
||||
}));
|
||||
|
||||
drive.device().trash("mirrored/b.txt");
|
||||
assert!(wait_until(Duration::from_secs(60), || {
|
||||
!dir.join("local").join("b.txt").exists()
|
||||
}));
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(30), || effects(&daemon).is_empty()),
|
||||
"{:#?}",
|
||||
effects(&daemon)
|
||||
);
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A restart owes the disk a walk in full, since nothing watched it
|
||||
/// meanwhile, and owes Drive nothing: its event stream resumes from the
|
||||
/// cursor (`root`).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_restart_walks_the_disk_in_full_and_not_drive() {
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("restart-owes");
|
||||
let (daemon, folder, _client) =
|
||||
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
take_logged();
|
||||
let daemon = daemon.restart().unwrap();
|
||||
let quiet = quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let logged = take_logged();
|
||||
let roots: Vec<&String> = logged
|
||||
.iter()
|
||||
.filter(|line| line.contains("sync: root state"))
|
||||
.collect();
|
||||
assert!(
|
||||
roots.len() == 1
|
||||
&& roots[0].contains("from=auditing (local: Restart)")
|
||||
&& roots[0].contains("to=following")
|
||||
&& roots[0].contains("Covered { local: true, remote: false }"),
|
||||
"{roots:?}"
|
||||
);
|
||||
assert!(
|
||||
!logged
|
||||
.iter()
|
||||
.any(|line| line.contains("the root state asks for a walk of all of Drive")),
|
||||
"a restart owes Drive nothing"
|
||||
);
|
||||
assert!(counted(&quiet, "reused") > 0, "{quiet}");
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_mirror_pass_reports_where_its_time_went() {
|
||||
@@ -1897,6 +2308,9 @@ mod tests {
|
||||
let first = traced_pass(&daemon, folder, |t| calls(t, "upload") > 0)
|
||||
.expect("the first pass is traced");
|
||||
assert_eq!(calls(&first, "upload"), 3);
|
||||
// Each upload waited for the daemon's admission first, and the time
|
||||
// in line is its own entry, apart from the time on the network.
|
||||
assert_eq!(calls(&first, "admission wait"), 3, "{first}");
|
||||
assert_eq!(counted(&first, "local entries"), 3);
|
||||
assert!(counted(&first, "remote folders") >= 1);
|
||||
for phase in ["baseline", "local walk", "remote walk", "apply"] {
|
||||
@@ -1910,6 +2324,17 @@ mod tests {
|
||||
.iter()
|
||||
.any(|line| line.contains("sync: pass trace"))
|
||||
);
|
||||
let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics)
|
||||
else {
|
||||
panic!("no diagnostics");
|
||||
};
|
||||
let mirror = diagnostics
|
||||
.admission
|
||||
.iter()
|
||||
.find(|load| load.class == "mirror")
|
||||
.expect("the admission reports mirror steps");
|
||||
assert!(mirror.admitted >= 3, "{mirror:?}");
|
||||
assert_eq!((mirror.running, mirror.waiting), (0, 0), "{mirror:?}");
|
||||
|
||||
// Drive does not list a node it has just made at once, so the read
|
||||
// back after an upload has no revision id to record. The next pass
|
||||
@@ -2150,6 +2575,70 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_mirror_create_whose_reply_was_lost_is_adopted_after_a_restart_and_its_edit_lands() {
|
||||
// Drive made the file, but the answer never came back, and the daemon
|
||||
// stopped before it tried again. While it was stopped the file was
|
||||
// written again. A one-request small upload makes this the common way
|
||||
// a create goes unanswered: it leaves a whole file, never a draft. The
|
||||
// start must find that file, take it as this one, and put the newer
|
||||
// bytes on it: one file, no conflict copy.
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("mirror-lost-create-restart");
|
||||
let (daemon, folder, client) = start_mirror(&drive, &dir, &[("a.txt", b"one")]);
|
||||
let local = dir.join("local");
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
|
||||
client.lose_reply_to_next_create();
|
||||
std::fs::write(local.join("new.txt"), b"first").unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
on_drive(&drive, "mirrored/new.txt").is_some_and(|bytes| bytes == b"first")
|
||||
}));
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
|
||||
std::fs::write(local.join("new.txt"), b"second, written while stopped").unwrap();
|
||||
let daemon = Daemon::start(&dir, client).unwrap();
|
||||
let landed = wait_until(Duration::from_secs(60), || {
|
||||
on_drive(&drive, "mirrored/new.txt")
|
||||
.is_some_and(|bytes| bytes == b"second, written while stopped")
|
||||
});
|
||||
let logged = take_logged();
|
||||
assert!(
|
||||
landed,
|
||||
"{:#?}\n{:#?}",
|
||||
drive.tree(),
|
||||
logged
|
||||
.iter()
|
||||
.filter(|l| l.contains("sync") || l.contains("new"))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
|
||||
assert!(conflict_copies(&local, "new").is_empty());
|
||||
let tree = drive.tree();
|
||||
assert!(
|
||||
!tree.keys().any(|k| k.contains("sync-conflict")),
|
||||
"{tree:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
tree.keys().filter(|k| k.contains("new")).count(),
|
||||
1,
|
||||
"{tree:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(local.join("new.txt")).unwrap(),
|
||||
b"second, written while stopped"
|
||||
);
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
assert!(
|
||||
reopen(&dir).sync_intents(Some(folder)).unwrap().is_empty(),
|
||||
"every intent settled"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_revision_made_during_a_mirror_download_still_arrives() {
|
||||
@@ -2868,6 +3357,67 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_listing_taken_while_a_withdrawn_create_lands_does_not_keep_it() {
|
||||
// A file deleted while its create was on the wire. Drive made the node
|
||||
// and listed it before the drain had its answer, and a refresh then put
|
||||
// it in the tree. The drain hid it and trashed it, but the entry stayed:
|
||||
// a new file made under the name opened the trashed node, and every
|
||||
// write and rename of it was refused with EACCES (B303).
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("withdrawn-create-listed");
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
|
||||
let mnt = daemon.mountpoint.clone();
|
||||
let file = |bytes: &[u8]| Some(Entry::File(Arc::new(bytes.to_vec())));
|
||||
|
||||
let held = daemon.client.hold_reply_to_next_create();
|
||||
daemon.write_new(&mnt.join("d"), b"first").unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || held.reached()));
|
||||
std::fs::remove_file(mnt.join("d")).unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
drive.tree().get("d").cloned() == file(b"first")
|
||||
}));
|
||||
// Past the listing lag, so the refresh finds the node Drive made.
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
let refresh = Request::Refresh {
|
||||
scope: RefreshScope::Dir {
|
||||
path: mnt.to_string_lossy().into_owned(),
|
||||
},
|
||||
};
|
||||
assert!(matches!(daemon.request(&refresh), Ok(Response::Ok { .. })));
|
||||
let _ = std::fs::read_dir(&mnt).unwrap().count();
|
||||
drop(held);
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(30), || {
|
||||
daemon.pending().is_ok_and(|items| items.is_empty())
|
||||
&& !drive.tree().contains_key("d")
|
||||
}),
|
||||
"{:?} {:?}",
|
||||
daemon.pending(),
|
||||
drive.tree()
|
||||
);
|
||||
assert!(
|
||||
!mnt.join("d").exists(),
|
||||
"the trashed create is still listed"
|
||||
);
|
||||
|
||||
std::fs::write(mnt.join("d"), b"second").unwrap();
|
||||
std::fs::rename(mnt.join("d"), mnt.join("c.bin")).unwrap();
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(30), || {
|
||||
daemon.pending().is_ok_and(|items| items.is_empty())
|
||||
&& drive.tree().get("c.bin").cloned() == file(b"second")
|
||||
}),
|
||||
"{:?} {:?}",
|
||||
daemon.pending(),
|
||||
drive.tree()
|
||||
);
|
||||
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_file_made_under_the_name_of_a_create_on_the_wire_waits_for_it() {
|
||||
@@ -4020,6 +4570,57 @@ mod tests {
|
||||
id
|
||||
}
|
||||
|
||||
/// Stop syncing with "Also delete from Proton Drive" on, while Drive cannot
|
||||
/// be reached. The folder stops syncing, but its copy in Proton Drive
|
||||
/// stays. The reply was a plain success, so the app said "Stopped syncing
|
||||
/// folder" and nothing told the user the cloud copy was still there.
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn stopping_sync_says_so_when_its_drive_folder_could_not_be_deleted() {
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("stop-sync-delete-offline");
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
|
||||
let local = dir.join("docs");
|
||||
let id = sync_folder(&daemon, &local, "mirror");
|
||||
std::fs::write(local.join("keep.txt"), b"keep").unwrap();
|
||||
daemon.request(&Request::SyncNow { id: Some(id) }).unwrap();
|
||||
let on_drive = || {
|
||||
drive.tree().iter().any(|(path, entry)| {
|
||||
path.ends_with("docs/keep.txt") && *entry == Entry::File(Arc::new(b"keep".to_vec()))
|
||||
})
|
||||
};
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(30), || on_drive()
|
||||
&& listed_folder(&daemon, id).is_some_and(|f| f.state == "idle")),
|
||||
"the folder synced: {:?}",
|
||||
listed_folder(&daemon, id)
|
||||
);
|
||||
|
||||
daemon.client.set_online(false);
|
||||
let error = daemon
|
||||
.request(&Request::RemoveSyncFolder {
|
||||
id,
|
||||
delete_remote: true,
|
||||
})
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
daemon.client.set_online(true);
|
||||
|
||||
assert!(
|
||||
error.contains("stopped syncing the folder")
|
||||
&& error.contains("was not moved to the trash"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(
|
||||
listed_folder(&daemon, id).is_none(),
|
||||
"the folder still syncs"
|
||||
);
|
||||
assert!(on_drive(), "the copy in Proton Drive is gone after all");
|
||||
assert_eq!(std::fs::read(local.join("keep.txt")).unwrap(), b"keep");
|
||||
daemon.stop().unwrap();
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_move_out_of_an_on_demand_folder_refuses_a_file_still_open_for_writing() {
|
||||
@@ -4550,4 +5151,118 @@ mod tests {
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The state a stop leaves between the two steps of a replacing rename
|
||||
/// sent to Drive inline: the replaced file in the trash, the source under
|
||||
/// its old name, and the journal entry. The next start puts the replaced
|
||||
/// file back (B302).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_replace_cut_off_after_its_trash_brings_the_replaced_file_back() {
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("replace-cut-trash");
|
||||
// Only this test's daemons in the log a failure prints.
|
||||
take_logged();
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
|
||||
std::fs::write(daemon.mountpoint.join("report.odt"), b"old").unwrap();
|
||||
std::fs::write(daemon.mountpoint.join("report.odt.tmp"), b"new").unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
let tree = drive.tree();
|
||||
tree.contains_key("report.odt") && tree.contains_key("report.odt.tmp")
|
||||
}));
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
|
||||
let victim = drive.lookup("report.odt").unwrap();
|
||||
let source = drive.lookup("report.odt.tmp").unwrap();
|
||||
cut_off_replace(&dir, &source, &victim, &drive.root(), "report.odt");
|
||||
drive.device().trash("report.odt");
|
||||
|
||||
// Without the listing lag: a lagging read shows the trash made just
|
||||
// above as not done yet, and a restart quicker than the lag then left
|
||||
// the file in the trash as never removed. A real stop comes long
|
||||
// after its own trash.
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::none())).unwrap();
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(30), || {
|
||||
drive.tree().get("report.odt") == Some(&Entry::File(Arc::new(b"old".to_vec())))
|
||||
}),
|
||||
"the replaced file came back: {:?}\n{}",
|
||||
drive.tree(),
|
||||
take_logged().join("\n")
|
||||
);
|
||||
assert!(drive.tree().contains_key("report.odt.tmp"));
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
std::fs::read(daemon.mountpoint.join("report.odt")).is_ok_and(|b| b == b"old")
|
||||
}));
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let db = Db::open(&dir.join("pdfs.db")).unwrap();
|
||||
assert!(db.open_replaces().unwrap().is_empty());
|
||||
drop(db);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The state a stop leaves between the two steps of a queued replacing
|
||||
/// rename: the replaced file's trash queued, the rename not. The next
|
||||
/// start drops the queued trash, so the file is never trashed (B302).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_replace_cut_off_after_queueing_its_trash_keeps_the_replaced_file() {
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("replace-cut-queue");
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
|
||||
std::fs::write(daemon.mountpoint.join("report.odt"), b"old").unwrap();
|
||||
std::fs::write(daemon.mountpoint.join("report.odt.tmp"), b"new").unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
let tree = drive.tree();
|
||||
tree.contains_key("report.odt") && tree.contains_key("report.odt.tmp")
|
||||
}));
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
|
||||
let victim = drive.lookup("report.odt").unwrap();
|
||||
let source = drive.lookup("report.odt.tmp").unwrap();
|
||||
cut_off_replace(&dir, &source, &victim, &drive.root(), "report.odt");
|
||||
let db = Db::open(&dir.join("pdfs.db")).unwrap();
|
||||
db.replace_ops_with_trash(&victim.to_string(), "report.odt", 1)
|
||||
.unwrap();
|
||||
drop(db);
|
||||
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
std::fs::read(daemon.mountpoint.join("report.odt")).is_ok_and(|b| b == b"old")
|
||||
}));
|
||||
// Long enough for the drain to have sent a trash it still held.
|
||||
std::thread::sleep(Duration::from_secs(3));
|
||||
assert!(
|
||||
drive.tree().contains_key("report.odt"),
|
||||
"the replaced file stayed: {:?}",
|
||||
drive.tree()
|
||||
);
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let db = Db::open(&dir.join("pdfs.db")).unwrap();
|
||||
assert!(db.open_replaces().unwrap().is_empty());
|
||||
assert!(!db.has_pending_op(&victim.to_string(), "trash").unwrap());
|
||||
drop(db);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Write the journal entry of a replacing rename, as an earlier run would
|
||||
/// have before it removed the victim.
|
||||
fn cut_off_replace(
|
||||
dir: &Path,
|
||||
source: &NodeUid,
|
||||
victim: &NodeUid,
|
||||
parent: &NodeUid,
|
||||
name: &str,
|
||||
) {
|
||||
let db = Db::open(&dir.join("pdfs.db")).unwrap();
|
||||
db.begin_replace(&pdfs_store::db::ReplaceIntent {
|
||||
source_uid: source.to_string(),
|
||||
victim_uid: victim.to_string(),
|
||||
new_parent_uid: parent.to_string(),
|
||||
new_name: name.to_owned(),
|
||||
started_ms: 1,
|
||||
run: 0,
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The simulation tests of `docs/TESTING.md`: a fake Drive with
|
||||
//! the faults the real one has, and the tools to drive daemons against it.
|
||||
|
||||
pub(crate) mod conformance;
|
||||
pub(crate) mod daemon;
|
||||
pub(crate) use pdfs_drive::sim::fake_drive;
|
||||
pub(crate) mod model;
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -159,9 +165,9 @@ impl Core {
|
||||
return;
|
||||
}
|
||||
let queue = self.sizes.size_waiters.clone();
|
||||
if let Err(error) = std::thread::Builder::new()
|
||||
.name("pdfs-size-waiters".into())
|
||||
.spawn(move || queue.serve())
|
||||
if let Err(error) = self
|
||||
.services
|
||||
.spawn_job("pdfs-size-waiters", move || queue.serve())
|
||||
{
|
||||
// Without a thread nothing would ever answer these. A provisional
|
||||
// size is wrong; a `stat` that never returns wedges the caller.
|
||||
@@ -184,6 +190,11 @@ impl Core {
|
||||
let (mut key, mut uids, mut slot) = (key, uids, slot);
|
||||
loop {
|
||||
for chunk in uids.chunks(SIZE_UPGRADE_CHUNK) {
|
||||
// A stop joins this job; the rest of the folder can wait for
|
||||
// the next mount, which lists it afresh.
|
||||
if self.shutdown.is_stopping() {
|
||||
break;
|
||||
}
|
||||
let result =
|
||||
self.block_on_within(BATCH_CALL_TIMEOUT, self.drive.enumerate_nodes(chunk));
|
||||
self.apply_size_upgrade(key, result);
|
||||
@@ -321,7 +332,7 @@ impl Core {
|
||||
};
|
||||
changed.push(ino);
|
||||
// An open write handle is ahead of the server too (B109).
|
||||
if st.active_writes.contains_key(&ino) {
|
||||
if st.open.is_writing(ino) {
|
||||
continue;
|
||||
}
|
||||
let NodeKind::File { claimed_size, .. } = &node.kind else {
|
||||
|
||||
+117
-43
@@ -30,6 +30,10 @@ use pdfs_core::control::ActivityKind;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_drive::DriveApi;
|
||||
use pdfs_store::db::Db;
|
||||
|
||||
use super::{Core, node_content_sha1, node_revision_id, node_size};
|
||||
|
||||
/// What the conflict sweep may do, and the copies it already checked this
|
||||
@@ -44,7 +48,7 @@ pub(crate) struct SweepState {
|
||||
/// Conflict copies the sweep has already checked against the activity log
|
||||
/// this run, so each pass does not ask the database again. The log itself
|
||||
/// is what keeps a copy from being flagged again after a restart. See
|
||||
/// [`Core::run_conflict_sweep_loop`] and `docs/BUGS.md` B99.
|
||||
/// [`Sweeper::run`] and `docs/BUGS.md` B99.
|
||||
pub(crate) conflict_notified: Arc<Mutex<HashSet<NodeUid>>>,
|
||||
}
|
||||
|
||||
@@ -107,17 +111,113 @@ pub(crate) fn conflict_base_name(name: &str) -> Option<String> {
|
||||
Some(base)
|
||||
}
|
||||
|
||||
/// What the conflict sweep needs from the rest of the daemon: the tree of
|
||||
/// every mount and the activity feed.
|
||||
pub(crate) trait SweepHost: Send + Sync {
|
||||
/// Whether `uid` is on this account's own volume, or a virtual node.
|
||||
fn is_own_or_virtual(&self, uid: &NodeUid) -> bool;
|
||||
/// Whether the mount believes Drive is reachable.
|
||||
fn is_online(&self) -> bool;
|
||||
/// Whether a node is being written or held open in any mount.
|
||||
fn is_busy(&self, uid: &NodeUid) -> bool;
|
||||
/// For one pass: whether the conflict listing can show a copy.
|
||||
fn conflict_locator(&self) -> Box<dyn Fn(&NodeUid) -> bool + '_>;
|
||||
/// Unhook a node Drive no longer has from every mount, and drop its
|
||||
/// cached content and open readers.
|
||||
fn forget(&self, uid: &NodeUid);
|
||||
fn log_activity(&self, kind: ActivityKind, target: &str, detail: String, ok: bool);
|
||||
}
|
||||
|
||||
impl SweepHost for Core {
|
||||
fn is_own_or_virtual(&self, uid: &NodeUid) -> bool {
|
||||
Core::is_own_or_virtual(self, uid)
|
||||
}
|
||||
|
||||
fn is_online(&self) -> bool {
|
||||
Core::is_online(self)
|
||||
}
|
||||
|
||||
fn is_busy(&self, uid: &NodeUid) -> bool {
|
||||
Core::is_busy(self, uid)
|
||||
}
|
||||
|
||||
fn conflict_locator(&self) -> Box<dyn Fn(&NodeUid) -> bool + '_> {
|
||||
let roots = Core::search_roots(self);
|
||||
Box::new(move |uid| self.conflict_path(&roots, uid).is_some())
|
||||
}
|
||||
|
||||
fn forget(&self, uid: &NodeUid) {
|
||||
// Leaving a conflict copy hooked up in the tree keeps a node we have
|
||||
// just trashed remotely visible and readable in whichever mount shows
|
||||
// it (`docs/BUGS.md` B74).
|
||||
self.for_each_state(|st| {
|
||||
st.forget_or_unlink(uid);
|
||||
});
|
||||
self.cache.evict(uid);
|
||||
self.evict_reader(uid);
|
||||
}
|
||||
|
||||
fn log_activity(&self, kind: ActivityKind, target: &str, detail: String, ok: bool) {
|
||||
Core::log_activity(self, kind, target, detail, ok);
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// The conflict sweep, with this daemon as its host.
|
||||
pub(crate) fn sweeper(&self) -> Sweeper {
|
||||
Sweeper {
|
||||
drive: self.drive.clone(),
|
||||
rt: self.rt.clone(),
|
||||
db: self.db.clone(),
|
||||
shutdown: self.shutdown.clone(),
|
||||
state: self.sweep.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a node has a write in flight or a file handle open against it.
|
||||
/// Read-only opens use fh 0 and are not tracked, so this is specifically the
|
||||
/// writer/holder check.
|
||||
/// Asked across **every** mount. The sweep runs on the primary Core but
|
||||
/// trashes nodes anywhere in the tree, and a file open inside a sync folder
|
||||
/// is tracked in that fork's `State` — so consulting `self.state` alone
|
||||
/// answered "idle" for every such file and let the sweep delete one with a
|
||||
/// writer attached (`docs/BUGS.md` B74). Busy anywhere means busy.
|
||||
pub(crate) fn is_busy(&self, uid: &NodeUid) -> bool {
|
||||
let mut busy = false;
|
||||
self.for_each_state(|st| {
|
||||
let Some(&ino) = st.by_uid.get(uid) else {
|
||||
return;
|
||||
};
|
||||
busy |= st.open.is_busy(ino);
|
||||
});
|
||||
busy
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconciles leftover conflict copies (the module documentation says how).
|
||||
/// Holds Drive, the runtime, the database, the stop signal and its own state;
|
||||
/// it reaches the mounts through [`SweepHost`].
|
||||
pub(crate) struct Sweeper {
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
db: Arc<Db>,
|
||||
shutdown: Arc<Shutdown>,
|
||||
state: SweepState,
|
||||
host: Arc<dyn SweepHost>,
|
||||
}
|
||||
|
||||
impl Sweeper {
|
||||
/// Sweep for stale conflict copies forever, on its own thread. See the module
|
||||
/// docs for the identical/divergent policy.
|
||||
pub(crate) fn run_conflict_sweep_loop(&self) {
|
||||
pub(crate) fn run(&self) {
|
||||
// Both waits are interruptible, so teardown does not have to sit out a
|
||||
// five-minute interval to join this thread (`docs/BUGS.md` B44).
|
||||
if !self.shutdown.sleep(CONFLICT_SWEEP_WARMUP) {
|
||||
return;
|
||||
}
|
||||
loop {
|
||||
self.sweep_conflicts_once();
|
||||
self.sweep_once();
|
||||
if !self.shutdown.sleep(CONFLICT_SWEEP_INTERVAL) {
|
||||
return;
|
||||
}
|
||||
@@ -125,7 +225,7 @@ impl Core {
|
||||
}
|
||||
|
||||
/// One sweep pass over every node the daemon currently knows.
|
||||
fn sweep_conflicts_once(&self) {
|
||||
fn sweep_once(&self) {
|
||||
let stored = match self.db.load_all() {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
@@ -136,7 +236,7 @@ impl Core {
|
||||
let nodes: Vec<_> = stored
|
||||
.into_iter()
|
||||
.map(|stored| stored.node)
|
||||
.filter(|node| self.is_own_or_virtual(&node.uid))
|
||||
.filter(|node| self.host.is_own_or_virtual(&node.uid))
|
||||
.collect();
|
||||
|
||||
// Index live (non-trashed) files by (parent, name) for sibling lookup.
|
||||
@@ -153,8 +253,8 @@ impl Core {
|
||||
by_parent_name.insert((parent, node.name.as_str()), node);
|
||||
}
|
||||
|
||||
let roots = self.search_roots();
|
||||
let online = self.online.load(std::sync::atomic::Ordering::Relaxed);
|
||||
let listed = self.host.conflict_locator();
|
||||
let online = self.host.is_online();
|
||||
for node in &nodes {
|
||||
if node.trashed || node.is_folder() {
|
||||
continue;
|
||||
@@ -169,7 +269,7 @@ impl Core {
|
||||
.unwrap_or_default();
|
||||
let sibling = by_parent_name.get(&(parent, base.as_str())).copied();
|
||||
|
||||
match decide(node, sibling, &base, self.sweep.sweep_mode) {
|
||||
match decide(node, sibling, &base, self.state.sweep_mode) {
|
||||
SweepAction::Remove => {
|
||||
// Only while online — the remote trash is the point. Offline,
|
||||
// it waits for a later pass.
|
||||
@@ -181,7 +281,7 @@ impl Core {
|
||||
// would sit in the feed as "resolved" with no way to act on
|
||||
// it (`docs/BUGS.md` B99).
|
||||
SweepAction::Flag(detail) => {
|
||||
if self.conflict_path(&roots, &node.uid).is_some() {
|
||||
if listed(&node.uid) {
|
||||
self.flag_conflict(&node.uid, &node.name, detail);
|
||||
} else {
|
||||
debug!(uid = %node.uid, name = %node.name, "conflict sweep: copy is outside every location; not flagged");
|
||||
@@ -219,12 +319,7 @@ impl Core {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Leaving a conflict copy hooked up in the tree keeps a node we have
|
||||
// just trashed remotely visible and readable in whichever mount shows
|
||||
// it (`docs/BUGS.md` B74).
|
||||
self.for_each_state(|st| {
|
||||
st.forget_or_unlink(uid);
|
||||
});
|
||||
self.host.forget(uid);
|
||||
// Deliberately *not* `discard_queued_ops`: `duplicate_still_removable`
|
||||
// proved the queue empty before the trash above, but that proof is stale
|
||||
// the moment `trash_nodes` goes to the network. A `close(2)` landing in
|
||||
@@ -232,14 +327,12 @@ impl Core {
|
||||
// blob holding the only copy of them. Leaving the op queued is the
|
||||
// non-destructive outcome: the drain re-reads the node, sees it trashed,
|
||||
// and `revision_conflict` routes it to `keep_as_conflict_copy`.
|
||||
self.cache.evict(uid);
|
||||
self.evict_reader(uid);
|
||||
if let Err(e) = self.db.delete_node(uid) {
|
||||
warn!(%uid, error = ?e, "conflict sweep: db delete after trash failed");
|
||||
}
|
||||
self.invalidate_trash();
|
||||
self.sweep.conflict_notified.lock().remove(uid);
|
||||
self.log_activity(
|
||||
super::trash::invalidate_trash(&self.db);
|
||||
self.state.conflict_notified.lock().remove(uid);
|
||||
self.host.log_activity(
|
||||
ActivityKind::Trash,
|
||||
name,
|
||||
format!("auto-removed duplicate of {base}"),
|
||||
@@ -273,7 +366,7 @@ impl Core {
|
||||
|
||||
// Someone is writing to it, or holds it open. Trashing now would pull the
|
||||
// node out from under a live handle.
|
||||
if self.is_busy(uid) {
|
||||
if self.host.is_busy(uid) {
|
||||
debug!(%uid, name, "conflict sweep: skipping duplicate that is open or being written");
|
||||
return false;
|
||||
}
|
||||
@@ -306,32 +399,12 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a node has a write in flight or a file handle open against it.
|
||||
/// Read-only opens use fh 0 and are not tracked, so this is specifically the
|
||||
/// writer/holder check.
|
||||
/// Asked across **every** mount. The sweep runs on the primary Core but
|
||||
/// trashes nodes anywhere in the tree, and a file open inside a sync folder
|
||||
/// is tracked in that fork's `State` — so consulting `self.state` alone
|
||||
/// answered "idle" for every such file and let the sweep delete one with a
|
||||
/// writer attached (`docs/BUGS.md` B74). Busy anywhere means busy.
|
||||
pub(crate) fn is_busy(&self, uid: &NodeUid) -> bool {
|
||||
let mut busy = false;
|
||||
self.for_each_state(|st| {
|
||||
let Some(&ino) = st.by_uid.get(uid) else {
|
||||
return;
|
||||
};
|
||||
busy |=
|
||||
st.active_writes.contains_key(&ino) || st.handles.values().any(|&held| held == ino);
|
||||
});
|
||||
busy
|
||||
}
|
||||
|
||||
/// Surface a conflict copy that needs the user's attention, once. The
|
||||
/// in-memory set spares the database each pass; the activity log itself is
|
||||
/// what keeps a restart from logging the same copy again (`docs/BUGS.md`
|
||||
/// B99). A copy's name carries its own timestamp, so the name identifies it.
|
||||
fn flag_conflict(&self, uid: &NodeUid, name: &str, detail: String) {
|
||||
if !self.sweep.conflict_notified.lock().insert(uid.clone()) {
|
||||
if !self.state.conflict_notified.lock().insert(uid.clone()) {
|
||||
return;
|
||||
}
|
||||
match self.db.activity_has(ActivityKind::Conflict, name) {
|
||||
@@ -342,7 +415,8 @@ impl Core {
|
||||
Err(e) => warn!(%uid, name, error = ?e, "conflict sweep: activity check failed"),
|
||||
}
|
||||
debug!(%uid, name, detail, "conflict sweep: flagged divergent conflict copy");
|
||||
self.log_activity(ActivityKind::Conflict, name, detail, false);
|
||||
self.host
|
||||
.log_activity(ActivityKind::Conflict, name, detail, false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ impl SyncHost for Core {
|
||||
}
|
||||
|
||||
fn upload_thumbnails(&self, path: &Path, name: &str) -> Vec<Thumbnail> {
|
||||
Core::upload_thumbnails(self, path, name)
|
||||
self.photos().upload_thumbnails(path, name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+114
-44
@@ -2,6 +2,7 @@
|
||||
//! listing in the background, restoring from it, deleting from it for good.
|
||||
|
||||
use super::*;
|
||||
use crate::listing::listing_stale;
|
||||
|
||||
/// Whether a trash refresh is running, and the wake-up for requests waiting
|
||||
/// on its progress.
|
||||
@@ -13,7 +14,7 @@ pub(crate) struct TrashState {
|
||||
/// Fires whenever a trash refresh persists a batch or finishes, so a
|
||||
/// `ListTrash` request waiting on a first-ever refresh wakes on progress
|
||||
/// instead of polling or blocking for the whole run. See
|
||||
/// [`Core::await_trash_refresh`].
|
||||
/// [`Trash::await_trash_refresh`].
|
||||
pub(crate) trash_progress: Arc<tokio::sync::Notify>,
|
||||
}
|
||||
|
||||
@@ -26,7 +27,75 @@ impl TrashState {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Drive trash as a service: listing it, refreshing that listing, and
|
||||
/// restoring or deleting from it.
|
||||
///
|
||||
/// It holds only the handles it calls, and reaches the mounted trees through
|
||||
/// [`TrashHost`]. [`Core::trash`] builds one on demand with the daemon as its
|
||||
/// host. A clone shares everything, which is how a refresh moves onto a
|
||||
/// background task.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Trash {
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
db: Arc<Db>,
|
||||
events: Arc<events::EventHub>,
|
||||
services: pdfs_core::lifecycle::ServiceBoard,
|
||||
writes: writes::WriteState,
|
||||
jobs: TrashState,
|
||||
host: Arc<dyn TrashHost>,
|
||||
}
|
||||
|
||||
/// What the trash needs from the mounted trees.
|
||||
pub(crate) trait TrashHost: Send + Sync {
|
||||
/// Re-enumerate these folders on next access, in every mount, because a
|
||||
/// restored node reappears under one of them.
|
||||
fn invalidate_listings_of(&self, parents: &[NodeUid]);
|
||||
/// Forget nodes the server no longer has, in every mount, with any cached
|
||||
/// content they own.
|
||||
fn drop_local(&self, uids: &[NodeUid]);
|
||||
}
|
||||
|
||||
impl TrashHost for Core {
|
||||
fn invalidate_listings_of(&self, parents: &[NodeUid]) {
|
||||
// Keyed by uid, so it applies to every mount: a restored node reappears
|
||||
// in whichever mounts show its parent, not only the primary one.
|
||||
self.for_each_state(|st| {
|
||||
for parent in parents {
|
||||
if let Some(&ino) = st.by_uid.get(parent) {
|
||||
st.invalidate_listing(ino);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn drop_local(&self, uids: &[NodeUid]) {
|
||||
Core::drop_local(self, uids);
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// [`Trash::invalidate_trash`], without building the service.
|
||||
pub(super) fn invalidate_trash(&self) {
|
||||
invalidate_trash(&self.db);
|
||||
}
|
||||
|
||||
/// The trash service, with this daemon as its host.
|
||||
pub(crate) fn trash(&self) -> Trash {
|
||||
Trash {
|
||||
drive: self.drive.clone(),
|
||||
rt: self.rt.clone(),
|
||||
db: self.db.clone(),
|
||||
events: self.events.clone(),
|
||||
services: self.services.clone(),
|
||||
writes: self.writes.clone(),
|
||||
jobs: self.trash_jobs.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Trash {
|
||||
/// List the account's trash, from the DB. Trashed nodes are outside the
|
||||
/// mounted tree — the FUSE side forgot them when they were trashed — so the
|
||||
/// listing is persisted in its own table rather than derived from `State`, and
|
||||
@@ -36,7 +105,7 @@ impl Core {
|
||||
/// Stale-while-revalidate, like the photos timeline: a persisted listing comes
|
||||
/// back at DB speed and is refreshed in the background past [`TRASH_TTL`].
|
||||
/// Our own trash mutations invalidate it outright (see
|
||||
/// [`Core::invalidate_trash`]), so the TTL only covers changes made elsewhere.
|
||||
/// [`Trash::invalidate_trash`]), so the TTL only covers changes made elsewhere.
|
||||
///
|
||||
/// The refresh always runs *off* the request: a never-fetched trash waits for
|
||||
/// it, but only for [`TRASH_FIRST_WAIT`], and then answers with the batches
|
||||
@@ -44,9 +113,9 @@ impl Core {
|
||||
/// made a large trash unlistable — the refresh outran the front-end's read
|
||||
/// timeout, the user asked again, and each attempt left another full refresh
|
||||
/// grinding in the daemon (`docs/BUGS.md` B72).
|
||||
pub(super) fn list_trash(&self) -> CoreResult<Vec<DirEntry>> {
|
||||
pub(crate) fn list_trash(&self) -> CoreResult<Vec<DirEntry>> {
|
||||
let never_fetched = self.db.state_i64(TRASH_SYNCED_MS).ok().flatten().is_none();
|
||||
if never_fetched || self.listing_stale(TRASH_SYNCED_MS, TRASH_TTL) {
|
||||
if never_fetched || listing_stale(&self.db, TRASH_SYNCED_MS, TRASH_TTL) {
|
||||
self.spawn_trash_refresh();
|
||||
}
|
||||
if never_fetched {
|
||||
@@ -99,7 +168,7 @@ impl Core {
|
||||
|
||||
/// What a trashed folder holds: its children on the server, and the
|
||||
/// stored trash entries trashed inside it before it went.
|
||||
pub(super) fn list_trashed_folder(&self, uid: &str) -> CoreResult<Vec<DirEntry>> {
|
||||
pub(crate) fn list_trashed_folder(&self, uid: &str) -> CoreResult<Vec<DirEntry>> {
|
||||
let folder =
|
||||
parse_uid(uid).ok_or_else(|| CoreError::invalid(format!("invalid uid: {uid}")))?;
|
||||
let children = self
|
||||
@@ -177,7 +246,7 @@ impl Core {
|
||||
/// [`TRASH_MATERIALIZE_CHUNK`] is stored as it lands, so a large trash
|
||||
/// fills the page while it loads. Rows the server no longer lists go once
|
||||
/// the whole listing is in, never earlier.
|
||||
pub(super) async fn refresh_trash(&self) -> CoreResult<()> {
|
||||
pub(crate) async fn refresh_trash(&self) -> CoreResult<()> {
|
||||
let started = Instant::now();
|
||||
let uids = within_trash_call("enumerate trash", self.drive.enumerate_trash_node_uids())
|
||||
.await?
|
||||
@@ -200,7 +269,7 @@ impl Core {
|
||||
let listed: HashSet<String> = uids.iter().map(ToString::to_string).collect();
|
||||
let removed = self.db.trash_retain(&listed).map_err(CoreError::from)?;
|
||||
if removed > 0 {
|
||||
self.trash.trash_progress.notify_waiters();
|
||||
self.jobs.trash_progress.notify_waiters();
|
||||
}
|
||||
let missing: Vec<NodeUid> = uids
|
||||
.into_iter()
|
||||
@@ -235,7 +304,7 @@ impl Core {
|
||||
.collect();
|
||||
materialized += items.len();
|
||||
self.db.trash_upsert(&items).map_err(CoreError::from)?;
|
||||
self.trash.trash_progress.notify_waiters();
|
||||
self.jobs.trash_progress.notify_waiters();
|
||||
self.events.publish(&[Topic::Trash]);
|
||||
debug!(
|
||||
materialized,
|
||||
@@ -258,43 +327,44 @@ impl Core {
|
||||
}
|
||||
|
||||
/// Refresh the trash off the request path. At most one refresh at a time —
|
||||
/// including the one a first-ever [`Core::list_trash`] waits on, so a burst
|
||||
/// including the one a first-ever [`Trash::list_trash`] waits on, so a burst
|
||||
/// of requests against an unfetched trash joins one refresh instead of
|
||||
/// starting one apiece.
|
||||
pub(super) fn spawn_trash_refresh(&self) {
|
||||
if self.trash.trash_refreshing.swap(true, Ordering::SeqCst) {
|
||||
pub(crate) fn spawn_trash_refresh(&self) {
|
||||
if self.jobs.trash_refreshing.swap(true, Ordering::SeqCst) {
|
||||
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();
|
||||
});
|
||||
let this = self.clone();
|
||||
self.services
|
||||
.spawn_task_job(&self.rt, "pdfs-trash-refresh", async move {
|
||||
let refreshed = this.refresh_trash().await;
|
||||
this.jobs.trash_refreshing.store(false, Ordering::SeqCst);
|
||||
match refreshed {
|
||||
Ok(_) => this.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.
|
||||
this.jobs.trash_progress.notify_waiters();
|
||||
});
|
||||
}
|
||||
|
||||
/// Wait for the in-flight trash refresh to make progress, for at most
|
||||
/// `budget`. Returns early when it finishes; never cancels it — the refresh
|
||||
/// is a detached task, so giving up here costs the work nothing.
|
||||
pub(super) fn await_trash_refresh(&self, budget: Duration) {
|
||||
pub(crate) fn await_trash_refresh(&self, budget: Duration) {
|
||||
let deadline = Instant::now() + budget;
|
||||
self.rt.block_on(async {
|
||||
while self.trash.trash_refreshing.load(Ordering::SeqCst) {
|
||||
while self.jobs.trash_refreshing.load(Ordering::SeqCst) {
|
||||
let Some(left) = deadline.checked_duration_since(Instant::now()) else {
|
||||
break;
|
||||
};
|
||||
let notified = self.trash.trash_progress.notified();
|
||||
let notified = self.jobs.trash_progress.notified();
|
||||
tokio::pin!(notified);
|
||||
// Register before re-checking the flag: a refresh that finishes
|
||||
// in between must not leave us waiting for a notify that has
|
||||
// already fired.
|
||||
notified.as_mut().enable();
|
||||
if !self.trash.trash_refreshing.load(Ordering::SeqCst) {
|
||||
if !self.jobs.trash_refreshing.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
if tokio::time::timeout(left, notified).await.is_err() {
|
||||
@@ -312,8 +382,8 @@ impl Core {
|
||||
/// trash ourselves. The next Trash page then *waits* for a fresh listing
|
||||
/// rather than painting one from before the mutation — the user just made the
|
||||
/// change and is about to look straight at it.
|
||||
pub(super) fn invalidate_trash(&self) {
|
||||
let _ = self.db.clear_state(TRASH_SYNCED_MS);
|
||||
pub(crate) fn invalidate_trash(&self) {
|
||||
invalidate_trash(&self.db);
|
||||
}
|
||||
|
||||
/// Restore trashed nodes to the folders they were trashed from, together
|
||||
@@ -334,8 +404,8 @@ impl Core {
|
||||
/// The destination parents are read *before* the restore — a restored node
|
||||
/// reappears in a listing the daemon may already have cached, so each one is
|
||||
/// invalidated and re-enumerated on next access.
|
||||
pub(super) fn restore(&self, uids: &[String]) -> CoreResult<usize> {
|
||||
let requested = Self::parse_uids(uids)?;
|
||||
pub(crate) fn restore(&self, uids: &[String]) -> CoreResult<usize> {
|
||||
let requested = Core::parse_uids(uids)?;
|
||||
// A listing we could not read is not a reason to refuse the restore: it
|
||||
// only costs the expansion, and the requested nodes still go back.
|
||||
let relations = self.db.trash_parents().unwrap_or_default();
|
||||
@@ -378,7 +448,7 @@ impl Core {
|
||||
let (uid, outcome) = item?;
|
||||
match outcome {
|
||||
Ok(()) => {
|
||||
self.hidden.lock().remove(&uid);
|
||||
self.writes.unhide(&uid);
|
||||
restored.push(uid);
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -398,13 +468,7 @@ impl Core {
|
||||
}
|
||||
// Keyed by uid, so it applies to every mount: a restored node reappears
|
||||
// in whichever mounts show its parent, not only the primary one.
|
||||
self.for_each_state(|st| {
|
||||
for parent in &parents {
|
||||
if let Some(&ino) = st.by_uid.get(parent) {
|
||||
st.invalidate_listing(ino);
|
||||
}
|
||||
}
|
||||
});
|
||||
self.host.invalidate_listings_of(&parents);
|
||||
let back: Vec<String> = restored.iter().map(ToString::to_string).collect();
|
||||
let _ = self.db.trash_remove(&back);
|
||||
self.invalidate_trash();
|
||||
@@ -413,8 +477,8 @@ impl Core {
|
||||
|
||||
/// Permanently delete trashed nodes. Irreversible on the server; locally it
|
||||
/// drops any metadata and cached content the node still owns.
|
||||
pub(super) fn delete_forever(&self, uids: &[String]) -> CoreResult<usize> {
|
||||
let parsed = Self::parse_uids(uids)?;
|
||||
pub(crate) fn delete_forever(&self, uids: &[String]) -> CoreResult<usize> {
|
||||
let parsed = Core::parse_uids(uids)?;
|
||||
// Streamed, and each node's local state is dropped as its batch lands.
|
||||
// A permanent delete is irreversible, so the useful property is that a
|
||||
// daemon interrupted mid-batch has already forgotten exactly the nodes
|
||||
@@ -429,7 +493,7 @@ impl Core {
|
||||
let (uid, outcome) = item?;
|
||||
match outcome {
|
||||
Ok(()) => {
|
||||
self.drop_local(std::slice::from_ref(&uid));
|
||||
self.host.drop_local(std::slice::from_ref(&uid));
|
||||
gone.push(uid.to_string());
|
||||
deleted += 1;
|
||||
}
|
||||
@@ -460,7 +524,7 @@ impl Core {
|
||||
/// is what kept the delete from ever being sent (`docs/BUGS.md` B293).
|
||||
/// The stored listing is cleared at once, and the server is asked again
|
||||
/// after [`TRASH_TTL`], so anything it still holds then shows up again.
|
||||
pub(super) fn empty_trash(&self) -> CoreResult<usize> {
|
||||
pub(crate) fn empty_trash(&self) -> CoreResult<usize> {
|
||||
let uids: Vec<String> = self
|
||||
.db
|
||||
.trash_seen()
|
||||
@@ -471,7 +535,7 @@ impl Core {
|
||||
.block_on(within_trash_call("empty trash", self.drive.empty_trash()))?
|
||||
.map_err(|e| CoreError::from_api(&e, "empty trash"))?;
|
||||
let parsed: Vec<NodeUid> = uids.iter().filter_map(|uid| parse_uid(uid)).collect();
|
||||
self.drop_local(&parsed);
|
||||
self.host.drop_local(&parsed);
|
||||
let _ = self.db.trash_replace(&[]);
|
||||
let _ = self.db.set_state_i64(TRASH_SYNCED_MS, now_ms());
|
||||
self.events.publish(&[Topic::Trash]);
|
||||
@@ -479,7 +543,7 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
/// An entry inside a trashed folder, for [`Core::list_trashed_folder`].
|
||||
/// An entry inside a trashed folder, for [`Trash::list_trashed_folder`].
|
||||
pub(super) fn trashed_entry(
|
||||
uid: String,
|
||||
name: String,
|
||||
@@ -618,3 +682,9 @@ pub(super) fn expand_restore(
|
||||
waves.retain(|wave| !wave.is_empty());
|
||||
waves
|
||||
}
|
||||
|
||||
/// Mark the stored trash listing stale, so the next listing waits for a
|
||||
/// fresh one.
|
||||
pub(crate) fn invalidate_trash(db: &Db) {
|
||||
let _ = db.clear_state(TRASH_SYNCED_MS);
|
||||
}
|
||||
@@ -70,6 +70,7 @@ async fn run_uploads(
|
||||
));
|
||||
}
|
||||
let thumbnails = core
|
||||
.photos()
|
||||
.upload_thumbnails_async(t.path.clone(), t.name.clone())
|
||||
.await;
|
||||
match core
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::time::{Duration, Instant};
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, NodeUid, VolumeId};
|
||||
use proton_drive_rs::{Node, NodeKind};
|
||||
|
||||
pub(crate) const VIRTUAL_VOLUME: &str = "virtual";
|
||||
pub(crate) use pdfs_vfs::ids::{VIRTUAL_VOLUME, is_virtual_uid};
|
||||
pub(crate) const SHARED_WITH_ME_LINK: &str = "sharedwithme";
|
||||
pub(crate) const SHARED_WITH_ME_BASE: &str = "Shared with me";
|
||||
const MAX_COMPONENT_BYTES: usize = 255;
|
||||
@@ -18,10 +18,6 @@ pub(crate) fn shared_with_me_uid() -> NodeUid {
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn is_virtual_uid(uid: &NodeUid) -> bool {
|
||||
uid.volume_id.as_str() == VIRTUAL_VOLUME
|
||||
}
|
||||
|
||||
pub(crate) fn is_own_or_virtual_uid(uid: &NodeUid, own_volume: &VolumeId) -> bool {
|
||||
uid.volume_id == *own_volume || is_virtual_uid(uid)
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ scale.browser-status-meter trough { min-width: 140px; min-height: 6px; }
|
||||
.dropzone-active { border-color: var(--accent-bg-color); background: color-mix(in srgb, var(--accent-bg-color) 10%, transparent); }
|
||||
.files-drop-active { outline: 2px dashed var(--accent-bg-color); outline-offset: -4px; border-radius: 12px; background: color-mix(in srgb, var(--accent-bg-color) 6%, transparent); }
|
||||
.files-drop-folder { border-radius: 8px; background: color-mix(in srgb, var(--accent-bg-color) 22%, transparent); box-shadow: inset 0 0 0 2px var(--accent-bg-color); }
|
||||
.files-drop-hint { padding: 8px 16px; border-radius: 9999px; background: var(--accent-bg-color); color: var(--accent-fg-color); font-weight: bold; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2); }
|
||||
.file-pending { opacity: 0.45; }
|
||||
|
||||
/* Photo viewer: always light-on-dark, whatever the system style */
|
||||
|
||||
@@ -500,6 +500,7 @@ fn build_window(app: &adw::Application) {
|
||||
restore: RefCell::new(None),
|
||||
crumb: browser_widgets.crumb.clone(),
|
||||
content: browser_widgets.content.clone(),
|
||||
drop_hint: browser_widgets.drop_hint.clone(),
|
||||
status: browser_widgets.status.clone(),
|
||||
retry: browser_widgets.retry.clone(),
|
||||
split: browser_widgets.split.clone(),
|
||||
@@ -548,6 +549,8 @@ fn build_window(app: &adw::Application) {
|
||||
subtitle: trash_widgets.subtitle.clone(),
|
||||
selection_bar: trash_widgets.selection_bar.clone(),
|
||||
selection_label: trash_widgets.selection_label.clone(),
|
||||
restore_selected: trash_widgets.restore_selected.clone(),
|
||||
delete_selected: trash_widgets.delete_selected.clone(),
|
||||
loader: Loader::new(&trash_widgets.content),
|
||||
back: trash_widgets.back.clone(),
|
||||
crumb: trash_widgets.crumb.clone(),
|
||||
|
||||
@@ -31,6 +31,9 @@ pub(crate) struct BrowserState {
|
||||
/// Swaps the Files content area between the grid/list views and the status
|
||||
/// page below; see [`browser_status`].
|
||||
pub(crate) content: gtk4::Stack,
|
||||
/// Floats over the views while something is dragged over them, saying
|
||||
/// what a drop there does; see [`show_drop_preview`].
|
||||
pub(crate) drop_hint: gtk4::Label,
|
||||
/// The Files empty/loading/error surface, shown in place of the views.
|
||||
pub(crate) status: adw::StatusPage,
|
||||
/// Sits in [`Self::status`]; shown when a load failed because the mount
|
||||
@@ -135,6 +138,7 @@ pub(crate) struct BrowserWidgets {
|
||||
pub(crate) crumb: gtk4::Box,
|
||||
/// Swaps the content area between the grid/list views and the status page.
|
||||
pub(crate) content: gtk4::Stack,
|
||||
pub(crate) drop_hint: gtk4::Label,
|
||||
/// The empty/loading/error surface shown in place of the views.
|
||||
pub(crate) status: adw::StatusPage,
|
||||
/// Sits in the status page; shown only when the mount service is down.
|
||||
@@ -344,6 +348,19 @@ pub(crate) fn build_browser_page() -> (gtk4::Widget, BrowserWidgets) {
|
||||
content.set_transition_type(gtk4::StackTransitionType::Crossfade);
|
||||
content.add_named(&view_stack, Some("views"));
|
||||
content.add_named(&status, Some("status"));
|
||||
// What a drop does, over the views while a drag is over them.
|
||||
let drop_hint = gtk4::Label::builder()
|
||||
.halign(gtk4::Align::Center)
|
||||
.valign(gtk4::Align::End)
|
||||
.margin_bottom(18)
|
||||
.justify(gtk4::Justification::Center)
|
||||
.wrap(true)
|
||||
.visible(false)
|
||||
.can_target(false)
|
||||
.build();
|
||||
drop_hint.add_css_class("files-drop-hint");
|
||||
let content_overlay = gtk4::Overlay::builder().child(&content).build();
|
||||
content_overlay.add_overlay(&drop_hint);
|
||||
|
||||
// The details pane slides in from the right while its header toggle is on.
|
||||
let (details_pane, details) = build_details_pane();
|
||||
@@ -356,7 +373,7 @@ pub(crate) fn build_browser_page() -> (gtk4::Widget, BrowserWidgets) {
|
||||
// itself; the header toggle alone decides.
|
||||
.pin_sidebar(true)
|
||||
.max_sidebar_width(300.0)
|
||||
.content(&content)
|
||||
.content(&content_overlay)
|
||||
.sidebar(&details_pane)
|
||||
.build();
|
||||
|
||||
@@ -492,6 +509,7 @@ pub(crate) fn build_browser_page() -> (gtk4::Widget, BrowserWidgets) {
|
||||
files,
|
||||
crumb,
|
||||
content,
|
||||
drop_hint,
|
||||
status,
|
||||
retry,
|
||||
search,
|
||||
@@ -1401,11 +1419,16 @@ pub(crate) fn wire_browser_actions(ui: &Rc<Ui>, build_thumbnails: >k4::Button)
|
||||
gtk4::gdk::FileList::static_type(),
|
||||
gtk4::gdk::DragAction::COPY | gtk4::gdk::DragAction::MOVE,
|
||||
);
|
||||
// Loaded on enter, so the hint can say what the drop does before it lands.
|
||||
drop.set_preload(true);
|
||||
let ui_enter = ui.clone();
|
||||
drop.connect_enter(move |_, _, _| {
|
||||
drop.connect_enter(move |target, _, _| {
|
||||
ui_enter.browser.content.add_css_class("files-drop-active");
|
||||
page_drop_preview(&ui_enter, target);
|
||||
browser_drop_action()
|
||||
});
|
||||
let ui_value = ui.clone();
|
||||
drop.connect_value_notify(move |target| page_drop_preview(&ui_value, target));
|
||||
drop.connect_motion(|_, _, _| browser_drop_action());
|
||||
let ui_leave = ui.clone();
|
||||
drop.connect_leave(move |_| {
|
||||
@@ -1413,6 +1436,7 @@ pub(crate) fn wire_browser_actions(ui: &Rc<Ui>, build_thumbnails: >k4::Button)
|
||||
.browser
|
||||
.content
|
||||
.remove_css_class("files-drop-active");
|
||||
ui_leave.browser.drop_hint.set_visible(false);
|
||||
});
|
||||
let ui_drop = ui.clone();
|
||||
drop.connect_drop(move |target, value, _, _| {
|
||||
@@ -1420,6 +1444,7 @@ pub(crate) fn wire_browser_actions(ui: &Rc<Ui>, build_thumbnails: >k4::Button)
|
||||
.browser
|
||||
.content
|
||||
.remove_css_class("files-drop-active");
|
||||
ui_drop.browser.drop_hint.set_visible(false);
|
||||
let Ok(files) = value.get::<gtk4::gdk::FileList>() else {
|
||||
return false;
|
||||
};
|
||||
@@ -3024,19 +3049,29 @@ pub(crate) fn attach_drop(ui: &Rc<Ui>, item: >k4::ListItem, anchor: >k4::Box
|
||||
.formats()
|
||||
.contains_type(gtk4::gdk::FileList::static_type())
|
||||
});
|
||||
let anchor_enter = anchor.clone();
|
||||
target.connect_enter(move |_, _, _| {
|
||||
target.set_preload(true);
|
||||
let (anchor_enter, ui_enter, item_enter) = (anchor.clone(), ui.clone(), item.clone());
|
||||
target.connect_enter(move |target, _, _| {
|
||||
anchor_enter.add_css_class("files-drop-folder");
|
||||
folder_drop_preview(&ui_enter, target, &item_enter);
|
||||
browser_drop_action()
|
||||
});
|
||||
let (ui_value, item_value) = (ui.clone(), item.clone());
|
||||
target.connect_value_notify(move |target| folder_drop_preview(&ui_value, target, &item_value));
|
||||
target.connect_motion(|_, _, _| browser_drop_action());
|
||||
let anchor_leave = anchor.clone();
|
||||
target.connect_leave(move |_| anchor_leave.remove_css_class("files-drop-folder"));
|
||||
let (anchor_leave, ui_leave) = (anchor.clone(), ui.clone());
|
||||
target.connect_leave(move |_| {
|
||||
anchor_leave.remove_css_class("files-drop-folder");
|
||||
// The page's own target takes over under the pointer; it repaints the
|
||||
// hint for the folder on screen as it is entered.
|
||||
ui_leave.browser.drop_hint.set_visible(false);
|
||||
});
|
||||
let ui = ui.clone();
|
||||
let item = item.clone();
|
||||
let anchor_drop = anchor.clone();
|
||||
target.connect_drop(move |target, value, _, _| {
|
||||
anchor_drop.remove_css_class("files-drop-folder");
|
||||
ui.browser.drop_hint.set_visible(false);
|
||||
let Some(obj) = item.item().and_downcast::<BoxedAnyObject>() else {
|
||||
return false;
|
||||
};
|
||||
@@ -3055,6 +3090,123 @@ pub(crate) fn attach_drop(ui: &Rc<Ui>, item: >k4::ListItem, anchor: >k4::Box
|
||||
anchor.add_controller(target);
|
||||
}
|
||||
|
||||
/// The page's drop hint, for the folder on screen.
|
||||
fn page_drop_preview(ui: &Rc<Ui>, target: >k4::DropTarget) {
|
||||
if !ui.browser.search.text().trim().is_empty() {
|
||||
// Search results have no one folder to drop into.
|
||||
ui.browser.drop_hint.set_visible(false);
|
||||
return;
|
||||
}
|
||||
let dest = ui.browser.path.borrow().clone();
|
||||
let name = match dest.rsplit('/').next().filter(|name| !name.is_empty()) {
|
||||
Some(name) => name.to_string(),
|
||||
None => gettext("My files"),
|
||||
};
|
||||
show_drop_preview(ui, target, &dest, &name);
|
||||
}
|
||||
|
||||
/// A folder cell's drop hint, for that folder.
|
||||
fn folder_drop_preview(ui: &Rc<Ui>, target: >k4::DropTarget, item: >k4::ListItem) {
|
||||
let Some(obj) = item.item().and_downcast::<BoxedAnyObject>() else {
|
||||
return;
|
||||
};
|
||||
let (dest, name) = {
|
||||
let entry = obj.borrow::<DirEntry>();
|
||||
(entry_rel(ui, &entry), entry.name.clone())
|
||||
};
|
||||
show_drop_preview(ui, target, &dest, &name);
|
||||
}
|
||||
|
||||
/// Say what dropping what `target` holds into `dest` would do, the way
|
||||
/// [`drop_files`] will do it. Nothing is shown until the files have loaded.
|
||||
fn show_drop_preview(ui: &Rc<Ui>, target: >k4::DropTarget, dest: &str, name: &str) {
|
||||
let hint = &ui.browser.drop_hint;
|
||||
let Some(files) = target
|
||||
.value()
|
||||
.and_then(|value| value.get::<gtk4::gdk::FileList>().ok())
|
||||
else {
|
||||
hint.set_visible(false);
|
||||
return;
|
||||
};
|
||||
let mountpoint = ui.dirs.resolved_mountpoint(&ui.dirs.load_config());
|
||||
let (in_drive, uploads) =
|
||||
split_dropped(&mountpoint, files.files().iter().filter_map(|f| f.path()));
|
||||
let moving = from_this_app(target);
|
||||
let dropped = in_drive.len();
|
||||
let going = drop_targets(in_drive, dest, moving).len();
|
||||
hint.set_label(&drop_preview(
|
||||
DropPlan {
|
||||
going,
|
||||
skipped: dropped - going,
|
||||
uploads: uploads.len(),
|
||||
moving,
|
||||
},
|
||||
name,
|
||||
));
|
||||
hint.set_visible(true);
|
||||
}
|
||||
|
||||
/// What a drop would do, counted: see [`drop_files`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct DropPlan {
|
||||
/// Items already in Proton Drive that go to the folder.
|
||||
pub(crate) going: usize,
|
||||
/// Items already in Proton Drive that cannot go there: the folder itself,
|
||||
/// one of its parents, or, for a move, what is in it already.
|
||||
pub(crate) skipped: usize,
|
||||
/// Files from outside Proton Drive, uploaded into the folder.
|
||||
pub(crate) uploads: usize,
|
||||
/// The items in Proton Drive move rather than copy.
|
||||
pub(crate) moving: bool,
|
||||
}
|
||||
|
||||
/// The drop hint for `plan` into the folder called `folder`. Each line is one
|
||||
/// sentence, so no translation is put together from pieces.
|
||||
pub(crate) fn drop_preview(plan: DropPlan, folder: &str) -> String {
|
||||
if plan.going == 0 && plan.uploads == 0 {
|
||||
return gettext("Nothing here can go into this folder");
|
||||
}
|
||||
let mut lines = Vec::new();
|
||||
if plan.going > 0 {
|
||||
let n = plan.going as u64;
|
||||
lines.push(if plan.moving {
|
||||
// Translators: shown while dragging; {folder} is the folder the items would go to.
|
||||
ngettext_f(
|
||||
"Move {n} item to “{folder}”",
|
||||
"Move {n} items to “{folder}”",
|
||||
n,
|
||||
&[("folder", folder)],
|
||||
)
|
||||
} else {
|
||||
// Translators: shown while dragging; {folder} is the folder the items would go to.
|
||||
ngettext_f(
|
||||
"Copy {n} item to “{folder}”",
|
||||
"Copy {n} items to “{folder}”",
|
||||
n,
|
||||
&[("folder", folder)],
|
||||
)
|
||||
});
|
||||
}
|
||||
if plan.uploads > 0 {
|
||||
// Translators: shown while dragging; {folder} is the folder the files would go to.
|
||||
lines.push(ngettext_f(
|
||||
"Upload {n} item to “{folder}”",
|
||||
"Upload {n} items to “{folder}”",
|
||||
plan.uploads as u64,
|
||||
&[("folder", folder)],
|
||||
));
|
||||
}
|
||||
if plan.skipped > 0 {
|
||||
lines.push(ngettext_f(
|
||||
"{n} item can't go there and is left out",
|
||||
"{n} items can't go there and are left out",
|
||||
plan.skipped as u64,
|
||||
&[],
|
||||
));
|
||||
}
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
/// The action to answer a drag over the browser with: always a copy. Rows
|
||||
/// dragged from this app offer nothing else (see [`attach_drag`]), and an
|
||||
/// outside drag is never answered with a move, which would have the source
|
||||
@@ -3564,9 +3716,9 @@ fn listing_summary(files: usize, folders: usize, file_bytes: u64) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
MoveTarget, badge_for, copy_target_allowed, drop_targets, hit_location, icon_base_for,
|
||||
listing_summary, move_target_allowed, show_thumbnail_build_progress, sort_entries,
|
||||
split_dropped,
|
||||
DropPlan, MoveTarget, badge_for, copy_target_allowed, drop_preview, drop_targets,
|
||||
hit_location, icon_base_for, listing_summary, move_target_allowed,
|
||||
show_thumbnail_build_progress, sort_entries, split_dropped,
|
||||
};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -3645,6 +3797,40 @@ mod tests {
|
||||
["Docs/a.pdf", "Photos/b.jpg"]
|
||||
);
|
||||
}
|
||||
|
||||
/// The hint says the same thing the drop will do: a move for rows from
|
||||
/// this app, a copy for files from a file manager browsing the mount, and
|
||||
/// how many are left out.
|
||||
#[test]
|
||||
fn the_drop_hint_names_the_action_and_what_is_left_out() {
|
||||
let plan = |going, skipped, uploads, moving| DropPlan {
|
||||
going,
|
||||
skipped,
|
||||
uploads,
|
||||
moving,
|
||||
};
|
||||
assert_eq!(
|
||||
drop_preview(plan(3, 0, 0, true), "Receipts"),
|
||||
"Move 3 items to “Receipts”"
|
||||
);
|
||||
assert_eq!(
|
||||
drop_preview(plan(1, 0, 0, false), "Receipts"),
|
||||
"Copy 1 item to “Receipts”"
|
||||
);
|
||||
assert_eq!(
|
||||
drop_preview(plan(0, 0, 2, false), "Receipts"),
|
||||
"Upload 2 items to “Receipts”"
|
||||
);
|
||||
// A selection that holds the folder itself: the rest still moves.
|
||||
assert_eq!(
|
||||
drop_preview(plan(2, 1, 0, true), "Receipts"),
|
||||
"Move 2 items to “Receipts”\n1 item can't go there and is left out"
|
||||
);
|
||||
assert_eq!(
|
||||
drop_preview(plan(0, 2, 0, true), "Receipts"),
|
||||
"Nothing here can go into this folder"
|
||||
);
|
||||
}
|
||||
use pdfs_core::config::{FileSort, FilesView};
|
||||
use pdfs_core::control::{DirEntry, SyncIssue, ThumbnailBuildStatus};
|
||||
|
||||
|
||||
@@ -1007,20 +1007,54 @@ pub(crate) fn prompt_remove_sync_folder(
|
||||
dialog.set_response_appearance("remove", adw::ResponseAppearance::Destructive);
|
||||
dialog.set_default_response(Some("cancel"));
|
||||
dialog.set_close_response("cancel");
|
||||
let ui = ui.clone();
|
||||
dialog.connect_response(None, move |_, resp| {
|
||||
if resp == "remove" {
|
||||
run_devices_mutation(
|
||||
&ui,
|
||||
Request::RemoveSyncFolder {
|
||||
id,
|
||||
delete_remote: !attached && delete_remote.is_active(),
|
||||
// With the switch on, the button does more than stop syncing, so it says
|
||||
// so: the heading, the button and the outcome all name the deletion.
|
||||
delete_remote.connect_active_notify({
|
||||
let dialog = dialog.clone();
|
||||
move |row| {
|
||||
let deleting = row.is_active();
|
||||
dialog.set_heading(Some(&if deleting {
|
||||
gettext("Stop Syncing and Delete Folder?")
|
||||
} else {
|
||||
gettext("Stop Syncing Folder?")
|
||||
}));
|
||||
dialog.set_response_label(
|
||||
"remove",
|
||||
&if deleting {
|
||||
gettext("Stop Syncing and Delete")
|
||||
} else {
|
||||
gettext("Stop Syncing")
|
||||
},
|
||||
&gettext("Stopped syncing folder"),
|
||||
&gettext("Couldn't stop syncing the folder"),
|
||||
);
|
||||
}
|
||||
});
|
||||
let ui = ui.clone();
|
||||
dialog.connect_response(None, move |_, resp| {
|
||||
if resp != "remove" {
|
||||
return;
|
||||
}
|
||||
let deleting = !attached && delete_remote.is_active();
|
||||
let (done, failed) = if deleting {
|
||||
(
|
||||
gettext("Stopped syncing and moved the folder in Proton Drive to the trash"),
|
||||
gettext("Couldn't stop syncing and delete the folder"),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
gettext("Stopped syncing folder"),
|
||||
gettext("Couldn't stop syncing the folder"),
|
||||
)
|
||||
};
|
||||
run_devices_mutation(
|
||||
&ui,
|
||||
Request::RemoveSyncFolder {
|
||||
id,
|
||||
delete_remote: deleting,
|
||||
},
|
||||
&done,
|
||||
&failed,
|
||||
);
|
||||
});
|
||||
dialog.present(win.as_ref());
|
||||
}
|
||||
|
||||
|
||||
@@ -310,6 +310,7 @@ fn duplicate_review(
|
||||
|
||||
// Every copy's toggle, by set, so the button can count what goes.
|
||||
let toggles: Rc<RefCell<SetToggles>> = Rc::new(RefCell::new(Vec::new()));
|
||||
let mut kept_labels: Vec<gtk4::Label> = Vec::new();
|
||||
for set in sets {
|
||||
let Some(first) = set.first() else {
|
||||
continue;
|
||||
@@ -333,20 +334,29 @@ fn duplicate_review(
|
||||
};
|
||||
let heading = gtk4::Label::builder().label(title).xalign(0.0).build();
|
||||
heading.add_css_class("heading");
|
||||
// How many of the set stay, in the heading's line: a set wider than
|
||||
// the window hides some of its cards, and this still says what goes.
|
||||
let kept = gtk4::Label::builder().xalign(1.0).hexpand(true).build();
|
||||
kept.add_css_class("dim-label");
|
||||
let header = gtk4::Box::new(gtk4::Orientation::Horizontal, 12);
|
||||
header.append(&heading);
|
||||
header.append(&kept);
|
||||
let row = gtk4::Box::new(gtk4::Orientation::Horizontal, 12);
|
||||
let mut set_toggles = Vec::new();
|
||||
for (index, photo) in set.into_iter().enumerate() {
|
||||
let (card, keep) = copy_card(ui, &photo, index == 0 || finder == Finder::Similar);
|
||||
let (card, keep) =
|
||||
copy_card(ui, &photo, index == 0 || finder == Finder::Similar, finder);
|
||||
row.append(&card);
|
||||
set_toggles.push((photo, keep));
|
||||
}
|
||||
kept_labels.push(kept);
|
||||
let row_scroll = gtk4::ScrolledWindow::builder()
|
||||
.vscrollbar_policy(gtk4::PolicyType::Never)
|
||||
.propagate_natural_height(true)
|
||||
.child(&row)
|
||||
.build();
|
||||
let section = gtk4::Box::new(gtk4::Orientation::Vertical, 6);
|
||||
section.append(&heading);
|
||||
section.append(&header);
|
||||
section.append(&row_scroll);
|
||||
content.append(§ion);
|
||||
toggles.borrow_mut().push(set_toggles);
|
||||
@@ -356,22 +366,14 @@ fn duplicate_review(
|
||||
let toggles = toggles.clone();
|
||||
let trash = trash.clone();
|
||||
move || {
|
||||
let n = doomed(&toggles.borrow()).len();
|
||||
trash.set_label(&match finder {
|
||||
Finder::Exact => ngettext_f(
|
||||
"Move {n} copy to Trash",
|
||||
"Move {n} copies to Trash",
|
||||
n as u64,
|
||||
&[],
|
||||
),
|
||||
Finder::Similar => ngettext_f(
|
||||
"Move {n} photo to Trash",
|
||||
"Move {n} photos to Trash",
|
||||
n as u64,
|
||||
&[],
|
||||
),
|
||||
});
|
||||
let toggles = toggles.borrow();
|
||||
let (n, files) = doomed_counts(&toggles, finder);
|
||||
trash.set_label(&trash_label(finder, n, files));
|
||||
trash.set_sensitive(n > 0);
|
||||
for (set, label) in toggles.iter().zip(&kept_labels) {
|
||||
let keep = set.iter().filter(|(_, t)| t.is_active()).count();
|
||||
label.set_label(&kept_label(keep, set.len()));
|
||||
}
|
||||
}
|
||||
};
|
||||
sync();
|
||||
@@ -421,6 +423,94 @@ fn duplicate_review(
|
||||
(scroll.upcast(), handler)
|
||||
}
|
||||
|
||||
/// How many photos go to Trash, and how many files that is. An exact copy is
|
||||
/// one file. A similar photo takes its whole shot, a RAW and its JPEG
|
||||
/// together.
|
||||
fn doomed_counts(toggles: &SetToggles, finder: Finder) -> (usize, usize) {
|
||||
let doomed: Vec<&PhotoItem> = toggles
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|(_, keep)| !keep.is_active())
|
||||
.map(|(photo, _)| photo)
|
||||
.collect();
|
||||
(doomed.len(), files_of(doomed.into_iter(), finder))
|
||||
}
|
||||
|
||||
/// How many files trashing `photos` moves.
|
||||
fn files_of<'a>(photos: impl Iterator<Item = &'a PhotoItem>, finder: Finder) -> usize {
|
||||
photos
|
||||
.map(|photo| match finder {
|
||||
Finder::Exact => 1,
|
||||
Finder::Similar => photo.group_size.max(1) as usize,
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// The footer button: what it moves, in photos and, when that differs, files.
|
||||
fn trash_label(finder: Finder, photos: usize, files: usize) -> String {
|
||||
match finder {
|
||||
Finder::Exact => ngettext_f(
|
||||
"Move {n} copy to Trash",
|
||||
"Move {n} copies to Trash",
|
||||
photos as u64,
|
||||
&[],
|
||||
),
|
||||
Finder::Similar if files > photos => ngettext_f(
|
||||
// Translators: {n} is a number of photos, {files} how many files they are stored as (always more than {n}).
|
||||
"Move {n} photo ({files} files) to Trash",
|
||||
"Move {n} photos ({files} files) to Trash",
|
||||
photos as u64,
|
||||
&[("files", &files.to_string())],
|
||||
),
|
||||
Finder::Similar => ngettext_f(
|
||||
"Move {n} photo to Trash",
|
||||
"Move {n} photos to Trash",
|
||||
photos as u64,
|
||||
&[],
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// How many of a set stay.
|
||||
fn kept_label(kept: usize, of: usize) -> String {
|
||||
ngettext_f(
|
||||
// Translators: {n} photos of a set of {total} stay; the rest go to Trash.
|
||||
"Keeping {n} of {total}",
|
||||
"Keeping {n} of {total}",
|
||||
kept as u64,
|
||||
&[("total", &of.to_string())],
|
||||
)
|
||||
}
|
||||
|
||||
/// What a card's photo is stored as, when that is more than one file.
|
||||
fn stored_as(photo: &PhotoItem) -> Option<String> {
|
||||
let n = photo.group_size;
|
||||
(n > 1).then(|| {
|
||||
if photo.has_raw {
|
||||
ngettext_f(
|
||||
// Translators: a shot stored as a camera RAW file and others, such as its JPEG.
|
||||
"RAW + {n} more file",
|
||||
"RAW + {n} more files",
|
||||
u64::from(n - 1),
|
||||
&[],
|
||||
)
|
||||
} else {
|
||||
ngettext_f("{n} file", "{n} files", u64::from(n), &[])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// What happens to a card's photo, under its toggle.
|
||||
fn outcome_label(keep: bool) -> String {
|
||||
if keep {
|
||||
// Translators: a photo in the duplicates review that stays.
|
||||
pgettext("duplicates", "Kept")
|
||||
} else {
|
||||
// Translators: a photo in the duplicates review that goes to Trash.
|
||||
pgettext("duplicates", "Moves to Trash")
|
||||
}
|
||||
}
|
||||
|
||||
/// The uids of every copy not kept.
|
||||
fn doomed(toggles: &SetToggles) -> Vec<String> {
|
||||
toggles
|
||||
@@ -431,8 +521,14 @@ fn doomed(toggles: &SetToggles) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One copy: its thumbnail, its file name, and whether to keep it.
|
||||
fn copy_card(ui: &Rc<Ui>, photo: &PhotoItem, keep: bool) -> (gtk4::Box, gtk4::ToggleButton) {
|
||||
/// One copy: its thumbnail, its file name, and whether to keep it. A similar
|
||||
/// shot stored as several files says so, since all of them go with it.
|
||||
fn copy_card(
|
||||
ui: &Rc<Ui>,
|
||||
photo: &PhotoItem,
|
||||
keep: bool,
|
||||
finder: Finder,
|
||||
) -> (gtk4::Box, gtk4::ToggleButton) {
|
||||
let picture = gtk4::Picture::builder()
|
||||
.content_fit(gtk4::ContentFit::Cover)
|
||||
.can_shrink(true)
|
||||
@@ -464,11 +560,88 @@ fn copy_card(ui: &Rc<Ui>, photo: &PhotoItem, keep: bool) -> (gtk4::Box, gtk4::To
|
||||
.active(keep)
|
||||
.build();
|
||||
toggle.add_css_class("pill");
|
||||
let outcome = gtk4::Label::builder().label(outcome_label(keep)).build();
|
||||
outcome.add_css_class("caption");
|
||||
if !keep {
|
||||
outcome.add_css_class("error");
|
||||
}
|
||||
let outcome_t = outcome.clone();
|
||||
toggle.connect_toggled(move |toggle| {
|
||||
outcome_t.set_label(&outcome_label(toggle.is_active()));
|
||||
if toggle.is_active() {
|
||||
outcome_t.remove_css_class("error");
|
||||
} else {
|
||||
outcome_t.add_css_class("error");
|
||||
}
|
||||
});
|
||||
|
||||
let card = gtk4::Box::new(gtk4::Orientation::Vertical, 6);
|
||||
card.set_size_request(COPY_SIZE, -1);
|
||||
card.append(&overlay);
|
||||
card.append(&label);
|
||||
if finder == Finder::Similar
|
||||
&& let Some(files) = stored_as(photo)
|
||||
{
|
||||
let files = gtk4::Label::builder().label(files).build();
|
||||
files.add_css_class("caption");
|
||||
files.add_css_class("dim-label");
|
||||
card.append(&files);
|
||||
}
|
||||
card.append(&toggle);
|
||||
card.append(&outcome);
|
||||
(card, toggle)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn shot(files: u32, has_raw: bool) -> PhotoItem {
|
||||
PhotoItem {
|
||||
uid: "vol~shot".into(),
|
||||
capture_time: 0,
|
||||
thumb_path: None,
|
||||
name: None,
|
||||
ratio: None,
|
||||
no_thumb: false,
|
||||
kind: PhotoKind::Photo,
|
||||
favorite: false,
|
||||
group_size: files,
|
||||
has_raw,
|
||||
place_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One RAW+JPEG shot marked and another kept: the footer counts both.
|
||||
#[test]
|
||||
fn the_footer_counts_files_when_a_shot_is_several() {
|
||||
let raw_jpeg = shot(2, true);
|
||||
let files = files_of([&raw_jpeg].into_iter(), Finder::Similar);
|
||||
assert_eq!(files, 2);
|
||||
assert_eq!(
|
||||
trash_label(Finder::Similar, 1, files),
|
||||
"Move 1 photo (2 files) to Trash"
|
||||
);
|
||||
assert_eq!(trash_label(Finder::Similar, 2, 2), "Move 2 photos to Trash");
|
||||
}
|
||||
|
||||
/// An exact copy is one file, whatever its shot holds.
|
||||
#[test]
|
||||
fn an_exact_copy_is_one_file() {
|
||||
let raw_jpeg = shot(2, true);
|
||||
assert_eq!(files_of([&raw_jpeg].into_iter(), Finder::Exact), 1);
|
||||
assert_eq!(trash_label(Finder::Exact, 1, 1), "Move 1 copy to Trash");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_card_names_what_its_shot_is_stored_as() {
|
||||
assert_eq!(stored_as(&shot(1, false)), None);
|
||||
assert_eq!(stored_as(&shot(0, false)), None);
|
||||
assert_eq!(
|
||||
stored_as(&shot(2, true)).as_deref(),
|
||||
Some("RAW + 1 more file")
|
||||
);
|
||||
assert_eq!(stored_as(&shot(3, false)).as_deref(), Some("3 files"));
|
||||
assert_eq!(kept_label(1, 4), "Keeping 1 of 4");
|
||||
}
|
||||
}
|
||||
@@ -671,15 +671,34 @@ fn repaint_queue(ui: &Rc<Ui>, items: &[PendingOpInfo]) {
|
||||
.map(|now| now.to_unix())
|
||||
.unwrap_or_default();
|
||||
let mut rows = queue.rows.borrow_mut();
|
||||
for op in items.into_iter().take(QUEUE_ROWS_SHOWN) {
|
||||
let row = queue_row(ui, op, now);
|
||||
for op in items.iter().copied().take(QUEUE_ROWS_SHOWN) {
|
||||
let scope = discard_scope(op, &items);
|
||||
let row = queue_row(ui, op, &scope, now);
|
||||
queue.group.add(&row);
|
||||
rows.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
fn queue_row(ui: &Rc<Ui>, op: &PendingOpInfo, now: i64) -> adw::ActionRow {
|
||||
let (icon, action) = match op.kind.as_str() {
|
||||
/// The queued ops a discard of `op` drops: every op on the same node, `op`
|
||||
/// first and the rest in queue order. The daemon drops them all, since each
|
||||
/// was made on top of the one before.
|
||||
fn discard_scope<'a>(op: &'a PendingOpInfo, all: &[&'a PendingOpInfo]) -> Vec<&'a PendingOpInfo> {
|
||||
let mut scope = vec![op];
|
||||
if !op.node.is_empty() {
|
||||
let mut others: Vec<&PendingOpInfo> = all
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|other| other.node == op.node && other.id != op.id)
|
||||
.collect();
|
||||
others.sort_by_key(|other| other.id);
|
||||
scope.extend(others);
|
||||
}
|
||||
scope
|
||||
}
|
||||
|
||||
/// A queued op's kind, as an icon and a short action.
|
||||
fn op_action(kind: &str) -> (&'static str, String) {
|
||||
match kind {
|
||||
"revision" => ("pdfs-upload-symbolic", gettext("Upload changes")),
|
||||
"create" => ("pdfs-upload-symbolic", gettext("Upload new file")),
|
||||
"mkdir" => ("folder-new-symbolic", gettext("Create folder")),
|
||||
@@ -687,7 +706,28 @@ fn queue_row(ui: &Rc<Ui>, op: &PendingOpInfo, now: i64) -> adw::ActionRow {
|
||||
"trash" => ("user-trash-symbolic", gettext("Move to trash")),
|
||||
// Translators: a queued change of an unknown kind.
|
||||
_ => ("pdfs-sync-symbolic", pgettext("noun", "Change")),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// What the discard dialog needs to say about one discard.
|
||||
#[derive(Clone)]
|
||||
struct DiscardScope {
|
||||
id: i64,
|
||||
path: String,
|
||||
/// The op whose content can be exported, if any of them carries some.
|
||||
exportable: Option<i64>,
|
||||
local_only: bool,
|
||||
/// Each dropped op's action, the asked one first.
|
||||
actions: Vec<String>,
|
||||
}
|
||||
|
||||
fn queue_row(
|
||||
ui: &Rc<Ui>,
|
||||
op: &PendingOpInfo,
|
||||
scope: &[&PendingOpInfo],
|
||||
now: i64,
|
||||
) -> adw::ActionRow {
|
||||
let (icon, action) = op_action(&op.kind);
|
||||
let state = match (op.parked, op.next_attempt_at) {
|
||||
(true, _) => gettext("waiting for the app writing it to finish"),
|
||||
(false, Some(at)) if at > now && op.attempts > 0 => {
|
||||
@@ -769,10 +809,15 @@ fn queue_row(ui: &Rc<Ui>, op: &PendingOpInfo, now: i64) -> adw::ActionRow {
|
||||
.build();
|
||||
discard.add_css_class("flat");
|
||||
let ui = ui.clone();
|
||||
let id = op.id;
|
||||
let path = op.path.clone();
|
||||
let exportable = op.exportable;
|
||||
discard.connect_clicked(move |_| prompt_discard_queued(&ui, id, &path, exportable));
|
||||
let scope = DiscardScope {
|
||||
id: op.id,
|
||||
path: op.path.clone(),
|
||||
// The newest content is the version the user would lose.
|
||||
exportable: scope.iter().rev().find(|op| op.exportable).map(|op| op.id),
|
||||
local_only: op.local_only,
|
||||
actions: scope.iter().map(|op| op_action(&op.kind).1).collect(),
|
||||
};
|
||||
discard.connect_clicked(move |_| prompt_discard_queued(&ui, &scope));
|
||||
row.add_suffix(&discard);
|
||||
}
|
||||
row
|
||||
@@ -844,35 +889,77 @@ fn prompt_export_queued(ui: &Rc<Ui>, id: i64, name: &str) {
|
||||
}
|
||||
|
||||
/// Confirm, then have the daemon drop a queued change and undo it here.
|
||||
fn prompt_discard_queued(ui: &Rc<Ui>, id: i64, path: &str, exportable: bool) {
|
||||
let body = if exportable {
|
||||
// Translators: {path} is the file whose queued change would be dropped.
|
||||
///
|
||||
/// The daemon drops every change queued on the same file or folder, so the
|
||||
/// dialog lists them all, says whether the item goes back to how Proton Drive
|
||||
/// has it or disappears from this computer, and offers the export first.
|
||||
fn prompt_discard_queued(ui: &Rc<Ui>, scope: &DiscardScope) {
|
||||
let name = Path::new(&scope.path)
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| scope.path.clone());
|
||||
let count = scope.actions.len() as u64;
|
||||
let outcome = if scope.local_only {
|
||||
// Translators: {path} is a file or folder made on this computer that never reached Proton Drive.
|
||||
gettext_f(
|
||||
"Your changes to {path} are undone here and never reach Proton Drive. Export the file first to keep your version.",
|
||||
&[("path", path)],
|
||||
"{path} was made on this computer and is not on Proton Drive yet. Discarding removes it from this computer.",
|
||||
&[("path", &scope.path)],
|
||||
)
|
||||
} else {
|
||||
// Translators: {path} is the file or folder whose queued change would be dropped.
|
||||
// Translators: {path} is a file or folder that is on Proton Drive.
|
||||
gettext_f(
|
||||
"The change to {path} is undone here and never reaches Proton Drive.",
|
||||
&[("path", path)],
|
||||
"{path} goes back to how it is on Proton Drive, and the changes below are undone here.",
|
||||
&[("path", &scope.path)],
|
||||
)
|
||||
};
|
||||
let body = if scope.exportable.is_some() {
|
||||
format!(
|
||||
"{outcome}\n\n{}",
|
||||
gettext("Export the file first to keep your version.")
|
||||
)
|
||||
} else {
|
||||
outcome
|
||||
};
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.heading(gettext("Discard Change?"))
|
||||
// Translators: {name} is the file or folder name, {n} how many queued changes a discard drops.
|
||||
.heading(ngettext_f(
|
||||
"Discard the Change to “{name}”?",
|
||||
"Discard {n} Changes to “{name}”?",
|
||||
count,
|
||||
&[("name", &name)],
|
||||
))
|
||||
.body(body)
|
||||
.build();
|
||||
let list = gtk4::ListBox::builder()
|
||||
.selection_mode(gtk4::SelectionMode::None)
|
||||
.css_classes(["boxed-list"])
|
||||
.build();
|
||||
for action in &scope.actions {
|
||||
list.append(&adw::ActionRow::builder().title(action.as_str()).build());
|
||||
}
|
||||
dialog.set_extra_child(Some(&list));
|
||||
dialog.add_response("cancel", &gettext("Cancel"));
|
||||
dialog.add_response("discard", &gettext("Discard"));
|
||||
if scope.exportable.is_some() {
|
||||
dialog.add_response("export", &gettext("Export My Version…"));
|
||||
}
|
||||
dialog.add_response(
|
||||
"discard",
|
||||
&ngettext_f("Discard Change", "Discard {n} Changes", count, &[]),
|
||||
);
|
||||
dialog.set_response_appearance("discard", adw::ResponseAppearance::Destructive);
|
||||
dialog.set_default_response(Some("cancel"));
|
||||
dialog.set_close_response("cancel");
|
||||
let window = ui_window(ui);
|
||||
let ui = ui.clone();
|
||||
dialog.connect_response(None, move |_, resp| {
|
||||
if resp == "discard" {
|
||||
discard_queued(&ui, id);
|
||||
let scope = scope.clone();
|
||||
dialog.connect_response(None, move |_, resp| match resp {
|
||||
"discard" => discard_queued(&ui, scope.id),
|
||||
"export" => {
|
||||
if let Some(id) = scope.exportable {
|
||||
prompt_export_queued(&ui, id, &name);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
dialog.present(window.as_ref());
|
||||
}
|
||||
@@ -1786,6 +1873,51 @@ pub(crate) fn location_subtitle(spec: &MountSpec) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn queued(id: i64, kind: &str, node: &str) -> PendingOpInfo {
|
||||
PendingOpInfo {
|
||||
id,
|
||||
kind: kind.into(),
|
||||
path: "Docs/report.odt".into(),
|
||||
attempts: 0,
|
||||
last_error: None,
|
||||
queued_at: 0,
|
||||
next_attempt_at: None,
|
||||
parked: false,
|
||||
failing: true,
|
||||
issue: None,
|
||||
exportable: kind == "revision",
|
||||
node: node.into(),
|
||||
local_only: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_discard_names_every_change_queued_on_the_same_node() {
|
||||
let rename = queued(9, "rename", "vol~a");
|
||||
let edit = queued(4, "revision", "vol~a");
|
||||
let other = queued(5, "revision", "vol~b");
|
||||
let all = [&rename, &edit, &other];
|
||||
|
||||
let scope: Vec<i64> = discard_scope(&rename, &all)
|
||||
.iter()
|
||||
.map(|op| op.id)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
scope,
|
||||
[9, 4],
|
||||
"the asked change first, then the rest by age"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_discard_from_an_older_daemon_names_only_its_own_change() {
|
||||
let rename = queued(9, "rename", "");
|
||||
let edit = queued(4, "revision", "");
|
||||
let all = [&rename, &edit];
|
||||
|
||||
assert_eq!(discard_scope(&rename, &all).len(), 1);
|
||||
}
|
||||
|
||||
fn spec(kind: MountKind, mode: MountMode, mounted: bool) -> MountSpec {
|
||||
MountSpec {
|
||||
id: 1,
|
||||
|
||||
@@ -682,32 +682,40 @@ pub(crate) fn sign_out(ui: &Rc<Ui>) {
|
||||
let rx = spawn_request(ui.dirs.control_socket(), Request::Status);
|
||||
let ui = ui.clone();
|
||||
glib::spawn_future_local(async move {
|
||||
// `None` when the service did not answer: then nobody knows whether
|
||||
// changes are still waiting, which is not the same as none.
|
||||
let queued = match rx.recv().await {
|
||||
Ok(Ok(Response::Status {
|
||||
pending_uploads,
|
||||
pending_changes,
|
||||
parked_uploads,
|
||||
..
|
||||
})) => pending_uploads + pending_changes + parked_uploads,
|
||||
_ => 0,
|
||||
})) => Some(pending_uploads + pending_changes + parked_uploads),
|
||||
_ => None,
|
||||
};
|
||||
confirm_sign_out(&ui, queued);
|
||||
});
|
||||
}
|
||||
|
||||
fn confirm_sign_out(ui: &Rc<Ui>, queued: u64) {
|
||||
fn confirm_sign_out(ui: &Rc<Ui>, queued: Option<u64>) {
|
||||
let Some(window) = ui_window(ui) else { return };
|
||||
let ui = ui.clone();
|
||||
let mut body = gettext(
|
||||
"Proton Drive will disconnect and stop syncing until you sign in again. Files already on this computer stay where they are.",
|
||||
);
|
||||
if queued > 0 {
|
||||
let warning = ngettext_f(
|
||||
let warning = match queued {
|
||||
Some(0) => None,
|
||||
Some(queued) => Some(ngettext_f(
|
||||
"{n} change is not on Proton Drive yet. It stays on this computer and is sent after you sign in again.",
|
||||
"{n} changes are not on Proton Drive yet. They stay on this computer and are sent after you sign in again.",
|
||||
queued,
|
||||
&[],
|
||||
);
|
||||
)),
|
||||
None => Some(gettext(
|
||||
"The Proton Drive service didn't answer, so it isn't known whether changes are still waiting to be sent. Any that are stay on this computer and are sent after you sign in again.",
|
||||
)),
|
||||
};
|
||||
if let Some(warning) = warning {
|
||||
body = format!("{warning}\n\n{body}");
|
||||
}
|
||||
confirm_destructive(
|
||||
@@ -720,24 +728,65 @@ fn confirm_sign_out(ui: &Rc<Ui>, queued: u64) {
|
||||
if let Some(galleries) = galleries {
|
||||
galleries.reset();
|
||||
}
|
||||
// systemctl and the keyring both block, so run them on a worker.
|
||||
let ui = ui.clone();
|
||||
glib::spawn_future_local(async move {
|
||||
let result = gio::spawn_blocking(|| {
|
||||
service::disable_stop();
|
||||
auth::logout().map(|_| ()).map_err(|e| e.to_string())
|
||||
})
|
||||
.await;
|
||||
if let Ok(Err(e)) = result {
|
||||
tracing::error!("logout failed: {e}");
|
||||
}
|
||||
*ui.session.borrow_mut() = None;
|
||||
refresh(&ui);
|
||||
});
|
||||
sign_out_now(&ui);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Stop the service and forget the stored session, then say what happened.
|
||||
///
|
||||
/// Two parts can fail on their own. Proton may not confirm that the session
|
||||
/// ended, which leaves it listed in the account's security settings until it
|
||||
/// expires. Removing the sign-in from the keyring may fail, which leaves this
|
||||
/// computer signed in at the next start. The first is a notice, the second
|
||||
/// needs the user, so it stays on screen with a way to try again.
|
||||
fn sign_out_now(ui: &Rc<Ui>) {
|
||||
// systemctl and the keyring both block, so run them on a worker.
|
||||
let ui = ui.clone();
|
||||
glib::spawn_future_local(async move {
|
||||
let result = gio::spawn_blocking(|| {
|
||||
service::disable_stop();
|
||||
auth::logout().map_err(|e| e.to_string())
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| Err("the sign-out worker stopped".into()));
|
||||
*ui.session.borrow_mut() = None;
|
||||
refresh(&ui);
|
||||
match result {
|
||||
Ok(true) => {}
|
||||
Ok(false) => toast(
|
||||
&ui,
|
||||
&gettext(
|
||||
"Signed out on this computer. Proton didn't confirm that the session ended; you can end it in your Proton account's security settings.",
|
||||
),
|
||||
),
|
||||
Err(error) => {
|
||||
tracing::error!("logout failed: {error}");
|
||||
present_sign_out_failure(&ui, &error);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn present_sign_out_failure(ui: &Rc<Ui>, error: &str) {
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.heading(gettext("Sign-In Still Saved"))
|
||||
// Translators: {error} is the reason the keyring gave.
|
||||
.body(gettext_f(
|
||||
"Proton Drive stopped, but your sign-in couldn't be removed from this computer: {error}\n\nUntil it is removed, Proton Drive may sign in again at the next start. Unlock your keyring, then try again.",
|
||||
&[("error", error)],
|
||||
))
|
||||
.build();
|
||||
dialog.add_response("close", &gettext("Close"));
|
||||
dialog.add_response("again", &gettext("Try Again"));
|
||||
dialog.set_response_appearance("again", adw::ResponseAppearance::Suggested);
|
||||
dialog.set_default_response(Some("again"));
|
||||
dialog.set_close_response("close");
|
||||
let ui_c = ui.clone();
|
||||
dialog.connect_response(Some("again"), move |_, _| sign_out_now(&ui_c));
|
||||
dialog.present(ui_window(ui).as_ref());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::login_error_message;
|
||||
|
||||
@@ -24,6 +24,9 @@ pub(crate) struct AppsPrefs {
|
||||
prompt_terminal_row: adw::EntryRow,
|
||||
limit_row: adw::SpinRow,
|
||||
icons_row: adw::SwitchRow,
|
||||
remember_row: adw::SwitchRow,
|
||||
clear_row: adw::ActionRow,
|
||||
clear_button: gtk4::Button,
|
||||
}
|
||||
|
||||
/// The launcher modes in the order the combo row lists them.
|
||||
@@ -102,6 +105,23 @@ pub(crate) fn build_apps_prefs() -> AppsPrefs {
|
||||
.title(gettext("Show icons"))
|
||||
.subtitle(gettext("When the launcher can show them"))
|
||||
.build();
|
||||
let remember_row = adw::SwitchRow::builder()
|
||||
.title(gettext("Remember recent files"))
|
||||
.subtitle(gettext(
|
||||
"List what you opened before you type, and rank it higher in results. Off, the list is cleared.",
|
||||
))
|
||||
.build();
|
||||
let clear_button = gtk4::Button::builder()
|
||||
.label(gettext("Clear"))
|
||||
.valign(gtk4::Align::Center)
|
||||
.build();
|
||||
let clear_row = adw::ActionRow::builder()
|
||||
.title(gettext("Clear recent files"))
|
||||
.subtitle(gettext(
|
||||
"The search window forgets what it opened. Your files are not touched.",
|
||||
))
|
||||
.build();
|
||||
clear_row.add_suffix(&clear_button);
|
||||
let launcher = adw::PreferencesGroup::builder()
|
||||
.title(gettext("Search Launcher"))
|
||||
.description(gettext(
|
||||
@@ -113,6 +133,8 @@ pub(crate) fn build_apps_prefs() -> AppsPrefs {
|
||||
launcher.add(&prompt_terminal_row);
|
||||
launcher.add(&limit_row);
|
||||
launcher.add(&icons_row);
|
||||
launcher.add(&remember_row);
|
||||
launcher.add(&clear_row);
|
||||
|
||||
let page = adw::PreferencesPage::builder()
|
||||
.title(gettext("Apps"))
|
||||
@@ -133,6 +155,9 @@ pub(crate) fn build_apps_prefs() -> AppsPrefs {
|
||||
prompt_terminal_row,
|
||||
limit_row,
|
||||
icons_row,
|
||||
remember_row,
|
||||
clear_row,
|
||||
clear_button,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,6 +208,7 @@ pub(crate) fn wire_apps_prefs(ui: &Rc<Ui>, widgets: AppsPrefs) {
|
||||
.set_text(&format_command(prompt.terminal.as_deref().unwrap_or(&[])));
|
||||
w.limit_row.set_value(prompt.resolved_menu_limit() as f64);
|
||||
w.icons_row.set_active(prompt.resolved_menu_icons());
|
||||
w.remember_row.set_active(prompt.resolved_remember_recent());
|
||||
show_mode_rows(w, mode);
|
||||
ui.status.settings_suppress.set(suppress);
|
||||
|
||||
@@ -239,6 +265,56 @@ pub(crate) fn wire_apps_prefs(ui: &Rc<Ui>, widgets: AppsPrefs) {
|
||||
prompt_of(config).menu_icons = (!on).then_some(false)
|
||||
});
|
||||
});
|
||||
let a = apps.clone();
|
||||
w.remember_row.connect_active_notify(move |row| {
|
||||
if a.ui.status.settings_suppress.get() {
|
||||
return;
|
||||
}
|
||||
let on = row.is_active();
|
||||
// The window clears the list itself the next time it opens; clearing
|
||||
// here as well means nothing waits on disk until then.
|
||||
if !on {
|
||||
clear_history(&a);
|
||||
}
|
||||
save(&a, move |config| {
|
||||
prompt_of(config).remember_recent = (!on).then_some(false)
|
||||
});
|
||||
});
|
||||
let a = apps.clone();
|
||||
w.clear_button.connect_clicked(move |_| {
|
||||
if clear_history(&a) {
|
||||
prefs_toast(&a.ui, &gettext("Recent files cleared"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Delete the search window's history. It reads the file again each time it
|
||||
/// opens. Says whether that worked.
|
||||
fn clear_history(apps: &Rc<Apps>) -> bool {
|
||||
match std::fs::remove_file(history_path(&apps.ui)) {
|
||||
Ok(()) => true,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
|
||||
Err(e) => {
|
||||
prefs_toast(
|
||||
&apps.ui,
|
||||
&gettext_f(
|
||||
"{what}: {detail}",
|
||||
&[
|
||||
("what", &gettext("Couldn't clear recent files")),
|
||||
("detail", &e.to_string()),
|
||||
],
|
||||
),
|
||||
);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the search window keeps what it opened (`hud/history.rs`).
|
||||
fn history_path(ui: &Ui) -> std::path::PathBuf {
|
||||
ui.dirs
|
||||
.state_dir()
|
||||
.join(pdfs_core::menu::PROMPT_HISTORY_FILE)
|
||||
}
|
||||
|
||||
/// Show only the rows the chosen launcher mode uses.
|
||||
@@ -247,6 +323,9 @@ fn show_mode_rows(w: &AppsPrefs, mode: PromptMode) {
|
||||
w.icons_row.set_visible(mode == PromptMode::Dmenu);
|
||||
w.prompt_terminal_row.set_visible(mode == PromptMode::Fzf);
|
||||
w.limit_row.set_visible(mode != PromptMode::Gtk);
|
||||
// Only the search window keeps a history.
|
||||
w.remember_row.set_visible(mode == PromptMode::Gtk);
|
||||
w.clear_row.set_visible(mode == PromptMode::Gtk);
|
||||
}
|
||||
|
||||
/// The `open_with` section, created when absent.
|
||||
|
||||
@@ -955,16 +955,36 @@ pub(crate) fn prompt_leave_shared(ui: &Rc<Ui>, entries: &[DirEntry]) {
|
||||
dialog.set_default_response(Some("cancel"));
|
||||
dialog.set_close_response("cancel");
|
||||
let ui_c = ui.clone();
|
||||
let uids: Vec<String> = entries.iter().map(|e| e.uid.clone()).collect();
|
||||
let targets: Vec<(String, String)> = entries
|
||||
.iter()
|
||||
.map(|e| (e.name.clone(), e.uid.clone()))
|
||||
.collect();
|
||||
dialog.connect_response(Some("leave"), move |_, _| {
|
||||
let count = uids.len();
|
||||
let count = targets.len();
|
||||
let items = targets
|
||||
.iter()
|
||||
.map(|(name, uid)| BatchItem {
|
||||
name: name.clone(),
|
||||
uid: uid.clone(),
|
||||
request: |uid| Request::LeaveShared { uid },
|
||||
})
|
||||
.collect();
|
||||
let text = BatchText {
|
||||
failed: gettext_noop("Couldn't leave the shared item"),
|
||||
partial: |went, total| {
|
||||
ngettext_f(
|
||||
"Left {went} of {n} Shared Item",
|
||||
"Left {went} of {n} Shared Items",
|
||||
total,
|
||||
&[("went", &went.to_string())],
|
||||
)
|
||||
},
|
||||
};
|
||||
run_requests(
|
||||
&ui_c,
|
||||
uids.iter()
|
||||
.map(|uid| Request::LeaveShared { uid: uid.clone() })
|
||||
.collect(),
|
||||
gettext_noop("Couldn't leave the shared item"),
|
||||
move |ui| {
|
||||
items,
|
||||
text,
|
||||
Rc::new(move |ui| {
|
||||
load_shared(ui);
|
||||
toast(
|
||||
ui,
|
||||
@@ -975,50 +995,158 @@ pub(crate) fn prompt_leave_shared(ui: &Rc<Ui>, entries: &[DirEntry]) {
|
||||
&[],
|
||||
),
|
||||
);
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
dialog.present(ui_window(ui).as_ref());
|
||||
}
|
||||
|
||||
/// Send `requests` one after the other, stopping at the first failure, which
|
||||
/// is reported under `failed` (an untranslated msgid). `done` runs once all
|
||||
/// succeeded. After a failure the page on screen is reloaded instead, since
|
||||
/// the requests before it went through.
|
||||
pub(crate) fn run_requests(
|
||||
ui: &Rc<Ui>,
|
||||
requests: Vec<Request>,
|
||||
failed: &'static str,
|
||||
done: impl FnOnce(&Rc<Ui>) + 'static,
|
||||
) {
|
||||
/// What became of one request of a batch.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) enum Outcome {
|
||||
Done,
|
||||
/// The service refused it, with this message.
|
||||
Failed(String),
|
||||
/// The service did not answer, so it may or may not have happened.
|
||||
Unknown,
|
||||
/// Not sent: the service had stopped answering before its turn.
|
||||
NotTried,
|
||||
}
|
||||
|
||||
/// One item of a batch: its name, as the summary lists it, and the uid its
|
||||
/// request acts on. A retry sends the request again, so it is built from the
|
||||
/// uid each time.
|
||||
pub(crate) struct BatchItem {
|
||||
pub(crate) name: String,
|
||||
pub(crate) uid: String,
|
||||
pub(crate) request: fn(String) -> Request,
|
||||
}
|
||||
|
||||
/// What runs once every item of a batch went through. Kept for a retry.
|
||||
pub(crate) type BatchDone = Rc<dyn Fn(&Rc<Ui>)>;
|
||||
|
||||
/// The texts a batch reports with.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct BatchText {
|
||||
/// The failure title, an untranslated msgid.
|
||||
pub(crate) failed: &'static str,
|
||||
/// The heading of a batch that partly went through, from how many items
|
||||
/// went through and how many there were.
|
||||
pub(crate) partial: fn(u64, u64) -> String,
|
||||
}
|
||||
|
||||
/// Send each request in turn. `done` runs once all succeeded.
|
||||
///
|
||||
/// A request the service refuses does not stop the others, since each item
|
||||
/// stands on its own. Once the service stops answering, the rest are not
|
||||
/// sent. When any item did not go through, the page on screen is reloaded,
|
||||
/// so a lost reply shows its real state, and a summary names every item that
|
||||
/// did not, with a way to try those again. A batch of one reports as before,
|
||||
/// with a toast.
|
||||
pub(crate) fn run_requests(ui: &Rc<Ui>, items: Vec<BatchItem>, text: BatchText, done: BatchDone) {
|
||||
ui.busy_begin();
|
||||
let ui = ui.clone();
|
||||
let socket = ui.dirs.control_socket();
|
||||
glib::spawn_future_local(async move {
|
||||
for req in requests {
|
||||
let result = spawn_request(socket.clone(), req).recv().await;
|
||||
let error = match result {
|
||||
Ok(Ok(Response::Ok { .. })) => continue,
|
||||
Ok(Ok(Response::Error { message, kind })) => Some((message, kind)),
|
||||
_ => None,
|
||||
};
|
||||
ui.busy_end();
|
||||
reload_current_page(&ui);
|
||||
match error {
|
||||
Some((message, kind)) => toast_failure(&ui, &gettext(failed), &message, kind),
|
||||
let mut outcomes = Vec::with_capacity(items.len());
|
||||
let mut first_error = None;
|
||||
let mut answering = true;
|
||||
for item in &items {
|
||||
if !answering {
|
||||
outcomes.push(Outcome::NotTried);
|
||||
continue;
|
||||
}
|
||||
let result = spawn_request(socket.clone(), (item.request)(item.uid.clone()))
|
||||
.recv()
|
||||
.await;
|
||||
outcomes.push(match result {
|
||||
Ok(Ok(Response::Ok { .. })) => Outcome::Done,
|
||||
Ok(Ok(Response::Error { message, kind })) => {
|
||||
first_error.get_or_insert((message.clone(), kind));
|
||||
Outcome::Failed(message)
|
||||
}
|
||||
_ => {
|
||||
answering = false;
|
||||
Outcome::Unknown
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.busy_end();
|
||||
if outcomes.iter().all(|outcome| *outcome == Outcome::Done) {
|
||||
done(&ui);
|
||||
return;
|
||||
}
|
||||
reload_current_page(&ui);
|
||||
if items.len() == 1 {
|
||||
match first_error {
|
||||
Some((message, kind)) => toast_failure(&ui, &gettext(text.failed), &message, kind),
|
||||
None => toast_error(
|
||||
&ui,
|
||||
&gettext(failed),
|
||||
&gettext(text.failed),
|
||||
&gettext("The Proton Drive service didn't respond."),
|
||||
),
|
||||
}
|
||||
return;
|
||||
}
|
||||
ui.busy_end();
|
||||
done(&ui);
|
||||
present_batch_summary(&ui, items, outcomes, text, done);
|
||||
});
|
||||
}
|
||||
|
||||
/// Name every item of a batch that did not go through, and offer to try
|
||||
/// them again.
|
||||
fn present_batch_summary(
|
||||
ui: &Rc<Ui>,
|
||||
items: Vec<BatchItem>,
|
||||
outcomes: Vec<Outcome>,
|
||||
text: BatchText,
|
||||
done: BatchDone,
|
||||
) {
|
||||
let total = items.len() as u64;
|
||||
let went = outcomes.iter().filter(|o| **o == Outcome::Done).count() as u64;
|
||||
let list = gtk4::ListBox::builder()
|
||||
.selection_mode(gtk4::SelectionMode::None)
|
||||
.css_classes(["boxed-list"])
|
||||
.build();
|
||||
let mut again = Vec::new();
|
||||
for (item, outcome) in items.into_iter().zip(&outcomes) {
|
||||
let state = match outcome {
|
||||
Outcome::Done => continue,
|
||||
// Translators: {error} is the reason the service gave.
|
||||
Outcome::Failed(error) => gettext_f("Refused: {error}", &[("error", error)]),
|
||||
Outcome::Unknown => {
|
||||
gettext("The service didn't answer. The page shows whether it went through.")
|
||||
}
|
||||
Outcome::NotTried => gettext("Not tried yet"),
|
||||
};
|
||||
list.append(
|
||||
&adw::ActionRow::builder()
|
||||
.title(glib::markup_escape_text(&item.name).as_str())
|
||||
.subtitle(glib::markup_escape_text(&state).as_str())
|
||||
.subtitle_lines(3)
|
||||
.build(),
|
||||
);
|
||||
again.push(item);
|
||||
}
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.heading((text.partial)(went, total))
|
||||
.body(gettext("These items did not go through:"))
|
||||
.extra_child(&list)
|
||||
.build();
|
||||
dialog.add_response("close", &gettext("Close"));
|
||||
dialog.add_response("again", &gettext("Try Again"));
|
||||
dialog.set_response_appearance("again", adw::ResponseAppearance::Suggested);
|
||||
dialog.set_default_response(Some("close"));
|
||||
dialog.set_close_response("close");
|
||||
let ui_c = ui.clone();
|
||||
let again = RefCell::new(Some(again));
|
||||
dialog.connect_response(Some("again"), move |_, _| {
|
||||
if let Some(items) = again.borrow_mut().take() {
|
||||
run_requests(&ui_c, items, text, done.clone());
|
||||
}
|
||||
});
|
||||
dialog.present(ui_window(ui).as_ref());
|
||||
}
|
||||
|
||||
/// Confirm, then remove a saved link. The shared item itself is untouched.
|
||||
pub(crate) fn prompt_remove_bookmark(ui: &Rc<Ui>, token: &str, name: &str) {
|
||||
let win = ui_window(ui);
|
||||
|
||||
@@ -466,6 +466,16 @@ fn rebind_rows(ui: &Rc<Ui>, uids: &HashSet<String>) {
|
||||
/// node by uid, so every shared item can be managed from here.
|
||||
fn shared_by_me_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
|
||||
let mut menu = ActionMenu::new();
|
||||
let now = glib::real_time() / 1_000_000;
|
||||
let link = find_item(&ui.shared_by_me.items, &entry.uid).and_then(|item| item.link);
|
||||
// An expired link has nothing to copy or open; what it needs is a new
|
||||
// expiry, which the Share dialog's link settings give it.
|
||||
if link.as_ref().is_some_and(|link| link_expired(link, now)) {
|
||||
let (ui_c, entry_c) = (ui.clone(), entry.clone());
|
||||
menu.item(&gettext("Edit Link Expiry…"), move || {
|
||||
open_share_dialog(&ui_c, &entry_c)
|
||||
});
|
||||
}
|
||||
let (ui_c, entry_c) = (ui.clone(), entry.clone());
|
||||
menu.item(&gettext("Manage Access…"), move || {
|
||||
open_share_dialog(&ui_c, &entry_c)
|
||||
@@ -481,9 +491,7 @@ fn shared_by_me_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
|
||||
show_in_my_files(&ui_c, &entry_c)
|
||||
});
|
||||
}
|
||||
let now = glib::real_time() / 1_000_000;
|
||||
let url = find_item(&ui.shared_by_me.items, &entry.uid)
|
||||
.and_then(|item| item.link)
|
||||
let url = link
|
||||
.filter(|link| !link_expired(link, now))
|
||||
.and_then(|link| link.url);
|
||||
if let Some(url) = url {
|
||||
@@ -564,21 +572,41 @@ pub(crate) fn prompt_stop_sharing(ui: &Rc<Ui>, entries: &[DirEntry]) {
|
||||
&[],
|
||||
),
|
||||
};
|
||||
let uids: Vec<String> = entries.iter().map(|e| e.uid.clone()).collect();
|
||||
let targets: Vec<(String, String)> = entries
|
||||
.iter()
|
||||
.map(|e| (e.name.clone(), e.uid.clone()))
|
||||
.collect();
|
||||
dialog.connect_response(Some("stop"), move |_, _| {
|
||||
let done = done.clone();
|
||||
let stopped = uids.clone();
|
||||
let stopped: Vec<String> = targets.iter().map(|(_, uid)| uid.clone()).collect();
|
||||
let items = targets
|
||||
.iter()
|
||||
.map(|(name, uid)| BatchItem {
|
||||
name: name.clone(),
|
||||
uid: uid.clone(),
|
||||
request: |uid| Request::StopSharingByUid { uid },
|
||||
})
|
||||
.collect();
|
||||
let text = BatchText {
|
||||
failed: gettext_noop("Couldn't stop sharing"),
|
||||
partial: |went, total| {
|
||||
ngettext_f(
|
||||
"Stopped Sharing {went} of {n} Item",
|
||||
"Stopped Sharing {went} of {n} Items",
|
||||
total,
|
||||
&[("went", &went.to_string())],
|
||||
)
|
||||
},
|
||||
};
|
||||
run_requests(
|
||||
&ui_c,
|
||||
uids.iter()
|
||||
.map(|uid| Request::StopSharingByUid { uid: uid.clone() })
|
||||
.collect(),
|
||||
gettext_noop("Couldn't stop sharing"),
|
||||
move |ui| {
|
||||
items,
|
||||
text,
|
||||
Rc::new(move |ui| {
|
||||
forget_shared_by_me(ui, &stopped);
|
||||
reload_listing(ui);
|
||||
toast(ui, &done);
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
dialog.present(ui_window(ui).as_ref());
|
||||
|
||||
@@ -14,6 +14,10 @@ pub(crate) struct TrashState {
|
||||
/// The bottom bar acting on the selection; revealed while anything is selected.
|
||||
pub(crate) selection_bar: gtk4::Revealer,
|
||||
pub(crate) selection_label: gtk4::Label,
|
||||
/// The bar's actions, labelled for what they act on (see
|
||||
/// [`sync_trash_selection`]).
|
||||
pub(crate) restore_selected: gtk4::Button,
|
||||
pub(crate) delete_selected: gtk4::Button,
|
||||
/// Runs the loads; the rows stay up while one runs.
|
||||
pub(crate) loader: Rc<Loader>,
|
||||
/// Back, the breadcrumb and the search entry over the list.
|
||||
@@ -312,11 +316,13 @@ fn trash_entry_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
|
||||
&& !in_trash(ui, &entry.uid)
|
||||
&& let Some(folder) = outer_folder(ui)
|
||||
{
|
||||
// Went to the trash with the folder, so only the folder goes back.
|
||||
// Went to the trash with the folder, so only the folder goes back,
|
||||
// and only the folder can be deleted for good.
|
||||
menu.labelled_section(&gettext("Deleted with its folder"));
|
||||
let ui_c = ui.clone();
|
||||
let label = gettext_f(
|
||||
// Translators: {name} is a folder name.
|
||||
"Restore “{name}”",
|
||||
"Restore Folder “{name}”",
|
||||
&[("name", &folder.name)],
|
||||
);
|
||||
menu.item(&label, move || {
|
||||
@@ -324,8 +330,16 @@ fn trash_entry_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
|
||||
});
|
||||
return menu;
|
||||
}
|
||||
let restore = match location_key(&entry.uid) {
|
||||
// A location row stands for everything deleted from that folder.
|
||||
Some(_) => {
|
||||
let n = trashed_targets(ui, std::slice::from_ref(entry)).len() as u64;
|
||||
ngettext_f("Restore {n} Item", "Restore {n} Items", n, &[])
|
||||
}
|
||||
None => pgettext("verb", "Restore"),
|
||||
};
|
||||
let (ui_c, entry_c) = (ui.clone(), entry.clone());
|
||||
menu.item(&pgettext("verb", "Restore"), move || {
|
||||
menu.item(&restore, move || {
|
||||
restore_entries(&ui_c, std::slice::from_ref(&entry_c))
|
||||
});
|
||||
menu.section();
|
||||
@@ -374,18 +388,52 @@ fn trash_background_menu(ui: &Rc<Ui>) -> ActionMenu {
|
||||
menu
|
||||
}
|
||||
|
||||
/// Reveal the selection bar while anything is selected and count what is.
|
||||
/// Reveal the selection bar while anything is selected, count what is, and
|
||||
/// label its actions for what they act on, which is not always the selection.
|
||||
fn sync_trash_selection(ui: &Rc<Ui>) {
|
||||
let count = ui.trash.files.selection.selection().size() as usize;
|
||||
ui.trash.selection_bar.set_reveal_child(count > 0);
|
||||
if count > 0 {
|
||||
ui.trash.selection_label.set_label(&ngettext_f(
|
||||
"{n} item selected",
|
||||
"{n} items selected",
|
||||
count as u64,
|
||||
&[],
|
||||
));
|
||||
if count == 0 {
|
||||
return;
|
||||
}
|
||||
ui.trash.selection_label.set_label(&ngettext_f(
|
||||
"{n} item selected",
|
||||
"{n} items selected",
|
||||
count as u64,
|
||||
&[],
|
||||
));
|
||||
let selected = ui.trash.files.selected();
|
||||
let targets = {
|
||||
let all = ui.trash.all.borrow();
|
||||
resolve_targets(&all, outer_folder(ui).as_ref(), &selected)
|
||||
};
|
||||
let (restore, deletable) = match (&targets.inherited, targets.own.len()) {
|
||||
(Some(folder), 0) => (
|
||||
// Translators: {name} is a folder name.
|
||||
gettext_f("Restore Folder “{name}”", &[("name", &folder.name)]),
|
||||
false,
|
||||
),
|
||||
(inherited, own) if inherited.is_some() || own != count => {
|
||||
let n = (own + usize::from(inherited.is_some())) as u64;
|
||||
(
|
||||
ngettext_f("Restore {n} Item", "Restore {n} Items", n, &[]),
|
||||
own > 0,
|
||||
)
|
||||
}
|
||||
_ => (pgettext("verb", "Restore"), true),
|
||||
};
|
||||
ui.trash.restore_selected.set_label(&restore);
|
||||
let delete = &ui.trash.delete_selected;
|
||||
delete.set_sensitive(deletable);
|
||||
delete.set_tooltip_text(
|
||||
(!deletable)
|
||||
.then(|| {
|
||||
gettext(
|
||||
"These went to the trash with their folder. Only the whole folder can be deleted permanently, from the top of the trash.",
|
||||
)
|
||||
})
|
||||
.as_deref(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Fetch the trash listing and repaint the page.
|
||||
@@ -727,14 +775,24 @@ fn outer_folder(ui: &Ui) -> Option<DirEntry> {
|
||||
ui.trash.all.borrow().iter().find(|e| e.uid == uid).cloned()
|
||||
}
|
||||
|
||||
/// What acting on `entries` acts on: a location row stands for everything
|
||||
/// deleted from that folder, and an item that went with its folder for the
|
||||
/// folder. Each node once.
|
||||
fn trashed_targets(ui: &Ui, entries: &[DirEntry]) -> Vec<DirEntry> {
|
||||
let all = ui.trash.all.borrow();
|
||||
let outer = outer_folder(ui);
|
||||
/// What acting on a selection acts on.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct Targets {
|
||||
/// The trashed items themselves: each selected item that is in the trash
|
||||
/// on its own, and for a location row everything deleted from that folder.
|
||||
own: Vec<DirEntry>,
|
||||
/// The open trashed folder, when the selection holds items that went to
|
||||
/// the trash with it. They can only go back with the folder, so a restore
|
||||
/// restores it. A permanent deletion does not: deleting the folder for
|
||||
/// good takes an explicit choice of the folder itself.
|
||||
inherited: Option<DirEntry>,
|
||||
}
|
||||
|
||||
/// Resolve `entries` against the trash listing `all`, inside `outer` when a
|
||||
/// trashed folder is open. Each node once.
|
||||
fn resolve_targets(all: &[DirEntry], outer: Option<&DirEntry>, entries: &[DirEntry]) -> Targets {
|
||||
let mut seen = HashSet::new();
|
||||
let mut targets = Vec::new();
|
||||
let mut targets = Targets::default();
|
||||
for entry in entries {
|
||||
let picked: Vec<DirEntry> = if let Some(key) = location_key(&entry.uid) {
|
||||
all.iter()
|
||||
@@ -744,17 +802,38 @@ fn trashed_targets(ui: &Ui, entries: &[DirEntry]) -> Vec<DirEntry> {
|
||||
} else if all.iter().any(|e| e.uid == entry.uid) {
|
||||
vec![entry.clone()]
|
||||
} else {
|
||||
outer.clone().into_iter().collect()
|
||||
if targets.inherited.is_none() {
|
||||
targets.inherited = outer.cloned();
|
||||
}
|
||||
Vec::new()
|
||||
};
|
||||
for target in picked {
|
||||
if seen.insert(target.uid.clone()) {
|
||||
targets.push(target);
|
||||
targets.own.push(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The folder may be selected too, at a level that shows it.
|
||||
if let Some(folder) = &targets.inherited
|
||||
&& seen.contains(&folder.uid)
|
||||
{
|
||||
targets.inherited = None;
|
||||
}
|
||||
targets
|
||||
}
|
||||
|
||||
/// What a restore of `entries` restores: the items, and the open folder for
|
||||
/// those that went to the trash with it.
|
||||
fn trashed_targets(ui: &Ui, entries: &[DirEntry]) -> Vec<DirEntry> {
|
||||
let targets = {
|
||||
let all = ui.trash.all.borrow();
|
||||
resolve_targets(&all, outer_folder(ui).as_ref(), entries)
|
||||
};
|
||||
let mut restore = targets.own;
|
||||
restore.extend(targets.inherited);
|
||||
restore
|
||||
}
|
||||
|
||||
/// Rebuild the path bar for `nav`: "Trash", then each place down to the
|
||||
/// current one. Hidden at the top, where there is nowhere to go back to.
|
||||
fn repaint_trash_crumb(ui: &Rc<Ui>) {
|
||||
@@ -850,9 +929,26 @@ fn common_origin(entries: &[DirEntry]) -> Option<String> {
|
||||
}
|
||||
|
||||
/// Confirm, then permanently delete trashed entries. Irreversible, so it asks.
|
||||
///
|
||||
/// Only what was selected is deleted. An item that went to the trash with its
|
||||
/// folder cannot be deleted on its own, and is not taken to mean its folder.
|
||||
pub(crate) fn prompt_delete_forever(ui: &Rc<Ui>, entries: &[DirEntry]) {
|
||||
let entries = &trashed_targets(ui, entries)[..];
|
||||
let targets = {
|
||||
let all = ui.trash.all.borrow();
|
||||
resolve_targets(&all, outer_folder(ui).as_ref(), entries)
|
||||
};
|
||||
let entries = &targets.own[..];
|
||||
if entries.is_empty() {
|
||||
if let Some(folder) = targets.inherited {
|
||||
toast(
|
||||
ui,
|
||||
// Translators: {name} is a folder name.
|
||||
&gettext_f(
|
||||
"These went to the trash with “{name}”. Delete the whole folder from the top of the trash.",
|
||||
&[("name", &folder.name)],
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let win = ui_window(ui);
|
||||
@@ -973,6 +1069,55 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn uids(entries: &[DirEntry]) -> Vec<&str> {
|
||||
entries.iter().map(|e| e.uid.as_str()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_item_deleted_with_its_folder_restores_the_folder_and_deletes_nothing() {
|
||||
let projects = DirEntry {
|
||||
is_dir: true,
|
||||
..trashed("projects", 5, 1, Some("Work"))
|
||||
};
|
||||
let all = vec![projects.clone()];
|
||||
// Two siblings inside the open trashed folder: neither is in the trash
|
||||
// on its own.
|
||||
let a = trashed("a.txt", 5, 1, None);
|
||||
let b = trashed("b.txt", 5, 1, None);
|
||||
|
||||
let targets = resolve_targets(&all, Some(&projects), &[a, b]);
|
||||
|
||||
assert!(targets.own.is_empty(), "nothing of its own to delete");
|
||||
assert_eq!(targets.inherited, Some(projects));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_location_row_stands_for_every_item_deleted_from_that_folder() {
|
||||
let all = vec![
|
||||
trashed("one", 3, 1, Some("Work")),
|
||||
trashed("two", 2, 1, Some("Work")),
|
||||
trashed("other", 1, 1, Some("Home")),
|
||||
inside("nested", "one"),
|
||||
];
|
||||
let row = location_row(Some("Work".into()));
|
||||
|
||||
let targets = resolve_targets(&all, None, &[row]);
|
||||
|
||||
assert_eq!(uids(&targets.own), ["one", "two"]);
|
||||
assert_eq!(targets.inherited, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_item_counts_once_and_stays_itself() {
|
||||
let all = vec![trashed("one", 3, 1, Some("Work"))];
|
||||
let one = all[0].clone();
|
||||
|
||||
let targets = resolve_targets(&all, None, &[one.clone(), one]);
|
||||
|
||||
assert_eq!(uids(&targets.own), ["one"]);
|
||||
assert_eq!(targets.inherited, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locations_group_top_level_items_by_folder() {
|
||||
let all = vec![
|
||||
|
||||
@@ -669,30 +669,70 @@ pub(crate) fn repaint_share_link(state: &Rc<ShareDialog>, link: Option<&PublicLi
|
||||
|
||||
match link {
|
||||
Some(link) => {
|
||||
let now = glib::real_time() / 1_000_000;
|
||||
let url = link.url.clone().unwrap_or_default();
|
||||
let role = role_label(&link.role).unwrap_or_else(|| capitalize(&link.role));
|
||||
// Translators: {role} is the link's role, such as "Viewer".
|
||||
let mut subtitle = gettext_f("Anyone with the link ({role})", &[("role", &role)]);
|
||||
if link.has_password {
|
||||
subtitle.push_str(" · ");
|
||||
subtitle.push_str(&gettext("password-protected"));
|
||||
}
|
||||
if let Some(expires) = link.expires {
|
||||
subtitle.push_str(" · ");
|
||||
subtitle.push_str(&link_expiry_label(expires, glib::real_time() / 1_000_000));
|
||||
}
|
||||
let expired = link.expires.is_some_and(|at| at <= now);
|
||||
// The row says how the link works, not where it is: the address
|
||||
// is a key, and someone showing their screen should not hand it
|
||||
// out by opening the dialog.
|
||||
let row = adw::ActionRow::builder()
|
||||
.title(if url.is_empty() {
|
||||
gettext("Public link")
|
||||
} else {
|
||||
url.clone()
|
||||
})
|
||||
.subtitle(&subtitle)
|
||||
.title(link_row_title(link.role == "editor", expired))
|
||||
.subtitle(link_policy(
|
||||
link.role == "editor",
|
||||
link.has_password,
|
||||
link.expires,
|
||||
now,
|
||||
))
|
||||
.use_markup(false)
|
||||
.build();
|
||||
row.add_css_class("property");
|
||||
let (settings, expiry_drop) = link_settings_row(state, link);
|
||||
|
||||
// The address, hidden until asked for. Every repaint hides it again.
|
||||
let address = adw::ActionRow::builder()
|
||||
.title(&url)
|
||||
.title_selectable(true)
|
||||
.use_markup(false)
|
||||
.visible(false)
|
||||
.build();
|
||||
address.add_css_class("monospace");
|
||||
|
||||
if expired {
|
||||
// An expired link gives nothing to copy: whoever gets it sees an
|
||||
// error. What the owner can do is give it a new expiry.
|
||||
let edit = gtk4::Button::builder()
|
||||
.label(gettext("Edit Expiry"))
|
||||
.valign(gtk4::Align::Center)
|
||||
.build();
|
||||
let (settings, expiry_drop) = (settings.clone(), expiry_drop.clone());
|
||||
edit.connect_clicked(move |_| {
|
||||
settings.set_expanded(true);
|
||||
expiry_drop.grab_focus();
|
||||
});
|
||||
row.add_suffix(&edit);
|
||||
} else if !url.is_empty() {
|
||||
let reveal = gtk4::ToggleButton::builder()
|
||||
.icon_name("view-reveal-symbolic")
|
||||
.tooltip_text(gettext("Show link address"))
|
||||
.valign(gtk4::Align::Center)
|
||||
.build();
|
||||
reveal.add_css_class("flat");
|
||||
let address_t = address.clone();
|
||||
reveal.connect_toggled(move |btn| {
|
||||
address_t.set_visible(btn.is_active());
|
||||
btn.set_icon_name(if btn.is_active() {
|
||||
"view-conceal-symbolic"
|
||||
} else {
|
||||
"view-reveal-symbolic"
|
||||
});
|
||||
btn.set_tooltip_text(Some(&if btn.is_active() {
|
||||
gettext("Hide link address")
|
||||
} else {
|
||||
gettext("Show link address")
|
||||
}));
|
||||
});
|
||||
row.add_suffix(&reveal);
|
||||
|
||||
if !url.is_empty() {
|
||||
let copy = gtk4::Button::builder()
|
||||
.icon_name("edit-copy-symbolic")
|
||||
.tooltip_text(gettext("Copy link"))
|
||||
@@ -744,8 +784,8 @@ pub(crate) fn repaint_share_link(state: &Rc<ShareDialog>, link: Option<&PublicLi
|
||||
|
||||
state.link_group.add(&row);
|
||||
rows.push(row.upcast());
|
||||
|
||||
let settings = link_settings_row(state, link);
|
||||
state.link_group.add(&address);
|
||||
rows.push(address.upcast());
|
||||
state.link_group.add(&settings);
|
||||
rows.push(settings.upcast());
|
||||
}
|
||||
@@ -757,11 +797,45 @@ pub(crate) fn repaint_share_link(state: &Rc<ShareDialog>, link: Option<&PublicLi
|
||||
let expiry_names: Vec<String> =
|
||||
LINK_EXPIRY.iter().map(|(name, _)| gettext(name)).collect();
|
||||
let (expiry_row, expiry_drop) = dropdown_row(&gettext("Expires"), &expiry_names, 0);
|
||||
// How the link will work, right above the button that makes it.
|
||||
let now = glib::real_time() / 1_000_000;
|
||||
let summary = adw::ActionRow::builder()
|
||||
.title(gettext("The new link"))
|
||||
.subtitle(link_policy(false, false, None, now))
|
||||
.use_markup(false)
|
||||
.build();
|
||||
summary.add_css_class("property");
|
||||
let create = group_button(&gettext("Create Public Link"));
|
||||
|
||||
// Enter in the password field creates the link.
|
||||
let btn = create.clone();
|
||||
pw_row.connect_entry_activated(move |_| btn.emit_clicked());
|
||||
let refresh: Rc<dyn Fn()> = {
|
||||
let (summary, role_drop, pw_row, expiry_drop) = (
|
||||
summary.clone(),
|
||||
role_drop.clone(),
|
||||
pw_row.clone(),
|
||||
expiry_drop.clone(),
|
||||
);
|
||||
Rc::new(move || {
|
||||
let now = glib::real_time() / 1_000_000;
|
||||
summary.set_subtitle(&link_policy(
|
||||
role_drop.selected() == 1,
|
||||
!pw_row.text().is_empty(),
|
||||
link_expiry_at(expiry_drop.selected(), now),
|
||||
now,
|
||||
));
|
||||
})
|
||||
};
|
||||
let r = refresh.clone();
|
||||
role_drop.connect_selected_notify(move |_| r());
|
||||
let r = refresh.clone();
|
||||
pw_row.connect_changed(move |_| r());
|
||||
expiry_drop.connect_selected_notify(move |_| refresh());
|
||||
|
||||
// Enter in the password field moves on to the expiry, which comes
|
||||
// next: creating the link there would skip it.
|
||||
let next = expiry_drop.clone();
|
||||
pw_row.connect_entry_activated(move |_| {
|
||||
next.grab_focus();
|
||||
});
|
||||
|
||||
let state_c = Rc::downgrade(state);
|
||||
let pw_for = pw_row.clone();
|
||||
@@ -787,124 +861,265 @@ pub(crate) fn repaint_share_link(state: &Rc<ShareDialog>, link: Option<&PublicLi
|
||||
state.link_group.add(&role_row);
|
||||
state.link_group.add(&pw_row);
|
||||
state.link_group.add(&expiry_row);
|
||||
state.link_group.add(&summary);
|
||||
state.link_group.add(&create);
|
||||
rows.push(role_row.upcast());
|
||||
rows.push(pw_row.upcast());
|
||||
rows.push(expiry_row.upcast());
|
||||
rows.push(summary.upcast());
|
||||
rows.push(create.upcast());
|
||||
}
|
||||
}
|
||||
*state.link_rows.borrow_mut() = rows;
|
||||
}
|
||||
|
||||
/// The settings of an existing link, collapsed under one row. Each control
|
||||
/// applies at once, the way a member's role does. While a change is on its way
|
||||
/// the whole row is insensitive: the daemon fills in what a change keeps from
|
||||
/// the link as it stands, so two changes in flight could undo each other.
|
||||
fn link_settings_row(state: &Rc<ShareDialog>, link: &PublicLinkInfo) -> adw::ExpanderRow {
|
||||
/// What the owner has chosen in an existing link's settings and not saved yet.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct LinkDraft {
|
||||
/// Anyone with the link can edit.
|
||||
pub(crate) editor: bool,
|
||||
/// The chosen entry of [`link_expiry_choices`].
|
||||
pub(crate) expiry: u32,
|
||||
/// The link asks for a password.
|
||||
pub(crate) protect: bool,
|
||||
/// A new password; empty keeps the one the link has.
|
||||
pub(crate) password: String,
|
||||
}
|
||||
|
||||
impl LinkDraft {
|
||||
/// The draft that changes nothing about `link`.
|
||||
pub(crate) fn of(link: &PublicLinkInfo) -> Self {
|
||||
Self {
|
||||
editor: link.role == "editor",
|
||||
expiry: 0,
|
||||
protect: link.has_password,
|
||||
password: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The one update that saving a [`LinkDraft`] sends.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct LinkEdit {
|
||||
pub(crate) role: Option<String>,
|
||||
pub(crate) password: LinkChange<String>,
|
||||
pub(crate) expires: LinkChange<i64>,
|
||||
}
|
||||
|
||||
/// What saving `draft` would ask of `link`: `Ok(None)` when it changes
|
||||
/// nothing, `Err(())` when it cannot be saved yet. That is a password asked for
|
||||
/// on a link that has none, with no password typed.
|
||||
pub(crate) fn link_edit(
|
||||
link: &PublicLinkInfo,
|
||||
draft: &LinkDraft,
|
||||
now: i64,
|
||||
) -> Result<Option<LinkEdit>, ()> {
|
||||
let role = (draft.editor != (link.role == "editor"))
|
||||
.then(|| if draft.editor { "editor" } else { "viewer" }.to_string());
|
||||
let password = match (draft.protect, draft.password.is_empty(), link.has_password) {
|
||||
(false, _, true) => LinkChange::Remove,
|
||||
(false, _, false) | (true, true, true) => LinkChange::Keep,
|
||||
(true, true, false) => return Err(()),
|
||||
(true, false, _) => LinkChange::Set(draft.password.clone()),
|
||||
};
|
||||
let expires = link_expiry_change(draft.expiry, link.expires, now);
|
||||
let edit = LinkEdit {
|
||||
role,
|
||||
password,
|
||||
expires,
|
||||
};
|
||||
let unchanged = edit.role.is_none()
|
||||
&& edit.password == LinkChange::Keep
|
||||
&& edit.expires == LinkChange::Keep;
|
||||
Ok((!unchanged).then_some(edit))
|
||||
}
|
||||
|
||||
/// The title of an existing link's row: what kind of link it is, never its
|
||||
/// address.
|
||||
pub(crate) fn link_row_title(editor: bool, expired: bool) -> String {
|
||||
match (expired, editor) {
|
||||
(true, _) => gettext("Expired public link"),
|
||||
(false, true) => gettext("Public editor link"),
|
||||
(false, false) => gettext("Public viewer link"),
|
||||
}
|
||||
}
|
||||
|
||||
/// How a link works, in one line: who can do what, the password, the expiry.
|
||||
pub(crate) fn link_policy(editor: bool, password: bool, expires: Option<i64>, now: i64) -> String {
|
||||
let mut parts = vec![if editor {
|
||||
gettext("Anyone with the link can edit")
|
||||
} else {
|
||||
gettext("Anyone with the link can view")
|
||||
}];
|
||||
parts.push(if password {
|
||||
gettext("password-protected")
|
||||
} else {
|
||||
gettext("no password")
|
||||
});
|
||||
parts.push(match expires {
|
||||
Some(at) => link_expiry_label(at, now),
|
||||
None => gettext("never expires"),
|
||||
});
|
||||
parts.join(" · ")
|
||||
}
|
||||
|
||||
/// How `link` works once `edit` is saved.
|
||||
fn link_policy_after(
|
||||
link: &PublicLinkInfo,
|
||||
draft: &LinkDraft,
|
||||
edit: &LinkEdit,
|
||||
now: i64,
|
||||
) -> String {
|
||||
let expires = match edit.expires {
|
||||
LinkChange::Keep => link.expires,
|
||||
LinkChange::Remove => None,
|
||||
LinkChange::Set(at) => Some(at),
|
||||
};
|
||||
link_policy(draft.editor, draft.protect, expires, now)
|
||||
}
|
||||
|
||||
/// The settings of an existing link, collapsed under one row. Nothing reaches
|
||||
/// Drive until Save: an owner turning a viewer link into an editor link with a
|
||||
/// password must not hand out editing before the password is set, so every
|
||||
/// change goes in one update. Closing the dialog drops what was not saved.
|
||||
/// Returns the row and its Expires dropdown, which an expired link's Edit
|
||||
/// Expiry button opens the row on.
|
||||
fn link_settings_row(
|
||||
state: &Rc<ShareDialog>,
|
||||
link: &PublicLinkInfo,
|
||||
) -> (adw::ExpanderRow, gtk4::DropDown) {
|
||||
let now = glib::real_time() / 1_000_000;
|
||||
let expander = adw::ExpanderRow::builder()
|
||||
.title(gettext("Link settings"))
|
||||
.subtitle(gettext(
|
||||
"Change who can edit, the password or the expiry. The link stays the same.",
|
||||
"Change who can edit, the password or the expiry, then save. The link stays the same.",
|
||||
))
|
||||
.build();
|
||||
let draft = Rc::new(RefCell::new(LinkDraft::of(link)));
|
||||
|
||||
let selected_role = u32::from(link.role == "editor");
|
||||
let (role_row, role_drop) = dropdown_row(&gettext("Link role"), &link_roles(), selected_role);
|
||||
let (state_w, expander_w, id) = (Rc::downgrade(state), expander.clone(), link.id.clone());
|
||||
role_drop.connect_selected_notify(move |d| {
|
||||
let Some(state) = state_w.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let role = if d.selected() == 1 {
|
||||
"editor"
|
||||
} else {
|
||||
"viewer"
|
||||
};
|
||||
let request = state.target.update_link(
|
||||
id.clone(),
|
||||
Some(role.into()),
|
||||
LinkChange::Keep,
|
||||
LinkChange::Keep,
|
||||
);
|
||||
share_dialog_update_link(&state, request, &expander_w);
|
||||
});
|
||||
let (role_row, role_drop) = dropdown_row(
|
||||
&gettext("Link role"),
|
||||
&link_roles(),
|
||||
u32::from(draft.borrow().editor),
|
||||
);
|
||||
expander.add_row(&role_row);
|
||||
|
||||
let current = link.expires;
|
||||
let (expiry_row, expiry_drop) =
|
||||
dropdown_row(&gettext("Expires"), &link_expiry_choices(current, now), 0);
|
||||
let (state_w, expander_w, id) = (Rc::downgrade(state), expander.clone(), link.id.clone());
|
||||
expiry_drop.connect_selected_notify(move |d| {
|
||||
let Some(state) = state_w.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let expires = link_expiry_change(d.selected(), current, glib::real_time() / 1_000_000);
|
||||
if expires == LinkChange::Keep {
|
||||
return;
|
||||
}
|
||||
let request = state
|
||||
.target
|
||||
.update_link(id.clone(), None, LinkChange::Keep, expires);
|
||||
share_dialog_update_link(&state, request, &expander_w);
|
||||
});
|
||||
let (expiry_row, expiry_drop) = dropdown_row(
|
||||
&gettext("Expires"),
|
||||
&link_expiry_choices(link.expires, now),
|
||||
0,
|
||||
);
|
||||
expander.add_row(&expiry_row);
|
||||
|
||||
let protect = adw::SwitchRow::builder()
|
||||
.title(gettext("Require a password"))
|
||||
.active(link.has_password)
|
||||
.build();
|
||||
expander.add_row(&protect);
|
||||
let pw_row = adw::PasswordEntryRow::builder()
|
||||
.title(if link.has_password {
|
||||
gettext("New password")
|
||||
gettext("New password (optional)")
|
||||
} else {
|
||||
gettext("Add a password")
|
||||
gettext("Password")
|
||||
})
|
||||
.show_apply_button(true)
|
||||
.visible(link.has_password)
|
||||
.build();
|
||||
let (state_w, expander_w, id) = (Rc::downgrade(state), expander.clone(), link.id.clone());
|
||||
pw_row.connect_apply(move |row| {
|
||||
expander.add_row(&pw_row);
|
||||
|
||||
// What the link will do once saved, right above the one action that sends it.
|
||||
let summary = adw::ActionRow::builder()
|
||||
.title(gettext("No changes"))
|
||||
.use_markup(false)
|
||||
.build();
|
||||
summary.add_css_class("property");
|
||||
let save = gtk4::Button::builder()
|
||||
.label(gettext("Save Link Settings"))
|
||||
.valign(gtk4::Align::Center)
|
||||
.sensitive(false)
|
||||
.build();
|
||||
save.add_css_class("suggested-action");
|
||||
summary.add_suffix(&save);
|
||||
expander.add_row(&summary);
|
||||
|
||||
let refresh: Rc<dyn Fn()> = {
|
||||
let (draft, link, summary, save) =
|
||||
(draft.clone(), link.clone(), summary.clone(), save.clone());
|
||||
Rc::new(move || {
|
||||
let draft = draft.borrow();
|
||||
let now = glib::real_time() / 1_000_000;
|
||||
match link_edit(&link, &draft, now) {
|
||||
Ok(None) => {
|
||||
summary.set_title(&gettext("No changes"));
|
||||
summary.set_subtitle("");
|
||||
save.set_sensitive(false);
|
||||
}
|
||||
Ok(Some(edit)) => {
|
||||
summary.set_title(&gettext("After saving"));
|
||||
summary.set_subtitle(&link_policy_after(&link, &draft, &edit, now));
|
||||
save.set_sensitive(true);
|
||||
}
|
||||
Err(()) => {
|
||||
summary.set_title(&gettext("Enter a password to save"));
|
||||
summary.set_subtitle("");
|
||||
save.set_sensitive(false);
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
{
|
||||
let (draft, refresh) = (draft.clone(), refresh.clone());
|
||||
role_drop.connect_selected_notify(move |d| {
|
||||
draft.borrow_mut().editor = d.selected() == 1;
|
||||
refresh();
|
||||
});
|
||||
}
|
||||
{
|
||||
let (draft, refresh) = (draft.clone(), refresh.clone());
|
||||
expiry_drop.connect_selected_notify(move |d| {
|
||||
draft.borrow_mut().expiry = d.selected();
|
||||
refresh();
|
||||
});
|
||||
}
|
||||
{
|
||||
let (draft, refresh, pw_row) = (draft.clone(), refresh.clone(), pw_row.clone());
|
||||
protect.connect_active_notify(move |s| {
|
||||
draft.borrow_mut().protect = s.is_active();
|
||||
pw_row.set_visible(s.is_active());
|
||||
if s.is_active() {
|
||||
pw_row.grab_focus();
|
||||
}
|
||||
refresh();
|
||||
});
|
||||
}
|
||||
{
|
||||
let (draft, refresh) = (draft.clone(), refresh.clone());
|
||||
pw_row.connect_changed(move |row| {
|
||||
draft.borrow_mut().password = row.text().to_string();
|
||||
refresh();
|
||||
});
|
||||
}
|
||||
{
|
||||
let save = save.clone();
|
||||
pw_row.connect_entry_activated(move |_| {
|
||||
if save.is_sensitive() {
|
||||
save.emit_clicked();
|
||||
}
|
||||
});
|
||||
}
|
||||
let (state_w, expander_w, link) = (Rc::downgrade(state), expander.clone(), link.clone());
|
||||
save.connect_clicked(move |_| {
|
||||
let Some(state) = state_w.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let password = row.text().to_string();
|
||||
if password.is_empty() {
|
||||
let Ok(Some(edit)) = link_edit(&link, &draft.borrow(), glib::real_time() / 1_000_000)
|
||||
else {
|
||||
return;
|
||||
}
|
||||
let request = state.target.update_link(
|
||||
id.clone(),
|
||||
None,
|
||||
LinkChange::Set(password),
|
||||
LinkChange::Keep,
|
||||
);
|
||||
};
|
||||
let request =
|
||||
state
|
||||
.target
|
||||
.update_link(link.id.clone(), edit.role, edit.password, edit.expires);
|
||||
share_dialog_update_link(&state, request, &expander_w);
|
||||
});
|
||||
expander.add_row(&pw_row);
|
||||
|
||||
if link.has_password {
|
||||
let remove = gtk4::Button::builder()
|
||||
.label(gettext("Remove"))
|
||||
.valign(gtk4::Align::Center)
|
||||
.build();
|
||||
remove.add_css_class("flat");
|
||||
let row = adw::ActionRow::builder()
|
||||
.title(gettext("Remove the password"))
|
||||
.subtitle(gettext(
|
||||
"Anyone with the link can open it without a password.",
|
||||
))
|
||||
.build();
|
||||
row.add_suffix(&remove);
|
||||
let (state_w, expander_w, id) = (Rc::downgrade(state), expander.clone(), link.id.clone());
|
||||
remove.connect_clicked(move |_| {
|
||||
let Some(state) = state_w.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let request =
|
||||
state
|
||||
.target
|
||||
.update_link(id.clone(), None, LinkChange::Remove, LinkChange::Keep);
|
||||
share_dialog_update_link(&state, request, &expander_w);
|
||||
});
|
||||
expander.add_row(&row);
|
||||
}
|
||||
expander
|
||||
(expander, expiry_drop)
|
||||
}
|
||||
|
||||
/// Send a link change, then reload the dialog: on success to show the link as
|
||||
@@ -1084,6 +1299,111 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
fn viewer_link(has_password: bool, expires: Option<i64>) -> PublicLinkInfo {
|
||||
PublicLinkInfo {
|
||||
id: "link".into(),
|
||||
url: Some("https://drive.proton.me/urls/X#y".into()),
|
||||
role: "viewer".into(),
|
||||
expires,
|
||||
has_password,
|
||||
created: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untouched_draft_sends_nothing() {
|
||||
let link = viewer_link(true, Some(2_000_000_000));
|
||||
assert_eq!(link_edit(&link, &LinkDraft::of(&link), 1_000), Ok(None));
|
||||
}
|
||||
|
||||
/// Editor and a password go in one update, so link holders never get edit
|
||||
/// access without the password.
|
||||
#[test]
|
||||
fn editor_and_a_password_are_saved_together() {
|
||||
let link = viewer_link(false, None);
|
||||
let draft = LinkDraft {
|
||||
editor: true,
|
||||
protect: true,
|
||||
password: "hunter2".into(),
|
||||
..LinkDraft::of(&link)
|
||||
};
|
||||
assert_eq!(
|
||||
link_edit(&link, &draft, 1_000),
|
||||
Ok(Some(LinkEdit {
|
||||
role: Some("editor".into()),
|
||||
password: LinkChange::Set("hunter2".into()),
|
||||
expires: LinkChange::Keep,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asking_for_a_password_without_one_cannot_be_saved() {
|
||||
let link = viewer_link(false, None);
|
||||
let draft = LinkDraft {
|
||||
editor: true,
|
||||
protect: true,
|
||||
..LinkDraft::of(&link)
|
||||
};
|
||||
assert_eq!(link_edit(&link, &draft, 1_000), Err(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_password_stays_and_a_dropped_one_goes() {
|
||||
let link = viewer_link(true, None);
|
||||
let keep = LinkDraft {
|
||||
expiry: 2,
|
||||
..LinkDraft::of(&link)
|
||||
};
|
||||
assert_eq!(
|
||||
link_edit(&link, &keep, 1_000).unwrap().unwrap().password,
|
||||
LinkChange::Keep
|
||||
);
|
||||
let drop = LinkDraft {
|
||||
protect: false,
|
||||
password: "typed then switched off".into(),
|
||||
..LinkDraft::of(&link)
|
||||
};
|
||||
assert_eq!(
|
||||
link_edit(&link, &drop, 1_000),
|
||||
Ok(Some(LinkEdit {
|
||||
role: None,
|
||||
password: LinkChange::Remove,
|
||||
expires: LinkChange::Keep,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_summary_shows_the_policy_after_saving() {
|
||||
let link = viewer_link(true, Some(2_000_000_000));
|
||||
let draft = LinkDraft {
|
||||
editor: true,
|
||||
expiry: 1,
|
||||
protect: false,
|
||||
..LinkDraft::of(&link)
|
||||
};
|
||||
let edit = link_edit(&link, &draft, 1_000).unwrap().unwrap();
|
||||
assert_eq!(
|
||||
link_policy_after(&link, &draft, &edit, 1_000),
|
||||
"Anyone with the link can edit · no password · never expires"
|
||||
);
|
||||
}
|
||||
|
||||
/// The row names the kind of link and never its address.
|
||||
#[test]
|
||||
fn a_link_row_is_titled_by_what_the_link_does() {
|
||||
assert_eq!(link_row_title(false, false), "Public viewer link");
|
||||
assert_eq!(link_row_title(true, false), "Public editor link");
|
||||
assert_eq!(link_row_title(true, true), "Expired public link");
|
||||
let link = viewer_link(false, Some(10));
|
||||
assert!(!link_row_title(false, false).contains(link.url.as_deref().unwrap()));
|
||||
assert_eq!(
|
||||
link_policy(false, false, link.expires, 20),
|
||||
"Anyone with the link can view · no password · expired"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn past_expiry_reads_expired() {
|
||||
assert_eq!(link_expiry_label(10, 20), "expired");
|
||||
|
||||
@@ -5,6 +5,13 @@
|
||||
//! searching a file opened often and lately gets a bonus on top of its match
|
||||
//! score (see [`frecency_bonus`]).
|
||||
//!
|
||||
//! A Drive file is remembered with the account it was opened from, and only
|
||||
//! that account's files are shown: after a switch to another account, the
|
||||
//! first one's names and paths stay out of the window. Local files are shown
|
||||
//! whoever is signed in. Preferences can turn the history off or clear it; the
|
||||
//! window loads the file again each time it opens, so a clear made in the app
|
||||
//! takes effect at once.
|
||||
//!
|
||||
//! One writer thread owns the file: it loads it, applies every recorded visit
|
||||
//! in order and writes the result back atomically. A visit recorded before the
|
||||
//! first load finished simply waits in the channel, so it is merged into the
|
||||
@@ -42,6 +49,19 @@ pub(crate) struct Visit {
|
||||
/// When the file was last opened, in epoch seconds.
|
||||
pub(crate) last: i64,
|
||||
pub(crate) count: u32,
|
||||
/// The account a Drive file was opened from. `None` for a local file, and
|
||||
/// for a Drive file remembered before accounts were recorded, which is
|
||||
/// never shown since nobody can say whose it is.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) account: Option<String>,
|
||||
}
|
||||
|
||||
/// Whether `visit` may be shown while `account` is signed in.
|
||||
fn visible(visit: &Visit, account: Option<&str>) -> bool {
|
||||
match visit.hit {
|
||||
Hit::Local(_) => true,
|
||||
Hit::Drive(_) => account.is_some() && visit.account.as_deref() == account,
|
||||
}
|
||||
}
|
||||
|
||||
/// The history bonus for a file opened `count` times, the last time
|
||||
@@ -55,9 +75,16 @@ pub(crate) fn frecency_bonus(count: u32, age_secs: i64) -> i64 {
|
||||
/// Count one more visit of `hit` at `now`, newest first, and keep at most
|
||||
/// [`MAX_VISITS`]. The stored hit is replaced, so its size, date and sync
|
||||
/// state are the ones from the latest search.
|
||||
fn record(visits: &mut Vec<Visit>, hit: Hit, now: i64) {
|
||||
fn record(visits: &mut Vec<Visit>, hit: Hit, now: i64, account: Option<String>) {
|
||||
let key = hit.key();
|
||||
let count = match visits.iter().position(|visit| visit.hit.key() == key) {
|
||||
let account = match hit {
|
||||
Hit::Local(_) => None,
|
||||
Hit::Drive(_) => account,
|
||||
};
|
||||
let count = match visits
|
||||
.iter()
|
||||
.position(|visit| visit.hit.key() == key && visit.account == account)
|
||||
{
|
||||
Some(at) => visits.remove(at).count.saturating_add(1),
|
||||
None => 1,
|
||||
};
|
||||
@@ -67,6 +94,7 @@ fn record(visits: &mut Vec<Visit>, hit: Hit, now: i64) {
|
||||
hit,
|
||||
last: now,
|
||||
count,
|
||||
account,
|
||||
},
|
||||
);
|
||||
visits.truncate(MAX_VISITS);
|
||||
@@ -107,9 +135,19 @@ fn save(path: &Path, visits: &[Visit]) -> std::io::Result<()> {
|
||||
std::fs::rename(&tmp, path)
|
||||
}
|
||||
|
||||
/// Delete the history file. Used by the window when the history is turned off,
|
||||
/// and by the app's Clear Recent Files.
|
||||
pub(crate) fn clear(path: &Path) -> std::io::Result<()> {
|
||||
std::fs::remove_file(path)
|
||||
}
|
||||
|
||||
enum Command {
|
||||
Record(Hit, i64),
|
||||
Record(Hit, i64, Option<String>),
|
||||
Prune,
|
||||
/// Read the file again: the app may have cleared it.
|
||||
Reload,
|
||||
/// Forget everything, on disk too.
|
||||
Clear,
|
||||
}
|
||||
|
||||
/// The writer thread's loop: load, then apply commands until the launcher
|
||||
@@ -123,11 +161,29 @@ fn serve(path: &Path, commands: &async_channel::Receiver<Command>, publish: impl
|
||||
}
|
||||
while let Ok(command) = commands.recv_blocking() {
|
||||
let changed = match command {
|
||||
Command::Record(hit, now) => {
|
||||
record(&mut visits, hit, now);
|
||||
Command::Record(hit, now, account) => {
|
||||
record(&mut visits, hit, now, account);
|
||||
true
|
||||
}
|
||||
Command::Prune => prune(&mut visits),
|
||||
Command::Reload => {
|
||||
visits = load(path);
|
||||
publish(visits.clone());
|
||||
false
|
||||
}
|
||||
Command::Clear => {
|
||||
if let Err(e) = clear(path)
|
||||
&& e.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
tracing::warn!("cannot remove {}: {e}", path.display());
|
||||
}
|
||||
let had = !visits.is_empty();
|
||||
visits.clear();
|
||||
if had {
|
||||
publish(Vec::new());
|
||||
}
|
||||
false
|
||||
}
|
||||
};
|
||||
if changed {
|
||||
if let Err(e) = save(path, &visits) {
|
||||
@@ -142,6 +198,10 @@ fn serve(path: &Path, commands: &async_channel::Receiver<Command>, publish: impl
|
||||
pub(crate) struct History {
|
||||
visits: Rc<RefCell<Vec<Visit>>>,
|
||||
commands: async_channel::Sender<Command>,
|
||||
/// Who is signed in, as the service last said; `None` until it has.
|
||||
account: RefCell<Option<String>>,
|
||||
/// Whether to remember anything, as Preferences last said.
|
||||
remember: std::cell::Cell<bool>,
|
||||
}
|
||||
|
||||
impl History {
|
||||
@@ -169,12 +229,38 @@ impl History {
|
||||
changed();
|
||||
}
|
||||
});
|
||||
Self { visits, commands }
|
||||
Self {
|
||||
visits,
|
||||
commands,
|
||||
account: RefCell::new(None),
|
||||
remember: std::cell::Cell::new(true),
|
||||
}
|
||||
}
|
||||
|
||||
/// Who is signed in now. Drive files opened by anyone else stay hidden.
|
||||
pub(crate) fn set_account(&self, account: Option<String>) {
|
||||
*self.account.borrow_mut() = account;
|
||||
}
|
||||
|
||||
/// Apply Preferences as the window opens: read the file again, since the
|
||||
/// app may have cleared it, or clear it when the history is turned off.
|
||||
pub(crate) fn refresh(&self, remember: bool) {
|
||||
self.remember.set(remember);
|
||||
let command = if remember {
|
||||
Command::Reload
|
||||
} else {
|
||||
Command::Clear
|
||||
};
|
||||
let _ = self.commands.try_send(command);
|
||||
}
|
||||
|
||||
/// Remember that `hit` was opened just now.
|
||||
pub(crate) fn record(&self, hit: Hit) {
|
||||
let _ = self.commands.try_send(Command::Record(hit, now()));
|
||||
if !self.remember.get() {
|
||||
return;
|
||||
}
|
||||
let account = self.account.borrow().clone();
|
||||
let _ = self.commands.try_send(Command::Record(hit, now(), account));
|
||||
}
|
||||
|
||||
/// Forget local files that were deleted since they were opened.
|
||||
@@ -184,9 +270,11 @@ impl History {
|
||||
|
||||
/// The most recently opened files, newest first.
|
||||
pub(crate) fn recent(&self, limit: usize) -> Vec<Hit> {
|
||||
let account = self.account.borrow();
|
||||
self.visits
|
||||
.borrow()
|
||||
.iter()
|
||||
.filter(|visit| visible(visit, account.as_deref()))
|
||||
.take(limit)
|
||||
.map(|visit| visit.hit.clone())
|
||||
.collect()
|
||||
@@ -195,9 +283,11 @@ impl History {
|
||||
/// The frecency bonus of every remembered file, by [`Hit::key`].
|
||||
pub(crate) fn bonuses(&self) -> HashMap<(bool, String), i64> {
|
||||
let now = now();
|
||||
let account = self.account.borrow();
|
||||
self.visits
|
||||
.borrow()
|
||||
.iter()
|
||||
.filter(|visit| visible(visit, account.as_deref()))
|
||||
.map(|visit| {
|
||||
(
|
||||
visit.hit.key(),
|
||||
@@ -220,6 +310,8 @@ mod tests {
|
||||
use pdfs_core::control::{LocalHit, SearchHit};
|
||||
|
||||
const DAY: i64 = 86_400;
|
||||
/// The account the tests open Drive files from.
|
||||
const A: &str = "a@proton.me";
|
||||
|
||||
fn drive(name: &str) -> Hit {
|
||||
Hit::Drive(SearchHit {
|
||||
@@ -266,9 +358,9 @@ mod tests {
|
||||
#[test]
|
||||
fn a_repeat_visit_moves_the_file_to_the_top_and_counts_it() {
|
||||
let mut visits = Vec::new();
|
||||
record(&mut visits, drive("a.pdf"), 10);
|
||||
record(&mut visits, drive("b.pdf"), 20);
|
||||
record(&mut visits, drive("a.pdf"), 30);
|
||||
record(&mut visits, drive("a.pdf"), 10, Some(A.into()));
|
||||
record(&mut visits, drive("b.pdf"), 20, Some(A.into()));
|
||||
record(&mut visits, drive("a.pdf"), 30, Some(A.into()));
|
||||
assert_eq!(visits.len(), 2);
|
||||
assert_eq!(visits[0].hit.name(), "a.pdf");
|
||||
assert_eq!((visits[0].count, visits[0].last), (2, 30));
|
||||
@@ -279,7 +371,7 @@ mod tests {
|
||||
fn the_history_keeps_the_newest_fifty_files() {
|
||||
let mut visits = Vec::new();
|
||||
for n in 0..60 {
|
||||
record(&mut visits, drive(&format!("{n}.pdf")), n);
|
||||
record(&mut visits, drive(&format!("{n}.pdf")), n, Some(A.into()));
|
||||
}
|
||||
assert_eq!(visits.len(), MAX_VISITS);
|
||||
assert_eq!(visits[0].hit.name(), "59.pdf");
|
||||
@@ -291,8 +383,8 @@ mod tests {
|
||||
let dir = scratch_dir("round-trip");
|
||||
let path = dir.join("prompt-history.json");
|
||||
let mut visits = Vec::new();
|
||||
record(&mut visits, drive("a.pdf"), 10);
|
||||
record(&mut visits, drive("a.pdf"), 20);
|
||||
record(&mut visits, drive("a.pdf"), 10, Some(A.into()));
|
||||
record(&mut visits, drive("a.pdf"), 20, Some(A.into()));
|
||||
save(&path, &visits).unwrap();
|
||||
|
||||
let loaded = load(&path);
|
||||
@@ -308,17 +400,17 @@ mod tests {
|
||||
let dir = scratch_dir("merge");
|
||||
let path = dir.join("prompt-history.json");
|
||||
let mut stored = Vec::new();
|
||||
record(&mut stored, drive("old.pdf"), 10);
|
||||
record(&mut stored, drive("old.pdf"), 20);
|
||||
record(&mut stored, drive("old.pdf"), 10, Some(A.into()));
|
||||
record(&mut stored, drive("old.pdf"), 20, Some(A.into()));
|
||||
save(&path, &stored).unwrap();
|
||||
|
||||
// Both visits are queued before the writer has read the file.
|
||||
let (commands, inbox) = async_channel::unbounded();
|
||||
commands
|
||||
.send_blocking(Command::Record(drive("old.pdf"), 30))
|
||||
.send_blocking(Command::Record(drive("old.pdf"), 30, Some(A.into())))
|
||||
.unwrap();
|
||||
commands
|
||||
.send_blocking(Command::Record(drive("new.pdf"), 40))
|
||||
.send_blocking(Command::Record(drive("new.pdf"), 40, Some(A.into())))
|
||||
.unwrap();
|
||||
drop(commands);
|
||||
|
||||
@@ -351,13 +443,114 @@ mod tests {
|
||||
})
|
||||
};
|
||||
let mut visits = Vec::new();
|
||||
record(&mut visits, local(&kept), 1);
|
||||
record(&mut visits, local(&dir.join("gone.txt")), 2);
|
||||
record(&mut visits, drive("remote.pdf"), 3);
|
||||
record(&mut visits, local(&kept), 1, Some(A.into()));
|
||||
record(&mut visits, local(&dir.join("gone.txt")), 2, Some(A.into()));
|
||||
record(&mut visits, drive("remote.pdf"), 3, Some(A.into()));
|
||||
|
||||
assert!(prune(&mut visits));
|
||||
let names: Vec<&str> = visits.iter().map(|visit| visit.hit.name()).collect();
|
||||
assert_eq!(names, ["remote.pdf", "kept.txt"]);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// After a switch to account B, account A's Drive files are not shown and
|
||||
/// give no ranking bonus. Local files stay.
|
||||
#[test]
|
||||
fn only_the_signed_in_accounts_drive_files_are_shown() {
|
||||
let mut visits = Vec::new();
|
||||
record(&mut visits, drive("a-secret.pdf"), 1, Some(A.into()));
|
||||
record(
|
||||
&mut visits,
|
||||
drive("b-notes.pdf"),
|
||||
2,
|
||||
Some("b@proton.me".into()),
|
||||
);
|
||||
let local = Hit::Local(LocalHit {
|
||||
name: "here.txt".into(),
|
||||
path: "/home/me/here.txt".into(),
|
||||
is_dir: false,
|
||||
size: 1,
|
||||
modified: 1,
|
||||
score: 0,
|
||||
});
|
||||
record(&mut visits, local, 3, Some(A.into()));
|
||||
assert_eq!(
|
||||
visits[0].account, None,
|
||||
"a local file belongs to no account"
|
||||
);
|
||||
|
||||
let shown = |account: Option<&str>| -> Vec<&str> {
|
||||
visits
|
||||
.iter()
|
||||
.filter(|visit| visible(visit, account))
|
||||
.map(|visit| visit.hit.name())
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(shown(Some("b@proton.me")), ["here.txt", "b-notes.pdf"]);
|
||||
assert_eq!(shown(Some(A)), ["here.txt", "a-secret.pdf"]);
|
||||
// Before the service has said who is signed in, no Drive file shows.
|
||||
assert_eq!(shown(None), ["here.txt"]);
|
||||
}
|
||||
|
||||
/// A Drive file remembered before accounts were recorded has no owner, so
|
||||
/// it is never shown.
|
||||
#[test]
|
||||
fn a_drive_file_from_before_accounts_were_recorded_stays_hidden() {
|
||||
let old: Vec<Visit> = serde_json::from_value(
|
||||
serde_json::json!([{"hit": drive("old.pdf"), "last": 1, "count": 1}]),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!visible(&old[0], Some(A)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_forgets_everything_on_disk_too() {
|
||||
let dir = scratch_dir("clear");
|
||||
let path = dir.join("prompt-history.json");
|
||||
let mut stored = Vec::new();
|
||||
record(&mut stored, drive("old.pdf"), 10, Some(A.into()));
|
||||
save(&path, &stored).unwrap();
|
||||
|
||||
let (commands, inbox) = async_channel::unbounded();
|
||||
commands.send_blocking(Command::Clear).unwrap();
|
||||
drop(commands);
|
||||
let published = RefCell::new(Vec::new());
|
||||
serve(&path, &inbox, |visits| published.borrow_mut().push(visits));
|
||||
|
||||
assert!(published.borrow().last().unwrap().is_empty());
|
||||
assert!(!path.exists());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// The app clears the file while the window is hidden; the window reads
|
||||
/// it again when it opens and shows nothing.
|
||||
#[test]
|
||||
fn a_reload_picks_up_a_clear_made_elsewhere() {
|
||||
let dir = scratch_dir("reload");
|
||||
let path = dir.join("prompt-history.json");
|
||||
let mut stored = Vec::new();
|
||||
record(&mut stored, drive("old.pdf"), 10, Some(A.into()));
|
||||
save(&path, &stored).unwrap();
|
||||
|
||||
let (commands, inbox) = async_channel::unbounded();
|
||||
let published = std::sync::Mutex::new(Vec::new());
|
||||
std::thread::scope(|scope| {
|
||||
scope.spawn(|| {
|
||||
serve(&path, &inbox, |visits| {
|
||||
published.lock().unwrap().push(visits)
|
||||
})
|
||||
});
|
||||
// Let the first load happen, then clear behind the writer's back.
|
||||
while published.lock().unwrap().is_empty() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
clear(&path).unwrap();
|
||||
commands.send_blocking(Command::Reload).unwrap();
|
||||
drop(commands);
|
||||
});
|
||||
let published = published.into_inner().unwrap();
|
||||
assert_eq!(published.first().unwrap().len(), 1);
|
||||
assert!(published.last().unwrap().is_empty());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user