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