Skip to main content

rustango_cms/block/
enrich.rs

1//! Host-registrable async stream enrichment.
2//!
3//! [`Block::render`](super::Block::render) is synchronous, so a block
4//! cannot fetch anything while it renders. The CMS already works around
5//! that for its own chooser blocks: `enrich_chooser_refs_async` walks a
6//! parsed stream **before** the sync render and writes resolved data
7//! into each block's `value` under `_`-prefixed keys, so the template
8//! only ever reads what is already there.
9//!
10//! That walker knows a fixed set of block types. This hook opens the
11//! same moment to host applications: a block that needs a query result,
12//! a third-party API response or anything else async can fill its own
13//! value in, then render synchronously like every other block.
14//!
15//! ```ignore
16//! fn enrich<'a>(stream: &'a mut serde_json::Value, pool: &'a Pool)
17//!     -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>
18//! {
19//!     Box::pin(async move {
20//!         // walk `stream`, fill `value._rows` on blocks you own
21//!     })
22//! }
23//! rustango_cms::register_block_enricher!(enrich);
24//! ```
25//!
26//! ## Contract
27//!
28//! * **Own your own block types.** Enrichers all see the same stream.
29//!   Match on `type` and touch nothing else; the CMS's own chooser
30//!   enrichment has already run by this point and its `_` keys are not
31//!   yours to rewrite.
32//! * **Use the `_` prefix**, as the built-in enrichment does, so
33//!   injected keys can never collide with an author-defined field.
34//! * **Recurse yourself** if your blocks can nest inside `Stream` /
35//!   `Repeat` fields. The fan-out hands each enricher the whole stream
36//!   once rather than guessing at a traversal that fits every host.
37//! * **Don't fail the page.** Report a problem by writing it into the
38//!   value (`_error`) so the template can render it; the enrichment
39//!   moment has no error channel, because a report that cannot load is
40//!   a broken widget, not a broken page.
41//!
42//! Enrichers run **sequentially** in registration order, and each one
43//! gets `&mut` to the whole stream — concurrency across enrichers would
44//! need a lock per call and buy nothing, since the work inside one
45//! enricher (which is where the fan-out actually pays) is free to be as
46//! concurrent as it likes.
47
48use std::future::Future;
49use std::pin::Pin;
50
51use rustango::sql::Pool;
52
53/// Boxed future returned by a [`BlockEnricher`]. Borrows both the
54/// stream it mutates and the context it reads from, so an enricher can
55/// hold either across an await without cloning.
56pub type EnrichFuture<'a> = Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
57
58/// What an enricher is told about the render it is part of.
59///
60/// A struct rather than a bare `&Pool` so this can gain fields without
61/// breaking every registered enricher — and because the pool alone is
62/// not enough to answer "where am I?", which is the first thing a block
63/// that inherits something from its page needs to know.
64///
65/// `#[non_exhaustive]` so a new field breaks no one: a host that
66/// drives the walker builds one with [`EnrichCtx::new`].
67#[derive(Clone, Copy)]
68#[non_exhaustive]
69pub struct EnrichCtx<'a> {
70    /// The tenant's database.
71    pub pool: &'a Pool,
72    /// The tenant this render belongs to, or `""` when the caller did
73    /// not supply one (the non-`_with` pre-render, or a host driving
74    /// the walker itself).
75    ///
76    /// An enricher that caches **must** include this in its key. The
77    /// pool is already tenant-specific, so the query is safe either way
78    /// — but a process-wide cache keyed on a row id alone will serve one
79    /// tenant another tenant's data, and that is not a failure anything
80    /// downstream can detect.
81    pub tenant: &'a str,
82    /// The page whose stream this is, when there is one. `None` for
83    /// renders with no page behind them — a preview of unsaved content,
84    /// or a host calling the pre-render directly.
85    pub page_id: Option<i64>,
86}
87
88impl<'a> EnrichCtx<'a> {
89    /// The context for one render: the tenant's pool, its slug, and the
90    /// page the stream belongs to, if any.
91    #[must_use]
92    pub fn new(pool: &'a Pool, tenant: &'a str, page_id: Option<i64>) -> Self {
93        Self { pool, tenant, page_id }
94    }
95}
96
97/// A host-registered async enrichment pass over one parsed stream.
98///
99/// A plain `fn` pointer rather than a boxed closure: the registration
100/// is collected by `inventory` at link time, which needs a value that
101/// can be built in a `static` initializer.
102#[derive(Clone, Copy)]
103pub struct BlockEnricher(
104    pub for<'a> fn(&'a mut serde_json::Value, EnrichCtx<'a>) -> EnrichFuture<'a>,
105);
106
107inventory::collect!(BlockEnricher);
108
109/// Register a [`BlockEnricher`] at compile time.
110///
111/// The submission lives in a static initializer, so a binary that never
112/// otherwise mentions the containing module can have it stripped by the
113/// linker. Reference the module from `main` (the `blocks::link()`
114/// convention) to keep it.
115#[macro_export]
116macro_rules! register_block_enricher {
117    ($f:expr) => {
118        ::rustango_cms::inventory::submit! {
119            $crate::block::enrich::BlockEnricher($f)
120        }
121    };
122}
123
124/// Run every registered enricher over `stream`, in registration order.
125///
126/// Called from the public pre-render right after the built-in chooser
127/// enrichment, so hosts see a stream whose `page_chooser` / `image` /
128/// `snippet_chooser` blocks are already resolved.
129///
130/// A panicking enricher is **not** caught here, unlike the sync hooks
131/// in [`crate::hooks`]: catching across an await point would need the
132/// future to be `UnwindSafe`, which a `&mut` borrow of the stream is
133/// not. An enricher that panics takes the request down — so keep the
134/// fallible parts inside a `Result` and write the failure into the
135/// value.
136pub async fn fire(stream: &mut serde_json::Value, ctx: EnrichCtx<'_>) {
137    for hook in inventory::iter::<BlockEnricher>() {
138        (hook.0)(stream, ctx).await;
139    }
140}
141
142/// Whether any enricher is registered. Lets a caller skip the walk
143/// entirely on the overwhelmingly common path where a deployment has
144/// registered none.
145#[must_use]
146pub fn any_registered() -> bool {
147    inventory::iter::<BlockEnricher>().next().is_some()
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    /// The library registers no enricher of its own, so the hook must
155    /// cost nothing in a deployment that doesn't use it. The fan-out
156    /// with an enricher actually registered is exercised end to end in
157    /// `tests/block_enrich.rs` — a registration is process-wide, so it
158    /// can't share a test binary with this assertion.
159    #[test]
160    fn nothing_is_registered_by_the_library_itself() {
161        assert!(!any_registered());
162    }
163}