1use std::sync::atomic::{AtomicBool, Ordering};
2use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
3use std::time::Duration;
4
5use chrono::{DateTime, Utc};
6use futures_util::stream::SplitStream;
7use futures_util::{SinkExt, StreamExt};
8use serde::{Deserialize, Serialize};
9use serde_json::{Map, Value, json};
10use tokio::net::TcpStream;
11use tokio::sync::{mpsc, oneshot, watch};
12use tokio_tungstenite::tungstenite::Message;
13use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
14
15use crate::authentification::{CredentialsOrApiKey, Profile};
16use crate::billing::PageQuery;
17use crate::error::{Error, Result};
18use crate::http::{client, encode, ok, websocket};
19
20#[derive(Debug, Clone)]
21pub enum Authorization {
22 Server {
23 authorization: CredentialsOrApiKey,
24 server: String,
25 group: Option<String>,
26 },
27 AccessCode {
28 authorization: CredentialsOrApiKey,
29 access_code: String,
30 },
31}
32
33pub trait Hooks: Send + Sync {
37 fn create_room(&self, _room: &Room, _state: &Value) {}
38
39 fn create_presence(&self, _room: &Room, _presence: &Presence) {}
40 fn remove_presence(&self, _room: &Room, _presence: &Presence) {}
41
42 fn on_connection(&self, _room: &Room, _state: &Value) {}
45
46 fn on_event(&self, _room: &Room, _packet: &Value) -> bool {
47 false
48 }
49
50 fn on_binary(&self, _room: &Room, _data: &[u8]) {}
52
53 fn on_presence(&self, _room: &Room) {}
55
56 fn on_closed(&self, _room: &Room, _reason: Option<&str>) {}
59}
60
61const RECONNECT_FIRST: Duration = Duration::from_millis(500);
63const RECONNECT_MAX: Duration = Duration::from_secs(10);
64const CONNECT_WAIT: Duration = Duration::from_secs(15);
66
67impl Hooks for () {}
68
69#[derive(Debug, Clone, Default, Deserialize)]
71pub struct PresencePatch {
72 #[serde(default)]
73 pub position: Option<[f64; 3]>,
74 #[serde(default)]
75 pub status: Option<String>,
76}
77
78#[derive(Default)]
79struct PresenceState {
80 position: [f64; 3],
81 status: Option<String>,
82}
83
84struct PresenceInner {
85 room: Room,
86 id: Mutex<String>,
88 profile: Profile,
89 state: Mutex<PresenceState>,
90}
91
92#[derive(Clone)]
93pub struct Presence(Arc<PresenceInner>);
94
95impl Presence {
96 fn new(room: &Room, id: String, profile: Profile) -> Self {
97 Presence(Arc::new(PresenceInner {
98 room: room.clone(),
99 id: Mutex::new(id),
100 profile,
101 state: Mutex::new(PresenceState::default()),
102 }))
103 }
104
105 fn state(&self) -> MutexGuard<'_, PresenceState> {
106 self.0.state.lock().unwrap_or_else(PoisonError::into_inner)
107 }
108
109 pub fn room(&self) -> &Room {
110 &self.0.room
111 }
112
113 pub fn id(&self) -> String {
114 self.0
115 .id
116 .lock()
117 .unwrap_or_else(PoisonError::into_inner)
118 .clone()
119 }
120
121 fn reseat(&self, id: String) {
122 *self.0.id.lock().unwrap_or_else(PoisonError::into_inner) = id;
123 }
124
125 pub fn profile(&self) -> &Profile {
126 &self.0.profile
127 }
128
129 pub fn position(&self) -> [f64; 3] {
130 self.state().position
131 }
132
133 pub fn status(&self) -> String {
134 self.state().status.clone().unwrap_or_default()
135 }
136
137 pub fn r#move(&self, position: [f64; 3]) {
138 self.state().position = position;
139
140 self.room().post(&json!({
141 "event": "update-client",
142 "client": self.to_json(),
143 }));
144 }
145
146 pub fn set_status(&self, status: &str) {
147 self.state().status = Some(status.to_string());
148
149 self.room().post(&json!({
150 "event": "update-client",
151 "client": self.to_json(),
152 }));
153 }
154
155 pub fn update(&self, patch: &PresencePatch) {
156 let mut state = self.state();
157 if let Some(position) = patch.position {
158 state.position = position;
159 }
160 if let Some(status) = &patch.status {
161 state.status = Some(status.clone());
162 }
163 }
164
165 pub fn to_json(&self) -> Value {
166 let (position, status) = {
167 let state = self.state();
168 (state.position, state.status.clone().unwrap_or_default())
169 };
170 json!({
171 "id": self.id(),
172 "profile": self.profile(),
173 "position": position,
174 "status": status,
175 })
176 }
177}
178
179struct RoomInner {
180 endpoint: String,
181 ws: mpsc::UnboundedSender<Message>,
184 authorization: Authorization,
185
186 id: String,
187
188 presences: Mutex<Vec<Presence>>,
189 closed: watch::Sender<bool>,
191 ended: AtomicBool,
193}
194
195#[derive(Clone)]
196pub struct Room(Arc<RoomInner>);
197
198#[derive(Clone)]
200pub struct RoomSocket {
201 outbox: mpsc::UnboundedSender<Message>,
202 closed: watch::Receiver<bool>,
203}
204
205impl RoomSocket {
206 pub fn is_open(&self) -> bool {
208 !*self.closed.borrow() && !self.outbox.is_closed()
209 }
210}
211
212impl Room {
213 pub(crate) fn new(
214 endpoint: String,
215 ws: mpsc::UnboundedSender<Message>,
216 authorization: Authorization,
217 id: String,
218 ) -> Self {
219 Room(Arc::new(RoomInner {
220 endpoint,
221 ws,
222 authorization,
223 id,
224 presences: Mutex::new(Vec::new()),
225 closed: watch::channel(false).0,
226 ended: AtomicBool::new(false),
227 }))
228 }
229
230 fn presences(&self) -> MutexGuard<'_, Vec<Presence>> {
231 self.0
232 .presences
233 .lock()
234 .unwrap_or_else(PoisonError::into_inner)
235 }
236
237 pub fn endpoint(&self) -> &str {
238 &self.0.endpoint
239 }
240
241 pub fn ws(&self) -> RoomSocket {
242 RoomSocket {
243 outbox: self.0.ws.clone(),
244 closed: self.0.closed.subscribe(),
245 }
246 }
247
248 pub fn authorization(&self) -> &Authorization {
249 &self.0.authorization
250 }
251
252 pub fn id(&self) -> &str {
253 &self.0.id
254 }
255
256 pub fn get_presences(&self) -> Vec<Presence> {
257 self.presences().clone()
258 }
259
260 pub(crate) fn clear_presences(&self) {
261 self.presences().clear();
262 }
263
264 pub(crate) fn socket_closed(&self) -> watch::Receiver<bool> {
266 self.0.closed.subscribe()
267 }
268
269 fn end(&self) {
270 self.0.ended.store(true, Ordering::SeqCst);
271 }
272
273 fn ended(&self) -> bool {
274 self.0.ended.load(Ordering::SeqCst)
275 }
276
277 pub fn get_authorization(&self) -> &CredentialsOrApiKey {
279 match &self.0.authorization {
280 Authorization::Server { authorization, .. } => authorization,
281 Authorization::AccessCode { authorization, .. } => authorization,
282 }
283 }
284
285 pub fn post(&self, packet: &Value) {
287 let _ = self.0.ws.send(Message::text(packet.to_string()));
288 }
289
290 pub fn disconnect(&self) {
291 self.presences().clear();
292 self.end();
293 let _ = self.0.ws.send(Message::Close(None));
294 }
295
296 pub async fn generate_access_code(&self) -> Result<String> {
297 let endpoint = self.endpoint().strip_suffix('/').unwrap_or(self.endpoint());
298 let request = client().post(format!("{endpoint}/access-code")).header(
299 "Authorization",
300 match self.get_authorization() {
301 CredentialsOrApiKey::Credentials(credentials) => {
302 format!("Token {}", credentials.token)
303 }
304 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
305 },
306 );
307 let request = match self.authorization() {
310 Authorization::Server { server, group, .. } => {
311 let request = request.header("Server", server);
312 match group {
313 Some(group) => request.header("Group", group),
314 None => request,
315 }
316 }
317 Authorization::AccessCode { .. } => request,
318 };
319 let response = request.send().await?;
320 Ok(ok(response).await?.text().await?)
321 }
322}
323
324type Reader = SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>;
325
326pub async fn connect(
327 authorization: Authorization,
328 endpoint: &str,
329 hooks: Arc<dyn Hooks>,
330) -> Result<Presence> {
331 let mut params = Map::new();
333 let header = match &authorization {
334 Authorization::Server { authorization, .. }
335 | Authorization::AccessCode { authorization, .. } => match authorization {
336 CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
337 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
338 },
339 };
340 params.insert("Authorization".to_string(), Value::String(header));
341 match &authorization {
342 Authorization::Server { server, group, .. } => {
343 params.insert("Server".to_string(), Value::String(server.clone()));
344 if let Some(group) = group {
345 params.insert("Group".to_string(), Value::String(group.clone()));
346 }
347 }
348 Authorization::AccessCode { access_code, .. } => {
349 params.insert("AccessCode".to_string(), Value::String(access_code.clone()));
350 }
351 }
352 let auth_param = crate::http::encode(&Value::Object(params).to_string());
353
354 let ws_url = websocket(endpoint);
355 let ws_url = ws_url.strip_suffix('/').unwrap_or(&ws_url).to_string();
356 let url = format!("{ws_url}?authorization={auth_param}");
357
358 let (read, writer) = open_socket(&url, &ws_url).await?;
360 let current: Current = Arc::new(Mutex::new(Some(writer.clone())));
361 let (ws, mut outbox) = mpsc::unbounded_channel::<Message>();
362 {
363 let current = current.clone();
364 tokio::spawn(async move {
365 while let Some(message) = outbox.recv().await {
366 let closing = matches!(message, Message::Close(_));
367 if let Some(writer) = lock(¤t).as_ref() {
368 let _ = writer.send(message);
369 }
370 if closing {
371 break;
372 }
373 }
374 });
375 }
376
377 let (ready, settled) = oneshot::channel();
378 let live = Live {
379 hooks,
380 authorization,
381 endpoint: endpoint.to_string(),
382 ws: ws.clone(),
383 url,
384 ws_url: ws_url.clone(),
385 room: None,
386 me: None,
387 };
388 tokio::spawn(live.run(read, writer, current, ready));
389
390 match tokio::time::timeout(CONNECT_WAIT, settled).await {
391 Ok(Ok(result)) => result,
392 Ok(Err(_)) => Err(Error::Message(format!(
393 "WebSocket closed before the room connected ({ws_url})"
394 ))),
395 Err(_) => {
396 let _ = ws.send(Message::Close(None));
397 Err(Error::Message(format!(
398 "Timed out waiting for the room ({ws_url})."
399 )))
400 }
401 }
402}
403
404type Current = Arc<Mutex<Option<mpsc::UnboundedSender<Message>>>>;
406
407fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
408 mutex.lock().unwrap_or_else(PoisonError::into_inner)
409}
410
411async fn open_socket(url: &str, ws_url: &str) -> Result<(Reader, mpsc::UnboundedSender<Message>)> {
413 let connected = tokio::time::timeout(CONNECT_WAIT, tokio_tungstenite::connect_async(url)).await;
414 let stream = match connected {
415 Ok(Ok((stream, _))) => stream,
416 Ok(Err(_)) => {
417 return Err(Error::Message(format!(
418 "WebSocket connection failed ({ws_url})"
419 )));
420 }
421 Err(_) => {
422 return Err(Error::Message(format!(
423 "Timed out waiting for the room ({ws_url})."
424 )));
425 }
426 };
427 let (mut write, read) = stream.split();
428 let (writer, mut outbox) = mpsc::unbounded_channel::<Message>();
429 tokio::spawn(async move {
430 while let Some(message) = outbox.recv().await {
431 let closing = matches!(message, Message::Close(_));
432 if write.send(message).await.is_err() || closing {
433 break;
434 }
435 }
436 let _ = write.close().await;
437 });
438 Ok((read, writer))
439}
440
441fn fail(
442 ready: &mut Option<oneshot::Sender<Result<Presence>>>,
443 writer: &mpsc::UnboundedSender<Message>,
444 message: String,
445) {
446 if let Some(ready) = ready.take() {
447 let _ = writer.send(Message::Close(None));
448 let _ = ready.send(Err(Error::Message(message)));
449 }
450}
451
452enum Session {
454 Dropped { seated: bool },
456 Refused(String),
458}
459
460fn text(value: &Value) -> String {
461 match value {
462 Value::String(value) => value.clone(),
463 Value::Null => String::new(),
464 value => value.to_string(),
465 }
466}
467
468fn profile(client: &Value) -> Profile {
469 serde_json::from_value(client["profile"].clone()).unwrap_or_default()
470}
471
472fn patch(client: &Value) -> PresencePatch {
473 serde_json::from_value(client.clone()).unwrap_or_default()
474}
475
476struct Live {
478 hooks: Arc<dyn Hooks>,
479 authorization: Authorization,
480 endpoint: String,
481 ws: mpsc::UnboundedSender<Message>,
482 url: String,
483 ws_url: String,
484 room: Option<Room>,
485 me: Option<Presence>,
486}
487
488impl Live {
489 async fn run(
490 mut self,
491 mut read: Reader,
492 mut writer: mpsc::UnboundedSender<Message>,
493 current: Current,
494 ready: oneshot::Sender<Result<Presence>>,
495 ) {
496 let mut ready = Some(ready);
497 let mut delay = RECONNECT_FIRST;
498 loop {
499 let session = self.session(read, &writer, &mut ready).await;
500 *lock(¤t) = None;
501 let Some(room) = self.room.clone() else {
502 fail(
503 &mut ready,
504 &writer,
505 format!(
506 "WebSocket closed before the room connected ({})",
507 self.ws_url
508 ),
509 );
510 return;
511 };
512 match session {
513 Session::Refused(reason) => {
514 room.end();
515 room.presences().clear();
516 self.hooks.on_closed(&room, Some(&reason));
517 }
518 Session::Dropped { seated } => {
519 if seated {
520 delay = RECONNECT_FIRST;
521 }
522 }
523 }
524 if room.ended() {
525 break;
526 }
527 let opened = loop {
528 tokio::time::sleep(delay).await;
529 if room.ended() {
530 break None;
531 }
532 match open_socket(&self.url, &self.ws_url).await {
533 Ok(opened) => break Some(opened),
534 Err(_) => delay = (delay * 2).min(RECONNECT_MAX),
535 }
536 };
537 let Some((next, next_writer)) = opened else {
538 break;
539 };
540 read = next;
541 writer = next_writer;
542 *lock(¤t) = Some(writer.clone());
543 }
544 if let Some(room) = &self.room {
545 room.0.closed.send_replace(true);
546 }
547 }
548
549 async fn session(
551 &mut self,
552 mut read: Reader,
553 writer: &mpsc::UnboundedSender<Message>,
554 ready: &mut Option<oneshot::Sender<Result<Presence>>>,
555 ) -> Session {
556 let hooks = self.hooks.clone();
557 let ws_url = self.ws_url.clone();
558 let mut self_id: Option<String> = None;
559
560 while let Some(message) = read.next().await {
561 let raw = match message {
562 Ok(Message::Text(text)) => text.to_string(),
563 Ok(Message::Binary(bytes)) => {
564 if let Some(room) = &self.room {
565 hooks.on_binary(room, &bytes);
566 }
567 continue;
568 }
569 Ok(Message::Close(_)) => break,
570 Ok(_) => continue,
571 Err(_) => {
572 fail(
573 ready,
574 writer,
575 format!("WebSocket connection failed ({ws_url})"),
576 );
577 break;
578 }
579 };
580 let Ok(json) = serde_json::from_str::<Value>(&raw) else {
581 fail(ready, writer, "Room connection failed".to_string());
582 continue;
583 };
584
585 if json["event"] == "error" {
586 let message = json["message"]
587 .as_str()
588 .filter(|message| !message.is_empty())
589 .unwrap_or("Room connection failed")
590 .to_string();
591 if self.room.is_some() && self_id.is_none() {
592 let _ = writer.send(Message::Close(None));
593 return Session::Refused(message);
594 }
595 fail(ready, writer, message);
596 continue;
597 }
598
599 match json["event"].as_str().unwrap_or_default() {
600 "connection" => {
601 let client = &json["data"]["client"];
602 let client_id = text(&client["id"]);
603 if client_id.is_empty() {
604 fail(ready, writer, "Room connection missing self.".to_string());
605 continue;
606 }
607 self_id = Some(client_id.clone());
608 let state = json["data"]["state"].clone();
609 let (room, me, reconnected) = match (&self.room, &self.me) {
610 (Some(room), Some(me)) => {
611 me.reseat(client_id.clone());
612 room.presences().clear();
613 (room.clone(), me.clone(), true)
614 }
615 _ => {
616 let id = text(&json["data"]["server"]["id"]);
617 let joined = Room::new(
618 self.endpoint.clone(),
619 self.ws.clone(),
620 self.authorization.clone(),
621 id,
622 );
623 hooks.create_room(&joined, &state);
624 let me = Presence::new(&joined, client_id.clone(), profile(client));
625 hooks.create_presence(&joined, &me);
626 (joined, me, false)
627 }
628 };
629 me.update(&patch(client));
630
631 for presence in json["data"]["clients"].as_array().into_iter().flatten() {
632 if text(&presence["id"]) == client_id {
633 continue;
634 }
635 let other = Presence::new(&room, text(&presence["id"]), profile(presence));
636 hooks.create_presence(&room, &other);
637 other.update(&patch(presence));
638 room.presences().push(other);
639 }
640
641 hooks.on_connection(&room, &state);
642 if reconnected {
643 hooks.on_presence(&room);
644 }
645
646 self.room = Some(room);
647 self.me = Some(me.clone());
648 if let Some(ready) = ready.take() {
649 let _ = ready.send(Ok(me));
650 }
651 }
652 "add-client" => {
653 let Some(room) = &self.room else {
654 fail(ready, writer, "Room not found".to_string());
655 continue;
656 };
657 let client = &json["data"]["client"];
658 if Some(text(&client["id"])) == self_id {
659 continue;
660 }
661
662 let presence = Presence::new(room, text(&client["id"]), profile(client));
663 hooks.create_presence(room, &presence);
664 presence.update(&patch(client));
665 room.presences().push(presence);
666 hooks.on_presence(room);
667 }
668 "update-client" => {
669 let Some(room) = &self.room else {
670 fail(ready, writer, "Room not found".to_string());
671 continue;
672 };
673 let client = &json["data"]["client"];
674 let id = text(&client["id"]);
675 if Some(id.clone()) == self_id {
676 continue;
677 }
678
679 let presence = room
680 .presences()
681 .iter()
682 .find(|presence| presence.id() == id)
683 .cloned();
684 let Some(presence) = presence else {
685 fail(ready, writer, "Presence not found".to_string());
686 continue;
687 };
688
689 presence.update(&patch(client));
690 hooks.on_presence(room);
691 }
692 "remove-client" => {
693 let Some(room) = &self.room else {
694 fail(ready, writer, "Room not found".to_string());
695 continue;
696 };
697
698 let id = text(&json["data"]["client"]["id"]);
699 let presence = room
700 .presences()
701 .iter()
702 .find(|presence| presence.id() == id)
703 .cloned();
704
705 if let Some(presence) = &presence {
706 hooks.remove_presence(room, presence);
707 room.presences().retain(|other| other.id() != id);
708 }
709 hooks.on_presence(room);
710 }
711 "server-closed" => {
712 let Some(room) = &self.room else {
713 fail(ready, writer, "Room closed before connect".to_string());
714 continue;
715 };
716 let reason = json["data"]["reason"].as_str();
717 room.end();
718 room.presences().clear();
719 hooks.on_closed(room, reason);
720 let _ = writer.send(Message::Close(None));
721 }
722 _ => {
723 if let Some(room) = &self.room {
724 hooks.on_event(room, &json);
725 }
726 }
727 }
728 }
729 Session::Dropped {
730 seated: self_id.is_some(),
731 }
732 }
733}
734
735#[derive(Debug, Clone, Serialize)]
737#[serde(rename_all = "camelCase")]
738pub struct AccessCode {
739 pub code: String,
740 pub reference: String,
742 pub write: bool,
744 pub expires: DateTime<Utc>,
745}
746
747impl AccessCode {
748 pub fn from_json(json: &Value) -> AccessCode {
749 AccessCode {
750 code: json["code"].as_str().unwrap_or_default().to_string(),
751 reference: json["reference"].as_str().unwrap_or_default().to_string(),
752 write: json["write"].as_bool().unwrap_or(false),
753 expires: crate::tickets::parse_date(&json["expires"]).unwrap_or_default(),
754 }
755 }
756}
757
758pub async fn list_access_codes(
761 authorization: &CredentialsOrApiKey,
762 query: PageQuery,
763) -> Result<Vec<AccessCode>> {
764 let response = client()
765 .get(format!(
766 "{}/access-codes?cursor={}&max={}",
767 crate::get_url(),
768 query.cursor,
769 query.max
770 ))
771 .header(
772 "Authorization",
773 match authorization {
774 CredentialsOrApiKey::Credentials(credentials) => {
775 format!("Token {}", credentials.token)
776 }
777 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
778 },
779 )
780 .send()
781 .await?;
782 let rows: Vec<Value> = ok(response).await?.json().await?;
783 Ok(rows.iter().map(AccessCode::from_json).collect())
784}
785
786pub async fn revoke_access_code(authorization: &CredentialsOrApiKey, code: &str) -> Result<()> {
789 let response = client()
790 .delete(format!(
791 "{}/access-codes/{}",
792 crate::get_url(),
793 encode(code)
794 ))
795 .header(
796 "Authorization",
797 match authorization {
798 CredentialsOrApiKey::Credentials(credentials) => {
799 format!("Token {}", credentials.token)
800 }
801 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
802 },
803 )
804 .send()
805 .await?;
806 ok(response).await?;
807 Ok(())
808}
809
810#[cfg(test)]
811mod tests {
812 use super::*;
813 use crate::authentification::ApiKey;
814
815 fn joined() -> (Room, mpsc::UnboundedReceiver<Message>) {
816 let (ws, outbox) = mpsc::unbounded_channel();
817 let authorization = Authorization::Server {
818 authorization: CredentialsOrApiKey::ApiKey(ApiKey::default()),
819 server: "fauna:ticket:1".to_string(),
820 group: None,
821 };
822 let endpoint = "http://localhost/tickets".to_string();
823 (
824 Room::new(endpoint, ws, authorization, "1".to_string()),
825 outbox,
826 )
827 }
828
829 #[test]
830 fn the_socket_is_open_until_either_side_closes_it() {
831 let (room, outbox) = joined();
832 let socket = room.ws();
833 assert!(socket.is_open());
834 drop(outbox);
835 assert!(!socket.is_open());
836
837 let (room, _outbox) = joined();
838 let socket = room.ws();
839 room.0.closed.send_replace(true);
840 assert!(!socket.is_open());
841 assert!(!room.ws().is_open());
842 }
843}