Skip to main content

indicatrix_web_compute/
lib.rs

1//! The Web Worker entry point of the indicatrix browser app.
2//!
3//! Trunk builds this crate as a worker (`data-type="worker"` in
4//! `apps/indicatrix-web/index.html`): wasm-bindgen's `no-modules` output plus a loader
5//! shim, `indicatrix-web-compute_loader.js`, which the page starts with
6//! `new Worker(...)` (see `indicatrix_web_core::WORKER_LOADER_URL`).
7//!
8//! On start the Worker installs its `onmessage` handler, then posts `Loaded`. Each
9//! message is a postcard-encoded `ToWorker` in a transferred `ArrayBuffer`; it is
10//! handed to `indicatrix_web_core::worker::WorkerHandler`, which owns every decision
11//! (and the cached scene, plane arena and HDR map, kept across chunks), and the reply
12//! goes back the same way. A long solve job's progress reports are posted as they are
13//! emitted, before the reply. Time is `performance.now()` from the Worker's own global.
14//!
15//! Like `apps/indicatrix-web`, everything is `#[cfg(target_arch = "wasm32")]`, so a
16//! native build of the workspace compiles this crate to nothing.
17
18#[cfg(target_arch = "wasm32")]
19mod entry {
20    use std::cell::{Cell, RefCell};
21
22    use indicatrix_web_core::{
23        protocol::{FromWorker, decode_to_worker, encode_from_worker},
24        worker::{CancelProbe, WorkerHandler},
25    };
26    use js_sys::{Array, ArrayBuffer, Uint8Array};
27    use wasm_bindgen::{JsCast, closure::Closure, prelude::wasm_bindgen};
28    use web_sys::{DedicatedWorkerGlobalScope, MessageEvent};
29
30    thread_local! {
31        static HANDLER: RefCell<WorkerHandler> = RefCell::new(WorkerHandler::new());
32        /// Whether this Worker can make a synchronous request to a `blob:` URL it made
33        /// itself; found out the first time a request to the page's cancel URL fails.
34        static OWN_BLOB_REQUEST_WORKS: Cell<Option<bool>> = const { Cell::new(None) };
35    }
36
37    fn scope() -> DedicatedWorkerGlobalScope {
38        js_sys::global().unchecked_into()
39    }
40
41    fn now_ms() -> f64 {
42        scope().performance().map_or(0.0, |p| p.now())
43    }
44
45    fn post(message: &FromWorker) {
46        let bytes = match encode_from_worker(message) {
47            Ok(bytes) => bytes,
48            Err(error) => {
49                web_sys::console::error_1(&error.into());
50                return;
51            }
52        };
53        let Ok(length) = u32::try_from(bytes.len()) else {
54            web_sys::console::error_1(&"indicatrix worker: reply over 4 GiB".into());
55            return;
56        };
57        let array = Uint8Array::new_with_length(length);
58        array.copy_from(&bytes);
59        let buffer = array.buffer();
60        if let Err(error) = scope().post_message_with_transfer(&buffer, &Array::of1(&buffer)) {
61            web_sys::console::error_2(&"indicatrix worker: postMessage failed".into(), &error);
62        }
63    }
64
65    /// How one synchronous `GET` of a `blob:` URL ended.
66    enum Attempt {
67        /// The URL was served.
68        Served,
69        /// The request was made and failed (a revoked URL fails like this).
70        Failed,
71        /// No request could be made, or it reported no status at all.
72        CouldNotRun,
73    }
74
75    fn attempt(url: &str) -> Attempt {
76        let Ok(request) = web_sys::XmlHttpRequest::new() else {
77            return Attempt::CouldNotRun;
78        };
79        if request.open_with_async("GET", url, false).is_err() {
80            return Attempt::CouldNotRun;
81        }
82        match request.send() {
83            Ok(()) => match request.status() {
84                Ok(0) | Err(_) => Attempt::CouldNotRun,
85                Ok(_) => Attempt::Served,
86            },
87            Err(_) => Attempt::Failed,
88        }
89    }
90
91    /// Whether this Worker can request a `blob:` URL at all: makes one of its own,
92    /// requests it and revokes it. Asked once and remembered.
93    fn own_blob_request_works() -> bool {
94        if let Some(known) = OWN_BLOB_REQUEST_WORKS.with(Cell::get) {
95            return known;
96        }
97        let works = web_sys::Blob::new()
98            .ok()
99            .and_then(|blob| web_sys::Url::create_object_url_with_blob(&blob).ok())
100            .is_some_and(|own| {
101                let served = matches!(attempt(&own), Attempt::Served);
102                let _ = web_sys::Url::revoke_object_url(&own);
103                served
104            });
105        OWN_BLOB_REQUEST_WORKS.with(|cell| cell.set(Some(works)));
106        works
107    }
108
109    /// What the page's cancel URL says about the running job: `url` is a `blob:` URL the
110    /// page made for it and revokes to cancel it (`ToWorker::WatchCancel`). A Worker
111    /// cannot read a message while it computes, but it can make a SYNCHRONOUS request,
112    /// and a request for a revoked `blob:` URL fails.
113    ///
114    /// A strict content-security policy (`connect-src` without `blob:`) makes the same
115    /// request fail, so a failure only counts as a revocation when a URL this Worker made
116    /// itself can be requested. Anything else that stops the probe running (no request
117    /// object, `open` refused, no status in the answer) is `Unavailable`: the job then
118    /// carries on instead of being stopped by a probe that could not run.
119    fn cancel_url_probe(url: &str) -> CancelProbe {
120        match attempt(url) {
121            Attempt::Served => CancelProbe::Live,
122            Attempt::CouldNotRun => CancelProbe::Unavailable,
123            Attempt::Failed => {
124                if own_blob_request_works() {
125                    CancelProbe::Revoked
126                } else {
127                    CancelProbe::Unavailable
128                }
129            }
130        }
131    }
132
133    fn handle_bytes(bytes: &[u8]) -> Option<FromWorker> {
134        match decode_to_worker(bytes) {
135            // A long job (an Optimize or Retarget search, a render chunk) may post its
136            // progress while it computes: the Worker cannot read messages then, but it
137            // can post them, and it can look at its cancel URL between tier decisions
138            // (between row groups).
139            Ok(message) => HANDLER.with(|handler| {
140                handler.borrow_mut().handle_probed(
141                    message,
142                    &now_ms,
143                    &|streamed| post(&streamed),
144                    &cancel_url_probe,
145                )
146            }),
147            Err(message) => Some(FromWorker::Error { message }),
148        }
149    }
150
151    fn on_message(event: &MessageEvent) {
152        let reply = event.data().dyn_into::<ArrayBuffer>().map_or_else(
153            |_| {
154                Some(FromWorker::Error {
155                    message: "a worker message was not an ArrayBuffer".to_string(),
156                })
157            },
158            |buffer| handle_bytes(&Uint8Array::new(&buffer).to_vec()),
159        );
160        if let Some(reply) = reply {
161            post(&reply);
162        }
163    }
164
165    /// Runs when the module is instantiated: hook up `onmessage`, then say so.
166    #[wasm_bindgen(start)]
167    pub fn start() {
168        console_error_panic_hook::set_once();
169        let closure = Closure::<dyn FnMut(MessageEvent)>::new(|event: MessageEvent| {
170            on_message(&event);
171        });
172        scope().set_onmessage(Some(closure.as_ref().unchecked_ref()));
173        // The handler lives as long as the Worker.
174        closure.forget();
175        post(&WorkerHandler::loaded_message());
176    }
177}