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::pool::Pool;
23use mln_util::queue::{Queue, TimedTask};
24use mln_util::thread::Joined;
25use mln_util::time::Instant;
26use parking_lot::Mutex;
27
28use crate::completion::{Completion, Resolver};
29use crate::event::{EventHandler, RuntimeEvent};
30use crate::log_target;
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!(target: log_target::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
423impl Drop for RuntimeCore {
424    /// Stops the file sources' threads, and waits for them, after the maps
425    /// have gone. The sources can outlive the runtime's handles of them: a
426    /// response's callback holds the loader while it runs on a source's
427    /// thread, and a provider's request holds the online source, so their
428    /// last handles can drop where a drop doesn't wait, such as on the
429    /// source's own thread.
430    fn drop(&mut self) {
431        self.maps.clear();
432        #[cfg(not(target_family = "wasm"))]
433        if let Some(database) = self.database.get() {
434            database.shut_down();
435        }
436        if let Some(online) = self.online.get() {
437            online.shut_down();
438        }
439    }
440}
441
442/// What the library's own network loading of a runtime follows.
443struct NetworkOptions {
444    status: Arc<NetworkStatus>,
445    /// [`RuntimeOptions::fetch_preloads`].
446    #[cfg(target_family = "wasm")]
447    fetch_preloads: Option<js_sys::Function>,
448}
449
450impl RuntimeCore {
451    fn new(
452        resource_options: ResourceOptions,
453        network_options: NetworkOptions,
454        queue: CoreQueue,
455        queued: Arc<AtomicUsize>,
456        failure: Arc<OnceLock<Error>>,
457        registry: Arc<Registry>,
458        pool: Pool,
459    ) -> Self {
460        RuntimeCore {
461            maps: BTreeMap::new(),
462            event_handler: None,
463            hooks: Arc::new(ResourceHooks::default()),
464            resource_options,
465            loader: OnceCell::new(),
466            #[cfg(not(target_family = "wasm"))]
467            database: OnceCell::new(),
468            online: OnceCell::new(),
469            network_options,
470            network: OnceCell::new(),
471            queue,
472            registry,
473            pool,
474            queued,
475            failure,
476            burst_left: 0,
477            holding: false,
478            spare_deliveries: Vec::new(),
479        }
480    }
481
482    /// Starts a task that [`RuntimeShared::post`] sent. The tasks that were
483    /// queued when a burst's first one starts make up the burst, and while a
484    /// burst of more than one runs, the maps hold their updates back, so that
485    /// a render session draws what the whole burst changed in one frame. A
486    /// task sent during a burst is in the next one, so a host that keeps
487    /// sending holds no update back for longer than a burst.
488    fn begin_burst_task(&mut self) {
489        let queued = self.queued.fetch_sub(1, Ordering::SeqCst);
490        if self.burst_left == 0 {
491            self.burst_left = queued;
492            self.holding = queued > 1;
493            if self.holding {
494                self.maps.values_mut().for_each(|entry| entry.core.hold_updates());
495            }
496        }
497    }
498
499    /// Ends a task of the burst, and after its last, shows what the maps
500    /// held back, and tells their sessions what ran meanwhile.
501    fn end_burst_task(&mut self, outbox: &mut Outbox) {
502        self.burst_left = self.burst_left.saturating_sub(1);
503        if self.burst_left > 0 || !std::mem::take(&mut self.holding) {
504            return;
505        }
506        let ids: Vec<MapId> = self.maps.keys().copied().collect();
507        for id in ids {
508            if let Some(entry) = self.maps.get_mut(&id) {
509                entry.core.release_updates();
510            }
511            crate::map::flush(self, id, outbox);
512            if let Some(entry) = self.maps.get_mut(&id) {
513                crate::map::report_held(entry);
514            }
515        }
516    }
517
518    /// Whether the maps hold their updates back for a burst.
519    pub(crate) fn holding_updates(&self) -> bool {
520        self.holding
521    }
522
523    /// The loader that the runtime's maps share.
524    pub(crate) fn loader(&self) -> &Arc<dyn FileSource> {
525        self.loader.get_or_init(|| {
526            let builder = Loader::builder(&self.pool)
527                .asset_path(&self.resource_options.asset_path)
528                .network(Arc::clone(self.network()));
529            #[cfg(not(target_family = "wasm"))]
530            let builder = builder.database(Arc::<RegionDatabase>::clone(self.database()));
531            Arc::new(builder.build())
532        })
533    }
534
535    /// The library's own network loading.
536    fn online(&self) -> &Arc<OnlineFileSource> {
537        self.online.get_or_init(|| {
538            #[cfg(not(target_family = "wasm"))]
539            let online = OnlineFileSource::new(Arc::clone(&self.network_options.status));
540            #[cfg(target_family = "wasm")]
541            let online = crate::web::online(
542                Arc::clone(&self.network_options.status),
543                self.network_options.fetch_preloads.clone(),
544            );
545            Arc::new(online)
546        })
547    }
548
549    /// The runtime's network: the host's resource provider, in front of the
550    /// library's own loading.
551    fn network(&self) -> &Arc<dyn FileSource> {
552        self.network
553            .get_or_init(|| Arc::new(ProviderFileSource::new(Arc::clone(self.online()), Arc::clone(&self.hooks))))
554    }
555
556    /// Where the runtime's background work runs, and its results come back.
557    pub(crate) fn background(&self) -> Background {
558        Background { pool: self.pool.clone(), queue: self.queue.clone() }
559    }
560
561    /// Sends `events` to the event handler.
562    pub(crate) fn send_events(&self, events: Vec<RuntimeEvent>, outbox: &mut Outbox) {
563        if events.is_empty() {
564            return;
565        }
566        if let Some(handler) = self.event_handler.clone() {
567            outbox.push(move || handler(&events));
568        }
569    }
570
571    /// The cache database, which every runtime but the browser build's has.
572    #[cfg(not(target_family = "wasm"))]
573    pub(crate) fn database(&self) -> &Arc<RegionDatabase> {
574        self.database.get_or_init(|| {
575            Arc::new(mln_storage_offline::region_database(
576                &self.resource_options.cache_path,
577                Some(Arc::clone(self.network())),
578                Arc::clone(self.registry.style()),
579            ))
580        })
581    }
582}
583
584/// Delivers a database result on the runtime's thread, so it keeps its
585/// place among the runtime's other results and events. It needs no runtime
586/// state, so a result that arrives while the runtime shuts down, which waits
587/// for the database's work, still resolves rather than being cancelled.
588#[cfg(not(target_family = "wasm"))]
589pub(crate) fn reply_on<T: Send + 'static, E: Into<Error>>(
590    queue: CoreQueue,
591    resolver: Resolver<T>,
592) -> impl FnOnce(Result<T, E>) + Send + 'static {
593    move |result| {
594        let result = result.map_err(Into::into);
595        queue.post(move |_| resolver.resolve(result));
596    }
597}
598
599/// The runtime's resource options, with the cache file created when there
600/// is one, so that a path the runtime can't use fails here.
601fn resource_options(options: &RuntimeOptions) -> Result<ResourceOptions, Error> {
602    let mut resource_options = ResourceOptions::default();
603    if let Some(asset_path) = &options.asset_path {
604        resource_options.asset_path = utf8(asset_path, "asset path")?.to_owned();
605    }
606    #[cfg(target_os = "android")]
607    if options.asset_path.is_none() {
608        resource_options.asset_path = mln_storage::android::APP_ASSETS.to_owned();
609    }
610    if options.cache_path.is_some() && cfg!(target_family = "wasm") {
611        return Err(Error::unsupported("the browser build has no cache database: the browser caches the requests"));
612    }
613    if let Some(cache_path) = &options.cache_path {
614        let path = utf8(cache_path, "cache path")?;
615        std::fs::OpenOptions::new()
616            .read(true)
617            .write(true)
618            .create(true)
619            .truncate(false)
620            .open(cache_path)
621            .map_err(|error| Error::invalid_argument(format!("can't open the cache database {path}: {error}")))?;
622        resource_options.cache_path = path.to_owned();
623    }
624    Ok(resource_options)
625}
626
627fn utf8<'a>(path: &'a Path, what: &str) -> Result<&'a str, Error> {
628    path.to_str().ok_or_else(|| Error::invalid_argument(format!("the {what} {} isn't UTF-8", path.display())))
629}
630
631impl Runtime {
632    /// Starts a runtime and its thread, with the built-in registrations.
633    ///
634    /// In the browser, the runtime's thread is the one that calls this, which
635    /// a wasm instance has only one of, and the runtime never blocks it: its
636    /// commands run in tasks of their own on the browser's event loop
637    /// (`mln_web_host::pump`), never inside the call that sends them.
638    ///
639    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) when the
640    /// cache database file can't be opened or created, and in the browser
641    /// with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a cache path.
642    pub fn new(options: &RuntimeOptions) -> Result<Runtime, Error> {
643        Self::with_registry(options, Registry::with_builtins())
644    }
645
646    /// Starts a runtime and its thread, whose maps parse their styles
647    /// against `registry`, and whose renderers and tile workers use it. In
648    /// the browser, the tile workers' Web Workers must serve with registries
649    /// filled by the same calls (`mln_web_host::tile_worker::serve`).
650    ///
651    /// Fails as [`new`](Self::new) does.
652    pub fn with_registry(options: &RuntimeOptions, registry: Arc<Registry>) -> Result<Runtime, Error> {
653        let resource_options = resource_options(options)?;
654        let network_options = NetworkOptions {
655            status: options.network_status.clone().unwrap_or_default(),
656            #[cfg(target_family = "wasm")]
657            fetch_preloads: options.fetch_preloads.clone(),
658        };
659        let queued = Arc::new(AtomicUsize::new(0));
660        let failure = Arc::new(OnceLock::new());
661        let queue = CoreQueue::default();
662        let pool = runtime_pool();
663        // A panic in a task of the runtime's maps or their sessions stops the
664        // runtime, as one on its thread does.
665        let failing = queue.downgrade();
666        pool.set_panic_handler(Some(Arc::new(move |message| {
667            if let Some(queue) = failing.upgrade() {
668                queue.post(move |core| fail(core, &message));
669            }
670        })));
671        let (thread, thread_end) = Self::start(
672            resource_options,
673            network_options,
674            queue.clone(),
675            Arc::clone(&queued),
676            Arc::clone(&failure),
677            Arc::clone(&registry),
678            pool.clone(),
679        )?;
680        Ok(Runtime {
681            shared: Arc::new(RuntimeShared {
682                queue,
683                queued,
684                thread,
685                lifecycle: Mutex::new(Lifecycle { released: false, live_maps: 0, shut_down: false }),
686                failure,
687                next_map_id: AtomicU64::new(1),
688                glyph_cache: Arc::default(),
689                font_face_engine: font_face_engine(),
690                registry,
691                pool,
692                thread_end,
693            }),
694        })
695    }
696
697    /// Builds the runtime's state on a thread of its own, which owns it and
698    /// runs `queue` until the runtime shuts down.
699    #[cfg(not(target_family = "wasm"))]
700    fn start(
701        resource_options: ResourceOptions,
702        network_options: NetworkOptions,
703        queue: CoreQueue,
704        queued: Arc<AtomicUsize>,
705        failure: Arc<OnceLock<Error>>,
706        registry: Arc<Registry>,
707        pool: Pool,
708    ) -> Result<(ThreadId, Option<Joined>), Error> {
709        let thread = mln_util::thread::spawn("Runtime", move || {
710            let own_pool = pool.clone();
711            let mut core = Some(RuntimeCore::new(
712                resource_options,
713                network_options,
714                queue.clone(),
715                queued,
716                failure,
717                registry,
718                pool,
719            ));
720            queue.run(&mut core);
721            // What comes after the shutdown drops at once, so tasks that hold
722            // the queue can't keep it alive.
723            queue.close();
724            drop(core);
725            // Nothing of the runtime runs after this, but a render session
726            // that kept its graphics forgot its renderer, which holds the
727            // pool: its workers stop here rather than with the last handle.
728            own_pool.shut_down();
729        })
730        .map_err(|error| Error::native(format!("can't start the runtime's thread: {error}")))?;
731        let thread_id = thread.thread().id();
732        // The thread ends by itself once the runtime shuts down.
733        Ok((thread_id, Some(Joined::new(thread))))
734    }
735
736    /// Builds the runtime's state on this thread, where the instance's pump
737    /// runs `queue` with it until the runtime shuts down.
738    #[cfg(target_family = "wasm")]
739    #[expect(clippy::unnecessary_wraps, reason = "the threads of other builds can fail to start")]
740    fn start(
741        resource_options: ResourceOptions,
742        network_options: NetworkOptions,
743        queue: CoreQueue,
744        queued: Arc<AtomicUsize>,
745        failure: Arc<OnceLock<Error>>,
746        registry: Arc<Registry>,
747        pool: Pool,
748    ) -> Result<(ThreadId, Option<Joined>), Error> {
749        let core = RuntimeCore::new(resource_options, network_options, queue.clone(), queued, failure, registry, pool);
750        let pool = core.pool.clone();
751        crate::web::drive(&pool, queue, Some(core));
752        Ok((std::thread::current().id(), None))
753    }
754
755    /// What the runtime's maps parse against, their renderers draw and
756    /// their tile workers lay out.
757    #[must_use]
758    pub fn registry(&self) -> &Arc<Registry> {
759        &self.shared.registry
760    }
761
762    /// Sends a command to the runtime's thread.
763    fn command<T: Send + 'static>(
764        &self,
765        command: impl FnOnce(&mut RuntimeCore, &mut Outbox, Resolver<T>) + Send + 'static,
766    ) -> Result<Completion<T>, Error> {
767        self.shared.check_live()?;
768        let (completion, resolver) = self.shared.completion();
769        self.shared.post(move |core, outbox| command(core, outbox, resolver));
770        Ok(completion)
771    }
772
773    /// Sends a command that runs on the runtime's state and completes at once.
774    fn apply<T: Send + 'static>(
775        &self,
776        apply: impl FnOnce(&mut RuntimeCore) -> Result<T, Error> + Send + 'static,
777    ) -> Result<Completion<T>, Error> {
778        self.command(move |core, outbox, resolver| {
779            let result = apply(core);
780            outbox.resolve(resolver, result);
781        })
782    }
783
784    /// Creates a map on the runtime.
785    ///
786    /// The map's handle is ready at once, and the commands sent to it wait
787    /// for the map to be built. If building fails, the completion reports
788    /// why and those commands fail with
789    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind).
790    ///
791    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for an
792    /// empty size or a pixel ratio that isn't finite and positive.
793    pub fn create_map(&self, options: MapOptions) -> Result<(Map, Completion<Applied>), Error> {
794        let size = options.map.size;
795        let pixel_ratio = options.map.pixel_ratio;
796        if size.is_empty() {
797            return Err(Error::invalid_argument("the map's size must not be empty"));
798        }
799        if !pixel_ratio.is_finite() || pixel_ratio <= 0.0 {
800            return Err(Error::invalid_argument("the map's pixel ratio must be finite and positive"));
801        }
802        self.shared.check_running()?;
803        {
804            let mut lifecycle = self.shared.lifecycle.lock();
805            if lifecycle.released {
806                return Err(released());
807            }
808            lifecycle.live_maps += 1;
809        }
810        if options.system_fonts {
811            mln_system_fonts::prefetch();
812        }
813        let id = MapId(self.shared.next_map_id.fetch_add(1, Ordering::Relaxed));
814        let published = Arc::new(Published::new(options.event_mask));
815        let map = Map::new(MapShared::new(id, Arc::clone(&self.shared), &options, Arc::clone(&published)));
816        let (completion, resolver) = self.shared.completion();
817        self.shared.post(move |core, outbox| crate::map::create(core, id, &options, published, resolver, outbox));
818        Ok((map, completion))
819    }
820
821    /// Sends the events of the runtime and its maps to `handler`, in batches
822    /// on the runtime's thread. It replaces the handler before.
823    pub fn set_event_handler(
824        &self,
825        handler: impl Fn(&[RuntimeEvent]) + Send + Sync + 'static,
826    ) -> Result<Completion<()>, Error> {
827        let handler: EventHandler = Arc::new(handler);
828        self.command(move |core, outbox, resolver| {
829            let previous = core.event_handler.replace(handler);
830            outbox.push(move || drop(previous));
831            outbox.resolve(resolver, Ok(()));
832        })
833    }
834
835    /// Stops sending events to a handler.
836    pub fn clear_event_handler(&self) -> Result<Completion<()>, Error> {
837        self.command(move |core, outbox, resolver| {
838            let previous = core.event_handler.take();
839            outbox.push(move || drop(previous));
840            outbox.resolve(resolver, Ok(()));
841        })
842    }
843
844    /// Serves the runtime's network requests that `provider` serves through
845    /// it, and the rest as usual. It replaces the provider before.
846    pub fn set_resource_provider(&self, provider: impl ResourceProvider) -> Result<Completion<()>, Error> {
847        self.replace_provider(Some(Box::new(provider)))
848    }
849
850    /// Removes the resource provider, so the library loads every request
851    /// itself.
852    pub fn clear_resource_provider(&self) -> Result<Completion<()>, Error> {
853        self.replace_provider(None)
854    }
855
856    fn replace_provider(&self, provider: Option<Box<dyn ResourceProvider>>) -> Result<Completion<()>, Error> {
857        self.command(move |core, outbox, resolver| {
858            let previous = core.hooks.set_provider(provider);
859            outbox.push(move || drop(previous));
860            outbox.resolve(resolver, Ok(()));
861        })
862    }
863
864    /// Rewrites the URLs of the runtime's network requests before they go
865    /// out: `transform` gets the resource's kind and URL, and answers through
866    /// the callback, now or later and on any thread, with the URL to load or
867    /// the error to fail the request with. It replaces the transform before.
868    pub fn set_resource_transform(
869        &self,
870        transform: impl Fn(Kind, &str, FinishedCallback) + Send + Sync + 'static,
871    ) -> Result<Completion<()>, Error> {
872        let transform: ResourceTransform = Arc::new(transform);
873        self.apply(move |core| {
874            core.online().set_resource_transform(Some(transform));
875            core.hooks.set_transform_set(true);
876            Ok(())
877        })
878    }
879
880    /// Stops rewriting request URLs.
881    pub fn clear_resource_transform(&self) -> Result<Completion<()>, Error> {
882        self.apply(move |core| {
883            core.online().set_resource_transform(None);
884            core.hooks.set_transform_set(false);
885            Ok(())
886        })
887    }
888
889    /// Adds the headers that `transform` returns to the runtime's HTTP
890    /// requests: it gets the resource's kind and the URL after any resource
891    /// transform, and runs for each attempt of a request, which waits for
892    /// it. Names that the library manages, such as `Range` or `User-Agent`,
893    /// are dropped, and a later value of a name replaces an earlier one. An
894    /// `Accept` replaces the one the library sends for tiles and images. It
895    /// replaces the transform before.
896    ///
897    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) in the
898    /// browser, where the browser sends the requests.
899    pub fn set_http_header_transform(
900        &self,
901        transform: impl Fn(Kind, &str) -> HttpHeaders + Send + Sync + 'static,
902    ) -> Result<Completion<()>, Error> {
903        if cfg!(target_family = "wasm") {
904            return Err(Error::unsupported("the browser sends the requests and sets their headers"));
905        }
906        let transform = HttpHeaderTransform::new(Some(Arc::new(move |kind: Kind, url: &str| {
907            crate::resources::sanitize_headers(transform(kind, url))
908        })));
909        self.apply(move |core| {
910            core.online().set_http_header_transform(transform);
911            Ok(())
912        })
913    }
914
915    /// Stops adding headers to HTTP requests.
916    pub fn clear_http_header_transform(&self) -> Result<Completion<()>, Error> {
917        self.apply(move |core| {
918            core.online().set_http_header_transform(HttpHeaderTransform::default());
919            Ok(())
920        })
921    }
922
923    /// Runs a maintenance action on the cache database.
924    ///
925    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) in the
926    /// browser, which has no cache database.
927    #[cfg(target_family = "wasm")]
928    pub fn run_cache_database_operation(&self, operation: CacheDatabaseOperation) -> Result<Completion<()>, Error> {
929        let _ = operation;
930        Err(no_database())
931    }
932
933    /// Runs a maintenance action on the cache database.
934    #[cfg(not(target_family = "wasm"))]
935    pub fn run_cache_database_operation(&self, operation: CacheDatabaseOperation) -> Result<Completion<()>, Error> {
936        self.command(move |core, _, resolver| {
937            let database = core.database();
938            let reply = reply_on(core.queue.clone(), resolver);
939            match operation {
940                CacheDatabaseOperation::Clear => database.clear_ambient_cache(reply),
941                CacheDatabaseOperation::Invalidate => database.invalidate_ambient_cache(reply),
942                CacheDatabaseOperation::Pack => database.pack_database(reply),
943                CacheDatabaseOperation::Reset => database.reset_database(reply),
944            }
945        })
946    }
947
948    /// Limits the ambient cache to `size` bytes. Offline regions don't count
949    /// toward it.
950    ///
951    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) in the
952    /// browser, which has no cache database.
953    #[cfg(target_family = "wasm")]
954    pub fn set_maximum_ambient_cache_size(&self, size: u64) -> Result<Completion<()>, Error> {
955        let _ = size;
956        Err(no_database())
957    }
958
959    /// Limits the ambient cache to `size` bytes. Offline regions don't count
960    /// toward it.
961    #[cfg(not(target_family = "wasm"))]
962    pub fn set_maximum_ambient_cache_size(&self, size: u64) -> Result<Completion<()>, Error> {
963        self.command(move |core, _, resolver| {
964            core.database().set_maximum_ambient_cache_size(size, reply_on(core.queue.clone(), resolver));
965        })
966    }
967
968    /// The offline regions in the runtime's cache database.
969    #[must_use]
970    pub fn offline(&self) -> Offline<'_> {
971        Offline::new(self)
972    }
973
974    /// Shuts the runtime down. The completion reports when its thread has
975    /// let go of its maps' resources and its file sources, and nothing waits
976    /// for the thread to end after that.
977    ///
978    /// Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind) while the
979    /// runtime has maps that aren't released, or when the runtime was
980    /// released already. Every call on the runtime fails the same way after.
981    pub fn release(&self) -> Result<Completion<()>, Error> {
982        {
983            let mut lifecycle = self.shared.lifecycle.lock();
984            if lifecycle.released {
985                return Err(released());
986            }
987            if lifecycle.live_maps > 0 {
988                return Err(Error::invalid_state("release the runtime's maps first"));
989            }
990            lifecycle.released = true;
991            lifecycle.shut_down = true;
992        }
993        self.shared.detach_thread();
994        let (completion, resolver) = self.shared.completion();
995        self.shared.shut_down(Some(resolver));
996        Ok(completion)
997    }
998
999    /// Releases the runtime whatever its state, without waiting: it shuts
1000    /// down once its last map is released, and nothing waits for its thread
1001    /// to end. Every call on the runtime fails with
1002    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) after.
1003    pub fn dispose(&self) -> Result<(), Error> {
1004        let shut_down = {
1005            let mut lifecycle = self.shared.lifecycle.lock();
1006            if lifecycle.released {
1007                return Err(released());
1008            }
1009            lifecycle.released = true;
1010            let shut_down = lifecycle.live_maps == 0;
1011            lifecycle.shut_down |= shut_down;
1012            shut_down
1013        };
1014        self.shared.detach_thread();
1015        if shut_down {
1016            self.shared.shut_down(None);
1017        }
1018        Ok(())
1019    }
1020
1021    /// Sends a command for the offline API.
1022    #[cfg(not(target_family = "wasm"))]
1023    pub(crate) fn offline_command<T: Send + 'static>(
1024        &self,
1025        command: impl FnOnce(&RegionDatabase, &RuntimeCore, Resolver<T>) + Send + 'static,
1026    ) -> Result<Completion<T>, Error> {
1027        self.command(move |core, _, resolver| command(core.database(), core, resolver))
1028    }
1029}
1030
1031// Handles cross threads; the core never leaves its own.
1032const _: () = {
1033    const fn assert_send_sync<T: Send + Sync>() {}
1034    assert_send_sync::<Runtime>();
1035    assert_send_sync::<Map>();
1036};