use crate::extensions::flow_state::FlowStore;
use crate::extensions::template::RequestData;
use rand::RngExt;
use regex::Regex;
use serde_json::Value;
use std::sync::OnceLock;
pub struct TemplateContext<'a> {
pub request: &'a RequestData,
pub flow_id: &'a str,
pub flow_store: &'a dyn FlowStore,
pub previous_value: Option<&'a Value>,
}
pub fn render_templated(
input: &str,
ctx: &TemplateContext<'_>,
debug: bool,
) -> Result<String, String> {
render_templated_mapped(input, ctx, debug, |value| value)
}
pub(crate) fn render_templated_mapped<F>(
input: &str,
ctx: &TemplateContext<'_>,
debug: bool,
map: F,
) -> Result<String, String>
where
F: Fn(String) -> String,
{
render_templated_spliced(input, ctx, debug, map).map(crate::behaviors::Spliced::into_text)
}
pub(crate) fn render_templated_spliced<F>(
input: &str,
ctx: &TemplateContext<'_>,
debug: bool,
map: F,
) -> Result<crate::behaviors::Spliced, String>
where
F: Fn(String) -> String,
{
let expanded = crate::extensions::template::apply_date_templates(input);
render(
crate::behaviors::Spliced::authored(expanded),
ctx,
debug,
map,
)
}
#[must_use]
pub fn template_heads(input: &str) -> Vec<String> {
expr_regex()
.captures_iter(input)
.filter_map(|caps| {
let inner = caps.get(1)?.as_str().trim();
let base = split_top_level(inner, '|').into_iter().next()?;
tokenize_words(&base).into_iter().next()
})
.collect()
}
#[must_use]
pub fn reads_flow_state(input: &str) -> bool {
if !input.contains("state.") {
return false;
}
template_heads(&crate::extensions::template::apply_date_templates(input))
.iter()
.any(|head| head.starts_with("state."))
}
fn render<F>(
mut input: crate::behaviors::Spliced,
ctx: &TemplateContext<'_>,
debug: bool,
map: F,
) -> Result<crate::behaviors::Spliced, String>
where
F: Fn(String) -> String,
{
let re = expr_regex();
let mut first_error: Option<String> = None;
input.replace_regex(re, |caps: ®ex::Captures| {
if first_error.is_some() {
return String::new();
}
let raw = &caps[0];
let inner = caps[1].trim();
match evaluate(inner, ctx) {
Ok(value) => map(value),
Err(reason) => {
if debug {
first_error = Some(format!("template error in `{raw}`: {reason}"));
} else {
tracing::warn!(
target: "rift::template",
token = %raw,
reason = %reason,
"template token failed; substituting empty string"
);
}
String::new()
}
}
});
match first_error {
Some(e) => Err(e),
None => Ok(input),
}
}
fn expr_regex() -> &'static Regex {
static EXPR_REGEX: OnceLock<Regex> = OnceLock::new();
EXPR_REGEX.get_or_init(|| {
Regex::new(r"\{\{\s*([^{}]+?)\s*\}\}").unwrap_or_else(|e| {
unreachable!("static template expression regex must compile: {e}")
})
})
}
fn evaluate(inner: &str, ctx: &TemplateContext<'_>) -> Result<String, String> {
let mut segments = split_top_level(inner, '|').into_iter();
let base = segments.next().unwrap_or_default();
let base_words = tokenize_words(&base);
let head = base_words
.first()
.ok_or_else(|| "empty template expression".to_string())?;
let mut value = eval_base(head, &base_words[1..], ctx)?;
for filter_part in segments {
let filter_words = tokenize_words(&filter_part);
let fname = filter_words
.first()
.ok_or_else(|| "empty filter after `|`".to_string())?;
value = apply_filter(&value, fname, &filter_words[1..])?;
}
Ok(value)
}
fn split_top_level(s: &str, sep: char) -> Vec<String> {
let mut parts = Vec::new();
let mut current = String::new();
let mut in_quotes = false;
for c in s.chars() {
match c {
'\'' => {
in_quotes = !in_quotes;
current.push(c);
}
c if c == sep && !in_quotes => {
parts.push(std::mem::take(&mut current));
}
c => current.push(c),
}
}
parts.push(current);
parts
}
fn tokenize_words(s: &str) -> Vec<String> {
let mut words = Vec::new();
let mut current = String::new();
let mut in_quotes = false;
let mut has_content = false;
for c in s.chars() {
match c {
'\'' => {
in_quotes = !in_quotes;
has_content = true;
}
c if c.is_whitespace() && !in_quotes => {
if has_content {
words.push(std::mem::take(&mut current));
has_content = false;
}
}
c => {
current.push(c);
has_content = true;
}
}
}
if has_content {
words.push(current);
}
words
}
fn eval_base(head: &str, args: &[String], ctx: &TemplateContext<'_>) -> Result<String, String> {
match head {
"request.method" => Ok(ctx.request.method.clone()),
"request.path" => Ok(ctx.request.path.clone()),
"request.header" => {
let name = args.first().ok_or_else(|| {
"request.header requires a quoted header name, e.g. request.header 'Name'"
.to_string()
})?;
ctx.request
.headers
.get(&name.to_lowercase())
.cloned()
.ok_or_else(|| format!("no such header: '{name}'"))
}
"request.json" => {
let path = args.first().ok_or_else(|| {
"request.json requires a quoted jsonpath, e.g. request.json '$.a.b'".to_string()
})?;
let json: Value = serde_json::from_str(&ctx.request.body)
.map_err(|e| format!("request body is not valid JSON: {e}"))?;
let resolved = eval_jsonpath(&json, path)?;
Ok(value_to_string(&resolved))
}
"now" => {
let mut offset = None;
let mut format = None;
for arg in args {
if let Some(v) = arg.strip_prefix("offset=") {
offset = Some(v.to_string());
} else if let Some(v) = arg.strip_prefix("format=") {
format = Some(v.to_string());
} else {
return Err(format!(
"now: unknown argument '{arg}' (expected offset='...' or format='...')"
));
}
}
eval_now(offset.as_deref(), format.as_deref())
}
"uuid" => Ok(match crate::imposter::rng::current() {
Some(mut rng) => {
let mut bytes = [0u8; 16];
rand::TryRng::try_fill_bytes(&mut rng, &mut bytes).unwrap_or_else(|e| match e {});
uuid::Builder::from_random_bytes(bytes).into_uuid()
}
None => uuid::Uuid::new_v4(),
}
.to_string()),
"previousValue" => Ok(ctx.previous_value.map(value_to_string).unwrap_or_default()),
"randomInt" => {
let lo_str = args.first().ok_or_else(|| {
"randomInt requires two integer arguments: randomInt a b".to_string()
})?;
let hi_str = args.get(1).ok_or_else(|| {
"randomInt requires two integer arguments: randomInt a b".to_string()
})?;
let lo: i64 = lo_str
.parse()
.map_err(|_| format!("randomInt: invalid integer '{lo_str}'"))?;
let hi: i64 = hi_str
.parse()
.map_err(|_| format!("randomInt: invalid integer '{hi_str}'"))?;
if lo > hi {
return Err(format!(
"randomInt: lower bound {lo} is greater than upper bound {hi}"
));
}
let n = match crate::imposter::rng::current() {
Some(mut rng) => rng.random_range(lo..=hi),
None => rand::rng().random_range(lo..=hi),
};
Ok(n.to_string())
}
_ => {
if let Some(name) = head.strip_prefix("request.query.") {
return ctx
.request
.query
.get(name)
.cloned()
.ok_or_else(|| format!("no such query parameter: '{name}'"));
}
if let Some(key) = head.strip_prefix("state.") {
if key.is_empty() {
return Err("state requires a key, e.g. state.myKey".to_string());
}
let found = ctx
.flow_store
.get(ctx.flow_id, key)
.map_err(|e| format!("state.{key}: flow store error: {e:#}"))?;
return found
.map(|v| value_to_string(&v))
.ok_or_else(|| format!("no such state key: '{key}'"));
}
Err(format!("unknown template function: '{head}'"))
}
}
}
fn apply_filter(value: &str, name: &str, args: &[String]) -> Result<String, String> {
match name {
"last_segment" => Ok(value
.trim_end_matches('/')
.rsplit('/')
.next()
.unwrap_or("")
.to_string()),
"regex" => {
let pattern = args.first().ok_or_else(|| {
"regex filter requires a quoted pattern, e.g. | regex '(\\d+)$' 1".to_string()
})?;
let group_str = args.get(1).ok_or_else(|| {
"regex filter requires a capture group number, e.g. | regex '(\\d+)$' 1".to_string()
})?;
let group: usize = group_str
.parse()
.map_err(|_| format!("regex filter: invalid group number '{group_str}'"))?;
let Some(re) = crate::imposter::predicates::regex_cache::cached_regex(pattern, false)
else {
return Err(match Regex::new(pattern) {
Err(e) => format!("regex filter: invalid pattern '{pattern}': {e}"),
Ok(_) => format!("regex filter: invalid pattern '{pattern}'"),
});
};
let caps = re
.captures(value)
.ok_or_else(|| format!("regex filter: pattern '{pattern}' did not match"))?;
caps.get(group)
.map(|m| m.as_str().to_string())
.ok_or_else(|| format!("regex filter: no capture group {group}"))
}
"json" => {
let quoted = serde_json::to_string(value)
.map_err(|e| format!("json filter: could not encode value: {e}"))?;
let interior = quoted
.strip_prefix('"')
.and_then(|s| s.strip_suffix('"'))
.unwrap_or("ed);
Ok(interior.to_string())
}
_ => Err(format!("unknown template filter: '{name}'")),
}
}
enum PathSegment {
Key(String),
Index(usize),
}
fn parse_jsonpath(path: &str) -> Result<Vec<PathSegment>, String> {
let rest = path
.trim()
.strip_prefix('$')
.ok_or_else(|| format!("jsonpath must start with '$': '{path}'"))?;
let mut segments = Vec::new();
let mut chars = rest.chars().peekable();
while let Some(&c) = chars.peek() {
match c {
'.' => {
chars.next();
let mut key = String::new();
while let Some(&c2) = chars.peek() {
if c2 == '.' || c2 == '[' {
break;
}
key.push(c2);
chars.next();
}
if key.is_empty() {
return Err(format!("empty key segment in jsonpath: '{path}'"));
}
segments.push(PathSegment::Key(key));
}
'[' => {
chars.next();
let mut idx = String::new();
while let Some(&c2) = chars.peek() {
if c2 == ']' {
break;
}
idx.push(c2);
chars.next();
}
if chars.next() != Some(']') {
return Err(format!("unterminated '[' in jsonpath: '{path}'"));
}
let n: usize = idx
.parse()
.map_err(|_| format!("invalid array index '{idx}' in jsonpath: '{path}'"))?;
segments.push(PathSegment::Index(n));
}
other => {
return Err(format!(
"unexpected character '{other}' in jsonpath: '{path}'"
));
}
}
}
Ok(segments)
}
pub fn eval_jsonpath(root: &Value, path: &str) -> Result<Value, String> {
let segments = parse_jsonpath(path)?;
let mut current = root;
for segment in &segments {
current = match segment {
PathSegment::Key(k) => current
.get(k)
.ok_or_else(|| format!("jsonpath: no such key '{k}' in '{path}'"))?,
PathSegment::Index(i) => current
.get(i)
.ok_or_else(|| format!("jsonpath: index {i} out of bounds in '{path}'"))?,
};
}
Ok(current.clone())
}
fn value_to_string(v: &Value) -> String {
match v {
Value::String(s) => s.clone(),
Value::Null => "null".to_string(),
Value::Bool(b) => b.to_string(),
Value::Number(n) => n.to_string(),
other => serde_json::to_string(other).unwrap_or_default(),
}
}
fn parse_offset(s: &str) -> Result<chrono::Duration, String> {
let s = s.trim();
if s.is_empty() {
return Err("empty offset".to_string());
}
let (sign, rest) = match s.chars().next() {
Some('+') => (1i64, &s[1..]),
Some('-') => (-1i64, &s[1..]),
_ => (1i64, s),
};
let unit = rest
.chars()
.last()
.ok_or_else(|| format!("empty offset magnitude: '{s}'"))?;
let num_str = &rest[..rest.len() - unit.len_utf8()];
let num: i64 = num_str
.parse()
.map_err(|_| format!("invalid offset number '{num_str}' in '{s}'"))?;
let magnitude = match unit {
's' => chrono::Duration::try_seconds(num),
'm' => chrono::Duration::try_minutes(num),
'h' => chrono::Duration::try_hours(num),
'd' => chrono::Duration::try_days(num),
other => return Err(format!("invalid offset unit '{other}' (expected s/m/h/d)")),
}
.ok_or_else(|| format!("offset overflows the representable range: '{s}'"))?;
Ok(if sign < 0 { -magnitude } else { magnitude })
}
fn eval_now(offset: Option<&str>, format: Option<&str>) -> Result<String, String> {
let mut dt = crate::scripting::env::now_utc();
if let Some(off) = offset {
let duration = parse_offset(off)?;
dt = dt
.checked_add_signed(duration)
.ok_or_else(|| format!("now: offset '{off}' overflows the representable date range"))?;
}
match format {
Some(fmt) => {
use chrono::format::{Item, StrftimeItems};
if StrftimeItems::new(fmt).any(|item| matches!(item, Item::Error)) {
return Err(format!("now: invalid strftime format string '{fmt}'"));
}
Ok(dt.format(fmt).to_string())
}
None => Ok(dt.to_rfc3339()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::backends::InMemoryFlowStore;
use std::collections::HashMap;
fn hdrs(pairs: &[(&str, &[&str])]) -> crate::util::OrderedMap<String, Vec<String>> {
pairs
.iter()
.map(|(k, vs)| {
(
(*k).to_string(),
vs.iter().map(|v| (*v).to_string()).collect(),
)
})
.collect()
}
fn request_data() -> RequestData {
let headers = hdrs(&[]);
let mut data = RequestData::new(
"POST",
"/orders/11111111-1111-1111-1111-111111111111",
Some("name=John&age=30"),
&headers,
Some(r#"{"variant":{"variantAttribute":"blue"},"items":[{"id":42},{"id":43}]}"#),
);
data.headers
.insert("x-request-id".to_string(), "req-1".to_string());
data
}
fn store() -> InMemoryFlowStore {
InMemoryFlowStore::new(60)
}
#[test]
fn the_map_is_applied_to_substitutions_only() {
let request = request_data();
let store = store();
let ctx = ctx(&request, "flow", &store);
let out = render_templated_mapped("a\u{1}b{{ request.method }}", &ctx, false, |v| {
format!("[{v}]")
})
.expect("renders");
assert_eq!(
out, "a\u{1}b[POST]",
"only the substitution was mapped; the author's literal text was passed through"
);
}
#[test]
fn render_templated_is_the_identity_mapped_case() {
let request = request_data();
let store = store();
let ctx = ctx(&request, "flow", &store);
let input = "a\u{1}b{{ request.method }}";
assert_eq!(
render_templated(input, &ctx, false).expect("renders"),
render_templated_mapped(input, &ctx, false, |v| v).expect("renders"),
);
}
#[test]
fn the_map_receives_only_the_substituted_text() {
let request = request_data();
let store = store();
let ctx = ctx(&request, "flow", &store);
let seen = std::cell::RefCell::new(Vec::new());
let out = render_templated_mapped(
"zzmarker-{{ request.method }}-{{ request.path }}",
&ctx,
false,
|v| {
seen.borrow_mut().push(v.clone());
v
},
)
.expect("renders");
assert_eq!(
*seen.borrow(),
vec![
"POST".to_string(),
"/orders/11111111-1111-1111-1111-111111111111".to_string()
],
"the map sees each substitution and never the literal text around it"
);
assert!(out.starts_with("zzmarker-"), "got {out:?}");
}
#[test]
fn date_tokens_expand_before_the_map_and_are_not_mapped() {
let request = request_data();
let store = store();
let ctx = ctx(&request, "flow", &store);
let out =
render_templated_mapped("{{NOW}}", &ctx, false, |v| format!("[{v}]")).expect("renders");
assert!(
!out.contains('['),
"a date token is expanded before the map and must not pass through it, got {out:?}"
);
}
#[test]
fn a_failed_token_in_debug_mode_aborts_before_the_map() {
let request = request_data();
let store = store();
let ctx = ctx(&request, "flow", &store);
let err = render_templated_mapped("[{{ nosuchfunction }}]", &ctx, true, |_| {
"MAPPED".to_string()
})
.expect_err("debug mode fails the render");
assert!(
err.contains("nosuchfunction"),
"the error names the offending token, got {err:?}"
);
}
#[test]
fn a_failed_token_is_not_mapped() {
let request = request_data();
let store = store();
let ctx = ctx(&request, "flow", &store);
let out = render_templated_mapped("[{{ nosuchfunction }}]", &ctx, false, |_| {
"MAPPED".to_string()
})
.expect("non-debug substitutes rather than failing");
assert_eq!(out, "[]", "the failed token is empty, not mapped");
}
fn ctx<'a>(
request: &'a RequestData,
flow_id: &'a str,
store: &'a InMemoryFlowStore,
) -> TemplateContext<'a> {
TemplateContext {
request,
flow_id,
flow_store: store,
previous_value: None,
}
}
#[test]
fn reads_flow_state_true_only_for_a_state_head() {
assert!(reads_flow_state("{{ state.hits }}"));
assert!(
reads_flow_state("{{state.a|json}}"),
"no spaces, with a filter"
);
assert!(
reads_flow_state("x {{ now }} {{ state.b }} y"),
"mixed heads"
);
assert!(
reads_flow_state("{{ state. }}"),
"empty key is a deliberate over-approximation: render errors on it before touching \
the store, and reporting a read is the safe direction"
);
assert!(!reads_flow_state("{{ request.path }}"));
assert!(!reads_flow_state("{{ now }}"));
assert!(!reads_flow_state("{{ uuid }}"));
assert!(!reads_flow_state("{{ previousValue }}"));
assert!(
!reads_flow_state("{{ state }}"),
"no dot: an unknown function to the evaluator, which never reaches the store"
);
assert!(!reads_flow_state("{{NOW}}"), "legacy date token");
assert!(!reads_flow_state("plain text with no template at all"));
assert!(!reads_flow_state(""));
assert!(!reads_flow_state("{{ unterminated"));
assert!(reads_flow_state("{{ state.x {{NOW}} }}"));
}
#[test]
fn a_render_that_touches_the_store_is_always_predicted() {
use crate::extensions::flow_state::FlowStore;
use std::sync::atomic::{AtomicUsize, Ordering};
struct CountingStore {
inner: crate::backends::inmemory::InMemoryFlowStore,
gets: AtomicUsize,
}
impl FlowStore for CountingStore {
fn get(&self, flow_id: &str, key: &str) -> anyhow::Result<Option<Value>> {
self.gets.fetch_add(1, Ordering::SeqCst);
self.inner.get(flow_id, key)
}
fn set(&self, flow_id: &str, key: &str, value: Value) -> anyhow::Result<()> {
self.inner.set(flow_id, key, value)
}
fn exists(&self, flow_id: &str, key: &str) -> anyhow::Result<bool> {
self.inner.exists(flow_id, key)
}
fn delete(&self, flow_id: &str, key: &str) -> anyhow::Result<()> {
self.inner.delete(flow_id, key)
}
fn increment(&self, flow_id: &str, key: &str) -> anyhow::Result<i64> {
self.inner.increment(flow_id, key)
}
fn set_ttl(&self, flow_id: &str, ttl_seconds: i64) -> anyhow::Result<()> {
self.inner.set_ttl(flow_id, ttl_seconds)
}
fn compare_and_set(
&self,
flow_id: &str,
key: &str,
expected: Option<&Value>,
new: Value,
) -> anyhow::Result<crate::extensions::flow_state::CasOutcome> {
self.inner.compare_and_set(flow_id, key, expected, new)
}
}
let inputs = [
"{{ state.hits }}",
"{{state.a|json}}",
"x {{ now }} {{ state.b }} y",
"{{ state. }}",
"{{ request.path }}",
"{{ now }}",
"{{ uuid }}",
"{{ previousValue }}",
"{{ state }}",
"{{NOW}}",
"plain text with no template at all",
"",
"{{ unterminated",
"{{ state.a }} and {{ state.b }}",
"{{ state.c | json }}",
"{{ state.x {{NOW}} }}",
];
for input in inputs {
let store = CountingStore {
inner: crate::backends::inmemory::InMemoryFlowStore::new(300),
gets: AtomicUsize::new(0),
};
store.set("flow-1", "hits", Value::from(1)).expect("seed");
store.gets.store(0, Ordering::SeqCst);
let request = RequestData::new("GET", "/x", None, &hdrs(&[]), None);
let ctx = TemplateContext {
request: &request,
flow_id: "flow-1",
flow_store: &store,
previous_value: None,
};
let _ = render_templated(input, &ctx, false);
let touched = store.gets.load(Ordering::SeqCst) > 0;
assert!(
!touched || reads_flow_state(input),
"FALSE NEGATIVE for {input:?}: the render read the store but the predicate said \
it would not — this is the #971 deadlock reintroduced. Note an enumerated table \
can only catch shapes someone thought of: the `{{{{NOW}}}}` case below was missed \
on the first pass and found by hand."
);
}
}
#[test]
fn templated_false_leaves_literal_braces_untouched() {
}
#[test]
fn request_method_and_path() {
let data = request_data();
let s = store();
let tctx = ctx(&data, "flow-1", &s);
assert_eq!(
render_templated("{{request.method}}", &tctx, false).unwrap(),
"POST"
);
assert_eq!(
render_templated("{{request.path}}", &tctx, false).unwrap(),
"/orders/11111111-1111-1111-1111-111111111111"
);
}
#[test]
fn request_query_present_and_missing() {
let data = request_data();
let s = store();
let tctx = ctx(&data, "flow-1", &s);
assert_eq!(
render_templated("{{request.query.name}}", &tctx, false).unwrap(),
"John"
);
assert_eq!(
render_templated("[{{request.query.missing}}]", &tctx, false).unwrap(),
"[]"
);
}
#[test]
fn request_header_case_insensitive() {
let data = request_data();
let s = store();
let tctx = ctx(&data, "flow-1", &s);
assert_eq!(
render_templated("{{request.header 'X-Request-Id'}}", &tctx, false).unwrap(),
"req-1"
);
assert_eq!(
render_templated("{{request.header 'x-request-id'}}", &tctx, false).unwrap(),
"req-1"
);
}
#[test]
fn request_json_nested_and_array_index() {
let data = request_data();
let s = store();
let tctx = ctx(&data, "flow-1", &s);
assert_eq!(
render_templated(
"{{request.json '$.variant.variantAttribute'}}",
&tctx,
false
)
.unwrap(),
"blue"
);
assert_eq!(
render_templated("{{request.json '$.items[0].id'}}", &tctx, false).unwrap(),
"42"
);
assert_eq!(
render_templated("{{request.json '$.items[1].id'}}", &tctx, false).unwrap(),
"43"
);
}
#[test]
fn request_json_missing_path_empty_in_non_debug_error_in_debug() {
let data = request_data();
let s = store();
let tctx = ctx(&data, "flow-1", &s);
assert_eq!(
render_templated("[{{request.json '$.nope'}}]", &tctx, false).unwrap(),
"[]"
);
assert!(render_templated("{{request.json '$.nope'}}", &tctx, true).is_err());
}
#[test]
fn last_segment_filter() {
let data = request_data();
let s = store();
let tctx = ctx(&data, "flow-1", &s);
assert_eq!(
render_templated("{{request.path | last_segment}}", &tctx, false).unwrap(),
"11111111-1111-1111-1111-111111111111"
);
}
#[test]
fn regex_filter_capture_group() {
let data = request_data();
let s = store();
let tctx = ctx(&data, "flow-1", &s);
let out = render_templated(
"{{request.path | regex '^/orders/([0-9a-f-]+)$' 1}}",
&tctx,
false,
)
.unwrap();
assert_eq!(out, "11111111-1111-1111-1111-111111111111");
}
#[test]
fn regex_filter_invalid_pattern_errors() {
let data = request_data();
let s = store();
let tctx = ctx(&data, "flow-1", &s);
let err = render_templated("{{request.path | regex '([' 1}}", &tctx, true).unwrap_err();
assert!(err.contains("invalid pattern"), "got: {err}");
}
#[test]
fn now_with_offset_and_format() {
let data = request_data();
let s = store();
let tctx = ctx(&data, "flow-1", &s);
let out = render_templated("{{now}}", &tctx, false).unwrap();
chrono::DateTime::parse_from_rfc3339(&out).expect("default now() is RFC3339");
let minus = render_templated("{{now offset='-36h'}}", &tctx, false).unwrap();
let expected = chrono::Utc::now() - chrono::Duration::hours(36);
let parsed = chrono::DateTime::parse_from_rfc3339(&minus).expect("valid RFC3339");
assert!((parsed.timestamp() - expected.timestamp()).abs() <= 2);
let plus = render_templated("{{now offset='+2d'}}", &tctx, false).unwrap();
let expected = chrono::Utc::now() + chrono::Duration::days(2);
let parsed = chrono::DateTime::parse_from_rfc3339(&plus).expect("valid RFC3339");
assert!((parsed.timestamp() - expected.timestamp()).abs() <= 2);
let formatted = render_templated("{{now format='%Y-%m-%d'}}", &tctx, false).unwrap();
assert_eq!(formatted.len(), "2026-07-08".len());
}
#[test]
fn uuid_is_valid_v4_shape() {
let data = request_data();
let s = store();
let tctx = ctx(&data, "flow-1", &s);
let out = render_templated("{{uuid}}", &tctx, false).unwrap();
let parsed = uuid::Uuid::parse_str(&out).expect("valid uuid");
assert_eq!(parsed.get_version_num(), 4);
}
#[test]
fn random_int_in_range() {
let data = request_data();
let s = store();
let tctx = ctx(&data, "flow-1", &s);
for _ in 0..20 {
let out = render_templated("{{randomInt 5 9}}", &tctx, false).unwrap();
let n: i64 = out.parse().expect("integer output");
assert!((5..=9).contains(&n), "randomInt out of range: {n}");
}
}
#[test]
fn state_present_and_missing() {
let data = request_data();
let s = store();
s.set("flow-1", "attempts", serde_json::json!(3)).unwrap();
let tctx = ctx(&data, "flow-1", &s);
assert_eq!(
render_templated("{{state.attempts}}", &tctx, false).unwrap(),
"3"
);
assert_eq!(
render_templated("[{{state.missing}}]", &tctx, false).unwrap(),
"[]"
);
assert!(render_templated("{{state.missing}}", &tctx, true).is_err());
}
#[test]
fn unknown_function_debug_errors_non_debug_empty_and_warns() {
let data = request_data();
let s = store();
let tctx = ctx(&data, "flow-1", &s);
assert!(render_templated("{{bogus}}", &tctx, true).is_err());
assert_eq!(render_templated("[{{bogus}}]", &tctx, false).unwrap(), "[]");
}
#[test]
fn headers_map_dotted_query_and_multiple_tokens_in_one_body() {
let mut headers = HashMap::new();
headers.insert("q".to_string(), "1".to_string());
let hm = hdrs(&[]);
let data = RequestData::new("GET", "/x/abc", Some("q=1"), &hm, None);
let s = store();
let tctx = ctx(&data, "flow-1", &s);
let out = render_templated(
"{\"method\":\"{{request.method}}\",\"q\":\"{{request.query.q}}\",\"seg\":\"{{request.path | last_segment}}\"}",
&tctx,
false,
)
.unwrap();
assert_eq!(out, r#"{"method":"GET","q":"1","seg":"abc"}"#);
let _ = headers; }
#[test]
fn legacy_date_tokens_still_expand_through_render_templated() {
let data = request_data();
let s = store();
let tctx = ctx(&data, "flow-1", &s);
let out = render_templated("{{NOW}}", &tctx, false).unwrap();
chrono::DateTime::parse_from_rfc3339(&out).expect("legacy {{NOW}} still expands");
}
#[test]
fn now_malformed_format_is_error_not_panic() {
let data = request_data();
let s = store();
let tctx = ctx(&data, "flow-1", &s);
for bad in ["100%", "%", "%-"] {
let token = format!("{{{{now format='{bad}'}}}}");
assert!(
render_templated(&token, &tctx, true).is_err(),
"malformed format '{bad}' must be a debug-mode error"
);
assert_eq!(
render_templated(&format!("[{token}]"), &tctx, false).unwrap(),
"[]",
"malformed format '{bad}' must degrade to empty in non-debug"
);
}
let ok = render_templated("{{now format='%Y-%m-%d'}}", &tctx, false).unwrap();
assert_eq!(ok.len(), "2026-07-08".len());
}
#[test]
fn json_filter_escapes_for_string_literal() {
let headers = hdrs(&[("X-Payload", &[r#"he said "hi"\ and left"#])]);
let data = RequestData::new("GET", "/x", None, &headers, None);
let s = store();
let tctx = ctx(&data, "flow-1", &s);
let out = render_templated(
r#"{"echo":"{{request.header 'X-Payload' | json}}"}"#,
&tctx,
false,
)
.unwrap();
let parsed: Value = serde_json::from_str(&out).expect("json filter yields valid JSON body");
assert_eq!(parsed["echo"], r#"he said "hi"\ and left"#);
}
#[test]
fn jsonpath_parser_rejects_malformed_paths() {
assert!(parse_jsonpath("a.b").is_err(), "must start with $");
assert!(parse_jsonpath("$.a[").is_err(), "unterminated [");
assert!(parse_jsonpath("$.a[x]").is_err(), "non-numeric index");
}
}