Skip to main content

fauna_api/shared/
server.rs

1use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
2use std::time::Duration;
3
4use futures_util::stream::SplitStream;
5use futures_util::{SinkExt, StreamExt};
6use serde::Deserialize;
7use serde_json::{Map, Value, json};
8use tokio::net::TcpStream;
9use tokio::sync::{mpsc, oneshot};
10use tokio_tungstenite::tungstenite::Message;
11use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
12
13use crate::authentification::{CredentialsOrApiKey, Profile};
14use crate::error::{Error, Result};
15use crate::http::{client, ok, websocket};
16
17#[derive(Debug, Clone)]
18pub enum Authorization {
19    Server {
20        authorization: CredentialsOrApiKey,
21        server: String,
22        group: Option<String>,
23    },
24    AccessCode {
25        authorization: CredentialsOrApiKey,
26        access_code: String,
27    },
28}
29
30/// Room lifecycle hooks. Every method defaults to a no-op, like the optional
31/// members of the TypeScript `Hooks` object. Rust can't return a `Room`
32/// subclass from `create_room`, so wrappers capture the base room there instead.
33pub trait Hooks: Send + Sync {
34    fn create_room(&self, _room: &Room, _state: &Value) {}
35
36    fn create_presence(&self, _room: &Room, _presence: &Presence) {}
37    fn remove_presence(&self, _room: &Room, _presence: &Presence) {}
38
39    // Called once the connection snapshot arrives, with the service state block
40    // the edge embedded (durable domain rows). Lets a Room wrapper hydrate.
41    fn on_connection(&self, _room: &Room, _state: &Value) {}
42
43    fn on_event(&self, _room: &Room, _packet: &Value) -> bool {
44        false
45    }
46
47    /// Fired after the presence list changes (join / leave / update).
48    fn on_presence(&self, _room: &Room) {}
49
50    /// Room was destroyed (host left, empty reap, or TTL). Socket is closing.
51    fn on_closed(&self, _room: &Room, _reason: Option<&str>) {}
52}
53
54impl Hooks for () {}
55
56/// `Partial<{ position, status }>` in the TypeScript SDK.
57#[derive(Debug, Clone, Default, Deserialize)]
58pub struct PresencePatch {
59    #[serde(default)]
60    pub position: Option<[f64; 3]>,
61    #[serde(default)]
62    pub status: Option<String>,
63}
64
65#[derive(Default)]
66struct PresenceState {
67    position: [f64; 3],
68    status: Option<String>,
69}
70
71struct PresenceInner {
72    room: Room,
73    id: String,
74    profile: Profile,
75    state: Mutex<PresenceState>,
76}
77
78#[derive(Clone)]
79pub struct Presence(Arc<PresenceInner>);
80
81impl Presence {
82    fn new(room: &Room, id: String, profile: Profile) -> Self {
83        Presence(Arc::new(PresenceInner {
84            room: room.clone(),
85            id,
86            profile,
87            state: Mutex::new(PresenceState::default()),
88        }))
89    }
90
91    fn state(&self) -> MutexGuard<'_, PresenceState> {
92        self.0.state.lock().unwrap_or_else(PoisonError::into_inner)
93    }
94
95    pub fn room(&self) -> &Room {
96        &self.0.room
97    }
98
99    pub fn id(&self) -> &str {
100        &self.0.id
101    }
102
103    pub fn profile(&self) -> &Profile {
104        &self.0.profile
105    }
106
107    pub fn position(&self) -> [f64; 3] {
108        self.state().position
109    }
110
111    pub fn status(&self) -> String {
112        self.state().status.clone().unwrap_or_default()
113    }
114
115    pub fn r#move(&self, position: [f64; 3]) {
116        self.state().position = position;
117
118        self.room().post(&json!({
119            "event": "update-client",
120            "client": self.to_json(),
121        }));
122    }
123
124    pub fn set_status(&self, status: &str) {
125        self.state().status = Some(status.to_string());
126
127        self.room().post(&json!({
128            "event": "update-client",
129            "client": self.to_json(),
130        }));
131    }
132
133    pub fn update(&self, patch: &PresencePatch) {
134        let mut state = self.state();
135        if let Some(position) = patch.position {
136            state.position = position;
137        }
138        if let Some(status) = &patch.status {
139            state.status = Some(status.clone());
140        }
141    }
142
143    pub fn to_json(&self) -> Value {
144        let (position, status) = {
145            let state = self.state();
146            (state.position, state.status.clone().unwrap_or_default())
147        };
148        json!({
149            "id": self.id(),
150            "profile": self.profile(),
151            "position": position,
152            "status": status,
153        })
154    }
155}
156
157struct RoomInner {
158    endpoint: String,
159    ws: mpsc::UnboundedSender<Message>,
160    authorization: Authorization,
161
162    id: String,
163
164    presences: Mutex<Vec<Presence>>,
165}
166
167#[derive(Clone)]
168pub struct Room(Arc<RoomInner>);
169
170impl Room {
171    fn new(
172        endpoint: String,
173        ws: mpsc::UnboundedSender<Message>,
174        authorization: Authorization,
175        id: String,
176    ) -> Self {
177        Room(Arc::new(RoomInner {
178            endpoint,
179            ws,
180            authorization,
181            id,
182            presences: Mutex::new(Vec::new()),
183        }))
184    }
185
186    fn presences(&self) -> MutexGuard<'_, Vec<Presence>> {
187        self.0
188            .presences
189            .lock()
190            .unwrap_or_else(PoisonError::into_inner)
191    }
192
193    pub fn endpoint(&self) -> &str {
194        &self.0.endpoint
195    }
196
197    pub fn authorization(&self) -> &Authorization {
198        &self.0.authorization
199    }
200
201    pub fn id(&self) -> &str {
202        &self.0.id
203    }
204
205    pub fn get_presences(&self) -> Vec<Presence> {
206        self.presences().clone()
207    }
208
209    /// The caller's Credentials or ApiKey from the live authorization pack.
210    pub fn get_authorization(&self) -> &CredentialsOrApiKey {
211        match &self.0.authorization {
212            Authorization::Server { authorization, .. } => authorization,
213            Authorization::AccessCode { authorization, .. } => authorization,
214        }
215    }
216
217    // Send a raw frame to the room edge.
218    pub fn post(&self, packet: &Value) {
219        let _ = self.0.ws.send(Message::text(packet.to_string()));
220    }
221
222    pub fn disconnect(&self) {
223        self.presences().clear();
224        let _ = self.0.ws.send(Message::Close(None));
225    }
226
227    pub async fn generate_access_code(&self) -> Result<String> {
228        let endpoint = self.endpoint().strip_suffix('/').unwrap_or(self.endpoint());
229        let request = client().post(format!("{endpoint}/access-code")).header(
230            "Authorization",
231            match self.get_authorization() {
232                CredentialsOrApiKey::Credentials(credentials) => {
233                    format!("Token {}", credentials.token)
234                }
235                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
236            },
237        );
238        // Mint resolves the room the same way live connect does: Server
239        // (+ optional Group for group-hosted rooms).
240        let request = match self.authorization() {
241            Authorization::Server { server, group, .. } => {
242                let request = request.header("Server", server);
243                match group {
244                    Some(group) => request.header("Group", group),
245                    None => request,
246                }
247            }
248            Authorization::AccessCode { .. } => request,
249        };
250        let response = request.send().await?;
251        Ok(ok(response).await?.text().await?)
252    }
253}
254
255type Reader = SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>;
256
257pub async fn connect(
258    authorization: Authorization,
259    endpoint: &str,
260    hooks: Arc<dyn Hooks>,
261) -> Result<Presence> {
262    // Build WebSocket URL
263    let mut params = Map::new();
264    let header = match &authorization {
265        Authorization::Server { authorization, .. }
266        | Authorization::AccessCode { authorization, .. } => match authorization {
267            CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
268            CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
269        },
270    };
271    params.insert("Authorization".to_string(), Value::String(header));
272    match &authorization {
273        Authorization::Server { server, group, .. } => {
274            params.insert("Server".to_string(), Value::String(server.clone()));
275            if let Some(group) = group {
276                params.insert("Group".to_string(), Value::String(group.clone()));
277            }
278        }
279        Authorization::AccessCode { access_code, .. } => {
280            params.insert("AccessCode".to_string(), Value::String(access_code.clone()));
281        }
282    }
283    let auth_param = crate::http::encode(&Value::Object(params).to_string());
284
285    let ws_url = websocket(endpoint);
286    let ws_url = ws_url.strip_suffix('/').unwrap_or(&ws_url).to_string();
287
288    // Wait for connection
289    let timer = Duration::from_secs(15);
290    let connected = tokio::time::timeout(
291        timer,
292        tokio_tungstenite::connect_async(format!("{ws_url}?authorization={auth_param}")),
293    )
294    .await;
295    let stream = match connected {
296        Ok(Ok((stream, _))) => stream,
297        Ok(Err(_)) => {
298            return Err(Error::Message(format!(
299                "WebSocket connection failed ({ws_url})"
300            )));
301        }
302        Err(_) => {
303            return Err(Error::Message(format!(
304                "Timed out waiting for the room ({ws_url})."
305            )));
306        }
307    };
308
309    let (mut write, read) = stream.split();
310    let (ws, mut outbox) = mpsc::unbounded_channel::<Message>();
311    tokio::spawn(async move {
312        while let Some(message) = outbox.recv().await {
313            let closing = matches!(message, Message::Close(_));
314            if write.send(message).await.is_err() || closing {
315                break;
316            }
317        }
318        let _ = write.close().await;
319    });
320
321    let (ready, settled) = oneshot::channel();
322    tokio::spawn(listen(
323        read,
324        ws.clone(),
325        authorization,
326        endpoint.to_string(),
327        ws_url.clone(),
328        hooks,
329        ready,
330    ));
331
332    match tokio::time::timeout(timer, settled).await {
333        Ok(Ok(result)) => result,
334        Ok(Err(_)) => Err(Error::Message(format!(
335            "WebSocket closed before the room connected ({ws_url})"
336        ))),
337        Err(_) => {
338            let _ = ws.send(Message::Close(None));
339            Err(Error::Message(format!(
340                "Timed out waiting for the room ({ws_url})."
341            )))
342        }
343    }
344}
345
346fn fail(
347    ready: &mut Option<oneshot::Sender<Result<Presence>>>,
348    ws: &mpsc::UnboundedSender<Message>,
349    message: String,
350) {
351    if let Some(ready) = ready.take() {
352        let _ = ws.send(Message::Close(None));
353        let _ = ready.send(Err(Error::Message(message)));
354    }
355}
356
357fn text(value: &Value) -> String {
358    match value {
359        Value::String(value) => value.clone(),
360        Value::Null => String::new(),
361        value => value.to_string(),
362    }
363}
364
365fn profile(client: &Value) -> Profile {
366    serde_json::from_value(client["profile"].clone()).unwrap_or_default()
367}
368
369fn patch(client: &Value) -> PresencePatch {
370    serde_json::from_value(client.clone()).unwrap_or_default()
371}
372
373async fn listen(
374    mut read: Reader,
375    ws: mpsc::UnboundedSender<Message>,
376    authorization: Authorization,
377    endpoint: String,
378    ws_url: String,
379    hooks: Arc<dyn Hooks>,
380    ready: oneshot::Sender<Result<Presence>>,
381) {
382    let mut ready = Some(ready);
383    let mut room: Option<Room> = None;
384    let mut self_id: Option<String> = None;
385
386    while let Some(message) = read.next().await {
387        let raw = match message {
388            Ok(Message::Text(text)) => text.to_string(),
389            Ok(Message::Binary(bytes)) => String::from_utf8_lossy(&bytes).into_owned(),
390            Ok(Message::Close(_)) => break,
391            Ok(_) => continue,
392            Err(_) => {
393                fail(
394                    &mut ready,
395                    &ws,
396                    format!("WebSocket connection failed ({ws_url})"),
397                );
398                break;
399            }
400        };
401        let Ok(json) = serde_json::from_str::<Value>(&raw) else {
402            fail(&mut ready, &ws, "Room connection failed".to_string());
403            continue;
404        };
405
406        if json["event"] == "error" {
407            let message = json["message"]
408                .as_str()
409                .filter(|message| !message.is_empty());
410            fail(
411                &mut ready,
412                &ws,
413                message.unwrap_or("Room connection failed").to_string(),
414            );
415            continue;
416        }
417
418        match json["event"].as_str().unwrap_or_default() {
419            "connection" => {
420                let client = &json["data"]["client"];
421                let client_id = text(&client["id"]);
422                if client_id.is_empty() {
423                    fail(&mut ready, &ws, "Room connection missing self.".to_string());
424                    continue;
425                }
426                self_id = Some(client_id.clone());
427                let id = text(&json["data"]["server"]["id"]);
428                let state = json["data"]["state"].clone();
429                let joined = Room::new(endpoint.clone(), ws.clone(), authorization.clone(), id);
430                hooks.create_room(&joined, &state);
431                let me = Presence::new(&joined, client_id.clone(), profile(client));
432                hooks.create_presence(&joined, &me);
433                me.update(&patch(client));
434
435                for presence in json["data"]["clients"].as_array().into_iter().flatten() {
436                    if text(&presence["id"]) == client_id {
437                        continue;
438                    }
439                    let other = Presence::new(&joined, text(&presence["id"]), profile(presence));
440                    hooks.create_presence(&joined, &other);
441                    other.update(&patch(presence));
442                    joined.presences().push(other);
443                }
444
445                hooks.on_connection(&joined, &state);
446
447                room = Some(joined);
448                if let Some(ready) = ready.take() {
449                    let _ = ready.send(Ok(me));
450                }
451            }
452            "add-client" => {
453                let Some(room) = &room else {
454                    fail(&mut ready, &ws, "Room not found".to_string());
455                    continue;
456                };
457                let client = &json["data"]["client"];
458                if Some(text(&client["id"])) == self_id {
459                    continue;
460                }
461
462                let presence = Presence::new(room, text(&client["id"]), profile(client));
463                hooks.create_presence(room, &presence);
464                presence.update(&patch(client));
465                room.presences().push(presence);
466                hooks.on_presence(room);
467            }
468            "update-client" => {
469                let Some(room) = &room else {
470                    fail(&mut ready, &ws, "Room not found".to_string());
471                    continue;
472                };
473                let client = &json["data"]["client"];
474                let id = text(&client["id"]);
475                if Some(id.clone()) == self_id {
476                    continue;
477                }
478
479                let presence = room
480                    .presences()
481                    .iter()
482                    .find(|presence| presence.id() == id)
483                    .cloned();
484                let Some(presence) = presence else {
485                    fail(&mut ready, &ws, "Presence not found".to_string());
486                    continue;
487                };
488
489                presence.update(&patch(client));
490                hooks.on_presence(room);
491            }
492            "remove-client" => {
493                let Some(room) = &room else {
494                    fail(&mut ready, &ws, "Room not found".to_string());
495                    continue;
496                };
497
498                let id = text(&json["data"]["client"]["id"]);
499                let presence = room
500                    .presences()
501                    .iter()
502                    .find(|presence| presence.id() == id)
503                    .cloned();
504
505                if let Some(presence) = &presence {
506                    hooks.remove_presence(room, presence);
507                    room.presences().retain(|other| other.id() != id);
508                }
509                hooks.on_presence(room);
510            }
511            "server-closed" => {
512                let Some(room) = &room else {
513                    fail(&mut ready, &ws, "Room closed before connect".to_string());
514                    continue;
515                };
516                let reason = json["data"]["reason"].as_str();
517                room.presences().clear();
518                hooks.on_closed(room, reason);
519                let _ = ws.send(Message::Close(None));
520            }
521            _ => {
522                if let Some(room) = &room {
523                    hooks.on_event(room, &json);
524                }
525            }
526        }
527    }
528
529    fail(
530        &mut ready,
531        &ws,
532        format!("WebSocket closed before the room connected ({ws_url})"),
533    );
534}