use minijinja::Environment;
use parking_lot::RwLock;
use rand::Rng;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use super::cache::FileCache;
use super::context::TemplateContext;
pub type ParsedTemplate = Arc<String>;
pub struct TemplateEngine {
file_cache: Arc<FileCache>,
env: RwLock<Environment<'static>>,
compiled: RwLock<HashMap<String, String>>,
templates: RwLock<HashMap<String, ParsedTemplate>>,
next_id: AtomicU64,
}
impl TemplateEngine {
pub fn new() -> Self {
let file_cache = Arc::new(FileCache::new());
let mut env = Environment::new();
Self::register_functions(&mut env, Arc::clone(&file_cache));
Self {
file_cache,
env: RwLock::new(env),
compiled: RwLock::new(HashMap::new()),
templates: RwLock::new(HashMap::new()),
next_id: AtomicU64::new(0),
}
}
fn compile_once(&self, source: &str) -> anyhow::Result<String> {
if let Some(name) = self.compiled.read().get(source) {
return Ok(name.clone());
}
let name = format!(
"__compiled_{}",
self.next_id.fetch_add(1, Ordering::Relaxed)
);
self.env
.write()
.add_template_owned(name.clone(), source.to_string())
.map_err(|e| anyhow::anyhow!("failed to parse template: {e}"))?;
self.compiled
.write()
.insert(source.to_string(), name.clone());
Ok(name)
}
fn render_named(&self, name: &str, ctx: &TemplateContext) -> anyhow::Result<String> {
let env = self.env.read();
let tmpl = env
.get_template(name)
.map_err(|e| anyhow::anyhow!("failed to get template: {e}"))?;
tmpl.render(minijinja::context! {
user_id => &ctx.user_id,
})
.map_err(|e| anyhow::anyhow!("failed to render template: {e}"))
}
pub fn parse(&self, name: &str, text: &str) -> anyhow::Result<ParsedTemplate> {
let processed = Self::preprocess(text);
self.env
.write()
.add_template_owned(name.to_string(), processed.clone())
.map_err(|e| anyhow::anyhow!("failed to parse template '{name}': {e}"))?;
let tpl = Arc::new(processed);
self.templates
.write()
.insert(name.to_string(), Arc::clone(&tpl));
Ok(tpl)
}
pub fn execute(
&self,
template: &ParsedTemplate,
ctx: &TemplateContext,
) -> anyhow::Result<String> {
let name = self.compile_once(template.as_str())?;
self.render_named(&name, ctx)
}
pub fn execute_str(&self, text: &str, ctx: &TemplateContext) -> anyhow::Result<String> {
let processed = Self::preprocess(text);
let name = self.compile_once(&processed)?;
self.render_named(&name, ctx)
}
pub fn compiled_template_count(&self) -> usize {
self.compiled.read().len()
}
pub fn file_cache(&self) -> &Arc<FileCache> {
&self.file_cache
}
fn register_functions(env: &mut Environment<'static>, file_cache: Arc<FileCache>) {
let file_cache = Arc::clone(&file_cache);
env.add_function("random_int", |min: i64, max: i64| -> i64 {
if min >= max {
min
} else {
rand::thread_rng().gen_range(min..max)
}
});
env.add_function("uuid", || -> String { uuid::Uuid::new_v4().to_string() });
env.add_function("random_choice", |values: Vec<String>| -> String {
if values.is_empty() {
String::new()
} else {
let idx = rand::thread_rng().gen_range(0..values.len());
values[idx].clone()
}
});
let fc1 = Arc::clone(&file_cache);
env.add_function("random_line", move |path: String| -> String {
match fc1.get_lines(&path) {
Ok(lines) if !lines.is_empty() => {
let idx = rand::thread_rng().gen_range(0..lines.len());
lines[idx].clone()
}
_ => String::new(),
}
});
let fc2 = Arc::clone(&file_cache);
env.add_function("read_file", move |path: String| -> String {
fc2.get_raw(&path).unwrap_or_default()
});
}
fn preprocess(input: &str) -> String {
let mut output = input.to_string();
output = output.replace("{{userID}}", "{{ user_id }}");
output = output.replace("{{uuid}}", "{{ uuid() }}");
output = output.replace("{{requestID}}", "{{ uuid() }}");
output
}
}
impl Default for TemplateEngine {
fn default() -> Self {
Self::new()
}
}