mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-06 23:00:15 +08:00
refactor(task): move the keyed timer queue into clash-verge-task
The timer scheduler in the app kept its own queue bookkeeping: when a key is due, that a run in flight cannot start a second one, that a key removed mid-run is dropped once it reports back, and that a finished run waits a whole interval. Move that bookkeeping into clash-verge-task as KeyedTimers, so the rules run and are tested without the desktop app. The app keeps the schedule, the logging and the update tasks.
This commit is contained in:
Generated
+1
@@ -1338,6 +1338,7 @@ dependencies = [
|
||||
"futures",
|
||||
"parking_lot 0.13.0",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -99,6 +99,7 @@ tokio = { version = "1.54.1", features = [
|
||||
] }
|
||||
flexi_logger = "0.32.0"
|
||||
log = "0.4.35"
|
||||
tokio-util = { version = "0.7.20", features = ["time"] }
|
||||
reqwest = { version = "0.13.5", features = [
|
||||
"json",
|
||||
"cookies",
|
||||
|
||||
@@ -8,6 +8,7 @@ publish = false
|
||||
futures = { workspace = true }
|
||||
parking_lot = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tokio-util = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
@@ -3,4 +3,5 @@
|
||||
pub mod countdown;
|
||||
pub mod retry;
|
||||
pub mod scheduled_task;
|
||||
pub mod timers;
|
||||
pub mod watch_task;
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
//! Keyed timers whose runs never overlap per key.
|
||||
|
||||
use futures::StreamExt as _;
|
||||
use std::{borrow::Borrow, collections::HashMap, hash::Hash, time::Duration};
|
||||
use tokio_util::time::{DelayQueue, delay_queue::Key};
|
||||
|
||||
/// When a timer fires.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct TimerPlan {
|
||||
/// Delay until the first fire, or until the next fire after the interval changed.
|
||||
pub first_delay: Duration,
|
||||
/// Delay from one finished run to the next fire.
|
||||
pub interval: Duration,
|
||||
}
|
||||
|
||||
/// What applying a schedule changed, removals first.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum TimerChange<K> {
|
||||
/// Removed while its run was in flight; dropped once the run reports back.
|
||||
Retired(K),
|
||||
Removed(K),
|
||||
Added(K),
|
||||
Updated(K),
|
||||
}
|
||||
|
||||
struct TaskState {
|
||||
key: Option<Key>,
|
||||
interval: Duration,
|
||||
running: bool,
|
||||
/// Disabled mid-update. Entry outlives removal so re-enabling reuses the `running` guard
|
||||
/// instead of building a fresh state that would fire a second update at zero delay.
|
||||
retired: bool,
|
||||
}
|
||||
|
||||
/// One timer per key. A key whose run is in flight does not fire again until it reports back.
|
||||
pub struct KeyedTimers<K> {
|
||||
queue: DelayQueue<K>,
|
||||
tasks: HashMap<K, TaskState>,
|
||||
}
|
||||
|
||||
impl<K: Eq + Hash + Clone> Default for KeyedTimers<K> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: Eq + Hash + Clone> KeyedTimers<K> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
queue: DelayQueue::new(),
|
||||
tasks: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgets every timer; a run still in flight reports back to nothing.
|
||||
pub fn clear(&mut self) {
|
||||
self.queue = DelayQueue::new();
|
||||
self.tasks.clear();
|
||||
}
|
||||
|
||||
/// Replaces the schedule. Timers that stay keep their next fire unless their interval
|
||||
/// changed; a changed interval restarts from the new plan's `first_delay`.
|
||||
pub fn apply(&mut self, schedule: HashMap<K, TimerPlan>) -> Vec<TimerChange<K>> {
|
||||
let Self { queue, tasks } = self;
|
||||
let mut changes = Vec::new();
|
||||
|
||||
tasks.retain(|key, state| {
|
||||
if schedule.contains_key(key) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if let Some(entry) = state.key.take() {
|
||||
queue.remove(&entry);
|
||||
}
|
||||
|
||||
if state.running {
|
||||
state.retired = true;
|
||||
changes.push(TimerChange::Retired(key.clone()));
|
||||
return true;
|
||||
}
|
||||
|
||||
changes.push(TimerChange::Removed(key.clone()));
|
||||
false
|
||||
});
|
||||
|
||||
for (key, plan) in schedule {
|
||||
match tasks.get_mut(&key) {
|
||||
None => {
|
||||
let entry = queue.insert(key.clone(), plan.first_delay);
|
||||
tasks.insert(
|
||||
key.clone(),
|
||||
TaskState {
|
||||
key: Some(entry),
|
||||
interval: plan.interval,
|
||||
running: false,
|
||||
retired: false,
|
||||
},
|
||||
);
|
||||
changes.push(TimerChange::Added(key));
|
||||
}
|
||||
Some(state) => {
|
||||
// Re-enabled before retirement took effect; finish re-arms it.
|
||||
state.retired = false;
|
||||
|
||||
if state.interval == plan.interval {
|
||||
continue;
|
||||
}
|
||||
|
||||
state.interval = plan.interval;
|
||||
|
||||
if let Some(entry) = state.key.as_ref() {
|
||||
queue.reset(entry, plan.first_delay);
|
||||
} else if !state.running {
|
||||
state.key = Some(queue.insert(key.clone(), plan.first_delay));
|
||||
}
|
||||
|
||||
changes.push(TimerChange::Updated(key));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
changes
|
||||
}
|
||||
|
||||
/// Resolves with the next due key, or `None` once the queue is empty.
|
||||
pub async fn next_expired(&mut self) -> Option<K> {
|
||||
self.queue.next().await.map(|expired| expired.into_inner())
|
||||
}
|
||||
|
||||
/// Marks the key running; `false` when the key is unknown or a run is already in flight.
|
||||
pub fn start(&mut self, key: &K) -> bool {
|
||||
let Some(state) = self.tasks.get_mut(key) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
state.key = None;
|
||||
if state.running {
|
||||
return false;
|
||||
}
|
||||
state.running = true;
|
||||
true
|
||||
}
|
||||
|
||||
/// Reports that the run finished and re-arms the timer. Returns `true` when the timer was
|
||||
/// retired meanwhile and is now dropped.
|
||||
pub fn finish(&mut self, key: &K) -> bool {
|
||||
let Some(state) = self.tasks.get_mut(key) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
state.running = false;
|
||||
|
||||
if state.retired {
|
||||
self.tasks.remove(key);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Full interval, not from `updated`: a failed run leaves `updated` in the past, so
|
||||
// counting from it would retry at zero delay and spin.
|
||||
state.key = Some(self.queue.insert(key.clone(), state.interval));
|
||||
false
|
||||
}
|
||||
|
||||
/// The interval of a timer still scheduled to run; `None` for an unknown or retired key.
|
||||
/// Takes any borrowed form of the key, so a `&str` lookup needs no owned key.
|
||||
pub fn interval<Q>(&self, key: &Q) -> Option<Duration>
|
||||
where
|
||||
K: Borrow<Q>,
|
||||
Q: Eq + Hash + ?Sized,
|
||||
{
|
||||
self.tasks
|
||||
.get(key)
|
||||
.filter(|state| !state.retired)
|
||||
.map(|state| state.interval)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
use clash_verge_task::timers::{KeyedTimers, TimerChange, TimerPlan};
|
||||
use std::{collections::HashMap, task::Poll, time::Duration};
|
||||
|
||||
const MINUTE: Duration = Duration::from_secs(60);
|
||||
|
||||
const fn plan(first_delay: Duration, interval: Duration) -> TimerPlan {
|
||||
TimerPlan { first_delay, interval }
|
||||
}
|
||||
|
||||
/// Polled, not awaited: a not-yet-due entry would park the test on the paused clock.
|
||||
async fn take_expired(timers: &mut KeyedTimers<String>) -> Option<String> {
|
||||
match futures::poll!(Box::pin(timers.next_expired())) {
|
||||
Poll::Ready(Some(key)) => Some(key),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Empty queue reports `Ready(None)`, not `Pending`, so both count as "nothing due".
|
||||
async fn nothing_due(timers: &mut KeyedTimers<String>) -> bool {
|
||||
matches!(
|
||||
futures::poll!(Box::pin(timers.next_expired())),
|
||||
Poll::Pending | Poll::Ready(None)
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn queue_fires_at_the_remaining_time_then_waits_a_whole_interval() {
|
||||
let mut timers = KeyedTimers::new();
|
||||
// 1439min into a 1440min interval: due in a minute, not a day.
|
||||
timers.apply(HashMap::from([("remote".to_owned(), plan(MINUTE, 1440 * MINUTE))]));
|
||||
|
||||
tokio::time::advance(Duration::from_secs(61)).await;
|
||||
assert_eq!(
|
||||
take_expired(&mut timers).await.as_deref(),
|
||||
Some("remote"),
|
||||
"the raised interval must fire one minute in, not a full day in"
|
||||
);
|
||||
|
||||
// After it reports back, the next one is a whole interval away.
|
||||
assert!(timers.start(&"remote".to_owned()));
|
||||
assert!(!timers.finish(&"remote".to_owned()));
|
||||
|
||||
tokio::time::advance(Duration::from_secs(1439 * 60)).await;
|
||||
assert!(
|
||||
nothing_due(&mut timers).await,
|
||||
"a finished task waits the whole interval, not the remainder of the old one"
|
||||
);
|
||||
|
||||
tokio::time::advance(Duration::from_secs(120)).await;
|
||||
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("remote"));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn disabling_a_profile_mid_update_cannot_start_a_second_one() {
|
||||
let mut timers = KeyedTimers::new();
|
||||
// Overdue: every re-insert would land at zero delay.
|
||||
let overdue = || plan(Duration::ZERO, 60 * MINUTE);
|
||||
|
||||
timers.apply(HashMap::from([("local".to_owned(), overdue())]));
|
||||
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("local"));
|
||||
assert!(timers.start(&"local".to_owned()));
|
||||
|
||||
// Toggled off then on while the run is still in flight.
|
||||
assert_eq!(
|
||||
timers.apply(HashMap::new()),
|
||||
vec![TimerChange::Retired("local".to_owned())]
|
||||
);
|
||||
assert!(
|
||||
timers
|
||||
.apply(HashMap::from([("local".to_owned(), overdue())]))
|
||||
.is_empty(),
|
||||
"the entry must survive the toggle so the in-flight run is still accounted for"
|
||||
);
|
||||
assert!(
|
||||
!timers.start(&"local".to_owned()),
|
||||
"a second run while the first is in flight is refused"
|
||||
);
|
||||
assert!(
|
||||
nothing_due(&mut timers).await,
|
||||
"re-enabling must not queue a second run alongside the one already going"
|
||||
);
|
||||
|
||||
// Original run reports back, re-arms exactly once.
|
||||
assert!(!timers.finish(&"local".to_owned()));
|
||||
tokio::time::advance(Duration::from_secs(3601)).await;
|
||||
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("local"));
|
||||
assert!(nothing_due(&mut timers).await, "exactly one key, no orphan");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_profile_disabled_mid_update_is_dropped_when_it_reports_back() {
|
||||
let mut timers = KeyedTimers::new();
|
||||
|
||||
timers.apply(HashMap::from([("local".to_owned(), plan(Duration::ZERO, 60 * MINUTE))]));
|
||||
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("local"));
|
||||
assert!(timers.start(&"local".to_owned()));
|
||||
|
||||
assert_eq!(
|
||||
timers.apply(HashMap::new()),
|
||||
vec![TimerChange::Retired("local".to_owned())]
|
||||
);
|
||||
assert!(
|
||||
timers.finish(&"local".to_owned()),
|
||||
"a task retired mid-update must not outlive the update"
|
||||
);
|
||||
assert_eq!(timers.interval(&"local".to_owned()), None);
|
||||
|
||||
tokio::time::advance(Duration::from_secs(7200)).await;
|
||||
assert!(nothing_due(&mut timers).await, "and must never be scheduled again");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn apply_reports_removals_first_and_reenable_changes_nothing() {
|
||||
let mut timers = KeyedTimers::new();
|
||||
timers.apply(HashMap::from([
|
||||
("a".to_owned(), plan(MINUTE, MINUTE)),
|
||||
("b".to_owned(), plan(MINUTE, 2 * MINUTE)),
|
||||
("c".to_owned(), plan(MINUTE, 3 * MINUTE)),
|
||||
]));
|
||||
let mut tail = timers.apply(HashMap::from([
|
||||
("a".to_owned(), plan(2 * MINUTE, 2 * MINUTE)),
|
||||
("c".to_owned(), plan(MINUTE, 3 * MINUTE)),
|
||||
("d".to_owned(), plan(MINUTE, MINUTE)),
|
||||
]));
|
||||
assert_eq!(tail.remove(0), TimerChange::Removed("b".to_owned()));
|
||||
assert_eq!(tail.len(), 2); // HashMap order decides which of these comes first
|
||||
assert!(tail.contains(&TimerChange::Added("d".to_owned())));
|
||||
assert!(tail.contains(&TimerChange::Updated("a".to_owned())));
|
||||
assert!(timers.start(&"a".to_owned()));
|
||||
let retired = timers.apply(HashMap::from([("c".to_owned(), plan(MINUTE, 3 * MINUTE))]));
|
||||
assert_eq!(retired.len(), 2, "the running key is retired and the idle one removed");
|
||||
assert!(retired.contains(&TimerChange::Retired("a".to_owned())));
|
||||
assert!(retired.contains(&TimerChange::Removed("d".to_owned())));
|
||||
assert!(
|
||||
timers
|
||||
.apply(HashMap::from([
|
||||
("a".to_owned(), plan(2 * MINUTE, 2 * MINUTE)),
|
||||
("c".to_owned(), plan(MINUTE, 3 * MINUTE)),
|
||||
]))
|
||||
.is_empty()
|
||||
);
|
||||
assert!(!timers.finish(&"a".to_owned()));
|
||||
assert_eq!(timers.interval(&"a".to_owned()), Some(2 * MINUTE));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn interval_queries_answer_before_initialization() {
|
||||
let mut timers = KeyedTimers::new();
|
||||
timers.apply(HashMap::from([("a".to_owned(), plan(MINUTE, MINUTE))]));
|
||||
assert_eq!(timers.interval(&"a".to_owned()), Some(MINUTE));
|
||||
assert_eq!(timers.interval("a"), Some(MINUTE));
|
||||
assert_eq!(timers.interval("b"), None);
|
||||
assert_eq!(timers.apply(HashMap::new()), vec![TimerChange::Removed("a".to_owned())]);
|
||||
assert_eq!(timers.interval("a"), None);
|
||||
assert!(nothing_due(&mut timers).await);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn finishing_an_unknown_or_cleared_key_does_nothing() {
|
||||
let mut timers = KeyedTimers::new();
|
||||
assert!(!timers.finish(&"missing".to_owned()));
|
||||
timers.apply(HashMap::from([("a".to_owned(), plan(MINUTE, MINUTE))]));
|
||||
assert!(timers.start(&"a".to_owned()));
|
||||
timers.clear();
|
||||
assert!(!timers.finish(&"a".to_owned()));
|
||||
assert_eq!(timers.interval(&"a".to_owned()), None);
|
||||
tokio::time::advance(24 * 60 * MINUTE).await;
|
||||
assert!(nothing_due(&mut timers).await);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn an_interval_changed_during_a_run_is_reported_and_used_on_finish() {
|
||||
let mut timers = KeyedTimers::new();
|
||||
timers.apply(HashMap::from([("a".to_owned(), plan(Duration::ZERO, MINUTE))]));
|
||||
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("a"));
|
||||
assert!(timers.start(&"a".to_owned()));
|
||||
assert_eq!(
|
||||
timers.apply(HashMap::from([("a".to_owned(), plan(5 * MINUTE, 5 * MINUTE))])),
|
||||
vec![TimerChange::Updated("a".to_owned())]
|
||||
);
|
||||
assert!(nothing_due(&mut timers).await);
|
||||
assert_eq!(timers.interval(&"a".to_owned()), Some(5 * MINUTE));
|
||||
assert!(!timers.finish(&"a".to_owned()));
|
||||
tokio::time::advance(5 * MINUTE - Duration::from_secs(1)).await;
|
||||
assert!(nothing_due(&mut timers).await);
|
||||
tokio::time::advance(Duration::from_secs(1)).await;
|
||||
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("a"));
|
||||
}
|
||||
@@ -104,7 +104,7 @@ rustls = { version = "0.23.47", features = ["ring"] }
|
||||
webpki-roots = "1.0.12"
|
||||
dark-light = "3.0.0"
|
||||
bytes = "1.12.2"
|
||||
tokio-util = { version = "0.7.20", features = ["time"] }
|
||||
tokio-util = { workspace = true }
|
||||
specta = { workspace = true, features = ["derive", "function", "serde_json"] }
|
||||
tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] }
|
||||
specta-typescript = "=0.0.13"
|
||||
|
||||
+77
-292
@@ -9,13 +9,13 @@ use anyhow::{Context as _, Result};
|
||||
use clash_verge_draft::Draft;
|
||||
use clash_verge_logging::{Type, logging, logging_error};
|
||||
use clash_verge_profile::SubscriptionSchedule as TaskSchedule;
|
||||
use futures::{FutureExt as _, StreamExt as _};
|
||||
use clash_verge_task::timers::{KeyedTimers, TimerChange, TimerPlan};
|
||||
use futures::FutureExt as _;
|
||||
use std::{collections::HashMap, panic::AssertUnwindSafe, time::Duration};
|
||||
use tokio::{
|
||||
sync::{mpsc, oneshot},
|
||||
time::{sleep, timeout},
|
||||
};
|
||||
use tokio_util::time::{DelayQueue, delay_queue::Key};
|
||||
use tristr::alias::String;
|
||||
|
||||
enum TimerCommand {
|
||||
@@ -25,15 +25,6 @@ enum TimerCommand {
|
||||
TaskFinished(String),
|
||||
}
|
||||
|
||||
struct TaskState {
|
||||
key: Option<Key>,
|
||||
interval_minutes: u64,
|
||||
running: bool,
|
||||
/// Disabled mid-update. Entry outlives removal so re-enabling reuses the `running` guard
|
||||
/// instead of building a fresh state that would fire a second update at zero delay.
|
||||
retired: bool,
|
||||
}
|
||||
|
||||
async fn run_timer_profile_update_transition<Started, Update, UpdateFuture, Finished, Completed, Output>(
|
||||
update_started: Started,
|
||||
update_profile: Update,
|
||||
@@ -52,17 +43,6 @@ async fn run_timer_profile_update_transition<Started, Update, UpdateFuture, Fini
|
||||
update_completed();
|
||||
}
|
||||
|
||||
impl TaskState {
|
||||
const fn new(key: Option<Key>, interval_minutes: u64) -> Self {
|
||||
Self {
|
||||
key,
|
||||
interval_minutes,
|
||||
running: false,
|
||||
retired: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Timer {
|
||||
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
||||
}
|
||||
@@ -116,15 +96,15 @@ impl Timer {
|
||||
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
||||
profiles: Draft<IProfiles>,
|
||||
) {
|
||||
let mut queue = DelayQueue::new();
|
||||
let mut tasks = HashMap::new();
|
||||
let mut timers = KeyedTimers::<String>::new();
|
||||
let mut initialized = false;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
Some(expired) = queue.next(), if initialized => {
|
||||
let uid = expired.into_inner();
|
||||
Self::run_expired_task(&mut tasks, uid, command_tx.clone());
|
||||
Some(expired) = timers.next_expired(), if initialized => {
|
||||
if timers.start(&expired) {
|
||||
Self::spawn_update_task(expired, command_tx.clone());
|
||||
}
|
||||
}
|
||||
|
||||
command = command_rx.recv() => {
|
||||
@@ -135,8 +115,8 @@ impl Timer {
|
||||
// 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);
|
||||
timers.clear();
|
||||
Self::log_changes(&schedule, timers.apply(Self::plans(&schedule)));
|
||||
initialized = true;
|
||||
logging!(info, Type::Timer, "Timer initialization completed");
|
||||
}
|
||||
@@ -146,21 +126,20 @@ impl Timer {
|
||||
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);
|
||||
Self::log_changes(&schedule, timers.apply(Self::plans(&schedule)));
|
||||
} else {
|
||||
tasks = schedule
|
||||
.into_iter()
|
||||
.map(|(uid, schedule)| (uid, TaskState::new(None, schedule.interval_minutes)))
|
||||
.collect();
|
||||
timers.apply(Self::plans(&schedule));
|
||||
}
|
||||
let _ = reply.send(());
|
||||
}
|
||||
Some(TimerCommand::NextUpdateTime(uid, reply)) => {
|
||||
let next = Self::next_update_time(&tasks, &profiles.latest_arc(), &uid);
|
||||
let next = Self::next_update_time(&timers, &profiles.latest_arc(), &uid);
|
||||
let _ = reply.send(next);
|
||||
}
|
||||
Some(TimerCommand::TaskFinished(uid)) => {
|
||||
Self::finish_task(&mut queue, &mut tasks, uid);
|
||||
if timers.finish(&uid) {
|
||||
logging!(debug, Type::Timer, "Dropped retired timer task now that its update finished: uid={uid}");
|
||||
}
|
||||
}
|
||||
None => break,
|
||||
}
|
||||
@@ -169,128 +148,63 @@ impl Timer {
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_timer_map(
|
||||
queue: &mut DelayQueue<String>,
|
||||
tasks: &mut HashMap<String, TaskState>,
|
||||
new_map: HashMap<String, TaskSchedule>,
|
||||
) {
|
||||
tasks.retain(|uid, state| {
|
||||
if new_map.contains_key(uid) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if let Some(key) = state.key.take() {
|
||||
queue.remove(&key);
|
||||
}
|
||||
|
||||
if state.running {
|
||||
state.retired = true;
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Retiring timer task once its in-flight update reports back: uid={}",
|
||||
uid
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
logging!(debug, Type::Timer, "Removed timer task for uid={}", uid);
|
||||
false
|
||||
});
|
||||
|
||||
for (uid, schedule) in new_map {
|
||||
let Some(state) = tasks.get_mut(&uid) else {
|
||||
Self::insert_task(queue, tasks, uid, &schedule);
|
||||
continue;
|
||||
};
|
||||
|
||||
// Re-enabled before retirement took effect; finish_task re-arms it.
|
||||
state.retired = false;
|
||||
|
||||
if state.interval_minutes == schedule.interval_minutes {
|
||||
continue;
|
||||
}
|
||||
|
||||
Self::update_task_interval(queue, &uid, state, &schedule);
|
||||
}
|
||||
fn plans(schedule: &HashMap<String, TaskSchedule>) -> HashMap<String, TimerPlan> {
|
||||
schedule
|
||||
.iter()
|
||||
.map(|(uid, schedule)| {
|
||||
(
|
||||
uid.clone(),
|
||||
TimerPlan {
|
||||
first_delay: schedule.first_delay,
|
||||
interval: TaskSchedule::interval_duration(schedule.interval_minutes),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn insert_task(
|
||||
queue: &mut DelayQueue<String>,
|
||||
tasks: &mut HashMap<String, TaskState>,
|
||||
uid: String,
|
||||
schedule: &TaskSchedule,
|
||||
) {
|
||||
let key = Self::schedule_task(queue, &uid, schedule.first_delay);
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Added timer task: uid={}, interval={}min, first fire in {}s",
|
||||
uid,
|
||||
schedule.interval_minutes,
|
||||
schedule.first_delay.as_secs()
|
||||
);
|
||||
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) {
|
||||
state.interval_minutes = schedule.interval_minutes;
|
||||
|
||||
if let Some(key) = state.key.as_ref() {
|
||||
queue.reset(key, schedule.first_delay);
|
||||
} else if !state.running {
|
||||
state.key = Some(Self::schedule_task(queue, uid, schedule.first_delay));
|
||||
fn log_changes(schedule: &HashMap<String, TaskSchedule>, changes: Vec<TimerChange<String>>) {
|
||||
for change in changes {
|
||||
match change {
|
||||
TimerChange::Retired(uid) => {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Retiring timer task once its in-flight update reports back: uid={}",
|
||||
uid
|
||||
);
|
||||
}
|
||||
TimerChange::Removed(uid) => {
|
||||
logging!(debug, Type::Timer, "Removed timer task for uid={}", uid);
|
||||
}
|
||||
TimerChange::Added(uid) => {
|
||||
let Some(schedule) = schedule.get(&uid) else {
|
||||
continue;
|
||||
};
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Added timer task: uid={}, interval={}min, first fire in {}s",
|
||||
uid,
|
||||
schedule.interval_minutes,
|
||||
schedule.first_delay.as_secs()
|
||||
);
|
||||
}
|
||||
TimerChange::Updated(uid) => {
|
||||
let Some(schedule) = schedule.get(&uid) else {
|
||||
continue;
|
||||
};
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Updated timer task interval: uid={}, interval={}min, next fire in {}s",
|
||||
uid,
|
||||
schedule.interval_minutes,
|
||||
schedule.first_delay.as_secs()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Updated timer task interval: uid={}, interval={}min, next fire in {}s",
|
||||
uid,
|
||||
schedule.interval_minutes,
|
||||
schedule.first_delay.as_secs()
|
||||
);
|
||||
}
|
||||
|
||||
fn run_expired_task(
|
||||
tasks: &mut HashMap<String, TaskState>,
|
||||
uid: String,
|
||||
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
||||
) {
|
||||
let Some(state) = tasks.get_mut(&uid) else {
|
||||
return;
|
||||
};
|
||||
|
||||
state.key = None;
|
||||
if state.running {
|
||||
return;
|
||||
}
|
||||
state.running = true;
|
||||
Self::spawn_update_task(uid, command_tx);
|
||||
}
|
||||
|
||||
fn finish_task(queue: &mut DelayQueue<String>, tasks: &mut HashMap<String, TaskState>, uid: String) {
|
||||
let Some(state) = tasks.get_mut(&uid) else {
|
||||
return;
|
||||
};
|
||||
|
||||
state.running = false;
|
||||
|
||||
if state.retired {
|
||||
tasks.remove(&uid);
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Dropped retired timer task now that its update finished: uid={}",
|
||||
uid
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Full interval, not from `updated`: a failed run leaves `updated` in the past, so
|
||||
// counting from it would retry at zero delay and spin.
|
||||
let key = Self::schedule_task(queue, &uid, TaskSchedule::interval_duration(state.interval_minutes));
|
||||
state.key = Some(key);
|
||||
}
|
||||
|
||||
fn spawn_update_task(uid: String, command_tx: mpsc::UnboundedSender<TimerCommand>) {
|
||||
@@ -302,10 +216,6 @@ impl Timer {
|
||||
});
|
||||
}
|
||||
|
||||
fn schedule_task(queue: &mut DelayQueue<String>, uid: &str, delay: Duration) -> Key {
|
||||
queue.insert(String::from(uid), delay)
|
||||
}
|
||||
|
||||
pub async fn get_next_update_time(&self, uid: &str) -> Option<i64> {
|
||||
let (reply, result) = oneshot::channel();
|
||||
self.command_tx
|
||||
@@ -314,10 +224,15 @@ impl Timer {
|
||||
result.await.ok().flatten()
|
||||
}
|
||||
|
||||
fn next_update_time(tasks: &HashMap<String, TaskState>, profiles: &IProfiles, uid: &str) -> Option<i64> {
|
||||
let task = tasks.get(uid).filter(|task| !task.retired)?;
|
||||
fn next_update_time(timers: &KeyedTimers<String>, profiles: &IProfiles, uid: &str) -> Option<i64> {
|
||||
let updated = profiles.get_item(uid).ok()?.updated;
|
||||
TaskSchedule::reported_deadline(task.interval_minutes, updated)
|
||||
TaskSchedule::reported_deadline(Self::minutes(timers.interval(uid)?)?, updated)
|
||||
}
|
||||
|
||||
/// A saturated interval is not a whole number of minutes, so the query stays unanswered as before.
|
||||
const fn minutes(interval: Duration) -> Option<u64> {
|
||||
let secs = interval.as_secs();
|
||||
if secs.is_multiple_of(60) { Some(secs / 60) } else { None }
|
||||
}
|
||||
|
||||
fn emit_update_event(uid: &str, is_start: bool) {
|
||||
@@ -364,9 +279,7 @@ impl Timer {
|
||||
mod tests {
|
||||
use super::{TaskSchedule, Timer, run_timer_profile_update_transition};
|
||||
use crate::config::{PrfItem, PrfOption};
|
||||
use futures::StreamExt as _;
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::{
|
||||
sync::{
|
||||
Arc,
|
||||
@@ -376,8 +289,6 @@ mod tests {
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::sync::Barrier;
|
||||
use tokio_util::time::DelayQueue;
|
||||
use tristr::alias::String;
|
||||
|
||||
struct CancellationProbe {
|
||||
cancelled: Arc<AtomicBool>,
|
||||
@@ -469,132 +380,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Polled, not awaited: a not-yet-due entry would park the test on the paused clock.
|
||||
async fn take_expired(queue: &mut DelayQueue<String>) -> Option<String> {
|
||||
match futures::poll!(Box::pin(queue.next())) {
|
||||
Poll::Ready(Some(expired)) => Some(expired.into_inner()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// What `run_expired_task` does, minus spawning the real update.
|
||||
fn mark_running(tasks: &mut HashMap<String, super::TaskState>, uid: &str) {
|
||||
assert!(tasks.contains_key(uid), "task {uid} must exist before it can run");
|
||||
|
||||
if let Some(state) = tasks.get_mut(uid) {
|
||||
state.key = None;
|
||||
state.running = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Empty queue reports `Ready(None)`, not `Pending`, so both count as "nothing due".
|
||||
async fn nothing_due(queue: &mut DelayQueue<String>) -> bool {
|
||||
matches!(
|
||||
futures::poll!(Box::pin(queue.next())),
|
||||
Poll::Pending | Poll::Ready(None)
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn queue_fires_at_the_remaining_time_then_waits_a_whole_interval() {
|
||||
const NOW: i64 = 1_700_000_000;
|
||||
|
||||
let mut queue = DelayQueue::new();
|
||||
let mut tasks = HashMap::new();
|
||||
|
||||
// 1439min into a 1440min interval: due in a minute, not a day.
|
||||
let mut map = HashMap::new();
|
||||
map.insert(
|
||||
String::from("uid"),
|
||||
TaskSchedule::new(1440, Some((NOW - 1439 * 60) as usize), NOW),
|
||||
);
|
||||
Timer::apply_timer_map(&mut queue, &mut tasks, map);
|
||||
|
||||
tokio::time::advance(Duration::from_secs(61)).await;
|
||||
assert_eq!(
|
||||
take_expired(&mut queue).await.as_deref(),
|
||||
Some("uid"),
|
||||
"the raised interval must fire one minute in, not a full day in"
|
||||
);
|
||||
|
||||
// After it reports back, the next one is a whole interval away.
|
||||
mark_running(&mut tasks, "uid");
|
||||
Timer::finish_task(&mut queue, &mut tasks, String::from("uid"));
|
||||
|
||||
tokio::time::advance(Duration::from_secs(1439 * 60)).await;
|
||||
assert!(
|
||||
nothing_due(&mut queue).await,
|
||||
"a finished task waits the whole interval, not the remainder of the old one"
|
||||
);
|
||||
|
||||
tokio::time::advance(Duration::from_secs(120)).await;
|
||||
assert_eq!(take_expired(&mut queue).await.as_deref(), Some("uid"));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn disabling_a_profile_mid_update_cannot_start_a_second_one() {
|
||||
const NOW: i64 = 1_700_000_000;
|
||||
|
||||
let mut queue = DelayQueue::new();
|
||||
let mut tasks = HashMap::new();
|
||||
// Overdue: every re-insert would land at zero delay.
|
||||
let schedule = || TaskSchedule::new(60, Some((NOW - 7200) as usize), NOW);
|
||||
|
||||
let mut map = HashMap::new();
|
||||
map.insert(String::from("uid"), schedule());
|
||||
Timer::apply_timer_map(&mut queue, &mut tasks, map);
|
||||
assert_eq!(take_expired(&mut queue).await.as_deref(), Some("uid"));
|
||||
mark_running(&mut tasks, "uid");
|
||||
|
||||
// Toggled off then on while the run is still in flight.
|
||||
Timer::apply_timer_map(&mut queue, &mut tasks, HashMap::new());
|
||||
let mut back_on = HashMap::new();
|
||||
back_on.insert(String::from("uid"), schedule());
|
||||
Timer::apply_timer_map(&mut queue, &mut tasks, back_on);
|
||||
|
||||
assert!(
|
||||
tasks.get("uid").is_some_and(|state| state.running),
|
||||
"the entry must survive the toggle so the in-flight run is still accounted for"
|
||||
);
|
||||
assert!(
|
||||
nothing_due(&mut queue).await,
|
||||
"re-enabling must not queue a second run alongside the one already going"
|
||||
);
|
||||
|
||||
// Original run reports back, re-arms exactly once.
|
||||
Timer::finish_task(&mut queue, &mut tasks, String::from("uid"));
|
||||
tokio::time::advance(Duration::from_secs(3601)).await;
|
||||
assert_eq!(take_expired(&mut queue).await.as_deref(), Some("uid"));
|
||||
assert!(nothing_due(&mut queue).await, "exactly one key, no orphan");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_profile_disabled_mid_update_is_dropped_when_it_reports_back() {
|
||||
const NOW: i64 = 1_700_000_000;
|
||||
|
||||
let mut queue = DelayQueue::new();
|
||||
let mut tasks = HashMap::new();
|
||||
|
||||
let mut map = HashMap::new();
|
||||
map.insert(
|
||||
String::from("uid"),
|
||||
TaskSchedule::new(60, Some((NOW - 7200) as usize), NOW),
|
||||
);
|
||||
Timer::apply_timer_map(&mut queue, &mut tasks, map);
|
||||
assert_eq!(take_expired(&mut queue).await.as_deref(), Some("uid"));
|
||||
mark_running(&mut tasks, "uid");
|
||||
|
||||
Timer::apply_timer_map(&mut queue, &mut tasks, HashMap::new());
|
||||
Timer::finish_task(&mut queue, &mut tasks, String::from("uid"));
|
||||
|
||||
assert!(
|
||||
tasks.is_empty(),
|
||||
"a task retired mid-update must not outlive the update"
|
||||
);
|
||||
tokio::time::advance(Duration::from_secs(7200)).await;
|
||||
assert!(nothing_due(&mut queue).await, "and must never be scheduled again");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn timer_profile_update_runs_past_former_deadline_and_pairs_events() -> anyhow::Result<()> {
|
||||
let calls = Arc::new(Mutex::new(Vec::new()));
|
||||
|
||||
Reference in New Issue
Block a user