From a37cdb755014fc15eb4f7ed7b80989db9e7e8d29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 17 Oct 2026 09:24:08 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20perf:=20replace=20polling=20loops?= =?UTF-8?q?=20with=20event-driven=20wakes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - workers sleep until their next due time, with a 15-minute backstop - ci claim wakes all runners --- crates/forge-core/src/store/webhooks.rs | 15 +++ crates/forge-web/src/advisories/worker.rs | 95 +++++++++++----- crates/forge-web/src/backup/scheduler.rs | 124 +++++++++++++-------- crates/forge-web/src/ci/reaper.rs | 4 +- crates/forge-web/src/ci/schedule.rs | 2 +- crates/forge-web/src/mail/worker.rs | 23 ++-- crates/forge-web/src/mirrors/worker.rs | 39 ++++--- crates/forge-web/src/pages/repo_mirrors.rs | 5 +- crates/forge-web/src/replication/mod.rs | 11 ++ crates/forge-web/src/replication/worker.rs | 18 ++- crates/forge-web/src/webhooks/worker.rs | 56 +++++++++- 11 files changed, 278 insertions(+), 114 deletions(-) diff --git a/crates/forge-core/src/store/webhooks.rs b/crates/forge-core/src/store/webhooks.rs index 29e7449..d7d7345 100644 --- a/crates/forge-core/src/store/webhooks.rs +++ b/crates/forge-core/src/store/webhooks.rs @@ -450,6 +450,21 @@ impl Store { finish(tx, outcome).await } + /// The earliest `next_attempt_at` among pending and failed deliveries, or `None` when none is + /// pending. A claimed delivery carries its lease expiry here, so the lease counts as due time. + pub async fn next_delivery_due(&self) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + "SELECT MIN(next_attempt_at) FROM webhook_deliveries \ + WHERE state IN ('pending', 'failed')", + (), + |row| col_opt_text(row, 0), + ) + .await + .map(Option::flatten) + } + /// Records the outcome of one attempt. See [`AttemptOutcome`] for the resulting state. /// On success `delivered_at` is stamped and `next_attempt_at` is cleared. The response body /// is truncated to 64 KiB. `NotFound` if the delivery does not exist. diff --git a/crates/forge-web/src/advisories/worker.rs b/crates/forge-web/src/advisories/worker.rs index dd6e4b2..83e85fd 100644 --- a/crates/forge-web/src/advisories/worker.rs +++ b/crates/forge-web/src/advisories/worker.rs @@ -1,8 +1,10 @@ //! The advisory worker. When `[advisories] enabled = true`, it keeps an OSV dump per configured -//! ecosystem in `/advisories//all.zip`. A dump older than `refresh_hours` is -//! downloaded again (capped at [`MAX_DUMP_BYTES`], with timeouts, no redirects). A dump that is -//! newer than the last import is imported, and then every repo is rescanned. It checks once an -//! hour, and once at boot, so an existing dump is imported without a download. +//! ecosystem in `/advisories//all.zip`. Each dump is downloaded again +//! `refresh_hours` after its last refresh (the file's modification time), sleeping until then +//! (capped at [`MAX_DUMP_BYTES`], with timeouts, no redirects). A failed download is retried with +//! a backoff that doubles from [`RETRY_FIRST`] up to [`RETRY_MAX`]. A dump that is newer than the +//! last import is imported, and then every repo is rescanned. At boot, a fresh dump is imported +//! without a download. use std::collections::HashMap; use std::fs::{self, File}; @@ -16,8 +18,10 @@ use forge_core::{Error, Result}; use super::scan::scan_all; use crate::state::AppState; -/// How often the worker checks the dumps. -const CHECK_EVERY: Duration = Duration::from_secs(60 * 60); +/// First wait after a failed download. It doubles with each further failure. +const RETRY_FIRST: Duration = Duration::from_secs(5 * 60); +/// Longest wait after a failed download. +const RETRY_MAX: Duration = Duration::from_secs(60 * 60); /// Largest dump accepted, in bytes. const MAX_DUMP_BYTES: u64 = 500 * 1024 * 1024; const CONNECT_TIMEOUT: Duration = Duration::from_secs(30); @@ -57,40 +61,83 @@ async fn run(state: AppState) { return; } }; + let refresh_after = Duration::from_secs(state.config.advisories.refresh_hours.max(1) * 3600); let mut imported: HashMap = HashMap::new(); + // When each ecosystem's dump is next downloaded, and how many downloads in a row failed. + let mut due: HashMap = HashMap::new(); + let mut failures: HashMap = HashMap::new(); loop { + let mut wake_at: Option = None; for ecosystem in &state.config.advisories.ecosystems { if !KNOWN_ECOSYSTEMS.contains(&ecosystem.as_str()) { tracing::warn!(ecosystem = %ecosystem, "advisories: unknown ecosystem, skipped"); continue; } - if let Err(e) = refresh_one(&state, &client, ecosystem, &mut imported).await { - tracing::error!(error = %e, ecosystem = %ecosystem, "advisories: refresh failed"); + let path = dump_path(&state.config.data_dir, ecosystem); + let mut refresh_at = *due + .entry(ecosystem.clone()) + .or_insert_with(|| next_refresh_at(&path, refresh_after)); + let now = SystemTime::now(); + if refresh_at <= now { + refresh_at = match download(&client, ecosystem, &path).await { + Ok(()) => { + failures.remove(ecosystem); + next_refresh_at(&path, refresh_after) + } + Err(e) => { + tracing::error!(error = %e, ecosystem = %ecosystem, "advisories: refresh failed"); + let count = failures.entry(ecosystem.clone()).or_insert(0); + *count += 1; + now + retry_delay(*count) + } + }; + due.insert(ecosystem.clone(), refresh_at); } + if let Err(e) = import_if_changed(&state, ecosystem, &path, &mut imported).await { + tracing::error!(error = %e, ecosystem = %ecosystem, "advisories: import failed"); + } + wake_at = Some(wake_at.map_or(refresh_at, |at| at.min(refresh_at))); } - tokio::time::sleep(CHECK_EVERY).await; + let Some(wake_at) = wake_at else { + tracing::info!("advisories: no known ecosystems configured, worker stopped"); + return; + }; + let wait = wake_at + .duration_since(SystemTime::now()) + .unwrap_or(Duration::ZERO); + tokio::time::sleep(wait).await; } } -/// Downloads `ecosystem`'s dump if it is stale, then imports it if it changed since the last import. -async fn refresh_one( +/// When the dump at `path` is due for its next download: `refresh_after` past its last refresh. +/// A missing dump is due now. +fn next_refresh_at(path: &Path, refresh_after: Duration) -> SystemTime { + match modified_time(path) { + None => SystemTime::now(), + Some(last) => last + refresh_after, + } +} + +/// The wait after the `failures`-th failed download in a row: 5 minutes, doubling, capped at an hour. +fn retry_delay(failures: u32) -> Duration { + let shift = failures.saturating_sub(1).min(16); + (RETRY_FIRST * 2u32.pow(shift)).min(RETRY_MAX) +} + +/// Imports the dump of `ecosystem` if it changed since the last import, then rescans every repo. +async fn import_if_changed( state: &AppState, - client: &reqwest::Client, ecosystem: &str, + path: &Path, imported: &mut HashMap, ) -> Result<()> { - let path = dump_path(&state.config.data_dir, ecosystem); - let max_age = Duration::from_secs(state.config.advisories.refresh_hours.max(1) * 3600); - if is_older_than(&path, max_age) { - download(client, ecosystem, &path).await?; - } - let Some(modified) = modified_time(&path) else { + let Some(modified) = modified_time(path) else { return Ok(()); }; if imported.get(ecosystem) == Some(&modified) { return Ok(()); } - import(state, ecosystem, &path).await?; + import(state, ecosystem, path).await?; imported.insert(ecosystem.to_owned(), modified); scan_all(state).await; Ok(()) @@ -100,16 +147,6 @@ fn modified_time(path: &Path) -> Option { fs::metadata(path).and_then(|m| m.modified()).ok() } -/// True when the file is missing or was written more than `max_age` ago. -fn is_older_than(path: &Path, max_age: Duration) -> bool { - match modified_time(path) { - None => true, - Some(at) => SystemTime::now() - .duration_since(at) - .is_ok_and(|age| age > max_age), - } -} - /// Streams the dump to `.part` and renames it into place once complete. A response that is /// too large, or that fails midway, leaves the previous dump in place. async fn download(client: &reqwest::Client, ecosystem: &str, path: &Path) -> Result<()> { diff --git a/crates/forge-web/src/backup/scheduler.rs b/crates/forge-web/src/backup/scheduler.rs index c8d69f9..1d8eb2a 100644 --- a/crates/forge-web/src/backup/scheduler.rs +++ b/crates/forge-web/src/backup/scheduler.rs @@ -17,10 +17,11 @@ use super::{ }; use crate::state::AppState; -/// How often the scheduler looks at the clock. -const TICK: Duration = Duration::from_secs(30); /// After a failed run, the next try waits at least this long. const RETRY_AFTER_SECS: i64 = 60 * 60; +/// Pause after each pass. A due job that did not clear its due time (it could not take the run +/// slot while a manual run held it, say) waits this long instead of spinning the loop. +const RECHECK: Duration = Duration::from_secs(30); /// The one run slot of this process. #[derive(Default)] @@ -101,61 +102,87 @@ pub fn secs_until_due( } /// Starts the scheduler loop. The caller checks that `[backup] dir` is set. +/// +/// Each pass sleeps until the earliest of the backup and fsck is due, runs what is due, and then +/// works out the next instant from the run history again. pub fn spawn(state: AppState) -> tokio::task::JoinHandle<()> { tokio::spawn(async move { loop { - tick(&state).await; - tokio::time::sleep(TICK).await; + match next_due_in(&state).await { + Ok(wait) => { + let until = tokio::time::Instant::now() + + Duration::from_secs(u64::try_from(wait).unwrap_or(0)); + tokio::time::sleep_until(until).await; + } + Err(e) => { + tracing::error!(error = %e, "backup scheduler could not read its history"); + tokio::time::sleep(RECHECK).await; + continue; + } + } + run_due(&state).await; + tokio::time::sleep(RECHECK).await; } }) } -/// One pass of the loop: runs the backup and the fsck when either is due. -async fn tick(state: &AppState) { +/// How often a job of this kind is due, in seconds. +fn interval_secs(state: &AppState, kind: RunKind) -> i64 { let cfg = &state.config.backup; - let backup_every = i64::try_from(cfg.interval_hours.saturating_mul(3600)).unwrap_or(i64::MAX); - let fsck_every = - i64::try_from(cfg.fsck_interval_days.saturating_mul(86_400)).unwrap_or(i64::MAX); - let backup_wait = match due_inputs(state, RunKind::Backup).await { - Ok((ok, attempt)) => secs_until_due( - OffsetDateTime::now_utc(), - ok.as_ref(), - attempt.as_ref(), - backup_every, - RETRY_AFTER_SECS, - ), - Err(e) => { - tracing::error!(error = %e, "backup scheduler could not read its history"); - return; + match kind { + RunKind::Backup => { + i64::try_from(cfg.interval_hours.saturating_mul(3600)).unwrap_or(i64::MAX) } - }; - if backup_wait == 0 { - // A manual run holding the slot just means this run waits for the next tick. - if let Ok(guard) = state.jobs.claim(RunKind::Backup) { - if let Err(e) = scheduled_backup(state).await { - tracing::error!(error = %e, "scheduled backup failed"); - } - drop(guard); + RunKind::Fsck => { + i64::try_from(cfg.fsck_interval_days.saturating_mul(86_400)).unwrap_or(i64::MAX) } } - let fsck_wait = match due_inputs(state, RunKind::Fsck).await { - Ok((ok, attempt)) => secs_until_due( - OffsetDateTime::now_utc(), - ok.as_ref(), - attempt.as_ref(), - fsck_every, - RETRY_AFTER_SECS, - ), - Err(e) => { - tracing::error!(error = %e, "fsck scheduler could not read its history"); - return; +} + +/// Seconds until a job of this kind is due, from its run history. Zero means run now. +async fn secs_until_run(state: &AppState, kind: RunKind) -> Result { + let (ok, attempt) = due_inputs(state, kind).await?; + Ok(secs_until_due( + OffsetDateTime::now_utc(), + ok.as_ref(), + attempt.as_ref(), + interval_secs(state, kind), + RETRY_AFTER_SECS, + )) +} + +/// Seconds until the earlier of the backup and the fsck is due. Zero means one is due now. +async fn next_due_in(state: &AppState) -> Result { + let backup = secs_until_run(state, RunKind::Backup).await?; + let fsck = secs_until_run(state, RunKind::Fsck).await?; + Ok(backup.min(fsck)) +} + +/// Runs each job that is due now. A job that cannot take the run slot, because a manual run holds +/// it, is left for the next pass. +async fn run_due(state: &AppState) { + for kind in [RunKind::Backup, RunKind::Fsck] { + let due = match secs_until_run(state, kind).await { + Ok(wait) => wait == 0, + Err(e) => { + tracing::error!(error = %e, kind = kind.as_str(), "scheduler could not read its history"); + false + } + }; + if !due { + continue; } - }; - if fsck_wait == 0 - && let Ok(guard) = state.jobs.claim(RunKind::Fsck) - { - if let Err(e) = fsck_job(state, RunTrigger::Schedule, false).await { - tracing::error!(error = %e, "scheduled fsck failed"); + let Ok(guard) = state.jobs.claim(kind) else { + continue; + }; + let outcome = match kind { + RunKind::Backup => scheduled_backup(state).await.map(|_| ()), + RunKind::Fsck => fsck_job(state, RunTrigger::Schedule, false) + .await + .map(|_| ()), + }; + if let Err(e) = outcome { + tracing::error!(error = %e, kind = kind.as_str(), "scheduled run failed"); } drop(guard); } @@ -463,6 +490,13 @@ mod tests { assert_eq!(state.jobs.running(), None); } + #[tokio::test] + async fn a_fresh_install_wakes_at_once() { + let dir = tempfile::tempdir().expect("tempdir"); + let state = crate::test_support::test_state(dir.path()).await; + assert_eq!(next_due_in(&state).await.expect("next due"), 0); + } + #[tokio::test] async fn scheduled_backup_is_recorded_verified_and_pinged() { let dir = tempfile::tempdir().expect("tempdir"); diff --git a/crates/forge-web/src/ci/reaper.rs b/crates/forge-web/src/ci/reaper.rs index a9aa2ca..794a37e 100644 --- a/crates/forge-web/src/ci/reaper.rs +++ b/crates/forge-web/src/ci/reaper.rs @@ -58,6 +58,8 @@ pub async fn reap_before(state: &AppState, older_than: &str) -> usize { let mut seen = HashSet::new(); let mut wake = false; for job in &jobs { + state.ci_live.close_job(&job.id); + state.ci_live.bump_run(&job.run_id); if !seen.insert(job.run_id.clone()) { continue; } @@ -73,7 +75,7 @@ pub async fn reap_before(state: &AppState, older_than: &str) -> usize { } } if wake { - state.ci_waker.notify_one(); + state.ci_waker.notify_waiters(); } if !jobs.is_empty() { tracing::warn!(count = jobs.len(), "ci: reaped lost jobs"); diff --git a/crates/forge-web/src/ci/schedule.rs b/crates/forge-web/src/ci/schedule.rs index 072f927..4af755c 100644 --- a/crates/forge-web/src/ci/schedule.rs +++ b/crates/forge-web/src/ci/schedule.rs @@ -243,7 +243,7 @@ async fn create( .await; } if sync_run_statuses(state, &run).await? { - state.ci_waker.notify_one(); + state.ci_waker.notify_waiters(); } Ok(run) } diff --git a/crates/forge-web/src/mail/worker.rs b/crates/forge-web/src/mail/worker.rs index 46bf37b..f0787da 100644 --- a/crates/forge-web/src/mail/worker.rs +++ b/crates/forge-web/src/mail/worker.rs @@ -13,8 +13,8 @@ use time::format_description::well_known::Rfc3339; use crate::state::AppState; -/// The longest the worker sleeps when nothing wakes it. -const POLL: Duration = Duration::from_secs(60); +/// The longest the worker sleeps. It guards against a missed wake, not polling. +const BACKSTOP: Duration = Duration::from_secs(15 * 60); /// The shortest sleep, so a due time that has already passed does not spin the loop. const MIN_SLEEP: Duration = Duration::from_secs(1); /// Messages leased per pass. @@ -33,7 +33,7 @@ async fn run(state: AppState) { Ok(nap) => nap, Err(e) => { tracing::error!(error = %e, "mail: could not run a pass"); - POLL + BACKSTOP } }; tokio::select! { @@ -47,7 +47,8 @@ async fn run(state: AppState) { async fn tick(state: &AppState) -> forge_core::Result { let settings = state.store.mail_settings().await?; if !settings.enabled { - return Ok(POLL); + // Turning mail on notifies the waker; the backstop only guards a missed wake. + return Ok(BACKSTOP); } let now = now_stamp(); let lease_until = stamp_after(LEASE); @@ -93,13 +94,13 @@ async fn deliver(state: &AppState, entry: &OutboxEntry) { } /// How long the worker sleeps: until `next_due` (an RFC 3339 stamp), clamped to -/// `MIN_SLEEP..=POLL`. `None` or an unparsable stamp gives `POLL`. +/// `MIN_SLEEP..=BACKSTOP`. `None` (nothing queued) or an unparsable stamp gives `BACKSTOP`. pub fn sleep_for(next_due: Option<&str>, now: OffsetDateTime) -> Duration { let Some(due) = next_due.and_then(|s| OffsetDateTime::parse(s, &Rfc3339).ok()) else { - return POLL; + return BACKSTOP; }; let until = Duration::try_from(due - now).unwrap_or(Duration::ZERO); - until.clamp(MIN_SLEEP, POLL) + until.clamp(MIN_SLEEP, BACKSTOP) } #[cfg(test)] @@ -140,14 +141,14 @@ mod tests { let now = datetime!(2026-10-15 12:00:00 UTC); let stamp = |t: OffsetDateTime| t.format(&Rfc3339).expect("stamp"); - assert_eq!(sleep_for(None, now), POLL); + assert_eq!(sleep_for(None, now), BACKSTOP); let in_10s = stamp(now + time::Duration::seconds(10)); assert_eq!(sleep_for(Some(&in_10s), now), Duration::from_secs(10)); let in_1h = stamp(now + time::Duration::hours(1)); - assert_eq!(sleep_for(Some(&in_1h), now), POLL); + assert_eq!(sleep_for(Some(&in_1h), now), BACKSTOP); let past = stamp(now - time::Duration::seconds(5)); assert_eq!(sleep_for(Some(&past), now), MIN_SLEEP); - assert_eq!(sleep_for(Some("soon"), now), POLL); + assert_eq!(sleep_for(Some("soon"), now), BACKSTOP); } #[tokio::test] @@ -197,7 +198,7 @@ mod tests { enqueue(&state, "k", "a@example.com", "Hi", "body") .await .expect("queued"); - assert_eq!(tick(&state).await.expect("pass"), POLL); + assert_eq!(tick(&state).await.expect("pass"), BACKSTOP); assert!(fake.sent().is_empty()); let row = state.store.recent_mail(10).await.expect("rows"); assert_eq!(row[0].status(), OutboxStatus::Queued); diff --git a/crates/forge-web/src/mirrors/worker.rs b/crates/forge-web/src/mirrors/worker.rs index b64f01f..1d90c9d 100644 --- a/crates/forge-web/src/mirrors/worker.rs +++ b/crates/forge-web/src/mirrors/worker.rs @@ -1,6 +1,6 @@ -//! The mirror sync worker. It polls for due mirrors every minute, and wakes at once when -//! `AppState::mirror_waker` is notified (a "sync now", a new mirror, or a push). At most two runs -//! are in flight, and never two on the same repo. +//! The mirror sync worker. It sleeps until the next due mirror, and wakes at once when +//! `AppState::mirror_waker` is notified (a "sync now", a new mirror, or a push). With nothing due +//! it waits on the waker alone. At most two runs are in flight, and never two on the same repo. use std::collections::HashSet; use std::time::Duration; @@ -14,8 +14,8 @@ use super::{policy, run_one}; use crate::state::AppState; use crate::webhooks::client::WebhookPolicy; -/// The longest the worker sleeps when nothing wakes it. -const POLL: Duration = Duration::from_secs(60); +/// The longest the worker sleeps. It guards against a missed wake, not polling. +const BACKSTOP: Duration = Duration::from_secs(15 * 60); /// The shortest sleep, so a due time that has already passed does not spin the loop. const MIN_SLEEP: Duration = Duration::from_secs(1); /// Runs in flight at once. @@ -44,14 +44,13 @@ async fn run(state: AppState) { .await; // Wake when the earliest enabled mirror is due, so a push mirror queued with a short // debounce runs on time instead of waiting for the next poll. - let next = match state.store.next_mirror_due().await { - Ok(next) => next, + let nap = match state.store.next_mirror_due().await { + Ok(next) => sleep_for(next.as_deref(), OffsetDateTime::now_utc()), Err(e) => { tracing::error!(error = %e, "mirrors: could not read the next due time"); - None + BACKSTOP } }; - let nap = sleep_for(next.as_deref(), OffsetDateTime::now_utc()); tokio::select! { _ = tokio::time::sleep(nap) => {} _ = state.mirror_waker.notified() => {} @@ -64,14 +63,14 @@ async fn run(state: AppState) { } /// How long the worker sleeps before its next pass: until `next_due` (an RFC 3339 stamp, the -/// earliest enabled mirror), clamped to `MIN_SLEEP..=POLL`. `None` or an unparsable stamp gives -/// `POLL`. +/// earliest enabled mirror), clamped to `MIN_SLEEP..=BACKSTOP`. `None` (nothing enabled) or an +/// unparsable stamp gives `BACKSTOP`. pub fn sleep_for(next_due: Option<&str>, now: OffsetDateTime) -> Duration { let Some(due) = next_due.and_then(|s| OffsetDateTime::parse(s, &Rfc3339).ok()) else { - return POLL; + return BACKSTOP; }; let until = Duration::try_from(due - now).unwrap_or(Duration::ZERO); - until.clamp(MIN_SLEEP, POLL) + until.clamp(MIN_SLEEP, BACKSTOP) } /// Starts runs for due mirrors until the concurrency limit, skipping mirrors and repos already @@ -130,22 +129,22 @@ mod tests { let now = datetime!(2026-10-15 12:00:00 UTC); let stamp = |t: OffsetDateTime| t.format(&Rfc3339).expect("stamp"); - // Nothing enabled: the full poll interval. - assert_eq!(super::sleep_for(None, now), super::POLL); - // A push queued with a 10 s debounce: sleep until it is due, not the full poll. + // Nothing enabled: the backstop. + assert_eq!(super::sleep_for(None, now), super::BACKSTOP); + // A push queued with a 10 s debounce: sleep until it is due. let in_10s = stamp(now + time::Duration::seconds(10)); assert_eq!( super::sleep_for(Some(&in_10s), now), Duration::from_secs(10) ); - // Due later than the poll interval: wake at the poll interval. + // Due later than the backstop: wake at the backstop. let in_1h = stamp(now + time::Duration::hours(1)); - assert_eq!(super::sleep_for(Some(&in_1h), now), super::POLL); + assert_eq!(super::sleep_for(Some(&in_1h), now), super::BACKSTOP); // Already due (or in flight and still due): do not spin, wait the minimum. let past = stamp(now - time::Duration::seconds(5)); assert_eq!(super::sleep_for(Some(&past), now), super::MIN_SLEEP); - // A stamp that does not parse falls back to the poll interval. - assert_eq!(super::sleep_for(Some("soon"), now), super::POLL); + // A stamp that does not parse falls back to the backstop. + assert_eq!(super::sleep_for(Some("soon"), now), super::BACKSTOP); } /// Plain git against a bare repo, for setting up the fake upstream. diff --git a/crates/forge-web/src/pages/repo_mirrors.rs b/crates/forge-web/src/pages/repo_mirrors.rs index 4242052..80a44a1 100644 --- a/crates/forge-web/src/pages/repo_mirrors.rs +++ b/crates/forge-web/src/pages/repo_mirrors.rs @@ -633,8 +633,9 @@ async fn store_mirror( .store .schedule_mirror(&mirror.id, &now_stamp()) .await?; - state.mirror_waker.notify_one(); } + // A new mirror is due now, push or pull. + state.mirror_waker.notify_one(); Ok(Ok(mirror)) } @@ -931,6 +932,8 @@ async fn mirror_update(cx: &Cx, Form(form): Form) -> Result form.enabled.is_some(), ) .await?; + // The interval and the enabled flag decide when this mirror runs next. + state.mirror_waker.notify_one(); audit::record( &state.store, Some(cx), diff --git a/crates/forge-web/src/replication/mod.rs b/crates/forge-web/src/replication/mod.rs index 55092bd..3da2b89 100644 --- a/crates/forge-web/src/replication/mod.rs +++ b/crates/forge-web/src/replication/mod.rs @@ -547,6 +547,16 @@ impl ReplicationQueue { due } + /// The earliest debounce due time among the queued repos, or `None` when nothing is queued. + pub fn next_due(&self) -> Option { + self.pending + .lock() + .unwrap_or_else(PoisonError::into_inner) + .values() + .min() + .copied() + } + /// Asks the worker for a full reconcile pass as soon as it can. pub fn request_reconcile(&self) { self.reconcile.store(true, Ordering::SeqCst); @@ -762,6 +772,7 @@ mod tests { let later = Instant::now() + PUSH_DEBOUNCE + Duration::from_millis(10); assert_eq!(queue.take_due(later), ["a", "b"]); assert!(queue.take_due(later).is_empty(), "drained"); + assert_eq!(queue.next_due(), None, "nothing left to wait for"); assert!(!queue.take_reconcile_request()); queue.request_reconcile(); assert!(queue.take_reconcile_request()); diff --git a/crates/forge-web/src/replication/worker.rs b/crates/forge-web/src/replication/worker.rs index cbad9b1..454bca3 100644 --- a/crates/forge-web/src/replication/worker.rs +++ b/crates/forge-web/src/replication/worker.rs @@ -22,8 +22,8 @@ use super::{ use crate::backup::healthcheck; use crate::state::AppState; -/// How often the worker checks its queue and timers when nothing wakes it. -const TICK: Duration = Duration::from_secs(1); +/// Longest the worker sleeps with nothing due. Guards against a missed wake, not polling. +const BACKSTOP: Duration = Duration::from_secs(15 * 60); /// Everything a replication pass needs. The web side builds one from `AppState`; tests build one /// around a `LocalTransport`. @@ -83,9 +83,21 @@ async fn run(state: AppState) { let mut next_db = Instant::now(); let mut next_reconcile = Instant::now(); loop { + // Sleep until the earliest debounce or calendar timer, or until something is queued. + let backstop = Instant::now() + BACKSTOP; + let next = [ + state.replication.next_due(), + Some(next_db), + Some(next_reconcile), + Some(backstop), + ] + .into_iter() + .flatten() + .min() + .unwrap_or(backstop); tokio::select! { + () = tokio::time::sleep_until(tokio::time::Instant::from_std(next)) => {} () = state.replication.wait() => {} - () = tokio::time::sleep(TICK) => {} } for repo_id in state.replication.take_due(Instant::now()) { // A repo deleted since the update is skipped; the next reconcile removes its copy. diff --git a/crates/forge-web/src/webhooks/worker.rs b/crates/forge-web/src/webhooks/worker.rs index 91a8b1d..7bbed8d 100644 --- a/crates/forge-web/src/webhooks/worker.rs +++ b/crates/forge-web/src/webhooks/worker.rs @@ -15,6 +15,8 @@ use forge_core::time::{now_stamp, stamp_after, stamp_ago}; use forge_core::webhooks::{AttemptOutcome, Delivery}; use futures_util::StreamExt; use serde_json::{Map, Value}; +use time::OffsetDateTime; +use time::format_description::well_known::Rfc3339; use tokio::sync::Notify; use super::client::{HookClient, SendOutcome, WebhookPolicy, sign, validate_url}; @@ -27,8 +29,10 @@ pub type WebhookWaker = Arc; const BATCH: u32 = 16; /// Deliveries sent at once. const CONCURRENCY: usize = 4; -/// How long the worker sleeps when nothing wakes it. -const IDLE_POLL: Duration = Duration::from_secs(30); +/// The shortest sleep, so a due time that has already passed does not spin the loop. +const MIN_SLEEP: Duration = Duration::from_secs(1); +/// The longest sleep. It only guards against a missed wake, it is not polling. +const BACKSTOP: Duration = Duration::from_secs(15 * 60); /// Deliveries older than this are purged. const RETENTION: Duration = Duration::from_secs(14 * 24 * 60 * 60); /// How often the purge runs. @@ -86,14 +90,41 @@ async fn run(state: AppState, waker: WebhookWaker) { }; // A full batch may mean more is due, so go straight back for it. if claimed < usize::try_from(BATCH).unwrap_or(usize::MAX) { + // Wake when the earliest pending delivery is due (a claimed one wakes at its lease + // expiry), or at the next purge. With nothing pending, sleep up to `BACKSTOP`. + let next = match state.store.next_delivery_due().await { + Ok(next) => next, + Err(e) => { + tracing::error!(error = %e, "webhooks: could not read the next due time"); + None + } + }; + let nap = next + .as_deref() + .map_or(BACKSTOP, |due| sleep_for(due, OffsetDateTime::now_utc())); + let purge_nap = last_purge.map_or(Duration::ZERO, |at| { + PURGE_EVERY.saturating_sub(at.elapsed()) + }); tokio::select! { () = waker.notified() => {} - () = tokio::time::sleep(IDLE_POLL) => {} + () = tokio::time::sleep(nap) => {} + () = tokio::time::sleep(purge_nap) => {} } } } } +/// How long the worker sleeps until `next_due` (an RFC 3339 stamp, the earliest pending +/// delivery), clamped to `MIN_SLEEP..=BACKSTOP`. An unparsable stamp gives `MIN_SLEEP`, so it is +/// retried promptly rather than stalling. +fn sleep_for(next_due: &str, now: OffsetDateTime) -> Duration { + let Ok(due) = OffsetDateTime::parse(next_due, &Rfc3339) else { + return MIN_SLEEP; + }; + let until = Duration::try_from(due - now).unwrap_or(Duration::ZERO); + until.clamp(MIN_SLEEP, BACKSTOP) +} + /// Claims up to [`BATCH`] due deliveries at `now`, sends them, and records each result. Returns /// how many were claimed. pub(crate) async fn process_due( @@ -499,6 +530,25 @@ mod tests { assert!(row.next_attempt_at.is_some()); } + #[test] + fn sleep_stops_at_the_next_due_time_and_never_spins() { + use time::macros::datetime; + + let now = datetime!(2026-10-15 12:00:00 UTC); + let stamp = |t: OffsetDateTime| t.format(&Rfc3339).expect("stamp"); + // Due in 10 minutes: sleep until then. + let in_10m = stamp(now + time::Duration::minutes(10)); + assert_eq!(sleep_for(&in_10m, now), Duration::from_secs(600)); + // Due later than the backstop: wake at the backstop. + let in_1h = stamp(now + time::Duration::hours(1)); + assert_eq!(sleep_for(&in_1h, now), BACKSTOP); + // Already due, or a lease that has just passed: wait the minimum. + let past = stamp(now - time::Duration::seconds(5)); + assert_eq!(sleep_for(&past, now), MIN_SLEEP); + // A stamp that does not parse also waits the minimum. + assert_eq!(sleep_for("soon", now), MIN_SLEEP); + } + #[test] fn backoff_schedule_matches_the_contract() { assert_eq!(next_attempt_at(0), None);