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