Skip to main content

ignite_core/
registries.rs

1//! The registries of one Ignite app.
2//!
3//! Each app owns its registries, as each Laravel application has its own service container:
4//! the runtime resources and the slugs reserved for static resources, the policies, the editor
5//! script and the media library. Nothing is process-wide, so several apps, such as several
6//! admin panels, can live in one process and each sees only what was registered on it.
7//!
8//! `ignite_panel::Ignite::new()` creates an app's registries; [`Registries`] is a handle that
9//! shares them when cloned. An app reaches its handle with `Ignite::registries()` while it is
10//! built and as Rocket managed state (`&State<Registries>`) while it serves. For tests and
11//! libraries that need no panel, [`Registries::new`] makes a separate set.
12//!
13//! ```ignore
14//! let ignite = Ignite::new();
15//! let registries = ignite.registries();
16//! registries.register_editor("/vendor/editor/init.js");
17//! registries.register_runtime(resource)?;
18//! ```
19
20use std::collections::HashMap;
21use std::fmt;
22use std::sync::{Arc, OnceLock, RwLock};
23
24use crate::media::MediaLibrary;
25use crate::policy::Policy;
26use crate::runtime_resource::RuntimeRegistry;
27
28/// The registries of one app. Cloning gives another handle to the same registries; use
29/// [`Registries::new`] for a separate app.
30#[derive(Clone, Default)]
31pub struct Registries {
32    pub(crate) inner: Arc<Inner>,
33}
34
35#[derive(Default)]
36pub(crate) struct Inner {
37    pub(crate) runtime: RwLock<RuntimeRegistry>,
38    pub(crate) policies: RwLock<HashMap<String, Arc<dyn Policy>>>,
39    pub(crate) editor: RwLock<Option<String>>,
40    pub(crate) media: RwLock<Option<Arc<dyn MediaLibrary>>>,
41}
42
43impl Registries {
44    /// An empty set of registries, for a new app.
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    /// The default app's registries: the process-wide set that the free functions of
50    /// `ignite_core` (such as [`register_runtime`](crate::register_runtime)) act on, and that a
51    /// panel built with `Ignite::new()` serves when it takes no handle. Every call returns a
52    /// handle to the same registries.
53    pub fn default_app() -> Self {
54        static DEFAULT_APP: OnceLock<Registries> = OnceLock::new();
55        DEFAULT_APP.get_or_init(Registries::new).clone()
56    }
57
58    /// Whether `other` is a handle to the same registries as `self`.
59    pub fn same_app(&self, other: &Registries) -> bool {
60        Arc::ptr_eq(&self.inner, &other.inner)
61    }
62}
63
64impl fmt::Debug for Registries {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        f.debug_struct("Registries").finish_non_exhaustive()
67    }
68}