forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

live.rs285 lines, 10.3 KiBHistoryRawDownload
1//! Change signals for CI jobs, runs and repos. [`CiLive`] keeps one generation counter per job, one
2//! per run and one per repo. A write that changes a job or a run bumps its counter, and every
3//! subscriber wakes on the change. The counter carries no data: a subscriber reads the database or
4//! the log file again when it wakes. Nothing polls. A signal with no receivers left is removed, so
5//! the maps hold only the jobs, runs and repos somebody is watching. The hub is in-process only,
6//! like [`NotifyHub`].
7//!
8//! [`NotifyHub`]: crate::notify_hub::NotifyHub
9
10use std::collections::HashMap;
11use std::sync::{Mutex, MutexGuard, PoisonError};
12
13use tokio::sync::watch;
14
15/// The one key of the runners signal: the admin pages follow all runners together.
16const RUNNERS_KEY: &str = "runners";
17
18/// The one key of the any-run signal: a page that lists runs of many repos follows them together.
19/// It lives in the runs map, next to the per-run keys, which are run ids and never equal this.
20const RUNS_ANY_KEY: &str = "*runs";
21
22/// The change counters of CI jobs and runs, each keyed by its id.
23#[derive(Default)]
24pub struct CiLive {
25 jobs: Signals,
26 runs: Signals,
27 repos: Signals,
28 runners: Signals,
29 queues: Signals,
30 /// The last online state each runner was seen in. Only a change wakes the runners pages.
31 runner_online: Mutex<HashMap<String, bool>>,
32}
33
34impl CiLive {
35 /// Records whether runner `runner_id` is online now. Wakes the runners pages only when that
36 /// differs from the state last recorded, so a heartbeat of a runner that stays online costs one
37 /// map lookup.
38 pub fn note_runner_online(&self, runner_id: &str, online: bool) {
39 let changed = self
40 .runner_online
41 .lock()
42 .unwrap_or_else(PoisonError::into_inner)
43 .insert(runner_id.to_owned(), online)
44 != Some(online);
45 if changed {
46 self.bump_runners();
47 }
48 }
49
50 /// Whether runner `runner_id` was last recorded online.
51 pub fn runner_recorded_online(&self, runner_id: &str) -> bool {
52 self.runner_online
53 .lock()
54 .unwrap_or_else(PoisonError::into_inner)
55 .get(runner_id)
56 == Some(&true)
57 }
58
59 /// Forgets the recorded state of every runner not in `keep`, so a deleted runner leaves no entry.
60 pub fn forget_runners_except(&self, keep: &[&str]) {
61 self.runner_online
62 .lock()
63 .unwrap_or_else(PoisonError::into_inner)
64 .retain(|id, _| keep.contains(&id.as_str()));
65 }
66
67 /// Subscribes to changes of the merge queue of repo `repo_id`: an entry was added, moved or
68 /// finished. Same rules as [`CiLive::subscribe_job`].
69 pub fn subscribe_queue(&self, repo_id: &str) -> watch::Receiver<u64> {
70 self.queues.subscribe(repo_id)
71 }
72
73 /// Wakes the subscribers of the merge queue of repo `repo_id`.
74 pub fn bump_queue(&self, repo_id: &str) {
75 self.queues.bump(repo_id);
76 }
77
78 /// Subscribes to changes of job `job_id`. The receiver starts as seen, so a bump after this
79 /// call wakes it. Subscribe before the state you read, so a change in between is not lost.
80 pub fn subscribe_job(&self, job_id: &str) -> watch::Receiver<u64> {
81 self.jobs.subscribe(job_id)
82 }
83
84 /// Subscribes to changes of run `run_id`. Same rules as [`CiLive::subscribe_job`].
85 pub fn subscribe_run(&self, run_id: &str) -> watch::Receiver<u64> {
86 self.runs.subscribe(run_id)
87 }
88
89 /// Subscribes to changes of any run of any repo: a run was created or changed state, or one of
90 /// its jobs did. Same rules as [`CiLive::subscribe_job`].
91 pub fn subscribe_any_run(&self) -> watch::Receiver<u64> {
92 self.runs.subscribe(RUNS_ANY_KEY)
93 }
94
95 /// Subscribes to changes of repo `repo_id`: a run of the repo was created or changed state.
96 /// Same rules as [`CiLive::subscribe_job`].
97 pub fn subscribe_repo(&self, repo_id: &str) -> watch::Receiver<u64> {
98 self.repos.subscribe(repo_id)
99 }
100
101 /// Subscribes to changes of any runner: its jobs, live concurrency, reported config or an
102 /// admin edit. Same rules as [`CiLive::subscribe_job`].
103 pub fn subscribe_runners(&self) -> watch::Receiver<u64> {
104 self.runners.subscribe(RUNNERS_KEY)
105 }
106
107 /// Wakes the subscribers of the runners pages.
108 pub fn bump_runners(&self) {
109 self.runners.bump(RUNNERS_KEY);
110 }
111
112 /// Wakes the subscribers of job `job_id`: its log grew or its state changed. Does nothing when
113 /// nobody is subscribed.
114 pub fn bump_job(&self, job_id: &str) {
115 self.jobs.bump(job_id);
116 }
117
118 /// Wakes the subscribers of run `run_id`: one of its jobs or its own status changed.
119 pub fn bump_run(&self, run_id: &str) {
120 self.runs.bump(run_id);
121 self.runs.bump(RUNS_ANY_KEY);
122 }
123
124 /// Wakes the subscribers of repo `repo_id`: a run of the repo was created or changed state.
125 /// Callers bump it next to the run bump, since the run signal does not know its repo.
126 pub fn bump_repo(&self, repo_id: &str) {
127 self.repos.bump(repo_id);
128 self.runs.bump(RUNS_ANY_KEY);
129 }
130
131 /// Wakes the subscribers of job `job_id` once more and drops its signal. Call it when the job
132 /// has reached a terminal state: no change follows, so the signal is not kept. A subscriber
133 /// that waits on a closed signal wakes once and then sees it closed.
134 pub fn close_job(&self, job_id: &str) {
135 self.jobs.close(job_id);
136 }
137}
138
139/// One keyed set of counters. A key has an entry only while it has a receiver or a bump is due.
140#[derive(Default)]
141pub struct Signals {
142 counters: Mutex<HashMap<String, watch::Sender<u64>>>,
143}
144
145impl Signals {
146 fn counters(&self) -> MutexGuard<'_, HashMap<String, watch::Sender<u64>>> {
147 self.counters.lock().unwrap_or_else(PoisonError::into_inner)
148 }
149
150 pub fn subscribe(&self, key: &str) -> watch::Receiver<u64> {
151 self.counters()
152 .entry(key.to_owned())
153 .or_insert_with(|| watch::channel(0).0)
154 .subscribe()
155 }
156
157 /// Counts one change. Without a subscriber there is no entry, so the bump is a no-op. An entry
158 /// whose last receiver is gone is removed here.
159 pub fn bump(&self, key: &str) {
160 let mut counters = self.counters();
161 let Some(tx) = counters.get(key) else {
162 return;
163 };
164 tx.send_modify(|generation| *generation = generation.wrapping_add(1));
165 if tx.receiver_count() == 0 {
166 counters.remove(key);
167 }
168 }
169
170 /// Counts one last change and removes the entry. The sender is dropped afterwards, so each
171 /// subscriber wakes once more and then finds the signal closed.
172 fn close(&self, key: &str) {
173 let removed = self.counters().remove(key);
174 if let Some(tx) = removed {
175 tx.send_modify(|generation| *generation = generation.wrapping_add(1));
176 }
177 }
178}
179
180#[cfg(test)]
181mod tests {
182 use std::time::Duration;
183
184 use super::*;
185
186 #[tokio::test]
187 async fn a_bump_wakes_only_the_subscribers_of_that_job() {
188 let live = CiLive::default();
189 let mut job = live.subscribe_job("job-1");
190 let other = live.subscribe_job("job-2");
191 let run = live.subscribe_run("run-1");
192
193 live.bump_job("job-1");
194
195 tokio::time::timeout(Duration::from_secs(1), job.changed())
196 .await
197 .expect("woken")
198 .expect("open");
199 assert_eq!(*job.borrow_and_update(), 1);
200 assert!(!other.has_changed().expect("open"));
201 assert!(!run.has_changed().expect("open"));
202 }
203
204 #[tokio::test]
205 async fn a_bump_before_subscribing_is_not_seen_and_a_bump_after_is() {
206 let live = CiLive::default();
207 let early = live.subscribe_run("run-1");
208 live.bump_run("run-1");
209 let mut late = live.subscribe_run("run-1");
210 assert!(early.has_changed().expect("open"));
211 assert!(!late.has_changed().expect("open"));
212 live.bump_run("run-1");
213 assert!(late.has_changed().expect("open"));
214 late.changed().await.expect("open");
215 assert_eq!(*late.borrow_and_update(), 2);
216 }
217
218 #[test]
219 fn a_bump_without_subscribers_keeps_no_entry() {
220 let live = CiLive::default();
221 live.bump_job("job-1");
222 live.bump_run("run-1");
223 live.bump_repo("repo-1");
224 assert!(live.jobs.counters().is_empty());
225 assert!(live.runs.counters().is_empty());
226 assert!(live.repos.counters().is_empty());
227 }
228
229 #[tokio::test]
230 async fn a_repo_bump_wakes_only_the_subscribers_of_that_repo() {
231 let live = CiLive::default();
232 let mut repo = live.subscribe_repo("repo-1");
233 let other = live.subscribe_repo("repo-2");
234 let run = live.subscribe_run("run-1");
235
236 live.bump_repo("repo-1");
237
238 tokio::time::timeout(Duration::from_secs(1), repo.changed())
239 .await
240 .expect("woken")
241 .expect("open");
242 assert_eq!(*repo.borrow_and_update(), 1);
243 assert!(!other.has_changed().expect("open"));
244 assert!(!run.has_changed().expect("open"));
245 }
246
247 #[test]
248 fn a_bump_drops_the_entry_once_its_last_receiver_is_gone() {
249 let live = CiLive::default();
250 let rx = live.subscribe_job("job-1");
251 assert_eq!(live.jobs.counters().len(), 1);
252 drop(rx);
253 live.bump_job("job-1");
254 assert!(live.jobs.counters().is_empty());
255 }
256
257 #[tokio::test]
258 async fn a_runner_wakes_the_pages_only_when_its_online_state_changes() {
259 let live = CiLive::default();
260 let mut runners = live.subscribe_runners();
261
262 live.note_runner_online("runner-1", true);
263 assert!(runners.has_changed().expect("open"));
264 runners.borrow_and_update();
265
266 live.note_runner_online("runner-1", true);
267 assert!(!runners.has_changed().expect("open"));
268
269 live.note_runner_online("runner-1", false);
270 assert!(runners.has_changed().expect("open"));
271 assert!(!live.runner_recorded_online("runner-1"));
272 }
273
274 #[tokio::test]
275 async fn close_wakes_the_subscriber_once_and_then_ends_the_signal() {
276 let live = CiLive::default();
277 let mut rx = live.subscribe_job("job-1");
278 live.close_job("job-1");
279 assert!(live.jobs.counters().is_empty());
280
281 rx.changed().await.expect("the last change is delivered");
282 assert_eq!(*rx.borrow_and_update(), 1);
283 assert!(rx.changed().await.is_err());
284 }
285}