Skip to main content

rustysan_sword/
lib.rs

1#![doc = include_str!("../README.md")]
2mod auth;
3mod backend;
4mod cache;
5mod component;
6mod config;
7#[cfg(feature = "dump")]
8mod dump;
9mod error;
10mod host;
11mod parser;
12mod source_map;
13pub use auth::AuthContext;
14pub use cache::CacheStats;
15pub use component::{Component, ComponentError, Html};
16pub use config::{
17    CACHE_CAPACITY_ENV, Config, ConfigBuilder, ConfigError, DEFAULT_CACHE_CAPACITY,
18    DEFAULT_ENVIRONMENT, ENVIRONMENT_ENV, MAX_CACHE_CAPACITY, MAX_ENVIRONMENT_LEN, VIEWS_ENV,
19};
20pub use error::Error;
21use serde::Serialize;
22
23/// A renderer with ordered template roots.
24#[derive(Debug, Clone)]
25pub struct Sword {
26    config: Config,
27    cache: std::sync::Arc<cache::Cache>,
28    components: std::sync::Arc<component::Components>,
29}
30impl Sword {
31    /// A renderer for `config`.
32    pub fn new(config: Config) -> Self {
33        let components = std::sync::Arc::new(component::Components::default());
34        let cache = std::sync::Arc::new(cache::Cache::new(
35            config.cache_capacity(),
36            components.clone(),
37        ));
38        Self {
39            config,
40            cache,
41            components,
42        }
43    }
44    /// Register a typed component under the name used in markup: `"alert"` serves
45    /// `<x-alert>`, which renders `components/alert.sword.html`.
46    ///
47    /// The tag's attributes are deserialized into `T`; the template reads each field as a
48    /// variable. Registration happens while building the engine, which clears its cache.
49    /// It fails for a name that is invalid or already registered, and for a type that is
50    /// not a struct with named fields (`#[serde(flatten)]` is not supported).
51    pub fn with_component<T: Component>(mut self, name: &str) -> Result<Self, ComponentError> {
52        let mut components = (*self.components).clone();
53        components.register::<T>(name)?;
54        self.components = std::sync::Arc::new(components);
55        self.cache = std::sync::Arc::new(cache::Cache::new(
56            self.cache.stats().capacity,
57            self.components.clone(),
58        ));
59        Ok(self)
60    }
61    /// Set the maximum number of cached templates, capped at [`MAX_CACHE_CAPACITY`];
62    /// zero disables caching.
63    pub fn with_cache_capacity(mut self, capacity: usize) -> Self {
64        self.cache = std::sync::Arc::new(cache::Cache::new(
65            capacity.min(MAX_CACHE_CAPACITY),
66            self.components.clone(),
67        ));
68        self
69    }
70    /// Return cache counters and the current entry count.
71    pub fn cache_stats(&self) -> CacheStats {
72        self.cache.stats()
73    }
74    /// Whether `@dump` may run: compiled in, enabled, and in a development environment.
75    fn dump_enabled(&self) -> bool {
76        #[cfg(feature = "dump")]
77        {
78            self.config.dump() && dump::development(self.config.environment())
79        }
80        #[cfg(not(feature = "dump"))]
81        {
82            false
83        }
84    }
85    fn host(&self) -> std::sync::Arc<dyn host::Host> {
86        std::sync::Arc::new(host::Standalone {
87            environment: self.config.environment().to_owned(),
88        })
89    }
90    /// Render a source string with HTML escaping.
91    pub fn render_source(
92        &self,
93        name: &str,
94        source: &str,
95        data: &impl Serialize,
96    ) -> Result<String, Error> {
97        self.render_source_inner(name, source, None, data)
98    }
99    /// Render a source string and return only the named `@fragment`.
100    ///
101    /// The whole template still runs, so layouts, sections, and stacks have their usual
102    /// effects; only the captured fragment is returned. If the same fragment name is
103    /// rendered more than once, the last capture is returned. A name that never rendered
104    /// is [`Error::FragmentNotFound`].
105    pub fn render_source_fragment(
106        &self,
107        name: &str,
108        source: &str,
109        fragment: &str,
110        data: &impl Serialize,
111    ) -> Result<String, Error> {
112        self.render_source_inner(name, source, Some(fragment), data)
113    }
114    fn render_source_inner(
115        &self,
116        name: &str,
117        source: &str,
118        fragment: Option<&str>,
119        data: &impl Serialize,
120    ) -> Result<String, Error> {
121        let span = tracing::debug_span!("sword.render", view = name, source = "string");
122        let _entered = span.enter();
123        let started = std::time::Instant::now();
124        let job = backend::Job {
125            name,
126            source,
127            root_path: None,
128            trusted: &[],
129            fragment,
130            host: self.host(),
131            dump: self.dump_enabled(),
132        };
133        let result = backend::render(job, data, self.config.roots(), self.cache.clone());
134        record_outcome(&result, started);
135        result
136    }
137    /// Resolve a dotted view name under configured roots and render it.
138    ///
139    /// This reads template files and renders on the calling thread. From async code, run it
140    /// on a blocking thread, for example with `tokio::task::spawn_blocking`; `Sword` is
141    /// cheap to clone and is `Send + Sync`.
142    pub fn render(&self, name: &str, data: &impl Serialize) -> Result<String, Error> {
143        self.render_view(name, None, data)
144    }
145    /// Resolve a view and return only the named `@fragment`; see
146    /// [`Sword::render_source_fragment`].
147    pub fn render_fragment(
148        &self,
149        name: &str,
150        fragment: &str,
151        data: &impl Serialize,
152    ) -> Result<String, Error> {
153        self.render_view(name, Some(fragment), data)
154    }
155    fn render_view(
156        &self,
157        name: &str,
158        fragment: Option<&str>,
159        data: &impl Serialize,
160    ) -> Result<String, Error> {
161        let span = tracing::debug_span!("sword.render", view = name, source = "file");
162        let _entered = span.enter();
163        let started = std::time::Instant::now();
164        let result = self.render_file(name, fragment, data);
165        record_outcome(&result, started);
166        result
167    }
168
169    fn render_file(
170        &self,
171        name: &str,
172        fragment: Option<&str>,
173        data: &impl Serialize,
174    ) -> Result<String, Error> {
175        if !valid_name(name) {
176            return Err(Error::InvalidName(name.into()));
177        }
178        let relative = format!("{}.sword.html", name.replace('.', "/"));
179        for root in self.config.roots() {
180            let path = root.join(&relative);
181            match std::fs::read_to_string(&path) {
182                Ok(source) => {
183                    let job = backend::Job {
184                        name,
185                        source: &source,
186                        root_path: Some(path),
187                        trusted: &[],
188                        fragment,
189                        host: self.host(),
190                        dump: self.dump_enabled(),
191                    };
192                    return backend::render(job, data, self.config.roots(), self.cache.clone());
193                }
194                Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
195                Err(source) => return Err(Error::Io { path, source }),
196            }
197        }
198        Err(Error::NotFound(name.into()))
199    }
200}
201
202/// Log the outcome with allowlisted fields only: sizes, timing, and an error kind.
203fn record_outcome(result: &Result<String, Error>, started: std::time::Instant) {
204    match result {
205        Ok(html) => record_success(html, started),
206        Err(error) => record_failure(error, started),
207    }
208}
209
210fn elapsed_us(started: std::time::Instant) -> u64 {
211    u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX)
212}
213
214pub(crate) fn record_success(html: &str, started: std::time::Instant) {
215    tracing::debug!(
216        bytes = html.len(),
217        elapsed_us = elapsed_us(started),
218        "sword render finished"
219    );
220}
221
222pub(crate) fn record_failure(error: &Error, started: std::time::Instant) {
223    tracing::debug!(
224        error = error.kind(),
225        elapsed_us = elapsed_us(started),
226        "sword render failed"
227    );
228}
229
230impl Default for Sword {
231    fn default() -> Self {
232        Self::new(Config::default())
233    }
234}
235
236#[cfg(feature = "laravel")]
237pub mod laravel;
238
239fn valid_name(name: &str) -> bool {
240    !name.is_empty()
241        && name.split('.').all(|p| {
242            !p.is_empty()
243                && p.chars()
244                    .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
245        })
246}
247
248#[cfg(doctest)]
249mod guide {
250    include!(concat!(env!("OUT_DIR"), "/documentation.rs"));
251}