refactor(backend): extract workspace task drivers

This commit is contained in:
Tunglies
2026-11-28 21:13:05 +08:00
parent d4b138d553
commit f059d1ebb5
13 changed files with 308 additions and 81 deletions
Generated
+10
View File
@@ -1098,6 +1098,7 @@ dependencies = [
"clash-verge-logging",
"clash-verge-media-unlock",
"clash-verge-signal",
"clash-verge-task",
"clash_verge_service_ipc",
"dark-light",
"deelevate",
@@ -1222,6 +1223,15 @@ dependencies = [
"tokio",
]
[[package]]
name = "clash-verge-task"
version = "0.1.0"
dependencies = [
"futures",
"parking_lot 0.13.0",
"tokio",
]
[[package]]
name = "clash_verge_service_ipc"
version = "2.8.2"
+3
View File
@@ -2,6 +2,7 @@
members = [
"src-tauri",
"crates/clash-verge-draft",
"crates/clash-verge-task",
"crates/clash-verge-media-unlock",
"crates/clash-verge-logging",
"crates/clash-verge-signal",
@@ -52,6 +53,7 @@ muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdf
[workspace.dependencies]
clash-verge-draft = { path = "crates/clash-verge-draft" }
clash-verge-task = { path = "crates/clash-verge-task" }
clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" }
clash-verge-logging = { path = "crates/clash-verge-logging" }
clash-verge-signal = { path = "crates/clash-verge-signal" }
@@ -65,6 +67,7 @@ tauri = { version = "2.12.7" }
tauri-plugin-clipboard-manager = "2.5.0"
parking_lot = "0.13.0"
anyhow = "1.0.105"
futures = "0.3.34"
chrono = "0.4.45"
criterion = { version = "0.8.2", features = ["async_tokio"] }
tokio = { version = "1.54.1", features = [
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "clash-verge-task"
version = "0.1.0"
edition = "2024"
publish = false
[dependencies]
futures = { workspace = true }
parking_lot = { workspace = true }
tokio = { workspace = true }
[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
[lints]
workspace = true
+4
View File
@@ -0,0 +1,4 @@
//! Single-owner task drivers with caller-managed runtime and cancellation.
pub mod scheduled_task;
pub mod watch_task;
@@ -0,0 +1,94 @@
use futures::FutureExt as _;
use parking_lot::Mutex;
use std::{future::Future, panic::AssertUnwindSafe, sync::Arc};
use tokio::{
sync::Notify,
time::{Instant, sleep_until},
};
/// The next decision after the driver drains pending inputs.
pub enum Next<W> {
Idle,
At(Instant),
Run(W),
}
/// Synchronous policy owned and called by one driver.
pub trait ScheduledTask {
/// The merged pending input. Its default value represents no requests.
type Input: Default;
type Work: Copy + Send;
type Output;
fn on_input(&mut self, input: Self::Input, now: Instant);
fn next(&mut self, now: Instant) -> Next<Self::Work>;
/// Receives the execution result or an unwind from the execution callback.
fn finished(&mut self, work: Self::Work, result: std::thread::Result<Self::Output>, now: Instant);
}
/// A coalescing slot shared with one driver.
pub struct Mailbox<I> {
pending: Mutex<I>,
changed: Notify,
}
impl<I> Mailbox<I> {
/// Merge into the pending slot under a short synchronous lock.
///
/// Return true from `merge` when the driver should wake up. This only
/// submits input. Any completion reply belongs to the caller's protocol.
pub fn update(&self, merge: impl FnOnce(&mut I) -> bool) {
let changed = merge(&mut *self.pending.lock());
if changed {
self.changed.notify_one();
}
}
}
/// Create the mailbox and its driver. The caller chooses how to run the future.
///
/// While the driver is running, pending inputs wake idle waits and do not
/// interrupt an active job. Keep the driver alive until any issued effects
/// complete. Dropping producers does not shut it down.
pub fn new<P, F, Fut>(policy: P, execute: F) -> (Arc<Mailbox<P::Input>>, impl Future<Output = ()> + Send + 'static)
where
P: ScheduledTask + Send + 'static,
P::Input: Send + 'static,
F: FnMut(P::Work) -> Fut + Send + 'static,
Fut: Future<Output = P::Output> + Send + 'static,
{
let inbox = Arc::new(Mailbox {
pending: Mutex::default(),
changed: Notify::new(),
});
let receiver = Arc::clone(&inbox);
(inbox, drive(policy, receiver, execute))
}
async fn drive<P, F, Fut>(mut policy: P, inbox: Arc<Mailbox<P::Input>>, mut execute: F)
where
P: ScheduledTask,
F: FnMut(P::Work) -> Fut,
Fut: Future<Output = P::Output>,
{
loop {
let input = std::mem::take(&mut *inbox.pending.lock());
let now = Instant::now();
policy.on_input(input, now);
match policy.next(now) {
Next::Idle => inbox.changed.notified().await,
Next::At(due) => {
tokio::select! {
_ = inbox.changed.notified() => {}
_ = sleep_until(due) => {}
}
}
Next::Run(work) => {
// Pending inputs merge while the job runs. They cannot interrupt its effects.
let run = &mut execute;
let result = AssertUnwindSafe(async move { run(work).await }).catch_unwind().await;
policy.finished(work, result, Instant::now());
}
}
}
}
@@ -2,11 +2,14 @@ use futures::FutureExt as _;
use std::{future::Future, panic::AssertUnwindSafe};
use tokio::sync::watch;
pub(crate) async fn run<T, F, Fut>(
mut desired: watch::Receiver<Option<T>>,
mut run: F,
mut on_panic: impl FnMut(T) + Send,
) where
/// Run a session for each observed nonempty plan, beginning on the first change.
///
/// Subscribe while the plan is `None` before publishing the first session.
/// While a session runs, plans may coalesce to the latest value. The callback
/// chooses where to observe replacements and owns any issued effects until it
/// returns. An unwinding callback is reported before observing the next plan.
pub async fn run<T, F, Fut>(mut desired: watch::Receiver<Option<T>>, mut run: F, mut on_panic: impl FnMut(T) + Send)
where
T: Clone + Send + Sync,
F: FnMut(T, watch::Receiver<Option<T>>) -> Fut + Send,
Fut: Future<Output = ()> + Send,
+160
View File
@@ -0,0 +1,160 @@
use clash_verge_task::{
scheduled_task::{self, Mailbox, Next, ScheduledTask},
watch_task,
};
use std::{error::Error, time::Duration};
use tokio::{
sync::{mpsc, oneshot, watch},
time::{Instant, advance, timeout},
};
type TestResult = Result<(), Box<dyn Error>>;
struct Schedule {
due: Option<Instant>,
completed: mpsc::UnboundedSender<bool>,
}
impl ScheduledTask for Schedule {
type Input = Option<Instant>;
type Work = Instant;
type Output = ();
fn on_input(&mut self, input: Self::Input, _: Instant) {
self.due = self.due.into_iter().chain(input).min();
}
fn next(&mut self, now: Instant) -> Next<Instant> {
match self.due {
Some(due) if due <= now => {
self.due = None;
Next::Run(due)
}
Some(due) => Next::At(due),
None => Next::Idle,
}
}
fn finished(&mut self, _: Instant, result: std::thread::Result<()>, _: Instant) {
let _ = self.completed.send(result.is_ok());
}
}
fn request(mailbox: &Mailbox<Option<Instant>>, due: Instant) {
mailbox.update(|pending| {
if pending.is_some_and(|current| current <= due) {
return false;
}
*pending = Some(due);
true
});
}
async fn receive<T: Send>(receiver: &mut mpsc::UnboundedReceiver<T>) -> Result<T, Box<dyn Error>> {
timeout(Duration::from_secs(10), receiver.recv())
.await?
.ok_or_else(|| "driver event channel closed".into())
}
#[tokio::test(start_paused = true)]
async fn an_earlier_request_reschedules_an_idle_wait() -> TestResult {
let (completed, mut results) = mpsc::unbounded_channel();
let (mailbox, driver) = scheduled_task::new(Schedule { due: None, completed }, |_| async {});
let mut driver = Box::pin(driver);
let start = Instant::now();
request(&mailbox, start + Duration::from_secs(8));
assert!(futures::poll!(driver.as_mut()).is_pending());
request(&mailbox, start + Duration::from_secs(2));
let driver = tokio::spawn(driver);
assert!(receive(&mut results).await?);
assert_eq!(Instant::now() - start, Duration::from_secs(2));
driver.abort();
Ok(())
}
#[tokio::test(start_paused = true)]
async fn active_work_finishes_before_one_coalesced_successor() -> TestResult {
let (completed, mut results) = mpsc::unbounded_channel();
let (started, mut runs) = mpsc::unbounded_channel();
let (mailbox, driver) = scheduled_task::new(Schedule { due: None, completed }, move |due| {
let (release, wait) = oneshot::channel();
let _ = started.send((due, release));
async move {
let _ = wait.await;
}
});
let driver = tokio::spawn(driver);
let start = Instant::now();
request(&mailbox, start);
let (_, release) = receive(&mut runs).await?;
let next = start + Duration::from_secs(2);
request(&mailbox, start + Duration::from_secs(4));
request(&mailbox, next);
advance(Duration::from_secs(5)).await;
assert!(runs.try_recv().is_err());
assert!(results.try_recv().is_err());
release.send(()).map_err(|()| "first job was dropped")?;
assert!(receive(&mut results).await?);
let (due, release) = receive(&mut runs).await?;
assert_eq!(due, next);
release.send(()).map_err(|()| "second job was dropped")?;
assert!(receive(&mut results).await?);
assert!(timeout(Duration::from_secs(1), runs.recv()).await.is_err());
driver.abort();
Ok(())
}
#[tokio::test(start_paused = true)]
#[allow(clippy::panic, reason = "inject an unwind into the execution future")]
async fn a_job_panic_reports_failure_and_allows_more_work() -> TestResult {
let (completed, mut results) = mpsc::unbounded_channel();
let start = Instant::now();
let (mailbox, driver) = scheduled_task::new(Schedule { due: None, completed }, move |due| async move {
if due == start {
panic!("test job panic");
}
});
let driver = tokio::spawn(driver);
request(&mailbox, start);
assert!(!receive(&mut results).await?);
request(&mailbox, start + Duration::from_secs(1));
assert!(receive(&mut results).await?);
driver.abort();
Ok(())
}
#[tokio::test(start_paused = true)]
#[allow(clippy::panic, reason = "inject an unwind after observing session replacement")]
async fn a_session_panic_does_not_consume_the_replacement() -> TestResult {
let (plan, desired) = watch::channel(None);
let (event, mut events) = mpsc::unbounded_channel();
let panicked = event.clone();
let driver = tokio::spawn(watch_task::run(
desired,
move |session, mut updates| {
let event = event.clone();
async move {
let _ = event.send((session, false));
if session == 1 && updates.changed().await.is_ok() {
panic!("test session panic");
}
}
},
move |session| {
let _ = panicked.send((session, true));
},
));
plan.send_replace(Some(1));
assert_eq!(receive(&mut events).await?, (1, false));
plan.send_replace(Some(2));
assert_eq!(receive(&mut events).await?, (1, true));
assert_eq!(receive(&mut events).await?, (2, false));
drop(plan);
driver.await?;
Ok(())
}
+3 -1
View File
@@ -25,7 +25,9 @@ These rules supplement the repository's root `AGENTS.md`.
Cancel work only at cancellation-safe boundaries. Keep issued side effects
owned through completion or explicit reconciliation. Preserve shared
transaction boundaries and ensure a task can reply without acquiring a lock
held by the waiting caller.
held by the waiting caller. Reuse the drivers in
[`clash-verge-task`](../crates/clash-verge-task/src/lib.rs) for coalescing
jobs and replaceable sessions. Keep domain policy and runtime startup local.
- **Retry ownership.** Bounded retries share backend policy while preserving
attempts, delays and terminal errors. Background monitors own their lifetime
and cancellation separately; waiting for a condition or traversing distinct
+2 -1
View File
@@ -31,6 +31,7 @@ tauri-build = { version = "2.7.6", features = [] }
[dependencies]
clash-verge-draft = { workspace = true }
clash-verge-task = { workspace = true }
clash-verge-media-unlock = { workspace = true }
clash-verge-logging = { workspace = true }
clash-verge-i18n = { workspace = true }
@@ -82,7 +83,7 @@ aes-gcm = { version = "0.11.1" }
base64 = "0.23.1"
sha2 = "0.11.2"
getrandom = "0.4.3"
futures = "0.3.34"
futures = { workspace = true }
gethostname = "1.1.0"
tauri-plugin-notification = "2.8.1"
backon = { version = "1.6.0", features = ["tokio-sleep"] }
+2 -1
View File
@@ -8,7 +8,7 @@ use crate::{
service,
sysopt::{Sysopt, format_bypass},
},
process::{AsyncHandler, watch_task},
process::AsyncHandler,
utils::{
notification::{NotificationEvent, needs_system_notification, notify_event},
server,
@@ -18,6 +18,7 @@ use crate::{
use anyhow::{Result, ensure};
use clash_verge_logging::{Type, logging};
use clash_verge_service_ipc::{MacosProxyConfig, OwnerSessionProof, ProxyApplyOutcome};
use clash_verge_task::watch_task;
use std::{
borrow::Borrow,
future::Future,
+1 -1
View File
@@ -19,7 +19,6 @@ use crate::{
process::{
AsyncHandler,
scheduled_task::{self, Mailbox, Next, ScheduledTask},
watch_task,
},
};
use anyhow::{Context as _, Result, anyhow, bail};
@@ -30,6 +29,7 @@ use clash_verge_service_ipc::{
RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
StageRuntimeOutcome, StartClashRequest, WriterConfig,
};
use clash_verge_task::watch_task;
use parking_lot::Mutex;
use std::{
collections::HashMap,
-1
View File
@@ -2,4 +2,3 @@ mod async_handler;
pub use async_handler::AsyncHandler;
pub(crate) mod scheduled_task;
pub(crate) mod watch_task;
+5 -71
View File
@@ -1,41 +1,7 @@
use super::AsyncHandler;
use futures::FutureExt as _;
use parking_lot::Mutex;
use std::{future::Future, panic::AssertUnwindSafe, sync::Arc};
use tokio::{
sync::Notify,
time::{Instant, sleep_until},
};
use std::{future::Future, sync::Arc};
pub(crate) enum Next<W> {
Idle,
At(Instant),
Run(W),
}
pub(crate) trait ScheduledTask {
type Input: Default;
type Work: Copy + Send;
type Output;
fn on_input(&mut self, input: Self::Input, now: Instant);
fn next(&mut self, now: Instant) -> Next<Self::Work>;
fn finished(&mut self, work: Self::Work, result: std::thread::Result<Self::Output>, now: Instant);
}
pub(crate) struct Mailbox<I> {
pending: Mutex<I>,
changed: Notify,
}
impl<I> Mailbox<I> {
pub(crate) fn update(&self, merge: impl FnOnce(&mut I) -> bool) {
let changed = merge(&mut *self.pending.lock());
if changed {
self.changed.notify_one();
}
}
}
pub(crate) use clash_verge_task::scheduled_task::{Mailbox, Next, ScheduledTask};
pub(crate) fn spawn<P, F, Fut>(policy: P, execute: F) -> Arc<Mailbox<P::Input>>
where
@@ -44,39 +10,7 @@ where
F: FnMut(P::Work) -> Fut + Send + 'static,
Fut: Future<Output = P::Output> + Send + 'static,
{
let inbox = Arc::new(Mailbox {
pending: Mutex::default(),
changed: Notify::new(),
});
let receiver = Arc::clone(&inbox);
AsyncHandler::spawn(move || drive(policy, receiver, execute));
inbox
}
async fn drive<P, F, Fut>(mut policy: P, inbox: Arc<Mailbox<P::Input>>, mut execute: F)
where
P: ScheduledTask,
F: FnMut(P::Work) -> Fut,
Fut: Future<Output = P::Output>,
{
loop {
let input = std::mem::take(&mut *inbox.pending.lock());
let now = Instant::now();
policy.on_input(input, now);
match policy.next(now) {
Next::Idle => inbox.changed.notified().await,
Next::At(due) => {
tokio::select! {
_ = inbox.changed.notified() => {}
_ = sleep_until(due) => {}
}
}
Next::Run(work) => {
// Pending inputs merge while the job runs. They cannot interrupt its effects.
let run = &mut execute;
let result = AssertUnwindSafe(async move { run(work).await }).catch_unwind().await;
policy.finished(work, result, Instant::now());
}
}
}
let (mailbox, driver) = clash_verge_task::scheduled_task::new(policy, execute);
AsyncHandler::spawn(move || driver);
mailbox
}