mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-29 09:00:03 +08:00
refactor(backend): extract workspace task drivers
This commit is contained in:
@@ -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
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
use futures::FutureExt as _;
|
||||
use std::{future::Future, panic::AssertUnwindSafe};
|
||||
use tokio::sync::watch;
|
||||
|
||||
/// 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,
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
Reference in New Issue
Block a user