Compare commits

..
Author SHA1 Message Date
nvrl cb6e0e3228 feat(core,fuse): stop the event-stream loops with the mount's other services
The loops that follow the Drive and photos event streams, and the gallery
refresh, were bare tasks on the runtime. A stop ended every thread and left
them running until the process exited, still able to write to the database.

`Services::spawn_task` starts an async task as a service: it shows on the
service board, and a stop aborts it at its next `.await` and waits for it
up to the shared deadline. `ServiceBoard::spawn_task_job` lists the trash,
timeline and album refreshes a listing starts as jobs, and the My Files
share-id repair runs as a job too.

The sims now fail a run whose stops leave a service running.
2026-11-26 18:47:16 +01:00
8 changed files with 271 additions and 74 deletions

No files matched your search

+181 -24
View File
@@ -13,10 +13,17 @@
//! one up to a shared deadline, naming any that is still running then.
//! [`ServiceBoard`] is the live view of the same threads, for diagnostics.
//!
//! A service can also be an async task on the mount's runtime
//! ([`Services::spawn_task`]), such as the loops that follow Drive's event
//! streams. A stop aborts it at its next `.await` and waits for it to go, up
//! to the same deadline. Such a task used to run until the runtime went
//! away, which on a stop is when the process exits.
//!
//! Work a request starts and does not wait for runs as a one-shot job
//! ([`ServiceBoard::spawn_job`]): a named thread, listed on the board while
//! it runs, and not joined on stop.
//! ([`ServiceBoard::spawn_job`] on a thread, [`ServiceBoard::spawn_task_job`]
//! on the runtime): listed on the board while it runs, and not joined on stop.
use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::thread::JoinHandle;
@@ -105,16 +112,7 @@ impl ServiceBoard {
where
F: FnOnce() + Send + 'static,
{
let id = self.0.next_job.fetch_add(1, Ordering::Relaxed);
self.0.jobs.lock().push(Job {
id,
name: name.to_owned(),
started: Instant::now(),
});
let guard = JobGuard {
board: self.0.clone(),
id,
};
let guard = self.add_job(name);
std::thread::Builder::new()
.name(name.to_owned())
.spawn(move || {
@@ -126,6 +124,34 @@ impl ServiceBoard {
.map(|_| ())
}
/// Start `task` on `rt` as a one-shot job, like [`spawn_job`](Self::spawn_job)
/// for work that is async: a refresh a listing starts and does not wait
/// for. It shows in [`jobs`](Self::jobs) until it ends, by return, panic
/// or the runtime going away.
pub fn spawn_task_job<F>(&self, rt: &tokio::runtime::Handle, name: &str, task: F)
where
F: Future<Output = ()> + Send + 'static,
{
let guard = self.add_job(name);
rt.spawn(async move {
let _guard = guard;
task.await;
});
}
fn add_job(&self, name: &str) -> JobGuard {
let id = self.0.next_job.fetch_add(1, Ordering::Relaxed);
self.0.jobs.lock().push(Job {
id,
name: name.to_owned(),
started: Instant::now(),
});
JobGuard {
board: self.0.clone(),
id,
}
}
fn add(&self, name: &str) -> Arc<AtomicBool> {
let running = Arc::new(AtomicBool::new(true));
self.0.services.lock().push(Entry {
@@ -159,10 +185,28 @@ impl Drop for Running {
}
struct Service {
handle: JoinHandle<()>,
handle: Handle,
wake: Option<Wake>,
}
/// A service is a thread, or an async task on the mount's runtime.
enum Handle {
Thread(JoinHandle<()>),
Task {
name: String,
task: tokio::task::JoinHandle<()>,
},
}
impl Handle {
fn is_finished(&self) -> bool {
match self {
Handle::Thread(handle) => handle.is_finished(),
Handle::Task { task, .. } => task.is_finished(),
}
}
}
/// The service threads one mount started, and how to stop them.
pub struct Services {
board: ServiceBoard,
@@ -195,7 +239,10 @@ impl Services {
});
match spawned {
Ok(handle) => {
self.started.push(Service { handle, wake });
self.started.push(Service {
handle: Handle::Thread(handle),
wake,
});
Ok(())
}
Err(error) => {
@@ -206,31 +253,64 @@ impl Services {
}
}
/// How many threads were started.
/// Start `task` on `rt` as a service named `name`. [`stop`](Self::stop)
/// aborts it, so it ends at its next `.await`; a task does not need to
/// watch the [`Shutdown`] signal itself. Code between two `.await`s runs
/// to its end, so a write it makes there is not cut in half.
pub fn spawn_task<F>(&mut self, rt: &tokio::runtime::Handle, name: &str, task: F)
where
F: Future<Output = ()> + Send + 'static,
{
let guard = Running(self.board.add(name));
let task = rt.spawn(async move {
let _guard = guard;
task.await;
});
self.started.push(Service {
handle: Handle::Task {
name: name.to_owned(),
task,
},
wake: None,
});
}
/// How many services were started.
pub fn len(&self) -> usize {
self.started.len()
}
/// Whether no thread was started.
/// Whether no service was started.
pub fn is_empty(&self) -> bool {
self.started.is_empty()
}
/// Stop every thread: signal `shutdown`, wake each thread in reverse start
/// order, then join them in the same order until `deadline`. Returns the
/// names of the threads still running at the deadline; they are left
/// behind rather than waited for.
/// Stop every service: signal `shutdown`, wake each thread and abort each
/// task in reverse start order, then join them in the same order until
/// `deadline`. Returns the names of the services still running at the
/// deadline; they are left behind rather than waited for.
pub fn stop(self, shutdown: &Shutdown, deadline: Instant) -> Vec<String> {
shutdown.stop();
for service in self.started.iter().rev() {
if let Some(wake) = &service.wake {
wake();
}
if let Handle::Task { task, .. } = &service.handle {
task.abort();
}
}
join_until(
self.started.into_iter().rev().map(|service| service.handle),
deadline,
)
let mut running = Vec::new();
for service in self.started.into_iter().rev() {
while !service.handle.is_finished() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
match service.handle {
Handle::Thread(handle) => running.extend(join_until([handle], deadline)),
Handle::Task { name, task } if !task.is_finished() => running.push(name),
Handle::Task { .. } => {}
}
}
running
}
}
@@ -364,6 +444,83 @@ mod tests {
assert!(board.jobs().is_empty());
}
#[test]
fn a_stop_aborts_a_task_and_shows_it_ended() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
let board = ServiceBoard::default();
let mut services = Services::new(board.clone());
// Never ends on its own and never looks at the shutdown signal.
services.spawn_task(rt.handle(), "poller", async {
loop {
tokio::time::sleep(Duration::from_millis(5)).await;
}
});
assert_eq!(services.len(), 1);
assert!(board.health()[0].running);
let left = services.stop(
&Shutdown::default(),
Instant::now() + Duration::from_secs(5),
);
assert!(left.is_empty(), "still running: {left:?}");
assert!(!board.health()[0].running);
}
#[test]
fn a_task_stuck_between_awaits_is_named_at_the_deadline() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
let mut services = Services::new(ServiceBoard::default());
let (release, wait) = mpsc::channel::<()>();
let (started_tx, started_rx) = mpsc::channel::<()>();
// Blocks its worker thread, so an abort cannot reach it until it yields.
services.spawn_task(rt.handle(), "blocking", async move {
let _ = started_tx.send(());
let _ = wait.recv();
});
started_rx.recv_timeout(Duration::from_secs(5)).unwrap();
let left = services.stop(
&Shutdown::default(),
Instant::now() + Duration::from_millis(100),
);
assert_eq!(left, ["blocking"]);
drop(release);
}
#[test]
fn a_task_job_shows_while_it_runs_and_leaves_when_it_ends() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
let board = ServiceBoard::default();
let (release, wait) = tokio::sync::oneshot::channel::<()>();
board.spawn_task_job(rt.handle(), "pdfs-test-refresh", async move {
let _ = wait.await;
});
let jobs = board.jobs();
assert_eq!(jobs.len(), 1);
assert_eq!(jobs[0].name, "pdfs-test-refresh");
release.send(()).unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
while !board.jobs().is_empty() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
assert!(board.jobs().is_empty());
}
#[test]
fn a_job_that_panics_leaves_the_list() {
let board = ServiceBoard::default();
+17 -15
View File
@@ -140,16 +140,17 @@ impl Core {
return;
}
let core = self.clone();
self.rt.spawn(async move {
let refreshed = core.refresh_albums().await;
core.photo_jobs
.albums_refreshing
.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background album refresh failed"),
}
});
self.services
.spawn_task_job(&self.rt, "pdfs-albums-refresh", async move {
let refreshed = core.refresh_albums().await;
core.photo_jobs
.albums_refreshing
.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background album refresh failed"),
}
});
}
/// A page of one album's photos, newest capture first. The album's contents
@@ -179,11 +180,12 @@ impl Core {
} else if self.listing_stale(&stamp, TIMELINE_TTL) {
let core = self.clone();
let album = album.clone();
self.rt.spawn(async move {
if let Err(e) = core.refresh_album(&album).await {
warn!(%album, error = %e, "background album refresh failed");
}
});
self.services
.spawn_task_job(&self.rt, "pdfs-album-refresh", async move {
if let Err(e) = core.refresh_album(&album).await {
warn!(%album, error = %e, "background album refresh failed");
}
});
}
let page = self
+16 -7
View File
@@ -658,7 +658,7 @@ pub(crate) fn mount_with(
// the walk is I/O-heavy and must never sit in front of a FUSE callback.
if matches!(host, Host::Daemon) {
if let Some(gallery) = &core.gallery {
rt.spawn(gallery.clone().poll(core.clone()));
workers.spawn_task(&rt, "pdfs-gallery", gallery.clone().poll(core.clone()));
}
let db = core.db.clone();
let indexing = core.indexing.clone();
@@ -798,19 +798,28 @@ pub(crate) fn mount_with(
}
}
};
rt.spawn(run_event_sync(core.drive.clone(), scope, core.clone()));
// Services rather than bare tasks: a stop aborts them. Before, they ran
// until the runtime went away, which on a stop is when the process exits.
workers.spawn_task(
&rt,
"pdfs-event-sync",
run_event_sync(core.drive.clone(), scope, core.clone()),
);
// The photos volume has its own event stream; without it the gallery only
// learns about a phone-side deletion when the timeline goes stale.
rt.spawn(run_photos_event_sync(core.clone()));
workers.spawn_task(
&rt,
"pdfs-photo-events",
run_photos_event_sync(core.clone()),
);
// Not in a simulation: `client` there reaches no API, and the thread, still
// waiting on it after the stop, held the database a test opens next.
if online && matches!(host, Host::Daemon) {
let repair_core = core.clone();
let root_uid = core.primary_root_uid.clone();
if let Err(error) = std::thread::Builder::new()
.name("pdfs-share-id".into())
.spawn(move || repair_core.repair_primary_share_id(&root_uid))
{
if let Err(error) = core.services.spawn_job("pdfs-share-id", move || {
repair_core.repair_primary_share_id(&root_uid)
}) {
warn!(%error, "start My Files share-id repair failed");
}
}
+13 -12
View File
@@ -582,18 +582,19 @@ impl Core {
return;
}
let core = self.clone();
self.rt.spawn(async move {
let refreshed = core.refresh_timeline().await;
core.photo_jobs
.timeline_refreshing
.store(false, Ordering::SeqCst);
// Only a refresh that landed: a front-end re-reading after a failed
// one would find the timeline still stale and start another.
match refreshed {
Ok(_) => core.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background timeline refresh failed"),
}
});
self.services
.spawn_task_job(&self.rt, "pdfs-timeline-refresh", async move {
let refreshed = core.refresh_timeline().await;
core.photo_jobs
.timeline_refreshing
.store(false, Ordering::SeqCst);
// Only a refresh that landed: a front-end re-reading after a failed
// one would find the timeline still stale and start another.
match refreshed {
Ok(_) => core.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background timeline refresh failed"),
}
});
}
/// How far the running timeline refresh has got reading photo metadata, or
+14
View File
@@ -140,6 +140,14 @@ pub(crate) fn run(seed: u64, profile: &'static Profile) -> Result<(), String> {
}
}
run.logged.extend(take_logged());
// Every stop, the restarts' included, ends all the services a mount
// started; one left running is a second generation beside the next mount's.
let outcome = outcome.and_then(
|()| match run.logged.iter().find(|line| left_running(line)) {
Some(line) => Err(format!("shutdown: a stop left services running: {line}")),
None => Ok(()),
},
);
match outcome {
Ok(()) => {
let _ = std::fs::remove_dir_all(&dir);
@@ -608,6 +616,12 @@ fn outcome(actual: &Result<Result<(), i32>, String>) -> String {
}
}
/// Whether `line` is the mount's report of services still running at its
/// stop deadline (`mount::halt_workers`).
fn left_running(line: &str) -> bool {
line.starts_with("background workers did not finish in time")
}
/// Run `profile` over the seeds the environment asks for: `PDFS_SIM_SEED`
/// alone, or `PDFS_SIM_SEEDS` of them (default `default_seeds`) from 1.
pub(crate) fn run_seeds(profile: &'static Profile, default_seeds: u64) {
+11 -10
View File
@@ -266,16 +266,17 @@ impl Core {
return;
}
let core = self.clone();
self.rt.spawn(async move {
let refreshed = core.refresh_trash().await;
core.trash.trash_refreshing.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Trash]),
Err(e) => warn!(error = %e, "background trash refresh failed"),
}
// After the flag, so a waiter that wakes on this sees it cleared.
core.trash.trash_progress.notify_waiters();
});
self.services
.spawn_task_job(&self.rt, "pdfs-trash-refresh", async move {
let refreshed = core.refresh_trash().await;
core.trash.trash_refreshing.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Trash]),
Err(e) => warn!(error = %e, "background trash refresh failed"),
}
// After the flag, so a waiter that wakes on this sees it cleared.
core.trash.trash_progress.notify_waiters();
});
}
/// Wait for the in-flight trash refresh to make progress, for at most
+13 -4
View File
@@ -469,7 +469,9 @@ both with `pdfs_core::search::relevance_score`, so the prompt can merge them int
| `pdfs-control` | Accepts control connections; at most 64 handlers |
| `pdfs-events` | Publishes status, transfer and topic changes to subscribers |
| `pdfs-sync`, `pdfs-sync-poll` | Mirror passes and the remote poll (§7) |
| Tokio runtime | Remote calls, and the Drive and photos event streams (§6) |
| `pdfs-event-sync`, `pdfs-photo-events` | Async tasks on the Tokio runtime that follow the Drive and photos event streams (§6) |
| `pdfs-gallery` | Async task. Refreshes the gallery's visibility every minute and on request |
| Tokio runtime | Remote calls |
| `pdfs-online-probe` | Probes Drive while offline |
| `pdfs-pin-keeper` | Checks pins once a second for work: every pin at startup, when the link returns and after the event feed loses continuity, and the pins a batch of remote events changed. Downloads files kept offline that are missing or stale; failures retry with a backoff of 30 s to 30 min (`docs/BUGS.md` B282) |
| `pdfs-supervisor` | Logs workers that hold one job for minutes, a queue that stops draining, and control requests that never return; samples memory; pings the systemd watchdog only after a round trip over the control socket succeeds (`WatchdogSec=120`) |
@@ -481,14 +483,20 @@ instead of leaving them behind (`docs/BUGS.md` B44). The mount starts its long-l
through `pdfs_core::lifecycle::Services`. Each one is started with its name and, if it blocks where
the signal does not reach, the call that wakes it: the drain's condvar, the sync engine's `Stop`
message, a connection to the control socket. A stop signals, wakes and joins them in reverse start
order, up to one 10-second deadline, and names any that are still running at the end.
order, up to one 10-second deadline, and names any that are still running at the end. A
service can also be an async task on the runtime (`Services::spawn_task`): the event streams and
the gallery refresh. A stop aborts such a task at its next `.await` and waits for it to end. These
tasks used to run until the runtime went away, which on a stop is when the process exits.
The sims fail a run whose stops leave a service running.
`pdfs diagnostics` reports what each worker is doing and which services are still running. The
supervisor warns once about a service that ended while the mount runs.
Work a request starts and does not wait for (a cache check, `VACUUM`, an import, a folder pin, a
re-date, a profile backup, a size upgrade) runs as a one-shot job:
`ServiceBoard::spawn_job` starts it on a named thread and lists it until it ends. `pdfs
diagnostics` shows the jobs running and how long each has run. Jobs are not joined on stop.
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.
---
@@ -738,7 +746,8 @@ The work goes in steps. Each ships the same behaviour with the simulation tests
| 5 | `pdfs-vfs`: open files, then directories and renames, behind the FUSE adapter |
| 6 | One admission policy for mirrors, reads and writeback |
Step 3 so far: the daemon's long-lived threads start and stop through one `Services` set (§9).
Step 3 so far: the daemon's long-lived threads and async loops start and stop through one
`Services` set (§9).
`Core`'s fields are grouped by owner, each group a struct in the module that owns it:
`photos::PhotoJobs`, `drain::DrainState`, `reads::ReadState`, `sizes::SizeState`,
`trash::TrashState`, `shared::SharedState`, `sharing::QuotaCache` and `sweep::SweepState`.
+6 -2
View File
@@ -18,8 +18,8 @@ kept, with a list of the folders that changed on Proton Drive since (49).
- **`pdfs diagnostics` says which of the daemon's background services are running.** If one
ends while the drive is mounted, for example the sync engine after a crash, the journal says
so once, by name, instead of saying nothing until a restart. It also lists the jobs running
in the background, such as a cache check, an import or a folder being pinned, and how long
each has run.
in the background, such as a cache check, an import, a folder being pinned or a refresh of
the trash or the photo timeline, and how long each has run.
- **`PDFS_INSTANCE` runs a second client next to your own.** With a name set, the client keeps
its own directories, keyring entry, kernel keys and mountpoint, so a test account can run
alongside the account you use. `scripts/live-bench.py` uses it to time one edit, from the
@@ -59,6 +59,10 @@ kept, with a list of the folders that changed on Proton Drive since (49).
first pass, and whenever the change feed lost track (#53).
### Fixed
- **A stop ends the loops that follow Proton Drive's change feed before the daemon exits.**
The loops that read the Drive and photos event streams, and the gallery refresh, kept
running after every other service had stopped, and could still write to the database while
the process exited.
- **A synced folder whose folder on Drive is in the trash no longer blocks attaching another.**
Until it was removed, every `pdfs sync attach` failed with "remote sync folder is in the trash",
whatever folder it named (B299).