Skip to main content

zenkey_model/
template.rs

1//! Resource templates: the resource path below a key's kind chunk.
2//!
3//! - **Literal chunks** follow the plain-chunk charset.
4//! - **`{name}`** is one chunk.
5//! - **`{name...}`** is a *rest* parameter: one or more chunks, last segment only.
6//! - **Values are slugged injectively** when a key is built
7//!   ([`crate::slug::chunk_slug`]) and unslugged when one is matched.
8//! - **Precedence (r3.3 D1):** when two templates under one kind token
9//!   match a key, the most literal wins, chunk by chunk: literal > `{p}` >
10//!   `{p...}`.
11
12use std::cmp::Ordering;
13use std::collections::BTreeMap;
14use std::fmt;
15
16use thiserror::Error;
17
18use crate::chunk::{is_ident, is_plain_chunk};
19use crate::slug::{chunk_slug, chunk_unslug};
20
21/// One segment of a template.
22#[derive(Debug, Clone, PartialEq, Eq, Hash)]
23pub enum Segment {
24    Literal(String),
25    Param(String),
26    Rest(String),
27}
28
29impl Segment {
30    fn rank(&self) -> u8 {
31        match self {
32            Self::Literal(_) => 2,
33            Self::Param(_) => 1,
34            Self::Rest(_) => 0,
35        }
36    }
37}
38
39/// Why a template string was refused.
40#[derive(Debug, Clone, PartialEq, Eq, Error)]
41pub enum TemplateError {
42    #[error("template {0:?} is empty or has an empty segment")]
43    Empty(String),
44    #[error(
45        "template {0:?}: literal segment {1:?} is not a plain chunk, or starts with the slug prefix x-"
46    )]
47    Literal(String, String),
48    #[error("template {0:?}: parameter name {1:?} is not [a-z][a-z0-9_]*")]
49    ParamName(String, String),
50    #[error("template {0:?}: a rest parameter {{{1}...}} may only be the last segment")]
51    RestNotLast(String, String),
52    #[error("template {0:?}: parameter {1:?} appears twice")]
53    Duplicate(String, String),
54}
55
56/// A parsed resource template.
57#[derive(Debug, Clone, PartialEq, Eq, Hash)]
58pub struct Template {
59    raw: String,
60    segments: Vec<Segment>,
61}
62
63/// Values bound to a template's parameters. A rest parameter binds one or
64/// more values.
65pub type Bindings = BTreeMap<String, Vec<String>>;
66
67impl Template {
68    pub fn parse(raw: &str) -> Result<Self, TemplateError> {
69        if raw.is_empty() {
70            return Err(TemplateError::Empty(raw.to_owned()));
71        }
72        let parts: Vec<&str> = raw.split('/').collect();
73        let mut segments = Vec::with_capacity(parts.len());
74        let mut seen = std::collections::BTreeSet::new();
75        for (i, p) in parts.iter().enumerate() {
76            if p.is_empty() {
77                return Err(TemplateError::Empty(raw.to_owned()));
78            }
79            let seg = if let Some(inner) = p.strip_prefix('{').and_then(|r| r.strip_suffix('}')) {
80                if let Some(name) = inner.strip_suffix("...") {
81                    if i != parts.len() - 1 {
82                        return Err(TemplateError::RestNotLast(raw.to_owned(), name.to_owned()));
83                    }
84                    Segment::Rest(name.to_owned())
85                } else {
86                    Segment::Param(inner.to_owned())
87                }
88            } else if is_plain_chunk(p) && !p.starts_with("x-") {
89                Segment::Literal((*p).to_owned())
90            } else {
91                return Err(TemplateError::Literal(raw.to_owned(), (*p).to_owned()));
92            };
93            if let Segment::Param(n) | Segment::Rest(n) = &seg {
94                if !is_ident(n) {
95                    return Err(TemplateError::ParamName(raw.to_owned(), n.clone()));
96                }
97                if !seen.insert(n.clone()) {
98                    return Err(TemplateError::Duplicate(raw.to_owned(), n.clone()));
99                }
100            }
101            segments.push(seg);
102        }
103        Ok(Self {
104            raw: raw.to_owned(),
105            segments,
106        })
107    }
108
109    #[must_use]
110    pub fn as_str(&self) -> &str {
111        &self.raw
112    }
113
114    #[must_use]
115    pub fn segments(&self) -> &[Segment] {
116        &self.segments
117    }
118
119    /// Parameter names, in order, with whether each is a rest parameter.
120    pub fn params(&self) -> impl Iterator<Item = (&str, bool)> {
121        self.segments.iter().filter_map(|s| match s {
122            Segment::Param(n) => Some((n.as_str(), false)),
123            Segment::Rest(n) => Some((n.as_str(), true)),
124            Segment::Literal(_) => None,
125        })
126    }
127
128    #[must_use]
129    pub fn has_params(&self) -> bool {
130        self.params().next().is_some()
131    }
132
133    /// The template's *shape*: literal chunks kept, parameters erased. Two
134    /// templates under one kind token may not share a shape (r3.3 D1).
135    #[must_use]
136    pub fn shape(&self) -> String {
137        self.segments
138            .iter()
139            .map(|s| match s {
140                Segment::Literal(l) => l.as_str(),
141                Segment::Param(_) => "{}",
142                Segment::Rest(_) => "{...}",
143            })
144            .collect::<Vec<_>>()
145            .join("/")
146    }
147
148    /// Builds the resource chunks from raw (unslugged) values. Every value
149    /// is slugged; a rest parameter takes one or more values.
150    pub fn build(&self, values: &Bindings) -> Result<Vec<String>, String> {
151        let mut out = Vec::with_capacity(self.segments.len());
152        for s in &self.segments {
153            match s {
154                Segment::Literal(l) => out.push(l.clone()),
155                Segment::Param(n) => match values.get(n).map(Vec::as_slice) {
156                    Some([v]) => out.push(chunk_slug(v)),
157                    _ => return Err(format!("parameter {n:?} needs exactly one value")),
158                },
159                Segment::Rest(n) => match values.get(n) {
160                    Some(vs) if !vs.is_empty() => out.extend(vs.iter().map(|v| chunk_slug(v))),
161                    _ => return Err(format!("rest parameter {n:?} needs one or more values")),
162                },
163            }
164        }
165        Ok(out)
166    }
167
168    /// Matches resource chunks against this template, returning the
169    /// unslugged values. `None` when it does not match, or when a value is
170    /// not a canonical slug.
171    #[must_use]
172    pub fn matches(&self, chunks: &[&str]) -> Option<Bindings> {
173        let mut out = Bindings::new();
174        let mut i = 0;
175        for s in &self.segments {
176            match s {
177                Segment::Literal(l) => {
178                    if chunks.get(i) != Some(&l.as_str()) {
179                        return None;
180                    }
181                    i += 1;
182                }
183                Segment::Param(n) => {
184                    let v = chunk_unslug(chunks.get(i)?)?;
185                    out.insert(n.clone(), vec![v]);
186                    i += 1;
187                }
188                Segment::Rest(n) => {
189                    let rest = chunks.get(i..)?;
190                    if rest.is_empty() {
191                        return None;
192                    }
193                    let vs = rest
194                        .iter()
195                        .map(|c| chunk_unslug(c))
196                        .collect::<Option<Vec<_>>>()?;
197                    out.insert(n.clone(), vs);
198                    i = chunks.len();
199                }
200            }
201        }
202        (i == chunks.len()).then_some(out)
203    }
204
205    /// Whether some resource path matches both templates.
206    #[must_use]
207    pub fn overlaps(&self, other: &Template) -> bool {
208        fn go(a: &[Segment], b: &[Segment]) -> bool {
209            match (a.first(), b.first()) {
210                (None, None) => true,
211                // A rest parameter is always the last segment and absorbs one
212                // or more chunks, so it overlaps whatever is left on the other
213                // side as long as that produces at least one chunk.
214                (Some(Segment::Rest(_)), _) => !b.is_empty(),
215                (_, Some(Segment::Rest(_))) => !a.is_empty(),
216                (None, Some(_)) | (Some(_), None) => false,
217                (Some(x), Some(y)) => {
218                    let ok = match (x, y) {
219                        (Segment::Literal(p), Segment::Literal(q)) => p == q,
220                        _ => true,
221                    };
222                    ok && go(&a[1..], &b[1..])
223                }
224            }
225        }
226        go(&self.segments, &other.segments)
227    }
228
229    /// Precedence between two templates that both match a key: `Greater`
230    /// means `self` wins (it is more literal at the first differing
231    /// segment, r3.3 D1).
232    #[must_use]
233    pub fn precedence(&self, other: &Template) -> Ordering {
234        for (a, b) in self.segments.iter().zip(&other.segments) {
235            match a.rank().cmp(&b.rank()) {
236                Ordering::Equal => {}
237                o => return o,
238            }
239        }
240        // Equal prefix: the longer, fully literal-or-param template is the
241        // more specific; a template that still has segments beats one that
242        // ended in a rest parameter.
243        self.segments.len().cmp(&other.segments.len())
244    }
245}
246
247impl fmt::Display for Template {
248    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249        f.write_str(&self.raw)
250    }
251}
252
253/// Picks the winning template for `chunks` among `candidates`, by D1
254/// precedence. Returns its index and bindings.
255#[must_use]
256pub fn resolve<'a>(
257    candidates: impl IntoIterator<Item = &'a Template>,
258    chunks: &[&str],
259) -> Option<(usize, Bindings)> {
260    let mut best: Option<(usize, &Template, Bindings)> = None;
261    for (i, t) in candidates.into_iter().enumerate() {
262        if let Some(b) = t.matches(chunks) {
263            let better = match &best {
264                None => true,
265                Some((_, bt, _)) => t.precedence(bt) == Ordering::Greater,
266            };
267            if better {
268                best = Some((i, t, b));
269            }
270        }
271    }
272    best.map(|(i, _, b)| (i, b))
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278
279    fn t(s: &str) -> Template {
280        Template::parse(s).unwrap()
281    }
282
283    #[test]
284    fn parsing() {
285        assert_eq!(
286            t("devices/{device}/metrics/{metric...}").shape(),
287            "devices/{}/metrics/{...}"
288        );
289        for bad in ["", "a//b", "A", "{x...}/a", "{X}", "{a}/{a}", "a/{b-c}"] {
290            assert!(Template::parse(bad).is_err(), "{bad}");
291        }
292    }
293
294    #[test]
295    fn build_and_match_slug() {
296        let tpl = t("interfaces/{ns}/{iface}");
297        let mut b = Bindings::new();
298        b.insert("ns".into(), vec!["default".into()]);
299        b.insert("iface".into(), vec!["ETH0".into()]);
300        let chunks = tpl.build(&b).unwrap();
301        assert_eq!(chunks, ["interfaces", "default", "x-_x45_x54_x480"]);
302        let refs: Vec<&str> = chunks.iter().map(String::as_str).collect();
303        assert_eq!(tpl.matches(&refs).unwrap(), b);
304    }
305
306    #[test]
307    fn rest_parameters() {
308        let tpl = t("metrics/{metric...}");
309        assert!(tpl.matches(&["metrics"]).is_none());
310        let m = tpl.matches(&["metrics", "if", "3", "in_octets"]).unwrap();
311        assert_eq!(m["metric"], ["if", "3", "in_octets"]);
312    }
313
314    #[test]
315    fn most_literal_first() {
316        let catch = t("flow/{x}");
317        let lit = t("flow/duration_p50_ms");
318        let rest = t("flow/{x...}");
319        let cands = [catch.clone(), lit.clone(), rest.clone()];
320        assert_eq!(resolve(&cands, &["flow", "duration_p50_ms"]).unwrap().0, 1);
321        assert_eq!(resolve(&cands, &["flow", "other"]).unwrap().0, 0);
322        assert_eq!(resolve(&cands, &["flow", "a", "b"]).unwrap().0, 2);
323        assert!(catch.overlaps(&lit) && lit.overlaps(&rest) && catch.overlaps(&rest));
324        assert!(!t("a/{x}").overlaps(&t("b/{x}")));
325        assert!(!t("a/{x}").overlaps(&t("a/{x}/c")));
326        assert!(t("a/{x...}").overlaps(&t("a/b/c")));
327    }
328
329    #[test]
330    fn shapes_collide_regardless_of_param_names() {
331        assert_eq!(t("action/{name}").shape(), t("action/{event_id}").shape());
332    }
333}