Skip to main content

fauna_api/shared/
server.rs

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