BREP_app 0.36.1

The next.BREP.io CAD application on the Rust B-rep kernel: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame, native + wasm from one codebase.
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//! The stream's network side: axum serves the client page and the
//! WebSocket on a tokio runtime of its own; the [`Hub`] is what the host
//! loop and the sockets share (clients, roles, input, frame slots).
use super::encode::Held;
use super::input::ClientMsg;
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::extract::State;
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::extract::Path;
use axum::routing::{get, post};
use futures_util::{SinkExt, StreamExt};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;

pub const PROTOCOL: u32 = 1;
/// Frames a client may have un-acknowledged before it is skipped.
pub const MAX_INFLIGHT: u32 = 2;
/// A client whose frames take longer than this from send to ack is on a slow
/// link: it gets one frame in flight (so the next input's frame never queues
/// behind two) and the 3D view's lossy tiles at [`SLOW_JPEG`] at most.
pub const SLOW_LINK: std::time::Duration = std::time::Duration::from_millis(120);
pub const SLOW_JPEG: u8 = 40;
/// The largest file a page may upload.
pub const MAX_UPLOAD: u64 = 256 << 20;
/// Uploads announced and not yet sent, per client.
const MAX_ANNOUNCED: usize = 8;
/// Downloads kept on offer (the oldest goes first).
const MAX_OFFERED: usize = 64;
const INDEX_HTML: &str = include_str!("client/index.html");
const STREAM_JS: &str = include_str!("client/stream.js");

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Role {
    Control,
    View,
}

impl Role {
    fn name(self) -> &'static str {
        match self {
            Role::Control => "control",
            Role::View => "view",
        }
    }
}

/// One connected, authenticated client.
pub struct Client {
    pub role: Role,
    /// It asked for control in its hello: it takes control when the
    /// controller leaves (a reloaded page whose new connection arrived before
    /// the old one closed).
    wants_control: bool,
    ctrl: tokio::sync::mpsc::UnboundedSender<String>,
    /// The newest frame for the writer; filled only when empty.
    slot: Arc<Mutex<Option<Vec<u8>>>>,
    notify: Arc<tokio::sync::Notify>,
    pub held: Held,
    pub sent_seq: u32,
    pub acked_seq: u32,
    pub jpeg_quality: u8,
    /// `(seq, when sent)` of the frames not yet acknowledged.
    sent_at: std::collections::VecDeque<(u32, std::time::Instant)>,
    /// Smoothed send-to-ack time of this client's frames.
    pub frame_time: Option<std::time::Duration>,
}

impl Client {
    /// Whether this client's link is slow (see [`SLOW_LINK`]).
    pub fn slow(&self) -> bool {
        self.frame_time.is_some_and(|t| t > SLOW_LINK)
    }

    pub fn can_take_frame(&self) -> bool {
        let limit = if self.slow() { 1 } else { MAX_INFLIGHT };
        self.sent_seq.wrapping_sub(self.acked_seq) < limit && self.slot.lock().unwrap().is_none()
    }

    /// The JPEG quality this client's moving 3D view is sent at.
    pub fn quality(&self) -> u8 {
        if self.slow() { self.jpeg_quality.min(SLOW_JPEG) } else { self.jpeg_quality }
    }

    fn acked(&mut self, seq: u32) {
        self.acked_seq = seq;
        let now = std::time::Instant::now();
        while let Some(&(sent, at)) = self.sent_at.front() {
            // Sequence numbers wrap; anything not after `seq` is answered.
            if (seq.wrapping_sub(sent) as i32) < 0 {
                break;
            }
            self.sent_at.pop_front();
            if sent == seq {
                let took = now - at;
                self.frame_time = Some(match self.frame_time {
                    Some(t) => (t * 7 + took * 3) / 10,
                    None => took,
                });
            }
        }
    }

    pub fn send_frame(&mut self, message: Vec<u8>) {
        self.sent_at.push_back((self.sent_seq, std::time::Instant::now()));
        if self.sent_at.len() > 64 {
            self.sent_at.pop_front();
        }
        *self.slot.lock().unwrap() = Some(message);
        self.notify.notify_one();
    }

    pub fn send_json(&self, value: serde_json::Value) {
        let _ = self.ctrl.send(value.to_string());
    }
}

/// What the page asked for since the host last looked.
#[derive(Default)]
pub struct Inbox {
    /// Controller input, in order.
    pub input: Vec<ClientMsg>,
    /// The controller's latest surface `(w, h, dpr)` in CSS pixels.
    pub resize: Option<(f32, f32, f32)>,
    /// A client joined (it needs a frame even if nothing changed).
    pub joined: bool,
    /// An ack freed a client that had been skipped.
    pub acked: bool,
    /// Files the page uploaded, on disk, for the app to open.
    pub uploaded: Vec<std::path::PathBuf>,
}

/// An upload the controller announced: its bytes come by POST.
struct Announced {
    client: u64,
    name: String,
    size: u64,
}

/// An export the app wrote and the page may fetch.
struct Offered {
    path: std::path::PathBuf,
    name: String,
}

#[derive(Default)]
pub struct HubInner {
    pub clients: HashMap<u64, Client>,
    pub controller: Option<u64>,
    next_id: u64,
    pub inbox: Inbox,
    pub stopping: bool,
    announced: HashMap<String, Announced>,
    offered: HashMap<String, Offered>,
    /// Offer ids, oldest first.
    offer_order: std::collections::VecDeque<String>,
    uploads: u64,
}

/// Shared by the host loop and the sockets.
pub struct Hub {
    pub inner: Mutex<HubInner>,
    token: String,
    origins: Vec<String>,
    wake: crate::desktop_loop::Waker,
    pub session: String,
    /// The surface a client is told about at once in its welcome.
    pub surface: Mutex<(u32, u32, f32)>,
    /// Where uploads land: durable, since an opened document keeps its path.
    upload_dir: Mutex<std::path::PathBuf>,
}

impl Hub {
    pub fn new(token: String, origins: Vec<String>, wake: crate::desktop_loop::Waker) -> Arc<Hub> {
        Arc::new(Hub {
            inner: Mutex::default(),
            token,
            origins,
            wake,
            session: uuid::Uuid::new_v4().simple().to_string()[..12].to_string(),
            surface: Mutex::new((0, 0, 1.0)),
            upload_dir: Mutex::new(crate::help_local::data_dir().join("stream-uploads")),
        })
    }

    /// Put uploads in `dir` instead of `<data dir>/brep-app/stream-uploads`.
    pub fn set_upload_dir(&self, dir: std::path::PathBuf) {
        *self.upload_dir.lock().unwrap() = dir;
    }

    /// Send `value` to every client.
    pub fn to_all(&self, value: serde_json::Value) {
        let text = value.to_string();
        for c in self.lock().clients.values() {
            let _ = c.ctrl.send(text.clone());
        }
    }

    /// Offer the export at `path` to every page as a download.
    pub fn offer(&self, path: std::path::PathBuf) {
        let Ok(meta) = std::fs::metadata(&path) else { return };
        let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "download".into());
        let id = uuid::Uuid::new_v4().simple().to_string();
        let mut inner = self.lock();
        inner.offer_order.push_back(id.clone());
        if inner.offer_order.len() > MAX_OFFERED {
            if let Some(old) = inner.offer_order.pop_front() {
                inner.offered.remove(&old);
            }
        }
        inner.offered.insert(id.clone(), Offered { path, name: name.clone() });
        let text = serde_json::json!({"t": "download", "id": id, "name": name, "size": meta.len()}).to_string();
        for c in inner.clients.values() {
            let _ = c.ctrl.send(text.clone());
        }
    }

    /// Client `id` announces an upload: refused unless it controls the
    /// session, the name keeps something after sanitising, and the size is
    /// allowed; else answered with the id the bytes go to.
    fn announce(&self, inner: &mut HubInner, id: u64, name: &str, size: u64) {
        let refuse = |inner: &HubInner, msg: String| {
            if let Some(c) = inner.clients.get(&id) {
                c.send_json(serde_json::json!({"t": "error", "code": "upload", "name": name, "msg": msg}));
            }
        };
        if inner.controller != Some(id) {
            return refuse(inner, "only the controlling page uploads".into());
        }
        let Some(clean) = sanitise_name(name) else {
            return refuse(inner, format!("{name:?} is not a file name"));
        };
        if size > MAX_UPLOAD {
            return refuse(inner, format!("{clean} is {size} bytes; the limit is {MAX_UPLOAD}"));
        }
        if inner.announced.values().filter(|a| a.client == id).count() >= MAX_ANNOUNCED {
            return refuse(inner, "too many uploads waiting".into());
        }
        let upload = uuid::Uuid::new_v4().simple().to_string();
        inner.announced.insert(upload.clone(), Announced { client: id, name: clean.clone(), size });
        if let Some(c) = inner.clients.get(&id) {
            c.send_json(serde_json::json!({"t": "upload", "id": upload, "name": clean, "size": size}));
        }
    }

    /// End the session: the host loop returns (the app's `on_exit` runs).
    pub fn stop(&self) {
        self.lock().stopping = true;
        (self.wake)();
    }

    pub fn lock(&self) -> std::sync::MutexGuard<'_, HubInner> {
        self.inner.lock().unwrap_or_else(|p| p.into_inner())
    }

    /// Send `value` to the controller.
    pub fn to_controller(&self, value: serde_json::Value) {
        let inner = self.lock();
        if let Some(c) = inner.controller.and_then(|id| inner.clients.get(&id)) {
            c.send_json(value);
        }
    }

    fn token_ok(&self, given: &str) -> bool {
        // Constant time in the token's length.
        let (a, b) = (self.token.as_bytes(), given.as_bytes());
        let mut diff = a.len() ^ b.len();
        for (i, x) in a.iter().enumerate() {
            diff |= usize::from(x ^ b.get(i).copied().unwrap_or(0));
        }
        diff == 0
    }

    fn origin_ok(&self, headers: &HeaderMap) -> bool {
        let Some(origin) = headers.get(header::ORIGIN).and_then(|o| o.to_str().ok()) else {
            // Not a browser (a native client sends no Origin): the token decides.
            return true;
        };
        if self.origins.iter().any(|o| o == "*" || o == origin) {
            return true;
        }
        // The server's own origin: the page it served.
        let host = headers.get(header::HOST).and_then(|h| h.to_str().ok()).unwrap_or("");
        origin.strip_prefix("http://").or_else(|| origin.strip_prefix("https://")) == Some(host)
    }

    fn join(&self, role: Role, w: Option<f32>, h: Option<f32>, dpr: Option<f32>) -> (u64, Role, ClientIo) {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        let slot = Arc::new(Mutex::new(None));
        let notify = Arc::new(tokio::sync::Notify::new());
        let mut inner = self.lock();
        inner.next_id += 1;
        let id = inner.next_id;
        let wants_control = role == Role::Control;
        let role = if wants_control && inner.controller.is_none() { Role::Control } else { Role::View };
        if role == Role::Control {
            inner.controller = Some(id);
            if let (Some(w), Some(h)) = (w, h) {
                inner.inbox.resize = Some((w, h, dpr.unwrap_or(1.0)));
            }
        }
        inner.clients.insert(
            id,
            Client {
                role,
                wants_control,
                ctrl: tx,
                slot: slot.clone(),
                notify: notify.clone(),
                held: Held::default(),
                sent_seq: 0,
                acked_seq: 0,
                jpeg_quality: 70,
                sent_at: Default::default(),
                frame_time: None,
            },
        );
        inner.inbox.joined = true;
        drop(inner);
        (self.wake)();
        (id, role, ClientIo { rx, slot, notify })
    }

    fn leave(&self, id: u64) {
        let mut inner = self.lock();
        inner.clients.remove(&id);
        inner.announced.retain(|_, a| a.client != id);
        if inner.controller == Some(id) {
            inner.controller = None;
            // The oldest client that asked for control takes it.
            let next = inner.clients.iter().filter(|(_, c)| c.wants_control).map(|(id, _)| *id).min();
            if let Some(next) = next {
                inner.controller = Some(next);
                if let Some(c) = inner.clients.get_mut(&next) {
                    c.role = Role::Control;
                    c.send_json(serde_json::json!({"t": "role", "role": "control"}));
                }
                // Its page size applies from now: it sends it on the role change.
            }
        }
    }

    /// One message from client `id`.
    fn receive(&self, id: u64, msg: ClientMsg) {
        let mut inner = self.lock();
        let controller = inner.controller == Some(id);
        match msg {
            ClientMsg::Hello { .. } => {}
            ClientMsg::Ack { seq } => {
                if let Some(c) = inner.clients.get_mut(&id) {
                    c.acked(seq);
                }
                inner.inbox.acked = true;
            }
            ClientMsg::Quality { jpeg } => {
                if let (Some(c), Some(q)) = (inner.clients.get_mut(&id), jpeg) {
                    c.jpeg_quality = q.clamp(10, 95);
                }
            }
            ClientMsg::TakeControl => {
                if let Some(old) = inner.controller.filter(|old| *old != id) {
                    if let Some(c) = inner.clients.get_mut(&old) {
                        c.role = Role::View;
                        c.send_json(serde_json::json!({"t": "role", "role": "view"}));
                    }
                }
                inner.controller = Some(id);
                if let Some(c) = inner.clients.get_mut(&id) {
                    c.role = Role::Control;
                    c.send_json(serde_json::json!({"t": "role", "role": "control"}));
                }
            }
            ClientMsg::Drop { name, size } => {
                self.announce(&mut inner, id, &name, size);
                return;
            }
            ClientMsg::Resize { w, h, dpr } if controller => inner.inbox.resize = Some((w, h, dpr)),
            other if controller => inner.inbox.input.push(other),
            _ => return,
        }
        drop(inner);
        (self.wake)();
    }
}

struct ClientIo {
    rx: tokio::sync::mpsc::UnboundedReceiver<String>,
    slot: Arc<Mutex<Option<Vec<u8>>>>,
    notify: Arc<tokio::sync::Notify>,
}

/// Start the server on its own thread and runtime; returns once listening.
pub fn start(listener: std::net::TcpListener, hub: Arc<Hub>) -> Result<std::thread::JoinHandle<()>, String> {
    listener.set_nonblocking(true).map_err(|e| format!("listener: {e}"))?;
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .worker_threads(2)
        .thread_name("brep-stream")
        .enable_all()
        .build()
        .map_err(|e| format!("runtime: {e}"))?;
    let app = axum::Router::new()
        .route("/", get(|| async { axum::response::Redirect::temporary("/stream/") }))
        .route("/stream", get(|| async { axum::response::Redirect::temporary("/stream/") }))
        .route("/stream/", get(index))
        .route("/stream/stream.js", get(script))
        .route("/stream/ws", get(upgrade))
        .route("/stream/uploads/:id", post(upload))
        .route("/stream/downloads/:id", get(download))
        .with_state(hub);
    std::thread::Builder::new()
        .name("brep-stream-server".into())
        .spawn(move || {
            runtime.block_on(async move {
                let listener = match tokio::net::TcpListener::from_std(listener) {
                    Ok(l) => l,
                    Err(e) => return eprintln!("brep-app --stream: {e}"),
                };
                if let Err(e) = axum::serve(listener, app).await {
                    eprintln!("brep-app --stream: server stopped: {e}");
                }
            })
        })
        .map_err(|e| format!("server thread: {e}"))
}

fn no_store(content_type: &'static str, body: &'static str) -> Response {
    ([(header::CONTENT_TYPE, content_type), (header::CACHE_CONTROL, "no-store")], body).into_response()
}

async fn index() -> Response {
    no_store("text/html; charset=utf-8", INDEX_HTML)
}

async fn script() -> Response {
    no_store("text/javascript; charset=utf-8", STREAM_JS)
}

async fn upgrade(State(hub): State<Arc<Hub>>, headers: HeaderMap, ws: WebSocketUpgrade) -> Response {
    if !hub.origin_ok(&headers) {
        return (StatusCode::FORBIDDEN, "origin not allowed").into_response();
    }
    ws.max_message_size(64 << 20).on_upgrade(move |socket| serve(hub, socket))
}

/// A client's file name with no path in it: the last component, control and
/// path characters replaced, no leading dots, at most 120 bytes (the
/// extension kept). `None` when nothing is left.
pub fn sanitise_name(name: &str) -> Option<String> {
    let base = name.rsplit(['/', '\\']).next().unwrap_or("");
    let clean: String = base
        .chars()
        .map(|c| if c.is_control() || matches!(c, ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c })
        .collect();
    let clean = clean.trim().trim_start_matches('.').trim().to_string();
    if clean.is_empty() || clean.chars().all(|c| c == '_' || c == '.') {
        return None;
    }
    if clean.len() <= 120 {
        return Some(clean);
    }
    let (stem, ext) = match clean.rsplit_once('.') {
        Some((stem, ext)) if ext.len() <= 16 => (stem, format!(".{ext}")),
        _ => (clean.as_str(), String::new()),
    };
    let mut cut = 120 - ext.len();
    while !stem.is_char_boundary(cut) {
        cut -= 1;
    }
    Some(format!("{}{ext}", &stem[..cut]))
}

/// The `Authorization: Bearer` token, checked; a wrong one waits half a
/// second like a wrong hello.
async fn bearer_ok(hub: &Hub, headers: &HeaderMap) -> bool {
    let given = headers.get(header::AUTHORIZATION).and_then(|v| v.to_str().ok()).and_then(|v| v.strip_prefix("Bearer ")).unwrap_or("");
    if hub.token_ok(given) {
        return true;
    }
    tokio::time::sleep(Duration::from_millis(500)).await;
    false
}

/// `POST /stream/uploads/<id>`: the bytes of an announced upload. Nothing
/// is read before the origin, the token, the id, the announcer still holding
/// control and the declared length are checked, so a stranger cannot make the
/// server buffer a body. Written under a temporary name and renamed when
/// whole, so the app never opens a partial file; a body that does not arrive
/// whole leaves nothing.
async fn upload(State(hub): State<Arc<Hub>>, Path(id): Path<String>, headers: HeaderMap, body: axum::body::Body) -> Response {
    if !hub.origin_ok(&headers) {
        return (StatusCode::FORBIDDEN, "origin not allowed").into_response();
    }
    if !bearer_ok(&hub, &headers).await {
        return (StatusCode::UNAUTHORIZED, "wrong token").into_response();
    }
    let announced = {
        let mut inner = hub.lock();
        let Some(announced) = inner.announced.remove(&id) else {
            return (StatusCode::NOT_FOUND, "no such upload").into_response();
        };
        if inner.controller != Some(announced.client) {
            return (StatusCode::CONFLICT, "the page that announced this upload no longer controls the session").into_response();
        }
        announced
    };
    let declared = headers.get(header::CONTENT_LENGTH).and_then(|v| v.to_str().ok()).and_then(|v| v.parse::<u64>().ok());
    if declared != Some(announced.size) {
        return (StatusCode::BAD_REQUEST, format!("announced {} bytes; the request declares {declared:?}", announced.size)).into_response();
    }
    let body = match axum::body::to_bytes(body, announced.size as usize).await {
        Ok(body) if body.len() as u64 == announced.size => body,
        Ok(body) => return (StatusCode::BAD_REQUEST, format!("announced {} bytes, sent {}", announced.size, body.len())).into_response(),
        Err(e) => return (StatusCode::BAD_REQUEST, format!("the upload did not arrive whole: {e}")).into_response(),
    };
    let n = {
        let mut inner = hub.lock();
        inner.uploads += 1;
        inner.uploads
    };
    let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
    // A folder per upload keeps the page's file name (an imported tab is
    // named after it) and never collides.
    let dir = hub.upload_dir.lock().unwrap().join(format!("{stamp}-{n}"));
    let path = dir.join(&announced.name);
    let part = dir.join(".upload.part");
    let target = path.clone();
    let written = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
        std::fs::create_dir_all(&dir)?;
        std::fs::write(&part, &body)?;
        std::fs::rename(&part, &target).inspect_err(|_| {
            let _ = std::fs::remove_file(&part);
        })
    })
    .await;
    match written {
        Ok(Ok(())) => {}
        Ok(Err(e)) => return (StatusCode::INTERNAL_SERVER_ERROR, format!("could not write the upload: {e}")).into_response(),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, format!("upload task: {e}")).into_response(),
    }
    let shown = path.display().to_string();
    {
        let mut inner = hub.lock();
        inner.inbox.uploaded.push(path);
        if let Some(c) = inner.clients.get(&announced.client) {
            c.send_json(serde_json::json!({"t": "uploaded", "id": id, "name": announced.name, "path": shown}));
        }
    }
    (hub.wake)();
    ([(header::CONTENT_TYPE, "application/json")], serde_json::json!({"path": shown}).to_string()).into_response()
}

/// `GET /stream/downloads/<id>`: an export the app offered, never any
/// other path.
async fn download(State(hub): State<Arc<Hub>>, Path(id): Path<String>, headers: HeaderMap) -> Response {
    if !hub.origin_ok(&headers) {
        return (StatusCode::FORBIDDEN, "origin not allowed").into_response();
    }
    if !bearer_ok(&hub, &headers).await {
        return (StatusCode::UNAUTHORIZED, "wrong token").into_response();
    }
    let Some((path, name)) = hub.lock().offered.get(&id).map(|o| (o.path.clone(), o.name.clone())) else {
        return (StatusCode::NOT_FOUND, "no such download").into_response();
    };
    let bytes = match tokio::task::spawn_blocking(move || std::fs::read(path)).await {
        Ok(Ok(bytes)) => bytes,
        Ok(Err(e)) => return (StatusCode::GONE, format!("the export is gone: {e}")).into_response(),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, format!("download task: {e}")).into_response(),
    };
    let ascii: String = name.chars().map(|c| if c == ' ' || (c.is_ascii_graphic() && c != '"' && c != '\\') { c } else { '_' }).collect();
    (
        [
            (header::CONTENT_TYPE, "application/octet-stream".to_string()),
            (header::CONTENT_DISPOSITION, format!("attachment; filename=\"{ascii}\"")),
            (header::CACHE_CONTROL, "no-store".to_string()),
        ],
        bytes,
    )
        .into_response()
}

fn json(value: serde_json::Value) -> Message {
    Message::Text(value.to_string())
}

async fn serve(hub: Arc<Hub>, mut socket: WebSocket) {
    // The first message is the hello, within ten seconds.
    let hello = tokio::time::timeout(Duration::from_secs(10), socket.recv()).await;
    let Ok(Some(Ok(Message::Text(text)))) = hello else { return };
    let Ok(ClientMsg::Hello { v, token, role, w, h, dpr }) = serde_json::from_str::<ClientMsg>(&text) else {
        let _ = socket.send(json(serde_json::json!({"t": "error", "code": "protocol", "msg": "the first message must be hello"}))).await;
        return;
    };
    if !hub.token_ok(&token) {
        tokio::time::sleep(Duration::from_millis(500)).await;
        let _ = socket.send(json(serde_json::json!({"t": "error", "code": "auth", "msg": "wrong token"}))).await;
        return;
    }
    if v != PROTOCOL {
        let _ = socket.send(json(serde_json::json!({"t": "error", "code": "version", "msg": format!("this server speaks version {PROTOCOL}")}))).await;
        return;
    }
    let asked = if role.as_deref() == Some("view") { Role::View } else { Role::Control };
    let (id, role, mut io) = hub.join(asked, w, h, dpr);
    let (sw, sh, ppp) = *hub.surface.lock().unwrap();
    let welcome = serde_json::json!({
        "t": "welcome", "v": PROTOCOL, "session": hub.session, "role": role.name(),
        "caps": ["png", "jpeg"], "w": sw, "h": sh, "ppp": ppp,
    });
    let (mut tx, mut rx) = socket.split();
    if tx.send(json(welcome)).await.is_err() {
        return hub.leave(id);
    }
    // Input is read on its own task: a slow frame send never holds it.
    let reader_hub = hub.clone();
    let mut reader = tokio::spawn(async move {
        while let Some(Ok(message)) = rx.next().await {
            match message {
                Message::Text(text) => match serde_json::from_str::<ClientMsg>(&text) {
                    Ok(msg) => reader_hub.receive(id, msg),
                    Err(e) => log::debug!("stream: bad message: {e}"),
                },
                Message::Close(_) => break,
                _ => {}
            }
        }
    });
    loop {
        tokio::select! {
            biased;
            text = io.rx.recv() => match text {
                Some(text) => if tx.send(Message::Text(text)).await.is_err() { break },
                None => break,
            },
            _ = io.notify.notified() => {
                let frame = io.slot.lock().unwrap().take();
                if let Some(frame) = frame {
                    if tx.send(Message::Binary(frame)).await.is_err() { break }
                }
            }
            // The page closed (or its socket broke): leave at once, so a page
            // that reloads finds the controller's place free.
            _ = &mut reader => break,
        }
    }
    reader.abort();
    hub.leave(id);
}