ignite-core 0.7.3

Core types for Ignite, the admin panel for Rocket.rs: resources, fields, forms and runtime resources.
Documentation
//! The registries of one Ignite app.
//!
//! Each app owns its registries, as each Laravel application has its own service container:
//! the runtime resources and the slugs reserved for static resources, the policies, the editor
//! script and the media library. Nothing is process-wide, so several apps, such as several
//! admin panels, can live in one process and each sees only what was registered on it.
//!
//! `ignite_panel::Ignite::new()` creates an app's registries; [`Registries`] is a handle that
//! shares them when cloned. An app reaches its handle with `Ignite::registries()` while it is
//! built and as Rocket managed state (`&State<Registries>`) while it serves. For tests and
//! libraries that need no panel, [`Registries::new`] makes a separate set.
//!
//! ```ignore
//! let ignite = Ignite::new();
//! let registries = ignite.registries();
//! registries.register_editor("/vendor/editor/init.js");
//! registries.register_runtime(resource)?;
//! ```

use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, OnceLock, RwLock};

use crate::media::MediaLibrary;
use crate::policy::Policy;
use crate::runtime_resource::RuntimeRegistry;

/// The registries of one app. Cloning gives another handle to the same registries; use
/// [`Registries::new`] for a separate app.
#[derive(Clone, Default)]
pub struct Registries {
    pub(crate) inner: Arc<Inner>,
}

#[derive(Default)]
pub(crate) struct Inner {
    pub(crate) runtime: RwLock<RuntimeRegistry>,
    pub(crate) policies: RwLock<HashMap<String, Arc<dyn Policy>>>,
    pub(crate) editor: RwLock<Option<String>>,
    pub(crate) media: RwLock<Option<Arc<dyn MediaLibrary>>>,
}

impl Registries {
    /// An empty set of registries, for a new app.
    pub fn new() -> Self {
        Self::default()
    }

    /// The default app's registries: the process-wide set that the free functions of
    /// `ignite_core` (such as [`register_runtime`](crate::register_runtime)) act on, and that a
    /// panel built with `Ignite::new()` serves when it takes no handle. Every call returns a
    /// handle to the same registries.
    pub fn default_app() -> Self {
        static DEFAULT_APP: OnceLock<Registries> = OnceLock::new();
        DEFAULT_APP.get_or_init(Registries::new).clone()
    }

    /// Whether `other` is a handle to the same registries as `self`.
    pub fn same_app(&self, other: &Registries) -> bool {
        Arc::ptr_eq(&self.inner, &other.inner)
    }
}

impl fmt::Debug for Registries {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Registries").finish_non_exhaustive()
    }
}