kumo_template/
lib.rs

1use handlebars::{Handlebars, Renderable, Template as HandlebarsTemplate};
2use lruttl::declare_cache;
3use minijinja::value::{Enumerator, Object, ValueKind};
4use minijinja::{Environment, Template as JinjaTemplate, Value as JinjaValue};
5use minijinja_contrib::add_to_environment;
6use self_cell::self_cell;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::fmt::Write;
10use std::sync::{Arc, LazyLock, OnceLock};
11use std::time::Duration;
12use thiserror::Error;
13
14#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15pub enum TemplateDialect {
16    #[default]
17    Jinja,
18    Static,
19    Handlebars,
20}
21
22/// Builds the minijinja environment that every Jinja template renders with.
23fn new_jinja_environment() -> Environment<'static> {
24    let mut env = Environment::new();
25    env.set_unknown_method_callback(minijinja_contrib::pycompat::unknown_method_callback);
26    add_to_environment(&mut env);
27
28    env.add_filter(
29        "normalize_smtp_response",
30        mod_smtp_response_normalize::normalize,
31    );
32
33    env
34}
35
36/// The registry every Handlebars [`Template`] renders against. A handlebars
37/// template compiles independently of any registry and consults a registry at
38/// render time only to look up helpers. One shared instance serves every
39/// template.
40static HANDLEBARS_REGISTRY: LazyLock<Handlebars<'static>> = LazyLock::new(|| {
41    let mut registry = Handlebars::new();
42    registry.set_recursive_lookup(true);
43    registry
44});
45
46/// Converts a minijinja compile error into an error that names the template
47/// and quotes the offending line of `source`.
48fn describe_jinja_error(err: minijinja::Error, source: &str) -> anyhow::Error {
49    let mut reason = String::new();
50
51    if let Some(detail) = err.detail() {
52        write!(&mut reason, "{}: {}", err.kind(), detail).ok();
53    } else {
54        write!(&mut reason, "{}", err.kind()).ok();
55    }
56
57    if let Some((line_no, source_line)) = err.line().and_then(|line| {
58        source
59            .lines()
60            .nth(line - 1) // err.line() is 1-based
61            .map(|source_line| (line, source_line))
62    }) {
63        let truncated_line = &source_line[..source_line.ceil_char_boundary(1024)];
64
65        if let Some(name) = err.name() {
66            write!(
67                &mut reason,
68                " (in template '{name}' line {line_no}: '{truncated_line}')"
69            )
70            .ok();
71        } else {
72            write!(
73                &mut reason,
74                " (in template line {line_no}: '{truncated_line}')"
75            )
76            .ok();
77        }
78    }
79
80    anyhow::anyhow!("{reason}")
81}
82
83/// Returns true when `source` contains none of the expansion markers of
84/// `dialect`, meaning the engine would render it with no substitution.
85fn source_is_static(dialect: TemplateDialect, source: &str) -> bool {
86    match dialect {
87        TemplateDialect::Static => true,
88        TemplateDialect::Handlebars => !source.contains("{{"),
89        TemplateDialect::Jinja => {
90            !(source.contains("{{") || source.contains("{%") || source.contains("{#"))
91        }
92    }
93}
94
95/// Returns the prefix of `source` that `dialect` renders for a static value:
96/// for Jinja, `source` with one trailing `\n` and then one trailing `\r`
97/// removed, matching the trim the minijinja lexer applies to every template it
98/// compiles. For the other dialects, `source` unchanged.
99fn trim_static_source(dialect: TemplateDialect, source: &str) -> &str {
100    if dialect == TemplateDialect::Jinja {
101        let s = source.strip_suffix('\n').unwrap_or(source);
102        s.strip_suffix('\r').unwrap_or(s)
103    } else {
104        source
105    }
106}
107
108/// Renders `template` against `context` with the escaping rule the registry
109/// expects: substitutions are html-escaped only for a `.html` template name.
110fn render_handlebars(
111    registry: &Handlebars<'static>,
112    template: &HandlebarsTemplate,
113    context: &handlebars::Context,
114) -> anyhow::Result<String> {
115    let mut render_context = handlebars::RenderContext::new(None);
116    render_context.set_recursive_lookup(true);
117    let is_html = template
118        .name
119        .as_deref()
120        .map(|name| name.ends_with(".html"))
121        .unwrap_or(false);
122    render_context.set_disable_escape(!is_html);
123
124    Ok(template.renders(registry, context, &mut render_context)?)
125}
126
127/// A rendering context converted once into the native form of a dialect.
128pub enum PreparedContext {
129    Jinja(JinjaValue),
130    Static,
131    Handlebars(handlebars::Context),
132}
133
134impl PreparedContext {
135    fn new<CTX>(dialect: TemplateDialect, context: CTX) -> anyhow::Result<Self>
136    where
137        CTX: Serialize,
138    {
139        Ok(match dialect {
140            TemplateDialect::Jinja => Self::Jinja(JinjaValue::from_serialize(context)),
141            TemplateDialect::Static => Self::Static,
142            TemplateDialect::Handlebars => {
143                Self::Handlebars(handlebars::Context::from(serde_json::to_value(context)?))
144            }
145        })
146    }
147}
148
149/// A Jinja render context that converts its value on the first lookup, at
150/// most once, and also defines a global value named `alias` that returns
151/// that value.
152struct LazyContext<CTX> {
153    inner: Arc<CTX>,
154    alias: String,
155    converted: OnceLock<JinjaValue>,
156}
157
158impl<CTX: Serialize> LazyContext<CTX> {
159    fn value(&self) -> &JinjaValue {
160        self.converted
161            .get_or_init(|| JinjaValue::from_serialize(&*self.inner))
162    }
163}
164
165impl<CTX> std::fmt::Debug for LazyContext<CTX> {
166    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
167        fmt.debug_struct("LazyContext")
168            .field("alias", &self.alias)
169            .field("converted", &self.converted.get().is_some())
170            .finish()
171    }
172}
173
174impl<CTX: Serialize + Send + Sync + 'static> Object for LazyContext<CTX> {
175    fn get_value(self: &Arc<Self>, key: &JinjaValue) -> Option<JinjaValue> {
176        let key = key.as_str()?;
177        let value = self.value();
178        if value.kind() == ValueKind::Invalid {
179            // Return the `Invalid` value to ensure that the error is
180            // not rendered as an empty value.
181            return Some(value.clone());
182        }
183        if key == self.alias {
184            // The alias is explicitly defined as returning the entire value,
185            // taking precedence over a hypothetical conflicting field with
186            // the same name.
187            return Some(value.clone());
188        }
189        // A missing name must yield None rather than undefined, otherwise the
190        // engine would stop short of its own globals such as `range`.
191        value
192            .get_attr(key)
193            .ok()
194            .filter(|value| !value.is_undefined())
195    }
196
197    fn enumerate(self: &Arc<Self>) -> Enumerator {
198        match self.value().try_iter() {
199            Ok(keys) => Enumerator::Values(
200                keys.filter(|key| key.as_str() != Some(self.alias.as_str()))
201                    .chain(std::iter::once(JinjaValue::from(self.alias.as_str())))
202                    .collect(),
203            ),
204            Err(_) => Enumerator::NonEnumerable,
205        }
206    }
207}
208
209type JinjaTemplateRef<'a> = JinjaTemplate<'a, 'a>;
210
211self_cell!(
212    /// A compiled Jinja template kept together with the environment it
213    /// borrows from.
214    struct OwnedJinja {
215        owner: Environment<'static>,
216        #[covariant]
217        dependent: JinjaTemplateRef,
218    }
219);
220
221enum Compiled {
222    Static(String),
223    Jinja(OwnedJinja),
224    Handlebars(HandlebarsTemplate),
225}
226
227struct TemplateInner {
228    dialect: TemplateDialect,
229    name: String,
230    compiled: Compiled,
231}
232
233/// A compiled template. It owns everything it needs to render, is `Send` and
234/// `Sync`, and is cheap to clone: every clone shares the same compiled state
235/// and can be cached or rendered concurrently from any task.
236#[derive(Clone)]
237pub struct Template(Arc<TemplateInner>);
238
239impl std::fmt::Debug for Template {
240    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
241        fmt.debug_struct("Template")
242            .field("dialect", &self.0.dialect)
243            .field("name", &self.0.name)
244            .field("is_static", &self.is_static())
245            .finish()
246    }
247}
248
249impl Template {
250    /// Compiles `source` as a template of `dialect` named `name`. A name
251    /// ending in `.html` enables html entity escaping of substitutions.
252    /// If `source` is free of expansion markers, a Static Template is
253    /// returned.
254    fn compile(dialect: TemplateDialect, name: &str, source: &str) -> anyhow::Result<Self> {
255        let compiled = if source_is_static(dialect, source) {
256            Compiled::Static(trim_static_source(dialect, source).to_string())
257        } else {
258            match dialect {
259                TemplateDialect::Static => Compiled::Static(source.to_string()),
260                TemplateDialect::Jinja => {
261                    let mut env = new_jinja_environment();
262                    env.add_template_owned(name.to_string(), source.to_string())
263                        .map_err(|err| describe_jinja_error(err, source))?;
264                    Compiled::Jinja(OwnedJinja::try_new(env, |env| env.get_template(name))?)
265                }
266                TemplateDialect::Handlebars => Compiled::Handlebars(
267                    HandlebarsTemplate::compile_with_name(source, name.to_string())?,
268                ),
269            }
270        };
271
272        Ok(Self(Arc::new(TemplateInner {
273            dialect,
274            name: name.to_string(),
275            compiled,
276        })))
277    }
278
279    pub fn dialect(&self) -> TemplateDialect {
280        self.0.dialect
281    }
282
283    pub fn name(&self) -> &str {
284        &self.0.name
285    }
286
287    /// Returns true when this template renders its source verbatim
288    pub fn is_static(&self) -> bool {
289        matches!(self.0.compiled, Compiled::Static(_))
290    }
291
292    /// Renders this template against `ctx`, returning the rendered output.
293    pub fn render<S: Serialize>(&self, ctx: S) -> anyhow::Result<String> {
294        if let Compiled::Static(s) = &self.0.compiled {
295            return Ok(s.clone());
296        }
297        self.render_prepared(&PreparedContext::new(self.0.dialect, ctx)?)
298    }
299
300    /// Renders this template against a prepared context,
301    /// returning the rendered output.
302    pub fn render_prepared(&self, ctx: &PreparedContext) -> anyhow::Result<String> {
303        match (&self.0.compiled, ctx) {
304            (Compiled::Static(s), _) => Ok(s.clone()),
305            (Compiled::Jinja(cell), PreparedContext::Jinja(value)) => {
306                Ok(cell.borrow_dependent().render(value)?)
307            }
308            (Compiled::Handlebars(template), PreparedContext::Handlebars(context)) => {
309                render_handlebars(&HANDLEBARS_REGISTRY, template, context)
310            }
311            _ => anyhow::bail!("prepared context dialect does not match template dialect"),
312        }
313    }
314}
315
316/// Marks a compile error as distinct from a failure of the cache lookup machinery.
317#[derive(Debug, Error)]
318#[error("{0:#}")]
319struct CompileFailure(anyhow::Error);
320
321/// The reason [`TemplateEngine::compile`] failed.
322#[derive(Debug, Clone, Error)]
323pub enum CompileError {
324    /// The source does not and will never compile.
325    #[error("{0:#}")]
326    Compile(Arc<anyhow::Error>),
327    /// The cache could not answer, perhaps due to a timeout.
328    /// Potentially retryable.
329    #[error("{0:#}")]
330    Cache(Arc<anyhow::Error>),
331}
332
333/// Identifies a compiled template in [`COMPILED_TEMPLATES`] by a digest of
334/// its dialect, name and source.
335#[derive(Clone, Debug, Hash, PartialEq, Eq)]
336struct TemplateKey([u8; 32]);
337
338impl TemplateKey {
339    fn new(dialect: TemplateDialect, name: &str, source: &str) -> Self {
340        let mut hasher = blake3::Hasher::new();
341        hasher.update(&[dialect as u8]);
342        hasher.update(&(name.len() as u64).to_le_bytes());
343        hasher.update(name.as_bytes());
344        hasher.update(source.as_bytes());
345        Self(hasher.finalize().into())
346    }
347}
348
349declare_cache! {
350/// Compiled templates from the kumo-template module.
351static COMPILED_TEMPLATES: LruCacheWithTtl<TemplateKey, Template>::new("compiled_templates", 1024);
352}
353
354const COMPILED_TEMPLATE_TTL: Duration = Duration::from_secs(600);
355
356/// Compiles templates in a specific dialect and optionally
357/// provides a registry for named fragments.
358pub struct TemplateEngine {
359    dialect: TemplateDialect,
360    templates: HashMap<String, Template>,
361}
362
363impl TemplateEngine {
364    pub fn new() -> Self {
365        Self::with_dialect(TemplateDialect::default())
366    }
367
368    pub fn with_dialect(dialect: TemplateDialect) -> Self {
369        Self {
370            dialect,
371            templates: HashMap::new(),
372        }
373    }
374
375    pub fn dialect(&self) -> TemplateDialect {
376        self.dialect
377    }
378
379    /// Add a named template with the specified source. If name ends with
380    /// `.html` then automatic escaping of html entities will be performed on
381    /// substitutions.
382    ///
383    /// A source that is free of expansion markers for the active dialect is
384    /// stored as a literal static template, bypassing the compiler and
385    /// evaluator of the engine entirely.
386    pub fn add_template<N, S>(&mut self, name: N, source: S) -> anyhow::Result<()>
387    where
388        N: Into<String>,
389        S: AsRef<str>,
390    {
391        let name = name.into();
392        let template = Template::compile(self.dialect, &name, source.as_ref())?;
393        self.templates.insert(name, template);
394        Ok(())
395    }
396
397    /// Returns the template registered under `name` with
398    /// [`TemplateEngine::add_template`].
399    pub fn get_template(&self, name: &str) -> anyhow::Result<Template> {
400        self.templates
401            .get(name)
402            .cloned()
403            .ok_or_else(|| anyhow::anyhow!("template {name} is not defined"))
404    }
405
406    /// Compiles `source` as a template named `name`, without registering it.
407    /// The compilation is cached.
408    pub async fn compile(&self, name: &str, source: &str) -> Result<Template, CompileError> {
409        let dialect = self.dialect;
410
411        // Static fragments are returned directly, as the copy is much cheaper
412        // than maintaining a cached entry.
413        if source_is_static(dialect, source) {
414            return Template::compile(dialect, name, source)
415                .map_err(|err| CompileError::Compile(Arc::new(err)));
416        }
417
418        let key = TemplateKey::new(dialect, name, source);
419        let lookup = COMPILED_TEMPLATES
420            .get_or_try_insert(&key, |_| COMPILED_TEMPLATE_TTL, async {
421                Template::compile(dialect, name, source).map_err(CompileFailure)
422            })
423            .await
424            .map_err(|err| {
425                if err.downcast_ref::<CompileFailure>().is_some() {
426                    CompileError::Compile(err)
427                } else {
428                    CompileError::Cache(err)
429                }
430            })?;
431        Ok(lookup.item)
432    }
433
434    /// Converts `context` into the native form for this engine's dialect,
435    /// producing a [`PreparedContext`] that can render more than one template
436    /// without being converted again.
437    pub fn prepare_context<CTX>(&self, context: CTX) -> anyhow::Result<PreparedContext>
438    where
439        CTX: Serialize,
440    {
441        PreparedContext::new(self.dialect, context)
442    }
443
444    /// Converts `context` as [`TemplateEngine::prepare_context`] does, and in
445    /// addition binds the whole converted value to a global variable
446    /// named `alias`.
447    pub fn prepare_context_with_alias<CTX>(
448        &self,
449        context: Arc<CTX>,
450        alias: &str,
451    ) -> anyhow::Result<PreparedContext>
452    where
453        CTX: Serialize + Send + Sync + 'static,
454    {
455        Ok(match self.dialect {
456            TemplateDialect::Jinja => {
457                PreparedContext::Jinja(JinjaValue::from_object(LazyContext {
458                    inner: context,
459                    alias: alias.to_string(),
460                    converted: OnceLock::new(),
461                }))
462            }
463            TemplateDialect::Static => PreparedContext::Static,
464            TemplateDialect::Handlebars => {
465                let mut root = serde_json::to_value(&*context)?;
466                let whole = root.clone();
467                if let Some(fields) = root.as_object_mut() {
468                    fields.insert(alias.to_string(), whole);
469                }
470                PreparedContext::Handlebars(handlebars::Context::from(root))
471            }
472        })
473    }
474
475    /// Compiles `source` and renders it against `context` in one step.
476    pub fn render<CTX>(&self, name: &str, source: &str, context: CTX) -> anyhow::Result<String>
477    where
478        CTX: Serialize,
479    {
480        Template::compile(self.dialect, name, source)?.render(context)
481    }
482}
483
484#[cfg(test)]
485mod tests {
486    use super::*;
487    use serde_json::json;
488
489    const DIALECTS: [TemplateDialect; 3] = [
490        TemplateDialect::Jinja,
491        TemplateDialect::Handlebars,
492        TemplateDialect::Static,
493    ];
494
495    /// A marker-free source is a static template and renders to itself across
496    /// every dialect, ignoring the supplied context.
497    #[test]
498    fn marker_free_source_is_static() {
499        for dialect in DIALECTS {
500            let mut engine = TemplateEngine::with_dialect(dialect);
501            engine
502                .add_template("h", "In-Reply-To: <abc@example.com>")
503                .unwrap();
504            let t = engine.get_template("h").unwrap();
505            assert!(
506                t.is_static(),
507                "{dialect:?} should treat marker-free source as static"
508            );
509            k9::assert_equal!(
510                t.render(json!({"name": "ignored"})).unwrap(),
511                "In-Reply-To: <abc@example.com>".to_string()
512            );
513        }
514    }
515
516    /// Confirms a static template renders a marker-free source to the same
517    /// bytes the real engine would have produced for it, for Jinja (whose
518    /// lexer strips trailing bytes) and Handlebars (whose lexer does not).
519    #[test]
520    fn static_render_matches_engine_on_trailing_newline() {
521        // (source, expected output) pairs, expected being what the Jinja or
522        // Handlebars engine renders for that source.
523        let jinja_cases = [
524            ("text\n", "text"),
525            ("text\r\n", "text"),
526            ("text\n\n", "text\n"),
527            ("text", "text"),
528        ];
529        for (src, expected) in jinja_cases {
530            let mut engine = TemplateEngine::with_dialect(TemplateDialect::Jinja);
531            engine.add_template("t", src).unwrap();
532            let out = engine.get_template("t").unwrap().render(json!({})).unwrap();
533            k9::assert_equal!(out, expected.to_string());
534        }
535
536        let hbs_cases = [
537            ("text\n", "text\n"),
538            ("text\r\n", "text\r\n"),
539            ("text\n\n", "text\n\n"),
540            ("text", "text"),
541        ];
542        for (src, expected) in hbs_cases {
543            let mut engine = TemplateEngine::with_dialect(TemplateDialect::Handlebars);
544            engine.add_template("t", src).unwrap();
545            let out = engine.get_template("t").unwrap().render(json!({})).unwrap();
546            k9::assert_equal!(out, expected.to_string());
547        }
548
549        // TemplateEngine::render, the one-shot path used when a named template
550        // is not pre-added, strips the same trailing newline.
551        let jinja2 = TemplateEngine::with_dialect(TemplateDialect::Jinja);
552        k9::assert_equal!(
553            jinja2.render("t", "text\n", json!({})).unwrap(),
554            "text".to_string()
555        );
556    }
557
558    /// A prepared context renders identically to passing the serde context
559    /// directly, for dynamic and static templates in every dialect.
560    #[test]
561    fn render_prepared_matches_render() {
562        for dialect in DIALECTS {
563            let mut engine = TemplateEngine::with_dialect(dialect);
564            engine.add_template("dyn", "hello {{ name }}").unwrap();
565            engine.add_template("lit", "no markers here").unwrap();
566
567            let ctx = json!({"name": "Alice"});
568            let prepared = engine.prepare_context(&ctx).unwrap();
569            for key in ["dyn", "lit"] {
570                let template = engine.get_template(key).unwrap();
571                k9::assert_equal!(
572                    template.render_prepared(&prepared).unwrap(),
573                    template.render(&ctx).unwrap()
574                );
575            }
576        }
577    }
578
579    /// Confirms that a source containing a marker is rendered by the engine
580    /// rather than treated as static, even when the marker is a comment that
581    /// substitutes no value.
582    #[test]
583    fn marked_source_is_dynamic() {
584        let mut jinja = TemplateEngine::with_dialect(TemplateDialect::Jinja);
585        jinja.add_template("h", "hello {{ name }}").unwrap();
586        let t = jinja.get_template("h").unwrap();
587        assert!(!t.is_static());
588        k9::assert_equal!(
589            t.render(json!({"name": "Alice"})).unwrap(),
590            "hello Alice".to_string()
591        );
592
593        let mut hbs = TemplateEngine::with_dialect(TemplateDialect::Handlebars);
594        hbs.add_template("h", "hello {{ name }}").unwrap();
595        assert!(!hbs.get_template("h").unwrap().is_static());
596
597        // Jinja statement and comment markers also keep a source dynamic.
598        let mut j2 = TemplateEngine::with_dialect(TemplateDialect::Jinja);
599        j2.add_template("c", "{# comment #}kept").unwrap();
600        assert!(!j2.get_template("c").unwrap().is_static());
601    }
602
603    /// HTML auto-escaping applies to substituted values, never to literal
604    /// markup, and is selected by the `.html` name suffix in both engine
605    /// dialects. A marker-free source is all literal and renders unescaped.
606    #[test]
607    fn html_escaping_applies_only_to_substitutions() {
608        let literal = "<b>bold &amp; <i>italic</i></b>";
609
610        for dialect in [TemplateDialect::Jinja, TemplateDialect::Handlebars] {
611            let mut engine = TemplateEngine::with_dialect(dialect);
612            engine.add_template("static.html", literal).unwrap();
613            let static_template = engine.get_template("static.html").unwrap();
614            assert!(static_template.is_static());
615            k9::assert_equal!(
616                static_template.render(json!({})).unwrap(),
617                literal.to_string()
618            );
619
620            engine
621                .add_template("dynamic.html", "<b>{{ v }}</b>")
622                .unwrap();
623            let dynamic_template = engine.get_template("dynamic.html").unwrap();
624            assert!(!dynamic_template.is_static());
625            k9::assert_equal!(
626                dynamic_template.render(json!({"v": "a & b"})).unwrap(),
627                "<b>a &amp; b</b>".to_string()
628            );
629
630            engine
631                .add_template("dynamic.txt", "<b>{{ v }}</b>")
632                .unwrap();
633            k9::assert_equal!(
634                engine
635                    .get_template("dynamic.txt")
636                    .unwrap()
637                    .render(json!({"v": "a & b"}))
638                    .unwrap(),
639                "<b>a & b</b>".to_string()
640            );
641        }
642    }
643
644    /// A compile error reports the template name and the offending line.
645    #[test]
646    fn compile_error_names_template() {
647        let mut engine = TemplateEngine::with_dialect(TemplateDialect::Jinja);
648        let err = engine.add_template("t.txt", "ok\n{{ name").unwrap_err();
649        k9::snapshot!(
650            err.to_string(),
651            "syntax error: unexpected end of input, expected end of variable block (in template 't.txt' line 2: '{{ name')"
652        );
653    }
654
655    /// A template from the cached compile path renders the same output as the
656    /// same source registered with add_template, in every dialect.
657    #[tokio::test]
658    async fn compile_matches_add_template() {
659        for dialect in DIALECTS {
660            let ctx = json!({"name": "Alice"});
661            for source in ["hello {{ name }}", "no markers here", "trailing\n"] {
662                let mut engine = TemplateEngine::with_dialect(dialect);
663                engine.add_template("t.txt", source).unwrap();
664                let registered = engine.get_template("t.txt").unwrap();
665
666                let compiled = engine.compile("t.txt", source).await.unwrap();
667                k9::assert_equal!(compiled.is_static(), registered.is_static());
668                k9::assert_equal!(
669                    compiled.render(&ctx).unwrap(),
670                    registered.render(&ctx).unwrap()
671                );
672            }
673        }
674    }
675
676    /// Repeated compiles of the same dialect, name and source share one
677    /// compilation. A change to any of the three compiles afresh.
678    #[tokio::test]
679    async fn compile_shares_one_compilation() {
680        let source = "cached {{ name }} compile_shares_one_compilation";
681        let jinja = TemplateEngine::with_dialect(TemplateDialect::Jinja);
682        let first = jinja.compile("t.txt", source).await.unwrap();
683        let again = jinja.compile("t.txt", source).await.unwrap();
684        assert!(Arc::ptr_eq(&first.0, &again.0));
685
686        let other_name = jinja.compile("u.txt", source).await.unwrap();
687        assert!(!Arc::ptr_eq(&first.0, &other_name.0));
688
689        let hbs = TemplateEngine::with_dialect(TemplateDialect::Handlebars);
690        let other_dialect = hbs.compile("t.txt", source).await.unwrap();
691        assert!(!Arc::ptr_eq(&first.0, &other_dialect.0));
692        k9::assert_equal!(other_dialect.dialect(), TemplateDialect::Handlebars);
693
694        k9::assert_equal!(
695            first.render(json!({"name": "Alice"})).unwrap(),
696            "cached Alice compile_shares_one_compilation".to_string()
697        );
698    }
699
700    // Rendering a static template skips the conversion step where
701    // serialization would fail, unlike a dynamic template of the same dialect.
702    #[test]
703    fn static_render_does_not_serialize_context() {
704        struct Unserializable;
705
706        impl Serialize for Unserializable {
707            fn serialize<S>(&self, _ser: S) -> Result<S::Ok, S::Error>
708            where
709                S: serde::Serializer,
710            {
711                Err(serde::ser::Error::custom("cannot serialize"))
712            }
713        }
714
715        for dialect in [TemplateDialect::Jinja, TemplateDialect::Handlebars] {
716            let mut engine = TemplateEngine::with_dialect(dialect);
717            engine.add_template("lit", "no markers here").unwrap();
718            k9::assert_equal!(
719                engine
720                    .get_template("lit")
721                    .unwrap()
722                    .render(Unserializable)
723                    .unwrap(),
724                "no markers here".to_string()
725            );
726
727            engine.add_template("dyn", "hello {{ name }}").unwrap();
728            let err = engine
729                .get_template("dyn")
730                .unwrap()
731                .render(Unserializable)
732                .unwrap_err();
733            let expected = match dialect {
734                TemplateDialect::Jinja => {
735                    "could not serialize to value: cannot serialize".to_string()
736                }
737                _ => "cannot serialize".to_string(),
738            };
739            k9::assert_equal!(err.to_string(), expected);
740        }
741    }
742
743    /// A compile failure comes back through the cache as the `Compile`
744    /// variant with its message intact.
745    #[tokio::test]
746    async fn compile_reports_errors() {
747        let engine = TemplateEngine::with_dialect(TemplateDialect::Jinja);
748        let err = engine.compile("bad.txt", "{{ nope").await.unwrap_err();
749        assert!(
750            matches!(err, CompileError::Compile(_)),
751            "expected Compile, got {err:?}"
752        );
753        k9::snapshot!(
754            err.to_string(),
755            "syntax error: unexpected end of input, expected end of variable block (in template 'bad.txt' line 1: '{{ nope')"
756        );
757    }
758
759    /// A log record that counts how many times it is serialized.
760    struct CountingRecord {
761        serializations: std::sync::atomic::AtomicUsize,
762    }
763
764    impl Serialize for CountingRecord {
765        fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
766            self.serializations
767                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
768            json!({"type": "Delivery", "size": 1047}).serialize(serializer)
769        }
770    }
771
772    fn counting_record() -> Arc<CountingRecord> {
773        Arc::new(CountingRecord {
774            serializations: std::sync::atomic::AtomicUsize::new(0),
775        })
776    }
777
778    /// A record that serializes to JSON with a `log_record` key that
779    /// (potentially) shadows the global alias name.
780    struct ShadowingRecord;
781
782    impl Serialize for ShadowingRecord {
783        fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
784            json!({"type": "Delivery", "log_record": "shadowed"}).serialize(serializer)
785        }
786    }
787
788    /// Checks that an aliased context exposes the value's fields at the top
789    /// level and the whole value under the alias, in both engine dialects.
790    #[test]
791    fn aliased_context_exposes_fields_and_whole_value() {
792        for dialect in [TemplateDialect::Jinja, TemplateDialect::Handlebars] {
793            let mut engine = TemplateEngine::with_dialect(dialect);
794            engine
795                .add_template("t", "{{ type }}/{{ size }} {{ log_record.type }}")
796                .unwrap();
797            let prepared = engine
798                .prepare_context_with_alias(counting_record(), "log_record")
799                .unwrap();
800            k9::assert_equal!(
801                engine
802                    .get_template("t")
803                    .unwrap()
804                    .render_prepared(&prepared)
805                    .unwrap(),
806                "Delivery/1047 Delivery".to_string()
807            );
808        }
809
810        let mut jinja = TemplateEngine::with_dialect(TemplateDialect::Jinja);
811        jinja
812            .add_template("json", "{{ log_record | tojson }}")
813            .unwrap();
814        let prepared = jinja
815            .prepare_context_with_alias(counting_record(), "log_record")
816            .unwrap();
817        k9::assert_equal!(
818            jinja
819                .get_template("json")
820                .unwrap()
821                .render_prepared(&prepared)
822                .unwrap(),
823            r#"{"size":1047,"type":"Delivery"}"#.to_string()
824        );
825    }
826
827    /// Checks that the alias wins over a field of the same name in both
828    /// engine dialects, with that field still reachable through the alias.
829    #[test]
830    fn aliased_context_alias_wins_over_field() {
831        for dialect in [TemplateDialect::Jinja, TemplateDialect::Handlebars] {
832            let mut engine = TemplateEngine::with_dialect(dialect);
833            engine
834                .add_template("t", "{{ log_record.type }}/{{ log_record.log_record }}")
835                .unwrap();
836            let prepared = engine
837                .prepare_context_with_alias(Arc::new(ShadowingRecord), "log_record")
838                .unwrap();
839            k9::assert_equal!(
840                engine
841                    .get_template("t")
842                    .unwrap()
843                    .render_prepared(&prepared)
844                    .unwrap(),
845                "Delivery/shadowed".to_string()
846            );
847        }
848    }
849
850    /// Reports the serialization failure for both a top-level field and the
851    /// alias itself when an aliased Jinja context value fails to serialize,
852    /// rather than rendering an empty substitution.
853    #[test]
854    fn aliased_context_reports_serialization_failure() {
855        struct Unserializable;
856
857        impl Serialize for Unserializable {
858            fn serialize<S>(&self, _ser: S) -> Result<S::Ok, S::Error>
859            where
860                S: serde::Serializer,
861            {
862                Err(serde::ser::Error::custom("cannot serialize"))
863            }
864        }
865
866        let mut engine = TemplateEngine::with_dialect(TemplateDialect::Jinja);
867        engine.add_template("field", "{{ name }}").unwrap();
868        engine.add_template("alias", "{{ log_record }}").unwrap();
869        let prepared = engine
870            .prepare_context_with_alias(Arc::new(Unserializable), "log_record")
871            .unwrap();
872        for (name, expected) in [
873            (
874                "field",
875                "could not serialize to value: cannot serialize (in field:1)",
876            ),
877            (
878                "alias",
879                "could not serialize to value: cannot serialize (in alias:1)",
880            ),
881        ] {
882            let err = engine
883                .get_template(name)
884                .unwrap()
885                .render_prepared(&prepared)
886                .unwrap_err();
887            k9::assert_equal!(err.to_string(), expected.to_string());
888        }
889    }
890
891    /// Converts a Jinja aliased context value at most once, on the first name
892    /// lookup of any kind, however many fields and renders read it.
893    /// Names not defined in the value must still be resolved against
894    /// engine-provided globals.
895    #[test]
896    fn aliased_context_serializes_at_most_once() {
897        let mut engine = TemplateEngine::with_dialect(TemplateDialect::Jinja);
898        engine
899            .add_template("fields", "{{ type }} {{ size }} {{ log_record.size }}")
900            .unwrap();
901        engine
902            .add_template("globals", "{{ range(3) | length }}")
903            .unwrap();
904
905        let record = counting_record();
906        let prepared = engine
907            .prepare_context_with_alias(record.clone(), "log_record")
908            .unwrap();
909        let reads = || {
910            record
911                .serializations
912                .load(std::sync::atomic::Ordering::Relaxed)
913        };
914
915        k9::assert_equal!(reads(), 0);
916        let globals = engine.get_template("globals").unwrap();
917        k9::assert_equal!(globals.render_prepared(&prepared).unwrap(), "3".to_string());
918        k9::assert_equal!(reads(), 1);
919
920        let fields = engine.get_template("fields").unwrap();
921        for _ in 0..3 {
922            k9::assert_equal!(
923                fields.render_prepared(&prepared).unwrap(),
924                "Delivery 1047 1047".to_string()
925            );
926        }
927        k9::assert_equal!(reads(), 1);
928    }
929}