Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! AppRTC V1 room API, HTML pages, and static assets.

use crate::config::Config;
use crate::dashboard::StatusReport;
use crate::params::{RoomParameters, generate_random};
use crate::templates::Templates;
use crate::ws_client::RoomAuthority;
use axum::Router;
use axum::body::Body;
use axum::extract::{Path, State};
use axum::http::header::{
    ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN, CONTENT_TYPE, HOST,
};
use axum::http::{HeaderMap, HeaderValue, StatusCode, Uri};
use axum::response::{Html, IntoResponse, Response};
use axum::routing::{get, post};
use serde::Serialize;
use serde_json::json;
use std::error::Error;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;
use tower_http::services::ServeDir;
use url::Url;

const MAX_ROOM_CAPACITY: usize = 2;

struct Inner {
    config: Config,
    templates: Templates,
    authority: Arc<dyn RoomAuthority>,
    started: Instant,
    http_errors: AtomicU64,
}

#[derive(Clone)]
pub struct RoomServer {
    inner: Arc<Inner>,
}

#[derive(Debug, Default, Serialize)]
struct JoinResponse {
    result: String,
    params: RoomParameters,
}

impl RoomServer {
    pub fn new<A: RoomAuthority + 'static>(
        config: Config,
        authority: A,
    ) -> Result<Self, Box<dyn Error + Send + Sync>> {
        let templates = Templates::load(&config.web_root)?;
        Ok(Self {
            inner: Arc::new(Inner {
                config,
                templates,
                authority: Arc::new(authority),
                started: Instant::now(),
                http_errors: AtomicU64::new(0),
            }),
        })
    }

    pub fn router(self) -> Router {
        let web_root = self.inner.config.web_root.clone();
        Router::new()
            .route("/", get(main_page))
            .route("/r/{roomid}", get(room_page))
            .route("/join/{roomid}", post(join))
            .route("/leave/{roomid}/{clientid}", post(leave))
            .route("/message/{roomid}/{clientid}", post(message))
            .route("/params", get(params))
            .route("/v1alpha/iceconfig", get(ice_config).post(ice_config))
            .route("/status", get(status))
            // V1 call.js posts to wss_post_url + /{roomid}/{clientid}.
            .route(
                "/{roomid}/{clientid}",
                post(bridge_post).delete(bridge_delete),
            )
            // Keep the unified Go Collider's newer internal alias as well.
            .route(
                "/_internal/{roomid}/{clientid}",
                post(bridge_post).delete(bridge_delete),
            )
            .nest_service("/js", ServeDir::new(format!("{web_root}/js")))
            .nest_service("/css", ServeDir::new(format!("{web_root}/css")))
            .nest_service("/images", ServeDir::new(format!("{web_root}/images")))
            .nest_service("/html", ServeDir::new(format!("{web_root}/html")))
            .fallback_service(ServeDir::new(web_root))
            .with_state(self)
    }

    fn request_context(&self, headers: &HeaderMap, uri: &Uri) -> Result<(String, Url), String> {
        let host = headers
            .get(HOST)
            .and_then(|value| value.to_str().ok())
            .unwrap_or("localhost")
            .to_string();
        let url = Url::parse(&format!("http://{host}{uri}"))
            .map_err(|error| format!("Invalid request URL: {error}"))?;
        Ok((host, url))
    }

    fn http_error(&self, message: impl Into<String>) -> Response {
        self.inner.http_errors.fetch_add(1, Ordering::Relaxed);
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("{}\n", message.into()),
        )
            .into_response()
    }
}

async fn main_page(State(server): State<RoomServer>, headers: HeaderMap, uri: Uri) -> Response {
    let (host, url) = match server.request_context(&headers, &uri) {
        Ok(context) => context,
        Err(error) => return server.http_error(error),
    };
    let params = server
        .inner
        .config
        .build_room_parameters(host, &url, "", "", None);
    match server.inner.templates.render_index(&params) {
        Ok(body) => Html(body).into_response(),
        Err(error) => server.http_error(format!("Failed to render index: {error}")),
    }
}

async fn room_page(
    State(server): State<RoomServer>,
    Path(roomid): Path<String>,
    headers: HeaderMap,
    uri: Uri,
) -> Response {
    let (host, url) = match server.request_context(&headers, &uri) {
        Ok(context) => context,
        Err(error) => return server.http_error(error),
    };
    let occupancy = match server.inner.authority.occupancy(roomid.clone()).await {
        Ok(occupancy) => occupancy,
        Err(error) => return server.http_error(error),
    };
    let params = server
        .inner
        .config
        .build_room_parameters(host, &url, &roomid, "", None);
    let rendered = if occupancy >= MAX_ROOM_CAPACITY {
        server.inner.templates.render_full(&params)
    } else {
        server.inner.templates.render_index(&params)
    };
    match rendered {
        Ok(body) => Html(body).into_response(),
        Err(error) => server.http_error(format!("Failed to render page: {error}")),
    }
}

async fn params(State(server): State<RoomServer>, headers: HeaderMap, uri: Uri) -> Response {
    let (host, url) = match server.request_context(&headers, &uri) {
        Ok(context) => context,
        Err(error) => return server.http_error(error),
    };
    axum::Json(
        server
            .inner
            .config
            .build_room_parameters(host, &url, "", "", None),
    )
    .into_response()
}

async fn ice_config(State(server): State<RoomServer>) -> impl IntoResponse {
    axum::Json(server.inner.config.ice_config())
}

async fn join(
    State(server): State<RoomServer>,
    Path(roomid): Path<String>,
    headers: HeaderMap,
    uri: Uri,
) -> Response {
    let (host, url) = match server.request_context(&headers, &uri) {
        Ok(context) => context,
        Err(error) => return server.http_error(error),
    };
    let clientid = generate_random(8);
    let is_loopback = url
        .query_pairs()
        .any(|(key, value)| key == "debug" && value == "loopback");
    log::info!("HTTP join: room_id={roomid} client_id={clientid} loopback={is_loopback}");
    match server
        .inner
        .authority
        .admit(roomid.clone(), clientid.clone(), is_loopback)
        .await
    {
        Ok(admission) => {
            let mut params = server.inner.config.build_room_parameters(
                host,
                &url,
                &roomid,
                &clientid,
                Some(admission.is_initiator),
            );
            params.messages = admission.messages;
            axum::Json(JoinResponse {
                result: "SUCCESS".to_string(),
                params,
            })
            .into_response()
        }
        Err(result) => axum::Json(JoinResponse {
            result,
            ..Default::default()
        })
        .into_response(),
    }
}

async fn leave(
    State(server): State<RoomServer>,
    Path((roomid, clientid)): Path<(String, String)>,
) -> Response {
    log::info!("HTTP leave: room_id={roomid} client_id={clientid}");
    match server.inner.authority.remove(roomid, clientid).await {
        Ok(()) => StatusCode::OK.into_response(),
        Err(error) => server.http_error(error),
    }
}

async fn message(
    State(server): State<RoomServer>,
    Path((roomid, clientid)): Path<(String, String)>,
    body: String,
) -> Response {
    log::info!(
        "HTTP message: room_id={roomid} client_id={clientid} bytes={}",
        body.len()
    );
    match server.inner.authority.inject(roomid, clientid, body).await {
        Ok(()) => axum::Json(json!({ "result": "SUCCESS" })).into_response(),
        Err(result) => axum::Json(json!({ "result": result })).into_response(),
    }
}

async fn bridge_post(
    State(server): State<RoomServer>,
    Path((roomid, clientid)): Path<(String, String)>,
    body: String,
) -> Response {
    if body.is_empty() {
        return cors(server.http_error("Empty request body"), "POST, DELETE");
    }
    match server.inner.authority.inject(roomid, clientid, body).await {
        Ok(()) => cors_text("OK\n"),
        Err(error) => cors(
            server.http_error(format!("Failed to send the message: {error}")),
            "POST, DELETE",
        ),
    }
}

async fn bridge_delete(
    State(server): State<RoomServer>,
    Path((roomid, clientid)): Path<(String, String)>,
) -> Response {
    match server.inner.authority.remove(roomid, clientid).await {
        Ok(()) => cors_text("OK\n"),
        Err(error) => cors(server.http_error(error), "POST, DELETE"),
    }
}

async fn status(State(server): State<RoomServer>) -> Response {
    match server.inner.authority.status().await {
        Ok(snapshot) => {
            let report = StatusReport {
                up_time_sec: server.inner.started.elapsed().as_secs_f64(),
                open_ws: snapshot.websocket_connections as u64,
                total_ws: snapshot.total_websocket_connections,
                ws_errs: snapshot.websocket_errors,
                http_errs: server.inner.http_errors.load(Ordering::Relaxed),
            };
            let mut response = axum::Json(report).into_response();
            response
                .headers_mut()
                .insert(ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
            response.headers_mut().insert(
                ACCESS_CONTROL_ALLOW_METHODS,
                HeaderValue::from_static("GET"),
            );
            response
        }
        Err(error) => server.http_error(error),
    }
}

fn cors_text(body: &'static str) -> Response {
    let mut response = Response::new(Body::from(body));
    response.headers_mut().insert(
        CONTENT_TYPE,
        HeaderValue::from_static("text/plain; charset=utf-8"),
    );
    cors(response, "POST, DELETE")
}

fn cors(mut response: Response, methods: &'static str) -> Response {
    response
        .headers_mut()
        .insert(ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
    response.headers_mut().insert(
        ACCESS_CONTROL_ALLOW_METHODS,
        HeaderValue::from_static(methods),
    );
    response
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ws_client::StatusSnapshot;
    use crate::ws_client::{Admission, RoomAuthority};
    use async_trait::async_trait;
    use axum::body::to_bytes;
    use axum::http::{Method, Request};
    use serde_json::Value;
    use std::collections::HashMap;
    use std::sync::{Arc, Mutex};

    type MockClient = (String, Vec<String>);
    type MockRooms = HashMap<String, Vec<MockClient>>;

    #[derive(Clone, Default)]
    struct MockAuthority(Arc<Mutex<MockRooms>>);

    #[async_trait]
    impl RoomAuthority for MockAuthority {
        async fn admit(
            &self,
            roomid: String,
            clientid: String,
            _: bool,
        ) -> Result<Admission, String> {
            let mut rooms = self.0.lock().unwrap();
            let clients = rooms.entry(roomid).or_default();
            if clients.iter().any(|(id, _)| id == &clientid) {
                return Err("DUPLICATE_CLIENT".into());
            }
            if clients.len() >= 2 {
                return Err("FULL".into());
            }
            let initiator = clients.is_empty();
            let messages = clients.first().map(|(_, q)| q.clone()).unwrap_or_default();
            clients.push((clientid, Vec::new()));
            Ok(Admission {
                is_initiator: initiator,
                messages,
            })
        }
        async fn remove(&self, roomid: String, clientid: String) -> Result<(), String> {
            if let Some(clients) = self.0.lock().unwrap().get_mut(&roomid) {
                clients.retain(|(id, _)| id != &clientid);
            }
            Ok(())
        }
        async fn occupancy(&self, roomid: String) -> Result<usize, String> {
            Ok(self.0.lock().unwrap().get(&roomid).map_or(0, Vec::len))
        }
        async fn inject(
            &self,
            roomid: String,
            clientid: String,
            msg: String,
        ) -> Result<(), String> {
            let mut rooms = self.0.lock().unwrap();
            let clients = rooms.entry(roomid).or_default();
            if let Some((_, queue)) = clients.iter_mut().find(|(id, _)| id == &clientid) {
                queue.push(msg);
            } else {
                clients.push((clientid, vec![msg]));
            }
            Ok(())
        }
        async fn status(&self) -> Result<StatusSnapshot, String> {
            let rooms = self.0.lock().unwrap();
            Ok(StatusSnapshot {
                rooms: rooms.len(),
                clients: rooms.values().map(Vec::len).sum(),
                websocket_connections: 0,
                total_websocket_connections: 0,
                websocket_errors: 0,
            })
        }
    }
    use tower::ServiceExt;

    fn app() -> Router {
        let config = Config {
            web_root: env!("CARGO_MANIFEST_DIR").to_string(),
            ..Default::default()
        };
        RoomServer::new(config, MockAuthority::default())
            .unwrap()
            .router()
    }

    async fn request(app: &Router, method: Method, uri: &str, body: &str) -> Response {
        app.clone()
            .oneshot(
                Request::builder()
                    .method(method)
                    .uri(uri)
                    .header(HOST, "example.test")
                    .body(Body::from(body.to_string()))
                    .unwrap(),
            )
            .await
            .unwrap()
    }

    async fn json_body(response: Response) -> Value {
        let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
        serde_json::from_slice(&body).unwrap()
    }

    #[tokio::test]
    async fn v1_join_message_replay_capacity_and_leave_flow() {
        let app = app();
        let first = json_body(request(&app, Method::POST, "/join/room", "").await).await;
        assert_eq!(first["result"], "SUCCESS");
        assert_eq!(first["params"]["is_initiator"], "true");
        let first_id = first["params"]["client_id"].as_str().unwrap();
        assert_eq!(first_id.len(), 8);
        assert!(first_id.bytes().all(|byte| byte.is_ascii_digit()));

        let message_uri = format!("/message/room/{first_id}");
        let sent = json_body(request(&app, Method::POST, &message_uri, "offer").await).await;
        assert_eq!(sent["result"], "SUCCESS");

        let second = json_body(request(&app, Method::POST, "/join/room", "").await).await;
        assert_eq!(second["result"], "SUCCESS");
        assert_eq!(second["params"]["is_initiator"], "false");
        assert_eq!(second["params"]["messages"], json!(["offer"]));

        let full = json_body(request(&app, Method::POST, "/join/room", "").await).await;
        assert_eq!(full["result"], "FULL");

        let leave_uri = format!("/leave/room/{first_id}");
        let left = request(&app, Method::POST, &leave_uri, "").await;
        assert_eq!(left.status(), StatusCode::OK);
        assert!(
            to_bytes(left.into_body(), usize::MAX)
                .await
                .unwrap()
                .is_empty()
        );

        let replacement = json_body(request(&app, Method::POST, "/join/room", "").await).await;
        assert_eq!(replacement["result"], "SUCCESS");
    }

    #[tokio::test]
    async fn v1_pages_static_assets_bridge_and_status_are_served() {
        let app = app();
        let root = request(&app, Method::GET, "/", "").await;
        assert_eq!(root.status(), StatusCode::OK);
        assert!(
            root.headers()[CONTENT_TYPE]
                .to_str()
                .unwrap()
                .starts_with("text/html")
        );

        let script = request(&app, Method::GET, "/js/call.js", "").await;
        assert_eq!(script.status(), StatusCode::OK);

        let bridge = request(&app, Method::POST, "/room/client", "candidate").await;
        assert_eq!(bridge.status(), StatusCode::OK);
        assert_eq!(
            to_bytes(bridge.into_body(), usize::MAX).await.unwrap(),
            "OK\n"
        );

        let internal = request(&app, Method::DELETE, "/_internal/room/client", "").await;
        assert_eq!(internal.status(), StatusCode::OK);

        let status = request(&app, Method::GET, "/status", "").await;
        assert_eq!(status.status(), StatusCode::OK);
        assert_eq!(status.headers()[ACCESS_CONTROL_ALLOW_ORIGIN], "*");
        let status = json_body(status).await;
        assert!(status.get("upsec").is_some());
        assert!(status.get("openws").is_some());
        assert!(status.get("totalws").is_some());
        assert!(status.get("wserrors").is_some());
        assert!(status.get("httperrors").is_some());
    }

    #[tokio::test]
    async fn bridge_validates_empty_body_and_sets_cors_headers() {
        let app = app();
        let empty = request(&app, Method::POST, "/room/client", "").await;
        assert_eq!(empty.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(empty.headers()[ACCESS_CONTROL_ALLOW_ORIGIN], "*");
        assert_eq!(
            empty.headers()[ACCESS_CONTROL_ALLOW_METHODS],
            "POST, DELETE"
        );

        let invalid = request(&app, Method::GET, "/room/client", "").await;
        assert_eq!(invalid.status(), StatusCode::METHOD_NOT_ALLOWED);
    }

    #[tokio::test]
    async fn params_honor_query_options_and_request_host() {
        let config = Config {
            web_root: env!("CARGO_MANIFEST_DIR").to_string(),
            force_tls: true,
            ..Default::default()
        };
        let app = RoomServer::new(config, MockAuthority::default())
            .unwrap()
            .router();
        let response = request(
            &app,
            Method::GET,
            "/params?debug=loopback&it=relay&tt=relay",
            "",
        )
        .await;
        assert_eq!(response.status(), StatusCode::OK);
        let params = json_body(response).await;
        assert_eq!(params["wss_url"], "wss://example.test/ws");
        assert_eq!(params["is_loopback"], "true");
        assert_eq!(params["ice_server_transports"], "relay");
    }

    #[tokio::test]
    async fn room_page_switches_to_full_template_at_capacity() {
        let app = app();
        let first = json_body(request(&app, Method::POST, "/join/full-room", "").await).await;
        let second = json_body(request(&app, Method::POST, "/join/full-room", "").await).await;
        let page = request(&app, Method::GET, "/r/full-room", "").await;
        assert_eq!(page.status(), StatusCode::OK);
        let body = to_bytes(page.into_body(), usize::MAX).await.unwrap();
        assert!(String::from_utf8_lossy(&body).contains("this room is full"));
        let _ = request(
            &app,
            Method::POST,
            &format!(
                "/leave/full-room/{}",
                first["params"]["client_id"].as_str().unwrap()
            ),
            "",
        )
        .await;
        let _ = request(
            &app,
            Method::POST,
            &format!(
                "/leave/full-room/{}",
                second["params"]["client_id"].as_str().unwrap()
            ),
            "",
        )
        .await;
    }
}