Skip to main content

vantage_table/table/
inject.rs

1//! The build injector: a hook a vista factory runs on every table it builds
2//! from a spec — the root, each reference target and each `base:` table —
3//! after the table is built and before it is wrapped. It may add conditions
4//! and register hooks, or fail the build.
5//!
6//! Each backend's spec builder threads a [`BuildEnv`] through its builds and
7//! ends with [`BuildEnv::inject`]; `Table::with_spec_references` hands each
8//! reference target a fresh environment of kind [`BuildKind::Reference`].
9
10use std::cell::Cell;
11use std::fmt;
12use std::sync::Arc;
13
14use vantage_core::{Result, error};
15use vantage_types::EmptyEntity;
16use vantage_vista::SpecResolver;
17
18use crate::table::Table;
19use crate::traits::table_source::TableSource;
20
21/// Why a table is being built.
22#[derive(Clone, Debug, PartialEq, Eq)]
23#[non_exhaustive]
24pub enum BuildKind {
25    /// A table built for its own sake: a factory's `build_from_spec`, or a
26    /// table an injector asked for through [`InjectCx::build`].
27    Root,
28    /// The target of `relation` on the spec named `from`, built when the
29    /// relation is traversed.
30    Reference { from: String, relation: String },
31    /// The `base:` table the spec named `derived` reads from. Only the
32    /// conditions an injector adds here take effect: the derived table is a
33    /// fresh table over the base's `select()`, so hooks registered on a
34    /// `Base` build never fire. Register hooks on the derived build instead.
35    Base { derived: String },
36}
37
38/// What an injector receives besides the table: the spec key being built,
39/// why, and a builder for other tables of the same backend.
40#[non_exhaustive]
41pub struct InjectCx<'a, T: TableSource> {
42    pub key: &'a str,
43    pub kind: BuildKind,
44    /// Build another table by spec key, through the same factory and the
45    /// same injector (its kind is [`BuildKind::Root`]). Errors when the
46    /// factory has no resolver, the key has no spec, or the build would
47    /// re-enter a key already being built (a cycle).
48    pub build: &'a dyn Fn(&str) -> Result<Table<T, EmptyEntity>>,
49}
50
51/// A build injector. Typed per backend, since each backend's table is.
52pub type TableInjector<T> =
53    Arc<dyn Fn(&InjectCx<'_, T>, &mut Table<T, EmptyEntity>) -> Result<()> + Send + Sync>;
54
55/// The spec keys being built, outermost first. Nested builds (an injector
56/// building a parent, a `base:` chain) extend it; re-entering a key is a cycle.
57#[derive(Clone, Debug, Default, PartialEq, Eq)]
58pub struct BuildTrail {
59    keys: Vec<String>,
60}
61
62impl BuildTrail {
63    /// The trail with `key` appended; an error naming the path when `key` is
64    /// already on it.
65    pub fn enter(&self, key: &str) -> Result<BuildTrail> {
66        if self.keys.iter().any(|k| k == key) {
67            let path = self
68                .keys
69                .iter()
70                .map(String::as_str)
71                .chain([key])
72                .collect::<Vec<_>>()
73                .join(" -> ");
74            return Err(error!("table build cycle", path = path));
75        }
76        let mut keys = self.keys.clone();
77        keys.push(key.to_string());
78        Ok(BuildTrail { keys })
79    }
80
81    pub fn keys(&self) -> &[String] {
82        &self.keys
83    }
84}
85
86thread_local! {
87    /// Set while a table is built only for its stored name (see [`bare`]).
88    static BARE: Cell<bool> = const { Cell::new(false) };
89}
90
91struct Bare(bool);
92
93impl Drop for Bare {
94    fn drop(&mut self) {
95        BARE.with(|b| b.set(self.0));
96    }
97}
98
99/// Run `build` with every spec build inside it left uninjected. A table
100/// built only to read its stored name needs no roll-ups, rules or hooks, and
101/// an injected build builds further tables in turn: a has-one typing a link
102/// would build its target, the target's roll-up tables, their links, ….
103pub(crate) fn bare<R>(build: impl FnOnce() -> R) -> R {
104    let _restore = Bare(BARE.with(|b| b.replace(true)));
105    build()
106}
107
108/// Builds a table from spec `S` over data source `T`, carrying the build
109/// environment into nested builds.
110pub type SpecTableBuilder<S, T> = fn(&S, T, &BuildEnv<S, T>) -> Result<Table<T, EmptyEntity>>;
111
112/// What a spec build carries besides the spec and the data source: the
113/// resolver for references and `base:`, the injector, the trail of keys
114/// being built, and the kind of this build.
115pub struct BuildEnv<S, T: TableSource> {
116    pub resolver: Option<Arc<dyn SpecResolver<S>>>,
117    pub injector: Option<TableInjector<T>>,
118    pub trail: BuildTrail,
119    pub kind: BuildKind,
120}
121
122impl<S, T: TableSource> Clone for BuildEnv<S, T> {
123    fn clone(&self) -> Self {
124        Self {
125            resolver: self.resolver.clone(),
126            injector: self.injector.clone(),
127            trail: self.trail.clone(),
128            kind: self.kind.clone(),
129        }
130    }
131}
132
133impl<S, T: TableSource> fmt::Debug for BuildEnv<S, T> {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        f.debug_struct("BuildEnv")
136            .field("resolver", &self.resolver.is_some())
137            .field("injector", &self.injector.is_some())
138            .field("trail", &self.trail)
139            .field("kind", &self.kind)
140            .finish()
141    }
142}
143
144impl<S: 'static, T: TableSource> BuildEnv<S, T> {
145    /// The environment of a root build of `key`.
146    pub fn root(
147        key: &str,
148        resolver: Option<Arc<dyn SpecResolver<S>>>,
149        injector: Option<TableInjector<T>>,
150    ) -> Self {
151        Self {
152            resolver,
153            injector,
154            trail: BuildTrail {
155                keys: vec![key.to_string()],
156            },
157            kind: BuildKind::Root,
158        }
159    }
160
161    /// The environment for building `key` from inside this build, as `kind`.
162    /// Errors when `key` is already being built.
163    pub fn nested(&self, key: &str, kind: BuildKind) -> Result<Self> {
164        Ok(Self {
165            resolver: self.resolver.clone(),
166            injector: self.injector.clone(),
167            trail: self.trail.enter(key)?,
168            kind,
169        })
170    }
171
172    /// Run the injector, if any, on `table`, the result of building `key`.
173    /// `build` is the backend's spec builder, used for the tables the
174    /// injector asks for.
175    pub fn inject(
176        &self,
177        key: &str,
178        table: &mut Table<T, EmptyEntity>,
179        build: SpecTableBuilder<S, T>,
180    ) -> Result<()> {
181        let Some(injector) = self.injector.as_ref().filter(|_| !BARE.with(Cell::get)) else {
182            return Ok(());
183        };
184        let db = table.data_source().clone();
185        let nested = |other: &str| -> Result<Table<T, EmptyEntity>> {
186            let env = self.nested(other, BuildKind::Root)?;
187            let resolver = self.resolver.as_ref().ok_or_else(|| {
188                error!(
189                    "the injector's table builder needs a spec resolver",
190                    key = other
191                )
192            })?;
193            let spec = resolver
194                .resolve(other)
195                .ok_or_else(|| error!("the injector's table builder found no spec", key = other))?;
196            build(&spec, db.clone(), &env)
197        };
198        let cx = InjectCx {
199            key,
200            kind: self.kind.clone(),
201            build: &nested,
202        };
203        injector(&cx, table)
204    }
205}