mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-27 03:22:14 +01:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f4b1ce4b9 | ||
|
|
e855498edf | ||
|
|
54bb2fd10d | ||
|
|
c6806362ae | ||
|
|
7462edc07c | ||
|
|
b9571ad045 | ||
|
|
b210485430 | ||
|
|
24f1f51c2c | ||
|
|
bbaa24e6ce | ||
|
|
cb6e0e3228 | ||
|
|
a627542c20 | ||
|
|
58fa3b5953 | ||
|
|
633e268a7b | ||
|
|
afbf88aa2d | ||
|
|
e93e2a3ef9 | ||
|
|
d32f287763 | ||
|
|
04fb485e9f |
No files matched your search
@@ -323,6 +323,14 @@ pub(super) fn cmd_diagnostics() -> Result<()> {
|
||||
);
|
||||
}
|
||||
}
|
||||
if !d.jobs.is_empty() {
|
||||
let jobs: Vec<String> = d
|
||||
.jobs
|
||||
.iter()
|
||||
.map(|job| format!("{} ({})", job.name, human_secs(job.age_secs)))
|
||||
.collect();
|
||||
println!("jobs: {}", jobs.join(", "));
|
||||
}
|
||||
if let Some(sync) = &d.sync {
|
||||
println!("sync engine: {}", sync_engine_line(sync));
|
||||
for trace in &sync.traces {
|
||||
|
||||
@@ -2378,9 +2378,14 @@ pub struct Diagnostics {
|
||||
/// still running. Empty from a daemon that predates the field.
|
||||
#[serde(default)]
|
||||
pub services: Vec<ServiceState>,
|
||||
/// The one-shot jobs running now, such as a cache check, an import or a
|
||||
/// folder pin, oldest first. Empty from a daemon that predates the field.
|
||||
#[serde(default)]
|
||||
pub jobs: Vec<ServiceState>,
|
||||
}
|
||||
|
||||
/// One long-lived daemon thread, in [`Diagnostics::services`].
|
||||
/// One long-lived daemon thread, in [`Diagnostics::services`], or one
|
||||
/// one-shot job, in [`Diagnostics::jobs`].
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct ServiceState {
|
||||
/// The thread's name, such as `pdfs-sync`.
|
||||
|
||||
@@ -12,9 +12,20 @@
|
||||
//! reverse start order: it signals [`Shutdown`], wakes each one, and joins each
|
||||
//! one up to a shared deadline, naming any that is still running then.
|
||||
//! [`ServiceBoard`] is the live view of the same threads, for diagnostics.
|
||||
//!
|
||||
//! A service can also be an async task on the mount's runtime
|
||||
//! ([`Services::spawn_task`]), such as the loops that follow Drive's event
|
||||
//! streams. A stop aborts it at its next `.await` and waits for it to go, up
|
||||
//! to the same deadline. Such a task used to run until the runtime went
|
||||
//! away, which on a stop is when the process exits.
|
||||
//!
|
||||
//! Work a request starts and does not wait for runs as a one-shot job
|
||||
//! ([`ServiceBoard::spawn_job`] on a thread, [`ServiceBoard::spawn_task_job`]
|
||||
//! on the runtime): listed on the board while it runs, and not joined on stop.
|
||||
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -35,10 +46,18 @@ pub struct ServiceHealth {
|
||||
pub age: Duration,
|
||||
}
|
||||
|
||||
/// The live view of the service threads: which ones were started, and which
|
||||
/// are still running. Cheap to clone and to read; never blocks on a service.
|
||||
/// The live view of the service threads, which were started and which are
|
||||
/// still running, and of the one-shot jobs running now. Cheap to clone and to
|
||||
/// read; never blocks on a service or a job.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct ServiceBoard(Arc<Mutex<Vec<Entry>>>);
|
||||
pub struct ServiceBoard(Arc<Board>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct Board {
|
||||
services: Mutex<Vec<Entry>>,
|
||||
jobs: Mutex<Vec<Job>>,
|
||||
next_job: AtomicU64,
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
name: String,
|
||||
@@ -46,10 +65,17 @@ struct Entry {
|
||||
running: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
struct Job {
|
||||
id: u64,
|
||||
name: String,
|
||||
started: Instant,
|
||||
}
|
||||
|
||||
impl ServiceBoard {
|
||||
/// Every service thread started so far, in start order.
|
||||
pub fn health(&self) -> Vec<ServiceHealth> {
|
||||
self.0
|
||||
.services
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|entry| ServiceHealth {
|
||||
@@ -60,9 +86,75 @@ impl ServiceBoard {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The one-shot jobs running now, oldest first. A job leaves the list
|
||||
/// when its thread ends.
|
||||
pub fn jobs(&self) -> Vec<ServiceHealth> {
|
||||
self.0
|
||||
.jobs
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|job| ServiceHealth {
|
||||
name: job.name.clone(),
|
||||
running: true,
|
||||
age: job.started.elapsed(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Start `run` on a thread named `name`, as a one-shot job: a request's
|
||||
/// work that outlasts the request, such as a cache check, an import or a
|
||||
/// folder pin. It shows in [`jobs`](Self::jobs) until it ends, by return
|
||||
/// or by panic.
|
||||
///
|
||||
/// Not joined on stop. A job's work is either safe to cut short (the
|
||||
/// process exits) or bounded by the deadlines of the calls it makes.
|
||||
pub fn spawn_job<F>(&self, name: &str, run: F) -> std::io::Result<()>
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
{
|
||||
let guard = self.add_job(name);
|
||||
std::thread::Builder::new()
|
||||
.name(name.to_owned())
|
||||
.spawn(move || {
|
||||
let _guard = guard;
|
||||
run();
|
||||
})
|
||||
// On an error the closure, and the guard in it, are already
|
||||
// dropped, so the job is off the list.
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// Start `task` on `rt` as a one-shot job, like [`spawn_job`](Self::spawn_job)
|
||||
/// for work that is async: a refresh a listing starts and does not wait
|
||||
/// for. It shows in [`jobs`](Self::jobs) until it ends, by return, panic
|
||||
/// or the runtime going away.
|
||||
pub fn spawn_task_job<F>(&self, rt: &tokio::runtime::Handle, name: &str, task: F)
|
||||
where
|
||||
F: Future<Output = ()> + Send + 'static,
|
||||
{
|
||||
let guard = self.add_job(name);
|
||||
rt.spawn(async move {
|
||||
let _guard = guard;
|
||||
task.await;
|
||||
});
|
||||
}
|
||||
|
||||
fn add_job(&self, name: &str) -> JobGuard {
|
||||
let id = self.0.next_job.fetch_add(1, Ordering::Relaxed);
|
||||
self.0.jobs.lock().push(Job {
|
||||
id,
|
||||
name: name.to_owned(),
|
||||
started: Instant::now(),
|
||||
});
|
||||
JobGuard {
|
||||
board: self.0.clone(),
|
||||
id,
|
||||
}
|
||||
}
|
||||
|
||||
fn add(&self, name: &str) -> Arc<AtomicBool> {
|
||||
let running = Arc::new(AtomicBool::new(true));
|
||||
self.0.lock().push(Entry {
|
||||
self.0.services.lock().push(Entry {
|
||||
name: name.to_owned(),
|
||||
started: Instant::now(),
|
||||
running: running.clone(),
|
||||
@@ -71,6 +163,18 @@ impl ServiceBoard {
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes a job off the board when its thread ends, by return or by panic.
|
||||
struct JobGuard {
|
||||
board: Arc<Board>,
|
||||
id: u64,
|
||||
}
|
||||
|
||||
impl Drop for JobGuard {
|
||||
fn drop(&mut self) {
|
||||
self.board.jobs.lock().retain(|job| job.id != self.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears a service's `running` flag when its thread ends, by return or by panic.
|
||||
struct Running(Arc<AtomicBool>);
|
||||
|
||||
@@ -81,10 +185,28 @@ impl Drop for Running {
|
||||
}
|
||||
|
||||
struct Service {
|
||||
handle: JoinHandle<()>,
|
||||
handle: Handle,
|
||||
wake: Option<Wake>,
|
||||
}
|
||||
|
||||
/// A service is a thread, or an async task on the mount's runtime.
|
||||
enum Handle {
|
||||
Thread(JoinHandle<()>),
|
||||
Task {
|
||||
name: String,
|
||||
task: tokio::task::JoinHandle<()>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Handle {
|
||||
fn is_finished(&self) -> bool {
|
||||
match self {
|
||||
Handle::Thread(handle) => handle.is_finished(),
|
||||
Handle::Task { task, .. } => task.is_finished(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The service threads one mount started, and how to stop them.
|
||||
pub struct Services {
|
||||
board: ServiceBoard,
|
||||
@@ -117,7 +239,10 @@ impl Services {
|
||||
});
|
||||
match spawned {
|
||||
Ok(handle) => {
|
||||
self.started.push(Service { handle, wake });
|
||||
self.started.push(Service {
|
||||
handle: Handle::Thread(handle),
|
||||
wake,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => {
|
||||
@@ -128,31 +253,64 @@ impl Services {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many threads were started.
|
||||
/// Start `task` on `rt` as a service named `name`. [`stop`](Self::stop)
|
||||
/// aborts it, so it ends at its next `.await`; a task does not need to
|
||||
/// watch the [`Shutdown`] signal itself. Code between two `.await`s runs
|
||||
/// to its end, so a write it makes there is not cut in half.
|
||||
pub fn spawn_task<F>(&mut self, rt: &tokio::runtime::Handle, name: &str, task: F)
|
||||
where
|
||||
F: Future<Output = ()> + Send + 'static,
|
||||
{
|
||||
let guard = Running(self.board.add(name));
|
||||
let task = rt.spawn(async move {
|
||||
let _guard = guard;
|
||||
task.await;
|
||||
});
|
||||
self.started.push(Service {
|
||||
handle: Handle::Task {
|
||||
name: name.to_owned(),
|
||||
task,
|
||||
},
|
||||
wake: None,
|
||||
});
|
||||
}
|
||||
|
||||
/// How many services were started.
|
||||
pub fn len(&self) -> usize {
|
||||
self.started.len()
|
||||
}
|
||||
|
||||
/// Whether no thread was started.
|
||||
/// Whether no service was started.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.started.is_empty()
|
||||
}
|
||||
|
||||
/// Stop every thread: signal `shutdown`, wake each thread in reverse start
|
||||
/// order, then join them in the same order until `deadline`. Returns the
|
||||
/// names of the threads still running at the deadline; they are left
|
||||
/// behind rather than waited for.
|
||||
/// Stop every service: signal `shutdown`, wake each thread and abort each
|
||||
/// task in reverse start order, then join them in the same order until
|
||||
/// `deadline`. Returns the names of the services still running at the
|
||||
/// deadline; they are left behind rather than waited for.
|
||||
pub fn stop(self, shutdown: &Shutdown, deadline: Instant) -> Vec<String> {
|
||||
shutdown.stop();
|
||||
for service in self.started.iter().rev() {
|
||||
if let Some(wake) = &service.wake {
|
||||
wake();
|
||||
}
|
||||
if let Handle::Task { task, .. } = &service.handle {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
join_until(
|
||||
self.started.into_iter().rev().map(|service| service.handle),
|
||||
deadline,
|
||||
)
|
||||
let mut running = Vec::new();
|
||||
for service in self.started.into_iter().rev() {
|
||||
while !service.handle.is_finished() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
match service.handle {
|
||||
Handle::Thread(handle) => running.extend(join_until([handle], deadline)),
|
||||
Handle::Task { name, task } if !task.is_finished() => running.push(name),
|
||||
Handle::Task { .. } => {}
|
||||
}
|
||||
}
|
||||
running
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,4 +418,117 @@ mod tests {
|
||||
assert!(left.is_empty());
|
||||
assert!(!board.health()[0].running);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_job_shows_while_it_runs_and_leaves_when_it_ends() {
|
||||
let board = ServiceBoard::default();
|
||||
let (release, wait) = mpsc::channel::<()>();
|
||||
let (done_tx, done_rx) = mpsc::channel::<()>();
|
||||
board
|
||||
.spawn_job("pdfs-test-job", move || {
|
||||
let _ = wait.recv();
|
||||
let _done = done_tx;
|
||||
})
|
||||
.unwrap();
|
||||
let jobs = board.jobs();
|
||||
assert_eq!(jobs.len(), 1);
|
||||
assert_eq!(jobs[0].name, "pdfs-test-job");
|
||||
assert!(board.health().is_empty(), "a job is not a service");
|
||||
|
||||
release.send(()).unwrap();
|
||||
let _ = done_rx.recv_timeout(Duration::from_secs(5));
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !board.jobs().is_empty() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
assert!(board.jobs().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stop_aborts_a_task_and_shows_it_ended() {
|
||||
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(1)
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let board = ServiceBoard::default();
|
||||
let mut services = Services::new(board.clone());
|
||||
// Never ends on its own and never looks at the shutdown signal.
|
||||
services.spawn_task(rt.handle(), "poller", async {
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
});
|
||||
assert_eq!(services.len(), 1);
|
||||
assert!(board.health()[0].running);
|
||||
|
||||
let left = services.stop(
|
||||
&Shutdown::default(),
|
||||
Instant::now() + Duration::from_secs(5),
|
||||
);
|
||||
|
||||
assert!(left.is_empty(), "still running: {left:?}");
|
||||
assert!(!board.health()[0].running);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_task_stuck_between_awaits_is_named_at_the_deadline() {
|
||||
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(1)
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let mut services = Services::new(ServiceBoard::default());
|
||||
let (release, wait) = mpsc::channel::<()>();
|
||||
let (started_tx, started_rx) = mpsc::channel::<()>();
|
||||
// Blocks its worker thread, so an abort cannot reach it until it yields.
|
||||
services.spawn_task(rt.handle(), "blocking", async move {
|
||||
let _ = started_tx.send(());
|
||||
let _ = wait.recv();
|
||||
});
|
||||
started_rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
|
||||
let left = services.stop(
|
||||
&Shutdown::default(),
|
||||
Instant::now() + Duration::from_millis(100),
|
||||
);
|
||||
|
||||
assert_eq!(left, ["blocking"]);
|
||||
drop(release);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_task_job_shows_while_it_runs_and_leaves_when_it_ends() {
|
||||
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(1)
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let board = ServiceBoard::default();
|
||||
let (release, wait) = tokio::sync::oneshot::channel::<()>();
|
||||
board.spawn_task_job(rt.handle(), "pdfs-test-refresh", async move {
|
||||
let _ = wait.await;
|
||||
});
|
||||
let jobs = board.jobs();
|
||||
assert_eq!(jobs.len(), 1);
|
||||
assert_eq!(jobs[0].name, "pdfs-test-refresh");
|
||||
|
||||
release.send(()).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !board.jobs().is_empty() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
assert!(board.jobs().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_job_that_panics_leaves_the_list() {
|
||||
let board = ServiceBoard::default();
|
||||
board.spawn_job("doomed-job", || panic!("boom")).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !board.jobs().is_empty() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
assert!(board.jobs().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -140,16 +140,17 @@ impl Core {
|
||||
return;
|
||||
}
|
||||
let core = self.clone();
|
||||
self.rt.spawn(async move {
|
||||
let refreshed = core.refresh_albums().await;
|
||||
core.photo_jobs
|
||||
.albums_refreshing
|
||||
.store(false, Ordering::SeqCst);
|
||||
match refreshed {
|
||||
Ok(_) => core.events.publish(&[Topic::Photos]),
|
||||
Err(e) => warn!(error = %e, "background album refresh failed"),
|
||||
}
|
||||
});
|
||||
self.services
|
||||
.spawn_task_job(&self.rt, "pdfs-albums-refresh", async move {
|
||||
let refreshed = core.refresh_albums().await;
|
||||
core.photo_jobs
|
||||
.albums_refreshing
|
||||
.store(false, Ordering::SeqCst);
|
||||
match refreshed {
|
||||
Ok(_) => core.events.publish(&[Topic::Photos]),
|
||||
Err(e) => warn!(error = %e, "background album refresh failed"),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A page of one album's photos, newest capture first. The album's contents
|
||||
@@ -179,11 +180,12 @@ impl Core {
|
||||
} else if self.listing_stale(&stamp, TIMELINE_TTL) {
|
||||
let core = self.clone();
|
||||
let album = album.clone();
|
||||
self.rt.spawn(async move {
|
||||
if let Err(e) = core.refresh_album(&album).await {
|
||||
warn!(%album, error = %e, "background album refresh failed");
|
||||
}
|
||||
});
|
||||
self.services
|
||||
.spawn_task_job(&self.rt, "pdfs-album-refresh", async move {
|
||||
if let Err(e) = core.refresh_album(&album).await {
|
||||
warn!(%album, error = %e, "background album refresh failed");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let page = self
|
||||
|
||||
@@ -57,7 +57,7 @@ impl Core {
|
||||
mountpoint: &Path,
|
||||
) -> CoreResult<StoredSyncFolder> {
|
||||
let _registration = super::devices::SYNC_ROOT_REGISTRATION.lock();
|
||||
if !self.primary {
|
||||
if !self.session.primary {
|
||||
return Err(CoreError::invalid("attach must use My files"));
|
||||
}
|
||||
if remote.is_absolute()
|
||||
|
||||
@@ -176,7 +176,7 @@ fn apply_event(core: &Core, event: &DriveEvent, dirty: &mut DirtyParents) -> pdf
|
||||
// even for a trash, so an echo we no longer care about does not
|
||||
// linger to suppress a later foreign change.
|
||||
let echo = core.take_self_change(node_uid);
|
||||
let ours = !*is_trashed && (echo || core.pending.lock().contains_key(node_uid));
|
||||
let ours = !*is_trashed && (echo || core.writes.is_queued(node_uid));
|
||||
if ours {
|
||||
debug!(uid = %node_uid, "ignoring remote event for a node with a queued write");
|
||||
}
|
||||
|
||||
+37
-1067
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,444 @@
|
||||
//! The control requests about Photos: the timeline, albums, thumbnails, the gallery, and Takeout imports and redating.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The requests [`answer`] serves, as a pattern, so the control socket's match
|
||||
/// hands exactly these over and the compiler still checks that it covers every
|
||||
/// request.
|
||||
macro_rules! request {
|
||||
() => {
|
||||
::pdfs_core::control::Request::PhotosTimeline { .. }
|
||||
| ::pdfs_core::control::Request::PhotoDuplicates
|
||||
| ::pdfs_core::control::Request::PhotoSimilar
|
||||
| ::pdfs_core::control::Request::PhotoPlaces
|
||||
| ::pdfs_core::control::Request::PlacePhotos { .. }
|
||||
| ::pdfs_core::control::Request::PlaceLocations { .. }
|
||||
| ::pdfs_core::control::Request::PhotosOnThisDay { .. }
|
||||
| ::pdfs_core::control::Request::PhotoGroup { .. }
|
||||
| ::pdfs_core::control::Request::SetPhotoFavorite { .. }
|
||||
| ::pdfs_core::control::Request::PhotoAlbums
|
||||
| ::pdfs_core::control::Request::AlbumPhotos { .. }
|
||||
| ::pdfs_core::control::Request::CreateAlbum { .. }
|
||||
| ::pdfs_core::control::Request::RenameAlbum { .. }
|
||||
| ::pdfs_core::control::Request::DeleteAlbum { .. }
|
||||
| ::pdfs_core::control::Request::AddToAlbum { .. }
|
||||
| ::pdfs_core::control::Request::RemoveFromAlbum { .. }
|
||||
| ::pdfs_core::control::Request::PhotoPresence { .. }
|
||||
| ::pdfs_core::control::Request::PhotoMonths { .. }
|
||||
| ::pdfs_core::control::Request::PhotoThumbs { .. }
|
||||
| ::pdfs_core::control::Request::FileThumbs { .. }
|
||||
| ::pdfs_core::control::Request::ReserveFileThumbGeneration
|
||||
| ::pdfs_core::control::Request::CancelFileThumbs { .. }
|
||||
| ::pdfs_core::control::Request::StartThumbnailBuild { .. }
|
||||
| ::pdfs_core::control::Request::CancelThumbnailBuild
|
||||
| ::pdfs_core::control::Request::ThumbnailBuildStatus
|
||||
| ::pdfs_core::control::Request::PhotosRefreshStatus
|
||||
| ::pdfs_core::control::Request::OpenPhoto { .. }
|
||||
| ::pdfs_core::control::Request::DriveGallery { .. }
|
||||
| ::pdfs_core::control::Request::OpenGalleryVideo { .. }
|
||||
| ::pdfs_core::control::Request::OpenGalleryImage { .. }
|
||||
| ::pdfs_core::control::Request::CloseGalleryVideo { .. }
|
||||
| ::pdfs_core::control::Request::GalleryThumbnail { .. }
|
||||
| ::pdfs_core::control::Request::ImportTakeout { .. }
|
||||
| ::pdfs_core::control::Request::ImportStatus
|
||||
| ::pdfs_core::control::Request::ResumeImport
|
||||
| ::pdfs_core::control::Request::CancelImport
|
||||
| ::pdfs_core::control::Request::RedatePhotos { .. }
|
||||
| ::pdfs_core::control::Request::RedateStatus
|
||||
| ::pdfs_core::control::Request::CancelRedate
|
||||
| ::pdfs_core::control::Request::UploadPhoto { .. }
|
||||
};
|
||||
}
|
||||
pub(super) use request;
|
||||
|
||||
/// Answer a request that [`request!`] matches.
|
||||
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
let Ask {
|
||||
core,
|
||||
mountpoint,
|
||||
stream,
|
||||
visibility,
|
||||
excluded,
|
||||
..
|
||||
} = *ask;
|
||||
match request {
|
||||
CtlRequest::PhotosTimeline {
|
||||
offset,
|
||||
limit,
|
||||
kind,
|
||||
range,
|
||||
favorites,
|
||||
not_in_album,
|
||||
} => match core.photos_timeline(
|
||||
offset,
|
||||
clamp_limit(limit),
|
||||
kind,
|
||||
range,
|
||||
favorites,
|
||||
not_in_album,
|
||||
excluded,
|
||||
) {
|
||||
Ok(Some(items)) => CtlResponse::Photos {
|
||||
available: true,
|
||||
items,
|
||||
counts: core.db.photos_counts_visible(excluded).ok(),
|
||||
},
|
||||
Ok(None) => CtlResponse::Photos {
|
||||
available: false,
|
||||
items: Vec::new(),
|
||||
counts: None,
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PhotoDuplicates => match core.photo_duplicates() {
|
||||
Ok(sets) => CtlResponse::PhotoDuplicates { sets },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PhotoSimilar => match core.photo_similar() {
|
||||
Ok((sets, hashing, uncompared)) => CtlResponse::PhotoSimilar {
|
||||
sets,
|
||||
hashing,
|
||||
uncompared,
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PhotoPlaces => match core.photo_places(excluded) {
|
||||
Ok(items) => CtlResponse::Places {
|
||||
items,
|
||||
mapping: core.timeline_progress(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PlacePhotos { id, offset, limit } => {
|
||||
match core.place_photos(id, offset, clamp_limit(limit), excluded) {
|
||||
Ok(items) => CtlResponse::Photos {
|
||||
available: true,
|
||||
items,
|
||||
counts: None,
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::PlaceLocations { id } => match core.place_locations(id) {
|
||||
Ok(items) => CtlResponse::PhotoLocations { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PhotosOnThisDay { limit } => {
|
||||
match core.photos_on_this_day(clamp_limit(limit), excluded) {
|
||||
Ok(items) => CtlResponse::Photos {
|
||||
available: true,
|
||||
items,
|
||||
counts: None,
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::PhotoGroup { uid } => match core.photo_group(&uid) {
|
||||
Ok(items) => CtlResponse::Photos {
|
||||
available: true,
|
||||
items,
|
||||
counts: None,
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::SetPhotoFavorite { uid, favorite } => match parse_uid(&uid) {
|
||||
Some(node_uid) => match core.set_photo_favorite(&node_uid, favorite) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: if favorite {
|
||||
"added to favorites".to_string()
|
||||
} else {
|
||||
"removed from favorites".to_string()
|
||||
},
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
None => CtlResponse::error(CoreError::invalid(format!("invalid uid: {uid}"))),
|
||||
},
|
||||
CtlRequest::PhotoAlbums => match core.albums() {
|
||||
Ok(Some(items)) => CtlResponse::Albums {
|
||||
available: true,
|
||||
items,
|
||||
},
|
||||
Ok(None) => CtlResponse::Albums {
|
||||
available: false,
|
||||
items: Vec::new(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::AlbumPhotos { uid, offset, limit } => match parse_uid(&uid) {
|
||||
// An album page is a timeline page as far as the front-end is
|
||||
// concerned, so it comes back in the same reply — with `counts`
|
||||
// unset, which describe the whole timeline rather than this album.
|
||||
Some(album) => match visibility
|
||||
.permits(&uid)
|
||||
.and_then(|()| core.album_photos(&album, offset, clamp_limit(limit), excluded))
|
||||
{
|
||||
Ok(items) => CtlResponse::Photos {
|
||||
available: true,
|
||||
items,
|
||||
counts: None,
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
|
||||
},
|
||||
CtlRequest::CreateAlbum { name } => match core.create_album(&name) {
|
||||
Ok(uid) => CtlResponse::AlbumCreated { uid },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RenameAlbum { uid, name } => match parse_uid(&uid) {
|
||||
Some(album) => match core.rename_album(&album, &name) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: format!("renamed album to {name}"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
|
||||
},
|
||||
CtlRequest::DeleteAlbum { uid, delete_photos } => match parse_uid(&uid) {
|
||||
Some(album) => match core.delete_album(&album, delete_photos) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: "album deleted".to_string(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
|
||||
},
|
||||
CtlRequest::AddToAlbum { uid, photos } => album_change(&uid, &photos, |album, photos| {
|
||||
core.add_to_album(album, photos)
|
||||
}),
|
||||
CtlRequest::RemoveFromAlbum { uid, photos } => {
|
||||
album_change(&uid, &photos, |album, photos| {
|
||||
core.remove_from_album(album, photos)
|
||||
})
|
||||
}
|
||||
CtlRequest::PhotoPresence { uid, album } => match core.cached_gallery_visibility() {
|
||||
Ok(visibility)
|
||||
if visibility.media.contains(&uid)
|
||||
|| album
|
||||
.as_ref()
|
||||
.is_some_and(|uid| visibility.albums.contains(uid)) =>
|
||||
{
|
||||
CtlResponse::PhotoPresence { present: false }
|
||||
}
|
||||
Ok(_) => match core.db.photos_contains(&uid, album.as_deref()) {
|
||||
Ok(present) => CtlResponse::PhotoPresence { present },
|
||||
Err(error) => CtlResponse::error(error.into()),
|
||||
},
|
||||
Err(error) => CtlResponse::error(error),
|
||||
},
|
||||
CtlRequest::PhotoMonths { .. } => unreachable!("handled before visibility requests"),
|
||||
CtlRequest::PhotoThumbs { uids } => {
|
||||
let parsed: Vec<NodeUid> = uids
|
||||
.iter()
|
||||
.filter(|uid| !visibility.media.contains(*uid))
|
||||
.filter_map(|u| parse_uid(u))
|
||||
.collect();
|
||||
CtlResponse::Thumbs {
|
||||
items: core.photo_thumbs(&parsed),
|
||||
}
|
||||
}
|
||||
CtlRequest::FileThumbs { items, generation } => {
|
||||
match core.file_thumbs(&items, generation) {
|
||||
Some(items) => CtlResponse::Thumbs { items },
|
||||
None => CtlResponse::FileThumbsStale,
|
||||
}
|
||||
}
|
||||
CtlRequest::ReserveFileThumbGeneration => CtlResponse::FileThumbGeneration {
|
||||
generation: core.reserve_file_thumb_generation(),
|
||||
},
|
||||
CtlRequest::CancelFileThumbs { generation } => {
|
||||
core.cancel_file_thumbs(generation);
|
||||
CtlResponse::Ok {
|
||||
message: "thumbnail requests cancelled".to_string(),
|
||||
}
|
||||
}
|
||||
CtlRequest::StartThumbnailBuild { path } => match rel_to_mount(mountpoint, &path) {
|
||||
Ok(rel) => match core.start_thumbnail_build(rel) {
|
||||
Ok(status) => CtlResponse::ThumbnailBuild { status },
|
||||
Err(error) => CtlResponse::error(error),
|
||||
},
|
||||
Err(error) => CtlResponse::error(error),
|
||||
},
|
||||
CtlRequest::CancelThumbnailBuild => CtlResponse::ThumbnailBuild {
|
||||
status: core.cancel_thumbnail_build(),
|
||||
},
|
||||
CtlRequest::ThumbnailBuildStatus => CtlResponse::ThumbnailBuild {
|
||||
status: core.thumbnail_build_status(),
|
||||
},
|
||||
CtlRequest::PhotosRefreshStatus => CtlResponse::PhotosRefresh {
|
||||
running: core.timeline_refreshing(),
|
||||
},
|
||||
CtlRequest::OpenPhoto { uid } => match parse_uid(&uid) {
|
||||
Some(u) => match visibility.permits(&uid).and_then(|()| core.open_photo(&u)) {
|
||||
Ok(p) => CtlResponse::FilePath {
|
||||
path: p.display().to_string(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
None => CtlResponse::error(CoreError::invalid(format!("bad uid: {uid}"))),
|
||||
},
|
||||
CtlRequest::DriveGallery {
|
||||
action: pdfs_core::control::GalleryAction::AuthenticateHidden,
|
||||
} => core
|
||||
.authenticate_hidden_gallery(stream)
|
||||
.unwrap_or_else(CtlResponse::error),
|
||||
CtlRequest::DriveGallery { action } => core
|
||||
.drive_gallery(action)
|
||||
.unwrap_or_else(CtlResponse::error),
|
||||
CtlRequest::OpenGalleryVideo { uid, private } => core
|
||||
.open_gallery_video(&uid, private)
|
||||
.unwrap_or_else(CtlResponse::error),
|
||||
CtlRequest::OpenGalleryImage { uid, private: true } => {
|
||||
core.gallery_image(&uid).unwrap_or_else(CtlResponse::error)
|
||||
}
|
||||
CtlRequest::OpenGalleryImage {
|
||||
uid,
|
||||
private: false,
|
||||
} => match visibility
|
||||
.permits(&uid)
|
||||
.and_then(|()| core.sharing.open_shared_file(&uid))
|
||||
{
|
||||
Ok(path) => CtlResponse::FilePath {
|
||||
path: path.display().to_string(),
|
||||
},
|
||||
Err(error) => CtlResponse::error(error),
|
||||
},
|
||||
CtlRequest::CloseGalleryVideo { token } => core
|
||||
.close_gallery_video(&token)
|
||||
.unwrap_or_else(CtlResponse::error),
|
||||
CtlRequest::GalleryThumbnail { uid, private } => core
|
||||
.gallery_thumbnail(&uid, private)
|
||||
.unwrap_or_else(CtlResponse::error),
|
||||
CtlRequest::ImportTakeout { archives, dry_run } => {
|
||||
if archives.is_empty() {
|
||||
CtlResponse::error(CoreError::invalid("no Takeout archives given"))
|
||||
} else {
|
||||
let paths = archives.into_iter().map(PathBuf::from).collect();
|
||||
start_takeout_import(core, paths, dry_run)
|
||||
}
|
||||
}
|
||||
CtlRequest::ImportStatus => {
|
||||
let report = crate::takeout::import_status();
|
||||
CtlResponse::ImportStatus {
|
||||
running: report.running,
|
||||
summary: report.summary,
|
||||
progress: report.progress,
|
||||
resumable: report.resumable,
|
||||
}
|
||||
}
|
||||
CtlRequest::ResumeImport => match crate::takeout::resumable_archives() {
|
||||
None => CtlResponse::error(CoreError::not_found("there is no import to resume")),
|
||||
Some(paths) => start_takeout_import(core, paths, false),
|
||||
},
|
||||
CtlRequest::CancelImport => {
|
||||
if crate::takeout::cancel_import() {
|
||||
CtlResponse::Ok {
|
||||
message: "stopping the import".to_string(),
|
||||
}
|
||||
} else {
|
||||
CtlResponse::error(CoreError::invalid("no import is running"))
|
||||
}
|
||||
}
|
||||
CtlRequest::RedatePhotos {
|
||||
dry_run,
|
||||
limit,
|
||||
range,
|
||||
} => match core.spawn_redate(dry_run, limit, range) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: if dry_run {
|
||||
"checking photo dates".to_string()
|
||||
} else {
|
||||
"fixing photo dates".to_string()
|
||||
},
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RedateStatus => {
|
||||
let (running, summary) = crate::redate::redate_status();
|
||||
CtlResponse::RedateStatus { running, summary }
|
||||
}
|
||||
CtlRequest::CancelRedate => {
|
||||
if crate::redate::cancel_redate() {
|
||||
CtlResponse::Ok {
|
||||
message: "stopping the re-date".to_string(),
|
||||
}
|
||||
} else {
|
||||
CtlResponse::error(CoreError::invalid("no photo re-date is running"))
|
||||
}
|
||||
}
|
||||
CtlRequest::UploadPhoto {
|
||||
name,
|
||||
media_type,
|
||||
source_path,
|
||||
capture_time,
|
||||
} => {
|
||||
// Streamed off disk rather than carried over the socket: see the note
|
||||
// on `Request::UploadPhoto`. The length comes from the same handle the
|
||||
// bytes do, so a file changing size under us cannot make the two
|
||||
// disagree.
|
||||
match std::fs::File::open(&source_path).and_then(|f| f.metadata().map(|m| (f, m.len())))
|
||||
{
|
||||
Err(e) => CtlResponse::error(CoreError::invalid(format!(
|
||||
"cannot read {source_path}: {e}"
|
||||
))),
|
||||
Ok((file, len)) => {
|
||||
let photos = core.photos();
|
||||
// Unless the caller knows better: the photo's own EXIF,
|
||||
// then the file's modification time, which a copy resets.
|
||||
let capture_time = capture_time.or_else(|| {
|
||||
let path = Path::new(&source_path);
|
||||
pdfs_core::exiftime::capture_time_of(path).or_else(|| {
|
||||
let modified =
|
||||
std::fs::metadata(path).and_then(|m| m.modified()).ok()?;
|
||||
let since = modified.duration_since(std::time::UNIX_EPOCH).ok()?;
|
||||
Some(since.as_secs() as i64)
|
||||
})
|
||||
});
|
||||
let metadata = proton_drive_rs::PhotoUploadMetadata {
|
||||
capture_time,
|
||||
last_modification_time: capture_time
|
||||
.and_then(pdfs_core::timestamp::modification_time),
|
||||
..Default::default()
|
||||
};
|
||||
let thumbnails = core.upload_thumbnails(Path::new(&source_path), &name);
|
||||
let guard =
|
||||
core.transfers
|
||||
.begin(name.clone(), "", TransferDirection::Upload, len);
|
||||
let reader = CountingReader::new(std::io::BufReader::new(file), &guard);
|
||||
match core.rt.block_on(photos.upload_photo_from(
|
||||
&name,
|
||||
&media_type,
|
||||
reader,
|
||||
len as i64,
|
||||
thumbnails,
|
||||
metadata,
|
||||
false,
|
||||
)) {
|
||||
Ok(uid) => {
|
||||
// The photo we just uploaded belongs at the head of the
|
||||
// timeline, and the GUI reloads the gallery the moment this
|
||||
// reply lands — so refresh now rather than leaving it to a
|
||||
// background pass that would land just after that reload.
|
||||
core.invalidate_photos();
|
||||
if let Err(e) = core.refresh_timeline_joined() {
|
||||
warn!(error = %e, "timeline refresh after upload failed");
|
||||
}
|
||||
CtlResponse::Ok {
|
||||
message: format!("uploaded photo with uid {uid}"),
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
// The reply goes to the app's toast only; without
|
||||
// this the journal shows a failure and no reason.
|
||||
warn!(error = %e, "photo upload failed");
|
||||
CtlResponse::error(CoreError::from_api(&e, "upload photo failed"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// `control` only hands over what `request!` matches.
|
||||
_ => CtlResponse::error(CoreError::internal("not a photos request".to_string())),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//! The control requests about a file's earlier revisions: listing, restoring, deleting and saving one as a new file, by path or by uid.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The requests [`answer`] serves, as a pattern, so the control socket's match
|
||||
/// hands exactly these over and the compiler still checks that it covers every
|
||||
/// request.
|
||||
macro_rules! request {
|
||||
() => {
|
||||
::pdfs_core::control::Request::ListRevisions { .. }
|
||||
| ::pdfs_core::control::Request::ListRevisionsByUid { .. }
|
||||
| ::pdfs_core::control::Request::RestoreRevision { .. }
|
||||
| ::pdfs_core::control::Request::RestoreRevisionByUid { .. }
|
||||
| ::pdfs_core::control::Request::DeleteRevision { .. }
|
||||
| ::pdfs_core::control::Request::DeleteRevisionByUid { .. }
|
||||
| ::pdfs_core::control::Request::SaveRevisionAs { .. }
|
||||
| ::pdfs_core::control::Request::SaveRevisionAsByUid { .. }
|
||||
};
|
||||
}
|
||||
pub(super) use request;
|
||||
|
||||
/// Answer a request that [`request!`] matches.
|
||||
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
let Ask {
|
||||
core, mountpoint, ..
|
||||
} = *ask;
|
||||
match request {
|
||||
CtlRequest::ListRevisions { path } => match rel_to_mount(mountpoint, &path) {
|
||||
Ok(rel) => match core.list_revisions(&rel) {
|
||||
Ok(items) => CtlResponse::Revisions { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListRevisionsByUid { uid } => match core.list_revisions_by_uid(&uid) {
|
||||
Ok(items) => CtlResponse::Revisions { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RestoreRevision { path, revision_id } => {
|
||||
match rel_to_mount(mountpoint, &path) {
|
||||
Ok(rel) => match core.restore_revision(&rel, &revision_id) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: format!("restoring version {revision_id} of {path}"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::RestoreRevisionByUid { uid, revision_id } => {
|
||||
match core.restore_revision_by_uid(&uid, &revision_id) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: format!("restoring version {revision_id}"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::DeleteRevision { path, revision_id } => match rel_to_mount(mountpoint, &path) {
|
||||
Ok(rel) => match core.delete_revision(&rel, &revision_id) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: format!("deleted version {revision_id} of {path}"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::DeleteRevisionByUid { uid, revision_id } => {
|
||||
match core.delete_revision_by_uid(&uid, &revision_id) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: format!("deleted version {revision_id}"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::SaveRevisionAs {
|
||||
path,
|
||||
revision_id,
|
||||
dest,
|
||||
} => match rel_to_mount(mountpoint, &path) {
|
||||
Ok(rel) => match core.save_revision_as(&rel, &revision_id, Path::new(&dest)) {
|
||||
Ok(written) => CtlResponse::Ok {
|
||||
message: format!("wrote {} to {dest}", human_bytes(written)),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::SaveRevisionAsByUid {
|
||||
uid,
|
||||
revision_id,
|
||||
dest,
|
||||
} => match core.save_revision_as_by_uid(&uid, &revision_id, Path::new(&dest)) {
|
||||
Ok(written) => CtlResponse::Ok {
|
||||
message: format!("wrote {} to {dest}", human_bytes(written)),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
// `control` only hands over what `request!` matches.
|
||||
_ => CtlResponse::error(CoreError::internal("not a revisions request".to_string())),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
//! The control requests about sharing: who a node is shared with, its public
|
||||
//! link, what others share with this account, invitations and saved links.
|
||||
//!
|
||||
//! Most of them come in two forms, one naming the node by its path under the
|
||||
//! mount and one by its uid. Both are resolved to a uid here, once, and the
|
||||
//! [`Sharing`](crate::sharing::Sharing) service is only ever asked about a
|
||||
//! resolved node.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use pdfs_core::CoreResult;
|
||||
use pdfs_core::control::{ActivityKind, Request as CtlRequest, Response as CtlResponse};
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
|
||||
use super::rel_to_mount;
|
||||
use crate::Core;
|
||||
use crate::sharing::StopSharingOutcome;
|
||||
|
||||
/// The requests [`answer`] serves, as a pattern, so the control socket's
|
||||
/// match hands exactly these over and the compiler still checks that it covers
|
||||
/// every request.
|
||||
macro_rules! request {
|
||||
() => {
|
||||
::pdfs_core::control::Request::ShareNode { .. }
|
||||
| ::pdfs_core::control::Request::ShareNodeByUid { .. }
|
||||
| ::pdfs_core::control::Request::ListShare { .. }
|
||||
| ::pdfs_core::control::Request::ListShareByUid { .. }
|
||||
| ::pdfs_core::control::Request::UpdateShareRole { .. }
|
||||
| ::pdfs_core::control::Request::UpdateShareRoleByUid { .. }
|
||||
| ::pdfs_core::control::Request::RemoveShareEntry { .. }
|
||||
| ::pdfs_core::control::Request::RemoveShareEntryByUid { .. }
|
||||
| ::pdfs_core::control::Request::CreatePublicLink { .. }
|
||||
| ::pdfs_core::control::Request::CreatePublicLinkByUid { .. }
|
||||
| ::pdfs_core::control::Request::UpdatePublicLink { .. }
|
||||
| ::pdfs_core::control::Request::UpdatePublicLinkByUid { .. }
|
||||
| ::pdfs_core::control::Request::RemovePublicLink { .. }
|
||||
| ::pdfs_core::control::Request::RemovePublicLinkByUid { .. }
|
||||
| ::pdfs_core::control::Request::StopSharing { .. }
|
||||
| ::pdfs_core::control::Request::StopSharingByUid { .. }
|
||||
| ::pdfs_core::control::Request::ListSharedWithMe
|
||||
| ::pdfs_core::control::Request::ListSharedFolder { .. }
|
||||
| ::pdfs_core::control::Request::OpenSharedFile { .. }
|
||||
| ::pdfs_core::control::Request::LeaveShared { .. }
|
||||
| ::pdfs_core::control::Request::ListInvitations
|
||||
| ::pdfs_core::control::Request::AcceptInvitation { .. }
|
||||
| ::pdfs_core::control::Request::RejectInvitation { .. }
|
||||
| ::pdfs_core::control::Request::ListBookmarks
|
||||
| ::pdfs_core::control::Request::CreateBookmark { .. }
|
||||
| ::pdfs_core::control::Request::DeleteBookmark { .. }
|
||||
| ::pdfs_core::control::Request::ListSharedByMe
|
||||
};
|
||||
}
|
||||
pub(super) use request;
|
||||
|
||||
/// The node a request is about, and how the activity feed names it: the path
|
||||
/// the user gave, or the uid.
|
||||
struct Target {
|
||||
label: String,
|
||||
/// The node, or why it could not be resolved. A failure is reported
|
||||
/// through the request's own reply, so a share that fails here is logged
|
||||
/// as a failed share, as it was before the split.
|
||||
node: CoreResult<NodeUid>,
|
||||
}
|
||||
|
||||
impl Target {
|
||||
/// A node named by its path. A path outside the mount fails the request
|
||||
/// before it starts, without an activity entry.
|
||||
fn path(core: &Core, mountpoint: &Path, path: String) -> CoreResult<Self> {
|
||||
let rel = rel_to_mount(mountpoint, &path)?;
|
||||
Ok(Self {
|
||||
node: core.resolve(&rel).map(|(_ino, uid)| uid),
|
||||
label: path,
|
||||
})
|
||||
}
|
||||
|
||||
/// A node named by its uid, which one of this daemon's locations, or the
|
||||
/// Photos timeline, must show to be this account's.
|
||||
fn uid(core: &Core, uid: String) -> Self {
|
||||
Self {
|
||||
node: core.resolve_shareable(&uid),
|
||||
label: uid,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer a request that [`request!`] matches.
|
||||
pub(super) fn answer(ask: &super::Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
let (core, mountpoint) = (ask.core, ask.mountpoint);
|
||||
match answer_or_refuse(core, mountpoint, request) {
|
||||
Ok(response) => response,
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn answer_or_refuse(
|
||||
core: &Core,
|
||||
mountpoint: &Path,
|
||||
request: CtlRequest,
|
||||
) -> CoreResult<CtlResponse> {
|
||||
let sharing = &core.sharing;
|
||||
Ok(match request {
|
||||
CtlRequest::ShareNode {
|
||||
path,
|
||||
emails,
|
||||
role,
|
||||
message,
|
||||
} => share_node(
|
||||
core,
|
||||
Target::path(core, mountpoint, path)?,
|
||||
&emails,
|
||||
&role,
|
||||
message,
|
||||
),
|
||||
CtlRequest::ShareNodeByUid {
|
||||
uid,
|
||||
emails,
|
||||
role,
|
||||
message,
|
||||
} => share_node(core, Target::uid(core, uid), &emails, &role, message),
|
||||
CtlRequest::ListShare { path } => list_share(core, Target::path(core, mountpoint, path)?),
|
||||
CtlRequest::ListShareByUid { uid } => list_share(core, Target::uid(core, uid)),
|
||||
CtlRequest::UpdateShareRole {
|
||||
path,
|
||||
id,
|
||||
kind,
|
||||
role,
|
||||
} => {
|
||||
let target = Target::path(core, mountpoint, path)?;
|
||||
target
|
||||
.node
|
||||
.and_then(|uid| sharing.update_share_role(&uid, &id, kind, &role))?;
|
||||
role_updated(&role)
|
||||
}
|
||||
CtlRequest::UpdateShareRoleByUid {
|
||||
uid,
|
||||
id,
|
||||
kind,
|
||||
role,
|
||||
} => {
|
||||
let target = Target::uid(core, uid);
|
||||
target
|
||||
.node
|
||||
.and_then(|uid| sharing.update_share_role(&uid, &id, kind, &role))?;
|
||||
role_updated(&role)
|
||||
}
|
||||
CtlRequest::RemoveShareEntry { path, id, kind } => {
|
||||
let target = Target::path(core, mountpoint, path)?;
|
||||
remove_share_entry(core, target, &id, kind)?
|
||||
}
|
||||
CtlRequest::RemoveShareEntryByUid { uid, id, kind } => {
|
||||
remove_share_entry(core, Target::uid(core, uid), &id, kind)?
|
||||
}
|
||||
CtlRequest::CreatePublicLink {
|
||||
path,
|
||||
role,
|
||||
password,
|
||||
expires,
|
||||
} => {
|
||||
let target = Target::path(core, mountpoint, path)?;
|
||||
create_public_link(core, target, &role, password.as_deref(), expires)
|
||||
}
|
||||
CtlRequest::CreatePublicLinkByUid {
|
||||
uid,
|
||||
role,
|
||||
password,
|
||||
expires,
|
||||
} => create_public_link(
|
||||
core,
|
||||
Target::uid(core, uid),
|
||||
&role,
|
||||
password.as_deref(),
|
||||
expires,
|
||||
),
|
||||
CtlRequest::UpdatePublicLink {
|
||||
path,
|
||||
id,
|
||||
role,
|
||||
password,
|
||||
expires,
|
||||
} => {
|
||||
let uid = Target::path(core, mountpoint, path)?.node?;
|
||||
let link = sharing.update_public_link(&uid, &id, role.as_deref(), password, expires)?;
|
||||
CtlResponse::PublicLink { link }
|
||||
}
|
||||
CtlRequest::UpdatePublicLinkByUid {
|
||||
uid,
|
||||
id,
|
||||
role,
|
||||
password,
|
||||
expires,
|
||||
} => {
|
||||
let uid = Target::uid(core, uid).node?;
|
||||
let link = sharing.update_public_link(&uid, &id, role.as_deref(), password, expires)?;
|
||||
CtlResponse::PublicLink { link }
|
||||
}
|
||||
CtlRequest::RemovePublicLink { path, id } => {
|
||||
remove_public_link(core, Target::path(core, mountpoint, path)?, &id)?
|
||||
}
|
||||
CtlRequest::RemovePublicLinkByUid { uid, id } => {
|
||||
remove_public_link(core, Target::uid(core, uid), &id)?
|
||||
}
|
||||
CtlRequest::StopSharing { path } => {
|
||||
stop_sharing(core, Target::path(core, mountpoint, path)?)
|
||||
}
|
||||
CtlRequest::StopSharingByUid { uid } => stop_sharing(core, Target::uid(core, uid)),
|
||||
CtlRequest::ListSharedWithMe => CtlResponse::Entries {
|
||||
entries: sharing.list_shared_with_me()?,
|
||||
},
|
||||
CtlRequest::ListSharedFolder { uid } => CtlResponse::Entries {
|
||||
entries: sharing.list_shared_folder(&uid)?,
|
||||
},
|
||||
CtlRequest::OpenSharedFile { uid } => CtlResponse::FilePath {
|
||||
path: sharing.open_shared_file(&uid)?.display().to_string(),
|
||||
},
|
||||
CtlRequest::LeaveShared { uid } => {
|
||||
sharing.leave_shared(&uid)?;
|
||||
core.log_activity(ActivityKind::Unshare, "shared item", "left", true);
|
||||
ok("left shared item")
|
||||
}
|
||||
CtlRequest::ListInvitations => CtlResponse::Invitations {
|
||||
items: sharing.list_invitations()?,
|
||||
},
|
||||
CtlRequest::AcceptInvitation { id } => {
|
||||
sharing.accept_invitation(&id)?;
|
||||
ok("invitation accepted")
|
||||
}
|
||||
CtlRequest::RejectInvitation { id } => {
|
||||
sharing.reject_invitation(&id)?;
|
||||
ok("invitation rejected")
|
||||
}
|
||||
CtlRequest::ListBookmarks => CtlResponse::Bookmarks {
|
||||
items: sharing.list_bookmarks()?,
|
||||
},
|
||||
CtlRequest::CreateBookmark { url, password } => {
|
||||
sharing.create_bookmark(&url, password.as_deref())?;
|
||||
ok("bookmark saved")
|
||||
}
|
||||
CtlRequest::DeleteBookmark { token } => {
|
||||
sharing.delete_bookmark(&token)?;
|
||||
ok("bookmark removed")
|
||||
}
|
||||
CtlRequest::ListSharedByMe => CtlResponse::SharedByMe {
|
||||
items: sharing.list_shared_by_me()?,
|
||||
},
|
||||
// `control` only hands over what `request!` matches.
|
||||
_ => CtlResponse::error(pdfs_core::CoreError::internal(
|
||||
"not a sharing request".to_string(),
|
||||
)),
|
||||
})
|
||||
}
|
||||
|
||||
fn ok(message: &str) -> CtlResponse {
|
||||
CtlResponse::Ok {
|
||||
message: message.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn role_updated(role: &str) -> CtlResponse {
|
||||
CtlResponse::Ok {
|
||||
message: format!("role updated to {role}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn share_node(
|
||||
core: &Core,
|
||||
target: Target,
|
||||
emails: &[String],
|
||||
role: &str,
|
||||
message: Option<String>,
|
||||
) -> CtlResponse {
|
||||
let shared = target.node.and_then(|uid| {
|
||||
core.sharing
|
||||
.share_node(&uid, emails, role, message.as_deref())
|
||||
});
|
||||
match shared {
|
||||
Ok((proton, external)) => {
|
||||
core.log_activity(
|
||||
ActivityKind::Share,
|
||||
&target.label,
|
||||
format!("{} recipient(s) as {role}", proton + external),
|
||||
true,
|
||||
);
|
||||
ok(&format!(
|
||||
"invited {proton} Proton and {external} external user(s)"
|
||||
))
|
||||
}
|
||||
Err(e) => {
|
||||
core.log_activity(ActivityKind::Share, &target.label, &e, false);
|
||||
CtlResponse::error(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_share(core: &Core, target: Target) -> CtlResponse {
|
||||
match target.node.and_then(|uid| core.sharing.list_share(&uid)) {
|
||||
Ok((entries, link)) => CtlResponse::Share { entries, link },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_share_entry(
|
||||
core: &Core,
|
||||
target: Target,
|
||||
id: &str,
|
||||
kind: pdfs_core::control::ShareEntryKind,
|
||||
) -> CoreResult<CtlResponse> {
|
||||
target
|
||||
.node
|
||||
.and_then(|uid| core.sharing.remove_share_entry(&uid, id, kind))?;
|
||||
core.log_activity(ActivityKind::Unshare, &target.label, "access removed", true);
|
||||
Ok(ok("removed"))
|
||||
}
|
||||
|
||||
fn create_public_link(
|
||||
core: &Core,
|
||||
target: Target,
|
||||
role: &str,
|
||||
password: Option<&str>,
|
||||
expires: Option<i64>,
|
||||
) -> CtlResponse {
|
||||
let created = target.node.and_then(|uid| {
|
||||
core.sharing
|
||||
.create_public_link(&uid, role, password, expires)
|
||||
});
|
||||
match created {
|
||||
Ok(link) => {
|
||||
core.log_activity(
|
||||
ActivityKind::PublicLink,
|
||||
&target.label,
|
||||
"link created",
|
||||
true,
|
||||
);
|
||||
CtlResponse::PublicLink { link }
|
||||
}
|
||||
Err(e) => {
|
||||
core.log_activity(ActivityKind::PublicLink, &target.label, &e, false);
|
||||
CtlResponse::error(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_public_link(core: &Core, target: Target, id: &str) -> CoreResult<CtlResponse> {
|
||||
target
|
||||
.node
|
||||
.and_then(|uid| core.sharing.remove_public_link(&uid, id))?;
|
||||
core.log_activity(ActivityKind::Unshare, &target.label, "link removed", true);
|
||||
Ok(ok("public link removed"))
|
||||
}
|
||||
|
||||
/// Log a stop-sharing request, and turn a partial removal into an error that
|
||||
/// names what is still shared.
|
||||
fn stop_sharing(core: &Core, target: Target) -> CtlResponse {
|
||||
let result: CoreResult<StopSharingOutcome> =
|
||||
target.node.and_then(|uid| core.sharing.stop_sharing(&uid));
|
||||
match result.map(|outcome| outcome.into_result()) {
|
||||
Ok(Ok(message)) => {
|
||||
core.log_activity(
|
||||
ActivityKind::Unshare,
|
||||
&target.label,
|
||||
"stopped sharing",
|
||||
true,
|
||||
);
|
||||
CtlResponse::Ok { message }
|
||||
}
|
||||
Ok(Err(left)) => {
|
||||
core.log_activity(ActivityKind::Unshare, &target.label, &left, false);
|
||||
CtlResponse::error(pdfs_core::CoreError::remote(left))
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
//! The control requests about synced folders and devices: adding, attaching, switching and removing folders, pausing, conflicts, the pending-change queue, and restoring a device's folders.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The requests [`answer`] serves, as a pattern, so the control socket's match
|
||||
/// hands exactly these over and the compiler still checks that it covers every
|
||||
/// request.
|
||||
macro_rules! request {
|
||||
() => {
|
||||
::pdfs_core::control::Request::ListDevices
|
||||
| ::pdfs_core::control::Request::ListLocations
|
||||
| ::pdfs_core::control::Request::RenameDevice { .. }
|
||||
| ::pdfs_core::control::Request::DeleteDevice { .. }
|
||||
| ::pdfs_core::control::Request::AdoptDevice { .. }
|
||||
| ::pdfs_core::control::Request::MigrateDevice { .. }
|
||||
| ::pdfs_core::control::Request::AddSyncFolder { .. }
|
||||
| ::pdfs_core::control::Request::AttachSyncFolder { .. }
|
||||
| ::pdfs_core::control::Request::ListSyncFolders
|
||||
| ::pdfs_core::control::Request::RemoveSyncFolder { .. }
|
||||
| ::pdfs_core::control::Request::SetSyncFolderMode { .. }
|
||||
| ::pdfs_core::control::Request::SetSyncFolderPaused { .. }
|
||||
| ::pdfs_core::control::Request::ResetSyncFolder { .. }
|
||||
| ::pdfs_core::control::Request::SyncNow { .. }
|
||||
| ::pdfs_core::control::Request::SetSyncPaused { .. }
|
||||
| ::pdfs_core::control::Request::ListConflicts
|
||||
| ::pdfs_core::control::Request::ResolveConflict { .. }
|
||||
| ::pdfs_core::control::Request::ListPendingOps
|
||||
| ::pdfs_core::control::Request::ExportPendingOp { .. }
|
||||
| ::pdfs_core::control::Request::DiscardPendingOp { .. }
|
||||
| ::pdfs_core::control::Request::RetryPendingOp { .. }
|
||||
| ::pdfs_core::control::Request::ListRestorableFolders
|
||||
| ::pdfs_core::control::Request::ListDeviceRestorableFolders { .. }
|
||||
| ::pdfs_core::control::Request::RestoreSyncFolders { .. }
|
||||
| ::pdfs_core::control::Request::RestoreDeviceFolders { .. }
|
||||
};
|
||||
}
|
||||
pub(super) use request;
|
||||
|
||||
/// Answer a request that [`request!`] matches.
|
||||
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
let Ask {
|
||||
core, mountpoint, ..
|
||||
} = *ask;
|
||||
match request {
|
||||
CtlRequest::ListDevices => match core.list_devices() {
|
||||
Ok(items) => CtlResponse::Devices { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListLocations => match core.list_locations() {
|
||||
Ok(items) => CtlResponse::Locations { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RenameDevice { uid, name } => match core.rename_device(&uid, &name) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: format!("renamed device to {name}"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::DeleteDevice { uid } => match core.delete_device(&uid) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: "device deleted".to_string(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::AdoptDevice { uid } => match core.adopt_device(uid.as_deref()) {
|
||||
Ok(message) => CtlResponse::Ok { message },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::MigrateDevice { uid } => match core.migrate_device(&uid) {
|
||||
Ok(message) => CtlResponse::Ok { message },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::AddSyncFolder { local_path } => {
|
||||
// Registering the device and uploading a folder tree far outlasts the
|
||||
// socket read timeout, so ack immediately and work on a background
|
||||
// thread. The folder appears in ListSyncFolders once the row lands;
|
||||
// completion (and any failures) go to the activity log.
|
||||
let core = core.clone();
|
||||
let path = PathBuf::from(&local_path);
|
||||
if let Err(error) = core
|
||||
.services
|
||||
.clone()
|
||||
.spawn_job("pdfs-add-sync-folder", move || {
|
||||
let started = Instant::now();
|
||||
match core.add_sync_folder(&path) {
|
||||
Ok(folder) => {
|
||||
core.touch_profile();
|
||||
let name = Path::new(&folder.local_path)
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.unwrap_or(&folder.local_path)
|
||||
.to_string();
|
||||
core.log_activity(
|
||||
ActivityKind::Upload,
|
||||
format!("synced {name}"),
|
||||
human_duration(started.elapsed()),
|
||||
folder.state != "error",
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(error = %e, "add sync folder failed");
|
||||
core.log_activity(ActivityKind::Upload, "add sync folder", &e, false);
|
||||
}
|
||||
}
|
||||
})
|
||||
{
|
||||
tracing::warn!(%error, "could not start pdfs-add-sync-folder");
|
||||
}
|
||||
CtlResponse::Ok {
|
||||
message: format!("adding {local_path}"),
|
||||
}
|
||||
}
|
||||
CtlRequest::AttachSyncFolder {
|
||||
local_path,
|
||||
remote_path,
|
||||
} => {
|
||||
let result = rel_to_mount(mountpoint, &remote_path).and_then(|remote| {
|
||||
core.attach_sync_folder(Path::new(&local_path), &remote, mountpoint)
|
||||
});
|
||||
match result {
|
||||
Ok(folder) => CtlResponse::Ok {
|
||||
message: format!("sync folder {} attached: {}", folder.id, folder.local_path),
|
||||
},
|
||||
Err(error) => CtlResponse::error(error),
|
||||
}
|
||||
}
|
||||
CtlRequest::ListSyncFolders => match core.list_sync_folders() {
|
||||
Ok(items) => CtlResponse::SyncFolders { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RemoveSyncFolder { id, delete_remote } => {
|
||||
match core.remove_sync_folder(id, delete_remote) {
|
||||
Ok(()) => {
|
||||
core.touch_profile();
|
||||
CtlResponse::Ok {
|
||||
message: "removed synced folder".to_string(),
|
||||
}
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::SetSyncFolderMode { id, mode } => {
|
||||
match core.request_sync_folder_mode(id, &mode) {
|
||||
Ok(message) => {
|
||||
core.touch_profile();
|
||||
core.log_activity(ActivityKind::Upload, &message, "", true);
|
||||
CtlResponse::Ok { message }
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::SetSyncFolderPaused { id, paused } => {
|
||||
match core.set_sync_folder_paused(id, paused) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: match paused {
|
||||
true => format!("folder {id} paused"),
|
||||
false => format!("folder {id} resumed"),
|
||||
},
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::ResetSyncFolder { id } => match core.reset_sync_folder(id) {
|
||||
Ok(message) => {
|
||||
core.log_activity(ActivityKind::Sync, &message, "", true);
|
||||
CtlResponse::Ok { message }
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::SyncNow { id } => {
|
||||
core.sync_now(id);
|
||||
CtlResponse::Ok {
|
||||
message: match id {
|
||||
Some(id) => format!("reconciling folder {id}"),
|
||||
None => "reconciling all folders".to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
CtlRequest::SetSyncPaused { paused, until } => match core.set_sync_paused(paused, until) {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: match (paused, until) {
|
||||
(false, _) => "sync resumed".to_string(),
|
||||
(true, None) => "sync paused until resumed".to_string(),
|
||||
(true, Some(_)) => "sync paused".to_string(),
|
||||
},
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListConflicts => match core.list_conflicts() {
|
||||
Ok(items) => CtlResponse::Conflicts { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ResolveConflict { path, keep } => match route_change(core, mountpoint, &path) {
|
||||
Ok((core, rel)) => match core.resolve_conflict(&rel, &keep) {
|
||||
Ok(message) => CtlResponse::Ok { message },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListPendingOps => match core.pending_op_infos() {
|
||||
Ok(items) => CtlResponse::PendingOps { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ExportPendingOp { id, dest } => {
|
||||
match core.export_pending_op(id, Path::new(&dest)) {
|
||||
Ok(written) => CtlResponse::Ok {
|
||||
message: format!("wrote {} to {dest}", human_bytes(written)),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
CtlRequest::DiscardPendingOp { id } => match core.discard_pending_op(id) {
|
||||
Ok(path) => CtlResponse::Ok {
|
||||
message: format!("discarded the queued change to {path}"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::RetryPendingOp { id } => match core.retry_pending_ops(id) {
|
||||
Ok(0) if id.is_some() => CtlResponse::Ok {
|
||||
message: "nothing to retry: the operation is already due or waiting for a rename"
|
||||
.to_string(),
|
||||
},
|
||||
Ok(moved) => CtlResponse::Ok {
|
||||
message: format!("retrying {moved} queued operation(s) now"),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListRestorableFolders => match core.list_restorable_folders(None) {
|
||||
Ok(items) => CtlResponse::RestorableFolders { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListDeviceRestorableFolders { device } => {
|
||||
match core.list_restorable_folders(Some(&device)) {
|
||||
Ok(items) => CtlResponse::RestorableFolders { items },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
}
|
||||
request @ (CtlRequest::RestoreSyncFolders { .. }
|
||||
| CtlRequest::RestoreDeviceFolders { .. }) => {
|
||||
let (device, items) = match request {
|
||||
CtlRequest::RestoreDeviceFolders { device, items } => (Some(device), items),
|
||||
CtlRequest::RestoreSyncFolders { items } => (None, items),
|
||||
_ => unreachable!("matched above"),
|
||||
};
|
||||
// Like AddSyncFolder: each restored folder downloads a whole tree,
|
||||
// which outlasts the socket timeout. Ack, then work.
|
||||
let core = core.clone();
|
||||
if let Err(error) =
|
||||
core.services
|
||||
.clone()
|
||||
.spawn_job("pdfs-restore-sync-folders", move || {
|
||||
match core.restore_sync_folders(&items, device.as_deref()) {
|
||||
Ok(outcome) => {
|
||||
core.touch_profile();
|
||||
if !outcome.complete() {
|
||||
warn!(skipped = ?outcome.skipped, "restore skipped folders");
|
||||
}
|
||||
core.log_activity(
|
||||
ActivityKind::Download,
|
||||
outcome.summary(),
|
||||
outcome.skipped.join("; "),
|
||||
outcome.complete(),
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(error = %e, "restore failed");
|
||||
core.log_activity(
|
||||
ActivityKind::Download,
|
||||
"restore folders",
|
||||
&e,
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
})
|
||||
{
|
||||
tracing::warn!(%error, "could not start pdfs-restore-sync-folders");
|
||||
}
|
||||
CtlResponse::Ok {
|
||||
message: "restoring folders".to_string(),
|
||||
}
|
||||
}
|
||||
// `control` only hands over what `request!` matches.
|
||||
_ => CtlResponse::error(CoreError::internal("not a sync request".to_string())),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//! The control requests about Drive's trash and the local content cache.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The requests [`answer`] serves, as a pattern, so the control socket's match
|
||||
/// hands exactly these over and the compiler still checks that it covers every
|
||||
/// request.
|
||||
macro_rules! request {
|
||||
() => {
|
||||
::pdfs_core::control::Request::ListTrash
|
||||
| ::pdfs_core::control::Request::ListTrashedFolder { .. }
|
||||
| ::pdfs_core::control::Request::Restore { .. }
|
||||
| ::pdfs_core::control::Request::DeleteForever { .. }
|
||||
| ::pdfs_core::control::Request::EmptyTrash
|
||||
| ::pdfs_core::control::Request::PurgeCache
|
||||
| ::pdfs_core::control::Request::CacheInspect { .. }
|
||||
| ::pdfs_core::control::Request::CacheVacuum
|
||||
| ::pdfs_core::control::Request::SetCacheBudget { .. }
|
||||
};
|
||||
}
|
||||
pub(super) use request;
|
||||
|
||||
/// Answer a request that [`request!`] matches.
|
||||
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
let Ask { core, .. } = *ask;
|
||||
match request {
|
||||
CtlRequest::ListTrash => match core.list_trash() {
|
||||
Ok(entries) => CtlResponse::Entries { entries },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::ListTrashedFolder { uid } => match core.list_trashed_folder(&uid) {
|
||||
Ok(entries) => CtlResponse::Entries { entries },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::Restore { uids } => match core.restore(&uids) {
|
||||
Ok(n) => {
|
||||
core.log_activity(ActivityKind::Restore, format!("{n} item(s)"), "", true);
|
||||
CtlResponse::Ok {
|
||||
message: format!("restored {n} item(s)"),
|
||||
}
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::DeleteForever { uids } => match core.delete_forever(&uids) {
|
||||
Ok(n) => {
|
||||
core.log_activity(
|
||||
ActivityKind::DeleteForever,
|
||||
format!("{n} item(s)"),
|
||||
"",
|
||||
true,
|
||||
);
|
||||
CtlResponse::Ok {
|
||||
message: format!("permanently deleted {n} item(s)"),
|
||||
}
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::EmptyTrash => match core.empty_trash() {
|
||||
Ok(n) => {
|
||||
let items = if n == 1 {
|
||||
"1 item".to_string()
|
||||
} else {
|
||||
format!("{n} items")
|
||||
};
|
||||
core.log_activity(ActivityKind::EmptyTrash, items.clone(), "", true);
|
||||
CtlResponse::Ok {
|
||||
message: format!("emptied trash ({items})"),
|
||||
}
|
||||
}
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::PurgeCache => {
|
||||
let freed = core.cache.clear_unpinned();
|
||||
CtlResponse::Ok {
|
||||
message: format!(
|
||||
"purged {:.1} MiB of unpinned cache",
|
||||
freed as f64 / 1_048_576.0
|
||||
),
|
||||
}
|
||||
}
|
||||
CtlRequest::CacheInspect { deep } => match core.db.stats() {
|
||||
Ok(stats) => {
|
||||
// The deep check reads every page — tens of seconds on a real
|
||||
// database, all of it holding the connection every FUSE handler
|
||||
// needs — so it runs on a thread and this request returns
|
||||
// whatever the last completed check found. `integrity_checked`
|
||||
// tells the caller which answer it is holding, since "no
|
||||
// problems found" and "never looked" are both an empty list;
|
||||
// `integrity_running` says a fresh answer is on its way.
|
||||
let (integrity_problems, integrity_checked, integrity_running) = if deep {
|
||||
core.start_or_read_integrity_check()
|
||||
} else {
|
||||
(Vec::new(), false, false)
|
||||
};
|
||||
CtlResponse::CacheReport {
|
||||
integrity_running,
|
||||
schema_version: stats.schema_version,
|
||||
db_bytes: stats.total_bytes(),
|
||||
db_reclaimable_bytes: stats.reclaimable_bytes(),
|
||||
tables: stats.tables,
|
||||
cache_used: core.cache.usage(),
|
||||
cache_budget: core.cache.budget(),
|
||||
integrity_problems,
|
||||
integrity_checked,
|
||||
}
|
||||
}
|
||||
Err(e) => CtlResponse::error(CoreError::internal(format!("read db stats: {e:?}"))),
|
||||
},
|
||||
CtlRequest::CacheVacuum => match core.start_vacuum() {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: "compacting the cache database in the background".into(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
CtlRequest::SetCacheBudget { bytes } => {
|
||||
core.cache.set_budget(bytes);
|
||||
// Persist so the next mount keeps the new cap. Best-effort: a config
|
||||
// write failure is reported but the live cap is already applied.
|
||||
match AppDirs::new()
|
||||
.map(|dirs| dirs.update_config(|cfg| cfg.cache_budget = Some(bytes)))
|
||||
{
|
||||
Ok(Ok(())) => {
|
||||
core.touch_profile();
|
||||
CtlResponse::Ok {
|
||||
message: format!("cache budget set to {bytes} bytes"),
|
||||
}
|
||||
}
|
||||
Ok(Err(e)) => CtlResponse::error(CoreError::internal(format!(
|
||||
"budget applied but config write failed: {e}"
|
||||
))),
|
||||
Err(e) => CtlResponse::error(CoreError::internal(format!(
|
||||
"budget applied but config unavailable: {e}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
// `control` only hands over what `request!` matches.
|
||||
_ => CtlResponse::error(CoreError::internal("not a trash request".to_string())),
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::batch;
|
||||
@@ -23,7 +22,6 @@ use pdfs_core::{CoreError, CoreResult};
|
||||
use pdfs_store::db::{StoredDevice, StoredSyncFolder};
|
||||
use proton_drive_rs::proton_sdk::ids::{DeviceUid, NodeUid};
|
||||
use proton_drive_rs::{DeviceType, Node};
|
||||
use std::sync::OnceLock;
|
||||
use tracing::{info, warn};
|
||||
|
||||
use super::sync::{self, base_name};
|
||||
@@ -782,10 +780,7 @@ impl Core {
|
||||
/// kernel channel, both filled in when the session is built.
|
||||
pub(crate) fn fork_state(&self) -> Core {
|
||||
let mut fork = self.clone();
|
||||
fork.primary = false;
|
||||
fork.root = Arc::new(OnceLock::new());
|
||||
fork.notifier = Arc::new(OnceLock::new());
|
||||
fork.session_live = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
fork.session = self.session.fork();
|
||||
fork
|
||||
}
|
||||
|
||||
@@ -1173,7 +1168,7 @@ impl Core {
|
||||
root: Node,
|
||||
) -> CoreResult<SecondaryMount> {
|
||||
let core = self.fork_state();
|
||||
let session_live = core.session_live.clone();
|
||||
let session_live = core.session.session_live.clone();
|
||||
// The fork owns this state/path registration. `spawn_session` only
|
||||
// marks it live after FUSE has spawned successfully.
|
||||
core.register_state(local);
|
||||
|
||||
@@ -174,6 +174,16 @@ impl Core {
|
||||
age_secs: service.age.as_secs(),
|
||||
})
|
||||
.collect(),
|
||||
jobs: self
|
||||
.services
|
||||
.jobs()
|
||||
.into_iter()
|
||||
.map(|job| ServiceState {
|
||||
name: job.name,
|
||||
running: job.running,
|
||||
age_secs: job.age.as_secs(),
|
||||
})
|
||||
.collect(),
|
||||
drive_calls: self
|
||||
.drive_calls
|
||||
.snapshot()
|
||||
|
||||
@@ -394,7 +394,7 @@ impl Core {
|
||||
// the wire, so trashing its folder kept it as a trash; claimed
|
||||
// only to be handed back, it was kept although nothing had sent
|
||||
// it (`docs/BUGS.md` B178).
|
||||
let online = self.online.load(Ordering::Relaxed);
|
||||
let online = self.is_online();
|
||||
let paused = self.sync_paused();
|
||||
// One row, chosen and *claimed* by the database. Reading the whole
|
||||
// queue to pick one op made a long queue quadratic to drain, and
|
||||
@@ -773,7 +773,7 @@ impl Core {
|
||||
/// is disarmed, letting a gap-fill read from a revision that no longer
|
||||
/// describes the file.
|
||||
pub(crate) fn release_pending(&self, uid: &NodeUid, blob: &Path) {
|
||||
let mut pending = self.pending.lock();
|
||||
let mut pending = self.writes.pending.lock();
|
||||
if let Some(current) = pending.get(uid)
|
||||
&& current.path == blob
|
||||
{
|
||||
|
||||
@@ -233,7 +233,7 @@ impl Core {
|
||||
.insert(real.clone(), local.clone());
|
||||
}
|
||||
// The feed will report this create back to us; the tree already has it
|
||||
// under its real uid, so that event is ours to ignore (`Core::self_changes`).
|
||||
// under its real uid, so that event is ours to ignore (`WriteState::note_echo`).
|
||||
self.note_self_change(&real);
|
||||
// The uploaded blob is done with either way: a write that replaced it
|
||||
// while it was on the wire already discarded it when it attached.
|
||||
@@ -358,7 +358,7 @@ impl Core {
|
||||
// while its trash is on the wire or a listing still shows it. Taking a
|
||||
// folder removed and made again put the new one's contents into the
|
||||
// old one, and its trash took them along (docs/BUGS.md B162).
|
||||
let hidden = self.hidden.lock().clone();
|
||||
let hidden = self.writes.hidden();
|
||||
let Some(twin) = children
|
||||
.into_iter()
|
||||
.find(|node| node.name == name && !node.trashed && !hidden.contains(&node.uid))
|
||||
@@ -514,7 +514,7 @@ impl Core {
|
||||
real: &NodeUid,
|
||||
) -> Result<CreateRetired, Box<dyn std::error::Error>> {
|
||||
let retired = {
|
||||
let mut pending = self.pending.lock();
|
||||
let mut pending = self.writes.pending.lock();
|
||||
let retired = self.db.finish_create(op.id, uploaded, landing, |json| {
|
||||
let mut meta: StagedWrite = serde_json::from_str(json).ok()?;
|
||||
meta.uid = landing.real.to_string();
|
||||
|
||||
@@ -552,7 +552,7 @@ impl Core {
|
||||
// This function's whole job is to bring the tree level with the revision
|
||||
// we just sealed, so the feed's report of that revision has nothing left
|
||||
// to tell us. Claimed here rather than at the upload call so it is only
|
||||
// recorded when the node was actually re-read (`Core::self_changes`).
|
||||
// recorded when the node was actually re-read (`WriteState::note_echo`).
|
||||
self.note_self_change(uid);
|
||||
// Rebase any *open* write handles targeting this node. A handle opened
|
||||
// before this upload carries a stale base — its `base_mtime`/`base_size`
|
||||
@@ -680,7 +680,7 @@ impl Core {
|
||||
hash: None,
|
||||
revision_id: node_revision_id(sealed),
|
||||
};
|
||||
let mut pending = self.pending.lock();
|
||||
let mut pending = self.writes.pending.lock();
|
||||
let Some(p) = pending.get_mut(uid) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -19,7 +19,7 @@ impl Core {
|
||||
if is_local_uid_str(&op.uid) {
|
||||
match self.withdrawn_twin(op)? {
|
||||
Some(twin) => {
|
||||
self.hidden.lock().insert(twin.clone());
|
||||
self.writes.hide(&twin);
|
||||
match self
|
||||
.block_on_bounded(self.drive.trash_nodes(std::slice::from_ref(&twin)))
|
||||
.and_then(batch::into_unit)
|
||||
@@ -131,7 +131,7 @@ impl Core {
|
||||
// mount trashed is not one, and a node in the tree was answered for.
|
||||
// A file of the user's renamed to the name the create was sent under
|
||||
// was taken for it, and trashed (`docs/BUGS.md` B193).
|
||||
let hidden = self.hidden.lock().clone();
|
||||
let hidden = self.writes.hidden();
|
||||
let Some(twin) = children
|
||||
.into_iter()
|
||||
.find(|node| node.name == name && !node.trashed && !hidden.contains(&node.uid))
|
||||
@@ -191,7 +191,7 @@ impl Core {
|
||||
real: &NodeUid,
|
||||
name: &str,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
self.hidden.lock().insert(real.clone());
|
||||
self.writes.hide(real);
|
||||
self.note_self_change(real);
|
||||
let trash = PendingOp {
|
||||
id: trash,
|
||||
|
||||
@@ -7,22 +7,22 @@ impl Core {
|
||||
/// Record that this daemon just changed `uid` on the remote, so the event
|
||||
/// feed's echo of that change is recognised instead of re-applied. Called
|
||||
/// from the drain once the remote has actually accepted the change and the
|
||||
/// tree has been brought level with it. See [`Core::self_changes`].
|
||||
/// tree has been brought level with it. See [`writes::WriteState`].
|
||||
pub(crate) fn note_self_change(&self, uid: &NodeUid) {
|
||||
note_self_change(&mut self.self_changes.lock(), uid, now_millis());
|
||||
self.writes.note_echo(uid, now_millis());
|
||||
}
|
||||
|
||||
/// Claim one outstanding echo for `uid`, reporting whether this event is one
|
||||
/// this daemon caused. Consuming rather than merely testing is what bounds
|
||||
/// the suppression: the next event for the node applies normally.
|
||||
pub(super) fn take_self_change(&self, uid: &NodeUid) -> bool {
|
||||
take_self_change(&mut self.self_changes.lock(), uid, now_millis())
|
||||
self.writes.take_echo(uid, now_millis())
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a change this daemon made stays recognisable as its own. Generous
|
||||
/// against a feed that can lag, but finite: past it, an event for the node is
|
||||
/// applied like any other. See [`Core::self_changes`].
|
||||
/// applied like any other. See [`writes::WriteState`].
|
||||
pub(super) const SELF_CHANGE_TTL_MS: i64 = 120_000;
|
||||
|
||||
/// A remote change this daemon made, awaiting its echo from the event feed.
|
||||
|
||||
@@ -204,7 +204,7 @@ impl Core {
|
||||
if is_local_uid(uid) {
|
||||
return None;
|
||||
}
|
||||
match self.pending.lock().get(uid) {
|
||||
match self.writes.pending.lock().get(uid) {
|
||||
Some(p) => p.meta.based_on.clone(),
|
||||
None => Some(Baseline {
|
||||
mtime: base_mtime,
|
||||
@@ -247,7 +247,7 @@ impl Core {
|
||||
// of exactly the ranges this write did not touch, and what neither wrote
|
||||
// is still the remote content that the earlier write was based on, which
|
||||
// is why the baseline is inherited along with them.
|
||||
let previous = self.pending.lock().get(uid).cloned();
|
||||
let previous = self.writes.queued(uid);
|
||||
if !meta.complete
|
||||
&& let Some(previous) = previous
|
||||
&& let Err(error) = merge_over_pending(&mut meta, src, &previous)
|
||||
@@ -302,7 +302,7 @@ impl Core {
|
||||
// carries it over, or has already finished and this write
|
||||
// queues against the real uid below (`Core::retire_create`).
|
||||
let meta_json = serde_json::to_string(&meta).unwrap_or_default();
|
||||
let mut pending = self.pending.lock();
|
||||
let mut pending = self.writes.pending.lock();
|
||||
let attached = self
|
||||
.db
|
||||
.attach_blob_to_create(&uid.to_string(), &path.to_string_lossy(), &meta_json)
|
||||
@@ -325,7 +325,7 @@ impl Core {
|
||||
debug!(local = %uid, %real, "create landed under an open write; queueing a revision");
|
||||
uid = real;
|
||||
meta.uid = uid.to_string();
|
||||
let previous = self.pending.lock().get(&uid).cloned();
|
||||
let previous = self.writes.queued(&uid);
|
||||
meta.based_on = previous.as_ref().and_then(|p| p.meta.based_on.clone());
|
||||
if !meta.complete
|
||||
&& let Some(previous) = previous
|
||||
@@ -353,7 +353,8 @@ impl Core {
|
||||
error!(%uid, error = %e, "queueing upload failed");
|
||||
Errno::EIO
|
||||
})?;
|
||||
self.pending
|
||||
self.writes
|
||||
.pending
|
||||
.lock()
|
||||
.insert(uid.clone(), PendingRevision { path, meta });
|
||||
superseded
|
||||
@@ -436,7 +437,7 @@ impl Core {
|
||||
// case the remote is *not* our base: the complete staged revision is.
|
||||
// Compose from those local bytes so the truncate can supersede the
|
||||
// queued upload without fetching stale remote content or returning EIO.
|
||||
let pending_base = self.pending.lock().get(&uid).cloned();
|
||||
let pending_base = self.writes.queued(&uid);
|
||||
if pending_base
|
||||
.as_ref()
|
||||
.is_some_and(|pending| !pending.meta.complete)
|
||||
@@ -726,7 +727,7 @@ impl Core {
|
||||
} else {
|
||||
self.release_dropped_ops(uid, blobs);
|
||||
}
|
||||
self.hidden.lock().insert(uid.clone());
|
||||
self.writes.hide(uid);
|
||||
// Withdrawn from the tree, which every mount serves from, so no other
|
||||
// mount goes on serving a file the user just trashed (`docs/BUGS.md`
|
||||
// B74).
|
||||
@@ -786,7 +787,7 @@ impl Core {
|
||||
/// (`docs/BUGS.md` B102), so the entries to forget are found by blob, not
|
||||
/// only by `uid`.
|
||||
pub(super) fn release_dropped_ops(&self, uid: &NodeUid, blobs: Vec<String>) {
|
||||
self.pending.lock().remove(uid);
|
||||
self.writes.pending.lock().remove(uid);
|
||||
self.release_dropped_below(blobs);
|
||||
}
|
||||
|
||||
@@ -794,7 +795,7 @@ impl Core {
|
||||
/// entry.
|
||||
pub(super) fn release_dropped_below(&self, blobs: Vec<String>) {
|
||||
let below: Vec<NodeUid> = {
|
||||
let mut pending = self.pending.lock();
|
||||
let mut pending = self.writes.pending.lock();
|
||||
let below: Vec<NodeUid> = pending
|
||||
.iter()
|
||||
.filter(|(_, p)| blobs.iter().any(|b| p.path == Path::new(b)))
|
||||
|
||||
@@ -325,7 +325,7 @@ impl Filesystem for ProtonFs {
|
||||
};
|
||||
let is_video =
|
||||
PhotoKind::classify(Some(&e.node.name), media_type) == PhotoKind::Video;
|
||||
let queued = self.core.pending.lock().get(&e.uid).map(|p| p.meta.len);
|
||||
let queued = self.core.writes.queued_len(&e.uid);
|
||||
// Still the cheap enumeration's ciphertext size (B12).
|
||||
let provisional = queued.is_none()
|
||||
&& matches!(
|
||||
@@ -1160,7 +1160,7 @@ impl ProtonFs {
|
||||
/// the folder an on-demand location shows).
|
||||
pub(super) fn new(core: Core, root: Node) -> Self {
|
||||
let root = core.state().install_root(root);
|
||||
let _ = core.root.set(root);
|
||||
let _ = core.session.root.set(root);
|
||||
// SAFETY: geteuid/getegid are infallible and have no preconditions.
|
||||
let (uid, gid) = unsafe { (libc::geteuid(), libc::getegid()) };
|
||||
Self {
|
||||
@@ -1413,7 +1413,7 @@ impl ProtonFs {
|
||||
}
|
||||
}
|
||||
}
|
||||
let pending_base = self.core.pending.lock().get(&uid).cloned();
|
||||
let pending_base = self.core.writes.queued(&uid);
|
||||
let (file, path) = match self.core.cache.create_scratch() {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
@@ -2234,7 +2234,7 @@ impl ProtonFs {
|
||||
// before it lets those updates overwrite our invalidation
|
||||
// and retain an empty destination readdir page.
|
||||
reply.ok();
|
||||
if let Some(notifier) = self.core.notifier.get() {
|
||||
if let Some(notifier) = self.core.session.notifier.get() {
|
||||
let _ = notifier.inval_entry(parent, OsStr::new(&name));
|
||||
let _ = notifier.inval_entry(newparent, OsStr::new(&newname));
|
||||
let _ = notifier.inval_inode(parent);
|
||||
@@ -2402,7 +2402,7 @@ impl ProtonFs {
|
||||
}
|
||||
// Only remove the namespace entry after Drive accepted the mutation.
|
||||
// Otherwise an EIO response still made the path disappear locally.
|
||||
self.core.hidden.lock().insert(uid.clone());
|
||||
self.core.writes.hide(&uid);
|
||||
self.core.state().forget_or_unlink(&uid);
|
||||
if open_now {
|
||||
// The open handle keeps the staged bytes; the drain must not send
|
||||
|
||||
@@ -231,7 +231,7 @@ impl Core {
|
||||
claimed_size.is_none(),
|
||||
)
|
||||
};
|
||||
if is_local_uid(&uid) || self.pending.lock().contains_key(&uid) {
|
||||
if is_local_uid(&uid) || self.writes.is_queued(&uid) {
|
||||
return None;
|
||||
}
|
||||
let size = match provisional {
|
||||
|
||||
+47
-100
@@ -108,6 +108,8 @@ mod inhibit;
|
||||
mod keeper;
|
||||
mod link;
|
||||
mod listing;
|
||||
mod session;
|
||||
mod writes;
|
||||
pub use filesystem::ProtonFs;
|
||||
mod maintenance;
|
||||
mod mount;
|
||||
@@ -116,6 +118,7 @@ mod photos;
|
||||
mod pins;
|
||||
mod profile;
|
||||
mod queue;
|
||||
mod quota;
|
||||
mod reads;
|
||||
mod recovery;
|
||||
mod redate;
|
||||
@@ -533,14 +536,15 @@ struct Core {
|
||||
/// The daemon's My Files root. Forked on-demand sessions retain this value
|
||||
/// so ownership checks never mistake their own mount root for account scope.
|
||||
primary_root_uid: NodeUid,
|
||||
/// False only for a forked on-demand device mount. The synthetic shared
|
||||
/// directory belongs exclusively to the primary My Files mount.
|
||||
primary: bool,
|
||||
/// What belongs to one mount's FUSE session rather than to the daemon: whether
|
||||
/// it is the primary My Files mount, the tree inode it is rooted at, its
|
||||
/// kernel channel and whether the session is up.
|
||||
///
|
||||
/// Every other part of `Core` is shared between the primary mount and its
|
||||
/// on-demand forks. A fork gets fresh cells from [`SessionCells::fork`].
|
||||
session: session::SessionCells,
|
||||
/// The one tree every mount of the daemon serves from.
|
||||
state: Arc<Ranked<State>>,
|
||||
/// The tree inode this mount's session is rooted at, set when the session
|
||||
/// is built ([`ProtonFs::new`]). Each fork has its own cell.
|
||||
root: Arc<OnceLock<u64>>,
|
||||
cache: Arc<ContentCache>,
|
||||
/// What the read path keeps between reads: open revision readers, decrypted
|
||||
/// blocks, fetches in flight and prefetch. See [`reads::ReadState`].
|
||||
@@ -556,29 +560,20 @@ struct Core {
|
||||
/// Publication of the shared listing, and what invalidates a listing on the
|
||||
/// wire or suppresses its next refresh.
|
||||
shared: shared::SharedState,
|
||||
/// False while the API is unreachable and we are serving the cached tree.
|
||||
/// Set by the probe thread; read by front-ends through
|
||||
/// `Response::Status` so the UI can say so rather than leaving the user to
|
||||
/// infer it from a wall of EIO.
|
||||
online: Arc<AtomicBool>,
|
||||
/// When the link went down and a condvar for its coming back; the other
|
||||
/// half of `online` (see [`link`]).
|
||||
/// Whether Drive answers, when the link went down and a condvar for its
|
||||
/// coming back (see [`link`]).
|
||||
link: Arc<link::Link>,
|
||||
/// When the user paused syncing, the Unix second it resumes by itself;
|
||||
/// [`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>,
|
||||
/// 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.
|
||||
/// Whether the user paused syncing, and until when. Persisted, so a pause
|
||||
/// survives a restart. See [`pause::SyncPause`].
|
||||
pause: pause::SyncPause,
|
||||
/// The write-back's state: writes accepted from the kernel and not yet sent,
|
||||
/// nodes removed here that a stale listing may still return, and the changes
|
||||
/// this daemon made that Drive's event feed will echo back.
|
||||
///
|
||||
/// Two things read it: [`Core::read_range`], because until the op drains the
|
||||
/// staged blob *is* the file's content and the remote still holds the old
|
||||
/// revision; and the drain worker, which performs the uploads.
|
||||
pending: Arc<Mutex<HashMap<NodeUid, PendingRevision>>>,
|
||||
/// Nodes removed through this daemon which a briefly stale remote listing
|
||||
/// may still return. Uids are not reused; an explicit restore clears one.
|
||||
hidden: Arc<Mutex<HashSet<NodeUid>>>,
|
||||
/// The drain, the queue and recovery own it. Everything else, the read path,
|
||||
/// listings, the pin keeper and the event feed, asks through the methods
|
||||
/// below instead of taking its locks.
|
||||
writes: writes::WriteState,
|
||||
/// The drain's own bookkeeping: its wake-up, the creates and uploads on
|
||||
/// the wire, and what they left behind. See [`drain::DrainState`].
|
||||
drain: drain::DrainState,
|
||||
@@ -605,7 +600,10 @@ struct Core {
|
||||
photo_jobs: photos::PhotoJobs,
|
||||
/// The last account quota answer, for `statfs(2)`, and whether a refresh
|
||||
/// of it is running.
|
||||
quota_cache: sharing::QuotaCache,
|
||||
quota: quota::QuotaCache,
|
||||
/// Sharing, public links, invitations and bookmarks. See
|
||||
/// [`sharing::Sharing`].
|
||||
sharing: sharing::Sharing,
|
||||
/// Database maintenance that has been moved off the request thread.
|
||||
///
|
||||
/// `VACUUM` and a deep `integrity_check` both hold the single connection for
|
||||
@@ -617,19 +615,6 @@ struct Core {
|
||||
/// The size upgrades running now, and the replies parked on them. Shared
|
||||
/// by every mount: the bound that matters is per daemon.
|
||||
sizes: sizes::SizeState,
|
||||
/// This mount's kernel notification channel, for telling the kernel to drop
|
||||
/// metadata it has cached. Set once the session exists — which is *after*
|
||||
/// the `Core` it is built from, hence the cell.
|
||||
///
|
||||
/// Per mount, not per daemon: each session calls its own root inode 1.
|
||||
/// [`Core::fork_state`] gives each fork an empty cell of its own. Work that
|
||||
/// changes the tree for every mount tells every session
|
||||
/// ([`Core::for_each_mount`]).
|
||||
notifier: Arc<OnceLock<KernelChannel>>,
|
||||
/// True only after this mount's FUSE session spawned successfully.
|
||||
/// Registration happens earlier for the primary drain, so registration
|
||||
/// alone cannot answer whether the location is mounted.
|
||||
session_live: Arc<AtomicBool>,
|
||||
/// In-flight upload/download progress, served to `GetQueueStatus`. Shared
|
||||
/// across the FUSE session and the control-socket task.
|
||||
transfers: Arc<TransferRegistry>,
|
||||
@@ -653,26 +638,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>>>,
|
||||
/// Nodes this daemon changed on the remote itself, and how many echoes of
|
||||
/// those changes the event feed still owes us.
|
||||
///
|
||||
/// The feed replays our own writes back at us seconds later, and a
|
||||
/// `NodeUpdated` carries no revision id — nothing in it distinguishes "another
|
||||
/// device changed this file" from "you changed this file". Treating the echo
|
||||
/// as foreign is not free: it evicts the content blob we just uploaded, so the
|
||||
/// next read re-downloads a revision the API may not be serving yet. That is
|
||||
/// how a SQLite database written on the mount came back `malformed`, and how a
|
||||
/// mount doing bulk uploads spent its time re-fetching its own bytes.
|
||||
///
|
||||
/// So the first event for a node we changed ourselves, within
|
||||
/// [`SELF_CHANGE_TTL_MS`], is consumed rather than applied: the tree already
|
||||
/// holds what that event describes, because [`Core::refresh_after_upload`] put
|
||||
/// it there. Anything beyond that applies normally, which bounds the staleness
|
||||
/// a genuine remote change can suffer to one event.
|
||||
///
|
||||
/// Shared across forks like `pending`: the drain that records the change and
|
||||
/// the event task that consumes the echo are both per-daemon.
|
||||
self_changes: Arc<Mutex<HashMap<NodeUid, echoes::SelfChange>>>,
|
||||
/// Every live mount: the primary and one per on-demand fork
|
||||
/// ([`Core::fork_state`]), with its mountpoint, root and kernel channel.
|
||||
/// Shared by every fork.
|
||||
@@ -820,16 +785,16 @@ impl Core {
|
||||
fn register_state(&self, mountpoint: &Path) {
|
||||
self.states.register(
|
||||
mountpoint,
|
||||
&self.notifier,
|
||||
self.session_live.clone(),
|
||||
self.root.clone(),
|
||||
&self.session.notifier,
|
||||
self.session.session_live.clone(),
|
||||
self.session.root.clone(),
|
||||
);
|
||||
}
|
||||
|
||||
/// The tree inode this mount is rooted at. [`ROOT_INO`] until the session
|
||||
/// is built, which is where a test that builds a bare tree puts its root.
|
||||
pub(crate) fn root_ino(&self) -> u64 {
|
||||
self.root.get().copied().unwrap_or(ROOT_INO)
|
||||
self.session.root.get().copied().unwrap_or(ROOT_INO)
|
||||
}
|
||||
|
||||
/// Whether `uid` names an owned node reachable from the root of a mounted
|
||||
@@ -857,14 +822,16 @@ impl Core {
|
||||
let mount = self.states.covering(abs)?;
|
||||
let rel = abs.strip_prefix(&mount.mountpoint).ok()?.to_path_buf();
|
||||
let mut core = self.clone();
|
||||
if !Arc::ptr_eq(&mount.notifier, &self.notifier) {
|
||||
if !Arc::ptr_eq(&mount.notifier, &self.session.notifier) {
|
||||
// Another mount, so adopt its per-mount half wholesale. `primary`
|
||||
// is a property of the mount, and the only mount this `Core` can
|
||||
// be the primary of is the one it was built for.
|
||||
core.primary = false;
|
||||
core.notifier = mount.notifier;
|
||||
core.session_live = mount.session_live;
|
||||
core.root = mount.root;
|
||||
core.session = session::SessionCells {
|
||||
primary: false,
|
||||
notifier: mount.notifier,
|
||||
session_live: mount.session_live,
|
||||
root: mount.root,
|
||||
};
|
||||
}
|
||||
Some((core, rel))
|
||||
}
|
||||
@@ -1398,7 +1365,7 @@ impl Core {
|
||||
/// swaps the map entry to point at it, so an unchanged path means the base a
|
||||
/// caller sampled earlier is still the base now (`docs/BUGS.md` B32).
|
||||
fn pending_blob(&self, uid: &NodeUid) -> Option<PathBuf> {
|
||||
self.pending.lock().get(uid).map(|p| p.path.clone())
|
||||
self.writes.queued(uid).map(|queued| queued.path)
|
||||
}
|
||||
|
||||
/// Nudge the drain worker to re-examine the queue now.
|
||||
@@ -1408,32 +1375,12 @@ impl Core {
|
||||
cv.notify_all();
|
||||
}
|
||||
|
||||
/// Download a whole file's plaintext, registering the transfer so
|
||||
/// Download a whole file into `out`, registering the transfer so
|
||||
/// `GetQueueStatus` can report its progress. `total` is the expected size
|
||||
/// (`0` if unknown). Streams through [`download_file_to`] so each block ticks
|
||||
/// the progress counter.
|
||||
/// the progress counter, and nothing is held in memory.
|
||||
///
|
||||
/// [`download_file_to`]: ProtonDriveClient::download_file_to
|
||||
fn download_file_tracked(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
name: &str,
|
||||
total: u64,
|
||||
) -> std::result::Result<Vec<u8>, ProtonError> {
|
||||
let guard = self
|
||||
.transfers
|
||||
.begin(name, uid.to_string(), TransferDirection::Download, total);
|
||||
let mut out = CountingWriter::new(Vec::with_capacity(total as usize), &guard);
|
||||
self.rt
|
||||
.block_on(self.drive.download_file_to(uid, &mut out))?;
|
||||
Ok(out.into_inner())
|
||||
}
|
||||
|
||||
/// Download a whole file directly into `out`, without retaining its
|
||||
/// plaintext in memory. This is the disk-backed twin of
|
||||
/// [`Core::download_file_tracked`], and preserves the same transfer
|
||||
/// accounting while allowing callers that only need an on-disk file to
|
||||
/// keep memory use independent of file size.
|
||||
fn download_file_tracked_to<W: Write + Send>(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
@@ -1450,10 +1397,10 @@ impl Core {
|
||||
Ok(out.into_inner())
|
||||
}
|
||||
|
||||
/// Like [`download_file_tracked`] for a photo, streaming through the photos
|
||||
/// client's [`download_photo_to`].
|
||||
/// Like [`download_file_tracked_to`] for a photo, streaming through the
|
||||
/// photos client's [`download_photo_to`].
|
||||
///
|
||||
/// [`download_file_tracked`]: Core::download_file_tracked
|
||||
/// [`download_file_tracked_to`]: Core::download_file_tracked_to
|
||||
/// [`download_photo_to`]: ProtonPhotosClient::download_photo_to
|
||||
fn download_photo_tracked(
|
||||
&self,
|
||||
@@ -3924,7 +3871,7 @@ mod tests {
|
||||
assert_before(revision, "preserve_on_access_denied", "fill_gaps");
|
||||
|
||||
let staged = function_source(source, "fn enqueue_staged_write(");
|
||||
assert_before(staged, "preserve_on_access_denied", "self.pending.lock()");
|
||||
assert_before(staged, "preserve_on_access_denied", "self.writes.queued(");
|
||||
assert_before(
|
||||
staged,
|
||||
"preserve_on_access_denied",
|
||||
@@ -3932,7 +3879,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let truncate = function_source(source, "fn queue_truncate(");
|
||||
assert_before(truncate, "require_uid_writable", "self.pending.lock()");
|
||||
assert_before(truncate, "require_uid_writable", "self.writes.queued(");
|
||||
assert_before(truncate, "require_uid_writable", "create_scratch");
|
||||
|
||||
for (signature, first_side_effect) in [
|
||||
@@ -4081,7 +4028,7 @@ mod tests {
|
||||
assert_before(
|
||||
restore,
|
||||
"self.drive.restore_nodes(",
|
||||
"self.hidden.lock().remove(uid)",
|
||||
"self.writes.unhide(uid)",
|
||||
);
|
||||
assert!(restore.contains("st.invalidate_listing(ino)"));
|
||||
assert!(restore.contains("notify.inval_entry(ino, name.to_string())"));
|
||||
@@ -4328,7 +4275,7 @@ mod tests {
|
||||
// once; the bytes the handle reads go with the last close.
|
||||
let withdraw = function_source(CORE_SOURCE, "fn withdraw_queued_ops(");
|
||||
assert_before(withdraw, "self.pending_blob(uid)", "release_dropped_below");
|
||||
assert!(!withdraw.contains("self.pending.lock().remove(uid)"));
|
||||
assert!(!withdraw.contains("self.writes.pending.lock().remove(uid)"));
|
||||
|
||||
let filesystem = include_str!("filesystem.rs");
|
||||
let trash = function_source(filesystem, "fn trash_child(");
|
||||
|
||||
@@ -58,6 +58,11 @@ const IDLE_CHECK: Duration = Duration::from_secs(1);
|
||||
/// that fires on every change so waiters need not poll.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Link {
|
||||
/// False while the API is unreachable and we are serving the cached tree.
|
||||
/// Set by the probe thread; read by front-ends through
|
||||
/// `Response::Status` so the UI can say so rather than leaving the user to
|
||||
/// infer it from a wall of EIO.
|
||||
online: AtomicBool,
|
||||
lost_at: Mutex<Option<Instant>>,
|
||||
changed: Condvar,
|
||||
/// Folders listed from the DB alone while offline, to relist once back.
|
||||
@@ -74,10 +79,11 @@ pub(crate) struct Link {
|
||||
}
|
||||
|
||||
impl Link {
|
||||
/// The link of a mount that comes up with Proton refusing its session, or
|
||||
/// not.
|
||||
pub(crate) fn starting(session_expired: bool) -> Self {
|
||||
/// The link of a mount that comes up online or from the cache, with
|
||||
/// Proton refusing its session or not.
|
||||
pub(crate) fn starting(online: bool, session_expired: bool) -> Self {
|
||||
Self {
|
||||
online: AtomicBool::new(online),
|
||||
session_expired: AtomicBool::new(session_expired),
|
||||
..Default::default()
|
||||
}
|
||||
@@ -154,7 +160,7 @@ fn next_probe_delay(delay: Duration, outage: Duration) -> Duration {
|
||||
impl Core {
|
||||
/// Whether the mount currently believes Proton is reachable.
|
||||
pub(crate) fn is_online(&self) -> bool {
|
||||
self.online.load(Ordering::Relaxed)
|
||||
self.link.online.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Whether a namespace change through the mount goes to Drive inside the
|
||||
@@ -237,7 +243,7 @@ impl Core {
|
||||
/// outage logs it; the rest are the same outage.
|
||||
pub(crate) fn mark_offline(&self, what: &str, error: &dyn std::fmt::Display) {
|
||||
let mut lost_at = self.link.lost_at.lock();
|
||||
if self.online.swap(false, Ordering::Relaxed) {
|
||||
if self.link.online.swap(false, Ordering::Relaxed) {
|
||||
*lost_at = Some(Instant::now());
|
||||
warn!(during = what, %error,
|
||||
"lost the connection to Proton; queueing changes until it returns");
|
||||
@@ -250,7 +256,7 @@ impl Core {
|
||||
fn mark_online(&self) {
|
||||
{
|
||||
let mut lost_at = self.link.lost_at.lock();
|
||||
self.online.store(true, Ordering::Relaxed);
|
||||
self.link.online.store(true, Ordering::Relaxed);
|
||||
match lost_at.take() {
|
||||
Some(since) => {
|
||||
info!(
|
||||
|
||||
@@ -32,10 +32,7 @@ impl Core {
|
||||
None
|
||||
};
|
||||
freshness.is_none_or(|key| {
|
||||
!listing_needs_refresh(
|
||||
self.online.load(Ordering::Relaxed),
|
||||
self.shared_listing_stale(&key),
|
||||
)
|
||||
!listing_needs_refresh(self.is_online(), self.shared_listing_stale(&key))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -58,16 +55,10 @@ impl Core {
|
||||
/// lock: no site in the daemon holds `pending` and `state` at once, and this
|
||||
/// is not the place to become the first.
|
||||
pub(super) fn stamp_pending_sizes(&self, nodes: &mut [Node]) {
|
||||
let sizes: HashMap<NodeUid, u64> = {
|
||||
let pending = self.pending.lock();
|
||||
if pending.is_empty() {
|
||||
return;
|
||||
}
|
||||
pending
|
||||
.iter()
|
||||
.map(|(uid, pr)| (uid.clone(), pr.meta.len))
|
||||
.collect()
|
||||
};
|
||||
let sizes = self.writes.queued_sizes();
|
||||
if sizes.is_empty() {
|
||||
return;
|
||||
}
|
||||
apply_pending_sizes(nodes, &sizes);
|
||||
}
|
||||
|
||||
@@ -167,7 +158,7 @@ impl Core {
|
||||
// Before the lock: a DB row carries the size the server last
|
||||
// sealed, which a queued write is ahead of (B11).
|
||||
self.stamp_pending_sizes(&mut nodes);
|
||||
let hidden = self.hidden.lock().clone();
|
||||
let hidden = self.writes.hidden();
|
||||
let mut st = self.state();
|
||||
if st.children.contains_key(&ino) {
|
||||
return Ok(());
|
||||
@@ -235,14 +226,11 @@ impl Core {
|
||||
}
|
||||
|
||||
let primary_root =
|
||||
is_primary_root_listing(self.primary, &folder_uid, &self.primary_root_uid);
|
||||
is_primary_root_listing(self.session.primary, &folder_uid, &self.primary_root_uid);
|
||||
let foreign = !self.is_own_or_virtual(&folder_uid) && !is_local_uid(&folder_uid);
|
||||
let foreign_key = foreign.then(|| Self::shared_folder_freshness_key(&folder_uid));
|
||||
let refresh_foreign = foreign_key.as_deref().is_some_and(|key| {
|
||||
listing_needs_refresh(
|
||||
self.online.load(Ordering::Relaxed),
|
||||
self.shared_listing_stale(key),
|
||||
)
|
||||
listing_needs_refresh(self.is_online(), self.shared_listing_stale(key))
|
||||
});
|
||||
if cached && !refresh_foreign {
|
||||
if primary_root {
|
||||
@@ -334,7 +322,7 @@ impl Core {
|
||||
// Same as the DB path above: the remote's size for a file with a write
|
||||
// still queued is the pre-write one (B11).
|
||||
self.stamp_pending_sizes(&mut nodes);
|
||||
let hidden = self.hidden.lock().clone();
|
||||
let hidden = self.writes.hidden();
|
||||
let mut filtered_nodes: Vec<Node> = nodes
|
||||
.into_iter()
|
||||
.filter(|node| node_visible(node, &folder_uid, &hidden))
|
||||
|
||||
@@ -22,7 +22,7 @@ impl Core {
|
||||
m.running = true;
|
||||
}
|
||||
let core = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
if let Err(error) = self.services.spawn_job("pdfs-vacuum", move || {
|
||||
let job = core.transfers.begin_job("Compacting the cache database");
|
||||
job.detail("Rewriting the database file");
|
||||
let started = Instant::now();
|
||||
@@ -38,7 +38,9 @@ impl Core {
|
||||
Err(e) => warn!(error = %e, "vacuum failed"),
|
||||
}
|
||||
core.maintenance.lock().running = false;
|
||||
});
|
||||
}) {
|
||||
tracing::warn!(%error, "could not start pdfs-vacuum");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -61,7 +63,7 @@ impl Core {
|
||||
drop(m);
|
||||
|
||||
let core = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
if let Err(error) = self.services.spawn_job("pdfs-integrity-check", move || {
|
||||
let job = core
|
||||
.transfers
|
||||
.begin_background_job("Checking the cache database");
|
||||
@@ -78,7 +80,9 @@ impl Core {
|
||||
let mut m = core.maintenance.lock();
|
||||
m.integrity = Some(problems);
|
||||
m.running = false;
|
||||
});
|
||||
}) {
|
||||
tracing::warn!(%error, "could not start pdfs-integrity-check");
|
||||
}
|
||||
(Vec::new(), false, true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,16 +351,17 @@ pub(super) fn spawn_session(
|
||||
clear_stale_mount(mountpoint);
|
||||
info!(mountpoint = %mountpoint.display(), "mounting Proton Drive location");
|
||||
let fs = ProtonFs::new(core.clone(), root);
|
||||
if core.primary {
|
||||
if core.session.primary {
|
||||
// Only My Files rehydrates the daemon-wide node cache, once. A
|
||||
// secondary mount shares the tree it fills.
|
||||
core.hydrate();
|
||||
}
|
||||
let session = Session::new(fs, mountpoint, &config)?.spawn()?;
|
||||
let _ = core
|
||||
.session
|
||||
.notifier
|
||||
.set(KernelChannel::new(session.notifier(), core.root_ino()));
|
||||
core.session_live.store(true, Ordering::Release);
|
||||
core.session.session_live.store(true, Ordering::Release);
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
@@ -488,7 +489,7 @@ pub(crate) fn mount_with(
|
||||
// handlers can trigger reconciles.
|
||||
let (sync_tx, sync_rx) = std::sync::mpsc::channel::<sync::SyncMsg>();
|
||||
|
||||
let paused_until = pause::load_paused_until(&db);
|
||||
let pause = pause::SyncPause::load(db.clone());
|
||||
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)));
|
||||
@@ -511,6 +512,18 @@ pub(crate) fn mount_with(
|
||||
abandon: Arc::default(),
|
||||
events_read_at: Arc::new(AtomicI64::new(0)),
|
||||
};
|
||||
let state = Arc::new(Ranked::new(
|
||||
Rank::State,
|
||||
State::new(db.clone(), share_access),
|
||||
));
|
||||
let sharing = super::sharing::Sharing::new(
|
||||
client.clone(),
|
||||
drive.clone(),
|
||||
rt.clone(),
|
||||
cache.clone(),
|
||||
transfers.clone(),
|
||||
state.clone(),
|
||||
);
|
||||
let core = Core {
|
||||
drive,
|
||||
drive_calls,
|
||||
@@ -519,35 +532,27 @@ pub(crate) fn mount_with(
|
||||
rt: rt.clone(),
|
||||
maintenance: Arc::new(Mutex::new(Default::default())),
|
||||
primary_root_uid: root.uid.clone(),
|
||||
primary: true,
|
||||
state: Arc::new(Ranked::new(
|
||||
Rank::State,
|
||||
State::new(db.clone(), share_access),
|
||||
)),
|
||||
root: Arc::new(OnceLock::new()),
|
||||
state: state.clone(),
|
||||
cache,
|
||||
reads: super::reads::ReadState::new(),
|
||||
workers: Arc::new(Workers::new(FUSE_WORKERS)?),
|
||||
db,
|
||||
online: Arc::new(AtomicBool::new(online)),
|
||||
link: Arc::new(link::Link::starting(start == Start::SessionExpired)),
|
||||
sync_paused_until: Arc::new(AtomicI64::new(paused_until)),
|
||||
pending: Arc::new(Mutex::new(HashMap::new())),
|
||||
hidden: Arc::new(Mutex::new(HashSet::new())),
|
||||
link: Arc::new(link::Link::starting(online, start == Start::SessionExpired)),
|
||||
pause,
|
||||
drain: super::drain::DrainState::new(),
|
||||
pin_work: Arc::new(Mutex::new(Default::default())),
|
||||
sizes: super::sizes::SizeState::new(),
|
||||
trash: super::trash::TrashState::new(),
|
||||
shared: super::shared::SharedState::new(),
|
||||
quota_cache: super::sharing::QuotaCache::new(),
|
||||
quota: super::quota::QuotaCache::new(),
|
||||
sharing,
|
||||
sweep: super::sweep::SweepState::new(sweep_mode),
|
||||
writes: super::writes::WriteState::new(),
|
||||
session: super::session::SessionCells::new(),
|
||||
shutdown,
|
||||
services: ServiceBoard::default(),
|
||||
photo_jobs: super::photos::PhotoJobs::new(),
|
||||
local_first,
|
||||
self_changes: Arc::new(Mutex::new(HashMap::new())),
|
||||
notifier: Arc::new(OnceLock::new()),
|
||||
session_live: Arc::new(AtomicBool::new(false)),
|
||||
transfers,
|
||||
sync,
|
||||
events: Arc::new(Default::default()),
|
||||
@@ -612,8 +617,8 @@ pub(crate) fn mount_with(
|
||||
}
|
||||
}
|
||||
// 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);
|
||||
if let Some(until) = core.pause.deadline() {
|
||||
core.arm_pause_timer(until);
|
||||
}
|
||||
|
||||
// Reconcile leftover `(sync-conflict …)` copies: drop the ones that turned
|
||||
@@ -658,7 +663,7 @@ pub(crate) fn mount_with(
|
||||
// the walk is I/O-heavy and must never sit in front of a FUSE callback.
|
||||
if matches!(host, Host::Daemon) {
|
||||
if let Some(gallery) = &core.gallery {
|
||||
rt.spawn(gallery.clone().poll(core.clone()));
|
||||
workers.spawn_task(&rt, "pdfs-gallery", gallery.clone().poll(core.clone()));
|
||||
}
|
||||
let db = core.db.clone();
|
||||
let indexing = core.indexing.clone();
|
||||
@@ -736,7 +741,7 @@ pub(crate) fn mount_with(
|
||||
warn!(id, error = %unmount_error, "secondary teardown after control startup failure failed");
|
||||
}
|
||||
}
|
||||
if let Err(unmount_error) = teardown_session(&core.session_live, || {
|
||||
if let Err(unmount_error) = teardown_session(&core.session.session_live, || {
|
||||
umount_session_unblocked(bg, main_conn)
|
||||
}) {
|
||||
warn!(error = %unmount_error, "unmount after control startup failure failed");
|
||||
@@ -798,19 +803,28 @@ pub(crate) fn mount_with(
|
||||
}
|
||||
}
|
||||
};
|
||||
rt.spawn(run_event_sync(core.drive.clone(), scope, core.clone()));
|
||||
// Services rather than bare tasks: a stop aborts them. Before, they ran
|
||||
// until the runtime went away, which on a stop is when the process exits.
|
||||
workers.spawn_task(
|
||||
&rt,
|
||||
"pdfs-event-sync",
|
||||
run_event_sync(core.drive.clone(), scope, core.clone()),
|
||||
);
|
||||
// The photos volume has its own event stream; without it the gallery only
|
||||
// learns about a phone-side deletion when the timeline goes stale.
|
||||
rt.spawn(run_photos_event_sync(core.clone()));
|
||||
workers.spawn_task(
|
||||
&rt,
|
||||
"pdfs-photo-events",
|
||||
run_photos_event_sync(core.clone()),
|
||||
);
|
||||
// Not in a simulation: `client` there reaches no API, and the thread, still
|
||||
// waiting on it after the stop, held the database a test opens next.
|
||||
if online && matches!(host, Host::Daemon) {
|
||||
let repair_core = core.clone();
|
||||
let root_uid = core.primary_root_uid.clone();
|
||||
if let Err(error) = std::thread::Builder::new()
|
||||
.name("pdfs-share-id".into())
|
||||
.spawn(move || repair_core.repair_primary_share_id(&root_uid))
|
||||
{
|
||||
if let Err(error) = core.services.spawn_job("pdfs-share-id", move || {
|
||||
repair_core.repair_primary_share_id(&root_uid)
|
||||
}) {
|
||||
warn!(%error, "start My Files share-id repair failed");
|
||||
}
|
||||
}
|
||||
@@ -844,7 +858,7 @@ pub(crate) fn mount_with(
|
||||
Ok(()) => {
|
||||
info!("stop requested; unmounting");
|
||||
core.mounts.lock().close();
|
||||
if let Err(e) = teardown_session(&core.session_live, || {
|
||||
if let Err(e) = teardown_session(&core.session.session_live, || {
|
||||
umount_session_unblocked(bg, main_conn)
|
||||
}) {
|
||||
warn!(error = %e, "umount_and_join failed");
|
||||
@@ -856,7 +870,7 @@ pub(crate) fn mount_with(
|
||||
{
|
||||
info!("unmounting to resume the stored session");
|
||||
core.mounts.lock().close();
|
||||
if let Err(e) = teardown_session(&core.session_live, || {
|
||||
if let Err(e) = teardown_session(&core.session.session_live, || {
|
||||
umount_session_unblocked(bg, main_conn)
|
||||
}) {
|
||||
warn!(error = %e, "umount_and_join failed");
|
||||
@@ -867,7 +881,7 @@ pub(crate) fn mount_with(
|
||||
if bg.guard.is_finished() {
|
||||
info!("mount ended externally");
|
||||
core.mounts.lock().close();
|
||||
if let Err(e) = teardown_session(&core.session_live, || bg.join()) {
|
||||
if let Err(e) = teardown_session(&core.session.session_live, || bg.join()) {
|
||||
warn!(error = %e, "session join failed");
|
||||
}
|
||||
break MountOutcome::Unmounted;
|
||||
@@ -876,7 +890,7 @@ pub(crate) fn mount_with(
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
|
||||
// Signal task gone (failed to install); fall back to join.
|
||||
core.mounts.lock().close();
|
||||
let _ = teardown_session(&core.session_live, || bg.join());
|
||||
let _ = teardown_session(&core.session.session_live, || bg.join());
|
||||
break MountOutcome::Unmounted;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,41 +51,106 @@ fn store_folder_paused(db: &Db, id: i64, paused: bool) -> pdfs_core::Result<()>
|
||||
/// A pause with no end time: it lasts until the user resumes.
|
||||
pub(crate) const PAUSED_INDEFINITELY: i64 = i64::MAX;
|
||||
|
||||
/// The persisted pause, or `0` when there is none (or it cannot be read — a
|
||||
/// broken state row must not keep sync paused forever).
|
||||
pub(crate) fn load_paused_until(db: &Db) -> i64 {
|
||||
match db.state_i64(PAUSED_UNTIL_KEY) {
|
||||
Ok(Some(until)) => until,
|
||||
Ok(None) => 0,
|
||||
Err(error) => {
|
||||
warn!(%error, "reading the sync pause failed; treating sync as running");
|
||||
0
|
||||
/// The global pause: when it ends, in memory and in the database.
|
||||
///
|
||||
/// The value is the Unix second the pause ends, [`PAUSED_INDEFINITELY`] for
|
||||
/// "until resumed", or `0` when sync runs. Only this type reads or writes it;
|
||||
/// the rest of the daemon asks [`Core::sync_paused`].
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct SyncPause {
|
||||
until: Arc<AtomicI64>,
|
||||
db: Arc<Db>,
|
||||
}
|
||||
|
||||
impl SyncPause {
|
||||
/// The persisted pause, or none when there is no row or it cannot be read:
|
||||
/// a broken state row must not keep sync paused forever.
|
||||
pub(crate) fn load(db: Arc<Db>) -> Self {
|
||||
let until = match db.state_i64(PAUSED_UNTIL_KEY) {
|
||||
Ok(Some(until)) => until,
|
||||
Ok(None) => 0,
|
||||
Err(error) => {
|
||||
warn!(%error, "reading the sync pause failed; treating sync as running");
|
||||
0
|
||||
}
|
||||
};
|
||||
Self {
|
||||
until: Arc::new(AtomicI64::new(until)),
|
||||
db,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_paused(&self) -> bool {
|
||||
paused_at(self.until.load(Ordering::Relaxed), now_secs())
|
||||
}
|
||||
|
||||
/// `None` when not paused, `Some(None)` when paused until resumed,
|
||||
/// `Some(Some(t))` when it ends at Unix second `t`.
|
||||
fn status(&self) -> Option<Option<i64>> {
|
||||
let until = self.until.load(Ordering::Relaxed);
|
||||
match paused_at(until, now_secs()) {
|
||||
false => None,
|
||||
true if until == PAUSED_INDEFINITELY => Some(None),
|
||||
true => Some(Some(until)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of a timed pause still in force, which needs a timer.
|
||||
pub(crate) fn deadline(&self) -> Option<i64> {
|
||||
self.status().flatten()
|
||||
}
|
||||
|
||||
/// Persist `value`, then take it. A pause that cannot be saved is not
|
||||
/// taken, so what the user sees never outlives a restart by surprise.
|
||||
fn store(&self, value: i64) -> Result<(), CoreError> {
|
||||
let persisted = match value {
|
||||
0 => self.db.clear_state(PAUSED_UNTIL_KEY),
|
||||
value => self.db.set_state_i64(PAUSED_UNTIL_KEY, value),
|
||||
};
|
||||
if let Err(error) = persisted {
|
||||
return Err(CoreError::internal(format!(
|
||||
"saving the sync pause: {error}"
|
||||
)));
|
||||
}
|
||||
self.until.store(value, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// End the pause that lasts until `until`, if it is still the one in
|
||||
/// force. Returns whether it was: a later pause or resume replaced it
|
||||
/// otherwise, and the timer that asks has nothing to do.
|
||||
fn expire(&self, until: i64) -> bool {
|
||||
if self
|
||||
.until
|
||||
.compare_exchange(until, 0, Ordering::Relaxed, Ordering::Relaxed)
|
||||
.is_err()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let Err(error) = self.db.clear_state(PAUSED_UNTIL_KEY) {
|
||||
warn!(%error, "clearing an expired sync pause failed");
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a pause lasting until `until` is still in force at `now` (both Unix
|
||||
/// seconds). `0` is "not paused".
|
||||
pub(crate) fn paused_at(until: i64, now: i64) -> bool {
|
||||
fn paused_at(until: i64, now: i64) -> bool {
|
||||
until != 0 && now < until
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// True while the user has sync paused.
|
||||
pub(crate) fn sync_paused(&self) -> bool {
|
||||
paused_at(self.sync_paused_until.load(Ordering::Relaxed), now_secs())
|
||||
self.pause.is_paused()
|
||||
}
|
||||
|
||||
/// The pause's end, for status reporting: `None` when not paused,
|
||||
/// `Some(None)` when paused until resumed, `Some(Some(t))` when it ends at
|
||||
/// Unix second `t`.
|
||||
pub(crate) fn sync_pause(&self) -> Option<Option<i64>> {
|
||||
let until = self.sync_paused_until.load(Ordering::Relaxed);
|
||||
match paused_at(until, now_secs()) {
|
||||
false => None,
|
||||
true if until == PAUSED_INDEFINITELY => Some(None),
|
||||
true => Some(Some(until)),
|
||||
}
|
||||
self.pause.status()
|
||||
}
|
||||
|
||||
/// Pause sync until Unix second `until` (`None`: until resumed), or resume
|
||||
@@ -103,16 +168,7 @@ impl Core {
|
||||
}
|
||||
(true, Some(until)) => until,
|
||||
};
|
||||
let persisted = match value {
|
||||
0 => self.db.clear_state(PAUSED_UNTIL_KEY),
|
||||
value => self.db.set_state_i64(PAUSED_UNTIL_KEY, value),
|
||||
};
|
||||
if let Err(error) = persisted {
|
||||
return Err(CoreError::internal(format!(
|
||||
"saving the sync pause: {error}"
|
||||
)));
|
||||
}
|
||||
self.sync_paused_until.store(value, Ordering::Relaxed);
|
||||
self.pause.store(value)?;
|
||||
match value {
|
||||
0 => {
|
||||
info!("sync resumed");
|
||||
@@ -182,24 +238,15 @@ impl Core {
|
||||
pub(crate) fn arm_pause_timer(&self, until: i64) {
|
||||
let core = self.clone();
|
||||
let wait = Duration::from_secs(until.saturating_sub(now_secs()).max(0) as u64);
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("pdfs-pause".into())
|
||||
.spawn(move || {
|
||||
if !core.shutdown.sleep(wait) {
|
||||
return;
|
||||
}
|
||||
if core
|
||||
.sync_paused_until
|
||||
.compare_exchange(until, 0, Ordering::Relaxed, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
{
|
||||
if let Err(error) = core.db.clear_state(PAUSED_UNTIL_KEY) {
|
||||
warn!(%error, "clearing an expired sync pause failed");
|
||||
}
|
||||
info!("sync pause ended");
|
||||
core.resume_sync_work();
|
||||
}
|
||||
});
|
||||
let spawned = self.services.spawn_job("pdfs-pause", move || {
|
||||
if !core.shutdown.sleep(wait) {
|
||||
return;
|
||||
}
|
||||
if core.pause.expire(until) {
|
||||
info!("sync pause ended");
|
||||
core.resume_sync_work();
|
||||
}
|
||||
});
|
||||
if let Err(error) = spawned {
|
||||
// The drain and the reconcile still read the clock, so the pause
|
||||
// still ends — just at the next idle poll instead of on time.
|
||||
|
||||
@@ -159,16 +159,14 @@ impl Core {
|
||||
return;
|
||||
}
|
||||
let core = self.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("pdfs-similar".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = core.hash_similar() {
|
||||
warn!(error = %e, "similar-photo hashing failed");
|
||||
}
|
||||
core.photo_jobs
|
||||
.similar_hashing
|
||||
.store(false, Ordering::SeqCst);
|
||||
});
|
||||
let spawned = self.services.spawn_job("pdfs-similar", move || {
|
||||
if let Err(e) = core.hash_similar() {
|
||||
warn!(error = %e, "similar-photo hashing failed");
|
||||
}
|
||||
core.photo_jobs
|
||||
.similar_hashing
|
||||
.store(false, Ordering::SeqCst);
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
warn!(error = %e, "could not start similar-photo hashing");
|
||||
self.photo_jobs
|
||||
@@ -584,18 +582,19 @@ impl Core {
|
||||
return;
|
||||
}
|
||||
let core = self.clone();
|
||||
self.rt.spawn(async move {
|
||||
let refreshed = core.refresh_timeline().await;
|
||||
core.photo_jobs
|
||||
.timeline_refreshing
|
||||
.store(false, Ordering::SeqCst);
|
||||
// Only a refresh that landed: a front-end re-reading after a failed
|
||||
// one would find the timeline still stale and start another.
|
||||
match refreshed {
|
||||
Ok(_) => core.events.publish(&[Topic::Photos]),
|
||||
Err(e) => warn!(error = %e, "background timeline refresh failed"),
|
||||
}
|
||||
});
|
||||
self.services
|
||||
.spawn_task_job(&self.rt, "pdfs-timeline-refresh", async move {
|
||||
let refreshed = core.refresh_timeline().await;
|
||||
core.photo_jobs
|
||||
.timeline_refreshing
|
||||
.store(false, Ordering::SeqCst);
|
||||
// Only a refresh that landed: a front-end re-reading after a failed
|
||||
// one would find the timeline still stale and start another.
|
||||
match refreshed {
|
||||
Ok(_) => core.events.publish(&[Topic::Photos]),
|
||||
Err(e) => warn!(error = %e, "background timeline refresh failed"),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// How far the running timeline refresh has got reading photo metadata, or
|
||||
|
||||
@@ -42,9 +42,10 @@ impl Core {
|
||||
.map_err(|e| CoreError::from_api(&e, "pin"))?;
|
||||
let core = self.clone();
|
||||
let folder = name.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("pin-folder".into())
|
||||
.spawn(move || core.pin_subtree(ino, &uid, &folder))
|
||||
self.services
|
||||
.spawn_job("pdfs-pin-folder", move || {
|
||||
core.pin_subtree(ino, &uid, &folder)
|
||||
})
|
||||
.map_err(|e| CoreError::internal(format!("spawn pin: {e}")))?;
|
||||
return Ok(format!("{name}: downloading its files in the background"));
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ impl Core {
|
||||
return;
|
||||
}
|
||||
let core = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
if let Err(error) = self.services.spawn_job("pdfs-profile-backup", move || {
|
||||
let (saving, dirty) = save_state();
|
||||
while dirty.swap(false, Ordering::SeqCst) {
|
||||
if let Err(e) = core.save_profile() {
|
||||
@@ -64,7 +64,9 @@ impl Core {
|
||||
}
|
||||
}
|
||||
saving.store(false, Ordering::SeqCst);
|
||||
});
|
||||
}) {
|
||||
tracing::warn!(%error, "could not start pdfs-profile-backup");
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialize this machine's arrangement and upload it to its own
|
||||
|
||||
@@ -172,7 +172,7 @@ impl Core {
|
||||
CoreError::conflict(format!("{path} is being sent right now; try again"))
|
||||
})?;
|
||||
self.release_dropped_ops(uid, blobs);
|
||||
self.hidden.lock().remove(uid);
|
||||
self.writes.unhide(uid);
|
||||
match node {
|
||||
Some(node) => self.for_each_mount(|st, notify| {
|
||||
put_back(st, notify, node);
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! The account's storage quota, as `statfs(2)` and the control socket ask
|
||||
//! for it.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::{CoreError, CoreResult};
|
||||
use tracing::debug;
|
||||
|
||||
use super::{Core, QUOTA_TTL};
|
||||
|
||||
/// The last account quota answer, for `statfs(2)`, and whether a refresh
|
||||
/// of it is running.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct QuotaCache {
|
||||
/// Last account quota answer and when it was learned, for `statfs(2)`.
|
||||
///
|
||||
/// `df` and the free-space preflight of every file manager and installer ask
|
||||
/// for this, and the answer costs a round trip — so it is served from here
|
||||
/// for [`QUOTA_TTL`] and refreshed on a worker afterwards. Total account
|
||||
/// storage moves slowly enough that a minute-old number is a better answer
|
||||
/// than either a stall or the zeroes the default implementation returns.
|
||||
last: Arc<Mutex<Option<(std::time::Instant, i64, i64)>>>,
|
||||
/// Set while a `statfs` is refreshing [`QuotaCache::last`], so the others serve
|
||||
/// the last figures instead of each holding a worker on the same request.
|
||||
refreshing: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl QuotaCache {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
last: Arc::new(Mutex::new(None)),
|
||||
refreshing: Arc::new(AtomicBool::new(false)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// Total account storage usage `(max_space, used_space)` in bytes, across all
|
||||
/// Proton products (not Drive-only). A remote round-trip; nothing here is
|
||||
/// cached.
|
||||
pub(crate) fn account_quota(&self) -> CoreResult<(i64, i64)> {
|
||||
let q = self.block_on_bounded(self.drive.quota()).map_err(|e| {
|
||||
self.lost_link(&e, "account quota");
|
||||
CoreError::from_api(&e, "account quota")
|
||||
})?;
|
||||
*self.quota.last.lock() = Some((std::time::Instant::now(), q.max_space, q.used_space));
|
||||
Ok((q.max_space, q.used_space))
|
||||
}
|
||||
|
||||
/// The account quota as `statfs(2)` needs it: cached for [`QUOTA_TTL`],
|
||||
/// refetched after that, and `None` when there is no usable answer at all —
|
||||
/// offline with nothing cached.
|
||||
///
|
||||
/// Never blocks on the network for a *fresh* value when a recent one exists,
|
||||
/// because the callers are `df` and every "is there room?" preflight, and a
|
||||
/// stale byte count is worth more to them than a stalled syscall. Offline,
|
||||
/// the last known figures keep being served rather than degrading to zero.
|
||||
pub(crate) fn account_quota_cached(&self) -> Option<(i64, i64)> {
|
||||
if let Some((at, max_space, used_space)) = *self.quota.last.lock()
|
||||
&& at.elapsed() < QUOTA_TTL
|
||||
{
|
||||
return Some((max_space, used_space));
|
||||
}
|
||||
let last = || self.quota.last.lock().map(|(_, max, used)| (max, used));
|
||||
if !self.is_online()
|
||||
|| self
|
||||
.quota
|
||||
.refreshing
|
||||
.swap(true, std::sync::atomic::Ordering::AcqRel)
|
||||
{
|
||||
return last();
|
||||
}
|
||||
let refreshed = self.account_quota();
|
||||
self.quota
|
||||
.refreshing
|
||||
.store(false, std::sync::atomic::Ordering::Release);
|
||||
match refreshed {
|
||||
Ok(q) => Some(q),
|
||||
Err(error) => {
|
||||
debug!(%error, "account quota refresh failed; serving the last known figures");
|
||||
last()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -507,7 +507,7 @@ impl Core {
|
||||
// A queued write has not reached the remote yet, so the remote's current
|
||||
// revision is stale and the staged blob is the truth. Serve from it until
|
||||
// the drain worker lands the upload.
|
||||
if let Some(pending) = self.pending.lock().get(uid).cloned() {
|
||||
if let Some(pending) = self.writes.queued(uid) {
|
||||
return self.read_pending(&pending, offset, len);
|
||||
}
|
||||
// A node created offline and never written has no blob and no remote: it
|
||||
@@ -1132,7 +1132,7 @@ impl Core {
|
||||
true => self.landed_stand_in_uid(&uid).unwrap_or(uid),
|
||||
false => uid,
|
||||
};
|
||||
if let Some(pending) = self.pending.lock().get(&uid).cloned() {
|
||||
if let Some(pending) = self.writes.queued(&uid) {
|
||||
let m = &pending.meta;
|
||||
let file = File::open(&pending.path).map_err(|e| {
|
||||
error!(%uid, path = %pending.path.display(), error = %e, "open staged blob failed");
|
||||
|
||||
@@ -28,17 +28,11 @@ impl Core {
|
||||
// lying about the size reads as data loss. `hydrate_pending` ran before
|
||||
// us, so the pending map is populated; snapshot it here rather than hold
|
||||
// both locks at once.
|
||||
let pending_sizes: HashMap<NodeUid, u64> = {
|
||||
let pending = self.pending.lock();
|
||||
pending
|
||||
.iter()
|
||||
.map(|(uid, pr)| (uid.clone(), pr.meta.len))
|
||||
.collect()
|
||||
};
|
||||
let pending_sizes = self.writes.queued_sizes();
|
||||
// `hydrate_pending` runs first and restores queued-trash tombstones.
|
||||
// Their node rows remain persisted as drain-time access authority, but
|
||||
// must not reappear in the mounted namespace after a restart.
|
||||
let hidden = self.hidden.lock().clone();
|
||||
let hidden = self.writes.hidden();
|
||||
let mut st = self.state();
|
||||
|
||||
// Pass 1: give every uid its inode from its local id (the root is
|
||||
@@ -123,7 +117,7 @@ impl Core {
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut map = self.pending.lock();
|
||||
let mut map = self.writes.pending.lock();
|
||||
let mut restored = 0usize;
|
||||
for op in ops {
|
||||
let Some(uid) = parse_node_uid(&op.uid) else {
|
||||
@@ -132,7 +126,7 @@ impl Core {
|
||||
continue;
|
||||
};
|
||||
if op.kind == OP_TRASH {
|
||||
self.hidden.lock().insert(uid.clone());
|
||||
self.writes.hide(&uid);
|
||||
}
|
||||
restored += 1;
|
||||
// Only a revision must have a blob. A create carries none until
|
||||
@@ -225,7 +219,7 @@ impl Core {
|
||||
example.get_or_insert_with(|| blob.clone());
|
||||
continue;
|
||||
};
|
||||
if self.pending.lock().contains_key(&uid) {
|
||||
if self.writes.is_queued(&uid) {
|
||||
// A newer write for the same node is queued and carries its own
|
||||
// blob. These bytes are older; keeping them is right, uploading
|
||||
// them over the newer ones is not.
|
||||
@@ -266,7 +260,7 @@ impl Core {
|
||||
if let Some(old) = superseded {
|
||||
self.cache.discard_staged(Path::new(&old));
|
||||
}
|
||||
self.pending.lock().insert(
|
||||
self.writes.pending.lock().insert(
|
||||
uid.clone(),
|
||||
PendingRevision {
|
||||
path: blob.clone(),
|
||||
@@ -336,7 +330,7 @@ impl Core {
|
||||
// now would use the wrong remote base. enqueue_staged_write would abandon it
|
||||
// to staging; keep it in recovery instead so the drain loop can queue it
|
||||
// once the queue clears.
|
||||
if !meta.complete && self.pending.lock().contains_key(&uid) {
|
||||
if !meta.complete && self.writes.is_queued(&uid) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -288,7 +288,7 @@ impl Core {
|
||||
}
|
||||
|
||||
let core = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
if let Err(error) = self.services.spawn_job("pdfs-redate", move || {
|
||||
let outcome = core.redate_photos(dry_run, limit, range, cancel);
|
||||
let mut state = REDATE.lock();
|
||||
state.running = false;
|
||||
@@ -310,7 +310,9 @@ impl Core {
|
||||
),
|
||||
Err(e) => warn!(error = %e, "photo re-date failed"),
|
||||
}
|
||||
});
|
||||
}) {
|
||||
tracing::warn!(%error, "could not start pdfs-redate");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,7 +172,7 @@ impl Core {
|
||||
rel: dest_rel,
|
||||
},
|
||||
) = (&source, &dest)
|
||||
&& Arc::ptr_eq(&core.root, &dest_core.root)
|
||||
&& Arc::ptr_eq(&core.session.root, &dest_core.session.root)
|
||||
{
|
||||
return core.move_to(rel, dest_rel);
|
||||
}
|
||||
|
||||
@@ -693,7 +693,7 @@ impl Core {
|
||||
self.for_each_state(|st| {
|
||||
st.forget_or_unlink(uid);
|
||||
});
|
||||
self.hidden.lock().insert(uid.clone());
|
||||
self.writes.hide(uid);
|
||||
if open_now {
|
||||
if let Err(error) = self.withdraw_queued_ops(uid) {
|
||||
error!(%uid, "remote replacement landed but queued-op cleanup failed");
|
||||
@@ -763,7 +763,7 @@ impl Core {
|
||||
.and_then(batch::into_unit)
|
||||
{
|
||||
Ok(()) => {
|
||||
self.hidden.lock().remove(uid);
|
||||
self.writes.unhide(uid);
|
||||
self.for_each_mount(|st, notify| {
|
||||
if let Some(&ino) = st.by_uid.get(parent) {
|
||||
st.invalidate_listing(ino);
|
||||
|
||||
@@ -133,7 +133,7 @@ impl Core {
|
||||
// These paths walk the tree lazily, so a cold node needs the API.
|
||||
// Offline that surfaces as EIO, which on its own would read to the
|
||||
// user as a broken file rather than a missing network.
|
||||
libc::EIO if !self.online.load(Ordering::Relaxed) => CoreError::offline(),
|
||||
libc::EIO if !self.is_online() => CoreError::offline(),
|
||||
libc::EINVAL => CoreError::invalid(format!("{what}: not a usable path")),
|
||||
libc::ENOSPC => CoreError::new(ErrorKind::Quota, format!("{what}: out of space")),
|
||||
libc::EEXIST => CoreError::conflict(format!("{what}: already exists")),
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
//! The cells that belong to one mount's FUSE session (`SessionCells`).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// What belongs to one mount's FUSE session rather than to the daemon: whether
|
||||
/// it is the primary My Files mount, the tree inode it is rooted at, its
|
||||
/// kernel channel and whether the session is up.
|
||||
///
|
||||
/// Every other part of `Core` is shared between the primary mount and its
|
||||
/// on-demand forks. A fork gets fresh cells from [`SessionCells::fork`].
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct SessionCells {
|
||||
/// False only for a forked on-demand device mount. The synthetic shared
|
||||
/// directory belongs exclusively to the primary My Files mount.
|
||||
pub(crate) primary: bool,
|
||||
/// The tree inode this mount's session is rooted at, set when the session
|
||||
/// is built ([`ProtonFs::new`]). Each fork has its own cell.
|
||||
pub(crate) root: Arc<OnceLock<u64>>,
|
||||
/// This mount's kernel notification channel, for telling the kernel to drop
|
||||
/// metadata it has cached. Set once the session exists — which is *after*
|
||||
/// the `Core` it is built from, hence the cell.
|
||||
///
|
||||
/// Per mount, not per daemon: each session calls its own root inode 1.
|
||||
/// [`Core::fork_state`] gives each fork an empty cell of its own. Work that
|
||||
/// changes the tree for every mount tells every session
|
||||
/// ([`Core::for_each_mount`]).
|
||||
pub(crate) notifier: Arc<OnceLock<KernelChannel>>,
|
||||
/// True only after this mount's FUSE session spawned successfully.
|
||||
/// Registration happens earlier for the primary drain, so registration
|
||||
/// alone cannot answer whether the location is mounted.
|
||||
pub(crate) session_live: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl SessionCells {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
primary: true,
|
||||
root: Arc::new(OnceLock::new()),
|
||||
notifier: Arc::new(OnceLock::new()),
|
||||
session_live: Arc::new(AtomicBool::new(false)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fresh cells for an on-demand fork: not the primary mount, and no root,
|
||||
/// channel or session until the fork's own session is built.
|
||||
pub(crate) fn fork(&self) -> Self {
|
||||
Self {
|
||||
primary: false,
|
||||
..Self::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -122,7 +122,7 @@ impl Core {
|
||||
}
|
||||
|
||||
pub(super) fn ensure_shared_children(&self, ino: u64) -> Result<(), Errno> {
|
||||
let online = self.online.load(Ordering::Relaxed);
|
||||
let online = self.is_online();
|
||||
let resident = self.state().children.contains_key(&ino);
|
||||
match shared_listing_plan(
|
||||
resident,
|
||||
@@ -235,7 +235,7 @@ impl Core {
|
||||
drop(st);
|
||||
self.flush_access_changes();
|
||||
self.mark_shared_refresh_success(SHARED_WITH_ME_SYNCED_MS);
|
||||
if let Some(notifier) = self.notifier.get() {
|
||||
if let Some(notifier) = self.session.notifier.get() {
|
||||
let _ = notifier.inval_inode(ino);
|
||||
}
|
||||
Ok(())
|
||||
|
||||
+70
-267
@@ -2,54 +2,62 @@
|
||||
//! account has received, saved public-link bookmarks, and the reverse view of
|
||||
//! everything this account shares out.
|
||||
//!
|
||||
//! All of it is remote-only state — nothing here touches the inode maps or the
|
||||
//! content cache, so every method is a round-trip wrapped in the crate error
|
||||
//! shape the control socket expects.
|
||||
//! All of it is remote-only state: nothing here changes the tree or the
|
||||
//! content cache's entries for this account's own files, so every method is a
|
||||
//! round trip wrapped in the error shape the control socket expects.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
|
||||
use pdfs_core::control::{
|
||||
BookmarkInfo, DirEntry, InvitationInfo, LinkChange, PublicLinkInfo, ShareEntry, ShareEntryKind,
|
||||
SharedItem,
|
||||
SharedItem, TransferDirection,
|
||||
};
|
||||
use pdfs_core::lockrank::Ranked;
|
||||
use pdfs_core::{CoreError, CoreResult};
|
||||
use tracing::debug;
|
||||
|
||||
use crate::QUOTA_TTL;
|
||||
use pdfs_store::cache::ContentCache;
|
||||
use proton_drive_rs::proton_sdk::crypto::VerificationStatus;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use proton_drive_rs::{MemberRole, NodeKind};
|
||||
use proton_drive_rs::{MemberRole, Node, NodeKind, ProtonDriveClient};
|
||||
use tracing::debug;
|
||||
|
||||
use proton_drive_rs::Node;
|
||||
use super::drive::DriveApi;
|
||||
use super::transfers::{CountingWriter, TransferRegistry};
|
||||
use super::{State, node_size, parse_uid, public_link_info, role_from_str, role_to_str};
|
||||
|
||||
use super::{Core, node_size, parse_uid, public_link_info, role_from_str, role_to_str};
|
||||
|
||||
/// The last account quota answer, for `statfs(2)`, and whether a refresh
|
||||
/// of it is running.
|
||||
/// Sharing as a service of its own: what this account shares and with whom,
|
||||
/// its public links, what others share with it, and its saved links.
|
||||
///
|
||||
/// Every method takes a node already resolved to its uid. Turning a path or a
|
||||
/// wire-format uid into one, and the check that the node is this daemon's to
|
||||
/// share, are the caller's (the control socket's), so this holds only the
|
||||
/// handles it calls: the client, Drive, the content cache and the transfer
|
||||
/// list for opening a shared file, and a read of the tree for paths.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct QuotaCache {
|
||||
/// Last account quota answer and when it was learned, for `statfs(2)`.
|
||||
///
|
||||
/// `df` and the free-space preflight of every file manager and installer ask
|
||||
/// for this, and the answer costs a round trip — so it is served from here
|
||||
/// for [`QUOTA_TTL`] and refreshed on a worker afterwards. Total account
|
||||
/// storage moves slowly enough that a minute-old number is a better answer
|
||||
/// than either a stall or the zeroes the default implementation returns.
|
||||
pub(crate) quota: Arc<Mutex<Option<(std::time::Instant, i64, i64)>>>,
|
||||
/// Set while a `statfs` is refreshing [`Core::quota`], so the others serve
|
||||
/// the last figures instead of each holding a worker on the same request.
|
||||
pub(crate) quota_refreshing: Arc<AtomicBool>,
|
||||
pub(crate) struct Sharing {
|
||||
client: ProtonDriveClient,
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
cache: Arc<ContentCache>,
|
||||
transfers: Arc<TransferRegistry>,
|
||||
state: Arc<Ranked<State>>,
|
||||
}
|
||||
|
||||
impl QuotaCache {
|
||||
pub(crate) fn new() -> Self {
|
||||
impl Sharing {
|
||||
pub(crate) fn new(
|
||||
client: ProtonDriveClient,
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
cache: Arc<ContentCache>,
|
||||
transfers: Arc<TransferRegistry>,
|
||||
state: Arc<Ranked<State>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
quota: Arc::new(Mutex::new(None)),
|
||||
quota_refreshing: Arc::new(AtomicBool::new(false)),
|
||||
client,
|
||||
drive,
|
||||
rt,
|
||||
cache,
|
||||
transfers,
|
||||
state,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,7 +70,7 @@ impl QuotaCache {
|
||||
/// offer path-keyed actions on it. The local-state flags (`pinned`, `cached`)
|
||||
/// stay false: they describe content this account owns a local copy policy for,
|
||||
/// which a share on someone else's volume is not.
|
||||
fn shared_entry_of(core: &Core, n: Node) -> DirEntry {
|
||||
fn shared_entry_of(sharing: &Sharing, n: Node) -> DirEntry {
|
||||
let is_dir = n.is_folder();
|
||||
let size = match &n.kind {
|
||||
NodeKind::File {
|
||||
@@ -99,7 +107,7 @@ fn shared_entry_of(core: &Core, n: Node) -> DirEntry {
|
||||
pinned: false,
|
||||
pinned_by_folder: false,
|
||||
cached: false,
|
||||
path: core.rel_path_for_uid(&n.uid).unwrap_or_default(),
|
||||
path: sharing.rel_path_for_uid(&n.uid).unwrap_or_default(),
|
||||
uid: n.uid.to_string(),
|
||||
role,
|
||||
shared_by,
|
||||
@@ -112,35 +120,12 @@ fn shared_entry_of(core: &Core, n: Node) -> DirEntry {
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
impl Sharing {
|
||||
// ---- sharing a node ---------------------------------------------------
|
||||
|
||||
/// Invite Proton and/or external emails to the node at `rel` at `role`.
|
||||
/// Invite Proton and/or external emails to the node `uid` at `role`.
|
||||
/// Returns `(proton_invited, external_invited)`.
|
||||
pub(crate) fn share_node(
|
||||
&self,
|
||||
rel: &Path,
|
||||
emails: &[String],
|
||||
role: &str,
|
||||
message: Option<&str>,
|
||||
) -> CoreResult<(usize, usize)> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.share_node_for_uid(&uid, emails, role, message)
|
||||
}
|
||||
|
||||
/// [`Core::share_node`] for a node addressed through any daemon location.
|
||||
pub(crate) fn share_node_by_uid(
|
||||
&self,
|
||||
uid: &str,
|
||||
emails: &[String],
|
||||
role: &str,
|
||||
message: Option<&str>,
|
||||
) -> CoreResult<(usize, usize)> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.share_node_for_uid(&uid, emails, role, message)
|
||||
}
|
||||
|
||||
fn share_node_for_uid(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
emails: &[String],
|
||||
@@ -155,25 +140,8 @@ impl Core {
|
||||
.map_err(|e| CoreError::from_api(&e, "share"))
|
||||
}
|
||||
|
||||
/// List the members, pending invitations and public link of the node at `rel`.
|
||||
/// List the members, pending invitations and public link of the node `uid`.
|
||||
pub(crate) fn list_share(
|
||||
&self,
|
||||
rel: &Path,
|
||||
) -> CoreResult<(Vec<ShareEntry>, Option<PublicLinkInfo>)> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.list_share_for_uid(&uid)
|
||||
}
|
||||
|
||||
/// [`Core::list_share`] for a node addressed through any daemon location.
|
||||
pub(crate) fn list_share_by_uid(
|
||||
&self,
|
||||
uid: &str,
|
||||
) -> CoreResult<(Vec<ShareEntry>, Option<PublicLinkInfo>)> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.list_share_for_uid(&uid)
|
||||
}
|
||||
|
||||
fn list_share_for_uid(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
) -> CoreResult<(Vec<ShareEntry>, Option<PublicLinkInfo>)> {
|
||||
@@ -225,32 +193,8 @@ impl Core {
|
||||
}
|
||||
|
||||
/// Change the role of a member or pending Proton invitation on the node at
|
||||
/// `rel`. External invitations have no role-update endpoint.
|
||||
/// `uid`. External invitations have no role-update endpoint.
|
||||
pub(crate) fn update_share_role(
|
||||
&self,
|
||||
rel: &Path,
|
||||
id: &str,
|
||||
kind: ShareEntryKind,
|
||||
role: &str,
|
||||
) -> CoreResult<()> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.update_share_role_for_uid(&uid, id, kind, role)
|
||||
}
|
||||
|
||||
/// [`Core::update_share_role`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn update_share_role_by_uid(
|
||||
&self,
|
||||
uid: &str,
|
||||
id: &str,
|
||||
kind: ShareEntryKind,
|
||||
role: &str,
|
||||
) -> CoreResult<()> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.update_share_role_for_uid(&uid, id, kind, role)
|
||||
}
|
||||
|
||||
fn update_share_role_for_uid(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
id: &str,
|
||||
@@ -290,30 +234,8 @@ impl Core {
|
||||
}
|
||||
|
||||
/// Remove a member, pending Proton invite, or external invite from the node
|
||||
/// at `rel`.
|
||||
/// at `uid`.
|
||||
pub(crate) fn remove_share_entry(
|
||||
&self,
|
||||
rel: &Path,
|
||||
id: &str,
|
||||
kind: ShareEntryKind,
|
||||
) -> CoreResult<()> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.remove_share_entry_for_uid(&uid, id, kind)
|
||||
}
|
||||
|
||||
/// [`Core::remove_share_entry`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn remove_share_entry_by_uid(
|
||||
&self,
|
||||
uid: &str,
|
||||
id: &str,
|
||||
kind: ShareEntryKind,
|
||||
) -> CoreResult<()> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.remove_share_entry_for_uid(&uid, id, kind)
|
||||
}
|
||||
|
||||
fn remove_share_entry_for_uid(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
id: &str,
|
||||
@@ -359,32 +281,8 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a public link on the node at `rel`, returning its info (with URL).
|
||||
/// Create a public link on the node `uid`, returning its info (with URL).
|
||||
pub(crate) fn create_public_link(
|
||||
&self,
|
||||
rel: &Path,
|
||||
role: &str,
|
||||
password: Option<&str>,
|
||||
expires: Option<i64>,
|
||||
) -> CoreResult<PublicLinkInfo> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.create_public_link_for_uid(&uid, role, password, expires)
|
||||
}
|
||||
|
||||
/// [`Core::create_public_link`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn create_public_link_by_uid(
|
||||
&self,
|
||||
uid: &str,
|
||||
role: &str,
|
||||
password: Option<&str>,
|
||||
expires: Option<i64>,
|
||||
) -> CoreResult<PublicLinkInfo> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.create_public_link_for_uid(&uid, role, password, expires)
|
||||
}
|
||||
|
||||
fn create_public_link_for_uid(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
role: &str,
|
||||
@@ -399,36 +297,11 @@ impl Core {
|
||||
Ok(public_link_info(link))
|
||||
}
|
||||
|
||||
/// Change the public link `id` on the node at `rel`, keeping its URL.
|
||||
pub(crate) fn update_public_link(
|
||||
&self,
|
||||
rel: &Path,
|
||||
id: &str,
|
||||
role: Option<&str>,
|
||||
password: LinkChange<String>,
|
||||
expires: LinkChange<i64>,
|
||||
) -> CoreResult<PublicLinkInfo> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.update_public_link_for_uid(&uid, id, role, password, expires)
|
||||
}
|
||||
|
||||
/// [`Core::update_public_link`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn update_public_link_by_uid(
|
||||
&self,
|
||||
uid: &str,
|
||||
id: &str,
|
||||
role: Option<&str>,
|
||||
password: LinkChange<String>,
|
||||
expires: LinkChange<i64>,
|
||||
) -> CoreResult<PublicLinkInfo> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.update_public_link_for_uid(&uid, id, role, password, expires)
|
||||
}
|
||||
|
||||
/// Change the public link `id` on the node `uid`, keeping its URL.
|
||||
///
|
||||
/// The SDK sets all three options on every update, so each `Keep` is
|
||||
/// filled in from the link as it stands.
|
||||
fn update_public_link_for_uid(
|
||||
pub(crate) fn update_public_link(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
id: &str,
|
||||
@@ -482,20 +355,8 @@ impl Core {
|
||||
Ok(public_link_info(link))
|
||||
}
|
||||
|
||||
/// Remove the public link `id` from the node at `rel`.
|
||||
pub(crate) fn remove_public_link(&self, rel: &Path, id: &str) -> CoreResult<()> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.remove_public_link_for_uid(&uid, id)
|
||||
}
|
||||
|
||||
/// [`Core::remove_public_link`] for a node addressed through any daemon
|
||||
/// location.
|
||||
pub(crate) fn remove_public_link_by_uid(&self, uid: &str, id: &str) -> CoreResult<()> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.remove_public_link_for_uid(&uid, id)
|
||||
}
|
||||
|
||||
fn remove_public_link_for_uid(&self, uid: &NodeUid, id: &str) -> CoreResult<()> {
|
||||
/// Remove the public link `id` from the node `uid`.
|
||||
pub(crate) fn remove_public_link(&self, uid: &NodeUid, id: &str) -> CoreResult<()> {
|
||||
let link = self
|
||||
.rt
|
||||
.block_on(self.client.get_public_link(uid))
|
||||
@@ -507,25 +368,15 @@ impl Core {
|
||||
.map_err(|e| CoreError::from_api(&e, "remove public link"))
|
||||
}
|
||||
|
||||
/// Stop sharing the node at `rel`: remove its public link, then every
|
||||
/// Stop sharing the node `uid`: remove its public link, then every
|
||||
/// external invitation, Proton invitation and member. The SDK has no call
|
||||
/// that deletes a share outright, so this composes the per-entry ones.
|
||||
pub(crate) fn stop_sharing(&self, rel: &Path) -> CoreResult<StopSharingOutcome> {
|
||||
let (_ino, uid) = self.resolve(rel)?;
|
||||
self.stop_sharing_for_uid(&uid)
|
||||
}
|
||||
|
||||
/// [`Core::stop_sharing`] for a node addressed through any daemon location.
|
||||
pub(crate) fn stop_sharing_by_uid(&self, uid: &str) -> CoreResult<StopSharingOutcome> {
|
||||
let uid = self.resolve_shareable(uid)?;
|
||||
self.stop_sharing_for_uid(&uid)
|
||||
}
|
||||
|
||||
///
|
||||
/// Each step runs even when an earlier one failed, so a single stuck
|
||||
/// member does not leave the public link up. The link goes first: it is the
|
||||
/// widest exposure. Only a failure to list what is there fails the whole
|
||||
/// request; a failed removal is counted in the outcome.
|
||||
fn stop_sharing_for_uid(&self, uid: &NodeUid) -> CoreResult<StopSharingOutcome> {
|
||||
pub(crate) fn stop_sharing(&self, uid: &NodeUid) -> CoreResult<StopSharingOutcome> {
|
||||
let mut outcome = StopSharingOutcome::default();
|
||||
let link = self
|
||||
.rt
|
||||
@@ -637,9 +488,17 @@ impl Core {
|
||||
if let Some(p) = self.cache.cached_content_path(&uid, mtime, size) {
|
||||
return Ok(p);
|
||||
}
|
||||
let bytes = self
|
||||
.download_file_tracked(&uid, &node.name, size)
|
||||
let guard = self.transfers.begin(
|
||||
&node.name,
|
||||
uid.to_string(),
|
||||
TransferDirection::Download,
|
||||
size,
|
||||
);
|
||||
let mut out = CountingWriter::new(Vec::with_capacity(size as usize), &guard);
|
||||
self.rt
|
||||
.block_on(self.drive.download_file_to(&uid, &mut out))
|
||||
.map_err(|e| CoreError::from_api(&e, "download"))?;
|
||||
let bytes = out.into_inner();
|
||||
self.cache
|
||||
.store(&uid, mtime, size, &bytes)
|
||||
.map_err(|e| CoreError::internal(format!("cache store: {e}")))?;
|
||||
@@ -721,62 +580,6 @@ impl Core {
|
||||
.map_err(|e| CoreError::from_api(&e, "delete bookmark"))
|
||||
}
|
||||
|
||||
// ---- account ----------------------------------------------------------
|
||||
|
||||
/// Total account storage usage `(max_space, used_space)` in bytes, across all
|
||||
/// Proton products (not Drive-only). A remote round-trip; nothing here is
|
||||
/// cached.
|
||||
pub(crate) fn account_quota(&self) -> CoreResult<(i64, i64)> {
|
||||
let q = self.block_on_bounded(self.drive.quota()).map_err(|e| {
|
||||
self.lost_link(&e, "account quota");
|
||||
CoreError::from_api(&e, "account quota")
|
||||
})?;
|
||||
*self.quota_cache.quota.lock() =
|
||||
Some((std::time::Instant::now(), q.max_space, q.used_space));
|
||||
Ok((q.max_space, q.used_space))
|
||||
}
|
||||
|
||||
/// The account quota as `statfs(2)` needs it: cached for [`QUOTA_TTL`],
|
||||
/// refetched after that, and `None` when there is no usable answer at all —
|
||||
/// offline with nothing cached.
|
||||
///
|
||||
/// Never blocks on the network for a *fresh* value when a recent one exists,
|
||||
/// because the callers are `df` and every "is there room?" preflight, and a
|
||||
/// stale byte count is worth more to them than a stalled syscall. Offline,
|
||||
/// the last known figures keep being served rather than degrading to zero.
|
||||
pub(crate) fn account_quota_cached(&self) -> Option<(i64, i64)> {
|
||||
if let Some((at, max_space, used_space)) = *self.quota_cache.quota.lock()
|
||||
&& at.elapsed() < QUOTA_TTL
|
||||
{
|
||||
return Some((max_space, used_space));
|
||||
}
|
||||
let last = || {
|
||||
self.quota_cache
|
||||
.quota
|
||||
.lock()
|
||||
.map(|(_, max, used)| (max, used))
|
||||
};
|
||||
if !self.is_online()
|
||||
|| self
|
||||
.quota_cache
|
||||
.quota_refreshing
|
||||
.swap(true, std::sync::atomic::Ordering::AcqRel)
|
||||
{
|
||||
return last();
|
||||
}
|
||||
let refreshed = self.account_quota();
|
||||
self.quota_cache
|
||||
.quota_refreshing
|
||||
.store(false, std::sync::atomic::Ordering::Release);
|
||||
match refreshed {
|
||||
Ok(q) => Some(q),
|
||||
Err(error) => {
|
||||
debug!(%error, "account quota refresh failed; serving the last known figures");
|
||||
last()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- shared by me -----------------------------------------------------
|
||||
|
||||
/// List the nodes I have shared with others, each with a summary of its share
|
||||
@@ -846,15 +649,15 @@ impl Core {
|
||||
/// tree, by walking parent inodes to the root. `None` when the node has never
|
||||
/// been seen through the mount (e.g. shared but not browsed to this session) —
|
||||
/// the caller then leaves the path empty.
|
||||
pub(crate) fn rel_path_for_uid(&self, uid: &NodeUid) -> Option<String> {
|
||||
fn rel_path_for_uid(&self, uid: &NodeUid) -> Option<String> {
|
||||
// Relative to whichever root the node sits under: a node browsed
|
||||
// through a sync folder is under that fork's root, not My Files
|
||||
// (`docs/BUGS.md` B74).
|
||||
walk_to_root(&self.state(), uid)
|
||||
walk_to_root(&self.state.lock(), uid)
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`Core::stop_sharing`] managed to remove.
|
||||
/// What [`Sharing::stop_sharing`] managed to remove.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct StopSharingOutcome {
|
||||
/// Entries removed (the link, invitations and members alike).
|
||||
|
||||
@@ -140,6 +140,14 @@ pub(crate) fn run(seed: u64, profile: &'static Profile) -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
run.logged.extend(take_logged());
|
||||
// Every stop, the restarts' included, ends all the services a mount
|
||||
// started; one left running is a second generation beside the next mount's.
|
||||
let outcome = outcome.and_then(
|
||||
|()| match run.logged.iter().find(|line| left_running(line)) {
|
||||
Some(line) => Err(format!("shutdown: a stop left services running: {line}")),
|
||||
None => Ok(()),
|
||||
},
|
||||
);
|
||||
match outcome {
|
||||
Ok(()) => {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
@@ -608,6 +616,12 @@ fn outcome(actual: &Result<Result<(), i32>, String>) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `line` is the mount's report of services still running at its
|
||||
/// stop deadline (`mount::halt_workers`).
|
||||
fn left_running(line: &str) -> bool {
|
||||
line.starts_with("background workers did not finish in time")
|
||||
}
|
||||
|
||||
/// Run `profile` over the seeds the environment asks for: `PDFS_SIM_SEED`
|
||||
/// alone, or `PDFS_SIM_SEEDS` of them (default `default_seeds`) from 1.
|
||||
pub(crate) fn run_seeds(profile: &'static Profile, default_seeds: u64) {
|
||||
|
||||
@@ -130,7 +130,13 @@ impl Core {
|
||||
SizeUpgradeClaim::Start(slot, uids) => {
|
||||
let core = self.clone();
|
||||
let worker = slot.clone();
|
||||
std::thread::spawn(move || core.run_size_upgrade(key, uids, worker));
|
||||
if let Err(error) = self.services.spawn_job("pdfs-size-upgrade", move || {
|
||||
core.run_size_upgrade(key, uids, worker)
|
||||
}) {
|
||||
// The waiters give up on the slot at their deadline and
|
||||
// answer with the size they have.
|
||||
warn!(%error, "could not start a size upgrade");
|
||||
}
|
||||
Some(slot)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,7 +154,7 @@ impl Core {
|
||||
}
|
||||
|
||||
let roots = self.search_roots();
|
||||
let online = self.online.load(std::sync::atomic::Ordering::Relaxed);
|
||||
let online = self.is_online();
|
||||
for node in &nodes {
|
||||
if node.trashed || node.is_folder() {
|
||||
continue;
|
||||
|
||||
@@ -1153,7 +1153,7 @@ impl Core {
|
||||
}
|
||||
|
||||
let core = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
if let Err(error) = self.services.spawn_job("pdfs-import", move || {
|
||||
// The job is dropped only after the final state is stored: the
|
||||
// job leaving the transfer snapshot is the front-ends' cue to ask
|
||||
// for the result, which must then be there.
|
||||
@@ -1186,7 +1186,9 @@ impl Core {
|
||||
summary.complete(),
|
||||
);
|
||||
}
|
||||
});
|
||||
}) {
|
||||
tracing::warn!(%error, "could not start pdfs-import");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,16 +266,17 @@ impl Core {
|
||||
return;
|
||||
}
|
||||
let core = self.clone();
|
||||
self.rt.spawn(async move {
|
||||
let refreshed = core.refresh_trash().await;
|
||||
core.trash.trash_refreshing.store(false, Ordering::SeqCst);
|
||||
match refreshed {
|
||||
Ok(_) => core.events.publish(&[Topic::Trash]),
|
||||
Err(e) => warn!(error = %e, "background trash refresh failed"),
|
||||
}
|
||||
// After the flag, so a waiter that wakes on this sees it cleared.
|
||||
core.trash.trash_progress.notify_waiters();
|
||||
});
|
||||
self.services
|
||||
.spawn_task_job(&self.rt, "pdfs-trash-refresh", async move {
|
||||
let refreshed = core.refresh_trash().await;
|
||||
core.trash.trash_refreshing.store(false, Ordering::SeqCst);
|
||||
match refreshed {
|
||||
Ok(_) => core.events.publish(&[Topic::Trash]),
|
||||
Err(e) => warn!(error = %e, "background trash refresh failed"),
|
||||
}
|
||||
// After the flag, so a waiter that wakes on this sees it cleared.
|
||||
core.trash.trash_progress.notify_waiters();
|
||||
});
|
||||
}
|
||||
|
||||
/// Wait for the in-flight trash refresh to make progress, for at most
|
||||
@@ -378,7 +379,7 @@ impl Core {
|
||||
let (uid, outcome) = item?;
|
||||
match outcome {
|
||||
Ok(()) => {
|
||||
self.hidden.lock().remove(&uid);
|
||||
self.writes.unhide(&uid);
|
||||
restored.push(uid);
|
||||
}
|
||||
Err(e) => {
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
//! What the mount accepted and has not yet sent to Drive (`WriteState`).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The write-back's state: writes accepted from the kernel and not yet sent,
|
||||
/// nodes removed here that a stale listing may still return, and the changes
|
||||
/// this daemon made that Drive's event feed will echo back.
|
||||
///
|
||||
/// The drain, the queue and recovery own it. Everything else, the read path,
|
||||
/// listings, the pin keeper and the event feed, asks through the methods
|
||||
/// below instead of taking its locks.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct WriteState {
|
||||
/// 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.
|
||||
///
|
||||
/// Two things read it: [`Core::read_range`], because until the op drains the
|
||||
/// staged blob *is* the file's content and the remote still holds the old
|
||||
/// revision; and the drain worker, which performs the uploads.
|
||||
pub(crate) pending: Arc<Mutex<HashMap<NodeUid, PendingRevision>>>,
|
||||
/// Nodes removed through this daemon which a briefly stale remote listing
|
||||
/// may still return. Uids are not reused; an explicit restore clears one.
|
||||
hidden: Arc<Mutex<HashSet<NodeUid>>>,
|
||||
/// Nodes this daemon changed on the remote itself, and how many echoes of
|
||||
/// those changes the event feed still owes us.
|
||||
///
|
||||
/// The feed replays our own writes back at us seconds later, and a
|
||||
/// `NodeUpdated` carries no revision id — nothing in it distinguishes "another
|
||||
/// device changed this file" from "you changed this file". Treating the echo
|
||||
/// as foreign is not free: it evicts the content blob we just uploaded, so the
|
||||
/// next read re-downloads a revision the API may not be serving yet. That is
|
||||
/// how a SQLite database written on the mount came back `malformed`, and how a
|
||||
/// mount doing bulk uploads spent its time re-fetching its own bytes.
|
||||
///
|
||||
/// So the first event for a node we changed ourselves, within
|
||||
/// [`SELF_CHANGE_TTL_MS`], is consumed rather than applied: the tree already
|
||||
/// holds what that event describes, because [`Core::refresh_after_upload`] put
|
||||
/// it there. Anything beyond that applies normally, which bounds the staleness
|
||||
/// a genuine remote change can suffer to one event.
|
||||
///
|
||||
/// Shared across forks like `pending`: the drain that records the change and
|
||||
/// the event task that consumes the echo are both per-daemon.
|
||||
self_changes: Arc<Mutex<HashMap<NodeUid, echoes::SelfChange>>>,
|
||||
}
|
||||
|
||||
impl WriteState {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
pending: Arc::new(Mutex::new(HashMap::new())),
|
||||
hidden: Arc::new(Mutex::new(HashSet::new())),
|
||||
self_changes: Arc::new(Mutex::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The write queued for `uid`, if any: its staged blob is the file's
|
||||
/// content until the drain sends it.
|
||||
pub(crate) fn queued(&self, uid: &NodeUid) -> Option<PendingRevision> {
|
||||
self.pending.lock().get(uid).cloned()
|
||||
}
|
||||
|
||||
/// Whether a write for `uid` is queued and not yet sent. A remote change
|
||||
/// to such a node is not applied over it.
|
||||
pub(crate) fn is_queued(&self, uid: &NodeUid) -> bool {
|
||||
self.pending.lock().contains_key(uid)
|
||||
}
|
||||
|
||||
/// The size the queued write for `uid` gives the file, if one is queued.
|
||||
pub(crate) fn queued_len(&self, uid: &NodeUid) -> Option<u64> {
|
||||
self.pending.lock().get(uid).map(|queued| queued.meta.len)
|
||||
}
|
||||
|
||||
/// The size each queued write gives its file. Empty when nothing is
|
||||
/// queued.
|
||||
pub(crate) fn queued_sizes(&self) -> HashMap<NodeUid, u64> {
|
||||
self.pending
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|(uid, queued)| (uid.clone(), queued.meta.len))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The nodes removed here that a listing must leave out, even if Drive
|
||||
/// still returns them.
|
||||
pub(crate) fn hidden(&self) -> HashSet<NodeUid> {
|
||||
self.hidden.lock().clone()
|
||||
}
|
||||
|
||||
/// Leave `uid` out of listings from now on: it was removed here.
|
||||
pub(crate) fn hide(&self, uid: &NodeUid) {
|
||||
self.hidden.lock().insert(uid.clone());
|
||||
}
|
||||
|
||||
/// List `uid` again: it was restored or put back.
|
||||
pub(crate) fn unhide(&self, uid: &NodeUid) {
|
||||
self.hidden.lock().remove(uid);
|
||||
}
|
||||
|
||||
/// Record that this daemon just changed `uid` on Drive, so the event
|
||||
/// feed's echo of the change is recognised (see [`echoes`]).
|
||||
pub(crate) fn note_echo(&self, uid: &NodeUid, now_ms: i64) {
|
||||
echoes::note_self_change(&mut self.self_changes.lock(), uid, now_ms);
|
||||
}
|
||||
|
||||
/// Claim one outstanding echo for `uid`: whether the event being applied
|
||||
/// is one this daemon caused.
|
||||
pub(crate) fn take_echo(&self, uid: &NodeUid, now_ms: i64) -> bool {
|
||||
echoes::take_self_change(&mut self.self_changes.lock(), uid, now_ms)
|
||||
}
|
||||
}
|
||||
+3
-1454
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,578 @@
|
||||
//! Applying a pass's plan: uploads, downloads and the other effects, in
|
||||
//! batches, and the baseline each one leaves behind.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Syncer {
|
||||
/// Store the revision id of each file in one listing whose baseline row has
|
||||
/// none, when the size the walk just read shows that file unchanged.
|
||||
///
|
||||
/// The classification step does the same, but only a pass that gets all the
|
||||
/// way through the walk reaches it. A large folder whose walk is cut short
|
||||
/// every time (a restart, a logout) then reads the size of every such file
|
||||
/// again, one key unlock each, on every pass, and never finishes (B294).
|
||||
pub(super) fn record_revisions(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
prefix: &str,
|
||||
nodes: &[Node],
|
||||
sized: &HashMap<String, (i64, Option<String>)>,
|
||||
baseline: &HashMap<String, StoredSyncEntry>,
|
||||
) {
|
||||
let rows = revisions_to_record(prefix, nodes, sized, baseline);
|
||||
if rows.is_empty() {
|
||||
return;
|
||||
}
|
||||
match self.store.sync_entries_set_revision(folder_id, &rows) {
|
||||
Ok(n) => self.trace_count(Count::Revisions, n),
|
||||
Err(e) => debug!(folder = prefix, error = ?e, "sync: cannot record revision ids"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Record a folder's baseline row (folders carry no content signature).
|
||||
pub(super) fn baseline_dir(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel: &str,
|
||||
uid: &NodeUid,
|
||||
) -> Result<(), String> {
|
||||
self.store
|
||||
.sync_entry_upsert(folder_id, &dir_row(rel, uid))
|
||||
.map_err(|e| format!("baseline dir {rel}: {e:?}"))
|
||||
}
|
||||
|
||||
/// Run a batch of queued [`Pending`] ops concurrently (bounded by
|
||||
/// [`SYNC_CONCURRENCY`]) and fold their results back into the reconcile's
|
||||
/// shared state on the engine thread: created folders are registered in
|
||||
/// `remote_dirs` (so deeper paths resolve their parent), and what each op did
|
||||
/// is tallied into `outcome`. Driven by `block_on` from the (non-runtime) sync
|
||||
/// engine thread, spawning the tasks onto the shared runtime.
|
||||
///
|
||||
/// Fails with [`PassAbort::Stopped`] once the daemon is stopping, after the
|
||||
/// ops already sending have finished.
|
||||
pub(super) fn flush_batch(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
local_root: &Path,
|
||||
remote_dirs: &mut HashMap<String, NodeUid>,
|
||||
batch: Vec<Pending>,
|
||||
outcome: &mut Outcome,
|
||||
) -> Result<(), PassAbort> {
|
||||
if batch.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.progress_queued(folder_id, batch.len());
|
||||
self.trace_count(Count::Queued, batch.len());
|
||||
let applying = Instant::now();
|
||||
let core = self.clone();
|
||||
let root = local_root.to_path_buf();
|
||||
let results = self.rt.block_on(async move {
|
||||
let sem = Arc::new(tokio::sync::Semaphore::new(SYNC_CONCURRENCY));
|
||||
let mut set = tokio::task::JoinSet::new();
|
||||
for op in batch {
|
||||
let core = core.clone();
|
||||
let sem = sem.clone();
|
||||
let root = root.clone();
|
||||
set.spawn(async move {
|
||||
let _permit = sem.acquire_owned().await.expect("semaphore not closed");
|
||||
// An op still waiting for its turn when the stop comes is
|
||||
// not started; the ones already sending finish.
|
||||
if core.shutdown.is_stopping() {
|
||||
return None;
|
||||
}
|
||||
Some(core.apply_pending(folder_id, &root, op).await)
|
||||
});
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut join_errors = 0usize;
|
||||
while let Some(joined) = set.join_next().await {
|
||||
match joined {
|
||||
Ok(Some(result)) => out.push(result),
|
||||
Ok(None) => {}
|
||||
// The runtime ends with the daemon and cancels what is left.
|
||||
Err(e) if e.is_cancelled() => {}
|
||||
Err(e) => {
|
||||
join_errors += 1;
|
||||
warn!(error = %e, "sync: task panicked");
|
||||
}
|
||||
}
|
||||
}
|
||||
(out, join_errors)
|
||||
});
|
||||
self.trace_phase(Phase::Apply, applying.elapsed());
|
||||
let (results, join_errors) = results;
|
||||
outcome.errors += join_errors;
|
||||
for result in results {
|
||||
match result {
|
||||
Ok(applied) => {
|
||||
outcome.record(&applied);
|
||||
if let Applied::Dir(rel, uid) = applied {
|
||||
remote_dirs.insert(rel, uid);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(error = %e, "sync: step failed; continuing");
|
||||
outcome.failed(&e);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The pass goes no further: the next depth's paths may need a folder
|
||||
// this batch did not get to make, and went on to fail one by one
|
||||
// (`docs/BUGS.md` B169).
|
||||
if self.shutdown.is_stopping() {
|
||||
return Err(PassAbort::Stopped);
|
||||
}
|
||||
if self.pass_abandoned(folder_id) {
|
||||
return Err(PassAbort::Abandoned);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a removal of `folder_id` is waiting for its running pass.
|
||||
pub(super) fn pass_abandoned(&self, folder_id: i64) -> bool {
|
||||
self.abandon.lock().contains(&folder_id)
|
||||
}
|
||||
|
||||
/// Apply one [`Pending`] op (async, so it can run concurrently in a batch),
|
||||
/// reporting it to the folder's live progress and to the activity feed. Each
|
||||
/// item logs its own line — the feed is meant to answer "what is it doing",
|
||||
/// which a pass-level summary alone cannot.
|
||||
pub(super) async fn apply_pending(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
local_root: &Path,
|
||||
op: Pending,
|
||||
) -> Result<Applied, String> {
|
||||
self.progress_started(folder_id, base_name(op.rel()));
|
||||
let step = Instant::now();
|
||||
let result = self.apply_one(folder_id, local_root, &op).await;
|
||||
self.trace_call(op.call(), step.elapsed());
|
||||
self.progress_finished(folder_id);
|
||||
let name = base_name(op.rel());
|
||||
match &result {
|
||||
Ok(Applied::Adopted) => {}
|
||||
Ok(_) => self.log_activity(op.kind(), name, op.detail(), true),
|
||||
Err(e) => self.log_activity(op.kind(), name, e.clone(), false),
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The body of one [`Pending`] op, without the progress/activity bookkeeping.
|
||||
pub(super) async fn apply_one(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
local_root: &Path,
|
||||
op: &Pending,
|
||||
) -> Result<Applied, String> {
|
||||
match op {
|
||||
Pending::CreateDir { rel, parent } => {
|
||||
let uid = self
|
||||
.drive
|
||||
.create_folder(parent, base_name(rel), Some(now_secs()))
|
||||
.await
|
||||
.map_err(|e| format!("create remote folder {rel}: {e}"))?;
|
||||
// The parent has gained a child that no cached listing of it
|
||||
// knows about (B86).
|
||||
self.invalidate_children_of(parent);
|
||||
self.baseline_dir(folder_id, rel, &uid)?;
|
||||
Ok(Applied::Dir(rel.clone(), uid))
|
||||
}
|
||||
Pending::UploadNew { rel, parent } => {
|
||||
self.upload_new(folder_id, local_root, rel, parent).await
|
||||
}
|
||||
Pending::UploadRevision { rel, uid, seen } => {
|
||||
self.upload_revision(folder_id, local_root, rel, uid, seen)
|
||||
.await
|
||||
}
|
||||
Pending::Download {
|
||||
rel,
|
||||
uid,
|
||||
seen,
|
||||
local,
|
||||
} => {
|
||||
self.download_file(folder_id, local_root, rel, uid, seen, *local)
|
||||
.await?;
|
||||
Ok(Applied::Downloaded)
|
||||
}
|
||||
Pending::Adopt {
|
||||
rel,
|
||||
uid,
|
||||
seen: remote,
|
||||
sha1,
|
||||
local,
|
||||
} => {
|
||||
let path = local_root.join(rel_to_path(rel));
|
||||
let hashed = tokio::task::spawn_blocking(move || local_sha1(&path))
|
||||
.await
|
||||
.map_err(|e| format!("hash {rel}: {e}"))?
|
||||
.map_err(|e| format!("hash {rel}: {e}"))?;
|
||||
let Some((seen, digest)) = hashed else {
|
||||
return Ok(Applied::Vanished);
|
||||
};
|
||||
// Edited since the scan: the next pass plans it again.
|
||||
if !seen.same_content(local) {
|
||||
return Ok(Applied::Vanished);
|
||||
}
|
||||
if !digest.eq_ignore_ascii_case(sha1) {
|
||||
info!(
|
||||
rel,
|
||||
"sync: same size as on Drive but different content; keeping a conflict copy"
|
||||
);
|
||||
return self
|
||||
.take_remote_keeping_local(folder_id, local_root, rel, uid, remote)
|
||||
.await;
|
||||
}
|
||||
self.store
|
||||
.sync_entry_upsert(
|
||||
folder_id,
|
||||
&StoredSyncEntry {
|
||||
rel_path: rel.clone(),
|
||||
remote_uid: Some(uid.to_string()),
|
||||
local_mtime: seen.mtime,
|
||||
local_mtime_ns: seen.mtime_ns,
|
||||
local_size: seen.size,
|
||||
remote_rev: Some(remote.mtime.to_string()),
|
||||
remote_hash: Some(remote.size.to_string()),
|
||||
remote_revision_id: remote.revision.clone(),
|
||||
},
|
||||
)
|
||||
.map_err(|e| format!("adopt baseline {rel}: {e:?}"))?;
|
||||
Ok(Applied::Adopted)
|
||||
}
|
||||
Pending::Conflict { rel, uid, seen } => {
|
||||
self.take_remote_keeping_local(folder_id, local_root, rel, uid, seen)
|
||||
.await
|
||||
}
|
||||
Pending::PushConflict { rel, parent } => {
|
||||
// The ordinary conflict resolution — rename the local copy aside and
|
||||
// let the next pass upload it — loses the file here: the folder is
|
||||
// going on-demand, so "next pass" comes after the local tree has been
|
||||
// evicted. Push the conflict copy now, while it still exists, and
|
||||
// leave the remote file holding the original path.
|
||||
let path = local_root.join(rel_to_path(rel));
|
||||
let conflict = preserve_conflict_copy(&path, now_secs())
|
||||
.map_err(|e| format!("set aside conflict copy for {rel}: {e}"))?;
|
||||
let name = conflict
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.ok_or_else(|| format!("conflict copy for {rel} has no name"))?;
|
||||
let conflict_rel = join_rel(parent_rel(rel), &name);
|
||||
self.upload_new(folder_id, local_root, &conflict_rel, parent)
|
||||
.await?;
|
||||
info!(rel, "sync: uploaded local changes as a conflict copy");
|
||||
Ok(Applied::Conflict)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the local copy aside (it re-uploads as a new file next pass), then
|
||||
/// take the remote version as the shared truth.
|
||||
pub(super) async fn take_remote_keeping_local(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
local_root: &Path,
|
||||
rel: &str,
|
||||
uid: &NodeUid,
|
||||
seen: &RemoteSeen,
|
||||
) -> Result<Applied, String> {
|
||||
let path = local_root.join(rel_to_path(rel));
|
||||
if path.exists() {
|
||||
preserve_conflict_copy(&path, now_secs())
|
||||
.map_err(|e| format!("set aside conflict copy for {rel}: {e}"))?;
|
||||
info!(rel, "sync: kept local changes as a conflict copy");
|
||||
}
|
||||
// The local copy has just been moved aside, so the state this
|
||||
// download expects to find at the path is "nothing" — anything
|
||||
// that appears while it runs is a *new* racing write, and gets
|
||||
// its own conflict copy rather than being overwritten (B39).
|
||||
self.download_file(folder_id, local_root, rel, uid, seen, None)
|
||||
.await?;
|
||||
Ok(Applied::Conflict)
|
||||
}
|
||||
|
||||
/// Upload a brand-new local file to its remote parent, then record baseline.
|
||||
pub(super) async fn upload_new(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
local_root: &Path,
|
||||
rel: &str,
|
||||
parent: &NodeUid,
|
||||
) -> Result<Applied, String> {
|
||||
let path = local_root.join(rel_to_path(rel));
|
||||
let name = base_name(rel);
|
||||
let Some(file) = open_to_upload(&path, rel)? else {
|
||||
return Ok(Applied::Vanished);
|
||||
};
|
||||
let meta = file.metadata().map_err(|e| format!("stat {rel}: {e}"))?;
|
||||
let mtime = system_mtime(&meta);
|
||||
// Taken from the descriptor being streamed, so it names the content that
|
||||
// actually goes up rather than whatever is at the path when we finish.
|
||||
let streamed = LocalSig::from(&meta);
|
||||
let thumbnails = self
|
||||
.thumbnails_for_upload(path.clone(), name.to_string())
|
||||
.await;
|
||||
// Count the bytes as they are read, so this upload shows up in
|
||||
// `GetQueueStatus` next to a manual one. The uid isn't known until the
|
||||
// draft is sealed, so the transfer registers without one.
|
||||
let (reader, sent) = Sha1Tap::new(OwnedCountingReader::new(
|
||||
file,
|
||||
self.transfers
|
||||
.begin(name, "", TransferDirection::Upload, meta.len()),
|
||||
));
|
||||
let uid = self
|
||||
.drive
|
||||
// Mirror push: the local file is authoritative. If a prior attempt was
|
||||
// interrupted mid-upload it left an unsealed draft of this name; recover
|
||||
// it even across a daemon restart (which rotates our client uid), so the
|
||||
// folder can reach idle instead of `AlreadyExists`-looping forever.
|
||||
.upload_file_replacing_draft_from(
|
||||
parent,
|
||||
name,
|
||||
pdfs_drive::media_type_for(name),
|
||||
reader,
|
||||
meta.len() as i64,
|
||||
thumbnails,
|
||||
Some(mtime),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| format!("upload {rel}: {e}"))?;
|
||||
// The parent has gained a child that no cached listing of it knows
|
||||
// about. Without this, a folder later switched to on-demand serves a
|
||||
// snapshot that predates this upload (B86).
|
||||
self.invalidate_children_of(parent);
|
||||
warn_if_torn(rel, &path, streamed);
|
||||
let remote = self
|
||||
.landed_as_sent(rel, &uid, &sent.digest(), streamed)
|
||||
.await?;
|
||||
self.record_file_baseline(folder_id, rel, Some(streamed), &uid, &remote)?;
|
||||
Ok(Applied::Uploaded)
|
||||
}
|
||||
|
||||
/// Upload a changed local file as a new revision of an existing remote node.
|
||||
///
|
||||
/// The revision supersedes whatever is current on Drive, and the plan comes
|
||||
/// from a walk that may be minutes old. Another computer syncing the same
|
||||
/// folder may have committed a revision since, and uploading over it would
|
||||
/// leave that edit only in the revision history. So Drive is asked first,
|
||||
/// and a file that moved on is left for the next pass, which keeps the
|
||||
/// local edit as a conflict copy (B249). A revision committed between this
|
||||
/// check and the upload's own draft is not caught here; the read-back after
|
||||
/// the upload catches one committed after it.
|
||||
pub(super) async fn upload_revision(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
local_root: &Path,
|
||||
rel: &str,
|
||||
uid: &NodeUid,
|
||||
seen: &RemoteSeen,
|
||||
) -> Result<Applied, String> {
|
||||
let path = local_root.join(rel_to_path(rel));
|
||||
let Some(file) = open_to_upload(&path, rel)? else {
|
||||
return Ok(Applied::Vanished);
|
||||
};
|
||||
let current = self
|
||||
.drive
|
||||
.enumerate_nodes(std::slice::from_ref(uid))
|
||||
.await
|
||||
.map_err(|e| format!("check {rel} on Drive: {e}"))?;
|
||||
match current.first() {
|
||||
Some(node) if !node.trashed && seen.still_current(node) => {}
|
||||
Some(node) if !node.trashed => {
|
||||
return Err(format!(
|
||||
"{rel} changed on Drive since this pass looked; it is compared again on the next pass"
|
||||
));
|
||||
}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"{rel} is no longer on Drive where this pass saw it; it is compared again on the next pass"
|
||||
));
|
||||
}
|
||||
}
|
||||
let meta = file.metadata().map_err(|e| format!("stat {rel}: {e}"))?;
|
||||
let mtime = system_mtime(&meta);
|
||||
let streamed = LocalSig::from(&meta);
|
||||
let thumbnails = self
|
||||
.thumbnails_for_upload(path.clone(), base_name(rel).to_string())
|
||||
.await;
|
||||
let (reader, sent) = Sha1Tap::new(OwnedCountingReader::new(
|
||||
file,
|
||||
self.transfers.begin(
|
||||
base_name(rel),
|
||||
uid.to_string(),
|
||||
TransferDirection::Upload,
|
||||
meta.len(),
|
||||
),
|
||||
));
|
||||
self.drive
|
||||
.upload_new_revision_from(uid, reader, meta.len() as i64, thumbnails, Some(mtime))
|
||||
.await
|
||||
.map_err(|e| format!("upload revision {rel}: {e}"))?;
|
||||
warn_if_torn(rel, &path, streamed);
|
||||
let remote = self
|
||||
.landed_as_sent(rel, uid, &sent.digest(), streamed)
|
||||
.await?;
|
||||
self.record_file_baseline(folder_id, rel, Some(streamed), uid, &remote)?;
|
||||
Ok(Applied::Uploaded)
|
||||
}
|
||||
|
||||
/// Download a remote file to its local path (atomically via a temp file),
|
||||
/// stamp the local mtime to match the remote, then record baseline.
|
||||
///
|
||||
/// `expected_local` is the identity planning saw at the destination. The
|
||||
/// rename below is the destructive step, and the download in between can run
|
||||
/// for minutes, so the destination is re-examined right before it: a local
|
||||
/// file that no longer matches the plan is set aside as a conflict copy
|
||||
/// instead of being replaced (`docs/BUGS.md` B39).
|
||||
///
|
||||
/// The baseline records `seen`, the revision the pass planned to download,
|
||||
/// and not a read of the node afterwards. Another computer may commit a
|
||||
/// revision while the download runs, and a read-back would record that
|
||||
/// revision as synced while the disk holds the older one, so its edit would
|
||||
/// never arrive (B250). If the download did fetch the newer revision, the
|
||||
/// next pass fetches it once more, which costs a transfer and loses nothing.
|
||||
pub(super) async fn download_file(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
local_root: &Path,
|
||||
rel: &str,
|
||||
uid: &NodeUid,
|
||||
seen: &RemoteSeen,
|
||||
expected_local: Option<LocalSig>,
|
||||
) -> Result<(), String> {
|
||||
let (mtime, size) = (seen.mtime, seen.size);
|
||||
let path = local_root.join(rel_to_path(rel));
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("mkdir for {rel}: {e}"))?;
|
||||
}
|
||||
let tmp = staging_path(&path);
|
||||
// A file an on-demand mount already read, say one just moved here from
|
||||
// it, is in the content cache under the same revision key.
|
||||
let seeded = size > 0 && self.cache.copy_cached_to(uid, mtime, size as u64, &tmp);
|
||||
if seeded {
|
||||
std::fs::File::open(&tmp)
|
||||
.and_then(|f| f.sync_all())
|
||||
.map_err(|e| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
format!("sync tmp {rel}: {e}")
|
||||
})?;
|
||||
debug!(
|
||||
rel,
|
||||
"sync: placed from the content cache instead of downloading"
|
||||
);
|
||||
} else {
|
||||
let out = std::fs::File::create(&tmp).map_err(|e| format!("create tmp {rel}: {e}"))?;
|
||||
// Count the bytes as they land, so the download reports progress like
|
||||
// an on-demand hydration does.
|
||||
let guard = self.transfers.begin(
|
||||
base_name(rel),
|
||||
uid.to_string(),
|
||||
TransferDirection::Download,
|
||||
size.max(0) as u64,
|
||||
);
|
||||
let mut out = CountingWriter::new(out, &guard);
|
||||
self.drive
|
||||
.download_file_to(uid, &mut out)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
format!("download {rel}: {e}")
|
||||
})?;
|
||||
let mut out = out.into_inner();
|
||||
out.flush().map_err(|e| format!("flush tmp {rel}: {e}"))?;
|
||||
out.sync_all().map_err(|e| format!("sync tmp {rel}: {e}"))?;
|
||||
}
|
||||
place_download(&tmp, &path, expected_local, mtime, rel)?;
|
||||
// Here the file on disk *is* the transferred content: it was published
|
||||
// by a rename and stamped just above, so its stat is the identity.
|
||||
self.record_file_baseline(folder_id, rel, local_sig(&path), uid, seen)
|
||||
}
|
||||
|
||||
/// What Drive holds for `uid` after this daemon uploaded content with SHA-1
|
||||
/// `sent` and identity `streamed` to it, as the baseline should record it.
|
||||
///
|
||||
/// Read back so the stored signature is exactly what a walk reports next
|
||||
/// time. A digest on Drive that is not `sent` means another computer
|
||||
/// committed a revision right after this upload. Recording that revision
|
||||
/// as synced would hide it, and the edit here would be lost to it on the
|
||||
/// next download. So the baseline is left as it was, and the next pass sees
|
||||
/// both sides changed and keeps a conflict copy (B250).
|
||||
pub(super) async fn landed_as_sent(
|
||||
&self,
|
||||
rel: &str,
|
||||
uid: &NodeUid,
|
||||
sent: &str,
|
||||
streamed: LocalSig,
|
||||
) -> Result<RemoteSeen, String> {
|
||||
let node = match self.drive.enumerate_nodes(std::slice::from_ref(uid)).await {
|
||||
Ok(nodes) => nodes.into_iter().next(),
|
||||
Err(e) => {
|
||||
warn!(rel, error = %e, "sync: baseline refetch failed; using local mtime");
|
||||
None
|
||||
}
|
||||
};
|
||||
let Some(node) = node else {
|
||||
// Drive does not list a node it has just made at once. The upload
|
||||
// stamped it with the local modification time, so that and the
|
||||
// size sent are what a walk reports.
|
||||
return Ok(RemoteSeen {
|
||||
mtime: streamed.mtime,
|
||||
size: streamed.size,
|
||||
revision: None,
|
||||
});
|
||||
};
|
||||
if let Some(digest) = pdfs_drive::node_content_sha1(&node)
|
||||
&& !digest.eq_ignore_ascii_case(sent)
|
||||
{
|
||||
return Err(format!(
|
||||
"{rel} was changed on Drive by another client right after this upload; it is compared again on the next pass"
|
||||
));
|
||||
}
|
||||
let (mtime, size) = remote_file_sig(&node);
|
||||
Ok(RemoteSeen {
|
||||
mtime,
|
||||
size,
|
||||
revision: pdfs_drive::node_revision_id(&node),
|
||||
})
|
||||
}
|
||||
|
||||
/// Record a file's baseline: the local identity these bytes came from and
|
||||
/// the remote revision they were synced with. Called after every
|
||||
/// upload/download so the very next reconcile sees the path as unchanged.
|
||||
///
|
||||
/// `local` is the identity the *transferred content* corresponds to, which
|
||||
/// is not always the file's current stat. An upload streams the live file,
|
||||
/// so it passes the identity it read the first byte at: if a writer changed
|
||||
/// the file mid-stream, the remote now holds a torn revision, and recording
|
||||
/// the pre-upload identity is what makes the next pass see the path as
|
||||
/// locally changed and upload a whole, clean revision over it. Recording the
|
||||
/// post-upload stat instead declared the torn revision synchronized and left
|
||||
/// it as the file's content on Drive (`docs/BUGS.md` B40).
|
||||
pub(super) fn record_file_baseline(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel: &str,
|
||||
local: Option<LocalSig>,
|
||||
uid: &NodeUid,
|
||||
remote: &RemoteSeen,
|
||||
) -> Result<(), String> {
|
||||
let Some(local) = local else {
|
||||
return Err(format!("stat {rel}: no local identity to baseline"));
|
||||
};
|
||||
self.store
|
||||
.sync_entry_upsert(
|
||||
folder_id,
|
||||
&StoredSyncEntry {
|
||||
rel_path: rel.to_string(),
|
||||
remote_uid: Some(uid.to_string()),
|
||||
local_mtime: local.mtime,
|
||||
local_mtime_ns: local.mtime_ns,
|
||||
local_size: local.size,
|
||||
remote_rev: Some(remote.mtime.to_string()),
|
||||
remote_hash: Some(remote.size.to_string()),
|
||||
remote_revision_id: remote.revision.clone(),
|
||||
},
|
||||
)
|
||||
.map_err(|e| format!("baseline {rel}: {e:?}"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
//! The push pass: sending local changes to Drive between full passes.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Syncer {
|
||||
/// Get every local change up to Drive, and nothing else — the pass run for a
|
||||
/// folder waiting to go on-demand, whose local copy is about to be evicted.
|
||||
///
|
||||
/// This exists because a full [`do_reconcile`](Self::do_reconcile) is both too
|
||||
/// slow and too wasteful to stand between the user and the switch they asked
|
||||
/// for. It walks the whole remote tree (the minutes-long part of a pass over a
|
||||
/// large folder) to answer a question the switch makes irrelevant — what the
|
||||
/// remote side has that we don't — and then downloads those files onto a disk
|
||||
/// we are about to clear. A push pass answers only "is anything here not on
|
||||
/// Drive yet?", which the local tree and the baseline already know, so it needs
|
||||
/// no remote walk at all and finishes in the time the local walk takes.
|
||||
///
|
||||
/// The remote is consulted for exactly one thing: the files whose local copy
|
||||
/// changed. Those, and only those, could be a two-sided edit, so their nodes are
|
||||
/// fetched (cheaply, in one batch) to check whether the remote moved too. If it
|
||||
/// did, the local copy goes up under a conflict name rather than overwriting the
|
||||
/// other side. Everything else — remote edits, remote deletions, remote-only
|
||||
/// files — is left for the FUSE mount to show live once the switch lands.
|
||||
///
|
||||
/// Per-path failures are counted, never fatal, exactly as in `do_reconcile`; a
|
||||
/// non-zero [`Outcome::errors`] leaves the folder out of `idle`, which keeps the
|
||||
/// queued switch waiting rather than evicting a file that never made it up.
|
||||
pub(super) fn push_pass(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
local_root: &Path,
|
||||
remote_root: &NodeUid,
|
||||
rules: &IgnoreRules,
|
||||
) -> Result<Outcome, PassAbort> {
|
||||
// This pass uploads without walking Drive, so a walk saved by an
|
||||
// earlier pass would not know what it sent; see `do_reconcile`.
|
||||
self.store
|
||||
.sync_walk_clear(folder_id)
|
||||
.map_err(|e| format!("drop the saved walk: {e:?}"))?;
|
||||
let step = Instant::now();
|
||||
let baseline = self
|
||||
.store
|
||||
.sync_entries(folder_id)
|
||||
.map_err(|e| format!("load baseline: {e:?}"))?;
|
||||
self.trace_phase(Phase::Baseline, step.elapsed());
|
||||
// Only the local side is walked here, so each baseline path is checked once.
|
||||
self.progress_scan_total(folder_id, baseline.len());
|
||||
|
||||
let mut local: HashMap<String, LocalItem> = HashMap::new();
|
||||
let mut unscanned = Unscanned::default();
|
||||
let step = Instant::now();
|
||||
let writing = open_for_write_set(local_root);
|
||||
self.walk_local(
|
||||
folder_id,
|
||||
local_root,
|
||||
rules,
|
||||
&writing,
|
||||
&mut local,
|
||||
&mut unscanned,
|
||||
)?;
|
||||
self.trace_phase(Phase::LocalWalk, step.elapsed());
|
||||
self.trace_count(Count::LocalEntries, local.len());
|
||||
// The guard compares against the paths this pass could still see: an
|
||||
// ignored or unreadable path is absent from `local` by rule or by
|
||||
// failure, not by loss, and counting those as missing would trip the
|
||||
// guard on every pass — wedging the folder's sync permanently — the
|
||||
// moment a rule covers the whole tree.
|
||||
let tracked = tracked_baseline(&baseline, rules, &unscanned);
|
||||
// A local copy that is gone in its entirety is not trashed on Drive,
|
||||
// for the reason `guard_local_wipe` gives. A full pass stops there, but
|
||||
// this one exists for a switch to on-demand, which needs nothing local
|
||||
// and leaves Drive as it is: refusing the pass would only keep the
|
||||
// folder out of `idle`, wedging the switch for good (#46). So the pass
|
||||
// forgets those paths instead of trashing them, and the mount then
|
||||
// shows everything Drive still has.
|
||||
let local_gone = match guard_local_wipe(&tracked, &local) {
|
||||
Ok(()) => false,
|
||||
Err(reason) => {
|
||||
warn!(id = folder_id, %reason, "sync: going on-demand without trashing anything on Drive");
|
||||
true
|
||||
}
|
||||
};
|
||||
|
||||
// The remote folder uids come from the baseline instead of a walk: every
|
||||
// directory this device has synced recorded its uid there when it was
|
||||
// created or first matched up.
|
||||
let mut remote_dirs: HashMap<String, NodeUid> = HashMap::new();
|
||||
remote_dirs.insert(String::new(), remote_root.clone());
|
||||
for (rel, item) in &local {
|
||||
if !item.is_dir {
|
||||
continue;
|
||||
}
|
||||
if let Some(uid) = baseline
|
||||
.get(rel)
|
||||
.and_then(|e| e.remote_uid.as_deref())
|
||||
.and_then(parse_uid)
|
||||
{
|
||||
remote_dirs.insert(rel.clone(), uid);
|
||||
}
|
||||
}
|
||||
// A local directory the baseline has no uid for is either brand new or one
|
||||
// whose first pass never finished — and those look identical from here.
|
||||
// Creating it blindly would duplicate a remote folder we simply haven't
|
||||
// looked at, so when any exist, the remote folder tree is walked for real.
|
||||
// It costs one light listing per folder and no file keys, and a folder whose
|
||||
// baseline is complete — the case this pass is written for — skips it
|
||||
// entirely and touches the network only for the files it uploads.
|
||||
if local
|
||||
.iter()
|
||||
.any(|(rel, item)| item.is_dir && !remote_dirs.contains_key(rel))
|
||||
{
|
||||
self.walk_remote_dirs(folder_id, remote_root, "", &mut remote_dirs)?;
|
||||
}
|
||||
|
||||
// Files whose local copy has moved since the baseline: the only ones with
|
||||
// anything to push, and the only ones that could be a two-sided edit.
|
||||
let changed: Vec<&String> = local
|
||||
.iter()
|
||||
.filter(|(_, item)| !item.is_dir && !item.open_for_write)
|
||||
.filter(|(rel, item)| {
|
||||
baseline
|
||||
.get(*rel)
|
||||
.is_none_or(|b| b.local_mtime != item.mtime || b.local_size != item.size)
|
||||
})
|
||||
.map(|(rel, _)| rel)
|
||||
.collect();
|
||||
|
||||
// One light batch tells us which of those also changed remotely. A light
|
||||
// node carries the modification time and the revision id without
|
||||
// unlocking the node key, and those are what the baseline compares
|
||||
// against.
|
||||
let check: Vec<NodeUid> = changed
|
||||
.iter()
|
||||
.filter_map(|rel| baseline.get(*rel))
|
||||
.filter_map(|e| e.remote_uid.as_deref())
|
||||
.filter_map(parse_uid)
|
||||
.collect();
|
||||
let remote_now: HashMap<String, (i64, Option<String>)> = if check.is_empty() {
|
||||
HashMap::new()
|
||||
} else {
|
||||
self.rt
|
||||
.block_on(self.drive.enumerate_nodes_light(&check))
|
||||
.map_err(|e| format!("resolve changed nodes: {e}"))?
|
||||
.into_iter()
|
||||
.filter(|n| !n.trashed)
|
||||
.map(|n| {
|
||||
let revision = pdfs_drive::node_revision_id(&n);
|
||||
(n.uid.to_string(), (n.modification_time, revision))
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let changed: HashSet<&String> = changed.into_iter().collect();
|
||||
|
||||
let mut outcome = Outcome {
|
||||
deferred: local.values().filter(|item| item.open_for_write).count(),
|
||||
unscanned: unscanned.report(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut order: Vec<&String> = local.keys().collect();
|
||||
order.sort_by_key(|p| p.matches('/').count());
|
||||
|
||||
// Same depth-ascending batching as `do_reconcile`: a folder is created
|
||||
// remotely before the paths inside it are classified, so their parent uid is
|
||||
// in `remote_dirs` by the time they need it.
|
||||
let mut batch: Vec<Pending> = Vec::new();
|
||||
let mut batch_depth = 0usize;
|
||||
for rel in order {
|
||||
let depth = rel.matches('/').count();
|
||||
if depth > batch_depth {
|
||||
self.flush_batch(
|
||||
folder_id,
|
||||
local_root,
|
||||
&mut remote_dirs,
|
||||
std::mem::take(&mut batch),
|
||||
&mut outcome,
|
||||
)?;
|
||||
batch_depth = depth;
|
||||
}
|
||||
let item = &local[rel];
|
||||
if item.is_dir {
|
||||
// The folder is already on Drive, so only its children carry work —
|
||||
// but if the walk above is what found it, record the uid now so the
|
||||
// next pass over this folder needs no walk at all.
|
||||
if let Some(uid) = remote_dirs.get(rel) {
|
||||
if baseline
|
||||
.get(rel)
|
||||
.and_then(|e| e.remote_uid.as_deref())
|
||||
.is_none()
|
||||
&& let Err(e) = self.baseline_dir(folder_id, rel, uid)
|
||||
{
|
||||
warn!(rel, error = %e, "sync: folder step failed; continuing");
|
||||
outcome.failed(&format!("{rel}: {e}"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match remote_dirs.get(parent_rel(rel)) {
|
||||
Some(parent) => batch.push(Pending::CreateDir {
|
||||
rel: rel.clone(),
|
||||
parent: parent.clone(),
|
||||
}),
|
||||
None => {
|
||||
warn!(rel, "sync: no remote parent for folder; continuing");
|
||||
outcome.failed(&format!("{rel}: no remote parent for folder"));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !changed.contains(rel) {
|
||||
// Local copy matches the baseline, so it is already on Drive.
|
||||
continue;
|
||||
}
|
||||
|
||||
let base = baseline.get(rel);
|
||||
let uid = base
|
||||
.and_then(|e| e.remote_uid.as_deref())
|
||||
.and_then(parse_uid);
|
||||
match uid {
|
||||
// Never uploaded (or the remote node is gone): it goes up as a new file.
|
||||
None => match remote_dirs.get(parent_rel(rel)) {
|
||||
Some(parent) => batch.push(Pending::UploadNew {
|
||||
rel: rel.clone(),
|
||||
parent: parent.clone(),
|
||||
}),
|
||||
None => {
|
||||
warn!(rel, "sync: no remote parent for file; continuing");
|
||||
outcome.failed(&format!("{rel}: no remote parent for file"));
|
||||
}
|
||||
},
|
||||
Some(uid) => {
|
||||
let (remote_moved, seen) = match remote_now.get(&uid.to_string()) {
|
||||
Some((mtime, revision)) => {
|
||||
let recorded = base.and_then(remote_sig);
|
||||
let moved = recorded.is_none_or(|(m, _)| m != *mtime)
|
||||
|| revision_moved(base, revision.as_deref());
|
||||
let seen = RemoteSeen {
|
||||
mtime: *mtime,
|
||||
size: recorded.map_or(0, |(_, size)| size),
|
||||
revision: revision.clone(),
|
||||
};
|
||||
(moved, seen)
|
||||
}
|
||||
// Trashed or unreadable remotely — treat as gone and re-upload
|
||||
// the local copy as a new file rather than losing it.
|
||||
None => {
|
||||
match remote_dirs.get(parent_rel(rel)) {
|
||||
Some(parent) => batch.push(Pending::UploadNew {
|
||||
rel: rel.clone(),
|
||||
parent: parent.clone(),
|
||||
}),
|
||||
None => {
|
||||
warn!(rel, "sync: no remote parent for file; continuing");
|
||||
outcome.failed(&format!("{rel}: no remote parent for file"));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if remote_moved {
|
||||
match remote_dirs.get(parent_rel(rel)) {
|
||||
Some(parent) => batch.push(Pending::PushConflict {
|
||||
rel: rel.clone(),
|
||||
parent: parent.clone(),
|
||||
}),
|
||||
None => {
|
||||
warn!(rel, "sync: no remote parent for file; continuing");
|
||||
outcome.failed(&format!("{rel}: no remote parent for file"));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
batch.push(Pending::UploadRevision {
|
||||
rel: rel.clone(),
|
||||
uid,
|
||||
seen,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.flush_batch(
|
||||
folder_id,
|
||||
local_root,
|
||||
&mut remote_dirs,
|
||||
std::mem::take(&mut batch),
|
||||
&mut outcome,
|
||||
)?;
|
||||
|
||||
// Paths the baseline knows that are no longer on disk: the user deleted them
|
||||
// locally, and the deletion has to reach Drive before the mount starts
|
||||
// showing the folder's remote contents — otherwise everything they deleted
|
||||
// comes back the moment the switch lands. Shallowest first, skipping anything
|
||||
// under a folder already trashed (its children went with it).
|
||||
let deletions = local_deletions(&tracked, &local);
|
||||
if local_gone {
|
||||
// Forgotten instead of trashed. A row left behind would read to
|
||||
// the switch as a deletion not on Drive yet and withdraw it, and
|
||||
// to a later full pass as a reason to stop again. Forgotten, a full
|
||||
// pass downloads the paths again.
|
||||
let mut forgotten: HashSet<&str> = HashSet::new();
|
||||
for rel in &deletions {
|
||||
let mut parent = parent_rel(rel);
|
||||
while !parent.is_empty() && !forgotten.contains(parent) {
|
||||
parent = parent_rel(parent);
|
||||
}
|
||||
if parent.is_empty() {
|
||||
let _ = self.store.sync_entries_remove_subtree(folder_id, rel);
|
||||
forgotten.insert(rel);
|
||||
}
|
||||
}
|
||||
return Ok(outcome);
|
||||
}
|
||||
let mut trashed: Vec<String> = Vec::new();
|
||||
for rel in &deletions {
|
||||
if trashed
|
||||
.iter()
|
||||
.any(|dir| rel.starts_with(&format!("{dir}/")))
|
||||
{
|
||||
let _ = self.store.sync_entry_remove(folder_id, rel);
|
||||
continue;
|
||||
}
|
||||
let Some(uid) = baseline[rel].remote_uid.as_deref().and_then(parse_uid) else {
|
||||
let _ = self.store.sync_entry_remove(folder_id, rel);
|
||||
continue;
|
||||
};
|
||||
if let Err(e) = self
|
||||
.rt
|
||||
.block_on(self.drive.trash_nodes(&[uid]))
|
||||
.and_then(batch::into_unit)
|
||||
{
|
||||
warn!(rel, error = %e, "sync: trash remote failed");
|
||||
self.log_activity(ActivityKind::Trash, base_name(rel), e.to_string(), false);
|
||||
outcome.failed(&format!("{rel}: {e}"));
|
||||
continue;
|
||||
}
|
||||
trashed.push(rel.clone());
|
||||
if let Some(parent) = parent_uid_of(rel, &remote_dirs, &baseline) {
|
||||
self.invalidate_children_of(&parent);
|
||||
}
|
||||
let _ = self.store.sync_entry_remove(folder_id, rel);
|
||||
self.log_activity(
|
||||
ActivityKind::Trash,
|
||||
base_name(rel),
|
||||
"removed on Drive",
|
||||
true,
|
||||
);
|
||||
outcome.deleted += 1;
|
||||
}
|
||||
|
||||
Ok(outcome)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,553 @@
|
||||
//! The walks of a pass: the local tree, Drive's folders (resumable, and only
|
||||
//! the changed ones when the event feed can be trusted), and listing one.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Syncer {
|
||||
/// Recursively walk a local tree into `out`, keyed by `/`-joined relative
|
||||
/// path. Symlinks and other special files are skipped, and paths that cannot
|
||||
/// be read go to `unscanned`. Reports each entry to the pass's scan progress.
|
||||
pub(super) fn walk_local(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
root: &Path,
|
||||
rules: &IgnoreRules,
|
||||
writing: &HashSet<PathBuf>,
|
||||
out: &mut HashMap<String, LocalItem>,
|
||||
unscanned: &mut Unscanned,
|
||||
) -> Result<(), String> {
|
||||
walk_local_tree(root, rules, writing, out, unscanned, &mut |rel| {
|
||||
self.progress_scanned(folder_id, base_name(rel))
|
||||
})
|
||||
}
|
||||
|
||||
/// Map every remote folder under `folder` to its uid by rel path, ignoring
|
||||
/// files. The cheap half of [`walk_remote`](Self::walk_remote): folders carry no
|
||||
/// content signature, so a light listing answers this without unlocking a single
|
||||
/// node key. Used by [`push_pass`](Self::push_pass) to tell a folder it must
|
||||
/// create from one it just hasn't recorded yet.
|
||||
pub(super) fn walk_remote_dirs(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
folder: &NodeUid,
|
||||
prefix: &str,
|
||||
dirs: &mut HashMap<String, NodeUid>,
|
||||
) -> Result<(), String> {
|
||||
let uids = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_folder_children_node_uids(folder))
|
||||
.map_err(|e| format!("enumerate {folder}: {e}"))?;
|
||||
if uids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let nodes = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_nodes_light(&uids))
|
||||
.map_err(|e| format!("resolve nodes: {e}"))?;
|
||||
for node in nodes {
|
||||
if node.trashed || !node.is_folder() || !pdfs_drive::remote_name_is_safe(&node.name) {
|
||||
continue;
|
||||
}
|
||||
let rel = join_rel(prefix, &node.name);
|
||||
self.progress_scanned(folder_id, base_name(&rel));
|
||||
dirs.insert(rel.clone(), node.uid.clone());
|
||||
self.walk_remote_dirs(folder_id, &node.uid, &rel, dirs)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Walk the remote tree of a mirror folder into `walk`, folder by folder,
|
||||
/// recording every descendant's relative path, and mapping each subfolder's
|
||||
/// rel path to its uid in `walk.dirs`.
|
||||
///
|
||||
/// A file's size comes from its extended attributes, which only its own node
|
||||
/// key can decrypt — and unlocking that key costs an S2K derivation (tens of
|
||||
/// milliseconds) *per file*, which is the bulk of a pass over a large folder.
|
||||
/// So the walk enumerates cheaply ([`enumerate_nodes_light`]) and only pays
|
||||
/// for the files whose modification time has moved away from `baseline`: an
|
||||
/// unchanged mtime means the recorded size still stands.
|
||||
///
|
||||
/// [`enumerate_nodes_light`]: proton_drive_rs::ProtonDriveClient::enumerate_nodes_light
|
||||
///
|
||||
/// What the walk could not read goes to `walk.gaps`, never silently out of
|
||||
/// the map: a missing path reads as deleted on Drive.
|
||||
///
|
||||
/// Each folder's listing is saved as it comes in. A walk cut short by a
|
||||
/// stop resumes from what was saved and lists only the folders it had not
|
||||
/// reached, where it used to start over and, on a folder large enough,
|
||||
/// never finish (B294). The database drops a saved walk whenever the
|
||||
/// folder's baseline changes, so a resumed walk never meets a baseline
|
||||
/// newer than its listings; it is as old as a long walk's first listings
|
||||
/// would be, and the apply step checks each file again before it acts.
|
||||
pub(super) fn walk_remote(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
root: &NodeUid,
|
||||
walk: &mut RemoteWalk<'_>,
|
||||
baseline: &HashMap<String, StoredSyncEntry>,
|
||||
) -> Result<(), PassAbort> {
|
||||
let WalkStart {
|
||||
mut todo,
|
||||
mut children,
|
||||
dirty_upto,
|
||||
} = self.start_walk(folder_id, root, walk);
|
||||
// Folders to list again next pass: their listing failed or came back
|
||||
// short this time.
|
||||
let mut again: Vec<String> = Vec::new();
|
||||
let mut listed: HashSet<String> = HashSet::new();
|
||||
while let Some(next) = todo.pop_front() {
|
||||
// Checked per folder, not per pass: this walk is the long pole on a
|
||||
// large tree, and a user who asks for on-demand three minutes into
|
||||
// it should not wait out the rest of a survey of files they want
|
||||
// deleted. Bailing out here is safe precisely because the walk has
|
||||
// applied nothing — a *partial* remote map, on the other hand,
|
||||
// would be read as "the remote deleted everything we haven't
|
||||
// reached yet", so it must never reach the diff.
|
||||
if self.shutdown.is_stopping() {
|
||||
return Err(PassAbort::Stopped);
|
||||
}
|
||||
if self.pass_abandoned(folder_id) {
|
||||
return Err(PassAbort::Abandoned);
|
||||
}
|
||||
if self.ondemand_queued(folder_id) {
|
||||
return Err(PassAbort::Interrupted);
|
||||
}
|
||||
// Gone with a folder listed again before it, or listed already.
|
||||
if walk.dirs.get(&next.prefix) != Some(&next.uid) || !listed.insert(next.prefix.clone())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let prefix = next.prefix;
|
||||
// What an earlier listing could not read is read again now.
|
||||
walk.gaps.forget(&prefix);
|
||||
let Some(listing) = self.list_remote(folder_id, &next.uid, &prefix, walk, baseline)?
|
||||
else {
|
||||
// What the saved walk holds of it is older than the change
|
||||
// that marked it: its files are left out of this pass, as a
|
||||
// folder a full walk could not list is.
|
||||
if let Some(children) = &children {
|
||||
for rel in children.of(&prefix) {
|
||||
if !walk.dirs.contains_key(rel) {
|
||||
walk.out.remove(rel);
|
||||
}
|
||||
}
|
||||
}
|
||||
again.push(prefix);
|
||||
continue;
|
||||
};
|
||||
if listing.short || !listing.unread.is_empty() {
|
||||
again.push(prefix.clone());
|
||||
}
|
||||
let mut removed = Vec::new();
|
||||
let mut kept: HashSet<String> = HashSet::new();
|
||||
if let Some(children) = &mut children {
|
||||
// Listed again: what it held before and no longer holds goes,
|
||||
// with all under it. A folder still there under the same uid
|
||||
// keeps what was saved under it.
|
||||
let fresh: HashMap<&str, &RemoteItem> = listing
|
||||
.items
|
||||
.iter()
|
||||
.map(|(rel, item)| (rel.as_str(), item))
|
||||
.collect();
|
||||
for old in children.take(&prefix) {
|
||||
let same_folder = walk.dirs.get(&old).is_some_and(|uid| {
|
||||
fresh
|
||||
.get(old.as_str())
|
||||
.is_some_and(|item| item.is_dir && &item.uid == uid)
|
||||
});
|
||||
if same_folder {
|
||||
kept.insert(old);
|
||||
} else {
|
||||
children.remove_subtree(&old, walk, &mut removed);
|
||||
}
|
||||
}
|
||||
children.add(
|
||||
&prefix,
|
||||
listing
|
||||
.items
|
||||
.iter()
|
||||
.map(|(rel, _)| rel)
|
||||
.chain(&listing.unread),
|
||||
);
|
||||
}
|
||||
let mut saved = Vec::with_capacity(listing.items.len() + listing.unread.len());
|
||||
for (rel, item) in listing.items {
|
||||
self.progress_scanned(folder_id, base_name(&rel));
|
||||
saved.push(SavedWalkItem {
|
||||
rel_path: rel.clone(),
|
||||
uid: Some(item.uid.to_string()),
|
||||
is_dir: item.is_dir,
|
||||
mtime: item.mtime,
|
||||
size: item.size,
|
||||
revision: item.revision.clone(),
|
||||
sha1: item.sha1.clone(),
|
||||
});
|
||||
if item.is_dir {
|
||||
walk.dirs.insert(rel.clone(), item.uid.clone());
|
||||
if !kept.contains(&rel) {
|
||||
todo.push_back(WalkNext {
|
||||
prefix: rel.clone(),
|
||||
uid: item.uid.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
walk.out.insert(rel, item);
|
||||
}
|
||||
for rel in listing.unread {
|
||||
self.progress_scanned(folder_id, base_name(&rel));
|
||||
saved.push(SavedWalkItem {
|
||||
rel_path: rel.clone(),
|
||||
uid: None,
|
||||
is_dir: false,
|
||||
mtime: 0,
|
||||
size: 0,
|
||||
revision: None,
|
||||
sha1: None,
|
||||
});
|
||||
walk.gaps.unread(rel);
|
||||
}
|
||||
// A walk that cannot be saved still runs; it just starts over if
|
||||
// it is cut short.
|
||||
if let Err(e) =
|
||||
self.store
|
||||
.sync_walk_record(folder_id, &prefix, listing.short, &saved, &removed)
|
||||
{
|
||||
debug!(folder = prefix, error = ?e, "sync: cannot save the walk's progress");
|
||||
}
|
||||
}
|
||||
// A stop that came during the last listing still ends the pass here,
|
||||
// and the next one resumes a walk with nothing left to list.
|
||||
if self.shutdown.is_stopping() {
|
||||
return Err(PassAbort::Stopped);
|
||||
}
|
||||
self.finish_walk(folder_id, dirty_upto, &again)
|
||||
.map_err(|e| PassAbort::from(format!("save the walk of Drive: {e:?}")))
|
||||
}
|
||||
|
||||
/// Keep a walk that reached its end as the next pass's picture of Drive.
|
||||
/// A walk that listed every folder drops the dirty marks it read past; a
|
||||
/// walk of the dirty folders only drops the marks it read, up to
|
||||
/// `dirty_upto`. Either way, the folders in `again` stay dirty, so the
|
||||
/// next pass lists them again.
|
||||
pub(super) fn finish_walk(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
dirty_upto: Option<i64>,
|
||||
again: &[String],
|
||||
) -> pdfs_core::Result<()> {
|
||||
if !again.is_empty() {
|
||||
self.store.sync_remote_mark(folder_id, again)?;
|
||||
}
|
||||
match dirty_upto {
|
||||
Some(seq) => self.store.sync_remote_dirty_consume(folder_id, seq),
|
||||
None => {
|
||||
if !self.store.sync_walk_complete(folder_id)? {
|
||||
debug!(
|
||||
id = folder_id,
|
||||
"sync: the walk of Drive was dropped before its end"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a walk of Drive starts.
|
||||
///
|
||||
/// - A complete walk, kept up to date by the event stream, is loaded into
|
||||
/// `walk`, and only the folders marked dirty since are listed again.
|
||||
/// - A walk an earlier pass did not finish is loaded and continues, when
|
||||
/// it is recent enough.
|
||||
/// - Otherwise a new walk starts at the root.
|
||||
pub(super) fn start_walk(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
root: &NodeUid,
|
||||
walk: &mut RemoteWalk<'_>,
|
||||
) -> WalkStart {
|
||||
let root_uid = root.to_string();
|
||||
let saved = match self.store.sync_walk_load(folder_id) {
|
||||
Ok(saved) => saved,
|
||||
Err(e) => {
|
||||
warn!(id = folder_id, error = ?e, "sync: cannot read the saved walk; starting over");
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(saved) = saved
|
||||
&& saved.root_uid == root_uid
|
||||
{
|
||||
let age = now_secs().saturating_sub(saved.started);
|
||||
if saved.complete
|
||||
&& age < AUDIT_INTERVAL.as_secs() as i64
|
||||
&& self.events_trusted(root)
|
||||
&& let Some(start) = self.walk_dirty(folder_id, &saved, walk)
|
||||
{
|
||||
return start;
|
||||
}
|
||||
if !saved.complete
|
||||
&& age < WALK_MAX_AGE.as_secs() as i64
|
||||
&& let Some(restored) = restore_walk(&saved, walk)
|
||||
{
|
||||
self.progress_scanned_many(folder_id, restored.items);
|
||||
self.trace_count(Count::Resumed, restored.items);
|
||||
info!(
|
||||
id = folder_id,
|
||||
restored = restored.items,
|
||||
folders_left = restored.todo.len(),
|
||||
age_s = age,
|
||||
"sync: resuming the walk of Drive"
|
||||
);
|
||||
return WalkStart {
|
||||
todo: restored.todo,
|
||||
children: None,
|
||||
dirty_upto: None,
|
||||
};
|
||||
}
|
||||
// Loaded into `walk`, and of no use: start from nothing.
|
||||
walk.out.clear();
|
||||
walk.dirs.retain(|rel, _| rel.is_empty());
|
||||
*walk.gaps = RemoteGaps::default();
|
||||
}
|
||||
if let Err(e) = self.store.sync_walk_begin(folder_id, &root_uid, now_secs()) {
|
||||
debug!(id = folder_id, error = ?e, "sync: cannot save the walk's progress");
|
||||
}
|
||||
WalkStart {
|
||||
todo: VecDeque::from([WalkNext {
|
||||
prefix: String::new(),
|
||||
uid: root.clone(),
|
||||
}]),
|
||||
children: None,
|
||||
dirty_upto: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Start from a complete walk: load it into `walk`, and list again the
|
||||
/// folders marked dirty since, plus any found since and not listed yet.
|
||||
/// `None` when it cannot be read back.
|
||||
pub(super) fn walk_dirty(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
saved: &SavedWalk,
|
||||
walk: &mut RemoteWalk<'_>,
|
||||
) -> Option<WalkStart> {
|
||||
let dirty = match self.store.sync_remote_dirty(folder_id) {
|
||||
Ok(dirty) => dirty,
|
||||
Err(e) => {
|
||||
warn!(id = folder_id, error = ?e, "sync: cannot read what changed on Drive");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let restored = restore_walk(saved, walk)?;
|
||||
let mut todo = restored.todo;
|
||||
let mut dirs: Vec<&str> = dirty.iter().map(|(_, dir)| dir.as_str()).collect();
|
||||
dirs.sort_by_key(|dir| (dir.matches('/').count(), *dir));
|
||||
dirs.dedup();
|
||||
// Shallowest first: a folder listed again may turn out new or gone,
|
||||
// and is then listed whole or dropped with what is under it.
|
||||
for dir in &dirs {
|
||||
match walk.dirs.get(*dir) {
|
||||
Some(uid) => todo.push_back(WalkNext {
|
||||
prefix: dir.to_string(),
|
||||
uid: uid.clone(),
|
||||
}),
|
||||
// Gone from Drive, or new and not listed yet: listing its
|
||||
// parent, marked too, settles it.
|
||||
None => debug!(id = folder_id, dir, "sync: a dirty folder is not on Drive"),
|
||||
}
|
||||
}
|
||||
self.progress_scanned_many(folder_id, restored.items);
|
||||
self.trace_count(Count::Reused, restored.items);
|
||||
self.trace_count(Count::Dirty, dirs.len());
|
||||
info!(
|
||||
id = folder_id,
|
||||
known = restored.items,
|
||||
dirty = dirs.len(),
|
||||
to_list = todo.len(),
|
||||
"sync: listing only the folders changed on Drive"
|
||||
);
|
||||
Some(WalkStart {
|
||||
todo,
|
||||
children: Some(restored.children),
|
||||
dirty_upto: Some(dirty.iter().map(|(seq, _)| *seq).max().unwrap_or(0)),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether Drive's event stream for `root` is being followed, so a
|
||||
/// change on Drive is marked dirty by the time a pass looks. The stream
|
||||
/// covers the account's own volume only, and must have been read lately.
|
||||
///
|
||||
/// Right after a start, the stream has not been read yet: wait a little
|
||||
/// for it rather than walk all of Drive again.
|
||||
pub(super) fn events_trusted(&self, root: &NodeUid) -> bool {
|
||||
if root.volume_id != self.primary_root_uid.volume_id {
|
||||
return false;
|
||||
}
|
||||
let started = Instant::now();
|
||||
while self.events_read_at.load(Ordering::Relaxed) == 0
|
||||
&& started.elapsed() < EVENTS_FRESH
|
||||
&& self.shutdown.sleep(Duration::from_millis(250))
|
||||
{}
|
||||
let read_at = self.events_read_at.load(Ordering::Relaxed);
|
||||
read_at > 0 && now_secs().saturating_sub(read_at) < EVENTS_FRESH.as_secs() as i64
|
||||
}
|
||||
|
||||
/// List one folder on Drive. `None` when the listing failed: that is
|
||||
/// noted in `walk.gaps`, and the folder is not saved as listed, so a
|
||||
/// resumed walk asks again. A failure at the root fails the pass.
|
||||
pub(super) fn list_remote(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
folder: &NodeUid,
|
||||
prefix: &str,
|
||||
walk: &mut RemoteWalk<'_>,
|
||||
baseline: &HashMap<String, StoredSyncEntry>,
|
||||
) -> Result<Option<Listing>, PassAbort> {
|
||||
let listing = Instant::now();
|
||||
let step = Instant::now();
|
||||
let uids = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_folder_children_node_uids(folder))
|
||||
.map_err(|e| format!("enumerate {folder}: {e}"));
|
||||
self.trace_call(Call::ListChildren, step.elapsed());
|
||||
self.trace_count(Count::RemoteFolders, 1);
|
||||
let Some(uids) = unlisted_gap(walk, prefix, uids)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut out = Listing::default();
|
||||
if uids.is_empty() {
|
||||
return Ok(Some(out));
|
||||
}
|
||||
let step = Instant::now();
|
||||
let nodes = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_nodes_light(&uids))
|
||||
.map_err(|e| format!("resolve nodes: {e}"));
|
||||
self.trace_call(Call::ReadNodes, step.elapsed());
|
||||
let Some(nodes) = unlisted_gap(walk, prefix, nodes)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
// The SDK leaves out a node it cannot decrypt, and says so only in its
|
||||
// log. Its name went with it, so all this can record is the folder.
|
||||
if nodes.len() < uids.len() {
|
||||
warn!(
|
||||
folder = prefix,
|
||||
listed = uids.len(),
|
||||
read = nodes.len(),
|
||||
"sync: some nodes on Drive cannot be read; leaving them out"
|
||||
);
|
||||
walk.gaps.short_listing(prefix);
|
||||
out.short = true;
|
||||
}
|
||||
let nodes: Vec<Node> = nodes
|
||||
.into_iter()
|
||||
.filter(|node| {
|
||||
let safe = pdfs_drive::remote_name_is_safe(&node.name);
|
||||
if !safe {
|
||||
warn!(folder = prefix, uid = %node.uid, "sync: a name on Drive cannot be a local file name; leaving it out");
|
||||
}
|
||||
safe
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Files whose recorded mtime no longer matches: their size has to be
|
||||
// read for real, so these are the only node keys worth unlocking.
|
||||
let stale: Vec<NodeUid> = nodes
|
||||
.iter()
|
||||
.filter(|n| !n.trashed && !n.is_folder())
|
||||
.filter(|n| {
|
||||
unchanged_remote_size(
|
||||
baseline,
|
||||
&join_rel(prefix, &n.name),
|
||||
n.modification_time,
|
||||
pdfs_drive::node_revision_id(n).as_deref(),
|
||||
)
|
||||
.is_none()
|
||||
})
|
||||
.map(|n| n.uid.clone())
|
||||
.collect();
|
||||
// The full enumeration also decrypts the content digest, which the
|
||||
// first sync of a path compares against the local file (B248).
|
||||
let sized: HashMap<String, (i64, Option<String>)> = if stale.is_empty() {
|
||||
HashMap::new()
|
||||
} else {
|
||||
let step = Instant::now();
|
||||
let full = self
|
||||
.rt
|
||||
.block_on(self.drive.enumerate_nodes(&stale))
|
||||
.map_err(|e| format!("resolve nodes: {e}"));
|
||||
self.trace_call(Call::ReadNodesFull, step.elapsed());
|
||||
self.trace_count(Count::NodesFull, stale.len());
|
||||
let Some(full) = unlisted_gap(walk, prefix, full)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
full.iter()
|
||||
.map(|n| {
|
||||
(
|
||||
n.uid.to_string(),
|
||||
(remote_file_sig(n).1, pdfs_drive::node_content_sha1(n)),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let stale: HashSet<String> = stale.iter().map(|u| u.to_string()).collect();
|
||||
self.record_revisions(folder_id, prefix, &nodes, &sized, baseline);
|
||||
self.trace_count(Count::Nodes, nodes.len());
|
||||
self.engine.trace(|t| t.listing(prefix, listing.elapsed()));
|
||||
|
||||
for node in nodes {
|
||||
if node.trashed {
|
||||
continue;
|
||||
}
|
||||
let rel = join_rel(prefix, &node.name);
|
||||
if node.is_folder() {
|
||||
out.items.push((
|
||||
rel,
|
||||
RemoteItem {
|
||||
uid: node.uid,
|
||||
is_dir: true,
|
||||
mtime: 0,
|
||||
size: 0,
|
||||
revision: None,
|
||||
sha1: None,
|
||||
},
|
||||
));
|
||||
continue;
|
||||
}
|
||||
let (size, sha1) = if stale.contains(&node.uid.to_string()) {
|
||||
match sized.get(&node.uid.to_string()) {
|
||||
Some(sized) => sized.clone(),
|
||||
// Its size was needed but could not be read (the full
|
||||
// enumeration skipped it as undecryptable). Leave it out
|
||||
// rather than record a stale size, and say so: missing,
|
||||
// it would read as deleted on Drive.
|
||||
None => {
|
||||
out.unread.push(rel);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match unchanged_remote_size(
|
||||
baseline,
|
||||
&rel,
|
||||
node.modification_time,
|
||||
pdfs_drive::node_revision_id(&node).as_deref(),
|
||||
) {
|
||||
Some(size) => (size, None),
|
||||
None => continue,
|
||||
}
|
||||
};
|
||||
out.items.push((
|
||||
rel,
|
||||
RemoteItem {
|
||||
revision: pdfs_drive::node_revision_id(&node),
|
||||
uid: node.uid,
|
||||
is_dir: false,
|
||||
mtime: node.modification_time,
|
||||
size,
|
||||
sha1,
|
||||
},
|
||||
));
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
}
|
||||
+47
-8
@@ -50,7 +50,7 @@ graph TD
|
||||
| [`pdfs-core`](../crates/pdfs-core) | Authentication and keyring (`auth`), configuration and directories (`config`), the control protocol (`control`), search scoring, ignore rules, Google Takeout parsing, the machine profile, the transfer registry (`transfers`) and the shutdown signal (`shutdown`) |
|
||||
| [`pdfs-store`](../crates/pdfs-store) | The SQLite schema and queries (`db/`), the content cache (`cache`) |
|
||||
| [`pdfs-drive`](../crates/pdfs-drive) | The `DriveApi` seam over the SDK, the call counter (`counted`), and `FakeDrive` for the simulations |
|
||||
| [`pdfs-sync`](../crates/pdfs-sync) | The mirror engine: its passes and engine thread (`mirror`), with its reads and writes of the local disk in one module (`mirror::local`), and the parts with no I/O: planner, pass model and pass trace. It owns its state (`SyncParts`), reads and writes its tables only through `SyncStore`, and reaches the daemon only through `SyncHost` |
|
||||
| [`pdfs-sync`](../crates/pdfs-sync) | The mirror engine: its passes (`mirror`), split into the walks (`mirror::walk`), applying a plan (`mirror::apply`) and the push pass (`mirror::push`), its engine thread (`mirror::engine`), its reads and writes of the local disk in one module (`mirror::local`), and the parts with no I/O: planner, pass model and pass trace. It owns its state (`SyncParts`), reads and writes its tables only through `SyncStore`, and reaches the daemon only through `SyncHost` |
|
||||
| [`pdfs-fuse`](../crates/pdfs-fuse) | The daemon: FUSE handlers (`filesystem`), the tree (`state`), finding nodes (`resolve`), folder listings and file sizes (`listing`, `sizes`), reads (`reads`), queueing and the drain (`enqueue`, `queue`, `drain`, `upload`), calls sent straight to Drive (`remote`), requests by path (`requests`), startup recovery (`recovery`), pins, search, trash, the shared tree (`shared`), 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-daemon`](../crates/pdfs-daemon) | The daemon's composition root: waits for a session, opens the database and the content cache, resumes the session and mounts, then remounts or retries with a backoff and records each failure |
|
||||
| [`pdfs-cli`](../crates/pdfs-cli) | The `pdfs` binary. `pdfs daemon` runs `pdfs_daemon::run` in-process; every other command is a control-socket client |
|
||||
@@ -469,7 +469,9 @@ both with `pdfs_core::search::relevance_score`, so the prompt can merge them int
|
||||
| `pdfs-control` | Accepts control connections; at most 64 handlers |
|
||||
| `pdfs-events` | Publishes status, transfer and topic changes to subscribers |
|
||||
| `pdfs-sync`, `pdfs-sync-poll` | Mirror passes and the remote poll (§7) |
|
||||
| Tokio runtime | Remote calls, and the Drive and photos event streams (§6) |
|
||||
| `pdfs-event-sync`, `pdfs-photo-events` | Async tasks on the Tokio runtime that follow the Drive and photos event streams (§6) |
|
||||
| `pdfs-gallery` | Async task. Refreshes the gallery's visibility every minute and on request |
|
||||
| Tokio runtime | Remote calls |
|
||||
| `pdfs-online-probe` | Probes Drive while offline |
|
||||
| `pdfs-pin-keeper` | Checks pins once a second for work: every pin at startup, when the link returns and after the event feed loses continuity, and the pins a batch of remote events changed. Downloads files kept offline that are missing or stale; failures retry with a backoff of 30 s to 30 min (`docs/BUGS.md` B282) |
|
||||
| `pdfs-supervisor` | Logs workers that hold one job for minutes, a queue that stops draining, and control requests that never return; samples memory; pings the systemd watchdog only after a round trip over the control socket succeeds (`WatchdogSec=120`) |
|
||||
@@ -481,10 +483,21 @@ instead of leaving them behind (`docs/BUGS.md` B44). The mount starts its long-l
|
||||
through `pdfs_core::lifecycle::Services`. Each one is started with its name and, if it blocks where
|
||||
the signal does not reach, the call that wakes it: the drain's condvar, the sync engine's `Stop`
|
||||
message, a connection to the control socket. A stop signals, wakes and joins them in reverse start
|
||||
order, up to one 10-second deadline, and names any that are still running at the end.
|
||||
order, up to one 10-second deadline, and names any that are still running at the end. A
|
||||
service can also be an async task on the runtime (`Services::spawn_task`): the event streams and
|
||||
the gallery refresh. A stop aborts such a task at its next `.await` and waits for it to end. These
|
||||
tasks used to run until the runtime went away, which on a stop is when the process exits.
|
||||
The sims fail a run whose stops leave a service running.
|
||||
`pdfs diagnostics` reports what each worker is doing and which services are still running. The
|
||||
supervisor warns once about a service that ended while the mount runs.
|
||||
|
||||
Work a request starts and does not wait for (a cache check, `VACUUM`, an import, a folder pin, a
|
||||
re-date, a profile backup, a size upgrade) runs as a one-shot job:
|
||||
`ServiceBoard::spawn_job` starts it on a named thread and lists it until it ends. `pdfs
|
||||
diagnostics` shows the jobs running and how long each has run. Async work of the same kind (the
|
||||
trash, timeline and album refreshes a listing starts) goes through `ServiceBoard::spawn_task_job`
|
||||
and is listed the same way. Jobs are not joined on stop.
|
||||
|
||||
---
|
||||
|
||||
## 10. Threat model: what this client writes to disk in plaintext
|
||||
@@ -733,14 +746,40 @@ The work goes in steps. Each ships the same behaviour with the simulation tests
|
||||
| 5 | `pdfs-vfs`: open files, then directories and renames, behind the FUSE adapter |
|
||||
| 6 | One admission policy for mirrors, reads and writeback |
|
||||
|
||||
Step 3 so far: the daemon's long-lived threads start and stop through one `Services` set (§9).
|
||||
Step 3 so far: the daemon's long-lived threads and async loops start and stop through one
|
||||
`Services` set (§9).
|
||||
`Core`'s fields are grouped by owner, each group a struct in the module that owns it:
|
||||
`photos::PhotoJobs`, `drain::DrainState`, `reads::ReadState`, `sizes::SizeState`,
|
||||
`trash::TrashState`, `shared::SharedState`, `sharing::QuotaCache` and `sweep::SweepState`.
|
||||
`trash::TrashState`, `shared::SharedState`, `quota::QuotaCache`, `pause::SyncPause` and
|
||||
`sweep::SweepState`.
|
||||
`Core`'s methods are split by area out of `lib.rs` into their own modules. The daemon's run loop
|
||||
moved out of `pdfs-cli` into `pdfs-daemon`, which is where the services will be built. What is left in `Core`
|
||||
is shared by several owners (the tree, the database, the queue's `pending` map) and needs ports
|
||||
before it can move.
|
||||
moved out of `pdfs-cli` into `pdfs-daemon`, which is where the services will be built.
|
||||
|
||||
State that several owners share sits behind a narrow interface of its own:
|
||||
|
||||
- `writes::WriteState` holds the write-back's queued writes, the nodes removed here and the echoes
|
||||
the event feed owes. The queue, the drain and recovery own it. The read path, listings, the pin
|
||||
keeper and the event feed ask it whether a node has a queued write, what size it gives the file,
|
||||
and which nodes to leave out. They do not take its locks.
|
||||
- `session::SessionCells` holds what belongs to one mount's FUSE session: whether it is the
|
||||
primary mount, its root inode, its kernel channel and whether it is up. An on-demand fork gets
|
||||
fresh cells from `SessionCells::fork`, and shares the rest of `Core`.
|
||||
- `link::Link` holds whether Drive answers, next to when the link went down. Code reads it through
|
||||
`Core::is_online`.
|
||||
|
||||
Some areas are services of their own rather than methods on `Core`. `sharing::Sharing` holds
|
||||
only the handles it calls (the client, Drive, the content cache, the transfer list and a read of
|
||||
the tree), and every one of its methods takes a node already resolved to its uid. Like the sync
|
||||
engine's `Syncer`, it can be built and tested without the rest of the daemon.
|
||||
|
||||
The control socket answers each area's requests in a module of its own under `control/`:
|
||||
sharing, Photos, synced folders and devices, revisions, and the trash and cache. Each module
|
||||
exports a pattern macro naming its requests, and the main match hands them over in one arm, so
|
||||
the compiler still checks that every request has an answer. A module turns a path or a uid into a
|
||||
node once, then asks the service.
|
||||
|
||||
What is left in `Core` is the tree, the database, the cache and the Drive client, which most
|
||||
owners use, plus single fields that belong to one module each.
|
||||
|
||||
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
|
||||
|
||||
@@ -4801,6 +4801,12 @@ which survives the landing, and queues the write against the real uid when the n
|
||||
**Test:** the unit tests `a_landed_placeholder_keeps_its_lid` and
|
||||
`an_inode_gives_back_the_lid_it_was_made_from`. Seed 1 of three-clients passes.
|
||||
|
||||
**Seen again:** 2026-11-26, once in a full local sim run, in
|
||||
`a_move_blocked_by_trash_can_be_retried_after_restore`. Its first write, of a new file in a new
|
||||
folder, logged "access changed before the write could be queued" for `local~14`, and the file
|
||||
read back empty. The next five runs of that test passed, and so did five on main. The race left
|
||||
is somewhere other than the lookup by local id that the fix added.
|
||||
|
||||
---
|
||||
|
||||
### B138 — A file created where another is leaving lands as a conflict copy
|
||||
|
||||
+7
-1
@@ -17,7 +17,9 @@ kept, with a list of the folders that changed on Proton Drive since (49).
|
||||
### Added
|
||||
- **`pdfs diagnostics` says which of the daemon's background services are running.** If one
|
||||
ends while the drive is mounted, for example the sync engine after a crash, the journal says
|
||||
so once, by name, instead of saying nothing until a restart.
|
||||
so once, by name, instead of saying nothing until a restart. It also lists the jobs running
|
||||
in the background, such as a cache check, an import, a folder being pinned or a refresh of
|
||||
the trash or the photo timeline, and how long each has run.
|
||||
- **`PDFS_INSTANCE` runs a second client next to your own.** With a name set, the client keeps
|
||||
its own directories, keyring entry, kernel keys and mountpoint, so a test account can run
|
||||
alongside the account you use. `scripts/live-bench.py` uses it to time one edit, from the
|
||||
@@ -57,6 +59,10 @@ 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 stop ends the loops that follow Proton Drive's change feed before the daemon exits.**
|
||||
The loops that read the Drive and photos event streams, and the gallery refresh, kept
|
||||
running after every other service had stopped, and could still write to the database while
|
||||
the process exited.
|
||||
- **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).
|
||||
|
||||
Reference in new issue
Block a user