mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-26 11:02:14 +01:00
Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8dd0c6f424 | ||
|
|
3e0e581bf8 | ||
|
|
16970ecf35 | ||
|
|
d428457514 | ||
|
|
ff37d1b081 | ||
|
|
83938db712 | ||
|
|
bfe14b3fc9 | ||
|
|
bfa58357c9 | ||
|
|
64906bd786 | ||
|
|
6abb1a6cd9 | ||
|
|
ce97b86638 | ||
|
|
3879ee7922 | ||
|
|
6ecf713d3a | ||
|
|
d40c7f7ebb | ||
|
|
fe9528ce29 | ||
|
|
b6ee07161c | ||
|
|
8e3e048005 | ||
|
|
c2f5537bd7 | ||
|
|
06d099f0de | ||
|
|
c171a713cb | ||
|
|
23a961d020 | ||
|
|
d84b35c039 | ||
|
|
bf7d26ce23 | ||
|
|
62ae18efbf | ||
|
|
7cffeb924d |
No files matched your search
Generated
+4
@@ -3776,10 +3776,14 @@ dependencies = [
|
||||
name = "pdfs-sync"
|
||||
version = "3.10.0"
|
||||
dependencies = [
|
||||
"notify",
|
||||
"parking_lot 0.13.0",
|
||||
"pdfs-core",
|
||||
"pdfs-drive",
|
||||
"pdfs-store",
|
||||
"proton-drive-rs",
|
||||
"sha1 0.11.0",
|
||||
"tokio",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
|
||||
@@ -3646,6 +3646,15 @@ fn cmd_diagnostics() -> Result<()> {
|
||||
);
|
||||
}
|
||||
}
|
||||
if !d.drive_calls.is_empty() {
|
||||
println!("calls to Drive since start:");
|
||||
for call in &d.drive_calls {
|
||||
println!(
|
||||
" {:<38} {:>7} calls {:>5} failed {:>9} ms total {:>7} ms longest",
|
||||
call.call, call.count, call.errors, call.total_ms, call.longest_ms,
|
||||
);
|
||||
}
|
||||
}
|
||||
if d.inflight.is_empty() {
|
||||
println!("in-flight requests: none");
|
||||
} else {
|
||||
|
||||
@@ -2369,6 +2369,22 @@ pub struct Diagnostics {
|
||||
/// The folder-sync engine. `None` from a daemon that predates the field.
|
||||
#[serde(default)]
|
||||
pub sync: Option<SyncEngineState>,
|
||||
/// Every kind of call made to Drive since start: how many, how many
|
||||
/// failed, and how long they took. Empty from a daemon that predates the
|
||||
/// field.
|
||||
#[serde(default)]
|
||||
pub drive_calls: Vec<DriveCallStat>,
|
||||
}
|
||||
|
||||
/// One kind of call to Drive, in [`Diagnostics::drive_calls`].
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct DriveCallStat {
|
||||
/// The client method, such as `enumerate_folder_children_node_uids`.
|
||||
pub call: String,
|
||||
pub count: u64,
|
||||
pub errors: u64,
|
||||
pub total_ms: u64,
|
||||
pub longest_ms: u64,
|
||||
}
|
||||
|
||||
/// What the folder-sync engine is doing, for [`Diagnostics`].
|
||||
|
||||
@@ -22,9 +22,11 @@ pub mod sdkcache;
|
||||
pub mod search;
|
||||
pub mod service;
|
||||
pub mod shell;
|
||||
pub mod shutdown;
|
||||
pub mod syncignore;
|
||||
pub mod syncroot;
|
||||
pub mod timestamp;
|
||||
pub mod transfers;
|
||||
pub mod tray;
|
||||
pub mod update;
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ use parking_lot::{Condvar, Mutex};
|
||||
/// The daemon's stop signal. Set once, never cleared: a `Core` that has been
|
||||
/// told to stop belongs to a mount that is going away.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Shutdown {
|
||||
pub struct Shutdown {
|
||||
stopping: Mutex<bool>,
|
||||
changed: Condvar,
|
||||
}
|
||||
@@ -29,14 +29,14 @@ pub(crate) struct Shutdown {
|
||||
impl Shutdown {
|
||||
/// Whether teardown has begun. Loops check this where they would otherwise
|
||||
/// start another unit of work.
|
||||
pub(crate) fn is_stopping(&self) -> bool {
|
||||
pub fn is_stopping(&self) -> bool {
|
||||
*self.stopping.lock()
|
||||
}
|
||||
|
||||
/// Begin teardown and wake everything waiting in [`sleep`](Self::sleep).
|
||||
/// Idempotent, because more than one path can reach teardown (a signal, the
|
||||
/// kernel mount ending, a failed startup).
|
||||
pub(crate) fn stop(&self) {
|
||||
pub fn stop(&self) {
|
||||
let mut stopping = self.stopping.lock();
|
||||
*stopping = true;
|
||||
self.changed.notify_all();
|
||||
@@ -47,7 +47,7 @@ impl Shutdown {
|
||||
/// Returns `false` if the daemon is stopping — including when it was already
|
||||
/// stopping on entry, so `while shutdown.sleep(interval)` is a complete and
|
||||
/// correct loop condition and no separate check is needed at the top.
|
||||
pub(crate) fn sleep(&self, duration: Duration) -> bool {
|
||||
pub fn sleep(&self, duration: Duration) -> bool {
|
||||
let mut stopping = self.stopping.lock();
|
||||
if !*stopping {
|
||||
self.changed.wait_for(&mut stopping, duration);
|
||||
@@ -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())
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
//! transfer moves is charged to its direction's [`RateLimit`], and the thread
|
||||
//! moving it sleeps off whatever the charge puts it over the cap.
|
||||
//!
|
||||
//! [`Request::GetQueueStatus`]: pdfs_core::control::Request::GetQueueStatus
|
||||
//! [`Request::GetQueueStatus`]: crate::control::Request::GetQueueStatus
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
@@ -26,7 +26,7 @@ use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use pdfs_core::control::{JobItem, TransferDirection, TransferItem};
|
||||
use crate::control::{JobItem, TransferDirection, TransferItem};
|
||||
|
||||
/// One registered transfer. `done` is bumped from the I/O wrapper without the
|
||||
/// registry lock; the rest is immutable for the transfer's lifetime.
|
||||
@@ -198,7 +198,7 @@ impl TransferRegistry {
|
||||
/// Snapshot every in-flight job for [`Response::Transfers`], oldest first, so
|
||||
/// a front-end's rows keep their order across polls.
|
||||
///
|
||||
/// [`Response::Transfers`]: pdfs_core::control::Response::Transfers
|
||||
/// [`Response::Transfers`]: crate::control::Response::Transfers
|
||||
pub fn jobs_snapshot(&self) -> Vec<JobItem> {
|
||||
let map = self.jobs.lock();
|
||||
let mut ids: Vec<_> = map.keys().copied().collect();
|
||||
@@ -222,7 +222,7 @@ impl TransferRegistry {
|
||||
/// running average since the transfer began — simple, and stable enough for a
|
||||
/// progress widget without per-tick sampling state.
|
||||
///
|
||||
/// [`Response::Transfers`]: pdfs_core::control::Response::Transfers
|
||||
/// [`Response::Transfers`]: crate::control::Response::Transfers
|
||||
pub fn snapshot(&self) -> Vec<TransferItem> {
|
||||
let map = self.inner.lock();
|
||||
let mut ids: Vec<_> = map.keys().copied().collect();
|
||||
@@ -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,597 @@
|
||||
//! A [`DriveApi`] that counts and times every call it forwards.
|
||||
//!
|
||||
//! Wrapping the client in [`Counted`] answers "what is the daemon asking Drive,
|
||||
//! and how long does Drive take" without a debugger or a log at debug level:
|
||||
//! [`CallStats::snapshot`] gives, per kind of call, how many were made, how
|
||||
//! many failed, and their total and longest time. The diagnostics report shows
|
||||
//! it.
|
||||
//!
|
||||
//! A streaming call (a batch move, restore or delete) is counted once when it
|
||||
//! starts. Its time is not measured, because the stream outlives the call.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use proton_drive_rs::proton_sdk::account::Quota;
|
||||
use proton_drive_rs::proton_sdk::error::Result;
|
||||
use proton_drive_rs::proton_sdk::ids::{DriveEventId, NodeUid, ShareId};
|
||||
use proton_drive_rs::{
|
||||
AvailableNameTarget, Device, DeviceType, DriveEvent, DriveEventScopeId, Node, NodeMoveItem,
|
||||
Thumbnail, ThumbnailType, TrashedNode,
|
||||
};
|
||||
|
||||
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
|
||||
|
||||
/// Every kind of call [`DriveApi`] makes, one per method.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DriveCall {
|
||||
GetMyFilesFolder,
|
||||
ContextShareId,
|
||||
GetNode,
|
||||
EnumerateNodes,
|
||||
EnumerateNodesLight,
|
||||
EnumerateChildren,
|
||||
EnumerateEvents,
|
||||
InvalidateCaches,
|
||||
CreateFolder,
|
||||
UploadFile,
|
||||
UploadFileFrom,
|
||||
UploadFileReplacingDraft,
|
||||
UploadNewRevision,
|
||||
OpenRevision,
|
||||
DownloadThumbnail,
|
||||
DownloadFile,
|
||||
DownloadRevision,
|
||||
RenameNode,
|
||||
MoveNode,
|
||||
CopyNode,
|
||||
GetAvailableName,
|
||||
MoveNodes,
|
||||
TrashNodes,
|
||||
RestoreNodes,
|
||||
RestoreNodesStreaming,
|
||||
DeleteNodes,
|
||||
EnumerateTrash,
|
||||
EmptyTrash,
|
||||
EnumerateTrashedNodes,
|
||||
Quota,
|
||||
EnumerateDevices,
|
||||
CreateDevice,
|
||||
}
|
||||
|
||||
impl DriveCall {
|
||||
pub const ALL: [DriveCall; 32] = [
|
||||
DriveCall::GetMyFilesFolder,
|
||||
DriveCall::ContextShareId,
|
||||
DriveCall::GetNode,
|
||||
DriveCall::EnumerateNodes,
|
||||
DriveCall::EnumerateNodesLight,
|
||||
DriveCall::EnumerateChildren,
|
||||
DriveCall::EnumerateEvents,
|
||||
DriveCall::InvalidateCaches,
|
||||
DriveCall::CreateFolder,
|
||||
DriveCall::UploadFile,
|
||||
DriveCall::UploadFileFrom,
|
||||
DriveCall::UploadFileReplacingDraft,
|
||||
DriveCall::UploadNewRevision,
|
||||
DriveCall::OpenRevision,
|
||||
DriveCall::DownloadThumbnail,
|
||||
DriveCall::DownloadFile,
|
||||
DriveCall::DownloadRevision,
|
||||
DriveCall::RenameNode,
|
||||
DriveCall::MoveNode,
|
||||
DriveCall::CopyNode,
|
||||
DriveCall::GetAvailableName,
|
||||
DriveCall::MoveNodes,
|
||||
DriveCall::TrashNodes,
|
||||
DriveCall::RestoreNodes,
|
||||
DriveCall::RestoreNodesStreaming,
|
||||
DriveCall::DeleteNodes,
|
||||
DriveCall::EnumerateTrash,
|
||||
DriveCall::EmptyTrash,
|
||||
DriveCall::EnumerateTrashedNodes,
|
||||
DriveCall::Quota,
|
||||
DriveCall::EnumerateDevices,
|
||||
DriveCall::CreateDevice,
|
||||
];
|
||||
|
||||
/// The name the diagnostics report shows: the client method's own.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
DriveCall::GetMyFilesFolder => "get_my_files_folder",
|
||||
DriveCall::ContextShareId => "context_share_id",
|
||||
DriveCall::GetNode => "get_node",
|
||||
DriveCall::EnumerateNodes => "enumerate_nodes",
|
||||
DriveCall::EnumerateNodesLight => "enumerate_nodes_light",
|
||||
DriveCall::EnumerateChildren => "enumerate_folder_children_node_uids",
|
||||
DriveCall::EnumerateEvents => "enumerate_events",
|
||||
DriveCall::InvalidateCaches => "invalidate_caches_for_event",
|
||||
DriveCall::CreateFolder => "create_folder",
|
||||
DriveCall::UploadFile => "upload_file",
|
||||
DriveCall::UploadFileFrom => "upload_file_from",
|
||||
DriveCall::UploadFileReplacingDraft => "upload_file_replacing_draft_from",
|
||||
DriveCall::UploadNewRevision => "upload_new_revision_from",
|
||||
DriveCall::OpenRevision => "open_revision",
|
||||
DriveCall::DownloadThumbnail => "download_thumbnail",
|
||||
DriveCall::DownloadFile => "download_file_to",
|
||||
DriveCall::DownloadRevision => "download_revision_to",
|
||||
DriveCall::RenameNode => "rename_node",
|
||||
DriveCall::MoveNode => "move_node",
|
||||
DriveCall::CopyNode => "copy_node",
|
||||
DriveCall::GetAvailableName => "get_available_name",
|
||||
DriveCall::MoveNodes => "move_nodes_streaming",
|
||||
DriveCall::TrashNodes => "trash_nodes",
|
||||
DriveCall::RestoreNodes => "restore_nodes",
|
||||
DriveCall::RestoreNodesStreaming => "restore_nodes_streaming",
|
||||
DriveCall::DeleteNodes => "delete_nodes_streaming",
|
||||
DriveCall::EnumerateTrash => "enumerate_trash_node_uids",
|
||||
DriveCall::EmptyTrash => "empty_trash",
|
||||
DriveCall::EnumerateTrashedNodes => "enumerate_trashed_nodes_light",
|
||||
DriveCall::Quota => "quota",
|
||||
DriveCall::EnumerateDevices => "enumerate_devices",
|
||||
DriveCall::CreateDevice => "create_device",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One kind of call, as [`CallStats::snapshot`] reports it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CallStat {
|
||||
pub call: DriveCall,
|
||||
pub count: u64,
|
||||
pub errors: u64,
|
||||
pub total: Duration,
|
||||
pub longest: Duration,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Counter {
|
||||
count: AtomicU64,
|
||||
errors: AtomicU64,
|
||||
total_us: AtomicU64,
|
||||
longest_us: AtomicU64,
|
||||
}
|
||||
|
||||
/// The counts behind a [`Counted`] drive, shared with whoever reports them.
|
||||
pub struct CallStats {
|
||||
counters: [Counter; DriveCall::ALL.len()],
|
||||
}
|
||||
|
||||
impl Default for CallStats {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
counters: std::array::from_fn(|_| Counter::default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CallStats {
|
||||
fn record(&self, call: DriveCall, failed: bool, took: Option<Duration>) {
|
||||
let counter = &self.counters[call as usize];
|
||||
counter.count.fetch_add(1, Ordering::Relaxed);
|
||||
if failed {
|
||||
counter.errors.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
if let Some(took) = took {
|
||||
let us = u64::try_from(took.as_micros()).unwrap_or(u64::MAX);
|
||||
counter.total_us.fetch_add(us, Ordering::Relaxed);
|
||||
counter.longest_us.fetch_max(us, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every kind of call made at least once, in [`DriveCall::ALL`] order.
|
||||
pub fn snapshot(&self) -> Vec<CallStat> {
|
||||
DriveCall::ALL
|
||||
.iter()
|
||||
.filter_map(|&call| {
|
||||
let counter = &self.counters[call as usize];
|
||||
let count = counter.count.load(Ordering::Relaxed);
|
||||
(count > 0).then(|| CallStat {
|
||||
call,
|
||||
count,
|
||||
errors: counter.errors.load(Ordering::Relaxed),
|
||||
total: Duration::from_micros(counter.total_us.load(Ordering::Relaxed)),
|
||||
longest: Duration::from_micros(counter.longest_us.load(Ordering::Relaxed)),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`DriveApi`] that forwards to `inner` and records every call in `stats`.
|
||||
pub struct Counted {
|
||||
inner: Arc<dyn DriveApi>,
|
||||
stats: Arc<CallStats>,
|
||||
}
|
||||
|
||||
impl Counted {
|
||||
pub fn new(inner: Arc<dyn DriveApi>, stats: Arc<CallStats>) -> Self {
|
||||
Self { inner, stats }
|
||||
}
|
||||
|
||||
async fn timed<T>(
|
||||
&self,
|
||||
call: DriveCall,
|
||||
future: impl std::future::Future<Output = Result<T>>,
|
||||
) -> Result<T> {
|
||||
let started = Instant::now();
|
||||
let result = future.await;
|
||||
self.stats
|
||||
.record(call, result.is_err(), Some(started.elapsed()));
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl DriveApi for Counted {
|
||||
async fn get_my_files_folder(&self) -> Result<Node> {
|
||||
self.timed(
|
||||
DriveCall::GetMyFilesFolder,
|
||||
self.inner.get_my_files_folder(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn context_share_id(&self, uid: &NodeUid) -> Result<ShareId> {
|
||||
self.timed(DriveCall::ContextShareId, self.inner.context_share_id(uid))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn get_node(&self, uid: &NodeUid) -> Result<Option<Node>> {
|
||||
self.timed(DriveCall::GetNode, self.inner.get_node(uid))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn enumerate_nodes(&self, uids: &[NodeUid]) -> Result<Vec<Node>> {
|
||||
self.timed(DriveCall::EnumerateNodes, self.inner.enumerate_nodes(uids))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn enumerate_nodes_light(&self, uids: &[NodeUid]) -> Result<Vec<Node>> {
|
||||
self.timed(
|
||||
DriveCall::EnumerateNodesLight,
|
||||
self.inner.enumerate_nodes_light(uids),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn enumerate_folder_children_node_uids(
|
||||
&self,
|
||||
folder_uid: &NodeUid,
|
||||
) -> Result<Vec<NodeUid>> {
|
||||
self.timed(
|
||||
DriveCall::EnumerateChildren,
|
||||
self.inner.enumerate_folder_children_node_uids(folder_uid),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn enumerate_events(
|
||||
&self,
|
||||
scope: &DriveEventScopeId,
|
||||
cursor: Option<&DriveEventId>,
|
||||
) -> Result<Vec<DriveEvent>> {
|
||||
self.timed(
|
||||
DriveCall::EnumerateEvents,
|
||||
self.inner.enumerate_events(scope, cursor),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn invalidate_caches_for_event(&self, event: &DriveEvent) -> Result<()> {
|
||||
self.timed(
|
||||
DriveCall::InvalidateCaches,
|
||||
self.inner.invalidate_caches_for_event(event),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn create_folder(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<NodeUid> {
|
||||
self.timed(
|
||||
DriveCall::CreateFolder,
|
||||
self.inner
|
||||
.create_folder(parent_uid, name, last_modification_time),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn upload_file(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
media_type: &str,
|
||||
contents: &[u8],
|
||||
) -> Result<NodeUid> {
|
||||
self.timed(
|
||||
DriveCall::UploadFile,
|
||||
self.inner
|
||||
.upload_file(parent_uid, name, media_type, contents),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn upload_file_from_dyn(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
media_type: &str,
|
||||
reader: &mut (dyn Read + Send),
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
aead: bool,
|
||||
) -> Result<NodeUid> {
|
||||
self.timed(
|
||||
DriveCall::UploadFileFrom,
|
||||
self.inner.upload_file_from_dyn(
|
||||
parent_uid,
|
||||
name,
|
||||
media_type,
|
||||
reader,
|
||||
intended_size,
|
||||
thumbnails,
|
||||
last_modification_time,
|
||||
aead,
|
||||
),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn upload_file_replacing_draft_from_dyn(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
media_type: &str,
|
||||
reader: &mut (dyn Read + Send),
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
aead: bool,
|
||||
) -> Result<NodeUid> {
|
||||
self.timed(
|
||||
DriveCall::UploadFileReplacingDraft,
|
||||
self.inner.upload_file_replacing_draft_from_dyn(
|
||||
parent_uid,
|
||||
name,
|
||||
media_type,
|
||||
reader,
|
||||
intended_size,
|
||||
thumbnails,
|
||||
last_modification_time,
|
||||
aead,
|
||||
),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn upload_new_revision_from_dyn(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
reader: &mut (dyn Read + Send),
|
||||
intended_size: i64,
|
||||
thumbnails: Vec<Thumbnail>,
|
||||
last_modification_time: Option<i64>,
|
||||
) -> Result<()> {
|
||||
self.timed(
|
||||
DriveCall::UploadNewRevision,
|
||||
self.inner.upload_new_revision_from_dyn(
|
||||
file_uid,
|
||||
reader,
|
||||
intended_size,
|
||||
thumbnails,
|
||||
last_modification_time,
|
||||
),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
|
||||
self.timed(DriveCall::OpenRevision, self.inner.open_revision(uid))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn download_thumbnail(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
thumbnail_type: ThumbnailType,
|
||||
) -> Result<Option<Vec<u8>>> {
|
||||
self.timed(
|
||||
DriveCall::DownloadThumbnail,
|
||||
self.inner.download_thumbnail(uid, thumbnail_type),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn download_file_to_dyn(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
output: &mut (dyn Write + Send),
|
||||
) -> Result<()> {
|
||||
self.timed(
|
||||
DriveCall::DownloadFile,
|
||||
self.inner.download_file_to_dyn(uid, output),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn download_revision_to_dyn(
|
||||
&self,
|
||||
file_uid: &NodeUid,
|
||||
revision_id: &str,
|
||||
writer: &mut (dyn Write + Send),
|
||||
) -> Result<()> {
|
||||
self.timed(
|
||||
DriveCall::DownloadRevision,
|
||||
self.inner
|
||||
.download_revision_to_dyn(file_uid, revision_id, writer),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn rename_node(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
new_name: &str,
|
||||
new_media_type: Option<&str>,
|
||||
) -> Result<()> {
|
||||
self.timed(
|
||||
DriveCall::RenameNode,
|
||||
self.inner.rename_node(uid, new_name, new_media_type),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn move_node(&self, uid: &NodeUid, new_parent: &NodeUid) -> Result<()> {
|
||||
self.timed(DriveCall::MoveNode, self.inner.move_node(uid, new_parent))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn copy_node(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
new_parent: &NodeUid,
|
||||
name: Option<&str>,
|
||||
) -> Result<NodeUid> {
|
||||
self.timed(
|
||||
DriveCall::CopyNode,
|
||||
self.inner.copy_node(uid, new_parent, name),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn get_available_name(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
target: AvailableNameTarget,
|
||||
) -> Result<String> {
|
||||
self.timed(
|
||||
DriveCall::GetAvailableName,
|
||||
self.inner.get_available_name(parent_uid, name, target),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn move_nodes_streaming<'a>(
|
||||
&'a self,
|
||||
items: Vec<NodeMoveItem>,
|
||||
new_parent: NodeUid,
|
||||
) -> OutcomeStream<'a> {
|
||||
self.stats.record(DriveCall::MoveNodes, false, None);
|
||||
self.inner.move_nodes_streaming(items, new_parent)
|
||||
}
|
||||
|
||||
async fn trash_nodes(&self, uids: &[NodeUid]) -> Result<NodeOutcomes> {
|
||||
self.timed(DriveCall::TrashNodes, self.inner.trash_nodes(uids))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn restore_nodes(&self, uids: &[NodeUid]) -> Result<NodeOutcomes> {
|
||||
self.timed(DriveCall::RestoreNodes, self.inner.restore_nodes(uids))
|
||||
.await
|
||||
}
|
||||
|
||||
fn restore_nodes_streaming<'a>(&'a self, uids: &[NodeUid]) -> OutcomeStream<'a> {
|
||||
self.stats
|
||||
.record(DriveCall::RestoreNodesStreaming, false, None);
|
||||
self.inner.restore_nodes_streaming(uids)
|
||||
}
|
||||
|
||||
fn delete_nodes_streaming<'a>(&'a self, uids: &[NodeUid]) -> OutcomeStream<'a> {
|
||||
self.stats.record(DriveCall::DeleteNodes, false, None);
|
||||
self.inner.delete_nodes_streaming(uids)
|
||||
}
|
||||
|
||||
async fn enumerate_trash_node_uids(&self) -> Result<Vec<NodeUid>> {
|
||||
self.timed(
|
||||
DriveCall::EnumerateTrash,
|
||||
self.inner.enumerate_trash_node_uids(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn empty_trash(&self) -> Result<()> {
|
||||
self.timed(DriveCall::EmptyTrash, self.inner.empty_trash())
|
||||
.await
|
||||
}
|
||||
|
||||
async fn enumerate_trashed_nodes_light(&self, uids: &[NodeUid]) -> Result<Vec<TrashedNode>> {
|
||||
self.timed(
|
||||
DriveCall::EnumerateTrashedNodes,
|
||||
self.inner.enumerate_trashed_nodes_light(uids),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn quota(&self) -> Result<Quota> {
|
||||
self.timed(DriveCall::Quota, self.inner.quota()).await
|
||||
}
|
||||
|
||||
async fn enumerate_devices(&self) -> Result<Vec<Device>> {
|
||||
self.timed(DriveCall::EnumerateDevices, self.inner.enumerate_devices())
|
||||
.await
|
||||
}
|
||||
|
||||
async fn create_device(&self, name: &str, device_type: DeviceType) -> Result<Device> {
|
||||
self.timed(
|
||||
DriveCall::CreateDevice,
|
||||
self.inner.create_device(name, device_type),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn landing(&self, uid: &NodeUid) {
|
||||
self.inner.landing(uid);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_call_has_its_own_counter() {
|
||||
for (index, call) in DriveCall::ALL.iter().enumerate() {
|
||||
assert_eq!(*call as usize, index, "{} is out of order", call.name());
|
||||
}
|
||||
let names: std::collections::HashSet<_> =
|
||||
DriveCall::ALL.iter().map(|call| call.name()).collect();
|
||||
assert_eq!(names.len(), DriveCall::ALL.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_is_counted_with_its_failures_and_time() {
|
||||
let stats = CallStats::default();
|
||||
stats.record(DriveCall::GetNode, false, Some(Duration::from_millis(30)));
|
||||
stats.record(DriveCall::GetNode, true, Some(Duration::from_millis(10)));
|
||||
stats.record(DriveCall::DeleteNodes, false, None);
|
||||
|
||||
assert_eq!(
|
||||
stats.snapshot(),
|
||||
vec![
|
||||
CallStat {
|
||||
call: DriveCall::GetNode,
|
||||
count: 2,
|
||||
errors: 1,
|
||||
total: Duration::from_millis(40),
|
||||
longest: Duration::from_millis(30),
|
||||
},
|
||||
CallStat {
|
||||
call: DriveCall::DeleteNodes,
|
||||
count: 1,
|
||||
errors: 0,
|
||||
total: Duration::ZERO,
|
||||
longest: Duration::ZERO,
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,12 +27,15 @@ 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<()>)>;
|
||||
|
||||
@@ -607,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,
|
||||
|
||||
@@ -18,7 +18,7 @@ use std::sync::{Arc, LazyLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::control::{Diagnostics, InflightRequest, WorkerState};
|
||||
use pdfs_core::control::{Diagnostics, DriveCallStat, InflightRequest, WorkerState};
|
||||
|
||||
use super::Core;
|
||||
|
||||
@@ -163,7 +163,19 @@ 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()
|
||||
.into_iter()
|
||||
.map(|stat| DriveCallStat {
|
||||
call: stat.call.name().to_owned(),
|
||||
count: stat.count,
|
||||
errors: stat.errors,
|
||||
total_ms: u64::try_from(stat.total.as_millis()).unwrap_or(u64::MAX),
|
||||
longest_ms: u64::try_from(stat.longest.as_millis()).unwrap_or(u64::MAX),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
-184
@@ -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};
|
||||
@@ -113,7 +115,7 @@ mod redate;
|
||||
mod relocate;
|
||||
mod revisions;
|
||||
mod sharing;
|
||||
mod shutdown;
|
||||
use pdfs_core::shutdown;
|
||||
#[cfg(test)]
|
||||
mod sim;
|
||||
mod state;
|
||||
@@ -122,7 +124,7 @@ mod sweep;
|
||||
mod sync;
|
||||
mod systemd;
|
||||
mod takeout;
|
||||
mod transfers;
|
||||
use pdfs_core::transfers;
|
||||
mod upload;
|
||||
mod r#virtual;
|
||||
mod workers;
|
||||
@@ -175,7 +177,7 @@ const MAX_BACKGROUND: u16 = 64;
|
||||
const MAX_NAME_LEN: u32 = 255;
|
||||
|
||||
/// How often the background task polls the remote event cursor.
|
||||
const POLL_INTERVAL: Duration = Duration::from_secs(10);
|
||||
const POLL_INTERVAL: Duration = pdfs_sync::EVENT_POLL_INTERVAL;
|
||||
/// Retry backoff for a queued upload, doubling per attempt between these. The
|
||||
/// floor is short because the common failure is a brief network blip; the
|
||||
/// ceiling keeps a persistently failing op from spinning.
|
||||
@@ -507,6 +509,8 @@ struct Core {
|
||||
/// downloads, renames, moves and trashes. The real client in production, an
|
||||
/// in-memory Drive in the simulation tests. See [`drive`].
|
||||
drive: Arc<dyn DriveApi>,
|
||||
/// What [`Core::drive`] has been asked, for the diagnostics report.
|
||||
drive_calls: Arc<pdfs_drive::counted::CallStats>,
|
||||
/// The concrete client, for what [`DriveApi`] does not cover: sharing,
|
||||
/// Photos, devices, invitations and public links.
|
||||
client: ProtonDriveClient,
|
||||
@@ -574,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.
|
||||
@@ -739,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
|
||||
@@ -765,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.
|
||||
///
|
||||
@@ -6170,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(
|
||||
@@ -6382,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 {
|
||||
@@ -6590,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
|
||||
@@ -7060,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 {
|
||||
@@ -7125,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");
|
||||
|
||||
@@ -466,6 +466,12 @@ pub(crate) fn mount_with(
|
||||
// Start the uptime clock here rather than at the first `pdfs diagnostics`,
|
||||
// so the age it reports is the daemon's own.
|
||||
super::diagnostics::start_clock();
|
||||
// Count every call to Drive from the first, the root lookup included.
|
||||
let drive_calls = Arc::new(pdfs_drive::counted::CallStats::default());
|
||||
let drive: Arc<dyn DriveApi> = Arc::new(pdfs_drive::counted::Counted::new(
|
||||
drive,
|
||||
drive_calls.clone(),
|
||||
));
|
||||
check_mountpoint(mountpoint)?;
|
||||
let (root, start) = fetch_or_recall_root(drive.as_ref(), &rt, &db)?;
|
||||
let online = start == Start::Online;
|
||||
@@ -485,8 +491,28 @@ 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,
|
||||
client,
|
||||
gallery,
|
||||
rt: rt.clone(),
|
||||
@@ -498,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()),
|
||||
@@ -513,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())),
|
||||
@@ -522,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)),
|
||||
@@ -552,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
|
||||
@@ -601,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);
|
||||
@@ -984,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
|
||||
|
||||
@@ -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(|| {
|
||||
|
||||
@@ -30,6 +30,16 @@ const MOUNT_DEADLINE: Duration = Duration::from_secs(20);
|
||||
/// How long a restart may wait for the last run to let go of its database.
|
||||
const LAST_RUN_DEADLINE: Duration = Duration::from_secs(30);
|
||||
|
||||
/// How long a stop may wait for the mount to end before it aborts the FUSE
|
||||
/// connection. A mount that stops answering otherwise hangs the test, and the
|
||||
/// whole run with it (`docs/BUGS.md` B297).
|
||||
const STOP_DEADLINE: Duration = Duration::from_secs(60);
|
||||
|
||||
/// How long one daemon may live. Past this, its FUSE connection is aborted, so
|
||||
/// a test blocked on a request the mount never answers fails with `ENOTCONN`
|
||||
/// instead of hanging the run. The whole suite takes about 15 minutes in CI.
|
||||
const LIFETIME_LIMIT: Duration = Duration::from_secs(20 * 60);
|
||||
|
||||
pub(crate) struct Daemon {
|
||||
pub(crate) client: FakeClient,
|
||||
pub(crate) mountpoint: PathBuf,
|
||||
@@ -38,6 +48,13 @@ pub(crate) struct Daemon {
|
||||
stop: SyncSender<()>,
|
||||
mount: Option<JoinHandle<io::Result<MountOutcome>>>,
|
||||
rt: Option<tokio::runtime::Runtime>,
|
||||
/// The mount's FUSE connection, as `/sys/fs/fuse/connections` names it.
|
||||
connection: u64,
|
||||
/// Dropped with the daemon, which ends the thread enforcing
|
||||
/// [`LIFETIME_LIMIT`].
|
||||
_alive: std::sync::mpsc::Sender<()>,
|
||||
/// Dropped after `shut_down`, so the next simulation waits for this one.
|
||||
_turn: Turn,
|
||||
}
|
||||
|
||||
impl Daemon {
|
||||
@@ -45,6 +62,7 @@ impl Daemon {
|
||||
/// A later start on the same `dir` is a restart: it finds the queue, the
|
||||
/// cache and the database the last run left.
|
||||
pub(crate) fn start(dir: &Path, client: FakeClient) -> io::Result<Self> {
|
||||
let turn = Turn::take();
|
||||
log_to_test_output();
|
||||
isolate_from_the_developer();
|
||||
let mountpoint = dir.join("mnt");
|
||||
@@ -112,6 +130,27 @@ impl Daemon {
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
let connection = {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
u64::from(libc::minor(std::fs::metadata(&mountpoint)?.dev()))
|
||||
};
|
||||
let (alive, dropped) = std::sync::mpsc::channel::<()>();
|
||||
{
|
||||
let mountpoint = mountpoint.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("sim-lifetime".into())
|
||||
.spawn(move || {
|
||||
if let Err(std::sync::mpsc::RecvTimeoutError::Timeout) =
|
||||
dropped.recv_timeout(LIFETIME_LIMIT)
|
||||
{
|
||||
eprintln!(
|
||||
"{}: the daemon outlived {LIFETIME_LIMIT:?}; aborting its FUSE connection",
|
||||
mountpoint.display()
|
||||
);
|
||||
abort_connection(connection);
|
||||
}
|
||||
})?;
|
||||
}
|
||||
Ok(Self {
|
||||
client,
|
||||
mountpoint,
|
||||
@@ -120,6 +159,9 @@ impl Daemon {
|
||||
stop,
|
||||
mount: Some(mount),
|
||||
rt: Some(rt),
|
||||
connection,
|
||||
_alive: alive,
|
||||
_turn: turn,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -215,6 +257,21 @@ impl Daemon {
|
||||
return Ok(MountOutcome::Shutdown);
|
||||
};
|
||||
let _ = self.stop.try_send(());
|
||||
if !wait_until(STOP_DEADLINE, || mount.is_finished()) {
|
||||
abort_connection(self.connection);
|
||||
let _ = wait_until(STOP_DEADLINE, || mount.is_finished());
|
||||
if !mount.is_finished() {
|
||||
// Joining would hang the run; leak the thread instead.
|
||||
return Err(io::Error::other(format!(
|
||||
"{}: the mount did not end after its FUSE connection was aborted",
|
||||
self.mountpoint.display()
|
||||
)));
|
||||
}
|
||||
return Err(io::Error::other(format!(
|
||||
"{}: the mount did not stop within {STOP_DEADLINE:?}, so its FUSE connection was aborted",
|
||||
self.mountpoint.display()
|
||||
)));
|
||||
}
|
||||
let outcome = mount
|
||||
.join()
|
||||
.unwrap_or_else(|_| Err(io::Error::other("mount thread panicked")));
|
||||
@@ -231,6 +288,61 @@ impl Drop for Daemon {
|
||||
}
|
||||
}
|
||||
|
||||
/// Abort FUSE connection `connection`: every request waiting on it fails with
|
||||
/// `ENOTCONN`, and the mount's session ends. The connection belongs to the
|
||||
/// user who mounted it, so this needs no privileges.
|
||||
fn abort_connection(connection: u64) {
|
||||
let path = format!("/sys/fs/fuse/connections/{connection}/abort");
|
||||
if let Err(error) = std::fs::write(&path, "1") {
|
||||
eprintln!("could not abort {path}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// One simulation's turn to run daemons. The simulations share the process:
|
||||
/// its environment (see [`isolate_from_the_developer`]), its cores and its
|
||||
/// mounts. Run side by side, as plain `cargo test` does, they miss their
|
||||
/// deadlines and can hang (`docs/BUGS.md` B297). So a daemon started on one
|
||||
/// test thread waits while another test thread still has one.
|
||||
struct Turn;
|
||||
|
||||
/// The test thread whose daemons run now, and how many it has.
|
||||
static TURN: parking_lot::Mutex<Option<(std::thread::ThreadId, usize)>> =
|
||||
parking_lot::Mutex::new(None);
|
||||
static TURN_FREE: parking_lot::Condvar = parking_lot::Condvar::new();
|
||||
|
||||
impl Turn {
|
||||
fn take() -> Self {
|
||||
let me = std::thread::current().id();
|
||||
let mut turn = TURN.lock();
|
||||
loop {
|
||||
match turn.as_mut() {
|
||||
None => {
|
||||
*turn = Some((me, 1));
|
||||
return Turn;
|
||||
}
|
||||
Some((owner, count)) if *owner == me => {
|
||||
*count += 1;
|
||||
return Turn;
|
||||
}
|
||||
Some(_) => TURN_FREE.wait(&mut turn),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Turn {
|
||||
fn drop(&mut self) {
|
||||
let mut turn = TURN.lock();
|
||||
if let Some((_, count)) = turn.as_mut() {
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
*turn = None;
|
||||
TURN_FREE.notify_all();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a file system is mounted at `path`: it sits on another device than
|
||||
/// its parent.
|
||||
fn is_mounted(path: &Path) -> bool {
|
||||
@@ -369,6 +481,63 @@ mod tests {
|
||||
use pdfs_core::control::{RefreshScope, SyncIssue};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_simulation_on_another_thread_waits_for_this_ones_daemons() {
|
||||
// Side by side, the simulations missed their deadlines and could hang
|
||||
// on a mount (B297).
|
||||
let drive = FakeDrive::new();
|
||||
let first = Daemon::start(&scratch("turn-first"), drive.client(1, Faults::lan())).unwrap();
|
||||
let second_up = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let other = {
|
||||
let drive = drive.clone();
|
||||
let second_up = second_up.clone();
|
||||
std::thread::spawn(move || {
|
||||
let second =
|
||||
Daemon::start(&scratch("turn-second"), drive.client(2, Faults::lan())).unwrap();
|
||||
second_up.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
second.stop().unwrap();
|
||||
})
|
||||
};
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
assert!(!second_up.load(std::sync::atomic::Ordering::SeqCst));
|
||||
|
||||
// A second daemon on this thread does not wait for the first.
|
||||
let restarted = first.restart().unwrap();
|
||||
assert!(!second_up.load(std::sync::atomic::Ordering::SeqCst));
|
||||
restarted.stop().unwrap();
|
||||
other.join().unwrap();
|
||||
assert!(second_up.load(std::sync::atomic::Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn diagnostics_count_the_calls_made_to_drive() {
|
||||
let drive = FakeDrive::new();
|
||||
let daemon =
|
||||
Daemon::start(&scratch("drive-calls"), drive.client(1, Faults::lan())).unwrap();
|
||||
std::fs::write(daemon.mountpoint.join("a.txt"), b"a").unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || drive
|
||||
.tree()
|
||||
.contains_key("a.txt")));
|
||||
|
||||
let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics)
|
||||
else {
|
||||
panic!("no diagnostics");
|
||||
};
|
||||
let calls: BTreeMap<_, _> = diagnostics
|
||||
.drive_calls
|
||||
.iter()
|
||||
.map(|stat| (stat.call.as_str(), stat))
|
||||
.collect();
|
||||
assert!(calls.contains_key("get_my_files_folder"), "{calls:?}");
|
||||
let uploads = calls
|
||||
.get("upload_file_from")
|
||||
.or_else(|| calls.get("upload_file_replacing_draft_from"))
|
||||
.unwrap_or_else(|| panic!("no upload counted: {calls:?}"));
|
||||
assert!(uploads.count >= 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_daemon_on_the_fake_drive_syncs_both_ways() {
|
||||
@@ -1941,6 +2110,46 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_mirror_edit_whose_reply_was_lost_is_not_kept_as_a_conflict() {
|
||||
// Drive made the revision, but the answer never came back. The next
|
||||
// pass saw both sides changed since the baseline and kept a conflict
|
||||
// copy of this computer's own edit.
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("mirror-lost-revision-reply");
|
||||
let (daemon, folder, client) = start_mirror(&drive, &dir, &[("a.txt", b"one")]);
|
||||
let local = dir.join("local");
|
||||
assert!(wait_until(Duration::from_secs(30), || drive
|
||||
.lookup("mirrored/a.txt")
|
||||
.is_some()));
|
||||
assert!(wait_for_pass(&daemon, folder, 0));
|
||||
|
||||
client.lose_reply_to_next_revision();
|
||||
std::fs::write(local.join("a.txt"), b"two").unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
on_drive(&drive, "mirrored/a.txt").is_some_and(|bytes| bytes == b"two")
|
||||
}));
|
||||
daemon
|
||||
.request(&Request::SyncNow { id: Some(folder) })
|
||||
.unwrap();
|
||||
assert!(wait_for_pass(&daemon, folder, 0));
|
||||
daemon
|
||||
.request(&Request::SyncNow { id: Some(folder) })
|
||||
.unwrap();
|
||||
assert!(wait_for_pass(&daemon, folder, 0));
|
||||
|
||||
assert!(conflict_copies(&local, "a").is_empty());
|
||||
assert!(
|
||||
!drive.tree().keys().any(|k| k.contains("sync-conflict")),
|
||||
"{:?}",
|
||||
drive.tree()
|
||||
);
|
||||
assert_eq!(std::fs::read(local.join("a.txt")).unwrap(), b"two");
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_revision_made_during_a_mirror_download_still_arrives() {
|
||||
@@ -3503,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
-4528
File diff suppressed because it is too large.
Load diff
@@ -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::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::*;
|
||||
|
||||
@@ -15,3 +15,7 @@ pdfs-drive.workspace = true
|
||||
pdfs-store.workspace = true
|
||||
proton-drive-rs.workspace = true
|
||||
tracing.workspace = true
|
||||
notify = "8"
|
||||
parking_lot.workspace = true
|
||||
sha1.workspace = true
|
||||
tokio.workspace = true
|
||||
@@ -1,9 +1,13 @@
|
||||
//! The mirror engine's decisions, apart from the I/O that feeds and applies them.
|
||||
//! The mirror engine: two-way sync between a local folder and a folder on Drive.
|
||||
//!
|
||||
//! [`model`] is what a pass knows about each path, [`planner`] decides what to
|
||||
//! do with it and refuses what looks like a wipe, [`trace`] records where a pass
|
||||
//! spent its time, and [`naming`] names conflict copies. None of it touches the
|
||||
//! disk, the database or Drive, so all of it is tested without a daemon.
|
||||
//! [`mirror`] runs the passes. It walks both sides, applies the plan and runs
|
||||
//! the engine thread; it owns its state and reaches the rest of the daemon only
|
||||
//! through [`mirror::SyncHost`]. The rest is the engine's decisions, apart from
|
||||
//! the I/O that feeds and applies them: [`model`] is what a pass knows about
|
||||
//! each path, [`planner`] decides what to do with it and refuses what looks
|
||||
//! like a wipe, [`trace`] records where a pass spent its time, and [`naming`]
|
||||
//! names conflict copies. None of those touch the disk, the database or Drive,
|
||||
//! so they are tested without a daemon.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -15,6 +19,7 @@ use pdfs_store::db::StoredSyncEntry;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use proton_drive_rs::{Node, NodeKind};
|
||||
|
||||
pub mod mirror;
|
||||
pub mod model;
|
||||
pub mod naming;
|
||||
pub mod planner;
|
||||
@@ -22,3 +27,7 @@ pub mod trace;
|
||||
|
||||
use model::{LocalItem, LocalSig, RemoteItem};
|
||||
use trace::Call;
|
||||
|
||||
/// How often the daemon reads the Drive event feed. A pass trusts the feed's
|
||||
/// list of changed folders only while reads keep coming at about this pace.
|
||||
pub const EVENT_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -31,13 +31,13 @@ const POLL_INTERVAL: Duration = Duration::from_secs(120);
|
||||
/// per-item work is a network round-trip, so a folder with thousands of files is
|
||||
/// unusable done one-at-a-time; this bounds concurrency like the bulk-upload
|
||||
/// engine does.
|
||||
pub(crate) const SYNC_CONCURRENCY: usize = 8;
|
||||
pub const SYNC_CONCURRENCY: usize = 8;
|
||||
/// How long after a failed watch the engine tries the watches again. Each try
|
||||
/// walks the folder's whole tree, so not on every burst.
|
||||
const REWATCH_RETRY: Duration = Duration::from_secs(600);
|
||||
|
||||
/// A message to the sync engine's control thread.
|
||||
pub(crate) enum SyncMsg {
|
||||
pub enum SyncMsg {
|
||||
/// Reconcile one folder by id (a local change, or a targeted `SyncNow`).
|
||||
Reconcile(i64),
|
||||
/// Reconcile every mirror folder (periodic poll, or startup).
|
||||
@@ -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 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))
|
||||
@@ -72,7 +72,7 @@ pub(crate) fn spawn(core: Core, rx: Receiver<SyncMsg>) -> Option<std::thread::Jo
|
||||
/// file event and poll then went into a channel nobody read, the folder stayed
|
||||
/// `syncing`, and nothing said so until a restart (`docs/BUGS.md` B259).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct EngineHealth {
|
||||
pub struct EngineHealth {
|
||||
running: AtomicBool,
|
||||
pass: Mutex<Option<PassClock>>,
|
||||
panics: AtomicU64,
|
||||
@@ -100,7 +100,7 @@ const PASS_HEARTBEAT: Duration = Duration::from_secs(300);
|
||||
impl EngineHealth {
|
||||
/// Note that the running pass reported progress. Returns the pass's folder
|
||||
/// and age once every [`PASS_HEARTBEAT`], when it is time to log it.
|
||||
pub(crate) fn moved(&self) -> Option<(i64, Duration)> {
|
||||
pub fn moved(&self) -> Option<(i64, Duration)> {
|
||||
let mut pass = self.pass.lock();
|
||||
let pass = pass.as_mut()?;
|
||||
let now = Instant::now();
|
||||
@@ -114,7 +114,7 @@ impl EngineHealth {
|
||||
|
||||
/// The engine's state now. `try_lock`, like the rest of the diagnostics:
|
||||
/// a report must not wait on the thing it reports about.
|
||||
pub(crate) fn report(&self) -> SyncEngineState {
|
||||
pub fn report(&self) -> SyncEngineState {
|
||||
let pass = self.pass.try_lock().and_then(|pass| *pass);
|
||||
let mut traces: Vec<_> = self
|
||||
.traces
|
||||
@@ -167,7 +167,7 @@ impl EngineHealth {
|
||||
}
|
||||
|
||||
/// Apply `f` to the running pass's trace. Does nothing outside a pass.
|
||||
pub(crate) fn trace(&self, f: impl FnOnce(&mut PassTrace)) {
|
||||
pub fn trace(&self, f: impl FnOnce(&mut PassTrace)) {
|
||||
if let Some(trace) = self.trace.lock().as_mut() {
|
||||
f(trace);
|
||||
}
|
||||
@@ -175,7 +175,7 @@ impl EngineHealth {
|
||||
|
||||
/// Note that the running pass ended, `how`, and return its trace for the
|
||||
/// journal.
|
||||
pub(crate) fn end_trace(&self, how: &'static str) -> Option<PassTrace> {
|
||||
pub fn end_trace(&self, how: &'static str) -> Option<PassTrace> {
|
||||
let mut trace = self.trace.lock();
|
||||
let trace = trace.as_mut()?;
|
||||
trace.end(how);
|
||||
@@ -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,254 @@
|
||||
//! 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 the daemon's `Core`, the struct
|
||||
//! every subsystem shares, so any part of a pass could read or lock anything in the
|
||||
//! daemon. Its own state now lives in [`SyncParts`], next to the handles it
|
||||
//! borrows (the database, Drive, the content cache), and everything else it
|
||||
//! needs from the daemon goes through [`SyncHost`]. A [`Syncer`] is the two
|
||||
//! together: the value the engine's methods run on.
|
||||
//!
|
||||
//! The daemon implements [`SyncHost`] in `pdfs-fuse`.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ops::Deref;
|
||||
use std::path::{Path, PathBuf};
|
||||
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_core::shutdown::Shutdown;
|
||||
use pdfs_core::transfers::TransferRegistry;
|
||||
use pdfs_drive::DriveApi;
|
||||
use pdfs_store::cache::ContentCache;
|
||||
use pdfs_store::db::Db;
|
||||
use proton_drive_rs::Thumbnail;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use tracing::info;
|
||||
|
||||
use super::{EngineHealth, SyncMsg};
|
||||
|
||||
/// What the sync engine needs from the daemon that it does not own.
|
||||
pub 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 thumbnails to upload with the file at `path`, named `name`; none
|
||||
/// when it is not an image or video this machine can render. Blocking.
|
||||
fn upload_thumbnails(&self, path: &Path, name: &str) -> Vec<Thumbnail>;
|
||||
}
|
||||
|
||||
/// The sync engine's state, and the daemon handles it uses.
|
||||
#[derive(Clone)]
|
||||
pub struct SyncParts {
|
||||
pub db: Arc<Db>,
|
||||
pub drive: Arc<dyn DriveApi>,
|
||||
pub rt: tokio::runtime::Handle,
|
||||
pub cache: Arc<ContentCache>,
|
||||
pub transfers: Arc<TransferRegistry>,
|
||||
pub shutdown: Arc<Shutdown>,
|
||||
/// My files' root: an attached folder must stay below it.
|
||||
pub 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 progress: Arc<Mutex<HashMap<i64, SyncProgress>>>,
|
||||
/// Whether the engine is alive, and which pass it is on.
|
||||
pub engine: Arc<EngineHealth>,
|
||||
/// Channel to the engine: nudges it to reconcile a folder, reconcile
|
||||
/// everything, or re-scan its watch set.
|
||||
pub 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 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 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 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 events_read_at: Arc<AtomicI64>,
|
||||
}
|
||||
|
||||
impl SyncParts {
|
||||
/// The lock guarding synced folder `id` against a pass and a mode switch
|
||||
/// running at once.
|
||||
pub 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 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 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 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 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 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 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 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 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 struct Syncer {
|
||||
parts: SyncParts,
|
||||
host: Arc<dyn SyncHost>,
|
||||
}
|
||||
|
||||
impl Deref for Syncer {
|
||||
type Target = SyncParts;
|
||||
|
||||
fn deref(&self) -> &SyncParts {
|
||||
&self.parts
|
||||
}
|
||||
}
|
||||
|
||||
impl Syncer {
|
||||
pub fn new(parts: SyncParts, host: Arc<dyn SyncHost>) -> Self {
|
||||
Self { parts, host }
|
||||
}
|
||||
|
||||
pub 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 fn invalidate_children_of(&self, parent: &NodeUid) {
|
||||
self.host.invalidate_children_of(parent);
|
||||
}
|
||||
|
||||
pub fn attach_ancestors(&self, start: &NodeUid) -> CoreResult<Vec<NodeUid>> {
|
||||
self.host.attach_ancestors(start)
|
||||
}
|
||||
|
||||
pub fn settle_pending_mode(&self, id: i64) {
|
||||
self.host.settle_pending_mode(id);
|
||||
}
|
||||
|
||||
pub fn sync_paused(&self) -> bool {
|
||||
self.host.sync_paused()
|
||||
}
|
||||
|
||||
pub fn sync_folder_paused(&self, id: i64) -> bool {
|
||||
self.host.sync_folder_paused(id)
|
||||
}
|
||||
|
||||
/// [`SyncHost::upload_thumbnails`], off the async runtime's threads.
|
||||
pub async fn thumbnails_for_upload(&self, path: PathBuf, name: String) -> Vec<Thumbnail> {
|
||||
let host = self.host.clone();
|
||||
tokio::task::spawn_blocking(move || host.upload_thumbnails(&path, &name))
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -544,15 +544,15 @@ pub fn plan_file(
|
||||
(false, false) => FilePlan::Unchanged,
|
||||
(true, false) => FilePlan::UploadRevision,
|
||||
(false, true) => FilePlan::Download,
|
||||
// With a baseline, both-changed is a genuine concurrent edit and must
|
||||
// be preserved as a conflict. Without one, "both changed" only means
|
||||
// this is the first sync and there was nothing to compare to: when the
|
||||
// sizes match and Drive has a digest to compare against, the apply
|
||||
// step hashes the local file before adopting it. Divergent sizes, or
|
||||
// no digest, stay a real conflict: a missing digest proves nothing.
|
||||
(true, true) if baseline.is_none() && l.size == r.size && r.sha1.is_some() => {
|
||||
FilePlan::AdoptBaseline
|
||||
}
|
||||
// Both sides changed. When the sizes match and Drive has a digest,
|
||||
// the apply step hashes the local file first, and records a
|
||||
// baseline without a transfer if they are the same bytes. Without
|
||||
// a baseline that is a first sync of a file already on both sides.
|
||||
// With one, it is an upload whose reply was lost: Drive holds this
|
||||
// computer's own edit, and a conflict copy of it would be a copy of
|
||||
// itself. Different bytes, divergent sizes, or no digest stay a
|
||||
// real conflict: a missing digest proves nothing.
|
||||
(true, true) if l.size == r.size && r.sha1.is_some() => FilePlan::AdoptBaseline,
|
||||
(true, true) => FilePlan::Conflict,
|
||||
},
|
||||
(Some(_), None) if baseline.is_none() || local_changed => FilePlan::UploadNew,
|
||||
@@ -790,6 +790,17 @@ mod file_plan_tests {
|
||||
plan_file(Some(&edited), Some(&newer), Some(&base)),
|
||||
FilePlan::Conflict
|
||||
);
|
||||
// The same size with a digest is hashed first: it may be this
|
||||
// computer's own upload whose reply was lost.
|
||||
let digested = RemoteItem {
|
||||
revision: Some("r2".into()),
|
||||
sha1: Some("da39a3ee".into()),
|
||||
..remote(30, 40)
|
||||
};
|
||||
assert_eq!(
|
||||
plan_file(Some(&local(11, 40)), Some(&digested), Some(&base)),
|
||||
FilePlan::AdoptBaseline
|
||||
);
|
||||
|
||||
// A row from before schema 44 has no id to compare, and a node read
|
||||
// without one says nothing: both fall back to the signature.
|
||||
|
||||
+62
-3
@@ -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, the transfer registry (`transfers`) and the shutdown signal (`shutdown`) |
|
||||
| [`pdfs-store`](../crates/pdfs-store) | The SQLite schema and queries (`db/`), the content cache (`cache`) |
|
||||
| [`pdfs-drive`](../crates/pdfs-drive) | The `DriveApi` seam over the SDK, the call counter (`counted`), and `FakeDrive` for the simulations |
|
||||
| [`pdfs-sync`](../crates/pdfs-sync) | The mirror engine: its passes and engine thread (`mirror`), and the parts with no I/O: planner, pass model and pass trace. It owns its state (`SyncParts`) and reaches the daemon only through `SyncHost` |
|
||||
| [`pdfs-fuse`](../crates/pdfs-fuse) | The daemon: FUSE handlers (`filesystem`), the tree (`state`), reads (`reads`), the queue and the drain (`queue`, `drain`, `upload`), the link state (`link`), remote events (`background`), the daemon's side of the sync engine (`sync`, which implements `SyncHost`), moves between locations (`relocate`), control handlers (`control`), push events (`events`), photos, sharing, devices, the supervisor, and the simulation tests (`sim/`) |
|
||||
| [`pdfs-cli`](../crates/pdfs-cli) | The `pdfs` binary. `pdfs daemon` runs the daemon in-process; every other command is a control-socket client |
|
||||
| [`pdfs-gui`](../crates/pdfs-gui) | `pdfs-app`, `pdfs-tray` and `pdfs-prompt`. Pages in `src/app/pages/`, widgets in `src/app/widgets/`, CSS and icons in `resources/` |
|
||||
|
||||
@@ -303,7 +306,7 @@ so it only drops gallery rows or marks the timeline stale (`TIMELINE_TTL`, 60 s)
|
||||
## 7. Synced folders
|
||||
|
||||
A synced folder in **mirror** mode is a plain local directory kept in step with a folder under
|
||||
this computer's device in Drive. It has its own engine (`sync.rs`, `sync/`); it does not use the
|
||||
this computer's device in Drive. It has its own engine (`pdfs-sync`'s `mirror`); it does not use the
|
||||
queue of §5 yet (§13). A folder in **online-only** mode is a FUSE session on the tree (§2), and
|
||||
its changes go through the queue like My files.
|
||||
|
||||
@@ -672,4 +675,60 @@ local state per node as each batch lands.
|
||||
- **Mirrored folders** still have their own engine (§7). They move onto the local tree and the
|
||||
queue after that.
|
||||
|
||||
### 4.0: from one daemon to composed services
|
||||
|
||||
The daemon grew one feature at a time inside `pdfs-fuse`, which now holds the FUSE handlers, the
|
||||
drain, the sync engine, photos, thumbnails, takeout, devices, the control server, the supervisor
|
||||
and diagnostics. Everything shares one `Core` struct (`lib.rs`) with over seventy fields, so any
|
||||
code can take any lock in any order, and a new feature can deadlock an old one (`docs/BUGS.md`
|
||||
B110, the cold size upgrade, the diagnostics threads stuck behind the database writer). Over
|
||||
forty threads are spawned ad hoc, each with its own stop and join rules. The only real seam is
|
||||
`DriveApi` (`drive.rs`), which is what lets the simulation tests run against a fake Drive.
|
||||
|
||||
4.0 splits the daemon into services that each own their state and threads, behind ports that can
|
||||
be swapped and tested alone. Dependencies point inward; inner crates never see GTK, `fuser`,
|
||||
`libc` error numbers or SDK node types.
|
||||
|
||||
```
|
||||
apps pdfs-cli, pdfs-gui talk to the daemon over the control socket only
|
||||
daemon pdfs-daemon builds the services, supervisor, diagnostics, control server
|
||||
adapters pdfs-fuse (Linux FUSE), pdfs-local (watch, scan, place), pdfs-drive (SDK adapter, fake Drive)
|
||||
services pdfs-sync (mirrors), pdfs-vfs (mounted files: objects, handles, generations), photos, ...
|
||||
base pdfs-store (SQLite, migrations), pdfs-core (config, protocol, ids, errors)
|
||||
```
|
||||
|
||||
Six rules hold that shape:
|
||||
|
||||
1. **Ownership.** Each service owns its state and its threads. Services talk through typed ports
|
||||
or messages, never through another service's lock.
|
||||
2. **Lifecycle.** Each service starts from its dependencies and returns a handle with `stop`, a
|
||||
bounded `join` and a health snapshot. The supervisor starts the services in dependency order
|
||||
and stops them in reverse. No thread is left detached.
|
||||
3. **No lock across a boundary.** No lock is held across an SDK call, a FUSE reply or kernel
|
||||
notification, a blocking send or a join. Debug builds check the order of the nested locks
|
||||
that remain.
|
||||
4. **Short transactions.** A read never falls back to the writer connection. Diagnostics use
|
||||
their own connection and report "busy" instead of waiting.
|
||||
5. **Absence is a fact, not a gap.** A locked, unreadable, partly listed or ignored path is never
|
||||
read as deleted, whether in sync, in the mount or behind a locked store.
|
||||
6. **Headless tests.** Each service runs in tests without a mount, a desktop or a Proton account:
|
||||
sync against the fake Drive and a temporary directory, the mounted-files service against a
|
||||
fake store.
|
||||
|
||||
The work goes in steps. Each ships the same behaviour with the simulation tests green:
|
||||
|
||||
| Step | What |
|
||||
|---|---|
|
||||
| 0 | Finish what is open: the resumable walk of Drive's changed folders (B294), the ignored `set_len` error on a resize (B295), a reopen after close that depends on the single dispatch thread, and no conflict copy when a lost reply left the same content on Drive |
|
||||
| 1 | Seams and measurement: a `DriveApi` decorator that counts calls and their time, diagnostics that cannot hang (B296), lock-order checks, a live one-edit benchmark |
|
||||
| 2 | Move code into `pdfs-store`, `pdfs-drive` and `pdfs-sync` without changing it |
|
||||
| 3 | Split `Core` into services with a lifecycle, under a supervisor in `pdfs-daemon` |
|
||||
| 4 | Sync on evidence: a local dirty set, typed absence, a delete guard over the whole walk, and a durable intent for each effect, first in shadow mode |
|
||||
| 5 | `pdfs-vfs`: open files, then directories and renames, behind the FUSE adapter |
|
||||
| 6 | One admission policy for mirrors, reads and writeback |
|
||||
|
||||
Steps 0 to 3 are 4.0.0. Steps 4 to 6 follow in 4.x, one service at a time. Out of scope for
|
||||
now: an encrypted local vault (full-disk encryption covers a copied disk today), Windows and
|
||||
macOS adapters, and a separate repository for the sync engine.
|
||||
|
||||
[ROADMAP.md](ROADMAP.md) tracks these and the rest of the planned work.
|
||||
+102
@@ -108,6 +108,9 @@ 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 |
|
||||
| [B294](#b294--a-mirror-folder-too-large-to-finish-in-one-run-never-syncs-and-holds-back-the-others) | A mirror folder too large to finish in one run never syncs, and holds back the others |
|
||||
| [B66](#b66--local-only-pending-data-is-not-protected-at-shutdown-high-21) | Local-only pending data is not protected at shutdown (HIGH-21) |
|
||||
@@ -308,6 +311,7 @@ a live account since.
|
||||
|
||||
| Entry | Title |
|
||||
|---|---|
|
||||
| [B295](#b295--a-resize-the-scratch-file-refused-still-succeeded) | A resize the scratch file refused still succeeded |
|
||||
| [B293](#b293--a-large-trash-never-lists-and-empty-trash-never-empties-it) | A large trash never lists, and Empty Trash never empties it |
|
||||
| [B292](#b292--two-programs-changing-settings-at-once-lose-one-of-the-changes) | Two programs changing settings at once lose one of the changes |
|
||||
| [B290](#b290--reopening-the-database-right-after-closing-it-can-be-refused-as-another-daemon) | Reopening the database right after closing it can be refused as another daemon |
|
||||
@@ -398,6 +402,104 @@ 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)
|
||||
**Found:** 2026-11-26, in the 4.0 review of the mirror planner. B155 fixed the same symptom in
|
||||
the mount's drain; the mirror engine has its own path.
|
||||
**Where:** `plan_file` in `crates/pdfs-sync/src/planner.rs`
|
||||
|
||||
**Repro:** Edit a file in a mirrored folder. Drive makes the new revision, but the answer to
|
||||
the upload never comes back. The next pass sees the local file changed since the baseline,
|
||||
and the file on Drive changed too, so it keeps the local file as `a (sync-conflict …).txt`
|
||||
and downloads Drive's copy, which holds the same bytes. The simulation
|
||||
`a_mirror_edit_whose_reply_was_lost_is_not_kept_as_a_conflict` does this with a lost
|
||||
revision reply.
|
||||
|
||||
**Cause.** The planner hashed the local file against Drive's digest only on a first sync,
|
||||
with no baseline. With a baseline, both sides changed always meant a conflict.
|
||||
|
||||
**Fix.** When both sides changed, the sizes match and Drive has a digest, the planner asks
|
||||
for the same hash check whether or not there is a baseline. The same bytes record a new
|
||||
baseline without a transfer. Different bytes take the conflict path as before.
|
||||
|
||||
**Verified:** `a_mirror_edit_whose_reply_was_lost_is_not_kept_as_a_conflict`, which fails
|
||||
without the fix, and the planner test
|
||||
`a_new_remote_revision_is_a_change_even_at_the_same_mtime_and_size`.
|
||||
|
||||
---
|
||||
|
||||
### B297 — The simulations fail and hang when run in parallel, and nothing stops that
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
**Found:** 2026-11-25, while running the full simulation suite several times each for #134, #135
|
||||
and the 4.0 crate moves, with `cargo test -p pdfs-fuse --lib -- --ignored sim::`. That command
|
||||
leaves out `--test-threads=1`, which CI and [TESTING.md](TESTING.md) use, so libtest ran up to
|
||||
eight simulations at once in one process.
|
||||
**Where:** `crates/pdfs-fuse/src/sim/daemon.rs`, `Daemon::start` and `Daemon::shut_down`
|
||||
|
||||
**Repro:** Run the suite without `--test-threads=1`. Of 18 such runs on three branches based on
|
||||
main, 6 passed, 10 failed and 2 hung until a 900 s timeout. The failures were timing asserts
|
||||
in many tests, among them `a_write_that_failed_on_a_short_outage_goes_out_soon_after_the_link_returns`,
|
||||
`three_clients_one_writer_each` and `one_client_with_stale_hashes_and_reordered_echoes`.
|
||||
Each passes when run alone.
|
||||
|
||||
In a hung run, one test thread stayed in state D in `request_wait_answer`, waiting on a FUSE
|
||||
request to a mount its own process serves. Killing the process left it a zombie and left its
|
||||
mounts in place until their connections were aborted through
|
||||
`/sys/fs/fuse/connections/<n>/abort`.
|
||||
|
||||
Run serially, the same branches pass in CI (#133 to #137).
|
||||
|
||||
**Cause.** The simulations share process-wide state: `isolate_from_the_developer` sets the XDG
|
||||
variables once, which is sound only while no other test reads the environment, and every
|
||||
daemon runs drain workers, a sync engine and a runtime on the same few cores. In parallel the
|
||||
timing asserts miss their deadlines, and the harness has no way out of a mount that stops
|
||||
answering.
|
||||
|
||||
**Fix.** `Daemon::start` takes a turn: a daemon started on one test thread waits while
|
||||
another test thread still has one, so plain `cargo test` runs the simulations one after the
|
||||
other. A daemon on the same thread, as in a restart or the multi-client runs, does not wait.
|
||||
`--test-threads=1` stays the documented way, because it also keeps the parts of a test
|
||||
before its first daemon apart.
|
||||
|
||||
A mount that does not stop within 60 s has its FUSE connection aborted through
|
||||
`/sys/fs/fuse/connections/<n>/abort`, which the mounting user may write, and the stop fails
|
||||
with that message. A daemon alive after 20 minutes gets the same, so a test blocked on a
|
||||
request the mount never answers fails with `ENOTCONN` instead of hanging the run.
|
||||
|
||||
**Verified:** `a_simulation_on_another_thread_waits_for_this_ones_daemons`, which fails
|
||||
without the turn.
|
||||
|
||||
Separately, CI on main (`0b9e849`) failed `a_move_blocked_by_trash_can_be_retried_after_restore`
|
||||
once, serially ([run](https://github.com/narrrl/proton-drive-linux/actions/runs/45694939718)):
|
||||
the assert at `daemon.rs:2209` found an empty list. It has not failed since.
|
||||
|
||||
---
|
||||
### B296 — A busy database stalls reads, and piles up diagnostics threads
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
|
||||
@@ -15,6 +15,9 @@ Schema: **49**. New tables save a mirror folder's walk of Proton Drive (48). A f
|
||||
kept, with a list of the folders that changed on Proton Drive since (49).
|
||||
|
||||
### Added
|
||||
- **`pdfs diagnostics` 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`.
|
||||
- **`pdfs diagnostics` and the journal say where a sync pass spends its time.** Each pass over a
|
||||
synced folder records how long it took to walk this computer's copy, list Proton Drive, plan
|
||||
and apply. It also records how many calls to Proton Drive it made of each kind, how long they
|
||||
@@ -47,6 +50,12 @@ 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).
|
||||
- **A busy database no longer stalls reads or piles up threads.** A read that cannot get its own
|
||||
connection fails instead of waiting behind a long write. `pdfs diagnostics` reports the
|
||||
number of queued operations as unknown when the database does not answer in time, and no
|
||||
|
||||
Reference in new issue
Block a user