rustysan-sword 0.1.1

Blade-inspired HTML templates for Rust
Documentation
#![doc = include_str!("../README.md")]
mod auth;
mod backend;
mod cache;
mod component;
mod config;
#[cfg(feature = "dump")]
mod dump;
mod error;
mod host;
mod parser;
mod source_map;
pub use auth::AuthContext;
pub use cache::CacheStats;
pub use component::{Component, ComponentError, Html};
pub use config::{
    CACHE_CAPACITY_ENV, Config, ConfigBuilder, ConfigError, DEFAULT_CACHE_CAPACITY,
    DEFAULT_ENVIRONMENT, ENVIRONMENT_ENV, MAX_CACHE_CAPACITY, MAX_ENVIRONMENT_LEN, VIEWS_ENV,
};
pub use error::Error;
use serde::Serialize;

/// A renderer with ordered template roots.
#[derive(Debug, Clone)]
pub struct Sword {
    config: Config,
    cache: std::sync::Arc<cache::Cache>,
    components: std::sync::Arc<component::Components>,
}
impl Sword {
    /// A renderer for `config`.
    pub fn new(config: Config) -> Self {
        let components = std::sync::Arc::new(component::Components::default());
        let cache = std::sync::Arc::new(cache::Cache::new(
            config.cache_capacity(),
            components.clone(),
        ));
        Self {
            config,
            cache,
            components,
        }
    }
    /// Register a typed component under the name used in markup: `"alert"` serves
    /// `<x-alert>`, which renders `components/alert.sword.html`.
    ///
    /// The tag's attributes are deserialized into `T`; the template reads each field as a
    /// variable. Registration happens while building the engine, which clears its cache.
    /// It fails for a name that is invalid or already registered, and for a type that is
    /// not a struct with named fields (`#[serde(flatten)]` is not supported).
    pub fn with_component<T: Component>(mut self, name: &str) -> Result<Self, ComponentError> {
        let mut components = (*self.components).clone();
        components.register::<T>(name)?;
        self.components = std::sync::Arc::new(components);
        self.cache = std::sync::Arc::new(cache::Cache::new(
            self.cache.stats().capacity,
            self.components.clone(),
        ));
        Ok(self)
    }
    /// Set the maximum number of cached templates, capped at [`MAX_CACHE_CAPACITY`];
    /// zero disables caching.
    pub fn with_cache_capacity(mut self, capacity: usize) -> Self {
        self.cache = std::sync::Arc::new(cache::Cache::new(
            capacity.min(MAX_CACHE_CAPACITY),
            self.components.clone(),
        ));
        self
    }
    /// Return cache counters and the current entry count.
    pub fn cache_stats(&self) -> CacheStats {
        self.cache.stats()
    }
    /// Whether `@dump` may run: compiled in, enabled, and in a development environment.
    fn dump_enabled(&self) -> bool {
        #[cfg(feature = "dump")]
        {
            self.config.dump() && dump::development(self.config.environment())
        }
        #[cfg(not(feature = "dump"))]
        {
            false
        }
    }
    fn host(&self) -> std::sync::Arc<dyn host::Host> {
        std::sync::Arc::new(host::Standalone {
            environment: self.config.environment().to_owned(),
        })
    }
    /// Render a source string with HTML escaping.
    pub fn render_source(
        &self,
        name: &str,
        source: &str,
        data: &impl Serialize,
    ) -> Result<String, Error> {
        self.render_source_inner(name, source, None, data)
    }
    /// Render a source string and return only the named `@fragment`.
    ///
    /// The whole template still runs, so layouts, sections, and stacks have their usual
    /// effects; only the captured fragment is returned. If the same fragment name is
    /// rendered more than once, the last capture is returned. A name that never rendered
    /// is [`Error::FragmentNotFound`].
    pub fn render_source_fragment(
        &self,
        name: &str,
        source: &str,
        fragment: &str,
        data: &impl Serialize,
    ) -> Result<String, Error> {
        self.render_source_inner(name, source, Some(fragment), data)
    }
    fn render_source_inner(
        &self,
        name: &str,
        source: &str,
        fragment: Option<&str>,
        data: &impl Serialize,
    ) -> Result<String, Error> {
        let span = tracing::debug_span!("sword.render", view = name, source = "string");
        let _entered = span.enter();
        let started = std::time::Instant::now();
        let job = backend::Job {
            name,
            source,
            root_path: None,
            trusted: &[],
            fragment,
            host: self.host(),
            dump: self.dump_enabled(),
        };
        let result = backend::render(job, data, self.config.roots(), self.cache.clone());
        record_outcome(&result, started);
        result
    }
    /// Resolve a dotted view name under configured roots and render it.
    ///
    /// This reads template files and renders on the calling thread. From async code, run it
    /// on a blocking thread, for example with `tokio::task::spawn_blocking`; `Sword` is
    /// cheap to clone and is `Send + Sync`.
    pub fn render(&self, name: &str, data: &impl Serialize) -> Result<String, Error> {
        self.render_view(name, None, data)
    }
    /// Resolve a view and return only the named `@fragment`; see
    /// [`Sword::render_source_fragment`].
    pub fn render_fragment(
        &self,
        name: &str,
        fragment: &str,
        data: &impl Serialize,
    ) -> Result<String, Error> {
        self.render_view(name, Some(fragment), data)
    }
    fn render_view(
        &self,
        name: &str,
        fragment: Option<&str>,
        data: &impl Serialize,
    ) -> Result<String, Error> {
        let span = tracing::debug_span!("sword.render", view = name, source = "file");
        let _entered = span.enter();
        let started = std::time::Instant::now();
        let result = self.render_file(name, fragment, data);
        record_outcome(&result, started);
        result
    }

    fn render_file(
        &self,
        name: &str,
        fragment: Option<&str>,
        data: &impl Serialize,
    ) -> Result<String, Error> {
        if !valid_name(name) {
            return Err(Error::InvalidName(name.into()));
        }
        let relative = format!("{}.sword.html", name.replace('.', "/"));
        for root in self.config.roots() {
            let path = root.join(&relative);
            match std::fs::read_to_string(&path) {
                Ok(source) => {
                    let job = backend::Job {
                        name,
                        source: &source,
                        root_path: Some(path),
                        trusted: &[],
                        fragment,
                        host: self.host(),
                        dump: self.dump_enabled(),
                    };
                    return backend::render(job, data, self.config.roots(), self.cache.clone());
                }
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
                Err(source) => return Err(Error::Io { path, source }),
            }
        }
        Err(Error::NotFound(name.into()))
    }
}

/// Log the outcome with allowlisted fields only: sizes, timing, and an error kind.
fn record_outcome(result: &Result<String, Error>, started: std::time::Instant) {
    match result {
        Ok(html) => record_success(html, started),
        Err(error) => record_failure(error, started),
    }
}

fn elapsed_us(started: std::time::Instant) -> u64 {
    u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX)
}

pub(crate) fn record_success(html: &str, started: std::time::Instant) {
    tracing::debug!(
        bytes = html.len(),
        elapsed_us = elapsed_us(started),
        "sword render finished"
    );
}

pub(crate) fn record_failure(error: &Error, started: std::time::Instant) {
    tracing::debug!(
        error = error.kind(),
        elapsed_us = elapsed_us(started),
        "sword render failed"
    );
}

impl Default for Sword {
    fn default() -> Self {
        Self::new(Config::default())
    }
}

#[cfg(feature = "laravel")]
pub mod laravel;

fn valid_name(name: &str) -> bool {
    !name.is_empty()
        && name.split('.').all(|p| {
            !p.is_empty()
                && p.chars()
                    .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
        })
}

#[cfg(doctest)]
mod guide {
    include!(concat!(env!("OUT_DIR"), "/documentation.rs"));
}