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
+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
}
-28
View File
@@ -1,28 +0,0 @@
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
T: Clone + Send + Sync,
F: FnMut(T, watch::Receiver<Option<T>>) -> Fut + Send,
Fut: Future<Output = ()> + Send,
{
while desired.changed().await.is_ok() {
let state = desired.borrow_and_update().clone();
if let Some(state) = state {
// Cancellation can consume updates on this clone without skipping them in the owner.
let updates = desired.clone();
if AssertUnwindSafe(async { run(state.clone(), updates).await })
.catch_unwind()
.await
.is_err()
{
on_panic(state);
}
}
}
}