From e8e5094e9a48ac3e3bd54f3f6a8aef2e84894d73 Mon Sep 17 00:00:00 2001 From: Daan Oosterveld Date: Fri, 12 Feb 2021 15:58:17 +0100 Subject: [PATCH] Light cloning of templates Currently we are serving templates which are re-loadable asynchronously. There are also assets which are shared by the templates and are accessible through an async read lock. For rendering we need to register specific helpers which will alter the response for each request. The solution would be to clone all templates for each request. Then add the specific helpers for that situation. This is not ideal, because cloning all templates is slow. So by adding an Arc to Templates, they can be shared between all handlers building responses. Cloning is somewhat lighter with this change. It does break the get_templates call on registry. The other solution I have thought of was to add a generic type to the render call, which can be used by the helpers. This can then default to () for common cases. Third solution would be to separate the template management from the registry of helpers. In that case the templates can be put into a custom structure, and would aid custom reloading schemes. E.g. loading of the templates and then add that to a second structure holding the helpers, then render. The registry is a composition of these two structures. Asynchronous helpers would also fix this for us. But in the mean time this would help. --- src/registry.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/registry.rs b/src/registry.rs index cbf884a0c..e22ac0ee8 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -54,7 +54,7 @@ pub fn no_escape(data: &str) -> String { /// It maintains compiled templates and registered helpers. #[derive(Clone)] pub struct Registry<'reg> { - templates: HashMap, + templates: HashMap>, helpers: HashMap>, decorators: HashMap>, @@ -196,7 +196,7 @@ impl<'reg> Registry<'reg> { /// insert cannot fail. If there is an existing template with this name it /// will be overwritten. pub fn register_template(&mut self, name: &str, tpl: Template) { - self.templates.insert(name.to_string(), tpl); + self.templates.insert(name.to_string(), Arc::new(tpl)); } /// Register a template string @@ -398,7 +398,7 @@ impl<'reg> Registry<'reg> { /// Return a registered template, pub fn get_template(&self, name: &str) -> Option<&Template> { - self.templates.get(name) + self.templates.get(name).map(|x| &**x) } #[inline] @@ -413,6 +413,7 @@ impl<'reg> Registry<'reg> { } else { self.templates .get(name) + .map(|x| &**x) .map(Cow::Borrowed) .ok_or_else(|| RenderError::new(format!("Template not found: {}", name))) } @@ -454,7 +455,7 @@ impl<'reg> Registry<'reg> { } /// Return all templates registered - pub fn get_templates(&self) -> &HashMap { + pub fn get_templates(&self) -> &HashMap> { &self.templates }