1use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
2use std::time::Duration;
3
4use chrono::{DateTime, Utc};
5use futures_util::stream::SplitStream;
6use futures_util::{SinkExt, StreamExt};
7use serde::{Deserialize, Serialize};
8use serde_json::{Map, Value, json};
9use tokio::net::TcpStream;
10use tokio::sync::{mpsc, oneshot, watch};
11use tokio_tungstenite::tungstenite::Message;
12use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
13
14use crate::authentification::{CredentialsOrApiKey, Profile};
15use crate::billing::PageQuery;
16use crate::error::{Error, Result};
17use crate::http::{client, encode, ok, websocket};
18
19#[derive(Debug, Clone)]
20pub enum Authorization {
21 Server {
22 authorization: CredentialsOrApiKey,
23 server: String,
24 group: Option<String>,
25 },
26 AccessCode {
27 authorization: CredentialsOrApiKey,
28 access_code: String,
29 },
30}
31
32pub trait Hooks: Send + Sync {
36 fn create_room(&self, _room: &Room, _state: &Value) {}
37
38 fn create_presence(&self, _room: &Room, _presence: &Presence) {}
39 fn remove_presence(&self, _room: &Room, _presence: &Presence) {}
40
41 fn on_connection(&self, _room: &Room, _state: &Value) {}
44
45 fn on_event(&self, _room: &Room, _packet: &Value) -> bool {
46 false
47 }
48
49 fn on_binary(&self, _room: &Room, _data: &[u8]) {}
51
52 fn on_presence(&self, _room: &Room) {}
54
55 fn on_closed(&self, _room: &Room, _reason: Option<&str>) {}
57}
58
59impl Hooks for () {}
60
61#[derive(Debug, Clone, Default, Deserialize)]
63pub struct PresencePatch {
64 #[serde(default)]
65 pub position: Option<[f64; 3]>,
66 #[serde(default)]
67 pub status: Option<String>,
68}
69
70#[derive(Default)]
71struct PresenceState {
72 position: [f64; 3],
73 status: Option<String>,
74}
75
76struct PresenceInner {
77 room: Room,
78 id: String,
79 profile: Profile,
80 state: Mutex<PresenceState>,
81}
82
83#[derive(Clone)]
84pub struct Presence(Arc<PresenceInner>);
85
86impl Presence {
87 fn new(room: &Room, id: String, profile: Profile) -> Self {
88 Presence(Arc::new(PresenceInner {
89 room: room.clone(),
90 id,
91 profile,
92 state: Mutex::new(PresenceState::default()),
93 }))
94 }
95
96 fn state(&self) -> MutexGuard<'_, PresenceState> {
97 self.0.state.lock().unwrap_or_else(PoisonError::into_inner)
98 }
99
100 pub fn room(&self) -> &Room {
101 &self.0.room
102 }
103
104 pub fn id(&self) -> &str {
105 &self.0.id
106 }
107
108 pub fn profile(&self) -> &Profile {
109 &self.0.profile
110 }
111
112 pub fn position(&self) -> [f64; 3] {
113 self.state().position
114 }
115
116 pub fn status(&self) -> String {
117 self.state().status.clone().unwrap_or_default()
118 }
119
120 pub fn r#move(&self, position: [f64; 3]) {
121 self.state().position = position;
122
123 self.room().post(&json!({
124 "event": "update-client",
125 "client": self.to_json(),
126 }));
127 }
128
129 pub fn set_status(&self, status: &str) {
130 self.state().status = Some(status.to_string());
131
132 self.room().post(&json!({
133 "event": "update-client",
134 "client": self.to_json(),
135 }));
136 }
137
138 pub fn update(&self, patch: &PresencePatch) {
139 let mut state = self.state();
140 if let Some(position) = patch.position {
141 state.position = position;
142 }
143 if let Some(status) = &patch.status {
144 state.status = Some(status.clone());
145 }
146 }
147
148 pub fn to_json(&self) -> Value {
149 let (position, status) = {
150 let state = self.state();
151 (state.position, state.status.clone().unwrap_or_default())
152 };
153 json!({
154 "id": self.id(),
155 "profile": self.profile(),
156 "position": position,
157 "status": status,
158 })
159 }
160}
161
162struct RoomInner {
163 endpoint: String,
164 ws: mpsc::UnboundedSender<Message>,
165 authorization: Authorization,
166
167 id: String,
168
169 presences: Mutex<Vec<Presence>>,
170 closed: watch::Sender<bool>,
171}
172
173#[derive(Clone)]
174pub struct Room(Arc<RoomInner>);
175
176#[derive(Clone)]
178pub struct RoomSocket {
179 outbox: mpsc::UnboundedSender<Message>,
180 closed: watch::Receiver<bool>,
181}
182
183impl RoomSocket {
184 pub fn is_open(&self) -> bool {
186 !*self.closed.borrow() && !self.outbox.is_closed()
187 }
188}
189
190impl Room {
191 pub(crate) fn new(
192 endpoint: String,
193 ws: mpsc::UnboundedSender<Message>,
194 authorization: Authorization,
195 id: String,
196 ) -> Self {
197 Room(Arc::new(RoomInner {
198 endpoint,
199 ws,
200 authorization,
201 id,
202 presences: Mutex::new(Vec::new()),
203 closed: watch::channel(false).0,
204 }))
205 }
206
207 fn presences(&self) -> MutexGuard<'_, Vec<Presence>> {
208 self.0
209 .presences
210 .lock()
211 .unwrap_or_else(PoisonError::into_inner)
212 }
213
214 pub fn endpoint(&self) -> &str {
215 &self.0.endpoint
216 }
217
218 pub fn ws(&self) -> RoomSocket {
219 RoomSocket {
220 outbox: self.0.ws.clone(),
221 closed: self.0.closed.subscribe(),
222 }
223 }
224
225 pub fn authorization(&self) -> &Authorization {
226 &self.0.authorization
227 }
228
229 pub fn id(&self) -> &str {
230 &self.0.id
231 }
232
233 pub fn get_presences(&self) -> Vec<Presence> {
234 self.presences().clone()
235 }
236
237 pub(crate) fn clear_presences(&self) {
238 self.presences().clear();
239 }
240
241 pub(crate) fn socket_closed(&self) -> watch::Receiver<bool> {
243 self.0.closed.subscribe()
244 }
245
246 pub fn get_authorization(&self) -> &CredentialsOrApiKey {
248 match &self.0.authorization {
249 Authorization::Server { authorization, .. } => authorization,
250 Authorization::AccessCode { authorization, .. } => authorization,
251 }
252 }
253
254 pub fn post(&self, packet: &Value) {
256 let _ = self.0.ws.send(Message::text(packet.to_string()));
257 }
258
259 pub fn disconnect(&self) {
260 self.presences().clear();
261 let _ = self.0.ws.send(Message::Close(None));
262 }
263
264 pub async fn generate_access_code(&self) -> Result<String> {
265 let endpoint = self.endpoint().strip_suffix('/').unwrap_or(self.endpoint());
266 let request = client().post(format!("{endpoint}/access-code")).header(
267 "Authorization",
268 match self.get_authorization() {
269 CredentialsOrApiKey::Credentials(credentials) => {
270 format!("Token {}", credentials.token)
271 }
272 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
273 },
274 );
275 let request = match self.authorization() {
278 Authorization::Server { server, group, .. } => {
279 let request = request.header("Server", server);
280 match group {
281 Some(group) => request.header("Group", group),
282 None => request,
283 }
284 }
285 Authorization::AccessCode { .. } => request,
286 };
287 let response = request.send().await?;
288 Ok(ok(response).await?.text().await?)
289 }
290}
291
292type Reader = SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>;
293
294pub async fn connect(
295 authorization: Authorization,
296 endpoint: &str,
297 hooks: Arc<dyn Hooks>,
298) -> Result<Presence> {
299 let mut params = Map::new();
301 let header = match &authorization {
302 Authorization::Server { authorization, .. }
303 | Authorization::AccessCode { authorization, .. } => match authorization {
304 CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
305 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
306 },
307 };
308 params.insert("Authorization".to_string(), Value::String(header));
309 match &authorization {
310 Authorization::Server { server, group, .. } => {
311 params.insert("Server".to_string(), Value::String(server.clone()));
312 if let Some(group) = group {
313 params.insert("Group".to_string(), Value::String(group.clone()));
314 }
315 }
316 Authorization::AccessCode { access_code, .. } => {
317 params.insert("AccessCode".to_string(), Value::String(access_code.clone()));
318 }
319 }
320 let auth_param = crate::http::encode(&Value::Object(params).to_string());
321
322 let ws_url = websocket(endpoint);
323 let ws_url = ws_url.strip_suffix('/').unwrap_or(&ws_url).to_string();
324
325 let timer = Duration::from_secs(15);
327 let connected = tokio::time::timeout(
328 timer,
329 tokio_tungstenite::connect_async(format!("{ws_url}?authorization={auth_param}")),
330 )
331 .await;
332 let stream = match connected {
333 Ok(Ok((stream, _))) => stream,
334 Ok(Err(_)) => {
335 return Err(Error::Message(format!(
336 "WebSocket connection failed ({ws_url})"
337 )));
338 }
339 Err(_) => {
340 return Err(Error::Message(format!(
341 "Timed out waiting for the room ({ws_url})."
342 )));
343 }
344 };
345
346 let (mut write, read) = stream.split();
347 let (ws, mut outbox) = mpsc::unbounded_channel::<Message>();
348 tokio::spawn(async move {
349 while let Some(message) = outbox.recv().await {
350 let closing = matches!(message, Message::Close(_));
351 if write.send(message).await.is_err() || closing {
352 break;
353 }
354 }
355 let _ = write.close().await;
356 });
357
358 let (ready, settled) = oneshot::channel();
359 tokio::spawn(listen(
360 read,
361 ws.clone(),
362 authorization,
363 endpoint.to_string(),
364 ws_url.clone(),
365 hooks,
366 ready,
367 ));
368
369 match tokio::time::timeout(timer, settled).await {
370 Ok(Ok(result)) => result,
371 Ok(Err(_)) => Err(Error::Message(format!(
372 "WebSocket closed before the room connected ({ws_url})"
373 ))),
374 Err(_) => {
375 let _ = ws.send(Message::Close(None));
376 Err(Error::Message(format!(
377 "Timed out waiting for the room ({ws_url})."
378 )))
379 }
380 }
381}
382
383fn fail(
384 ready: &mut Option<oneshot::Sender<Result<Presence>>>,
385 ws: &mpsc::UnboundedSender<Message>,
386 message: String,
387) {
388 if let Some(ready) = ready.take() {
389 let _ = ws.send(Message::Close(None));
390 let _ = ready.send(Err(Error::Message(message)));
391 }
392}
393
394fn text(value: &Value) -> String {
395 match value {
396 Value::String(value) => value.clone(),
397 Value::Null => String::new(),
398 value => value.to_string(),
399 }
400}
401
402fn profile(client: &Value) -> Profile {
403 serde_json::from_value(client["profile"].clone()).unwrap_or_default()
404}
405
406fn patch(client: &Value) -> PresencePatch {
407 serde_json::from_value(client.clone()).unwrap_or_default()
408}
409
410async fn listen(
411 mut read: Reader,
412 ws: mpsc::UnboundedSender<Message>,
413 authorization: Authorization,
414 endpoint: String,
415 ws_url: String,
416 hooks: Arc<dyn Hooks>,
417 ready: oneshot::Sender<Result<Presence>>,
418) {
419 let mut ready = Some(ready);
420 let mut room: Option<Room> = None;
421 let mut self_id: Option<String> = None;
422
423 while let Some(message) = read.next().await {
424 let raw = match message {
425 Ok(Message::Text(text)) => text.to_string(),
426 Ok(Message::Binary(bytes)) => {
427 if let Some(room) = &room {
428 hooks.on_binary(room, &bytes);
429 }
430 continue;
431 }
432 Ok(Message::Close(_)) => break,
433 Ok(_) => continue,
434 Err(_) => {
435 fail(
436 &mut ready,
437 &ws,
438 format!("WebSocket connection failed ({ws_url})"),
439 );
440 break;
441 }
442 };
443 let Ok(json) = serde_json::from_str::<Value>(&raw) else {
444 fail(&mut ready, &ws, "Room connection failed".to_string());
445 continue;
446 };
447
448 if json["event"] == "error" {
449 let message = json["message"]
450 .as_str()
451 .filter(|message| !message.is_empty());
452 fail(
453 &mut ready,
454 &ws,
455 message.unwrap_or("Room connection failed").to_string(),
456 );
457 continue;
458 }
459
460 match json["event"].as_str().unwrap_or_default() {
461 "connection" => {
462 let client = &json["data"]["client"];
463 let client_id = text(&client["id"]);
464 if client_id.is_empty() {
465 fail(&mut ready, &ws, "Room connection missing self.".to_string());
466 continue;
467 }
468 self_id = Some(client_id.clone());
469 let id = text(&json["data"]["server"]["id"]);
470 let state = json["data"]["state"].clone();
471 let joined = Room::new(endpoint.clone(), ws.clone(), authorization.clone(), id);
472 hooks.create_room(&joined, &state);
473 let me = Presence::new(&joined, client_id.clone(), profile(client));
474 hooks.create_presence(&joined, &me);
475 me.update(&patch(client));
476
477 for presence in json["data"]["clients"].as_array().into_iter().flatten() {
478 if text(&presence["id"]) == client_id {
479 continue;
480 }
481 let other = Presence::new(&joined, text(&presence["id"]), profile(presence));
482 hooks.create_presence(&joined, &other);
483 other.update(&patch(presence));
484 joined.presences().push(other);
485 }
486
487 hooks.on_connection(&joined, &state);
488
489 room = Some(joined);
490 if let Some(ready) = ready.take() {
491 let _ = ready.send(Ok(me));
492 }
493 }
494 "add-client" => {
495 let Some(room) = &room else {
496 fail(&mut ready, &ws, "Room not found".to_string());
497 continue;
498 };
499 let client = &json["data"]["client"];
500 if Some(text(&client["id"])) == self_id {
501 continue;
502 }
503
504 let presence = Presence::new(room, text(&client["id"]), profile(client));
505 hooks.create_presence(room, &presence);
506 presence.update(&patch(client));
507 room.presences().push(presence);
508 hooks.on_presence(room);
509 }
510 "update-client" => {
511 let Some(room) = &room else {
512 fail(&mut ready, &ws, "Room not found".to_string());
513 continue;
514 };
515 let client = &json["data"]["client"];
516 let id = text(&client["id"]);
517 if Some(id.clone()) == self_id {
518 continue;
519 }
520
521 let presence = room
522 .presences()
523 .iter()
524 .find(|presence| presence.id() == id)
525 .cloned();
526 let Some(presence) = presence else {
527 fail(&mut ready, &ws, "Presence not found".to_string());
528 continue;
529 };
530
531 presence.update(&patch(client));
532 hooks.on_presence(room);
533 }
534 "remove-client" => {
535 let Some(room) = &room else {
536 fail(&mut ready, &ws, "Room not found".to_string());
537 continue;
538 };
539
540 let id = text(&json["data"]["client"]["id"]);
541 let presence = room
542 .presences()
543 .iter()
544 .find(|presence| presence.id() == id)
545 .cloned();
546
547 if let Some(presence) = &presence {
548 hooks.remove_presence(room, presence);
549 room.presences().retain(|other| other.id() != id);
550 }
551 hooks.on_presence(room);
552 }
553 "server-closed" => {
554 let Some(room) = &room else {
555 fail(&mut ready, &ws, "Room closed before connect".to_string());
556 continue;
557 };
558 let reason = json["data"]["reason"].as_str();
559 room.presences().clear();
560 hooks.on_closed(room, reason);
561 let _ = ws.send(Message::Close(None));
562 }
563 _ => {
564 if let Some(room) = &room {
565 hooks.on_event(room, &json);
566 }
567 }
568 }
569 }
570
571 if let Some(room) = &room {
572 room.0.closed.send_replace(true);
573 }
574 fail(
575 &mut ready,
576 &ws,
577 format!("WebSocket closed before the room connected ({ws_url})"),
578 );
579}
580
581#[derive(Debug, Clone, Serialize)]
583#[serde(rename_all = "camelCase")]
584pub struct AccessCode {
585 pub code: String,
586 pub reference: String,
588 pub write: bool,
590 pub expires: DateTime<Utc>,
591}
592
593impl AccessCode {
594 pub fn from_json(json: &Value) -> AccessCode {
595 AccessCode {
596 code: json["code"].as_str().unwrap_or_default().to_string(),
597 reference: json["reference"].as_str().unwrap_or_default().to_string(),
598 write: json["write"].as_bool().unwrap_or(false),
599 expires: crate::tickets::parse_date(&json["expires"]).unwrap_or_default(),
600 }
601 }
602}
603
604pub async fn list_access_codes(
607 authorization: &CredentialsOrApiKey,
608 query: PageQuery,
609) -> Result<Vec<AccessCode>> {
610 let response = client()
611 .get(format!(
612 "{}/access-codes?cursor={}&max={}",
613 crate::get_url(),
614 query.cursor,
615 query.max
616 ))
617 .header(
618 "Authorization",
619 match authorization {
620 CredentialsOrApiKey::Credentials(credentials) => {
621 format!("Token {}", credentials.token)
622 }
623 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
624 },
625 )
626 .send()
627 .await?;
628 let rows: Vec<Value> = ok(response).await?.json().await?;
629 Ok(rows.iter().map(AccessCode::from_json).collect())
630}
631
632pub async fn revoke_access_code(authorization: &CredentialsOrApiKey, code: &str) -> Result<()> {
635 let response = client()
636 .delete(format!(
637 "{}/access-codes/{}",
638 crate::get_url(),
639 encode(code)
640 ))
641 .header(
642 "Authorization",
643 match authorization {
644 CredentialsOrApiKey::Credentials(credentials) => {
645 format!("Token {}", credentials.token)
646 }
647 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
648 },
649 )
650 .send()
651 .await?;
652 ok(response).await?;
653 Ok(())
654}
655
656#[cfg(test)]
657mod tests {
658 use super::*;
659 use crate::authentification::ApiKey;
660
661 fn joined() -> (Room, mpsc::UnboundedReceiver<Message>) {
662 let (ws, outbox) = mpsc::unbounded_channel();
663 let authorization = Authorization::Server {
664 authorization: CredentialsOrApiKey::ApiKey(ApiKey::default()),
665 server: "fauna:ticket:1".to_string(),
666 group: None,
667 };
668 let endpoint = "http://localhost/tickets".to_string();
669 (
670 Room::new(endpoint, ws, authorization, "1".to_string()),
671 outbox,
672 )
673 }
674
675 #[test]
676 fn the_socket_is_open_until_either_side_closes_it() {
677 let (room, outbox) = joined();
678 let socket = room.ws();
679 assert!(socket.is_open());
680 drop(outbox);
681 assert!(!socket.is_open());
682
683 let (room, _outbox) = joined();
684 let socket = room.ws();
685 room.0.closed.send_replace(true);
686 assert!(!socket.is_open());
687 assert!(!room.ws().is_open());
688 }
689}