mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-26 19:12:14 +01:00
Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b7e2fffa8 | ||
|
|
8cd30ef0c1 | ||
|
|
4a38b7992c | ||
|
|
200ca1461f | ||
|
|
87dc2b9d6d | ||
|
|
b1516f1403 | ||
|
|
25b0ea4ce8 | ||
|
|
c5c376e2b3 | ||
|
|
61994f7754 | ||
|
|
c453421a53 | ||
|
|
c323def397 | ||
|
|
050ac3fe85 | ||
|
|
b98364d82a | ||
|
|
41d7355f9a | ||
|
|
667c086dd5 | ||
|
|
e2cbb442f2 | ||
|
|
83391d6d96 | ||
|
|
67786c9462 | ||
|
|
3255bc2f36 | ||
|
|
f6c3e45fd3 | ||
|
|
5c1a2c78b6 |
No files matched your search
@@ -129,7 +129,7 @@ fn cache_file(key: &str) -> Option<PathBuf> {
|
||||
let runtime = PathBuf::from(std::env::var_os("XDG_RUNTIME_DIR")?);
|
||||
Some(
|
||||
runtime
|
||||
.join("proton-drive-linux")
|
||||
.join(pdfs_core::config::app_dir_name())
|
||||
.join(format!("completion-{key}.json")),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1035,7 +1035,11 @@ fn cli_error(kind: ErrorKind, message: &str) -> String {
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
// First: a completion request answers on stdout and exits, so nothing may
|
||||
// A bad `PDFS_INSTANCE` is refused before anything reads a path or the
|
||||
// keyring; falling back to the default instance would touch the user's
|
||||
// own account.
|
||||
pdfs_core::config::check_instance()?;
|
||||
// Next: a completion request answers on stdout and exits, so nothing may
|
||||
// write there before it.
|
||||
complete::handle_request();
|
||||
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
@@ -3631,6 +3635,23 @@ fn cmd_diagnostics() -> Result<()> {
|
||||
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 let Some(sync) = &d.sync {
|
||||
println!("sync engine: {}", sync_engine_line(sync));
|
||||
for trace in &sync.traces {
|
||||
|
||||
@@ -26,7 +26,7 @@ use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::{Datelike, Local, TimeZone};
|
||||
use pdfs_core::config::{AppDirs, KEYRING_SERVICE};
|
||||
use pdfs_core::config::AppDirs;
|
||||
use pdfs_core::control::Pin;
|
||||
use pdfs_core::control::{
|
||||
ActivityEntry, ActivityKind, AlbumInfo, DeviceInfo, DirEntry, Event, LocalHit, PhotoItem,
|
||||
@@ -108,7 +108,7 @@ fn seed_keyring() -> Result<(), String> {
|
||||
let store: Arc<keyring_core::CredentialStore> =
|
||||
dbus_secret_service_keyring_store::Store::new().map_err(|e| e.to_string())?;
|
||||
keyring_core::set_default_store(store);
|
||||
keyring_core::Entry::new(KEYRING_SERVICE, "session")
|
||||
keyring_core::Entry::new(pdfs_core::config::keyring_service(), "session")
|
||||
.and_then(|entry| entry.set_password(&session.to_string()))
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ use proton_sdk::telemetry::TracingTelemetry;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::config::{APP_VERSION, AppDirs, KEYRING_SERVICE, USER_AGENT};
|
||||
use crate::config::{APP_VERSION, AppDirs, USER_AGENT};
|
||||
use crate::error::{Error, Result};
|
||||
use crate::kernelkey;
|
||||
|
||||
@@ -141,12 +141,15 @@ fn keyring() -> &'static KeyringStore {
|
||||
STORE.get_or_init(|| {
|
||||
#[cfg(not(test))]
|
||||
{
|
||||
KeyringStore::new(KEYRING_SERVICE)
|
||||
KeyringStore::new(crate::config::keyring_service())
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
KeyringStore::with_connector(KEYRING_SERVICE, Arc::new(tests::connect_keyring_store))
|
||||
.replace_items(|| tests::MOCK_STORE.lock().is_none())
|
||||
KeyringStore::with_connector(
|
||||
crate::config::KEYRING_SERVICE,
|
||||
Arc::new(tests::connect_keyring_store),
|
||||
)
|
||||
.replace_items(|| tests::MOCK_STORE.lock().is_none())
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1273,7 +1276,7 @@ mod tests {
|
||||
|
||||
/// The session's entry, to make its next call fail.
|
||||
fn keyring_entry() -> Entry {
|
||||
Entry::new(KEYRING_SERVICE, KEYRING_USER).unwrap()
|
||||
Entry::new(crate::config::KEYRING_SERVICE, KEYRING_USER).unwrap()
|
||||
}
|
||||
|
||||
/// Make the session entry's next call fail with `error`.
|
||||
@@ -1420,7 +1423,7 @@ mod tests {
|
||||
.unwrap();
|
||||
let found = ss
|
||||
.search_items(std::collections::HashMap::from([
|
||||
("service", KEYRING_SERVICE),
|
||||
("service", crate::config::KEYRING_SERVICE),
|
||||
("username", KEYRING_USER),
|
||||
]))
|
||||
.unwrap();
|
||||
|
||||
@@ -26,9 +26,93 @@ pub const USER_AGENT: &str = concat!("proton-drive-linux/", env!("CARGO_PKG_VERS
|
||||
const LEGACY_APP_VERSION: &str = "external-drive-linux@0.1.0-alpha";
|
||||
const LEGACY_USER_AGENT: &str = "proton-drive-linux/0.1.0";
|
||||
|
||||
/// Keyring service name; one entry per credential kind keyed by username.
|
||||
/// Keyring service name of the default instance; see [`keyring_service`].
|
||||
pub const KEYRING_SERVICE: &str = "proton-drive-linux";
|
||||
|
||||
/// Environment variable that names a separate instance of the client.
|
||||
///
|
||||
/// Unset, everything is as it always was. Set to a name, every place the client
|
||||
/// keeps an account apart is suffixed with it: the XDG config, state and cache
|
||||
/// directories (and with them the database, the control socket and the
|
||||
/// machine id), the Secret Service entry, the kernel keys and the default
|
||||
/// mountpoint. A second daemon can then run on another account next to the
|
||||
/// user's own, and neither sees the other's session. The test tooling uses it
|
||||
/// to run against a test account without signing the user out.
|
||||
///
|
||||
/// The systemd unit belongs to the default instance only: with an instance
|
||||
/// set, the `service` calls do nothing, so a `pdfs login` for a test account
|
||||
/// never restarts the user's daemon. Start that instance's `pdfs daemon` by
|
||||
/// hand.
|
||||
pub const INSTANCE_ENV: &str = "PDFS_INSTANCE";
|
||||
|
||||
/// Base name of the client's directories and Secret Service entry.
|
||||
const APP_NAME: &str = "proton-drive-linux";
|
||||
|
||||
/// The instance named by [`INSTANCE_ENV`], read once per process. `None` for
|
||||
/// the default instance.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// When the name is not 1 to 32 lowercase ASCII letters, digits or `-`. A name
|
||||
/// that was ignored instead would fall back to the default instance and touch
|
||||
/// the user's own account. Front ends call [`check_instance`] first to report
|
||||
/// it as an error.
|
||||
pub fn instance() -> Option<&'static str> {
|
||||
match parsed_instance() {
|
||||
Ok(instance) => *instance,
|
||||
Err(message) => panic!("{message}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fails when [`INSTANCE_ENV`] is set to a name [`instance`] would refuse.
|
||||
pub fn check_instance() -> Result<()> {
|
||||
match parsed_instance() {
|
||||
Ok(_) => Ok(()),
|
||||
Err(message) => Err(Error::Other(message.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
fn parsed_instance() -> &'static std::result::Result<Option<&'static str>, String> {
|
||||
static INSTANCE: std::sync::OnceLock<std::result::Result<Option<&'static str>, String>> =
|
||||
std::sync::OnceLock::new();
|
||||
INSTANCE.get_or_init(|| match std::env::var(INSTANCE_ENV) {
|
||||
Err(std::env::VarError::NotPresent) => Ok(None),
|
||||
Ok(name) if name.is_empty() => Ok(None),
|
||||
Ok(name) if is_instance_name(&name) => Ok(Some(Box::leak(name.into_boxed_str()))),
|
||||
_ => Err(format!(
|
||||
"{INSTANCE_ENV} must be 1 to 32 lowercase letters, digits or '-'"
|
||||
)),
|
||||
})
|
||||
}
|
||||
|
||||
fn is_instance_name(name: &str) -> bool {
|
||||
(1..=32).contains(&name.len())
|
||||
&& name
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
|
||||
}
|
||||
|
||||
/// `base`, or `base` and the instance name joined by `separator`.
|
||||
pub fn instance_suffixed(base: &str, separator: char) -> String {
|
||||
match instance() {
|
||||
Some(name) => format!("{base}{separator}{name}"),
|
||||
None => base.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Secret Service name the session is stored under: [`KEYRING_SERVICE`],
|
||||
/// suffixed with the [`instance`] when one is set.
|
||||
pub fn keyring_service() -> &'static str {
|
||||
static SERVICE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
SERVICE.get_or_init(|| instance_suffixed(KEYRING_SERVICE, '-'))
|
||||
}
|
||||
|
||||
/// The directory name under each XDG base directory: `proton-drive-linux`,
|
||||
/// suffixed with the [`instance`] when one is set.
|
||||
pub fn app_dir_name() -> String {
|
||||
instance_suffixed(APP_NAME, '-')
|
||||
}
|
||||
|
||||
/// Default soft cap on the on-disk content cache (5 GiB). LRU-evicts unpinned
|
||||
/// blobs back under this; pinned files are exempt. See `pdfs_store::cache`.
|
||||
pub const DEFAULT_CACHE_BUDGET_BYTES: u64 = 5 * 1024 * 1024 * 1024;
|
||||
@@ -526,7 +610,7 @@ pub struct AppDirs {
|
||||
|
||||
impl AppDirs {
|
||||
pub fn new() -> Result<Self> {
|
||||
let dirs = ProjectDirs::from("io", "narl", "proton-drive-linux")
|
||||
let dirs = ProjectDirs::from("io", "narl", &app_dir_name())
|
||||
.ok_or_else(|| Error::Other("cannot resolve home directory".into()))?;
|
||||
Ok(Self { dirs })
|
||||
}
|
||||
@@ -659,11 +743,13 @@ impl AppDirs {
|
||||
directories::UserDirs::new().map(|u| u.home_dir().to_path_buf())
|
||||
}
|
||||
|
||||
/// Default mountpoint when the user does not pass one explicitly.
|
||||
/// Default mountpoint when the user does not pass one explicitly:
|
||||
/// `~/ProtonDrive`, or `~/ProtonDrive-<instance>` for a named [`instance`].
|
||||
pub fn default_mountpoint(&self) -> PathBuf {
|
||||
let name = instance_suffixed("ProtonDrive", '-');
|
||||
directories::UserDirs::new()
|
||||
.map(|u| u.home_dir().join("ProtonDrive"))
|
||||
.unwrap_or_else(|| PathBuf::from("/tmp/ProtonDrive"))
|
||||
.map(|u| u.home_dir().join(&name))
|
||||
.unwrap_or_else(|| PathBuf::from("/tmp").join(&name))
|
||||
}
|
||||
|
||||
/// The effective mountpoint: the config's explicit path, or
|
||||
@@ -762,6 +848,31 @@ mod tests {
|
||||
std::fs::metadata(p).unwrap().permissions().mode() & 0o777
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_name_is_short_lowercase_ascii() {
|
||||
for good in ["test", "bench-1", "a", &"x".repeat(32)] {
|
||||
assert!(is_instance_name(good), "{good:?}");
|
||||
}
|
||||
for bad in ["", "Test", "a/b", "../x", "a b", "ü", &"x".repeat(33)] {
|
||||
assert!(!is_instance_name(bad), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The test process has no `PDFS_INSTANCE`, so it is the default instance
|
||||
/// and every name is the one releases before 4.0 used.
|
||||
#[test]
|
||||
fn the_default_instance_keeps_the_old_names() {
|
||||
assert_eq!(instance(), None);
|
||||
assert_eq!(keyring_service(), "proton-drive-linux");
|
||||
assert_eq!(app_dir_name(), "proton-drive-linux");
|
||||
assert!(
|
||||
AppDirs::new()
|
||||
.unwrap()
|
||||
.default_mountpoint()
|
||||
.ends_with("ProtonDrive")
|
||||
);
|
||||
}
|
||||
|
||||
/// Two writers changing different settings at once both keep their change
|
||||
/// (`docs/BUGS.md` B292).
|
||||
#[test]
|
||||
|
||||
@@ -2374,6 +2374,22 @@ pub struct Diagnostics {
|
||||
/// field.
|
||||
#[serde(default)]
|
||||
pub drive_calls: Vec<DriveCallStat>,
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
/// One long-lived daemon thread, in [`Diagnostics::services`].
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct ServiceState {
|
||||
/// The thread's name, such as `pdfs-sync`.
|
||||
pub name: String,
|
||||
/// `false` once the thread has ended, by return or by panic. Every service
|
||||
/// runs until the mount stops, so one that ended early is a fault.
|
||||
pub running: bool,
|
||||
/// How long ago the thread was started.
|
||||
pub age_secs: u64,
|
||||
}
|
||||
|
||||
/// One kind of call to Drive, in [`Diagnostics::drive_calls`].
|
||||
|
||||
@@ -18,36 +18,38 @@
|
||||
//! `CONFIG_KEYS`); every operation then reports it as an error and the caller
|
||||
//! falls back to asking again, never to storing the secret somewhere weaker.
|
||||
|
||||
use std::ffi::CString;
|
||||
use std::io;
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// One secret in the user keyring, by its description. Descriptions are
|
||||
/// namespaced so they cannot collide with another program's keys.
|
||||
/// namespaced so they cannot collide with another program's keys, and carry
|
||||
/// the [`crate::config::instance`] so a second instance keeps its own.
|
||||
pub struct Key {
|
||||
description: &'static [u8],
|
||||
name: &'static str,
|
||||
}
|
||||
|
||||
/// The account's key passphrases (see the module docs).
|
||||
#[cfg(not(test))]
|
||||
pub const PASSPHRASES: Key = Key {
|
||||
description: b"pdfs:key-passphrases\0",
|
||||
name: "pdfs:key-passphrases",
|
||||
};
|
||||
/// Tests must never touch a real unlock.
|
||||
#[cfg(test)]
|
||||
pub const PASSPHRASES: Key = Key {
|
||||
description: b"pdfs:key-passphrases:test\0",
|
||||
name: "pdfs:key-passphrases:test",
|
||||
};
|
||||
|
||||
/// Session tokens the Secret Service refused to store, until it takes them.
|
||||
/// A refresh token held only in a process's memory dies with the process.
|
||||
#[cfg(not(test))]
|
||||
pub const UNSAVED_TOKENS: Key = Key {
|
||||
description: b"pdfs:unsaved-tokens\0",
|
||||
name: "pdfs:unsaved-tokens",
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub const UNSAVED_TOKENS: Key = Key {
|
||||
description: b"pdfs:unsaved-tokens:test\0",
|
||||
name: "pdfs:unsaved-tokens:test",
|
||||
};
|
||||
|
||||
const KEY_TYPE: &[u8] = b"user\0";
|
||||
@@ -73,7 +75,7 @@ fn last_error<T>() -> io::Result<T> {
|
||||
Err(io::Error::last_os_error())
|
||||
}
|
||||
|
||||
fn find(description: &[u8]) -> io::Result<Option<libc::c_long>> {
|
||||
fn find(description: &std::ffi::CStr) -> io::Result<Option<libc::c_long>> {
|
||||
// SAFETY: both strings are NUL-terminated and outlive the call.
|
||||
let id = unsafe {
|
||||
libc::syscall(
|
||||
@@ -108,15 +110,23 @@ pub fn forbid_dumps() {
|
||||
}
|
||||
|
||||
impl Key {
|
||||
/// The key's description: its name, suffixed with the instance when one
|
||||
/// is set.
|
||||
fn description(&self) -> CString {
|
||||
CString::new(crate::config::instance_suffixed(self.name, ':'))
|
||||
.expect("key names and instance names hold no NUL")
|
||||
}
|
||||
|
||||
/// Store `secret`, replacing any earlier one.
|
||||
pub fn store(&self, secret: &[u8]) -> io::Result<()> {
|
||||
// SAFETY: strings are NUL-terminated; the payload pointer/length pair
|
||||
// describes `secret`, which outlives the call.
|
||||
let description = self.description();
|
||||
let id = unsafe {
|
||||
libc::syscall(
|
||||
libc::SYS_add_key,
|
||||
KEY_TYPE.as_ptr(),
|
||||
self.description.as_ptr(),
|
||||
description.as_ptr(),
|
||||
secret.as_ptr(),
|
||||
secret.len(),
|
||||
KEY_SPEC_USER_KEYRING,
|
||||
@@ -145,7 +155,7 @@ impl Key {
|
||||
|
||||
/// Read the stored secret, or `None` when there is none.
|
||||
pub fn load(&self) -> io::Result<Option<Zeroizing<Vec<u8>>>> {
|
||||
let Some(id) = find(self.description)? else {
|
||||
let Some(id) = find(&self.description())? else {
|
||||
return Ok(None);
|
||||
};
|
||||
// Size first, then read; retry if the key was replaced in between.
|
||||
@@ -190,7 +200,7 @@ impl Key {
|
||||
|
||||
/// Remove the stored secret. Succeeds when there is none.
|
||||
pub fn clear(&self) -> io::Result<()> {
|
||||
let Some(id) = find(self.description)? else {
|
||||
let Some(id) = find(&self.description())? else {
|
||||
return Ok(());
|
||||
};
|
||||
// SAFETY: plain integer arguments.
|
||||
|
||||
@@ -10,6 +10,7 @@ pub mod control;
|
||||
pub mod error;
|
||||
pub mod kernelkey;
|
||||
pub mod keycheck;
|
||||
pub mod lifecycle;
|
||||
pub mod localindex;
|
||||
pub mod lockrank;
|
||||
pub mod menu;
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
//! The daemon's long-lived threads, started, watched and stopped in one place.
|
||||
//!
|
||||
//! Each long-lived thread used to be started on its own, with its own rules
|
||||
//! for how it learns to stop, and the mount kept a bare list of join handles.
|
||||
//! Waking a thread that blocks somewhere other than [`Shutdown::sleep`] (the
|
||||
//! drain's condvar, the sync engine's channel, the control socket's `accept`)
|
||||
//! was a separate list of calls far from the spawn, and nothing could say which
|
||||
//! threads were still alive.
|
||||
//!
|
||||
//! [`Services`] keeps all of it together. Each thread is started with its name
|
||||
//! and the call that wakes it, if it needs one. [`Services::stop`] stops them in
|
||||
//! 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.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
|
||||
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>;
|
||||
|
||||
/// Whether one service thread is still running, for diagnostics.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ServiceHealth {
|
||||
/// The thread's name, such as `pdfs-sync`.
|
||||
pub name: String,
|
||||
pub running: bool,
|
||||
/// How long ago the thread was started.
|
||||
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.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct ServiceBoard(Arc<Mutex<Vec<Entry>>>);
|
||||
|
||||
struct Entry {
|
||||
name: String,
|
||||
started: Instant,
|
||||
running: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl ServiceBoard {
|
||||
/// Every service thread started so far, in start order.
|
||||
pub fn health(&self) -> Vec<ServiceHealth> {
|
||||
self.0
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|entry| ServiceHealth {
|
||||
name: entry.name.clone(),
|
||||
running: entry.running.load(Ordering::Relaxed),
|
||||
age: entry.started.elapsed(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn add(&self, name: &str) -> Arc<AtomicBool> {
|
||||
let running = Arc::new(AtomicBool::new(true));
|
||||
self.0.lock().push(Entry {
|
||||
name: name.to_owned(),
|
||||
started: Instant::now(),
|
||||
running: running.clone(),
|
||||
});
|
||||
running
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears a service's `running` flag when its thread ends, by return or by panic.
|
||||
struct Running(Arc<AtomicBool>);
|
||||
|
||||
impl Drop for Running {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(false, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
struct Service {
|
||||
handle: JoinHandle<()>,
|
||||
wake: Option<Wake>,
|
||||
}
|
||||
|
||||
/// The service threads one mount started, and how to stop them.
|
||||
pub struct Services {
|
||||
board: ServiceBoard,
|
||||
started: Vec<Service>,
|
||||
}
|
||||
|
||||
impl Services {
|
||||
/// Start an empty set whose threads show on `board`.
|
||||
pub fn new(board: ServiceBoard) -> Self {
|
||||
Self {
|
||||
board,
|
||||
started: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start `run` on a thread named `name`. `wake`, if given, is called on
|
||||
/// [`stop`](Self::stop) after the [`Shutdown`] signal, for a thread that
|
||||
/// blocks where that signal does not reach.
|
||||
pub fn spawn<F>(&mut self, name: &str, wake: Option<Wake>, run: F) -> std::io::Result<()>
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
{
|
||||
let running = self.board.add(name);
|
||||
let guard = Running(running.clone());
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name(name.to_owned())
|
||||
.spawn(move || {
|
||||
let _guard = guard;
|
||||
run();
|
||||
});
|
||||
match spawned {
|
||||
Ok(handle) => {
|
||||
self.started.push(Service { handle, wake });
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => {
|
||||
// The closure, and the guard in it, are dropped with the error,
|
||||
// so the board already shows the thread as not running.
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many threads were started.
|
||||
pub fn len(&self) -> usize {
|
||||
self.started.len()
|
||||
}
|
||||
|
||||
/// Whether no thread 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.
|
||||
pub fn stop(self, shutdown: &Shutdown, deadline: Instant) -> Vec<String> {
|
||||
shutdown.stop();
|
||||
for service in self.started.iter().rev() {
|
||||
if let Some(wake) = &service.wake {
|
||||
wake();
|
||||
}
|
||||
}
|
||||
join_until(
|
||||
self.started.into_iter().rev().map(|service| service.handle),
|
||||
deadline,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Join `handles` until `deadline`, and name the ones still running then.
|
||||
///
|
||||
/// A stop used to wait for each thread however long it took. The sync engine's
|
||||
/// mirror pass waits on Drive with no deadline, and a stop that waited for it
|
||||
/// was killed by systemd (`docs/BUGS.md` B165).
|
||||
pub fn join_until(
|
||||
handles: impl IntoIterator<Item = JoinHandle<()>>,
|
||||
deadline: Instant,
|
||||
) -> Vec<String> {
|
||||
let mut running = Vec::new();
|
||||
for handle in handles {
|
||||
while !handle.is_finished() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
if !handle.is_finished() {
|
||||
running.push(handle.thread().name().unwrap_or("unnamed").to_string());
|
||||
} else if handle.join().is_err() {
|
||||
tracing::warn!("a background worker panicked before shutdown");
|
||||
}
|
||||
}
|
||||
running
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::mpsc;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_stop_wakes_in_reverse_order_and_names_what_is_still_running() {
|
||||
let board = ServiceBoard::default();
|
||||
let shutdown = Arc::new(Shutdown::default());
|
||||
let mut services = Services::new(board.clone());
|
||||
let woken = Arc::new(Mutex::new(Vec::new()));
|
||||
|
||||
// Ends on the shutdown signal alone.
|
||||
let signalled = shutdown.clone();
|
||||
services
|
||||
.spawn("sleeper", None, move || {
|
||||
while signalled.sleep(Duration::from_secs(3600)) {}
|
||||
})
|
||||
.unwrap();
|
||||
// Blocks on a channel: only its wake ends it.
|
||||
let (tx, rx) = mpsc::channel::<()>();
|
||||
let order = woken.clone();
|
||||
services
|
||||
.spawn(
|
||||
"listener",
|
||||
Some(Box::new(move || {
|
||||
order.lock().push("listener");
|
||||
let _ = tx.send(());
|
||||
})),
|
||||
move || {
|
||||
let _ = rx.recv();
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
// Never ends within the deadline.
|
||||
let (_hold, stuck) = mpsc::channel::<()>();
|
||||
let order = woken.clone();
|
||||
services
|
||||
.spawn(
|
||||
"stuck",
|
||||
Some(Box::new(move || order.lock().push("stuck"))),
|
||||
move || {
|
||||
let _ = stuck.recv();
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(services.len(), 3);
|
||||
assert!(board.health().iter().all(|service| service.running));
|
||||
|
||||
let left = services.stop(&shutdown, Instant::now() + Duration::from_millis(500));
|
||||
|
||||
assert_eq!(left, ["stuck"]);
|
||||
assert_eq!(*woken.lock(), ["stuck", "listener"]);
|
||||
let running: Vec<_> = board
|
||||
.health()
|
||||
.into_iter()
|
||||
.map(|service| (service.name, service.running))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
running,
|
||||
[
|
||||
("sleeper".to_string(), false),
|
||||
("listener".to_string(), false),
|
||||
("stuck".to_string(), true),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_service_that_panics_shows_as_not_running() {
|
||||
let board = ServiceBoard::default();
|
||||
let mut services = Services::new(board.clone());
|
||||
services.spawn("doomed", None, || panic!("boom")).unwrap();
|
||||
let left = services.stop(
|
||||
&Shutdown::default(),
|
||||
Instant::now() + Duration::from_secs(5),
|
||||
);
|
||||
assert!(left.is_empty());
|
||||
assert!(!board.health()[0].running);
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,15 @@ pub const SERVICE: &str = "proton-drive.service";
|
||||
|
||||
/// Run one `systemctl --user <args> proton-drive.service`, returning whether it
|
||||
/// succeeded. Output is suppressed; failures are logged.
|
||||
///
|
||||
/// The unit runs the default instance. With a named
|
||||
/// [`crate::config::instance`], nothing is run and the answer is `false`, so a
|
||||
/// test account's `pdfs login` never restarts the user's own daemon.
|
||||
fn systemctl(args: &[&str]) -> bool {
|
||||
if crate::config::instance().is_some() {
|
||||
tracing::debug!(args = ?args, "not running systemctl for a named instance");
|
||||
return false;
|
||||
}
|
||||
let ok = Command::new("systemctl")
|
||||
.arg("--user")
|
||||
.args(args)
|
||||
@@ -36,6 +44,9 @@ fn systemctl(args: &[&str]) -> bool {
|
||||
/// rather than a failure to log. For query verbs (`is-active`, `is-failed`)
|
||||
/// where "no" is the normal, expected result.
|
||||
fn systemctl_query(args: &[&str]) -> bool {
|
||||
if crate::config::instance().is_some() {
|
||||
return false;
|
||||
}
|
||||
Command::new("systemctl")
|
||||
.arg("--user")
|
||||
.args(args)
|
||||
|
||||
@@ -132,13 +132,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.albums_refreshing.swap(true, Ordering::SeqCst) {
|
||||
if self
|
||||
.photo_jobs
|
||||
.albums_refreshing
|
||||
.swap(true, Ordering::SeqCst)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let core = self.clone();
|
||||
self.rt.spawn(async move {
|
||||
let refreshed = core.refresh_albums().await;
|
||||
core.albums_refreshing.store(false, Ordering::SeqCst);
|
||||
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"),
|
||||
|
||||
@@ -109,7 +109,7 @@ fn apply_event(core: &Core, event: &DriveEvent, dirty: &mut DirtyParents) -> pdf
|
||||
let foreign_delete = is_foreign_node_delete(event, &core.primary_root_uid.volume_id);
|
||||
let serializes_shared_publication =
|
||||
event_serializes_shared_publication(event, &core.primary_root_uid.volume_id);
|
||||
let _publication = serializes_shared_publication.then(|| core.shared_publication.lock());
|
||||
let _publication = serializes_shared_publication.then(|| core.shared.shared_publication.lock());
|
||||
if serializes_shared_publication {
|
||||
core.invalidate_shared_refreshes();
|
||||
}
|
||||
|
||||
@@ -151,7 +151,7 @@ impl Core {
|
||||
rel.display()
|
||||
)));
|
||||
}
|
||||
self.conflict_notified.lock().remove(&uid);
|
||||
self.sweep.conflict_notified.lock().remove(&uid);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -364,7 +364,7 @@ pub(crate) fn status_response(core: &Core, username: &str, mountpoint: &Path) ->
|
||||
let queued = core.db.pending_op_counts().unwrap_or_default();
|
||||
// Read after the queue: the drain counts an upload as landing before it
|
||||
// retires the op, so one of the two always has it (B119).
|
||||
let landing = core.landing_uploads.load(Ordering::SeqCst);
|
||||
let landing = core.drain.landing_uploads.load(Ordering::SeqCst);
|
||||
let staging = core.cache.staging_usage();
|
||||
CtlResponse::Status {
|
||||
parked_uploads: queued.parked.max(0) as u64,
|
||||
|
||||
@@ -18,7 +18,7 @@ use std::sync::{Arc, LazyLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::control::{Diagnostics, DriveCallStat, InflightRequest, WorkerState};
|
||||
use pdfs_core::control::{Diagnostics, DriveCallStat, InflightRequest, ServiceState, WorkerState};
|
||||
|
||||
use super::Core;
|
||||
|
||||
@@ -164,6 +164,16 @@ impl Core {
|
||||
control_handler_limit: super::control::handler_limit(),
|
||||
pending_ops: self.pending_ops_quickly(),
|
||||
sync: Some(self.sync.engine.report()),
|
||||
services: self
|
||||
.services
|
||||
.health()
|
||||
.into_iter()
|
||||
.map(|service| ServiceState {
|
||||
name: service.name,
|
||||
running: service.running,
|
||||
age_secs: service.age.as_secs(),
|
||||
})
|
||||
.collect(),
|
||||
drive_calls: self
|
||||
.drive_calls
|
||||
.snapshot()
|
||||
|
||||
@@ -27,7 +27,7 @@ use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use parking_lot::{Condvar, Mutex};
|
||||
|
||||
use pdfs_core::batch;
|
||||
use pdfs_core::control::{ActivityKind, SyncIssue, TransferDirection};
|
||||
@@ -53,6 +53,65 @@ use super::{
|
||||
use proton_drive_rs::proton_sdk::api::ResponseCode;
|
||||
use proton_drive_rs::proton_sdk::error::ProtonError;
|
||||
|
||||
/// The drain's own bookkeeping, shared by its workers and by every mount of
|
||||
/// the daemon: the wake-up for idle workers, the creates and uploads on the
|
||||
/// wire, and what a landed one left behind until the tree catches up.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct DrainState {
|
||||
/// Nudges the drain workers: set true and notify to have them re-examine
|
||||
/// the queue instead of waiting out their backoff.
|
||||
pub(crate) drain_wake: Arc<(Mutex<bool>, Condvar)>,
|
||||
/// The folder and name each create on the wire was sent with, by op id.
|
||||
/// Drive holds that name until the create lands and a rename or trash
|
||||
/// queued behind it frees it again.
|
||||
pub(crate) creating: Arc<Mutex<HashMap<i64, (NodeUid, String)>>>,
|
||||
/// Creates that landed but could not be read back, by the uid Drive gave
|
||||
/// them, with the placeholder's. The drain adopts one before it sends
|
||||
/// anything else for it.
|
||||
pub(crate) unadopted: Arc<Mutex<HashMap<NodeUid, NodeUid>>>,
|
||||
/// The SHA-1 of the last revision this daemon uploaded to a file and could
|
||||
/// not read back, so its revision id is not known (`docs/BUGS.md` B157).
|
||||
pub(crate) sealed_unread: Arc<Mutex<HashMap<NodeUid, String>>>,
|
||||
/// The node an upload has just put on Drive, from when the drain lets go
|
||||
/// of its blob until the tree has the node (`docs/BUGS.md` B170).
|
||||
pub(crate) landed: Arc<Mutex<HashMap<NodeUid, Node>>>,
|
||||
/// How long this node's last upload actually took, in milliseconds, with
|
||||
/// the time it was measured for eviction. Feeds
|
||||
/// [`Core::revision_debounce`]: a file that takes 30 seconds to send needs
|
||||
/// a grace period on that scale, or every save supersedes an upload that
|
||||
/// was already on the wire. Bounded by [`UPLOAD_TIME_MEMORY`].
|
||||
pub(crate) upload_times: Arc<Mutex<HashMap<String, (u64, i64)>>>,
|
||||
/// Cancellation flags for uploads currently on the wire, keyed by node.
|
||||
///
|
||||
/// Set when a newer revision of the same file is queued: the bytes in
|
||||
/// flight have just been superseded, and the only thing finishing them
|
||||
/// achieves is spending the user's uplink on a revision the next op
|
||||
/// replaces. Read by the upload's own reader ([`CountingReader`]), which is
|
||||
/// the one thing the SDK calls often enough to notice.
|
||||
pub(crate) upload_cancel: Arc<Mutex<HashMap<NodeUid, Arc<AtomicBool>>>>,
|
||||
/// Uploads whose op is retired but whose bytes the content cache has not
|
||||
/// adopted yet, because the revision just sealed is still being read back.
|
||||
/// The status counts them as pending, so an empty queue means every file
|
||||
/// written through the mount reads without the network (`docs/BUGS.md`
|
||||
/// B119).
|
||||
pub(crate) landing_uploads: Arc<AtomicU64>,
|
||||
}
|
||||
|
||||
impl DrainState {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
drain_wake: Arc::new((Mutex::new(false), Condvar::new())),
|
||||
creating: Arc::new(Mutex::new(HashMap::new())),
|
||||
unadopted: Arc::new(Mutex::new(HashMap::new())),
|
||||
sealed_unread: Arc::new(Mutex::new(HashMap::new())),
|
||||
landed: Arc::new(Mutex::new(HashMap::new())),
|
||||
upload_times: Arc::new(Mutex::new(HashMap::new())),
|
||||
upload_cancel: Arc::new(Mutex::new(HashMap::new())),
|
||||
landing_uploads: Arc::new(AtomicU64::new(0)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TrashedMove(String);
|
||||
|
||||
@@ -659,6 +718,7 @@ impl Core {
|
||||
/// [`DRAIN_REVISION_DEBOUNCE_MAX`]: super::DRAIN_REVISION_DEBOUNCE_MAX
|
||||
pub(crate) fn revision_debounce(&self, uid: &NodeUid) -> Duration {
|
||||
let measured = self
|
||||
.drain
|
||||
.upload_times
|
||||
.lock()
|
||||
.get(&uid.to_string())
|
||||
@@ -674,7 +734,7 @@ impl Core {
|
||||
/// takes to send, and feeding that back would let one network fault widen
|
||||
/// the debounce for good.
|
||||
fn record_upload_time(&self, uid: &NodeUid, took: Duration) {
|
||||
let mut times = self.upload_times.lock();
|
||||
let mut times = self.drain.upload_times.lock();
|
||||
let now = now_millis();
|
||||
if times.len() >= UPLOAD_TIME_MEMORY
|
||||
&& !times.contains_key(&uid.to_string())
|
||||
@@ -697,9 +757,12 @@ impl Core {
|
||||
/// leave the newer upload uncancellable.
|
||||
fn begin_cancellable_upload(&self, uid: &NodeUid) -> UploadCancel {
|
||||
let flag = Arc::new(AtomicBool::new(false));
|
||||
self.upload_cancel.lock().insert(uid.clone(), flag.clone());
|
||||
self.drain
|
||||
.upload_cancel
|
||||
.lock()
|
||||
.insert(uid.clone(), flag.clone());
|
||||
UploadCancel {
|
||||
registry: self.upload_cancel.clone(),
|
||||
registry: self.drain.upload_cancel.clone(),
|
||||
uid: uid.clone(),
|
||||
flag,
|
||||
}
|
||||
@@ -712,7 +775,7 @@ impl Core {
|
||||
/// 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.upload_cancel.lock().get(uid) {
|
||||
if let Some(flag) = self.drain.upload_cancel.lock().get(uid) {
|
||||
flag.store(true, Ordering::Relaxed);
|
||||
debug!(%uid, "cancelling a superseded upload");
|
||||
}
|
||||
@@ -722,7 +785,7 @@ impl Core {
|
||||
/// the shortest outstanding backoff elapsing.
|
||||
pub(crate) fn wait_for_drain_work(&self) {
|
||||
sleep_for_drain_work(
|
||||
&self.drain_wake,
|
||||
&self.drain.drain_wake,
|
||||
|| self.shutdown.is_stopping(),
|
||||
DRAIN_IDLE_POLL,
|
||||
);
|
||||
@@ -741,7 +804,11 @@ impl Core {
|
||||
None
|
||||
};
|
||||
let timeout = idle_wait(claiming, earliest, now_millis());
|
||||
sleep_for_drain_work(&self.drain_wake, || self.shutdown.is_stopping(), timeout);
|
||||
sleep_for_drain_work(
|
||||
&self.drain.drain_wake,
|
||||
|| self.shutdown.is_stopping(),
|
||||
timeout,
|
||||
);
|
||||
}
|
||||
|
||||
/// Perform one queued op and retire it.
|
||||
@@ -767,7 +834,7 @@ impl Core {
|
||||
let Some(real) = parse_node_uid(&op.uid) else {
|
||||
return Ok(());
|
||||
};
|
||||
let local = match self.unadopted.lock().get(&real).cloned() {
|
||||
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
|
||||
@@ -779,7 +846,7 @@ impl Core {
|
||||
if self.fetch_node_remote(&real)?.is_some() {
|
||||
self.adopt_real_uid(&local, &real, |_| {})?;
|
||||
}
|
||||
self.unadopted.lock().remove(&real);
|
||||
self.drain.unadopted.lock().remove(&real);
|
||||
debug!(%local, %real, "adopted a landed create");
|
||||
Ok(())
|
||||
}
|
||||
@@ -1176,12 +1243,13 @@ impl Core {
|
||||
if let (Some(parent), Some(name)) = (op.parent_uid.as_deref(), op.name.as_deref())
|
||||
&& let Some(parent) = parse_node_uid(parent)
|
||||
{
|
||||
self.creating
|
||||
self.drain
|
||||
.creating
|
||||
.lock()
|
||||
.insert(op.id, (parent, name.to_string()));
|
||||
}
|
||||
let created = self.create_local_node(op);
|
||||
self.creating.lock().remove(&op.id);
|
||||
self.drain.creating.lock().remove(&op.id);
|
||||
created
|
||||
}
|
||||
|
||||
@@ -1317,7 +1385,7 @@ impl Core {
|
||||
// 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.landing_uploads);
|
||||
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);
|
||||
@@ -1345,7 +1413,10 @@ impl Core {
|
||||
}
|
||||
}) {
|
||||
warn!(%local, %real, error = %e, "reading back a landed create failed; adopting it later");
|
||||
self.unadopted.lock().insert(real.clone(), local.clone());
|
||||
self.drain
|
||||
.unadopted
|
||||
.lock()
|
||||
.insert(real.clone(), local.clone());
|
||||
}
|
||||
// The feed will report this create back to us; the tree already has it
|
||||
// under its real uid, so that event is ours to ignore (`Core::self_changes`).
|
||||
@@ -1390,6 +1461,7 @@ impl Core {
|
||||
return Ok(false);
|
||||
}
|
||||
let creating = self
|
||||
.drain
|
||||
.creating
|
||||
.lock()
|
||||
.iter()
|
||||
@@ -1400,7 +1472,8 @@ impl Core {
|
||||
/// Whether a create other than `op` is on the wire under `name`, in any
|
||||
/// folder.
|
||||
fn creating_named(&self, op: &PendingOp, name: &str) -> bool {
|
||||
self.creating
|
||||
self.drain
|
||||
.creating
|
||||
.lock()
|
||||
.iter()
|
||||
.any(|(id, (_, n))| *id != op.id && n == name)
|
||||
@@ -1503,6 +1576,7 @@ impl Core {
|
||||
// first one's rename took the second one's bytes along
|
||||
// (docs/BUGS.md B147).
|
||||
let racing = self
|
||||
.drain
|
||||
.creating
|
||||
.lock()
|
||||
.iter()
|
||||
@@ -1953,7 +2027,7 @@ impl Core {
|
||||
// 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.sealed_unread.lock().get(uid).cloned();
|
||||
let sealed = self.drain.sealed_unread.lock().get(uid).cloned();
|
||||
if meta.complete
|
||||
&& let Some(sealed) = sealed
|
||||
&& let NodeKind::File {
|
||||
@@ -2394,7 +2468,7 @@ impl Core {
|
||||
// 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.landing_uploads);
|
||||
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.
|
||||
@@ -2479,7 +2553,7 @@ impl Core {
|
||||
.unwrap_or(false);
|
||||
let fetched = self.fetch_node_remote(uid);
|
||||
if fetched.is_ok() {
|
||||
self.sealed_unread.lock().remove(uid);
|
||||
self.drain.sealed_unread.lock().remove(uid);
|
||||
}
|
||||
let node = match fetched {
|
||||
Ok(Some(node)) => node,
|
||||
@@ -2495,10 +2569,10 @@ impl Core {
|
||||
the next write to this file may conflict with itself");
|
||||
match staged_sha1(blob) {
|
||||
Ok(sha) => {
|
||||
self.sealed_unread.lock().insert(uid.clone(), sha);
|
||||
self.drain.sealed_unread.lock().insert(uid.clone(), sha);
|
||||
}
|
||||
Err(_) => {
|
||||
self.sealed_unread.lock().remove(uid);
|
||||
self.drain.sealed_unread.lock().remove(uid);
|
||||
}
|
||||
}
|
||||
// No newer write took over, so the tree's stamp is this upload's.
|
||||
@@ -2553,14 +2627,14 @@ impl Core {
|
||||
// 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.landed.lock().insert(uid.clone(), node.clone());
|
||||
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.landed.lock().remove(uid);
|
||||
self.drain.landed.lock().remove(uid);
|
||||
Some(node)
|
||||
}
|
||||
|
||||
|
||||
@@ -1469,7 +1469,7 @@ impl ProtonFs {
|
||||
// a lock-tight comparison — against the multi-gigabyte copy
|
||||
// above, which is the window that actually loses data.
|
||||
let current = self.core.pending_blob(&uid);
|
||||
let landed = self.core.landed.lock().get(&uid).cloned();
|
||||
let landed = self.core.drain.landed.lock().get(&uid).cloned();
|
||||
let mut st = self.core.state();
|
||||
// Only a handle this open is about to *create* can carry a stale
|
||||
// base; if one already exists, that handle is authoritative and
|
||||
|
||||
+62
-1917
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,99 @@
|
||||
//! Database maintenance moved off the request thread: `VACUUM` and the deep
|
||||
//! integrity check, one at a time, with the last check's result kept.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Core {
|
||||
/// Start a background `VACUUM`, or refuse because maintenance is already
|
||||
/// running.
|
||||
///
|
||||
/// Returns as soon as the thread is spawned; the caller acknowledges the
|
||||
/// 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<()> {
|
||||
{
|
||||
let mut m = self.maintenance.lock();
|
||||
if m.running {
|
||||
return Err(CoreError::conflict(
|
||||
"database maintenance is already running",
|
||||
));
|
||||
}
|
||||
m.running = true;
|
||||
}
|
||||
let core = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
let job = core.transfers.begin_job("Compacting the cache database");
|
||||
job.detail("Rewriting the database file");
|
||||
let started = Instant::now();
|
||||
match core.db.vacuum() {
|
||||
Ok(outcome) => info!(
|
||||
freed_bytes = outcome.freed_bytes(),
|
||||
before_bytes = outcome.before_bytes,
|
||||
after_bytes = outcome.after_bytes,
|
||||
wal_frames = outcome.wal_frames_checkpointed,
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"cache database vacuumed"
|
||||
),
|
||||
Err(e) => warn!(error = %e, "vacuum failed"),
|
||||
}
|
||||
core.maintenance.lock().running = false;
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Answer a deep `CacheInspect`: hand back the last completed integrity
|
||||
/// check, and start one if none is running.
|
||||
///
|
||||
/// Returns `(problems, checked, running)`. A first request gets
|
||||
/// `(_, 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();
|
||||
if let Some(problems) = m.integrity.clone() {
|
||||
return (problems, true, m.running);
|
||||
}
|
||||
if m.running {
|
||||
return (Vec::new(), false, true);
|
||||
}
|
||||
m.running = true;
|
||||
drop(m);
|
||||
|
||||
let core = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
let job = core
|
||||
.transfers
|
||||
.begin_background_job("Checking the cache database");
|
||||
job.detail("Verifying every page");
|
||||
let problems = match core.db.integrity_check() {
|
||||
Ok(problems) => problems,
|
||||
Err(e) => vec![format!("integrity check failed: {e:?}")],
|
||||
};
|
||||
if problems.is_empty() {
|
||||
info!("cache database integrity check found no problems");
|
||||
} else {
|
||||
warn!(problems = problems.len(), "cache database integrity check");
|
||||
}
|
||||
let mut m = core.maintenance.lock();
|
||||
m.integrity = Some(problems);
|
||||
m.running = false;
|
||||
});
|
||||
(Vec::new(), false, true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Background database maintenance: what is running, and what the last deep
|
||||
/// integrity check found.
|
||||
///
|
||||
/// One at a time — both operations are whole-database and there is nothing to
|
||||
/// 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 {
|
||||
/// A vacuum or integrity check is running right now.
|
||||
running: bool,
|
||||
/// Findings of the most recent completed deep check. `None` means none has
|
||||
/// finished this run, which is *not* the same as "found nothing".
|
||||
integrity: Option<Vec<String>>,
|
||||
}
|
||||
+91
-123
@@ -1,6 +1,7 @@
|
||||
//! Mount lifecycle and background-service orchestration.
|
||||
|
||||
use super::*;
|
||||
use pdfs_core::lifecycle::{ServiceBoard, Services, Wake};
|
||||
|
||||
/// Why a [`mount`] call returned. Lets the daemon decide whether to exit (clean
|
||||
/// shutdown) or remount (the mount went away under it).
|
||||
@@ -495,7 +496,7 @@ pub(crate) fn mount_with(
|
||||
let shutdown = Arc::new(crate::shutdown::Shutdown::default());
|
||||
let transfers = TransferRegistry::new();
|
||||
let sync = sync::SyncParts {
|
||||
db: db.clone(),
|
||||
store: db.clone(),
|
||||
drive: drive.clone(),
|
||||
rt: rt.clone(),
|
||||
cache: cache.clone(),
|
||||
@@ -525,56 +526,26 @@ pub(crate) fn mount_with(
|
||||
)),
|
||||
root: Arc::new(OnceLock::new()),
|
||||
cache,
|
||||
readers: Arc::new(Mutex::new(HashMap::new())),
|
||||
block_ring: Arc::new(Mutex::new(BlockRing::default())),
|
||||
block_flight: Arc::new(BlockFlight::default()),
|
||||
content_repairs: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
|
||||
prefetch: Arc::new(Prefetch::default()),
|
||||
prefetch_budget: Arc::new(tokio::sync::Semaphore::new(PREFETCH_BUDGET)),
|
||||
reads: super::reads::ReadState::new(),
|
||||
workers: Arc::new(Workers::new(FUSE_WORKERS)?),
|
||||
db,
|
||||
shared_publication: Arc::new(Ranked::new(Rank::SharedPublication, ())),
|
||||
shared_generation: Arc::new(AtomicU64::new(0)),
|
||||
shared_refresh_deadlines: Arc::new(Mutex::new(SharedRefreshDeadlines::default())),
|
||||
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())),
|
||||
creating: Arc::new(Mutex::new(HashMap::new())),
|
||||
sealed_unread: Arc::new(Mutex::new(HashMap::new())),
|
||||
landed: Arc::new(Mutex::new(HashMap::new())),
|
||||
unadopted: Arc::new(Mutex::new(HashMap::new())),
|
||||
drain_wake: Arc::new((Mutex::new(false), Condvar::new())),
|
||||
drain: super::drain::DrainState::new(),
|
||||
pin_work: Arc::new(Mutex::new(Default::default())),
|
||||
sizes: super::sizes::SizeState::new(),
|
||||
trash: super::trash::TrashState::new(),
|
||||
shared: super::shared::SharedState::new(),
|
||||
quota_cache: super::sharing::QuotaCache::new(),
|
||||
sweep: super::sweep::SweepState::new(sweep_mode),
|
||||
shutdown,
|
||||
upload_times: Arc::new(Mutex::new(HashMap::new())),
|
||||
upload_cancel: Arc::new(Mutex::new(HashMap::new())),
|
||||
landing_uploads: Arc::new(AtomicU64::new(0)),
|
||||
timeline_refreshing: Arc::new(AtomicBool::new(false)),
|
||||
timeline_progress: Arc::new(Mutex::new(None)),
|
||||
similar_hashing: Arc::new(AtomicBool::new(false)),
|
||||
albums_refreshing: Arc::new(AtomicBool::new(false)),
|
||||
trash_refreshing: Arc::new(AtomicBool::new(false)),
|
||||
trash_progress: Arc::new(tokio::sync::Notify::new()),
|
||||
conflict_notified: Arc::new(Mutex::new(HashSet::new())),
|
||||
sweep_mode,
|
||||
services: ServiceBoard::default(),
|
||||
photo_jobs: super::photos::PhotoJobs::new(),
|
||||
local_first,
|
||||
self_changes: Arc::new(Mutex::new(HashMap::new())),
|
||||
thumb_gen: Arc::new(Mutex::new(HashSet::new())),
|
||||
thumb_gen_budget: Arc::new(tokio::sync::Semaphore::new(
|
||||
super::photos::THUMB_GEN_CONCURRENCY,
|
||||
)),
|
||||
file_thumb_generation: Arc::new(AtomicU64::new(0)),
|
||||
file_thumb_cancel: Arc::new(tokio::sync::Notify::new()),
|
||||
thumbnail_build: Arc::new(Mutex::new(Default::default())),
|
||||
thumbnail_build_cancelled: Arc::new(AtomicBool::new(false)),
|
||||
thumbnail_build_cancel: Arc::new(tokio::sync::Notify::new()),
|
||||
thumbnail_misses: Arc::new(Mutex::new(Default::default())),
|
||||
quota: Arc::new(Mutex::new(None)),
|
||||
quota_refreshing: Arc::new(AtomicBool::new(false)),
|
||||
size_upgrades: Arc::new(Mutex::new(HashMap::new())),
|
||||
size_waiters: Arc::new(Default::default()),
|
||||
notifier: Arc::new(OnceLock::new()),
|
||||
session_live: Arc::new(AtomicBool::new(false)),
|
||||
transfers,
|
||||
@@ -610,18 +581,36 @@ pub(crate) fn mount_with(
|
||||
// joined at the end of this function. Leaving them running turned an
|
||||
// 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: Vec<std::thread::JoinHandle<()>> = Vec::new();
|
||||
let mut workers = Services::new(core.services.clone());
|
||||
for worker in 0..DRAIN_WORKERS {
|
||||
let drain_core = core.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name(format!("pdfs-drain-{worker}"))
|
||||
.spawn(move || drain_core.run_pending_drain(worker == 0));
|
||||
// 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)?;
|
||||
}
|
||||
|
||||
// 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.
|
||||
workers.extend(sync::spawn(core.syncer(), sync_rx));
|
||||
// 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);
|
||||
@@ -637,9 +626,9 @@ pub(crate) fn mount_with(
|
||||
} else {
|
||||
info!(mode = ?sweep_mode, "conflict sweep enabled");
|
||||
let sweep_core = core.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("pdfs-conflict-sweep".into())
|
||||
.spawn(move || sweep_core.run_conflict_sweep_loop());
|
||||
let spawned = workers.spawn("pdfs-conflict-sweep", None, move || {
|
||||
sweep_core.run_conflict_sweep_loop()
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
}
|
||||
|
||||
@@ -648,9 +637,9 @@ pub(crate) fn mount_with(
|
||||
// must notice it coming back just the same.
|
||||
{
|
||||
let probe_core = core.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("pdfs-online-probe".into())
|
||||
.spawn(move || probe_core.run_online_probe());
|
||||
let spawned = workers.spawn("pdfs-online-probe", None, move || {
|
||||
probe_core.run_online_probe()
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
}
|
||||
|
||||
@@ -659,9 +648,9 @@ pub(crate) fn mount_with(
|
||||
// B282). Its own thread: a check lists folders and downloads files.
|
||||
{
|
||||
let keeper_core = core.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("pdfs-pin-keeper".into())
|
||||
.spawn(move || keeper_core.run_pin_keeper());
|
||||
let spawned = workers.spawn("pdfs-pin-keeper", None, move || {
|
||||
keeper_core.run_pin_keeper()
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
}
|
||||
|
||||
@@ -676,9 +665,9 @@ pub(crate) fn mount_with(
|
||||
let transfers = core.transfers.clone();
|
||||
let mountpoint = mountpoint.to_path_buf();
|
||||
let shutdown = core.shutdown.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("pdfs-localindex".into())
|
||||
.spawn(move || run_local_index(db, indexing, transfers, mountpoint, shutdown));
|
||||
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)?;
|
||||
}
|
||||
|
||||
@@ -722,11 +711,21 @@ pub(crate) fn mount_with(
|
||||
let control_core = core.clone();
|
||||
let username = username.clone();
|
||||
let mountpoint = mountpoint.to_path_buf();
|
||||
match std::thread::Builder::new()
|
||||
.name("pdfs-control".into())
|
||||
.spawn(move || run_control_socket(control_core, username, mountpoint, listener))
|
||||
{
|
||||
Ok(handle) => workers.push(handle),
|
||||
// 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)
|
||||
}) {
|
||||
Ok(()) => {}
|
||||
Err(error) => {
|
||||
// A failure here abandons the mount, so the background threads
|
||||
// started above have to be told to stop with it.
|
||||
@@ -753,14 +752,12 @@ pub(crate) fn mount_with(
|
||||
let sampler_core = core.clone();
|
||||
let username = username.clone();
|
||||
let mountpoint = mountpoint.to_path_buf();
|
||||
match std::thread::Builder::new()
|
||||
.name("pdfs-events".into())
|
||||
.spawn(move || events::run_event_sampler(sampler_core, username, mountpoint))
|
||||
{
|
||||
Ok(handle) => workers.push(handle),
|
||||
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.
|
||||
Err(error) => warn!(error = %error, "could not start the event sampler"),
|
||||
warn!(error = %error, "could not start the event sampler");
|
||||
}
|
||||
}
|
||||
// The supervisor watches the pool and answers the systemd watchdog. Started
|
||||
@@ -769,14 +766,12 @@ pub(crate) fn mount_with(
|
||||
{
|
||||
let supervisor_core = core.clone();
|
||||
let socket = control_socket.to_path_buf();
|
||||
match std::thread::Builder::new()
|
||||
.name("pdfs-supervisor".into())
|
||||
.spawn(move || supervisor::run(supervisor_core, socket))
|
||||
{
|
||||
Ok(handle) => workers.push(handle),
|
||||
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.
|
||||
Err(error) => warn!(error = %error, "could not start the daemon supervisor"),
|
||||
warn!(error = %error, "could not start the daemon supervisor");
|
||||
}
|
||||
}
|
||||
// The mount is live and the control socket answers: this is the moment the
|
||||
@@ -823,10 +818,9 @@ pub(crate) fn mount_with(
|
||||
// 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) = std::thread::Builder::new()
|
||||
.name("pdfs-inhibit".into())
|
||||
.spawn(move || crate::inhibit::run(inhibit_core))
|
||||
{
|
||||
if let Err(error) = workers.spawn("pdfs-inhibit", None, move || {
|
||||
crate::inhibit::run(inhibit_core)
|
||||
}) {
|
||||
warn!(%error, "start the shutdown inhibitor failed");
|
||||
}
|
||||
}
|
||||
@@ -958,7 +952,7 @@ const WORKER_JOIN_DEADLINE: Duration = Duration::from_secs(10);
|
||||
/// expected and correct: a worker part-way through an upload finishes it rather
|
||||
/// than abandoning the user's bytes mid-flight. Up to [`WORKER_JOIN_DEADLINE`]:
|
||||
/// past it, systemd kills the daemon anyway, and a queued op is sent again.
|
||||
fn stop_workers(core: &Core, control_socket: &Path, workers: Vec<std::thread::JoinHandle<()>>) {
|
||||
fn stop_workers(core: &Core, control_socket: &Path, workers: Services) {
|
||||
// Say so before the joins: a teardown that takes a while must not be read as
|
||||
// a missed watchdog ping and turned into a kill.
|
||||
systemd::stopping();
|
||||
@@ -973,7 +967,7 @@ fn stop_workers(core: &Core, control_socket: &Path, workers: Vec<std::thread::Jo
|
||||
/// (`docs/BUGS.md` B264). Unlike [`stop_workers`] this does not tell systemd
|
||||
/// the daemon is stopping, because it is about to try again, and a manager
|
||||
/// told so would wait for the process to exit and then kill it.
|
||||
fn abandon_workers(core: &Core, control_socket: &Path, workers: Vec<std::thread::JoinHandle<()>>) {
|
||||
fn abandon_workers(core: &Core, control_socket: &Path, workers: Services) {
|
||||
halt_workers(core, control_socket, workers);
|
||||
}
|
||||
|
||||
@@ -982,37 +976,30 @@ fn abandon_workers(core: &Core, control_socket: &Path, workers: Vec<std::thread:
|
||||
fn keep_or_abandon(
|
||||
core: &Core,
|
||||
control_socket: &Path,
|
||||
workers: &mut Vec<std::thread::JoinHandle<()>>,
|
||||
spawned: std::io::Result<std::thread::JoinHandle<()>>,
|
||||
workers: &mut Services,
|
||||
spawned: std::io::Result<()>,
|
||||
) -> std::io::Result<()> {
|
||||
match spawned {
|
||||
Ok(handle) => {
|
||||
workers.push(handle);
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => {
|
||||
abandon_workers(core, control_socket, std::mem::take(workers));
|
||||
Err(error)
|
||||
}
|
||||
if let Err(error) = spawned {
|
||||
let started = std::mem::replace(workers, Services::new(core.services.clone()));
|
||||
abandon_workers(core, control_socket, started);
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Signal every worker to stop, then join them up to [`WORKER_JOIN_DEADLINE`].
|
||||
fn halt_workers(core: &Core, control_socket: &Path, workers: Vec<std::thread::JoinHandle<()>>) {
|
||||
core.shutdown.stop();
|
||||
///
|
||||
/// Each worker was started with the call that wakes it, if it blocks where the
|
||||
/// shutdown signal does not reach; [`Services::stop`] makes those calls.
|
||||
fn halt_workers(core: &Core, control_socket: &Path, workers: Services) {
|
||||
if let Some(gallery) = &core.gallery {
|
||||
gallery.cancel();
|
||||
}
|
||||
core.wake_drain();
|
||||
let _ = core.sync.tx.send(sync::SyncMsg::Stop);
|
||||
// Connect while the socket still exists — that is the whole point of the
|
||||
// poke — then unlink it so nothing else can arrive behind us. The listener
|
||||
// re-checks the flag after every accept, so even a connection that races the
|
||||
// unlink cannot put it back to sleep.
|
||||
let _ = std::os::unix::net::UnixStream::connect(control_socket);
|
||||
let _ = std::fs::remove_file(control_socket);
|
||||
let deadline = Instant::now() + WORKER_JOIN_DEADLINE;
|
||||
let running = join_until(workers, deadline);
|
||||
let running = workers.stop(&core.shutdown, deadline);
|
||||
// A mount that failed before the control thread started has no wake to
|
||||
// unlink its socket.
|
||||
let _ = std::fs::remove_file(control_socket);
|
||||
if !running.is_empty() {
|
||||
warn!(
|
||||
running = running.join(","),
|
||||
@@ -1029,32 +1016,13 @@ fn halt_workers(core: &Core, control_socket: &Path, workers: Vec<std::thread::Jo
|
||||
debug!("background workers stopped");
|
||||
}
|
||||
|
||||
/// Join `workers` until `deadline`, and name the ones still running then.
|
||||
///
|
||||
/// A stop used to wait for each one however long it took. The sync engine's
|
||||
/// mirror pass waits on Drive with no deadline, and a stop that waited for it
|
||||
/// was killed by systemd (`docs/BUGS.md` B165).
|
||||
fn join_until(workers: Vec<std::thread::JoinHandle<()>>, deadline: Instant) -> Vec<String> {
|
||||
let mut running = Vec::new();
|
||||
for worker in workers {
|
||||
while !worker.is_finished() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
if !worker.is_finished() {
|
||||
running.push(worker.thread().name().unwrap_or("unnamed").to_string());
|
||||
} else if worker.join().is_err() {
|
||||
warn!("a background worker panicked before shutdown");
|
||||
}
|
||||
}
|
||||
running
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::{SecondaryInsertRejection, SecondaryMountRegistry, join_until, teardown_session};
|
||||
use super::{SecondaryInsertRejection, SecondaryMountRegistry, teardown_session};
|
||||
use pdfs_core::lifecycle::join_until;
|
||||
|
||||
#[test]
|
||||
fn a_stop_names_the_workers_still_running_at_its_deadline() {
|
||||
|
||||
+186
-59
@@ -12,11 +12,12 @@ use std::io::{Read as _, Write as _};
|
||||
use std::os::unix::fs::{FileExt as _, OpenOptionsExt as _};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Once, OnceLock};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Once, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use base64::Engine as _;
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::control::{
|
||||
FileThumbRequest, MappingProgress, PhotoItem, PhotoKind, PhotoLocation, PhotoThumb, PlaceInfo,
|
||||
ThumbnailBuildStatus, Topic, is_audio_file_name, is_raw_image_name, is_thumbnail_image_name,
|
||||
@@ -32,8 +33,8 @@ use tracing::{debug, info, warn};
|
||||
|
||||
use super::drive::RevisionRead;
|
||||
use super::{
|
||||
Core, PHOTOS_AVAILABLE, PHOTOS_SYNCED_MS, TIMELINE_ENRICH_CHUNK, WriteAuthority, link,
|
||||
node_size, now_ms, parse_uid,
|
||||
Core, PHOTOS_AVAILABLE, PHOTOS_SYNCED_MS, TIMELINE_ENRICH_CHUNK, ThumbnailMissCaches,
|
||||
WriteAuthority, link, node_size, now_ms, parse_uid,
|
||||
};
|
||||
|
||||
/// Longest edge, in px, of a thumbnail generated locally for a photo the server
|
||||
@@ -46,6 +47,7 @@ const THUMB_QUALITY: u8 = 82;
|
||||
/// thumbnails. Bounded: a screenful of 20 MB digicam JPEGs would otherwise
|
||||
/// saturate the link and starve the rest of the daemon.
|
||||
pub(crate) const THUMB_GEN_CONCURRENCY: usize = 4;
|
||||
|
||||
/// Shots the similar-photo pass fetches thumbnails for at a time.
|
||||
const SIMILAR_CHUNK: usize = 64;
|
||||
/// Images processed between recursive-build progress updates.
|
||||
@@ -127,6 +129,75 @@ const DECODE_BUDGET_BYTES: u64 = 512 * 1024 * 1024;
|
||||
/// The process-wide [`DecodeBudget`] every thumbnail decode draws from.
|
||||
static DECODE_BUDGET: DecodeBudget = DecodeBudget::new(DECODE_BUDGET_BYTES);
|
||||
|
||||
/// What the Photos and thumbnail jobs are doing right now: which refreshes
|
||||
/// and builds are running, how far they got, and which thumbnails are known
|
||||
/// to be missing. Shared by every mount of the daemon; only this module and
|
||||
/// the status reports read it.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct PhotoJobs {
|
||||
/// True while a background refresh of the photos timeline is already
|
||||
/// running, so a burst of page requests against a stale listing kicks off
|
||||
/// one refresh rather than one per request.
|
||||
pub(crate) timeline_refreshing: Arc<AtomicBool>,
|
||||
/// How far the running timeline refresh has got resolving photo metadata,
|
||||
/// as `(done, total)` photos; `None` when no refresh is resolving any. The
|
||||
/// Places view shows it while a library's locations are first read.
|
||||
pub(crate) timeline_progress: Arc<Mutex<Option<(usize, usize)>>>,
|
||||
/// The same, for the album listing.
|
||||
pub(crate) albums_refreshing: Arc<AtomicBool>,
|
||||
/// True while the similar-photo pass hashes thumbnails (see
|
||||
/// [`Core::photo_similar`]), so asking again doesn't start a second one.
|
||||
pub(crate) similar_hashing: Arc<AtomicBool>,
|
||||
/// Photos whose missing thumbnail is being generated right now. A tile that is
|
||||
/// still on screen asks for its thumbnail again every few seconds, and each of
|
||||
/// those downloads is a full-size photo — so an in-flight uid is never started
|
||||
/// twice.
|
||||
pub(crate) thumb_gen: Arc<Mutex<HashSet<NodeUid>>>,
|
||||
/// Global permit pool for locally generated thumbnails. The old per-request
|
||||
/// limit multiplied when the GUI sent several batches, allowing dozens of
|
||||
/// full-size images to download at once.
|
||||
pub(crate) thumb_gen_budget: Arc<tokio::sync::Semaphore>,
|
||||
/// Current ordinary-file listing generation and a wake-up for tasks waiting
|
||||
/// on a permit or a download when that listing is abandoned.
|
||||
pub(crate) file_thumb_generation: Arc<AtomicU64>,
|
||||
pub(crate) file_thumb_cancel: Arc<tokio::sync::Notify>,
|
||||
/// Progress of the explicit recursive build started from the Files toolbar.
|
||||
pub(crate) thumbnail_build: Arc<Mutex<ThumbnailBuildStatus>>,
|
||||
/// Cancellation for the explicit recursive build. Separate from ordinary
|
||||
/// listing cancellation because the two jobs have independent lifetimes.
|
||||
pub(crate) thumbnail_build_cancelled: Arc<AtomicBool>,
|
||||
pub(crate) thumbnail_build_cancel: Arc<tokio::sync::Notify>,
|
||||
/// Negative thumbnail knowledge, separated by whether the remote lacked a
|
||||
/// thumbnail or local decoding proved this revision unsupported.
|
||||
///
|
||||
/// Absence has to be cached or it costs a round trip every time it is asked
|
||||
/// for, and it is asked for constantly: an `ls -l` from an xattr-aware lister
|
||||
/// issues a `getxattr` per advertised name per entry, so a 65-file directory
|
||||
/// of videos re-probed 130 times per listing at ~186 ms each (B5). The mtime
|
||||
/// is the validity tag — a new revision may well have a thumbnail — matching
|
||||
/// how [`ContentCache::read_thumbnail`] validates the positive side.
|
||||
pub(crate) thumbnail_misses: Arc<Mutex<ThumbnailMissCaches>>,
|
||||
}
|
||||
|
||||
impl PhotoJobs {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
timeline_refreshing: Arc::new(AtomicBool::new(false)),
|
||||
timeline_progress: Arc::new(Mutex::new(None)),
|
||||
albums_refreshing: Arc::new(AtomicBool::new(false)),
|
||||
similar_hashing: Arc::new(AtomicBool::new(false)),
|
||||
thumb_gen: Arc::new(Mutex::new(HashSet::new())),
|
||||
thumb_gen_budget: Arc::new(tokio::sync::Semaphore::new(THUMB_GEN_CONCURRENCY)),
|
||||
file_thumb_generation: Arc::new(AtomicU64::new(0)),
|
||||
file_thumb_cancel: Arc::new(tokio::sync::Notify::new()),
|
||||
thumbnail_build: Arc::new(Mutex::new(Default::default())),
|
||||
thumbnail_build_cancelled: Arc::new(AtomicBool::new(false)),
|
||||
thumbnail_build_cancel: Arc::new(tokio::sync::Notify::new()),
|
||||
thumbnail_misses: Arc::new(Mutex::new(Default::default())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A counting gate over bytes: [`acquire`](Self::acquire) waits until the cost
|
||||
/// fits beside what is already held.
|
||||
struct DecodeBudget {
|
||||
@@ -1301,6 +1372,7 @@ impl Core {
|
||||
let sets = self.db.photo_similar().map_err(CoreError::from)?;
|
||||
let (done, total) = self.db.similar_progress().map_err(CoreError::from)?;
|
||||
let hashing = self
|
||||
.photo_jobs
|
||||
.similar_hashing
|
||||
.load(Ordering::SeqCst)
|
||||
.then_some(MappingProgress { done, total });
|
||||
@@ -1313,7 +1385,7 @@ impl Core {
|
||||
}
|
||||
|
||||
fn spawn_similar_hashing(&self) {
|
||||
if self.similar_hashing.swap(true, Ordering::SeqCst) {
|
||||
if self.photo_jobs.similar_hashing.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
let core = self.clone();
|
||||
@@ -1323,11 +1395,15 @@ impl Core {
|
||||
if let Err(e) = core.hash_similar() {
|
||||
warn!(error = %e, "similar-photo hashing failed");
|
||||
}
|
||||
core.similar_hashing.store(false, Ordering::SeqCst);
|
||||
core.photo_jobs
|
||||
.similar_hashing
|
||||
.store(false, Ordering::SeqCst);
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
warn!(error = %e, "could not start similar-photo hashing");
|
||||
self.similar_hashing.store(false, Ordering::SeqCst);
|
||||
self.photo_jobs
|
||||
.similar_hashing
|
||||
.store(false, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1697,7 +1773,7 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
let pending = self.thumb_gen.lock();
|
||||
let pending = self.photo_jobs.thumb_gen.lock();
|
||||
requested
|
||||
.iter()
|
||||
.zip(uids)
|
||||
@@ -1748,8 +1824,8 @@ impl Core {
|
||||
items: &[FileThumbRequest],
|
||||
generation: u64,
|
||||
) -> Option<Vec<PhotoThumb>> {
|
||||
let current =
|
||||
generation != 0 && self.file_thumb_generation.load(Ordering::SeqCst) == generation;
|
||||
let current = generation != 0
|
||||
&& self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation;
|
||||
if !current {
|
||||
return None;
|
||||
}
|
||||
@@ -1781,6 +1857,7 @@ impl Core {
|
||||
.cached_thumbnail_path(uid, ttype, *modified)
|
||||
.is_some()
|
||||
|| self
|
||||
.photo_jobs
|
||||
.thumbnail_misses
|
||||
.lock()
|
||||
.local_contains(&(uid.clone(), ttype), *modified)
|
||||
@@ -1795,7 +1872,7 @@ impl Core {
|
||||
self.spawn_generate_thumbs(wanted, &tags, &names, ThumbJob::Files(generation));
|
||||
}
|
||||
|
||||
let pending = self.thumb_gen.lock();
|
||||
let pending = self.photo_jobs.thumb_gen.lock();
|
||||
Some(
|
||||
items
|
||||
.iter()
|
||||
@@ -1821,13 +1898,14 @@ impl Core {
|
||||
pub(crate) fn reserve_file_thumb_generation(&self) -> u64 {
|
||||
let next = |current| if current == u64::MAX { 1 } else { current + 1 };
|
||||
let previous = self
|
||||
.photo_jobs
|
||||
.file_thumb_generation
|
||||
.try_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
|
||||
Some(next(current))
|
||||
})
|
||||
.expect("generation update always succeeds");
|
||||
let generation = next(previous);
|
||||
self.file_thumb_cancel.notify_waiters();
|
||||
self.photo_jobs.file_thumb_cancel.notify_waiters();
|
||||
generation
|
||||
}
|
||||
|
||||
@@ -1836,10 +1914,11 @@ impl Core {
|
||||
/// recursive builds do not use this generation and continue normally.
|
||||
pub(crate) fn cancel_file_thumbs(&self, generation: u64) {
|
||||
let previous = self
|
||||
.photo_jobs
|
||||
.file_thumb_generation
|
||||
.fetch_max(generation, Ordering::SeqCst);
|
||||
if generation > previous {
|
||||
self.file_thumb_cancel.notify_waiters();
|
||||
self.photo_jobs.file_thumb_cancel.notify_waiters();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1854,7 +1933,7 @@ impl Core {
|
||||
job: ThumbJob,
|
||||
) {
|
||||
let fresh: Vec<NodeUid> = {
|
||||
let mut inflight = self.thumb_gen.lock();
|
||||
let mut inflight = self.photo_jobs.thumb_gen.lock();
|
||||
uids.into_iter()
|
||||
.filter(|uid| inflight.insert(uid.clone()))
|
||||
.collect()
|
||||
@@ -1872,7 +1951,7 @@ impl Core {
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
core.generate_thumbs(&fresh, &tags, &names, job)
|
||||
}));
|
||||
let mut inflight = core.thumb_gen.lock();
|
||||
let mut inflight = core.photo_jobs.thumb_gen.lock();
|
||||
for uid in &fresh {
|
||||
inflight.remove(uid);
|
||||
}
|
||||
@@ -1894,10 +1973,13 @@ impl Core {
|
||||
fn thumb_job_current(&self, job: ThumbJob) -> bool {
|
||||
match job {
|
||||
ThumbJob::Files(generation) => {
|
||||
self.file_thumb_generation.load(Ordering::SeqCst) == generation
|
||||
self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation
|
||||
}
|
||||
ThumbJob::Photos => true,
|
||||
ThumbJob::Build => !self.thumbnail_build_cancelled.load(Ordering::SeqCst),
|
||||
ThumbJob::Build => !self
|
||||
.photo_jobs
|
||||
.thumbnail_build_cancelled
|
||||
.load(Ordering::SeqCst),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1934,13 +2016,13 @@ impl Core {
|
||||
// One shared permit pool bounds all thumbnail batches,
|
||||
// rather than multiplying the limit by every control
|
||||
// request the GUI happens to have in flight.
|
||||
let acquire = core.thumb_gen_budget.clone().acquire_owned();
|
||||
let acquire = core.photo_jobs.thumb_gen_budget.clone().acquire_owned();
|
||||
tokio::pin!(acquire);
|
||||
let _permit = match job {
|
||||
ThumbJob::Files(_) => loop {
|
||||
tokio::select! {
|
||||
permit = &mut acquire => break permit.ok(),
|
||||
_ = core.file_thumb_cancel.notified() => {
|
||||
_ = core.photo_jobs.file_thumb_cancel.notified() => {
|
||||
if !core.thumb_job_current(job) {
|
||||
return (uid, ThumbAttempt::Cancelled);
|
||||
}
|
||||
@@ -1955,7 +2037,7 @@ impl Core {
|
||||
ThumbJob::Build => loop {
|
||||
tokio::select! {
|
||||
permit = &mut acquire => break permit.ok(),
|
||||
_ = core.thumbnail_build_cancel.notified() => {
|
||||
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
|
||||
if !core.thumb_job_current(job) {
|
||||
return (uid, ThumbAttempt::Cancelled);
|
||||
}
|
||||
@@ -2015,7 +2097,7 @@ impl Core {
|
||||
ThumbJob::Files(_) => loop {
|
||||
tokio::select! {
|
||||
result = &mut download => break Some(result),
|
||||
_ = core.file_thumb_cancel.notified() => {
|
||||
_ = core.photo_jobs.file_thumb_cancel.notified() => {
|
||||
if !core.thumb_job_current(job) {
|
||||
break None;
|
||||
}
|
||||
@@ -2030,7 +2112,7 @@ impl Core {
|
||||
ThumbJob::Build => loop {
|
||||
tokio::select! {
|
||||
result = &mut download => break Some(result),
|
||||
_ = core.thumbnail_build_cancel.notified() => {
|
||||
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
|
||||
if !core.thumb_job_current(job) {
|
||||
break None;
|
||||
}
|
||||
@@ -2120,7 +2202,8 @@ impl Core {
|
||||
match self.cache.store_thumbnail(&uid, ttype, tag, &thumb.bytes) {
|
||||
Ok(()) => {
|
||||
summary.made += 1;
|
||||
self.thumbnail_misses
|
||||
self.photo_jobs
|
||||
.thumbnail_misses
|
||||
.lock()
|
||||
.forget_local(&(uid.clone(), ttype));
|
||||
self.record_thumb(&uid, db::THUMB_HAVE, Some(thumb.ratio));
|
||||
@@ -2136,7 +2219,8 @@ impl Core {
|
||||
ThumbAttempt::Undecodable => {
|
||||
summary.undecodable += 1;
|
||||
if let Some(&tag) = tags.get(&uid.to_string()) {
|
||||
self.thumbnail_misses
|
||||
self.photo_jobs
|
||||
.thumbnail_misses
|
||||
.lock()
|
||||
.remember_local((uid.clone(), ttype), tag);
|
||||
}
|
||||
@@ -2229,7 +2313,7 @@ impl Core {
|
||||
}
|
||||
|
||||
pub(crate) fn thumbnail_build_status(&self) -> ThumbnailBuildStatus {
|
||||
self.thumbnail_build.lock().clone()
|
||||
self.photo_jobs.thumbnail_build.lock().clone()
|
||||
}
|
||||
|
||||
/// Start one recursive local-thumbnail build. A request for the same root
|
||||
@@ -2238,11 +2322,12 @@ impl Core {
|
||||
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.thumbnail_build.lock();
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
if !thumbnail_build_may_start(&status, &path)? {
|
||||
return Ok(status.clone());
|
||||
}
|
||||
self.thumbnail_build_cancelled
|
||||
self.photo_jobs
|
||||
.thumbnail_build_cancelled
|
||||
.store(false, Ordering::SeqCst);
|
||||
*status = ThumbnailBuildStatus {
|
||||
running: true,
|
||||
@@ -2264,11 +2349,12 @@ impl Core {
|
||||
}))
|
||||
.is_err()
|
||||
{
|
||||
let mut status = core.thumbnail_build.lock();
|
||||
let mut status = core.photo_jobs.thumbnail_build.lock();
|
||||
status.running = false;
|
||||
status.scanning = false;
|
||||
status.message = Some("Thumbnail generation stopped unexpectedly".to_string());
|
||||
core.thumbnail_build_cancelled
|
||||
core.photo_jobs
|
||||
.thumbnail_build_cancelled
|
||||
.store(false, Ordering::SeqCst);
|
||||
warn!(path = %status.path, "recursive thumbnail build panicked");
|
||||
}
|
||||
@@ -2278,22 +2364,27 @@ impl Core {
|
||||
|
||||
pub(crate) fn cancel_thumbnail_build(&self) -> ThumbnailBuildStatus {
|
||||
let (status, cancelled) = {
|
||||
let status = self.thumbnail_build.lock();
|
||||
let status = self.photo_jobs.thumbnail_build.lock();
|
||||
let cancelled = status.running;
|
||||
if cancelled {
|
||||
self.thumbnail_build_cancelled.store(true, Ordering::SeqCst);
|
||||
self.photo_jobs
|
||||
.thumbnail_build_cancelled
|
||||
.store(true, Ordering::SeqCst);
|
||||
}
|
||||
(status.clone(), cancelled)
|
||||
};
|
||||
if cancelled {
|
||||
self.thumbnail_build_cancel.notify_waiters();
|
||||
self.photo_jobs.thumbnail_build_cancel.notify_waiters();
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
fn finish_thumbnail_build(&self) {
|
||||
let mut status = self.thumbnail_build.lock();
|
||||
let cancelled = self.thumbnail_build_cancelled.swap(false, Ordering::SeqCst);
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
let cancelled = self
|
||||
.photo_jobs
|
||||
.thumbnail_build_cancelled
|
||||
.swap(false, Ordering::SeqCst);
|
||||
status.running = false;
|
||||
status.scanning = false;
|
||||
if cancelled {
|
||||
@@ -2315,19 +2406,23 @@ impl Core {
|
||||
let mut seen_images = HashSet::new();
|
||||
|
||||
while let Some(folder) = folders.pop() {
|
||||
if self.thumbnail_build_cancelled.load(Ordering::SeqCst) {
|
||||
if self
|
||||
.photo_jobs
|
||||
.thumbnail_build_cancelled
|
||||
.load(Ordering::SeqCst)
|
||||
{
|
||||
self.finish_thumbnail_build();
|
||||
return;
|
||||
}
|
||||
let listing = self.list_dir(&folder);
|
||||
{
|
||||
let mut status = self.thumbnail_build.lock();
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
status.folders_scanned += 1;
|
||||
}
|
||||
let entries = match listing {
|
||||
Ok(entries) => entries,
|
||||
Err(error) => {
|
||||
let mut status = self.thumbnail_build.lock();
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
if status.message.is_none() {
|
||||
status.message = Some(format!(
|
||||
"Some folders could not be read ({}: {error})",
|
||||
@@ -2359,14 +2454,18 @@ impl Core {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut status = self.thumbnail_build.lock();
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
status.images_found += found_here;
|
||||
status.completed += invalid_here;
|
||||
status.failed += invalid_here;
|
||||
}
|
||||
|
||||
self.thumbnail_build.lock().scanning = false;
|
||||
if self.thumbnail_build_cancelled.load(Ordering::SeqCst) {
|
||||
self.photo_jobs.thumbnail_build.lock().scanning = false;
|
||||
if self
|
||||
.photo_jobs
|
||||
.thumbnail_build_cancelled
|
||||
.load(Ordering::SeqCst)
|
||||
{
|
||||
self.finish_thumbnail_build();
|
||||
return;
|
||||
}
|
||||
@@ -2378,13 +2477,14 @@ impl Core {
|
||||
.cached_thumbnail_path(&uid, ttype, modified)
|
||||
.is_some()
|
||||
{
|
||||
self.thumbnail_build.lock().completed += 1;
|
||||
self.photo_jobs.thumbnail_build.lock().completed += 1;
|
||||
} else if self
|
||||
.photo_jobs
|
||||
.thumbnail_misses
|
||||
.lock()
|
||||
.local_contains(&(uid.clone(), ttype), modified)
|
||||
{
|
||||
let mut status = self.thumbnail_build.lock();
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
status.completed += 1;
|
||||
status.failed += 1;
|
||||
} else {
|
||||
@@ -2393,7 +2493,11 @@ impl Core {
|
||||
}
|
||||
|
||||
for chunk in todo.chunks(THUMB_BUILD_CHUNK) {
|
||||
if self.thumbnail_build_cancelled.load(Ordering::SeqCst) {
|
||||
if self
|
||||
.photo_jobs
|
||||
.thumbnail_build_cancelled
|
||||
.load(Ordering::SeqCst)
|
||||
{
|
||||
self.finish_thumbnail_build();
|
||||
return;
|
||||
}
|
||||
@@ -2406,7 +2510,11 @@ impl Core {
|
||||
// than downloading the full image twice.
|
||||
let waiting_since = Instant::now();
|
||||
loop {
|
||||
if self.thumbnail_build_cancelled.load(Ordering::SeqCst) {
|
||||
if self
|
||||
.photo_jobs
|
||||
.thumbnail_build_cancelled
|
||||
.load(Ordering::SeqCst)
|
||||
{
|
||||
self.finish_thumbnail_build();
|
||||
return;
|
||||
}
|
||||
@@ -2415,27 +2523,28 @@ impl Core {
|
||||
.cached_thumbnail_path(uid, ttype, *modified)
|
||||
.is_some()
|
||||
{
|
||||
self.thumbnail_build.lock().completed += 1;
|
||||
self.photo_jobs.thumbnail_build.lock().completed += 1;
|
||||
break;
|
||||
}
|
||||
if self
|
||||
.photo_jobs
|
||||
.thumbnail_misses
|
||||
.lock()
|
||||
.local_contains(&(uid.clone(), ttype), *modified)
|
||||
{
|
||||
let mut status = self.thumbnail_build.lock();
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
status.completed += 1;
|
||||
status.failed += 1;
|
||||
break;
|
||||
}
|
||||
if self.thumb_gen.lock().insert(uid.clone()) {
|
||||
if self.photo_jobs.thumb_gen.lock().insert(uid.clone()) {
|
||||
tags.insert(uid.to_string(), *modified);
|
||||
names.insert(uid.to_string(), name.clone());
|
||||
claimed.push(uid.clone());
|
||||
break;
|
||||
}
|
||||
if waiting_since.elapsed() >= THUMB_BUILD_CLAIM_TIMEOUT {
|
||||
let mut status = self.thumbnail_build.lock();
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
status.completed += 1;
|
||||
status.failed += 1;
|
||||
if status.message.is_none() {
|
||||
@@ -2456,12 +2565,12 @@ impl Core {
|
||||
self.generate_thumbs(&claimed, &tags, &names, ThumbJob::Build)
|
||||
}));
|
||||
{
|
||||
let mut inflight = self.thumb_gen.lock();
|
||||
let mut inflight = self.photo_jobs.thumb_gen.lock();
|
||||
for uid in &claimed {
|
||||
inflight.remove(uid);
|
||||
}
|
||||
}
|
||||
let mut status = self.thumbnail_build.lock();
|
||||
let mut status = self.photo_jobs.thumbnail_build.lock();
|
||||
match result {
|
||||
Ok(summary) => {
|
||||
status.completed += summary.processed();
|
||||
@@ -2544,7 +2653,7 @@ impl Core {
|
||||
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.timeline_progress);
|
||||
let progress = ProgressGuard(&self.photo_jobs.timeline_progress);
|
||||
for (index, chunk) in pending.chunks(TIMELINE_ENRICH_CHUNK).enumerate() {
|
||||
if self.shutdown.is_stopping() {
|
||||
break;
|
||||
@@ -2613,8 +2722,14 @@ impl Core {
|
||||
/// 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.timeline_refreshing.swap(true, Ordering::SeqCst) {
|
||||
while self.timeline_refreshing.load(Ordering::SeqCst) && !self.shutdown.is_stopping() {
|
||||
if self
|
||||
.photo_jobs
|
||||
.timeline_refreshing
|
||||
.swap(true, Ordering::SeqCst)
|
||||
{
|
||||
while self.photo_jobs.timeline_refreshing.load(Ordering::SeqCst)
|
||||
&& !self.shutdown.is_stopping()
|
||||
{
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
}
|
||||
// A refresh that landed stamped the timeline fresh. One that failed
|
||||
@@ -2625,13 +2740,18 @@ impl Core {
|
||||
.state_i64(PHOTOS_SYNCED_MS)
|
||||
.map_err(CoreError::from)?
|
||||
.is_some()
|
||||
|| self.timeline_refreshing.swap(true, Ordering::SeqCst)
|
||||
|| self
|
||||
.photo_jobs
|
||||
.timeline_refreshing
|
||||
.swap(true, Ordering::SeqCst)
|
||||
{
|
||||
return Ok(self.db.state_i64(PHOTOS_AVAILABLE).ok().flatten() != Some(0));
|
||||
}
|
||||
}
|
||||
let refreshed = self.rt.block_on(self.refresh_timeline());
|
||||
self.timeline_refreshing.store(false, Ordering::SeqCst);
|
||||
self.photo_jobs
|
||||
.timeline_refreshing
|
||||
.store(false, Ordering::SeqCst);
|
||||
if refreshed.is_ok() {
|
||||
self.events.publish(&[Topic::Photos]);
|
||||
}
|
||||
@@ -2639,13 +2759,19 @@ impl Core {
|
||||
}
|
||||
|
||||
pub(crate) fn spawn_timeline_refresh(&self) {
|
||||
if self.timeline_refreshing.swap(true, Ordering::SeqCst) {
|
||||
if self
|
||||
.photo_jobs
|
||||
.timeline_refreshing
|
||||
.swap(true, Ordering::SeqCst)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let core = self.clone();
|
||||
self.rt.spawn(async move {
|
||||
let refreshed = core.refresh_timeline().await;
|
||||
core.timeline_refreshing.store(false, Ordering::SeqCst);
|
||||
core.photo_jobs
|
||||
.timeline_refreshing
|
||||
.store(false, Ordering::SeqCst);
|
||||
// Only a refresh that landed: a front-end re-reading after a failed
|
||||
// one would find the timeline still stale and start another.
|
||||
match refreshed {
|
||||
@@ -2658,7 +2784,8 @@ impl Core {
|
||||
/// 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.timeline_progress
|
||||
self.photo_jobs
|
||||
.timeline_progress
|
||||
.lock()
|
||||
.map(|(done, total)| MappingProgress { done, total })
|
||||
}
|
||||
@@ -2666,7 +2793,7 @@ impl Core {
|
||||
/// 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.timeline_refreshing.load(Ordering::SeqCst)
|
||||
self.photo_jobs.timeline_refreshing.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Download a photo's full content into the content cache, returning its
|
||||
|
||||
@@ -127,6 +127,49 @@ static NEXT_OPEN_ID: AtomicU64 = AtomicU64::new(0);
|
||||
/// re-planned read misses rather than being served the wrong bytes.
|
||||
type RingKey = (NodeUid, BlockSpan);
|
||||
|
||||
/// What the read path keeps between reads, shared by every mount of the
|
||||
/// daemon: open revision readers, decrypted blocks, block fetches in flight,
|
||||
/// whole-file repairs, and the prefetch detector with its permits.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ReadState {
|
||||
/// Open [`RevisionReader`]s keyed by node, so the block fetches of a file
|
||||
/// resolve its keys and block table once instead of once per block.
|
||||
/// Validated by `(mtime, size)` exactly like the content cache, and bounded
|
||||
/// by [`MAX_OPEN_READERS`].
|
||||
pub(crate) readers: Arc<Mutex<HashMap<NodeUid, ReaderSlot>>>,
|
||||
/// Decrypted blocks held in memory, so the ~32 kernel reads a 4 MiB block is
|
||||
/// delivered in cost the block once — a download for a streaming file, a
|
||||
/// disk read for a cached one. See [`BlockRing`].
|
||||
pub(crate) block_ring: Arc<Mutex<BlockRing>>,
|
||||
/// Block fetches in flight, so concurrent readers of one block (demand read,
|
||||
/// kernel read-ahead, our own prefetch) share a single download and decrypt.
|
||||
/// See [`BlockFlight`].
|
||||
pub(crate) block_flight: Arc<BlockFlight>,
|
||||
/// One lock per file being repaired by [`Core::repair_block`], so the
|
||||
/// concurrent block reads that all discover the same untrustworthy block
|
||||
/// table share a single whole-file download instead of one each.
|
||||
pub(crate) content_repairs:
|
||||
Arc<tokio::sync::Mutex<HashMap<NodeUid, Arc<tokio::sync::Mutex<()>>>>>,
|
||||
/// Per-file sequential-read detection driving [`Core::prefetch`].
|
||||
pub(crate) prefetch: Arc<Prefetch>,
|
||||
/// Permits bounding speculative block fetches, so prefetch cannot queue in
|
||||
/// front of a read someone is waiting on.
|
||||
pub(crate) prefetch_budget: Arc<tokio::sync::Semaphore>,
|
||||
}
|
||||
|
||||
impl ReadState {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
readers: Arc::new(Mutex::new(HashMap::new())),
|
||||
block_ring: Arc::new(Mutex::new(BlockRing::default())),
|
||||
block_flight: Arc::new(BlockFlight::default()),
|
||||
content_repairs: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
|
||||
prefetch: Arc::new(Prefetch::default()),
|
||||
prefetch_budget: Arc::new(tokio::sync::Semaphore::new(PREFETCH_BUDGET)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct BlockRing {
|
||||
blocks: HashMap<RingKey, Arc<Vec<u8>>>,
|
||||
@@ -296,7 +339,7 @@ impl Core {
|
||||
),
|
||||
}
|
||||
let act = {
|
||||
let mut readers = self.readers.lock();
|
||||
let mut readers = self.reads.readers.lock();
|
||||
match readers.get_mut(uid) {
|
||||
Some(ReaderSlot::Ready(entry))
|
||||
if entry.mtime == mtime && entry.size == fsize =>
|
||||
@@ -355,7 +398,7 @@ impl Core {
|
||||
}
|
||||
};
|
||||
{
|
||||
let mut readers = self.readers.lock();
|
||||
let mut readers = self.reads.readers.lock();
|
||||
// Publish only into the slot we claimed. If it is gone
|
||||
// or belongs to a later attempt, an eviction or a newer
|
||||
// revision overtook us: our reader still answers the
|
||||
@@ -421,11 +464,11 @@ impl Core {
|
||||
/// to cache what it opened, which is what we want — the eviction says that
|
||||
/// revision is no longer the truth.
|
||||
pub(super) fn evict_reader(&self, uid: &NodeUid) {
|
||||
self.readers.lock().remove(uid);
|
||||
self.reads.readers.lock().remove(uid);
|
||||
// The ring holds decrypted bytes of the same revision, and an eviction is
|
||||
// exactly the statement that those are no longer the file's content.
|
||||
self.block_ring.lock().drop_node(uid);
|
||||
self.prefetch.streams.lock().remove(uid);
|
||||
self.reads.block_ring.lock().drop_node(uid);
|
||||
self.reads.prefetch.streams.lock().remove(uid);
|
||||
}
|
||||
|
||||
/// How this revision's plaintext is divided into content blocks.
|
||||
@@ -551,7 +594,8 @@ impl Core {
|
||||
cache_blocks: bool,
|
||||
) -> BlockResult {
|
||||
let key: BlockKey = (uid.clone(), mtime, fsize, span);
|
||||
self.block_flight
|
||||
self.reads
|
||||
.block_flight
|
||||
.join(key, || {
|
||||
self.read_block(reader, uid, mtime, fsize, span, cache_blocks)
|
||||
})
|
||||
@@ -625,7 +669,8 @@ impl Core {
|
||||
let _ = cache.store_block(&uid, mtime, fsize, span, &bytes);
|
||||
});
|
||||
}
|
||||
self.block_ring
|
||||
self.reads
|
||||
.block_ring
|
||||
.lock()
|
||||
.insert(uid, mtime, fsize, span, bytes.clone());
|
||||
Ok(bytes)
|
||||
@@ -665,7 +710,7 @@ impl Core {
|
||||
// One download per file, not per block: every block of a file with a bad
|
||||
// block table discovers the same problem at once.
|
||||
let lock = {
|
||||
let mut locks = self.content_repairs.lock().await;
|
||||
let mut locks = self.reads.content_repairs.lock().await;
|
||||
locks.entry(uid.clone()).or_default().clone()
|
||||
};
|
||||
let guard = lock.clone().lock_owned().await;
|
||||
@@ -746,7 +791,7 @@ impl Core {
|
||||
/// Drop a repair lock's map entry once nobody else holds it, so a file
|
||||
/// repaired long ago does not keep a mutex alive forever.
|
||||
async fn release_repair_lock(&self, uid: &NodeUid, lock: Arc<tokio::sync::Mutex<()>>) {
|
||||
let mut locks = self.content_repairs.lock().await;
|
||||
let mut locks = self.reads.content_repairs.lock().await;
|
||||
// Two: the map's and ours. Anything more means a waiter still needs it.
|
||||
if Arc::strong_count(&lock) <= 2 {
|
||||
locks.remove(uid);
|
||||
@@ -775,7 +820,7 @@ impl Core {
|
||||
last: u64,
|
||||
cache_blocks: bool,
|
||||
) {
|
||||
let depth = self.prefetch.window(uid, first, last);
|
||||
let depth = self.reads.prefetch.window(uid, first, last);
|
||||
if depth == 0 {
|
||||
return;
|
||||
}
|
||||
@@ -787,7 +832,8 @@ impl Core {
|
||||
// Blocks already in memory need nothing; blocks already on disk
|
||||
// are cheap enough to serve that spending a round-trip to move
|
||||
// them into the ring would be the wrong trade.
|
||||
self.block_ring
|
||||
self.reads
|
||||
.block_ring
|
||||
.lock()
|
||||
.get(uid, mtime, fsize, span)
|
||||
.is_none()
|
||||
@@ -809,7 +855,7 @@ impl Core {
|
||||
// finishes.
|
||||
let mut set = tokio::task::JoinSet::new();
|
||||
for span in wanted {
|
||||
let Ok(permit) = core.prefetch_budget.clone().try_acquire_owned() else {
|
||||
let Ok(permit) = core.reads.prefetch_budget.clone().try_acquire_owned() else {
|
||||
break; // the budget is spent; the demand path can have it
|
||||
};
|
||||
let (core, reader, uid) = (core.clone(), reader.clone(), uid.clone());
|
||||
@@ -870,7 +916,7 @@ impl Core {
|
||||
// no other cache at all, and a cached one would otherwise pay two
|
||||
// opens, a JSON parse and a 4 MiB read+alloc for every 128 KiB the
|
||||
// kernel asks for (audit T3).
|
||||
let hit = self.block_ring.lock().get(uid, mtime, fsize, span);
|
||||
let hit = self.reads.block_ring.lock().get(uid, mtime, fsize, span);
|
||||
let hit = hit.or_else(|| {
|
||||
if !cache_blocks {
|
||||
return None;
|
||||
@@ -878,7 +924,8 @@ impl Core {
|
||||
let bytes = Arc::new(self.cache.cached_block(uid, mtime, fsize, span)?);
|
||||
// Promote it, so the other ~31 reads of this block are answered
|
||||
// from memory.
|
||||
self.block_ring
|
||||
self.reads
|
||||
.block_ring
|
||||
.lock()
|
||||
.insert(uid, mtime, fsize, span, bytes.clone());
|
||||
Some(bytes)
|
||||
@@ -1152,7 +1199,7 @@ impl Core {
|
||||
}
|
||||
let mut out = Vec::with_capacity((end - offset) as usize);
|
||||
for span in self.block_geometry(uid, mtime, fsize).spans(offset, end) {
|
||||
let ring = self.block_ring.lock().get(uid, mtime, fsize, span);
|
||||
let ring = self.reads.block_ring.lock().get(uid, mtime, fsize, span);
|
||||
let block = match ring {
|
||||
Some(bytes) => bytes,
|
||||
None => Arc::new(self.cache.cached_block(uid, mtime, fsize, span)?),
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
//! The mounted shared tree's listing: the synthetic root, when its folders
|
||||
//! are listed again, and what invalidates a listing on the wire.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Publication of the shared listing, and what invalidates a listing on the
|
||||
/// wire or suppresses its next refresh.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct SharedState {
|
||||
/// Serializes only shared-list publication and access-loss invalidation.
|
||||
/// Network calls happen before taking it.
|
||||
pub(crate) shared_publication: Arc<Ranked<()>>,
|
||||
/// Invalidates in-flight shared responses when access/list events arrive.
|
||||
pub(crate) shared_generation: Arc<AtomicU64>,
|
||||
/// Successful refreshes suppress retries even if persisting their timestamp
|
||||
/// fails. Shared across primary/fork clones and cleared by access events.
|
||||
pub(crate) shared_refresh_deadlines: Arc<Mutex<SharedRefreshDeadlines>>,
|
||||
}
|
||||
|
||||
impl SharedState {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
shared_publication: Arc::new(Ranked::new(Rank::SharedPublication, ())),
|
||||
shared_generation: Arc::new(AtomicU64::new(0)),
|
||||
shared_refresh_deadlines: Arc::new(Mutex::new(SharedRefreshDeadlines::default())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// Read the inputs for virtual-root publication without changing SQLite.
|
||||
///
|
||||
/// The caller validates the listing snapshot after these reads. Keeping all
|
||||
/// writes out of this phase prevents an invalidated/repopulated root listing
|
||||
/// from changing the synthetic node's persisted visibility or FTS ancestry.
|
||||
pub(super) fn prepare_virtual_root(
|
||||
&self,
|
||||
real_names: &HashSet<String>,
|
||||
) -> Result<VirtualRootPlan, Errno> {
|
||||
let pinned = self.db.state_str(SHARED_WITH_ME_NAME).map_err(|error| {
|
||||
error!(%error, "reading shared-root display name failed");
|
||||
Errno::EIO
|
||||
})?;
|
||||
let (name, visible) = virtual_root_name(real_names, pinned.as_deref());
|
||||
|
||||
let uid = shared_with_me_uid();
|
||||
let previous_node = self.db.node_by_uid(&uid.to_string()).map_err(|error| {
|
||||
error!(%error, "reading synthetic shared root failed");
|
||||
Errno::EIO
|
||||
})?;
|
||||
let mut node = previous_node.unwrap_or_else(|| {
|
||||
virtual_node(self.primary_root_uid.clone(), name.clone(), now_secs())
|
||||
});
|
||||
node.parent_uid = Some(self.primary_root_uid.clone());
|
||||
node.name = name;
|
||||
node.kind = NodeKind::Folder;
|
||||
// A later real-name collision suppresses both the dentry and its search
|
||||
// hit. The row and pinned name remain, and clearing the collision
|
||||
// restores both by writing `trashed = false` again.
|
||||
node.trashed = !visible;
|
||||
node.membership = None;
|
||||
Ok(VirtualRootPlan { node, visible })
|
||||
}
|
||||
|
||||
/// Reconcile the synthetic dentry against an already-known primary-root
|
||||
/// listing. The node remains persisted and pinned even while a real folder
|
||||
/// of the same name temporarily suppresses its dentry.
|
||||
pub(super) fn reconcile_virtual_root_dentry(
|
||||
&self,
|
||||
parent_ino: u64,
|
||||
snapshot: RootListingSnapshot,
|
||||
) -> Result<(), Errno> {
|
||||
let _publication = self.shared.shared_publication.lock();
|
||||
let plan = self.prepare_virtual_root(&snapshot.real_names())?;
|
||||
let mut st = self.state();
|
||||
// State methods already establish the state -> DB lock order. No path
|
||||
// holds the DB connection while acquiring state, including shared event
|
||||
// publication, so keeping state locked across this one transaction
|
||||
// closes the crash window without introducing an inverse order.
|
||||
publish_virtual_root_in_listing(&self.db, &mut st, parent_ino, &snapshot, plan)?;
|
||||
drop(st);
|
||||
self.flush_access_changes();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn resident_root_listing_snapshot(
|
||||
&self,
|
||||
ino: u64,
|
||||
) -> Result<RootListingSnapshot, Errno> {
|
||||
RootListingSnapshot::capture(&self.state(), ino).ok_or(Errno::EAGAIN)
|
||||
}
|
||||
|
||||
pub(super) fn shared_folder_freshness_key(uid: &NodeUid) -> String {
|
||||
format!("{SHARED_FOLDER_SYNCED_PREFIX}{uid}")
|
||||
}
|
||||
|
||||
pub(super) fn shared_listing_stale(&self, key: &str) -> bool {
|
||||
if self
|
||||
.shared
|
||||
.shared_refresh_deadlines
|
||||
.lock()
|
||||
.is_fresh(key, Instant::now())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.listing_stale(key, SHARED_LISTING_TTL)
|
||||
}
|
||||
|
||||
pub(super) fn mark_shared_refresh_success(&self, key: &str) {
|
||||
self.shared
|
||||
.shared_refresh_deadlines
|
||||
.lock()
|
||||
.mark(key, Instant::now(), SHARED_LISTING_TTL);
|
||||
if let Err(error) = self.db.set_state_i64(key, now_millis()) {
|
||||
warn!(key, %error, "persisting shared-list freshness failed");
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn invalidate_shared_refreshes(&self) {
|
||||
self.shared.shared_generation.fetch_add(1, Ordering::SeqCst);
|
||||
self.shared.shared_refresh_deadlines.lock().clear();
|
||||
}
|
||||
|
||||
pub(super) fn ensure_shared_children(&self, ino: u64) -> Result<(), Errno> {
|
||||
let online = self.online.load(Ordering::Relaxed);
|
||||
let resident = self.state().children.contains_key(&ino);
|
||||
match shared_listing_plan(
|
||||
resident,
|
||||
online,
|
||||
self.shared_listing_stale(SHARED_WITH_ME_SYNCED_MS),
|
||||
) {
|
||||
SharedListingPlan::Resident => return Ok(()),
|
||||
SharedListingPlan::Persisted => {
|
||||
// A completed snapshot remains useful offline even after an
|
||||
// event expired its freshness stamp.
|
||||
let nodes = self
|
||||
.db
|
||||
.visible_children(&shared_with_me_uid())
|
||||
.map_err(|error| {
|
||||
error!(%error, "loading persisted shared roots failed");
|
||||
Errno::EIO
|
||||
})?;
|
||||
let mut st = self.state();
|
||||
if st.children.contains_key(&ino) {
|
||||
return Ok(());
|
||||
}
|
||||
let children = nodes
|
||||
.into_iter()
|
||||
.map(|node| {
|
||||
let access = st
|
||||
.share_access
|
||||
.get(&node.uid)
|
||||
.copied()
|
||||
.unwrap_or(Access::Viewer);
|
||||
st.intern_published_share_root(ino, node, access)
|
||||
})
|
||||
.collect();
|
||||
st.children.insert(ino, children);
|
||||
drop(st);
|
||||
self.flush_access_changes();
|
||||
return Ok(());
|
||||
}
|
||||
SharedListingPlan::Refresh => {}
|
||||
}
|
||||
|
||||
let generation = self.shared.shared_generation.load(Ordering::SeqCst);
|
||||
let accepted = accepted_share_provenance(
|
||||
self.block_on_within(BATCH_CALL_TIMEOUT, self.client.enumerate_shared_with_me())
|
||||
.map_err(|error| {
|
||||
error!(%error, "enumerating shared roots failed");
|
||||
Errno::EIO
|
||||
})?,
|
||||
);
|
||||
let nodes = if accepted.uids.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.block_on_within(
|
||||
BATCH_CALL_TIMEOUT,
|
||||
self.drive.enumerate_nodes_light(&accepted.uids),
|
||||
)
|
||||
.map_err(|error| {
|
||||
error!(%error, "materializing shared roots failed");
|
||||
Errno::EIO
|
||||
})?
|
||||
};
|
||||
let virtual_uid = shared_with_me_uid();
|
||||
let published = prepare_shared_roots(&accepted, nodes, &virtual_uid);
|
||||
|
||||
let _publication = self.shared.shared_publication.lock();
|
||||
if !refresh_generation_is_current(
|
||||
generation,
|
||||
self.shared.shared_generation.load(Ordering::SeqCst),
|
||||
) {
|
||||
return Err(Errno::EAGAIN);
|
||||
}
|
||||
let removed = match self
|
||||
.db
|
||||
.publish_shared_roots(&virtual_uid, &accepted.uids, &published)
|
||||
{
|
||||
Ok(removed) => removed,
|
||||
Err(error) => {
|
||||
error!(%error, "publishing shared-root listing failed");
|
||||
let mut st = self.state();
|
||||
for uid in &accepted.uids {
|
||||
st.downgrade_shared_subtree(uid);
|
||||
}
|
||||
drop(st);
|
||||
self.flush_access_changes();
|
||||
return Err(Errno::EIO);
|
||||
}
|
||||
};
|
||||
let snapshot = self.db.visible_children(&virtual_uid).map_err(|error| {
|
||||
error!(%error, "loading published shared-root listing failed");
|
||||
Errno::EIO
|
||||
})?;
|
||||
let published_access: HashMap<NodeUid, Access> = published
|
||||
.iter()
|
||||
.map(|root| (root.node.uid.clone(), root.access))
|
||||
.collect();
|
||||
let mut st = self.state();
|
||||
for uid in &removed {
|
||||
st.hide_shared_root(uid);
|
||||
}
|
||||
let mut children = Vec::with_capacity(snapshot.len());
|
||||
for node in snapshot {
|
||||
let uid = node.uid.clone();
|
||||
let access = published_access
|
||||
.get(&uid)
|
||||
.copied()
|
||||
.unwrap_or(Access::Viewer);
|
||||
let child = st.intern_published_share_root(ino, node, access);
|
||||
children.push(child);
|
||||
}
|
||||
st.children.insert(ino, children);
|
||||
drop(st);
|
||||
self.flush_access_changes();
|
||||
self.mark_shared_refresh_success(SHARED_WITH_ME_SYNCED_MS);
|
||||
if let Some(notifier) = self.notifier.get() {
|
||||
let _ = notifier.inval_inode(ino);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,10 @@
|
||||
//! 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,
|
||||
@@ -24,6 +28,32 @@ use proton_drive_rs::Node;
|
||||
|
||||
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.
|
||||
#[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>,
|
||||
}
|
||||
|
||||
impl QuotaCache {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
quota: Arc::new(Mutex::new(None)),
|
||||
quota_refreshing: Arc::new(AtomicBool::new(false)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A node from a *shared* listing as a [`DirEntry`].
|
||||
///
|
||||
/// Still uid-addressed — that is the only handle a foreign-volume node is
|
||||
@@ -701,7 +731,8 @@ impl Core {
|
||||
self.lost_link(&e, "account quota");
|
||||
CoreError::from_api(&e, "account quota")
|
||||
})?;
|
||||
*self.quota.lock() = Some((std::time::Instant::now(), q.max_space, q.used_space));
|
||||
*self.quota_cache.quota.lock() =
|
||||
Some((std::time::Instant::now(), q.max_space, q.used_space));
|
||||
Ok((q.max_space, q.used_space))
|
||||
}
|
||||
|
||||
@@ -714,21 +745,28 @@ impl Core {
|
||||
/// 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.lock()
|
||||
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.lock().map(|(_, max, used)| (max, used));
|
||||
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_refreshing
|
||||
self.quota_cache
|
||||
.quota_refreshing
|
||||
.store(false, std::sync::atomic::Ordering::Release);
|
||||
match refreshed {
|
||||
Ok(q) => Some(q),
|
||||
|
||||
@@ -0,0 +1,897 @@
|
||||
//! File sizes filled in after a cheap listing: one batch per folder, the
|
||||
//! `getattr`s and `lookup`s that need a real size parked on it, and the
|
||||
//! results applied to the tree as each chunk lands (`docs/BUGS.md` B14).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The size upgrades running now, and the replies parked on them. Shared
|
||||
/// by every mount: the bound that matters is per daemon.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct SizeState {
|
||||
/// Folders whose listing was enumerated cheaply and is having its file sizes
|
||||
/// filled in right now, so a burst of `stat`s over a fresh listing starts one
|
||||
/// upgrade rather than one per entry. See [`Core::spawn_size_upgrade`].
|
||||
/// Size upgrades currently running, per folder inode, across every mount. A `getattr` that
|
||||
/// needs a real size waits on the entry rather than issuing its own fetch —
|
||||
/// `ls -l` of a folder is one `getattr` per file, and they must collapse
|
||||
/// onto a single batch (`docs/BUGS.md` B14).
|
||||
pub(crate) size_upgrades: Arc<Mutex<HashMap<u64, Arc<SizeUpgrade>>>>,
|
||||
/// Replies parked on those upgrades. Shared across every mount for the same
|
||||
/// reason the pool is: the bound that matters is per daemon.
|
||||
pub(crate) size_waiters: Arc<SizeWaitQueue>,
|
||||
}
|
||||
|
||||
impl SizeState {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
size_upgrades: Arc::new(Mutex::new(HashMap::new())),
|
||||
size_waiters: Arc::new(Default::default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// Resolve the real size of every file in `parent`'s listing still carrying
|
||||
/// a provisional one, returning when they are in `state`.
|
||||
///
|
||||
/// Called when a `stat` lands on such a file. That covers the paths
|
||||
/// [`Core::ensure_children`] cannot: a listing rebuilt from the DB, or one
|
||||
/// restored by [`Core::hydrate`] on mount, whose rows were persisted before
|
||||
/// an earlier upgrade had a chance to run. Gathers the whole folder rather
|
||||
/// than the one file asked for, because a `stat` of one entry in a listing
|
||||
/// almost always means a `stat` of all of them.
|
||||
pub(super) fn upgrade_sizes_for_parent(
|
||||
&self,
|
||||
ino: u64,
|
||||
uid: &NodeUid,
|
||||
parent: u64,
|
||||
) -> Option<Arc<SizeUpgrade>> {
|
||||
let provisional = |e: &Entry| {
|
||||
matches!(
|
||||
&e.node.kind,
|
||||
NodeKind::File {
|
||||
claimed_size: None,
|
||||
..
|
||||
}
|
||||
)
|
||||
};
|
||||
let (key, mut missing): (u64, Vec<NodeUid>) = {
|
||||
let st = self.state();
|
||||
match st.children.get(&parent) {
|
||||
// The listing is resident: batch the whole folder under its
|
||||
// inode, so the rest of an `ls -l` rides along on this fetch.
|
||||
Some(kids) => (
|
||||
parent,
|
||||
kids.iter()
|
||||
.filter_map(|k| st.entries.get(k))
|
||||
.filter(|e| provisional(e))
|
||||
.map(|e| e.uid.clone())
|
||||
.collect(),
|
||||
),
|
||||
// It is not, and returning here is what let a provisional size
|
||||
// reach the caller anyway: a rename invalidates its parents'
|
||||
// listings, so a freshly renamed file always landed in this
|
||||
// branch. Resolve the single node instead, keyed by its own
|
||||
// inode — folder and file inodes share one space, so the two
|
||||
// single-flight keys cannot collide. (Same shape as B4: an
|
||||
// early return that assumed the hot cache was authoritative.)
|
||||
None => (ino, Vec::new()),
|
||||
}
|
||||
};
|
||||
// The node that was actually asked about is never optional, whichever
|
||||
// branch produced the batch.
|
||||
if !missing.iter().any(|u| u == uid) {
|
||||
missing.push(uid.clone());
|
||||
}
|
||||
// Returned, not awaited here: the caller is a `getattr` that must not
|
||||
// answer with a provisional size (`docs/BUGS.md` B14), and it parks its reply
|
||||
// on this batch rather than holding a thread until it lands.
|
||||
self.upgrade_sizes(key, missing)
|
||||
}
|
||||
|
||||
/// Fill in the true sizes of files a `Light` enumeration returned without
|
||||
/// one, on a worker, after the listing has already been served.
|
||||
///
|
||||
/// This is the other half of the split in [`Core::ensure_children`]. The
|
||||
/// listing itself needs only names and parentage, so it is served from the
|
||||
/// cheap enumeration immediately; the S2K-per-file work that produces
|
||||
/// `claimed_size` happens here, off the path the user is waiting on.
|
||||
///
|
||||
/// **Sizes are provisional until this lands.** `node_size` falls back to
|
||||
/// `total_size_on_storage`, the *ciphertext* size, which is slightly larger
|
||||
/// than the real one. A read must not plan on it: since B84 a size the
|
||||
/// revision disagrees with fails the read, so `read` settles the size first
|
||||
/// ([`Core::resolve_provisional_size`], `docs/BUGS.md` B100). In `stat` it is a
|
||||
/// discrepancy that closes within a round trip, not a repeat of B11 (which
|
||||
/// reported **0** and so suppressed reads entirely).
|
||||
///
|
||||
/// Single-flight per folder: a `stat` of every entry in a fresh listing is
|
||||
/// the normal case, and each one must not start its own upgrade.
|
||||
pub(super) fn spawn_size_upgrade(&self, folder_ino: u64, uids: Vec<NodeUid>) {
|
||||
self.upgrade_sizes(folder_ino, uids);
|
||||
}
|
||||
|
||||
/// Start (or join) the size upgrade for `key`, returning the batch a caller
|
||||
/// can wait on — `None` when there was nothing to upgrade.
|
||||
///
|
||||
/// Single-flight per `key`. The fetch runs on its own thread rather than on
|
||||
/// the [`Workers`] pool: callers wait on `Lane::Meta`, so a batch queued onto
|
||||
/// that lane could have a wide enough `ls -l` fill it with threads waiting
|
||||
/// for a job that can never be scheduled. `Lane::Transfer` would swap that
|
||||
/// for starvation behind bulk reads. One short-lived thread per folder,
|
||||
/// bounded by the single-flight, avoids both.
|
||||
pub(super) fn upgrade_sizes(&self, key: u64, uids: Vec<NodeUid>) -> Option<Arc<SizeUpgrade>> {
|
||||
if uids.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let claim = claim_size_upgrade(&mut self.sizes.size_upgrades.lock(), key, uids);
|
||||
match claim {
|
||||
SizeUpgradeClaim::Joined(slot) | SizeUpgradeClaim::Queued(slot) => Some(slot),
|
||||
SizeUpgradeClaim::Start(slot, uids) => {
|
||||
let core = self.clone();
|
||||
let worker = slot.clone();
|
||||
std::thread::spawn(move || core.run_size_upgrade(key, uids, worker));
|
||||
Some(slot)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hold `respond` back until `ino` has a real size, `slot`'s batch ends, or
|
||||
/// [`SizeUpgrade::WAIT`] elapses — then run it, on the queue's thread.
|
||||
///
|
||||
/// The caller returns immediately. That is the whole point: the thread it
|
||||
/// was running on is a FUSE dispatch thread or a [`Workers`] one, and both
|
||||
/// are needed by everything else on the mount (audit F4).
|
||||
pub(super) fn await_size(
|
||||
&self,
|
||||
ino: u64,
|
||||
slot: Arc<SizeUpgrade>,
|
||||
respond: impl FnOnce() + Send + 'static,
|
||||
) {
|
||||
let core = self.clone();
|
||||
let waiter = SizeWaiter {
|
||||
slot,
|
||||
resolved: Box::new(move || core.size_is_real(ino)),
|
||||
deadline: Instant::now() + SizeUpgrade::WAIT,
|
||||
respond: Box::new(respond),
|
||||
};
|
||||
if !self.sizes.size_waiters.park(waiter) {
|
||||
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())
|
||||
{
|
||||
// Without a thread nothing would ever answer these. A provisional
|
||||
// size is wrong; a `stat` that never returns wedges the caller.
|
||||
warn!(%error, "no thread for parked size waiters; answering provisionally");
|
||||
self.sizes.size_waiters.answer_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch `uids` in chunks, applying and announcing each one as it lands.
|
||||
///
|
||||
/// Chunked so a waiter is released as soon as *its* file is resolved. A
|
||||
/// single 793-node batch took ~80 s, which outran [`SizeUpgrade::WAIT`] and
|
||||
/// put provisional sizes back in front of callers — the bug this was
|
||||
/// supposed to fix (`docs/BUGS.md` B14).
|
||||
///
|
||||
/// When the batch ends, the thread takes over the oldest batch the cap held
|
||||
/// back, so at most [`MAX_SIZE_UPGRADES`] threads run however many folders
|
||||
/// a recursive walk touches (`docs/BUGS.md` B100).
|
||||
pub(super) fn run_size_upgrade(&self, key: u64, uids: Vec<NodeUid>, slot: Arc<SizeUpgrade>) {
|
||||
let (mut key, mut uids, mut slot) = (key, uids, slot);
|
||||
loop {
|
||||
for chunk in uids.chunks(SIZE_UPGRADE_CHUNK) {
|
||||
let result =
|
||||
self.block_on_within(BATCH_CALL_TIMEOUT, self.drive.enumerate_nodes(chunk));
|
||||
self.apply_size_upgrade(key, result);
|
||||
slot.chunk_done();
|
||||
}
|
||||
// Both of these must happen however the loop ended: a folder whose
|
||||
// upgrade failed has to be retryable, and its waiters released.
|
||||
let next = next_size_upgrade(&mut self.sizes.size_upgrades.lock(), key);
|
||||
slot.finish();
|
||||
let Some(next) = next else {
|
||||
return;
|
||||
};
|
||||
(key, uids, slot) = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// Settle the size of a file whose listing only carries the provisional
|
||||
/// one, before a read plans its blocks on it or a write handle starts from
|
||||
/// it. Returns the real size, or `None` when the fetch did not produce one.
|
||||
///
|
||||
/// A provisional size is the ciphertext size. The read path checks the
|
||||
/// size it is given against the revision's own block table and fails the
|
||||
/// read on a mismatch (B84), so reading on the provisional size is an `EIO`
|
||||
/// every time. `getattr` usually settles the size first, but not when its
|
||||
/// wait times out, so the read cannot rely on it (`docs/BUGS.md` B100).
|
||||
pub(super) fn resolve_provisional_size(&self, ino: u64, uid: &NodeUid) -> Option<u64> {
|
||||
let parent = self.state().entries.get(&ino)?.parent;
|
||||
// Without a network the answer is `None` either way; the bound keeps a
|
||||
// dead link from holding the open or read for the SDK's two minutes.
|
||||
if !self.is_online() {
|
||||
return None;
|
||||
}
|
||||
let result = self.block_on_bounded(self.drive.enumerate_nodes(std::slice::from_ref(uid)));
|
||||
if let Err(e) = &result {
|
||||
self.lost_link(e, "settle a provisional size");
|
||||
}
|
||||
self.apply_size_upgrade(parent, result);
|
||||
let st = self.state();
|
||||
match &st.entries.get(&ino)?.node.kind {
|
||||
NodeKind::File {
|
||||
claimed_size: Some(size),
|
||||
..
|
||||
} => Some((*size).max(0) as u64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait, up to [`SizeUpgrade::WAIT`] as a `stat` would, for the real size
|
||||
/// of every file in `ino`'s listing that still carries a provisional one.
|
||||
///
|
||||
/// For callers that read a whole listing's sizes straight from `state` and
|
||||
/// do not run on a FUSE thread: `pdfs ls` and the app's file browser. A
|
||||
/// listing just fetched has the ciphertext size of every file in it until
|
||||
/// its upgrade lands, and they showed those (`docs/BUGS.md` B115).
|
||||
pub(super) fn settle_listing_sizes(&self, ino: u64) {
|
||||
// Offline the fetch cannot succeed; the wait would only delay the
|
||||
// answer it ends up giving anyway.
|
||||
if !self.is_online() {
|
||||
return;
|
||||
}
|
||||
let missing: Vec<NodeUid> = {
|
||||
let st = self.state();
|
||||
st.children
|
||||
.get(&ino)
|
||||
.map(|kids| {
|
||||
kids.iter()
|
||||
.filter_map(|k| st.entries.get(k))
|
||||
.filter(|e| {
|
||||
!is_local_uid(&e.uid)
|
||||
&& matches!(
|
||||
&e.node.kind,
|
||||
NodeKind::File {
|
||||
claimed_size: None,
|
||||
..
|
||||
}
|
||||
)
|
||||
})
|
||||
.map(|e| e.uid.clone())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
if let Some(slot) = self.upgrade_sizes(ino, missing) {
|
||||
slot.wait_finished(Instant::now() + SizeUpgrade::WAIT);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `ino` has a real size — the condition a waiter is waiting on.
|
||||
/// A node that vanished counts as resolved; there is nothing left to wait
|
||||
/// for, and its caller will find the `ENOENT` for itself.
|
||||
pub(super) fn size_is_real(&self, ino: u64) -> bool {
|
||||
let st = self.state();
|
||||
st.entries.get(&ino).is_none_or(|e| {
|
||||
!matches!(
|
||||
&e.node.kind,
|
||||
NodeKind::File {
|
||||
claimed_size: None,
|
||||
..
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Adopt the sizes a completed upgrade fetched. Split from
|
||||
/// [`Core::upgrade_sizes`] so the single-flight bookkeeping there has one
|
||||
/// exit path rather than one per early return.
|
||||
pub(super) fn apply_size_upgrade(
|
||||
&self,
|
||||
folder_ino: u64,
|
||||
result: Result<Vec<Node>, ProtonError>,
|
||||
) {
|
||||
let core = self;
|
||||
{
|
||||
let mut nodes = match result {
|
||||
Ok(nodes) => nodes,
|
||||
Err(e) => {
|
||||
// Not fatal: the listing stands, sizes just stay provisional
|
||||
// until something invalidates and re-enumerates it.
|
||||
warn!(folder_ino, error = %e, "size upgrade failed; sizes stay provisional");
|
||||
return;
|
||||
}
|
||||
};
|
||||
// A queued write is ahead of anything the server can report, so its
|
||||
// optimistic size must survive this just as it survives a re-listing
|
||||
// (B11).
|
||||
core.stamp_pending_sizes(&mut nodes);
|
||||
let mut changed: Vec<u64> = Vec::new();
|
||||
let mut st = core.state();
|
||||
for node in nodes {
|
||||
// Only adopt the size. Re-interning wholesale would also adopt a
|
||||
// name or parent that a rename/move may have changed locally
|
||||
// while this was in flight, undoing it.
|
||||
let Some(&ino) = st.by_uid.get(&node.uid) else {
|
||||
continue;
|
||||
};
|
||||
changed.push(ino);
|
||||
// An open write handle is ahead of the server too (B109).
|
||||
if st.active_writes.contains_key(&ino) {
|
||||
continue;
|
||||
}
|
||||
let NodeKind::File { claimed_size, .. } = &node.kind else {
|
||||
continue;
|
||||
};
|
||||
let (Some(size), Some(entry)) = (*claimed_size, st.entries.get_mut(&ino)) else {
|
||||
continue;
|
||||
};
|
||||
if let NodeKind::File { claimed_size, .. } = &mut entry.node.kind {
|
||||
*claimed_size = Some(size);
|
||||
}
|
||||
}
|
||||
let updated: Vec<Node> = st
|
||||
.children
|
||||
.get(&folder_ino)
|
||||
.map(|kids| {
|
||||
kids.iter()
|
||||
.filter_map(|k| st.entries.get(k).map(|e| e.node.clone()))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
drop(st);
|
||||
if let Err(e) = core.db.upsert_nodes(&updated) {
|
||||
warn!(folder_ino, error = %e, "persisting upgraded sizes failed");
|
||||
}
|
||||
// Without this the corrected size is invisible for the length of the
|
||||
// attr TTL: the kernel answers `stat` from the provisional attrs it
|
||||
// cached while the listing was being served, so `ls -l` reports the
|
||||
// ciphertext size for up to 30 s even though the daemon has had the
|
||||
// real one all along. Notify *after* the DB write, so a re-`getattr`
|
||||
// provoked by the invalidation cannot race the persistence.
|
||||
//
|
||||
// Attributes only (offset -1): the content did not change, and a
|
||||
// page-cache invalidation deadlocks when this runs inside a `read`
|
||||
// (B100 resolves sizes there). The kernel holds the page lock of
|
||||
// that read until we reply, and the invalidation waits for the
|
||||
// same lock, so the read never answered (docs/BUGS.md B110).
|
||||
for mount in core.states.live() {
|
||||
if let Some(notifier) = mount.notifier.get() {
|
||||
for &ino in &changed {
|
||||
let _ = notifier.inval_attrs(ino);
|
||||
}
|
||||
}
|
||||
}
|
||||
debug!(folder_ino, files = updated.len(), "filled in listing sizes");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A size upgrade in flight for one folder, so the `getattr`s that need its
|
||||
/// result wait for the one batch instead of each fetching its own node.
|
||||
///
|
||||
/// A plain `Condvar` rather than a channel: the waiters do not want a value,
|
||||
/// only the edge, and there may be hundreds of them for one folder.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Progress {
|
||||
/// The whole batch has been applied (or failed). Nothing more is coming.
|
||||
done: bool,
|
||||
/// Bumped every time a chunk lands, so a waiter can tell "no progress since
|
||||
/// I last looked" from "progress happened while I was looking".
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
/// A size upgrade in flight for one folder, so the `getattr`s and `lookup`s that
|
||||
/// need its result wait for the one batch instead of each fetching its own node.
|
||||
///
|
||||
/// Waiters are released **per chunk**, not once at the end: a waiter only cares
|
||||
/// about its own file, and waiting for the other 792 is what let a large folder
|
||||
/// outrun the timeout (`docs/BUGS.md` B14).
|
||||
#[derive(Default)]
|
||||
pub(super) struct SizeUpgrade {
|
||||
inner: Mutex<Progress>,
|
||||
ready: Condvar,
|
||||
/// The batch, while it waits for a thread because [`MAX_SIZE_UPGRADES`]
|
||||
/// were already running, with when it was queued so the oldest goes first.
|
||||
/// `None` once a thread has it.
|
||||
queued: Mutex<Option<(Instant, Vec<NodeUid>)>>,
|
||||
}
|
||||
|
||||
/// What [`Core::upgrade_sizes`] does with one folder's batch.
|
||||
pub(super) enum SizeUpgradeClaim {
|
||||
/// A batch for this folder is already running or queued; wait on it.
|
||||
Joined(Arc<SizeUpgrade>),
|
||||
/// The cap is reached. The batch waits for a running thread to take it.
|
||||
Queued(Arc<SizeUpgrade>),
|
||||
/// Start a thread for the batch.
|
||||
Start(Arc<SizeUpgrade>, Vec<NodeUid>),
|
||||
}
|
||||
|
||||
/// Register the batch for `key` in `in_flight` and decide who runs it.
|
||||
///
|
||||
/// Past the cap this used to return nothing, and the caller answered with the
|
||||
/// provisional size at once. Nothing retried the folder until the next `stat`,
|
||||
/// so a recursive walk over more than [`MAX_SIZE_UPGRADES`] fresh folders showed
|
||||
/// ciphertext sizes for most of them (`docs/BUGS.md` B100). Queued, the batch is still
|
||||
/// fetched, and a waiter gets the real size unless [`SizeUpgrade::WAIT`] runs out.
|
||||
pub(super) fn claim_size_upgrade(
|
||||
in_flight: &mut HashMap<u64, Arc<SizeUpgrade>>,
|
||||
key: u64,
|
||||
uids: Vec<NodeUid>,
|
||||
) -> SizeUpgradeClaim {
|
||||
if let Some(existing) = in_flight.get(&key) {
|
||||
return SizeUpgradeClaim::Joined(existing.clone());
|
||||
}
|
||||
let running = in_flight
|
||||
.values()
|
||||
.filter(|slot| slot.queued.lock().is_none())
|
||||
.count();
|
||||
let slot = Arc::new(SizeUpgrade::default());
|
||||
in_flight.insert(key, slot.clone());
|
||||
if running >= MAX_SIZE_UPGRADES {
|
||||
*slot.queued.lock() = Some((Instant::now(), uids));
|
||||
return SizeUpgradeClaim::Queued(slot);
|
||||
}
|
||||
SizeUpgradeClaim::Start(slot, uids)
|
||||
}
|
||||
|
||||
/// Retire the finished batch for `done` and hand its thread the oldest queued
|
||||
/// batch, if there is one.
|
||||
pub(super) fn next_size_upgrade(
|
||||
in_flight: &mut HashMap<u64, Arc<SizeUpgrade>>,
|
||||
done: u64,
|
||||
) -> Option<(u64, Vec<NodeUid>, Arc<SizeUpgrade>)> {
|
||||
in_flight.remove(&done);
|
||||
let (key, slot) = in_flight
|
||||
.iter()
|
||||
.filter_map(|(key, slot)| slot.queued.lock().as_ref().map(|(at, _)| (*at, *key, slot)))
|
||||
.min_by_key(|(at, _, _)| *at)
|
||||
.map(|(_, key, slot)| (key, slot.clone()))?;
|
||||
let (_, uids) = slot.queued.lock().take()?;
|
||||
Some((key, uids, slot))
|
||||
}
|
||||
|
||||
impl SizeUpgrade {
|
||||
/// How long a caller will wait for a real size before answering with the
|
||||
/// provisional one.
|
||||
///
|
||||
/// A `stat` that never returns is far worse than one that is briefly wrong:
|
||||
/// on timeout the caller falls back to the pre-fix behaviour rather than
|
||||
/// wedging whatever is listing the directory.
|
||||
const WAIT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// Whether the batch has ended, however it ended. A waiter that sees this
|
||||
/// has nothing left to wait for.
|
||||
fn is_finished(&self) -> bool {
|
||||
self.inner.lock().done
|
||||
}
|
||||
|
||||
/// Announce that a chunk has been applied. Every waiter re-checks its own
|
||||
/// node; the ones it resolved return, the rest go back to sleep.
|
||||
fn chunk_done(&self) {
|
||||
self.inner.lock().generation += 1;
|
||||
self.ready.notify_all();
|
||||
}
|
||||
|
||||
/// Block until the batch has ended or `deadline` has passed. Only for a
|
||||
/// caller that is not on a FUSE or [`Workers`] thread; those park their
|
||||
/// reply with [`Core::await_size`] instead.
|
||||
fn wait_finished(&self, deadline: Instant) {
|
||||
let mut progress = self.inner.lock();
|
||||
while !progress.done {
|
||||
if self.ready.wait_until(&mut progress, deadline).timed_out() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Release every waiter for good. The worker must reach this on all paths.
|
||||
fn finish(&self) {
|
||||
let mut progress = self.inner.lock();
|
||||
progress.done = true;
|
||||
progress.generation += 1;
|
||||
drop(progress);
|
||||
self.ready.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// How often [`SizeWaitQueue::serve`] re-tests its parked waiters.
|
||||
///
|
||||
/// The predicates read `state`, which the applying thread writes under its own
|
||||
/// lock, so this polls rather than waiting on each slot's condvar: one thread
|
||||
/// cannot wait on a hundred condvars, and the whole point of the queue is that
|
||||
/// there is only one thread. Twenty milliseconds is far below the round trip a
|
||||
/// waiter is waiting on and only ticks while something is actually parked.
|
||||
pub(super) const SIZE_WAIT_POLL: Duration = Duration::from_millis(20);
|
||||
|
||||
/// A reply held back until a size upgrade resolves the node it describes.
|
||||
pub(super) struct SizeWaiter {
|
||||
/// The batch this reply is waiting on. When it ends, so does the wait.
|
||||
slot: Arc<SizeUpgrade>,
|
||||
/// Whether *this* waiter's node now has a real size.
|
||||
///
|
||||
/// Called with no queue lock held: it reaches into `state`, and the thread
|
||||
/// applying a chunk holds `state` before it announces the chunk — taking
|
||||
/// them in the other order would close the cycle.
|
||||
resolved: Box<dyn Fn() -> bool + Send>,
|
||||
/// When to answer with the provisional size anyway. A `stat` that never
|
||||
/// returns is far worse than one that is briefly wrong.
|
||||
deadline: Instant,
|
||||
/// Sends the FUSE reply. Runs on the serving thread.
|
||||
respond: Box<dyn FnOnce() + Send>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Parked {
|
||||
waiters: Vec<SizeWaiter>,
|
||||
/// Whether a thread is currently serving `waiters`. The thread clears this
|
||||
/// as it retires, so the next park starts a new one.
|
||||
running: bool,
|
||||
}
|
||||
|
||||
/// Every reply parked on a size upgrade, served by at most one thread.
|
||||
///
|
||||
/// This exists because waiting used to happen on the [`Workers`] pool. Sizes
|
||||
/// are single-flighted per folder, so an `ls -l` across N cold folders parks a
|
||||
/// waiter per entry — and each of those held a pool thread asleep on a condvar
|
||||
/// for up to [`SizeUpgrade::WAIT`]. With enough folders that is every thread in
|
||||
/// both lanes, including the ones reserved for metadata precisely so that this
|
||||
/// could not happen (audit F4). Parking the `Reply` instead costs one thread
|
||||
/// for the whole mount, and only while something is parked.
|
||||
#[derive(Default)]
|
||||
pub(super) struct SizeWaitQueue {
|
||||
parked: Mutex<Parked>,
|
||||
/// Woken when a waiter is added, so a serving thread re-computes how long
|
||||
/// it may sleep.
|
||||
added: Condvar,
|
||||
}
|
||||
|
||||
impl SizeWaitQueue {
|
||||
/// Park `waiter`. Returns whether the caller must start a serving thread.
|
||||
fn park(&self, waiter: SizeWaiter) -> bool {
|
||||
let mut parked = self.parked.lock();
|
||||
parked.waiters.push(waiter);
|
||||
if parked.running {
|
||||
drop(parked);
|
||||
self.added.notify_all();
|
||||
return false;
|
||||
}
|
||||
parked.running = true;
|
||||
true
|
||||
}
|
||||
|
||||
/// Answer every waiter whose node has resolved, whose batch has ended, or
|
||||
/// whose deadline has passed; sleep until the next one might. Returns when
|
||||
/// nothing is parked any more.
|
||||
fn serve(&self) {
|
||||
loop {
|
||||
// Taken out of the lock wholesale: the predicates and the replies
|
||||
// both take locks of their own, and none of them may be called
|
||||
// while this one is held.
|
||||
let taken = std::mem::take(&mut self.parked.lock().waiters);
|
||||
let now = Instant::now();
|
||||
let mut keep = Vec::with_capacity(taken.len());
|
||||
for waiter in taken {
|
||||
if now >= waiter.deadline || waiter.slot.is_finished() || (waiter.resolved)() {
|
||||
(waiter.respond)();
|
||||
} else {
|
||||
keep.push(waiter);
|
||||
}
|
||||
}
|
||||
let mut parked = self.parked.lock();
|
||||
parked.waiters.append(&mut keep);
|
||||
if parked.waiters.is_empty() {
|
||||
parked.running = false;
|
||||
return;
|
||||
}
|
||||
let until = parked
|
||||
.waiters
|
||||
.iter()
|
||||
.map(|w| w.deadline)
|
||||
.min()
|
||||
.unwrap_or(now)
|
||||
.min(Instant::now() + SIZE_WAIT_POLL);
|
||||
self.added.wait_until(&mut parked, until);
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer everything parked, immediately, and retire the serving thread.
|
||||
/// Used when there is no thread to serve with: a provisional size now beats
|
||||
/// a reply that never comes.
|
||||
fn answer_all(&self) {
|
||||
let taken = {
|
||||
let mut parked = self.parked.lock();
|
||||
parked.running = false;
|
||||
std::mem::take(&mut parked.waiters)
|
||||
};
|
||||
for waiter in taken {
|
||||
(waiter.respond)();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
LinkId, MAX_SIZE_UPGRADES, NodeUid, SizeUpgrade, SizeUpgradeClaim, SizeWaitQueue,
|
||||
SizeWaiter, VolumeId, claim_size_upgrade, next_size_upgrade,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Park a waiter the way [`Core::await_size`] does, and hand back the
|
||||
/// channel its reply is sent down, so a test can time the release.
|
||||
fn park(
|
||||
queue: &Arc<SizeWaitQueue>,
|
||||
slot: Arc<SizeUpgrade>,
|
||||
resolved: impl Fn() -> bool + Send + 'static,
|
||||
deadline: Instant,
|
||||
) -> mpsc::Receiver<()> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let waiter = SizeWaiter {
|
||||
slot,
|
||||
resolved: Box::new(resolved),
|
||||
deadline,
|
||||
respond: Box::new(move || {
|
||||
let _ = tx.send(());
|
||||
}),
|
||||
};
|
||||
if queue.park(waiter) {
|
||||
let queue = queue.clone();
|
||||
std::thread::spawn(move || queue.serve());
|
||||
}
|
||||
rx
|
||||
}
|
||||
|
||||
/// Long enough that a test never trips the deadline by accident, short
|
||||
/// enough that one which is *meant* to does not take ten seconds.
|
||||
fn far_off() -> Instant {
|
||||
Instant::now() + Duration::from_secs(30)
|
||||
}
|
||||
|
||||
/// The point of the per-chunk design: a waiter is answered as soon as *its
|
||||
/// own* file is resolved, without waiting for the rest of the folder. A
|
||||
/// single batch over 793 nodes took ~80 s, which outran the timeout and
|
||||
/// handed back the provisional size this is all meant to prevent.
|
||||
#[test]
|
||||
fn a_waiter_returns_on_the_chunk_that_resolves_it() {
|
||||
let queue = Arc::new(SizeWaitQueue::default());
|
||||
let slot = Arc::new(SizeUpgrade::default());
|
||||
let mine = Arc::new(AtomicBool::new(false));
|
||||
let worker = slot.clone();
|
||||
let flag = mine.clone();
|
||||
let t = std::thread::spawn(move || {
|
||||
// Our node lands in the first chunk; two more follow.
|
||||
std::thread::sleep(Duration::from_millis(30));
|
||||
flag.store(true, Ordering::SeqCst);
|
||||
worker.chunk_done();
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
worker.chunk_done();
|
||||
worker.finish();
|
||||
});
|
||||
let started = Instant::now();
|
||||
let rx = park(&queue, slot, move || mine.load(Ordering::SeqCst), far_off());
|
||||
rx.recv().expect("the waiter is answered");
|
||||
// Released by the first chunk, not the last.
|
||||
assert!(started.elapsed() < Duration::from_millis(200));
|
||||
t.join().unwrap();
|
||||
}
|
||||
|
||||
/// `pdfs ls` waits for the whole batch, so it lists no ciphertext size
|
||||
/// (`docs/BUGS.md` B115), but no longer than a `stat` would.
|
||||
#[test]
|
||||
fn a_listing_waits_for_the_whole_size_batch_but_not_forever() {
|
||||
let slot = Arc::new(SizeUpgrade::default());
|
||||
let worker = slot.clone();
|
||||
// Read before the spawn: the worker's sleeps can start before this
|
||||
// thread runs again, which made the bound below fail on a busy runner.
|
||||
let started = Instant::now();
|
||||
let t = std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(30));
|
||||
worker.chunk_done();
|
||||
std::thread::sleep(Duration::from_millis(60));
|
||||
worker.finish();
|
||||
});
|
||||
slot.wait_finished(started + Duration::from_secs(5));
|
||||
// Past the first chunk, up to the end of the batch.
|
||||
assert!(started.elapsed() >= Duration::from_millis(90));
|
||||
assert!(slot.is_finished());
|
||||
t.join().unwrap();
|
||||
|
||||
let stuck = SizeUpgrade::default();
|
||||
let started = Instant::now();
|
||||
stuck.wait_finished(started + Duration::from_millis(50));
|
||||
assert!(started.elapsed() < Duration::from_secs(1));
|
||||
assert!(!stuck.is_finished());
|
||||
}
|
||||
|
||||
/// A chunk that does not resolve this waiter must not answer it.
|
||||
#[test]
|
||||
fn an_unrelated_chunk_does_not_release_a_waiter() {
|
||||
let queue = Arc::new(SizeWaitQueue::default());
|
||||
let slot = Arc::new(SizeUpgrade::default());
|
||||
let worker = slot.clone();
|
||||
let t = std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(30));
|
||||
worker.chunk_done();
|
||||
std::thread::sleep(Duration::from_millis(120));
|
||||
worker.finish();
|
||||
});
|
||||
let started = Instant::now();
|
||||
// Never resolved: only `finish` can end this wait.
|
||||
let rx = park(&queue, slot, || false, far_off());
|
||||
rx.recv().expect("the waiter is answered");
|
||||
assert!(started.elapsed() >= Duration::from_millis(140));
|
||||
t.join().unwrap();
|
||||
}
|
||||
|
||||
/// A batch that ends without resolving the node — a failed fetch — still
|
||||
/// answers its waiters, who fall back to the provisional size.
|
||||
#[test]
|
||||
fn finish_releases_a_waiter_that_was_never_resolved() {
|
||||
let queue = Arc::new(SizeWaitQueue::default());
|
||||
let slot = Arc::new(SizeUpgrade::default());
|
||||
let worker = slot.clone();
|
||||
let t = std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(30));
|
||||
worker.finish();
|
||||
});
|
||||
let started = Instant::now();
|
||||
let rx = park(&queue, slot, || false, far_off());
|
||||
rx.recv().expect("the waiter is answered");
|
||||
assert!(started.elapsed() < SizeUpgrade::WAIT);
|
||||
t.join().unwrap();
|
||||
}
|
||||
|
||||
/// Already resolved before parking: answered on the first pass. This is the
|
||||
/// follower that arrives after the chunk it needed has landed.
|
||||
#[test]
|
||||
fn an_already_resolved_waiter_does_not_block() {
|
||||
let queue = Arc::new(SizeWaitQueue::default());
|
||||
let started = Instant::now();
|
||||
let rx = park(&queue, Arc::new(SizeUpgrade::default()), || true, far_off());
|
||||
rx.recv().expect("the waiter is answered");
|
||||
assert!(started.elapsed() < Duration::from_millis(100));
|
||||
}
|
||||
|
||||
/// Finishing before anyone parks must not strand the late arrival — the
|
||||
/// flag is what is checked, not the notification, which it would miss.
|
||||
#[test]
|
||||
fn waiting_after_finish_returns_at_once() {
|
||||
let queue = Arc::new(SizeWaitQueue::default());
|
||||
let slot = Arc::new(SizeUpgrade::default());
|
||||
slot.finish();
|
||||
let started = Instant::now();
|
||||
let rx = park(&queue, slot, || false, far_off());
|
||||
rx.recv().expect("the waiter is answered");
|
||||
assert!(started.elapsed() < Duration::from_millis(100));
|
||||
}
|
||||
|
||||
/// Every waiter is answered, not just the first: one `ls -l` puts one
|
||||
/// waiter per file on the same folder.
|
||||
#[test]
|
||||
fn all_waiters_are_released() {
|
||||
let queue = Arc::new(SizeWaitQueue::default());
|
||||
let slot = Arc::new(SizeUpgrade::default());
|
||||
let waiters: Vec<_> = (0..8)
|
||||
.map(|_| park(&queue, slot.clone(), || false, far_off()))
|
||||
.collect();
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
slot.finish();
|
||||
for rx in waiters {
|
||||
rx.recv().expect("every waiter is answered");
|
||||
}
|
||||
}
|
||||
|
||||
/// The deadline is the backstop: a batch that never finishes must not wedge
|
||||
/// the caller's `stat` forever.
|
||||
#[test]
|
||||
fn a_waiter_gives_up_at_the_deadline() {
|
||||
let queue = Arc::new(SizeWaitQueue::default());
|
||||
let started = Instant::now();
|
||||
// Nothing will ever resolve or finish this.
|
||||
let rx = park(
|
||||
&queue,
|
||||
Arc::new(SizeUpgrade::default()),
|
||||
|| false,
|
||||
Instant::now() + Duration::from_millis(120),
|
||||
);
|
||||
rx.recv().expect("the waiter is answered");
|
||||
assert!(started.elapsed() >= Duration::from_millis(120));
|
||||
}
|
||||
|
||||
/// The serving thread retires when nothing is parked, and a later park
|
||||
/// starts a new one — otherwise the second `ls -l` of the session would
|
||||
/// hang forever.
|
||||
#[test]
|
||||
fn the_queue_serves_again_after_it_has_drained() {
|
||||
let queue = Arc::new(SizeWaitQueue::default());
|
||||
for _ in 0..3 {
|
||||
let rx = park(&queue, Arc::new(SizeUpgrade::default()), || true, far_off());
|
||||
rx.recv().expect("the waiter is answered");
|
||||
}
|
||||
}
|
||||
|
||||
/// With no thread to serve them, waiters are answered on the spot rather
|
||||
/// than never: a provisional size beats a `stat` that does not return.
|
||||
#[test]
|
||||
fn answer_all_releases_everything_parked() {
|
||||
let queue = SizeWaitQueue::default();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
for _ in 0..4 {
|
||||
let tx = tx.clone();
|
||||
queue.park(SizeWaiter {
|
||||
slot: Arc::new(SizeUpgrade::default()),
|
||||
resolved: Box::new(|| false),
|
||||
deadline: far_off(),
|
||||
respond: Box::new(move || {
|
||||
let _ = tx.send(());
|
||||
}),
|
||||
});
|
||||
}
|
||||
drop(tx);
|
||||
queue.answer_all();
|
||||
assert_eq!(rx.into_iter().count(), 4);
|
||||
}
|
||||
|
||||
fn uids(links: &[&str]) -> Vec<NodeUid> {
|
||||
links
|
||||
.iter()
|
||||
.map(|link| NodeUid::new(VolumeId::from("vol"), LinkId::from(*link)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Past the cap a folder used to get no upgrade at all, so a recursive
|
||||
/// walk reported ciphertext sizes for most of what it listed (`docs/BUGS.md` B100).
|
||||
#[test]
|
||||
fn a_folder_past_the_cap_is_queued_not_dropped() {
|
||||
let mut in_flight = HashMap::new();
|
||||
for key in 0..MAX_SIZE_UPGRADES as u64 {
|
||||
let claim = claim_size_upgrade(&mut in_flight, key, uids(&["a"]));
|
||||
assert!(matches!(claim, SizeUpgradeClaim::Start(..)));
|
||||
}
|
||||
let key = MAX_SIZE_UPGRADES as u64;
|
||||
let claim = claim_size_upgrade(&mut in_flight, key, uids(&["late"]));
|
||||
let SizeUpgradeClaim::Queued(slot) = claim else {
|
||||
panic!("expected the batch to be queued");
|
||||
};
|
||||
assert!(Arc::ptr_eq(&slot, &in_flight[&key]));
|
||||
// A second caller for the queued folder waits on the same batch.
|
||||
let again = claim_size_upgrade(&mut in_flight, key, uids(&["late"]));
|
||||
assert!(matches!(again, SizeUpgradeClaim::Joined(s) if Arc::ptr_eq(&s, &slot)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_batch_hands_its_thread_the_oldest_queued_one() {
|
||||
let mut in_flight = HashMap::new();
|
||||
for key in 0..MAX_SIZE_UPGRADES as u64 {
|
||||
claim_size_upgrade(&mut in_flight, key, uids(&["a"]));
|
||||
}
|
||||
let first = MAX_SIZE_UPGRADES as u64;
|
||||
claim_size_upgrade(&mut in_flight, first, uids(&["first"]));
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
claim_size_upgrade(&mut in_flight, first + 1, uids(&["second"]));
|
||||
|
||||
let (key, taken, slot) = next_size_upgrade(&mut in_flight, 0).expect("a queued batch");
|
||||
assert_eq!((key, taken), (first, uids(&["first"])));
|
||||
assert!(slot.queued.lock().is_none());
|
||||
assert!(!in_flight.contains_key(&0));
|
||||
// Still at the cap: the handed-over batch counts as running.
|
||||
let running = in_flight
|
||||
.values()
|
||||
.filter(|s| s.queued.lock().is_none())
|
||||
.count();
|
||||
assert_eq!(running, MAX_SIZE_UPGRADES);
|
||||
|
||||
let (key, _, _) = next_size_upgrade(&mut in_flight, 1).expect("the other one");
|
||||
assert_eq!(key, first + 1);
|
||||
assert!(next_size_upgrade(&mut in_flight, 2).is_none());
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@
|
||||
//! 3. **Sample memory.** That hang peaked at 5.2 GiB resident, and nobody knew
|
||||
//! until it was over.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::io::{BufRead, BufReader, Write as _};
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -64,10 +65,12 @@ pub(crate) fn run(core: Core, control_socket: PathBuf) {
|
||||
// Per-lane completion counts from the previous tick, to tell a queue that is
|
||||
// being worked through from one that is not moving at all.
|
||||
let mut last_completed = (0_u64, 0_u64);
|
||||
// The services already reported as ended, so each is reported once.
|
||||
let mut ended = HashSet::new();
|
||||
|
||||
while core.shutdown.sleep(TICK) {
|
||||
let report = core.diagnostics();
|
||||
let stalled = report_stalls(&report, last_completed);
|
||||
let stalled = report_stalls(&report, last_completed) | report_ended(&report, &mut ended);
|
||||
last_completed = (report.meta_completed, report.transfer_completed);
|
||||
|
||||
if last_rss.elapsed() >= RSS_EVERY {
|
||||
@@ -174,6 +177,24 @@ fn report_stalls(report: &pdfs_core::control::Diagnostics, last_completed: (u64,
|
||||
stalled
|
||||
}
|
||||
|
||||
/// WARN once about each service thread that has ended. Every one of them runs
|
||||
/// until the mount stops, and the supervisor stops looking once a stop
|
||||
/// begins, so an ended one died early: a panic, or a loop that gave up.
|
||||
/// Returns whether any is ended.
|
||||
fn report_ended(report: &pdfs_core::control::Diagnostics, reported: &mut HashSet<String>) -> bool {
|
||||
let mut any = false;
|
||||
for service in report.services.iter().filter(|service| !service.running) {
|
||||
any = true;
|
||||
if reported.insert(service.name.clone()) {
|
||||
warn!(
|
||||
service = %service.name,
|
||||
"a daemon service has ended while the mount runs; it does not restart until the daemon does"
|
||||
);
|
||||
}
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
/// Whether the watchdog wants its next ping. The first one is due at once.
|
||||
fn ping_due(last_ping: Option<Instant>, period: Duration) -> bool {
|
||||
last_ping.is_none_or(|at| at.elapsed() >= period)
|
||||
@@ -208,7 +229,36 @@ fn probe(control_socket: &Path) -> bool {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pdfs_core::control::{Diagnostics, InflightRequest, SyncEngineState, WorkerState};
|
||||
use pdfs_core::control::{
|
||||
Diagnostics, InflightRequest, ServiceState, SyncEngineState, WorkerState,
|
||||
};
|
||||
|
||||
/// A service that ended is reported, once, and one still running is not.
|
||||
#[test]
|
||||
fn an_ended_service_is_reported_once() {
|
||||
let service = |name: &str, running| ServiceState {
|
||||
name: name.into(),
|
||||
running,
|
||||
age_secs: 60,
|
||||
};
|
||||
let report = Diagnostics {
|
||||
services: vec![
|
||||
service("pdfs-sync", true),
|
||||
service("pdfs-pin-keeper", false),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let mut reported = HashSet::new();
|
||||
assert!(report_ended(&report, &mut reported));
|
||||
assert_eq!(reported, HashSet::from(["pdfs-pin-keeper".to_string()]));
|
||||
assert!(report_ended(&report, &mut reported));
|
||||
assert_eq!(reported.len(), 1);
|
||||
let healthy = Diagnostics {
|
||||
services: vec![service("pdfs-sync", true)],
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!report_ended(&healthy, &mut HashSet::new()));
|
||||
}
|
||||
|
||||
fn busy_worker(age_secs: u64) -> WorkerState {
|
||||
WorkerState {
|
||||
|
||||
@@ -18,7 +18,10 @@
|
||||
//! copy whose sibling has no recorded SHA-1 is treated as divergent — the sweep
|
||||
//! never removes a file it cannot prove is a duplicate.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use pdfs_core::batch;
|
||||
@@ -29,6 +32,31 @@ use tracing::{debug, info, warn};
|
||||
|
||||
use super::{Core, node_content_sha1, node_revision_id, node_size};
|
||||
|
||||
/// What the conflict sweep may do, and the copies it already checked this
|
||||
/// run.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct SweepState {
|
||||
/// Whether the conflict sweep may actually trash the duplicates it finds, or
|
||||
/// only report them. Resolved once at mount from config + environment
|
||||
/// ([`AppConfig::resolved_conflict_sweep`]); [`SweepMode::Off`] means the
|
||||
/// sweep thread is never spawned at all. See `docs/BUGS.md` B71.
|
||||
pub(crate) sweep_mode: SweepMode,
|
||||
/// 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.
|
||||
pub(crate) conflict_notified: Arc<Mutex<HashSet<NodeUid>>>,
|
||||
}
|
||||
|
||||
impl SweepState {
|
||||
pub(crate) fn new(sweep_mode: SweepMode) -> Self {
|
||||
Self {
|
||||
sweep_mode,
|
||||
conflict_notified: Arc::new(Mutex::new(HashSet::new())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Time between sweeps. Conflicts are rare and non-urgent; a slow cadence keeps
|
||||
/// the sweep off the hot path while still cleaning up within a few minutes.
|
||||
const CONFLICT_SWEEP_INTERVAL: Duration = Duration::from_secs(300);
|
||||
@@ -141,7 +169,7 @@ impl Core {
|
||||
.unwrap_or_default();
|
||||
let sibling = by_parent_name.get(&(parent, base.as_str())).copied();
|
||||
|
||||
match decide(node, sibling, &base, self.sweep_mode) {
|
||||
match decide(node, sibling, &base, self.sweep.sweep_mode) {
|
||||
SweepAction::Remove => {
|
||||
// Only while online — the remote trash is the point. Offline,
|
||||
// it waits for a later pass.
|
||||
@@ -210,7 +238,7 @@ impl Core {
|
||||
warn!(%uid, error = ?e, "conflict sweep: db delete after trash failed");
|
||||
}
|
||||
self.invalidate_trash();
|
||||
self.conflict_notified.lock().remove(uid);
|
||||
self.sweep.conflict_notified.lock().remove(uid);
|
||||
self.log_activity(
|
||||
ActivityKind::Trash,
|
||||
name,
|
||||
@@ -303,7 +331,7 @@ impl Core {
|
||||
/// 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.conflict_notified.lock().insert(uid.clone()) {
|
||||
if !self.sweep.conflict_notified.lock().insert(uid.clone()) {
|
||||
return;
|
||||
}
|
||||
match self.db.activity_has(ActivityKind::Conflict, name) {
|
||||
|
||||
@@ -0,0 +1,620 @@
|
||||
//! The Drive trash as the front-ends see it: listing it, refreshing that
|
||||
//! listing in the background, restoring from it, deleting from it for good.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Whether a trash refresh is running, and the wake-up for requests waiting
|
||||
/// on its progress.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct TrashState {
|
||||
/// True while a background refresh of the trash is already running, so a
|
||||
/// burst of requests against a stale listing starts one refresh.
|
||||
pub(crate) trash_refreshing: Arc<AtomicBool>,
|
||||
/// 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`].
|
||||
pub(crate) trash_progress: Arc<tokio::sync::Notify>,
|
||||
}
|
||||
|
||||
impl TrashState {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
trash_refreshing: Arc::new(AtomicBool::new(false)),
|
||||
trash_progress: Arc::new(tokio::sync::Notify::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// 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
|
||||
/// each entry is identified by its uid (its only remaining handle) with an
|
||||
/// empty path.
|
||||
///
|
||||
/// 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.
|
||||
///
|
||||
/// 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
|
||||
/// that have landed so far. Blocking the request on the whole refresh is what
|
||||
/// 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>> {
|
||||
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) {
|
||||
self.spawn_trash_refresh();
|
||||
}
|
||||
if never_fetched {
|
||||
self.await_trash_refresh(TRASH_FIRST_WAIT);
|
||||
}
|
||||
|
||||
let items = self.db.trash_list().map_err(CoreError::from)?;
|
||||
let trashed: HashSet<&str> = items.iter().map(|item| item.uid.as_str()).collect();
|
||||
let trashed_parents: Vec<Option<String>> = items
|
||||
.iter()
|
||||
.map(|item| {
|
||||
item.parent_uid
|
||||
.clone()
|
||||
.filter(|parent| trashed.contains(parent.as_str()))
|
||||
})
|
||||
.collect();
|
||||
// Most of a trash comes from a handful of folders.
|
||||
let mut origins: HashMap<String, Option<String>> = HashMap::new();
|
||||
Ok(items
|
||||
.into_iter()
|
||||
.zip(trashed_parents)
|
||||
.map(|(item, trashed_parent)| DirEntry {
|
||||
trashed_from: item.parent_uid.as_ref().and_then(|parent| {
|
||||
origins
|
||||
.entry(parent.clone())
|
||||
.or_insert_with(|| self.db.node_path(parent).ok().flatten())
|
||||
.clone()
|
||||
}),
|
||||
trashed_parent,
|
||||
trashed_at: item.trashed_at.unwrap_or(0),
|
||||
name: item.name,
|
||||
is_dir: item.is_dir,
|
||||
size: item.size.max(0) as u64,
|
||||
modified: item.mtime,
|
||||
// A trashed node can't be pinned or served from the mount, so its
|
||||
// content is never current cache: report neither.
|
||||
pinned: false,
|
||||
pinned_by_folder: false,
|
||||
cached: false,
|
||||
uid: item.uid,
|
||||
path: String::new(),
|
||||
role: String::new(),
|
||||
shared_by: String::new(),
|
||||
shared_at: 0,
|
||||
shared_by_unverified: false,
|
||||
issue: None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// 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>> {
|
||||
let folder =
|
||||
parse_uid(uid).ok_or_else(|| CoreError::invalid(format!("invalid uid: {uid}")))?;
|
||||
let children = self
|
||||
.rt
|
||||
.block_on(within_trash_call(
|
||||
"enumerate trashed folder",
|
||||
self.drive.enumerate_folder_children_node_uids(&folder),
|
||||
))?
|
||||
.map_err(|e| CoreError::from_api(&e, "enumerate trashed folder"))?;
|
||||
let mut nodes = Vec::with_capacity(children.len());
|
||||
for chunk in children.chunks(TRASH_MATERIALIZE_CHUNK) {
|
||||
nodes.extend(
|
||||
self.rt
|
||||
.block_on(within_trash_call(
|
||||
"enumerate nodes",
|
||||
self.drive.enumerate_trashed_nodes_light(chunk),
|
||||
))?
|
||||
.map_err(|e| CoreError::from_api(&e, "enumerate nodes"))?,
|
||||
);
|
||||
}
|
||||
let stored = self.db.trash_list().map_err(CoreError::from)?;
|
||||
let stored_at: HashMap<&str, Option<i64>> = stored
|
||||
.iter()
|
||||
.map(|item| (item.uid.as_str(), item.trashed_at))
|
||||
.collect();
|
||||
let mut entries: Vec<DirEntry> = nodes
|
||||
.iter()
|
||||
.map(|TrashedNode { node, trash_time }| {
|
||||
let uid = node.uid.to_string();
|
||||
let trashed_at = trash_time
|
||||
.or_else(|| stored_at.get(uid.as_str()).copied().flatten())
|
||||
.unwrap_or(0);
|
||||
trashed_entry(
|
||||
uid,
|
||||
node.name.clone(),
|
||||
node.is_folder(),
|
||||
node_size(node) as i64,
|
||||
node.modification_time,
|
||||
trashed_at,
|
||||
folder.to_string(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let listed: HashSet<String> = entries.iter().map(|e| e.uid.clone()).collect();
|
||||
entries.extend(
|
||||
stored
|
||||
.into_iter()
|
||||
.filter(|item| {
|
||||
item.parent_uid.as_deref() == Some(uid) && !listed.contains(&item.uid)
|
||||
})
|
||||
.map(|item| {
|
||||
trashed_entry(
|
||||
item.uid,
|
||||
item.name,
|
||||
item.is_dir,
|
||||
item.size,
|
||||
item.mtime,
|
||||
item.trashed_at.unwrap_or(0),
|
||||
folder.to_string(),
|
||||
)
|
||||
}),
|
||||
);
|
||||
entries.sort_by(|a, b| {
|
||||
b.is_dir
|
||||
.cmp(&a.is_dir)
|
||||
.then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
|
||||
});
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
/// Re-fetch the trash listing from the server and persist it.
|
||||
///
|
||||
/// Only nodes the stored listing does not hold yet are read, and light: a
|
||||
/// trashed file needs no content key, so none is unlocked. Each chunk of
|
||||
/// [`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<()> {
|
||||
let started = Instant::now();
|
||||
let uids = within_trash_call("enumerate trash", self.drive.enumerate_trash_node_uids())
|
||||
.await?
|
||||
.map_err(|e| CoreError::from_api(&e, "enumerate trash"))?;
|
||||
info!(
|
||||
count = uids.len(),
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"trash refresh: enumerated"
|
||||
);
|
||||
|
||||
let seen = self.db.trash_seen().unwrap_or_default();
|
||||
let complete = self
|
||||
.db
|
||||
.state_i64(TRASH_COMPLETE_MS)
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some();
|
||||
let now = now_secs();
|
||||
|
||||
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();
|
||||
}
|
||||
let missing: Vec<NodeUid> = uids
|
||||
.into_iter()
|
||||
.filter(|uid| !seen.contains_key(&uid.to_string()))
|
||||
.collect();
|
||||
let mut materialized = 0usize;
|
||||
for chunk in missing.chunks(TRASH_MATERIALIZE_CHUNK) {
|
||||
let chunk_started = Instant::now();
|
||||
let nodes = within_trash_call(
|
||||
"enumerate nodes",
|
||||
self.drive.enumerate_trashed_nodes_light(chunk),
|
||||
)
|
||||
.await?
|
||||
.map_err(|e| CoreError::from_api(&e, "enumerate nodes"))?;
|
||||
let items: Vec<StoredTrash> = nodes
|
||||
.into_iter()
|
||||
.map(|TrashedNode { node, trash_time }| {
|
||||
let uid = node.uid.to_string();
|
||||
StoredTrash {
|
||||
trashed_at: trash_time
|
||||
.or_else(|| first_seen_in_trash(&seen, &uid, complete, now)),
|
||||
uid,
|
||||
name: node.name.clone(),
|
||||
is_dir: node.is_folder(),
|
||||
size: node_size(&node) as i64,
|
||||
mtime: node.modification_time,
|
||||
// The folder the node will go back to, which is also what
|
||||
// tells a restore whether that folder is itself in the trash.
|
||||
parent_uid: node.parent_uid.as_ref().map(|uid| uid.to_string()),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
materialized += items.len();
|
||||
self.db.trash_upsert(&items).map_err(CoreError::from)?;
|
||||
self.trash.trash_progress.notify_waiters();
|
||||
self.events.publish(&[Topic::Trash]);
|
||||
debug!(
|
||||
materialized,
|
||||
total = missing.len(),
|
||||
chunk_ms = chunk_started.elapsed().as_millis() as u64,
|
||||
"trash refresh: batch"
|
||||
);
|
||||
}
|
||||
|
||||
let _ = self.db.set_state_i64(TRASH_SYNCED_MS, now_ms());
|
||||
let _ = self.db.set_state_i64(TRASH_COMPLETE_MS, now_ms());
|
||||
info!(
|
||||
count = listed.len(),
|
||||
new = materialized,
|
||||
removed,
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"trash refresh: done"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// 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) {
|
||||
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();
|
||||
});
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
let deadline = Instant::now() + budget;
|
||||
self.rt.block_on(async {
|
||||
while self.trash.trash_refreshing.load(Ordering::SeqCst) {
|
||||
let Some(left) = deadline.checked_duration_since(Instant::now()) else {
|
||||
break;
|
||||
};
|
||||
let notified = self.trash.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) {
|
||||
break;
|
||||
}
|
||||
if tokio::time::timeout(left, notified).await.is_err() {
|
||||
warn!(
|
||||
budget_s = budget.as_secs(),
|
||||
"trash refresh still running; answering with what has materialized"
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Drop the persisted trash listing's freshness stamp after we changed the
|
||||
/// 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);
|
||||
}
|
||||
|
||||
/// Restore trashed nodes to the folders they were trashed from, together
|
||||
/// with the rest of the trashed tree they belong to.
|
||||
///
|
||||
/// The trash is a flat list, but a user deletes a shape: a folder, and often
|
||||
/// items inside it that were trashed separately beforehand. Restoring one of
|
||||
/// those in isolation is not what anyone means by it — a folder would come
|
||||
/// back without the contents that were deleted with it, and a file would come
|
||||
/// back inside a folder that is still in the trash, which is to say nowhere
|
||||
/// the user can see. So a restore takes the whole connected piece:
|
||||
/// every trashed descendant of what was asked for, and every trashed ancestor
|
||||
/// above it. See [`expand_restore`] for the exact rule.
|
||||
///
|
||||
/// The waves are restored shallowest first, because a node cannot be put back
|
||||
/// under a parent that is still trashed.
|
||||
///
|
||||
/// 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)?;
|
||||
// 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();
|
||||
let waves = expand_restore(uids, &relations);
|
||||
let waves: Vec<Vec<NodeUid>> = if waves.is_empty() {
|
||||
vec![requested.clone()]
|
||||
} else {
|
||||
waves
|
||||
.iter()
|
||||
.map(|wave| {
|
||||
wave.iter()
|
||||
.filter_map(|uid| parse_uid(uid))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.filter(|wave: &Vec<NodeUid>| !wave.is_empty())
|
||||
.collect()
|
||||
};
|
||||
|
||||
let all: Vec<NodeUid> = waves.iter().flatten().cloned().collect();
|
||||
let parents: Vec<NodeUid> = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_nodes(&all))
|
||||
.map_err(|e| CoreError::from_api(&e, "enumerate nodes"))?
|
||||
.into_iter()
|
||||
.filter_map(|n| n.parent_uid)
|
||||
.collect();
|
||||
// Streamed per-node outcomes: a uid the server refuses (already restored,
|
||||
// gone) leaves the rest of the batch restored, and each node is unhidden
|
||||
// as *its* batch lands rather than after the last one — a daemon killed
|
||||
// half way through a large restore leaves local state describing what the
|
||||
// server actually did. Only a batch that restored nothing is an error the
|
||||
// caller can act on.
|
||||
let mut restored: Vec<NodeUid> = Vec::with_capacity(all.len());
|
||||
let mut first_error: Option<ProtonError> = None;
|
||||
for wave in &waves {
|
||||
self.rt
|
||||
.block_on(async {
|
||||
let mut outcomes = std::pin::pin!(self.drive.restore_nodes_streaming(wave));
|
||||
while let Some(item) = outcomes.next().await {
|
||||
let (uid, outcome) = item?;
|
||||
match outcome {
|
||||
Ok(()) => {
|
||||
self.hidden.lock().remove(&uid);
|
||||
restored.push(uid);
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(%uid, error = %e, "restore failed for a node");
|
||||
first_error.get_or_insert(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok::<(), ProtonError>(())
|
||||
})
|
||||
.map_err(|e| CoreError::from_api(&e, "restore"))?;
|
||||
}
|
||||
if restored.is_empty()
|
||||
&& let Some(error) = first_error
|
||||
{
|
||||
return Err(CoreError::from_api(&error, "restore"));
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
});
|
||||
let back: Vec<String> = restored.iter().map(ToString::to_string).collect();
|
||||
let _ = self.db.trash_remove(&back);
|
||||
self.invalidate_trash();
|
||||
Ok(restored.len())
|
||||
}
|
||||
|
||||
/// 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)?;
|
||||
// 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
|
||||
// the server destroyed — never more, never fewer.
|
||||
let mut deleted = 0usize;
|
||||
let mut gone: Vec<String> = Vec::new();
|
||||
let mut first_error: Option<ProtonError> = None;
|
||||
self.rt
|
||||
.block_on(async {
|
||||
let mut outcomes = std::pin::pin!(self.drive.delete_nodes_streaming(&parsed));
|
||||
while let Some(item) = outcomes.next().await {
|
||||
let (uid, outcome) = item?;
|
||||
match outcome {
|
||||
Ok(()) => {
|
||||
self.drop_local(std::slice::from_ref(&uid));
|
||||
gone.push(uid.to_string());
|
||||
deleted += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(%uid, error = %e, "permanent delete failed for a node");
|
||||
first_error.get_or_insert(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok::<(), ProtonError>(())
|
||||
})
|
||||
.map_err(|e| CoreError::from_api(&e, "delete"))?;
|
||||
if deleted == 0
|
||||
&& let Some(error) = first_error
|
||||
{
|
||||
return Err(CoreError::from_api(&error, "delete"));
|
||||
}
|
||||
let _ = self.db.trash_remove(&gone);
|
||||
self.invalidate_trash();
|
||||
Ok(deleted)
|
||||
}
|
||||
|
||||
/// Permanently delete everything in the trash.
|
||||
///
|
||||
/// The stored listing says what goes, so the blobs of items trashed by
|
||||
/// another client, which this daemon may still hold, are reclaimed too. It
|
||||
/// is not read from the server again first: on a large trash that listing
|
||||
/// 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> {
|
||||
let uids: Vec<String> = self
|
||||
.db
|
||||
.trash_seen()
|
||||
.map_err(CoreError::from)?
|
||||
.into_keys()
|
||||
.collect();
|
||||
self.rt
|
||||
.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);
|
||||
let _ = self.db.trash_replace(&[]);
|
||||
let _ = self.db.set_state_i64(TRASH_SYNCED_MS, now_ms());
|
||||
self.events.publish(&[Topic::Trash]);
|
||||
Ok(uids.len())
|
||||
}
|
||||
}
|
||||
|
||||
/// An entry inside a trashed folder, for [`Core::list_trashed_folder`].
|
||||
pub(super) fn trashed_entry(
|
||||
uid: String,
|
||||
name: String,
|
||||
is_dir: bool,
|
||||
size: i64,
|
||||
mtime: i64,
|
||||
trashed_at: i64,
|
||||
parent: String,
|
||||
) -> DirEntry {
|
||||
DirEntry {
|
||||
name,
|
||||
is_dir,
|
||||
size: size.max(0) as u64,
|
||||
modified: mtime,
|
||||
pinned: false,
|
||||
pinned_by_folder: false,
|
||||
cached: false,
|
||||
uid,
|
||||
path: String::new(),
|
||||
role: String::new(),
|
||||
shared_by: String::new(),
|
||||
shared_at: 0,
|
||||
shared_by_unverified: false,
|
||||
trashed_at,
|
||||
trashed_from: None,
|
||||
trashed_parent: Some(parent),
|
||||
issue: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// When a node a trash refresh found went to the trash, as far as the daemon
|
||||
/// can tell. A node the stored listing already had keeps the time it had. A new
|
||||
/// one went there since the last refresh, so now is close, but only when that
|
||||
/// refresh saw the whole trash (`complete`): after a first or interrupted one,
|
||||
/// a node missing from the listing may be years old, and no date beats a wrong
|
||||
/// one.
|
||||
pub(super) fn first_seen_in_trash(
|
||||
seen: &HashMap<String, Option<i64>>,
|
||||
uid: &str,
|
||||
complete: bool,
|
||||
now: i64,
|
||||
) -> Option<i64> {
|
||||
match seen.get(uid) {
|
||||
Some(at) => *at,
|
||||
None if complete => Some(now),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand a restore request across the trashed tree, and order it so a parent is
|
||||
/// always restored before its children.
|
||||
///
|
||||
/// `relations` is the persisted trash listing as `(uid, parent_uid)` pairs; a
|
||||
/// parent that is not itself in the listing is a live folder, which ends the
|
||||
/// walk upward. The rule is:
|
||||
///
|
||||
/// - every trashed descendant of a requested node joins the restore, so a folder
|
||||
/// comes back with the items that were trashed inside it;
|
||||
/// - every trashed ancestor of a requested node joins it too, so a file never
|
||||
/// lands in a folder that is still in the trash;
|
||||
/// - a requested uid the listing does not know about is restored on its own,
|
||||
/// because a stale or half-materialised listing must not silently drop it.
|
||||
///
|
||||
/// The result is one wave per depth, shallowest first. Waves are disjoint and
|
||||
/// together contain each uid exactly once.
|
||||
pub(super) fn expand_restore(
|
||||
requested: &[String],
|
||||
relations: &[(String, Option<String>)],
|
||||
) -> Vec<Vec<String>> {
|
||||
let parents: HashMap<&str, Option<&str>> = relations
|
||||
.iter()
|
||||
.map(|(uid, parent)| (uid.as_str(), parent.as_deref()))
|
||||
.collect();
|
||||
let mut children: HashMap<&str, Vec<&str>> = HashMap::new();
|
||||
for (uid, parent) in relations {
|
||||
// Only a trashed parent: a live one keeps its child as a root here.
|
||||
if let Some(parent) = parent.as_deref()
|
||||
&& parents.contains_key(parent)
|
||||
{
|
||||
children.entry(parent).or_default().push(uid.as_str());
|
||||
}
|
||||
}
|
||||
|
||||
let mut selected: HashSet<&str> = HashSet::new();
|
||||
for uid in requested {
|
||||
let uid = uid.as_str();
|
||||
if !parents.contains_key(uid) {
|
||||
selected.insert(uid);
|
||||
continue;
|
||||
}
|
||||
// Upward: every trashed ancestor, so the destination folder exists again.
|
||||
let mut cursor = Some(uid);
|
||||
while let Some(current) = cursor {
|
||||
// A parent outside the listing is live: the walk stops under it.
|
||||
if !parents.contains_key(current) || !selected.insert(current) {
|
||||
break;
|
||||
}
|
||||
cursor = parents.get(current).copied().flatten();
|
||||
}
|
||||
// Downward: the whole trashed subtree, so the folder comes back full.
|
||||
let mut stack = vec![uid];
|
||||
while let Some(current) = stack.pop() {
|
||||
for child in children.get(current).into_iter().flatten() {
|
||||
if selected.insert(child) {
|
||||
stack.push(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Depth within the *trash*, not within the drive: a node whose parent is live
|
||||
// (or unknown) is at depth 0 and can be restored straight away.
|
||||
let mut waves: Vec<Vec<String>> = Vec::new();
|
||||
for uid in &selected {
|
||||
let mut depth = 0usize;
|
||||
let mut cursor = parents.get(uid).copied().flatten();
|
||||
// Only trashed ancestors count, and the walk is bounded by the listing's
|
||||
// size: server data that somehow describes a cycle must not spin here.
|
||||
while let Some(current) = cursor
|
||||
&& parents.contains_key(current)
|
||||
&& depth < parents.len()
|
||||
{
|
||||
depth += 1;
|
||||
cursor = parents.get(current).copied().flatten();
|
||||
}
|
||||
if waves.len() <= depth {
|
||||
waves.resize(depth + 1, Vec::new());
|
||||
}
|
||||
waves[depth].push((*uid).to_string());
|
||||
}
|
||||
// Stable output, so a restore of the same trash is the same sequence of calls
|
||||
// every time — the batches are what shows up in the log and in the tests.
|
||||
for wave in &mut waves {
|
||||
wave.sort();
|
||||
}
|
||||
waves.retain(|wave| !wave.is_empty());
|
||||
waves
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
//!
|
||||
//! [`mirror`] runs the passes. It walks both sides, applies the plan and runs
|
||||
//! the engine thread; it owns its state and reaches the rest of the daemon only
|
||||
//! through [`mirror::SyncHost`]. The rest is the engine's decisions, apart from
|
||||
//! through [`mirror::SyncHost`], and its database tables only through
|
||||
//! [`store::SyncStore`]. The rest is the engine's decisions, apart from
|
||||
//! the I/O that feeds and applies them: [`model`] is what a pass knows about
|
||||
//! each path, [`planner`] decides what to do with it and refuses what looks
|
||||
//! like a wipe, [`trace`] records where a pass spent its time, and [`naming`]
|
||||
@@ -23,6 +24,7 @@ pub mod mirror;
|
||||
pub mod model;
|
||||
pub mod naming;
|
||||
pub mod planner;
|
||||
pub mod store;
|
||||
pub mod trace;
|
||||
|
||||
use model::{LocalItem, LocalSig, RemoteItem};
|
||||
|
||||
+57
-581
@@ -30,7 +30,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::mpsc::{Receiver, RecvTimeoutError};
|
||||
use std::time::{Duration, Instant, SystemTime};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use notify::{RecursiveMode, Watcher};
|
||||
use proton_drive_rs::Node;
|
||||
@@ -48,32 +48,37 @@ use pdfs_store::db::{SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder
|
||||
|
||||
mod engine;
|
||||
mod host;
|
||||
mod local;
|
||||
mod local_scan;
|
||||
use crate::model;
|
||||
use crate::planner;
|
||||
use crate::trace;
|
||||
pub use engine::SYNC_CONCURRENCY;
|
||||
pub use engine::{EngineHealth, SyncMsg, spawn};
|
||||
pub use engine::{EngineHealth, SyncMsg, run};
|
||||
#[cfg(test)]
|
||||
use engine::{Running, burst_order, keep_wanted, smallest_first};
|
||||
#[cfg(test)]
|
||||
use engine::{classify, event_target, settle_with};
|
||||
pub use host::{SyncHost, SyncParts, Syncer};
|
||||
use local::*;
|
||||
pub use local::{mirror_subtree_unsynced, mirror_tree_gone, mirror_tree_unsynced};
|
||||
#[cfg(test)]
|
||||
use local_scan::is_write_mode;
|
||||
use local_scan::open_for_write_set;
|
||||
use model::{Applied, remote_file_sig, system_mtime, system_mtime_ns};
|
||||
use model::{Applied, remote_file_sig, system_mtime};
|
||||
use model::{LocalItem, LocalSig, Outcome, PassAbort, Pending, RemoteItem, RemoteSeen};
|
||||
pub use planner::base_name;
|
||||
#[cfg(test)]
|
||||
use planner::conflict_path;
|
||||
#[cfg(test)]
|
||||
use planner::conflict_path_as;
|
||||
#[cfg(test)]
|
||||
use planner::filter_baseline;
|
||||
use planner::{
|
||||
FilePlan, RemoteGaps, Unscanned, classification_order, conflict_path_with_suffix,
|
||||
filter_baseline, guard_local_wipe, guard_remote_wipe, join_rel, local_deletions, parent_rel,
|
||||
plan_file, rel_to_path, remote_sig, remote_subtree_changed, revision_confirms_baseline,
|
||||
revision_moved, tracked_baseline, unchanged_remote_size,
|
||||
FilePlan, RemoteGaps, Unscanned, classification_order, guard_local_wipe, guard_remote_wipe,
|
||||
join_rel, local_deletions, parent_rel, plan_file, rel_to_path, remote_sig,
|
||||
remote_subtree_changed, revision_confirms_baseline, revision_moved, tracked_baseline,
|
||||
unchanged_remote_size,
|
||||
};
|
||||
use trace::{Call, Count, Phase};
|
||||
|
||||
@@ -116,7 +121,7 @@ impl Syncer {
|
||||
self.trace_phase(Phase::LockWait, waited.elapsed());
|
||||
// `folder` was read before the lock; a switch may have landed in between, so
|
||||
// re-read and re-check the mode rather than trusting the snapshot.
|
||||
let current = match self.db.sync_folder_get(folder.id) {
|
||||
let current = match self.store.sync_folder_get(folder.id) {
|
||||
Ok(Some(current)) if current.mode == "mirror" => current,
|
||||
Ok(Some(_)) => return,
|
||||
Ok(None) => return,
|
||||
@@ -137,13 +142,13 @@ impl Syncer {
|
||||
if !local_root.is_dir() {
|
||||
warn!(id = folder.id, path = %local_root.display(), "sync: local root missing");
|
||||
let _ = self
|
||||
.db
|
||||
.store
|
||||
.sync_folder_set_state(folder.id, "error", now_secs());
|
||||
return;
|
||||
}
|
||||
|
||||
let _ = self
|
||||
.db
|
||||
.store
|
||||
.sync_folder_set_state(folder.id, "syncing", folder.last_sync);
|
||||
let name = base_name(&folder.local_path);
|
||||
// Rebuilt per pass rather than cached on `Core`, so editing `.pdfsignore`
|
||||
@@ -218,7 +223,9 @@ impl Syncer {
|
||||
} else {
|
||||
"idle"
|
||||
};
|
||||
let _ = self.db.sync_folder_set_state(folder.id, state, now_secs());
|
||||
let _ = self
|
||||
.store
|
||||
.sync_folder_set_state(folder.id, state, now_secs());
|
||||
let elapsed = started.elapsed();
|
||||
if let Some(first_error) = &outcome.first_error {
|
||||
warn!(
|
||||
@@ -283,9 +290,9 @@ impl Syncer {
|
||||
total = progress.as_ref().map_or(0, |p| p.total),
|
||||
"sync: pass cut short by the stop"
|
||||
);
|
||||
let _ = self
|
||||
.db
|
||||
.sync_folder_set_state(folder.id, ¤t.state, current.last_sync);
|
||||
let _ =
|
||||
self.store
|
||||
.sync_folder_set_state(folder.id, ¤t.state, current.last_sync);
|
||||
}
|
||||
Err(PassAbort::Abandoned) => {
|
||||
info!(
|
||||
@@ -293,14 +300,14 @@ impl Syncer {
|
||||
elapsed_s = started.elapsed().as_secs(),
|
||||
"sync: pass stopped for the folder's removal"
|
||||
);
|
||||
let _ = self
|
||||
.db
|
||||
.sync_folder_set_state(folder.id, ¤t.state, current.last_sync);
|
||||
let _ =
|
||||
self.store
|
||||
.sync_folder_set_state(folder.id, ¤t.state, current.last_sync);
|
||||
}
|
||||
Err(PassAbort::Failed(e)) => {
|
||||
warn!(id = folder.id, error = %e, "sync: reconcile failed");
|
||||
let _ = self
|
||||
.db
|
||||
.store
|
||||
.sync_folder_set_state(folder.id, "error", now_secs());
|
||||
if folder.state != "error" {
|
||||
self.log_activity(
|
||||
@@ -416,7 +423,7 @@ impl Syncer {
|
||||
/// both agree on.
|
||||
fn ondemand_queued(&self, folder_id: i64) -> bool {
|
||||
matches!(
|
||||
self.db.sync_folder_get(folder_id),
|
||||
self.store.sync_folder_get(folder_id),
|
||||
Ok(Some(f)) if f.pending_mode.as_deref() == Some("ondemand")
|
||||
)
|
||||
}
|
||||
@@ -452,12 +459,12 @@ impl Syncer {
|
||||
) -> Result<Outcome, PassAbort> {
|
||||
// This pass uploads without walking Drive, so a walk saved by an
|
||||
// earlier pass would not know what it sent; see `do_reconcile`.
|
||||
self.db
|
||||
self.store
|
||||
.sync_walk_clear(folder_id)
|
||||
.map_err(|e| format!("drop the saved walk: {e:?}"))?;
|
||||
let step = Instant::now();
|
||||
let baseline = self
|
||||
.db
|
||||
.store
|
||||
.sync_entries(folder_id)
|
||||
.map_err(|e| format!("load baseline: {e:?}"))?;
|
||||
self.trace_phase(Phase::Baseline, step.elapsed());
|
||||
@@ -720,7 +727,7 @@ impl Syncer {
|
||||
parent = parent_rel(parent);
|
||||
}
|
||||
if parent.is_empty() {
|
||||
let _ = self.db.sync_entries_remove_subtree(folder_id, rel);
|
||||
let _ = self.store.sync_entries_remove_subtree(folder_id, rel);
|
||||
forgotten.insert(rel);
|
||||
}
|
||||
}
|
||||
@@ -732,11 +739,11 @@ impl Syncer {
|
||||
.iter()
|
||||
.any(|dir| rel.starts_with(&format!("{dir}/")))
|
||||
{
|
||||
let _ = self.db.sync_entry_remove(folder_id, rel);
|
||||
let _ = self.store.sync_entry_remove(folder_id, rel);
|
||||
continue;
|
||||
}
|
||||
let Some(uid) = baseline[rel].remote_uid.as_deref().and_then(parse_uid) else {
|
||||
let _ = self.db.sync_entry_remove(folder_id, rel);
|
||||
let _ = self.store.sync_entry_remove(folder_id, rel);
|
||||
continue;
|
||||
};
|
||||
if let Err(e) = self
|
||||
@@ -753,7 +760,7 @@ impl Syncer {
|
||||
if let Some(parent) = parent_uid_of(rel, &remote_dirs, &baseline) {
|
||||
self.invalidate_children_of(&parent);
|
||||
}
|
||||
let _ = self.db.sync_entry_remove(folder_id, rel);
|
||||
let _ = self.store.sync_entry_remove(folder_id, rel);
|
||||
self.log_activity(
|
||||
ActivityKind::Trash,
|
||||
base_name(rel),
|
||||
@@ -786,7 +793,7 @@ impl Syncer {
|
||||
// discover the real figure only by finishing.
|
||||
let step = Instant::now();
|
||||
let baseline = self
|
||||
.db
|
||||
.store
|
||||
.sync_entries(folder_id)
|
||||
.map_err(|e| format!("load baseline: {e:?}"))?;
|
||||
self.trace_phase(Phase::Baseline, step.elapsed());
|
||||
@@ -939,7 +946,7 @@ impl Syncer {
|
||||
delete_remote_dirs.push((rel.clone(), remote[rel].uid.clone()));
|
||||
}
|
||||
(false, false) => {
|
||||
let _ = self.db.sync_entry_remove(folder_id, rel);
|
||||
let _ = self.store.sync_entry_remove(folder_id, rel);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
@@ -958,7 +965,7 @@ impl Syncer {
|
||||
remote_revision_id: Some(revision.clone()),
|
||||
..base.clone()
|
||||
};
|
||||
if let Err(e) = self.db.sync_entry_upsert(folder_id, &row) {
|
||||
if let Err(e) = self.store.sync_entry_upsert(folder_id, &row) {
|
||||
debug!(rel, error = ?e, "sync: cannot record the revision id");
|
||||
}
|
||||
}
|
||||
@@ -1047,7 +1054,7 @@ impl Syncer {
|
||||
outcome.failed(&format!("{rel}: {e}"));
|
||||
continue;
|
||||
}
|
||||
let _ = self.db.sync_entry_remove(folder_id, rel);
|
||||
let _ = self.store.sync_entry_remove(folder_id, rel);
|
||||
self.log_activity(ActivityKind::Trash, base_name(rel), "removed locally", true);
|
||||
outcome.deleted += 1;
|
||||
}
|
||||
@@ -1073,7 +1080,7 @@ impl Syncer {
|
||||
if let Some(parent) = parent_uid_of(rel, &remote_dirs, &baseline) {
|
||||
self.invalidate_children_of(&parent);
|
||||
}
|
||||
let _ = self.db.sync_entry_remove(folder_id, rel);
|
||||
let _ = self.store.sync_entry_remove(folder_id, rel);
|
||||
self.log_activity(
|
||||
ActivityKind::Trash,
|
||||
base_name(rel),
|
||||
@@ -1083,7 +1090,7 @@ impl Syncer {
|
||||
outcome.deleted += 1;
|
||||
}
|
||||
FilePlan::ForgetBaseline => {
|
||||
let _ = self.db.sync_entry_remove(folder_id, rel);
|
||||
let _ = self.store.sync_entry_remove(folder_id, rel);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1103,13 +1110,13 @@ impl Syncer {
|
||||
// creates it on Drive again and uploads what it holds (B211).
|
||||
if !delete_local_dirs.is_empty() {
|
||||
let mut current = self
|
||||
.db
|
||||
.store
|
||||
.sync_entries(folder_id)
|
||||
.map_err(|e| format!("reload baseline: {e:?}"))?;
|
||||
for removal in remove_local_dirs(local_root, delete_local_dirs, &mut current) {
|
||||
match removal {
|
||||
DirRemoval::Removed(rel) => {
|
||||
let _ = self.db.sync_entry_remove(folder_id, &rel);
|
||||
let _ = self.store.sync_entry_remove(folder_id, &rel);
|
||||
self.log_activity(
|
||||
ActivityKind::Trash,
|
||||
base_name(&rel),
|
||||
@@ -1123,7 +1130,7 @@ impl Syncer {
|
||||
rel,
|
||||
reason, "sync: deleted on Drive, but holds unsynced data; keeping it"
|
||||
);
|
||||
let _ = self.db.sync_entry_remove(folder_id, &rel);
|
||||
let _ = self.store.sync_entry_remove(folder_id, &rel);
|
||||
self.log_activity(
|
||||
ActivityKind::Trash,
|
||||
base_name(&rel),
|
||||
@@ -1177,7 +1184,7 @@ impl Syncer {
|
||||
if let Some(parent) = parent_uid_of(&rel, &remote_dirs, &baseline) {
|
||||
self.invalidate_children_of(&parent);
|
||||
}
|
||||
let _ = self.db.sync_entry_remove(folder_id, &rel);
|
||||
let _ = self.store.sync_entry_remove(folder_id, &rel);
|
||||
self.log_activity(
|
||||
ActivityKind::Trash,
|
||||
base_name(&rel),
|
||||
@@ -1396,7 +1403,7 @@ impl Syncer {
|
||||
// A walk that cannot be saved still runs; it just starts over if
|
||||
// it is cut short.
|
||||
if let Err(e) =
|
||||
self.db
|
||||
self.store
|
||||
.sync_walk_record(folder_id, &prefix, listing.short, &saved, &removed)
|
||||
{
|
||||
debug!(folder = prefix, error = ?e, "sync: cannot save the walk's progress");
|
||||
@@ -1423,12 +1430,12 @@ impl Syncer {
|
||||
again: &[String],
|
||||
) -> pdfs_core::Result<()> {
|
||||
if !again.is_empty() {
|
||||
self.db.sync_remote_mark(folder_id, again)?;
|
||||
self.store.sync_remote_mark(folder_id, again)?;
|
||||
}
|
||||
match dirty_upto {
|
||||
Some(seq) => self.db.sync_remote_dirty_consume(folder_id, seq),
|
||||
Some(seq) => self.store.sync_remote_dirty_consume(folder_id, seq),
|
||||
None => {
|
||||
if !self.db.sync_walk_complete(folder_id)? {
|
||||
if !self.store.sync_walk_complete(folder_id)? {
|
||||
debug!(
|
||||
id = folder_id,
|
||||
"sync: the walk of Drive was dropped before its end"
|
||||
@@ -1448,7 +1455,7 @@ impl Syncer {
|
||||
/// - Otherwise a new walk starts at the root.
|
||||
fn start_walk(&self, folder_id: i64, root: &NodeUid, walk: &mut RemoteWalk<'_>) -> WalkStart {
|
||||
let root_uid = root.to_string();
|
||||
let saved = match self.db.sync_walk_load(folder_id) {
|
||||
let saved = match self.store.sync_walk_load(folder_id) {
|
||||
Ok(saved) => saved,
|
||||
Err(e) => {
|
||||
warn!(id = folder_id, error = ?e, "sync: cannot read the saved walk; starting over");
|
||||
@@ -1490,7 +1497,7 @@ impl Syncer {
|
||||
walk.dirs.retain(|rel, _| rel.is_empty());
|
||||
*walk.gaps = RemoteGaps::default();
|
||||
}
|
||||
if let Err(e) = self.db.sync_walk_begin(folder_id, &root_uid, now_secs()) {
|
||||
if let Err(e) = self.store.sync_walk_begin(folder_id, &root_uid, now_secs()) {
|
||||
debug!(id = folder_id, error = ?e, "sync: cannot save the walk's progress");
|
||||
}
|
||||
WalkStart {
|
||||
@@ -1512,7 +1519,7 @@ impl Syncer {
|
||||
saved: &SavedWalk,
|
||||
walk: &mut RemoteWalk<'_>,
|
||||
) -> Option<WalkStart> {
|
||||
let dirty = match self.db.sync_remote_dirty(folder_id) {
|
||||
let dirty = match self.store.sync_remote_dirty(folder_id) {
|
||||
Ok(dirty) => dirty,
|
||||
Err(e) => {
|
||||
warn!(id = folder_id, error = ?e, "sync: cannot read what changed on Drive");
|
||||
@@ -1752,7 +1759,7 @@ impl Syncer {
|
||||
if rows.is_empty() {
|
||||
return;
|
||||
}
|
||||
match self.db.sync_entries_set_revision(folder_id, &rows) {
|
||||
match self.store.sync_entries_set_revision(folder_id, &rows) {
|
||||
Ok(n) => self.trace_count(Count::Revisions, n),
|
||||
Err(e) => debug!(folder = prefix, error = ?e, "sync: cannot record revision ids"),
|
||||
}
|
||||
@@ -1760,7 +1767,7 @@ impl Syncer {
|
||||
|
||||
/// Record a folder's baseline row (folders carry no content signature).
|
||||
fn baseline_dir(&self, folder_id: i64, rel: &str, uid: &NodeUid) -> Result<(), String> {
|
||||
self.db
|
||||
self.store
|
||||
.sync_entry_upsert(folder_id, &dir_row(rel, uid))
|
||||
.map_err(|e| format!("baseline dir {rel}: {e:?}"))
|
||||
}
|
||||
@@ -1946,7 +1953,7 @@ impl Syncer {
|
||||
.take_remote_keeping_local(folder_id, local_root, rel, uid, remote)
|
||||
.await;
|
||||
}
|
||||
self.db
|
||||
self.store
|
||||
.sync_entry_upsert(
|
||||
folder_id,
|
||||
&StoredSyncEntry {
|
||||
@@ -2169,13 +2176,7 @@ impl Syncer {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("mkdir for {rel}: {e}"))?;
|
||||
}
|
||||
let tmp = path.with_extension(format!(
|
||||
"pdfs-tmp-{}",
|
||||
SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0)
|
||||
));
|
||||
let tmp = staging_path(&path);
|
||||
// A file an on-demand mount already read, say one just moved here from
|
||||
// it, is in the content cache under the same revision key.
|
||||
let seeded = size > 0 && self.cache.copy_cached_to(uid, mtime, size as u64, &tmp);
|
||||
@@ -2212,28 +2213,7 @@ impl Syncer {
|
||||
out.flush().map_err(|e| format!("flush tmp {rel}: {e}"))?;
|
||||
out.sync_all().map_err(|e| format!("sync tmp {rel}: {e}"))?;
|
||||
}
|
||||
// The last moment at which the destination can still be saved. Anything
|
||||
// other than the state planning classified means a writer got there
|
||||
// first, and its bytes are the ones nothing else has a copy of.
|
||||
if let Err(e) = keep_racing_local_edit(&path, expected_local) {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(format!("set aside racing local edit for {rel}: {e}"));
|
||||
}
|
||||
std::fs::rename(&tmp, &path).map_err(|e| format!("place {rel}: {e}"))?;
|
||||
// Match local mtime to the remote's so neither side looks "changed" next pass.
|
||||
let f = std::fs::File::options()
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.map_err(|e| format!("open placed file {rel}: {e}"))?;
|
||||
f.set_modified(SystemTime::UNIX_EPOCH + Duration::from_secs(mtime.max(0) as u64))
|
||||
.map_err(|e| format!("set mtime for {rel}: {e}"))?;
|
||||
f.sync_all()
|
||||
.map_err(|e| format!("sync placed file {rel}: {e}"))?;
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::File::open(parent)
|
||||
.and_then(|dir| dir.sync_all())
|
||||
.map_err(|e| format!("sync directory for {rel}: {e}"))?;
|
||||
}
|
||||
place_download(&tmp, &path, expected_local, mtime, rel)?;
|
||||
// Here the file on disk *is* the transferred content: it was published
|
||||
// by a rename and stamped just above, so its stat is the identity.
|
||||
self.record_file_baseline(folder_id, rel, local_sig(&path), uid, seen)
|
||||
@@ -2310,7 +2290,7 @@ impl Syncer {
|
||||
let Some(local) = local else {
|
||||
return Err(format!("stat {rel}: no local identity to baseline"));
|
||||
};
|
||||
self.db
|
||||
self.store
|
||||
.sync_entry_upsert(
|
||||
folder_id,
|
||||
&StoredSyncEntry {
|
||||
@@ -2360,26 +2340,6 @@ impl SentDigest {
|
||||
}
|
||||
}
|
||||
|
||||
/// A local file's identity and content SHA-1, both read from one descriptor,
|
||||
/// or `None` when it is gone. The identity is taken after the hash, so a file
|
||||
/// written to while it was hashed no longer matches the scan's.
|
||||
fn local_sha1(path: &Path) -> std::io::Result<Option<(LocalSig, String)>> {
|
||||
let mut file = match std::fs::File::open(path) {
|
||||
Ok(file) => file,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let digest =
|
||||
pdfs_drive::digest::sha1_of(&mut file).map_err(|e| std::io::Error::other(e.message))?;
|
||||
Ok(Some((LocalSig::from(&file.metadata()?), digest)))
|
||||
}
|
||||
|
||||
/// Open a local file for upload, or `None` when it is gone.
|
||||
///
|
||||
/// A scan plans uploads from a listing, and the file can be deleted before its
|
||||
/// upload starts — a build or a test tree cleaned up mid-pass. That is not a
|
||||
/// failure: the next pass sees the deletion. Counting it as one put the folder
|
||||
/// in `error` for a file nobody wanted any more (B108).
|
||||
/// The `(rel_path, revision_id)` pairs [`Core::record_revisions`] stores for
|
||||
/// one listing: files whose size was read for real and matches the baseline.
|
||||
fn revisions_to_record(
|
||||
@@ -2401,122 +2361,6 @@ fn revisions_to_record(
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn open_to_upload(path: &Path, rel: &str) -> Result<Option<std::fs::File>, String> {
|
||||
match std::fs::File::open(path) {
|
||||
Ok(file) => Ok(Some(file)),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
debug!(rel, "sync: file deleted before its upload; skipping");
|
||||
Ok(None)
|
||||
}
|
||||
Err(e) => Err(format!("open {rel}: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Say so when a file changed under an upload that was streaming it.
|
||||
///
|
||||
/// Purely diagnostic — the correction is already in place, because the baseline
|
||||
/// records the identity the upload *read* rather than the one on disk now, so
|
||||
/// the next pass classifies the path as locally changed and replaces the torn
|
||||
/// revision. Without the log there is nothing in the journal to explain the
|
||||
/// extra revision (`docs/BUGS.md` B40).
|
||||
fn warn_if_torn(rel: &str, path: &Path, streamed: LocalSig) {
|
||||
let now = local_sig(path);
|
||||
if !now.is_some_and(|now| now.same_content(&streamed)) {
|
||||
warn!(
|
||||
rel,
|
||||
?streamed,
|
||||
?now,
|
||||
"sync: file changed while uploading; the remote revision may be torn \
|
||||
and will be replaced on the next pass"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The identity a reconcile pass uses to recognise a local file it has already
|
||||
/// looked at: `None` when nothing is at the path.
|
||||
fn local_sig(path: &Path) -> Option<LocalSig> {
|
||||
std::fs::metadata(path).ok().map(|m| LocalSig {
|
||||
mtime: system_mtime(&m),
|
||||
mtime_ns: system_mtime_ns(&m),
|
||||
size: m.len() as i64,
|
||||
})
|
||||
}
|
||||
|
||||
/// Guard the destination of a download: if what is at `path` is no longer what
|
||||
/// planning classified, move it aside as a conflict copy before the caller
|
||||
/// renames over it.
|
||||
///
|
||||
/// A reconcile pass decides what to do from a walk that finished before the
|
||||
/// transfer started, and a download of a large file can run for minutes. Without
|
||||
/// this, a local edit completed inside that window was replaced by the remote
|
||||
/// version with no copy of it kept anywhere — the one shape of loss a sync
|
||||
/// engine must not have (`docs/BUGS.md` B39). Keeping the copy makes it re-upload as a
|
||||
/// new file on the next pass, which is the same resolution a both-sides-changed
|
||||
/// conflict already gets.
|
||||
///
|
||||
/// A path that is empty when it was expected to be is not a conflict: the
|
||||
/// download is about to recreate it, and there is nothing to preserve.
|
||||
fn keep_racing_local_edit(path: &Path, expected: Option<LocalSig>) -> std::io::Result<()> {
|
||||
let actual = local_sig(path);
|
||||
let unchanged = match (actual, expected) {
|
||||
(Some(a), Some(e)) => a.same_content(&e),
|
||||
// Nothing there: the download is about to create it, and there is
|
||||
// nothing to preserve either way.
|
||||
(None, _) => true,
|
||||
(Some(_), None) => false,
|
||||
};
|
||||
if unchanged {
|
||||
return Ok(());
|
||||
}
|
||||
warn!(
|
||||
path = %path.display(),
|
||||
?expected,
|
||||
?actual,
|
||||
"sync: local file changed while downloading; keeping it as a conflict copy"
|
||||
);
|
||||
preserve_conflict_copy(path, now_secs()).map(|_| ())
|
||||
}
|
||||
|
||||
/// What became of one folder [`remove_local_dirs`] was asked to remove.
|
||||
enum DirRemoval {
|
||||
Removed(String),
|
||||
/// Left in place, with why: it holds something Drive does not have.
|
||||
Kept(String, String),
|
||||
Failed(String, std::io::Error),
|
||||
}
|
||||
|
||||
/// Remove the mirror folders in `dirs`, which Drive deleted, deepest first,
|
||||
/// except those that hold something Drive never had.
|
||||
///
|
||||
/// The uploads of a new file or an edit in such a folder failed earlier in the
|
||||
/// pass for want of a parent, and an ignored `.git` is never uploaded at all,
|
||||
/// so removing the folder would lose them for good (B211). `current` is the
|
||||
/// baseline as the pass has left it: a row the pass already removed with its
|
||||
/// file must not read as a deletion not carried up yet, and a subfolder removed
|
||||
/// here takes its rows with it for the same reason. A kept folder loses its own
|
||||
/// row, so its parent sees it as new and is kept too.
|
||||
fn remove_local_dirs(
|
||||
root: &Path,
|
||||
mut dirs: Vec<String>,
|
||||
current: &mut HashMap<String, StoredSyncEntry>,
|
||||
) -> Vec<DirRemoval> {
|
||||
dirs.sort_by_key(|p| std::cmp::Reverse(p.matches('/').count()));
|
||||
dirs.into_iter()
|
||||
.map(|rel| {
|
||||
if let Some(reason) = mirror_subtree_unsynced(root, &rel, current) {
|
||||
current.remove(&rel);
|
||||
return DirRemoval::Kept(rel, reason);
|
||||
}
|
||||
let prefix = format!("{rel}/");
|
||||
current.retain(|path, _| *path != rel && !path.starts_with(&prefix));
|
||||
match removed_locally(std::fs::remove_dir_all(root.join(rel_to_path(&rel)))) {
|
||||
Ok(()) => DirRemoval::Removed(rel),
|
||||
Err(e) => DirRemoval::Failed(rel, e),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What one folder's listing on Drive held.
|
||||
#[derive(Default)]
|
||||
struct Listing {
|
||||
@@ -2699,367 +2543,6 @@ fn unlisted_gap<T>(
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the file at `path` is no longer what the scan saw as `planned`.
|
||||
/// A file that is gone has nothing left to lose, so it has not changed.
|
||||
fn changed_since_scan(path: &Path, planned: &LocalItem) -> bool {
|
||||
local_sig(path).is_some_and(|now| !now.same_content(&LocalSig::from(planned)))
|
||||
}
|
||||
|
||||
/// Read a local removal as the sync engine has to read it: the *state* it was
|
||||
/// asking for is "this path is gone", so a path that was already gone is a
|
||||
/// success, not a failure.
|
||||
///
|
||||
/// It matters because the baseline is only dropped on success. Treating
|
||||
/// `NotFound` as an error left the baseline in place for a file that no longer
|
||||
/// exists, so the same removal was re-attempted and re-reported as an error on
|
||||
/// every pass, forever. Every other error is still an error, and keeping the
|
||||
/// baseline is exactly right there: the surviving file must not be mistaken for
|
||||
/// a new local creation on the next pass and uploaded back (`docs/BUGS.md` B42).
|
||||
fn removed_locally(result: std::io::Result<()>) -> std::io::Result<()> {
|
||||
match result {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// The body of [`Core::walk_local`], without a `Core`: recursively collect the
|
||||
/// local tree under `root` into `out`, reporting each entry to `scanned`.
|
||||
///
|
||||
/// **A path the scan cannot read is left out and recorded in `unscanned`, never
|
||||
/// silently dropped.** Every pass drops what `unscanned` covers from
|
||||
/// classification, so a baseline row under it is neither a local deletion nor a
|
||||
/// download target (`docs/BUGS.md` B55). That covers a subfolder the pass has no
|
||||
/// permission for, an entry that vanished between the listing and its `stat`,
|
||||
/// and a name that is not UTF-8. Failing the whole pass on any of them, as this
|
||||
/// did before, left one root-owned folder stopping everything else in the tree
|
||||
/// from syncing, on every pass, for good (B196).
|
||||
///
|
||||
/// The root is the exception, and so is any other I/O error: an absent or
|
||||
/// unreadable root fails the pass, since leaving the root out would leave
|
||||
/// nothing in, and an error this cannot name a cause for is not one to guess
|
||||
/// about.
|
||||
///
|
||||
/// Split out from the method so exactly that can be tested against a real tree
|
||||
/// with a real unreadable directory in it, which needs no `Core` at all.
|
||||
fn walk_local_tree(
|
||||
root: &Path,
|
||||
rules: &IgnoreRules,
|
||||
writing: &HashSet<PathBuf>,
|
||||
out: &mut HashMap<String, LocalItem>,
|
||||
unscanned: &mut Unscanned,
|
||||
scanned: &mut dyn FnMut(&str),
|
||||
) -> Result<(), String> {
|
||||
walk_local_dir(root, root, rules, writing, out, unscanned, scanned).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Why [`walk_local_dir`] could not finish a folder.
|
||||
enum ScanError {
|
||||
/// An I/O error on `what`, which the caller may leave out of the pass.
|
||||
Io { what: String, error: std::io::Error },
|
||||
/// Anything else, which fails the pass.
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ScanError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ScanError::Io { what, error } => write!(f, "{what}: {error}"),
|
||||
ScanError::Failed(message) => f.write_str(message),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Leave `rel` out of the pass for `failure`, or hand it back when it is one
|
||||
/// that fails the pass. Permission denied is reported to the user; an entry
|
||||
/// that vanished mid-scan is not, since the next pass sees it settled.
|
||||
fn leave_out(rel: &str, failure: ScanError, unscanned: &mut Unscanned) -> Result<(), ScanError> {
|
||||
let ScanError::Io { what, error } = &failure else {
|
||||
return Err(failure);
|
||||
};
|
||||
match error.kind() {
|
||||
std::io::ErrorKind::PermissionDenied => {
|
||||
warn!(%what, %error, "sync: cannot read; leaving it out of the pass");
|
||||
unscanned.unreadable(rel.to_string(), &error.to_string());
|
||||
Ok(())
|
||||
}
|
||||
std::io::ErrorKind::NotFound => {
|
||||
debug!(%what, "sync: gone mid-scan; leaving it out of the pass");
|
||||
unscanned.vanished(rel.to_string());
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(failure),
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_local_dir(
|
||||
root: &Path,
|
||||
dir: &Path,
|
||||
rules: &IgnoreRules,
|
||||
writing: &HashSet<PathBuf>,
|
||||
out: &mut HashMap<String, LocalItem>,
|
||||
unscanned: &mut Unscanned,
|
||||
scanned: &mut dyn FnMut(&str),
|
||||
) -> Result<(), ScanError> {
|
||||
let io = |what: String| move |error| ScanError::Io { what, error };
|
||||
let entries = std::fs::read_dir(dir).map_err(io(format!("read {}", dir.display())))?;
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(io(format!("read entry in {}", dir.display())))?;
|
||||
let path = entry.path();
|
||||
let stripped = path.strip_prefix(root).map_err(|e| {
|
||||
ScanError::Failed(format!(
|
||||
"local path {} escaped sync root {}: {e}",
|
||||
path.display(),
|
||||
root.display()
|
||||
))
|
||||
})?;
|
||||
let Some(rel) = stripped.to_str() else {
|
||||
// Nothing can be keyed by this name: not the baseline, which only
|
||||
// ever held paths this scan produced, and not Drive, whose names are
|
||||
// UTF-8. Leaving it out cannot read as a deletion of anything.
|
||||
warn!(path = %path.display(), "sync: name is not valid UTF-8; leaving it out of the pass");
|
||||
unscanned.unreadable(
|
||||
stripped.to_string_lossy().into_owned(),
|
||||
"name is not valid UTF-8",
|
||||
);
|
||||
continue;
|
||||
};
|
||||
// Ignore our own in-flight download temp files.
|
||||
if rel.contains(".pdfs-tmp-") {
|
||||
continue;
|
||||
}
|
||||
let meta = match std::fs::symlink_metadata(&path) {
|
||||
Ok(meta) => meta,
|
||||
// Gone since the listing, or in a folder that lists but does not
|
||||
// allow `stat`. Either way this pass cannot say what it is.
|
||||
Err(error) => {
|
||||
let what = format!("stat {}", path.display());
|
||||
leave_out(rel, ScanError::Io { what, error }, unscanned)?;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// Ignored paths are dropped here as well as from the classification
|
||||
// union — not for correctness (the union filter is what makes this
|
||||
// safe) but so an ignored `node_modules/` is never descended into or
|
||||
// counted against scan progress.
|
||||
if rules.is_ignored(rel, meta.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
if meta.is_dir() {
|
||||
out.insert(
|
||||
rel.to_string(),
|
||||
LocalItem {
|
||||
is_dir: true,
|
||||
mtime: 0,
|
||||
mtime_ns: None,
|
||||
size: 0,
|
||||
open_for_write: false,
|
||||
},
|
||||
);
|
||||
scanned(rel);
|
||||
if let Err(failure) =
|
||||
walk_local_dir(root, &path, rules, writing, out, unscanned, scanned)
|
||||
{
|
||||
leave_out(rel, failure, unscanned)?;
|
||||
// What the folder did list before failing goes with it: a
|
||||
// half-read folder is as unknown as an unread one.
|
||||
let prefix = format!("{rel}/");
|
||||
out.retain(|k, _| k != rel && !k.starts_with(&prefix));
|
||||
}
|
||||
} else if meta.is_file() {
|
||||
// Check whether any process holds this file open for writing.
|
||||
// The canonical path is used because /proc/*/fd links resolve
|
||||
// to canonical targets.
|
||||
let ofw = std::fs::canonicalize(&path)
|
||||
.map(|canon| writing.contains(&canon))
|
||||
.unwrap_or(false);
|
||||
out.insert(
|
||||
rel.to_string(),
|
||||
LocalItem {
|
||||
is_dir: false,
|
||||
mtime: system_mtime(&meta),
|
||||
mtime_ns: system_mtime_ns(&meta),
|
||||
size: meta.len() as i64,
|
||||
open_for_write: ofw,
|
||||
},
|
||||
);
|
||||
scanned(rel);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Why the mirror copy at `rel` holds something Proton Drive does not, or
|
||||
/// `None` when everything under it is on Drive exactly as it is on disk.
|
||||
///
|
||||
/// A move out of a mirror folder removes the local copy once Drive has moved
|
||||
/// the node, so anything only this disk has would be lost with it: a file not
|
||||
/// uploaded yet, one edited since, a deletion not carried up yet, or anything
|
||||
/// the engine never uploads. That is why ignored names count here, and why the
|
||||
/// walk is its own rather than [`walk_local_tree`], which skips symlinks.
|
||||
pub fn mirror_subtree_unsynced(
|
||||
root: &Path,
|
||||
rel: &str,
|
||||
baseline: &HashMap<String, StoredSyncEntry>,
|
||||
) -> Option<String> {
|
||||
let mut seen = HashSet::new();
|
||||
if let Some(reason) = unsynced_local(root, rel, baseline, None, &mut seen) {
|
||||
return Some(reason);
|
||||
}
|
||||
let prefix = format!("{rel}/");
|
||||
baseline
|
||||
.keys()
|
||||
.filter(|r| *r == rel || r.starts_with(&prefix))
|
||||
.find(|r| !seen.contains(r.as_str()))
|
||||
.map(|r| format!("{r} was deleted here but not on Proton Drive yet"))
|
||||
}
|
||||
|
||||
/// [`mirror_subtree_unsynced`] for a whole mirror folder: why its local copy
|
||||
/// holds something Proton Drive does not, or `None` when evicting it loses
|
||||
/// nothing. The switch to on-demand asks this before it empties the folder.
|
||||
///
|
||||
/// A push pass that ends `idle` is not enough on its own. It never uploads an
|
||||
/// ignored path, a symlink or a folder it cannot read, it defers a file open
|
||||
/// for writing, and a file can change after it finishes; the eviction deleted
|
||||
/// all of those for good (B198).
|
||||
///
|
||||
/// A tracked path deleted here but still in the baseline counts, since the
|
||||
/// mount would show it again. An ignored one does not: ignoring never carries
|
||||
/// a deletion to Drive, so its row stays in the baseline for good, and holding
|
||||
/// the switch on it would hold it forever.
|
||||
pub fn mirror_tree_unsynced(
|
||||
root: &Path,
|
||||
baseline: &HashMap<String, StoredSyncEntry>,
|
||||
rules: &IgnoreRules,
|
||||
) -> Option<String> {
|
||||
let mut seen = HashSet::new();
|
||||
if let Some(reason) = unsynced_local(root, "", baseline, Some(rules), &mut seen) {
|
||||
return Some(reason);
|
||||
}
|
||||
let mut missing: Vec<String> = filter_baseline(baseline, rules)
|
||||
.into_keys()
|
||||
.filter(|r| !seen.contains(r.as_str()))
|
||||
.collect();
|
||||
missing.sort_unstable();
|
||||
missing
|
||||
.first()
|
||||
.map(|r| format!("{r} was deleted here but not on Proton Drive yet"))
|
||||
}
|
||||
|
||||
/// Whether a mirror folder's local copy is gone in full: the folder is still
|
||||
/// there, but not one tracked path of its baseline is.
|
||||
///
|
||||
/// [`mirror_tree_unsynced`] reads that as deletions not carried up yet, which
|
||||
/// would refuse the switch to on-demand for good. It is the wipe guard's case
|
||||
/// instead, which the push pass a queued switch runs settles without trashing
|
||||
/// anything on Drive (#46), so the switch waits for that pass.
|
||||
pub fn mirror_tree_gone(
|
||||
root: &Path,
|
||||
baseline: &HashMap<String, StoredSyncEntry>,
|
||||
rules: &IgnoreRules,
|
||||
) -> bool {
|
||||
let tracked = filter_baseline(baseline, rules);
|
||||
root.is_dir()
|
||||
&& !tracked.is_empty()
|
||||
&& tracked.keys().all(|rel| {
|
||||
std::fs::symlink_metadata(root.join(rel_to_path(rel)))
|
||||
.is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound)
|
||||
})
|
||||
}
|
||||
|
||||
/// The walk behind both checks. `rules`, when given, only names an ignored
|
||||
/// path as such in the reason; it is still something only this disk has.
|
||||
fn unsynced_local(
|
||||
root: &Path,
|
||||
rel: &str,
|
||||
baseline: &HashMap<String, StoredSyncEntry>,
|
||||
rules: Option<&IgnoreRules>,
|
||||
seen: &mut HashSet<String>,
|
||||
) -> Option<String> {
|
||||
let path = if rel.is_empty() {
|
||||
root.to_path_buf()
|
||||
} else {
|
||||
root.join(rel_to_path(rel))
|
||||
};
|
||||
// The folder itself has no baseline row; only what is in it does.
|
||||
if !rel.is_empty() {
|
||||
let meta = match std::fs::symlink_metadata(&path) {
|
||||
Ok(meta) => meta,
|
||||
Err(e) => return Some(format!("cannot read {rel}: {e}")),
|
||||
};
|
||||
let Some(base) = baseline.get(rel) else {
|
||||
if rules.is_some_and(|rules| rules.is_ignored(rel, meta.is_dir())) {
|
||||
return Some(format!(
|
||||
"{rel} is excluded from sync, so it is only on this computer"
|
||||
));
|
||||
}
|
||||
return Some(format!("{rel} is not on Proton Drive yet"));
|
||||
};
|
||||
seen.insert(rel.to_string());
|
||||
if meta.is_file() {
|
||||
return (!LocalSig::from(&meta).same_content(&LocalSig::from(base)))
|
||||
.then(|| format!("{rel} has changes that are not on Proton Drive yet"));
|
||||
}
|
||||
if !meta.is_dir() {
|
||||
return Some(format!("{rel} is not a regular file or folder"));
|
||||
}
|
||||
}
|
||||
let shown = if rel.is_empty() { "the folder" } else { rel };
|
||||
let entries = match std::fs::read_dir(&path) {
|
||||
Ok(entries) => entries,
|
||||
Err(e) => return Some(format!("cannot read {shown}: {e}")),
|
||||
};
|
||||
for entry in entries {
|
||||
let name = match entry {
|
||||
Ok(entry) => entry.file_name(),
|
||||
Err(e) => return Some(format!("cannot read {shown}: {e}")),
|
||||
};
|
||||
let Some(name) = name.to_str() else {
|
||||
return Some(format!("{shown} holds a name that is not valid UTF-8"));
|
||||
};
|
||||
// A download the engine left half done; it is the engine's to clean up.
|
||||
if name.contains(".pdfs-tmp-") {
|
||||
continue;
|
||||
}
|
||||
if let Some(reason) = unsynced_local(root, &join_rel(rel, name), baseline, rules, seen) {
|
||||
return Some(reason);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Publish a conflict copy without overwriting an earlier conflict bearing the
|
||||
/// same timestamp. The original is removed only after the new copy is durable.
|
||||
fn preserve_conflict_copy(path: &Path, stamp: i64) -> std::io::Result<PathBuf> {
|
||||
let metadata = std::fs::metadata(path)?;
|
||||
for suffix in 0..=u32::MAX {
|
||||
let conflict = conflict_path_with_suffix(path, stamp, suffix);
|
||||
let mut source = std::fs::File::open(path)?;
|
||||
let mut target = match std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&conflict)
|
||||
{
|
||||
Ok(file) => file,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if let Err(e) = std::io::copy(&mut source, &mut target).and_then(|_| target.sync_all()) {
|
||||
let _ = std::fs::remove_file(&conflict);
|
||||
return Err(e);
|
||||
}
|
||||
target.set_permissions(metadata.permissions())?;
|
||||
if let Ok(modified) = metadata.modified() {
|
||||
target.set_modified(modified)?;
|
||||
}
|
||||
target.sync_all()?;
|
||||
sync_parent_dir(&conflict)?;
|
||||
std::fs::remove_file(path)?;
|
||||
sync_parent_dir(&conflict)?;
|
||||
return Ok(conflict);
|
||||
}
|
||||
unreachable!("u32 conflict suffix space exhausted")
|
||||
}
|
||||
|
||||
/// The remote uid of `rel`'s parent folder: from the pass's folder-uid map
|
||||
/// first, and from the baseline second for a parent the map never covered.
|
||||
///
|
||||
@@ -3080,13 +2563,6 @@ fn parent_uid_of(
|
||||
})
|
||||
}
|
||||
|
||||
fn sync_parent_dir(path: &Path) -> std::io::Result<()> {
|
||||
match path.parent() {
|
||||
Some(parent) => std::fs::File::open(parent)?.sync_all(),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- helpers --------------------------------------------------------------
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -4469,8 +3945,8 @@ mod tests {
|
||||
}
|
||||
|
||||
fn sync_test_dir(label: &str) -> PathBuf {
|
||||
let nonce = SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
let nonce = std::time::SystemTime::now()
|
||||
.duration_since(std::time::SystemTime::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let path =
|
||||
|
||||
@@ -49,22 +49,6 @@ pub enum SyncMsg {
|
||||
Stop,
|
||||
}
|
||||
|
||||
/// Start the sync engine: a control thread that owns the filesystem watcher and
|
||||
/// serialises reconcile passes, plus a periodic poll thread. The engine receives
|
||||
/// on `rx`; senders live in [`SyncParts::tx`].
|
||||
pub fn spawn(core: Syncer, rx: Receiver<SyncMsg>) -> Option<std::thread::JoinHandle<()>> {
|
||||
match std::thread::Builder::new()
|
||||
.name("pdfs-sync".into())
|
||||
.spawn(move || engine_loop(core, rx))
|
||||
{
|
||||
Ok(handle) => Some(handle),
|
||||
Err(e) => {
|
||||
warn!(error = %e, "failed to start sync engine");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the engine is alive and which pass it is on, for
|
||||
/// [`Core::diagnostics`] and the supervisor.
|
||||
///
|
||||
@@ -213,7 +197,7 @@ fn run_pass(core: &Syncer, folder: &StoredSyncFolder) {
|
||||
}
|
||||
core.progress_end(folder.id);
|
||||
let _ = core
|
||||
.db
|
||||
.store
|
||||
.sync_folder_set_state(folder.id, "error", folder.last_sync);
|
||||
error!(
|
||||
id = folder.id,
|
||||
@@ -231,21 +215,24 @@ fn run_pass(core: &Syncer, folder: &StoredSyncFolder) {
|
||||
/// The pass a `Reconcile(id)` asked for. A folder removed since, or one the
|
||||
/// database cannot read, is said so rather than dropped in silence.
|
||||
fn run_pass_by_id(core: &Syncer, id: i64) {
|
||||
match core.db.sync_folder_get(id) {
|
||||
match core.store.sync_folder_get(id) {
|
||||
Ok(Some(folder)) => run_pass(core, &folder),
|
||||
Ok(None) => debug!(id, "sync: folder removed before its pass; skipping"),
|
||||
Err(e) => warn!(id, error = ?e, "sync: cannot read folder; skipping its pass"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The engine control loop. Single-threaded so reconcile passes never overlap.
|
||||
fn engine_loop(core: Syncer, rx: Receiver<SyncMsg>) {
|
||||
/// The sync engine, run on the daemon's `pdfs-sync` thread: it owns the
|
||||
/// filesystem watcher and serialises reconcile passes, and starts the periodic
|
||||
/// poll thread. It receives on `rx`; senders live in [`SyncParts::tx`]. Passes
|
||||
/// never overlap. Returns on [`SyncMsg::Stop`] or when the channel closes.
|
||||
pub fn run(core: Syncer, rx: Receiver<SyncMsg>) {
|
||||
let health = core.engine.clone();
|
||||
let _running = Running::start(&health);
|
||||
// No pass runs before this thread starts one, so a folder in `syncing` was
|
||||
// left there by a daemon that was killed mid-pass. It would read as busy
|
||||
// until its next pass ends, which on a large folder is hours away.
|
||||
match core.db.sync_folders_reset_syncing() {
|
||||
match core.store.sync_folders_reset_syncing() {
|
||||
Ok(0) => {}
|
||||
Ok(n) => info!(
|
||||
folders = n,
|
||||
@@ -377,7 +364,7 @@ fn run_burst(core: &Syncer, ids: &HashSet<i64>, all: bool) {
|
||||
return;
|
||||
}
|
||||
let folders = if all {
|
||||
match core.db.sync_folder_list() {
|
||||
match core.store.sync_folder_list() {
|
||||
Ok(folders) => folders,
|
||||
Err(e) => {
|
||||
warn!(error = ?e, "sync: cannot list folders");
|
||||
@@ -389,7 +376,7 @@ fn run_burst(core: &Syncer, ids: &HashSet<i64>, all: bool) {
|
||||
};
|
||||
let listed: Vec<i64> = folders.iter().map(|f| f.id).collect();
|
||||
let listed = if listed.len() > 1 {
|
||||
match core.db.sync_entry_counts() {
|
||||
match core.store.sync_entry_counts() {
|
||||
Ok(counts) => smallest_first(&listed, &counts),
|
||||
Err(e) => {
|
||||
warn!(error = ?e, "sync: cannot count baseline rows; keeping the folder order");
|
||||
@@ -538,7 +525,7 @@ fn rewatch(
|
||||
watcher: &mut notify::RecommendedWatcher,
|
||||
watched: &Mutex<Vec<(PathBuf, i64)>>,
|
||||
) -> bool {
|
||||
let want: Vec<(PathBuf, i64)> = match core.db.sync_folder_list() {
|
||||
let want: Vec<(PathBuf, i64)> = match core.store.sync_folder_list() {
|
||||
Ok(f) => f
|
||||
.into_iter()
|
||||
.filter(|f| f.mode == "mirror")
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! The engine used to be a set of methods on the daemon's `Core`, the struct
|
||||
//! every subsystem shares, so any part of a pass could read or lock anything in the
|
||||
//! daemon. Its own state now lives in [`SyncParts`], next to the handles it
|
||||
//! borrows (the database, Drive, the content cache), and everything else it
|
||||
//! borrows (its tables through [`SyncStore`], Drive, the content cache), and everything else it
|
||||
//! needs from the daemon goes through [`SyncHost`]. A [`Syncer`] is the two
|
||||
//! together: the value the engine's methods run on.
|
||||
//!
|
||||
@@ -24,12 +24,12 @@ use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_core::transfers::TransferRegistry;
|
||||
use pdfs_drive::DriveApi;
|
||||
use pdfs_store::cache::ContentCache;
|
||||
use pdfs_store::db::Db;
|
||||
use proton_drive_rs::Thumbnail;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use tracing::info;
|
||||
|
||||
use super::{EngineHealth, SyncMsg};
|
||||
use crate::store::SyncStore;
|
||||
|
||||
/// What the sync engine needs from the daemon that it does not own.
|
||||
pub trait SyncHost: Send + Sync {
|
||||
@@ -53,7 +53,8 @@ pub trait SyncHost: Send + Sync {
|
||||
/// The sync engine's state, and the daemon handles it uses.
|
||||
#[derive(Clone)]
|
||||
pub struct SyncParts {
|
||||
pub db: Arc<Db>,
|
||||
/// The engine's tables: synced folders, baselines and saved walks.
|
||||
pub store: Arc<dyn SyncStore>,
|
||||
pub drive: Arc<dyn DriveApi>,
|
||||
pub rt: tokio::runtime::Handle,
|
||||
pub cache: Arc<ContentCache>,
|
||||
|
||||
@@ -0,0 +1,583 @@
|
||||
//! The mirror engine's reads and writes of the local disk, in one place.
|
||||
//!
|
||||
//! A pass touches the local tree in a few ways only: it scans it, hashes and
|
||||
//! opens files to upload, places downloads, removes what Drive deleted, and
|
||||
//! sets a racing local edit aside as a conflict copy. Every one of them reads a
|
||||
//! missing, unreadable or changed path the way the engine has to: as a fact to
|
||||
//! report, never as a deletion. Keeping them here, apart from the planning and
|
||||
//! the Drive calls, is the first step towards the `LocalFs` port in
|
||||
//! `docs/ARCHITECTURE.md`.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use pdfs_core::syncignore::IgnoreRules;
|
||||
use pdfs_core::timestamp::now_secs;
|
||||
use pdfs_store::db::StoredSyncEntry;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use super::model::{LocalItem, LocalSig, system_mtime, system_mtime_ns};
|
||||
use super::planner::{
|
||||
Unscanned, conflict_path_with_suffix, filter_baseline, join_rel, rel_to_path,
|
||||
};
|
||||
|
||||
/// A local file's identity and content SHA-1, both read from one descriptor,
|
||||
/// or `None` when it is gone. The identity is taken after the hash, so a file
|
||||
/// written to while it was hashed no longer matches the scan's.
|
||||
pub(super) fn local_sha1(path: &Path) -> std::io::Result<Option<(LocalSig, String)>> {
|
||||
let mut file = match std::fs::File::open(path) {
|
||||
Ok(file) => file,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let digest =
|
||||
pdfs_drive::digest::sha1_of(&mut file).map_err(|e| std::io::Error::other(e.message))?;
|
||||
Ok(Some((LocalSig::from(&file.metadata()?), digest)))
|
||||
}
|
||||
|
||||
/// Open a local file for upload, or `None` when it is gone.
|
||||
///
|
||||
/// A scan plans uploads from a listing, and the file can be deleted before its
|
||||
/// upload starts — a build or a test tree cleaned up mid-pass. That is not a
|
||||
/// failure: the next pass sees the deletion. Counting it as one put the folder
|
||||
/// in `error` for a file nobody wanted any more (B108).
|
||||
pub(super) fn open_to_upload(path: &Path, rel: &str) -> Result<Option<std::fs::File>, String> {
|
||||
match std::fs::File::open(path) {
|
||||
Ok(file) => Ok(Some(file)),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
debug!(rel, "sync: file deleted before its upload; skipping");
|
||||
Ok(None)
|
||||
}
|
||||
Err(e) => Err(format!("open {rel}: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Say so when a file changed under an upload that was streaming it.
|
||||
///
|
||||
/// Purely diagnostic — the correction is already in place, because the baseline
|
||||
/// records the identity the upload *read* rather than the one on disk now, so
|
||||
/// the next pass classifies the path as locally changed and replaces the torn
|
||||
/// revision. Without the log there is nothing in the journal to explain the
|
||||
/// extra revision (`docs/BUGS.md` B40).
|
||||
pub(super) fn warn_if_torn(rel: &str, path: &Path, streamed: LocalSig) {
|
||||
let now = local_sig(path);
|
||||
if !now.is_some_and(|now| now.same_content(&streamed)) {
|
||||
warn!(
|
||||
rel,
|
||||
?streamed,
|
||||
?now,
|
||||
"sync: file changed while uploading; the remote revision may be torn \
|
||||
and will be replaced on the next pass"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The identity a reconcile pass uses to recognise a local file it has already
|
||||
/// looked at: `None` when nothing is at the path.
|
||||
pub(super) fn local_sig(path: &Path) -> Option<LocalSig> {
|
||||
std::fs::metadata(path).ok().map(|m| LocalSig {
|
||||
mtime: system_mtime(&m),
|
||||
mtime_ns: system_mtime_ns(&m),
|
||||
size: m.len() as i64,
|
||||
})
|
||||
}
|
||||
|
||||
/// Guard the destination of a download: if what is at `path` is no longer what
|
||||
/// planning classified, move it aside as a conflict copy before the caller
|
||||
/// renames over it.
|
||||
///
|
||||
/// A reconcile pass decides what to do from a walk that finished before the
|
||||
/// transfer started, and a download of a large file can run for minutes. Without
|
||||
/// this, a local edit completed inside that window was replaced by the remote
|
||||
/// version with no copy of it kept anywhere — the one shape of loss a sync
|
||||
/// engine must not have (`docs/BUGS.md` B39). Keeping the copy makes it re-upload as a
|
||||
/// new file on the next pass, which is the same resolution a both-sides-changed
|
||||
/// conflict already gets.
|
||||
///
|
||||
/// A path that is empty when it was expected to be is not a conflict: the
|
||||
/// download is about to recreate it, and there is nothing to preserve.
|
||||
pub(super) fn keep_racing_local_edit(
|
||||
path: &Path,
|
||||
expected: Option<LocalSig>,
|
||||
) -> std::io::Result<()> {
|
||||
let actual = local_sig(path);
|
||||
let unchanged = match (actual, expected) {
|
||||
(Some(a), Some(e)) => a.same_content(&e),
|
||||
// Nothing there: the download is about to create it, and there is
|
||||
// nothing to preserve either way.
|
||||
(None, _) => true,
|
||||
(Some(_), None) => false,
|
||||
};
|
||||
if unchanged {
|
||||
return Ok(());
|
||||
}
|
||||
warn!(
|
||||
path = %path.display(),
|
||||
?expected,
|
||||
?actual,
|
||||
"sync: local file changed while downloading; keeping it as a conflict copy"
|
||||
);
|
||||
preserve_conflict_copy(path, now_secs()).map(|_| ())
|
||||
}
|
||||
|
||||
/// What became of one folder [`remove_local_dirs`] was asked to remove.
|
||||
pub(super) enum DirRemoval {
|
||||
Removed(String),
|
||||
/// Left in place, with why: it holds something Drive does not have.
|
||||
Kept(String, String),
|
||||
Failed(String, std::io::Error),
|
||||
}
|
||||
|
||||
/// Remove the mirror folders in `dirs`, which Drive deleted, deepest first,
|
||||
/// except those that hold something Drive never had.
|
||||
///
|
||||
/// The uploads of a new file or an edit in such a folder failed earlier in the
|
||||
/// pass for want of a parent, and an ignored `.git` is never uploaded at all,
|
||||
/// so removing the folder would lose them for good (B211). `current` is the
|
||||
/// baseline as the pass has left it: a row the pass already removed with its
|
||||
/// file must not read as a deletion not carried up yet, and a subfolder removed
|
||||
/// here takes its rows with it for the same reason. A kept folder loses its own
|
||||
/// row, so its parent sees it as new and is kept too.
|
||||
pub(super) fn remove_local_dirs(
|
||||
root: &Path,
|
||||
mut dirs: Vec<String>,
|
||||
current: &mut HashMap<String, StoredSyncEntry>,
|
||||
) -> Vec<DirRemoval> {
|
||||
dirs.sort_by_key(|p| std::cmp::Reverse(p.matches('/').count()));
|
||||
dirs.into_iter()
|
||||
.map(|rel| {
|
||||
if let Some(reason) = mirror_subtree_unsynced(root, &rel, current) {
|
||||
current.remove(&rel);
|
||||
return DirRemoval::Kept(rel, reason);
|
||||
}
|
||||
let prefix = format!("{rel}/");
|
||||
current.retain(|path, _| *path != rel && !path.starts_with(&prefix));
|
||||
match removed_locally(std::fs::remove_dir_all(root.join(rel_to_path(&rel)))) {
|
||||
Ok(()) => DirRemoval::Removed(rel),
|
||||
Err(e) => DirRemoval::Failed(rel, e),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether the file at `path` is no longer what the scan saw as `planned`.
|
||||
/// A file that is gone has nothing left to lose, so it has not changed.
|
||||
pub(super) fn changed_since_scan(path: &Path, planned: &LocalItem) -> bool {
|
||||
local_sig(path).is_some_and(|now| !now.same_content(&LocalSig::from(planned)))
|
||||
}
|
||||
|
||||
/// Read a local removal as the sync engine has to read it: the *state* it was
|
||||
/// asking for is "this path is gone", so a path that was already gone is a
|
||||
/// success, not a failure.
|
||||
///
|
||||
/// It matters because the baseline is only dropped on success. Treating
|
||||
/// `NotFound` as an error left the baseline in place for a file that no longer
|
||||
/// exists, so the same removal was re-attempted and re-reported as an error on
|
||||
/// every pass, forever. Every other error is still an error, and keeping the
|
||||
/// baseline is exactly right there: the surviving file must not be mistaken for
|
||||
/// a new local creation on the next pass and uploaded back (`docs/BUGS.md` B42).
|
||||
pub(super) fn removed_locally(result: std::io::Result<()>) -> std::io::Result<()> {
|
||||
match result {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// The body of [`Core::walk_local`], without a `Core`: recursively collect the
|
||||
/// local tree under `root` into `out`, reporting each entry to `scanned`.
|
||||
///
|
||||
/// **A path the scan cannot read is left out and recorded in `unscanned`, never
|
||||
/// silently dropped.** Every pass drops what `unscanned` covers from
|
||||
/// classification, so a baseline row under it is neither a local deletion nor a
|
||||
/// download target (`docs/BUGS.md` B55). That covers a subfolder the pass has no
|
||||
/// permission for, an entry that vanished between the listing and its `stat`,
|
||||
/// and a name that is not UTF-8. Failing the whole pass on any of them, as this
|
||||
/// did before, left one root-owned folder stopping everything else in the tree
|
||||
/// from syncing, on every pass, for good (B196).
|
||||
///
|
||||
/// The root is the exception, and so is any other I/O error: an absent or
|
||||
/// unreadable root fails the pass, since leaving the root out would leave
|
||||
/// nothing in, and an error this cannot name a cause for is not one to guess
|
||||
/// about.
|
||||
///
|
||||
/// Split out from the method so exactly that can be tested against a real tree
|
||||
/// with a real unreadable directory in it, which needs no `Core` at all.
|
||||
pub(super) fn walk_local_tree(
|
||||
root: &Path,
|
||||
rules: &IgnoreRules,
|
||||
writing: &HashSet<PathBuf>,
|
||||
out: &mut HashMap<String, LocalItem>,
|
||||
unscanned: &mut Unscanned,
|
||||
scanned: &mut dyn FnMut(&str),
|
||||
) -> Result<(), String> {
|
||||
walk_local_dir(root, root, rules, writing, out, unscanned, scanned).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Why [`walk_local_dir`] could not finish a folder.
|
||||
pub(super) enum ScanError {
|
||||
/// An I/O error on `what`, which the caller may leave out of the pass.
|
||||
Io { what: String, error: std::io::Error },
|
||||
/// Anything else, which fails the pass.
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ScanError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ScanError::Io { what, error } => write!(f, "{what}: {error}"),
|
||||
ScanError::Failed(message) => f.write_str(message),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Leave `rel` out of the pass for `failure`, or hand it back when it is one
|
||||
/// that fails the pass. Permission denied is reported to the user; an entry
|
||||
/// that vanished mid-scan is not, since the next pass sees it settled.
|
||||
pub(super) fn leave_out(
|
||||
rel: &str,
|
||||
failure: ScanError,
|
||||
unscanned: &mut Unscanned,
|
||||
) -> Result<(), ScanError> {
|
||||
let ScanError::Io { what, error } = &failure else {
|
||||
return Err(failure);
|
||||
};
|
||||
match error.kind() {
|
||||
std::io::ErrorKind::PermissionDenied => {
|
||||
warn!(%what, %error, "sync: cannot read; leaving it out of the pass");
|
||||
unscanned.unreadable(rel.to_string(), &error.to_string());
|
||||
Ok(())
|
||||
}
|
||||
std::io::ErrorKind::NotFound => {
|
||||
debug!(%what, "sync: gone mid-scan; leaving it out of the pass");
|
||||
unscanned.vanished(rel.to_string());
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(failure),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn walk_local_dir(
|
||||
root: &Path,
|
||||
dir: &Path,
|
||||
rules: &IgnoreRules,
|
||||
writing: &HashSet<PathBuf>,
|
||||
out: &mut HashMap<String, LocalItem>,
|
||||
unscanned: &mut Unscanned,
|
||||
scanned: &mut dyn FnMut(&str),
|
||||
) -> Result<(), ScanError> {
|
||||
let io = |what: String| move |error| ScanError::Io { what, error };
|
||||
let entries = std::fs::read_dir(dir).map_err(io(format!("read {}", dir.display())))?;
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(io(format!("read entry in {}", dir.display())))?;
|
||||
let path = entry.path();
|
||||
let stripped = path.strip_prefix(root).map_err(|e| {
|
||||
ScanError::Failed(format!(
|
||||
"local path {} escaped sync root {}: {e}",
|
||||
path.display(),
|
||||
root.display()
|
||||
))
|
||||
})?;
|
||||
let Some(rel) = stripped.to_str() else {
|
||||
// Nothing can be keyed by this name: not the baseline, which only
|
||||
// ever held paths this scan produced, and not Drive, whose names are
|
||||
// UTF-8. Leaving it out cannot read as a deletion of anything.
|
||||
warn!(path = %path.display(), "sync: name is not valid UTF-8; leaving it out of the pass");
|
||||
unscanned.unreadable(
|
||||
stripped.to_string_lossy().into_owned(),
|
||||
"name is not valid UTF-8",
|
||||
);
|
||||
continue;
|
||||
};
|
||||
// Ignore our own in-flight download temp files.
|
||||
if rel.contains(".pdfs-tmp-") {
|
||||
continue;
|
||||
}
|
||||
let meta = match std::fs::symlink_metadata(&path) {
|
||||
Ok(meta) => meta,
|
||||
// Gone since the listing, or in a folder that lists but does not
|
||||
// allow `stat`. Either way this pass cannot say what it is.
|
||||
Err(error) => {
|
||||
let what = format!("stat {}", path.display());
|
||||
leave_out(rel, ScanError::Io { what, error }, unscanned)?;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// Ignored paths are dropped here as well as from the classification
|
||||
// union — not for correctness (the union filter is what makes this
|
||||
// safe) but so an ignored `node_modules/` is never descended into or
|
||||
// counted against scan progress.
|
||||
if rules.is_ignored(rel, meta.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
if meta.is_dir() {
|
||||
out.insert(
|
||||
rel.to_string(),
|
||||
LocalItem {
|
||||
is_dir: true,
|
||||
mtime: 0,
|
||||
mtime_ns: None,
|
||||
size: 0,
|
||||
open_for_write: false,
|
||||
},
|
||||
);
|
||||
scanned(rel);
|
||||
if let Err(failure) =
|
||||
walk_local_dir(root, &path, rules, writing, out, unscanned, scanned)
|
||||
{
|
||||
leave_out(rel, failure, unscanned)?;
|
||||
// What the folder did list before failing goes with it: a
|
||||
// half-read folder is as unknown as an unread one.
|
||||
let prefix = format!("{rel}/");
|
||||
out.retain(|k, _| k != rel && !k.starts_with(&prefix));
|
||||
}
|
||||
} else if meta.is_file() {
|
||||
// Check whether any process holds this file open for writing.
|
||||
// The canonical path is used because /proc/*/fd links resolve
|
||||
// to canonical targets.
|
||||
let ofw = std::fs::canonicalize(&path)
|
||||
.map(|canon| writing.contains(&canon))
|
||||
.unwrap_or(false);
|
||||
out.insert(
|
||||
rel.to_string(),
|
||||
LocalItem {
|
||||
is_dir: false,
|
||||
mtime: system_mtime(&meta),
|
||||
mtime_ns: system_mtime_ns(&meta),
|
||||
size: meta.len() as i64,
|
||||
open_for_write: ofw,
|
||||
},
|
||||
);
|
||||
scanned(rel);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Why the mirror copy at `rel` holds something Proton Drive does not, or
|
||||
/// `None` when everything under it is on Drive exactly as it is on disk.
|
||||
///
|
||||
/// A move out of a mirror folder removes the local copy once Drive has moved
|
||||
/// the node, so anything only this disk has would be lost with it: a file not
|
||||
/// uploaded yet, one edited since, a deletion not carried up yet, or anything
|
||||
/// the engine never uploads. That is why ignored names count here, and why the
|
||||
/// walk is its own rather than [`walk_local_tree`], which skips symlinks.
|
||||
pub fn mirror_subtree_unsynced(
|
||||
root: &Path,
|
||||
rel: &str,
|
||||
baseline: &HashMap<String, StoredSyncEntry>,
|
||||
) -> Option<String> {
|
||||
let mut seen = HashSet::new();
|
||||
if let Some(reason) = unsynced_local(root, rel, baseline, None, &mut seen) {
|
||||
return Some(reason);
|
||||
}
|
||||
let prefix = format!("{rel}/");
|
||||
baseline
|
||||
.keys()
|
||||
.filter(|r| *r == rel || r.starts_with(&prefix))
|
||||
.find(|r| !seen.contains(r.as_str()))
|
||||
.map(|r| format!("{r} was deleted here but not on Proton Drive yet"))
|
||||
}
|
||||
|
||||
/// [`mirror_subtree_unsynced`] for a whole mirror folder: why its local copy
|
||||
/// holds something Proton Drive does not, or `None` when evicting it loses
|
||||
/// nothing. The switch to on-demand asks this before it empties the folder.
|
||||
///
|
||||
/// A push pass that ends `idle` is not enough on its own. It never uploads an
|
||||
/// ignored path, a symlink or a folder it cannot read, it defers a file open
|
||||
/// for writing, and a file can change after it finishes; the eviction deleted
|
||||
/// all of those for good (B198).
|
||||
///
|
||||
/// A tracked path deleted here but still in the baseline counts, since the
|
||||
/// mount would show it again. An ignored one does not: ignoring never carries
|
||||
/// a deletion to Drive, so its row stays in the baseline for good, and holding
|
||||
/// the switch on it would hold it forever.
|
||||
pub fn mirror_tree_unsynced(
|
||||
root: &Path,
|
||||
baseline: &HashMap<String, StoredSyncEntry>,
|
||||
rules: &IgnoreRules,
|
||||
) -> Option<String> {
|
||||
let mut seen = HashSet::new();
|
||||
if let Some(reason) = unsynced_local(root, "", baseline, Some(rules), &mut seen) {
|
||||
return Some(reason);
|
||||
}
|
||||
let mut missing: Vec<String> = filter_baseline(baseline, rules)
|
||||
.into_keys()
|
||||
.filter(|r| !seen.contains(r.as_str()))
|
||||
.collect();
|
||||
missing.sort_unstable();
|
||||
missing
|
||||
.first()
|
||||
.map(|r| format!("{r} was deleted here but not on Proton Drive yet"))
|
||||
}
|
||||
|
||||
/// Whether a mirror folder's local copy is gone in full: the folder is still
|
||||
/// there, but not one tracked path of its baseline is.
|
||||
///
|
||||
/// [`mirror_tree_unsynced`] reads that as deletions not carried up yet, which
|
||||
/// would refuse the switch to on-demand for good. It is the wipe guard's case
|
||||
/// instead, which the push pass a queued switch runs settles without trashing
|
||||
/// anything on Drive (#46), so the switch waits for that pass.
|
||||
pub fn mirror_tree_gone(
|
||||
root: &Path,
|
||||
baseline: &HashMap<String, StoredSyncEntry>,
|
||||
rules: &IgnoreRules,
|
||||
) -> bool {
|
||||
let tracked = filter_baseline(baseline, rules);
|
||||
root.is_dir()
|
||||
&& !tracked.is_empty()
|
||||
&& tracked.keys().all(|rel| {
|
||||
std::fs::symlink_metadata(root.join(rel_to_path(rel)))
|
||||
.is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound)
|
||||
})
|
||||
}
|
||||
|
||||
/// The walk behind both checks. `rules`, when given, only names an ignored
|
||||
/// path as such in the reason; it is still something only this disk has.
|
||||
pub(super) fn unsynced_local(
|
||||
root: &Path,
|
||||
rel: &str,
|
||||
baseline: &HashMap<String, StoredSyncEntry>,
|
||||
rules: Option<&IgnoreRules>,
|
||||
seen: &mut HashSet<String>,
|
||||
) -> Option<String> {
|
||||
let path = if rel.is_empty() {
|
||||
root.to_path_buf()
|
||||
} else {
|
||||
root.join(rel_to_path(rel))
|
||||
};
|
||||
// The folder itself has no baseline row; only what is in it does.
|
||||
if !rel.is_empty() {
|
||||
let meta = match std::fs::symlink_metadata(&path) {
|
||||
Ok(meta) => meta,
|
||||
Err(e) => return Some(format!("cannot read {rel}: {e}")),
|
||||
};
|
||||
let Some(base) = baseline.get(rel) else {
|
||||
if rules.is_some_and(|rules| rules.is_ignored(rel, meta.is_dir())) {
|
||||
return Some(format!(
|
||||
"{rel} is excluded from sync, so it is only on this computer"
|
||||
));
|
||||
}
|
||||
return Some(format!("{rel} is not on Proton Drive yet"));
|
||||
};
|
||||
seen.insert(rel.to_string());
|
||||
if meta.is_file() {
|
||||
return (!LocalSig::from(&meta).same_content(&LocalSig::from(base)))
|
||||
.then(|| format!("{rel} has changes that are not on Proton Drive yet"));
|
||||
}
|
||||
if !meta.is_dir() {
|
||||
return Some(format!("{rel} is not a regular file or folder"));
|
||||
}
|
||||
}
|
||||
let shown = if rel.is_empty() { "the folder" } else { rel };
|
||||
let entries = match std::fs::read_dir(&path) {
|
||||
Ok(entries) => entries,
|
||||
Err(e) => return Some(format!("cannot read {shown}: {e}")),
|
||||
};
|
||||
for entry in entries {
|
||||
let name = match entry {
|
||||
Ok(entry) => entry.file_name(),
|
||||
Err(e) => return Some(format!("cannot read {shown}: {e}")),
|
||||
};
|
||||
let Some(name) = name.to_str() else {
|
||||
return Some(format!("{shown} holds a name that is not valid UTF-8"));
|
||||
};
|
||||
// A download the engine left half done; it is the engine's to clean up.
|
||||
if name.contains(".pdfs-tmp-") {
|
||||
continue;
|
||||
}
|
||||
if let Some(reason) = unsynced_local(root, &join_rel(rel, name), baseline, rules, seen) {
|
||||
return Some(reason);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Publish a conflict copy without overwriting an earlier conflict bearing the
|
||||
/// same timestamp. The original is removed only after the new copy is durable.
|
||||
pub(super) fn preserve_conflict_copy(path: &Path, stamp: i64) -> std::io::Result<PathBuf> {
|
||||
let metadata = std::fs::metadata(path)?;
|
||||
for suffix in 0..=u32::MAX {
|
||||
let conflict = conflict_path_with_suffix(path, stamp, suffix);
|
||||
let mut source = std::fs::File::open(path)?;
|
||||
let mut target = match std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&conflict)
|
||||
{
|
||||
Ok(file) => file,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if let Err(e) = std::io::copy(&mut source, &mut target).and_then(|_| target.sync_all()) {
|
||||
let _ = std::fs::remove_file(&conflict);
|
||||
return Err(e);
|
||||
}
|
||||
target.set_permissions(metadata.permissions())?;
|
||||
if let Ok(modified) = metadata.modified() {
|
||||
target.set_modified(modified)?;
|
||||
}
|
||||
target.sync_all()?;
|
||||
sync_parent_dir(&conflict)?;
|
||||
std::fs::remove_file(path)?;
|
||||
sync_parent_dir(&conflict)?;
|
||||
return Ok(conflict);
|
||||
}
|
||||
unreachable!("u32 conflict suffix space exhausted")
|
||||
}
|
||||
|
||||
pub(super) fn sync_parent_dir(path: &Path) -> std::io::Result<()> {
|
||||
match path.parent() {
|
||||
Some(parent) => std::fs::File::open(parent)?.sync_all(),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a download into `path` is written before it is placed: next to it, so
|
||||
/// the rename that places it stays on one filesystem. A name with
|
||||
/// `.pdfs-tmp-` in it is never scanned or synced.
|
||||
pub(super) fn staging_path(path: &Path) -> PathBuf {
|
||||
path.with_extension(format!(
|
||||
"pdfs-tmp-{}",
|
||||
SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0)
|
||||
))
|
||||
}
|
||||
|
||||
/// Put a finished, durable download at `tmp` in place at `path`, stamped with
|
||||
/// the remote modification time `mtime`.
|
||||
///
|
||||
/// What is at `path` is checked one last time first: anything other than
|
||||
/// `expected` means a writer got there first, and its bytes are the ones
|
||||
/// nothing else has a copy of, so they are set aside as a conflict copy
|
||||
/// (`docs/BUGS.md` B39). On that failure `tmp` is removed.
|
||||
pub(super) fn place_download(
|
||||
tmp: &Path,
|
||||
path: &Path,
|
||||
expected: Option<LocalSig>,
|
||||
mtime: i64,
|
||||
rel: &str,
|
||||
) -> Result<(), String> {
|
||||
if let Err(e) = keep_racing_local_edit(path, expected) {
|
||||
let _ = std::fs::remove_file(tmp);
|
||||
return Err(format!("set aside racing local edit for {rel}: {e}"));
|
||||
}
|
||||
std::fs::rename(tmp, path).map_err(|e| format!("place {rel}: {e}"))?;
|
||||
// Match local mtime to the remote's so neither side looks "changed" next pass.
|
||||
let f = std::fs::File::options()
|
||||
.write(true)
|
||||
.open(path)
|
||||
.map_err(|e| format!("open placed file {rel}: {e}"))?;
|
||||
f.set_modified(SystemTime::UNIX_EPOCH + Duration::from_secs(mtime.max(0) as u64))
|
||||
.map_err(|e| format!("set mtime for {rel}: {e}"))?;
|
||||
f.sync_all()
|
||||
.map_err(|e| format!("sync placed file {rel}: {e}"))?;
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::File::open(parent)
|
||||
.and_then(|dir| dir.sync_all())
|
||||
.map_err(|e| format!("sync directory for {rel}: {e}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
//! The port through which the mirror engine reads and writes its own tables.
|
||||
//!
|
||||
//! The engine keeps three things in the database: the synced folders, the
|
||||
//! per-file baseline of each, and the saved walk of Drive with its dirty marks.
|
||||
//! [`SyncStore`] is exactly the calls a pass makes on them, so the engine does
|
||||
//! not depend on the whole database, and a test can give it a store of its own.
|
||||
//!
|
||||
//! The daemon's database implements it below; every method forwards to the
|
||||
//! [`Db`] method of the same name, which documents what it does.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use pdfs_core::Result;
|
||||
use pdfs_store::db::{Db, SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
|
||||
|
||||
/// The sync tables, as the mirror engine uses them.
|
||||
pub trait SyncStore: Send + Sync {
|
||||
// Synced folders.
|
||||
|
||||
/// Every synced folder, oldest first.
|
||||
fn sync_folder_list(&self) -> Result<Vec<StoredSyncFolder>>;
|
||||
/// One synced folder by id.
|
||||
fn sync_folder_get(&self, id: i64) -> Result<Option<StoredSyncFolder>>;
|
||||
/// Set a synced folder's state and its last sync time.
|
||||
fn sync_folder_set_state(&self, id: i64, state: &str, last_sync: i64) -> Result<()>;
|
||||
/// Move every folder a killed daemon left in `syncing` to `error`.
|
||||
fn sync_folders_reset_syncing(&self) -> Result<usize>;
|
||||
|
||||
// The baseline.
|
||||
|
||||
/// A synced folder's whole baseline, keyed by relative path.
|
||||
fn sync_entries(&self, folder_id: i64) -> Result<HashMap<String, StoredSyncEntry>>;
|
||||
/// How many baseline rows each synced folder has.
|
||||
fn sync_entry_counts(&self) -> Result<HashMap<i64, usize>>;
|
||||
/// Insert or replace one baseline row.
|
||||
fn sync_entry_upsert(&self, folder_id: i64, e: &StoredSyncEntry) -> Result<()>;
|
||||
/// Drop one baseline row.
|
||||
fn sync_entry_remove(&self, folder_id: i64, rel_path: &str) -> Result<()>;
|
||||
/// Drop the baseline rows at `rel_path` and below it.
|
||||
fn sync_entries_remove_subtree(&self, folder_id: i64, rel_path: &str) -> Result<()>;
|
||||
/// Fill in the revision id of baseline rows that have none, as
|
||||
/// `(rel_path, revision_id)`. Returns how many rows changed.
|
||||
fn sync_entries_set_revision(&self, folder_id: i64, rows: &[(String, String)])
|
||||
-> Result<usize>;
|
||||
|
||||
// The saved walk of Drive, and the folders changed on Drive since.
|
||||
|
||||
/// The walk of Drive a pass started and did not finish, if any.
|
||||
fn sync_walk_load(&self, folder_id: i64) -> Result<Option<SavedWalk>>;
|
||||
/// Start a new walk of Drive from the root, dropping any saved one.
|
||||
fn sync_walk_begin(&self, folder_id: i64, root_uid: &str, now: i64) -> Result<()>;
|
||||
/// Save the listing of one folder of the walk. `false` when the walk was
|
||||
/// dropped in the meantime.
|
||||
fn sync_walk_record(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
dir: &str,
|
||||
short: bool,
|
||||
items: &[SavedWalkItem],
|
||||
removed: &[String],
|
||||
) -> Result<bool>;
|
||||
/// Mark the walk complete and drop the dirty marks it has read past.
|
||||
/// `false` when there is no walk to complete.
|
||||
fn sync_walk_complete(&self, folder_id: i64) -> Result<bool>;
|
||||
/// Drop a folder's saved walk.
|
||||
fn sync_walk_clear(&self, folder_id: i64) -> Result<()>;
|
||||
/// The folders to list on Drive again, as `(seq, rel_path)`.
|
||||
fn sync_remote_dirty(&self, folder_id: i64) -> Result<Vec<(i64, String)>>;
|
||||
/// Drop the dirty marks up to and including `seq`.
|
||||
fn sync_remote_dirty_consume(&self, folder_id: i64, seq: i64) -> Result<()>;
|
||||
/// Mark folders to list on Drive again.
|
||||
fn sync_remote_mark(&self, folder_id: i64, dirs: &[String]) -> Result<()>;
|
||||
}
|
||||
|
||||
impl SyncStore for Db {
|
||||
fn sync_folder_list(&self) -> Result<Vec<StoredSyncFolder>> {
|
||||
Db::sync_folder_list(self)
|
||||
}
|
||||
fn sync_folder_get(&self, id: i64) -> Result<Option<StoredSyncFolder>> {
|
||||
Db::sync_folder_get(self, id)
|
||||
}
|
||||
fn sync_folder_set_state(&self, id: i64, state: &str, last_sync: i64) -> Result<()> {
|
||||
Db::sync_folder_set_state(self, id, state, last_sync)
|
||||
}
|
||||
fn sync_folders_reset_syncing(&self) -> Result<usize> {
|
||||
Db::sync_folders_reset_syncing(self)
|
||||
}
|
||||
fn sync_entries(&self, folder_id: i64) -> Result<HashMap<String, StoredSyncEntry>> {
|
||||
Db::sync_entries(self, folder_id)
|
||||
}
|
||||
fn sync_entry_counts(&self) -> Result<HashMap<i64, usize>> {
|
||||
Db::sync_entry_counts(self)
|
||||
}
|
||||
fn sync_entry_upsert(&self, folder_id: i64, e: &StoredSyncEntry) -> Result<()> {
|
||||
Db::sync_entry_upsert(self, folder_id, e)
|
||||
}
|
||||
fn sync_entry_remove(&self, folder_id: i64, rel_path: &str) -> Result<()> {
|
||||
Db::sync_entry_remove(self, folder_id, rel_path)
|
||||
}
|
||||
fn sync_entries_remove_subtree(&self, folder_id: i64, rel_path: &str) -> Result<()> {
|
||||
Db::sync_entries_remove_subtree(self, folder_id, rel_path)
|
||||
}
|
||||
fn sync_entries_set_revision(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rows: &[(String, String)],
|
||||
) -> Result<usize> {
|
||||
Db::sync_entries_set_revision(self, folder_id, rows)
|
||||
}
|
||||
fn sync_walk_load(&self, folder_id: i64) -> Result<Option<SavedWalk>> {
|
||||
Db::sync_walk_load(self, folder_id)
|
||||
}
|
||||
fn sync_walk_begin(&self, folder_id: i64, root_uid: &str, now: i64) -> Result<()> {
|
||||
Db::sync_walk_begin(self, folder_id, root_uid, now)
|
||||
}
|
||||
fn sync_walk_record(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
dir: &str,
|
||||
short: bool,
|
||||
items: &[SavedWalkItem],
|
||||
removed: &[String],
|
||||
) -> Result<bool> {
|
||||
Db::sync_walk_record(self, folder_id, dir, short, items, removed)
|
||||
}
|
||||
fn sync_walk_complete(&self, folder_id: i64) -> Result<bool> {
|
||||
Db::sync_walk_complete(self, folder_id)
|
||||
}
|
||||
fn sync_walk_clear(&self, folder_id: i64) -> Result<()> {
|
||||
Db::sync_walk_clear(self, folder_id)
|
||||
}
|
||||
fn sync_remote_dirty(&self, folder_id: i64) -> Result<Vec<(i64, String)>> {
|
||||
Db::sync_remote_dirty(self, folder_id)
|
||||
}
|
||||
fn sync_remote_dirty_consume(&self, folder_id: i64, seq: i64) -> Result<()> {
|
||||
Db::sync_remote_dirty_consume(self, folder_id, seq)
|
||||
}
|
||||
fn sync_remote_mark(&self, folder_id: i64, dirs: &[String]) -> Result<()> {
|
||||
Db::sync_remote_mark(self, folder_id, dirs)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn entry(rel_path: &str) -> StoredSyncEntry {
|
||||
StoredSyncEntry {
|
||||
rel_path: rel_path.into(),
|
||||
remote_uid: Some(format!("vol~{rel_path}")),
|
||||
local_mtime: 5,
|
||||
local_mtime_ns: None,
|
||||
local_size: 6,
|
||||
remote_rev: Some("7".into()),
|
||||
remote_hash: Some("8".into()),
|
||||
remote_revision_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_database_serves_the_engine_through_the_port() {
|
||||
let db = Db::open(std::path::Path::new(":memory:")).unwrap();
|
||||
let id = db
|
||||
.sync_folder_add("/home/me/Docs", "vol~docs", "share")
|
||||
.unwrap();
|
||||
let store: Arc<dyn SyncStore> = Arc::new(db);
|
||||
|
||||
assert_eq!(store.sync_folder_list().unwrap().len(), 1);
|
||||
store.sync_folder_set_state(id, "syncing", 9).unwrap();
|
||||
assert_eq!(store.sync_folders_reset_syncing().unwrap(), 1);
|
||||
let folder = store.sync_folder_get(id).unwrap().unwrap();
|
||||
assert_eq!((folder.state.as_str(), folder.last_sync), ("error", 9));
|
||||
|
||||
for rel in ["a.txt", "d", "d/b.txt"] {
|
||||
store.sync_entry_upsert(id, &entry(rel)).unwrap();
|
||||
}
|
||||
let set = [("a.txt".to_string(), "rev-a".to_string())];
|
||||
assert_eq!(store.sync_entries_set_revision(id, &set).unwrap(), 1);
|
||||
store.sync_entries_remove_subtree(id, "d").unwrap();
|
||||
let rows = store.sync_entries(id).unwrap();
|
||||
assert_eq!(rows.keys().collect::<Vec<_>>(), ["a.txt"]);
|
||||
assert_eq!(rows["a.txt"].remote_revision_id.as_deref(), Some("rev-a"));
|
||||
store.sync_entry_remove(id, "a.txt").unwrap();
|
||||
assert_eq!(store.sync_entry_counts().unwrap().get(&id), None);
|
||||
|
||||
assert!(store.sync_walk_load(id).unwrap().is_none());
|
||||
store.sync_walk_begin(id, "vol~docs", 10).unwrap();
|
||||
assert!(store.sync_walk_load(id).unwrap().is_some());
|
||||
store.sync_walk_clear(id).unwrap();
|
||||
assert!(store.sync_walk_load(id).unwrap().is_none());
|
||||
assert!(!store.sync_walk_complete(id).unwrap());
|
||||
|
||||
store.sync_remote_mark(id, &["d".to_string()]).unwrap();
|
||||
let dirty = store.sync_remote_dirty(id).unwrap();
|
||||
assert_eq!(
|
||||
dirty.iter().map(|(_, p)| p.as_str()).collect::<Vec<_>>(),
|
||||
["d"]
|
||||
);
|
||||
store.sync_remote_dirty_consume(id, dirty[0].0).unwrap();
|
||||
assert!(store.sync_remote_dirty(id).unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,7 @@ graph TD
|
||||
| [`pdfs-core`](../crates/pdfs-core) | Authentication and keyring (`auth`), configuration and directories (`config`), the control protocol (`control`), search scoring, ignore rules, Google Takeout parsing, the machine profile, the transfer registry (`transfers`) and the shutdown signal (`shutdown`) |
|
||||
| [`pdfs-store`](../crates/pdfs-store) | The SQLite schema and queries (`db/`), the content cache (`cache`) |
|
||||
| [`pdfs-drive`](../crates/pdfs-drive) | The `DriveApi` seam over the SDK, the call counter (`counted`), and `FakeDrive` for the simulations |
|
||||
| [`pdfs-sync`](../crates/pdfs-sync) | The mirror engine: its passes and engine thread (`mirror`), and the parts with no I/O: planner, pass model and pass trace. It owns its state (`SyncParts`) and reaches the daemon only through `SyncHost` |
|
||||
| [`pdfs-sync`](../crates/pdfs-sync) | The mirror engine: its passes and engine thread (`mirror`), with its reads and writes of the local disk in one module (`mirror::local`), and the parts with no I/O: planner, pass model and pass trace. It owns its state (`SyncParts`), reads and writes its tables only through `SyncStore`, and reaches the daemon only through `SyncHost` |
|
||||
| [`pdfs-fuse`](../crates/pdfs-fuse) | The daemon: FUSE handlers (`filesystem`), the tree (`state`), reads (`reads`), the queue and the drain (`queue`, `drain`, `upload`), the link state (`link`), remote events (`background`), the daemon's side of the sync engine (`sync`, which implements `SyncHost`), moves between locations (`relocate`), control handlers (`control`), push events (`events`), photos, sharing, devices, the supervisor, and the simulation tests (`sim/`) |
|
||||
| [`pdfs-cli`](../crates/pdfs-cli) | The `pdfs` binary. `pdfs daemon` runs the daemon in-process; every other command is a control-socket client |
|
||||
| [`pdfs-gui`](../crates/pdfs-gui) | `pdfs-app`, `pdfs-tray` and `pdfs-prompt`. Pages in `src/app/pages/`, widgets in `src/app/widgets/`, CSS and icons in `resources/` |
|
||||
@@ -476,8 +476,13 @@ both with `pdfs_core::search::relevance_score`, so the prompt can merge them int
|
||||
| Smaller helpers | `pdfs-localindex` (home index for search), `pdfs-pause` (ends a timed pause), `pdfs-similar` (similar photos, on request), `pdfs-diagnostics` |
|
||||
|
||||
Long-running loops wait on one shared `Shutdown` signal instead of sleeping, so a stop joins them
|
||||
instead of leaving them behind (`docs/BUGS.md` B44). `pdfs diagnostics` reports what each worker
|
||||
is doing.
|
||||
instead of leaving them behind (`docs/BUGS.md` B44). The mount starts its long-lived threads
|
||||
through `pdfs_core::lifecycle::Services`. Each one is started with its name and, if it blocks where
|
||||
the signal does not reach, the call that wakes it: the drain's condvar, the sync engine's `Stop`
|
||||
message, a connection to the control socket. A stop signals, wakes and joins them in reverse start
|
||||
order, up to one 10-second deadline, and names any that are still running at the end.
|
||||
`pdfs diagnostics` reports what each worker is doing and which services are still running. The
|
||||
supervisor warns once about a service that ended while the mount runs.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -15,6 +15,13 @@ Schema: **49**. New tables save a mirror folder's walk of Proton Drive (48). A f
|
||||
kept, with a list of the folders that changed on Proton Drive since (49).
|
||||
|
||||
### Added
|
||||
- **`pdfs diagnostics` says which of the daemon's background services are running.** If one
|
||||
ends while the drive is mounted, for example the sync engine after a crash, the journal says
|
||||
so once, by name, instead of saying nothing until a restart.
|
||||
- **`PDFS_INSTANCE` runs a second client next to your own.** With a name set, the client keeps
|
||||
its own directories, keyring entry, kernel keys and mountpoint, so a test account can run
|
||||
alongside the account you use. `scripts/live-bench.py` uses it to time one edit, from the
|
||||
write to the new revision on Proton Drive.
|
||||
- **`pdfs diagnostics` counts every call the daemon makes to Proton Drive.** Per kind of call it
|
||||
shows how many were made since start, how many failed, and their total and longest time. The
|
||||
JSON report has them as `drive_calls`.
|
||||
|
||||
@@ -267,6 +267,50 @@ typo it is. A release run leaves it unset.
|
||||
| `PDFS_ACCEPTANCE_MIN_MIBPS`, `PDFS_ACCEPTANCE_MIN_OPS` | Throughput floors |
|
||||
| `PDFS_ACCEPTANCE_UNIT` | The systemd unit `--durability` restarts |
|
||||
|
||||
## A second account next to your own
|
||||
|
||||
`PDFS_INSTANCE=<name>` runs the client as a separate instance. The name is 1 to 32 lowercase
|
||||
letters, digits or `-`. Everything that keeps an account apart gets the name as a suffix:
|
||||
|
||||
- the config, state and cache directories (`~/.config/proton-drive-linux-<name>` and so on),
|
||||
and with them the database, the control socket and the machine id
|
||||
- the Secret Service entry and the kernel keys
|
||||
- the default mountpoint, `~/ProtonDrive-<name>`
|
||||
|
||||
The systemd unit runs only the default instance. With an instance set, `pdfs login` does not
|
||||
restart it; start that instance's daemon by hand:
|
||||
|
||||
```bash
|
||||
PDFS_INSTANCE=test pdfs login
|
||||
PDFS_INSTANCE=test pdfs daemon
|
||||
```
|
||||
|
||||
### The one-edit benchmark
|
||||
|
||||
`scripts/live-bench.py` times a single edit in a synced folder against a real account, on its own
|
||||
instance (`bench` by default). For each tree size it attaches a new folder in My files, waits for
|
||||
the first sync, edits one file and reports:
|
||||
|
||||
- debounce: the write until the sync pass starts
|
||||
- the pass, by stage and by call to Drive, from `pdfs diagnostics`
|
||||
- verify: the end of the pass until `pdfs versions list` shows the new revision
|
||||
|
||||
Then it detaches the folder and moves it to the trash.
|
||||
|
||||
```bash
|
||||
scripts/live-bench.py --account-env path/to/.env --pdfs target/debug/pdfs --sizes 20,500
|
||||
```
|
||||
|
||||
The env file holds `username=`, `password=` and, for two-factor sign-in, `PROTON_TOTP_SECRET=`.
|
||||
The script types them into `pdfs login` and never prints them. The session stays in the
|
||||
instance's keyring entry so the next run does not sign in again; `--logout` forgets it. When
|
||||
Proton asks for a CAPTCHA, sign in once by hand with `PDFS_INSTANCE=bench pdfs login`.
|
||||
|
||||
The script refuses a `pdfs` built without `PDFS_INSTANCE`, which would act on your own account.
|
||||
A new folder's first sync uploads about one small file every four seconds, so with a 500-file
|
||||
tree the edit is timed about 35 minutes in. A run that is cut short leaves its folder behind; the
|
||||
next run removes it.
|
||||
|
||||
## Before a release
|
||||
|
||||
1. The quality gates and the simulation runs pass in CI.
|
||||
|
||||
Executable
+403
@@ -0,0 +1,403 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Time one edit in a synced folder, from the write to the new revision on Drive.
|
||||
|
||||
Runs against a real account on a separate instance (`PDFS_INSTANCE`), so the
|
||||
user's own daemon and session are never touched. For each tree size it:
|
||||
|
||||
1. makes a disposable folder in My files and a local tree of that many files,
|
||||
2. attaches the local tree to it and waits for the first sync to finish,
|
||||
3. edits one file and measures:
|
||||
- debounce: the write until the sync pass starts,
|
||||
- the pass, split into its stages and calls to Drive (`pdfs diagnostics`),
|
||||
- verify: the pass end until `pdfs versions list` shows the new revision,
|
||||
4. detaches the folder and trashes the remote copy.
|
||||
|
||||
The account comes from an env file with `username=`, `password=` and, for an
|
||||
account with two-factor sign-in, `PROTON_TOTP_SECRET=`. It is read here and
|
||||
typed into `pdfs login` over a pseudo-terminal; it is never printed or written
|
||||
anywhere. The session stays in the instance's keyring entry for the next run,
|
||||
so repeated runs do not sign in again (Proton limits sign-ins); pass
|
||||
`--logout` to forget it.
|
||||
|
||||
scripts/live-bench.py --account-env ../proton-sdk-rs/.env --pdfs target/debug/pdfs
|
||||
|
||||
The daemon mounts at `~/ProtonDrive-<instance>` and logs to the work directory.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import contextlib
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import pty
|
||||
import select
|
||||
import shutil
|
||||
import signal
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
POLL = 0.1
|
||||
|
||||
|
||||
def read_account(path: Path) -> dict[str, str]:
|
||||
values = {}
|
||||
for line in path.read_text().splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
values[key.strip()] = value.strip()
|
||||
for key in ("username", "password"):
|
||||
if not values.get(key):
|
||||
raise SystemExit(f"{path} has no {key}=")
|
||||
return values
|
||||
|
||||
|
||||
def totp(secret: str, at: float | None = None) -> str:
|
||||
"""RFC 6238: SHA-1, 30-second steps, six digits."""
|
||||
key = base64.b32decode(secret.upper() + "=" * (-len(secret) % 8))
|
||||
counter = int((at if at is not None else time.time()) // 30)
|
||||
digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
|
||||
offset = digest[-1] & 0x0F
|
||||
code = struct.unpack(">I", digest[offset : offset + 4])[0] & 0x7FFFFFFF
|
||||
return f"{code % 1_000_000:06d}"
|
||||
|
||||
|
||||
class Pdfs:
|
||||
def __init__(self, binary: str, instance: str) -> None:
|
||||
self.binary = binary
|
||||
self.env = dict(os.environ, PDFS_INSTANCE=instance)
|
||||
|
||||
def run(self, *args: str, check: bool = True, timeout: float = 120) -> str:
|
||||
result = subprocess.run(
|
||||
[self.binary, *args],
|
||||
env=self.env,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
stdin=subprocess.DEVNULL,
|
||||
timeout=timeout,
|
||||
)
|
||||
if check and result.returncode:
|
||||
detail = result.stderr.strip() or result.stdout.strip()
|
||||
raise RuntimeError(f"pdfs {' '.join(args)} failed ({result.returncode}): {detail}")
|
||||
return result.stdout
|
||||
|
||||
def json(self, *args: str) -> object:
|
||||
return json.loads(self.run("--json", *args))
|
||||
|
||||
def logged_in(self) -> bool:
|
||||
return "Not logged in" not in self.run("status", check=False)
|
||||
|
||||
def login(self, account: dict[str, str]) -> None:
|
||||
"""Answer `pdfs login`'s prompts over a pseudo-terminal."""
|
||||
pid, fd = pty.fork()
|
||||
if pid == 0:
|
||||
os.execve(self.binary, [self.binary, "login", "--username", account["username"]], self.env)
|
||||
transcript = b""
|
||||
answered: set[bytes] = set()
|
||||
deadline = time.monotonic() + 180
|
||||
try:
|
||||
while time.monotonic() < deadline:
|
||||
ready, _, _ = select.select([fd], [], [], 1)
|
||||
if not ready:
|
||||
continue
|
||||
try:
|
||||
chunk = os.read(fd, 4096)
|
||||
except OSError:
|
||||
break
|
||||
if not chunk:
|
||||
break
|
||||
transcript += chunk
|
||||
tail = transcript[-200:].lower()
|
||||
if b"password:" in tail and b"password" not in answered and b"mailbox" not in tail:
|
||||
answered.add(b"password")
|
||||
os.write(fd, account["password"].encode() + b"\n")
|
||||
elif b"2fa code:" in tail and b"totp" not in answered:
|
||||
secret = account.get("PROTON_TOTP_SECRET")
|
||||
if not secret:
|
||||
raise RuntimeError("the account asks for a 2FA code; add PROTON_TOTP_SECRET")
|
||||
answered.add(b"totp")
|
||||
os.write(fd, totp(secret).encode() + b"\n")
|
||||
elif b"mailbox" in tail:
|
||||
raise RuntimeError("two-password accounts are not supported by this benchmark")
|
||||
elif b"captcha" in tail:
|
||||
raise RuntimeError("Proton asks for a CAPTCHA; sign in once by hand with PDFS_INSTANCE set")
|
||||
finally:
|
||||
with contextlib.suppress(OSError):
|
||||
os.close(fd)
|
||||
_, status = os.waitpid(pid, 0)
|
||||
if os.waitstatus_to_exitcode(status) != 0:
|
||||
# The transcript holds only prompts and pdfs's own messages: the
|
||||
# password and the code are typed with echo off.
|
||||
last = transcript.decode(errors="replace").strip().splitlines()[-1:]
|
||||
raise RuntimeError(f"pdfs login failed: {' '.join(last)}")
|
||||
|
||||
|
||||
def sync_state(pdfs: Pdfs) -> dict:
|
||||
value = pdfs.json("diagnostics")
|
||||
|
||||
def find(node: object) -> dict | None:
|
||||
if isinstance(node, dict):
|
||||
if "traces" in node and "pass_folder" in node:
|
||||
return node
|
||||
for child in node.values():
|
||||
found = find(child)
|
||||
if found is not None:
|
||||
return found
|
||||
return None
|
||||
|
||||
return find(value) or {"traces": [], "pass_folder": None}
|
||||
|
||||
|
||||
def trace_for(state: dict, folder_id: int) -> dict | None:
|
||||
for trace in state.get("traces", []):
|
||||
if trace["folder_id"] == folder_id:
|
||||
return trace
|
||||
return None
|
||||
|
||||
|
||||
def wait(what: str, predicate, timeout: float):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
value = predicate()
|
||||
if value:
|
||||
return value
|
||||
time.sleep(POLL)
|
||||
raise TimeoutError(f"timed out after {timeout:.0f}s waiting for {what}")
|
||||
|
||||
|
||||
def make_tree(root: Path, files: int, per_dir: int = 50) -> list[Path]:
|
||||
paths = []
|
||||
for index in range(files):
|
||||
directory = root / f"d{index // per_dir:04d}"
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
path = directory / f"f{index:06d}.txt"
|
||||
path.write_bytes(f"file {index}\n".encode() * 64)
|
||||
paths.append(path)
|
||||
return paths
|
||||
|
||||
|
||||
def revisions(pdfs: Pdfs, path: str) -> int:
|
||||
value = pdfs.json("versions", "list", path)
|
||||
items = value.get("items", value) if isinstance(value, dict) else value
|
||||
return len(items)
|
||||
|
||||
|
||||
def wait_quiet(pdfs: Pdfs, folder_id: int, quiet: float, timeout: float) -> None:
|
||||
"""Wait until no pass has run over the folder for `quiet` seconds."""
|
||||
deadline = time.monotonic() + timeout
|
||||
last = trace_for(sync_state(pdfs), folder_id)
|
||||
since = time.monotonic()
|
||||
while time.monotonic() < deadline:
|
||||
state = sync_state(pdfs)
|
||||
trace = trace_for(state, folder_id)
|
||||
if state.get("pass_folder") == folder_id or trace != last:
|
||||
last = trace
|
||||
since = time.monotonic()
|
||||
elif time.monotonic() - since >= quiet:
|
||||
return
|
||||
time.sleep(POLL)
|
||||
raise TimeoutError(f"the folder did not go quiet within {timeout:.0f}s")
|
||||
|
||||
|
||||
def bench_one(
|
||||
pdfs: Pdfs, mount: Path, work: Path, files: int, timeout: float, quiet: float
|
||||
) -> dict:
|
||||
name = f"pdfs-bench-{files}-{uuid.uuid4().hex[:8]}"
|
||||
local = work / name
|
||||
local.mkdir()
|
||||
paths = make_tree(local, files)
|
||||
pdfs.run("mkdir", str(mount), name)
|
||||
folder_id = None
|
||||
try:
|
||||
# A removed folder's id is reused, and its last trace with it.
|
||||
stale = {json.dumps(t, sort_keys=True) for t in sync_state(pdfs).get("traces", [])}
|
||||
started = time.monotonic()
|
||||
pdfs.run("sync", "attach", "--to", name, str(local))
|
||||
folder = next(
|
||||
item
|
||||
for item in pdfs.json("sync", "list")["items"]
|
||||
if Path(item["local_path"]).resolve() == local.resolve()
|
||||
)
|
||||
folder_id = folder["id"]
|
||||
pdfs.run("sync", "flush", timeout=timeout)
|
||||
wait(
|
||||
"the first pass",
|
||||
lambda: (t := trace_for(sync_state(pdfs), folder_id))
|
||||
and t["ended"] == "finished"
|
||||
and json.dumps(t, sort_keys=True) not in stale,
|
||||
timeout,
|
||||
)
|
||||
first_pass_s = time.monotonic() - started
|
||||
|
||||
# The first pass's own uploads come back as Drive events and start
|
||||
# another pass. An edit made while it runs would be timed against it.
|
||||
wait_quiet(pdfs, folder_id, quiet, timeout)
|
||||
|
||||
target = paths[len(paths) // 2]
|
||||
remote_path = f"{name}/{target.relative_to(local)}"
|
||||
before = revisions(pdfs, remote_path)
|
||||
previous = trace_for(sync_state(pdfs), folder_id)
|
||||
|
||||
edited = time.monotonic()
|
||||
with target.open("ab") as file:
|
||||
file.write(b"edited\n")
|
||||
file.flush()
|
||||
os.fsync(file.fileno())
|
||||
|
||||
def edit_pass():
|
||||
"""The ended pass that uploaded the edit. A pass that ended without
|
||||
uploading (a watcher event that came early) is skipped."""
|
||||
nonlocal previous
|
||||
state = sync_state(pdfs)
|
||||
trace = trace_for(state, folder_id)
|
||||
if state.get("pass_folder") == folder_id or not trace or trace == previous:
|
||||
return None
|
||||
if not trace["ended"]:
|
||||
return None
|
||||
previous = trace
|
||||
if any(call["name"] == "upload revision" for call in trace.get("calls", [])):
|
||||
return trace
|
||||
return None
|
||||
|
||||
trace = wait("the pass that uploads the edit", edit_pass, timeout)
|
||||
pass_end = time.monotonic()
|
||||
pass_start = pass_end - trace["elapsed_ms"] / 1000
|
||||
wait("the new revision on Drive", lambda: revisions(pdfs, remote_path) > before, timeout)
|
||||
verified = time.monotonic()
|
||||
return {
|
||||
"files": files,
|
||||
"first_pass_s": round(first_pass_s, 2),
|
||||
"debounce_ms": round((pass_start - edited) * 1000),
|
||||
"pass_ms": round((pass_end - pass_start) * 1000),
|
||||
"verify_ms": round((verified - pass_end) * 1000),
|
||||
"total_ms": round((verified - edited) * 1000),
|
||||
"trace": trace,
|
||||
}
|
||||
finally:
|
||||
if folder_id is not None:
|
||||
# A removal waits only briefly for a running pass to reach its next
|
||||
# checkpoint, and a pass mid-upload can take longer: retry, or the
|
||||
# synced folder outlives its tree and every later run trips on it.
|
||||
for _ in range(20):
|
||||
try:
|
||||
pdfs.run("sync", "rm", str(folder_id))
|
||||
break
|
||||
except Exception as error: # noqa: BLE001
|
||||
print(f" sync rm: {error}; retrying", file=sys.stderr)
|
||||
time.sleep(6)
|
||||
with contextlib.suppress(Exception):
|
||||
pdfs.run("rm", f"{mount}/{name}")
|
||||
shutil.rmtree(local, ignore_errors=True)
|
||||
|
||||
|
||||
def refuse_without_instances(binary: str) -> None:
|
||||
"""Stop unless `binary` honours PDFS_INSTANCE. One built before it existed
|
||||
ignores the variable and would sign in, attach and delete on the default
|
||||
instance: the user's own account."""
|
||||
result = subprocess.run(
|
||||
[binary, "status"],
|
||||
env=dict(os.environ, PDFS_INSTANCE="Not A Valid Name"),
|
||||
text=True,
|
||||
capture_output=True,
|
||||
stdin=subprocess.DEVNULL,
|
||||
timeout=30,
|
||||
)
|
||||
if result.returncode == 0 or "PDFS_INSTANCE" not in result.stderr:
|
||||
raise SystemExit(f"{binary} does not support PDFS_INSTANCE; refusing to run")
|
||||
|
||||
|
||||
def remove_leftovers(pdfs: Pdfs, mount: Path) -> None:
|
||||
"""Remove what an earlier run cut short left behind: its synced folders,
|
||||
and their folders on Drive."""
|
||||
for item in pdfs.json("sync", "list")["items"]:
|
||||
name = Path(item["local_path"]).name
|
||||
if not name.startswith("pdfs-bench-"):
|
||||
continue
|
||||
print(f"removing {name}, left by an earlier run", file=sys.stderr)
|
||||
with contextlib.suppress(Exception):
|
||||
pdfs.run("sync", "rm", str(item["id"]))
|
||||
with contextlib.suppress(Exception):
|
||||
pdfs.run("rm", f"{mount}/{name}")
|
||||
|
||||
|
||||
def print_result(result: dict) -> None:
|
||||
print(
|
||||
f"{result['files']:>6} files: edit to verified {result['total_ms']} ms "
|
||||
f"(debounce {result['debounce_ms']}, pass {result['pass_ms']}, verify {result['verify_ms']}); "
|
||||
f"first sync {result['first_pass_s']} s"
|
||||
)
|
||||
trace = result["trace"]
|
||||
for kind in ("phases", "calls"):
|
||||
line = ", ".join(f"{s['name']} {s['count']}x/{s['total_ms']}ms" for s in trace.get(kind, []))
|
||||
if line:
|
||||
print(f" {kind}: {line}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--account-env", type=Path, required=True, help="env file with the test account")
|
||||
parser.add_argument("--pdfs", default="pdfs", help="the pdfs CLI to run")
|
||||
parser.add_argument("--instance", default="bench", help="PDFS_INSTANCE to run under")
|
||||
parser.add_argument("--sizes", default="20,500", help="tree sizes, comma-separated")
|
||||
parser.add_argument("--timeout", type=float, default=3600, help="seconds per wait")
|
||||
parser.add_argument(
|
||||
"--quiet", type=float, default=15, help="seconds without a pass before the edit"
|
||||
)
|
||||
parser.add_argument("--work", type=Path, help="where the local trees and the daemon log go")
|
||||
parser.add_argument("--json", type=Path, help="also write the results here")
|
||||
parser.add_argument("--logout", action="store_true", help="forget the session afterwards")
|
||||
args = parser.parse_args()
|
||||
if args.instance in ("", "default"):
|
||||
raise SystemExit("refusing to run on the default instance")
|
||||
|
||||
pdfs = Pdfs(args.pdfs, args.instance)
|
||||
refuse_without_instances(args.pdfs)
|
||||
if not pdfs.logged_in():
|
||||
pdfs.login(read_account(args.account_env))
|
||||
|
||||
work = args.work or Path(tempfile.mkdtemp(prefix="pdfs-bench-"))
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
log = (work / "daemon.log").open("w")
|
||||
daemon = subprocess.Popen(
|
||||
[args.pdfs, "daemon"], env=pdfs.env, stdin=subprocess.DEVNULL, stdout=log, stderr=log
|
||||
)
|
||||
results = []
|
||||
try:
|
||||
status = wait(
|
||||
"the daemon to mount",
|
||||
lambda: (s := pdfs.json("status")) and s.get("mount") and s,
|
||||
args.timeout,
|
||||
)
|
||||
mount = Path(status["mount"].get("mountpoint") or Path.home() / f"ProtonDrive-{args.instance}")
|
||||
remove_leftovers(pdfs, mount)
|
||||
for size in (int(s) for s in args.sizes.split(",")):
|
||||
result = bench_one(pdfs, mount, work, size, args.timeout, args.quiet)
|
||||
print_result(result)
|
||||
results.append(result)
|
||||
if args.json:
|
||||
args.json.write_text(json.dumps(results, indent=2))
|
||||
finally:
|
||||
daemon.send_signal(signal.SIGTERM)
|
||||
try:
|
||||
daemon.wait(timeout=60)
|
||||
except subprocess.TimeoutExpired:
|
||||
daemon.kill()
|
||||
log.close()
|
||||
if args.logout:
|
||||
pdfs.run("logout", check=False)
|
||||
print(f"daemon log: {work / 'daemon.log'}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user