forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

hub.rs228 lines, 6.1 KiBHistoryRawDownload
1use std::{
2 collections::{HashMap, HashSet},
3 sync::{
4 Arc, Mutex,
5 atomic::{AtomicBool, AtomicU64, Ordering},
6 },
7};
8
9use bytes::Bytes;
10use common::{
11 model::Id,
12 transport::Close,
13 update::{Install, Sha},
14};
15use quinn::Connection;
16use tokio::sync::mpsc::{self, error::TrySendError};
17use tracing::warn;
18
19pub type ConnId = u64;
20
21const QUEUE_LENGTH: usize = 256;
22
23static NEXT_ID: AtomicU64 = AtomicU64::new(1);
24
25pub struct Signed {
26 pub user_id: Id,
27 pub session_id: Id,
28}
29
30pub struct Client {
31 pub id: ConnId,
32 pub conn: Option<Connection>,
33 pub me: Option<Signed>,
34 pub build: Option<Sha>,
35 pub install: Install,
36 tx: mpsc::Sender<Bytes>,
37 pub closed: AtomicBool,
38 watching: Mutex<Option<Id>>,
39 ghost_logged: Mutex<HashSet<Id>>,
40}
41
42impl Client {
43 pub fn new(
44 conn: Option<Connection>,
45 me: Option<Signed>,
46 build: Option<Sha>,
47 install: Install,
48 ) -> (Arc<Self>, mpsc::Receiver<Bytes>) {
49 let (tx, rx) = mpsc::channel(QUEUE_LENGTH);
50 let client = Arc::new(Self {
51 id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
52 conn,
53 me,
54 build,
55 install,
56 tx,
57 closed: AtomicBool::new(false),
58 watching: Mutex::new(None),
59 ghost_logged: Mutex::new(HashSet::new()),
60 });
61
62 (client, rx)
63 }
64
65 pub fn detached(me: Option<Signed>) -> Arc<Self> {
66 Self::new(None, me, None, Install::default()).0
67 }
68
69 pub fn user_id(&self) -> Option<Id> {
70 self.me.as_ref().map(|me| me.user_id)
71 }
72
73 pub fn close(&self, close: Close) {
74 if let Some(conn) = &self.conn {
75 conn.close(close.code(), close.reason().as_bytes());
76 }
77 }
78
79 pub fn first_visit(&self, community_id: Id) -> bool {
80 self.ghost_logged.lock().unwrap().insert(community_id)
81 }
82
83 pub fn watch(&self, community_id: Option<Id>) {
84 *self.watching.lock().unwrap() = community_id;
85 }
86}
87
88pub enum Presence {
89 None,
90 Online(Id),
91 Offline(Id),
92}
93
94#[derive(Clone, Default)]
95pub struct Hub(Arc<Mutex<HashMap<ConnId, Arc<Client>>>>);
96
97impl Hub {
98 pub fn add(&self, client: Arc<Client>) -> Presence {
99 let mut clients = self.0.lock().unwrap();
100 let user_id = client.user_id();
101 let was_online = user_id.is_some_and(|user_id| Self::online_in(&clients, user_id));
102 clients.insert(client.id, client);
103
104 match user_id {
105 Some(user_id) if !was_online => Presence::Online(user_id),
106 _ => Presence::None,
107 }
108 }
109
110 pub fn remove(&self, id: ConnId) -> Presence {
111 let mut clients = self.0.lock().unwrap();
112 let Some(client) = clients.remove(&id) else {
113 return Presence::None;
114 };
115
116 match client.user_id() {
117 Some(user_id) if !Self::online_in(&clients, user_id) => Presence::Offline(user_id),
118 _ => Presence::None,
119 }
120 }
121
122 fn online_in(clients: &HashMap<ConnId, Arc<Client>>, user_id: Id) -> bool {
123 clients
124 .values()
125 .any(|client| client.user_id() == Some(user_id))
126 }
127
128 pub fn is_online(&self, user_id: Id) -> bool {
129 Self::online_in(&self.0.lock().unwrap(), user_id)
130 }
131
132 pub fn online(&self) -> usize {
133 let clients = self.0.lock().unwrap();
134 let ids: HashSet<Id> = clients
135 .values()
136 .filter_map(|client| client.user_id())
137 .collect();
138
139 ids.len()
140 }
141
142 pub fn conns_of(&self, user_ids: &[Id]) -> Vec<ConnId> {
143 self.0
144 .lock()
145 .unwrap()
146 .values()
147 .filter(|client| client.user_id().is_some_and(|id| user_ids.contains(&id)))
148 .map(|client| client.id)
149 .collect()
150 }
151
152 pub fn watchers(&self, community_id: Id) -> Vec<ConnId> {
153 self.0
154 .lock()
155 .unwrap()
156 .values()
157 .filter(|client| *client.watching.lock().unwrap() == Some(community_id))
158 .map(|client| client.id)
159 .collect()
160 }
161
162 pub fn bytes(&self) -> (u64, u64) {
163 let clients = self.0.lock().unwrap();
164 let mut total = (0, 0);
165 for conn in clients.values().filter_map(|client| client.conn.as_ref()) {
166 let stats = conn.stats();
167 total.0 += stats.udp_tx.bytes;
168 total.1 += stats.udp_rx.bytes;
169 }
170 total
171 }
172
173 pub fn installs(&self) -> Vec<Install> {
174 self.0
175 .lock()
176 .unwrap()
177 .values()
178 .map(|client| client.install)
179 .collect()
180 }
181
182 pub fn all(&self) -> Vec<ConnId> {
183 self.0.lock().unwrap().keys().copied().collect()
184 }
185
186 pub fn send(&self, ids: &[ConnId], bytes: &Bytes, droppable: bool) {
187 let clients = self.0.lock().unwrap();
188 for id in ids {
189 let Some(client) = clients.get(id) else {
190 continue;
191 };
192 match client.tx.try_send(bytes.clone()) {
193 Ok(()) | Err(TrySendError::Closed(_)) => {}
194 Err(TrySendError::Full(_)) if droppable => {}
195 Err(TrySendError::Full(_)) => {
196 warn!("client {} too slow", client.id);
197 client.close(Close::Slow);
198 }
199 }
200 }
201 }
202
203 fn kick_where(&self, matches: impl Fn(&Signed) -> bool, close: Close) {
204 let targets: Vec<Arc<Client>> = self
205 .0
206 .lock()
207 .unwrap()
208 .values()
209 .filter(|client| client.me.as_ref().is_some_and(&matches))
210 .cloned()
211 .collect();
212 for client in targets {
213 client.close(close);
214 }
215 }
216
217 pub fn kick_user(&self, user_id: Id, close: Close) {
218 self.kick_where(|me| me.user_id == user_id, close);
219 }
220
221 pub fn kick_session(&self, session_id: Id, close: Close) {
222 self.kick_where(|me| me.session_id == session_id, close);
223 }
224
225 pub fn kick_all_except(&self, keep: &[Id], close: Close) {
226 self.kick_where(|me| !keep.contains(&me.user_id), close);
227 }
228}