mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-26 11:02:14 +01:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e0e581bf8 | ||
|
|
16970ecf35 | ||
|
|
d428457514 | ||
|
|
ff37d1b081 | ||
|
|
83938db712 |
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(pdfs_core::config::app_dir_name())
|
||||
.join("proton-drive-linux")
|
||||
.join(format!("completion-{key}.json")),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1035,11 +1035,7 @@ fn cli_error(kind: ErrorKind, message: &str) -> String {
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
// 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
|
||||
// First: 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;
|
||||
use pdfs_core::config::{AppDirs, KEYRING_SERVICE};
|
||||
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(pdfs_core::config::keyring_service(), "session")
|
||||
keyring_core::Entry::new(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, USER_AGENT};
|
||||
use crate::config::{APP_VERSION, AppDirs, KEYRING_SERVICE, USER_AGENT};
|
||||
use crate::error::{Error, Result};
|
||||
use crate::kernelkey;
|
||||
|
||||
@@ -141,15 +141,12 @@ fn keyring() -> &'static KeyringStore {
|
||||
STORE.get_or_init(|| {
|
||||
#[cfg(not(test))]
|
||||
{
|
||||
KeyringStore::new(crate::config::keyring_service())
|
||||
KeyringStore::new(KEYRING_SERVICE)
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
KeyringStore::with_connector(
|
||||
crate::config::KEYRING_SERVICE,
|
||||
Arc::new(tests::connect_keyring_store),
|
||||
)
|
||||
.replace_items(|| tests::MOCK_STORE.lock().is_none())
|
||||
KeyringStore::with_connector(KEYRING_SERVICE, Arc::new(tests::connect_keyring_store))
|
||||
.replace_items(|| tests::MOCK_STORE.lock().is_none())
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1276,7 +1273,7 @@ mod tests {
|
||||
|
||||
/// The session's entry, to make its next call fail.
|
||||
fn keyring_entry() -> Entry {
|
||||
Entry::new(crate::config::KEYRING_SERVICE, KEYRING_USER).unwrap()
|
||||
Entry::new(KEYRING_SERVICE, KEYRING_USER).unwrap()
|
||||
}
|
||||
|
||||
/// Make the session entry's next call fail with `error`.
|
||||
@@ -1423,7 +1420,7 @@ mod tests {
|
||||
.unwrap();
|
||||
let found = ss
|
||||
.search_items(std::collections::HashMap::from([
|
||||
("service", crate::config::KEYRING_SERVICE),
|
||||
("service", KEYRING_SERVICE),
|
||||
("username", KEYRING_USER),
|
||||
]))
|
||||
.unwrap();
|
||||
|
||||
@@ -26,93 +26,9 @@ 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 of the default instance; see [`keyring_service`].
|
||||
/// Keyring service name; one entry per credential kind keyed by username.
|
||||
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;
|
||||
@@ -610,7 +526,7 @@ pub struct AppDirs {
|
||||
|
||||
impl AppDirs {
|
||||
pub fn new() -> Result<Self> {
|
||||
let dirs = ProjectDirs::from("io", "narl", &app_dir_name())
|
||||
let dirs = ProjectDirs::from("io", "narl", "proton-drive-linux")
|
||||
.ok_or_else(|| Error::Other("cannot resolve home directory".into()))?;
|
||||
Ok(Self { dirs })
|
||||
}
|
||||
@@ -743,13 +659,11 @@ impl AppDirs {
|
||||
directories::UserDirs::new().map(|u| u.home_dir().to_path_buf())
|
||||
}
|
||||
|
||||
/// Default mountpoint when the user does not pass one explicitly:
|
||||
/// `~/ProtonDrive`, or `~/ProtonDrive-<instance>` for a named [`instance`].
|
||||
/// Default mountpoint when the user does not pass one explicitly.
|
||||
pub fn default_mountpoint(&self) -> PathBuf {
|
||||
let name = instance_suffixed("ProtonDrive", '-');
|
||||
directories::UserDirs::new()
|
||||
.map(|u| u.home_dir().join(&name))
|
||||
.unwrap_or_else(|| PathBuf::from("/tmp").join(&name))
|
||||
.map(|u| u.home_dir().join("ProtonDrive"))
|
||||
.unwrap_or_else(|| PathBuf::from("/tmp/ProtonDrive"))
|
||||
}
|
||||
|
||||
/// The effective mountpoint: the config's explicit path, or
|
||||
@@ -848,31 +762,6 @@ 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,38 +18,36 @@
|
||||
//! `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, and carry
|
||||
/// the [`crate::config::instance`] so a second instance keeps its own.
|
||||
/// namespaced so they cannot collide with another program's keys.
|
||||
pub struct Key {
|
||||
name: &'static str,
|
||||
description: &'static [u8],
|
||||
}
|
||||
|
||||
/// The account's key passphrases (see the module docs).
|
||||
#[cfg(not(test))]
|
||||
pub const PASSPHRASES: Key = Key {
|
||||
name: "pdfs:key-passphrases",
|
||||
description: b"pdfs:key-passphrases\0",
|
||||
};
|
||||
/// Tests must never touch a real unlock.
|
||||
#[cfg(test)]
|
||||
pub const PASSPHRASES: Key = Key {
|
||||
name: "pdfs:key-passphrases:test",
|
||||
description: b"pdfs:key-passphrases:test\0",
|
||||
};
|
||||
|
||||
/// 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 {
|
||||
name: "pdfs:unsaved-tokens",
|
||||
description: b"pdfs:unsaved-tokens\0",
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub const UNSAVED_TOKENS: Key = Key {
|
||||
name: "pdfs:unsaved-tokens:test",
|
||||
description: b"pdfs:unsaved-tokens:test\0",
|
||||
};
|
||||
|
||||
const KEY_TYPE: &[u8] = b"user\0";
|
||||
@@ -75,7 +73,7 @@ fn last_error<T>() -> io::Result<T> {
|
||||
Err(io::Error::last_os_error())
|
||||
}
|
||||
|
||||
fn find(description: &std::ffi::CStr) -> io::Result<Option<libc::c_long>> {
|
||||
fn find(description: &[u8]) -> io::Result<Option<libc::c_long>> {
|
||||
// SAFETY: both strings are NUL-terminated and outlive the call.
|
||||
let id = unsafe {
|
||||
libc::syscall(
|
||||
@@ -110,23 +108,15 @@ 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(),
|
||||
description.as_ptr(),
|
||||
self.description.as_ptr(),
|
||||
secret.as_ptr(),
|
||||
secret.len(),
|
||||
KEY_SPEC_USER_KEYRING,
|
||||
@@ -155,7 +145,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.
|
||||
@@ -200,7 +190,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.
|
||||
|
||||
@@ -16,15 +16,7 @@ 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)
|
||||
@@ -44,9 +36,6 @@ 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,7 +1,17 @@
|
||||
//! Convert the client's stored epoch seconds at the SDK boundary.
|
||||
//! Epoch seconds: the clock, and the conversion at the SDK boundary.
|
||||
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use proton_drive_rs::ModificationTime;
|
||||
|
||||
/// Current wall-clock time as epoch seconds (0 if the clock is before the epoch).
|
||||
pub fn now_secs() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// A UTC modification time, or `None` when outside the SDK's supported range.
|
||||
pub fn modification_time(seconds: i64) -> Option<ModificationTime> {
|
||||
chrono::DateTime::from_timestamp(seconds, 0).map(|time| time.fixed_offset())
|
||||
|
||||
@@ -11,7 +11,7 @@ description = "The Proton Drive calls the Linux client makes, behind a trait"
|
||||
|
||||
[features]
|
||||
# FakeDrive and the simulation RNG, for tests in this and other crates.
|
||||
sim = ["dep:parking_lot", "dep:sha1", "dep:tokio", "dep:pdfs-store"]
|
||||
sim = ["dep:parking_lot", "dep:tokio", "dep:pdfs-store"]
|
||||
|
||||
[dependencies]
|
||||
pdfs-core.workspace = true
|
||||
@@ -21,7 +21,7 @@ pdfs-store = { workspace = true, optional = true }
|
||||
async-trait.workspace = true
|
||||
futures.workspace = true
|
||||
parking_lot = { workspace = true, optional = true }
|
||||
sha1 = { workspace = true, optional = true }
|
||||
sha1.workspace = true
|
||||
tokio = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
//! The SHA-1 digests Drive keys content on.
|
||||
|
||||
use std::io::Read;
|
||||
|
||||
use pdfs_core::{CoreError, CoreResult};
|
||||
use sha1::{Digest, Sha1};
|
||||
|
||||
/// The lowercase-hex SHA-1 of everything `reader` yields — the digest Proton's
|
||||
/// photo duplicate detection is keyed on.
|
||||
pub fn sha1_of(reader: &mut (dyn Read + Send)) -> CoreResult<String> {
|
||||
let mut hasher = Sha1::new();
|
||||
let mut buffer = vec![0u8; 256 * 1024];
|
||||
loop {
|
||||
let read = reader
|
||||
.read(&mut buffer)
|
||||
.map_err(|e| CoreError::invalid(format!("read failed: {e}")))?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buffer[..read]);
|
||||
}
|
||||
Ok(hex_lower(&hasher.finalize()))
|
||||
}
|
||||
|
||||
/// `bytes` as lowercase hex.
|
||||
pub fn hex_lower(bytes: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(bytes.len() * 2);
|
||||
for byte in bytes {
|
||||
out.push_str(&format!("{byte:02x}"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sha1_of_an_empty_reader_is_the_well_known_digest() {
|
||||
let mut empty: &[u8] = &[];
|
||||
assert_eq!(
|
||||
sha1_of(&mut empty).unwrap(),
|
||||
"da39a3ee5e6b4b0d3255bfef95601890afd80709"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -27,13 +27,14 @@ use futures::stream::BoxStream;
|
||||
use proton_drive_rs::proton_sdk::account::Quota;
|
||||
use proton_drive_rs::proton_sdk::api::ResponseCode;
|
||||
use proton_drive_rs::proton_sdk::error::{ProtonError, Result};
|
||||
use proton_drive_rs::proton_sdk::ids::{DriveEventId, NodeUid, ShareId};
|
||||
use proton_drive_rs::proton_sdk::ids::{DriveEventId, LinkId, NodeUid, ShareId, VolumeId};
|
||||
use proton_drive_rs::{
|
||||
AvailableNameTarget, Device, DeviceType, DriveEvent, DriveEventScopeId, Node, NodeKind,
|
||||
NodeMoveItem, ProtonDriveClient, RevisionReader, Thumbnail, ThumbnailType, TrashedNode,
|
||||
};
|
||||
|
||||
pub mod counted;
|
||||
pub mod digest;
|
||||
|
||||
/// One outcome per node of a batch request; see [`ProtonDriveClient::trash_nodes`].
|
||||
pub type NodeOutcomes = Vec<(NodeUid, Result<()>)>;
|
||||
@@ -609,6 +610,58 @@ pub fn node_revision_id(node: &Node) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The plaintext content SHA-1 of a file node, if its active revision carried one.
|
||||
/// A download-free content fingerprint the conflict sweep uses to prove two files
|
||||
/// hold identical bytes before it removes one.
|
||||
pub fn node_content_sha1(node: &Node) -> Option<String> {
|
||||
match &node.kind {
|
||||
NodeKind::Folder => None,
|
||||
NodeKind::File { content_sha1, .. } => content_sha1.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a `volume~link` uid display string back into a [`NodeUid`]. Front-ends
|
||||
/// receive uids as strings over the control socket and pass them back verbatim.
|
||||
pub fn parse_uid(s: &str) -> Option<NodeUid> {
|
||||
let (vol, link) = s.split_once('~')?;
|
||||
if vol.is_empty() || link.is_empty() || link.contains('~') {
|
||||
return None;
|
||||
}
|
||||
Some(NodeUid::new(VolumeId::from(vol), LinkId::from(link)))
|
||||
}
|
||||
|
||||
/// Whether a decrypted remote name can stand as one local path component.
|
||||
///
|
||||
/// Drive checks names only when a client creates or renames a node, and only
|
||||
/// for length, so a name made by another client, or by a server that should
|
||||
/// not be trusted, can hold anything. Joined onto a local path, a `/` or a `..`
|
||||
/// in it walks out of the folder it belongs to, and the mirror engine would
|
||||
/// then write or delete outside the sync root. In the mount, the kernel fails
|
||||
/// the whole listing with EIO on a single such name (`docs/BUGS.md` B215).
|
||||
pub fn remote_name_is_safe(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& name != "."
|
||||
&& name != ".."
|
||||
&& name.len() <= 255
|
||||
&& !name.contains(['/', '\0'])
|
||||
}
|
||||
|
||||
/// A coarse MIME type guessed from a file name's extension; Proton stores this
|
||||
/// on the node but an exact value is not required for correctness.
|
||||
pub fn media_type_for(name: &str) -> &'static str {
|
||||
let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase());
|
||||
match ext.as_deref() {
|
||||
Some("txt" | "md" | "log") => "text/plain",
|
||||
Some("png") => "image/png",
|
||||
Some("jpg" | "jpeg") => "image/jpeg",
|
||||
Some("gif") => "image/gif",
|
||||
Some("pdf") => "application/pdf",
|
||||
Some("json") => "application/json",
|
||||
Some("html" | "htm") => "text/html",
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
}
|
||||
|
||||
/// An in-memory Drive and the seeded randomness the simulations share.
|
||||
#[cfg(feature = "sim")]
|
||||
pub mod sim;
|
||||
@@ -13,7 +13,14 @@ use std::path::{Component, Path, PathBuf};
|
||||
impl Core {
|
||||
/// A bounded, server-verified ancestry walk. Do not decide ownership or
|
||||
/// remote-root overlap from a possibly incomplete cached folder listing.
|
||||
pub(super) fn attach_ancestors(&self, start: &NodeUid) -> CoreResult<Vec<NodeUid>> {
|
||||
pub(crate) fn attach_ancestors(&self, start: &NodeUid) -> CoreResult<Vec<NodeUid>> {
|
||||
self.remote_ancestry(start, false)
|
||||
}
|
||||
|
||||
/// The ancestry walk behind [`attach_ancestors`](Self::attach_ancestors).
|
||||
/// With `through_trash`, a folder in the trash is walked like any other
|
||||
/// instead of failing the walk.
|
||||
fn remote_ancestry(&self, start: &NodeUid, through_trash: bool) -> CoreResult<Vec<NodeUid>> {
|
||||
let mut ancestors = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let mut next = Some(start.clone());
|
||||
@@ -35,7 +42,7 @@ impl Core {
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or_else(|| CoreError::not_found("remote sync folder is missing"))?;
|
||||
if node.trashed {
|
||||
if node.trashed && !through_trash {
|
||||
return Err(CoreError::invalid("remote sync folder is in the trash"));
|
||||
}
|
||||
next = node.parent_uid;
|
||||
@@ -103,10 +110,17 @@ impl Core {
|
||||
for other in existing.iter().filter(|f| f.kind == "attached") {
|
||||
let uid = parse_uid(&other.remote_uid)
|
||||
.ok_or_else(|| CoreError::internal("invalid existing remote sync root"))?;
|
||||
if uid == remote_uid
|
||||
|| ancestors.contains(&uid)
|
||||
|| self.attach_ancestors(&uid)?.contains(&remote_uid)
|
||||
{
|
||||
// Another synced folder whose Drive folder is in the trash, or gone
|
||||
// for good, must not block every attach: its own walk fails, but
|
||||
// the question is only whether it lies below the new one. A
|
||||
// trashed folder keeps its parent, so the walk goes through the
|
||||
// trash; one that no longer exists lies below nothing.
|
||||
let theirs = match self.remote_ancestry(&uid, true) {
|
||||
Ok(theirs) => theirs,
|
||||
Err(e) if e.kind == pdfs_core::control::ErrorKind::NotFound => Vec::new(),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if uid == remote_uid || ancestors.contains(&uid) || theirs.contains(&remote_uid) {
|
||||
return Err(CoreError::invalid(
|
||||
"remote folder overlaps an existing synced folder",
|
||||
));
|
||||
@@ -126,8 +140,8 @@ impl Core {
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
|
||||
// An empty baseline makes one-sided files new, never deletions. The
|
||||
// engine hashes matching-size files and preserves divergent versions.
|
||||
let _ = self.sync_tx.send(sync::SyncMsg::Rewatch);
|
||||
let _ = self.sync_tx.send(sync::SyncMsg::Reconcile(id));
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
|
||||
self.db
|
||||
.sync_folder_get(id)
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
|
||||
|
||||
@@ -502,7 +502,9 @@ pub(super) async fn run_event_sync(
|
||||
}
|
||||
};
|
||||
if events.is_empty() {
|
||||
core.events_read_at.store(now_secs(), Ordering::Relaxed);
|
||||
core.sync
|
||||
.events_read_at
|
||||
.store(now_secs(), Ordering::Relaxed);
|
||||
continue;
|
||||
}
|
||||
debug!(count = events.len(), "applying remote events");
|
||||
@@ -550,10 +552,12 @@ pub(super) async fn run_event_sync(
|
||||
core.recheck_pinned(uid);
|
||||
}
|
||||
for &id in &dirty.synced {
|
||||
let _ = core.sync_tx.send(crate::sync::SyncMsg::Reconcile(id));
|
||||
let _ = core.sync.tx.send(crate::sync::SyncMsg::Reconcile(id));
|
||||
}
|
||||
if whole {
|
||||
core.events_read_at.store(now_secs(), Ordering::Relaxed);
|
||||
core.sync
|
||||
.events_read_at
|
||||
.store(now_secs(), Ordering::Relaxed);
|
||||
}
|
||||
// Another device changed the tree: whatever a front-end lists may have
|
||||
// moved, including what is shared and what is in the trash.
|
||||
|
||||
@@ -17,7 +17,6 @@ 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};
|
||||
@@ -154,7 +153,7 @@ impl Core {
|
||||
|
||||
/// Unified local-location listing for the control protocol.
|
||||
pub(crate) fn list_locations(&self) -> CoreResult<Vec<MountSpec>> {
|
||||
let progress = self.sync_progress.lock();
|
||||
let progress = self.sync.progress.lock();
|
||||
let mut locations = self
|
||||
.db
|
||||
.mount_list()
|
||||
@@ -602,8 +601,8 @@ impl Core {
|
||||
// Hand the initial upload to the sync engine: an empty baseline against a
|
||||
// full local tree reconciles as "upload everything", and the folder is
|
||||
// added to the filesystem watch set in the same pass.
|
||||
let _ = self.sync_tx.send(sync::SyncMsg::Rewatch);
|
||||
let _ = self.sync_tx.send(sync::SyncMsg::Reconcile(id));
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
|
||||
|
||||
info!(local = %local.display(), id, "added sync folder");
|
||||
self.db
|
||||
@@ -617,7 +616,7 @@ impl Core {
|
||||
pub(crate) fn list_sync_folders(&self) -> CoreResult<Vec<SyncFolderInfo>> {
|
||||
// Copied out rather than held: the pass takes this lock for every
|
||||
// entry it scans, and the queries below need not stall it.
|
||||
let progress = self.sync_progress.lock().clone();
|
||||
let progress = self.sync.progress.lock().clone();
|
||||
Ok(self
|
||||
.db
|
||||
.sync_folder_list()
|
||||
@@ -643,7 +642,8 @@ impl Core {
|
||||
pub(crate) fn jobs_snapshot(&self) -> Vec<JobItem> {
|
||||
let mut jobs = self.transfers.jobs_snapshot();
|
||||
let mut passes: Vec<(i64, SyncProgress)> = self
|
||||
.sync_progress
|
||||
.sync
|
||||
.progress
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|(id, p)| (*id, p.clone()))
|
||||
@@ -698,30 +698,21 @@ impl Core {
|
||||
jobs
|
||||
}
|
||||
|
||||
/// The lock guarding sync-folder `id` against concurrent reconcile/mode-switch.
|
||||
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
|
||||
/// folder under the device root; otherwise the cloud copy is left in place.
|
||||
pub(crate) fn remove_sync_folder(&self, id: i64, delete_remote: bool) -> CoreResult<()> {
|
||||
let lock = self.sync_lock(id);
|
||||
let lock = self.sync.lock(id);
|
||||
// A pass holds the lock for as long as it runs, hours on a large
|
||||
// folder. Ask it to stop at its next checkpoint rather than wait it
|
||||
// out on a control handler (B294).
|
||||
self.sync_abandon.lock().insert(id);
|
||||
self.sync.abandon.lock().insert(id);
|
||||
let guard = lock.try_lock_for(REMOVE_LOCK_WAIT);
|
||||
let Some(_guard) = guard else {
|
||||
return Err(CoreError::conflict(
|
||||
"the folder is in the middle of a sync step; try again in a minute",
|
||||
));
|
||||
};
|
||||
self.sync_abandon.lock().remove(&id);
|
||||
self.sync.abandon.lock().remove(&id);
|
||||
let folder = self
|
||||
.db
|
||||
.sync_folder_get(id)
|
||||
@@ -764,7 +755,7 @@ impl Core {
|
||||
drop(_guard);
|
||||
self.clear_sync_folder_paused(id);
|
||||
// Stop watching the folder we just dropped.
|
||||
let _ = self.sync_tx.send(sync::SyncMsg::Rewatch);
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
|
||||
if delete_remote
|
||||
&& let Some(uid) = parse_uid(&folder.remote_uid)
|
||||
&& let Err(e) = self
|
||||
@@ -780,8 +771,8 @@ impl Core {
|
||||
/// Trigger a reconcile: one folder by id, or every folder when `id` is `None`.
|
||||
pub(crate) fn sync_now(&self, id: Option<i64>) {
|
||||
let _ = match id {
|
||||
Some(id) => self.sync_tx.send(sync::SyncMsg::Reconcile(id)),
|
||||
None => self.sync_tx.send(sync::SyncMsg::ReconcileAll),
|
||||
Some(id) => self.sync.tx.send(sync::SyncMsg::Reconcile(id)),
|
||||
None => self.sync.tx.send(sync::SyncMsg::ReconcileAll),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -834,7 +825,7 @@ impl Core {
|
||||
}
|
||||
if current_mode == target_mode {
|
||||
let mode_str = target_mode.as_str();
|
||||
let lock = self.sync_lock(id);
|
||||
let lock = self.sync.lock(id);
|
||||
match lock.try_lock() {
|
||||
Some(_guard) => {
|
||||
let current = self
|
||||
@@ -852,7 +843,7 @@ impl Core {
|
||||
self.db
|
||||
.sync_folder_set_pending_mode(id, None)
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
|
||||
let _ = self.sync_tx.send(sync::SyncMsg::Rewatch);
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
|
||||
return Ok(if current.pending_mode.is_some() {
|
||||
format!("staying {mode_str}")
|
||||
} else {
|
||||
@@ -869,7 +860,7 @@ impl Core {
|
||||
self.db
|
||||
.sync_folder_set_pending_mode(id, Some(mode_str))
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
|
||||
let _ = self.sync_tx.send(sync::SyncMsg::Reconcile(id));
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
|
||||
return Ok(format!("staying {mode_str}"));
|
||||
}
|
||||
}
|
||||
@@ -885,7 +876,7 @@ impl Core {
|
||||
self.db
|
||||
.sync_folder_set_pending_mode(id, Some(mode_str))
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
|
||||
let _ = self.sync_tx.send(sync::SyncMsg::Reconcile(id));
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
|
||||
Ok(match mode {
|
||||
ApplicableMountMode::OnDemand => format!(
|
||||
"{} will go on-demand once its local changes are uploaded",
|
||||
@@ -987,7 +978,7 @@ impl Core {
|
||||
// failing is exactly "still syncing" — and it is the only reliable signal:
|
||||
// the `state` column is still `idle` in the window between `add_sync_folder`
|
||||
// inserting the row and the engine picking it up.
|
||||
let lock = self.sync_lock(id);
|
||||
let lock = self.sync.lock(id);
|
||||
let Some(_guard) = lock.try_lock() else {
|
||||
return Err(SwitchBlocked::NotNow);
|
||||
};
|
||||
@@ -1032,7 +1023,7 @@ impl Core {
|
||||
.db
|
||||
.sync_entries(id)
|
||||
.map_err(|e| SwitchBlocked::Failed(format!("db: {e:?}")))?;
|
||||
let rules = self.ignore_rules(&local);
|
||||
let rules = self.syncer().ignore_rules(&local);
|
||||
// Emptied before any pass saw it, the folder is still `idle`, and
|
||||
// the check below would refuse the switch for good. The push pass
|
||||
// of a queued switch forgets those paths instead (`docs/BUGS.md`
|
||||
@@ -1091,7 +1082,7 @@ impl Core {
|
||||
})?;
|
||||
self.publish_secondary_mount(id, mount)
|
||||
.map_err(SwitchBlocked::Failed)?;
|
||||
let _ = self.sync_tx.send(sync::SyncMsg::Rewatch);
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
|
||||
self.db.sync_folder_set_state(id, "idle", now_secs()).ok();
|
||||
info!(id, path = %local.display(), "mounted sync folder on-demand");
|
||||
Ok(format!("{} is now on-demand", local.display()))
|
||||
@@ -1118,8 +1109,8 @@ impl Core {
|
||||
self.db
|
||||
.sync_folder_set_mode(id, "mirror")
|
||||
.map_err(|e| SwitchBlocked::Failed(format!("db: {e:?}")))?;
|
||||
let _ = self.sync_tx.send(sync::SyncMsg::Rewatch);
|
||||
let _ = self.sync_tx.send(sync::SyncMsg::Reconcile(id));
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
|
||||
info!(id, path = %local.display(), "restored sync folder to mirror");
|
||||
Ok(format!(
|
||||
"{} is mirroring again; downloading",
|
||||
@@ -1141,7 +1132,7 @@ impl Core {
|
||||
/// that switch runs reads an unrecorded local file as new and would upload
|
||||
/// a second copy of every file Drive already has.
|
||||
pub(crate) fn reset_sync_folder(&self, id: i64) -> CoreResult<String> {
|
||||
let lock = self.sync_lock(id);
|
||||
let lock = self.sync.lock(id);
|
||||
let Some(_guard) = lock.try_lock() else {
|
||||
return Err(CoreError::conflict(
|
||||
"this folder is syncing; try again when the pass ends",
|
||||
@@ -1165,7 +1156,7 @@ impl Core {
|
||||
.sync_folder_set_pending_mode(id, None)
|
||||
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
|
||||
}
|
||||
let _ = self.sync_tx.send(sync::SyncMsg::Reconcile(id));
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
|
||||
info!(id, path = %folder.local_path, "sync folder reset");
|
||||
Ok(format!(
|
||||
"{} will sync from scratch",
|
||||
@@ -1213,7 +1204,7 @@ impl Core {
|
||||
}
|
||||
|
||||
fn mark_restore_error_if_current(&self, snapshot: &StoredSyncFolder) {
|
||||
let lock = self.sync_lock(snapshot.id);
|
||||
let lock = self.sync.lock(snapshot.id);
|
||||
let _guard = lock.lock();
|
||||
if self
|
||||
.db
|
||||
@@ -1268,7 +1259,7 @@ impl Core {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let lock = self.sync_lock(folder.id);
|
||||
let lock = self.sync.lock(folder.id);
|
||||
let _guard = lock.lock();
|
||||
let current = match self.db.sync_folder_get(folder.id) {
|
||||
Ok(Some(current)) if restore_snapshot_matches(&folder, ¤t) => current,
|
||||
|
||||
@@ -163,7 +163,7 @@ impl Core {
|
||||
control_handlers: super::control::active_handlers(),
|
||||
control_handler_limit: super::control::handler_limit(),
|
||||
pending_ops: self.pending_ops_quickly(),
|
||||
sync: Some(self.sync_engine.report()),
|
||||
sync: Some(self.sync.engine.report()),
|
||||
drive_calls: self
|
||||
.drive_calls
|
||||
.snapshot()
|
||||
|
||||
+6
-181
@@ -59,7 +59,7 @@ use pdfs_core::batch;
|
||||
use pdfs_core::config::{AppDirs, SweepMode};
|
||||
use pdfs_core::control::{
|
||||
ActivityEntry, ActivityKind, DirEntry, ErrorKind, LocalHit, PhotoKind, PublicLinkInfo,
|
||||
SearchFilters, SearchHit, SearchSource, SyncFolderInfo, SyncIssue, SyncPhase, SyncProgress,
|
||||
SearchFilters, SearchHit, SearchSource, SyncFolderInfo, SyncIssue, SyncProgress,
|
||||
ThumbnailBuildStatus, Topic, TransferDirection,
|
||||
};
|
||||
use pdfs_core::localindex;
|
||||
@@ -91,8 +91,10 @@ mod devices;
|
||||
mod diagnostics;
|
||||
mod drain;
|
||||
use drive::{DriveApi, RevisionRead};
|
||||
use pdfs_core::timestamp::now_secs;
|
||||
use pdfs_drive as drive;
|
||||
use pdfs_drive::node_revision_id;
|
||||
pub(crate) use pdfs_drive::{media_type_for, node_content_sha1, parse_uid, remote_name_is_safe};
|
||||
#[cfg(test)]
|
||||
use pdfs_sync::naming::{conflict_label, conflict_label_of, conflict_name_as};
|
||||
use pdfs_sync::naming::{conflict_name, this_hostname};
|
||||
@@ -576,10 +578,6 @@ struct Core {
|
||||
/// [`pause::PAUSED_INDEFINITELY`] for "until resumed", `0` when not paused.
|
||||
/// Persisted, so a pause survives a restart (see [`Core::sync_paused`]).
|
||||
sync_paused_until: Arc<AtomicI64>,
|
||||
/// When Drive's event stream was last read to the end of a batch, in Unix
|
||||
/// seconds; `0` until the first time. A mirror pass relies on the dirty
|
||||
/// marks the stream makes only while this is recent (see `docs/SYNC_ENGINE.md`).
|
||||
events_read_at: Arc<AtomicI64>,
|
||||
/// Writes accepted from the kernel but not yet uploaded, keyed by node.
|
||||
/// The in-memory face of the `pending_op` table, from
|
||||
/// which it is rebuilt on mount.
|
||||
@@ -741,24 +739,18 @@ struct Core {
|
||||
/// In-flight upload/download progress, served to `GetQueueStatus`. Shared
|
||||
/// across the FUSE session and the control-socket task.
|
||||
transfers: Arc<TransferRegistry>,
|
||||
/// The folder-sync engine's own state, and the handles it shares with the
|
||||
/// rest of the daemon.
|
||||
sync: sync::SyncParts,
|
||||
/// Open [`Request::Subscribe`](pdfs_core::control::Request::Subscribe)
|
||||
/// connections, which every change a front-end shows is published to.
|
||||
events: Arc<events::EventHub>,
|
||||
/// True while the background scanner is rebuilding the local-file index, so
|
||||
/// `SearchLocal` can tell a front-end "still indexing" apart from "no match".
|
||||
indexing: Arc<AtomicBool>,
|
||||
/// Live per-folder sync progress, keyed by sync-folder id, so `ListSyncFolders`
|
||||
/// can say what a pass is doing rather than just "syncing". An entry exists
|
||||
/// only while that folder's reconcile pass is running.
|
||||
sync_progress: Arc<Mutex<HashMap<i64, SyncProgress>>>,
|
||||
/// Whether the folder-sync engine is alive, and which pass it is on.
|
||||
sync_engine: Arc<sync::EngineHealth>,
|
||||
/// Set while a diagnostics report's database probe is still out, so a
|
||||
/// database that does not answer costs one stuck thread, not one per report.
|
||||
pending_probe: Arc<AtomicBool>,
|
||||
/// Channel to the folder-sync engine: nudges it to
|
||||
/// reconcile a folder, reconcile everything, or re-scan its watch set.
|
||||
sync_tx: std::sync::mpsc::Sender<sync::SyncMsg>,
|
||||
/// Secondary FUSE sessions for `ondemand` sync folders, keyed by sync-folder
|
||||
/// id. Each is a `ProtonFs` rooted at the folder's remote
|
||||
/// node, mounted over its local path, sharing this Core's client/cache/db and
|
||||
@@ -767,20 +759,6 @@ struct Core {
|
||||
/// FUSE connection id and the fork's exact liveness flag so teardown first
|
||||
/// makes that mount unroutable.
|
||||
mounts: Arc<Mutex<mount::SecondaryMountRegistry<SecondaryMount>>>,
|
||||
/// Per-sync-folder locks, held for a whole reconcile pass and for a whole
|
||||
/// mode switch. A `mirror→ondemand` flip evicts the local tree and mounts
|
||||
/// 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<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>>>>,
|
||||
/// Sync folders whose running pass should stop at its next checkpoint,
|
||||
/// because a removal is waiting for the folder's lock. A pass over a large
|
||||
/// folder holds that lock for hours, and a removal that waited for it
|
||||
/// held a control handler just as long (B294).
|
||||
sync_abandon: Arc<Mutex<HashSet<i64>>>,
|
||||
/// Nodes this daemon changed on the remote itself, and how many echoes of
|
||||
/// those changes the event feed still owes us.
|
||||
///
|
||||
@@ -6172,100 +6150,6 @@ impl Core {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- live sync progress -----------------------------------------------
|
||||
|
||||
/// Start tracking a reconcile pass over `folder_id`, in [`SyncPhase::Scanning`].
|
||||
pub(crate) fn progress_begin(&self, folder_id: i64) {
|
||||
self.sync_progress.lock().insert(
|
||||
folder_id,
|
||||
SyncProgress {
|
||||
phase: SyncPhase::Scanning,
|
||||
done: 0,
|
||||
total: 0,
|
||||
current: String::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Apply `f` to a folder's live progress, if a pass is running for it.
|
||||
fn progress_update(&self, folder_id: i64, f: impl FnOnce(&mut SyncProgress)) {
|
||||
let now = self.sync_progress.lock().get_mut(&folder_id).map(|p| {
|
||||
f(p);
|
||||
(p.phase, p.done, p.total)
|
||||
});
|
||||
if let Some((folder, age)) = self.sync_engine.moved()
|
||||
&& let Some((phase, done, total)) = now
|
||||
&& folder == folder_id
|
||||
{
|
||||
info!(
|
||||
id = folder,
|
||||
?phase,
|
||||
done,
|
||||
total,
|
||||
elapsed_s = age.as_secs(),
|
||||
"sync: pass still running"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the number of items the scan expects to check, from the size of the
|
||||
/// last pass's baseline. Only an estimate — the folder may have grown since —
|
||||
/// but it turns the scan from an indeterminate pulse into a bar that moves,
|
||||
/// which is the difference between "it's stuck" and "it's working" on a folder
|
||||
/// whose walk takes minutes.
|
||||
pub(crate) fn progress_scan_total(&self, folder_id: i64, n: usize) {
|
||||
self.progress_update(folder_id, |p| p.total = n);
|
||||
}
|
||||
|
||||
/// Note that the scan has checked one more item, named `name`.
|
||||
pub(crate) fn progress_scanned(&self, folder_id: i64, name: &str) {
|
||||
self.progress_update(folder_id, |p| {
|
||||
p.done += 1;
|
||||
p.current = name.to_string();
|
||||
});
|
||||
}
|
||||
|
||||
/// Note that the scan has checked `n` more items at once, read back from
|
||||
/// a walk an earlier pass saved.
|
||||
pub(crate) fn progress_scanned_many(&self, folder_id: i64, n: usize) {
|
||||
self.progress_update(folder_id, |p| p.done += n);
|
||||
}
|
||||
|
||||
/// Note that `n` more items have been queued for this pass, and that it has
|
||||
/// moved on from scanning to applying the diff. The scan's counts are dropped:
|
||||
/// they measured a different quantity (items checked, not items to apply), so
|
||||
/// carrying them over would start the applying bar at a meaningless fraction.
|
||||
pub(crate) fn progress_queued(&self, folder_id: i64, n: usize) {
|
||||
self.progress_update(folder_id, |p| {
|
||||
if p.phase == SyncPhase::Scanning {
|
||||
p.phase = SyncPhase::Applying;
|
||||
p.done = 0;
|
||||
p.total = 0;
|
||||
p.current.clear();
|
||||
}
|
||||
p.total += n;
|
||||
});
|
||||
}
|
||||
|
||||
/// Note that work has started on `name` (shown as the pass's current item).
|
||||
pub(crate) fn progress_started(&self, folder_id: i64, name: &str) {
|
||||
self.progress_update(folder_id, |p| p.current = name.to_string());
|
||||
}
|
||||
|
||||
/// Note that one queued item finished, whether it succeeded or not.
|
||||
pub(crate) fn progress_finished(&self, folder_id: i64) {
|
||||
self.progress_update(folder_id, |p| {
|
||||
p.done += 1;
|
||||
p.current.clear();
|
||||
});
|
||||
}
|
||||
|
||||
/// Stop tracking a pass — no progress is reported for the folder until the
|
||||
/// next [`progress_begin`](Self::progress_begin).
|
||||
pub(crate) fn progress_end(&self, folder_id: i64) {
|
||||
self.sync_progress.lock().remove(&folder_id);
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_virtual_root_in_listing(
|
||||
@@ -6384,23 +6268,6 @@ fn public_link_info(link: proton_drive_rs::PublicLink) -> PublicLinkInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a `volume~link` uid display string back into a [`NodeUid`]. Front-ends
|
||||
/// receive uids as strings over the control socket and pass them back verbatim.
|
||||
pub(crate) fn parse_uid(s: &str) -> Option<NodeUid> {
|
||||
let (vol, link) = s.split_once('~')?;
|
||||
if vol.is_empty() || link.is_empty() || link.contains('~') {
|
||||
return None;
|
||||
}
|
||||
Some(NodeUid::new(VolumeId::from(vol), LinkId::from(link)))
|
||||
}
|
||||
/// Current wall-clock time as epoch seconds (0 if the clock is before the epoch).
|
||||
fn now_secs() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Current wall-clock time as epoch milliseconds, the resolution `pending_op`
|
||||
/// timestamps and backoff deadlines are kept in.
|
||||
fn now_millis() -> i64 {
|
||||
@@ -6592,22 +6459,6 @@ fn sync_folder_info(
|
||||
}
|
||||
}
|
||||
|
||||
/// A coarse MIME type guessed from a file name's extension; Proton stores this
|
||||
/// on the node but an exact value is not required for correctness.
|
||||
fn media_type_for(name: &str) -> &'static str {
|
||||
let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase());
|
||||
match ext.as_deref() {
|
||||
Some("txt" | "md" | "log") => "text/plain",
|
||||
Some("png") => "image/png",
|
||||
Some("jpg" | "jpeg") => "image/jpeg",
|
||||
Some("gif") => "image/gif",
|
||||
Some("pdf") => "application/pdf",
|
||||
Some("json") => "application/json",
|
||||
Some("html" | "htm") => "text/html",
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
}
|
||||
|
||||
/// The plaintext size, in bytes, that a node reports.
|
||||
/// Overwrite each file node's `claimed_size` with the optimistic size of its
|
||||
/// queued write, where it has one. Folders and nodes with nothing queued are
|
||||
@@ -7062,16 +6913,6 @@ fn expand_restore(
|
||||
waves
|
||||
}
|
||||
|
||||
/// The plaintext content SHA-1 of a file node, if its active revision carried one.
|
||||
/// A download-free content fingerprint the conflict sweep uses to prove two files
|
||||
/// hold identical bytes before it removes one.
|
||||
fn node_content_sha1(node: &Node) -> Option<String> {
|
||||
match &node.kind {
|
||||
NodeKind::Folder => None,
|
||||
NodeKind::File { content_sha1, .. } => content_sha1.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `"1 file"` / `"3 files"` — a count with a correctly pluralised noun, for
|
||||
/// human-readable activity-log lines.
|
||||
fn count_noun(n: usize, one: &str, many: &str) -> String {
|
||||
@@ -7127,22 +6968,6 @@ fn fuse_name(name: &OsStr) -> Result<String, Errno> {
|
||||
name.to_str().map(str::to_owned).ok_or(Errno::EILSEQ)
|
||||
}
|
||||
|
||||
/// Whether a decrypted remote name can stand as one local path component.
|
||||
///
|
||||
/// Drive checks names only when a client creates or renames a node, and only
|
||||
/// for length, so a name made by another client, or by a server that should
|
||||
/// not be trusted, can hold anything. Joined onto a local path, a `/` or a `..`
|
||||
/// in it walks out of the folder it belongs to, and the mirror engine would
|
||||
/// then write or delete outside the sync root. In the mount, the kernel fails
|
||||
/// the whole listing with EIO on a single such name (`docs/BUGS.md` B215).
|
||||
pub(crate) fn remote_name_is_safe(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& name != "."
|
||||
&& name != ".."
|
||||
&& name.len() <= 255
|
||||
&& !name.contains(['/', '\0'])
|
||||
}
|
||||
|
||||
fn node_visible(node: &Node, folder_uid: &NodeUid, hidden: &HashSet<NodeUid>) -> bool {
|
||||
if !remote_name_is_safe(&node.name) {
|
||||
warn!(uid = %node.uid, "a remote name cannot be a local file name; leaving it out");
|
||||
|
||||
@@ -491,6 +491,25 @@ pub(crate) fn mount_with(
|
||||
let gallery_dir = control_socket.with_file_name("gallery-catalog");
|
||||
let gallery =
|
||||
gallery_session.map(|session| Arc::new(super::gallery::Gallery::new(gallery_dir, session)));
|
||||
let cache = Arc::new(cache);
|
||||
let shutdown = Arc::new(crate::shutdown::Shutdown::default());
|
||||
let transfers = TransferRegistry::new();
|
||||
let sync = sync::SyncParts {
|
||||
db: db.clone(),
|
||||
drive: drive.clone(),
|
||||
rt: rt.clone(),
|
||||
cache: cache.clone(),
|
||||
transfers: transfers.clone(),
|
||||
shutdown: shutdown.clone(),
|
||||
primary_root_uid: root.uid.clone(),
|
||||
progress: Arc::default(),
|
||||
engine: Arc::default(),
|
||||
tx: sync_tx,
|
||||
locks: Arc::default(),
|
||||
unscanned: Arc::default(),
|
||||
abandon: Arc::default(),
|
||||
events_read_at: Arc::new(AtomicI64::new(0)),
|
||||
};
|
||||
let core = Core {
|
||||
drive,
|
||||
drive_calls,
|
||||
@@ -505,7 +524,7 @@ pub(crate) fn mount_with(
|
||||
State::new(db.clone(), share_access),
|
||||
)),
|
||||
root: Arc::new(OnceLock::new()),
|
||||
cache: Arc::new(cache),
|
||||
cache,
|
||||
readers: Arc::new(Mutex::new(HashMap::new())),
|
||||
block_ring: Arc::new(Mutex::new(BlockRing::default())),
|
||||
block_flight: Arc::new(BlockFlight::default()),
|
||||
@@ -520,7 +539,6 @@ pub(crate) fn mount_with(
|
||||
online: Arc::new(AtomicBool::new(online)),
|
||||
link: Arc::new(link::Link::starting(start == Start::SessionExpired)),
|
||||
sync_paused_until: Arc::new(AtomicI64::new(paused_until)),
|
||||
events_read_at: Arc::new(AtomicI64::new(0)),
|
||||
pending: Arc::new(Mutex::new(HashMap::new())),
|
||||
hidden: Arc::new(Mutex::new(HashSet::new())),
|
||||
creating: Arc::new(Mutex::new(HashMap::new())),
|
||||
@@ -529,7 +547,7 @@ pub(crate) fn mount_with(
|
||||
unadopted: Arc::new(Mutex::new(HashMap::new())),
|
||||
drain_wake: Arc::new((Mutex::new(false), Condvar::new())),
|
||||
pin_work: Arc::new(Mutex::new(Default::default())),
|
||||
shutdown: Arc::new(crate::shutdown::Shutdown::default()),
|
||||
shutdown,
|
||||
upload_times: Arc::new(Mutex::new(HashMap::new())),
|
||||
upload_cancel: Arc::new(Mutex::new(HashMap::new())),
|
||||
landing_uploads: Arc::new(AtomicU64::new(0)),
|
||||
@@ -559,17 +577,12 @@ pub(crate) fn mount_with(
|
||||
size_waiters: Arc::new(Default::default()),
|
||||
notifier: Arc::new(OnceLock::new()),
|
||||
session_live: Arc::new(AtomicBool::new(false)),
|
||||
transfers: TransferRegistry::new(),
|
||||
transfers,
|
||||
sync,
|
||||
events: Arc::new(Default::default()),
|
||||
indexing: Arc::new(AtomicBool::new(false)),
|
||||
sync_progress: Arc::new(Mutex::new(HashMap::new())),
|
||||
sync_engine: Arc::default(),
|
||||
pending_probe: Arc::default(),
|
||||
sync_tx,
|
||||
mounts: Arc::new(Mutex::new(SecondaryMountRegistry::default())),
|
||||
sync_locks: Arc::new(Mutex::new(HashMap::new())),
|
||||
sync_unscanned: Arc::new(Mutex::new(HashMap::new())),
|
||||
sync_abandon: Arc::default(),
|
||||
states: Arc::new(StateRegistry::default()),
|
||||
};
|
||||
// Before anything can queue work against it: the drain thread below reaches
|
||||
@@ -608,7 +621,7 @@ pub(crate) fn mount_with(
|
||||
|
||||
// Start the folder-sync engine. It watches every mirror folder, polls the
|
||||
// remotes, and reconciles on its own thread — never in front of a FUSE call.
|
||||
workers.extend(sync::spawn(core.clone(), sync_rx));
|
||||
workers.extend(sync::spawn(core.syncer(), sync_rx));
|
||||
// A timed pause persisted by an earlier run still has to end on time.
|
||||
if pause::paused_at(paused_until, now_secs()) && paused_until != pause::PAUSED_INDEFINITELY {
|
||||
core.arm_pause_timer(paused_until);
|
||||
@@ -991,7 +1004,7 @@ fn halt_workers(core: &Core, control_socket: &Path, workers: Vec<std::thread::Jo
|
||||
gallery.cancel();
|
||||
}
|
||||
core.wake_drain();
|
||||
let _ = core.sync_tx.send(sync::SyncMsg::Stop);
|
||||
let _ = core.sync.tx.send(sync::SyncMsg::Stop);
|
||||
// Connect while the socket still exists — that is the whole point of the
|
||||
// poke — then unlink it so nothing else can arrive behind us. The listener
|
||||
// re-checks the flag after every accept, so even a connection that races the
|
||||
|
||||
@@ -1157,10 +1157,7 @@ impl Core {
|
||||
path: PathBuf,
|
||||
name: String,
|
||||
) -> Vec<Thumbnail> {
|
||||
let staging_dir = self.cache.raw_thumbnail_staging_dir().to_path_buf();
|
||||
tokio::task::spawn_blocking(move || upload_thumbnails(&path, &name, &staging_dir))
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
thumbnails_for_upload(&self.cache, path, name).await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -3645,3 +3642,16 @@ mod thumb_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The thumbnails to upload with the file at `path`, made off the async
|
||||
/// runtime. Empty when the file is not an image or a video.
|
||||
pub(crate) async fn thumbnails_for_upload(
|
||||
cache: &pdfs_store::cache::ContentCache,
|
||||
path: PathBuf,
|
||||
name: String,
|
||||
) -> Vec<Thumbnail> {
|
||||
let staging_dir = cache.raw_thumbnail_staging_dir().to_path_buf();
|
||||
tokio::task::spawn_blocking(move || upload_thumbnails(&path, &name, &staging_dir))
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
@@ -453,7 +453,7 @@ impl Core {
|
||||
Err(e) => {
|
||||
// The folders restored before this one still need their
|
||||
// watches.
|
||||
let _ = self.sync_tx.send(sync::SyncMsg::Rewatch);
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
|
||||
return Err(CoreError::internal(format!("db: {e:?}")));
|
||||
}
|
||||
};
|
||||
@@ -463,11 +463,11 @@ impl Core {
|
||||
if mode == MountMode::OnDemand {
|
||||
let _ = self.request_sync_folder_mode(id, "ondemand");
|
||||
}
|
||||
let _ = self.sync_tx.send(sync::SyncMsg::Reconcile(id));
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
|
||||
roots.push(local);
|
||||
restored += 1;
|
||||
}
|
||||
let _ = self.sync_tx.send(sync::SyncMsg::Rewatch);
|
||||
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
|
||||
|
||||
// The reply is gone once the app has shown it; the log keeps why.
|
||||
for reason in &skipped {
|
||||
|
||||
@@ -200,7 +200,7 @@ impl Core {
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
let locks: Vec<Arc<pdfs_core::lockrank::Ranked<()>>> =
|
||||
ids.iter().map(|&id| self.sync_lock(id)).collect();
|
||||
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(|| {
|
||||
|
||||
@@ -3712,6 +3712,51 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run explicitly on an isolated fake Drive"]
|
||||
fn a_synced_folder_trashed_on_drive_does_not_block_attaching_another() {
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("attach-past-trash");
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
|
||||
for folder in ["Gone", "Next", "Parent", "Parent/Old"] {
|
||||
std::fs::create_dir(daemon.mountpoint.join(folder)).unwrap();
|
||||
}
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
daemon.pending().is_ok_and(|items| items.is_empty())
|
||||
&& drive.lookup("Parent/Old").is_some()
|
||||
&& drive.lookup("Next").is_some()
|
||||
}));
|
||||
let attach = |local: &str, remote: &str| {
|
||||
let path = dir.join(local);
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
daemon.request(&Request::AttachSyncFolder {
|
||||
local_path: path.to_str().unwrap().into(),
|
||||
remote_path: remote.into(),
|
||||
})
|
||||
};
|
||||
attach("gone", "Gone").unwrap();
|
||||
attach("old", "Parent/Old").unwrap();
|
||||
drive.device().trash("Gone");
|
||||
drive.device().trash("Parent/Old");
|
||||
// Reads lag the server: wait until this client sees both in the trash.
|
||||
assert!(wait_until(Duration::from_secs(60), || {
|
||||
!daemon.mountpoint.join("Gone").exists()
|
||||
&& !daemon.mountpoint.join("Parent/Old").exists()
|
||||
}));
|
||||
|
||||
// B299: the first synced folder in the trash failed every later attach
|
||||
// with "remote sync folder is in the trash".
|
||||
attach("next", "Next").expect("a trashed synced folder blocked an unrelated attach");
|
||||
// Its place on Drive still counts: the folder above it overlaps it.
|
||||
assert!(
|
||||
attach("parent", "Parent").is_err(),
|
||||
"attached a folder above a synced folder in the trash"
|
||||
);
|
||||
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn attached_my_files(daemon: &Daemon, drive: &FakeDrive, local: &Path) -> i64 {
|
||||
std::fs::create_dir(daemon.mountpoint.join("Work")).unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
|
||||
@@ -39,13 +39,14 @@ use sha1::{Digest as _, Sha1};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use crate::transfers::{CountingWriter, OwnedCountingReader};
|
||||
use crate::{Core, now_secs, parse_uid};
|
||||
use crate::{now_secs, parse_uid};
|
||||
use pdfs_core::batch;
|
||||
use pdfs_core::control::{ActivityKind, TransferDirection};
|
||||
use pdfs_core::syncignore::IgnoreRules;
|
||||
use pdfs_store::db::{SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
|
||||
|
||||
mod engine;
|
||||
mod host;
|
||||
mod local_scan;
|
||||
pub(crate) use engine::SYNC_CONCURRENCY;
|
||||
pub(crate) use engine::{EngineHealth, SyncMsg, spawn};
|
||||
@@ -53,6 +54,7 @@ pub(crate) use engine::{EngineHealth, SyncMsg, spawn};
|
||||
use engine::{Running, burst_order, keep_wanted, smallest_first};
|
||||
#[cfg(test)]
|
||||
use engine::{classify, event_target, settle_with};
|
||||
pub(crate) use host::{SyncParts, Syncer};
|
||||
#[cfg(test)]
|
||||
use local_scan::is_write_mode;
|
||||
use local_scan::open_for_write_set;
|
||||
@@ -78,7 +80,7 @@ use trace::{Call, Count, Phase};
|
||||
/// nothing, so the journal says where a slow engine spends its time.
|
||||
const SLOW_PASS: Duration = Duration::from_secs(30);
|
||||
|
||||
impl Core {
|
||||
impl Syncer {
|
||||
/// Reconcile one synced folder, then apply any mode switch queued while it was
|
||||
/// busy. Both halves live here because the switch has to happen with the pass
|
||||
/// finished and its lock released, and the engine thread is the only place that
|
||||
@@ -107,7 +109,7 @@ impl Core {
|
||||
}
|
||||
// Hold the folder's lock for the whole pass so a mode switch can't evict the
|
||||
// local tree (and mount FUSE over it) while we walk and upload it.
|
||||
let lock = self.sync_lock(folder.id);
|
||||
let lock = self.lock(folder.id);
|
||||
let waited = Instant::now();
|
||||
let _guard = lock.lock();
|
||||
self.trace_phase(Phase::LockWait, waited.elapsed());
|
||||
@@ -195,7 +197,7 @@ impl Core {
|
||||
result => result,
|
||||
}
|
||||
};
|
||||
let progress = self.sync_progress.lock().get(&folder.id).cloned();
|
||||
let progress = self.progress.lock().get(&folder.id).cloned();
|
||||
self.progress_end(folder.id);
|
||||
self.log_trace(folder, &result, started.elapsed());
|
||||
match result {
|
||||
@@ -311,7 +313,7 @@ impl Core {
|
||||
}
|
||||
// A removal that gave up waiting leaves its request behind; the next
|
||||
// pass runs whole unless the removal is asked for again.
|
||||
self.sync_abandon.lock().remove(&folder.id);
|
||||
self.abandon.lock().remove(&folder.id);
|
||||
}
|
||||
|
||||
/// End the running pass's trace and put it in the journal: at info for
|
||||
@@ -329,7 +331,7 @@ impl Core {
|
||||
Err(PassAbort::Abandoned) => "abandoned",
|
||||
Err(PassAbort::Failed(_)) => "failed",
|
||||
};
|
||||
let Some(trace) = self.sync_engine.end_trace(how) else {
|
||||
let Some(trace) = self.engine.end_trace(how) else {
|
||||
return;
|
||||
};
|
||||
if how != "finished" || folder.last_sync == 0 || elapsed >= SLOW_PASS {
|
||||
@@ -341,17 +343,17 @@ impl Core {
|
||||
|
||||
/// Add `took` to a stage of the running pass's trace.
|
||||
fn trace_phase(&self, phase: Phase, took: Duration) {
|
||||
self.sync_engine.trace(|t| t.phase(phase, took));
|
||||
self.engine.trace(|t| t.phase(phase, took));
|
||||
}
|
||||
|
||||
/// Add one call that took `took` to the running pass's trace.
|
||||
fn trace_call(&self, call: Call, took: Duration) {
|
||||
self.sync_engine.trace(|t| t.call(call, took));
|
||||
self.engine.trace(|t| t.call(call, took));
|
||||
}
|
||||
|
||||
/// Add `n` to a counter of the running pass's trace.
|
||||
fn trace_count(&self, count: Count, n: usize) {
|
||||
self.sync_engine.trace(|t| t.count(count, n));
|
||||
self.engine.trace(|t| t.count(count, n));
|
||||
}
|
||||
|
||||
/// Tell the activity feed what a pass over this folder had to leave out
|
||||
@@ -362,7 +364,7 @@ impl Core {
|
||||
/// (B196).
|
||||
fn report_unscanned(&self, folder_id: i64, name: &str, unscanned: &[String]) {
|
||||
let previous = {
|
||||
let mut last = self.sync_unscanned.lock();
|
||||
let mut last = self.unscanned.lock();
|
||||
if unscanned.is_empty() {
|
||||
last.remove(&folder_id)
|
||||
} else {
|
||||
@@ -1671,8 +1673,7 @@ impl Core {
|
||||
let stale: HashSet<String> = stale.iter().map(|u| u.to_string()).collect();
|
||||
self.record_revisions(folder_id, prefix, &nodes, &sized, baseline);
|
||||
self.trace_count(Count::Nodes, nodes.len());
|
||||
self.sync_engine
|
||||
.trace(|t| t.listing(prefix, listing.elapsed()));
|
||||
self.engine.trace(|t| t.listing(prefix, listing.elapsed()));
|
||||
|
||||
for node in nodes {
|
||||
if node.trashed {
|
||||
@@ -1852,7 +1853,7 @@ impl Core {
|
||||
|
||||
/// Whether a removal of `folder_id` is waiting for its running pass.
|
||||
fn pass_abandoned(&self, folder_id: i64) -> bool {
|
||||
self.sync_abandon.lock().contains(&folder_id)
|
||||
self.abandon.lock().contains(&folder_id)
|
||||
}
|
||||
|
||||
/// Apply one [`Pending`] op (async, so it can run concurrently in a batch),
|
||||
@@ -2030,9 +2031,8 @@ impl Core {
|
||||
// Taken from the descriptor being streamed, so it names the content that
|
||||
// actually goes up rather than whatever is at the path when we finish.
|
||||
let streamed = LocalSig::from(&meta);
|
||||
let thumbnails = self
|
||||
.upload_thumbnails_async(path.clone(), name.to_string())
|
||||
.await;
|
||||
let thumbnails =
|
||||
crate::photos::thumbnails_for_upload(&self.cache, path.clone(), name.to_string()).await;
|
||||
// Count the bytes as they are read, so this upload shows up in
|
||||
// `GetQueueStatus` next to a manual one. The uid isn't known until the
|
||||
// draft is sealed, so the transfer registers without one.
|
||||
@@ -2114,9 +2114,12 @@ impl Core {
|
||||
let meta = file.metadata().map_err(|e| format!("stat {rel}: {e}"))?;
|
||||
let mtime = system_mtime(&meta);
|
||||
let streamed = LocalSig::from(&meta);
|
||||
let thumbnails = self
|
||||
.upload_thumbnails_async(path.clone(), base_name(rel).to_string())
|
||||
.await;
|
||||
let thumbnails = crate::photos::thumbnails_for_upload(
|
||||
&self.cache,
|
||||
path.clone(),
|
||||
base_name(rel).to_string(),
|
||||
)
|
||||
.await;
|
||||
let (reader, sent) = Sha1Tap::new(OwnedCountingReader::new(
|
||||
file,
|
||||
self.transfers.begin(
|
||||
|
||||
@@ -51,8 +51,8 @@ pub(crate) enum SyncMsg {
|
||||
|
||||
/// Start the sync engine: a control thread that owns the filesystem watcher and
|
||||
/// serialises reconcile passes, plus a periodic poll thread. The engine receives
|
||||
/// on `rx`; senders live in [`Core::sync_tx`].
|
||||
pub(crate) fn spawn(core: Core, rx: Receiver<SyncMsg>) -> Option<std::thread::JoinHandle<()>> {
|
||||
/// on `rx`; senders live in [`SyncParts::tx`].
|
||||
pub(crate) fn spawn(core: Syncer, rx: Receiver<SyncMsg>) -> Option<std::thread::JoinHandle<()>> {
|
||||
match std::thread::Builder::new()
|
||||
.name("pdfs-sync".into())
|
||||
.spawn(move || engine_loop(core, rx))
|
||||
@@ -204,9 +204,9 @@ impl Drop for Running<'_> {
|
||||
|
||||
/// One folder's pass, contained: a panic in it sets the folder to `error` and
|
||||
/// leaves the engine running for the next one.
|
||||
fn run_pass(core: &Core, folder: &StoredSyncFolder) {
|
||||
fn run_pass(core: &Syncer, folder: &StoredSyncFolder) {
|
||||
if core
|
||||
.sync_engine
|
||||
.engine
|
||||
.contain(folder.id, || core.reconcile_folder(folder))
|
||||
{
|
||||
return;
|
||||
@@ -230,7 +230,7 @@ fn run_pass(core: &Core, 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: &Core, id: i64) {
|
||||
fn run_pass_by_id(core: &Syncer, id: i64) {
|
||||
match core.db.sync_folder_get(id) {
|
||||
Ok(Some(folder)) => run_pass(core, &folder),
|
||||
Ok(None) => debug!(id, "sync: folder removed before its pass; skipping"),
|
||||
@@ -239,8 +239,8 @@ fn run_pass_by_id(core: &Core, id: i64) {
|
||||
}
|
||||
|
||||
/// The engine control loop. Single-threaded so reconcile passes never overlap.
|
||||
fn engine_loop(core: Core, rx: Receiver<SyncMsg>) {
|
||||
let health = core.sync_engine.clone();
|
||||
fn engine_loop(core: Syncer, rx: Receiver<SyncMsg>) {
|
||||
let health = core.engine.clone();
|
||||
let _running = Running::start(&health);
|
||||
// No pass runs before this thread starts one, so a folder in `syncing` was
|
||||
// left there by a daemon that was killed mid-pass. It would read as busy
|
||||
@@ -257,7 +257,7 @@ fn engine_loop(core: Core, rx: Receiver<SyncMsg>) {
|
||||
// path can be resolved back to the folder it belongs to.
|
||||
let watched: Arc<Mutex<Vec<(PathBuf, i64)>>> = Arc::new(Mutex::new(Vec::new()));
|
||||
|
||||
let tx_events = core.sync_tx.clone();
|
||||
let tx_events = core.tx.clone();
|
||||
let watched_events = watched.clone();
|
||||
let handler = move |res: notify::Result<notify::Event>| {
|
||||
let event = match res {
|
||||
@@ -291,7 +291,7 @@ fn engine_loop(core: Core, rx: Receiver<SyncMsg>) {
|
||||
|
||||
// Periodic remote poll.
|
||||
{
|
||||
let tx = core.sync_tx.clone();
|
||||
let tx = core.tx.clone();
|
||||
let shutdown = core.shutdown.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("pdfs-sync-poll".into())
|
||||
@@ -334,9 +334,9 @@ fn engine_loop(core: Core, rx: Receiver<SyncMsg>) {
|
||||
}
|
||||
|
||||
/// Fallback loop when no filesystem watcher could be created: poll + SyncNow only.
|
||||
fn poll_only_loop(core: &Core, rx: Receiver<SyncMsg>) {
|
||||
fn poll_only_loop(core: &Syncer, rx: Receiver<SyncMsg>) {
|
||||
{
|
||||
let tx = core.sync_tx.clone();
|
||||
let tx = core.tx.clone();
|
||||
let shutdown = core.shutdown.clone();
|
||||
std::thread::spawn(move || {
|
||||
while shutdown.sleep(POLL_INTERVAL) {
|
||||
@@ -371,7 +371,7 @@ fn poll_only_loop(core: &Core, rx: Receiver<SyncMsg>) {
|
||||
/// Skipped while sync is paused, and cut short when a pause lands between
|
||||
/// passes: the resume sends a fresh [`SyncMsg::ReconcileAll`], which walks
|
||||
/// everything the watcher reported meanwhile.
|
||||
fn run_burst(core: &Core, ids: &HashSet<i64>, all: bool) {
|
||||
fn run_burst(core: &Syncer, ids: &HashSet<i64>, all: bool) {
|
||||
if core.sync_paused() {
|
||||
debug!("sync: paused, skipping reconcile");
|
||||
return;
|
||||
@@ -534,7 +534,7 @@ pub(super) fn event_target(watched: &[(PathBuf, i64)], paths: &[PathBuf]) -> Syn
|
||||
/// callback takes the same lock, and a backend that hands a watch request to
|
||||
/// its event thread and waits for the answer would deadlock against it.
|
||||
fn rewatch(
|
||||
core: &Core,
|
||||
core: &Syncer,
|
||||
watcher: &mut notify::RecommendedWatcher,
|
||||
watched: &Mutex<Vec<(PathBuf, i64)>>,
|
||||
) -> bool {
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
//! What the sync engine owns, and the narrow port through which it reaches the
|
||||
//! rest of the daemon.
|
||||
//!
|
||||
//! The engine used to be a set of methods on `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
|
||||
//! needs from the daemon goes through [`SyncHost`]. A [`Syncer`] is the two
|
||||
//! together: the value the engine's methods run on.
|
||||
//!
|
||||
//! This is the first half of moving the engine into `pdfs-sync`
|
||||
//! (`docs/ARCHITECTURE.md`, step 3).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ops::Deref;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicI64;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::CoreResult;
|
||||
use pdfs_core::control::{ActivityKind, SyncPhase, SyncProgress};
|
||||
use pdfs_core::lockrank::{Rank, Ranked};
|
||||
use pdfs_drive::DriveApi;
|
||||
use pdfs_store::cache::ContentCache;
|
||||
use pdfs_store::db::Db;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use tracing::info;
|
||||
|
||||
use super::{EngineHealth, SyncMsg};
|
||||
use crate::Core;
|
||||
use crate::shutdown::Shutdown;
|
||||
use crate::transfers::TransferRegistry;
|
||||
|
||||
/// What the sync engine needs from the daemon that it does not own.
|
||||
pub(crate) trait SyncHost: Send + Sync {
|
||||
/// Append an entry to the activity feed.
|
||||
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool);
|
||||
/// Forget the cached listing of `parent`, after a pass changed it on Drive.
|
||||
fn invalidate_children_of(&self, parent: &NodeUid);
|
||||
/// The folders above `start` on Drive, nearest first, read from the server.
|
||||
fn attach_ancestors(&self, start: &NodeUid) -> CoreResult<Vec<NodeUid>>;
|
||||
/// Apply a mode switch queued for synced folder `id`, if it can take it now.
|
||||
fn settle_pending_mode(&self, id: i64);
|
||||
/// Whether the user has paused all syncing.
|
||||
fn sync_paused(&self) -> bool;
|
||||
/// Whether the user has paused synced folder `id`.
|
||||
fn sync_folder_paused(&self, id: i64) -> bool;
|
||||
}
|
||||
|
||||
/// The sync engine's state, and the daemon handles it uses.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct SyncParts {
|
||||
pub(crate) db: Arc<Db>,
|
||||
pub(crate) drive: Arc<dyn DriveApi>,
|
||||
pub(crate) rt: tokio::runtime::Handle,
|
||||
pub(crate) cache: Arc<ContentCache>,
|
||||
pub(crate) transfers: Arc<TransferRegistry>,
|
||||
pub(crate) shutdown: Arc<Shutdown>,
|
||||
/// My files' root: an attached folder must stay below it.
|
||||
pub(crate) primary_root_uid: NodeUid,
|
||||
|
||||
/// Live per-folder progress, keyed by sync-folder id, so `ListSyncFolders`
|
||||
/// can say what a pass is doing rather than just "syncing". An entry exists
|
||||
/// only while that folder's pass is running.
|
||||
pub(crate) progress: Arc<Mutex<HashMap<i64, SyncProgress>>>,
|
||||
/// Whether the engine is alive, and which pass it is on.
|
||||
pub(crate) engine: Arc<EngineHealth>,
|
||||
/// Channel to the engine: nudges it to reconcile a folder, reconcile
|
||||
/// everything, or re-scan its watch set.
|
||||
pub(crate) tx: std::sync::mpsc::Sender<SyncMsg>,
|
||||
/// Per-folder locks, held for a whole pass and for a whole mode switch. A
|
||||
/// `mirror→ondemand` flip evicts the local tree and mounts FUSE over it, so
|
||||
/// it must never overlap a pass that is walking and uploading that tree.
|
||||
pub(crate) locks: Arc<Mutex<HashMap<i64, Arc<Ranked<()>>>>>,
|
||||
/// Per-folder paths the last pass could not read, so the activity feed
|
||||
/// says so when the set changes rather than on every poll (B196).
|
||||
pub(crate) unscanned: Arc<Mutex<HashMap<i64, Vec<String>>>>,
|
||||
/// Folders whose running pass should stop at its next checkpoint, because
|
||||
/// a removal is waiting for the folder's lock (B294).
|
||||
pub(crate) abandon: Arc<Mutex<HashSet<i64>>>,
|
||||
/// When the Drive event feed was last read, epoch seconds; 0 before the
|
||||
/// first read. A pass trusts the feed's dirty folders only while it is
|
||||
/// being read.
|
||||
pub(crate) events_read_at: Arc<AtomicI64>,
|
||||
}
|
||||
|
||||
impl SyncParts {
|
||||
/// The lock guarding synced folder `id` against a pass and a mode switch
|
||||
/// running at once.
|
||||
pub(crate) fn lock(&self, id: i64) -> Arc<Ranked<()>> {
|
||||
self.locks
|
||||
.lock()
|
||||
.entry(id)
|
||||
.or_insert_with(|| Arc::new(Ranked::new(Rank::SyncFolder, ())))
|
||||
.clone()
|
||||
}
|
||||
|
||||
// ---- live progress ----------------------------------------------------
|
||||
|
||||
/// Start tracking a pass over `folder_id`, in [`SyncPhase::Scanning`].
|
||||
pub(crate) fn progress_begin(&self, folder_id: i64) {
|
||||
self.progress.lock().insert(
|
||||
folder_id,
|
||||
SyncProgress {
|
||||
phase: SyncPhase::Scanning,
|
||||
done: 0,
|
||||
total: 0,
|
||||
current: String::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Apply `f` to a folder's live progress, if a pass is running for it.
|
||||
fn progress_update(&self, folder_id: i64, f: impl FnOnce(&mut SyncProgress)) {
|
||||
let now = self.progress.lock().get_mut(&folder_id).map(|p| {
|
||||
f(p);
|
||||
(p.phase, p.done, p.total)
|
||||
});
|
||||
if let Some((folder, age)) = self.engine.moved()
|
||||
&& let Some((phase, done, total)) = now
|
||||
&& folder == folder_id
|
||||
{
|
||||
info!(
|
||||
id = folder,
|
||||
?phase,
|
||||
done,
|
||||
total,
|
||||
elapsed_s = age.as_secs(),
|
||||
"sync: pass still running"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the number of items the scan expects to check, from the size of the
|
||||
/// last pass's baseline. Only an estimate — the folder may have grown since —
|
||||
/// but it turns the scan from an indeterminate pulse into a bar that moves,
|
||||
/// which is the difference between "it's stuck" and "it's working" on a folder
|
||||
/// whose walk takes minutes.
|
||||
pub(crate) fn progress_scan_total(&self, folder_id: i64, n: usize) {
|
||||
self.progress_update(folder_id, |p| p.total = n);
|
||||
}
|
||||
|
||||
/// Note that the scan has checked one more item, named `name`.
|
||||
pub(crate) fn progress_scanned(&self, folder_id: i64, name: &str) {
|
||||
self.progress_update(folder_id, |p| {
|
||||
p.done += 1;
|
||||
p.current = name.to_string();
|
||||
});
|
||||
}
|
||||
|
||||
/// Note that the scan has checked `n` more items at once, read back from
|
||||
/// a walk an earlier pass saved.
|
||||
pub(crate) fn progress_scanned_many(&self, folder_id: i64, n: usize) {
|
||||
self.progress_update(folder_id, |p| p.done += n);
|
||||
}
|
||||
|
||||
/// Note that `n` more items have been queued for this pass, and that it has
|
||||
/// moved on from scanning to applying the diff. The scan's counts are dropped:
|
||||
/// they measured a different quantity (items checked, not items to apply), so
|
||||
/// carrying them over would start the applying bar at a meaningless fraction.
|
||||
pub(crate) fn progress_queued(&self, folder_id: i64, n: usize) {
|
||||
self.progress_update(folder_id, |p| {
|
||||
if p.phase == SyncPhase::Scanning {
|
||||
p.phase = SyncPhase::Applying;
|
||||
p.done = 0;
|
||||
p.total = 0;
|
||||
p.current.clear();
|
||||
}
|
||||
p.total += n;
|
||||
});
|
||||
}
|
||||
|
||||
/// Note that work has started on `name` (shown as the pass's current item).
|
||||
pub(crate) fn progress_started(&self, folder_id: i64, name: &str) {
|
||||
self.progress_update(folder_id, |p| p.current = name.to_string());
|
||||
}
|
||||
|
||||
/// Note that one queued item finished, whether it succeeded or not.
|
||||
pub(crate) fn progress_finished(&self, folder_id: i64) {
|
||||
self.progress_update(folder_id, |p| {
|
||||
p.done += 1;
|
||||
p.current.clear();
|
||||
});
|
||||
}
|
||||
|
||||
/// Stop tracking a pass — no progress is reported for the folder until the
|
||||
/// next [`progress_begin`](Self::progress_begin).
|
||||
pub(crate) fn progress_end(&self, folder_id: i64) {
|
||||
self.progress.lock().remove(&folder_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// The sync engine's state and its port to the daemon: what a pass runs on.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Syncer {
|
||||
parts: SyncParts,
|
||||
host: Arc<dyn SyncHost>,
|
||||
}
|
||||
|
||||
impl Deref for Syncer {
|
||||
type Target = SyncParts;
|
||||
|
||||
fn deref(&self) -> &SyncParts {
|
||||
&self.parts
|
||||
}
|
||||
}
|
||||
|
||||
impl Syncer {
|
||||
pub(crate) fn new(parts: SyncParts, host: Arc<dyn SyncHost>) -> Self {
|
||||
Self { parts, host }
|
||||
}
|
||||
|
||||
pub(crate) fn log_activity(
|
||||
&self,
|
||||
kind: ActivityKind,
|
||||
target: impl Into<String>,
|
||||
detail: impl std::fmt::Display,
|
||||
ok: bool,
|
||||
) {
|
||||
self.host
|
||||
.log_activity(kind, target.into(), detail.to_string(), ok);
|
||||
}
|
||||
|
||||
pub(crate) fn invalidate_children_of(&self, parent: &NodeUid) {
|
||||
self.host.invalidate_children_of(parent);
|
||||
}
|
||||
|
||||
pub(crate) fn attach_ancestors(&self, start: &NodeUid) -> CoreResult<Vec<NodeUid>> {
|
||||
self.host.attach_ancestors(start)
|
||||
}
|
||||
|
||||
pub(crate) fn settle_pending_mode(&self, id: i64) {
|
||||
self.host.settle_pending_mode(id);
|
||||
}
|
||||
|
||||
pub(crate) fn sync_paused(&self) -> bool {
|
||||
self.host.sync_paused()
|
||||
}
|
||||
|
||||
pub(crate) fn sync_folder_paused(&self, id: i64) -> bool {
|
||||
self.host.sync_folder_paused(id)
|
||||
}
|
||||
}
|
||||
|
||||
impl SyncHost for Core {
|
||||
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool) {
|
||||
Core::log_activity(self, kind, target, detail, ok);
|
||||
}
|
||||
|
||||
fn invalidate_children_of(&self, parent: &NodeUid) {
|
||||
Core::invalidate_children_of(self, parent);
|
||||
}
|
||||
|
||||
fn attach_ancestors(&self, start: &NodeUid) -> pdfs_core::CoreResult<Vec<NodeUid>> {
|
||||
Core::attach_ancestors(self, start)
|
||||
}
|
||||
|
||||
fn settle_pending_mode(&self, id: i64) {
|
||||
Core::settle_pending_mode(self, id);
|
||||
}
|
||||
|
||||
fn sync_paused(&self) -> bool {
|
||||
Core::sync_paused(self)
|
||||
}
|
||||
|
||||
fn sync_folder_paused(&self, id: i64) -> bool {
|
||||
Core::sync_folder_paused(self, id)
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// The sync engine, with this daemon as its host.
|
||||
pub(crate) fn syncer(&self) -> Syncer {
|
||||
Syncer::new(self.sync.clone(), Arc::new(self.clone()))
|
||||
}
|
||||
}
|
||||
@@ -43,9 +43,10 @@ use pdfs_core::{CoreError, CoreResult};
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use proton_drive_rs::{PhotoLocation, PhotoTag, PhotoTagsUpdate, PhotoUploadMetadata};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha1::{Digest, Sha1};
|
||||
use tracing::{info, warn};
|
||||
|
||||
pub(crate) use pdfs_drive::digest::{hex_lower, sha1_of};
|
||||
|
||||
use super::Core;
|
||||
use crate::photos::can_make_thumbnail;
|
||||
use crate::transfers::CountingReader;
|
||||
@@ -1234,31 +1235,6 @@ fn open_archive(
|
||||
.map_err(|e| CoreError::invalid(format!("{} is not a readable zip: {e}", path.display())))
|
||||
}
|
||||
|
||||
/// The lowercase-hex SHA-1 of everything `reader` yields — the digest Proton's
|
||||
/// photo duplicate detection is keyed on.
|
||||
pub(crate) fn sha1_of(reader: &mut (dyn Read + Send)) -> CoreResult<String> {
|
||||
let mut hasher = Sha1::new();
|
||||
let mut buffer = vec![0u8; 256 * 1024];
|
||||
loop {
|
||||
let read = reader
|
||||
.read(&mut buffer)
|
||||
.map_err(|e| CoreError::invalid(format!("read failed: {e}")))?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buffer[..read]);
|
||||
}
|
||||
Ok(hex_lower(&hasher.finalize()))
|
||||
}
|
||||
|
||||
pub(crate) fn hex_lower(bytes: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(bytes.len() * 2);
|
||||
for byte in bytes {
|
||||
out.push_str(&format!("{byte:02x}"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -47,8 +47,11 @@ graph TD
|
||||
|
||||
| Crate | Holds |
|
||||
|---|---|
|
||||
| [`pdfs-core`](../crates/pdfs-core) | Authentication and keyring (`auth`), configuration and directories (`config`), the SQLite schema and queries (`db/`), the content cache (`cache`), the control protocol (`control`), search scoring, ignore rules, Google Takeout parsing, the machine profile |
|
||||
| [`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 sync engine (`sync`, `sync/`), moves between locations (`relocate`), control handlers (`control`), push events (`events`), photos, sharing, devices, the supervisor, and the simulation tests (`sim/`) |
|
||||
| [`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 |
|
||||
| [`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 sync planner, the pass model and the pass trace: the parts of the sync engine with no I/O |
|
||||
| [`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 sync engine (`sync`, `sync/`; its own state in `SyncParts`, its calls into the daemon through `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/` |
|
||||
|
||||
|
||||
@@ -108,6 +108,7 @@ a live account since.
|
||||
|
||||
| Entry | Title |
|
||||
|---|---|
|
||||
| [B299](#b299--a-synced-folder-in-the-trash-blocks-attaching-any-other-folder) | A synced folder in the trash blocks attaching any other folder |
|
||||
| [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 |
|
||||
@@ -401,6 +402,30 @@ a live account since.
|
||||
|
||||
Newest first.
|
||||
|
||||
### B299 — A synced folder in the trash blocks attaching any other folder
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
|
||||
**Found:** 2026-11-26, by the live one-edit benchmark: a run cut short left its synced folder
|
||||
behind after the folder had been removed on Drive, and every later `pdfs sync attach` failed.
|
||||
|
||||
**Where:** `attach_sync_folder` in `crates/pdfs-fuse/src/attach.rs`
|
||||
|
||||
**Repro:** Attach a folder, then move its Drive folder to the trash (from the web or another
|
||||
client) without removing the synced folder. Attach any other folder: it fails with "remote sync
|
||||
folder is in the trash", which names neither folder. The simulation
|
||||
`a_synced_folder_trashed_on_drive_does_not_block_attaching_another` does this.
|
||||
|
||||
**Cause.** To refuse overlapping folders, attach walks each existing synced folder's ancestry on
|
||||
Drive, and that walk fails on a folder in the trash. The overlap check passed the failure on, so
|
||||
one dead synced folder failed every attach, whatever was being attached.
|
||||
|
||||
**Fix.** The overlap check walks through the trash: a trashed folder keeps its parent, so the
|
||||
check still refuses to attach a folder above it. A folder that no longer exists on Drive lies
|
||||
below nothing and is skipped. The new folder's own walk still refuses the trash.
|
||||
|
||||
**Verified:** `a_synced_folder_trashed_on_drive_does_not_block_attaching_another`.
|
||||
|
||||
### B298 — A synced-folder edit whose upload lost its answer is kept as a conflict copy of itself
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
|
||||
+3
-4
@@ -15,10 +15,6 @@ 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`.
|
||||
@@ -54,6 +50,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
|
||||
- **A synced folder whose folder on Drive is in the trash no longer blocks attaching another.**
|
||||
Until it was removed, every `pdfs sync attach` failed with "remote sync folder is in the trash",
|
||||
whatever folder it named (B299).
|
||||
- **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).
|
||||
|
||||
@@ -267,50 +267,6 @@ 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.
|
||||
|
||||
@@ -1,403 +0,0 @@
|
||||
#!/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