Compare commits

...
Author SHA1 Message Date
nvrl 957a7ff391 Merge pull request #167 from narrrl/refactor/joined-workers
refactor(core,fuse): join jobs on stop and run the mount's loops as services
2026-11-27 01:34:57 +01:00
nvrl d9881810b7 Merge pull request #166 from narrrl/refactor/devices-service
refactor(fuse): make the device records and the profile backup services
2026-11-27 01:33:47 +01:00
nvrl d9dab26e86 docs(architecture): say what is left in Core after step 3 2026-11-26 22:25:14 +01:00
nvrl eae7ce90d2 refactor(fuse): give the hidden gallery its own handles
`gallery::Gallery` took a `&Core` on every call to reach the client, the
event hub and the database. It now holds those three, given when it is
built, and its background refresh no longer needs a `Core` either.
2026-11-26 22:24:40 +01:00
nvrl b674f3eb71 docs(architecture): describe the search and recovery services 2026-11-26 22:19:13 +01:00
nvrl 3a4812baae refactor(fuse): make queue recovery a service
Rebuilding the queue after a restart ran as methods on `Core`.
`recovery::Recovery` now holds the database, the content cache and the
write-back's state. It rebuilds the pending map, reconciles the staging
area and recovers fsynced writes. Queueing a recovered write goes through
`RecoveryHost`, which has one method.

Rebuilding the tree (`Core::hydrate`) stays on `Core`, because the tree is
part of the mounted-files service.
2026-11-26 22:18:46 +01:00
nvrl 3da45c0bf9 refactor(fuse): make search a service
Search ran as methods on `Core`. `search::Search` now holds the database,
the content cache, the on-demand mounts and the home indexer's busy flag,
which is all it reads. `Core::search_roots` stays as a shortcut, because the
conflict listing and the conflict sweep ask it too.
2026-11-26 22:15:24 +01:00
nvrl dc72991da2 docs(architecture): describe the mount's services and their ports 2026-11-26 22:12:45 +01:00
nvrl bdcabed1ee refactor(fuse): give the shutdown inhibitor only the database and the stop signal
The inhibitor took a whole `Core` to read the queue counts and wait on the
stop signal. It now takes those two handles.
2026-11-26 22:12:28 +01:00
nvrl 7def9e903b refactor(fuse): make the pin keeper a service
The pin keeper's loop ran as methods on `Core`. `keeper::PinKeeper` now
holds the content cache, the transfer list, the link, the stop signal and
its queue of work, which `Core::recheck_all_pins` and
`Core::recheck_pinned` still fill. It reaches the tree through
`KeeperHost`, which has five methods:
- find a node's inode, its parent's, and whether it is a folder;
- list every file under a kept folder;
- list a folder again if its listing was dropped;
- describe a file as a pin keeps it;
- download a pinned file.
2026-11-26 22:10:15 +01:00
nvrl bb376d7dc4 refactor(fuse): let the link own its state and make the probe a service
The online flag, the outage start and the condvar lived on `link::Link`, but
`Core` reached into them to flip the flag, log and wait. `Link` now does
that itself: `go_offline`, `go_online`, `wait_online` and the probe's idle
wait. `Core::mark_offline` and `Core::wait_online` delegate to it.

The online probe moves from `Core` to `link::OnlineProbe`, which holds the
link, Drive, the runtime and the stop signal. It reaches the rest of the
daemon through `LinkHost`, which has four methods:
- store the My Files root Drive answered with;
- after the reconnect, relist, retry backed-off ops, wake the drain and
  recheck the pins;
- report a refused session;
- repair the primary root's share id after an offline start.

The order is unchanged: the root is stored, the mount goes online, and then
what waited on the link runs.
2026-11-26 22:06:36 +01:00
nvrl 57e654924a refactor(fuse): make the conflict sweep a service
The conflict sweep ran as methods on `Core`. `sweep::Sweeper` now holds
Drive, the runtime, the database, the stop signal and its own state. It
reaches the mounts through `SweepHost`, which has six methods:
- whether a node is this account's own or virtual;
- whether the mount is online;
- whether a node is being written or held open in any mount;
- for one pass, whether the conflict listing can show a copy;
- unhook a trashed node from every mount and drop its cached content;
- add an activity entry.

`Core::is_busy` stays on `Core`, because resolving a conflict by hand asks
it too.
2026-11-26 22:02:44 +01:00
nvrl e3bc64df54 test(sim): let the short-outage test start from either side of the outage
`a_write_that_failed_on_a_short_outage_goes_out_soon_after_the_link_returns`
waited for the drain to record a failed attempt. When another caller, such
as the event poll or a sync pass, met the outage first and took the mount
offline, the drain claimed nothing, no attempt was ever recorded, and the
test failed after 30 seconds. It failed this way twice in a row in the CI of
#166.

The test now also accepts the mount having gone offline. The rest is
unchanged: the write still has to go out within 3 seconds of the mount
coming back.
2026-11-26 21:57:41 +01:00
nvrl 47576a389e refactor(fuse): make database maintenance a service
`VACUUM` and the deep integrity check were methods on `Core` behind a bare
`Arc<Mutex<Maintenance>>` field. `maintenance::Maintenance` now holds the
database, the transfer list, the board its jobs run on and its own state,
and the control socket calls it directly.
2026-11-26 21:56:04 +01:00
nvrl 7ed07e0056 refactor(core,fuse): start the mount's threads as services
Each long-lived thread the mount ran was a block in `mount.rs` with its own
spawn, wake and failure path, far from the loop it ran. A `Service` trait in
`pdfs_core::lifecycle` now carries the thread's name, whether the mount can
run without it, and the call that wakes it on a stop. The mount's loops are
types in `services.rs`, and `mount.rs` builds a list and starts it with
`Services::start`.

A required service that cannot start fails the mount attempt, as before. An
optional one (the sync engine, the event sampler, the supervisor and the
inhibitor) is logged and skipped, as before.
2026-11-26 21:52:03 +01:00
nvrl be99fffe1b refactor(core,fuse): join one-shot jobs on stop
A stop used to leave one-shot jobs running. A size upgrade still waiting on
Drive when the runtime went away panicked on its next timer ("A Tokio 1.x
context was found, but it is being shutdown"), seen in the simulation of
#166.

`Services::stop` now closes the board to new jobs, aborts the async ones,
and joins the thread jobs before the services, all up to the same deadline,
naming any still running then. A job asked for after the stop began is
refused. The size upgrade checks the stop signal between chunks.

The threads still started by hand go through the board: the parked size
waiters, the diagnostics probe and each control connection are jobs, so a
stop joins them. A subscription waits on its mailbox, so the control
listener's wake now rings every mailbox. The helper reader in `run_bounded`
is a scoped thread.
2026-11-26 21:44:54 +01:00
nvrl 96de4a8f46 refactor(fuse): make the profile backup a service
Saving this machine's profile, reading the profiles of other machines and
listing the folders a device offers for restore move from `Core` onto
`profile::ProfileBackup`. It holds Drive, the runtime, the database, the
service board and the `Devices` service, and needs nothing from the
filesystem, so it has no host port. `Core::profile` builds it on demand.

`restore_sync_folders` stays on `Core`: it creates synced folders and tells
the sync engine about them.
2026-11-26 20:57:37 +01:00
nvrl 97d9d671d2 refactor(fuse): make the device records a service with a host port
Listing, renaming, deleting, adopting and migrating devices, and
registering this computer as one, move from `Core` onto `devices::Devices`.
It holds the client, Drive, the runtime and the database. Migrating moves
another device's folders onto this one, and for that it reaches the rest of
the daemon through `DevicesHost`: move a folder on the server, run a sync
pass for a synced folder, and re-enumerate a folder. `Core::devices` builds
it on demand.

Synced folders, their modes and on-demand mounts stay on `Core`; they are
bound up with the mount registry and the sync engine.
2026-11-26 20:54:00 +01:00
nvrl 45e0b60994 refactor(fuse): make revisions a service that takes resolved nodes
Each revision operation was a method on `Core` in three copies: by path, by
uid, and the one that did the work. `revisions::Revisions` keeps only the
last, and takes the node's uid and the name the activity feed shows.
`control/revisions.rs` resolves the path or the uid once and, for a restore
by path, re-enumerates the parent folder afterwards, as before.

The service reaches the filesystem through `RevisionsHost`: check that the
node may be written, drop what describes the old content and fetch it again
if it is kept offline, and add an activity entry. Error messages and
activity entries are unchanged.
2026-11-26 20:49:41 +01:00
nvrl 96248e41e2 refactor(fuse): make the trash a service with a two-method host port
Listing, refreshing, restoring and deleting from the Drive trash move from
`Core` onto `trash::Trash`. It holds Drive, the runtime, the database, the
event hub, the service board, the write state (to unhide a restored node)
and its own refresh state. It reaches the mounts through `TrashHost`, which
re-enumerates the folders a restored node comes back into and forgets nodes
the server no longer has, in every mount. `Core::trash` builds it on demand.

`Core`'s field for the refresh state is renamed `trash_jobs` so the accessor
can be called `trash`. Marking the stored listing stale only clears a
database row, so `Core::invalidate_trash` stays and calls the same free
function as the service instead of building it.
2026-11-26 20:46:26 +01:00
nvrl ee2f28c5cd refactor(fuse): move the Google Photos import and the redate job into Photos
Both jobs only touched the Photos API, the runtime, the cache, the transfer
list and the shutdown signal, so they become methods on `photos::Photos` and
their modules move under `photos/`. The import's activity entry goes through
a third `PhotosHost` method, `log_activity`.
2026-11-26 20:40:16 +01:00
nvrl acc251c3d3 refactor(fuse): make Photos a service with a two-method host port
The timeline, albums and thumbnails were methods on `Core`. They are now
methods on `photos::Photos`, which holds only the handles it calls: the
client, Drive, the runtime, the content cache, the database, shutdown, the
service board, the event hub, the transfer list and the `PhotoJobs` state.
It reaches the filesystem through `PhotosHost`, which lists a folder for the
recursive thumbnail build and notes a change made here so its echo is not
taken for a remote edit. `Core::photos` builds one on demand with the daemon
as host, the same way `Core::syncer` builds the sync engine.

Albums move under `photos/`. Downloading a photo with a progress entry moves
from `Core` into the service. `listing_stale` becomes a free function over
the database so the service can use it. The Photos API handle is now named
`photos_api` on both `Core` and the service, which frees `photos` for the
service.

Trashing photos stays on `Core` in `photos/trash.rs`, because it checks
write authority against the tree, drops open readers and clears the trash
listing.
2026-11-26 20:35:59 +01:00
nvrl 89b3fce38d Merge pull request #163 from narrrl/refactor/write-state
refactor(fuse): put shared write-back, session and link state behind narrow interfaces
2026-11-26 20:15:54 +01:00
41 changed files with 2310 additions and 1186 deletions

No files matched your search

+237 -30
View File
@@ -21,7 +21,10 @@
//!
//! 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.
//! on the runtime): listed on the board while it runs. A stop closes the
//! board to new jobs, aborts the async ones and joins the rest up to the same
//! deadline as the services. A job used to be left running, and one still
//! waiting on Drive when the runtime went away panicked on its next timer.
use std::future::Future;
use std::sync::Arc;
@@ -36,6 +39,32 @@ use crate::shutdown::Shutdown;
/// Wakes a thread that blocks somewhere a [`Shutdown::stop`] alone does not reach.
pub type Wake = Box<dyn Fn() + Send + Sync>;
/// A long-lived loop a mount runs on a thread of its own.
///
/// Each one says in one place what it is called, how a stop reaches it and
/// whether the mount can do without it, next to the loop itself. The mount
/// starts a list of them with [`Services::start`] instead of spelling out
/// each spawn, wake and failure path.
pub trait Service: Send + 'static {
/// The thread's name, such as `pdfs-sync`.
fn name(&self) -> String;
/// Whether a mount fails when this cannot start. An optional service is
/// logged and skipped: the mount works without it, only less well.
fn required(&self) -> bool {
true
}
/// The call that wakes the loop on a stop, for one that blocks where the
/// [`Shutdown`] signal does not reach: a condvar, a channel, an `accept`.
fn wake(&self) -> Option<Wake> {
None
}
/// Run the loop until the [`Shutdown`] signal or the wake ends it.
fn run(self: Box<Self>);
}
/// Whether one service thread is still running, for diagnostics.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServiceHealth {
@@ -57,6 +86,28 @@ struct Board {
services: Mutex<Vec<Entry>>,
jobs: Mutex<Vec<Job>>,
next_job: AtomicU64,
/// The running jobs' handles, and whether a stop closed the board. One
/// lock for both, so a job is either refused or joined by the stop.
handles: Mutex<JobHandles>,
}
#[derive(Default)]
struct JobHandles {
closed: bool,
running: Vec<Handle>,
}
impl JobHandles {
/// Keep `handle`, dropping the handles of jobs that already ended.
fn keep(&mut self, handle: Handle) {
self.running.retain(|handle| !handle.is_finished());
self.running.push(handle);
}
}
/// Why a job did not start: the board's mount is stopping.
fn closed_error() -> std::io::Error {
std::io::Error::other("the mount is stopping; no new jobs start")
}
struct Entry {
@@ -106,37 +157,69 @@ impl ServiceBoard {
/// 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.
/// A stop joins it up to its deadline; a job that may run long checks the
/// [`Shutdown`] signal. Once a stop has begun, no job starts and this
/// returns an error.
pub fn spawn_job<F>(&self, name: &str, run: F) -> std::io::Result<()>
where
F: FnOnce() + Send + 'static,
{
let mut handles = self.0.handles.lock();
if handles.closed {
return Err(closed_error());
}
let guard = self.add_job(name);
std::thread::Builder::new()
let handle = 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(|_| ())
})?;
// On an error the closure, and the guard in it, are already dropped,
// so the job is off the list.
handles.keep(Handle::Thread(handle));
Ok(())
}
/// 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.
/// or abort. A stop aborts it at its next `.await`; once a stop has begun,
/// `task` is dropped without running.
pub fn spawn_task_job<F>(&self, rt: &tokio::runtime::Handle, name: &str, task: F)
where
F: Future<Output = ()> + Send + 'static,
{
let mut handles = self.0.handles.lock();
if handles.closed {
tracing::debug!(job = name, "not started: the mount is stopping");
return;
}
let guard = self.add_job(name);
rt.spawn(async move {
let task = rt.spawn(async move {
let _guard = guard;
task.await;
});
handles.keep(Handle::Task {
name: name.to_owned(),
task,
});
}
/// Close the board to new jobs and abort the async ones. The thread jobs
/// still running are handed back for [`join`](Handle::join_until).
fn close(&self) -> Vec<Handle> {
let running = {
let mut handles = self.0.handles.lock();
handles.closed = true;
std::mem::take(&mut handles.running)
};
for handle in &running {
if let Handle::Task { task, .. } = handle {
task.abort();
}
}
running
}
fn add_job(&self, name: &str) -> JobGuard {
@@ -184,7 +267,7 @@ impl Drop for Running {
}
}
struct Service {
struct Started {
handle: Handle,
wake: Option<Wake>,
}
@@ -205,12 +288,25 @@ impl Handle {
Handle::Task { task, .. } => task.is_finished(),
}
}
/// Wait for the thread or task to end, up to `deadline`, and name it if
/// it is still running then.
fn join_until(self, deadline: Instant) -> Option<String> {
while !self.is_finished() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
match self {
Handle::Thread(handle) => join_until([handle], deadline).pop(),
Handle::Task { name, task } if !task.is_finished() => Some(name),
Handle::Task { .. } => None,
}
}
}
/// The service threads one mount started, and how to stop them.
pub struct Services {
board: ServiceBoard,
started: Vec<Service>,
started: Vec<Started>,
}
impl Services {
@@ -239,7 +335,7 @@ impl Services {
});
match spawned {
Ok(handle) => {
self.started.push(Service {
self.started.push(Started {
handle: Handle::Thread(handle),
wake,
});
@@ -253,6 +349,21 @@ impl Services {
}
}
/// Start `service` on a thread of its own. A required service that cannot
/// start returns the error; an optional one is logged and skipped.
pub fn start(&mut self, service: Box<dyn Service>) -> std::io::Result<()> {
let name = service.name();
let required = service.required();
let wake = service.wake();
match self.spawn(&name, wake, move || service.run()) {
Err(error) if !required => {
tracing::warn!(service = name, %error, "optional service did not start");
Ok(())
}
started => 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
@@ -266,7 +377,7 @@ impl Services {
let _guard = guard;
task.await;
});
self.started.push(Service {
self.started.push(Started {
handle: Handle::Task {
name: name.to_owned(),
task,
@@ -285,12 +396,15 @@ impl Services {
self.started.is_empty()
}
/// 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.
/// Stop every service and every job: signal `shutdown`, close the board
/// to new jobs, wake each thread and abort each task in reverse start
/// order. Then join the jobs, which are the services' clients, and the
/// services in the same reverse order, all until `deadline`. Returns the
/// names of the services and jobs 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();
let jobs = self.board.close();
for service in self.started.iter().rev() {
if let Some(wake) = &service.wake {
wake();
@@ -299,18 +413,13 @@ impl Services {
task.abort();
}
}
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
let jobs = jobs.into_iter().filter_map(|job| job.join_until(deadline));
let services = self
.started
.into_iter()
.rev()
.filter_map(|service| service.handle.join_until(deadline));
jobs.chain(services).collect()
}
}
@@ -531,4 +640,102 @@ mod tests {
}
assert!(board.jobs().is_empty());
}
#[test]
fn a_stop_joins_the_running_jobs_and_names_a_stuck_one() {
let board = ServiceBoard::default();
let shutdown = Arc::new(Shutdown::default());
let services = Services::new(board.clone());
let signalled = shutdown.clone();
board
.spawn_job("pdfs-test-polite", move || {
while signalled.sleep(Duration::from_secs(3600)) {}
})
.unwrap();
let (_hold, stuck) = mpsc::channel::<()>();
board
.spawn_job("pdfs-test-stuck", move || {
let _ = stuck.recv();
})
.unwrap();
let left = services.stop(&shutdown, Instant::now() + Duration::from_millis(300));
assert_eq!(left, ["pdfs-test-stuck"]);
let jobs: Vec<_> = board.jobs().into_iter().map(|job| job.name).collect();
assert_eq!(jobs, ["pdfs-test-stuck"]);
}
#[test]
fn a_stop_aborts_a_task_job_and_refuses_new_jobs() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
let board = ServiceBoard::default();
let services = Services::new(board.clone());
board.spawn_task_job(rt.handle(), "pdfs-test-poller", async {
loop {
tokio::time::sleep(Duration::from_millis(5)).await;
}
});
let left = services.stop(
&Shutdown::default(),
Instant::now() + Duration::from_secs(5),
);
assert!(left.is_empty(), "still running: {left:?}");
assert!(board.jobs().is_empty());
assert!(board.spawn_job("pdfs-test-late", || {}).is_err());
board.spawn_task_job(rt.handle(), "pdfs-test-late", async {});
assert!(board.jobs().is_empty(), "a job started after the stop");
}
struct Waiter {
name: &'static str,
rx: mpsc::Receiver<()>,
tx: mpsc::Sender<()>,
}
impl Service for Waiter {
fn name(&self) -> String {
self.name.to_owned()
}
fn wake(&self) -> Option<Wake> {
let tx = self.tx.clone();
Some(Box::new(move || {
let _ = tx.send(());
}))
}
fn run(self: Box<Self>) {
let _ = self.rx.recv();
}
}
#[test]
fn a_started_service_is_woken_and_joined_by_a_stop() {
let board = ServiceBoard::default();
let mut services = Services::new(board.clone());
let (tx, rx) = mpsc::channel();
services
.start(Box::new(Waiter {
name: "pdfs-test-waiter",
rx,
tx,
}))
.unwrap();
assert_eq!(board.health()[0].name, "pdfs-test-waiter");
let left = services.stop(
&Shutdown::default(),
Instant::now() + Duration::from_secs(5),
);
assert!(left.is_empty(), "still running: {left:?}");
assert!(!board.health()[0].running);
}
}
+2 -2
View File
@@ -568,7 +568,7 @@ pub(super) async fn run_event_sync(
/// Follow the Photos volume and commit changes with its durable event cursor.
pub(super) async fn run_photos_event_sync(core: Core) {
let photos = core.photos();
let photos = core.photos_api();
// The photos volume only exists once the user has used Photos at all, and
// the daemon may well start before the network does.
let scope = loop {
@@ -635,7 +635,7 @@ pub(super) async fn run_photos_event_sync(core: Core) {
}
}
if core.db.photos_need_work().unwrap_or(true) {
core.spawn_timeline_refresh();
core.photos().spawn_timeline_refresh();
}
core.next_poll(POLL_INTERVAL).await;
}
+27 -19
View File
@@ -68,7 +68,7 @@ fn clamp_limit(limit: usize) -> usize {
fn album_change(
uid: &str,
photos: &[String],
change: impl FnOnce(&NodeUid, &[NodeUid]) -> CoreResult<super::albums::AlbumOutcome>,
change: impl FnOnce(&NodeUid, &[NodeUid]) -> CoreResult<super::photos::AlbumOutcome>,
) -> CtlResponse {
let Some(album) = parse_uid(uid) else {
return CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}")));
@@ -638,7 +638,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
Ok(CtlRequest::Pin { path }) => match route_keep(core, mountpoint, &path) {
Ok((routed, rel)) => match routed.pin(&rel, &pin_record(&routed, &rel, &path)) {
Ok(name) => {
core.touch_profile();
core.profile().touch_profile();
CtlResponse::Ok {
message: format!("pinned {name}"),
}
@@ -650,7 +650,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
Ok(CtlRequest::Unpin { path }) => match route_keep(core, mountpoint, &path) {
Ok((routed, rel)) => match routed.unpin(&rel) {
Ok(name) => {
core.touch_profile();
core.profile().touch_profile();
CtlResponse::Ok {
message: format!("unpinned {name}"),
}
@@ -689,7 +689,9 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
core.invalidate_trash();
Ok(())
}
RefreshScope::Photos { full } if !full && core.timeline_refreshing() => {
RefreshScope::Photos { full }
if !full && core.photos().timeline_refreshing() =>
{
// A refresh is already running and will publish exactly the
// timeline this request asks for. Doing the work again
// cannot make it newer, and the invalidation plus the
@@ -709,7 +711,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
}
// Whatever changed the timeline can just as easily have
// changed an album; one scope covers the whole photos view.
core.invalidate_albums();
core.photos().invalidate_albums();
// The refresh is started here, not awaited. A library of
// twelve thousand photos is re-read in chunks of
// `TIMELINE_ENRICH_CHUNK` nodes, which takes minutes —
@@ -717,7 +719,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
// returned `Resource temporarily unavailable` to a caller
// whose refresh was in fact running fine (B92). The front
// end follows it with `PhotosRefreshStatus`.
core.spawn_timeline_refresh();
core.photos().spawn_timeline_refresh();
Ok(())
}
};
@@ -769,15 +771,18 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
query,
limit,
scope,
}) => match core.search(&query, clamp_limit(limit), scope.as_deref()) {
}) => match core
.searcher()
.search(&query, clamp_limit(limit), scope.as_deref())
{
Ok(hits) => CtlResponse::SearchResults { hits },
Err(e) => CtlResponse::error(e),
},
Ok(CtlRequest::SearchLocal { query, limit }) => {
match core.search_local(&query, clamp_limit(limit)) {
match core.searcher().search_local(&query, clamp_limit(limit)) {
Ok(hits) => CtlResponse::LocalResults {
hits,
indexing: core.indexing.load(Ordering::Relaxed),
indexing: core.searcher().indexing(),
},
Err(e) => CtlResponse::error(e),
}
@@ -786,11 +791,14 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
query,
limit,
filters,
}) => match core.search_v2(&query, clamp_limit(limit), &filters) {
}) => match core
.searcher()
.search_v2(&query, clamp_limit(limit), &filters)
{
Ok((drive_hits, local_hits)) => CtlResponse::SearchResultsV2 {
drive_hits,
local_hits,
local_indexing: core.indexing.load(Ordering::Relaxed),
local_indexing: core.searcher().indexing(),
},
Err(e) => CtlResponse::error(e),
},
@@ -1102,13 +1110,13 @@ pub(crate) fn run_control_socket(
let core = core.clone();
let username = username.clone();
let mountpoint = mountpoint.clone();
if let Err(e) = std::thread::Builder::new()
.name("pdfs-control".into())
.spawn(move || {
let _permit = permit;
handle_control_conn(&core, &username, &mountpoint, stream);
})
{
// A job, so a stop joins it; a subscription ends on the
// stop's wake (`EventHub::wake_all`).
let board = core.services.clone();
if let Err(e) = board.spawn_job("pdfs-control-conn", move || {
let _permit = permit;
handle_control_conn(&core, &username, &mountpoint, stream);
}) {
warn!(error = %e, "control: spawn handler failed");
}
}
@@ -1133,7 +1141,7 @@ fn start_takeout_import(core: &Core, paths: Vec<PathBuf>, dry_run: bool) -> CtlR
)));
}
let count = paths.len();
match core.spawn_takeout_import(paths, dry_run) {
match core.photos().spawn_takeout_import(paths, dry_run) {
Ok(()) => CtlResponse::Ok {
message: format!(
"{} {count} archive(s)",
+49 -38
View File
@@ -69,7 +69,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
range,
favorites,
not_in_album,
} => match core.photos_timeline(
} => match core.photos().photos_timeline(
offset,
clamp_limit(limit),
kind,
@@ -90,11 +90,11 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::PhotoDuplicates => match core.photo_duplicates() {
CtlRequest::PhotoDuplicates => match core.photos().photo_duplicates() {
Ok(sets) => CtlResponse::PhotoDuplicates { sets },
Err(e) => CtlResponse::error(e),
},
CtlRequest::PhotoSimilar => match core.photo_similar() {
CtlRequest::PhotoSimilar => match core.photos().photo_similar() {
Ok((sets, hashing, uncompared)) => CtlResponse::PhotoSimilar {
sets,
hashing,
@@ -102,15 +102,18 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::PhotoPlaces => match core.photo_places(excluded) {
CtlRequest::PhotoPlaces => match core.photos().photo_places(excluded) {
Ok(items) => CtlResponse::Places {
items,
mapping: core.timeline_progress(),
mapping: core.photos().timeline_progress(),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::PlacePhotos { id, offset, limit } => {
match core.place_photos(id, offset, clamp_limit(limit), excluded) {
match core
.photos()
.place_photos(id, offset, clamp_limit(limit), excluded)
{
Ok(items) => CtlResponse::Photos {
available: true,
items,
@@ -119,12 +122,15 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::PlaceLocations { id } => match core.place_locations(id) {
CtlRequest::PlaceLocations { id } => match core.photos().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) {
match core
.photos()
.photos_on_this_day(clamp_limit(limit), excluded)
{
Ok(items) => CtlResponse::Photos {
available: true,
items,
@@ -133,7 +139,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::PhotoGroup { uid } => match core.photo_group(&uid) {
CtlRequest::PhotoGroup { uid } => match core.photos().photo_group(&uid) {
Ok(items) => CtlResponse::Photos {
available: true,
items,
@@ -142,7 +148,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
Err(e) => CtlResponse::error(e),
},
CtlRequest::SetPhotoFavorite { uid, favorite } => match parse_uid(&uid) {
Some(node_uid) => match core.set_photo_favorite(&node_uid, favorite) {
Some(node_uid) => match core.photos().set_photo_favorite(&node_uid, favorite) {
Ok(()) => CtlResponse::Ok {
message: if favorite {
"added to favorites".to_string()
@@ -154,7 +160,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
},
None => CtlResponse::error(CoreError::invalid(format!("invalid uid: {uid}"))),
},
CtlRequest::PhotoAlbums => match core.albums() {
CtlRequest::PhotoAlbums => match core.photos().albums() {
Ok(Some(items)) => CtlResponse::Albums {
available: true,
items,
@@ -169,10 +175,10 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
// 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))
{
Some(album) => match visibility.permits(&uid).and_then(|()| {
core.photos()
.album_photos(&album, offset, clamp_limit(limit), excluded)
}) {
Ok(items) => CtlResponse::Photos {
available: true,
items,
@@ -182,12 +188,12 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
},
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
},
CtlRequest::CreateAlbum { name } => match core.create_album(&name) {
CtlRequest::CreateAlbum { name } => match core.photos().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) {
Some(album) => match core.photos().rename_album(&album, &name) {
Ok(()) => CtlResponse::Ok {
message: format!("renamed album to {name}"),
},
@@ -196,7 +202,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
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) {
Some(album) => match core.photos().delete_album(&album, delete_photos) {
Ok(()) => CtlResponse::Ok {
message: "album deleted".to_string(),
},
@@ -205,11 +211,11 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
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)
core.photos().add_to_album(album, photos)
}),
CtlRequest::RemoveFromAlbum { uid, photos } => {
album_change(&uid, &photos, |album, photos| {
core.remove_from_album(album, photos)
core.photos().remove_from_album(album, photos)
})
}
CtlRequest::PhotoPresence { uid, album } => match core.cached_gallery_visibility() {
@@ -235,42 +241,45 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
.filter_map(|u| parse_uid(u))
.collect();
CtlResponse::Thumbs {
items: core.photo_thumbs(&parsed),
items: core.photos().photo_thumbs(&parsed),
}
}
CtlRequest::FileThumbs { items, generation } => {
match core.file_thumbs(&items, generation) {
match core.photos().file_thumbs(&items, generation) {
Some(items) => CtlResponse::Thumbs { items },
None => CtlResponse::FileThumbsStale,
}
}
CtlRequest::ReserveFileThumbGeneration => CtlResponse::FileThumbGeneration {
generation: core.reserve_file_thumb_generation(),
generation: core.photos().reserve_file_thumb_generation(),
},
CtlRequest::CancelFileThumbs { generation } => {
core.cancel_file_thumbs(generation);
core.photos().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(rel) => match core.photos().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(),
status: core.photos().cancel_thumbnail_build(),
},
CtlRequest::ThumbnailBuildStatus => CtlResponse::ThumbnailBuild {
status: core.thumbnail_build_status(),
status: core.photos().thumbnail_build_status(),
},
CtlRequest::PhotosRefreshStatus => CtlResponse::PhotosRefresh {
running: core.timeline_refreshing(),
running: core.photos().timeline_refreshing(),
},
CtlRequest::OpenPhoto { uid } => match parse_uid(&uid) {
Some(u) => match visibility.permits(&uid).and_then(|()| core.open_photo(&u)) {
Some(u) => match visibility
.permits(&uid)
.and_then(|()| core.photos().open_photo(&u))
{
Ok(p) => CtlResponse::FilePath {
path: p.display().to_string(),
},
@@ -319,7 +328,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
}
}
CtlRequest::ImportStatus => {
let report = crate::takeout::import_status();
let report = crate::photos::takeout::import_status();
CtlResponse::ImportStatus {
running: report.running,
summary: report.summary,
@@ -327,12 +336,12 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
resumable: report.resumable,
}
}
CtlRequest::ResumeImport => match crate::takeout::resumable_archives() {
CtlRequest::ResumeImport => match crate::photos::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() {
if crate::photos::takeout::cancel_import() {
CtlResponse::Ok {
message: "stopping the import".to_string(),
}
@@ -344,7 +353,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
dry_run,
limit,
range,
} => match core.spawn_redate(dry_run, limit, range) {
} => match core.photos().spawn_redate(dry_run, limit, range) {
Ok(()) => CtlResponse::Ok {
message: if dry_run {
"checking photo dates".to_string()
@@ -355,11 +364,11 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
Err(e) => CtlResponse::error(e),
},
CtlRequest::RedateStatus => {
let (running, summary) = crate::redate::redate_status();
let (running, summary) = crate::photos::redate::redate_status();
CtlResponse::RedateStatus { running, summary }
}
CtlRequest::CancelRedate => {
if crate::redate::cancel_redate() {
if crate::photos::redate::cancel_redate() {
CtlResponse::Ok {
message: "stopping the re-date".to_string(),
}
@@ -383,7 +392,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
"cannot read {source_path}: {e}"
))),
Ok((file, len)) => {
let photos = core.photos();
let photos = core.photos_api();
// 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(|| {
@@ -401,7 +410,9 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
.and_then(pdfs_core::timestamp::modification_time),
..Default::default()
};
let thumbnails = core.upload_thumbnails(Path::new(&source_path), &name);
let thumbnails = core
.photos()
.upload_thumbnails(Path::new(&source_path), &name);
let guard =
core.transfers
.begin(name.clone(), "", TransferDirection::Upload, len);
@@ -421,7 +432,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
// 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() {
if let Err(e) = core.photos().refresh_timeline_joined() {
warn!(error = %e, "timeline refresh after upload failed");
}
CtlResponse::Ok {
+76 -55
View File
@@ -19,83 +19,104 @@ macro_rules! request {
}
pub(super) use request;
/// The file a request is about, and how the activity feed names it: the file
/// name under the mount, or the uid.
struct Target {
uid: NodeUid,
name: String,
}
impl Target {
fn path(core: &Core, rel: &Path) -> CoreResult<Self> {
let (_ino, uid) = core.resolve(rel)?;
let name = rel
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| uid.to_string());
Ok(Self { uid, name })
}
fn uid(core: &Core, uid: &str) -> CoreResult<Self> {
let uid = core.resolve_anywhere(uid)?;
let name = uid.to_string();
Ok(Self { uid, name })
}
}
/// Answer a request that [`request!`] matches.
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
let Ask {
core, mountpoint, ..
} = *ask;
let revisions = core.revisions();
let at = |path: &str| rel_to_mount(mountpoint, path);
let reply = |result: CoreResult<String>| match result {
Ok(message) => CtlResponse::Ok { message },
Err(e) => CtlResponse::error(e),
};
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),
},
CtlRequest::ListRevisions { path } => {
match at(&path).and_then(|rel| Target::path(core, &rel)) {
Ok(file) => listed(revisions.list(&file.uid)),
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::ListRevisionsByUid { uid } => match Target::uid(core, &uid) {
Ok(file) => listed(revisions.list(&file.uid)),
Err(e) => CtlResponse::error(e),
},
CtlRequest::RestoreRevision { path, revision_id } => reply(at(&path).and_then(|rel| {
let file = Target::path(core, &rel)?;
revisions.restore(&file.uid, &revision_id, &file.name)?;
// The size and mtime a listing shows describe the revision that
// was active a moment ago.
core.invalidate_parent_listing(&rel);
Ok(format!("restoring version {revision_id} of {path}"))
})),
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),
}
reply(Target::uid(core, &uid).and_then(|file| {
revisions.restore(&file.uid, &revision_id, &file.name)?;
Ok(format!("restoring version {revision_id}"))
}))
}
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::DeleteRevision { path, revision_id } => reply(at(&path).and_then(|rel| {
let file = Target::path(core, &rel)?;
revisions.delete(&file.uid, &revision_id, &file.name)?;
Ok(format!("deleted version {revision_id} of {path}"))
})),
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),
}
reply(Target::uid(core, &uid).and_then(|file| {
revisions.delete(&file.uid, &revision_id, &file.name)?;
Ok(format!("deleted version {revision_id}"))
}))
}
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),
},
} => reply(at(&path).and_then(|rel| {
let file = Target::path(core, &rel)?;
let written =
revisions.save_as(&file.uid, &revision_id, &file.name, Path::new(&dest))?;
Ok(format!("wrote {} to {dest}", human_bytes(written)))
})),
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),
},
} => reply(Target::uid(core, &uid).and_then(|file| {
let written =
revisions.save_as(&file.uid, &revision_id, &file.name, Path::new(&dest))?;
Ok(format!("wrote {} to {dest}", human_bytes(written)))
})),
// `control` only hands over what `request!` matches.
_ => CtlResponse::error(CoreError::internal("not a revisions request".to_string())),
}
}
fn listed(result: CoreResult<Vec<pdfs_core::control::RevisionInfo>>) -> CtlResponse {
match result {
Ok(items) => CtlResponse::Revisions { items },
Err(e) => CtlResponse::error(e),
}
}
+11 -11
View File
@@ -42,7 +42,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
core, mountpoint, ..
} = *ask;
match request {
CtlRequest::ListDevices => match core.list_devices() {
CtlRequest::ListDevices => match core.devices().list_devices() {
Ok(items) => CtlResponse::Devices { items },
Err(e) => CtlResponse::error(e),
},
@@ -50,23 +50,23 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
Ok(items) => CtlResponse::Locations { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::RenameDevice { uid, name } => match core.rename_device(&uid, &name) {
CtlRequest::RenameDevice { uid, name } => match core.devices().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) {
CtlRequest::DeleteDevice { uid } => match core.devices().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()) {
CtlRequest::AdoptDevice { uid } => match core.devices().adopt_device(uid.as_deref()) {
Ok(message) => CtlResponse::Ok { message },
Err(e) => CtlResponse::error(e),
},
CtlRequest::MigrateDevice { uid } => match core.migrate_device(&uid) {
CtlRequest::MigrateDevice { uid } => match core.devices().migrate_device(&uid) {
Ok(message) => CtlResponse::Ok { message },
Err(e) => CtlResponse::error(e),
},
@@ -84,7 +84,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
let started = Instant::now();
match core.add_sync_folder(&path) {
Ok(folder) => {
core.touch_profile();
core.profile().touch_profile();
let name = Path::new(&folder.local_path)
.file_name()
.and_then(|n| n.to_str())
@@ -131,7 +131,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
CtlRequest::RemoveSyncFolder { id, delete_remote } => {
match core.remove_sync_folder(id, delete_remote) {
Ok(()) => {
core.touch_profile();
core.profile().touch_profile();
CtlResponse::Ok {
message: "removed synced folder".to_string(),
}
@@ -142,7 +142,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
CtlRequest::SetSyncFolderMode { id, mode } => {
match core.request_sync_folder_mode(id, &mode) {
Ok(message) => {
core.touch_profile();
core.profile().touch_profile();
core.log_activity(ActivityKind::Upload, &message, "", true);
CtlResponse::Ok { message }
}
@@ -225,12 +225,12 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListRestorableFolders => match core.list_restorable_folders(None) {
CtlRequest::ListRestorableFolders => match core.profile().list_restorable_folders(None) {
Ok(items) => CtlResponse::RestorableFolders { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListDeviceRestorableFolders { device } => {
match core.list_restorable_folders(Some(&device)) {
match core.profile().list_restorable_folders(Some(&device)) {
Ok(items) => CtlResponse::RestorableFolders { items },
Err(e) => CtlResponse::error(e),
}
@@ -251,7 +251,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
.spawn_job("pdfs-restore-sync-folders", move || {
match core.restore_sync_folders(&items, device.as_deref()) {
Ok(outcome) => {
core.touch_profile();
core.profile().touch_profile();
if !outcome.complete() {
warn!(skipped = ?outcome.skipped, "restore skipped folders");
}
+8 -8
View File
@@ -24,15 +24,15 @@ pub(super) use request;
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
let Ask { core, .. } = *ask;
match request {
CtlRequest::ListTrash => match core.list_trash() {
CtlRequest::ListTrash => match core.trash().list_trash() {
Ok(entries) => CtlResponse::Entries { entries },
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListTrashedFolder { uid } => match core.list_trashed_folder(&uid) {
CtlRequest::ListTrashedFolder { uid } => match core.trash().list_trashed_folder(&uid) {
Ok(entries) => CtlResponse::Entries { entries },
Err(e) => CtlResponse::error(e),
},
CtlRequest::Restore { uids } => match core.restore(&uids) {
CtlRequest::Restore { uids } => match core.trash().restore(&uids) {
Ok(n) => {
core.log_activity(ActivityKind::Restore, format!("{n} item(s)"), "", true);
CtlResponse::Ok {
@@ -41,7 +41,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
}
Err(e) => CtlResponse::error(e),
},
CtlRequest::DeleteForever { uids } => match core.delete_forever(&uids) {
CtlRequest::DeleteForever { uids } => match core.trash().delete_forever(&uids) {
Ok(n) => {
core.log_activity(
ActivityKind::DeleteForever,
@@ -55,7 +55,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
}
Err(e) => CtlResponse::error(e),
},
CtlRequest::EmptyTrash => match core.empty_trash() {
CtlRequest::EmptyTrash => match core.trash().empty_trash() {
Ok(n) => {
let items = if n == 1 {
"1 item".to_string()
@@ -88,7 +88,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
// 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()
core.maintenance.start_or_read_integrity_check()
} else {
(Vec::new(), false, false)
};
@@ -106,7 +106,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
}
Err(e) => CtlResponse::error(CoreError::internal(format!("read db stats: {e:?}"))),
},
CtlRequest::CacheVacuum => match core.start_vacuum() {
CtlRequest::CacheVacuum => match core.maintenance.start_vacuum() {
Ok(()) => CtlResponse::Ok {
message: "compacting the cache database in the background".into(),
},
@@ -120,7 +120,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
.map(|dirs| dirs.update_config(|cfg| cfg.cache_budget = Some(bytes)))
{
Ok(Ok(())) => {
core.touch_profile();
core.profile().touch_profile();
CtlResponse::Ok {
message: format!("cache budget set to {bytes} bytes"),
}
+97 -28
View File
@@ -20,6 +20,7 @@ use pdfs_core::mounts::MountMode;
use pdfs_core::profile::PROFILE_DIR_NAME;
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::{StoredDevice, StoredSyncFolder};
use proton_drive_rs::proton_sdk::error::ProtonError;
use proton_drive_rs::proton_sdk::ids::{DeviceUid, NodeUid};
use proton_drive_rs::{DeviceType, Node};
use tracing::{info, warn};
@@ -146,28 +147,70 @@ fn migrated_name(name: &str, device: &str, taken: &[String]) -> Option<String> {
.find(|candidate| free(candidate))
}
impl Core {
// ---- devices ----------------------------------------------------------
/// This account's devices on Drive, and which one is this computer: listing,
/// renaming, deleting, adopting and migrating them, and registering this one.
///
/// It reaches the rest of the daemon through [`DevicesHost`]. [`Core::devices`]
/// builds one on demand with the daemon as its host.
#[derive(Clone)]
pub(crate) struct Devices {
client: proton_drive_rs::ProtonDriveClient,
drive: std::sync::Arc<dyn crate::drive::DriveApi>,
rt: tokio::runtime::Handle,
db: std::sync::Arc<pdfs_store::db::Db>,
host: std::sync::Arc<dyn DevicesHost>,
}
/// Unified local-location listing for the control protocol.
pub(crate) fn list_locations(&self) -> CoreResult<Vec<MountSpec>> {
let progress = self.sync.progress.lock();
let mut locations = self
.db
.mount_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
for location in &mut locations {
location.mounted = self.states.is_mounted_at(Path::new(&location.local_path));
if let MountKind::Device { sync_folder_id } | MountKind::Attached { sync_folder_id } =
&location.kind
{
location.progress = progress.get(sync_folder_id).cloned();
location.paused = self.sync_folder_paused(*sync_folder_id);
}
}
Ok(locations)
/// What [`Devices`] needs from the rest of the daemon, to migrate a device's
/// folders onto this one.
pub(crate) trait DevicesHost: Send + Sync {
/// Move a node under `parent` on the server, renaming it to `name` if
/// given, and update the tree to match.
fn move_node(
&self,
uid: &NodeUid,
parent: &NodeUid,
name: Option<&str>,
) -> Result<(), ProtonError>;
/// Run a sync pass for one synced folder now.
fn sync_now(&self, id: Option<i64>);
/// Re-enumerate a folder's children on next access.
fn invalidate_children_of(&self, parent: &NodeUid);
}
impl DevicesHost for Core {
fn move_node(
&self,
uid: &NodeUid,
parent: &NodeUid,
name: Option<&str>,
) -> Result<(), ProtonError> {
self.move_rename_remote(uid, parent, name)
}
fn sync_now(&self, id: Option<i64>) {
Core::sync_now(self, id);
}
fn invalidate_children_of(&self, parent: &NodeUid) {
Core::invalidate_children_of(self, parent);
}
}
impl Core {
/// The devices service, with this daemon as its host.
pub(crate) fn devices(&self) -> Devices {
Devices {
client: self.client.clone(),
drive: self.drive.clone(),
rt: self.rt.clone(),
db: self.db.clone(),
host: std::sync::Arc::new(self.clone()),
}
}
}
impl Devices {
/// List the account's registered devices, flagging the one *this* machine
/// syncs to so a front-end can treat it as more than another computer in the
/// list — deleting it takes this machine's synced folders down with it.
@@ -354,7 +397,10 @@ impl Core {
continue;
}
let new_name = migrated_name(&node.name, &source.name, &taken);
if let Err(e) = self.move_rename_remote(&node.uid, &target_root, new_name.as_deref()) {
if let Err(e) = self
.host
.move_node(&node.uid, &target_root, new_name.as_deref())
{
warn!(name = %node.name, error = %e, "migrate: could not move folder");
failed.push(format!("{}: {e}", node.name));
continue;
@@ -371,11 +417,11 @@ impl Core {
if let Err(e) = self.db.sync_folder_set_share(folder.id, &target.share_id) {
warn!(id = folder.id, error = ?e, "migrate: could not re-point sync folder");
}
self.sync_now(Some(folder.id));
self.host.sync_now(Some(folder.id));
}
}
self.invalidate_children_of(&source_root);
self.invalidate_children_of(&target_root);
self.host.invalidate_children_of(&source_root);
self.host.invalidate_children_of(&target_root);
let mut message = format!("moved {moved} folder(s) from {}", source.name);
if !renamed.is_empty() {
@@ -395,8 +441,6 @@ impl Core {
Ok(message)
}
// ---- device folder sync -------------------------
/// Auto-register (or recover) this machine as a Proton Drive Device, caching
/// it so restarts reuse the same device. Recovery matches an existing remote
/// Linux device by name before creating a new one, so a lost local record
@@ -503,7 +547,7 @@ impl Core {
}
/// Everything directly under a device root, trashed nodes included.
pub(super) fn device_root_nodes(&self, root_uid: &NodeUid) -> CoreResult<Vec<Node>> {
pub(crate) fn device_root_nodes(&self, root_uid: &NodeUid) -> CoreResult<Vec<Node>> {
let uids = self
.rt
.block_on(self.drive.enumerate_folder_children_node_uids(root_uid))
@@ -515,6 +559,31 @@ impl Core {
.block_on(self.drive.enumerate_nodes(&uids))
.map_err(|e| CoreError::from_api(&e, "resolve device root children"))
}
}
impl Core {
// ---- devices ----------------------------------------------------------
/// Unified local-location listing for the control protocol.
pub(crate) fn list_locations(&self) -> CoreResult<Vec<MountSpec>> {
let progress = self.sync.progress.lock();
let mut locations = self
.db
.mount_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
for location in &mut locations {
location.mounted = self.states.is_mounted_at(Path::new(&location.local_path));
if let MountKind::Device { sync_folder_id } | MountKind::Attached { sync_folder_id } =
&location.kind
{
location.progress = progress.get(sync_folder_id).cloned();
location.paused = self.sync_folder_paused(*sync_folder_id);
}
}
Ok(locations)
}
// ---- device folder sync -------------------------
/// Add a local folder to this device's sync set: register the device if
/// needed, create a matching folder under the device root, upload the local
@@ -568,7 +637,7 @@ impl Core {
)));
}
let device = self.ensure_device()?;
let device = self.devices().ensure_device()?;
let root_uid = parse_uid(&device.root_uid).ok_or_else(|| {
CoreError::internal(format!("bad device root uid: {}", device.root_uid))
})?;
@@ -580,7 +649,7 @@ impl Core {
// original, not leave the user with two "Downloads" in their Drive. The
// reconcile treats an existing remote tree correctly: unmatched paths read as
// a conflict, not as data loss.
let remote_root = match self.find_device_child_folder(&root_uid, &name)? {
let remote_root = match self.devices().find_device_child_folder(&root_uid, &name)? {
Some(uid) => {
info!(name, "reusing existing device folder");
uid
+21 -14
View File
@@ -20,6 +20,8 @@ use std::time::{Duration, Instant};
use parking_lot::Mutex;
use pdfs_core::control::{Diagnostics, DriveCallStat, InflightRequest, ServiceState, WorkerState};
use pdfs_core::lifecycle::ServiceBoard;
use super::Core;
/// When this process started. Read at the first touch, which
@@ -207,10 +209,15 @@ impl Core {
/// is not started until the first one has returned.
fn pending_ops_quickly(&self) -> Option<u64> {
let db = self.db.clone();
probe_once(&self.pending_probe, PENDING_COUNT_DEADLINE, move || {
let counts = db.pending_op_counts().ok()?;
Some(counts.uploads.max(0) as u64 + counts.changes.max(0) as u64)
})
probe_once(
&self.services,
&self.pending_probe,
PENDING_COUNT_DEADLINE,
move || {
let counts = db.pending_op_counts().ok()?;
Some(counts.uploads.max(0) as u64 + counts.changes.max(0) as u64)
},
)
}
}
@@ -219,6 +226,7 @@ impl Core {
/// `None` when it did not answer in time, or when the previous probe sharing
/// `busy` has not returned yet: then no new thread is started at all.
fn probe_once<T: Send + 'static>(
board: &ServiceBoard,
busy: &Arc<AtomicBool>,
deadline: Duration,
probe: impl FnOnce() -> Option<T> + Send + 'static,
@@ -228,13 +236,11 @@ fn probe_once<T: Send + 'static>(
}
let done = Arc::clone(busy);
let (tx, rx) = std::sync::mpsc::channel();
let spawned = std::thread::Builder::new()
.name("pdfs-diagnostics".into())
.spawn(move || {
let answer = probe();
done.store(false, Ordering::Release);
let _ = tx.send(answer);
});
let spawned = board.spawn_job("pdfs-diagnostics", move || {
let answer = probe();
done.store(false, Ordering::Release);
let _ = tx.send(answer);
});
if spawned.is_err() {
busy.store(false, Ordering::Release);
return None;
@@ -310,11 +316,12 @@ mod tests {
#[test]
fn a_stuck_probe_is_not_started_again() {
let board = ServiceBoard::default();
let busy = Arc::new(AtomicBool::new(false));
let (release, wait) = std::sync::mpsc::channel::<()>();
let short = Duration::from_millis(50);
let stuck = probe_once(&busy, short, move || {
let stuck = probe_once(&board, &busy, short, move || {
let _ = wait.recv();
Some(1)
});
@@ -322,7 +329,7 @@ mod tests {
let started = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&started);
let second = probe_once(&busy, short, move || {
let second = probe_once(&board, &busy, short, move || {
flag.store(true, Ordering::SeqCst);
Some(2)
});
@@ -339,7 +346,7 @@ mod tests {
std::thread::yield_now();
}
assert_eq!(
probe_once(&busy, Duration::from_secs(10), || Some(3)),
probe_once(&board, &busy, Duration::from_secs(10), || Some(3)),
Some(3)
);
}
+2 -2
View File
@@ -41,8 +41,8 @@ use proton_drive_rs::{Node, NodeKind};
use tracing::{debug, error, info, warn};
use super::link::{self, is_network_error};
use super::photos::sha1_of;
use super::state::{Intervals, PendingRevision};
use super::takeout::sha1_of;
use super::transfers::CountingReader;
use super::{
Core, DRAIN_BACKOFF_MAX, DRAIN_BACKOFF_MIN, DRAIN_IDLE_POLL, DRAIN_REVISION_DEBOUNCE,
@@ -420,7 +420,7 @@ impl Core {
// touches get written (`ContentCache::flush_touches`).
// Cheap and a no-op when empty.
self.cache.flush_touches();
self.recover_fsynced_writes();
self.recovery().recover_fsynced_writes();
// Parked rows are invisible to `claim_next_due_op`, so
// an idle queue is exactly when a park that has outlived
// its writer has to be noticed.
+1 -1
View File
@@ -475,7 +475,7 @@ impl Core {
// a newer blob by the time it is retried (`Core::adoptable_twin`).
let sha = staged_sha1(Path::new(blob))?;
self.db.note_create_sent(op.id, &sha)?;
let thumbnails = self.upload_thumbnails(Path::new(blob), name);
let thumbnails = self.photos().upload_thumbnails(Path::new(blob), name);
let guard = self
.transfers
.begin(name, op.uid.clone(), TransferDirection::Upload, meta.len);
+2 -2
View File
@@ -232,7 +232,7 @@ impl Core {
}
let alt = conflict_name(&name, now_secs());
let thumbnails = self.upload_thumbnails(blob, &alt);
let thumbnails = self.photos().upload_thumbnails(blob, &alt);
let guard =
self.transfers
.begin(&alt, meta.uid.clone(), TransferDirection::Upload, meta.len);
@@ -377,7 +377,7 @@ impl Core {
}
let name = self.node_name(&uid);
let thumbnails = self.upload_thumbnails(&blob, &name);
let thumbnails = self.photos().upload_thumbnails(&blob, &name);
let guard =
self.transfers
.begin(&name, meta.uid.clone(), TransferDirection::Upload, meta.len);
+8
View File
@@ -116,6 +116,14 @@ impl EventHub {
.retain(|other| !Arc::ptr_eq(other, mailbox));
}
/// Wake every subscription waiting on its mailbox, so it sees a stop
/// now rather than at its next heartbeat.
pub(crate) fn wake_all(&self) {
for mailbox in self.mailboxes.lock().iter() {
mailbox.ready.notify_one();
}
}
fn has_subscribers(&self) -> bool {
!self.mailboxes.lock().is_empty()
}
+41 -33
View File
@@ -14,6 +14,8 @@ use pdfs_core::control::{
GalleryAction, GalleryAlbum, GalleryFolder, GalleryPlace, PhotoItem, PhotoKind, Response,
};
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::Db;
use proton_drive_rs::ProtonDriveClient;
use proton_drive_rs::proton_sdk::session::ProtonApiSession;
use proton_gallery_app_rs::{App, View};
use proton_gallery_rs::CancellationToken;
@@ -32,6 +34,9 @@ pub(super) struct Gallery {
refresh: Notify,
access: AtomicU64,
video: video::Server,
client: ProtonDriveClient,
events: Arc<super::events::EventHub>,
db: Arc<Db>,
}
#[derive(Default, PartialEq, Eq)]
@@ -50,8 +55,17 @@ impl Visibility {
}
impl Gallery {
pub(super) fn new(root: PathBuf, session: ProtonApiSession) -> Self {
pub(super) fn new(
root: PathBuf,
session: ProtonApiSession,
client: ProtonDriveClient,
events: Arc<super::events::EventHub>,
db: Arc<Db>,
) -> Self {
Self {
client,
events,
db,
root,
session,
cancel: CancellationToken::new(),
@@ -69,13 +83,13 @@ impl Gallery {
self.video.close_all();
}
async fn app(&self, core: &Core) -> CoreResult<&App> {
async fn app(&self) -> CoreResult<&App> {
self.app
.get_or_try_init(|| async {
App::open_hosted(
self.root.clone(),
self.session.clone(),
core.client.clone(),
self.client.clone(),
self.cancel.child_token(),
)
.await
@@ -84,12 +98,7 @@ impl Gallery {
.await
}
async fn ensure_visibility(
&self,
core: &Core,
app: &App,
force: bool,
) -> CoreResult<Arc<Visibility>> {
async fn ensure_visibility(&self, app: &App, force: bool) -> CoreResult<Arc<Visibility>> {
if self.cancel.is_cancelled() {
return Err(CoreError::remote("The Gallery session expired"));
}
@@ -111,7 +120,7 @@ impl Gallery {
.await
.map_err(gallery_error)?
{
self.publish_visibility(core, self.read_visibility(core, app).await?);
self.publish_visibility(self.read_visibility(app).await?);
}
let started = Instant::now();
let result = tokio::select! {
@@ -119,7 +128,7 @@ impl Gallery {
_ = self.cancel.cancelled() => Err(CoreError::remote("The Gallery session expired")),
result = tokio::time::timeout(Duration::from_secs(20), async {
app.refresh_gallery_configuration(false).await.map_err(gallery_error)?;
self.read_visibility(core, app).await
self.read_visibility(app).await
}) => result.unwrap_or_else(|_| Err(CoreError::remote("Gallery visibility check timed out"))),
};
tracing::debug!(
@@ -129,7 +138,7 @@ impl Gallery {
);
*checked = Some(Instant::now());
if let Ok(visibility) = result {
self.publish_visibility(core, visibility.clone());
self.publish_visibility(visibility.clone());
return Ok(visibility);
}
if !force && let Some(visibility) = self.snapshot() {
@@ -145,18 +154,18 @@ impl Gallery {
.clone()
}
fn publish_visibility(&self, core: &Core, visibility: Arc<Visibility>) {
fn publish_visibility(&self, visibility: Arc<Visibility>) {
let mut snapshot = self.visibility.write().unwrap_or_else(|e| e.into_inner());
if snapshot.as_ref() != Some(&visibility) {
*snapshot = Some(visibility);
drop(snapshot);
self.video.close_all();
core.events
self.events
.publish(&[pdfs_core::control::Topic::GalleryVisibilitySynced]);
}
}
async fn read_visibility(&self, core: &Core, app: &App) -> CoreResult<Arc<Visibility>> {
async fn read_visibility(&self, app: &App) -> CoreResult<Arc<Visibility>> {
let account = self.account()?;
let mut visibility = Visibility::default();
for (volume, node) in app
@@ -170,7 +179,7 @@ impl Gallery {
.insert(NodeUid::new(volume.into(), node.into()).to_string());
}
visibility.media.extend(
core.db
self.db
.photo_group_members_for(&visibility.media)
.map_err(CoreError::from)?,
);
@@ -328,7 +337,7 @@ impl Gallery {
Ok(())
}
pub(super) async fn poll(self: Arc<Self>, core: Core) {
pub(super) async fn poll(self: Arc<Self>) {
loop {
tokio::select! {
biased;
@@ -336,9 +345,8 @@ impl Gallery {
_ = self.refresh.notified() => {},
_ = tokio::time::sleep(Duration::from_secs(60)) => {}
}
if let Ok(Ok(app)) = tokio::time::timeout(Duration::from_secs(5), self.app(&core)).await
{
let _ = self.ensure_visibility(&core, app, false).await;
if let Ok(Ok(app)) = tokio::time::timeout(Duration::from_secs(5), self.app()).await {
let _ = self.ensure_visibility(app, false).await;
}
}
}
@@ -422,8 +430,8 @@ impl Core {
}
let gallery = self.gallery_host()?;
self.rt.block_on(async {
let app = gallery.app(self).await?;
gallery.ensure_visibility(self, app, false).await
let app = gallery.app().await?;
gallery.ensure_visibility(app, false).await
})
}
@@ -475,9 +483,9 @@ impl Core {
other => other,
};
self.rt.block_on(async {
let app = gallery.app(self).await?;
let app = gallery.app().await?;
gallery
.ensure_visibility(self, app, matches!(action, GalleryAction::Refresh))
.ensure_visibility(app, matches!(action, GalleryAction::Refresh))
.await?;
match action {
GalleryAction::AuthenticateHidden | GalleryAction::Lock => unreachable!(),
@@ -517,14 +525,14 @@ impl Core {
app.add_drive_folder(uid(&node)?)
.await
.map_err(gallery_error)?;
gallery.ensure_visibility(self, app, true).await?;
gallery.ensure_visibility(app, true).await?;
Ok(done())
}
GalleryAction::Remove { gallery: id } => {
app.forget_drive_gallery(SourceId::new(id).map_err(gallery_error)?)
.await
.map_err(gallery_error)?;
gallery.ensure_visibility(self, app, true).await?;
gallery.ensure_visibility(app, true).await?;
Ok(done())
}
GalleryAction::Refresh => {
@@ -535,7 +543,7 @@ impl Core {
);
app.scan_drive_folder(root).await.map_err(gallery_error)?;
}
gallery.ensure_visibility(self, app, true).await?;
gallery.ensure_visibility(app, true).await?;
Ok(done())
}
GalleryAction::Cover { album, uid: node } => {
@@ -565,7 +573,7 @@ impl Core {
.set_album_settings_at(Some(root), id, settings)
.await
.map_err(gallery_error)?;
gallery.ensure_visibility(self, app, true).await?;
gallery.ensure_visibility(app, true).await?;
Ok(done())
}
}
@@ -576,8 +584,8 @@ impl Core {
let gallery = self.gallery_host()?;
let uid = uid(node)?;
self.rt.block_on(async {
let app = gallery.app(self).await?;
let visibility = gallery.ensure_visibility(self, app, false).await?;
let app = gallery.app().await?;
let visibility = gallery.ensure_visibility(app, false).await?;
let access = if private {
Some(gallery.private_access()?)
} else {
@@ -605,7 +613,7 @@ impl Core {
let access = gallery.private_access()?;
let asset = gallery.asset(&uid(node)?)?;
self.rt.block_on(async {
let app = gallery.app(self).await?;
let app = gallery.app().await?;
let bytes = tokio::time::timeout(Duration::from_secs(30), async {
if let Some(bytes) = app.preview(&asset).await? {
Ok(bytes)
@@ -633,8 +641,8 @@ impl Core {
let gallery = self.gallery_host()?;
let asset = gallery.asset(&uid(node)?)?;
self.rt.block_on(async {
let app = gallery.app(self).await?;
let visibility = gallery.ensure_visibility(self, app, false).await?;
let app = gallery.app().await?;
let visibility = gallery.ensure_visibility(app, false).await?;
let access = if private {
Some(gallery.private_access()?)
} else {
+5 -7
View File
@@ -15,11 +15,10 @@
use std::process::{Child, Command, Stdio};
use std::time::Duration;
use pdfs_store::db::PendingCounts;
use pdfs_core::shutdown::Shutdown;
use pdfs_store::db::{Db, PendingCounts};
use tracing::{debug, warn};
use super::Core;
/// How often the queue is looked at.
const CHECK_EVERY: Duration = Duration::from_secs(5);
@@ -29,11 +28,10 @@ fn sendable(counts: &PendingCounts) -> i64 {
}
/// Run until the daemon stops, holding the inhibitor while changes wait.
pub(crate) fn run(core: Core) {
pub(crate) fn run(db: &Db, shutdown: &Shutdown) {
let mut held: Option<Child> = None;
loop {
let waiting = core
.db
let waiting = db
.pending_op_counts()
.map(|counts| sendable(&counts))
.unwrap_or(0);
@@ -52,7 +50,7 @@ pub(crate) fn run(core: Core) {
}
_ => {}
}
if !core.shutdown.sleep(CHECK_EVERY) {
if !shutdown.sleep(CHECK_EVERY) {
break;
}
}
+97 -22
View File
@@ -22,6 +22,16 @@ use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::{debug, info, warn};
use std::sync::Arc;
use fuser::Errno;
use parking_lot::Mutex;
use pdfs_core::CoreResult;
use pdfs_core::shutdown::Shutdown;
use pdfs_store::cache::ContentCache;
use super::link::Link;
use super::transfers::TransferRegistry;
use super::{Core, is_local_uid, node_size, parse_uid};
/// How often the keeper looks for work.
@@ -59,32 +69,76 @@ pub(crate) struct KeptFile {
pub(crate) size: u64,
}
impl Core {
/// Have the keeper check every pin.
pub(crate) fn recheck_all_pins(&self) {
self.pin_work.lock().all = true;
/// What the pin keeper needs from the tree.
pub(crate) trait KeeperHost: Send + Sync {
/// Where `uid` is in the tree: its inode, its parent's, and whether it is
/// a folder.
fn locate(&self, uid: &NodeUid) -> Option<(u64, u64, bool)>;
/// Every file under the folder at `ino`, listing what is not listed yet.
fn pin_subtree_files(&self, ino: u64) -> CoreResult<Vec<u64>>;
/// List the folder at `ino` again if its listing was dropped.
fn ensure_children(&self, ino: u64) -> Result<(), Errno>;
/// The file at `ino`, as a pin keeps it. See [`Core::kept_file`].
fn kept_file(&self, ino: u64) -> Option<KeptFile>;
/// Download a pinned file and keep it.
fn fetch_pinned(&self, uid: &NodeUid, name: &str, mtime: i64, size: u64) -> CoreResult<()>;
}
impl KeeperHost for Core {
fn locate(&self, uid: &NodeUid) -> Option<(u64, u64, bool)> {
let st = self.state();
st.by_uid.get(uid).and_then(|&ino| {
let e = st.entries.get(&ino)?;
Some((ino, e.parent, e.node.is_folder()))
})
}
/// Have the keeper check the pinned file or folder `uid`.
pub(crate) fn recheck_pinned(&self, uid: &NodeUid) {
self.pin_work.lock().nodes.insert(uid.clone());
fn pin_subtree_files(&self, ino: u64) -> CoreResult<Vec<u64>> {
Core::pin_subtree_files(self, ino)
}
fn ensure_children(&self, ino: u64) -> Result<(), Errno> {
Core::ensure_children(self, ino)
}
fn kept_file(&self, ino: u64) -> Option<KeptFile> {
Core::kept_file(self, ino)
}
fn fetch_pinned(&self, uid: &NodeUid, name: &str, mtime: i64, size: u64) -> CoreResult<()> {
Core::fetch_pinned(self, uid, name, mtime, size)
}
}
/// Checks pins again and downloads what is missing or stale (the module
/// documentation says when). Holds the content cache, the transfer list, the
/// link, the stop signal and the queue of work; it reaches the tree through
/// [`KeeperHost`].
pub(crate) struct PinKeeper {
cache: Arc<ContentCache>,
transfers: Arc<TransferRegistry>,
link: Arc<Link>,
shutdown: Arc<Shutdown>,
work: Arc<Mutex<PinWork>>,
host: Arc<dyn KeeperHost>,
}
impl PinKeeper {
/// The keeper's loop, until the daemon stops. Starts with a check of every
/// pin, which catches up on whatever changed while the daemon was down.
///
/// Work that failed waits out a backoff of its own. New work does not wait
/// for it, so a file that keeps failing does not hold up the next change.
pub(crate) fn run_pin_keeper(&self) {
self.recheck_all_pins();
pub(crate) fn run(&self) {
self.work.lock().all = true;
let mut backlog = PinWork::default();
let mut backlog_due = Instant::now();
let mut retry = RETRY_FIRST;
while self.shutdown.sleep(KEEPER_TICK) {
if !self.is_online() {
if !self.link.is_online() {
continue;
}
let mut work = std::mem::take(&mut *self.pin_work.lock());
let mut work = std::mem::take(&mut *self.work.lock());
let retrying = !backlog.is_empty() && Instant::now() >= backlog_due;
if retrying {
work.merge(std::mem::take(&mut backlog));
@@ -128,19 +182,13 @@ impl Core {
if !self.cache.is_pinned(&uid) {
continue;
}
let found = {
let st = self.state();
st.by_uid.get(&uid).and_then(|&ino| {
let e = st.entries.get(&ino)?;
Some((ino, e.parent, e.node.is_folder()))
})
};
let found = self.host.locate(&uid);
let Some((ino, parent, is_folder)) = found else {
debug!(%uid, "pin keeper: pinned node is not in the tree");
continue;
};
if is_folder {
match self.pin_subtree_files(ino) {
match self.host.pin_subtree_files(ino) {
Ok(inos) => files.extend(inos.into_iter().filter(|i| seen.insert(*i))),
Err(e) => {
warn!(%uid, error = %e, "pin keeper: listing a kept folder failed");
@@ -154,7 +202,7 @@ impl Core {
// now, which is what the cached copy is checked against.
if !work.all
&& parent != ino
&& let Err(e) = self.ensure_children(parent)
&& let Err(e) = self.host.ensure_children(parent)
{
warn!(%uid, error = ?e, "pin keeper: listing a kept file's folder failed");
failed.nodes.insert(uid);
@@ -167,7 +215,7 @@ impl Core {
let stale: Vec<KeptFile> = files
.into_iter()
.filter_map(|ino| self.kept_file(ino))
.filter_map(|ino| self.host.kept_file(ino))
.filter(|f| !self.cache.is_cached(&f.uid, f.mtime, f.size))
.collect();
if stale.is_empty() {
@@ -186,7 +234,10 @@ impl Core {
continue;
}
job.detail(file.name.clone());
match self.fetch_pinned(&file.uid, &file.name, file.mtime, file.size) {
match self
.host
.fetch_pinned(&file.uid, &file.name, file.mtime, file.size)
{
Ok(()) => fetched += 1,
Err(e) => {
warn!(uid = %file.uid, error = %e, "pin keeper: download failed");
@@ -203,6 +254,30 @@ impl Core {
);
failed
}
}
impl Core {
/// The pin keeper, with this daemon as its host.
pub(crate) fn pin_keeper(&self) -> PinKeeper {
PinKeeper {
cache: self.cache.clone(),
transfers: self.transfers.clone(),
link: self.link.clone(),
shutdown: self.shutdown.clone(),
work: self.pin_work.clone(),
host: Arc::new(self.clone()),
}
}
/// Have the keeper check every pin.
pub(crate) fn recheck_all_pins(&self) {
self.pin_work.lock().all = true;
}
/// Have the keeper check the pinned file or folder `uid`.
pub(crate) fn recheck_pinned(&self, uid: &NodeUid) {
self.pin_work.lock().nodes.insert(uid.clone());
}
/// The file at `ino`, as a pin keeps it. `None` for a folder, a file this
/// daemon still owes an upload for, or a file whose real size cannot be
+6 -29
View File
@@ -82,12 +82,10 @@ use proton_drive_rs::{
};
mod activity;
mod albums;
mod attach;
mod background;
mod conflicts;
mod control;
use control::run_control_socket;
mod devices;
mod diagnostics;
mod drain;
@@ -121,13 +119,13 @@ mod queue;
mod quota;
mod reads;
mod recovery;
mod redate;
mod relocate;
mod remote;
mod requests;
mod resolve;
mod revisions;
mod search;
mod services;
mod shared;
mod sharing;
mod sizes;
@@ -140,12 +138,11 @@ mod supervisor;
mod sweep;
mod sync;
mod systemd;
mod takeout;
use pdfs_core::transfers;
mod upload;
mod r#virtual;
mod workers;
use background::{forget_and_notify, run_event_sync, run_local_index, run_photos_event_sync};
use background::{forget_and_notify, run_event_sync, run_photos_event_sync};
use link::BATCH_CALL_TIMEOUT;
pub(crate) use mount::is_stale_mount;
pub use mount::prepare_mountpoint;
@@ -587,7 +584,7 @@ struct Core {
services: pdfs_core::lifecycle::ServiceBoard,
/// Whether a trash refresh is running, and the wake-up for requests waiting
/// on its progress.
trash: trash::TrashState,
trash_jobs: trash::TrashState,
/// What the conflict sweep may do, and the copies it already checked this
/// run.
sweep: sweep::SweepState,
@@ -611,7 +608,7 @@ struct Core {
/// that needs the database — so the handler acknowledges the request and a
/// thread does the work, exactly as the other long control requests already
/// do. See [`Maintenance`].
maintenance: Arc<Mutex<maintenance::Maintenance>>,
maintenance: maintenance::Maintenance,
/// 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,
@@ -1397,26 +1394,6 @@ impl Core {
Ok(out.into_inner())
}
/// Like [`download_file_tracked_to`] for a photo, streaming through the
/// photos client's [`download_photo_to`].
///
/// [`download_file_tracked_to`]: Core::download_file_tracked_to
/// [`download_photo_to`]: ProtonPhotosClient::download_photo_to
fn download_photo_tracked(
&self,
photos: &ProtonPhotosClient,
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(photos.download_photo_to(uid, &mut out))?;
Ok(out.into_inner())
}
/// Fetch a thumbnail of `ttype` for the file at `ino`, served from the cache
/// when fresh and otherwise downloaded from the remote and cached. Returns
/// `Ok(None)` when the node is not a file or has no thumbnail of that type.
@@ -1476,7 +1453,7 @@ impl Core {
/// reuses the daemon's single authenticated session rather than logging in
/// again (Proton refresh tokens are single-use). Cheap — the Drive client
/// is `Clone` over `Arc`-backed state.
fn photos(&self) -> ProtonPhotosClient {
fn photos_api(&self) -> ProtonPhotosClient {
ProtonPhotosClient::from_drive_client(self.client.clone())
}
@@ -4172,7 +4149,7 @@ mod tests {
"enumerate_folder_children_node_uids",
);
assert_eq!(ensure.matches("adopt_stale_listing(").count(), 3);
let online = function_source(include_str!("link.rs"), "fn mark_online(");
let online = function_source(include_str!("link.rs"), "fn after_reconnect(");
assert!(online.contains("self.relist_offline_listings();"));
}
+171 -82
View File
@@ -18,6 +18,11 @@ use proton_drive_rs::proton_sdk::api::ResponseCode;
use proton_drive_rs::proton_sdk::error::{ProtonApiError, ProtonError};
use tracing::{debug, info, warn};
use std::sync::Arc;
use pdfs_core::shutdown::Shutdown;
use pdfs_drive::DriveApi;
use crate::{Core, ONLINE_PROBE_MAX, ONLINE_PROBE_MIN};
/// How long a remote call a FUSE handler is waiting on may take before the link
@@ -88,6 +93,75 @@ impl Link {
..Default::default()
}
}
/// Whether the mount currently believes Proton is reachable.
pub(crate) fn is_online(&self) -> bool {
self.online.load(Ordering::Relaxed)
}
/// Whether Proton refused the session itself, so the mount stays offline
/// until the user signs in again.
pub(crate) fn session_expired(&self) -> bool {
self.session_expired.load(Ordering::Relaxed)
}
/// Flip the mount offline and wake the probe. Only the first caller of an
/// outage logs it; the rest are the same outage.
pub(crate) fn go_offline(&self, what: &str, error: &dyn std::fmt::Display) {
let mut lost_at = self.lost_at.lock();
if self.online.swap(false, Ordering::Relaxed) {
*lost_at = Some(Instant::now());
warn!(during = what, %error,
"lost the connection to Proton; queueing changes until it returns");
self.changed.notify_all();
}
}
/// Flip the mount back online and wake everything waiting for it.
fn go_online(&self) {
let mut lost_at = self.lost_at.lock();
self.online.store(true, Ordering::Relaxed);
match lost_at.take() {
Some(since) => {
info!(
offline_secs = since.elapsed().as_secs(),
"connection to Proton is back"
)
}
None => info!("back online"),
}
self.changed.notify_all();
}
/// Wait up to `budget` for the link to come back. Returns whether it is up.
pub(crate) fn wait_online(&self, budget: Duration, shutdown: &Shutdown) -> bool {
let deadline = Instant::now() + budget;
let mut lost_at = self.lost_at.lock();
while !self.is_online() {
if shutdown.is_stopping() || self.changed.wait_until(&mut lost_at, deadline).timed_out()
{
return self.is_online();
}
}
true
}
/// Wait while the link is up. Returns `false` if the daemon is stopping.
fn wait_offline(&self, shutdown: &Shutdown) -> bool {
let mut lost_at = self.lost_at.lock();
while self.is_online() {
if shutdown.is_stopping() {
return false;
}
self.changed.wait_for(&mut lost_at, IDLE_CHECK);
}
true
}
/// When the current outage began, if the link is down.
fn lost_at(&self) -> Option<Instant> {
*self.lost_at.lock()
}
}
pub(crate) use pdfs_drive::is_network_error;
@@ -160,7 +234,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.link.online.load(Ordering::Relaxed)
self.link.is_online()
}
/// Whether a namespace change through the mount goes to Drive inside the
@@ -195,7 +269,7 @@ impl Core {
/// Whether Proton refused the session itself, so nothing reaches it until
/// the user signs in again.
pub(crate) fn session_expired(&self) -> bool {
self.link.session_expired.load(Ordering::Relaxed)
self.link.session_expired()
}
/// Report a failed remote call. Returns whether it failed for want of a
@@ -239,65 +313,14 @@ impl Core {
self.mark_offline(what, error);
}
/// Flip the mount offline and wake the probe. Only the first caller of an
/// outage logs it; the rest are the same outage.
/// Flip the mount offline and wake the probe. See [`Link::go_offline`].
pub(crate) fn mark_offline(&self, what: &str, error: &dyn std::fmt::Display) {
let mut lost_at = self.link.lost_at.lock();
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");
self.link.changed.notify_all();
}
}
/// Flip the mount back online, wake everything waiting for it, and let the
/// queue drain.
fn mark_online(&self) {
{
let mut lost_at = self.link.lost_at.lock();
self.link.online.store(true, Ordering::Relaxed);
match lost_at.take() {
Some(since) => {
info!(
offline_secs = since.elapsed().as_secs(),
"connection to Proton is back"
)
}
None => info!("back online"),
}
self.link.changed.notify_all();
}
self.relist_offline_listings();
// Anything written while offline is queued and waiting on exactly this,
// including ops that failed on the way down and are sitting out a
// backoff sized for a server that keeps refusing. Ops Drive refused
// keep theirs: the link was not why.
if let Err(e) = self.db.retry_unrefused_ops_now(crate::now_millis()) {
warn!(error = %e, "moving backed-off ops up after a reconnect failed");
}
self.wake_drain();
// Downloads for pins failed while the link was down, and the events
// that would have named the files are behind us (`docs/BUGS.md` B282).
self.recheck_all_pins();
self.link.go_offline(what, error);
}
/// Wait up to `budget` for the link to come back. Returns whether it is up.
pub(crate) fn wait_online(&self, budget: Duration) -> bool {
let deadline = Instant::now() + budget;
let mut lost_at = self.link.lost_at.lock();
while !self.is_online() {
if self.shutdown.is_stopping()
|| self
.link
.changed
.wait_until(&mut lost_at, deadline)
.timed_out()
{
return self.is_online();
}
}
true
self.link.wait_online(budget, &self.shutdown)
}
/// Wait out `interval` before a background poll of Proton, and while the
@@ -318,29 +341,103 @@ impl Core {
}
}
/// The online probe, with this daemon as its host.
pub(crate) fn online_probe(&self) -> OnlineProbe {
OnlineProbe {
link: self.link.clone(),
drive: self.drive.clone(),
rt: self.rt.clone(),
shutdown: self.shutdown.clone(),
host: Arc::new(self.clone()),
}
}
/// The link is back: let everything that waited on it go. Anything
/// written while offline is queued and waiting on exactly this, including
/// ops that failed on the way down and are sitting out a backoff sized
/// for a server that keeps refusing. Ops Drive refused keep theirs: the
/// link was not why.
fn after_reconnect(&self) {
self.relist_offline_listings();
if let Err(e) = self.db.retry_unrefused_ops_now(crate::now_millis()) {
warn!(error = %e, "moving backed-off ops up after a reconnect failed");
}
self.wake_drain();
// Downloads for pins failed while the link was down, and the events
// that would have named the files are behind us (`docs/BUGS.md` B282).
self.recheck_all_pins();
}
}
/// What the online probe needs from the rest of the daemon.
pub(crate) trait LinkHost: Send + Sync {
/// Drive answered with the My Files root: store it in the tree and the
/// database before the mount goes online.
fn refresh_root(&self, root: &proton_drive_rs::Node);
/// The mount is online again: relist, retry and refetch what waited.
fn reconnected(&self);
/// Proton refused the session.
fn session_refused(&self, what: &str, error: &ProtonError);
/// Repair the primary root's share id, which an offline start could not.
fn repair_share_id(&self);
}
impl LinkHost for Core {
fn refresh_root(&self, root: &proton_drive_rs::Node) {
{
let root_ino = self.root_ino();
let mut st = self.state();
if let Some(e) = st.entries.get_mut(&root_ino) {
e.node = root.clone();
}
}
if let Err(e) = self.db.upsert_node(root) {
warn!(error = %e, "refresh root after reconnect failed");
}
}
fn reconnected(&self) {
self.after_reconnect();
}
fn session_refused(&self, what: &str, error: &ProtonError) {
self.mark_session_expired(what, error);
}
fn repair_share_id(&self) {
self.repair_primary_share_id(&self.primary_root_uid);
}
}
/// Watches the link for the life of the mount and probes it back while it is
/// down. Holds the link, Drive, the runtime and the stop signal; it reaches
/// the tree and the queue through [`LinkHost`].
pub(crate) struct OnlineProbe {
link: Arc<Link>,
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
shutdown: Arc<Shutdown>,
host: Arc<dyn LinkHost>,
}
impl OnlineProbe {
/// Watch the link for the life of the mount: sleep while it is up, and
/// probe it back while it is down.
///
/// A mount that started from the cache is down from the first moment; one
/// that started online goes down when [`Core::mark_offline`] says so.
pub(crate) fn run_online_probe(&self) {
/// that started online goes down when [`Link::go_offline`] says so.
pub(crate) fn run(&self) {
// Only an offline start never had a chance to repair its share id.
let mut repair_share_id = !self.is_online();
let mut repair_share_id = !self.link.is_online();
loop {
{
let mut lost_at = self.link.lost_at.lock();
while self.is_online() {
if self.shutdown.is_stopping() {
return;
}
self.link.changed.wait_for(&mut lost_at, IDLE_CHECK);
}
if !self.link.wait_offline(&self.shutdown) {
return;
}
if !self.probe_until_online() {
return;
}
if std::mem::take(&mut repair_share_id) {
self.repair_primary_share_id(&self.primary_root_uid);
self.host.repair_share_id();
}
}
}
@@ -351,7 +448,7 @@ impl Core {
/// A refused session is not probed: every probe would be refused the same
/// way, forever (issue #35). The thread waits for the stop instead.
fn probe_until_online(&self) -> bool {
let started = self.link.lost_at.lock().unwrap_or_else(Instant::now);
let started = self.link.lost_at().unwrap_or_else(Instant::now);
let mut delay = if started.elapsed() < YOUNG_OUTAGE {
PROBE_AFTER_DROP
} else {
@@ -361,7 +458,7 @@ impl Core {
if !self.shutdown.sleep(delay) {
return false;
}
if self.session_expired() {
if self.link.session_expired() {
delay = ONLINE_PROBE_MAX;
continue;
}
@@ -373,20 +470,12 @@ impl Core {
});
match probe {
Ok(root) => {
{
let root_ino = self.root_ino();
let mut st = self.state();
if let Some(e) = st.entries.get_mut(&root_ino) {
e.node = root.clone();
}
}
if let Err(e) = self.db.upsert_node(&root) {
warn!(error = %e, "refresh root after reconnect failed");
}
self.mark_online();
self.host.refresh_root(&root);
self.link.go_online();
self.host.reconnected();
return true;
}
Err(e) if session_revoked(&e) => self.mark_session_expired("online probe", &e),
Err(e) if session_revoked(&e) => self.host.session_refused("online probe", &e),
Err(e) => {
debug!(error = %e, ?delay, "online probe failed; still offline");
delay = next_probe_delay(delay, started.elapsed());
+11 -5
View File
@@ -434,11 +434,17 @@ impl Core {
///
/// Metadata only: a thumbnail path is attached for photos whose thumbnail is
/// already cached, and nothing is downloaded here — the front-end pulls the
/// thumbnails it actually paints via [`Core::photo_thumbs`].
/// thumbnails it actually paints via [`Photos::photo_thumbs`](crate::photos::Photos::photo_thumbs).
pub(super) fn listing_stale(&self, key: &str, ttl: Duration) -> bool {
match self.db.state_i64(key).ok().flatten() {
Some(ms) => now_ms().saturating_sub(ms) >= ttl.as_millis() as i64,
None => true,
}
listing_stale(&self.db, key, ttl)
}
}
/// Whether the listing stamped under `key` is older than `ttl`, or was never
/// stamped.
pub(crate) fn listing_stale(db: &Db, key: &str, ttl: Duration) -> bool {
match db.state_i64(key).ok().flatten() {
Some(ms) => now_ms().saturating_sub(ms) >= ttl.as_millis() as i64,
None => true,
}
}
+38 -14
View File
@@ -3,7 +3,31 @@
use super::*;
impl Core {
/// Runs `VACUUM` and the deep integrity check as jobs, one at a time, and
/// keeps the last check's findings. Holds the database, the transfer list for
/// the job's entry, and the board the job runs on.
#[derive(Clone)]
pub(crate) struct Maintenance {
db: Arc<Db>,
transfers: Arc<TransferRegistry>,
services: pdfs_core::lifecycle::ServiceBoard,
state: Arc<Mutex<MaintenanceState>>,
}
impl Maintenance {
pub(crate) fn new(
db: Arc<Db>,
transfers: Arc<TransferRegistry>,
services: pdfs_core::lifecycle::ServiceBoard,
) -> Self {
Self {
db,
transfers,
services,
state: Arc::default(),
}
}
/// Start a background `VACUUM`, or refuse because maintenance is already
/// running.
///
@@ -11,9 +35,9 @@ impl Core {
/// request. The outcome is a log line and a job that disappears from
/// `GetQueueStatus` when it is done — a vacuum has nothing to report that a
/// follow-up `CacheInspect` cannot show.
pub(super) fn start_vacuum(&self) -> CoreResult<()> {
pub(crate) fn start_vacuum(&self) -> CoreResult<()> {
{
let mut m = self.maintenance.lock();
let mut m = self.state.lock();
if m.running {
return Err(CoreError::conflict(
"database maintenance is already running",
@@ -21,12 +45,12 @@ impl Core {
}
m.running = true;
}
let core = self.clone();
let this = self.clone();
if let Err(error) = self.services.spawn_job("pdfs-vacuum", move || {
let job = core.transfers.begin_job("Compacting the cache database");
let job = this.transfers.begin_job("Compacting the cache database");
job.detail("Rewriting the database file");
let started = Instant::now();
match core.db.vacuum() {
match this.db.vacuum() {
Ok(outcome) => info!(
freed_bytes = outcome.freed_bytes(),
before_bytes = outcome.before_bytes,
@@ -37,7 +61,7 @@ impl Core {
),
Err(e) => warn!(error = %e, "vacuum failed"),
}
core.maintenance.lock().running = false;
this.state.lock().running = false;
}) {
tracing::warn!(%error, "could not start pdfs-vacuum");
}
@@ -51,8 +75,8 @@ impl Core {
/// `(_, false, true)` and the answer lands on a later one — the check reads
/// every page of the database under the connection mutex, so the choice is
/// between answering late and freezing the mount until it finishes.
pub(super) fn start_or_read_integrity_check(&self) -> (Vec<String>, bool, bool) {
let mut m = self.maintenance.lock();
pub(crate) fn start_or_read_integrity_check(&self) -> (Vec<String>, bool, bool) {
let mut m = self.state.lock();
if let Some(problems) = m.integrity.clone() {
return (problems, true, m.running);
}
@@ -62,13 +86,13 @@ impl Core {
m.running = true;
drop(m);
let core = self.clone();
let this = self.clone();
if let Err(error) = self.services.spawn_job("pdfs-integrity-check", move || {
let job = core
let job = this
.transfers
.begin_background_job("Checking the cache database");
job.detail("Verifying every page");
let problems = match core.db.integrity_check() {
let problems = match this.db.integrity_check() {
Ok(problems) => problems,
Err(e) => vec![format!("integrity check failed: {e:?}")],
};
@@ -77,7 +101,7 @@ impl Core {
} else {
warn!(problems = problems.len(), "cache database integrity check");
}
let mut m = core.maintenance.lock();
let mut m = this.state.lock();
m.integrity = Some(problems);
m.running = false;
}) {
@@ -94,7 +118,7 @@ impl Core {
/// gain from overlapping them — and the result of a check outlives the request
/// that asked for it, because the request is answered before the check finishes.
#[derive(Default)]
pub(super) struct Maintenance {
struct MaintenanceState {
/// A vacuum or integrity check is running right now.
running: bool,
/// Findings of the most recent completed deep check. `None` means none has
+94 -139
View File
@@ -1,7 +1,7 @@
//! Mount lifecycle and background-service orchestration.
use super::*;
use pdfs_core::lifecycle::{ServiceBoard, Services, Wake};
use pdfs_core::lifecycle::{Service, ServiceBoard, Services};
/// Why a [`mount`] call returned. Lets the daemon decide whether to exit (clean
/// shutdown) or remount (the mount went away under it).
@@ -490,12 +490,21 @@ pub(crate) fn mount_with(
let (sync_tx, sync_rx) = std::sync::mpsc::channel::<sync::SyncMsg>();
let pause = pause::SyncPause::load(db.clone());
let events: Arc<events::EventHub> = Arc::default();
let gallery_dir = control_socket.with_file_name("gallery-catalog");
let gallery =
gallery_session.map(|session| Arc::new(super::gallery::Gallery::new(gallery_dir, session)));
let gallery = gallery_session.map(|session| {
Arc::new(super::gallery::Gallery::new(
gallery_dir,
session,
client.clone(),
events.clone(),
db.clone(),
))
});
let cache = Arc::new(cache);
let shutdown = Arc::new(crate::shutdown::Shutdown::default());
let transfers = TransferRegistry::new();
let services = ServiceBoard::default();
let sync = sync::SyncParts {
store: db.clone(),
drive: drive.clone(),
@@ -530,7 +539,11 @@ pub(crate) fn mount_with(
client,
gallery,
rt: rt.clone(),
maintenance: Arc::new(Mutex::new(Default::default())),
maintenance: super::maintenance::Maintenance::new(
db.clone(),
transfers.clone(),
services.clone(),
),
primary_root_uid: root.uid.clone(),
state: state.clone(),
cache,
@@ -542,7 +555,7 @@ pub(crate) fn mount_with(
drain: super::drain::DrainState::new(),
pin_work: Arc::new(Mutex::new(Default::default())),
sizes: super::sizes::SizeState::new(),
trash: super::trash::TrashState::new(),
trash_jobs: super::trash::TrashState::new(),
shared: super::shared::SharedState::new(),
quota: super::quota::QuotaCache::new(),
sharing,
@@ -550,12 +563,12 @@ pub(crate) fn mount_with(
writes: super::writes::WriteState::new(),
session: super::session::SessionCells::new(),
shutdown,
services: ServiceBoard::default(),
services: services.clone(),
photo_jobs: super::photos::PhotoJobs::new(),
local_first,
transfers,
sync,
events: Arc::new(Default::default()),
events,
indexing: Arc::new(AtomicBool::new(false)),
pending_probe: Arc::default(),
mounts: Arc::new(Mutex::new(SecondaryMountRegistry::default())),
@@ -568,14 +581,14 @@ pub(crate) fn mount_with(
// Writes queued by a previous run (or left behind by a crash) are still owed
// an upload, and reads must be served from their staged blobs until they land.
core.hydrate_pending();
core.recovery().hydrate_pending();
// Then the writes that were fsynced but never closed, which the cache moved
// aside at open. After `hydrate_pending`, so a recovered partial write can
// see an already-queued write to the same node.
core.recover_fsynced_writes();
core.recovery().recover_fsynced_writes();
// And finally the staged blobs neither of those accounts for: bytes a
// failed release left behind with nothing pointing at them.
core.reconcile_staging();
core.recovery().reconcile_staging();
// Several drain workers over one queue. One thread meant a single large
// upload held every queued rename, trash and small write behind it for as
// long as it ran; the claim column (`Db::claim_next_due_op`) keeps the
@@ -587,93 +600,49 @@ pub(crate) fn mount_with(
// in-process remount into a second generation of drain workers, sync engines
// and sweeps all operating on a mount that no longer exists (`docs/BUGS.md` B44).
let mut workers = Services::new(core.services.clone());
for worker in 0..DRAIN_WORKERS {
let drain_core = core.clone();
// The drain workers wait on their own condvar, which a stop has to
// notify; one notify wakes them all.
let wake: Option<Wake> = (worker == 0).then(|| {
let core = core.clone();
Box::new(move || core.wake_drain()) as Wake
});
let spawned = workers.spawn(&format!("pdfs-drain-{worker}"), wake, move || {
drain_core.run_pending_drain(worker == 0)
});
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
let mut list: Vec<Box<dyn Service>> = Vec::new();
for index in 0..DRAIN_WORKERS {
list.push(Box::new(services::DrainWorker {
core: core.clone(),
index,
}));
}
// Start the folder-sync engine. It watches every mirror folder, polls the
// remotes, and reconciles on its own thread — never in front of a FUSE call.
// It waits on its channel, so a stop sends it `Stop`.
{
let syncer = core.syncer();
let tx = core.sync.tx.clone();
let wake: Wake = Box::new(move || {
let _ = tx.send(sync::SyncMsg::Stop);
});
if let Err(error) =
workers.spawn("pdfs-sync", Some(wake), move || sync::run(syncer, sync_rx))
{
warn!(%error, "failed to start sync engine");
}
}
// A timed pause persisted by an earlier run still has to end on time.
if let Some(until) = core.pause.deadline() {
core.arm_pause_timer(until);
}
// Reconcile leftover `(sync-conflict …)` copies: drop the ones that turned
// out identical to the live file, surface the ones that genuinely diverge.
// Its own thread — it enumerates and trashes, and must never block a FUSE call.
list.push(Box::new(services::SyncEngine {
syncer: core.syncer(),
tx: core.sync.tx.clone(),
rx: sync_rx,
}));
// `Off` skips the thread entirely rather than starting an idle one, so the
// setting is verifiable from the outside (`ls /proc/<pid>/task/*/comm`).
if sweep_mode == SweepMode::Off {
info!("conflict sweep disabled by configuration");
} else {
info!(mode = ?sweep_mode, "conflict sweep enabled");
let sweep_core = core.clone();
let spawned = workers.spawn("pdfs-conflict-sweep", None, move || {
sweep_core.run_conflict_sweep_loop()
});
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
list.push(Box::new(services::ConflictSweep(core.sweeper())));
}
// Watch the link for the life of the mount: a mount from the cache waits for
// the network to come back, and an online one can lose it at any moment and
// must notice it coming back just the same.
{
let probe_core = core.clone();
let spawned = workers.spawn("pdfs-online-probe", None, move || {
probe_core.run_online_probe()
});
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
}
// Keep pinned files on this computer through changes made elsewhere, and
// fetch the ones a failed or missed download left out (`docs/BUGS.md`
// B282). Its own thread: a check lists folders and downloads files.
{
let keeper_core = core.clone();
let spawned = workers.spawn("pdfs-pin-keeper", None, move || {
keeper_core.run_pin_keeper()
});
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
}
// Keep the launcher prompt's "This computer" index fresh. Its own thread:
// the walk is I/O-heavy and must never sit in front of a FUSE callback.
list.push(Box::new(services::OnlineProbe(core.online_probe())));
list.push(Box::new(services::PinKeeper(core.pin_keeper())));
if matches!(host, Host::Daemon) {
if let Some(gallery) = &core.gallery {
workers.spawn_task(&rt, "pdfs-gallery", gallery.clone().poll(core.clone()));
}
let db = core.db.clone();
let indexing = core.indexing.clone();
let transfers = core.transfers.clone();
let mountpoint = mountpoint.to_path_buf();
let shutdown = core.shutdown.clone();
let spawned = workers.spawn("pdfs-localindex", None, move || {
run_local_index(db, indexing, transfers, mountpoint, shutdown)
});
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
list.push(Box::new(services::LocalIndex {
db: core.db.clone(),
indexing: core.indexing.clone(),
transfers: core.transfers.clone(),
mountpoint: mountpoint.to_path_buf(),
shutdown: core.shutdown.clone(),
}));
}
for service in list {
let started = workers.start(service);
keep_or_abandon(&core, control_socket, &mut workers, started)?;
}
if matches!(host, Host::Daemon)
&& let Some(gallery) = &core.gallery
{
workers.spawn_task(&rt, "pdfs-gallery", gallery.clone().poll());
}
// A timed pause persisted by an earlier run still has to end on time.
if let Some(until) = core.pause.deadline() {
core.arm_pause_timer(until);
}
// Bind the control socket before the FUSE session takes over the thread. A
@@ -713,23 +682,14 @@ pub(crate) fn mount_with(
// mid-transfer can abort it rather than block `join` (see `abort_fuse_connection`).
let main_conn = fuse_connection_id(mountpoint);
{
let control_core = core.clone();
let username = username.clone();
let mountpoint = mountpoint.to_path_buf();
// The listener blocks in `accept`, which only returns when a connection
// arrives, so a stop connects to it. Connect while the socket still
// exists, which is the point of the poke, then unlink it so nothing else
// can arrive behind it. The listener checks the stop flag after every
// accept, so a connection that races the unlink cannot put it back to
// sleep.
let socket = control_socket.to_path_buf();
let wake: Wake = Box::new(move || {
let _ = std::os::unix::net::UnixStream::connect(&socket);
let _ = std::fs::remove_file(&socket);
});
match workers.spawn("pdfs-control", Some(wake), move || {
run_control_socket(control_core, username, mountpoint, listener)
}) {
let control = services::ControlListener {
core: core.clone(),
username: username.clone(),
mountpoint: mountpoint.to_path_buf(),
listener,
socket: control_socket.to_path_buf(),
};
match workers.start(Box::new(control)) {
Ok(()) => {}
Err(error) => {
// A failure here abandons the mount, so the background threads
@@ -751,34 +711,19 @@ pub(crate) fn mount_with(
}
}
}
// Publishes what changes without one place to publish it from (status,
// transfers, sync progress) to the front-ends subscribed on that socket.
{
let sampler_core = core.clone();
let username = username.clone();
let mountpoint = mountpoint.to_path_buf();
if let Err(error) = workers.spawn("pdfs-events", None, move || {
events::run_event_sampler(sampler_core, username, mountpoint)
}) {
// Not fatal: front-ends still get every published change, only
// not the sampled ones.
warn!(error = %error, "could not start the event sampler");
}
}
// The supervisor watches the pool and answers the systemd watchdog. Started
// after the listener, because its liveness probe is a round trip over that
// socket.
{
let supervisor_core = core.clone();
let socket = control_socket.to_path_buf();
if let Err(error) = workers.spawn("pdfs-supervisor", None, move || {
supervisor::run(supervisor_core, socket)
}) {
// Not fatal: the mount works without a supervisor, it just goes back
// to being undiagnosable if it wedges.
warn!(error = %error, "could not start the daemon supervisor");
}
}
// The supervisor's liveness probe is a round trip over the control socket,
// so it starts after the listener. Both are optional.
let sampler = services::EventSampler {
core: core.clone(),
username: username.clone(),
mountpoint: mountpoint.to_path_buf(),
};
let watchdog = services::Supervisor {
core: core.clone(),
socket: control_socket.to_path_buf(),
};
start_late(&mut workers, Box::new(sampler));
start_late(&mut workers, Box::new(watchdog));
// The mount is live and the control socket answers: this is the moment the
// unit is actually usable, which is what `Type=notify` reports. Whatever
// failure an earlier attempt recorded for the front ends is over.
@@ -831,12 +776,13 @@ pub(crate) fn mount_with(
// Hold off a shutdown while changes exist only here (B66). Only the real
// daemon: a simulation's queue is not the user's data.
if matches!(host, Host::Daemon) {
let inhibit_core = core.clone();
if let Err(error) = workers.spawn("pdfs-inhibit", None, move || {
crate::inhibit::run(inhibit_core)
}) {
warn!(%error, "start the shutdown inhibitor failed");
}
start_late(
&mut workers,
Box::new(services::Inhibitor {
db: core.db.clone(),
shutdown: core.shutdown.clone(),
}),
);
}
// Stop signals (SIGTERM from `systemctl --user stop`, SIGINT from Ctrl-C)
@@ -985,6 +931,15 @@ fn abandon_workers(core: &Core, control_socket: &Path, workers: Services) {
halt_workers(core, control_socket, workers);
}
/// Start a service once the session is live. Past that point a failure no
/// longer abandons the mount, so even a required one is only logged.
fn start_late(workers: &mut Services, service: Box<dyn Service>) {
let name = service.name();
if let Err(error) = workers.start(service) {
warn!(service = name, %error, "service did not start");
}
}
/// Keep a worker the mount just spawned, or, if the spawn failed, stop the
/// ones already running and hand the error back.
fn keep_or_abandon(
+135 -17
View File
@@ -31,11 +31,20 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{NodeKind, PhotoTag, PhotoTagsUpdate, Thumbnail, ThumbnailType};
use tracing::{debug, info, warn};
use super::drive::RevisionRead;
use super::ContentCache;
use super::drive::{DriveApi, RevisionRead};
use super::events::EventHub;
use super::shutdown::Shutdown;
use super::transfers::{CountingWriter, TransferRegistry};
use super::{
Core, PHOTOS_AVAILABLE, PHOTOS_SYNCED_MS, TIMELINE_ENRICH_CHUNK, ThumbnailMissCaches,
WriteAuthority, link, node_size, now_ms, parse_uid,
};
use pdfs_core::control::TransferDirection;
use pdfs_core::control::{ActivityKind, DirEntry};
use pdfs_core::lifecycle::ServiceBoard;
use proton_drive_rs::proton_sdk::error::ProtonError;
use proton_drive_rs::{ProtonDriveClient, ProtonPhotosClient};
/// Longest edge, in px, of a thumbnail generated locally for a photo the server
/// has none for. Matches the server's own thumbnail scale closely enough that a
@@ -129,8 +138,107 @@ const DECODE_BUDGET_BYTES: u64 = 512 * 1024 * 1024;
/// The process-wide [`DecodeBudget`] every thumbnail decode draws from.
static DECODE_BUDGET: DecodeBudget = DecodeBudget::new(DECODE_BUDGET_BYTES);
mod albums;
pub(crate) mod redate;
pub(crate) mod takeout;
pub(crate) use albums::AlbumOutcome;
pub(crate) use takeout::sha1_of;
mod thumbs;
mod timeline;
mod trash;
/// The Photos service: the timeline, albums and thumbnails.
///
/// It holds only the handles it calls, and reaches the filesystem through
/// [`PhotosHost`], so it does not depend on [`Core`]. [`Core::photos`] builds
/// one on demand, the same way [`Core::syncer`] builds the sync engine. A clone
/// shares everything, which is how a refresh or a thumbnail job moves onto a
/// background task.
#[derive(Clone)]
pub(crate) struct Photos {
client: ProtonDriveClient,
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
cache: Arc<ContentCache>,
db: Arc<pdfs_store::db::Db>,
shutdown: Arc<Shutdown>,
services: ServiceBoard,
events: Arc<EventHub>,
transfers: Arc<TransferRegistry>,
jobs: PhotoJobs,
host: Arc<dyn PhotosHost>,
}
/// What the Photos service needs from the filesystem.
pub(crate) trait PhotosHost: Send + Sync {
/// List a folder of the mount, for the recursive thumbnail build.
fn list_dir(&self, rel: &Path) -> CoreResult<Vec<DirEntry>>;
/// Record a change this daemon made, so its echo in the event feed is not
/// taken for a remote edit.
fn note_self_change(&self, uid: &NodeUid);
/// Add an entry to the activity log.
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool);
}
impl PhotosHost for Core {
fn list_dir(&self, rel: &Path) -> CoreResult<Vec<DirEntry>> {
Core::list_dir(self, rel)
}
fn note_self_change(&self, uid: &NodeUid) {
Core::note_self_change(self, uid)
}
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool) {
Core::log_activity(self, kind, target, detail, ok);
}
}
impl Core {
/// The Photos service, with this daemon as its host.
pub(crate) fn photos(&self) -> Photos {
Photos {
client: self.client.clone(),
drive: self.drive.clone(),
rt: self.rt.clone(),
cache: self.cache.clone(),
db: self.db.clone(),
shutdown: self.shutdown.clone(),
services: self.services.clone(),
events: self.events.clone(),
transfers: self.transfers.clone(),
jobs: self.photo_jobs.clone(),
host: Arc::new(self.clone()),
}
}
}
impl Photos {
/// The Photos API over the daemon's single authenticated session.
fn photos_api(&self) -> ProtonPhotosClient {
ProtonPhotosClient::from_drive_client(self.client.clone())
}
/// Like [`download_file_tracked_to`] for a photo, streaming through the
/// photos client's [`download_photo_to`].
///
/// [`download_file_tracked_to`]: crate::Core::download_file_tracked_to
/// [`download_photo_to`]: ProtonPhotosClient::download_photo_to
fn download_photo_tracked(
&self,
photos: &ProtonPhotosClient,
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(photos.download_photo_to(uid, &mut out))?;
Ok(out.into_inner())
}
}
/// What the Photos and thumbnail jobs are doing right now: which refreshes
/// and builds are running, how far they got, and which thumbnails are known
@@ -149,7 +257,7 @@ pub(crate) struct PhotoJobs {
/// The same, for the album listing.
pub(crate) albums_refreshing: Arc<AtomicBool>,
/// True while the similar-photo pass hashes thumbnails (see
/// [`Core::photo_similar`]), so asking again doesn't start a second one.
/// [`Photos::photo_similar`]), so asking again doesn't start a second one.
pub(crate) similar_hashing: Arc<AtomicBool>,
/// Photos whose missing thumbnail is being generated right now. A tile that is
/// still on screen asks for its thumbnail again every few seconds, and each of
@@ -601,12 +709,32 @@ fn run_bounded(mut command: Command, timeout: Duration) -> Result<Vec<u8>, ToolE
let _ = child.wait();
return Err(ToolError::Unavailable);
};
let reader = std::thread::spawn(move || {
let mut output = Vec::new();
stdout.read_to_end(&mut output).map(|_| output)
});
// Scoped, so the reader cannot outlive the call even when the child
// overruns and is killed.
std::thread::scope(|scope| {
let reader = scope.spawn(move || {
let mut output = Vec::new();
stdout.read_to_end(&mut output).map(|_| output)
});
let status = wait_bounded(&mut child, timeout);
let output = reader
.join()
.ok()
.and_then(Result::ok)
.ok_or(ToolError::Unavailable)?;
match status {
Some(true) => Ok(output),
Some(false) => Err(ToolError::Failed),
None => Err(ToolError::Unavailable),
}
})
}
/// Wait for `child` to exit, up to `timeout`, killing it past that. `None`
/// when it overran or could not be waited for.
fn wait_bounded(child: &mut std::process::Child, timeout: Duration) -> Option<bool> {
let started = Instant::now();
let status = loop {
loop {
match child.try_wait() {
Ok(Some(status)) => break Some(status.success()),
Ok(None) if started.elapsed() < timeout => {
@@ -618,16 +746,6 @@ fn run_bounded(mut command: Command, timeout: Duration) -> Result<Vec<u8>, ToolE
break None;
}
}
};
let output = reader
.join()
.ok()
.and_then(Result::ok)
.ok_or(ToolError::Unavailable)?;
match status {
Some(true) => Ok(output),
Some(false) => Err(ToolError::Failed),
None => Err(ToolError::Unavailable),
}
}
@@ -2,7 +2,7 @@
//!
//! Both are persisted projections of what the photos volume reports, refreshed
//! on the same stale-while-serving rule as the timeline
//! ([`crate::photos`]): a listing already on disk is served immediately and
//! ([`super`]): a listing already on disk is served immediately and
//! refreshed behind the caller, and only an empty one waits on the network.
//!
//! An album is a folder node carrying album properties, so it has a name like
@@ -23,15 +23,16 @@ use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::warn;
use super::{
ALBUM_SYNCED_PREFIX, ALBUMS_SYNCED_MS, Core, PHOTOS_AVAILABLE, TIMELINE_ENRICH_CHUNK,
TIMELINE_TTL, link, now_ms, parse_uid,
use super::Photos;
use crate::{
ALBUM_SYNCED_PREFIX, ALBUMS_SYNCED_MS, PHOTOS_AVAILABLE, TIMELINE_ENRICH_CHUNK, TIMELINE_TTL,
link, listing::listing_stale, now_ms, parse_uid,
};
impl Core {
impl Photos {
/// The album listing, served from disk and refreshed behind the caller when
/// stale. `None` means the account has no photos volume — the same signal
/// [`Core::photos_timeline`] gives.
/// [`Photos::photos_timeline`] gives.
pub(crate) fn albums(&self) -> CoreResult<Option<Vec<AlbumInfo>>> {
let count = self.db.albums_count().map_err(CoreError::from)?;
if count == 0
@@ -44,13 +45,13 @@ impl Core {
// Nothing on disk, so this one request waits for the fetch — unless
// the account is already known to have no photos volume.
let known_empty = self.db.state_i64(PHOTOS_AVAILABLE).ok().flatten() == Some(0);
if known_empty && !self.listing_stale(ALBUMS_SYNCED_MS, TIMELINE_TTL) {
if known_empty && !listing_stale(&self.db, ALBUMS_SYNCED_MS, TIMELINE_TTL) {
return Ok(None);
}
if !self.rt.block_on(self.refresh_albums())? {
return Ok(None);
}
} else if self.listing_stale(ALBUMS_SYNCED_MS, TIMELINE_TTL) {
} else if listing_stale(&self.db, ALBUMS_SYNCED_MS, TIMELINE_TTL) {
self.spawn_albums_refresh();
}
@@ -66,7 +67,7 @@ impl Core {
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos();
let photos = self.photos_api();
if link::bounded(photos.get_photos_root())
.await
.map_err(|e| CoreError::from_api(&e, "photos root"))?
@@ -132,22 +133,16 @@ impl Core {
/// Refresh the album listing off the request path. At most one runs at a time.
pub(crate) fn spawn_albums_refresh(&self) {
if self
.photo_jobs
.albums_refreshing
.swap(true, Ordering::SeqCst)
{
if self.jobs.albums_refreshing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
let this = self.clone();
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);
let refreshed = this.refresh_albums().await;
this.jobs.albums_refreshing.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Photos]),
Ok(_) => this.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background album refresh failed"),
}
});
@@ -177,12 +172,12 @@ impl Core {
.is_none()
{
self.rt.block_on(self.refresh_album(album))?;
} else if self.listing_stale(&stamp, TIMELINE_TTL) {
let core = self.clone();
} else if listing_stale(&self.db, &stamp, TIMELINE_TTL) {
let this = self.clone();
let album = album.clone();
self.services
.spawn_task_job(&self.rt, "pdfs-album-refresh", async move {
if let Err(e) = core.refresh_album(&album).await {
if let Err(e) = this.refresh_album(&album).await {
warn!(%album, error = %e, "background album refresh failed");
}
});
@@ -235,7 +230,7 @@ impl Core {
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos();
let photos = self.photos_api();
let items = link::bounded(photos.enumerate_album(album))
.await
.map_err(|e| CoreError::from_api(&e, "album"))?;
@@ -285,11 +280,11 @@ impl Core {
}
/// Create an album and return its uid. The listing is refreshed before
/// answering, so the next [`Core::albums`] already shows it.
/// answering, so the next [`Photos::albums`] already shows it.
pub(crate) fn create_album(&self, name: &str) -> CoreResult<String> {
let uid = self
.rt
.block_on(self.photos().create_album(name))
.block_on(self.photos_api().create_album(name))
.map_err(|e| CoreError::from_api(&e, "create album"))?;
self.after_album_change(None);
Ok(uid.to_string())
@@ -297,7 +292,7 @@ impl Core {
pub(crate) fn rename_album(&self, album: &NodeUid, name: &str) -> CoreResult<()> {
self.rt
.block_on(self.photos().rename_album(album, name))
.block_on(self.photos_api().rename_album(album, name))
.map_err(|e| CoreError::from_api(&e, "rename album"))?;
self.after_album_change(None);
Ok(())
@@ -307,7 +302,7 @@ impl Core {
/// which only matters for photos that exist in the album alone.
pub(crate) fn delete_album(&self, album: &NodeUid, delete_photos: bool) -> CoreResult<()> {
self.rt
.block_on(self.photos().delete_album(album, delete_photos))
.block_on(self.photos_api().delete_album(album, delete_photos))
.map_err(|e| CoreError::from_api(&e, "delete album"))?;
let key = album.to_string();
if let Err(error) = self.db.photos_delete(&[key]) {
@@ -325,7 +320,7 @@ impl Core {
) -> CoreResult<AlbumOutcome> {
let outcomes = self
.rt
.block_on(self.photos().add_photos_to_album(album, photos))
.block_on(self.photos_api().add_photos_to_album(album, photos))
.map_err(|e| CoreError::from_api(&e, "add to album"))?;
self.after_album_change(Some(album));
Ok(album_outcome(outcomes))
@@ -340,7 +335,7 @@ impl Core {
) -> CoreResult<AlbumOutcome> {
let outcomes = self
.rt
.block_on(self.photos().remove_photos_from_album(album, photos))
.block_on(self.photos_api().remove_photos_from_album(album, photos))
.map_err(|e| CoreError::from_api(&e, "remove from album"))?;
self.after_album_change(Some(album));
Ok(album_outcome(outcomes))
@@ -363,7 +358,7 @@ impl Core {
}
/// Drop the album listing's and every album's freshness stamp, so the next
/// request re-enumerates. Paired with [`Core::invalidate_photos`] — a change
/// request re-enumerates. Paired with [`Core::invalidate_photos`](crate::Core::invalidate_photos) — a change
/// to the timeline can just as easily be a change to an album.
pub(crate) fn invalidate_albums(&self) {
let _ = self.db.clear_state(ALBUMS_SYNCED_MS);
@@ -27,7 +27,7 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{PhotoTag, PhotoTagsUpdate, PhotoUploadMetadata};
use tracing::{info, warn};
use super::Core;
use super::Photos;
use crate::parse_uid as parse_node_uid;
use crate::transfers::CountingReader;
@@ -84,7 +84,7 @@ struct Candidate {
albums: Vec<String>,
}
impl Core {
impl Photos {
/// Re-date mis-dated photos. Blocking; run on its own thread.
///
/// `cancel` stops the run at the next photo boundary. A photo is only ever
@@ -184,7 +184,7 @@ impl Core {
/// trash the original. Every earlier step failing leaves the account exactly
/// as it was.
fn redate_one(&self, candidate: &Candidate, summary: &mut RedateSummary) -> CoreResult<()> {
let photos = self.photos();
let photos = self.photos_api();
let path = self.open_photo(&candidate.uid)?;
let size = std::fs::metadata(&path)
.map_err(|e| CoreError::internal(format!("stat {}: {e}", path.display())))?
@@ -227,7 +227,7 @@ impl Core {
match self.rt.block_on(photos.update_photos(&[update])) {
// As in `set_photo_favorite`: claim our own echo, so the tag we
// just set does not come back as a remote change.
Ok(_) => self.note_self_change(&new_uid),
Ok(_) => self.host.note_self_change(&new_uid),
Err(e) => {
warn!(name = candidate.name, error = %e, "cannot re-favorite re-dated photo")
}
@@ -287,9 +287,9 @@ impl Core {
state.last = None;
}
let core = self.clone();
let this = self.clone();
if let Err(error) = self.services.spawn_job("pdfs-redate", move || {
let outcome = core.redate_photos(dry_run, limit, range, cancel);
let outcome = this.redate_photos(dry_run, limit, range, cancel);
let mut state = REDATE.lock();
state.running = false;
state.cancel = None;
@@ -47,7 +47,7 @@ use tracing::{info, warn};
pub(crate) use pdfs_drive::digest::sha1_of;
use super::Core;
use super::Photos;
use crate::photos::can_make_thumbnail;
use crate::transfers::CountingReader;
@@ -468,7 +468,7 @@ fn read_entry<R>(
Ok(sink(&mut file))
}
impl Core {
impl Photos {
/// Copy archive entry `entry` into the thumbnail staging folder and return
/// its path. The caller removes it.
fn stage_takeout_entry(
@@ -611,7 +611,7 @@ impl Core {
));
}
let photos = self.photos();
let photos = self.photos_api();
if self
.rt
.block_on(photos.get_photos_root())
@@ -668,7 +668,7 @@ impl Core {
report: &Reporter,
) -> CoreResult<()> {
report.phase(ImportPhase::Checking, 0);
let photos = self.photos();
let photos = self.photos_api();
let names: Vec<String> = planned.iter().map(|p| p.photo.name.clone()).collect();
let collisions = self
.rt
@@ -919,7 +919,7 @@ impl Core {
report.step();
match done.result {
Ok(uid) => {
self.note_self_change(&uid);
self.host.note_self_change(&uid);
summary.uploaded += 1;
summary.bytes += done.photo.size;
if done.live {
@@ -954,7 +954,7 @@ impl Core {
tags: Vec<PhotoTag>,
main_uid: Option<NodeUid>,
) -> CoreResult<NodeUid> {
let photos = self.photos();
let photos = self.photos_api();
let guard = self.transfers.begin(
photo.name.clone(),
"",
@@ -1035,7 +1035,7 @@ impl Core {
tags_to_remove: Vec::new(),
})
.collect();
if let Err(e) = self.rt.block_on(self.photos().update_photos(&updates)) {
if let Err(e) = self.rt.block_on(self.photos_api().update_photos(&updates)) {
warn!(error = %e, "marking imported favorites failed");
}
}
@@ -1049,7 +1049,7 @@ impl Core {
summary: &mut ImportSummary,
report: &Reporter,
) -> CoreResult<()> {
let photos = self.photos();
let photos = self.photos_api();
// Existing albums by decrypted name, so a second import of the same
// export adds to the album it made the first time instead of a twin.
@@ -1152,14 +1152,14 @@ impl Core {
state.save();
}
let core = self.clone();
let this = self.clone();
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.
let job = core.transfers.begin_job("Importing Google Photos");
let job = this.transfers.begin_job("Importing Google Photos");
let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
core.import_takeout(&archives, dry_run, &cancel, &job)
this.import_takeout(&archives, dry_run, &cancel, &job)
}));
// A panic must not leave the import marked as running for the
// life of the daemon, refusing every later one.
@@ -1179,9 +1179,9 @@ impl Core {
}
drop(job);
if !dry_run {
core.log_activity(
this.host.log_activity(
ActivityKind::Upload,
"Google Photos import",
"Google Photos import".to_string(),
activity_line(&summary),
summary.complete(),
);
+76 -95
View File
@@ -4,14 +4,14 @@
use super::*;
impl Core {
impl Photos {
/// [`upload_thumbnails`] for a file about to upload, staging any RAW copy
/// under this cache. Blocking.
pub(crate) fn upload_thumbnails(&self, path: &Path, name: &str) -> Vec<Thumbnail> {
upload_thumbnails(path, name, self.cache.raw_thumbnail_staging_dir())
}
/// [`Core::upload_thumbnails`] on the blocking pool, for async callers.
/// [`Photos::upload_thumbnails`] on the blocking pool, for async callers.
pub(crate) async fn upload_thumbnails_async(
&self,
path: PathBuf,
@@ -26,7 +26,7 @@ impl Core {
/// Thumbnails for `uids`, served from the cache, fetched from the server for
/// whatever is missing, and — for the photos the server has no thumbnail for
/// at all — *generated locally* from the full file (see
/// [`Core::generate_thumbs`]). Requested on demand as tiles scroll into view,
/// [`Photos::generate_thumbs`]). Requested on demand as tiles scroll into view,
/// so a cold timeline paints immediately and only the photos actually on
/// screen cost a round-trip.
///
@@ -41,7 +41,7 @@ impl Core {
self.photo_thumbs_with(requested, true)
}
/// [`Core::photo_thumbs`], with local generation only when `generate` is
/// [`Photos::photo_thumbs`], with local generation only when `generate` is
/// set. Without it, a photo the server has no thumbnail for is left
/// without one rather than downloaded whole.
pub(crate) fn photo_thumbs_with(
@@ -117,7 +117,7 @@ impl Core {
if !want.is_empty() {
let mut missing = want.clone();
match self.rt.block_on(
self.photos()
self.photos_api()
.enumerate_thumbnails(&want, ThumbnailType::Thumbnail),
) {
Ok(thumbs) => {
@@ -154,7 +154,7 @@ impl Core {
}
}
let pending = self.photo_jobs.thumb_gen.lock();
let pending = self.jobs.thumb_gen.lock();
requested
.iter()
.zip(uids)
@@ -197,7 +197,7 @@ impl Core {
}
/// Thumbnails for image files shown by the regular file browser, Shared and
/// Trash pages. Unlike [`Core::photo_thumbs`], these nodes need not be in the
/// Trash pages. Unlike [`Photos::photo_thumbs`], these nodes need not be in the
/// Photos timeline: the request supplies each file's modification time as
/// the cache validity tag.
pub(crate) fn file_thumbs(
@@ -205,8 +205,8 @@ impl Core {
items: &[FileThumbRequest],
generation: u64,
) -> Option<Vec<PhotoThumb>> {
let current = generation != 0
&& self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation;
let current =
generation != 0 && self.jobs.file_thumb_generation.load(Ordering::SeqCst) == generation;
if !current {
return None;
}
@@ -238,7 +238,7 @@ impl Core {
.cached_thumbnail_path(uid, ttype, *modified)
.is_some()
|| self
.photo_jobs
.jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), *modified)
@@ -253,7 +253,7 @@ impl Core {
self.spawn_generate_thumbs(wanted, &tags, &names, ThumbJob::Files(generation));
}
let pending = self.photo_jobs.thumb_gen.lock();
let pending = self.jobs.thumb_gen.lock();
Some(
items
.iter()
@@ -279,14 +279,14 @@ impl Core {
pub(crate) fn reserve_file_thumb_generation(&self) -> u64 {
let next = |current| if current == u64::MAX { 1 } else { current + 1 };
let previous = self
.photo_jobs
.jobs
.file_thumb_generation
.try_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
Some(next(current))
})
.expect("generation update always succeeds");
let generation = next(previous);
self.photo_jobs.file_thumb_cancel.notify_waiters();
self.jobs.file_thumb_cancel.notify_waiters();
generation
}
@@ -295,11 +295,11 @@ impl Core {
/// recursive builds do not use this generation and continue normally.
pub(crate) fn cancel_file_thumbs(&self, generation: u64) {
let previous = self
.photo_jobs
.jobs
.file_thumb_generation
.fetch_max(generation, Ordering::SeqCst);
if generation > previous {
self.photo_jobs.file_thumb_cancel.notify_waiters();
self.jobs.file_thumb_cancel.notify_waiters();
}
}
@@ -314,7 +314,7 @@ impl Core {
job: ThumbJob,
) {
let fresh: Vec<NodeUid> = {
let mut inflight = self.photo_jobs.thumb_gen.lock();
let mut inflight = self.jobs.thumb_gen.lock();
uids.into_iter()
.filter(|uid| inflight.insert(uid.clone()))
.collect()
@@ -323,16 +323,16 @@ impl Core {
return;
}
let core = self.clone();
let this = self.clone();
let tags = tags.clone();
let names = names.clone();
// `generate_thumbs` blocks on the runtime itself, so it belongs on the
// blocking pool rather than on an async worker.
self.rt.spawn_blocking(move || {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
core.generate_thumbs(&fresh, &tags, &names, job)
this.generate_thumbs(&fresh, &tags, &names, job)
}));
let mut inflight = core.photo_jobs.thumb_gen.lock();
let mut inflight = this.jobs.thumb_gen.lock();
for uid in &fresh {
inflight.remove(uid);
}
@@ -354,13 +354,10 @@ impl Core {
pub(super) fn thumb_job_current(&self, job: ThumbJob) -> bool {
match job {
ThumbJob::Files(generation) => {
self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation
self.jobs.file_thumb_generation.load(Ordering::SeqCst) == generation
}
ThumbJob::Photos => true,
ThumbJob::Build => !self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst),
ThumbJob::Build => !self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst),
}
}
@@ -377,12 +374,12 @@ impl Core {
for chunk in uids.chunks(THUMB_GEN_CONCURRENCY) {
let mut set = tokio::task::JoinSet::new();
for uid in chunk {
let core = self.clone();
let this = self.clone();
let client = self.client.clone();
let uid = uid.clone();
let name = names.get(&uid.to_string()).cloned().unwrap_or_default();
set.spawn(async move {
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
let video = is_video_name(&name);
@@ -397,19 +394,19 @@ impl Core {
// One shared permit pool bounds all thumbnail batches,
// rather than multiplying the limit by every control
// request the GUI happens to have in flight.
let acquire = core.photo_jobs.thumb_gen_budget.clone().acquire_owned();
let acquire = this.jobs.thumb_gen_budget.clone().acquire_owned();
tokio::pin!(acquire);
let _permit = match job {
ThumbJob::Files(_) => loop {
tokio::select! {
permit = &mut acquire => break permit.ok(),
_ = core.photo_jobs.file_thumb_cancel.notified() => {
if !core.thumb_job_current(job) {
_ = this.jobs.file_thumb_cancel.notified() => {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
@@ -418,13 +415,13 @@ impl Core {
ThumbJob::Build => loop {
tokio::select! {
permit = &mut acquire => break permit.ok(),
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
if !core.thumb_job_current(job) {
_ = this.jobs.thumbnail_build_cancel.notified() => {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
@@ -435,12 +432,12 @@ impl Core {
let Some(_permit) = _permit else {
return (uid, ThumbAttempt::Unavailable);
};
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
let download_uid = uid.clone();
let drive = core.drive.clone();
let drive = this.drive.clone();
let audio_name = name.clone();
let download = async move {
// Photos asked the server in one batch already. A
@@ -478,13 +475,13 @@ impl Core {
ThumbJob::Files(_) => loop {
tokio::select! {
result = &mut download => break Some(result),
_ = core.photo_jobs.file_thumb_cancel.notified() => {
if !core.thumb_job_current(job) {
_ = this.jobs.file_thumb_cancel.notified() => {
if !this.thumb_job_current(job) {
break None;
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
break None;
}
}
@@ -493,13 +490,13 @@ impl Core {
ThumbJob::Build => loop {
tokio::select! {
result = &mut download => break Some(result),
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
if !core.thumb_job_current(job) {
_ = this.jobs.thumbnail_build_cancel.notified() => {
if !this.thumb_job_current(job) {
break None;
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
break None;
}
}
@@ -517,12 +514,12 @@ impl Core {
return (uid, ThumbAttempt::Unavailable);
}
};
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
// Decoding + scaling a 20 MP JPEG is CPU-bound and would
// stall the runtime's worker; hand it to the blocking pool.
let staging_dir = core.cache.raw_thumbnail_staging_dir().to_path_buf();
let staging_dir = this.cache.raw_thumbnail_staging_dir().to_path_buf();
let staging = staging_dir.clone();
let made = tokio::task::spawn_blocking(move || match fetched {
Fetched::Audio(sample) => {
@@ -547,12 +544,12 @@ impl Core {
// A song without a picture of its own shows its
// folder's cover.
let made = match made {
ScaleAttempt::Undecodable if audio && core.thumb_job_current(job) => {
core.folder_cover_thumbnail(&uid, staging).await
ScaleAttempt::Undecodable if audio && this.thumb_job_current(job) => {
this.folder_cover_thumbnail(&uid, staging).await
}
made => made,
};
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
match made {
@@ -583,7 +580,7 @@ impl Core {
match self.cache.store_thumbnail(&uid, ttype, tag, &thumb.bytes) {
Ok(()) => {
summary.made += 1;
self.photo_jobs
self.jobs
.thumbnail_misses
.lock()
.forget_local(&(uid.clone(), ttype));
@@ -600,7 +597,7 @@ impl Core {
ThumbAttempt::Undecodable => {
summary.undecodable += 1;
if let Some(&tag) = tags.get(&uid.to_string()) {
self.photo_jobs
self.jobs
.thumbnail_misses
.lock()
.remember_local((uid.clone(), ttype), tag);
@@ -698,7 +695,7 @@ impl Core {
}
pub(crate) fn thumbnail_build_status(&self) -> ThumbnailBuildStatus {
self.photo_jobs.thumbnail_build.lock().clone()
self.jobs.thumbnail_build.lock().clone()
}
/// Start one recursive local-thumbnail build. A request for the same root
@@ -707,11 +704,11 @@ impl Core {
pub(crate) fn start_thumbnail_build(&self, root: PathBuf) -> CoreResult<ThumbnailBuildStatus> {
let path = root.to_string_lossy().into_owned();
let status = {
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
if !thumbnail_build_may_start(&status, &path)? {
return Ok(status.clone());
}
self.photo_jobs
self.jobs
.thumbnail_build_cancelled
.store(false, Ordering::SeqCst);
*status = ThumbnailBuildStatus {
@@ -727,18 +724,18 @@ impl Core {
status.clone()
};
let core = self.clone();
let this = self.clone();
self.rt.spawn_blocking(move || {
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
core.run_thumbnail_build(root)
this.run_thumbnail_build(root)
}))
.is_err()
{
let mut status = core.photo_jobs.thumbnail_build.lock();
let mut status = this.jobs.thumbnail_build.lock();
status.running = false;
status.scanning = false;
status.message = Some("Thumbnail generation stopped unexpectedly".to_string());
core.photo_jobs
this.jobs
.thumbnail_build_cancelled
.store(false, Ordering::SeqCst);
warn!(path = %status.path, "recursive thumbnail build panicked");
@@ -749,25 +746,25 @@ impl Core {
pub(crate) fn cancel_thumbnail_build(&self) -> ThumbnailBuildStatus {
let (status, cancelled) = {
let status = self.photo_jobs.thumbnail_build.lock();
let status = self.jobs.thumbnail_build.lock();
let cancelled = status.running;
if cancelled {
self.photo_jobs
self.jobs
.thumbnail_build_cancelled
.store(true, Ordering::SeqCst);
}
(status.clone(), cancelled)
};
if cancelled {
self.photo_jobs.thumbnail_build_cancel.notify_waiters();
self.jobs.thumbnail_build_cancel.notify_waiters();
}
status
}
pub(crate) fn finish_thumbnail_build(&self) {
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
let cancelled = self
.photo_jobs
.jobs
.thumbnail_build_cancelled
.swap(false, Ordering::SeqCst);
status.running = false;
@@ -791,23 +788,19 @@ impl Core {
let mut seen_images = HashSet::new();
while let Some(folder) = folders.pop() {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
self.finish_thumbnail_build();
return;
}
let listing = self.list_dir(&folder);
let listing = self.host.list_dir(&folder);
{
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
status.folders_scanned += 1;
}
let entries = match listing {
Ok(entries) => entries,
Err(error) => {
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
if status.message.is_none() {
status.message = Some(format!(
"Some folders could not be read ({}: {error})",
@@ -839,18 +832,14 @@ impl Core {
}
}
}
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
status.images_found += found_here;
status.completed += invalid_here;
status.failed += invalid_here;
}
self.photo_jobs.thumbnail_build.lock().scanning = false;
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.jobs.thumbnail_build.lock().scanning = false;
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
self.finish_thumbnail_build();
return;
}
@@ -862,14 +851,14 @@ impl Core {
.cached_thumbnail_path(&uid, ttype, modified)
.is_some()
{
self.photo_jobs.thumbnail_build.lock().completed += 1;
self.jobs.thumbnail_build.lock().completed += 1;
} else if self
.photo_jobs
.jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), modified)
{
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
} else {
@@ -878,11 +867,7 @@ impl Core {
}
for chunk in todo.chunks(THUMB_BUILD_CHUNK) {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
self.finish_thumbnail_build();
return;
}
@@ -895,11 +880,7 @@ impl Core {
// than downloading the full image twice.
let waiting_since = Instant::now();
loop {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
self.finish_thumbnail_build();
return;
}
@@ -908,28 +889,28 @@ impl Core {
.cached_thumbnail_path(uid, ttype, *modified)
.is_some()
{
self.photo_jobs.thumbnail_build.lock().completed += 1;
self.jobs.thumbnail_build.lock().completed += 1;
break;
}
if self
.photo_jobs
.jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), *modified)
{
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
break;
}
if self.photo_jobs.thumb_gen.lock().insert(uid.clone()) {
if self.jobs.thumb_gen.lock().insert(uid.clone()) {
tags.insert(uid.to_string(), *modified);
names.insert(uid.to_string(), name.clone());
claimed.push(uid.clone());
break;
}
if waiting_since.elapsed() >= THUMB_BUILD_CLAIM_TIMEOUT {
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
if status.message.is_none() {
@@ -950,12 +931,12 @@ impl Core {
self.generate_thumbs(&claimed, &tags, &names, ThumbJob::Build)
}));
{
let mut inflight = self.photo_jobs.thumb_gen.lock();
let mut inflight = self.jobs.thumb_gen.lock();
for uid in &claimed {
inflight.remove(uid);
}
}
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
match result {
Ok(summary) => {
status.completed += summary.processed();
+23 -136
View File
@@ -3,7 +3,7 @@
use super::*;
impl Core {
impl Photos {
#[allow(clippy::too_many_arguments)]
pub(crate) fn photos_timeline(
&self,
@@ -90,7 +90,7 @@ impl Core {
/// The SDK reports one outcome per photo rather than failing the call, so the
/// single outcome is unwrapped back into this request's result.
pub(crate) fn set_photo_favorite(&self, uid: &NodeUid, favorite: bool) -> CoreResult<()> {
let photos = self.photos();
let photos = self.photos_api();
let update = PhotoTagsUpdate {
node_uid: uid.clone(),
tags_to_add: if favorite {
@@ -114,7 +114,7 @@ impl Core {
// `NodeUpdated`, which is indistinguishable from the same photo being
// favorited on a phone. Claim the echo, or the gallery pays for a
// resolve of a node whose one changed field is already stored below.
self.note_self_change(uid);
self.host.note_self_change(uid);
self.db
.photos_set_favorite(&uid.to_string(), favorite)
.map_err(CoreError::from)?;
@@ -142,7 +142,7 @@ impl Core {
let sets = self.db.photo_similar().map_err(CoreError::from)?;
let (done, total) = self.db.similar_progress().map_err(CoreError::from)?;
let hashing = self
.photo_jobs
.jobs
.similar_hashing
.load(Ordering::SeqCst)
.then_some(MappingProgress { done, total });
@@ -155,23 +155,19 @@ impl Core {
}
pub(crate) fn spawn_similar_hashing(&self) {
if self.photo_jobs.similar_hashing.swap(true, Ordering::SeqCst) {
if self.jobs.similar_hashing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
let this = self.clone();
let spawned = self.services.spawn_job("pdfs-similar", move || {
if let Err(e) = core.hash_similar() {
if let Err(e) = this.hash_similar() {
warn!(error = %e, "similar-photo hashing failed");
}
core.photo_jobs
.similar_hashing
.store(false, Ordering::SeqCst);
this.jobs.similar_hashing.store(false, Ordering::SeqCst);
});
if let Err(e) = spawned {
warn!(error = %e, "could not start similar-photo hashing");
self.photo_jobs
.similar_hashing
.store(false, Ordering::SeqCst);
self.jobs.similar_hashing.store(false, Ordering::SeqCst);
}
}
@@ -320,100 +316,6 @@ impl Core {
out
}
/// Mutation admission for a photo, which [`Core::require_uid_writable`]
/// cannot answer on its own.
///
/// Photos live on the photo volume, and that volume is not part of the FUSE
/// tree: a photo has no `nodes` row, so every authority comes back
/// [`WriteAuthority::Unknown`] and the plain check refuses the whole
/// library. Membership of our own timeline is the authority that does exist
/// here — the timeline is enumerated from our photo share, so a uid in it is
/// ours to trash. Anything else (an album photo on someone else's volume)
/// still fails closed.
pub(crate) fn require_photo_writable(&self, uid: &NodeUid) -> Result<(), fuser::Errno> {
match self.uid_write_authority(uid) {
WriteAuthority::Writable => Ok(()),
WriteAuthority::Denied => Err(fuser::Errno::EACCES),
WriteAuthority::Unknown => {
let key = uid.to_string();
let known = self
.db
.photos_by_uid(std::slice::from_ref(&key))
.map(|rows| !rows.is_empty())
.unwrap_or(false);
if known {
Ok(())
} else {
Err(fuser::Errno::EACCES)
}
}
}
}
/// Trash photos by uid, and forget them locally.
///
/// The gallery is not part of the FUSE mount, so this is the photos-side
/// counterpart of [`Core::delete`]: same destination (Proton trash, so the
/// Trash page can restore them), addressed by uid because that is all a tile
/// has.
///
/// The server answers per node, and so does this: a batch where one photo
/// fails still removes the ones that went, and the caller is told which is
/// which. Only what actually left the server is forgotten locally.
///
/// A photo that is one file of a group takes its whole group with it. The
/// gallery shows a RAW+JPEG shot as one tile, so deleting that tile has to
/// delete the shot — leaving the RAW behind would put the photo back on the
/// Raw tab and nowhere else. `files_only` turns that off, for removing
/// one copy of a shot that is stored twice.
pub(crate) fn trash_photos(
&self,
uids: &[NodeUid],
files_only: bool,
) -> CoreResult<TrashOutcome> {
if uids.is_empty() {
return Ok((Vec::new(), Vec::new()));
}
let expanded;
let uids = if files_only {
uids
} else {
expanded = self.expand_photo_groups(uids);
&expanded
};
for uid in uids {
self.require_photo_writable(uid)
.map_err(|errno| self.errno_error(errno, "trash access"))?;
}
let outcomes = self
.rt
.block_on(self.drive.trash_nodes(uids))
.map_err(|e| CoreError::from_api(&e, "trash"))?;
let (trashed, failed) = pdfs_core::batch::split(outcomes);
let trashed: Vec<String> = trashed.iter().map(|uid| uid.to_string()).collect();
for uid in &trashed {
if let Some(parsed) = parse_uid(uid) {
self.cache.evict(&parsed);
self.evict_reader(&parsed);
}
}
// The timeline is served from the database, so removing the rows is what
// makes the photos disappear now rather than at the next refresh.
if let Err(error) = self.db.photos_delete(&trashed) {
warn!(%error, "trashed photos could not be removed from the timeline");
}
self.invalidate_photos();
self.invalidate_albums();
self.invalidate_trash();
let failed = failed
.into_iter()
.map(|(uid, error)| (uid.to_string(), error.to_string()))
.collect();
Ok((trashed, failed))
}
/// Commit the lightweight listing before resolving pending nodes. The
/// feed generation fences both commits against events received in flight.
pub(crate) async fn refresh_timeline(&self) -> CoreResult<bool> {
@@ -422,7 +324,7 @@ impl Core {
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos();
let photos = self.photos_api();
if self
.db
.state_i64(PHOTOS_SYNCED_MS)
@@ -468,7 +370,7 @@ impl Core {
let total = self.db.photos_count().map_err(CoreError::from)?;
let skipped = total.saturating_sub(pending.len());
let mut resolved = 0;
let progress = ProgressGuard(&self.photo_jobs.timeline_progress);
let progress = ProgressGuard(&self.jobs.timeline_progress);
for (index, chunk) in pending.chunks(TIMELINE_ENRICH_CHUNK).enumerate() {
if self.shutdown.is_stopping() {
break;
@@ -537,12 +439,8 @@ impl Core {
/// whole library at once, sharing the session's rate limit and taking
/// minutes. Returns whether the account has a photos library.
pub(crate) fn refresh_timeline_joined(&self) -> CoreResult<bool> {
if self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
{
while self.photo_jobs.timeline_refreshing.load(Ordering::SeqCst)
if self.jobs.timeline_refreshing.swap(true, Ordering::SeqCst) {
while self.jobs.timeline_refreshing.load(Ordering::SeqCst)
&& !self.shutdown.is_stopping()
{
std::thread::sleep(std::time::Duration::from_millis(200));
@@ -555,18 +453,13 @@ impl Core {
.state_i64(PHOTOS_SYNCED_MS)
.map_err(CoreError::from)?
.is_some()
|| self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
|| self.jobs.timeline_refreshing.swap(true, Ordering::SeqCst)
{
return Ok(self.db.state_i64(PHOTOS_AVAILABLE).ok().flatten() != Some(0));
}
}
let refreshed = self.rt.block_on(self.refresh_timeline());
self.photo_jobs
.timeline_refreshing
.store(false, Ordering::SeqCst);
self.jobs.timeline_refreshing.store(false, Ordering::SeqCst);
if refreshed.is_ok() {
self.events.publish(&[Topic::Photos]);
}
@@ -574,24 +467,18 @@ impl Core {
}
pub(crate) fn spawn_timeline_refresh(&self) {
if self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
{
if self.jobs.timeline_refreshing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
let this = self.clone();
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);
let refreshed = this.refresh_timeline().await;
this.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]),
Ok(_) => this.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background timeline refresh failed"),
}
});
@@ -600,7 +487,7 @@ impl Core {
/// How far the running timeline refresh has got reading photo metadata, or
/// `None` when no refresh is reading any.
pub(crate) fn timeline_progress(&self) -> Option<MappingProgress> {
self.photo_jobs
self.jobs
.timeline_progress
.lock()
.map(|(done, total)| MappingProgress { done, total })
@@ -609,13 +496,13 @@ impl Core {
/// Whether a timeline refresh is running. A front-end that asked for one
/// watches this to know when the new timeline is worth re-reading.
pub(crate) fn timeline_refreshing(&self) -> bool {
self.photo_jobs.timeline_refreshing.load(Ordering::SeqCst)
self.jobs.timeline_refreshing.load(Ordering::SeqCst)
}
/// Download a photo's full content into the content cache, returning its
/// on-disk path (served from cache when a fresh blob already exists).
pub(crate) fn open_photo(&self, uid: &NodeUid) -> CoreResult<PathBuf> {
let photos = self.photos();
let photos = self.photos_api();
let node = self
.rt
.block_on(photos.get_node(uid))
+101
View File
@@ -0,0 +1,101 @@
//! Trashing photos by uid. This stays on [`Core`] rather than [`Photos`]: it
//! checks write authority against the tree, drops open readers and clears the
//! trash listing, all of which belong to the filesystem side.
use super::*;
impl Core {
/// Mutation admission for a photo, which [`Core::require_uid_writable`]
/// cannot answer on its own.
///
/// Photos live on the photo volume, and that volume is not part of the FUSE
/// tree: a photo has no `nodes` row, so every authority comes back
/// [`WriteAuthority::Unknown`] and the plain check refuses the whole
/// library. Membership of our own timeline is the authority that does exist
/// here — the timeline is enumerated from our photo share, so a uid in it is
/// ours to trash. Anything else (an album photo on someone else's volume)
/// still fails closed.
pub(crate) fn require_photo_writable(&self, uid: &NodeUid) -> Result<(), fuser::Errno> {
match self.uid_write_authority(uid) {
WriteAuthority::Writable => Ok(()),
WriteAuthority::Denied => Err(fuser::Errno::EACCES),
WriteAuthority::Unknown => {
let key = uid.to_string();
let known = self
.db
.photos_by_uid(std::slice::from_ref(&key))
.map(|rows| !rows.is_empty())
.unwrap_or(false);
if known {
Ok(())
} else {
Err(fuser::Errno::EACCES)
}
}
}
}
/// Trash photos by uid, and forget them locally.
///
/// The gallery is not part of the FUSE mount, so this is the photos-side
/// counterpart of [`Core::delete`]: same destination (Proton trash, so the
/// Trash page can restore them), addressed by uid because that is all a tile
/// has.
///
/// The server answers per node, and so does this: a batch where one photo
/// fails still removes the ones that went, and the caller is told which is
/// which. Only what actually left the server is forgotten locally.
///
/// A photo that is one file of a group takes its whole group with it. The
/// gallery shows a RAW+JPEG shot as one tile, so deleting that tile has to
/// delete the shot — leaving the RAW behind would put the photo back on the
/// Raw tab and nowhere else. `files_only` turns that off, for removing
/// one copy of a shot that is stored twice.
pub(crate) fn trash_photos(
&self,
uids: &[NodeUid],
files_only: bool,
) -> CoreResult<TrashOutcome> {
if uids.is_empty() {
return Ok((Vec::new(), Vec::new()));
}
let expanded;
let uids = if files_only {
uids
} else {
expanded = self.photos().expand_photo_groups(uids);
&expanded
};
for uid in uids {
self.require_photo_writable(uid)
.map_err(|errno| self.errno_error(errno, "trash access"))?;
}
let outcomes = self
.rt
.block_on(self.drive.trash_nodes(uids))
.map_err(|e| CoreError::from_api(&e, "trash"))?;
let (trashed, failed) = pdfs_core::batch::split(outcomes);
let trashed: Vec<String> = trashed.iter().map(|uid| uid.to_string()).collect();
for uid in &trashed {
if let Some(parsed) = parse_uid(uid) {
self.cache.evict(&parsed);
self.evict_reader(&parsed);
}
}
// The timeline is served from the database, so removing the rows is what
// makes the photos disappear now rather than at the next refresh.
if let Err(error) = self.db.photos_delete(&trashed) {
warn!(%error, "trashed photos could not be removed from the timeline");
}
self.invalidate_photos();
self.photos().invalidate_albums();
self.invalidate_trash();
let failed = failed
.into_iter()
.map(|(uid, error)| (uid.to_string(), error.to_string()))
.collect();
Ok((trashed, failed))
}
}
+160 -120
View File
@@ -21,8 +21,13 @@ use pdfs_core::{CoreError, CoreResult};
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::{info, warn};
use super::devices::Devices;
use super::drive::DriveApi;
use super::sync;
use super::{Core, now_secs, parse_uid, this_hostname};
use pdfs_core::lifecycle::ServiceBoard;
use pdfs_store::db::Db;
use std::sync::Arc;
/// Coalescing flags for background profile saves.
///
@@ -40,7 +45,146 @@ fn save_state() -> &'static (AtomicBool, AtomicBool) {
SAVE_STATE.get_or_init(|| (AtomicBool::new(false), AtomicBool::new(false)))
}
/// The backup of this machine's arrangement on Drive: which folders sync where
/// and in which mode. It writes the profile and reads the ones other machines
/// wrote, to offer their folders for restore.
///
/// It needs nothing from the filesystem. [`Core::profile`] builds one on
/// demand. A clone shares everything, which is how a save moves onto a
/// background job.
#[derive(Clone)]
pub(crate) struct ProfileBackup {
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
db: Arc<Db>,
services: ServiceBoard,
devices: Devices,
}
impl Core {
/// The profile backup.
pub(crate) fn profile(&self) -> ProfileBackup {
ProfileBackup {
drive: self.drive.clone(),
rt: self.rt.clone(),
db: self.db.clone(),
services: self.services.clone(),
devices: self.devices(),
}
}
/// Attach remote device folders to local paths and let the sync engine fill
/// them in.
///
/// The download is not written here: a new sync-folder row starts with an
/// empty baseline, and an empty baseline against an empty local directory
/// and a populated remote already classifies as "download everything". The
/// restore is therefore just bookkeeping plus a `Reconcile`, and it reuses
/// the engine's conflict handling for the case where the local directory
/// turns out not to be empty after all.
pub(crate) fn restore_sync_folders(
&self,
items: &[pdfs_core::control::RestoreItem],
device: Option<&str>,
) -> CoreResult<RestoreOutcome> {
let _registration = super::devices::SYNC_ROOT_REGISTRATION.lock();
if items.is_empty() {
return Err(CoreError::invalid("nothing to restore"));
}
let device = self.devices().restore_source(device)?;
let existing = self
.db
.sync_folder_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
// A caller must not smuggle a My files root into a device mapping,
// where destructive device-only operations would otherwise be allowed.
let device_root = super::parse_uid(&device.root_uid)
.ok_or_else(|| CoreError::internal("invalid device root"))?;
let children = self.devices().device_root_nodes(&device_root)?;
let reserved = crate::devices::sync_root_reserved();
let mut roots: Vec<PathBuf> = existing
.iter()
.map(|f| PathBuf::from(&f.local_path))
.collect();
let mut restored = 0usize;
let mut skipped: Vec<String> = Vec::new();
for item in items {
if !children.iter().any(|node| {
node.uid.to_string() == item.remote_uid
&& node.is_folder()
&& !node.trashed
&& node.name != PROFILE_DIR_NAME
}) {
skipped.push(format!(
"{}: not a folder under this device",
item.local_path
));
continue;
}
// The path is proposed from the profile another machine wrote, and
// may hold a folder name from Drive: checked like any new root.
let local = match pdfs_core::syncroot::resolve(Path::new(&item.local_path)) {
Ok(local) => local,
Err(e) => {
skipped.push(format!("{}: {e}", item.local_path));
continue;
}
};
if existing.iter().any(|f| f.remote_uid == item.remote_uid) {
skipped.push(format!("{}: already synced", item.local_path));
continue;
}
if let Some(problem) = pdfs_core::syncroot::problem(&local, &roots, &reserved) {
skipped.push(format!("{}: {problem}", item.local_path));
continue;
}
if let Err(e) = std::fs::create_dir_all(&local) {
skipped.push(format!("{}: {e}", item.local_path));
continue;
}
let mode = match restore_mode(&item.mode) {
Some(mode) => mode,
None => {
skipped.push(format!("{}: unknown mode {}", item.local_path, item.mode));
continue;
}
};
let id = match self.db.sync_folder_add(
&local.to_string_lossy(),
&item.remote_uid,
&device.share_id,
) {
Ok(id) => id,
Err(e) => {
// The folders restored before this one still need their
// watches.
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
return Err(CoreError::internal(format!("db: {e:?}")));
}
};
// `ondemand` is applied through the normal request path, which
// mounts the FUSE session and handles the folder being busy — the
// restore does not get its own copy of that logic.
if mode == MountMode::OnDemand {
let _ = self.request_sync_folder_mode(id, "ondemand");
}
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
roots.push(local);
restored += 1;
}
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
// The reply is gone once the app has shown it; the log keeps why.
for reason in &skipped {
info!(reason, "restore skipped a folder");
}
info!(restored, skipped = skipped.len(), "restore complete");
Ok(RestoreOutcome { restored, skipped })
}
}
impl ProfileBackup {
/// Note that the arrangement this machine's profile describes has changed,
/// and upload a fresh profile in the background.
///
@@ -54,11 +198,11 @@ impl Core {
if saving.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
let this = self.clone();
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() {
if let Err(e) = this.save_profile() {
warn!(error = %e.message, "profile backup failed");
break;
}
@@ -142,7 +286,7 @@ impl Core {
}
/// Snapshot the local arrangement into a [`Profile`].
fn build_profile(&self, device_uid: &str, machine_id: &str) -> CoreResult<Profile> {
pub(crate) fn build_profile(&self, device_uid: &str, machine_id: &str) -> CoreResult<Profile> {
let folders = profile_folders(
self.db
.sync_folder_list()
@@ -180,7 +324,7 @@ impl Core {
///
/// The sibling of `find_device_child_folder`; kept separate because a folder
/// named `profile.json` must not be mistaken for the profile.
fn find_device_child_file(
pub(crate) fn find_device_child_file(
&self,
parent_uid: &NodeUid,
name: &str,
@@ -204,7 +348,7 @@ impl Core {
/// The untrashed files directly under `parent_uid` whose name passes
/// `keep`.
fn device_child_files(
pub(crate) fn device_child_files(
&self,
parent_uid: &NodeUid,
keep: impl Fn(&str) -> bool,
@@ -233,8 +377,11 @@ impl Core {
/// Reused by stable identity rather than recreated: a second folder of the
/// same name would split the profile across two documents, and the restore
/// would have no way to tell which is current.
fn ensure_profile_dir(&self, root_uid: &NodeUid) -> CoreResult<NodeUid> {
if let Some(uid) = self.find_device_child_folder(root_uid, PROFILE_DIR_NAME)? {
pub(crate) fn ensure_profile_dir(&self, root_uid: &NodeUid) -> CoreResult<NodeUid> {
if let Some(uid) = self
.devices
.find_device_child_folder(root_uid, PROFILE_DIR_NAME)?
{
return Ok(uid);
}
let uid = self
@@ -258,8 +405,11 @@ impl Core {
/// is left alone rather than trashed, so an older client on another
/// machine keeps working. A profile that cannot be read is left out and
/// logged; the others still count.
fn load_profiles(&self, root_uid: &NodeUid) -> CoreResult<Vec<Profile>> {
let mut uids = match self.find_device_child_folder(root_uid, PROFILE_DIR_NAME)? {
pub(crate) fn load_profiles(&self, root_uid: &NodeUid) -> CoreResult<Vec<Profile>> {
let mut uids = match self
.devices
.find_device_child_folder(root_uid, PROFILE_DIR_NAME)?
{
Some(dir_uid) => self.device_child_files(&dir_uid, is_profile_file_name)?,
None => Vec::new(),
};
@@ -301,7 +451,7 @@ impl Core {
&self,
device: Option<&str>,
) -> CoreResult<Vec<RestorableFolder>> {
let device = self.restore_source(device)?;
let device = self.devices.restore_source(device)?;
let root_uid = parse_uid(&device.root_uid).ok_or_else(|| {
CoreError::internal(format!("bad device root uid: {}", device.root_uid))
})?;
@@ -368,116 +518,6 @@ impl Core {
})
.collect())
}
/// Attach remote device folders to local paths and let the sync engine fill
/// them in.
///
/// The download is not written here: a new sync-folder row starts with an
/// empty baseline, and an empty baseline against an empty local directory
/// and a populated remote already classifies as "download everything". The
/// restore is therefore just bookkeeping plus a `Reconcile`, and it reuses
/// the engine's conflict handling for the case where the local directory
/// turns out not to be empty after all.
pub(crate) fn restore_sync_folders(
&self,
items: &[pdfs_core::control::RestoreItem],
device: Option<&str>,
) -> CoreResult<RestoreOutcome> {
let _registration = super::devices::SYNC_ROOT_REGISTRATION.lock();
if items.is_empty() {
return Err(CoreError::invalid("nothing to restore"));
}
let device = self.restore_source(device)?;
let existing = self
.db
.sync_folder_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
// A caller must not smuggle a My files root into a device mapping,
// where destructive device-only operations would otherwise be allowed.
let device_root = super::parse_uid(&device.root_uid)
.ok_or_else(|| CoreError::internal("invalid device root"))?;
let children = self.device_root_nodes(&device_root)?;
let reserved = crate::devices::sync_root_reserved();
let mut roots: Vec<PathBuf> = existing
.iter()
.map(|f| PathBuf::from(&f.local_path))
.collect();
let mut restored = 0usize;
let mut skipped: Vec<String> = Vec::new();
for item in items {
if !children.iter().any(|node| {
node.uid.to_string() == item.remote_uid
&& node.is_folder()
&& !node.trashed
&& node.name != PROFILE_DIR_NAME
}) {
skipped.push(format!(
"{}: not a folder under this device",
item.local_path
));
continue;
}
// The path is proposed from the profile another machine wrote, and
// may hold a folder name from Drive: checked like any new root.
let local = match pdfs_core::syncroot::resolve(Path::new(&item.local_path)) {
Ok(local) => local,
Err(e) => {
skipped.push(format!("{}: {e}", item.local_path));
continue;
}
};
if existing.iter().any(|f| f.remote_uid == item.remote_uid) {
skipped.push(format!("{}: already synced", item.local_path));
continue;
}
if let Some(problem) = pdfs_core::syncroot::problem(&local, &roots, &reserved) {
skipped.push(format!("{}: {problem}", item.local_path));
continue;
}
if let Err(e) = std::fs::create_dir_all(&local) {
skipped.push(format!("{}: {e}", item.local_path));
continue;
}
let mode = match restore_mode(&item.mode) {
Some(mode) => mode,
None => {
skipped.push(format!("{}: unknown mode {}", item.local_path, item.mode));
continue;
}
};
let id = match self.db.sync_folder_add(
&local.to_string_lossy(),
&item.remote_uid,
&device.share_id,
) {
Ok(id) => id,
Err(e) => {
// The folders restored before this one still need their
// watches.
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
return Err(CoreError::internal(format!("db: {e:?}")));
}
};
// `ondemand` is applied through the normal request path, which
// mounts the FUSE session and handles the folder being busy — the
// restore does not get its own copy of that logic.
if mode == MountMode::OnDemand {
let _ = self.request_sync_folder_mode(id, "ondemand");
}
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
roots.push(local);
restored += 1;
}
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
// The reply is gone once the app has shown it; the log keeps why.
for reason in &skipped {
info!(reason, "restore skipped a folder");
}
info!(restored, skipped = skipped.len(), "restore complete");
Ok(RestoreOutcome { restored, skipped })
}
}
/// Only device backups belong in the device's cross-machine profile.
+40 -5
View File
@@ -101,6 +101,41 @@ impl Core {
info!(nodes = st.entries.len(), "hydrated metadata cache from db");
}
/// Startup recovery of the queue, with this daemon as its host.
pub(crate) fn recovery(&self) -> Recovery {
Recovery {
db: self.db.clone(),
cache: self.cache.clone(),
writes: self.writes.clone(),
host: Arc::new(self.clone()),
}
}
}
/// What recovery needs from the rest of the daemon.
pub(crate) trait RecoveryHost: Send + Sync {
/// Queue a write recovered from a blob fsynced before a stop, as if its
/// handle had just been released.
fn queue_recovered(&self, uid: &NodeUid, blob: &Path, meta: StagedWrite) -> Result<(), Errno>;
}
impl RecoveryHost for Core {
fn queue_recovered(&self, uid: &NodeUid, blob: &Path, meta: StagedWrite) -> Result<(), Errno> {
self.enqueue_staged_write(uid, 0, blob, meta)
}
}
/// Rebuilds the queue from the database and the staging area after a
/// restart. Holds the database, the content cache and the write-back's state;
/// queueing a recovered write goes through [`RecoveryHost`].
pub(crate) struct Recovery {
db: Arc<Db>,
cache: Arc<ContentCache>,
writes: writes::WriteState,
host: Arc<dyn RecoveryHost>,
}
impl Recovery {
/// Rebuild the in-memory pending map from the `pending_op` table on mount.
///
/// A queued write survives a restart — that is the point of persisting it —
@@ -109,7 +144,7 @@ impl Core {
///
/// A row whose blob has gone missing is dropped: there is nothing left to
/// upload, and keeping it would fail forever.
pub(super) fn hydrate_pending(&self) {
pub(crate) fn hydrate_pending(&self) {
let ops = match self.db.pending_ops() {
Ok(ops) => ops,
Err(e) => {
@@ -182,7 +217,7 @@ impl Core {
/// `local~` placeholder whose create is gone) is left in place and named in
/// the log: unexplained bytes are never evidence that user data is
/// disposable.
pub(super) fn reconcile_staging(&self) {
pub(crate) fn reconcile_staging(&self) {
let staged = self.cache.staged_writes();
if staged.is_empty() {
return;
@@ -314,7 +349,7 @@ impl Core {
/// Failure is per-write and never fatal: a node that no longer exists, or an
/// op that cannot be queued, leaves its blob in `recovery/` for the next run
/// (and for a human) instead of taking the mount down.
pub(super) fn recover_fsynced_writes(&self) {
pub(crate) fn recover_fsynced_writes(&self) {
let recovered = self.cache.recovered_writes();
if recovered.is_empty() {
return;
@@ -338,7 +373,7 @@ impl Core {
// size, and nothing is interned this early — `hydrate` reads the
// size back off `pending` when the node is first looked up, so 0
// (no such inode) is correct rather than merely tolerable.
match self.enqueue_staged_write(&uid, 0, &blob, meta) {
match self.host.queue_recovered(&uid, &blob, meta) {
Ok(()) => {
self.cache.discard_recovered(&blob);
queued += 1;
@@ -371,7 +406,7 @@ impl Core {
/// content is unrecoverable and nothing will ever mint it a real uid, so
/// leaving the row would strand a file in the tree that can be listed but
/// never read and never uploaded.
pub(super) fn drop_unrecoverable_op(&self, op: &PendingOp, uid: &NodeUid) {
fn drop_unrecoverable_op(&self, op: &PendingOp, uid: &NodeUid) {
let _ = self.db.delete_op(op.id);
if is_local_uid(uid) {
error!(%uid, name = op.name.as_deref().unwrap_or("?"),
+98 -125
View File
@@ -16,7 +16,7 @@
//! file rather than trying to describe the new one. The next read repopulates
//! from whatever is live by then.
//! - **The active revision cannot be deleted**, and the server — not this code —
//! is what enforces that. [`Core::delete_revision_for_uid`] refuses locally
//! is what enforces that. [`Revisions::delete`] refuses locally
//! too, so the user gets a sentence instead of an API code.
use std::path::Path;
@@ -27,7 +27,12 @@ use proton_drive_rs::Revision;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::info;
use std::sync::Arc;
use proton_drive_rs::ProtonDriveClient;
use super::Core;
use crate::drive::DriveApi;
/// A [`Revision`] as the control protocol reports it.
fn revision_info(revision: Revision) -> RevisionInfo {
@@ -45,70 +50,37 @@ fn revision_info(revision: Revision) -> RevisionInfo {
}
}
impl Core {
/// The version history of the file at mountpoint-relative `rel`.
pub(crate) fn list_revisions(&self, rel: &Path) -> CoreResult<Vec<RevisionInfo>> {
let (_ino, uid) = self.resolve(rel)?;
self.list_revisions_for_uid(&uid)
}
/// A file's revisions on Drive. Every method takes a node already resolved to
/// its uid, and the name the activity feed shows for it.
///
/// It reaches the filesystem through [`RevisionsHost`]. [`Core::revisions`]
/// builds one on demand with the daemon as its host.
pub(crate) struct Revisions {
client: ProtonDriveClient,
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
host: Arc<dyn RevisionsHost>,
}
/// [`Core::list_revisions`] for a node addressed through any daemon location.
pub(crate) fn list_revisions_by_uid(&self, uid: &str) -> CoreResult<Vec<RevisionInfo>> {
let uid = self.resolve_anywhere(uid)?;
self.list_revisions_for_uid(&uid)
}
/// What [`Revisions`] needs from the filesystem.
pub(crate) trait RevisionsHost: Send + Sync {
/// Refuse unless this daemon may change the node's content. `what` names
/// the operation in the error.
fn require_writable(&self, uid: &NodeUid, what: &str) -> CoreResult<()>;
/// The node's active revision changed on the server: forget its cached
/// content and open readers, and fetch it again if it is kept offline.
fn content_replaced(&self, uid: &NodeUid);
/// Add an entry to the activity log.
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool);
}
fn list_revisions_for_uid(&self, uid: &NodeUid) -> CoreResult<Vec<RevisionInfo>> {
let revisions = self
.rt
.block_on(self.client.enumerate_revisions(uid))
.map_err(|e| CoreError::from_api(&e, "list revisions"))?;
Ok(revisions.into_iter().map(revision_info).collect())
}
/// Make `revision_id` the current content of the file at `rel`.
pub(crate) fn restore_revision(&self, rel: &Path, revision_id: &str) -> CoreResult<()> {
let (_ino, uid) = self.resolve(rel)?;
let name = rel
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| uid.to_string());
self.restore_revision_for_uid(&uid, revision_id, &name)?;
// The size and mtime a listing shows describe the revision that was
// active a moment ago.
self.invalidate_parent_listing(rel);
Ok(())
}
/// [`Core::restore_revision`] for a node addressed through any daemon
/// location.
pub(crate) fn restore_revision_by_uid(&self, uid: &str, revision_id: &str) -> CoreResult<()> {
let uid = self.resolve_anywhere(uid)?;
let name = uid.to_string();
self.restore_revision_for_uid(&uid, revision_id, &name)
}
fn restore_revision_for_uid(
&self,
uid: &NodeUid,
revision_id: &str,
name: &str,
) -> CoreResult<()> {
// Restoring rewrites the file's content: the same authority a write
// needs, not the one a read needs.
impl RevisionsHost for Core {
fn require_writable(&self, uid: &NodeUid, what: &str) -> CoreResult<()> {
self.require_uid_writable(uid)
.map_err(|error| self.errno_error(error, "restore revision"))?;
if let Err(e) = self
.rt
.block_on(self.client.restore_revision(uid, revision_id))
{
let error = CoreError::from_api(&e, "restore revision");
self.log_activity(ActivityKind::Restore, name, &error, false);
return Err(error);
}
// The active revision is changing behind our back — anything describing
// the old one (cached blocks, an open reader, the size in a listing) is
// stale from here on, and the server may not have applied the swap yet.
.map_err(|error| self.errno_error(error, what))
}
fn content_replaced(&self, uid: &NodeUid) {
self.cache.evict(uid);
self.evict_reader(uid);
// A file kept offline gets the restored content back on disk, and
@@ -116,9 +88,58 @@ impl Core {
if self.cache.is_pinned(uid) {
self.recheck_pinned(uid);
}
self.log_activity(
}
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool) {
Core::log_activity(self, kind, target, detail, ok);
}
}
impl Core {
/// The revisions service, with this daemon as its host.
pub(crate) fn revisions(&self) -> Revisions {
Revisions {
client: self.client.clone(),
drive: self.drive.clone(),
rt: self.rt.clone(),
host: Arc::new(self.clone()),
}
}
}
impl Revisions {
pub(crate) fn list(&self, uid: &NodeUid) -> CoreResult<Vec<RevisionInfo>> {
let revisions = self
.rt
.block_on(self.client.enumerate_revisions(uid))
.map_err(|e| CoreError::from_api(&e, "list revisions"))?;
Ok(revisions.into_iter().map(revision_info).collect())
}
pub(crate) fn restore(&self, uid: &NodeUid, revision_id: &str, name: &str) -> CoreResult<()> {
// Restoring rewrites the file's content: the same authority a write
// needs, not the one a read needs.
self.host.require_writable(uid, "restore revision")?;
if let Err(e) = self
.rt
.block_on(self.client.restore_revision(uid, revision_id))
{
let error = CoreError::from_api(&e, "restore revision");
self.host.log_activity(
ActivityKind::Restore,
name.to_string(),
error.to_string(),
false,
);
return Err(error);
}
// The active revision is changing behind our back — anything describing
// the old one (cached blocks, an open reader, the size in a listing) is
// stale from here on, and the server may not have applied the swap yet.
self.host.content_replaced(uid);
self.host.log_activity(
ActivityKind::Restore,
name,
name.to_string(),
format!("restored version {revision_id}"),
true,
);
@@ -126,32 +147,8 @@ impl Core {
Ok(())
}
/// Permanently delete `revision_id` from the history of the file at `rel`.
pub(crate) fn delete_revision(&self, rel: &Path, revision_id: &str) -> CoreResult<()> {
let (_ino, uid) = self.resolve(rel)?;
let name = rel
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| uid.to_string());
self.delete_revision_for_uid(&uid, revision_id, &name)
}
/// [`Core::delete_revision`] for a node addressed through any daemon
/// location.
pub(crate) fn delete_revision_by_uid(&self, uid: &str, revision_id: &str) -> CoreResult<()> {
let uid = self.resolve_anywhere(uid)?;
let name = uid.to_string();
self.delete_revision_for_uid(&uid, revision_id, &name)
}
fn delete_revision_for_uid(
&self,
uid: &NodeUid,
revision_id: &str,
name: &str,
) -> CoreResult<()> {
self.require_uid_writable(uid)
.map_err(|error| self.errno_error(error, "delete revision"))?;
pub(crate) fn delete(&self, uid: &NodeUid, revision_id: &str, name: &str) -> CoreResult<()> {
self.host.require_writable(uid, "delete revision")?;
// The server rejects deleting the active revision; saying so here is a
// sentence the user can act on instead of an API code, and it costs one
// listing the front-end already made to show the version list.
@@ -171,9 +168,9 @@ impl Core {
self.rt
.block_on(self.client.delete_revision(uid, revision_id))
.map_err(|e| CoreError::from_api(&e, "delete revision"))?;
self.log_activity(
self.host.log_activity(
ActivityKind::DeleteForever,
name,
name.to_string(),
format!("deleted version {revision_id}"),
true,
);
@@ -181,36 +178,7 @@ impl Core {
Ok(())
}
/// Write `revision_id` of the file at `rel` to the absolute local path
/// `dest`, leaving the file itself untouched.
pub(crate) fn save_revision_as(
&self,
rel: &Path,
revision_id: &str,
dest: &Path,
) -> CoreResult<u64> {
let (_ino, uid) = self.resolve(rel)?;
let name = rel
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| uid.to_string());
self.save_revision_for_uid(&uid, revision_id, &name, dest)
}
/// [`Core::save_revision_as`] for a node addressed through any daemon
/// location.
pub(crate) fn save_revision_as_by_uid(
&self,
uid: &str,
revision_id: &str,
dest: &Path,
) -> CoreResult<u64> {
let uid = self.resolve_anywhere(uid)?;
let name = uid.to_string();
self.save_revision_for_uid(&uid, revision_id, &name, dest)
}
fn save_revision_for_uid(
pub(crate) fn save_as(
&self,
uid: &NodeUid,
revision_id: &str,
@@ -253,13 +221,18 @@ impl Core {
// A half-written file looks like a successful export to every
// tool that opens it afterwards.
let _ = std::fs::remove_file(dest);
self.log_activity(ActivityKind::Download, name, &error, false);
self.host.log_activity(
ActivityKind::Download,
name.to_string(),
error.to_string(),
false,
);
return Err(error);
}
};
self.log_activity(
self.host.log_activity(
ActivityKind::Download,
name,
name.to_string(),
format!("saved version {revision_id} to {}", dest.display()),
true,
);
+45 -3
View File
@@ -2,7 +2,49 @@
use super::*;
/// Search over the database's node and home indexes. Holds the database, the
/// content cache (to say whether a hit is on this computer), the on-demand
/// mounts (to say which folders a hit can be opened through) and the home
/// indexer's busy flag.
pub(crate) struct Search {
db: Arc<Db>,
cache: Arc<ContentCache>,
mounts: Arc<Mutex<mount::SecondaryMountRegistry<SecondaryMount>>>,
indexing: Arc<AtomicBool>,
}
impl Core {
/// Search, over this daemon's indexes.
pub(crate) fn searcher(&self) -> Search {
Search {
db: self.db.clone(),
cache: self.cache.clone(),
mounts: self.mounts.clone(),
indexing: self.indexing.clone(),
}
}
/// See [`Search::roots`].
pub(super) fn search_roots(&self) -> SearchRoots {
self.searcher().roots()
}
}
impl Search {
/// Whether the home indexer is walking right now.
pub(crate) fn indexing(&self) -> bool {
self.indexing.load(Ordering::Relaxed)
}
/// The pinned uids, expanded through pinned folders, as one query.
fn pinned_set(&self) -> HashSet<String> {
self.db
.pinned_uids()
.unwrap_or_default()
.into_iter()
.collect()
}
/// The local locations a search result can be opened through, resolved once
/// per search rather than once per hit.
///
@@ -14,7 +56,7 @@ impl Core {
/// This used to be a per-hit call that re-read the sync-folder list and ran
/// an ancestor walk per folder, against a candidate pool of up to a
/// thousand: the whole cost of a keystroke was in here.
pub(super) fn search_roots(&self) -> SearchRoots {
pub(super) fn roots(&self) -> SearchRoots {
let live_mounts = self.mounts.lock();
let folders = self.db.sync_folder_list().unwrap_or_default();
SearchRoots {
@@ -43,7 +85,7 @@ impl Core {
.db
.search_in(query, limit, scope)
.map_err(|e| CoreError::from_api(&e, "search"))?;
let roots = self.search_roots();
let roots = self.roots();
let pinned = self.pinned_set();
Ok(hits
.into_iter()
@@ -105,7 +147,7 @@ impl Core {
// SQLite boundary to `limit` would recreate the old empty-filter bug.
let candidate_limit = limit.saturating_mul(10).clamp(100, 1_000);
let mut drive_hits = if filters.sources.contains(&SearchSource::Drive) {
let roots = self.search_roots();
let roots = self.roots();
let pinned = self.pinned_set();
self.db
.search_candidates(query, candidate_limit)
+267
View File
@@ -0,0 +1,267 @@
//! The long-lived loops a mount runs, each as a [`Service`].
//!
//! Each type here names its thread, says how a stop reaches it and whether the
//! mount can do without it. `mount.rs` builds the list and starts it with
//! [`Services::start`](pdfs_core::lifecycle::Services::start); a stop wakes and
//! joins them in reverse order.
use std::os::unix::net::UnixListener;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use pdfs_core::lifecycle::{Service, Wake};
use pdfs_core::shutdown::Shutdown;
use pdfs_store::db::Db;
use super::Core;
use super::background::run_local_index;
use super::control::run_control_socket;
use super::events::{EventHub, run_event_sampler};
use super::sync;
use super::transfers::TransferRegistry;
/// One of the threads that send queued changes to Drive. The drain workers wait
/// on one condvar, which a stop has to notify; one notify wakes them all, so
/// only the first worker carries the wake.
pub(crate) struct DrainWorker {
pub(crate) core: Core,
pub(crate) index: usize,
}
impl Service for DrainWorker {
fn name(&self) -> String {
format!("pdfs-drain-{}", self.index)
}
fn wake(&self) -> Option<Wake> {
let core = self.core.clone();
(self.index == 0).then(|| Box::new(move || core.wake_drain()) as Wake)
}
fn run(self: Box<Self>) {
self.core.run_pending_drain(self.index == 0);
}
}
/// The folder-sync engine. It watches every mirror folder, polls the remotes and
/// reconciles on its own thread, never in front of a FUSE call. It waits on its
/// channel, so a stop sends it `Stop`.
///
/// Optional: the mount still serves files without it.
pub(crate) struct SyncEngine {
pub(crate) syncer: sync::Syncer,
pub(crate) tx: std::sync::mpsc::Sender<sync::SyncMsg>,
pub(crate) rx: std::sync::mpsc::Receiver<sync::SyncMsg>,
}
impl Service for SyncEngine {
fn name(&self) -> String {
"pdfs-sync".to_owned()
}
fn required(&self) -> bool {
false
}
fn wake(&self) -> Option<Wake> {
let tx = self.tx.clone();
Some(Box::new(move || {
let _ = tx.send(sync::SyncMsg::Stop);
}))
}
fn run(self: Box<Self>) {
let Self { syncer, rx, .. } = *self;
sync::run(syncer, rx);
}
}
/// Reconciles leftover `(sync-conflict …)` copies: drops the ones that turned
/// out identical to the live file and surfaces the ones that differ. It
/// enumerates and trashes, so it must never block a FUSE call.
pub(crate) struct ConflictSweep(pub(crate) super::sweep::Sweeper);
impl Service for ConflictSweep {
fn name(&self) -> String {
"pdfs-conflict-sweep".to_owned()
}
fn run(self: Box<Self>) {
self.0.run();
}
}
/// Watches the link for the life of the mount: a mount from the cache waits
/// for the network to come back, and an online one can lose it at any moment.
pub(crate) struct OnlineProbe(pub(crate) super::link::OnlineProbe);
impl Service for OnlineProbe {
fn name(&self) -> String {
"pdfs-online-probe".to_owned()
}
fn run(self: Box<Self>) {
self.0.run();
}
}
/// Keeps pinned files on this computer through changes made elsewhere, and
/// fetches the ones a failed or missed download left out (`docs/BUGS.md`
/// B282). A check lists folders and downloads files.
pub(crate) struct PinKeeper(pub(crate) super::keeper::PinKeeper);
impl Service for PinKeeper {
fn name(&self) -> String {
"pdfs-pin-keeper".to_owned()
}
fn run(self: Box<Self>) {
self.0.run();
}
}
/// Keeps the launcher prompt's "This computer" index fresh. The walk is
/// I/O-heavy and must never sit in front of a FUSE callback.
pub(crate) struct LocalIndex {
pub(crate) db: Arc<Db>,
pub(crate) indexing: Arc<AtomicBool>,
pub(crate) transfers: Arc<TransferRegistry>,
pub(crate) mountpoint: PathBuf,
pub(crate) shutdown: Arc<Shutdown>,
}
impl Service for LocalIndex {
fn name(&self) -> String {
"pdfs-localindex".to_owned()
}
fn run(self: Box<Self>) {
let Self {
db,
indexing,
transfers,
mountpoint,
shutdown,
} = *self;
run_local_index(db, indexing, transfers, mountpoint, shutdown);
}
}
/// Answers the control socket, one job per connection.
///
/// The listener blocks in `accept`, which only returns when a connection
/// arrives, so a stop connects to it. It connects while the socket still
/// exists, which is the point of the poke, then unlinks it so nothing else can
/// arrive behind it. The listener checks the stop flag after every accept, so
/// a connection that races the unlink cannot put it back to sleep. The
/// connections it handed off are jobs, which a stop joins; a subscription
/// among them waits on its mailbox, so the wake rings every mailbox too.
pub(crate) struct ControlListener {
pub(crate) core: Core,
pub(crate) username: String,
pub(crate) mountpoint: PathBuf,
pub(crate) listener: UnixListener,
pub(crate) socket: PathBuf,
}
impl Service for ControlListener {
fn name(&self) -> String {
"pdfs-control".to_owned()
}
fn wake(&self) -> Option<Wake> {
let socket = self.socket.clone();
let events: Arc<EventHub> = self.core.events.clone();
Some(Box::new(move || {
let _ = std::os::unix::net::UnixStream::connect(&socket);
let _ = std::fs::remove_file(&socket);
events.wake_all();
}))
}
fn run(self: Box<Self>) {
let Self {
core,
username,
mountpoint,
listener,
..
} = *self;
run_control_socket(core, username, mountpoint, listener);
}
}
/// Publishes what changes without one place to publish it from (status,
/// transfers, sync progress) to the front ends subscribed on the control
/// socket.
///
/// Optional: front ends still get every published change, only not the
/// sampled ones.
pub(crate) struct EventSampler {
pub(crate) core: Core,
pub(crate) username: String,
pub(crate) mountpoint: PathBuf,
}
impl Service for EventSampler {
fn name(&self) -> String {
"pdfs-events".to_owned()
}
fn required(&self) -> bool {
false
}
fn run(self: Box<Self>) {
run_event_sampler(self.core, self.username, self.mountpoint);
}
}
/// Watches the worker pool and answers the systemd watchdog. Its liveness
/// probe is a round trip over the control socket, so it starts after the
/// listener.
///
/// Optional: the mount works without it, only it is no longer diagnosable if
/// it wedges.
pub(crate) struct Supervisor {
pub(crate) core: Core,
pub(crate) socket: PathBuf,
}
impl Service for Supervisor {
fn name(&self) -> String {
"pdfs-supervisor".to_owned()
}
fn required(&self) -> bool {
false
}
fn run(self: Box<Self>) {
super::supervisor::run(self.core, self.socket);
}
}
/// Holds off a shutdown while changes exist only here (B66).
///
/// Optional: without it a shutdown is not delayed, and queued changes go out
/// on the next start.
pub(crate) struct Inhibitor {
pub(crate) db: Arc<Db>,
pub(crate) shutdown: Arc<Shutdown>,
}
impl Service for Inhibitor {
fn name(&self) -> String {
"pdfs-inhibit".to_owned()
}
fn required(&self) -> bool {
false
}
fn run(self: Box<Self>) {
super::inhibit::run(&self.db, &self.shutdown);
}
}
+6
View File
@@ -883,10 +883,16 @@ mod tests {
daemon.client.set_online(false);
std::fs::write(daemon.mountpoint.join("f.txt"), b"0123456789").unwrap();
// Usually the drain meets the outage first. Another caller (the event
// poll, a sync pass) can meet it first and take the mount offline,
// and then the drain claims nothing and the write has no failed
// attempt to wait out. Both must end with the write going out soon
// after the link returns.
assert!(wait_until(Duration::from_secs(30), || {
daemon
.pending()
.is_ok_and(|items| items.iter().any(|item| item.attempts > 0))
|| daemon.online().is_ok_and(|online| !online)
}));
// The drain records the failure just before it takes the mount
// offline. Left online, only the event poll would, much later.
+8 -3
View File
@@ -165,9 +165,9 @@ impl Core {
return;
}
let queue = self.sizes.size_waiters.clone();
if let Err(error) = std::thread::Builder::new()
.name("pdfs-size-waiters".into())
.spawn(move || queue.serve())
if let Err(error) = self
.services
.spawn_job("pdfs-size-waiters", move || queue.serve())
{
// Without a thread nothing would ever answer these. A provisional
// size is wrong; a `stat` that never returns wedges the caller.
@@ -190,6 +190,11 @@ impl Core {
let (mut key, mut uids, mut slot) = (key, uids, slot);
loop {
for chunk in uids.chunks(SIZE_UPGRADE_CHUNK) {
// A stop joins this job; the rest of the folder can wait for
// the next mount, which lists it afresh.
if self.shutdown.is_stopping() {
break;
}
let result =
self.block_on_within(BATCH_CALL_TIMEOUT, self.drive.enumerate_nodes(chunk));
self.apply_size_upgrade(key, result);
+118 -43
View File
@@ -30,6 +30,10 @@ use pdfs_core::control::ActivityKind;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::{debug, info, warn};
use pdfs_core::shutdown::Shutdown;
use pdfs_drive::DriveApi;
use pdfs_store::db::Db;
use super::{Core, node_content_sha1, node_revision_id, node_size};
/// What the conflict sweep may do, and the copies it already checked this
@@ -44,7 +48,7 @@ pub(crate) struct SweepState {
/// Conflict copies the sweep has already checked against the activity log
/// this run, so each pass does not ask the database again. The log itself
/// is what keeps a copy from being flagged again after a restart. See
/// [`Core::run_conflict_sweep_loop`] and `docs/BUGS.md` B99.
/// [`Sweeper::run`] and `docs/BUGS.md` B99.
pub(crate) conflict_notified: Arc<Mutex<HashSet<NodeUid>>>,
}
@@ -107,17 +111,114 @@ pub(crate) fn conflict_base_name(name: &str) -> Option<String> {
Some(base)
}
/// What the conflict sweep needs from the rest of the daemon: the tree of
/// every mount and the activity feed.
pub(crate) trait SweepHost: Send + Sync {
/// Whether `uid` is on this account's own volume, or a virtual node.
fn is_own_or_virtual(&self, uid: &NodeUid) -> bool;
/// Whether the mount believes Drive is reachable.
fn is_online(&self) -> bool;
/// Whether a node is being written or held open in any mount.
fn is_busy(&self, uid: &NodeUid) -> bool;
/// For one pass: whether the conflict listing can show a copy.
fn conflict_locator(&self) -> Box<dyn Fn(&NodeUid) -> bool + '_>;
/// Unhook a node Drive no longer has from every mount, and drop its
/// cached content and open readers.
fn forget(&self, uid: &NodeUid);
fn log_activity(&self, kind: ActivityKind, target: &str, detail: String, ok: bool);
}
impl SweepHost for Core {
fn is_own_or_virtual(&self, uid: &NodeUid) -> bool {
Core::is_own_or_virtual(self, uid)
}
fn is_online(&self) -> bool {
Core::is_online(self)
}
fn is_busy(&self, uid: &NodeUid) -> bool {
Core::is_busy(self, uid)
}
fn conflict_locator(&self) -> Box<dyn Fn(&NodeUid) -> bool + '_> {
let roots = Core::search_roots(self);
Box::new(move |uid| self.conflict_path(&roots, uid).is_some())
}
fn forget(&self, uid: &NodeUid) {
// Leaving a conflict copy hooked up in the tree keeps a node we have
// just trashed remotely visible and readable in whichever mount shows
// it (`docs/BUGS.md` B74).
self.for_each_state(|st| {
st.forget_or_unlink(uid);
});
self.cache.evict(uid);
self.evict_reader(uid);
}
fn log_activity(&self, kind: ActivityKind, target: &str, detail: String, ok: bool) {
Core::log_activity(self, kind, target, detail, ok);
}
}
impl Core {
/// The conflict sweep, with this daemon as its host.
pub(crate) fn sweeper(&self) -> Sweeper {
Sweeper {
drive: self.drive.clone(),
rt: self.rt.clone(),
db: self.db.clone(),
shutdown: self.shutdown.clone(),
state: self.sweep.clone(),
host: Arc::new(self.clone()),
}
}
/// Whether a node has a write in flight or a file handle open against it.
/// Read-only opens use fh 0 and are not tracked, so this is specifically the
/// writer/holder check.
/// Asked across **every** mount. The sweep runs on the primary Core but
/// trashes nodes anywhere in the tree, and a file open inside a sync folder
/// is tracked in that fork's `State` — so consulting `self.state` alone
/// answered "idle" for every such file and let the sweep delete one with a
/// writer attached (`docs/BUGS.md` B74). Busy anywhere means busy.
pub(crate) fn is_busy(&self, uid: &NodeUid) -> bool {
let mut busy = false;
self.for_each_state(|st| {
let Some(&ino) = st.by_uid.get(uid) else {
return;
};
busy |=
st.active_writes.contains_key(&ino) || st.handles.values().any(|&held| held == ino);
});
busy
}
}
/// Reconciles leftover conflict copies (the module documentation says how).
/// Holds Drive, the runtime, the database, the stop signal and its own state;
/// it reaches the mounts through [`SweepHost`].
pub(crate) struct Sweeper {
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
db: Arc<Db>,
shutdown: Arc<Shutdown>,
state: SweepState,
host: Arc<dyn SweepHost>,
}
impl Sweeper {
/// Sweep for stale conflict copies forever, on its own thread. See the module
/// docs for the identical/divergent policy.
pub(crate) fn run_conflict_sweep_loop(&self) {
pub(crate) fn run(&self) {
// Both waits are interruptible, so teardown does not have to sit out a
// five-minute interval to join this thread (`docs/BUGS.md` B44).
if !self.shutdown.sleep(CONFLICT_SWEEP_WARMUP) {
return;
}
loop {
self.sweep_conflicts_once();
self.sweep_once();
if !self.shutdown.sleep(CONFLICT_SWEEP_INTERVAL) {
return;
}
@@ -125,7 +226,7 @@ impl Core {
}
/// One sweep pass over every node the daemon currently knows.
fn sweep_conflicts_once(&self) {
fn sweep_once(&self) {
let stored = match self.db.load_all() {
Ok(s) => s,
Err(e) => {
@@ -136,7 +237,7 @@ impl Core {
let nodes: Vec<_> = stored
.into_iter()
.map(|stored| stored.node)
.filter(|node| self.is_own_or_virtual(&node.uid))
.filter(|node| self.host.is_own_or_virtual(&node.uid))
.collect();
// Index live (non-trashed) files by (parent, name) for sibling lookup.
@@ -153,8 +254,8 @@ impl Core {
by_parent_name.insert((parent, node.name.as_str()), node);
}
let roots = self.search_roots();
let online = self.is_online();
let listed = self.host.conflict_locator();
let online = self.host.is_online();
for node in &nodes {
if node.trashed || node.is_folder() {
continue;
@@ -169,7 +270,7 @@ impl Core {
.unwrap_or_default();
let sibling = by_parent_name.get(&(parent, base.as_str())).copied();
match decide(node, sibling, &base, self.sweep.sweep_mode) {
match decide(node, sibling, &base, self.state.sweep_mode) {
SweepAction::Remove => {
// Only while online — the remote trash is the point. Offline,
// it waits for a later pass.
@@ -181,7 +282,7 @@ impl Core {
// would sit in the feed as "resolved" with no way to act on
// it (`docs/BUGS.md` B99).
SweepAction::Flag(detail) => {
if self.conflict_path(&roots, &node.uid).is_some() {
if listed(&node.uid) {
self.flag_conflict(&node.uid, &node.name, detail);
} else {
debug!(uid = %node.uid, name = %node.name, "conflict sweep: copy is outside every location; not flagged");
@@ -219,12 +320,7 @@ impl Core {
return;
}
}
// Leaving a conflict copy hooked up in the tree keeps a node we have
// just trashed remotely visible and readable in whichever mount shows
// it (`docs/BUGS.md` B74).
self.for_each_state(|st| {
st.forget_or_unlink(uid);
});
self.host.forget(uid);
// Deliberately *not* `discard_queued_ops`: `duplicate_still_removable`
// proved the queue empty before the trash above, but that proof is stale
// the moment `trash_nodes` goes to the network. A `close(2)` landing in
@@ -232,14 +328,12 @@ impl Core {
// blob holding the only copy of them. Leaving the op queued is the
// non-destructive outcome: the drain re-reads the node, sees it trashed,
// and `revision_conflict` routes it to `keep_as_conflict_copy`.
self.cache.evict(uid);
self.evict_reader(uid);
if let Err(e) = self.db.delete_node(uid) {
warn!(%uid, error = ?e, "conflict sweep: db delete after trash failed");
}
self.invalidate_trash();
self.sweep.conflict_notified.lock().remove(uid);
self.log_activity(
super::trash::invalidate_trash(&self.db);
self.state.conflict_notified.lock().remove(uid);
self.host.log_activity(
ActivityKind::Trash,
name,
format!("auto-removed duplicate of {base}"),
@@ -273,7 +367,7 @@ impl Core {
// Someone is writing to it, or holds it open. Trashing now would pull the
// node out from under a live handle.
if self.is_busy(uid) {
if self.host.is_busy(uid) {
debug!(%uid, name, "conflict sweep: skipping duplicate that is open or being written");
return false;
}
@@ -306,32 +400,12 @@ impl Core {
}
}
/// Whether a node has a write in flight or a file handle open against it.
/// Read-only opens use fh 0 and are not tracked, so this is specifically the
/// writer/holder check.
/// Asked across **every** mount. The sweep runs on the primary Core but
/// trashes nodes anywhere in the tree, and a file open inside a sync folder
/// is tracked in that fork's `State` — so consulting `self.state` alone
/// answered "idle" for every such file and let the sweep delete one with a
/// writer attached (`docs/BUGS.md` B74). Busy anywhere means busy.
pub(crate) fn is_busy(&self, uid: &NodeUid) -> bool {
let mut busy = false;
self.for_each_state(|st| {
let Some(&ino) = st.by_uid.get(uid) else {
return;
};
busy |=
st.active_writes.contains_key(&ino) || st.handles.values().any(|&held| held == ino);
});
busy
}
/// Surface a conflict copy that needs the user's attention, once. The
/// in-memory set spares the database each pass; the activity log itself is
/// what keeps a restart from logging the same copy again (`docs/BUGS.md`
/// B99). A copy's name carries its own timestamp, so the name identifies it.
fn flag_conflict(&self, uid: &NodeUid, name: &str, detail: String) {
if !self.sweep.conflict_notified.lock().insert(uid.clone()) {
if !self.state.conflict_notified.lock().insert(uid.clone()) {
return;
}
match self.db.activity_has(ActivityKind::Conflict, name) {
@@ -342,7 +416,8 @@ impl Core {
Err(e) => warn!(%uid, name, error = ?e, "conflict sweep: activity check failed"),
}
debug!(%uid, name, detail, "conflict sweep: flagged divergent conflict copy");
self.log_activity(ActivityKind::Conflict, name, detail, false);
self.host
.log_activity(ActivityKind::Conflict, name, detail, false);
}
}
+1 -1
View File
@@ -38,7 +38,7 @@ impl SyncHost for Core {
}
fn upload_thumbnails(&self, path: &Path, name: &str) -> Vec<Thumbnail> {
Core::upload_thumbnails(self, path, name)
self.photos().upload_thumbnails(path, name)
}
}
+106 -37
View File
@@ -2,6 +2,7 @@
//! listing in the background, restoring from it, deleting from it for good.
use super::*;
use crate::listing::listing_stale;
/// Whether a trash refresh is running, and the wake-up for requests waiting
/// on its progress.
@@ -13,7 +14,7 @@ pub(crate) struct TrashState {
/// Fires whenever a trash refresh persists a batch or finishes, so a
/// `ListTrash` request waiting on a first-ever refresh wakes on progress
/// instead of polling or blocking for the whole run. See
/// [`Core::await_trash_refresh`].
/// [`Trash::await_trash_refresh`].
pub(crate) trash_progress: Arc<tokio::sync::Notify>,
}
@@ -26,7 +27,75 @@ impl TrashState {
}
}
/// The Drive trash as a service: listing it, refreshing that listing, and
/// restoring or deleting from it.
///
/// It holds only the handles it calls, and reaches the mounted trees through
/// [`TrashHost`]. [`Core::trash`] builds one on demand with the daemon as its
/// host. A clone shares everything, which is how a refresh moves onto a
/// background task.
#[derive(Clone)]
pub(crate) struct Trash {
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
db: Arc<Db>,
events: Arc<events::EventHub>,
services: pdfs_core::lifecycle::ServiceBoard,
writes: writes::WriteState,
jobs: TrashState,
host: Arc<dyn TrashHost>,
}
/// What the trash needs from the mounted trees.
pub(crate) trait TrashHost: Send + Sync {
/// Re-enumerate these folders on next access, in every mount, because a
/// restored node reappears under one of them.
fn invalidate_listings_of(&self, parents: &[NodeUid]);
/// Forget nodes the server no longer has, in every mount, with any cached
/// content they own.
fn drop_local(&self, uids: &[NodeUid]);
}
impl TrashHost for Core {
fn invalidate_listings_of(&self, parents: &[NodeUid]) {
// Keyed by uid, so it applies to every mount: a restored node reappears
// in whichever mounts show its parent, not only the primary one.
self.for_each_state(|st| {
for parent in parents {
if let Some(&ino) = st.by_uid.get(parent) {
st.invalidate_listing(ino);
}
}
});
}
fn drop_local(&self, uids: &[NodeUid]) {
Core::drop_local(self, uids);
}
}
impl Core {
/// [`Trash::invalidate_trash`], without building the service.
pub(super) fn invalidate_trash(&self) {
invalidate_trash(&self.db);
}
/// The trash service, with this daemon as its host.
pub(crate) fn trash(&self) -> Trash {
Trash {
drive: self.drive.clone(),
rt: self.rt.clone(),
db: self.db.clone(),
events: self.events.clone(),
services: self.services.clone(),
writes: self.writes.clone(),
jobs: self.trash_jobs.clone(),
host: Arc::new(self.clone()),
}
}
}
impl Trash {
/// List the account's trash, from the DB. Trashed nodes are outside the
/// mounted tree — the FUSE side forgot them when they were trashed — so the
/// listing is persisted in its own table rather than derived from `State`, and
@@ -36,7 +105,7 @@ impl Core {
/// Stale-while-revalidate, like the photos timeline: a persisted listing comes
/// back at DB speed and is refreshed in the background past [`TRASH_TTL`].
/// Our own trash mutations invalidate it outright (see
/// [`Core::invalidate_trash`]), so the TTL only covers changes made elsewhere.
/// [`Trash::invalidate_trash`]), so the TTL only covers changes made elsewhere.
///
/// The refresh always runs *off* the request: a never-fetched trash waits for
/// it, but only for [`TRASH_FIRST_WAIT`], and then answers with the batches
@@ -44,9 +113,9 @@ impl Core {
/// made a large trash unlistable — the refresh outran the front-end's read
/// timeout, the user asked again, and each attempt left another full refresh
/// grinding in the daemon (`docs/BUGS.md` B72).
pub(super) fn list_trash(&self) -> CoreResult<Vec<DirEntry>> {
pub(crate) fn list_trash(&self) -> CoreResult<Vec<DirEntry>> {
let never_fetched = self.db.state_i64(TRASH_SYNCED_MS).ok().flatten().is_none();
if never_fetched || self.listing_stale(TRASH_SYNCED_MS, TRASH_TTL) {
if never_fetched || listing_stale(&self.db, TRASH_SYNCED_MS, TRASH_TTL) {
self.spawn_trash_refresh();
}
if never_fetched {
@@ -99,7 +168,7 @@ impl Core {
/// What a trashed folder holds: its children on the server, and the
/// stored trash entries trashed inside it before it went.
pub(super) fn list_trashed_folder(&self, uid: &str) -> CoreResult<Vec<DirEntry>> {
pub(crate) fn list_trashed_folder(&self, uid: &str) -> CoreResult<Vec<DirEntry>> {
let folder =
parse_uid(uid).ok_or_else(|| CoreError::invalid(format!("invalid uid: {uid}")))?;
let children = self
@@ -177,7 +246,7 @@ impl Core {
/// [`TRASH_MATERIALIZE_CHUNK`] is stored as it lands, so a large trash
/// fills the page while it loads. Rows the server no longer lists go once
/// the whole listing is in, never earlier.
pub(super) async fn refresh_trash(&self) -> CoreResult<()> {
pub(crate) async fn refresh_trash(&self) -> CoreResult<()> {
let started = Instant::now();
let uids = within_trash_call("enumerate trash", self.drive.enumerate_trash_node_uids())
.await?
@@ -200,7 +269,7 @@ impl Core {
let listed: HashSet<String> = uids.iter().map(ToString::to_string).collect();
let removed = self.db.trash_retain(&listed).map_err(CoreError::from)?;
if removed > 0 {
self.trash.trash_progress.notify_waiters();
self.jobs.trash_progress.notify_waiters();
}
let missing: Vec<NodeUid> = uids
.into_iter()
@@ -235,7 +304,7 @@ impl Core {
.collect();
materialized += items.len();
self.db.trash_upsert(&items).map_err(CoreError::from)?;
self.trash.trash_progress.notify_waiters();
self.jobs.trash_progress.notify_waiters();
self.events.publish(&[Topic::Trash]);
debug!(
materialized,
@@ -258,44 +327,44 @@ impl Core {
}
/// Refresh the trash off the request path. At most one refresh at a time —
/// including the one a first-ever [`Core::list_trash`] waits on, so a burst
/// including the one a first-ever [`Trash::list_trash`] waits on, so a burst
/// of requests against an unfetched trash joins one refresh instead of
/// starting one apiece.
pub(super) fn spawn_trash_refresh(&self) {
if self.trash.trash_refreshing.swap(true, Ordering::SeqCst) {
pub(crate) fn spawn_trash_refresh(&self) {
if self.jobs.trash_refreshing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
let this = self.clone();
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);
let refreshed = this.refresh_trash().await;
this.jobs.trash_refreshing.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Trash]),
Ok(_) => this.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();
this.jobs.trash_progress.notify_waiters();
});
}
/// Wait for the in-flight trash refresh to make progress, for at most
/// `budget`. Returns early when it finishes; never cancels it — the refresh
/// is a detached task, so giving up here costs the work nothing.
pub(super) fn await_trash_refresh(&self, budget: Duration) {
pub(crate) fn await_trash_refresh(&self, budget: Duration) {
let deadline = Instant::now() + budget;
self.rt.block_on(async {
while self.trash.trash_refreshing.load(Ordering::SeqCst) {
while self.jobs.trash_refreshing.load(Ordering::SeqCst) {
let Some(left) = deadline.checked_duration_since(Instant::now()) else {
break;
};
let notified = self.trash.trash_progress.notified();
let notified = self.jobs.trash_progress.notified();
tokio::pin!(notified);
// Register before re-checking the flag: a refresh that finishes
// in between must not leave us waiting for a notify that has
// already fired.
notified.as_mut().enable();
if !self.trash.trash_refreshing.load(Ordering::SeqCst) {
if !self.jobs.trash_refreshing.load(Ordering::SeqCst) {
break;
}
if tokio::time::timeout(left, notified).await.is_err() {
@@ -313,8 +382,8 @@ impl Core {
/// trash ourselves. The next Trash page then *waits* for a fresh listing
/// rather than painting one from before the mutation — the user just made the
/// change and is about to look straight at it.
pub(super) fn invalidate_trash(&self) {
let _ = self.db.clear_state(TRASH_SYNCED_MS);
pub(crate) fn invalidate_trash(&self) {
invalidate_trash(&self.db);
}
/// Restore trashed nodes to the folders they were trashed from, together
@@ -335,8 +404,8 @@ impl Core {
/// The destination parents are read *before* the restore — a restored node
/// reappears in a listing the daemon may already have cached, so each one is
/// invalidated and re-enumerated on next access.
pub(super) fn restore(&self, uids: &[String]) -> CoreResult<usize> {
let requested = Self::parse_uids(uids)?;
pub(crate) fn restore(&self, uids: &[String]) -> CoreResult<usize> {
let requested = Core::parse_uids(uids)?;
// A listing we could not read is not a reason to refuse the restore: it
// only costs the expansion, and the requested nodes still go back.
let relations = self.db.trash_parents().unwrap_or_default();
@@ -399,13 +468,7 @@ impl Core {
}
// Keyed by uid, so it applies to every mount: a restored node reappears
// in whichever mounts show its parent, not only the primary one.
self.for_each_state(|st| {
for parent in &parents {
if let Some(&ino) = st.by_uid.get(parent) {
st.invalidate_listing(ino);
}
}
});
self.host.invalidate_listings_of(&parents);
let back: Vec<String> = restored.iter().map(ToString::to_string).collect();
let _ = self.db.trash_remove(&back);
self.invalidate_trash();
@@ -414,8 +477,8 @@ impl Core {
/// Permanently delete trashed nodes. Irreversible on the server; locally it
/// drops any metadata and cached content the node still owns.
pub(super) fn delete_forever(&self, uids: &[String]) -> CoreResult<usize> {
let parsed = Self::parse_uids(uids)?;
pub(crate) fn delete_forever(&self, uids: &[String]) -> CoreResult<usize> {
let parsed = Core::parse_uids(uids)?;
// Streamed, and each node's local state is dropped as its batch lands.
// A permanent delete is irreversible, so the useful property is that a
// daemon interrupted mid-batch has already forgotten exactly the nodes
@@ -430,7 +493,7 @@ impl Core {
let (uid, outcome) = item?;
match outcome {
Ok(()) => {
self.drop_local(std::slice::from_ref(&uid));
self.host.drop_local(std::slice::from_ref(&uid));
gone.push(uid.to_string());
deleted += 1;
}
@@ -461,7 +524,7 @@ impl Core {
/// is what kept the delete from ever being sent (`docs/BUGS.md` B293).
/// The stored listing is cleared at once, and the server is asked again
/// after [`TRASH_TTL`], so anything it still holds then shows up again.
pub(super) fn empty_trash(&self) -> CoreResult<usize> {
pub(crate) fn empty_trash(&self) -> CoreResult<usize> {
let uids: Vec<String> = self
.db
.trash_seen()
@@ -472,7 +535,7 @@ impl Core {
.block_on(within_trash_call("empty trash", self.drive.empty_trash()))?
.map_err(|e| CoreError::from_api(&e, "empty trash"))?;
let parsed: Vec<NodeUid> = uids.iter().filter_map(|uid| parse_uid(uid)).collect();
self.drop_local(&parsed);
self.host.drop_local(&parsed);
let _ = self.db.trash_replace(&[]);
let _ = self.db.set_state_i64(TRASH_SYNCED_MS, now_ms());
self.events.publish(&[Topic::Trash]);
@@ -480,7 +543,7 @@ impl Core {
}
}
/// An entry inside a trashed folder, for [`Core::list_trashed_folder`].
/// An entry inside a trashed folder, for [`Trash::list_trashed_folder`].
pub(super) fn trashed_entry(
uid: String,
name: String,
@@ -619,3 +682,9 @@ pub(super) fn expand_restore(
waves.retain(|wave| !wave.is_empty());
waves
}
/// Mark the stored trash listing stale, so the next listing waits for a
/// fresh one.
pub(crate) fn invalidate_trash(db: &Db) {
let _ = db.clear_state(TRASH_SYNCED_MS);
}
+1
View File
@@ -70,6 +70,7 @@ async fn run_uploads(
));
}
let thumbnails = core
.photos()
.upload_thumbnails_async(t.path.clone(), t.name.clone())
.await;
match core
+75 -9
View File
@@ -479,10 +479,14 @@ both with `pdfs_core::search::relevance_score`, so the prompt can merge them int
| Smaller helpers | `pdfs-localindex` (home index for search), `pdfs-pause` (ends a timed pause), `pdfs-similar` (similar photos, on request), `pdfs-diagnostics` |
Long-running loops wait on one shared `Shutdown` signal instead of sleeping, so a stop joins them
instead of leaving them behind (`docs/BUGS.md` B44). The mount starts its long-lived threads
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
instead of leaving them behind (`docs/BUGS.md` B44). Each long-lived thread is a
`pdfs_core::lifecycle::Service`, defined in `pdfs-fuse/src/services.rs`. A service says what its
thread is called, whether the mount can run without it, 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. The mount builds the list and starts it through
`Services::start`. A required service that cannot start fails the mount attempt, which is retried;
an optional one (the sync engine, the event sampler, the supervisor, the inhibitor) is logged and
skipped. 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. 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
@@ -496,7 +500,10 @@ 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.
and is listed the same way. Each control connection is a job too. A stop closes the board to new
jobs, aborts the async ones and joins the thread jobs before the services, up to the same
deadline. A long job checks the `Shutdown` signal between steps. Jobs used to be left running, and
one still waiting on Drive when the runtime went away panicked on its next timer.
---
@@ -764,22 +771,81 @@ State that several owners share sits behind a narrow interface of its own:
- `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`.
- `link::Link` holds whether Drive answers, next to when the link went down, and is the only
code that changes it: it flips the flag, logs the outage and wakes whoever waits. 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.
`photos::Photos` is the timeline, albums, thumbnails, the Google Photos import and the redate
job. It holds the handles it calls and the `PhotoJobs` state, and reaches the filesystem through a
`PhotosHost` port with three methods: list a folder, for the recursive thumbnail build; note a
change made here, so its echo in the event feed is not taken for a remote edit; and add an entry
to the activity log. `Core::photos` builds one on demand with the daemon as its
host, as `Core::syncer` does for the sync engine. Trashing photos stays on `Core`, because it
checks write authority against the tree and drops open readers.
`trash::Trash` lists the Drive trash, refreshes that listing, and restores or deletes from it. Its
`TrashHost` port has two methods, both of which reach every mount: re-enumerate the folders a
restored node comes back into, and forget nodes the server no longer has. `Core::trash` builds it
on demand.
`revisions::Revisions` lists, restores, deletes and saves a file's earlier revisions. Like
`Sharing`, it only takes a node already resolved to its uid. Its `RevisionsHost` port checks that
the node may be written, drops what describes the old content (cached blocks and open readers)
and fetches it again if it is kept offline, and adds an activity entry.
`devices::Devices` holds the account's devices on Drive: listing, renaming, deleting, adopting
and migrating them, and registering this computer. Its `DevicesHost` port moves a folder, runs a
sync pass and re-enumerates a folder, which is what migrating a device's folders needs. Synced
folders and on-demand mounts are still methods on `Core`.
`profile::ProfileBackup` writes this machine's profile to its device and reads the profiles other
machines wrote, to offer their folders for restore. It needs nothing from the filesystem, so it
has no host. Turning the offered folders into synced folders stays on `Core`.
`maintenance::Maintenance` runs `VACUUM` and the deep integrity check as jobs, one at a time, and
keeps the last check's findings.
`search::Search` answers searches over the node and home indexes. It holds the database, the
content cache, the on-demand mounts and the home indexer's busy flag.
`recovery::Recovery` rebuilds the queue after a restart: the pending map, the staging area and
writes fsynced before the stop. Its `RecoveryHost` port queues a recovered write. Rebuilding the
tree stays on `Core`.
The mount's background loops are services of their own too, each started from the list in
`services.rs`:
- `link::OnlineProbe` probes the link back while it is down. Its `LinkHost` port stores the root
Drive answered with, lets what waited on the link go (relisting, retrying backed-off ops,
waking the drain, rechecking pins), reports a refused session and repairs the root's share id.
- `sweep::Sweeper` is the conflict sweep. Its `SweepHost` port asks whether a node is the
account's own, whether the mount is online, whether a node is busy in any mount and whether
the conflict listing can show a copy; it unhooks a trashed copy from every mount and adds
activity entries.
- `keeper::PinKeeper` keeps pinned files current. Its `KeeperHost` port finds a node in the tree,
lists kept folders, describes a file as a pin keeps it and downloads it.
- The inhibitor takes only the database and the stop signal.
The drain workers, the control listener, the event sampler and the supervisor still take a whole
`Core`. The drain is the write-back, which is part of the mounted-files service (step 5); the
other three answer front ends with reports drawn from every area.
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.
What is left in `Core` is the mounted-files side: the tree and its per-mount state, reads,
queued writes and the drain, listings and sizes, path requests, and the registry of on-demand
mounts. Step 5 turns that into the `pdfs-vfs` service. `Core` also implements the services'
host ports and builds each service on demand, which moves to `pdfs-daemon` once the services no
longer need the tree.
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
+1 -1
View File
@@ -6004,7 +6004,7 @@ since Sep 20, 13:13 · Resolved`. `find` showed all six copies still on disk, in
journal showed the daemon mounting at 17:29:33, and the entries were stamped 17:30. That is the
sweep's 30-second warmup.
**Where:** `crates/pdfs-fuse/src/sweep.rs` (`flag_conflict`, `sweep_conflicts_once`),
**Where:** `crates/pdfs-fuse/src/sweep.rs` (`flag_conflict`, `Sweeper::sweep_once`),
`crates/pdfs-fuse/src/conflicts.rs` (`list_conflicts`), `crates/pdfs-fuse/src/control.rs`
(`ResolveConflict`).