From 24d28e27c6662a39f3ceba7b8a77965cd10a0c74 Mon Sep 17 00:00:00 2001 From: lassidevs Date: Tue, 28 Oct 2025 22:57:54 +0200 Subject: [PATCH 1/2] fix: typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7166c0a..2c6df1c 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ cargo build fastly compute publish ``` -## Devleopment +## Development #### Install viceroy for running tests ```sh From 1f653123791f3ed9dcb5f8eab185fedc4ca6230e Mon Sep 17 00:00:00 2001 From: lassidevs Date: Tue, 28 Oct 2025 23:58:33 +0200 Subject: [PATCH 2/2] feat: optimize handlebars with lazy globals Use a thread-safe OnceLock to lazily initialize and cache the global Handlebars renderer --- crates/common/src/synthetic.rs | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/crates/common/src/synthetic.rs b/crates/common/src/synthetic.rs index b62ec8c..83b7f0d 100644 --- a/crates/common/src/synthetic.rs +++ b/crates/common/src/synthetic.rs @@ -10,6 +10,7 @@ use handlebars::Handlebars; use hmac::{Hmac, Mac}; use serde_json::json; use sha2::Sha256; +use std::sync::OnceLock; use crate::constants::{HEADER_SYNTHETIC_PUB_USER_ID, HEADER_SYNTHETIC_TRUSTED_SERVER}; use crate::cookies::handle_request_cookies; @@ -18,6 +19,18 @@ use crate::settings::Settings; type HmacSha256 = Hmac; +static HANDLEBARS: OnceLock> = OnceLock::new(); + +/// Returns a global, lazily initialized `Handlebars` instance. +fn handlebars(hb_template: &str) -> &'static Handlebars<'static> { + HANDLEBARS.get_or_init(|| { + let mut hbs = Handlebars::new(); + hbs.register_template_string("synthetic_id", hb_template) + .expect("Failed to register synthetic ID template at startup"); + hbs + }) +} + /// Generates a fresh synthetic ID based on request parameters. /// /// Creates a deterministic ID using HMAC-SHA256 with the configured secret key @@ -50,7 +63,8 @@ pub fn generate_synthetic_id( .and_then(|h| h.to_str().ok()) .map(|lang| lang.split(',').next().unwrap_or("unknown")); - let handlebars = Handlebars::new(); + let handlebars = handlebars(&settings.synthetic.template); + let data = &json!({ "client_ip": client_ip.unwrap_or("unknown".to_string()), "user_agent": user_agent.unwrap_or("unknown"), @@ -60,11 +74,12 @@ pub fn generate_synthetic_id( "accept_language": accept_language.unwrap_or("unknown") }); - let input_string = handlebars - .render_template(&settings.synthetic.template, data) - .change_context(TrustedServerError::Template { - message: "Failed to render synthetic ID template".to_string(), - })?; + let input_string = + handlebars + .render("synthetic_id", data) + .change_context(TrustedServerError::Template { + message: "Failed to render synthetic ID template".to_string(), + })?; log::info!("Input string for fresh ID: {} {}", input_string, data);