Skip to main content

graphrt_core/
template.rs

1//! Variable templates: `Hello {{#start.name#}}, you said {{#sys.query#}}`.
2//!
3//! Templates are parsed once into [`Template`] parts at load time. Rendering
4//! never re-parses resolved values, so a variable whose content looks like a
5//! placeholder cannot inject further lookups.
6
7use std::fmt;
8
9use serde::{Deserialize, Deserializer, Serialize, Serializer};
10
11use crate::pool::{Selector, VariablePool};
12use crate::value::Value;
13
14/// One piece of a parsed template.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub enum Part {
17    Text(String),
18    Var(Selector),
19}
20
21/// A parsed `{{#ns.name.path#}}` template.
22#[derive(Clone, Default, PartialEq, Eq)]
23pub struct Template {
24    source: String,
25    parts: Vec<Part>,
26}
27
28impl Template {
29    /// Parse a template. Anything that is not a well-formed placeholder stays literal text.
30    pub fn parse(source: &str) -> Self {
31        let mut parts = Vec::new();
32        let mut text = String::new();
33        let mut rest = source;
34        while let Some(start) = rest.find("{{#") {
35            let (before, after_open) = rest.split_at(start);
36            text.push_str(before);
37            let body_start = &after_open[3..];
38            let Some((selector, end)) = placeholder_at(body_start) else {
39                // Not a placeholder: keep the opener as text and scan on after it.
40                text.push_str("{{#");
41                rest = body_start;
42                continue;
43            };
44            if !text.is_empty() {
45                parts.push(Part::Text(std::mem::take(&mut text)));
46            }
47            parts.push(Part::Var(selector));
48            rest = &body_start[end + 3..];
49        }
50        text.push_str(rest);
51        if !text.is_empty() {
52            parts.push(Part::Text(text));
53        }
54        Self { source: source.to_owned(), parts }
55    }
56
57    pub fn source(&self) -> &str {
58        &self.source
59    }
60
61    pub fn parts(&self) -> &[Part] {
62        &self.parts
63    }
64
65    /// Selectors referenced by this template, in order of appearance.
66    pub fn selectors(&self) -> impl Iterator<Item = &Selector> {
67        self.parts.iter().filter_map(|p| match p {
68            Part::Var(s) => Some(s),
69            Part::Text(_) => None,
70        })
71    }
72
73    /// Whether the template has no placeholders.
74    pub fn is_static(&self) -> bool {
75        self.selectors().next().is_none()
76    }
77
78    /// Render to text. Missing variables render as empty text; secrets are masked.
79    pub fn render(&self, pool: &VariablePool) -> String {
80        self.render_with(pool, Value::to_text)
81    }
82
83    /// Render revealing secrets. Only for nodes that must transmit plaintext
84    /// (e.g. HTTP auth headers).
85    pub fn render_exposed(&self, pool: &VariablePool) -> String {
86        self.render_with(pool, Value::to_text_exposed)
87    }
88
89    fn render_with(&self, pool: &VariablePool, f: fn(&Value) -> String) -> String {
90        let mut out = String::with_capacity(self.source.len());
91        for part in &self.parts {
92            match part {
93                Part::Text(t) => out.push_str(t),
94                Part::Var(sel) => {
95                    if let Some(v) = pool.get(sel) {
96                        out.push_str(&f(&v));
97                    }
98                }
99            }
100        }
101        out
102    }
103
104    /// If the template is exactly one placeholder, resolve it to the typed value
105    /// (so `"{{#llm.json#}}"` yields an object rather than its text). Otherwise render text.
106    pub fn resolve(&self, pool: &VariablePool) -> Value {
107        match self.parts.as_slice() {
108            [Part::Var(sel)] => pool.get_or_null(sel),
109            _ => Value::from(self.render(pool)),
110        }
111    }
112}
113
114/// Longest placeholder body that can be a selector.
115const MAX_PLACEHOLDER_BYTES: usize = 512;
116
117/// Offset of the `#}}` closing a placeholder body, looked for only as far as
118/// the longest possible body. Searching the rest of the text made a source
119/// with many `{{#` and one late `#}}` quadratic to parse.
120fn find_placeholder_end(body_start: &str) -> Option<usize> {
121    let window = body_start.as_bytes();
122    let window = window.get(..window.len().min(MAX_PLACEHOLDER_BYTES + 3)).unwrap_or(window);
123    // `#}}` is ASCII, so its offset is a char boundary.
124    window.windows(3).position(|w| w == b"#}}")
125}
126
127/// The selector of a well-formed placeholder whose body starts at `body_start`
128/// (just after `{{#`), with the offset of its closing `#}}`.
129fn placeholder_at(body_start: &str) -> Option<(Selector, usize)> {
130    let end = find_placeholder_end(body_start)?;
131    let selector = parse_placeholder(body_start.get(..end)?)?;
132    Some((selector, end))
133}
134
135fn parse_placeholder(body: &str) -> Option<Selector> {
136    if body.is_empty() || body.len() > MAX_PLACEHOLDER_BYTES {
137        return None;
138    }
139    let valid =
140        body.split('.').all(|seg| !seg.is_empty() && seg.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-'));
141    if !valid {
142        return None;
143    }
144    Selector::parse(body).ok()
145}
146
147impl fmt::Debug for Template {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        write!(f, "Template({:?})", self.source)
150    }
151}
152
153impl From<&str> for Template {
154    fn from(s: &str) -> Self {
155        Template::parse(s)
156    }
157}
158
159impl Serialize for Template {
160    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
161        serializer.serialize_str(&self.source)
162    }
163}
164
165impl<'de> Deserialize<'de> for Template {
166    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
167        let s = String::deserialize(deserializer)?;
168        Ok(Template::parse(&s))
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    fn pool() -> VariablePool {
177        let mut p = VariablePool::new();
178        p.insert("sys", "query", Value::from("hi"));
179        p.insert("n", "obj", Value::from_json(serde_json::json!({"list": ["a", "b"]})));
180        p.insert("n", "evil", Value::from("{{#sys.query#}}"));
181        p
182    }
183
184    #[test]
185    fn unclosed_placeholders_parse_in_linear_time() {
186        // Each `{{#` used to scan to the one `#}}` at the very end: quadratic.
187        let source = format!("{}{{{{#sys.query#}}}}", "{{#".repeat(100_000));
188        let started = std::time::Instant::now();
189        let template = Template::parse(&source);
190        assert!(started.elapsed() < std::time::Duration::from_secs(2), "took {:?}", started.elapsed());
191        assert_eq!(template.render(&pool()), format!("{}hi", "{{#".repeat(100_000)));
192        // A closing marker beyond the longest possible body stays literal text.
193        let far = format!("{{{{#{}#}}}}", "a".repeat(600));
194        assert!(Template::parse(&far).is_static());
195        let edge = format!("{{{{#sys.{}#}}}}", "q".repeat(MAX_PLACEHOLDER_BYTES - 4));
196        assert!(!Template::parse(&edge).is_static());
197    }
198
199    #[test]
200    fn renders_placeholders() {
201        let t = Template::parse("say {{#sys.query#}}! {{#n.obj.list.1#}}");
202        assert_eq!(t.render(&pool()), "say hi! b");
203    }
204
205    #[test]
206    fn missing_renders_empty_and_bare_text_is_literal() {
207        let t = Template::parse("sys.query {{#sys.nope#}}|");
208        assert_eq!(t.render(&pool()), "sys.query |");
209    }
210
211    #[test]
212    fn no_reinjection() {
213        let t = Template::parse("{{#n.evil#}}");
214        assert_eq!(t.render(&pool()), "{{#sys.query#}}");
215    }
216
217    #[test]
218    fn malformed_placeholders_stay_literal() {
219        let t = Template::parse("{{#bad#}} {{#a b.c#}} {{#unterminated");
220        assert!(t.is_static());
221        assert_eq!(t.render(&pool()), "{{#bad#}} {{#a b.c#}} {{#unterminated");
222    }
223
224    #[test]
225    fn single_placeholder_resolves_typed() {
226        let t = Template::parse("{{#n.obj#}}");
227        assert!(matches!(t.resolve(&pool()), Value::Object(_)));
228    }
229}