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
173impl Room {
174    pub(crate) fn new(
175        endpoint: String,
176        ws: mpsc::UnboundedSender<Message>,
177        authorization: Authorization,
178        id: String,
179    ) -> Self {
180        Room(Arc::new(RoomInner {
181            endpoint,
182            ws,
183            authorization,
184            id,
185            presences: Mutex::new(Vec::new()),
186            closed: watch::channel(false).0,
187        }))
188    }
189
190    fn presences(&self) -> MutexGuard<'_, Vec<Presence>> {
191        self.0
192            .presences
193            .lock()
194            .unwrap_or_else(PoisonError::into_inner)
195    }
196
197    pub fn endpoint(&self) -> &str {
198        &self.0.endpoint
199    }
200
201    pub fn authorization(&self) -> &Authorization {
202        &self.0.authorization
203    }
204
205    pub fn id(&self) -> &str {
206        &self.0.id
207    }
208
209    pub fn get_presences(&self) -> Vec<Presence> {
210        self.presences().clone()
211    }
212
213    pub(crate) fn clear_presences(&self) {
214        self.presences().clear();
215    }
216
217    /// Turns true once the socket has closed, for any reason.
218    pub(crate) fn socket_closed(&self) -> watch::Receiver<bool> {
219        self.0.closed.subscribe()
220    }
221
222    /// The caller's Credentials or ApiKey from the live authorization pack.
223    pub fn get_authorization(&self) -> &CredentialsOrApiKey {
224        match &self.0.authorization {
225            Authorization::Server { authorization, .. } => authorization,
226            Authorization::AccessCode { authorization, .. } => authorization,
227        }
228    }
229
230    // Send a raw frame to the room edge.
231    pub fn post(&self, packet: &Value) {
232        let _ = self.0.ws.send(Message::text(packet.to_string()));
233    }
234
235    pub fn disconnect(&self) {
236        self.presences().clear();
237        let _ = self.0.ws.send(Message::Close(None));
238    }
239
240    pub async fn generate_access_code(&self) -> Result<String> {
241        let endpoint = self.endpoint().strip_suffix('/').unwrap_or(self.endpoint());
242        let request = client().post(format!("{endpoint}/access-code")).header(
243            "Authorization",
244            match self.get_authorization() {
245                CredentialsOrApiKey::Credentials(credentials) => {
246                    format!("Token {}", credentials.token)
247                }
248                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
249            },
250        );
251        // Mint resolves the room the same way live connect does: Server
252        // (+ optional Group for group-hosted rooms).
253        let request = match self.authorization() {
254            Authorization::Server { server, group, .. } => {
255                let request = request.header("Server", server);
256                match group {
257                    Some(group) => request.header("Group", group),
258                    None => request,
259                }
260            }
261            Authorization::AccessCode { .. } => request,
262        };
263        let response = request.send().await?;
264        Ok(ok(response).await?.text().await?)
265    }
266}
267
268type Reader = SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>;
269
270pub async fn connect(
271    authorization: Authorization,
272    endpoint: &str,
273    hooks: Arc<dyn Hooks>,
274) -> Result<Presence> {
275    // Build WebSocket URL
276    let mut params = Map::new();
277    let header = match &authorization {
278        Authorization::Server { authorization, .. }
279        | Authorization::AccessCode { authorization, .. } => match authorization {
280            CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
281            CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
282        },
283    };
284    params.insert("Authorization".to_string(), Value::String(header));
285    match &authorization {
286        Authorization::Server { server, group, .. } => {
287            params.insert("Server".to_string(), Value::String(server.clone()));
288            if let Some(group) = group {
289                params.insert("Group".to_string(), Value::String(group.clone()));
290            }
291        }
292        Authorization::AccessCode { access_code, .. } => {
293            params.insert("AccessCode".to_string(), Value::String(access_code.clone()));
294        }
295    }
296    let auth_param = crate::http::encode(&Value::Object(params).to_string());
297
298    let ws_url = websocket(endpoint);
299    let ws_url = ws_url.strip_suffix('/').unwrap_or(&ws_url).to_string();
300
301    // Wait for connection
302    let timer = Duration::from_secs(15);
303    let connected = tokio::time::timeout(
304        timer,
305        tokio_tungstenite::connect_async(format!("{ws_url}?authorization={auth_param}")),
306    )
307    .await;
308    let stream = match connected {
309        Ok(Ok((stream, _))) => stream,
310        Ok(Err(_)) => {
311            return Err(Error::Message(format!(
312                "WebSocket connection failed ({ws_url})"
313            )));
314        }
315        Err(_) => {
316            return Err(Error::Message(format!(
317                "Timed out waiting for the room ({ws_url})."
318            )));
319        }
320    };
321
322    let (mut write, read) = stream.split();
323    let (ws, mut outbox) = mpsc::unbounded_channel::<Message>();
324    tokio::spawn(async move {
325        while let Some(message) = outbox.recv().await {
326            let closing = matches!(message, Message::Close(_));
327            if write.send(message).await.is_err() || closing {
328                break;
329            }
330        }
331        let _ = write.close().await;
332    });
333
334    let (ready, settled) = oneshot::channel();
335    tokio::spawn(listen(
336        read,
337        ws.clone(),
338        authorization,
339        endpoint.to_string(),
340        ws_url.clone(),
341        hooks,
342        ready,
343    ));
344
345    match tokio::time::timeout(timer, settled).await {
346        Ok(Ok(result)) => result,
347        Ok(Err(_)) => Err(Error::Message(format!(
348            "WebSocket closed before the room connected ({ws_url})"
349        ))),
350        Err(_) => {
351            let _ = ws.send(Message::Close(None));
352            Err(Error::Message(format!(
353                "Timed out waiting for the room ({ws_url})."
354            )))
355        }
356    }
357}
358
359fn fail(
360    ready: &mut Option<oneshot::Sender<Result<Presence>>>,
361    ws: &mpsc::UnboundedSender<Message>,
362    message: String,
363) {
364    if let Some(ready) = ready.take() {
365        let _ = ws.send(Message::Close(None));
366        let _ = ready.send(Err(Error::Message(message)));
367    }
368}
369
370fn text(value: &Value) -> String {
371    match value {
372        Value::String(value) => value.clone(),
373        Value::Null => String::new(),
374        value => value.to_string(),
375    }
376}
377
378fn profile(client: &Value) -> Profile {
379    serde_json::from_value(client["profile"].clone()).unwrap_or_default()
380}
381
382fn patch(client: &Value) -> PresencePatch {
383    serde_json::from_value(client.clone()).unwrap_or_default()
384}
385
386async fn listen(
387    mut read: Reader,
388    ws: mpsc::UnboundedSender<Message>,
389    authorization: Authorization,
390    endpoint: String,
391    ws_url: String,
392    hooks: Arc<dyn Hooks>,
393    ready: oneshot::Sender<Result<Presence>>,
394) {
395    let mut ready = Some(ready);
396    let mut room: Option<Room> = None;
397    let mut self_id: Option<String> = None;
398
399    while let Some(message) = read.next().await {
400        let raw = match message {
401            Ok(Message::Text(text)) => text.to_string(),
402            Ok(Message::Binary(bytes)) => String::from_utf8_lossy(&bytes).into_owned(),
403            Ok(Message::Close(_)) => break,
404            Ok(_) => continue,
405            Err(_) => {
406                fail(
407                    &mut ready,
408                    &ws,
409                    format!("WebSocket connection failed ({ws_url})"),
410                );
411                break;
412            }
413        };
414        let Ok(json) = serde_json::from_str::<Value>(&raw) else {
415            fail(&mut ready, &ws, "Room connection failed".to_string());
416            continue;
417        };
418
419        if json["event"] == "error" {
420            let message = json["message"]
421                .as_str()
422                .filter(|message| !message.is_empty());
423            fail(
424                &mut ready,
425                &ws,
426                message.unwrap_or("Room connection failed").to_string(),
427            );
428            continue;
429        }
430
431        match json["event"].as_str().unwrap_or_default() {
432            "connection" => {
433                let client = &json["data"]["client"];
434                let client_id = text(&client["id"]);
435                if client_id.is_empty() {
436                    fail(&mut ready, &ws, "Room connection missing self.".to_string());
437                    continue;
438                }
439                self_id = Some(client_id.clone());
440                let id = text(&json["data"]["server"]["id"]);
441                let state = json["data"]["state"].clone();
442                let joined = Room::new(endpoint.clone(), ws.clone(), authorization.clone(), id);
443                hooks.create_room(&joined, &state);
444                let me = Presence::new(&joined, client_id.clone(), profile(client));
445                hooks.create_presence(&joined, &me);
446                me.update(&patch(client));
447
448                for presence in json["data"]["clients"].as_array().into_iter().flatten() {
449                    if text(&presence["id"]) == client_id {
450                        continue;
451                    }
452                    let other = Presence::new(&joined, text(&presence["id"]), profile(presence));
453                    hooks.create_presence(&joined, &other);
454                    other.update(&patch(presence));
455                    joined.presences().push(other);
456                }
457
458                hooks.on_connection(&joined, &state);
459
460                room = Some(joined);
461                if let Some(ready) = ready.take() {
462                    let _ = ready.send(Ok(me));
463                }
464            }
465            "add-client" => {
466                let Some(room) = &room else {
467                    fail(&mut ready, &ws, "Room not found".to_string());
468                    continue;
469                };
470                let client = &json["data"]["client"];
471                if Some(text(&client["id"])) == self_id {
472                    continue;
473                }
474
475                let presence = Presence::new(room, text(&client["id"]), profile(client));
476                hooks.create_presence(room, &presence);
477                presence.update(&patch(client));
478                room.presences().push(presence);
479                hooks.on_presence(room);
480            }
481            "update-client" => {
482                let Some(room) = &room else {
483                    fail(&mut ready, &ws, "Room not found".to_string());
484                    continue;
485                };
486                let client = &json["data"]["client"];
487                let id = text(&client["id"]);
488                if Some(id.clone()) == self_id {
489                    continue;
490                }
491
492                let presence = room
493                    .presences()
494                    .iter()
495                    .find(|presence| presence.id() == id)
496                    .cloned();
497                let Some(presence) = presence else {
498                    fail(&mut ready, &ws, "Presence not found".to_string());
499                    continue;
500                };
501
502                presence.update(&patch(client));
503                hooks.on_presence(room);
504            }
505            "remove-client" => {
506                let Some(room) = &room else {
507                    fail(&mut ready, &ws, "Room not found".to_string());
508                    continue;
509                };
510
511                let id = text(&json["data"]["client"]["id"]);
512                let presence = room
513                    .presences()
514                    .iter()
515                    .find(|presence| presence.id() == id)
516                    .cloned();
517
518                if let Some(presence) = &presence {
519                    hooks.remove_presence(room, presence);
520                    room.presences().retain(|other| other.id() != id);
521                }
522                hooks.on_presence(room);
523            }
524            "server-closed" => {
525                let Some(room) = &room else {
526                    fail(&mut ready, &ws, "Room closed before connect".to_string());
527                    continue;
528                };
529                let reason = json["data"]["reason"].as_str();
530                room.presences().clear();
531                hooks.on_closed(room, reason);
532                let _ = ws.send(Message::Close(None));
533            }
534            _ => {
535                if let Some(room) = &room {
536                    hooks.on_event(room, &json);
537                }
538            }
539        }
540    }
541
542    if let Some(room) = &room {
543        room.0.closed.send_replace(true);
544    }
545    fail(
546        &mut ready,
547        &ws,
548        format!("WebSocket closed before the room connected ({ws_url})"),
549    );
550}
551
552/// A code you own: a room you shared, or a file link.
553#[derive(Debug, Clone, Serialize)]
554#[serde(rename_all = "camelCase")]
555pub struct AccessCode {
556    pub code: String,
557    /// What it opens, e.g. `parrot:chat:{id}` or `file:{path}`.
558    pub reference: String,
559    /// True when people who join with it may act in the room, not only watch.
560    pub write: bool,
561    pub expires: DateTime<Utc>,
562}
563
564impl AccessCode {
565    pub fn from_json(json: &Value) -> AccessCode {
566        AccessCode {
567            code: json["code"].as_str().unwrap_or_default().to_string(),
568            reference: json["reference"].as_str().unwrap_or_default().to_string(),
569            write: json["write"].as_bool().unwrap_or(false),
570            expires: crate::tickets::parse_date(&json["expires"]).unwrap_or_default(),
571        }
572    }
573}
574
575/// The access codes you own, the one that lasts longest first: your room shares
576/// and file links, and the ones you made for your groups.
577pub async fn list_access_codes(
578    authorization: &CredentialsOrApiKey,
579    query: PageQuery,
580) -> Result<Vec<AccessCode>> {
581    let response = client()
582        .get(format!(
583            "{}/access-codes?cursor={}&max={}",
584            crate::get_url(),
585            query.cursor,
586            query.max
587        ))
588        .header(
589            "Authorization",
590            match authorization {
591                CredentialsOrApiKey::Credentials(credentials) => {
592                    format!("Token {}", credentials.token)
593                }
594                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
595            },
596        )
597        .send()
598        .await?;
599    let rows: Vec<Value> = ok(response).await?.json().await?;
600    Ok(rows.iter().map(AccessCode::from_json).collect())
601}
602
603/// Revoke one of your access codes. It stops working at once; anyone in a room
604/// with it is disconnected.
605pub async fn revoke_access_code(authorization: &CredentialsOrApiKey, code: &str) -> Result<()> {
606    let response = client()
607        .delete(format!(
608            "{}/access-codes/{}",
609            crate::get_url(),
610            encode(code)
611        ))
612        .header(
613            "Authorization",
614            match authorization {
615                CredentialsOrApiKey::Credentials(credentials) => {
616                    format!("Token {}", credentials.token)
617                }
618                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
619            },
620        )
621        .send()
622        .await?;
623    ok(response).await?;
624    Ok(())
625}