Skip to main content

mln_runtime/
runtime.rs

1//! A runtime: the thread that its maps live on, and the file sources, cache
2//! and offline regions that they share.
3
4use std::cell::OnceCell;
5use std::collections::BTreeMap;
6use std::path::{Path, PathBuf};
7use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
8use std::sync::{Arc, OnceLock};
9use std::thread::ThreadId;
10
11use mln_renderer::Registry;
12use mln_renderer::text::font_face_engine::FontFaceEngine;
13use mln_storage::http_header_transform::{HttpHeaderTransform, HttpHeaders};
14use mln_storage::network_status::NetworkStatus;
15use mln_storage::resource::Kind;
16use mln_storage::resource_transform::{FinishedCallback, ResourceTransform};
17use mln_storage::{FileSource, Loader, OnlineFileSource, ResourceOptions};
18#[cfg(not(target_family = "wasm"))]
19use mln_storage_offline::RegionDatabase;
20use mln_text::GlyphCache;
21use mln_util::error::Error;
22use mln_util::logging::{Event, Log};
23use mln_util::pool::Pool;
24use mln_util::queue::{Queue, TimedTask};
25use mln_util::thread::Joined;
26use mln_util::time::Instant;
27use parking_lot::Mutex;
28
29use crate::completion::{Completion, Resolver};
30use crate::event::{EventHandler, RuntimeEvent};
31use crate::map::{Applied, Map, MapEntry, MapId, MapOptions, MapShared, Published};
32use crate::offline::Offline;
33use crate::resources::{CacheDatabaseOperation, ProviderFileSource, ResourceHooks, ResourceProvider};
34
35/// Where a runtime keeps its assets and its cache, and the network status
36/// its requests follow.
37#[derive(Clone, Debug, Default, PartialEq, Eq)]
38pub struct RuntimeOptions {
39    /// The directory that `asset://` URLs load from. `None` uses the working
40    /// directory, or on Android the app's assets, which
41    /// `mln_storage::android::init` gives the library.
42    pub asset_path: Option<PathBuf>,
43    /// The cache database file, which holds the ambient cache and the offline
44    /// regions. Its directory must be writable. `None` keeps the cache in
45    /// memory.
46    pub cache_path: Option<PathBuf>,
47    /// The network status that the runtime's network requests follow. `None`
48    /// gives the runtime one of its own, which stays online.
49    pub network_status: Option<Arc<NetworkStatus>>,
50    /// In the browser, where the browser's fetch looks for a response that
51    /// the host fetched ahead before it fetches a whole resource:
52    /// `take(url)` returns a promise of the `Response` fetched for exactly
53    /// `url`, at most once for each, or undefined. A promise that rejects
54    /// is fetched again. `None` fetches every resource.
55    #[cfg(target_family = "wasm")]
56    pub fetch_preloads: Option<js_sys::Function>,
57}
58
59/// A runtime: a thread of its own that holds maps, and the resource loading,
60/// cache and offline regions that they share.
61///
62/// Every call returns at once. Commands run on the runtime's thread in the
63/// order they were sent, across the runtime and all its maps, and report
64/// through a [`Completion`]. `Clone` is another handle to the same runtime,
65/// and any thread may use one.
66///
67/// The runtime lives until [`release`](Self::release) or
68/// [`dispose`](Self::dispose), or until its last handle and its last map
69/// are dropped. A handler or provider that holds a handle keeps it alive
70/// until then.
71///
72/// Unless the runtime was released or disposed, the drop of the last of its
73/// handles and maps returns once the runtime's threads have ended: its own
74/// and its file sources'. A worker that loads over HTTP and is stuck in a
75/// name lookup or a TCP connect is waited for up to a second, then left to
76/// end alone. The host's handlers, providers and transforms that the runtime
77/// holds are dropped on its thread meanwhile, so they mustn't wait for the
78/// thread that drops it. A drop on a thread of the library, such as in a
79/// handler or callback that the library runs, doesn't wait: it leaves the
80/// runtime's threads to end alone.
81///
82/// A panic in the work of the runtime or its maps is a bug in the library,
83/// and stops the runtime instead of the process. It logs the panic, the
84/// command that panicked fails with
85/// [`ErrorKind::Native`](mln_util::ErrorKind), those that waited are
86/// cancelled, and the commands sent to the runtime and its maps after fail
87/// with `ErrorKind::Native`. Release its maps and the runtime then.
88#[derive(Clone)]
89pub struct Runtime {
90    pub(crate) shared: Arc<RuntimeShared>,
91}
92
93impl std::fmt::Debug for Runtime {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        f.debug_struct("Runtime").field("thread", &self.shared.thread).finish()
96    }
97}
98
99struct Lifecycle {
100    released: bool,
101    live_maps: usize,
102    shut_down: bool,
103}
104
105pub(crate) struct RuntimeShared {
106    queue: CoreQueue,
107    /// The tasks that [`post`](Self::post) sent and the thread hasn't run.
108    queued: Arc<AtomicUsize>,
109    thread: ThreadId,
110    lifecycle: Mutex<Lifecycle>,
111    /// Why the runtime stopped, once a panic in its work stopped it.
112    failure: Arc<OnceLock<Error>>,
113    next_map_id: AtomicU64,
114    /// The glyphs that the renderers of the runtime's maps parse, which they
115    /// share.
116    pub(crate) glyph_cache: Arc<GlyphCache>,
117    /// What the renderers of the runtime's maps load font faces with: in
118    /// the browser, the shaper module, which loads the first time a style
119    /// declares font faces.
120    pub(crate) font_face_engine: Arc<dyn FontFaceEngine>,
121    pub(crate) registry: Arc<Registry>,
122    /// Where the runtime's background work runs: its maps', and their
123    /// render sessions'.
124    pub(crate) pool: Pool,
125    /// The runtime's thread, which the drop waits for after the shutdown
126    /// unless a release or disposal detached it, except in the browser,
127    /// where the thread is the host's.
128    thread_end: Option<Joined>,
129}
130
131impl RuntimeShared {
132    /// Runs `task` on the runtime's thread, after everything sent before it,
133    /// in the burst of the tasks queued with it.
134    pub(crate) fn post(&self, task: impl FnOnce(&mut RuntimeCore, &mut Outbox) + Send + 'static) {
135        self.queued.fetch_add(1, Ordering::SeqCst);
136        self.queue.post(move |core| run(core, task, true));
137    }
138
139    /// Runs `task` with `value` on the runtime's thread, after everything
140    /// sent before it, or `stopped` with `value` there instead once the
141    /// runtime has let go of its state, for work that ends the same either
142    /// way, such as a release.
143    pub(crate) fn post_or_stopped<V: Send + 'static>(
144        &self,
145        value: V,
146        task: impl FnOnce(&mut RuntimeCore, &mut Outbox, V) + Send + 'static,
147        stopped: impl FnOnce(V) + Send + 'static,
148    ) {
149        self.queued.fetch_add(1, Ordering::SeqCst);
150        self.queue.post(move |core| {
151            if core.is_some() {
152                run(core, move |core, outbox| task(core, outbox, value), true);
153            } else {
154                stopped(value);
155            }
156        });
157    }
158
159    /// Runs `task` on the runtime's thread, after everything sent before it,
160    /// outside the bursts of the tasks that [`post`](Self::post) sends: it
161    /// neither starts one nor counts in one.
162    pub(crate) fn post_apart(&self, task: impl FnOnce(&mut RuntimeCore, &mut Outbox) + Send + 'static) {
163        post(&self.queue, task);
164    }
165
166    /// Runs `task` with `value` on the runtime's thread, after everything
167    /// sent before it, or `instead` with `value` on this thread when the
168    /// runtime has shut down, so that what must happen either way isn't lost
169    /// with the runtime's queue.
170    pub(crate) fn post_or<V: Send + 'static>(
171        &self,
172        value: V,
173        task: impl FnOnce(&mut RuntimeCore, &mut Outbox, V) + Send + 'static,
174        instead: impl FnOnce(V),
175    ) {
176        // Posting with the lock held orders the task before a shutdown.
177        let lifecycle = self.lifecycle.lock();
178        if lifecycle.shut_down {
179            drop(lifecycle);
180            instead(value);
181        } else {
182            self.post(move |core, outbox| task(core, outbox, value));
183        }
184    }
185
186    pub(crate) fn thread(&self) -> ThreadId {
187        self.thread
188    }
189
190    /// A completion that the runtime's thread resolves.
191    pub(crate) fn completion<T: Send + 'static>(&self) -> (Completion<T>, Resolver<T>) {
192        Completion::new(Some(self.thread))
193    }
194
195    /// Leaves the runtime's thread to end alone, for a release or disposal,
196    /// which don't wait for it.
197    fn detach_thread(&self) {
198        if let Some(thread) = &self.thread_end {
199            thread.detach();
200        }
201    }
202
203    fn check_live(&self) -> Result<(), Error> {
204        if self.lifecycle.lock().released {
205            return Err(released());
206        }
207        self.check_running()
208    }
209
210    /// Fails once a panic in the runtime's work stopped it.
211    pub(crate) fn check_running(&self) -> Result<(), Error> {
212        self.failure.get().map_or(Ok(()), |failure| Err(failure.clone()))
213    }
214
215    /// A map of the runtime was released or dropped. A disposed runtime shuts
216    /// down with its last map.
217    pub(crate) fn map_released(&self) {
218        let shut_down = {
219            let mut lifecycle = self.lifecycle.lock();
220            lifecycle.live_maps -= 1;
221            let shut_down = lifecycle.released && lifecycle.live_maps == 0 && !lifecycle.shut_down;
222            lifecycle.shut_down |= shut_down;
223            shut_down
224        };
225        if shut_down {
226            self.shut_down(None);
227        }
228    }
229
230    /// Tears the runtime down on its thread, after the commands sent before.
231    fn shut_down(&self, done: Option<Resolver<()>>) {
232        let queue = self.queue.clone();
233        self.queue.post(move |core| {
234            // Dropping the database waits for its work, whose results queue
235            // up behind this task, so they resolve before `done`.
236            drop(core.take());
237            if let Some(done) = done {
238                queue.post(move |_| done.resolve(Ok(())));
239            }
240            queue.stop();
241        });
242    }
243}
244
245impl Drop for RuntimeShared {
246    /// Shuts the runtime down unless it has, then waits for its thread as
247    /// `thread_end` drops.
248    fn drop(&mut self) {
249        if !self.lifecycle.get_mut().shut_down {
250            self.shut_down(None);
251        }
252    }
253}
254
255#[cfg(target_family = "wasm")]
256fn no_database() -> Error {
257    Error::unsupported("the browser build has no cache database: the browser caches the requests")
258}
259
260#[cfg(not(target_family = "wasm"))]
261fn font_face_engine() -> Arc<dyn FontFaceEngine> {
262    mln_renderer::text::font_face_engine::default_engine()
263}
264
265#[cfg(target_family = "wasm")]
266fn font_face_engine() -> Arc<dyn FontFaceEngine> {
267    Arc::new(mln_web_host::shaper::ShaperModuleEngine)
268}
269
270/// The most worker threads of a runtime's pool.
271#[cfg(not(target_family = "wasm"))]
272const POOL_THREADS: usize = 4;
273
274/// The pool of a new runtime.
275#[cfg(not(target_family = "wasm"))]
276fn runtime_pool() -> Pool {
277    Pool::new(POOL_THREADS)
278}
279
280/// The pool of a new runtime: in the browser, one without threads, which
281/// the instance's pump runs.
282#[cfg(target_family = "wasm")]
283fn runtime_pool() -> Pool {
284    Pool::local()
285}
286
287fn released() -> Error {
288    Error::invalid_state("the runtime was released")
289}
290
291/// The work of a runtime's thread, which owns the runtime's state: `None`
292/// once the runtime shut down.
293pub(crate) type CoreQueue = Queue<Option<RuntimeCore>>;
294
295/// Where a runtime's background work runs, and where its results come back.
296#[derive(Clone)]
297pub(crate) struct Background {
298    pub(crate) pool: Pool,
299    pub(crate) queue: CoreQueue,
300}
301
302/// Posts `task` to the runtime thread that runs `queue`.
303pub(crate) fn post(queue: &CoreQueue, task: impl FnOnce(&mut RuntimeCore, &mut Outbox) + Send + 'static) {
304    queue.post(move |core| run(core, task, false));
305}
306
307/// Posts `task` to the runtime thread that runs `queue`, to run once
308/// `deadline` passed.
309pub(crate) fn post_at(
310    queue: &CoreQueue,
311    deadline: Instant,
312    task: impl FnOnce(&mut RuntimeCore, &mut Outbox) + Send + 'static,
313) -> TimedTask {
314    queue.post_at(deadline, move |core| run(core, task, false))
315}
316
317/// Runs `task` on the runtime's state, then delivers what it sends to the
318/// host. A task that comes after the runtime shut down drops, which cancels
319/// its completions. A task that [`RuntimeShared::post`] sent runs in its
320/// burst.
321fn run(core: &mut Option<RuntimeCore>, task: impl FnOnce(&mut RuntimeCore, &mut Outbox), in_burst: bool) {
322    let Some(state) = core.as_mut() else { return };
323    let mut outbox = Outbox { deliveries: std::mem::take(&mut state.spare_deliveries) };
324    let ran = mln_util::panic::catch(|| {
325        if in_burst {
326            state.begin_burst_task();
327        }
328        task(state, &mut outbox);
329        if in_burst {
330            state.end_burst_task(&mut outbox);
331        }
332    });
333    match ran {
334        Ok(()) => state.spare_deliveries = outbox.deliver(),
335        Err(message) => {
336            fail(core, &message);
337            outbox.deliver();
338        }
339    }
340}
341
342/// Stops the runtime after a panic in its work, a bug in the library: its
343/// state drops, as at a shutdown, which cancels the completions of the
344/// commands that it held, and the commands sent from now on fail.
345fn fail(core: &mut Option<RuntimeCore>, message: &str) {
346    let Some(state) = core.take() else { return };
347    let error = Error::native(format!("the runtime stopped after a panic in the library: {message}"));
348    Log::error(Event::Crash, &error.message);
349    let _ = state.failure.set(error);
350    // The panic may have left the state half-changed, so its drop may panic
351    // too.
352    let _ = mln_util::panic::catch(move || drop(state));
353}
354
355/// What a task sends to the host: event batches and results, in order. They
356/// go out once the task is done with the runtime's state, so host code that
357/// runs never finds it borrowed.
358#[derive(Default)]
359pub(crate) struct Outbox {
360    deliveries: Vec<Box<dyn FnOnce()>>,
361}
362
363impl Outbox {
364    pub(crate) fn push(&mut self, delivery: impl FnOnce() + 'static) {
365        self.deliveries.push(Box::new(delivery));
366    }
367
368    pub(crate) fn resolve<T: 'static>(&mut self, resolver: Resolver<T>, result: Result<T, Error>) {
369        // A success whose result is discarded runs nothing.
370        if resolver.discards() && result.is_ok() {
371            return resolver.resolve(result);
372        }
373        self.push(move || resolver.resolve(result));
374    }
375
376    /// Delivers what the outbox holds, and returns its emptied buffer.
377    pub(crate) fn deliver(mut self) -> Vec<Box<dyn FnOnce()>> {
378        for delivery in self.deliveries.drain(..) {
379            delivery();
380        }
381        self.deliveries
382    }
383}
384
385/// The runtime's state, on its thread.
386pub(crate) struct RuntimeCore {
387    /// Declared first, so the maps go before the file sources they use.
388    pub(crate) maps: BTreeMap<MapId, MapEntry>,
389    pub(crate) event_handler: Option<EventHandler>,
390    hooks: Arc<ResourceHooks>,
391    resource_options: ResourceOptions,
392    /// The runtime's file sources, made at their first use and held for the
393    /// runtime's life, so that each map, and each transform, finds the same
394    /// ones. A runtime that never loads a resource starts none of their
395    /// threads.
396    loader: OnceCell<Arc<dyn FileSource>>,
397    #[cfg(not(target_family = "wasm"))]
398    database: OnceCell<Arc<RegionDatabase>>,
399    /// The library's own network loading, behind the host's provider.
400    online: OnceCell<Arc<OnlineFileSource>>,
401    /// What the library's own network loading follows and, in the browser,
402    /// looks in first.
403    network_options: NetworkOptions,
404    network: OnceCell<Arc<dyn FileSource>>,
405    /// The runtime's thread's work.
406    pub(crate) queue: CoreQueue,
407    pub(crate) registry: Arc<Registry>,
408    /// [`RuntimeShared::pool`].
409    pub(crate) pool: Pool,
410    /// [`RuntimeShared::queued`].
411    queued: Arc<AtomicUsize>,
412    /// [`RuntimeShared::failure`].
413    failure: Arc<OnceLock<Error>>,
414    /// The tasks of the burst in progress that haven't finished.
415    burst_left: usize,
416    /// Whether the maps hold their updates back for the burst.
417    holding: bool,
418    /// The buffer of the outbox that the next task takes, so that each task
419    /// reuses the last one's.
420    spare_deliveries: Vec<Box<dyn FnOnce()>>,
421}
422
423/// What the library's own network loading of a runtime follows.
424struct NetworkOptions {
425    status: Arc<NetworkStatus>,
426    /// [`RuntimeOptions::fetch_preloads`].
427    #[cfg(target_family = "wasm")]
428    fetch_preloads: Option<js_sys::Function>,
429}
430
431impl RuntimeCore {
432    fn new(
433        resource_options: ResourceOptions,
434        network_options: NetworkOptions,
435        queue: CoreQueue,
436        queued: Arc<AtomicUsize>,
437        failure: Arc<OnceLock<Error>>,
438        registry: Arc<Registry>,
439        pool: Pool,
440    ) -> Self {
441        RuntimeCore {
442            maps: BTreeMap::new(),
443            event_handler: None,
444            hooks: Arc::new(ResourceHooks::default()),
445            resource_options,
446            loader: OnceCell::new(),
447            #[cfg(not(target_family = "wasm"))]
448            database: OnceCell::new(),
449            online: OnceCell::new(),
450            network_options,
451            network: OnceCell::new(),
452            queue,
453            registry,
454            pool,
455            queued,
456            failure,
457            burst_left: 0,
458            holding: false,
459            spare_deliveries: Vec::new(),
460        }
461    }
462
463    /// Starts a task that [`RuntimeShared::post`] sent. The tasks that were
464    /// queued when a burst's first one starts make up the burst, and while a
465    /// burst of more than one runs, the maps hold their updates back, so that
466    /// a render session draws what the whole burst changed in one frame. A
467    /// task sent during a burst is in the next one, so a host that keeps
468    /// sending holds no update back for longer than a burst.
469    fn begin_burst_task(&mut self) {
470        let queued = self.queued.fetch_sub(1, Ordering::SeqCst);
471        if self.burst_left == 0 {
472            self.burst_left = queued;
473            self.holding = queued > 1;
474            if self.holding {
475                self.maps.values_mut().for_each(|entry| entry.core.hold_updates());
476            }
477        }
478    }
479
480    /// Ends a task of the burst, and after its last, shows what the maps
481    /// held back, and tells their sessions what ran meanwhile.
482    fn end_burst_task(&mut self, outbox: &mut Outbox) {
483        self.burst_left = self.burst_left.saturating_sub(1);
484        if self.burst_left > 0 || !std::mem::take(&mut self.holding) {
485            return;
486        }
487        let ids: Vec<MapId> = self.maps.keys().copied().collect();
488        for id in ids {
489            if let Some(entry) = self.maps.get_mut(&id) {
490                entry.core.release_updates();
491            }
492            crate::map::flush(self, id, outbox);
493            if let Some(entry) = self.maps.get_mut(&id) {
494                crate::map::report_held(entry);
495            }
496        }
497    }
498
499    /// Whether the maps hold their updates back for a burst.
500    pub(crate) fn holding_updates(&self) -> bool {
501        self.holding
502    }
503
504    /// The loader that the runtime's maps share.
505    pub(crate) fn loader(&self) -> &Arc<dyn FileSource> {
506        self.loader.get_or_init(|| {
507            let builder = Loader::builder(&self.pool)
508                .asset_path(&self.resource_options.asset_path)
509                .network(Arc::clone(self.network()));
510            #[cfg(not(target_family = "wasm"))]
511            let builder = builder.database(Arc::<RegionDatabase>::clone(self.database()));
512            Arc::new(builder.build())
513        })
514    }
515
516    /// The library's own network loading.
517    fn online(&self) -> &Arc<OnlineFileSource> {
518        self.online.get_or_init(|| {
519            #[cfg(not(target_family = "wasm"))]
520            let online = OnlineFileSource::new(Arc::clone(&self.network_options.status));
521            #[cfg(target_family = "wasm")]
522            let online = crate::web::online(
523                Arc::clone(&self.network_options.status),
524                self.network_options.fetch_preloads.clone(),
525            );
526            Arc::new(online)
527        })
528    }
529
530    /// The runtime's network: the host's resource provider, in front of the
531    /// library's own loading.
532    fn network(&self) -> &Arc<dyn FileSource> {
533        self.network
534            .get_or_init(|| Arc::new(ProviderFileSource::new(Arc::clone(self.online()), Arc::clone(&self.hooks))))
535    }
536
537    /// Where the runtime's background work runs, and its results come back.
538    pub(crate) fn background(&self) -> Background {
539        Background { pool: self.pool.clone(), queue: self.queue.clone() }
540    }
541
542    /// Sends `events` to the event handler.
543    pub(crate) fn send_events(&self, events: Vec<RuntimeEvent>, outbox: &mut Outbox) {
544        if events.is_empty() {
545            return;
546        }
547        if let Some(handler) = self.event_handler.clone() {
548            outbox.push(move || handler(&events));
549        }
550    }
551
552    /// The cache database, which every runtime but the browser build's has.
553    #[cfg(not(target_family = "wasm"))]
554    pub(crate) fn database(&self) -> &Arc<RegionDatabase> {
555        self.database.get_or_init(|| {
556            Arc::new(mln_storage_offline::region_database(
557                &self.resource_options.cache_path,
558                Some(Arc::clone(self.network())),
559                Arc::clone(self.registry.style()),
560            ))
561        })
562    }
563}
564
565/// Delivers a database result on the runtime's thread, so it keeps its
566/// place among the runtime's other results and events. It needs no runtime
567/// state, so a result that arrives while the runtime shuts down, which waits
568/// for the database's work, still resolves rather than being cancelled.
569#[cfg(not(target_family = "wasm"))]
570pub(crate) fn reply_on<T: Send + 'static, E: Into<Error>>(
571    queue: CoreQueue,
572    resolver: Resolver<T>,
573) -> impl FnOnce(Result<T, E>) + Send + 'static {
574    move |result| {
575        let result = result.map_err(Into::into);
576        queue.post(move |_| resolver.resolve(result));
577    }
578}
579
580/// The runtime's resource options, with the cache file created when there
581/// is one, so that a path the runtime can't use fails here.
582fn resource_options(options: &RuntimeOptions) -> Result<ResourceOptions, Error> {
583    let mut resource_options = ResourceOptions::default();
584    if let Some(asset_path) = &options.asset_path {
585        resource_options.asset_path = utf8(asset_path, "asset path")?.to_owned();
586    }
587    #[cfg(target_os = "android")]
588    if options.asset_path.is_none() {
589        resource_options.asset_path = mln_storage::android::APP_ASSETS.to_owned();
590    }
591    if options.cache_path.is_some() && cfg!(target_family = "wasm") {
592        return Err(Error::unsupported("the browser build has no cache database: the browser caches the requests"));
593    }
594    if let Some(cache_path) = &options.cache_path {
595        let path = utf8(cache_path, "cache path")?;
596        std::fs::OpenOptions::new()
597            .read(true)
598            .write(true)
599            .create(true)
600            .truncate(false)
601            .open(cache_path)
602            .map_err(|error| Error::invalid_argument(format!("can't open the cache database {path}: {error}")))?;
603        resource_options.cache_path = path.to_owned();
604    }
605    Ok(resource_options)
606}
607
608fn utf8<'a>(path: &'a Path, what: &str) -> Result<&'a str, Error> {
609    path.to_str().ok_or_else(|| Error::invalid_argument(format!("the {what} {} isn't UTF-8", path.display())))
610}
611
612impl Runtime {
613    /// Starts a runtime and its thread, with the built-in registrations.
614    ///
615    /// In the browser, the runtime's thread is the one that calls this, which
616    /// a wasm instance has only one of, and the runtime never blocks it: its
617    /// commands run in tasks of their own on the browser's event loop
618    /// (`mln_web_host::pump`), never inside the call that sends them.
619    ///
620    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) when the
621    /// cache database file can't be opened or created, and in the browser
622    /// with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a cache path.
623    pub fn new(options: &RuntimeOptions) -> Result<Runtime, Error> {
624        Self::with_registry(options, Registry::with_builtins())
625    }
626
627    /// Starts a runtime and its thread, whose maps parse their styles
628    /// against `registry`, and whose renderers and tile workers use it. In
629    /// the browser, the tile workers' Web Workers must serve with registries
630    /// filled by the same calls (`mln_web_host::tile_worker::serve`).
631    ///
632    /// Fails as [`new`](Self::new) does.
633    pub fn with_registry(options: &RuntimeOptions, registry: Arc<Registry>) -> Result<Runtime, Error> {
634        let resource_options = resource_options(options)?;
635        let network_options = NetworkOptions {
636            status: options.network_status.clone().unwrap_or_default(),
637            #[cfg(target_family = "wasm")]
638            fetch_preloads: options.fetch_preloads.clone(),
639        };
640        let queued = Arc::new(AtomicUsize::new(0));
641        let failure = Arc::new(OnceLock::new());
642        let queue = CoreQueue::default();
643        let pool = runtime_pool();
644        // A panic in a task of the runtime's maps or their sessions stops the
645        // runtime, as one on its thread does.
646        let failing = queue.downgrade();
647        pool.set_panic_handler(Some(Arc::new(move |message| {
648            if let Some(queue) = failing.upgrade() {
649                queue.post(move |core| fail(core, &message));
650            }
651        })));
652        let (thread, thread_end) = Self::start(
653            resource_options,
654            network_options,
655            queue.clone(),
656            Arc::clone(&queued),
657            Arc::clone(&failure),
658            Arc::clone(&registry),
659            pool.clone(),
660        )?;
661        Ok(Runtime {
662            shared: Arc::new(RuntimeShared {
663                queue,
664                queued,
665                thread,
666                lifecycle: Mutex::new(Lifecycle { released: false, live_maps: 0, shut_down: false }),
667                failure,
668                next_map_id: AtomicU64::new(1),
669                glyph_cache: Arc::default(),
670                font_face_engine: font_face_engine(),
671                registry,
672                pool,
673                thread_end,
674            }),
675        })
676    }
677
678    /// Builds the runtime's state on a thread of its own, which owns it and
679    /// runs `queue` until the runtime shuts down.
680    #[cfg(not(target_family = "wasm"))]
681    fn start(
682        resource_options: ResourceOptions,
683        network_options: NetworkOptions,
684        queue: CoreQueue,
685        queued: Arc<AtomicUsize>,
686        failure: Arc<OnceLock<Error>>,
687        registry: Arc<Registry>,
688        pool: Pool,
689    ) -> Result<(ThreadId, Option<Joined>), Error> {
690        let thread = mln_util::thread::spawn("Runtime", move || {
691            let own_pool = pool.clone();
692            let mut core = Some(RuntimeCore::new(
693                resource_options,
694                network_options,
695                queue.clone(),
696                queued,
697                failure,
698                registry,
699                pool,
700            ));
701            queue.run(&mut core);
702            // What comes after the shutdown drops at once, so tasks that hold
703            // the queue can't keep it alive.
704            queue.close();
705            drop(core);
706            // Nothing of the runtime runs after this, but a render session
707            // that kept its graphics forgot its renderer, which holds the
708            // pool: its workers stop here rather than with the last handle.
709            own_pool.shut_down();
710        })
711        .map_err(|error| Error::native(format!("can't start the runtime's thread: {error}")))?;
712        let thread_id = thread.thread().id();
713        // The thread ends by itself once the runtime shuts down.
714        Ok((thread_id, Some(Joined::new(thread))))
715    }
716
717    /// Builds the runtime's state on this thread, where the instance's pump
718    /// runs `queue` with it until the runtime shuts down.
719    #[cfg(target_family = "wasm")]
720    #[expect(clippy::unnecessary_wraps, reason = "the threads of other builds can fail to start")]
721    fn start(
722        resource_options: ResourceOptions,
723        network_options: NetworkOptions,
724        queue: CoreQueue,
725        queued: Arc<AtomicUsize>,
726        failure: Arc<OnceLock<Error>>,
727        registry: Arc<Registry>,
728        pool: Pool,
729    ) -> Result<(ThreadId, Option<Joined>), Error> {
730        let core = RuntimeCore::new(resource_options, network_options, queue.clone(), queued, failure, registry, pool);
731        let pool = core.pool.clone();
732        crate::web::drive(&pool, queue, Some(core));
733        Ok((std::thread::current().id(), None))
734    }
735
736    /// What the runtime's maps parse against, their renderers draw and
737    /// their tile workers lay out.
738    #[must_use]
739    pub fn registry(&self) -> &Arc<Registry> {
740        &self.shared.registry
741    }
742
743    /// Sends a command to the runtime's thread.
744    fn command<T: Send + 'static>(
745        &self,
746        command: impl FnOnce(&mut RuntimeCore, &mut Outbox, Resolver<T>) + Send + 'static,
747    ) -> Result<Completion<T>, Error> {
748        self.shared.check_live()?;
749        let (completion, resolver) = self.shared.completion();
750        self.shared.post(move |core, outbox| command(core, outbox, resolver));
751        Ok(completion)
752    }
753
754    /// Sends a command that runs on the runtime's state and completes at once.
755    fn apply<T: Send + 'static>(
756        &self,
757        apply: impl FnOnce(&mut RuntimeCore) -> Result<T, Error> + Send + 'static,
758    ) -> Result<Completion<T>, Error> {
759        self.command(move |core, outbox, resolver| {
760            let result = apply(core);
761            outbox.resolve(resolver, result);
762        })
763    }
764
765    /// Creates a map on the runtime.
766    ///
767    /// The map's handle is ready at once, and the commands sent to it wait
768    /// for the map to be built. If building fails, the completion reports
769    /// why and those commands fail with
770    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind).
771    ///
772    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for an
773    /// empty size or a pixel ratio that isn't finite and positive.
774    pub fn create_map(&self, options: MapOptions) -> Result<(Map, Completion<Applied>), Error> {
775        let size = options.map.size;
776        let pixel_ratio = options.map.pixel_ratio;
777        if size.is_empty() {
778            return Err(Error::invalid_argument("the map's size must not be empty"));
779        }
780        if !pixel_ratio.is_finite() || pixel_ratio <= 0.0 {
781            return Err(Error::invalid_argument("the map's pixel ratio must be finite and positive"));
782        }
783        self.shared.check_running()?;
784        {
785            let mut lifecycle = self.shared.lifecycle.lock();
786            if lifecycle.released {
787                return Err(released());
788            }
789            lifecycle.live_maps += 1;
790        }
791        if options.system_fonts {
792            mln_system_fonts::prefetch();
793        }
794        let id = MapId(self.shared.next_map_id.fetch_add(1, Ordering::Relaxed));
795        let published = Arc::new(Published::new(options.event_mask));
796        let map = Map::new(MapShared::new(id, Arc::clone(&self.shared), &options, Arc::clone(&published)));
797        let (completion, resolver) = self.shared.completion();
798        self.shared.post(move |core, outbox| crate::map::create(core, id, &options, published, resolver, outbox));
799        Ok((map, completion))
800    }
801
802    /// Sends the events of the runtime and its maps to `handler`, in batches
803    /// on the runtime's thread. It replaces the handler before.
804    pub fn set_event_handler(
805        &self,
806        handler: impl Fn(&[RuntimeEvent]) + Send + Sync + 'static,
807    ) -> Result<Completion<()>, Error> {
808        let handler: EventHandler = Arc::new(handler);
809        self.command(move |core, outbox, resolver| {
810            let previous = core.event_handler.replace(handler);
811            outbox.push(move || drop(previous));
812            outbox.resolve(resolver, Ok(()));
813        })
814    }
815
816    /// Stops sending events to a handler.
817    pub fn clear_event_handler(&self) -> Result<Completion<()>, Error> {
818        self.command(move |core, outbox, resolver| {
819            let previous = core.event_handler.take();
820            outbox.push(move || drop(previous));
821            outbox.resolve(resolver, Ok(()));
822        })
823    }
824
825    /// Serves the runtime's network requests that `provider` serves through
826    /// it, and the rest as usual. It replaces the provider before.
827    pub fn set_resource_provider(&self, provider: impl ResourceProvider) -> Result<Completion<()>, Error> {
828        self.replace_provider(Some(Box::new(provider)))
829    }
830
831    /// Removes the resource provider, so the library loads every request
832    /// itself.
833    pub fn clear_resource_provider(&self) -> Result<Completion<()>, Error> {
834        self.replace_provider(None)
835    }
836
837    fn replace_provider(&self, provider: Option<Box<dyn ResourceProvider>>) -> Result<Completion<()>, Error> {
838        self.command(move |core, outbox, resolver| {
839            let previous = core.hooks.set_provider(provider);
840            outbox.push(move || drop(previous));
841            outbox.resolve(resolver, Ok(()));
842        })
843    }
844
845    /// Rewrites the URLs of the runtime's network requests before they go
846    /// out: `transform` gets the resource's kind and URL, and answers through
847    /// the callback, now or later and on any thread, with the URL to load or
848    /// the error to fail the request with. It replaces the transform before.
849    pub fn set_resource_transform(
850        &self,
851        transform: impl Fn(Kind, &str, FinishedCallback) + Send + Sync + 'static,
852    ) -> Result<Completion<()>, Error> {
853        let transform: ResourceTransform = Arc::new(transform);
854        self.apply(move |core| {
855            core.online().set_resource_transform(Some(transform));
856            core.hooks.set_transform_set(true);
857            Ok(())
858        })
859    }
860
861    /// Stops rewriting request URLs.
862    pub fn clear_resource_transform(&self) -> Result<Completion<()>, Error> {
863        self.apply(move |core| {
864            core.online().set_resource_transform(None);
865            core.hooks.set_transform_set(false);
866            Ok(())
867        })
868    }
869
870    /// Adds the headers that `transform` returns to the runtime's HTTP
871    /// requests: it gets the resource's kind and the URL after any resource
872    /// transform, and runs for each attempt of a request, which waits for
873    /// it. Names that the library manages, such as `Range` or `User-Agent`,
874    /// are dropped, and a later value of a name replaces an earlier one. It
875    /// replaces the transform before.
876    ///
877    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) in the
878    /// browser, where the browser sends the requests.
879    pub fn set_http_header_transform(
880        &self,
881        transform: impl Fn(Kind, &str) -> HttpHeaders + Send + Sync + 'static,
882    ) -> Result<Completion<()>, Error> {
883        if cfg!(target_family = "wasm") {
884            return Err(Error::unsupported("the browser sends the requests and sets their headers"));
885        }
886        let transform = HttpHeaderTransform::new(Some(Arc::new(move |kind: Kind, url: &str| {
887            crate::resources::sanitize_headers(transform(kind, url))
888        })));
889        self.apply(move |core| {
890            core.online().set_http_header_transform(transform);
891            Ok(())
892        })
893    }
894
895    /// Stops adding headers to HTTP requests.
896    pub fn clear_http_header_transform(&self) -> Result<Completion<()>, Error> {
897        self.apply(move |core| {
898            core.online().set_http_header_transform(HttpHeaderTransform::default());
899            Ok(())
900        })
901    }
902
903    /// Runs a maintenance action on the cache database.
904    ///
905    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) in the
906    /// browser, which has no cache database.
907    #[cfg(target_family = "wasm")]
908    pub fn run_cache_database_operation(&self, operation: CacheDatabaseOperation) -> Result<Completion<()>, Error> {
909        let _ = operation;
910        Err(no_database())
911    }
912
913    /// Runs a maintenance action on the cache database.
914    #[cfg(not(target_family = "wasm"))]
915    pub fn run_cache_database_operation(&self, operation: CacheDatabaseOperation) -> Result<Completion<()>, Error> {
916        self.command(move |core, _, resolver| {
917            let database = core.database();
918            let reply = reply_on(core.queue.clone(), resolver);
919            match operation {
920                CacheDatabaseOperation::Clear => database.clear_ambient_cache(reply),
921                CacheDatabaseOperation::Invalidate => database.invalidate_ambient_cache(reply),
922                CacheDatabaseOperation::Pack => database.pack_database(reply),
923                CacheDatabaseOperation::Reset => database.reset_database(reply),
924            }
925        })
926    }
927
928    /// Limits the ambient cache to `size` bytes. Offline regions don't count
929    /// toward it.
930    ///
931    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) in the
932    /// browser, which has no cache database.
933    #[cfg(target_family = "wasm")]
934    pub fn set_maximum_ambient_cache_size(&self, size: u64) -> Result<Completion<()>, Error> {
935        let _ = size;
936        Err(no_database())
937    }
938
939    /// Limits the ambient cache to `size` bytes. Offline regions don't count
940    /// toward it.
941    #[cfg(not(target_family = "wasm"))]
942    pub fn set_maximum_ambient_cache_size(&self, size: u64) -> Result<Completion<()>, Error> {
943        self.command(move |core, _, resolver| {
944            core.database().set_maximum_ambient_cache_size(size, reply_on(core.queue.clone(), resolver));
945        })
946    }
947
948    /// The offline regions in the runtime's cache database.
949    #[must_use]
950    pub fn offline(&self) -> Offline<'_> {
951        Offline::new(self)
952    }
953
954    /// Shuts the runtime down. The completion reports when its thread has
955    /// let go of its maps' resources and its file sources, and nothing waits
956    /// for the thread to end after that.
957    ///
958    /// Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind) while the
959    /// runtime has maps that aren't released, or when the runtime was
960    /// released already. Every call on the runtime fails the same way after.
961    pub fn release(&self) -> Result<Completion<()>, Error> {
962        {
963            let mut lifecycle = self.shared.lifecycle.lock();
964            if lifecycle.released {
965                return Err(released());
966            }
967            if lifecycle.live_maps > 0 {
968                return Err(Error::invalid_state("release the runtime's maps first"));
969            }
970            lifecycle.released = true;
971            lifecycle.shut_down = true;
972        }
973        self.shared.detach_thread();
974        let (completion, resolver) = self.shared.completion();
975        self.shared.shut_down(Some(resolver));
976        Ok(completion)
977    }
978
979    /// Releases the runtime whatever its state, without waiting: it shuts
980    /// down once its last map is released, and nothing waits for its thread
981    /// to end. Every call on the runtime fails with
982    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) after.
983    pub fn dispose(&self) -> Result<(), Error> {
984        let shut_down = {
985            let mut lifecycle = self.shared.lifecycle.lock();
986            if lifecycle.released {
987                return Err(released());
988            }
989            lifecycle.released = true;
990            let shut_down = lifecycle.live_maps == 0;
991            lifecycle.shut_down |= shut_down;
992            shut_down
993        };
994        self.shared.detach_thread();
995        if shut_down {
996            self.shared.shut_down(None);
997        }
998        Ok(())
999    }
1000
1001    /// Sends a command for the offline API.
1002    #[cfg(not(target_family = "wasm"))]
1003    pub(crate) fn offline_command<T: Send + 'static>(
1004        &self,
1005        command: impl FnOnce(&RegionDatabase, &RuntimeCore, Resolver<T>) + Send + 'static,
1006    ) -> Result<Completion<T>, Error> {
1007        self.command(move |core, _, resolver| command(core.database(), core, resolver))
1008    }
1009}
1010
1011// Handles cross threads; the core never leaves its own.
1012const _: () = {
1013    const fn assert_send_sync<T: Send + Sync>() {}
1014    assert_send_sync::<Runtime>();
1015    assert_send_sync::<Map>();
1016};