Skip to main content

fauna_api/marmot/
web.rs

1//! Marmot-owned live web-room client: HTTP bootstrap/assets, CSS and asset URL
2//! rewriting, and the WebRoom socket. DOM capture and replay stay in the
3//! TypeScript SDK, which runs in the page.
4
5use std::collections::{BTreeMap, HashMap};
6use std::ops::Deref;
7use std::sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock};
8use std::time::Duration;
9
10use base64::Engine;
11use base64::engine::general_purpose::STANDARD;
12use futures_util::StreamExt;
13use futures_util::future::BoxFuture;
14use serde::{Deserialize, Serialize};
15use serde_json::{Map, Value, json};
16use tokio::sync::oneshot;
17
18use crate::authentification::CredentialsOrApiKey;
19use crate::drive::Progress;
20use crate::error::{Error, Result};
21use crate::http::{client, ok, progress_body};
22use crate::shared::server::{Authorization, Hooks, Presence, Room, connect};
23
24/// A single serialized DOM node. `id` is a synthetic stable key assigned by the
25/// recorder; it is NOT the element's DOM id attribute.
26#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
27#[serde(tag = "kind", rename_all = "lowercase")]
28pub enum WebNode {
29    Element {
30        id: u64,
31        tag: String,
32        #[serde(default)]
33        attributes: BTreeMap<String, String>,
34        #[serde(default)]
35        children: Vec<u64>,
36    },
37    Text {
38        id: u64,
39        #[serde(default)]
40        text: String,
41    },
42}
43
44/// `{ width, height }` in the TypeScript SDK.
45#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
46pub struct WebViewport {
47    pub width: f64,
48    pub height: f64,
49}
50
51/// A full document snapshot: the root node id plus every node reachable from
52/// it, flattened into an id->node map for O(1) patching on the viewer.
53#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
54pub struct WebSnapshot {
55    pub root: u64,
56    pub nodes: HashMap<u64, WebNode>,
57    /// Viewport the host captured at (viewers use it only for reference; they
58    /// render at their own size).
59    pub viewport: WebViewport,
60}
61
62/// An incremental change to a previously-snapshotted tree.
63#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
64#[serde(tag = "kind", rename_all = "lowercase")]
65pub enum WebMutation {
66    Insert {
67        parent: u64,
68        node: WebNode,
69        #[serde(default)]
70        subtree: Vec<WebNode>,
71        before: Option<u64>,
72    },
73    Remove {
74        id: u64,
75    },
76    Text {
77        id: u64,
78        text: String,
79    },
80    Attribute {
81        id: u64,
82        name: String,
83        value: Option<String>,
84    },
85    /// The host's viewport changed. Viewers may use this to hint responsive
86    /// re-layout, but are never forced to match the host's dimensions.
87    Viewport {
88        width: f64,
89        height: f64,
90    },
91}
92
93/// Agent or host pointer. Sibling of WebMutation, not a DOM change.
94#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
95#[serde(rename_all = "camelCase")]
96pub struct HtmlPointer {
97    pub x: f64,
98    pub y: f64,
99    #[serde(default)]
100    pub scroll_x: f64,
101    #[serde(default)]
102    pub scroll_y: f64,
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub visible: Option<bool>,
105    /// The CSS cursor under the pointer (`pointer`, `text`, `nwse-resize`...), `default` for `auto`.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub shape: Option<String>,
108}
109
110/// Placeholder scheme rewritten into guest blob: URLs after asset download.
111pub const WEB_ASSET_SCHEME: &str = "fauna-web-asset:";
112
113/// `{ data, contentType }` in the TypeScript SDK: fetched bytes and their type.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct FetchedMedia {
116    pub data: Vec<u8>,
117    pub content_type: String,
118}
119
120/// Optional privileged fetcher (extension background).
121pub type MediaFetcher =
122    Arc<dyn Fn(String) -> BoxFuture<'static, Option<FetchedMedia>> + Send + Sync>;
123
124static MEDIA_FETCHER: RwLock<Option<MediaFetcher>> = RwLock::new(None);
125
126/// Install a privileged media fetcher.
127pub fn set_media_fetcher(fetcher: Option<MediaFetcher>) {
128    *MEDIA_FETCHER
129        .write()
130        .unwrap_or_else(PoisonError::into_inner) = fetcher;
131}
132
133fn consider_url(raw: Option<&str>, into: &mut Vec<String>) {
134    let Some(raw) = raw else {
135        return;
136    };
137    let trimmed = raw.trim();
138    if trimmed.is_empty()
139        || trimmed.starts_with(WEB_ASSET_SCHEME)
140        || trimmed.starts_with("javascript:")
141    {
142        return;
143    }
144    if trimmed.starts_with('#') || trimmed.starts_with("mailto:") || trimmed.starts_with("tel:") {
145        return;
146    }
147    if trimmed.starts_with("blob:") {
148        return;
149    }
150    // Leave data: URIs inline. Harvesting them is unnecessary (already self-
151    // contained) and a naive url() scan can truncate SVG data URIs at the
152    // first quote/paren, then rewrite the prefix and leave a base64 tail that
153    // the browser fetches as a relative path.
154    if trimmed.starts_with("data:") {
155        return;
156    }
157    if !into.iter().any(|known| known == trimmed) {
158        into.push(trimmed.to_string());
159    }
160}
161
162fn find_ignore_case(haystack: &str, needle: &str, from: usize) -> Option<usize> {
163    let bytes = haystack.as_bytes();
164    let needle = needle.as_bytes();
165    (from..=bytes.len().saturating_sub(needle.len())).find(|&index| {
166        bytes.len() >= index + needle.len()
167            && bytes[index..index + needle.len()].eq_ignore_ascii_case(needle)
168    })
169}
170
171fn skip_whitespace(text: &str, mut index: usize) -> usize {
172    while let Some(c) = text[index..].chars().next() {
173        if !c.is_whitespace() {
174            break;
175        }
176        index += c.len_utf8();
177    }
178    index
179}
180
181/// Walk `url(...)` tokens in CSS. Quoted values may contain `)` / quotes that
182/// would break a naive character class (common in SVG data URIs).
183fn for_each_css_url_token(css: &str, mut visit: impl FnMut(&str, &str, usize, usize)) {
184    let mut from = 0;
185    while let Some(start) = find_ignore_case(css, "url(", from) {
186        let i = skip_whitespace(css, start + 4);
187        if i >= css.len() {
188            break;
189        }
190        let first = css.as_bytes()[i];
191        if first == b'"' || first == b'\'' {
192            let quote = if first == b'"' { "\"" } else { "'" };
193            let begin = i + 1;
194            let Some(close_quote) = css[begin..].find(quote).map(|offset| begin + offset) else {
195                break;
196            };
197            let Some(close_paren) = css[close_quote + 1..]
198                .find(')')
199                .map(|offset| close_quote + 1 + offset)
200            else {
201                break;
202            };
203            visit(&css[begin..close_quote], quote, start, close_paren + 1);
204            from = close_paren + 1;
205            continue;
206        }
207        let Some(close_paren) = css[i..].find(')').map(|offset| i + offset) else {
208            break;
209        };
210        visit(css[i..close_paren].trim(), "", start, close_paren + 1);
211        from = close_paren + 1;
212    }
213}
214
215/// One `@import url(...)` or `@import "..."` rule: its start, end and target.
216fn next_import(css: &str, mut from: usize) -> Option<(usize, usize, String)> {
217    while let Some(start) = find_ignore_case(css, "@import", from) {
218        from = start + 1;
219        let after = start + "@import".len();
220        let i = skip_whitespace(css, after);
221        if i == after {
222            continue;
223        }
224        let bytes = css.as_bytes();
225        let mut target = None;
226        let mut end = i;
227        if find_ignore_case(css, "url(", i) == Some(i) {
228            let j = skip_whitespace(css, i + 4);
229            let quote = bytes.get(j).copied().filter(|c| *c == b'"' || *c == b'\'');
230            let begin = if quote.is_some() { j + 1 } else { j };
231            let stop = css[begin..]
232                .find(['\'', '"', ')'])
233                .map_or(css.len(), |offset| begin + offset);
234            if stop > begin {
235                let mut k = stop;
236                let closed = match quote {
237                    Some(quote) => {
238                        bytes.get(k) == Some(&quote) && {
239                            k += 1;
240                            true
241                        }
242                    }
243                    None => true,
244                };
245                if closed {
246                    let k = skip_whitespace(css, k);
247                    if bytes.get(k) == Some(&b')') {
248                        target = Some(css[begin..stop].to_string());
249                        end = k + 1;
250                    }
251                }
252            }
253        } else if let Some(&quote) = bytes.get(i).filter(|c| **c == b'"' || **c == b'\'') {
254            let begin = i + 1;
255            if let Some(stop) = css[begin..].find(['\'', '"']).map(|offset| begin + offset)
256                && stop > begin
257                && bytes[stop] == quote
258            {
259                target = Some(css[begin..stop].to_string());
260                end = stop + 1;
261            }
262        }
263        let Some(target) = target else {
264            continue;
265        };
266        let mut end = skip_whitespace(css, end);
267        if bytes.get(end) == Some(&b';') {
268            end += 1;
269        }
270        return Some((start, end, target));
271    }
272    None
273}
274
275/// Pull url(...) and @import targets out of CSS text (preserves @media as-is).
276pub fn extract_css_urls(css: &str) -> Vec<String> {
277    let mut found = Vec::new();
278    for_each_css_url_token(css, |raw, _, _, _| consider_url(Some(raw), &mut found));
279    let mut from = 0;
280    while let Some((_, end, target)) = next_import(css, from) {
281        consider_url(Some(&target), &mut found);
282        from = end;
283    }
284    found
285}
286
287/// Rewrite url()/ @import targets in CSS using fauna-web-asset codes.
288pub fn rewrite_css_urls(css: &str, map: &HashMap<String, String>) -> String {
289    let mut out = String::new();
290    let mut cursor = 0;
291    for_each_css_url_token(css, |raw, quote, start, end| {
292        out.push_str(&css[cursor..start]);
293        match map.get(raw.trim()) {
294            None => out.push_str(&css[start..end]),
295            Some(code) => out.push_str(&format!("url({quote}{WEB_ASSET_SCHEME}{code}{quote})")),
296        }
297        cursor = end;
298    });
299    out.push_str(&css[cursor..]);
300
301    let mut rewritten = String::new();
302    let mut cursor = 0;
303    while let Some((start, end, target)) = next_import(&out, cursor) {
304        rewritten.push_str(&out[cursor..start]);
305        let trimmed = target.trim();
306        match map.get(trimmed) {
307            Some(code) if !trimmed.starts_with("data:") => {
308                rewritten.push_str(&format!("@import url(\"{WEB_ASSET_SCHEME}{code}\");"))
309            }
310            _ => rewritten.push_str(&out[start..end]),
311        }
312        cursor = end;
313    }
314    rewritten.push_str(&out[cursor..]);
315    rewritten
316}
317
318fn asset_code_at(html: &str, from: usize) -> Option<(usize, usize, &str)> {
319    let mut from = from;
320    while let Some(offset) = html[from..].find(WEB_ASSET_SCHEME) {
321        let start = from + offset;
322        let begin = start + WEB_ASSET_SCHEME.len();
323        let length = html[begin..]
324            .bytes()
325            .take_while(|c| c.is_ascii_alphanumeric() || *c == b'_' || *c == b'-')
326            .count();
327        if length > 0 {
328            return Some((start, begin + length, &html[begin..begin + length]));
329        }
330        from = begin;
331    }
332    None
333}
334
335pub fn extract_asset_codes(html: &str) -> Vec<String> {
336    let mut codes: Vec<String> = Vec::new();
337    let mut from = 0;
338    while let Some((_, end, code)) = asset_code_at(html, from) {
339        if !codes.iter().any(|known| known == code) {
340            codes.push(code.to_string());
341        }
342        from = end;
343    }
344    codes
345}
346
347/// Replace `fauna-web-asset:CODE` markers with blob/object URLs from `blobs`.
348pub fn materialize_asset_urls(html: &str, blobs: &HashMap<String, String>) -> String {
349    let mut out = String::new();
350    let mut cursor = 0;
351    while let Some((start, end, code)) = asset_code_at(html, cursor) {
352        out.push_str(&html[cursor..start]);
353        match blobs.get(code) {
354            Some(url) => out.push_str(url),
355            None => out.push_str(&html[start..end]),
356        }
357        cursor = end;
358    }
359    out.push_str(&html[cursor..]);
360    out
361}
362
363fn decode_data_url(url: &str) -> Option<FetchedMedia> {
364    let comma = url.find(',')?;
365    let header = &url[5..comma];
366    let payload = &url[comma + 1..];
367    let content_type = header
368        .split(';')
369        .next()
370        .filter(|kind| !kind.is_empty())
371        .unwrap_or("application/octet-stream")
372        .to_string();
373    if header.contains(";base64") {
374        return Some(FetchedMedia {
375            data: STANDARD.decode(payload).ok()?,
376            content_type,
377        });
378    }
379    Some(FetchedMedia {
380        data: percent_encoding::percent_decode_str(payload).collect(),
381        content_type,
382    })
383}
384
385/// Best-effort fetch of a media URL; prefers a privileged `set_media_fetcher`.
386pub async fn fetch_media_bytes(url: &str) -> Option<FetchedMedia> {
387    if url.starts_with("data:") {
388        return decode_data_url(url);
389    }
390    let fetcher = MEDIA_FETCHER
391        .read()
392        .unwrap_or_else(PoisonError::into_inner)
393        .clone();
394    if let Some(fetcher) = fetcher
395        && let Some(via) = fetcher(url.to_string()).await
396    {
397        return Some(via);
398    }
399    let response = client().get(url).send().await.ok()?;
400    if !response.status().is_success() {
401        return None;
402    }
403    let content_type = response
404        .headers()
405        .get("Content-Type")
406        .and_then(|value| value.to_str().ok())
407        .filter(|value| !value.is_empty())
408        .unwrap_or("application/octet-stream")
409        .to_string();
410    Some(FetchedMedia {
411        data: response.bytes().await.ok()?.to_vec(),
412        content_type,
413    })
414}
415
416/// Absolute-resolve a URL against a base (`https://localhost/` without one).
417pub fn absolute_url(url: &str, base: Option<&str>) -> String {
418    if url.starts_with("data:") || url.starts_with("blob:") || url.starts_with(WEB_ASSET_SCHEME) {
419        return url.to_string();
420    }
421    let base = base
422        .filter(|base| !base.is_empty())
423        .unwrap_or("https://localhost/");
424    reqwest::Url::parse(base)
425        .and_then(|base| base.join(url))
426        .map(|resolved| resolved.to_string())
427        .unwrap_or_else(|_| url.to_string())
428}
429
430/// A web room addressed by an access code or a room reference.
431#[derive(Debug, Clone, PartialEq, Eq)]
432pub enum WebTarget {
433    Code { code: String },
434    Reference { reference: String },
435}
436
437fn target_header(request: reqwest::RequestBuilder, target: &WebTarget) -> reqwest::RequestBuilder {
438    match target {
439        WebTarget::Code { code } => request.header("Access-Code", code),
440        WebTarget::Reference { reference } => request.header("Server", reference),
441    }
442}
443
444#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
445#[serde(rename_all = "camelCase")]
446pub struct BootstrapMeta {
447    pub version: u64,
448    #[serde(default, skip_serializing_if = "Option::is_none")]
449    pub viewport: Option<WebViewport>,
450    #[serde(default, skip_serializing_if = "Option::is_none")]
451    pub content_length: Option<u64>,
452    #[serde(default, skip_serializing_if = "Option::is_none")]
453    pub content_type: Option<String>,
454    /// In-band HTML for server-hosted rooms (BrowserRoom). Extension share uses HTTP.
455    #[serde(default, skip_serializing_if = "Option::is_none")]
456    pub html: Option<String>,
457}
458
459#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
460#[serde(rename_all = "camelCase")]
461pub struct AssetUploadResult {
462    pub asset_id: String,
463    pub access_code: String,
464    pub content_type: String,
465}
466
467/// The `options` argument of `upload_bootstrap`.
468#[derive(Clone, Default)]
469pub struct BootstrapOptions {
470    pub version: Option<u64>,
471    pub viewport: Option<WebViewport>,
472    pub content_type: Option<String>,
473    pub on_progress: Option<Progress>,
474}
475
476/// `{ ok, version }` in the TypeScript SDK.
477#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
478pub struct BootstrapUpload {
479    pub ok: bool,
480    pub version: u64,
481}
482
483fn authorization_header(authorization: &CredentialsOrApiKey) -> String {
484    match authorization {
485        CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
486        CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
487    }
488}
489
490/// Upload cleaned HTML as a raw stream, reporting upload progress.
491pub async fn upload_bootstrap(
492    authorization: &CredentialsOrApiKey,
493    target: &WebTarget,
494    html: &[u8],
495    options: BootstrapOptions,
496) -> Result<BootstrapUpload> {
497    let version = options.version.unwrap_or(1);
498    let mut request = target_header(
499        client()
500            .post(format!("{}/extensions/web/bootstrap", super::get_url()))
501            .header("Authorization", authorization_header(authorization)),
502        target,
503    )
504    .header(
505        "Content-Type",
506        options
507            .content_type
508            .as_deref()
509            .unwrap_or("text/html; charset=utf-8"),
510    )
511    .header("Bootstrap-Version", version.to_string());
512    if let Some(viewport) = options.viewport {
513        request = request
514            .header("Viewport-Width", viewport.width.to_string())
515            .header("Viewport-Height", viewport.height.to_string());
516    }
517    let response = request
518        .header("Content-Length", html.len())
519        .body(progress_body(html.to_vec(), options.on_progress.clone()))
520        .send()
521        .await
522        .map_err(|_| Error::Message("Failed to upload bootstrap.".to_string()))?;
523    if let Some(progress) = &options.on_progress {
524        progress(1.0);
525    }
526    let status = response.status();
527    let text = response.text().await.unwrap_or_default();
528    if !status.is_success() {
529        return Err(Error::Message(if text.is_empty() {
530            format!("{}: bootstrap upload failed", status.as_u16())
531        } else {
532            text
533        }));
534    }
535    Ok(serde_json::from_str(&text).unwrap_or(BootstrapUpload { ok: true, version }))
536}
537
538async fn read_body(
539    response: reqwest::Response,
540    content_length: u64,
541    on_progress: Option<Progress>,
542) -> Result<Vec<u8>> {
543    let mut out = Vec::new();
544    let mut body = response.bytes_stream();
545    while let Some(chunk) = body.next().await {
546        out.extend_from_slice(&chunk?);
547        if let Some(progress) = &on_progress
548            && content_length > 0
549        {
550            progress((out.len() as f64 / content_length as f64).min(1.0));
551        }
552    }
553    if let Some(progress) = &on_progress {
554        progress(1.0);
555    }
556    Ok(out)
557}
558
559fn header_text(response: &reqwest::Response, name: &str) -> Option<String> {
560    response
561        .headers()
562        .get(name)
563        .and_then(|value| value.to_str().ok())
564        .filter(|value| !value.is_empty())
565        .map(str::to_string)
566}
567
568/// `{ html, contentLength, contentType }` in the TypeScript SDK.
569#[derive(Debug, Clone, PartialEq, Eq)]
570pub struct Bootstrap {
571    pub html: String,
572    pub content_length: u64,
573    pub content_type: String,
574}
575
576/// Download the room HTML bootstrap with download progress when Content-Length is known.
577pub async fn download_bootstrap(
578    authorization: &CredentialsOrApiKey,
579    target: &WebTarget,
580    on_progress: Option<Progress>,
581) -> Result<Bootstrap> {
582    let response = target_header(
583        client()
584            .get(format!("{}/extensions/web/bootstrap", super::get_url()))
585            .header("Authorization", authorization_header(authorization)),
586        target,
587    )
588    .send()
589    .await?;
590    let response = ok(response).await?;
591    let content_type = header_text(&response, "Content-Type")
592        .unwrap_or_else(|| "text/html; charset=utf-8".to_string());
593    let content_length = header_text(&response, "Content-Length")
594        .and_then(|length| length.parse().ok())
595        .unwrap_or(0);
596    let buffer = read_body(response, content_length, on_progress).await?;
597    Ok(Bootstrap {
598        html: String::from_utf8_lossy(&buffer).into_owned(),
599        content_length,
600        content_type,
601    })
602}
603
604/// The `options` argument of `upload_asset`.
605#[derive(Clone, Default)]
606pub struct AssetOptions {
607    pub asset_id: Option<String>,
608    pub on_progress: Option<Progress>,
609}
610
611/// Upload one media asset; returns a per-asset access code for guest download.
612pub async fn upload_asset(
613    authorization: &CredentialsOrApiKey,
614    target: &WebTarget,
615    data: &[u8],
616    content_type: &str,
617    options: AssetOptions,
618) -> Result<AssetUploadResult> {
619    let safe_type = content_type
620        .split(';')
621        .next()
622        .map(str::trim)
623        .filter(|kind| !kind.is_empty())
624        .unwrap_or("application/octet-stream");
625    let mut request = target_header(
626        client()
627            .post(format!("{}/extensions/web/asset", super::get_url()))
628            .header("Authorization", authorization_header(authorization)),
629        target,
630    )
631    .header("Content-Type", safe_type);
632    if let Some(asset_id) = &options.asset_id {
633        request = request.header("Asset-Id", asset_id);
634    }
635    let response = request
636        .header("Content-Length", data.len())
637        .body(progress_body(data.to_vec(), options.on_progress.clone()))
638        .send()
639        .await
640        .map_err(|_| Error::Message("Failed to upload asset.".to_string()))?;
641    if let Some(progress) = &options.on_progress {
642        progress(1.0);
643    }
644    let status = response.status();
645    let text = response.text().await.unwrap_or_default();
646    if !status.is_success() {
647        return Err(Error::Message(if text.is_empty() {
648            format!("{}: asset upload failed", status.as_u16())
649        } else {
650            text
651        }));
652    }
653    Ok(serde_json::from_str(&text)?)
654}
655
656/// Download one asset by its file access code.
657pub async fn download_asset(
658    authorization: &CredentialsOrApiKey,
659    access_code: &str,
660    on_progress: Option<Progress>,
661) -> Result<FetchedMedia> {
662    let response = client()
663        .get(format!("{}/extensions/web/asset", super::get_url()))
664        .header("Authorization", authorization_header(authorization))
665        .header("File-Access-Code", access_code)
666        .send()
667        .await?;
668    let response = ok(response).await?;
669    let content_type = header_text(&response, "Content-Type")
670        .unwrap_or_else(|| "application/octet-stream".to_string());
671    let content_length = header_text(&response, "Content-Length")
672        .and_then(|length| length.parse().ok())
673        .unwrap_or(0);
674    let data = read_body(response, content_length, on_progress).await?;
675    Ok(FetchedMedia { data, content_type })
676}
677
678/// One stage of `weighted_progress`: its share of the whole, and the work, which
679/// reports its own progress from 0 to 1.
680pub struct ProgressStage {
681    pub weight: f64,
682    pub run: Box<dyn FnOnce(Progress) -> BoxFuture<'static, Result<()>> + Send>,
683}
684
685/// Aggregate sequential upload/download stages into a single 0..1 progress.
686pub async fn weighted_progress(
687    stages: Vec<ProgressStage>,
688    on_progress: Option<Progress>,
689) -> Result<()> {
690    let total = stages
691        .iter()
692        .map(|stage| stage.weight.max(0.0))
693        .sum::<f64>();
694    let total = if total == 0.0 { 1.0 } else { total };
695    let mut completed = 0.0;
696    for stage in stages {
697        let weight = stage.weight.max(0.0);
698        let outer = on_progress.clone();
699        let done = completed;
700        (stage.run)(Arc::new(move |p: f64| {
701            if let Some(progress) = &outer {
702                progress((done + p.clamp(0.0, 1.0) * weight) / total);
703            }
704        }))
705        .await?;
706        completed += weight;
707        if let Some(progress) = &on_progress {
708            progress(completed / total);
709        }
710    }
711    Ok(())
712}
713
714/// Web room hooks. Every method defaults to a no-op, like the optional members
715/// of the TypeScript `WebRoomHooks` object.
716pub trait WebRoomHooks: Send + Sync {
717    /// Host published bootstrap meta: guests should HTTP GET the HTML.
718    fn on_bootstrap(&self, _room: &WebRoom, _bootstrap: &BootstrapMeta) {}
719    /// The host published a fresh full-page snapshot (fallback).
720    fn on_snapshot(&self, _room: &WebRoom, _snapshot: &WebSnapshot) {}
721    /// The host emitted one incremental DOM mutation.
722    fn on_mutation(&self, _room: &WebRoom, _mutation: &WebMutation) {}
723    /// The host disconnected / stopped sharing: the room is closing.
724    fn on_closed(&self, _room: &WebRoom) {}
725    /// Presence roster changed (join/leave/update).
726    fn on_presence(&self, _room: &WebRoom) {}
727}
728
729impl WebRoomHooks for () {}
730
731/// What a host runs for a `web-tool-call`: the tool's name and parameters in,
732/// its result out.
733pub type WebToolHandler =
734    Arc<dyn Fn(String, Map<String, Value>) -> BoxFuture<'static, Result<String>> + Send + Sync>;
735
736struct WebState {
737    hooks: Arc<dyn WebRoomHooks>,
738    latest: Option<WebSnapshot>,
739    bootstrap: Option<BootstrapMeta>,
740    tool_handler: Option<(u64, WebToolHandler)>,
741    next_handler: u64,
742    pending_tools: HashMap<String, oneshot::Sender<Result<String>>>,
743    // Tagged host principal from the live connection (`credentials:` / `group:` / ...).
744    host_principal: Option<String>,
745    // Server-computed: whether this caller may invite others to the share.
746    can_invite: bool,
747    owned: bool,
748}
749
750/// A live web room for page sharing. `WebRoom` wraps `Room` and carries presence
751/// and small DOM mutations. Initial HTML and media bytes travel over HTTP
752/// bootstrap/asset routes, not this socket.
753#[derive(Clone)]
754pub struct WebRoom {
755    room: Room,
756    state: Arc<Mutex<WebState>>,
757}
758
759impl Deref for WebRoom {
760    type Target = Room;
761    fn deref(&self) -> &Room {
762        &self.room
763    }
764}
765
766impl WebRoom {
767    fn new(
768        room: Room,
769        hooks: Arc<dyn WebRoomHooks>,
770        connection_state: &Value,
771        owned: bool,
772    ) -> WebRoom {
773        let meta = &connection_state["room"];
774        WebRoom {
775            room,
776            state: Arc::new(Mutex::new(WebState {
777                hooks,
778                latest: None,
779                bootstrap: None,
780                tool_handler: None,
781                next_handler: 0,
782                pending_tools: HashMap::new(),
783                host_principal: meta["hostPrincipal"]
784                    .as_str()
785                    .filter(|principal| !principal.is_empty())
786                    .map(str::to_string),
787                can_invite: meta["canInvite"].as_bool().unwrap_or(false),
788                owned,
789            })),
790        }
791    }
792
793    fn state(&self) -> MutexGuard<'_, WebState> {
794        self.state.lock().unwrap_or_else(PoisonError::into_inner)
795    }
796
797    fn hooks(&self) -> Arc<dyn WebRoomHooks> {
798        self.state().hooks.clone()
799    }
800
801    pub fn set_hooks(&self, hooks: Arc<dyn WebRoomHooks>) {
802        self.state().hooks = hooks;
803    }
804
805    /// Ingest-only child of a page room (same socket).
806    pub fn from_parent(
807        parent: &Room,
808        hooks: Option<Arc<dyn WebRoomHooks>>,
809        connection_state: &Value,
810    ) -> WebRoom {
811        WebRoom::new(
812            parent.clone(),
813            hooks.unwrap_or_else(|| Arc::new(())),
814            connection_state,
815            false,
816        )
817    }
818
819    /// Host principal tagged string, if the connection provided it.
820    pub fn get_host_principal(&self) -> Option<String> {
821        self.state().host_principal.clone()
822    }
823
824    /// Whether this signed-in caller may invite others (server-gated).
825    pub fn can_invite(&self) -> bool {
826        self.state().can_invite
827    }
828
829    pub fn get_snapshot(&self) -> Option<WebSnapshot> {
830        self.state().latest.clone()
831    }
832
833    pub fn get_bootstrap(&self) -> Option<BootstrapMeta> {
834        self.state().bootstrap.clone()
835    }
836
837    pub fn disconnect(&self) {
838        if !self.state().owned {
839            return;
840        }
841        self.room.disconnect();
842    }
843
844    pub fn ingest_snapshot(&self, snapshot: WebSnapshot) {
845        self.state().latest = Some(snapshot.clone());
846        self.hooks().on_snapshot(self, &snapshot);
847    }
848
849    pub fn ingest_bootstrap(&self, meta: BootstrapMeta) {
850        self.state().bootstrap = Some(meta.clone());
851        self.hooks().on_bootstrap(self, &meta);
852    }
853
854    pub fn publish_bootstrap(&self, meta: BootstrapMeta) {
855        self.post(&json!({ "event": "web-bootstrap", "data": { "bootstrap": meta } }));
856        self.state().bootstrap = Some(meta);
857    }
858
859    pub fn publish_snapshot(&self, snapshot: WebSnapshot) {
860        self.post(&json!({ "event": "web-snapshot", "data": { "snapshot": snapshot } }));
861        self.state().latest = Some(snapshot);
862    }
863
864    pub fn publish_mutation(&self, mutation: &WebMutation) {
865        self.post(&json!({ "event": "web-mutation", "data": { "mutation": mutation } }));
866    }
867
868    pub fn publish_closed(&self) {
869        self.post(&json!({ "event": "web-closed", "data": {} }));
870    }
871
872    /// Host: fulfill inbound `web-tool-call` frames. Returns a function that removes the handler.
873    pub fn set_tool_handler(&self, handler: WebToolHandler) -> Box<dyn FnOnce() + Send + Sync> {
874        let id = {
875            let mut state = self.state();
876            state.next_handler += 1;
877            let id = state.next_handler;
878            state.tool_handler = Some((id, handler));
879            id
880        };
881        let state = Arc::downgrade(&self.state);
882        Box::new(move || {
883            if let Some(state) = state.upgrade() {
884                let mut state = state.lock().unwrap_or_else(PoisonError::into_inner);
885                if state
886                    .tool_handler
887                    .as_ref()
888                    .is_some_and(|(current, _)| *current == id)
889                {
890                    state.tool_handler = None;
891                }
892            }
893        })
894    }
895
896    /// Any member: ask the host to run a page tool. Times out after `timeout_ms`
897    /// (30 seconds by default).
898    pub async fn invoke_tool(
899        &self,
900        name: &str,
901        params: Map<String, Value>,
902        timeout_ms: Option<u64>,
903    ) -> Result<String> {
904        let handler = self
905            .state()
906            .tool_handler
907            .as_ref()
908            .map(|(_, handler)| handler.clone());
909        if let Some(handler) = handler {
910            return handler(name.to_string(), params).await;
911        }
912        let id = uuid::Uuid::new_v4().to_string();
913        let (resolve, result) = oneshot::channel();
914        self.state().pending_tools.insert(id.clone(), resolve);
915        self.post(&json!({ "event": "web-tool-call", "data": { "id": id, "name": name, "params": params } }));
916        match tokio::time::timeout(Duration::from_millis(timeout_ms.unwrap_or(30_000)), result)
917            .await
918        {
919            Ok(Ok(result)) => result,
920            _ => {
921                self.state().pending_tools.remove(&id);
922                Err(Error::Message(format!("Tool timed out: {name}")))
923            }
924        }
925    }
926
927    pub fn handle_event(&self, packet: &Value) -> bool {
928        let data = &packet["data"];
929        match packet["event"].as_str().unwrap_or_default() {
930            "web-bootstrap" => {
931                let bootstrap: Option<BootstrapMeta> =
932                    serde_json::from_value(data["bootstrap"].clone()).ok();
933                self.state().bootstrap = bootstrap.clone();
934                if let Some(bootstrap) = bootstrap {
935                    self.hooks().on_bootstrap(self, &bootstrap);
936                }
937                true
938            }
939            "web-snapshot" => {
940                let snapshot: Option<WebSnapshot> =
941                    serde_json::from_value(data["snapshot"].clone()).ok();
942                self.state().latest = snapshot.clone();
943                if let Some(snapshot) = snapshot {
944                    self.hooks().on_snapshot(self, &snapshot);
945                }
946                true
947            }
948            "web-mutation" => {
949                if let Ok(mutation) =
950                    serde_json::from_value::<WebMutation>(data["mutation"].clone())
951                {
952                    self.hooks().on_mutation(self, &mutation);
953                }
954                true
955            }
956            "web-tool-call" => {
957                self.handle_tool_call(data);
958                true
959            }
960            "web-tool-result" => {
961                let Some(id) = data["id"].as_str().filter(|id| !id.is_empty()) else {
962                    return true;
963                };
964                let Some(pending) = self.state().pending_tools.remove(id) else {
965                    return true;
966                };
967                let result =
968                    if data["error"].is_null() || data["error"] == false || data["error"] == "" {
969                        Ok(match &data["result"] {
970                            Value::Null => String::new(),
971                            Value::String(result) => result.clone(),
972                            result => result.to_string(),
973                        })
974                    } else {
975                        Err(Error::Message(match &data["error"] {
976                            Value::String(error) => error.clone(),
977                            error => error.to_string(),
978                        }))
979                    };
980                let _ = pending.send(result);
981                true
982            }
983            "web-closed" | "server-closed" => {
984                self.hooks().on_closed(self);
985                true
986            }
987            _ => false,
988        }
989    }
990
991    fn handle_tool_call(&self, data: &Value) {
992        let id = data["id"].clone();
993        let Some(name) = data["name"]
994            .as_str()
995            .filter(|name| !name.is_empty())
996            .map(str::to_string)
997        else {
998            return;
999        };
1000        if id.is_null() || id == "" {
1001            return;
1002        }
1003        let Some(handler) = self
1004            .state()
1005            .tool_handler
1006            .as_ref()
1007            .map(|(_, handler)| handler.clone())
1008        else {
1009            return;
1010        };
1011        let params = data["params"].as_object().cloned().unwrap_or_default();
1012        let room = self.clone();
1013        tokio::spawn(async move {
1014            match handler(name, params).await {
1015                Ok(result) => room.post(
1016                    &json!({ "event": "web-tool-result", "data": { "id": id, "result": result } }),
1017                ),
1018                Err(error) => room.post(&json!({
1019                    "event": "web-tool-result",
1020                    "data": { "id": id, "error": error.to_string() },
1021                })),
1022            }
1023        });
1024    }
1025}
1026
1027struct WebHooks {
1028    room: Mutex<Option<WebRoom>>,
1029    hooks: Arc<dyn WebRoomHooks>,
1030}
1031
1032impl WebHooks {
1033    fn room(&self, room: &Room, state: &Value) -> WebRoom {
1034        let mut slot = self.room.lock().unwrap_or_else(PoisonError::into_inner);
1035        slot.get_or_insert_with(|| WebRoom::new(room.clone(), self.hooks.clone(), state, true))
1036            .clone()
1037    }
1038}
1039
1040impl Hooks for WebHooks {
1041    fn create_room(&self, room: &Room, state: &Value) {
1042        let created = self.room(room, state);
1043        if let Ok(bootstrap) = serde_json::from_value::<BootstrapMeta>(state["bootstrap"].clone()) {
1044            created.ingest_bootstrap(bootstrap);
1045        }
1046        if let Ok(snapshot) = serde_json::from_value::<WebSnapshot>(state["snapshot"].clone()) {
1047            created.ingest_snapshot(snapshot);
1048        }
1049    }
1050
1051    fn on_event(&self, room: &Room, packet: &Value) -> bool {
1052        self.room(room, &Value::Null).handle_event(packet)
1053    }
1054
1055    fn on_presence(&self, room: &Room) {
1056        let room = self.room(room, &Value::Null);
1057        room.hooks().on_presence(&room);
1058    }
1059
1060    fn on_closed(&self, room: &Room, _reason: Option<&str>) {
1061        let room = self.room(room, &Value::Null);
1062        room.hooks().on_closed(&room);
1063    }
1064}
1065
1066/// Connect to a web room. `target` is an access code (viewer joining a shared
1067/// page) or a room reference (host opening its own room).
1068pub async fn connect_web_room(
1069    authorization: &CredentialsOrApiKey,
1070    target: &WebTarget,
1071    hooks: Option<Arc<dyn WebRoomHooks>>,
1072) -> Result<(WebRoom, Presence)> {
1073    let auth = match target {
1074        WebTarget::Code { code } => Authorization::AccessCode {
1075            authorization: authorization.clone(),
1076            access_code: code.clone(),
1077        },
1078        WebTarget::Reference { reference } => Authorization::Server {
1079            authorization: authorization.clone(),
1080            server: reference.clone(),
1081            group: None,
1082        },
1083    };
1084    let web_hooks = Arc::new(WebHooks {
1085        room: Mutex::new(None),
1086        hooks: hooks.unwrap_or_else(|| Arc::new(())),
1087    });
1088    let me = connect(
1089        auth,
1090        &format!("{}/extensions/web/live", super::get_url()),
1091        web_hooks.clone(),
1092    )
1093    .await?;
1094    let room = web_hooks.room(me.room(), &Value::Null);
1095    room.hooks().on_presence(&room);
1096    Ok((room, me))
1097}