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}
20
21inventory::collect!(BlockRegistration);
22
23/// Register a [`Block`] at module-load time. Mirrors the
24/// `register_widget!` / `register_page_type!` patterns.
25///
26/// ```ignore
27/// pub struct HeadingBlock;
28///
29/// impl rustango_cms::Block for HeadingBlock {
30/// /* … */
31/// }
32///
33/// rustango_cms::register_block!(HeadingBlock);
34/// ```
35#[macro_export]
36macro_rules! register_block {
37 ($ty:ty) => {
38 $crate::inventory::submit! {
39 $crate::block::BlockRegistration {
40 factory: || Box::new(<$ty>::default()),
41 }
42 }
43 };
44 // Variant for blocks whose constructor isn't `Default::default()`
45 // — pass any expression returning a `Box<dyn Block>`.
46 ($factory:expr) => {
47 $crate::inventory::submit! {
48 $crate::block::BlockRegistration {
49 factory: $factory,
50 }
51 }
52 };
53}
54
55/// Iterator over every registered block. Each call to the factory
56/// returns a fresh `Box<dyn Block>` — cheap, blocks are stateless.
57pub fn registered_blocks() -> impl Iterator<Item = Box<dyn Block>> {
58 inventory::iter::<BlockRegistration>
59 .into_iter()
60 .map(|r| (r.factory)())
61}
62
63/// Look up a registered block by its `type_name`. Returns `None` when
64/// the name isn't registered; the editor surfaces this as a
65/// schema-drift warning rather than panicking.
66#[must_use]
67pub fn find_block(type_name: &str) -> Option<Box<dyn Block>> {
68 registered_blocks().find(|b| b.type_name() == type_name)
69}
70
71/// Surface duplicate `type_name`s — `Vec` is empty when the registry
72/// is clean. Two blocks with the same `type_name` would pick whichever
73/// one happens to be linked first; loud failure beats silent
74/// arbitrariness.
75#[must_use]
76pub fn duplicate_block_names() -> Vec<&'static str> {
77 let mut seen = std::collections::HashSet::new();
78 let mut dups = Vec::new();
79 for b in registered_blocks() {
80 if !seen.insert(b.type_name()) {
81 dups.push(b.type_name());
82 }
83 }
84 dups
85}
86
87/// Walk every registered block's [`crate::Block::fields`] and verify
88/// that every `Stream::allowed` entry + every `Repeat::item_type`
89/// resolves to a registered block.
90///
91/// Returns the first dangling reference found; an empty `Ok(())` means
92/// the cross-reference graph is clean.
93///
94/// # Errors
95/// [`BlockError::DanglingReference`] when a block's `fields()`
96/// declares a `Stream::allowed` or `Repeat::item_type` value that
97/// doesn't match any registered block's `type_name`.
98pub fn check_block_references() -> Result<(), BlockError> {
99 let names: std::collections::HashSet<&'static str> =
100 registered_blocks().map(|b| b.type_name()).collect();
101 for block in registered_blocks() {
102 let owner = block.type_name();
103 for field in block.fields() {
104 match field {
105 BlockField::Stream { allowed, .. } => {
106 for ref_name in &allowed {
107 if !names.contains(ref_name.as_str()) {
108 // SAFETY: type_name() returns &'static str
109 // from the trait, so leaking ref_name into
110 // the static-ish error type would need an
111 // intern step. Use a Box::leak for the
112 // diagnostic message — this only runs once
113 // at boot and only on misconfiguration.
114 let leaked: &'static str = Box::leak(ref_name.clone().into_boxed_str());
115 return Err(BlockError::DanglingReference {
116 owner,
117 referred: leaked,
118 });
119 }
120 }
121 }
122 BlockField::Repeat { item_type, .. } => {
123 if !names.contains(item_type.as_str()) {
124 let leaked: &'static str = Box::leak(item_type.clone().into_boxed_str());
125 return Err(BlockError::DanglingReference {
126 owner,
127 referred: leaked,
128 });
129 }
130 }
131 _ => {}
132 }
133 }
134 }
135 Ok(())
136}
137
138/// Boot-time validation hook. Call once during application startup
139/// before the admin router goes live. Panics with a loud diagnostic
140/// on (a) duplicate `type_name`s, (b) any dangling
141/// `Stream::allowed` / `Repeat::item_type` reference.
142///
143/// Mirrors [`crate::widget::registry::validate_registry`] for
144/// widgets.
145///
146/// # Panics
147/// - On duplicate block names.
148/// - On dangling cross-references.
149pub fn validate_block_registry() {
150 let dups = duplicate_block_names();
151 assert!(
152 dups.is_empty(),
153 "rustango_cms: duplicate block registrations: {dups:?}",
154 );
155 if let Err(e) = check_block_references() {
156 panic!("rustango_cms: block registry has a dangling reference: {e}");
157 }
158}