forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

live.rs594 lines, 25.0 KiBHistoryRawDownload
1//! Live pages: change signals keyed by [`Topic`], and the event stream that carries them.
2//!
3//! A write that changes what a topic shows calls [`LiveHub::bump`]. Every open stream subscribed
4//! to that topic wakes and sends one `changed` event. The signal carries no data: the page reads
5//! its state again on the client (a soft re-fetch of the URL, see `nav.js`), so a bump that
6//! lands during another one is never lost. Nothing polls. A topic with no subscriber is not kept.
7//!
8//! # Adding a topic
9//! 1. Add a variant to [`Topic`], keyed by what the page is about (a repo id, a user id, ...).
10//! 2. Call `state.live.bump(&Topic::Variant(..))` after the write that changes the page.
11//! 3. In the page's own route (its auth check first), return
12//! `live::stream_changes(cx, &state.live, &[topics], read)`. `read` returns a short fingerprint
13//! of the state the page shows; a `changed` event is sent only when it differs from the last
14//! one, so a bump that changes nothing visible sends nothing.
15//! 4. Render `data-live="<the route URL>"` on the page's element that the client follows.
16//!
17//! A page whose state is cheap to compare can use `stream_changes` (the fingerprint). A page
18//! whose every bump is a visible change (the issue pages) uses [`stream_wakes`] instead: one
19//! `changed` per wake, several bumps in a row coalesced into one.
20//! A user's topics are keyed by the user id and streamed only to that user: the route takes the
21//! viewer from the session, never from the URL, so one user cannot follow another user's inbox.
22//!
23//! The hub is in-process only, like [`crate::notify_hub::NotifyHub`]. [`crate::ci::CiLive`] keeps
24//! its own counters for CI and is not on this hub.
25
26use std::collections::HashMap;
27use std::future::Future;
28use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
29use std::time::Duration;
30
31use futures_util::future::select_all;
32use futures_util::{Stream, StreamExt, stream};
33use tokio::sync::watch;
34use topcoat::Result;
35use topcoat::context::Cx;
36use topcoat::router::HeaderValue;
37use topcoat::router::content::sse::{Event, KeepAlive, Sse};
38use topcoat::router::response::{IntoResponse, Response};
39
40use crate::state::AppState;
41
42/// What a live page follows. Add a variant when a page needs a new signal.
43#[derive(Clone, Debug, PartialEq, Eq, Hash)]
44pub enum Topic {
45 /// The refs of a repo: a branch or tag was created, deleted or moved. Keyed by repo id.
46 RepoRefs(String),
47 /// The issues of a repo as a list: an issue, label or milestone changed, or a count moved.
48 /// Keyed by repo id. The labels and milestones pages and the repo tabs follow it too.
49 RepoIssues(String),
50 /// One issue: its body, comments, events, state, labels, reactions. Keyed by issue id.
51 Issue(String),
52 /// The pull request list of a repo: a pull opened, or any pull in the repo changed. Keyed by
53 /// repo id. Bumped by the `pull_live` page.
54 PullList(String),
55 /// One pull request, its conversation, commits and files. Keyed by the pull's issue id.
56 /// Bumped by the `pull_live` page.
57 Pull(String),
58 /// A repo's own state that its header shows: stars, watchers, forks, its name, description,
59 /// archived flag and default branch, the tab switches, and the mirror's last sync. Keyed by repo
60 /// id. Bumped after the write, and also when a package linked to the repo publishes or yanks (the
61 /// home page shows its newest version). The header's counts follow [`Topic::RepoIssues`] and
62 /// [`Topic::PullList`] as well.
63 Repo(String),
64 /// A user's repo listing, pins and contribution calendar.
65 /// Keyed by user id (an organization is a user too).
66 User(String),
67 /// A user's inbox: a notification was added, read or marked read. Keyed by user id.
68 Inbox(String),
69 /// A user's review requests: a pull request asked the user to review, a request was withdrawn,
70 /// the user submitted a review, or a pull request with the user's request closed or merged.
71 /// Keyed by the reviewer's user id. Streamed only to that user. Bumped by
72 /// the `review_requests` page and the `pull_live` page.
73 ReviewRequests(String),
74 /// A user's import jobs: a job was queued, started, progressed or finished. Keyed by user id.
75 /// Bumped by the importer when a job's state changes. Streamed only to that user.
76 Imports(String),
77 /// The public repo listing: a public repo was added, changed, or starred. Global.
78 Explore,
79 /// The discussions of a repo as a list: a discussion was opened, or any discussion of the repo
80 /// changed (a comment, a reaction, an answer, a lock, a category). Keyed by repo id. Bumped by
81 /// the `discussion_live` page.
82 Discussions(String),
83 /// One discussion: its body, comments, reactions, answer and lock state. Keyed by discussion
84 /// id. Bumped by the `discussion_live` page.
85 Discussion(String),
86 /// A repo's wiki: a page was saved, or a push changed the wiki's main branch. Keyed by repo id.
87 /// Bumped by the `wiki_live` page and by the wiki push hook.
88 Wiki(String),
89 /// The snippet list: a snippet was created, changed or deleted. Global; each viewer's list is
90 /// fingerprinted, so a bump that changes nothing the viewer sees sends nothing.
91 Snippets,
92 /// One snippet: its files, title, visibility and revisions. Keyed by snippet id.
93 Snippet(String),
94 /// An organization's pages: its members, teams, team members and linked repos, and settings.
95 /// Keyed by the org's user id. Bumped by the `org_live` page after a POST under the org.
96 Org(String),
97 /// The account list of the admin area: an account was registered, edited, suspended, lifted,
98 /// given or lost admin rights, or deleted. Global. Admin pages only, on [`admin`].
99 AdminUsers,
100 /// One account's admin page: its facts, suspension and passkeys. Keyed by user id. Admin
101 /// pages only, on [`admin`].
102 AdminUser(String),
103 /// The audit log: an entry was written. Global. Admin pages only, on [`admin`].
104 AdminAudit,
105 /// Backup and fsck runs: one started or finished. Global. Admin pages only, on [`admin`].
106 AdminBackups,
107 /// Replication: a copy was written, failed, or removed. Global. Admin pages only, on [`admin`].
108 AdminReplication,
109 /// The health page: an alert was raised or cleared, or a backup or copy finished. Global.
110 /// Admin pages only, on [`admin`].
111 AdminHealth,
112 /// The server settings: a value was saved or reset, or a restart was requested. Global.
113 /// Admin pages only, on [`admin`].
114 AdminServer,
115 /// The releases of a repo: a release was created, edited or deleted, an asset was added,
116 /// replaced or removed, or an asset was downloaded (its count). Keyed by repo id. The release
117 /// list, the release pages and the repo home page's latest release card follow it. Bumped by
118 /// [`crate::release_ops`].
119 RepoReleases(String),
120 /// A user's own settings: a profile, key, token, passkey, session, notification or appearance
121 /// setting changed, or a sign-in or a key or token use happened. Keyed by user id. Streamed only
122 /// to that user, never to the public profile viewers who follow [`Topic::User`].
123 Account(String),
124 /// A repo's settings pages and the security and transfer pages: a setting, collaborator, rule,
125 /// secret, webhook or delivery, mirror sync, security alert, or a pending transfer changed.
126 /// Keyed by repo id. Bumped by the settings write layer and by the background writers.
127 RepoSettings(String),
128 /// The commit statuses of a repo: a status was reported or replaced. Keyed by repo id. Bumped
129 /// by the CI runner and the statuses API, after the write.
130 CommitStatuses(String),
131 /// The server settings that pages render (every `Kind::Live` setting, such as the banner, the
132 /// registration mode or the limits): one was saved or reset. Global. Every page holds
133 /// `/-/alive`, anonymous viewers included, and follows it there (see
134 /// `settings_live::alive_response`). Bumped by the server settings after a save
135 /// or reset.
136 ServerSettings,
137}
138
139/// The hub of the admin pages. It is process-wide, not part of [`crate::state::AppState`]: the
140/// audit writer has no app state, and every audit entry wakes the admin pages from there.
141pub fn admin() -> &'static LiveHub {
142 static ADMIN: OnceLock<LiveHub> = OnceLock::new();
143 ADMIN.get_or_init(LiveHub::default)
144}
145
146/// The open topics, each with the counter its subscribers wait on.
147#[derive(Default)]
148pub struct LiveHub {
149 topics: Mutex<HashMap<Topic, watch::Sender<u64>>>,
150}
151
152impl LiveHub {
153 fn topics(&self) -> MutexGuard<'_, HashMap<Topic, watch::Sender<u64>>> {
154 self.topics.lock().unwrap_or_else(PoisonError::into_inner)
155 }
156
157 /// Subscribes to `topic`. The receiver starts as seen, so a bump after this call wakes it.
158 /// Subscribe before reading the state, so a change in between is not lost. Topics nobody
159 /// holds any more are dropped here, so the map stays small.
160 pub fn subscribe(&self, topic: &Topic) -> watch::Receiver<u64> {
161 let mut topics = self.topics();
162 topics.retain(|_, tx| tx.receiver_count() > 0);
163 topics
164 .entry(topic.clone())
165 .or_insert_with(|| watch::channel(0).0)
166 .subscribe()
167 }
168
169 /// Wakes the subscribers of `topic`. Does nothing when nobody is subscribed.
170 pub fn bump(&self, topic: &Topic) {
171 let mut topics = self.topics();
172 let Some(tx) = topics.get(topic) else {
173 return;
174 };
175 tx.send_modify(|generation| *generation = generation.wrapping_add(1));
176 if tx.receiver_count() == 0 {
177 topics.remove(topic);
178 }
179 }
180
181 /// Wakes the issue list and the labels, milestones and tabs that follow the repo's issues. Call
182 /// it after a change to a label or milestone of `repo_id`.
183 pub fn bump_repo_issues(&self, repo_id: &str) {
184 self.bump(&Topic::RepoIssues(repo_id.to_owned()));
185 }
186
187 /// Wakes the issue list of `repo_id` and the page of `issue_id`. Call it after an issue write
188 /// has succeeded, with the repo the issue belongs to.
189 pub fn bump_issue(&self, repo_id: &str, issue_id: &str) {
190 self.bump(&Topic::RepoIssues(repo_id.to_owned()));
191 self.bump(&Topic::Issue(issue_id.to_owned()));
192 }
193
194 /// A repo changed in a way its owner's pages, the explore list and its own header show: it
195 /// was created, renamed, moved, re-described, starred, watched or forked. Call it once per
196 /// owner whose listing changed (a transfer has two). An organization owner's team pages list
197 /// its repos too, so they are woken as well.
198 pub fn bump_repo(&self, owner_id: &str, repo_id: &str) {
199 self.bump(&Topic::User(owner_id.to_owned()));
200 self.bump(&Topic::Org(owner_id.to_owned()));
201 self.bump(&Topic::Explore);
202 self.bump(&Topic::Repo(repo_id.to_owned()));
203 // The owner's repo count is on the admin page of the account.
204 admin().bump(&Topic::AdminUser(owner_id.to_owned()));
205 }
206}
207
208/// The state a stream follows between wakes: the receivers of its topics, the read, and the
209/// fingerprint last sent or seen.
210struct Follow<F> {
211 wakes: Vec<watch::Receiver<u64>>,
212 read: F,
213 last: String,
214}
215
216/// The `changed` event of a live page. The data is not read by the client.
217fn wake_event() -> Result<Event> {
218 Ok(Event::new().event("changed").data("1"))
219}
220
221/// A `name` event with no data the client reads, sent on each change of a page's state.
222fn named_event(name: &'static str) -> Result<Event> {
223 Ok(Event::new().event(name).data("1"))
224}
225
226/// Waits until one of `wakes` is bumped. False when a topic is gone, which ends the stream.
227async fn wait_any(wakes: &mut [watch::Receiver<u64>]) -> bool {
228 let waits = wakes.iter_mut().map(|rx| Box::pin(rx.changed()));
229 let (woken, _, _) = select_all(waits).await;
230 woken.is_ok()
231}
232
233/// The response of a live stream for any of `topics`. It sends `changed` after each wake, with no
234/// fingerprint: the caller bumps only after a write that changes the page. Nothing is sent on
235/// connect. The stream ends when a topic is gone, which cannot happen while the stream holds it.
236pub fn stream_wakes(cx: &Cx, hub: &LiveHub, topics: &[Topic]) -> Result<Response> {
237 let wakes: Vec<watch::Receiver<u64>> = topics.iter().map(|t| hub.subscribe(t)).collect();
238 let events = stream::unfold(wakes, |mut wakes| async move {
239 if !wait_any(&mut wakes).await {
240 return None;
241 }
242 Some((wake_event(), wakes))
243 });
244 events_response(cx, events)
245}
246
247/// The response of a live stream for `topics`. It sends `changed` after each wake whose
248/// fingerprint differs from the last one. Nothing is sent on connect: the page already shows the
249/// state the first read saw. The stream ends if the read fails.
250pub async fn stream_changes<F, Fut>(
251 cx: &Cx,
252 hub: &LiveHub,
253 topics: &[Topic],
254 read: F,
255) -> Result<Response>
256where
257 F: Fn() -> Fut + Send + 'static,
258 Fut: Future<Output = Result<String>> + Send,
259{
260 stream_changes_with(cx, hub, topics, Vec::new(), read).await
261}
262
263/// `stream_changes` that also wakes on `extra`, signals from another hub such as the CI one. They
264/// must be subscribed before this is called, so a change in between still wakes the stream.
265pub async fn stream_changes_with<F, Fut>(
266 cx: &Cx,
267 hub: &LiveHub,
268 topics: &[Topic],
269 extra: Vec<watch::Receiver<u64>>,
270 read: F,
271) -> Result<Response>
272where
273 F: Fn() -> Fut + Send + 'static,
274 Fut: Future<Output = Result<String>> + Send,
275{
276 let events = named_changes(hub, topics.to_vec(), extra, "changed", read).await?;
277 events_response(cx, events)
278}
279
280/// The events of [`stream_changes_with`] as a stream, each named `name`, for a caller that merges
281/// several streams into one response (see `pages::shell_events`).
282pub async fn named_changes<F, Fut>(
283 hub: &LiveHub,
284 topics: Vec<Topic>,
285 extra: Vec<watch::Receiver<u64>>,
286 name: &'static str,
287 read: F,
288) -> Result<impl Stream<Item = Result<Event>> + Send + 'static>
289where
290 F: Fn() -> Fut + Send + 'static,
291 Fut: Future<Output = Result<String>> + Send,
292{
293 // Subscribed before the first read, so a change in between wakes the stream.
294 let mut wakes: Vec<watch::Receiver<u64>> =
295 topics.iter().map(|topic| hub.subscribe(topic)).collect();
296 wakes.extend(extra);
297 let last = read().await?;
298 Ok(stream::unfold(
299 Follow { wakes, read, last },
300 move |mut follow| async move {
301 loop {
302 if !wait_any(&mut follow.wakes).await {
303 return None;
304 }
305 let now = match (follow.read)().await {
306 Ok(now) => now,
307 Err(e) => {
308 tracing::error!(error = %e, "live: could not read the page state");
309 return None;
310 }
311 };
312 if now == follow.last {
313 continue;
314 }
315 follow.last = now;
316 return Some((named_event(name), follow));
317 }
318 },
319 ))
320}
321
322/// Wakes the settings pages of `user_id`. Called after a write that changes what they show.
323pub fn bump_account(state: &AppState, user_id: &str) {
324 state.live.bump(&Topic::Account(user_id.to_owned()));
325}
326
327/// Bumps the settings topic of a repo, after a write that changes one of its settings pages.
328pub fn bump_settings(hub: &LiveHub, repo_id: &str) {
329 hub.bump(&Topic::RepoSettings(repo_id.to_owned()));
330}
331
332/// A write changed the wiki of `repo_id`: a page was saved, or a push moved its main branch.
333pub fn bump_wiki(state: &AppState, repo_id: &str) {
334 state.live.bump(&Topic::Wiki(repo_id.to_owned()));
335}
336
337// Bumps. Each one wakes the streams of the topics it names; none of them reads more than the
338// ids it needs. A failed lookup is logged and leaves the streams as they were.
339
340/// A write changed one pull request: its page and the list both follow it.
341pub fn bump_pull(state: &AppState, repo_id: &str, issue_id: &str) {
342 state.live.bump(&Topic::Pull(issue_id.to_owned()));
343 bump_list(state, repo_id);
344}
345
346/// A pull request was opened, or the list changed for another reason. Only the list follows.
347pub fn bump_list(state: &AppState, repo_id: &str) {
348 state.live.bump(&Topic::PullList(repo_id.to_owned()));
349}
350
351/// A change that may touch any pull of the repo (a push, a label or milestone edit, a merge run
352/// by auto-merge): the list and every pull page of the repo.
353pub async fn bump_repo_pulls(state: &AppState, repo_id: &str) {
354 bump_list(state, repo_id);
355 match state.store.pull_refs(repo_id).await {
356 Ok(refs) => {
357 for (issue_id, _) in refs {
358 state.live.bump(&Topic::Pull(issue_id));
359 }
360 }
361 Err(e) => tracing::error!(error = %e, repo_id, "live: listing pulls to bump failed"),
362 }
363}
364
365/// A commit status was written for `sha`: the pulls whose head is that commit, and the list.
366pub async fn bump_head(state: &AppState, repo_id: &str, sha: &str) {
367 bump_list(state, repo_id);
368 match state.store.pulls_for_head_oid(repo_id, sha).await {
369 Ok(refs) => {
370 for (issue_id, _) in refs {
371 state.live.bump(&Topic::Pull(issue_id));
372 }
373 }
374 Err(e) => {
375 tracing::error!(error = %e, repo_id, "live: listing pulls for a head to bump failed")
376 }
377 }
378}
379
380/// How often an idle event stream sends a `: keepalive` comment, so a reverse proxy does not drop
381/// the connection. This is not a poll: events follow the change signals.
382const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30);
383
384/// A run's or job's status word and whether it is terminal. `None` when the row is gone.
385pub type Status = Option<(String, bool)>;
386
387/// One `changed` event carrying the status word.
388pub fn changed_event(status: String) -> Result<Event> {
389 Ok(Event::new().event("changed").data(status))
390}
391
392/// The events of a CI page, each named `name` (`changed` on a page's own stream). The first event
393/// carries the status now. Each later one follows a wake of `wake`: with `only_on_status`, only when
394/// the status differs from the last one sent. The stream ends after the terminal status is sent,
395/// when the row is gone, or when the signal closes. Subscribe `wake` before the first read, so a
396/// change in between is not lost.
397pub fn changed_stream<F, Fut>(
398 wake: watch::Receiver<u64>,
399 only_on_status: bool,
400 name: &'static str,
401 read: F,
402) -> impl Stream<Item = Result<Event>> + Send + 'static
403where
404 F: Fn() -> Fut + Send + 'static,
405 Fut: Future<Output = Result<Status>> + Send,
406{
407 struct Follow<F> {
408 wake: watch::Receiver<u64>,
409 only_on_status: bool,
410 read: F,
411 /// The status last read, sent or not.
412 last: Option<String>,
413 /// Set once a terminal status is read. Nothing follows it.
414 done: bool,
415 /// False until the first read. Every later read waits for a wake first.
416 primed: bool,
417 }
418 stream::unfold(
419 Follow {
420 wake,
421 only_on_status,
422 read,
423 last: None,
424 done: false,
425 primed: false,
426 },
427 move |mut follow| async move {
428 loop {
429 if follow.done {
430 return None;
431 }
432 if follow.primed && follow.wake.changed().await.is_err() {
433 return None;
434 }
435 follow.primed = true;
436 let (status, terminal) = match (follow.read)().await {
437 Ok(Some(found)) => found,
438 Ok(None) => return None,
439 Err(e) => {
440 tracing::error!(error = %e, "ci: live stream could not read the status");
441 return None;
442 }
443 };
444 follow.done = terminal;
445 let changed = follow.last.as_deref() != Some(status.as_str());
446 let send = changed || !follow.only_on_status;
447 follow.last = Some(status.clone());
448 if send {
449 return Some((Ok(Event::new().event(name).data(status)), follow));
450 }
451 }
452 },
453 )
454}
455
456/// Open event streams one client address (IPv6 by /64) may hold. A page holds one or two, so this
457/// is many tabs; past it a script that opens streams in a loop is refused.
458const MAX_STREAMS_PER_CLIENT: usize = 64;
459/// Open event streams server-wide. Each is a task and a socket that stay until the client leaves.
460const MAX_STREAMS: usize = 4096;
461
462/// Open streams per client address, and their sum.
463static OPEN_STREAMS: Mutex<(usize, Option<HashMap<std::net::IpAddr, usize>>)> =
464 Mutex::new((0, None));
465
466/// One open event stream, counted against its client's and the server's cap until dropped.
467/// `ip` is `None` for an uncounted stream.
468struct StreamSlot {
469 ip: Option<std::net::IpAddr>,
470}
471
472impl StreamSlot {
473 /// A slot for this request's client, or `None` when a cap is reached. Without the app state
474 /// (unit tests of a bare router) nothing is counted.
475 fn take(cx: &Cx) -> Option<StreamSlot> {
476 if topcoat::context::try_context::<AppState>(cx).is_none() {
477 return Some(StreamSlot { ip: None });
478 }
479 let ip = crate::client_ip::client_ip(cx);
480 let mut open = OPEN_STREAMS.lock().unwrap_or_else(|e| e.into_inner());
481 let (total, per_client) = &mut *open;
482 let count = per_client
483 .get_or_insert_with(HashMap::new)
484 .entry(ip)
485 .or_insert(0);
486 if *total >= MAX_STREAMS || *count >= MAX_STREAMS_PER_CLIENT {
487 return None;
488 }
489 *count += 1;
490 *total += 1;
491 Some(StreamSlot { ip: Some(ip) })
492 }
493}
494
495impl Drop for StreamSlot {
496 fn drop(&mut self) {
497 let Some(ip) = self.ip else {
498 return;
499 };
500 let mut open = OPEN_STREAMS.lock().unwrap_or_else(|e| e.into_inner());
501 let (total, per_client) = &mut *open;
502 *total = total.saturating_sub(1);
503 if let Some(map) = per_client.as_mut()
504 && let Some(count) = map.get_mut(&ip)
505 {
506 *count = count.saturating_sub(1);
507 if *count == 0 {
508 map.remove(&ip);
509 }
510 }
511 }
512}
513
514/// How long the browser waits before it reconnects a dropped event stream. The browser's default is
515/// a few seconds; one second makes a page come back as soon as a server restart is done.
516pub const STREAM_RETRY: Duration = Duration::from_secs(1);
517
518/// The response of an event stream: keep-alive comments while idle, no buffering by a reverse
519/// proxy, and a `retry` field first so every stream reconnects after `STREAM_RETRY`.
520pub fn events_response(
521 cx: &Cx,
522 events: impl Stream<Item = Result<Event>> + Send + 'static,
523) -> Result<Response> {
524 // Past the cap the stream is refused: the page keeps working, only without live updates.
525 let Some(slot) = StreamSlot::take(cx) else {
526 let mut res = Response::new(topcoat::router::Body::from("too many open live streams"));
527 *res.status_mut() = http::StatusCode::TOO_MANY_REQUESTS;
528 return Ok(res);
529 };
530 // The slot lives as long as the stream: it is given back when the client goes away.
531 let events = events.map(move |event| {
532 let _held = &slot;
533 event
534 });
535 let retry = stream::once(std::future::ready(Ok(Event::new().retry(STREAM_RETRY))));
536 let events = Sse::new(retry.chain(events)).keep_alive(
537 KeepAlive::new()
538 .interval(STREAM_KEEP_ALIVE)
539 .text("keepalive"),
540 );
541 let mut res = events.into_response(cx)?;
542 res.headers_mut()
543 .insert("x-accel-buffering", HeaderValue::from_static("no"));
544 Ok(res)
545}
546
547#[cfg(test)]
548mod tests {
549 use super::*;
550
551 #[tokio::test]
552 async fn a_bump_wakes_only_the_subscribers_of_that_topic() {
553 let hub = LiveHub::default();
554 let a = Topic::RepoRefs("repo-a".to_owned());
555 let b = Topic::RepoRefs("repo-b".to_owned());
556 let mut wake_a = hub.subscribe(&a);
557 let wake_b = hub.subscribe(&b);
558
559 hub.bump(&a);
560
561 tokio::time::timeout(Duration::from_secs(1), wake_a.changed())
562 .await
563 .expect("woken")
564 .expect("open");
565 assert!(!wake_b.has_changed().expect("open"));
566 }
567
568 #[tokio::test]
569 async fn a_topic_nobody_holds_is_dropped_on_the_next_change() {
570 let hub = LiveHub::default();
571 let topic = Topic::RepoRefs("repo-a".to_owned());
572 let wake = hub.subscribe(&topic);
573 drop(wake);
574
575 hub.bump(&topic);
576 assert!(hub.topics().is_empty());
577 }
578
579 #[tokio::test]
580 async fn bump_repo_wakes_the_owner_the_explore_list_and_the_repo() {
581 let hub = LiveHub::default();
582 let owner = hub.subscribe(&Topic::User("owner".to_owned()));
583 let explore = hub.subscribe(&Topic::Explore);
584 let repo = hub.subscribe(&Topic::Repo("repo".to_owned()));
585 let other = hub.subscribe(&Topic::User("someone".to_owned()));
586
587 hub.bump_repo("owner", "repo");
588
589 assert!(owner.has_changed().expect("open"));
590 assert!(explore.has_changed().expect("open"));
591 assert!(repo.has_changed().expect("open"));
592 assert!(!other.has_changed().expect("open"));
593 }
594}