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            match body_start.find("#}}") {
39                Some(end) => {
40                    let body = &body_start[..end];
41                    match parse_placeholder(body) {
42                        Some(selector) => {
43                            if !text.is_empty() {
44                                parts.push(Part::Text(std::mem::take(&mut text)));
45                            }
46                            parts.push(Part::Var(selector));
47                            rest = &body_start[end + 3..];
48                        }
49                        None => {
50                            text.push_str("{{#");
51                            rest = body_start;
52                        }
53                    }
54                }
55                None => {
56                    text.push_str(after_open);
57                    rest = "";
58                }
59            }
60        }
61        text.push_str(rest);
62        if !text.is_empty() {
63            parts.push(Part::Text(text));
64        }
65        Self { source: source.to_owned(), parts }
66    }
67
68    pub fn source(&self) -> &str {
69        &self.source
70    }
71
72    pub fn parts(&self) -> &[Part] {
73        &self.parts
74    }
75
76    /// Selectors referenced by this template, in order of appearance.
77    pub fn selectors(&self) -> impl Iterator<Item = &Selector> {
78        self.parts.iter().filter_map(|p| match p {
79            Part::Var(s) => Some(s),
80            Part::Text(_) => None,
81        })
82    }
83
84    /// Whether the template has no placeholders.
85    pub fn is_static(&self) -> bool {
86        self.selectors().next().is_none()
87    }
88
89    /// Render to text. Missing variables render as empty text; secrets are masked.
90    pub fn render(&self, pool: &VariablePool) -> String {
91        self.render_with(pool, Value::to_text)
92    }
93
94    /// Render revealing secrets. Only for nodes that must transmit plaintext
95    /// (e.g. HTTP auth headers).
96    pub fn render_exposed(&self, pool: &VariablePool) -> String {
97        self.render_with(pool, Value::to_text_exposed)
98    }
99
100    fn render_with(&self, pool: &VariablePool, f: fn(&Value) -> String) -> String {
101        let mut out = String::with_capacity(self.source.len());
102        for part in &self.parts {
103            match part {
104                Part::Text(t) => out.push_str(t),
105                Part::Var(sel) => {
106                    if let Some(v) = pool.get(sel) {
107                        out.push_str(&f(&v));
108                    }
109                }
110            }
111        }
112        out
113    }
114
115    /// If the template is exactly one placeholder, resolve it to the typed value
116    /// (so `"{{#llm.json#}}"` yields an object rather than its text). Otherwise render text.
117    pub fn resolve(&self, pool: &VariablePool) -> Value {
118        match self.parts.as_slice() {
119            [Part::Var(sel)] => pool.get_or_null(sel),
120            _ => Value::from(self.render(pool)),
121        }
122    }
123}
124
125fn parse_placeholder(body: &str) -> Option<Selector> {
126    if body.is_empty() || body.len() > 512 {
127        return None;
128    }
129    let valid =
130        body.split('.').all(|seg| !seg.is_empty() && seg.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-'));
131    if !valid {
132        return None;
133    }
134    Selector::parse(body).ok()
135}
136
137impl fmt::Debug for Template {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        write!(f, "Template({:?})", self.source)
140    }
141}
142
143impl From<&str> for Template {
144    fn from(s: &str) -> Self {
145        Template::parse(s)
146    }
147}
148
149impl Serialize for Template {
150    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
151        serializer.serialize_str(&self.source)
152    }
153}
154
155impl<'de> Deserialize<'de> for Template {
156    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
157        let s = String::deserialize(deserializer)?;
158        Ok(Template::parse(&s))
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    fn pool() -> VariablePool {
167        let mut p = VariablePool::new();
168        p.insert("sys", "query", Value::from("hi"));
169        p.insert("n", "obj", Value::from_json(serde_json::json!({"list": ["a", "b"]})));
170        p.insert("n", "evil", Value::from("{{#sys.query#}}"));
171        p
172    }
173
174    #[test]
175    fn renders_placeholders() {
176        let t = Template::parse("say {{#sys.query#}}! {{#n.obj.list.1#}}");
177        assert_eq!(t.render(&pool()), "say hi! b");
178    }
179
180    #[test]
181    fn missing_renders_empty_and_bare_text_is_literal() {
182        let t = Template::parse("sys.query {{#sys.nope#}}|");
183        assert_eq!(t.render(&pool()), "sys.query |");
184    }
185
186    #[test]
187    fn no_reinjection() {
188        let t = Template::parse("{{#n.evil#}}");
189        assert_eq!(t.render(&pool()), "{{#sys.query#}}");
190    }
191
192    #[test]
193    fn malformed_placeholders_stay_literal() {
194        let t = Template::parse("{{#bad#}} {{#a b.c#}} {{#unterminated");
195        assert!(t.is_static());
196        assert_eq!(t.render(&pool()), "{{#bad#}} {{#a b.c#}} {{#unterminated");
197    }
198
199    #[test]
200    fn single_placeholder_resolves_typed() {
201        let t = Template::parse("{{#n.obj#}}");
202        assert!(matches!(t.resolve(&pool()), Value::Object(_)));
203    }
204}