1use std::sync::Arc;
2
3use serde_json::{Map, Value};
4
5use super::template_fake_data::{generate_fake_value, generate_lorem};
6use super::template_phone::generate_random_phone;
7use super::template_random_values::{
8 generate_random_float, generate_random_hex, generate_random_int, generate_random_text,
9 generate_ulid, generate_uuid_v4, generate_uuid_v7, random_index, read_charset,
10};
11use crate::{Clock, RandomSource, format_rfc3339};
12
13const DEFAULT_RANDOM_LENGTH: usize = 32;
14const MAXIMUM_RANDOM_LENGTH: usize = 1024;
15
16pub trait TemplateFunctions: Send + Sync {
19 fn call_function(&self, function_name: &str, arguments: &[Value]) -> Option<Value>;
21 fn function_names(&self) -> Vec<&'static str>;
23 fn to_shared(&self) -> Arc<dyn TemplateFunctions>;
25}
26
27const STANDARD_FUNCTION_NAMES: &[&str] = &[
28 "uuid",
29 "uuid7",
30 "ulid",
31 "now",
32 "now_iso",
33 "now_unix",
34 "timestamp",
35 "timestamp_ms",
36 "random_int",
37 "random_float",
38 "random_bool",
39 "random_string",
40 "random_hex",
41 "random_otp",
42 "random_choice",
43 "random_phone",
44 "lorem",
45];
46
47const FAKE_FUNCTION_PREFIX: &str = "fake.";
49const DEFAULT_LOREM_WORDS: usize = 8;
50
51#[derive(Clone)]
54pub struct StandardTemplateFunctions {
55 clock: Arc<dyn Clock>,
56 random_source: Arc<dyn RandomSource>,
57}
58
59struct FunctionArguments<'call> {
61 positional: &'call [Value],
62 keyword: Option<&'call Map<String, Value>>,
63}
64
65impl<'call> FunctionArguments<'call> {
66 fn new(arguments: &'call [Value]) -> Self {
67 match arguments.split_last() {
68 Some((Value::Object(keyword), positional)) => Self {
69 positional,
70 keyword: Some(keyword),
71 },
72 _ => Self {
73 positional: arguments,
74 keyword: None,
75 },
76 }
77 }
78
79 fn read(&self, position: usize, argument_name: &str) -> Option<&'call Value> {
80 self.positional
81 .get(position)
82 .or_else(|| self.keyword.and_then(|keyword| keyword.get(argument_name)))
83 }
84
85 fn read_float(&self, position: usize, argument_name: &str) -> Option<f64> {
86 match self.read(position, argument_name)? {
87 Value::Number(number) => number.as_f64(),
88 Value::String(number_text) => number_text.trim().parse().ok(),
89 _ => None,
90 }
91 }
92
93 fn read_integer(&self, position: usize, argument_name: &str) -> Option<i64> {
94 self.read_float(position, argument_name)
95 .map(|number| number as i64)
96 }
97
98 fn read_length(&self, position: usize, argument_name: &str, default_length: usize) -> usize {
99 self.read_integer(position, argument_name)
100 .and_then(|length| usize::try_from(length).ok())
101 .unwrap_or(default_length)
102 .min(MAXIMUM_RANDOM_LENGTH)
103 }
104
105 fn read_text(&self, position: usize, argument_name: &str) -> Option<&'call str> {
106 self.read(position, argument_name).and_then(Value::as_str)
107 }
108}
109
110impl StandardTemplateFunctions {
111 pub fn new(clock: Arc<dyn Clock>, random_source: Arc<dyn RandomSource>) -> Self {
112 Self {
113 clock,
114 random_source,
115 }
116 }
117
118 fn call_random_function(
119 &self,
120 function_name: &str,
121 arguments: &FunctionArguments,
122 ) -> Option<Value> {
123 let random_source = self.random_source.as_ref();
124 let random_value = match function_name {
125 "random_int" => Value::from(generate_random_int(
126 random_source,
127 arguments.read_integer(0, "min").unwrap_or(0),
128 arguments.read_integer(1, "max").unwrap_or(100),
129 )),
130 "random_float" => Value::from(generate_random_float(
131 random_source,
132 arguments.read_float(0, "min").unwrap_or(0.0),
133 arguments.read_float(1, "max").unwrap_or(1.0),
134 u32::try_from(arguments.read_integer(2, "decimals").unwrap_or(2)).unwrap_or(2),
135 )),
136 "random_bool" => Value::from(random_source.next_u64() % 2 == 1),
137 "random_string" => Value::from(generate_random_text(
138 random_source,
139 arguments.read_length(0, "len", DEFAULT_RANDOM_LENGTH),
140 read_charset(arguments.read_text(1, "charset").unwrap_or("alnum")),
141 )),
142 "random_hex" => Value::from(generate_random_hex(
143 random_source,
144 arguments.read_length(0, "len", DEFAULT_RANDOM_LENGTH),
145 )),
146 "random_otp" => Value::from(generate_random_text(
147 random_source,
148 arguments.read_length(0, "digits", 6),
149 read_charset("numeric"),
150 )),
151 "random_choice" => pick_random_item(random_source, arguments.read(0, "list")),
152 "random_phone" => Value::from(generate_random_phone(
153 random_source,
154 arguments.read_text(0, "country").unwrap_or("US"),
155 )),
156 "lorem" => Value::from(generate_lorem(
157 random_source,
158 arguments.read_length(0, "words", DEFAULT_LOREM_WORDS),
159 )),
160 _ => {
161 let fake_method = function_name.strip_prefix(FAKE_FUNCTION_PREFIX)?;
162 Value::from(generate_fake_value(random_source, fake_method)?)
163 }
164 };
165 Some(random_value)
166 }
167}
168
169fn pick_random_item(random_source: &dyn RandomSource, list: Option<&Value>) -> Value {
170 match list {
171 Some(Value::Array(items)) if !items.is_empty() => {
172 items[random_index(random_source, items.len())].clone()
173 }
174 _ => Value::Null,
175 }
176}
177
178impl TemplateFunctions for StandardTemplateFunctions {
179 fn call_function(&self, function_name: &str, arguments: &[Value]) -> Option<Value> {
180 let now_unix_ms = self.clock.now_unix_ms();
181 let random_source = self.random_source.as_ref();
182 let generated_value = match function_name {
183 "uuid" => Value::from(generate_uuid_v4(random_source)),
184 "uuid7" => Value::from(generate_uuid_v7(random_source, now_unix_ms)),
185 "ulid" => Value::from(generate_ulid(random_source, now_unix_ms)),
186 "now" | "now_iso" => Value::from(format_rfc3339(now_unix_ms)),
187 "now_unix" => Value::from((now_unix_ms / 1000).to_string()),
188 "timestamp" => Value::from(now_unix_ms / 1000),
189 "timestamp_ms" => Value::from(now_unix_ms),
190 _ => {
191 return self
192 .call_random_function(function_name, &FunctionArguments::new(arguments));
193 }
194 };
195 Some(generated_value)
196 }
197
198 fn function_names(&self) -> Vec<&'static str> {
199 STANDARD_FUNCTION_NAMES.to_vec()
200 }
201
202 fn to_shared(&self) -> Arc<dyn TemplateFunctions> {
203 Arc::new(self.clone())
204 }
205}
206
207#[cfg(test)]
208mod tests {
209 use serde_json::json;
210
211 use super::*;
212 use crate::{FixedClock, SeededRandomSource};
213
214 fn functions() -> StandardTemplateFunctions {
215 StandardTemplateFunctions::new(
216 Arc::new(FixedClock::new(1_767_225_600_000)),
217 Arc::new(SeededRandomSource::new(7)),
218 )
219 }
220
221 fn call_text(function_name: &str, arguments: &[Value]) -> String {
222 functions()
223 .call_function(function_name, arguments)
224 .and_then(|value| value.as_str().map(str::to_owned))
225 .unwrap_or_default()
226 }
227
228 #[test]
230 fn random_text_has_the_asked_length_and_charset() {
231 let hex_text = call_text("random_hex", &[json!(32)]);
232 let upper_text = call_text("random_string", &[json!(5), json!({ "charset": "upper" })]);
233 let otp_code = call_text("random_otp", &[json!({ "digits": 4 })]);
234
235 assert_eq!(hex_text.len(), 32);
236 assert!(
237 hex_text
238 .chars()
239 .all(|character| character.is_ascii_hexdigit())
240 );
241 assert_eq!(upper_text.len(), 5);
242 assert!(
243 upper_text
244 .chars()
245 .all(|character| character.is_ascii_uppercase())
246 );
247 assert_eq!(otp_code.len(), 4);
248 assert!(otp_code.chars().all(|character| character.is_ascii_digit()));
249 }
250
251 #[test]
253 fn times_come_from_the_clock() {
254 let template_functions = functions();
255
256 assert_eq!(
257 template_functions.call_function("now_unix", &[]),
258 Some(json!("1767225600"))
259 );
260 assert_eq!(
261 template_functions.call_function("timestamp", &[]),
262 Some(json!(1_767_225_600))
263 );
264 assert_eq!(
265 template_functions.call_function("timestamp_ms", &[]),
266 Some(json!(1_767_225_600_000_i64))
267 );
268 assert_eq!(
269 template_functions.call_function("now", &[]),
270 Some(json!("2026-01-01T00:00:00Z"))
271 );
272 }
273
274 #[test]
276 fn choices_booleans_and_phones_are_well_formed() {
277 let template_functions = functions();
278
279 let picked_item = template_functions.call_function("random_choice", &[json!(["a", "b"])]);
280 let random_bool = template_functions.call_function("random_bool", &[]);
281 let empty_choice = template_functions.call_function("random_choice", &[json!([])]);
282 let phone_number = call_text("random_phone", &[json!("GB")]);
283
284 assert!(matches!(picked_item, Some(Value::String(item)) if item == "a" || item == "b"));
285 assert!(matches!(random_bool, Some(Value::Bool(_))));
286 assert_eq!(empty_choice, Some(Value::Null));
287 assert!(phone_number.starts_with("+44"));
288 assert_eq!(template_functions.call_function("sha256", &[]), None);
289 }
290}