mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-01 10:40:14 +08:00
refactor(backend): share single-owner drivers for background tasks (#8759)
* docs(backend): define background task ownership * refactor(backend): give background operations single task owners * test(backend): remove actor migration regression cases * docs(changelog): drop backend actor migration entry * refactor(backend): extract workspace task drivers * fix(timer): omit profile identifier from panic log * docs(backend): define workspace crate boundaries * refactor(lightweight): use the task countdown driver * refactor(lightweight): name countdown callbacks * refactor(task): simplify driver startup and coalescing requests * refactor(core): bind service handoff to the sidecar generation * refactor(tun): coalesce background run state reconciliation * refactor(core): own sidecar exit resources in one session * refactor(core): remove automatic Windows service handoff * refactor(task): simplify coalescing job signals * refactor(runstate): keep operation status with service state * refactor(dns): coalesce background override synchronization * refactor(sysproxy): own the local guard under its operation lock * fix(tray): read menu settings at publication * fix(dns): retain script lock across caller cancellation * refactor(profiles): own selected node restoration in one task * refactor(timer): own subscription schedules in the scheduler * test(timer): remove the added application test * fix(service): renew provider sync retry budget on refresh
This commit is contained in:
+86
-189
@@ -1,32 +1,26 @@
|
||||
use crate::{
|
||||
config::{Config, PrfItem},
|
||||
config::{Config, IProfiles, PrfItem},
|
||||
feat,
|
||||
process::AsyncHandler,
|
||||
singleton,
|
||||
utils::resolve::is_resolve_done,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use anyhow::{Context as _, Result};
|
||||
use clash_verge_draft::Draft;
|
||||
use clash_verge_logging::{Type, logging, logging_error};
|
||||
use futures::StreamExt as _;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
use futures::{FutureExt as _, StreamExt as _};
|
||||
use std::{collections::HashMap, panic::AssertUnwindSafe, time::Duration};
|
||||
use tokio::{
|
||||
sync::mpsc,
|
||||
sync::{mpsc, oneshot},
|
||||
time::{sleep, timeout},
|
||||
};
|
||||
use tokio_util::time::{DelayQueue, delay_queue::Key};
|
||||
use tristr::alias::String;
|
||||
|
||||
enum TimerCommand {
|
||||
Apply(HashMap<String, TaskSchedule>),
|
||||
RunNow(String),
|
||||
Initialize(oneshot::Sender<()>),
|
||||
Refresh(oneshot::Sender<()>),
|
||||
NextUpdateTime(String, oneshot::Sender<Option<i64>>),
|
||||
TaskFinished(String),
|
||||
}
|
||||
|
||||
@@ -70,19 +64,19 @@ async fn run_timer_profile_update_transition<Started, Update, UpdateFuture, Fini
|
||||
Started: FnOnce(),
|
||||
Update: FnOnce() -> UpdateFuture,
|
||||
UpdateFuture: std::future::Future<Output = Output>,
|
||||
Finished: FnOnce(Output),
|
||||
Finished: FnOnce(std::thread::Result<Output>),
|
||||
Completed: FnOnce(),
|
||||
{
|
||||
update_started();
|
||||
let result = update_profile().await;
|
||||
let result = AssertUnwindSafe(async { update_profile().await }).catch_unwind().await;
|
||||
update_finished(result);
|
||||
update_completed();
|
||||
}
|
||||
|
||||
impl TaskState {
|
||||
const fn new(key: Key, interval_minutes: u64) -> Self {
|
||||
const fn new(key: Option<Key>, interval_minutes: u64) -> Self {
|
||||
Self {
|
||||
key: Some(key),
|
||||
key,
|
||||
interval_minutes,
|
||||
running: false,
|
||||
retired: false,
|
||||
@@ -92,10 +86,6 @@ impl TaskState {
|
||||
|
||||
pub struct Timer {
|
||||
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
||||
command_rx: Mutex<Option<mpsc::UnboundedReceiver<TimerCommand>>>,
|
||||
refresh_lock: tokio::sync::Mutex<()>,
|
||||
pub timer_map: Arc<RwLock<HashMap<String, u64>>>,
|
||||
pub initialized: AtomicBool,
|
||||
}
|
||||
|
||||
singleton!(Timer, TIMER_INSTANCE);
|
||||
@@ -103,115 +93,31 @@ singleton!(Timer, TIMER_INSTANCE);
|
||||
impl Timer {
|
||||
fn new() -> Self {
|
||||
let (command_tx, command_rx) = mpsc::unbounded_channel();
|
||||
Self {
|
||||
command_tx,
|
||||
command_rx: Mutex::new(Some(command_rx)),
|
||||
refresh_lock: tokio::sync::Mutex::new(()),
|
||||
timer_map: Arc::new(RwLock::new(HashMap::new())),
|
||||
initialized: AtomicBool::new(false),
|
||||
}
|
||||
let scheduler_tx = command_tx.clone();
|
||||
AsyncHandler::spawn(move || async move {
|
||||
let profiles = Config::profiles().await;
|
||||
Self::run_scheduler(command_rx, scheduler_tx, profiles).await;
|
||||
});
|
||||
Self { command_tx }
|
||||
}
|
||||
|
||||
pub async fn init(&self) -> Result<()> {
|
||||
if self
|
||||
.initialized
|
||||
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_err()
|
||||
{
|
||||
logging!(debug, Type::Timer, "Timer already initialized, skipping...");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let command_rx = { self.command_rx.lock().take() };
|
||||
if let Some(command_rx) = command_rx {
|
||||
let command_tx = self.command_tx.clone();
|
||||
AsyncHandler::spawn(move || async move {
|
||||
Self::run_scheduler(command_rx, command_tx).await;
|
||||
});
|
||||
}
|
||||
|
||||
if let Err(e) = self.refresh().await {
|
||||
self.initialized.store(false, Ordering::SeqCst);
|
||||
logging!(error, Type::Timer, "Failed to initialize timer: {e:#}");
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
{
|
||||
let timer_map = self.timer_map.read();
|
||||
logging!(debug, Type::Timer, "Registered timer task count: {}", timer_map.len());
|
||||
for (uid, interval) in timer_map.iter() {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Registered timer task: uid={}, interval={}min",
|
||||
uid,
|
||||
interval
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Redundant with first_delay == ZERO, kept as the immediate path; mark_task_running
|
||||
// no-ops whichever of the two arrives second.
|
||||
let cur_timestamp = chrono::Local::now().timestamp();
|
||||
if let Some(items) = Config::profiles().await.data_arc().items.as_ref() {
|
||||
for item in items.iter() {
|
||||
if let Some(option) = item.option.as_ref()
|
||||
&& option.allow_auto_update.unwrap_or(true)
|
||||
&& let Some(interval) = option.update_interval
|
||||
&& interval > 0
|
||||
&& let Some(uid) = item.uid.as_ref()
|
||||
&& let Some(updated) = item.updated
|
||||
&& cur_timestamp - (updated as i64) >= (interval as i64) * 60
|
||||
{
|
||||
logging!(info, Type::Timer, "Running overdue timer task immediately: uid={}", uid);
|
||||
let _ = self.command_tx.send(TimerCommand::RunNow(uid.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logging!(info, Type::Timer, "Timer initialization completed");
|
||||
Ok(())
|
||||
self.update_schedule(TimerCommand::Initialize).await
|
||||
}
|
||||
|
||||
pub async fn refresh(&self) -> Result<()> {
|
||||
let _refresh_guard = self.refresh_lock.lock().await;
|
||||
let new_schedule = self.gen_map().await;
|
||||
// Cache intervals only: first_delay shrinks every second, so comparing it would make
|
||||
// every refresh look like a change.
|
||||
let new_map: HashMap<String, u64> = new_schedule
|
||||
.iter()
|
||||
.map(|(uid, schedule)| (uid.clone(), schedule.interval_minutes))
|
||||
.collect();
|
||||
|
||||
let mut cache = self.timer_map.write();
|
||||
if *cache == new_map {
|
||||
logging!(debug, Type::Timer, "No timer changes needed");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
logging!(
|
||||
info,
|
||||
Type::Timer,
|
||||
"Refreshing timer tasks map, count: {}",
|
||||
new_map.len()
|
||||
);
|
||||
*cache = new_map;
|
||||
drop(cache);
|
||||
|
||||
let _ = self.command_tx.send(TimerCommand::Apply(new_schedule));
|
||||
|
||||
Ok(())
|
||||
self.update_schedule(TimerCommand::Refresh).await
|
||||
}
|
||||
|
||||
async fn gen_map(&self) -> HashMap<String, TaskSchedule> {
|
||||
if let Some(items) = Config::profiles().await.data_arc().items.as_ref() {
|
||||
return Self::gen_map_from_items(items);
|
||||
}
|
||||
|
||||
HashMap::new()
|
||||
async fn update_schedule(&self, command: fn(oneshot::Sender<()>) -> TimerCommand) -> Result<()> {
|
||||
let (reply, done) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(command(reply))
|
||||
.context("profile timer scheduler stopped")?;
|
||||
done.await.context("profile timer scheduler stopped")
|
||||
}
|
||||
|
||||
fn gen_map_from_items(items: &[PrfItem]) -> HashMap<String, TaskSchedule> {
|
||||
fn gen_map_from_items(items: &[PrfItem], initializing: bool) -> HashMap<String, TaskSchedule> {
|
||||
let now = chrono::Local::now().timestamp();
|
||||
let mut new_map = HashMap::new();
|
||||
|
||||
@@ -221,7 +127,12 @@ impl Timer {
|
||||
&& option.allow_auto_update.unwrap_or(true)
|
||||
&& interval > 0
|
||||
{
|
||||
new_map.insert(uid.clone(), TaskSchedule::new(interval, item.updated, now));
|
||||
let mut schedule = TaskSchedule::new(interval, item.updated, now);
|
||||
// Startup historically treats an explicit zero timestamp as overdue.
|
||||
if initializing && item.updated == Some(0) {
|
||||
schedule.first_delay = Duration::ZERO;
|
||||
}
|
||||
new_map.insert(uid.clone(), schedule);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,24 +142,50 @@ impl Timer {
|
||||
async fn run_scheduler(
|
||||
mut command_rx: mpsc::UnboundedReceiver<TimerCommand>,
|
||||
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
||||
profiles: Draft<IProfiles>,
|
||||
) {
|
||||
let mut queue = DelayQueue::new();
|
||||
let mut tasks = HashMap::new();
|
||||
let mut initialized = false;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
Some(expired) = queue.next() => {
|
||||
Some(expired) = queue.next(), if initialized => {
|
||||
let uid = expired.into_inner();
|
||||
Self::run_expired_task(&mut tasks, uid, command_tx.clone());
|
||||
}
|
||||
|
||||
command = command_rx.recv() => {
|
||||
match command {
|
||||
Some(TimerCommand::Apply(new_map)) => {
|
||||
Self::apply_timer_map(&mut queue, &mut tasks, new_map);
|
||||
Some(TimerCommand::Initialize(reply)) => {
|
||||
if !initialized {
|
||||
// Pre-init refreshes are queryable. Start from the current
|
||||
// timestamps when the queue first becomes eligible to fire.
|
||||
let profiles = profiles.data_arc();
|
||||
let schedule = Self::gen_map_from_items(profiles.items.as_deref().unwrap_or_default(), true);
|
||||
tasks.clear();
|
||||
Self::apply_timer_map(&mut queue, &mut tasks, schedule);
|
||||
initialized = true;
|
||||
logging!(info, Type::Timer, "Timer initialization completed");
|
||||
}
|
||||
let _ = reply.send(());
|
||||
}
|
||||
Some(TimerCommand::RunNow(uid)) => {
|
||||
Self::run_task_now(&mut queue, &mut tasks, uid, command_tx.clone());
|
||||
Some(TimerCommand::Refresh(reply)) => {
|
||||
let profiles = profiles.data_arc();
|
||||
let schedule = Self::gen_map_from_items(profiles.items.as_deref().unwrap_or_default(), false);
|
||||
if initialized {
|
||||
Self::apply_timer_map(&mut queue, &mut tasks, schedule);
|
||||
} else {
|
||||
tasks = schedule
|
||||
.into_iter()
|
||||
.map(|(uid, schedule)| (uid, TaskState::new(None, schedule.interval_minutes)))
|
||||
.collect();
|
||||
}
|
||||
let _ = reply.send(());
|
||||
}
|
||||
Some(TimerCommand::NextUpdateTime(uid, reply)) => {
|
||||
let next = Self::next_update_time(&tasks, &profiles.latest_arc(), &uid);
|
||||
let _ = reply.send(next);
|
||||
}
|
||||
Some(TimerCommand::TaskFinished(uid)) => {
|
||||
Self::finish_task(&mut queue, &mut tasks, uid);
|
||||
@@ -321,7 +258,7 @@ impl Timer {
|
||||
schedule.interval_minutes,
|
||||
schedule.first_delay.as_secs()
|
||||
);
|
||||
tasks.insert(uid, TaskState::new(key, schedule.interval_minutes));
|
||||
tasks.insert(uid, TaskState::new(Some(key), schedule.interval_minutes));
|
||||
}
|
||||
|
||||
fn update_task_interval(queue: &mut DelayQueue<String>, uid: &str, state: &mut TaskState, schedule: &TaskSchedule) {
|
||||
@@ -353,52 +290,13 @@ impl Timer {
|
||||
};
|
||||
|
||||
state.key = None;
|
||||
if !Self::mark_task_running(state, &uid, false) {
|
||||
if state.running {
|
||||
return;
|
||||
}
|
||||
|
||||
state.running = true;
|
||||
Self::spawn_update_task(uid, command_tx);
|
||||
}
|
||||
|
||||
fn run_task_now(
|
||||
queue: &mut DelayQueue<String>,
|
||||
tasks: &mut HashMap<String, TaskState>,
|
||||
uid: String,
|
||||
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
||||
) {
|
||||
let Some(state) = tasks.get_mut(&uid) else {
|
||||
return;
|
||||
};
|
||||
|
||||
if !Self::mark_task_running(state, &uid, true) {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(key) = state.key.take() {
|
||||
queue.remove(&key);
|
||||
}
|
||||
Self::spawn_update_task(uid, command_tx);
|
||||
}
|
||||
|
||||
fn mark_task_running(state: &mut TaskState, uid: &str, immediate: bool) -> bool {
|
||||
if !state.running {
|
||||
state.running = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
if immediate {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Timer task already running, skip immediate uid={}",
|
||||
uid
|
||||
);
|
||||
} else {
|
||||
logging!(debug, Type::Timer, "Timer task already running, skip uid={}", uid);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn finish_task(queue: &mut DelayQueue<String>, tasks: &mut HashMap<String, TaskState>, uid: String) {
|
||||
let Some(state) = tasks.get_mut(&uid) else {
|
||||
return;
|
||||
@@ -441,21 +339,19 @@ impl Timer {
|
||||
}
|
||||
|
||||
pub async fn get_next_update_time(&self, uid: &str) -> Option<i64> {
|
||||
logging!(debug, Type::Timer, "Getting next update time, uid={}", uid);
|
||||
let (reply, result) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(TimerCommand::NextUpdateTime(uid.into(), reply))
|
||||
.ok()?;
|
||||
result.await.ok().flatten()
|
||||
}
|
||||
|
||||
let task_interval = *self.timer_map.read().get(uid)?;
|
||||
let profiles = Config::profiles().await;
|
||||
let profiles_guard = profiles.latest_arc();
|
||||
let items = profiles_guard.items.as_ref()?;
|
||||
|
||||
let profile = items.iter().find(|item| item.uid.as_deref() == Some(uid))?;
|
||||
let updated = profile.updated.unwrap_or(0) as i64;
|
||||
|
||||
if updated > 0 {
|
||||
Some(updated + (task_interval as i64 * 60))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
fn next_update_time(tasks: &HashMap<String, TaskState>, profiles: &IProfiles, uid: &str) -> Option<i64> {
|
||||
let task = tasks.get(uid).filter(|task| !task.retired)?;
|
||||
let updated = profiles.get_item(uid).ok()?.updated.filter(|updated| *updated > 0)?;
|
||||
let updated = i64::try_from(updated).ok()?;
|
||||
let interval = i64::try_from(task.interval_minutes).ok()?.checked_mul(60)?;
|
||||
updated.checked_add(interval)
|
||||
}
|
||||
|
||||
fn emit_update_event(uid: &str, is_start: bool) {
|
||||
@@ -474,12 +370,13 @@ impl Timer {
|
||||
|| Self::emit_update_event(uid, true),
|
||||
|| feat::update_profile(uid, None, false),
|
||||
|result| match result {
|
||||
Ok(_) => {
|
||||
Ok(Ok(_)) => {
|
||||
logging!(debug, Type::Timer, "timer task completed for uid: {}", uid);
|
||||
}
|
||||
Err(e) => {
|
||||
Ok(Err(e)) => {
|
||||
logging_error!(Type::Timer, "Failed to update profile uid {}: {e:#}", uid);
|
||||
}
|
||||
Err(_) => logging!(error, Type::Timer, "Profile update worker panicked"),
|
||||
},
|
||||
|| Self::emit_update_event(uid, false),
|
||||
)
|
||||
@@ -552,7 +449,7 @@ mod tests {
|
||||
remote_profile("missing-interval", Some(true), None),
|
||||
];
|
||||
|
||||
let map = Timer::gen_map_from_items(&items);
|
||||
let map = Timer::gen_map_from_items(&items, false);
|
||||
|
||||
assert_eq!(map.len(), 2);
|
||||
assert_eq!(map.get("enabled").map(|s| s.interval_minutes), Some(30));
|
||||
@@ -763,8 +660,8 @@ mod tests {
|
||||
},
|
||||
{
|
||||
let calls = Arc::clone(&calls);
|
||||
move |result: anyhow::Result<()>| {
|
||||
assert!(result.is_ok());
|
||||
move |result| {
|
||||
assert!(matches!(result, Ok(Ok(()))));
|
||||
calls.lock().push("terminal-result");
|
||||
}
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user