mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-26 11:02:14 +01:00
Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c1a2c78b6 | ||
|
|
bfe14b3fc9 | ||
|
|
bfa58357c9 | ||
|
|
64906bd786 | ||
|
|
6abb1a6cd9 | ||
|
|
ce97b86638 | ||
|
|
3879ee7922 | ||
|
|
220d0ed21a | ||
|
|
d40c7f7ebb | ||
|
|
fe9528ce29 | ||
|
|
b6ee07161c | ||
|
|
c2f5537bd7 | ||
|
|
06d099f0de | ||
|
|
c171a713cb | ||
|
|
23a961d020 | ||
|
|
d84b35c039 | ||
|
|
bf7d26ce23 | ||
|
|
62ae18efbf | ||
|
|
7cffeb924d |
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()
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -11,6 +11,7 @@ pub mod error;
|
||||
pub mod kernelkey;
|
||||
pub mod keycheck;
|
||||
pub mod localindex;
|
||||
pub mod lockrank;
|
||||
pub mod menu;
|
||||
pub mod mountfail;
|
||||
pub mod mountpoint;
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
//! A mutex that knows where it sits in the daemon's lock order.
|
||||
//!
|
||||
//! Most of the daemon's deadlocks were two threads taking the same pair of
|
||||
//! locks in opposite orders (`docs/BUGS.md` B110, the cold size upgrade, the
|
||||
//! diagnostics threads behind the database writer). Each such order was
|
||||
//! written down in a comment, and the next feature did not read it.
|
||||
//!
|
||||
//! A [`Ranked`] lock carries a [`Rank`]. In a debug build, a thread that blocks
|
||||
//! on a lock while it holds one of a higher rank panics, naming both, at the
|
||||
//! line that would deadlock under the wrong interleaving. Release builds keep
|
||||
//! no record and check nothing.
|
||||
//!
|
||||
//! Locks of equal rank may be held together. The code that takes several of
|
||||
//! them orders them itself (several synced folders, lowest id first). A
|
||||
//! `try_lock` cannot wait, so it is never refused, but what it takes is
|
||||
//! recorded like any other lock.
|
||||
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::time::Duration;
|
||||
|
||||
use parking_lot::{Mutex, MutexGuard};
|
||||
|
||||
/// Where a lock sits in the order. A thread takes locks in increasing rank.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Rank {
|
||||
/// One synced folder's lock, held by its sync pass for as long as the pass
|
||||
/// runs.
|
||||
SyncFolder = 10,
|
||||
/// Publishing a shared change to every mounted session.
|
||||
SharedPublication = 20,
|
||||
/// The inode tree.
|
||||
State = 30,
|
||||
/// The database's single write connection.
|
||||
DbWriter = 40,
|
||||
}
|
||||
|
||||
/// A mutex with a [`Rank`]; see the module documentation.
|
||||
pub struct Ranked<T> {
|
||||
rank: Rank,
|
||||
inner: Mutex<T>,
|
||||
}
|
||||
|
||||
impl<T> Ranked<T> {
|
||||
pub const fn new(rank: Rank, value: T) -> Self {
|
||||
Self {
|
||||
rank,
|
||||
inner: Mutex::new(value),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rank(&self) -> Rank {
|
||||
self.rank
|
||||
}
|
||||
|
||||
/// Block until the lock is free. In a debug build, panics when this
|
||||
/// thread holds a lock of a higher rank.
|
||||
pub fn lock(&self) -> RankedGuard<'_, T> {
|
||||
held::check(self.rank);
|
||||
RankedGuard::new(self.inner.lock(), self.rank)
|
||||
}
|
||||
|
||||
/// Take the lock if it is free.
|
||||
pub fn try_lock(&self) -> Option<RankedGuard<'_, T>> {
|
||||
self.inner
|
||||
.try_lock()
|
||||
.map(|guard| RankedGuard::new(guard, self.rank))
|
||||
}
|
||||
|
||||
/// Wait up to `timeout` for the lock. It waits, so it is checked as
|
||||
/// [`Ranked::lock`] is.
|
||||
pub fn try_lock_for(&self, timeout: Duration) -> Option<RankedGuard<'_, T>> {
|
||||
held::check(self.rank);
|
||||
self.inner
|
||||
.try_lock_for(timeout)
|
||||
.map(|guard| RankedGuard::new(guard, self.rank))
|
||||
}
|
||||
|
||||
pub fn into_inner(self) -> T {
|
||||
self.inner.into_inner()
|
||||
}
|
||||
|
||||
pub fn get_mut(&mut self) -> &mut T {
|
||||
self.inner.get_mut()
|
||||
}
|
||||
}
|
||||
|
||||
/// A held [`Ranked`] lock.
|
||||
pub struct RankedGuard<'a, T> {
|
||||
guard: MutexGuard<'a, T>,
|
||||
_held: held::Held,
|
||||
}
|
||||
|
||||
impl<'a, T> RankedGuard<'a, T> {
|
||||
fn new(guard: MutexGuard<'a, T>, rank: Rank) -> Self {
|
||||
Self {
|
||||
guard,
|
||||
_held: held::Held::new(rank),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for RankedGuard<'_, T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &T {
|
||||
&self.guard
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> DerefMut for RankedGuard<'_, T> {
|
||||
fn deref_mut(&mut self) -> &mut T {
|
||||
&mut self.guard
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
mod held {
|
||||
use std::cell::RefCell;
|
||||
|
||||
use super::Rank;
|
||||
|
||||
thread_local! {
|
||||
/// The ranks this thread holds, in the order it took them.
|
||||
static HELD: RefCell<Vec<Rank>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
pub(super) fn check(rank: Rank) {
|
||||
HELD.with(|held| {
|
||||
let held = held.borrow();
|
||||
if let Some(higher) = held.iter().find(|&&other| other > rank) {
|
||||
panic!(
|
||||
"lock order: waiting on {rank:?} while holding {higher:?} \
|
||||
(held: {held:?}); take {rank:?} first (see pdfs_core::lockrank)"
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) struct Held(Rank);
|
||||
|
||||
impl Held {
|
||||
pub(super) fn new(rank: Rank) -> Self {
|
||||
HELD.with(|held| held.borrow_mut().push(rank));
|
||||
Self(rank)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Held {
|
||||
fn drop(&mut self) {
|
||||
HELD.with(|held| {
|
||||
let mut held = held.borrow_mut();
|
||||
// Guards can drop out of order; forget the latest of this rank.
|
||||
if let Some(at) = held.iter().rposition(|&rank| rank == self.0) {
|
||||
held.remove(at);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
mod held {
|
||||
use super::Rank;
|
||||
|
||||
#[inline]
|
||||
pub(super) fn check(_: Rank) {}
|
||||
|
||||
pub(super) struct Held;
|
||||
|
||||
impl Held {
|
||||
#[inline]
|
||||
pub(super) fn new(_: Rank) -> Self {
|
||||
Held
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, debug_assertions))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn locks_taken_in_rank_order_are_allowed() {
|
||||
let state = Ranked::new(Rank::State, 1);
|
||||
let db = Ranked::new(Rank::DbWriter, 2);
|
||||
let a = state.lock();
|
||||
let b = db.lock();
|
||||
assert_eq!(*a + *b, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "lock order: waiting on State while holding DbWriter")]
|
||||
fn a_lower_rank_taken_under_a_higher_one_panics() {
|
||||
let state = Ranked::new(Rank::State, ());
|
||||
let db = Ranked::new(Rank::DbWriter, ());
|
||||
let _db = db.lock();
|
||||
let _state = state.lock();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locks_of_equal_rank_may_be_held_together() {
|
||||
let one = Ranked::new(Rank::SyncFolder, ());
|
||||
let two = Ranked::new(Rank::SyncFolder, ());
|
||||
let _one = one.lock();
|
||||
let _two = two.lock();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_released_lock_no_longer_counts() {
|
||||
let state = Ranked::new(Rank::State, ());
|
||||
let db = Ranked::new(Rank::DbWriter, ());
|
||||
drop(db.lock());
|
||||
let _state = state.lock();
|
||||
let _db = db.lock();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guards_dropped_out_of_order_are_both_forgotten() {
|
||||
let publication = Ranked::new(Rank::SharedPublication, ());
|
||||
let state = Ranked::new(Rank::State, ());
|
||||
let db = Ranked::new(Rank::DbWriter, ());
|
||||
let p = publication.lock();
|
||||
let s = state.lock();
|
||||
drop(p);
|
||||
drop(s);
|
||||
let _db = db.lock();
|
||||
drop(_db);
|
||||
let _p = publication.lock();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_try_lock_is_never_refused_but_still_counts() {
|
||||
let state = Ranked::new(Rank::State, ());
|
||||
let db = Ranked::new(Rank::DbWriter, ());
|
||||
let _db = db.lock();
|
||||
let s = state.try_lock().expect("free");
|
||||
drop(_db);
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
let _ = Ranked::new(Rank::SharedPublication, ()).lock();
|
||||
}));
|
||||
drop(s);
|
||||
assert!(result.is_err(), "the try_lock'd State still counts as held");
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -17,6 +17,7 @@ use pdfs_core::control::{
|
||||
ActivityKind, DeviceInfo, JobItem, MountKind, MountSpec, SyncFolderInfo, SyncPhase,
|
||||
SyncProgress,
|
||||
};
|
||||
use pdfs_core::lockrank::{Rank, Ranked};
|
||||
use pdfs_core::mounts::MountMode;
|
||||
use pdfs_core::profile::PROFILE_DIR_NAME;
|
||||
use pdfs_core::{CoreError, CoreResult};
|
||||
@@ -698,8 +699,12 @@ impl Core {
|
||||
}
|
||||
|
||||
/// The lock guarding sync-folder `id` against concurrent reconcile/mode-switch.
|
||||
pub(crate) fn sync_lock(&self, id: i64) -> Arc<Mutex<()>> {
|
||||
self.sync_locks.lock().entry(id).or_default().clone()
|
||||
pub(crate) fn sync_lock(&self, id: i64) -> Arc<Ranked<()>> {
|
||||
self.sync_locks
|
||||
.lock()
|
||||
.entry(id)
|
||||
.or_insert_with(|| Arc::new(Ranked::new(Rank::SyncFolder, ())))
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Remove a synced folder from the sync set. `delete_remote` also deletes its
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
//! remainder of the file is pulled from the remote — lazily, at commit.
|
||||
|
||||
use parking_lot::{Condvar, Mutex};
|
||||
use pdfs_core::lockrank::{Rank, Ranked};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::ffi::OsStr;
|
||||
use std::fs::File;
|
||||
@@ -520,7 +521,7 @@ struct Core {
|
||||
/// directory belongs exclusively to the primary My Files mount.
|
||||
primary: bool,
|
||||
/// The one tree every mount of the daemon serves from.
|
||||
state: Arc<Mutex<State>>,
|
||||
state: Arc<Ranked<State>>,
|
||||
/// The tree inode this mount's session is rooted at, set when the session
|
||||
/// is built ([`ProtonFs::new`]). Each fork has its own cell.
|
||||
root: Arc<OnceLock<u64>>,
|
||||
@@ -557,7 +558,7 @@ struct Core {
|
||||
db: Arc<Db>,
|
||||
/// Serializes only shared-list publication and access-loss invalidation.
|
||||
/// Network calls happen before taking it.
|
||||
shared_publication: Arc<Mutex<()>>,
|
||||
shared_publication: Arc<Ranked<()>>,
|
||||
/// Invalidates in-flight shared responses when access/list events arrive.
|
||||
shared_generation: Arc<AtomicU64>,
|
||||
/// Successful refreshes suppress retries even if persisting their timestamp
|
||||
@@ -771,7 +772,7 @@ struct Core {
|
||||
/// FUSE over it, so it must never overlap a pass that is walking and
|
||||
/// uploading that same tree — the engine would upload files as they vanish
|
||||
/// and then walk the FUSE mount as if it were local.
|
||||
sync_locks: Arc<Mutex<HashMap<i64, Arc<Mutex<()>>>>>,
|
||||
sync_locks: Arc<Mutex<HashMap<i64, Arc<Ranked<()>>>>>,
|
||||
/// Per-sync-folder paths the last pass could not read, so the activity feed
|
||||
/// says so when the set changes rather than on every poll (B196).
|
||||
sync_unscanned: Arc<Mutex<HashMap<i64, Vec<String>>>>,
|
||||
|
||||
@@ -500,7 +500,10 @@ pub(crate) fn mount_with(
|
||||
maintenance: Arc::new(Mutex::new(Default::default())),
|
||||
primary_root_uid: root.uid.clone(),
|
||||
primary: true,
|
||||
state: Arc::new(Mutex::new(State::new(db.clone(), share_access))),
|
||||
state: Arc::new(Ranked::new(
|
||||
Rank::State,
|
||||
State::new(db.clone(), share_access),
|
||||
)),
|
||||
root: Arc::new(OnceLock::new()),
|
||||
cache: Arc::new(cache),
|
||||
readers: Arc::new(Mutex::new(HashMap::new())),
|
||||
@@ -511,7 +514,7 @@ pub(crate) fn mount_with(
|
||||
prefetch_budget: Arc::new(tokio::sync::Semaphore::new(PREFETCH_BUDGET)),
|
||||
workers: Arc::new(Workers::new(FUSE_WORKERS)?),
|
||||
db,
|
||||
shared_publication: Arc::new(Mutex::new(())),
|
||||
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)),
|
||||
|
||||
@@ -18,7 +18,6 @@ use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::{CoreError, CoreResult};
|
||||
use pdfs_store::db::{StoredSyncEntry, StoredSyncFolder};
|
||||
use proton_drive_rs::NodeKind;
|
||||
@@ -200,7 +199,8 @@ impl Core {
|
||||
.collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
let locks: Vec<Arc<Mutex<()>>> = ids.iter().map(|&id| self.sync_lock(id)).collect();
|
||||
let locks: Vec<Arc<pdfs_core::lockrank::Ranked<()>>> =
|
||||
ids.iter().map(|&id| self.sync_lock(id)).collect();
|
||||
let mut guards = Vec::with_capacity(locks.len());
|
||||
for lock in &locks {
|
||||
guards.push(lock.try_lock_for(MIRROR_LOCK_WAIT).ok_or_else(|| {
|
||||
|
||||
@@ -30,6 +30,16 @@ const MOUNT_DEADLINE: Duration = Duration::from_secs(20);
|
||||
/// How long a restart may wait for the last run to let go of its database.
|
||||
const LAST_RUN_DEADLINE: Duration = Duration::from_secs(30);
|
||||
|
||||
/// How long a stop may wait for the mount to end before it aborts the FUSE
|
||||
/// connection. A mount that stops answering otherwise hangs the test, and the
|
||||
/// whole run with it (`docs/BUGS.md` B297).
|
||||
const STOP_DEADLINE: Duration = Duration::from_secs(60);
|
||||
|
||||
/// How long one daemon may live. Past this, its FUSE connection is aborted, so
|
||||
/// a test blocked on a request the mount never answers fails with `ENOTCONN`
|
||||
/// instead of hanging the run. The whole suite takes about 15 minutes in CI.
|
||||
const LIFETIME_LIMIT: Duration = Duration::from_secs(20 * 60);
|
||||
|
||||
pub(crate) struct Daemon {
|
||||
pub(crate) client: FakeClient,
|
||||
pub(crate) mountpoint: PathBuf,
|
||||
@@ -38,6 +48,13 @@ pub(crate) struct Daemon {
|
||||
stop: SyncSender<()>,
|
||||
mount: Option<JoinHandle<io::Result<MountOutcome>>>,
|
||||
rt: Option<tokio::runtime::Runtime>,
|
||||
/// The mount's FUSE connection, as `/sys/fs/fuse/connections` names it.
|
||||
connection: u64,
|
||||
/// Dropped with the daemon, which ends the thread enforcing
|
||||
/// [`LIFETIME_LIMIT`].
|
||||
_alive: std::sync::mpsc::Sender<()>,
|
||||
/// Dropped after `shut_down`, so the next simulation waits for this one.
|
||||
_turn: Turn,
|
||||
}
|
||||
|
||||
impl Daemon {
|
||||
@@ -45,6 +62,7 @@ impl Daemon {
|
||||
/// A later start on the same `dir` is a restart: it finds the queue, the
|
||||
/// cache and the database the last run left.
|
||||
pub(crate) fn start(dir: &Path, client: FakeClient) -> io::Result<Self> {
|
||||
let turn = Turn::take();
|
||||
log_to_test_output();
|
||||
isolate_from_the_developer();
|
||||
let mountpoint = dir.join("mnt");
|
||||
@@ -112,6 +130,27 @@ impl Daemon {
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
let connection = {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
u64::from(libc::minor(std::fs::metadata(&mountpoint)?.dev()))
|
||||
};
|
||||
let (alive, dropped) = std::sync::mpsc::channel::<()>();
|
||||
{
|
||||
let mountpoint = mountpoint.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("sim-lifetime".into())
|
||||
.spawn(move || {
|
||||
if let Err(std::sync::mpsc::RecvTimeoutError::Timeout) =
|
||||
dropped.recv_timeout(LIFETIME_LIMIT)
|
||||
{
|
||||
eprintln!(
|
||||
"{}: the daemon outlived {LIFETIME_LIMIT:?}; aborting its FUSE connection",
|
||||
mountpoint.display()
|
||||
);
|
||||
abort_connection(connection);
|
||||
}
|
||||
})?;
|
||||
}
|
||||
Ok(Self {
|
||||
client,
|
||||
mountpoint,
|
||||
@@ -120,6 +159,9 @@ impl Daemon {
|
||||
stop,
|
||||
mount: Some(mount),
|
||||
rt: Some(rt),
|
||||
connection,
|
||||
_alive: alive,
|
||||
_turn: turn,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -215,6 +257,21 @@ impl Daemon {
|
||||
return Ok(MountOutcome::Shutdown);
|
||||
};
|
||||
let _ = self.stop.try_send(());
|
||||
if !wait_until(STOP_DEADLINE, || mount.is_finished()) {
|
||||
abort_connection(self.connection);
|
||||
let _ = wait_until(STOP_DEADLINE, || mount.is_finished());
|
||||
if !mount.is_finished() {
|
||||
// Joining would hang the run; leak the thread instead.
|
||||
return Err(io::Error::other(format!(
|
||||
"{}: the mount did not end after its FUSE connection was aborted",
|
||||
self.mountpoint.display()
|
||||
)));
|
||||
}
|
||||
return Err(io::Error::other(format!(
|
||||
"{}: the mount did not stop within {STOP_DEADLINE:?}, so its FUSE connection was aborted",
|
||||
self.mountpoint.display()
|
||||
)));
|
||||
}
|
||||
let outcome = mount
|
||||
.join()
|
||||
.unwrap_or_else(|_| Err(io::Error::other("mount thread panicked")));
|
||||
@@ -231,6 +288,61 @@ impl Drop for Daemon {
|
||||
}
|
||||
}
|
||||
|
||||
/// Abort FUSE connection `connection`: every request waiting on it fails with
|
||||
/// `ENOTCONN`, and the mount's session ends. The connection belongs to the
|
||||
/// user who mounted it, so this needs no privileges.
|
||||
fn abort_connection(connection: u64) {
|
||||
let path = format!("/sys/fs/fuse/connections/{connection}/abort");
|
||||
if let Err(error) = std::fs::write(&path, "1") {
|
||||
eprintln!("could not abort {path}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// One simulation's turn to run daemons. The simulations share the process:
|
||||
/// its environment (see [`isolate_from_the_developer`]), its cores and its
|
||||
/// mounts. Run side by side, as plain `cargo test` does, they miss their
|
||||
/// deadlines and can hang (`docs/BUGS.md` B297). So a daemon started on one
|
||||
/// test thread waits while another test thread still has one.
|
||||
struct Turn;
|
||||
|
||||
/// The test thread whose daemons run now, and how many it has.
|
||||
static TURN: parking_lot::Mutex<Option<(std::thread::ThreadId, usize)>> =
|
||||
parking_lot::Mutex::new(None);
|
||||
static TURN_FREE: parking_lot::Condvar = parking_lot::Condvar::new();
|
||||
|
||||
impl Turn {
|
||||
fn take() -> Self {
|
||||
let me = std::thread::current().id();
|
||||
let mut turn = TURN.lock();
|
||||
loop {
|
||||
match turn.as_mut() {
|
||||
None => {
|
||||
*turn = Some((me, 1));
|
||||
return Turn;
|
||||
}
|
||||
Some((owner, count)) if *owner == me => {
|
||||
*count += 1;
|
||||
return Turn;
|
||||
}
|
||||
Some(_) => TURN_FREE.wait(&mut turn),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Turn {
|
||||
fn drop(&mut self) {
|
||||
let mut turn = TURN.lock();
|
||||
if let Some((_, count)) = turn.as_mut() {
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
*turn = None;
|
||||
TURN_FREE.notify_all();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a file system is mounted at `path`: it sits on another device than
|
||||
/// its parent.
|
||||
fn is_mounted(path: &Path) -> bool {
|
||||
@@ -369,6 +481,35 @@ mod tests {
|
||||
use pdfs_core::control::{RefreshScope, SyncIssue};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_simulation_on_another_thread_waits_for_this_ones_daemons() {
|
||||
// Side by side, the simulations missed their deadlines and could hang
|
||||
// on a mount (B297).
|
||||
let drive = FakeDrive::new();
|
||||
let first = Daemon::start(&scratch("turn-first"), drive.client(1, Faults::lan())).unwrap();
|
||||
let second_up = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let other = {
|
||||
let drive = drive.clone();
|
||||
let second_up = second_up.clone();
|
||||
std::thread::spawn(move || {
|
||||
let second =
|
||||
Daemon::start(&scratch("turn-second"), drive.client(2, Faults::lan())).unwrap();
|
||||
second_up.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
second.stop().unwrap();
|
||||
})
|
||||
};
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
assert!(!second_up.load(std::sync::atomic::Ordering::SeqCst));
|
||||
|
||||
// A second daemon on this thread does not wait for the first.
|
||||
let restarted = first.restart().unwrap();
|
||||
assert!(!second_up.load(std::sync::atomic::Ordering::SeqCst));
|
||||
restarted.stop().unwrap();
|
||||
other.join().unwrap();
|
||||
assert!(second_up.load(std::sync::atomic::Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn diagnostics_count_the_calls_made_to_drive() {
|
||||
@@ -1969,6 +2110,46 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_mirror_edit_whose_reply_was_lost_is_not_kept_as_a_conflict() {
|
||||
// Drive made the revision, but the answer never came back. The next
|
||||
// pass saw both sides changed since the baseline and kept a conflict
|
||||
// copy of this computer's own edit.
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("mirror-lost-revision-reply");
|
||||
let (daemon, folder, client) = start_mirror(&drive, &dir, &[("a.txt", b"one")]);
|
||||
let local = dir.join("local");
|
||||
assert!(wait_until(Duration::from_secs(30), || drive
|
||||
.lookup("mirrored/a.txt")
|
||||
.is_some()));
|
||||
assert!(wait_for_pass(&daemon, folder, 0));
|
||||
|
||||
client.lose_reply_to_next_revision();
|
||||
std::fs::write(local.join("a.txt"), b"two").unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
on_drive(&drive, "mirrored/a.txt").is_some_and(|bytes| bytes == b"two")
|
||||
}));
|
||||
daemon
|
||||
.request(&Request::SyncNow { id: Some(folder) })
|
||||
.unwrap();
|
||||
assert!(wait_for_pass(&daemon, folder, 0));
|
||||
daemon
|
||||
.request(&Request::SyncNow { id: Some(folder) })
|
||||
.unwrap();
|
||||
assert!(wait_for_pass(&daemon, folder, 0));
|
||||
|
||||
assert!(conflict_copies(&local, "a").is_empty());
|
||||
assert!(
|
||||
!drive.tree().keys().any(|k| k.contains("sync-conflict")),
|
||||
"{:?}",
|
||||
drive.tree()
|
||||
);
|
||||
assert_eq!(std::fs::read(local.join("a.txt")).unwrap(), b"two");
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_revision_made_during_a_mirror_download_still_arrives() {
|
||||
|
||||
@@ -374,12 +374,12 @@ impl DbWrite {
|
||||
/// write still happens synchronously on this thread before the caller proceeds,
|
||||
/// so a read that follows a mutation still sees it.
|
||||
pub(crate) struct StateGuard<'a> {
|
||||
guard: Option<parking_lot::MutexGuard<'a, State>>,
|
||||
guard: Option<pdfs_core::lockrank::RankedGuard<'a, State>>,
|
||||
db: &'a Arc<Db>,
|
||||
}
|
||||
|
||||
impl<'a> StateGuard<'a> {
|
||||
pub(crate) fn new(guard: parking_lot::MutexGuard<'a, State>, db: &'a Arc<Db>) -> Self {
|
||||
pub(crate) fn new(guard: pdfs_core::lockrank::RankedGuard<'a, State>, db: &'a Arc<Db>) -> Self {
|
||||
Self {
|
||||
guard: Some(guard),
|
||||
db,
|
||||
@@ -1641,7 +1641,7 @@ mod tests {
|
||||
let (st, _dir) = state();
|
||||
let db = st.db.clone();
|
||||
let root = uid("root").to_string();
|
||||
let state = parking_lot::Mutex::new(st);
|
||||
let state = pdfs_core::lockrank::Ranked::new(pdfs_core::lockrank::Rank::State, st);
|
||||
{
|
||||
let mut guard = StateGuard::new(state.lock(), &db);
|
||||
guard.intern(0, node("root", "none", "My Files", true));
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
//! and never name a submodule.
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::lockrank::{Rank, Ranked, RankedGuard};
|
||||
use rusqlite::Connection;
|
||||
|
||||
use pdfs_core::{Error, Result};
|
||||
@@ -96,7 +97,7 @@ const WAL_AUTOCHECKPOINT_PAGES: i64 = 500;
|
||||
/// Cheap to wrap in an `Arc`; clone the `Arc`, not this. All access goes through
|
||||
/// the inner `Mutex<Connection>`.
|
||||
pub struct Db {
|
||||
conn: Mutex<Connection>,
|
||||
conn: Ranked<Connection>,
|
||||
/// Read-only connections for `SELECT`-only methods. `None` for an in-memory
|
||||
/// database, where a second connection would open a different, empty one —
|
||||
/// those fall back to the write connection.
|
||||
@@ -153,7 +154,7 @@ impl ReadPool {
|
||||
/// for `self.read()?` and nothing else.
|
||||
pub(super) struct Reader<'a> {
|
||||
pooled: Option<Connection>,
|
||||
writer: Option<parking_lot::MutexGuard<'a, Connection>>,
|
||||
writer: Option<RankedGuard<'a, Connection>>,
|
||||
pool: Option<&'a ReadPool>,
|
||||
}
|
||||
|
||||
@@ -185,10 +186,10 @@ impl Drop for Reader<'_> {
|
||||
/// reachable; losing that row loses a write `close()` already reported as
|
||||
/// done. A FULL commit syncs the WAL, which covers every NORMAL commit before
|
||||
/// it as well.
|
||||
pub(super) struct Durable<'a>(parking_lot::MutexGuard<'a, Connection>);
|
||||
pub(super) struct Durable<'a>(RankedGuard<'a, Connection>);
|
||||
|
||||
impl<'a> Durable<'a> {
|
||||
pub(super) fn new(conn: parking_lot::MutexGuard<'a, Connection>) -> Result<Self> {
|
||||
pub(super) fn new(conn: RankedGuard<'a, Connection>) -> Result<Self> {
|
||||
conn.pragma_update(None, "synchronous", "FULL")?;
|
||||
Ok(Self(conn))
|
||||
}
|
||||
@@ -284,7 +285,7 @@ impl Db {
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let db = Self {
|
||||
conn: Mutex::new(conn),
|
||||
conn: Ranked::new(Rank::DbWriter, conn),
|
||||
// No pool for `:memory:`. A second connection to that name is a
|
||||
// second, empty database rather than another view of this one, so
|
||||
// every routed read would find a schema that does not exist.
|
||||
@@ -380,7 +381,7 @@ impl Db {
|
||||
conn.pragma_update(None, "wal_autocheckpoint", WAL_AUTOCHECKPOINT_PAGES)?;
|
||||
|
||||
let db = Self {
|
||||
conn: Mutex::new(conn),
|
||||
conn: Ranked::new(Rank::DbWriter, conn),
|
||||
readers: None,
|
||||
_single_writer: None,
|
||||
};
|
||||
@@ -404,7 +405,7 @@ impl Db {
|
||||
// connection unless explicitly enabled.
|
||||
conn.pragma_update(None, "foreign_keys", "ON")?;
|
||||
let db = Self {
|
||||
conn: Mutex::new(conn),
|
||||
conn: Ranked::new(Rank::DbWriter, conn),
|
||||
readers: None,
|
||||
_single_writer: None,
|
||||
};
|
||||
|
||||
@@ -544,15 +544,15 @@ pub fn plan_file(
|
||||
(false, false) => FilePlan::Unchanged,
|
||||
(true, false) => FilePlan::UploadRevision,
|
||||
(false, true) => FilePlan::Download,
|
||||
// With a baseline, both-changed is a genuine concurrent edit and must
|
||||
// be preserved as a conflict. Without one, "both changed" only means
|
||||
// this is the first sync and there was nothing to compare to: when the
|
||||
// sizes match and Drive has a digest to compare against, the apply
|
||||
// step hashes the local file before adopting it. Divergent sizes, or
|
||||
// no digest, stay a real conflict: a missing digest proves nothing.
|
||||
(true, true) if baseline.is_none() && l.size == r.size && r.sha1.is_some() => {
|
||||
FilePlan::AdoptBaseline
|
||||
}
|
||||
// Both sides changed. When the sizes match and Drive has a digest,
|
||||
// the apply step hashes the local file first, and records a
|
||||
// baseline without a transfer if they are the same bytes. Without
|
||||
// a baseline that is a first sync of a file already on both sides.
|
||||
// With one, it is an upload whose reply was lost: Drive holds this
|
||||
// computer's own edit, and a conflict copy of it would be a copy of
|
||||
// itself. Different bytes, divergent sizes, or no digest stay a
|
||||
// real conflict: a missing digest proves nothing.
|
||||
(true, true) if l.size == r.size && r.sha1.is_some() => FilePlan::AdoptBaseline,
|
||||
(true, true) => FilePlan::Conflict,
|
||||
},
|
||||
(Some(_), None) if baseline.is_none() || local_changed => FilePlan::UploadNew,
|
||||
@@ -790,6 +790,17 @@ mod file_plan_tests {
|
||||
plan_file(Some(&edited), Some(&newer), Some(&base)),
|
||||
FilePlan::Conflict
|
||||
);
|
||||
// The same size with a digest is hashed first: it may be this
|
||||
// computer's own upload whose reply was lost.
|
||||
let digested = RemoteItem {
|
||||
revision: Some("r2".into()),
|
||||
sha1: Some("da39a3ee".into()),
|
||||
..remote(30, 40)
|
||||
};
|
||||
assert_eq!(
|
||||
plan_file(Some(&local(11, 40)), Some(&digested), Some(&base)),
|
||||
FilePlan::AdoptBaseline
|
||||
);
|
||||
|
||||
// A row from before schema 44 has no id to compare, and a node read
|
||||
// without one says nothing: both fall back to the signature.
|
||||
|
||||
@@ -672,4 +672,60 @@ local state per node as each batch lands.
|
||||
- **Mirrored folders** still have their own engine (§7). They move onto the local tree and the
|
||||
queue after that.
|
||||
|
||||
### 4.0: from one daemon to composed services
|
||||
|
||||
The daemon grew one feature at a time inside `pdfs-fuse`, which now holds the FUSE handlers, the
|
||||
drain, the sync engine, photos, thumbnails, takeout, devices, the control server, the supervisor
|
||||
and diagnostics. Everything shares one `Core` struct (`lib.rs`) with over seventy fields, so any
|
||||
code can take any lock in any order, and a new feature can deadlock an old one (`docs/BUGS.md`
|
||||
B110, the cold size upgrade, the diagnostics threads stuck behind the database writer). Over
|
||||
forty threads are spawned ad hoc, each with its own stop and join rules. The only real seam is
|
||||
`DriveApi` (`drive.rs`), which is what lets the simulation tests run against a fake Drive.
|
||||
|
||||
4.0 splits the daemon into services that each own their state and threads, behind ports that can
|
||||
be swapped and tested alone. Dependencies point inward; inner crates never see GTK, `fuser`,
|
||||
`libc` error numbers or SDK node types.
|
||||
|
||||
```
|
||||
apps pdfs-cli, pdfs-gui talk to the daemon over the control socket only
|
||||
daemon pdfs-daemon builds the services, supervisor, diagnostics, control server
|
||||
adapters pdfs-fuse (Linux FUSE), pdfs-local (watch, scan, place), pdfs-drive (SDK adapter, fake Drive)
|
||||
services pdfs-sync (mirrors), pdfs-vfs (mounted files: objects, handles, generations), photos, ...
|
||||
base pdfs-store (SQLite, migrations), pdfs-core (config, protocol, ids, errors)
|
||||
```
|
||||
|
||||
Six rules hold that shape:
|
||||
|
||||
1. **Ownership.** Each service owns its state and its threads. Services talk through typed ports
|
||||
or messages, never through another service's lock.
|
||||
2. **Lifecycle.** Each service starts from its dependencies and returns a handle with `stop`, a
|
||||
bounded `join` and a health snapshot. The supervisor starts the services in dependency order
|
||||
and stops them in reverse. No thread is left detached.
|
||||
3. **No lock across a boundary.** No lock is held across an SDK call, a FUSE reply or kernel
|
||||
notification, a blocking send or a join. Debug builds check the order of the nested locks
|
||||
that remain.
|
||||
4. **Short transactions.** A read never falls back to the writer connection. Diagnostics use
|
||||
their own connection and report "busy" instead of waiting.
|
||||
5. **Absence is a fact, not a gap.** A locked, unreadable, partly listed or ignored path is never
|
||||
read as deleted, whether in sync, in the mount or behind a locked store.
|
||||
6. **Headless tests.** Each service runs in tests without a mount, a desktop or a Proton account:
|
||||
sync against the fake Drive and a temporary directory, the mounted-files service against a
|
||||
fake store.
|
||||
|
||||
The work goes in steps. Each ships the same behaviour with the simulation tests green:
|
||||
|
||||
| Step | What |
|
||||
|---|---|
|
||||
| 0 | Finish what is open: the resumable walk of Drive's changed folders (B294), the ignored `set_len` error on a resize (B295), a reopen after close that depends on the single dispatch thread, and no conflict copy when a lost reply left the same content on Drive |
|
||||
| 1 | Seams and measurement: a `DriveApi` decorator that counts calls and their time, diagnostics that cannot hang (B296), lock-order checks, a live one-edit benchmark |
|
||||
| 2 | Move code into `pdfs-store`, `pdfs-drive` and `pdfs-sync` without changing it |
|
||||
| 3 | Split `Core` into services with a lifecycle, under a supervisor in `pdfs-daemon` |
|
||||
| 4 | Sync on evidence: a local dirty set, typed absence, a delete guard over the whole walk, and a durable intent for each effect, first in shadow mode |
|
||||
| 5 | `pdfs-vfs`: open files, then directories and renames, behind the FUSE adapter |
|
||||
| 6 | One admission policy for mirrors, reads and writeback |
|
||||
|
||||
Steps 0 to 3 are 4.0.0. Steps 4 to 6 follow in 4.x, one service at a time. Out of scope for
|
||||
now: an encrypted local vault (full-disk encryption covers a copied disk today), Windows and
|
||||
macOS adapters, and a separate repository for the sync engine.
|
||||
|
||||
[ROADMAP.md](ROADMAP.md) tracks these and the rest of the planned work.
|
||||
@@ -108,6 +108,8 @@ a live account since.
|
||||
|
||||
| Entry | Title |
|
||||
|---|---|
|
||||
| [B298](#b298--a-synced-folder-edit-whose-upload-lost-its-answer-is-kept-as-a-conflict-copy-of-itself) | A synced-folder edit whose upload lost its answer is kept as a conflict copy of itself |
|
||||
| [B297](#b297--the-simulations-fail-and-hang-when-run-in-parallel-and-nothing-stops-that) | The simulations fail and hang when run in parallel, and nothing stops that |
|
||||
| [B296](#b296--a-busy-database-stalls-reads-and-piles-up-diagnostics-threads) | A busy database stalls reads, and piles up diagnostics threads |
|
||||
| [B294](#b294--a-mirror-folder-too-large-to-finish-in-one-run-never-syncs-and-holds-back-the-others) | A mirror folder too large to finish in one run never syncs, and holds back the others |
|
||||
| [B66](#b66--local-only-pending-data-is-not-protected-at-shutdown-high-21) | Local-only pending data is not protected at shutdown (HIGH-21) |
|
||||
@@ -308,6 +310,7 @@ a live account since.
|
||||
|
||||
| Entry | Title |
|
||||
|---|---|
|
||||
| [B295](#b295--a-resize-the-scratch-file-refused-still-succeeded) | A resize the scratch file refused still succeeded |
|
||||
| [B293](#b293--a-large-trash-never-lists-and-empty-trash-never-empties-it) | A large trash never lists, and Empty Trash never empties it |
|
||||
| [B292](#b292--two-programs-changing-settings-at-once-lose-one-of-the-changes) | Two programs changing settings at once lose one of the changes |
|
||||
| [B290](#b290--reopening-the-database-right-after-closing-it-can-be-refused-as-another-daemon) | Reopening the database right after closing it can be refused as another daemon |
|
||||
@@ -398,6 +401,80 @@ a live account since.
|
||||
|
||||
Newest first.
|
||||
|
||||
### B298 — A synced-folder edit whose upload lost its answer is kept as a conflict copy of itself
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
**Found:** 2026-11-26, in the 4.0 review of the mirror planner. B155 fixed the same symptom in
|
||||
the mount's drain; the mirror engine has its own path.
|
||||
**Where:** `plan_file` in `crates/pdfs-sync/src/planner.rs`
|
||||
|
||||
**Repro:** Edit a file in a mirrored folder. Drive makes the new revision, but the answer to
|
||||
the upload never comes back. The next pass sees the local file changed since the baseline,
|
||||
and the file on Drive changed too, so it keeps the local file as `a (sync-conflict …).txt`
|
||||
and downloads Drive's copy, which holds the same bytes. The simulation
|
||||
`a_mirror_edit_whose_reply_was_lost_is_not_kept_as_a_conflict` does this with a lost
|
||||
revision reply.
|
||||
|
||||
**Cause.** The planner hashed the local file against Drive's digest only on a first sync,
|
||||
with no baseline. With a baseline, both sides changed always meant a conflict.
|
||||
|
||||
**Fix.** When both sides changed, the sizes match and Drive has a digest, the planner asks
|
||||
for the same hash check whether or not there is a baseline. The same bytes record a new
|
||||
baseline without a transfer. Different bytes take the conflict path as before.
|
||||
|
||||
**Verified:** `a_mirror_edit_whose_reply_was_lost_is_not_kept_as_a_conflict`, which fails
|
||||
without the fix, and the planner test
|
||||
`a_new_remote_revision_is_a_change_even_at_the_same_mtime_and_size`.
|
||||
|
||||
---
|
||||
|
||||
### B297 — The simulations fail and hang when run in parallel, and nothing stops that
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
**Found:** 2026-11-25, while running the full simulation suite several times each for #134, #135
|
||||
and the 4.0 crate moves, with `cargo test -p pdfs-fuse --lib -- --ignored sim::`. That command
|
||||
leaves out `--test-threads=1`, which CI and [TESTING.md](TESTING.md) use, so libtest ran up to
|
||||
eight simulations at once in one process.
|
||||
**Where:** `crates/pdfs-fuse/src/sim/daemon.rs`, `Daemon::start` and `Daemon::shut_down`
|
||||
|
||||
**Repro:** Run the suite without `--test-threads=1`. Of 18 such runs on three branches based on
|
||||
main, 6 passed, 10 failed and 2 hung until a 900 s timeout. The failures were timing asserts
|
||||
in many tests, among them `a_write_that_failed_on_a_short_outage_goes_out_soon_after_the_link_returns`,
|
||||
`three_clients_one_writer_each` and `one_client_with_stale_hashes_and_reordered_echoes`.
|
||||
Each passes when run alone.
|
||||
|
||||
In a hung run, one test thread stayed in state D in `request_wait_answer`, waiting on a FUSE
|
||||
request to a mount its own process serves. Killing the process left it a zombie and left its
|
||||
mounts in place until their connections were aborted through
|
||||
`/sys/fs/fuse/connections/<n>/abort`.
|
||||
|
||||
Run serially, the same branches pass in CI (#133 to #137).
|
||||
|
||||
**Cause.** The simulations share process-wide state: `isolate_from_the_developer` sets the XDG
|
||||
variables once, which is sound only while no other test reads the environment, and every
|
||||
daemon runs drain workers, a sync engine and a runtime on the same few cores. In parallel the
|
||||
timing asserts miss their deadlines, and the harness has no way out of a mount that stops
|
||||
answering.
|
||||
|
||||
**Fix.** `Daemon::start` takes a turn: a daemon started on one test thread waits while
|
||||
another test thread still has one, so plain `cargo test` runs the simulations one after the
|
||||
other. A daemon on the same thread, as in a restart or the multi-client runs, does not wait.
|
||||
`--test-threads=1` stays the documented way, because it also keeps the parts of a test
|
||||
before its first daemon apart.
|
||||
|
||||
A mount that does not stop within 60 s has its FUSE connection aborted through
|
||||
`/sys/fs/fuse/connections/<n>/abort`, which the mounting user may write, and the stop fails
|
||||
with that message. A daemon alive after 20 minutes gets the same, so a test blocked on a
|
||||
request the mount never answers fails with `ENOTCONN` instead of hanging the run.
|
||||
|
||||
**Verified:** `a_simulation_on_another_thread_waits_for_this_ones_daemons`, which fails
|
||||
without the turn.
|
||||
|
||||
Separately, CI on main (`0b9e849`) failed `a_move_blocked_by_trash_can_be_retried_after_restore`
|
||||
once, serially ([run](https://github.com/narrrl/proton-drive-linux/actions/runs/45694939718)):
|
||||
the assert at `daemon.rs:2209` found an empty list. It has not failed since.
|
||||
|
||||
---
|
||||
### B296 — A busy database stalls reads, and piles up diagnostics threads
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
|
||||
@@ -15,6 +15,10 @@ 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_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`.
|
||||
@@ -50,6 +54,9 @@ kept, with a list of the folders that changed on Proton Drive since (49).
|
||||
first pass, and whenever the change feed lost track (#53).
|
||||
|
||||
### Fixed
|
||||
- **An edit in a synced folder whose upload lost its answer is no longer kept as a conflict copy
|
||||
of itself.** When the file on Drive has the same size and content as the local one, the
|
||||
next sync records it as in step instead (B298).
|
||||
- **A busy database no longer stalls reads or piles up threads.** A read that cannot get its own
|
||||
connection fails instead of waiting behind a long write. `pdfs diagnostics` reports the
|
||||
number of queued operations as unknown when the database does not answer in time, and no
|
||||
|
||||
@@ -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