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