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