forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

packages_live.rs82 lines, 2.7 KiBHistoryRawDownload
1//! Change signals for package registries. [`PackagesLive`] keeps one generation counter per owner.
2//! A publish or a yank bumps the owner's counter, and every open page of that registry wakes and
3//! refetches. The counter carries no data, and nothing polls. A signal with no receivers left is
4//! removed, so the map holds only the owners somebody is watching. The hub is in-process only,
5//! like [`NotifyHub`].
6//!
7//! [`NotifyHub`]: crate::notify_hub::NotifyHub
8
9use std::collections::HashMap;
10use std::sync::{Mutex, MutexGuard, PoisonError};
11
12use tokio::sync::watch;
13
14/// The change counters of package registries, each keyed by its owner's id.
15#[derive(Default)]
16pub struct PackagesLive {
17 owners: Mutex<HashMap<String, watch::Sender<u64>>>,
18}
19
20impl PackagesLive {
21 /// Subscribes to changes of `owner_id`'s registry. The receiver starts as seen, so a bump
22 /// after this call wakes it. Subscribe before the state you read, so a change in between is
23 /// not lost.
24 pub fn subscribe(&self, owner_id: &str) -> watch::Receiver<u64> {
25 let mut owners = self.owners();
26 owners.retain(|_, tx| tx.receiver_count() > 0);
27 owners
28 .entry(owner_id.to_owned())
29 .or_insert_with(|| watch::channel(0).0)
30 .subscribe()
31 }
32
33 /// Counts one change to `owner_id`'s registry. Without a subscriber there is no entry, so the
34 /// bump is a no-op. An entry whose last receiver is gone is removed here.
35 pub fn bump(&self, owner_id: &str) {
36 let mut owners = self.owners();
37 let Some(tx) = owners.get(owner_id) else {
38 return;
39 };
40 tx.send_modify(|generation| *generation = generation.wrapping_add(1));
41 if tx.receiver_count() == 0 {
42 owners.remove(owner_id);
43 }
44 }
45
46 fn owners(&self) -> MutexGuard<'_, HashMap<String, watch::Sender<u64>>> {
47 self.owners.lock().unwrap_or_else(PoisonError::into_inner)
48 }
49}
50
51#[cfg(test)]
52mod tests {
53 use std::time::Duration;
54
55 use super::*;
56
57 #[tokio::test]
58 async fn a_bump_wakes_only_the_subscribers_of_that_owner() {
59 let live = PackagesLive::default();
60 let mut tahinli = live.subscribe("user-1");
61 let mut other = live.subscribe("user-2");
62
63 live.bump("user-1");
64
65 tokio::time::timeout(Duration::from_secs(1), tahinli.changed())
66 .await
67 .expect("woken")
68 .expect("open");
69 assert!(
70 tokio::time::timeout(Duration::from_millis(50), other.changed())
71 .await
72 .is_err()
73 );
74 }
75
76 #[test]
77 fn a_bump_without_subscribers_leaves_no_entry() {
78 let live = PackagesLive::default();
79 live.bump("nobody");
80 assert!(live.owners().is_empty());
81 }
82}