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::RefCell;
5use std::collections::BTreeMap;
6use std::path::{Path, PathBuf};
7use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
8use std::sync::{Arc, Mutex, mpsc};
9use std::thread::ThreadId;
10
11use mln_actor::{RunLoop, RunLoopHandle};
12use mln_storage::http_header_transform::{HttpHeaderTransform, HttpHeaders};
13use mln_storage::resource::Kind;
14use mln_storage::resource_transform::{FinishedCallback, ResourceTransform};
15use mln_storage::{DatabaseFileSource, FileSource, FileSourceManager, FileSourceType, ResourceOptions};
16use mln_text::GlyphCache;
17use mln_util::error::Error;
18use mln_util::sync::MutexExt;
19
20use crate::completion::{Completion, Resolver};
21use crate::event::{EventHandler, RuntimeEvent};
22use crate::map::{Applied, Map, MapEntry, MapId, MapOptions, MapShared, Published};
23use crate::offline::Offline;
24use crate::resources::{CacheDatabaseOperation, ProviderFileSource, ResourceHooks, ResourceProvider};
25
26/// Where a runtime keeps its assets and its cache.
27#[derive(Clone, Debug, Default, PartialEq, Eq)]
28pub struct RuntimeOptions {
29    /// The directory that `asset://` URLs load from. `None` uses the working
30    /// directory, or on Android the app's assets, which
31    /// `mln_storage::android::init` gives the library.
32    pub asset_path: Option<PathBuf>,
33    /// The cache database file, which holds the ambient cache and the offline
34    /// regions. Its directory must be writable. `None` keeps the cache in
35    /// memory.
36    pub cache_path: Option<PathBuf>,
37}
38
39/// A runtime: a thread of its own that holds maps, and the resource loading,
40/// cache and offline regions that they share.
41///
42/// Every call returns at once. Commands run on the runtime's thread in the
43/// order they were sent, across the runtime and all its maps, and report
44/// through a [`Completion`]. `Clone` is another handle to the same runtime,
45/// and any thread may use one.
46///
47/// The runtime lives until [`release`](Self::release) or
48/// [`dispose`](Self::dispose), or until its last handle and its last map
49/// are dropped. A handler or provider that holds a handle keeps it alive
50/// until then.
51#[derive(Clone)]
52pub struct Runtime {
53    pub(crate) shared: Arc<RuntimeShared>,
54}
55
56impl std::fmt::Debug for Runtime {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.debug_struct("Runtime").field("thread", &self.shared.thread).finish()
59    }
60}
61
62struct Lifecycle {
63    released: bool,
64    live_maps: usize,
65    shut_down: bool,
66}
67
68pub(crate) struct RuntimeShared {
69    run_loop: RunLoopHandle,
70    /// The tasks that [`post`](Self::post) sent and the thread hasn't run.
71    queued: Arc<AtomicUsize>,
72    thread: ThreadId,
73    lifecycle: Mutex<Lifecycle>,
74    next_map_id: AtomicU64,
75    /// The glyphs that the renderers of the runtime's maps parse, which they
76    /// share.
77    pub(crate) glyph_cache: Arc<GlyphCache>,
78}
79
80impl RuntimeShared {
81    /// Runs `task` on the runtime's thread, after everything sent before it,
82    /// in the burst of the tasks queued with it.
83    pub(crate) fn post(&self, task: impl FnOnce(&mut RuntimeCore, &mut Outbox) + Send + 'static) {
84        self.queued.fetch_add(1, Ordering::SeqCst);
85        self.run_loop.invoke(move || run(task, true));
86    }
87
88    /// Runs `task` with `value` on the runtime's thread, after everything
89    /// sent before it, or `instead` with `value` on this thread when the
90    /// runtime has shut down, so that what must happen either way isn't lost
91    /// with the runtime's loop.
92    pub(crate) fn post_or<V: Send + 'static>(
93        &self,
94        value: V,
95        task: impl FnOnce(&mut RuntimeCore, &mut Outbox, V) + Send + 'static,
96        instead: impl FnOnce(V),
97    ) {
98        // Posting with the lock held orders the task before a shutdown.
99        let lifecycle = self.lifecycle.lock_unpoisoned();
100        if lifecycle.shut_down {
101            drop(lifecycle);
102            instead(value);
103        } else {
104            self.post(move |core, outbox| task(core, outbox, value));
105        }
106    }
107
108    pub(crate) fn thread(&self) -> ThreadId {
109        self.thread
110    }
111
112    /// A completion that the runtime's thread resolves.
113    pub(crate) fn completion<T: Send + 'static>(&self) -> (Completion<T>, Resolver<T>) {
114        Completion::new(Some(self.thread))
115    }
116
117    fn check_live(&self) -> Result<(), Error> {
118        if self.lifecycle.lock_unpoisoned().released { Err(released()) } else { Ok(()) }
119    }
120
121    /// A map of the runtime was released or dropped. A disposed runtime shuts
122    /// down with its last map.
123    pub(crate) fn map_released(&self) {
124        let shut_down = {
125            let mut lifecycle = self.lifecycle.lock_unpoisoned();
126            lifecycle.live_maps -= 1;
127            let shut_down = lifecycle.released && lifecycle.live_maps == 0 && !lifecycle.shut_down;
128            lifecycle.shut_down |= shut_down;
129            shut_down
130        };
131        if shut_down {
132            self.shut_down(None);
133        }
134    }
135
136    /// Tears the runtime down on its thread, after the commands sent before.
137    fn shut_down(&self, done: Option<Resolver<()>>) {
138        let run_loop = self.run_loop.clone();
139        self.run_loop.invoke(move || {
140            let core = CORE.with(|core| core.borrow_mut().take());
141            drop(core);
142            if let Some(done) = done {
143                done.resolve(Ok(()));
144            }
145            run_loop.stop();
146        });
147    }
148}
149
150impl Drop for RuntimeShared {
151    fn drop(&mut self) {
152        if !self.lifecycle.get_mut_unpoisoned().shut_down {
153            self.shut_down(None);
154        }
155    }
156}
157
158fn released() -> Error {
159    Error::invalid_state("the runtime was released")
160}
161
162thread_local! {
163    /// The state of the runtime whose thread this is.
164    static CORE: RefCell<Option<RuntimeCore>> = const { RefCell::new(None) };
165}
166
167/// Posts `task` to the runtime thread whose loop is `run_loop`.
168pub(crate) fn post(run_loop: &RunLoopHandle, task: impl FnOnce(&mut RuntimeCore, &mut Outbox) + Send + 'static) {
169    run_loop.invoke(move || run(task, false));
170}
171
172/// Runs `task` on the runtime's state, then delivers what it sends to the
173/// host, with the state unborrowed. A task that comes after the runtime shut
174/// down drops, which cancels its completions. A task that
175/// [`RuntimeShared::post`] sent runs in its burst.
176fn run(task: impl FnOnce(&mut RuntimeCore, &mut Outbox), in_burst: bool) {
177    let mut outbox = Outbox::default();
178    let unrun = CORE.with(|core| match core.borrow_mut().as_mut() {
179        Some(core) => {
180            if in_burst {
181                core.begin_burst_task();
182            }
183            task(core, &mut outbox);
184            if in_burst {
185                core.end_burst_task(&mut outbox);
186            }
187            None
188        }
189        None => Some(task),
190    });
191    drop(unrun);
192    outbox.deliver();
193}
194
195/// What a task sends to the host: event batches and results, in order. They
196/// go out once the task is done with the runtime's state, so host code that
197/// runs never finds it borrowed.
198#[derive(Default)]
199pub(crate) struct Outbox {
200    deliveries: Vec<Box<dyn FnOnce()>>,
201}
202
203impl Outbox {
204    pub(crate) fn push(&mut self, delivery: impl FnOnce() + 'static) {
205        self.deliveries.push(Box::new(delivery));
206    }
207
208    pub(crate) fn resolve<T: 'static>(&mut self, resolver: Resolver<T>, result: Result<T, Error>) {
209        self.push(move || resolver.resolve(result));
210    }
211
212    pub(crate) fn deliver(self) {
213        for delivery in self.deliveries {
214            delivery();
215        }
216    }
217}
218
219/// The runtime's state, on its thread.
220pub(crate) struct RuntimeCore {
221    /// Declared first, so the maps go before the file sources they use.
222    pub(crate) maps: BTreeMap<MapId, MapEntry>,
223    pub(crate) event_handler: Option<EventHandler>,
224    hooks: Arc<ResourceHooks>,
225    file_sources: FileSourceManager,
226    resource_options: ResourceOptions,
227    /// The runtime's file sources, held for its life so that each map, and
228    /// each transform, finds the same ones.
229    _loader: Option<Arc<dyn FileSource>>,
230    database: Option<Arc<dyn FileSource>>,
231    network: Option<Arc<dyn FileSource>>,
232    pub(crate) run_loop: RunLoopHandle,
233    /// [`RuntimeShared::queued`].
234    queued: Arc<AtomicUsize>,
235    /// The tasks of the burst in progress that haven't finished.
236    burst_left: usize,
237    /// Whether the maps hold their updates back for the burst.
238    holding: bool,
239}
240
241impl RuntimeCore {
242    fn new(resource_options: ResourceOptions, run_loop: RunLoopHandle, queued: Arc<AtomicUsize>) -> Self {
243        let hooks = Arc::new(ResourceHooks::default());
244        let file_sources = FileSourceManager::new();
245        let network_hooks = hooks.clone();
246        file_sources.register_file_source_factory(
247            FileSourceType::Network,
248            Arc::new(move |_: &FileSourceManager, options: &ResourceOptions| {
249                Arc::new(ProviderFileSource::new(options, network_hooks.clone())) as Arc<dyn FileSource>
250            }),
251        );
252        let network = file_sources.get_file_source(FileSourceType::Network, &resource_options);
253        let database = file_sources.get_file_source(FileSourceType::Database, &resource_options);
254        let loader = file_sources.get_file_source(FileSourceType::ResourceLoader, &resource_options);
255        RuntimeCore {
256            maps: BTreeMap::new(),
257            event_handler: None,
258            hooks,
259            file_sources,
260            resource_options,
261            _loader: loader,
262            database,
263            network,
264            run_loop,
265            queued,
266            burst_left: 0,
267            holding: false,
268        }
269    }
270
271    /// Starts a task that [`RuntimeShared::post`] sent. The tasks that were
272    /// queued when a burst's first one starts make up the burst, and while a
273    /// burst of more than one runs, the maps hold their updates back, so that
274    /// a render session draws what the whole burst changed in one frame. A
275    /// task sent during a burst is in the next one, so a host that keeps
276    /// sending holds no update back for longer than a burst.
277    fn begin_burst_task(&mut self) {
278        let queued = self.queued.fetch_sub(1, Ordering::SeqCst);
279        if self.burst_left == 0 {
280            self.burst_left = queued;
281            self.holding = queued > 1;
282            if self.holding {
283                self.maps.values_mut().for_each(|entry| entry.core.hold_updates());
284            }
285        }
286    }
287
288    /// Ends a task of the burst, and after its last, shows what the maps
289    /// held back.
290    fn end_burst_task(&mut self, outbox: &mut Outbox) {
291        self.burst_left = self.burst_left.saturating_sub(1);
292        if self.burst_left > 0 || !std::mem::take(&mut self.holding) {
293            return;
294        }
295        let ids: Vec<MapId> = self.maps.keys().copied().collect();
296        for id in ids {
297            if let Some(entry) = self.maps.get_mut(&id) {
298                entry.core.release_updates();
299            }
300            crate::map::flush(self, id, outbox);
301        }
302    }
303
304    pub(crate) fn file_sources(&self) -> (&FileSourceManager, &ResourceOptions) {
305        (&self.file_sources, &self.resource_options)
306    }
307
308    /// Sends `events` to the event handler.
309    pub(crate) fn send_events(&self, events: Vec<RuntimeEvent>, outbox: &mut Outbox) {
310        if events.is_empty() {
311            return;
312        }
313        if let Some(handler) = self.event_handler.clone() {
314            outbox.push(move || handler(&events));
315        }
316    }
317
318    /// The cache database, which every runtime has.
319    pub(crate) fn database(&self) -> Result<&DatabaseFileSource, Error> {
320        self.database
321            .as_ref()
322            .and_then(|database| database.as_any())
323            .and_then(|database| database.downcast_ref::<DatabaseFileSource>())
324            .ok_or_else(|| Error::unsupported("the runtime has no cache database"))
325    }
326
327    fn network(&self) -> Result<&Arc<dyn FileSource>, Error> {
328        self.network.as_ref().ok_or_else(|| Error::unsupported("the runtime has no network file source"))
329    }
330}
331
332/// Delivers a database result on the runtime's thread, so it keeps its
333/// place among the runtime's other results and events.
334pub(crate) fn reply_on<T: Send + 'static, E: Into<Error>>(
335    run_loop: RunLoopHandle,
336    resolver: Resolver<T>,
337) -> impl FnOnce(Result<T, E>) + Send + 'static {
338    move |result| {
339        let result = result.map_err(Into::into);
340        post(&run_loop, move |_, outbox| outbox.resolve(resolver, result));
341    }
342}
343
344/// The runtime's resource options, with the cache file created when there
345/// is one, so that a path the runtime can't use fails here.
346fn resource_options(options: &RuntimeOptions) -> Result<ResourceOptions, Error> {
347    let mut resource_options = ResourceOptions::default();
348    if let Some(asset_path) = &options.asset_path {
349        resource_options = resource_options.with_asset_path(utf8(asset_path, "asset path")?);
350    }
351    #[cfg(target_os = "android")]
352    if options.asset_path.is_none() {
353        resource_options = resource_options.with_asset_path(mln_storage::android::APP_ASSETS);
354    }
355    if let Some(cache_path) = &options.cache_path {
356        let path = utf8(cache_path, "cache path")?;
357        std::fs::OpenOptions::new()
358            .read(true)
359            .write(true)
360            .create(true)
361            .truncate(false)
362            .open(cache_path)
363            .map_err(|error| Error::invalid_argument(format!("can't open the cache database {path}: {error}")))?;
364        resource_options = resource_options.with_cache_path(path);
365    }
366    Ok(resource_options)
367}
368
369fn utf8<'a>(path: &'a Path, what: &str) -> Result<&'a str, Error> {
370    path.to_str().ok_or_else(|| Error::invalid_argument(format!("the {what} {} isn't UTF-8", path.display())))
371}
372
373impl Runtime {
374    /// Starts a runtime and its thread.
375    ///
376    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) when the
377    /// cache database file can't be opened or created.
378    pub fn new(options: &RuntimeOptions) -> Result<Runtime, Error> {
379        let resource_options = resource_options(options)?;
380        let (started, start) = mpsc::channel();
381        let queued = Arc::new(AtomicUsize::new(0));
382        let core_queued = Arc::clone(&queued);
383        let thread = mln_util::thread::builder("Runtime")
384            .spawn(move || {
385                let run_loop = RunLoop::new();
386                let core = RuntimeCore::new(resource_options, run_loop.handle(), core_queued);
387                CORE.with(|cell| *cell.borrow_mut() = Some(core));
388                let _ = started.send(run_loop.handle());
389                run_loop.run();
390                let core = CORE.with(|cell| cell.borrow_mut().take());
391                drop(core);
392            })
393            .map_err(|error| Error::native(format!("can't start the runtime's thread: {error}")))?;
394        let thread_id = thread.thread().id();
395        // The thread ends by itself once the runtime shuts down, so nothing
396        // joins it: a runtime may shut down from its own thread.
397        drop(thread);
398        let run_loop = start.recv().map_err(|_| Error::native("the runtime's thread stopped as it started"))?;
399        Ok(Runtime {
400            shared: Arc::new(RuntimeShared {
401                run_loop,
402                queued,
403                thread: thread_id,
404                lifecycle: Mutex::new(Lifecycle { released: false, live_maps: 0, shut_down: false }),
405                next_map_id: AtomicU64::new(1),
406                glyph_cache: Arc::default(),
407            }),
408        })
409    }
410
411    /// Sends a command to the runtime's thread.
412    fn command<T: Send + 'static>(
413        &self,
414        command: impl FnOnce(&mut RuntimeCore, &mut Outbox, Resolver<T>) + Send + 'static,
415    ) -> Result<Completion<T>, Error> {
416        self.shared.check_live()?;
417        let (completion, resolver) = self.shared.completion();
418        self.shared.post(move |core, outbox| command(core, outbox, resolver));
419        Ok(completion)
420    }
421
422    /// Sends a command that runs on the runtime's state and completes at once.
423    fn apply<T: Send + 'static>(
424        &self,
425        apply: impl FnOnce(&mut RuntimeCore) -> Result<T, Error> + Send + 'static,
426    ) -> Result<Completion<T>, Error> {
427        self.command(move |core, outbox, resolver| {
428            let result = apply(core);
429            outbox.resolve(resolver, result);
430        })
431    }
432
433    /// Creates a map on the runtime.
434    ///
435    /// The map's handle is ready at once, and the commands sent to it wait
436    /// for the map to be built. If building fails, the completion reports
437    /// why and those commands fail with
438    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind).
439    ///
440    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for an
441    /// empty size or a pixel ratio that isn't finite and positive.
442    pub fn create_map(&self, options: MapOptions) -> Result<(Map, Completion<Applied>), Error> {
443        let size = options.map.size();
444        let pixel_ratio = options.map.pixel_ratio();
445        if size.is_empty() {
446            return Err(Error::invalid_argument("the map's size must not be empty"));
447        }
448        if !pixel_ratio.is_finite() || pixel_ratio <= 0.0 {
449            return Err(Error::invalid_argument("the map's pixel ratio must be finite and positive"));
450        }
451        {
452            let mut lifecycle = self.shared.lifecycle.lock_unpoisoned();
453            if lifecycle.released {
454                return Err(released());
455            }
456            lifecycle.live_maps += 1;
457        }
458        let id = MapId(self.shared.next_map_id.fetch_add(1, Ordering::Relaxed));
459        let published = Arc::new(Published::new(options.event_mask));
460        let map = Map::new(MapShared::new(id, self.shared.clone(), &options, published.clone()));
461        let (completion, resolver) = self.shared.completion();
462        self.shared.post(move |core, outbox| crate::map::create(core, id, &options, published, resolver, outbox));
463        Ok((map, completion))
464    }
465
466    /// Sends the events of the runtime and its maps to `handler`, in batches
467    /// on the runtime's thread. It replaces the handler before.
468    pub fn set_event_handler(
469        &self,
470        handler: impl Fn(&[RuntimeEvent]) + Send + Sync + 'static,
471    ) -> Result<Completion<()>, Error> {
472        let handler: EventHandler = Arc::new(handler);
473        self.command(move |core, outbox, resolver| {
474            let previous = core.event_handler.replace(handler);
475            outbox.push(move || drop(previous));
476            outbox.resolve(resolver, Ok(()));
477        })
478    }
479
480    /// Stops sending events to a handler.
481    pub fn clear_event_handler(&self) -> Result<Completion<()>, Error> {
482        self.command(move |core, outbox, resolver| {
483            let previous = core.event_handler.take();
484            outbox.push(move || drop(previous));
485            outbox.resolve(resolver, Ok(()));
486        })
487    }
488
489    /// Serves the runtime's network requests that `provider` serves through
490    /// it, and the rest as usual. It replaces the provider before.
491    pub fn set_resource_provider(&self, provider: impl ResourceProvider) -> Result<Completion<()>, Error> {
492        self.replace_provider(Some(Box::new(provider)))
493    }
494
495    /// Removes the resource provider, so the library loads every request
496    /// itself.
497    pub fn clear_resource_provider(&self) -> Result<Completion<()>, Error> {
498        self.replace_provider(None)
499    }
500
501    fn replace_provider(&self, provider: Option<Box<dyn ResourceProvider>>) -> Result<Completion<()>, Error> {
502        self.command(move |core, outbox, resolver| {
503            let previous = core.hooks.set_provider(provider);
504            outbox.push(move || drop(previous));
505            outbox.resolve(resolver, Ok(()));
506        })
507    }
508
509    /// Rewrites the URLs of the runtime's network requests before they go
510    /// out: `transform` gets the resource's kind and URL, and answers through
511    /// the callback, now or later and on any thread, with the URL to load or
512    /// the error to fail the request with. It replaces the transform before.
513    pub fn set_resource_transform(
514        &self,
515        transform: impl Fn(Kind, &str, FinishedCallback) + Send + Sync + 'static,
516    ) -> Result<Completion<()>, Error> {
517        let transform = ResourceTransform::new(Some(Arc::new(transform)));
518        self.apply(move |core| {
519            core.network()?.set_resource_transform(transform);
520            core.hooks.set_transform_set(true);
521            Ok(())
522        })
523    }
524
525    /// Stops rewriting request URLs.
526    pub fn clear_resource_transform(&self) -> Result<Completion<()>, Error> {
527        self.apply(move |core| {
528            core.network()?.set_resource_transform(ResourceTransform::default());
529            core.hooks.set_transform_set(false);
530            Ok(())
531        })
532    }
533
534    /// Adds the headers that `transform` returns to the runtime's HTTP
535    /// requests: it gets the resource's kind and the URL after any resource
536    /// transform, and runs for each attempt of a request, which waits for
537    /// it. Names that the library manages, such as `Range` or `User-Agent`,
538    /// are dropped, and a later value of a name replaces an earlier one. It
539    /// replaces the transform before.
540    ///
541    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) in the
542    /// browser, where the browser sends the requests.
543    pub fn set_http_header_transform(
544        &self,
545        transform: impl Fn(Kind, &str) -> HttpHeaders + Send + Sync + 'static,
546    ) -> Result<Completion<()>, Error> {
547        if cfg!(target_family = "wasm") {
548            return Err(Error::unsupported("the browser sends the requests and sets their headers"));
549        }
550        let transform = HttpHeaderTransform::new(Some(Arc::new(move |kind: Kind, url: &str| {
551            crate::resources::sanitize_headers(transform(kind, url))
552        })));
553        self.apply(move |core| {
554            core.network()?.set_http_header_transform(transform);
555            Ok(())
556        })
557    }
558
559    /// Stops adding headers to HTTP requests.
560    pub fn clear_http_header_transform(&self) -> Result<Completion<()>, Error> {
561        self.apply(move |core| {
562            core.network()?.set_http_header_transform(HttpHeaderTransform::default());
563            Ok(())
564        })
565    }
566
567    /// Runs a maintenance action on the cache database.
568    pub fn run_cache_database_operation(&self, operation: CacheDatabaseOperation) -> Result<Completion<()>, Error> {
569        self.command(move |core, outbox, resolver| {
570            let database = match core.database() {
571                Ok(database) => database,
572                Err(error) => return outbox.resolve(resolver, Err(error)),
573            };
574            let reply = reply_on(core.run_loop.clone(), resolver);
575            match operation {
576                CacheDatabaseOperation::Clear => database.clear_ambient_cache(reply),
577                CacheDatabaseOperation::Invalidate => database.invalidate_ambient_cache(reply),
578                CacheDatabaseOperation::Pack => database.pack_database(reply),
579                CacheDatabaseOperation::Reset => database.reset_database(reply),
580            }
581        })
582    }
583
584    /// Limits the ambient cache to `size` bytes. Offline regions don't count
585    /// toward it.
586    pub fn set_maximum_ambient_cache_size(&self, size: u64) -> Result<Completion<()>, Error> {
587        self.command(move |core, outbox, resolver| match core.database() {
588            Ok(database) => database.set_maximum_ambient_cache_size(size, reply_on(core.run_loop.clone(), resolver)),
589            Err(error) => outbox.resolve(resolver, Err(error)),
590        })
591    }
592
593    /// The offline regions in the runtime's cache database.
594    #[must_use]
595    pub fn offline(&self) -> Offline<'_> {
596        Offline::new(self)
597    }
598
599    /// Shuts the runtime down. The completion reports when its thread has
600    /// let go of its maps' resources and its file sources.
601    ///
602    /// Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind) while the
603    /// runtime has maps that aren't released, or when the runtime was
604    /// released already. Every call on the runtime fails the same way after.
605    pub fn release(&self) -> Result<Completion<()>, Error> {
606        {
607            let mut lifecycle = self.shared.lifecycle.lock_unpoisoned();
608            if lifecycle.released {
609                return Err(released());
610            }
611            if lifecycle.live_maps > 0 {
612                return Err(Error::invalid_state("release the runtime's maps first"));
613            }
614            lifecycle.released = true;
615            lifecycle.shut_down = true;
616        }
617        let (completion, resolver) = self.shared.completion();
618        self.shared.shut_down(Some(resolver));
619        Ok(completion)
620    }
621
622    /// Releases the runtime whatever its state, without waiting: it shuts
623    /// down once its last map is released. Every call on the runtime fails
624    /// with [`ErrorKind::InvalidState`](mln_util::ErrorKind) after.
625    pub fn dispose(&self) -> Result<(), Error> {
626        let shut_down = {
627            let mut lifecycle = self.shared.lifecycle.lock_unpoisoned();
628            if lifecycle.released {
629                return Err(released());
630            }
631            lifecycle.released = true;
632            let shut_down = lifecycle.live_maps == 0;
633            lifecycle.shut_down |= shut_down;
634            shut_down
635        };
636        if shut_down {
637            self.shared.shut_down(None);
638        }
639        Ok(())
640    }
641
642    /// Sends a command for the offline API.
643    pub(crate) fn offline_command<T: Send + 'static>(
644        &self,
645        command: impl FnOnce(&DatabaseFileSource, &RuntimeCore, Resolver<T>) + Send + 'static,
646    ) -> Result<Completion<T>, Error> {
647        self.command(move |core, outbox, resolver| match core.database() {
648            Ok(database) => command(database, core, resolver),
649            Err(error) => outbox.resolve(resolver, Err(error)),
650        })
651    }
652}
653
654// Handles cross threads; the core never leaves its own.
655const _: () = {
656    const fn assert_send_sync<T: Send + Sync>() {}
657    assert_send_sync::<Runtime>();
658    assert_send_sync::<Map>();
659};