Compare commits

..
Author SHA1 Message Date
nvrl e2cbb442f2 refactor(sync): reach the sync tables through a SyncStore port
The mirror engine held the whole database (`Arc<Db>`) but uses only the
18 calls on its own tables: synced folders, baselines, the saved walk of
Drive and its dirty marks. `SyncStore` is exactly those calls, the
database implements it by forwarding, and `SyncParts` now holds an
`Arc<dyn SyncStore>`. No behaviour changes.
2026-11-26 10:59:56 +01:00
nvrl 83391d6d96 Merge pull request #150 from narrrl/feat/pdfs-instance
feat(core,cli): PDFS_INSTANCE runs a second client next to your own
2026-11-26 10:10:51 +01:00
nvrl 67786c9462 Merge pull request #149 from narrrl/refactor/sync-engine-move
refactor(sync,fuse,core): move the mirror engine into pdfs-sync
2026-11-26 10:10:38 +01:00
nvrl 3255bc2f36 Merge pull request #148 from narrrl/refactor/sync-helpers
refactor(drive,core): move the node and digest helpers the sync engine uses
2026-11-26 10:10:24 +01:00
nvrl f6c3e45fd3 Merge pull request #147 from narrrl/refactor/sync-ports
refactor(fuse): give the sync engine its own state and a port to the daemon
2026-11-26 10:10:09 +01:00
nvrl 5c1a2c78b6 feat(core,cli): PDFS_INSTANCE runs a second client next to your own
With a name set, the client keeps its own XDG directories, Secret Service
entry, kernel keys and default mountpoint, and leaves the systemd unit
alone. A test account can then sign in without signing the user out.
scripts/live-bench.py uses it to time one edit in a synced folder, from
the write to the new revision on Drive.
2026-11-26 05:22:14 +01:00
17 changed files with 875 additions and 76 deletions

No files matched your search

+1 -1
View File
@@ -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")),
)
}
+5 -1
View File
@@ -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()
+2 -2
View File
@@ -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())
}
+9 -6
View File
@@ -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();
+116 -5
View File
@@ -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]
+20 -10
View File
@@ -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
View File
@@ -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)
+1 -1
View File
@@ -495,7 +495,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(),
+3 -1
View File
@@ -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};
+41 -39
View File
@@ -116,7 +116,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 +137,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 +218,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 +285,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, &current.state, current.last_sync);
let _ =
self.store
.sync_folder_set_state(folder.id, &current.state, current.last_sync);
}
Err(PassAbort::Abandoned) => {
info!(
@@ -293,14 +295,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, &current.state, current.last_sync);
let _ =
self.store
.sync_folder_set_state(folder.id, &current.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 +418,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 +454,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 +722,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 +734,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 +755,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 +788,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 +941,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 +960,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 +1049,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 +1075,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 +1085,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 +1105,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 +1125,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 +1179,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 +1398,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 +1425,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 +1450,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 +1492,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 +1514,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 +1754,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 +1762,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 +1948,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 {
@@ -2310,7 +2312,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 {
+6 -6
View File
@@ -213,7 +213,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,7 +231,7 @@ 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"),
@@ -245,7 +245,7 @@ fn engine_loop(core: Syncer, rx: Receiver<SyncMsg>) {
// 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 +377,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 +389,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 +538,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 -3
View File
@@ -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>,
+204
View File
@@ -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());
}
}
+1 -1
View File
@@ -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`), 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/` |
+4
View File
@@ -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`.
+44
View File
@@ -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.
+403
View File
@@ -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())