Skip to content

Commit f2e4504

Browse files
authored
perf(blocker): take a finished list download at once (#370)
2 parents 6a00922 + d27f44d commit f2e4504

9 files changed

Lines changed: 138 additions & 0 deletions

File tree

‎crates/zephium-app/src/actor/mailbox.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ enum CoalescedKey {
4141
BlockerPreferenceRetry(ProfileId),
4242
BlockerStartupDeadline(ProfileId),
4343
BlockerCatalogPoll,
44+
BlockerCatalogChanged,
4445
ContentRules(ProfileId, ContentPolicyGeneration),
4546
// Generations are monotonic and the newest settlement is authoritative;
4647
// scope-only coalescing prevents a rapid sequence from defeating the
@@ -1395,6 +1396,7 @@ fn command_coalesced_key(command: &Command) -> Option<CoalescedKey> {
13951396
Some(CoalescedKey::BlockerStartupDeadline(*profile))
13961397
}
13971398
Command::BlockerCatalogPoll { .. } => Some(CoalescedKey::BlockerCatalogPoll),
1399+
Command::BlockerCatalogChanged => Some(CoalescedKey::BlockerCatalogChanged),
13981400
Command::ProfileDeletionReady(profile) => {
13991401
Some(CoalescedKey::ProfileDeletionReady(*profile))
14001402
}

‎crates/zephium-app/src/api.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -858,6 +858,9 @@ pub enum Command {
858858
operation: u64,
859859
attempt: u8,
860860
},
861+
/// The catalog's update worker published a new status, such as a finished
862+
/// download, so the catalog is maintained now rather than at the next tick.
863+
BlockerCatalogChanged,
861864
/// One bounded-backoff retry for journal reconciliation, native erasure,
862865
/// or local SQLite finalization.
863866
ProfileDeletionRetry {

‎crates/zephium-app/src/shell/mod.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,12 @@ impl Shell {
574574
}
575575

576576
pub(super) fn attach_queue(&mut self, queue: CommandQueue) {
577+
let waker = queue.clone();
578+
self.blocker
579+
.service
580+
.set_change_waker(std::sync::Arc::new(move || {
581+
let _ = waker.try_push(Command::BlockerCatalogChanged);
582+
}));
577583
self.attach_queue_for_terminal_cleanup(queue);
578584
self.schedule_blocker_catalog_activation_poll();
579585
}
@@ -1380,6 +1386,7 @@ impl Shell {
13801386
Command::BlockerCatalogPoll { operation, attempt } => {
13811387
self.on_blocker_catalog_poll(operation, attempt)
13821388
}
1389+
Command::BlockerCatalogChanged => self.maintain_blocker_catalog(),
13831390
Command::ProfileDeletionRetry {
13841391
profile,
13851392
generation,

‎crates/zephium-app/src/shell/tests/blocker.rs‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ struct ControlledCompiler {
139139
shutdown_order: Mutex<Option<Arc<Mutex<Vec<&'static str>>>>>,
140140
catalog: Mutex<Option<BlockerCatalogSnapshot>>,
141141
refresh_admissions: Mutex<VecDeque<BlockerCatalogRefreshDispatch>>,
142+
change_waker: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
142143
}
143144

144145
impl ControlledCompiler {
@@ -174,6 +175,12 @@ impl ControlledCompiler {
174175
*self.catalog.lock().unwrap() = Some(catalog);
175176
}
176177

178+
/// What the update worker does when it publishes a status.
179+
fn wake(&self) {
180+
let wake = self.change_waker.lock().unwrap().clone();
181+
(wake.expect("the shell registers a waker"))();
182+
}
183+
177184
fn admit_refresh(&self, dispatch: BlockerCatalogRefreshDispatch) {
178185
self.refresh_admissions.lock().unwrap().push_back(dispatch);
179186
}
@@ -247,6 +254,10 @@ impl BlockerCompiler for ControlledCompiler {
247254
}
248255

249256
impl BlockerCatalog for ControlledCompiler {
257+
fn set_change_waker(&self, wake: Arc<dyn Fn() + Send + Sync>) {
258+
*self.change_waker.lock().unwrap() = Some(wake);
259+
}
260+
250261
fn maintain(&self) -> BlockerCatalogSnapshot {
251262
self.catalog
252263
.lock()
@@ -584,6 +595,33 @@ fn startup_candidate_advances_on_internal_polls_without_waiting_for_heartbeat()
584595
assert_eq!(shell.pending_catalog_activation_poll_for_test(), None);
585596
}
586597

598+
#[test]
599+
fn a_finished_download_is_taken_at_once_not_at_the_next_heartbeat() {
600+
let (mut shell, compiler) = shell_with_initial_catalog(catalog_revision(1, 1));
601+
let queue = CommandQueue::new();
602+
shell.attach_queue(queue.clone());
603+
while queue.try_recv().is_some() {}
604+
605+
let mut downloaded = catalog_revision(2, 2);
606+
downloaded.installed_revision = Some(1);
607+
downloaded.installed_manifest_sha256 = Some([1; 32]);
608+
set_catalog_candidate(&mut downloaded, 2);
609+
compiler.set_catalog(downloaded);
610+
// Two published statuses before the actor runs make one wake.
611+
compiler.wake();
612+
compiler.wake();
613+
let wake = queue
614+
.try_recv()
615+
.expect("a published status wakes the actor");
616+
assert!(matches!(wake, Command::BlockerCatalogChanged));
617+
assert!(queue.try_recv().is_none());
618+
619+
shell.handle(wake);
620+
let catalog = shell.blocker_catalog_for_test();
621+
assert_eq!(catalog.package_revision, Some(2));
622+
assert!(catalog.activation_pending);
623+
}
624+
587625
#[test]
588626
fn refreshing_candidate_keeps_fast_internal_settlement_polling() {
589627
let mut refreshing = catalog_revision(1, 1);

‎crates/zephium-blocker-service/src/lib.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1824,6 +1824,17 @@ impl BlockerCatalog for ManagedBlocker {
18241824
self.drive_locked(true)
18251825
}
18261826

1827+
fn set_change_waker(&self, wake: Arc<dyn Fn() + Send + Sync>) {
1828+
if let Some(updater) = self
1829+
.updater
1830+
.lock()
1831+
.unwrap_or_else(|poisoned| poisoned.into_inner())
1832+
.as_ref()
1833+
{
1834+
updater.set_change_waker(wake);
1835+
}
1836+
}
1837+
18271838
fn request_refresh(&self) -> BlockerCatalogRefreshDispatch {
18281839
let _serial = self
18291840
.maintenance_serial

‎crates/zephium-blocker-update/src/catalog_worker.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,16 @@ impl CatalogUpdateWorker {
136136
Worker::Official(worker) => worker.reject_candidate(identity, failure, reason, done),
137137
}
138138
}
139+
/// Calls `wake` after each status the worker publishes. The signed
140+
/// repository worker is not provisioned and keeps the routine check.
141+
pub fn set_change_waker(&self, wake: std::sync::Arc<dyn Fn() + Send + Sync>) {
142+
match &self.0 {
143+
#[cfg(feature = "tuf")]
144+
Worker::Tuf(_) => drop(wake),
145+
#[cfg(feature = "official-https")]
146+
Worker::Official(worker) => worker.set_change_waker(wake),
147+
}
148+
}
139149
/// Waits for a newer status revision, without periodic background polling.
140150
pub fn wait_for_change(&self, revision: u64, timeout: Duration) -> WaitForStatus {
141151
match &self.0 {

‎crates/zephium-blocker-update/src/lib.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,10 @@ mod disabled_worker {
8080
match *self {}
8181
}
8282
/// Unreachable without an enabled source worker.
83+
pub fn set_change_waker(&self, _wake: std::sync::Arc<dyn Fn() + Send + Sync>) {
84+
match *self {}
85+
}
86+
/// Unreachable without an enabled source worker.
8387
pub fn official_freshness(&self) -> Option<(u64, bool)> {
8488
match *self {}
8589
}

‎crates/zephium-blocker-update/src/official.rs‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ pub(crate) struct OfficialWorker {
2222
struct Shared {
2323
state: Mutex<State>,
2424
changed: Condvar,
25+
/// Told after each published status, outside the state lock.
26+
waker: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
2527
}
2628
struct State {
2729
snapshot: StatusSnapshot,
@@ -75,6 +77,15 @@ impl Shared {
7577
state.candidate_identity = record.candidate.as_ref().map(|p| p.identity.clone());
7678
state.busy = false;
7779
self.changed.notify_all();
80+
drop(state);
81+
let waker = self
82+
.waker
83+
.lock()
84+
.unwrap_or_else(|poisoned| poisoned.into_inner())
85+
.clone();
86+
if let Some(wake) = waker {
87+
wake();
88+
}
7889
}
7990
}
8091

@@ -156,6 +167,7 @@ impl OfficialWorker {
156167
repairs: 0,
157168
}),
158169
changed: Condvar::new(),
170+
waker: Mutex::new(None),
159171
});
160172
let (sender, receiver) = mpsc::sync_channel(2);
161173
let (cancel, mut cancelled) = watch::channel(false);
@@ -531,6 +543,13 @@ impl OfficialWorker {
531543
state.busy = true;
532544
Ok(())
533545
}
546+
pub(crate) fn set_change_waker(&self, wake: Arc<dyn Fn() + Send + Sync>) {
547+
*self
548+
.shared
549+
.waker
550+
.lock()
551+
.unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(wake);
552+
}
534553
pub(crate) fn wait_for_change(&self, revision: u64, timeout: Duration) -> WaitForStatus {
535554
let state = self.shared.lock();
536555
let (state, _) = self
@@ -887,6 +906,45 @@ mod tests {
887906
.unwrap()
888907
}
889908

909+
#[test]
910+
fn each_published_status_wakes_the_registered_caller_outside_the_lock() {
911+
let (_dir, store, _package) = fixture();
912+
let shared = Arc::new(Shared {
913+
state: Mutex::new(State {
914+
snapshot: StatusSnapshot {
915+
revision: 1,
916+
last_refresh_attempt_unix: None,
917+
status: UpdateStatus::Shutdown,
918+
},
919+
initial: None,
920+
candidate: None,
921+
candidate_identity: None,
922+
due: 0,
923+
verification: 0,
924+
freshness_deadline: 0,
925+
busy: false,
926+
sealed: false,
927+
operation: 0,
928+
repairs: 0,
929+
}),
930+
changed: Condvar::new(),
931+
waker: Mutex::new(None),
932+
});
933+
// Nothing is registered yet: publishing must not need a waker.
934+
shared.publish(&store.record, UpdateStatus::Shutdown);
935+
let wakes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
936+
let (seen, observed) = (wakes.clone(), Arc::downgrade(&shared));
937+
*shared.waker.lock().unwrap() = Some(Arc::new(move || {
938+
// The state lock is free while the caller is told.
939+
let shared = observed.upgrade().unwrap();
940+
assert!(shared.state.try_lock().is_ok());
941+
seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
942+
}));
943+
shared.publish(&store.record, UpdateStatus::Shutdown);
944+
shared.publish(&store.record, UpdateStatus::Shutdown);
945+
assert_eq!(wakes.load(std::sync::atomic::Ordering::SeqCst), 2);
946+
}
947+
890948
#[test]
891949
fn a_fresh_restart_preserves_due_time_and_never_admits_a_startup_request() {
892950
let dir = tempfile::tempdir_in(std::env::current_dir().unwrap()).unwrap();

‎crates/zephium-core/src/ports/blocker.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,11 @@ pub trait BlockerCatalog {
256256
fn maintain(&self) -> BlockerCatalogSnapshot;
257257

258258
fn request_refresh(&self) -> BlockerCatalogRefreshDispatch;
259+
260+
/// Registers `wake`, called from the update worker after each status it
261+
/// publishes, such as a finished download, so the caller can `maintain`
262+
/// at once instead of at its next routine check. It must only queue work.
263+
fn set_change_waker(&self, _wake: Arc<dyn Fn() + Send + Sync>) {}
259264
}
260265

261266
/// Bounded asynchronous compiler for browser-maintained filter material.

0 commit comments

Comments
 (0)