Skip to main content

rustango_cms/block/
registry.rs

1//! Block registry — inventory-collected `Block` constructors.
2//!
3//! Mirrors the [`crate::widget::registry`] + [`crate::page_type`]
4//! registry shapes: each crate that defines a [`Block`] submits a
5//! `BlockRegistration` carrying a `fn() -> Box<dyn Block>` factory,
6//! and the framework iterates the global collection at boot to
7//! validate uniqueness + cross-references.
8
9use super::{Block, BlockError, BlockField};
10
11/// One registered block — a factory the framework calls to materialize
12/// a [`Block`] trait object. Each call returns a fresh box (cheap;
13/// `Block`s are stateless descriptors). Submitted via
14/// [`crate::register_block!`].
15pub struct BlockRegistration {
16    /// Constructor function. Convention: `|| Box::new(MyBlock::default())`
17    /// — or any callable returning `Box<dyn Block>`.
18    pub factory: fn() -> Box<dyn Block>,
19    /// The module that registered it (`module_path!()` at the
20    /// `register_block!` call), so a site's block can be told from a
21    /// built-in one of the same name.
22    pub origin: &'static str,
23}
24
25impl BlockRegistration {
26    /// Registered by Rustango-CMS itself.
27    #[must_use]
28    pub fn is_builtin(&self) -> bool {
29        self.origin == "rustango_cms" || self.origin.starts_with("rustango_cms::")
30    }
31}
32
33inventory::collect!(BlockRegistration);
34
35/// Register a [`Block`] at module-load time. Mirrors the
36/// `register_widget!` / `register_page_type!` patterns.
37///
38/// ```ignore
39/// pub struct HeadingBlock;
40///
41/// impl rustango_cms::Block for HeadingBlock {
42///     /* … */
43/// }
44///
45/// rustango_cms::register_block!(HeadingBlock);
46/// ```
47#[macro_export]
48macro_rules! register_block {
49    ($ty:ty) => {
50        $crate::inventory::submit! {
51            $crate::block::BlockRegistration {
52                factory: || Box::new(<$ty>::default()),
53                origin: ::core::module_path!(),
54            }
55        }
56    };
57    // Variant for blocks whose constructor isn't `Default::default()`
58    // — pass any expression returning a `Box<dyn Block>`.
59    ($factory:expr) => {
60        $crate::inventory::submit! {
61            $crate::block::BlockRegistration {
62                factory: $factory,
63                origin: ::core::module_path!(),
64            }
65        }
66    };
67}
68
69/// Every registration, with name clashes resolved once:
70///
71/// - a site's block with the same `type_name` as a built-in **replaces**
72///   the built-in (logged once at info level), so a site can redefine
73///   `rich_text`, `gallery`, … deliberately;
74/// - two site blocks (or two built-ins) with the same name are a mistake:
75///   the first registered wins and the clash is logged once as an error.
76fn resolved() -> &'static [&'static BlockRegistration] {
77    static RESOLVED: std::sync::OnceLock<Vec<&'static BlockRegistration>> = std::sync::OnceLock::new();
78    RESOLVED.get_or_init(|| {
79        let all: Vec<&'static BlockRegistration> = inventory::iter::<BlockRegistration>.into_iter().collect();
80        let mut out: Vec<&'static BlockRegistration> = Vec::with_capacity(all.len());
81        for reg in all {
82            let name = (reg.factory)().type_name();
83            match out.iter().position(|r| (r.factory)().type_name() == name) {
84                None => out.push(reg),
85                Some(i) => {
86                    let kept = out[i];
87                    if kept.is_builtin() && !reg.is_builtin() {
88                        tracing::info!(target: "rustango_cms::block", block = name, by = reg.origin, "a site block replaces the built-in block of the same name");
89                        out[i] = reg;
90                    } else if !kept.is_builtin() && reg.is_builtin() {
91                        tracing::info!(target: "rustango_cms::block", block = name, by = kept.origin, "a site block replaces the built-in block of the same name");
92                    } else {
93                        tracing::error!(
94                            target: "rustango_cms::block",
95                            block = name, kept = kept.origin, ignored = reg.origin,
96                            "two blocks are registered with the same name; the first one is used — rename one of them"
97                        );
98                    }
99                }
100            }
101        }
102        out
103    })
104}
105
106/// Iterator over every registered block, one per `type_name` (see
107/// [`duplicate_block_names`] for how clashes resolve). Each call to the
108/// factory returns a fresh `Box<dyn Block>` — cheap, blocks are
109/// stateless.
110pub fn registered_blocks() -> impl Iterator<Item = Box<dyn Block>> {
111    resolved().iter().map(|r| (r.factory)())
112}
113
114/// Look up a registered block by its `type_name`. Returns `None` when
115/// the name isn't registered; the editor surfaces this as a
116/// schema-drift warning rather than panicking. A site's block wins over
117/// a built-in of the same name.
118#[must_use]
119pub fn find_block(type_name: &str) -> Option<Box<dyn Block>> {
120    registered_blocks().find(|b| b.type_name() == type_name)
121}
122
123/// Names registered more than once **without** a site-over-built-in
124/// override — two site blocks, or two built-ins, sharing a `type_name`.
125/// Empty when the registry is clean. (A site block replacing a built-in
126/// is intentional and not reported here.)
127#[must_use]
128pub fn duplicate_block_names() -> Vec<&'static str> {
129    let mut seen: std::collections::HashMap<&'static str, bool> = std::collections::HashMap::new();
130    let mut dups = Vec::new();
131    for reg in inventory::iter::<BlockRegistration> {
132        let name = (reg.factory)().type_name();
133        match seen.get(name) {
134            None => {
135                seen.insert(name, reg.is_builtin());
136            }
137            Some(&builtin) if builtin != reg.is_builtin() => {}
138            Some(_) => {
139                if !dups.contains(&name) {
140                    dups.push(name);
141                }
142            }
143        }
144    }
145    dups
146}
147
148/// Walk every registered block's [`crate::Block::fields`] and verify
149/// that every `Stream::allowed` entry + every `Repeat::item_type`
150/// resolves to a registered block.
151///
152/// Returns the first dangling reference found; an empty `Ok(())` means
153/// the cross-reference graph is clean.
154///
155/// # Errors
156/// [`BlockError::DanglingReference`] when a block's `fields()`
157/// declares a `Stream::allowed` or `Repeat::item_type` value that
158/// doesn't match any registered block's `type_name`.
159pub fn check_block_references() -> Result<(), BlockError> {
160    let names: std::collections::HashSet<&'static str> =
161        registered_blocks().map(|b| b.type_name()).collect();
162    for block in registered_blocks() {
163        let owner = block.type_name();
164        for field in block.fields() {
165            match field {
166                BlockField::Stream { allowed, .. } => {
167                    for ref_name in &allowed {
168                        if !names.contains(ref_name.as_str()) {
169                            // SAFETY: type_name() returns &'static str
170                            // from the trait, so leaking ref_name into
171                            // the static-ish error type would need an
172                            // intern step. Use a Box::leak for the
173                            // diagnostic message — this only runs once
174                            // at boot and only on misconfiguration.
175                            let leaked: &'static str = Box::leak(ref_name.clone().into_boxed_str());
176                            return Err(BlockError::DanglingReference {
177                                owner,
178                                referred: leaked,
179                            });
180                        }
181                    }
182                }
183                BlockField::Repeat { item_type, .. } => {
184                    if !names.contains(item_type.as_str()) {
185                        let leaked: &'static str = Box::leak(item_type.clone().into_boxed_str());
186                        return Err(BlockError::DanglingReference {
187                            owner,
188                            referred: leaked,
189                        });
190                    }
191                }
192                _ => {}
193            }
194        }
195    }
196    Ok(())
197}
198
199/// Boot-time validation hook. Call once during application startup
200/// before the admin router goes live. Panics with a loud diagnostic
201/// on (a) duplicate `type_name`s, (b) any dangling
202/// `Stream::allowed` / `Repeat::item_type` reference.
203///
204/// Mirrors [`crate::widget::registry::validate_registry`] for
205/// widgets.
206///
207/// # Panics
208/// - On duplicate block names.
209/// - On dangling cross-references.
210pub fn validate_block_registry() {
211    let dups = duplicate_block_names();
212    assert!(
213        dups.is_empty(),
214        "rustango_cms: duplicate block registrations: {dups:?}",
215    );
216    if let Err(e) = check_block_references() {
217        panic!("rustango_cms: block registry has a dangling reference: {e}");
218    }
219}