rustysan-sword 0.1.1

Blade-inspired HTML templates for Rust
Documentation
//! Laravel Rust integration. Register [`SwordServiceProvider`] during bootstrap.
use laravel::config::{Config, Env, Section};
use laravel::container::{Container, Registrar};
use laravel::foundation::ServiceProvider;
use laravel::view::{Engine, Html, Template, TemplateError};

/// Settings read from the environment when the application starts.
///
/// The provider registers this section, so an application can override it in `with_config`:
///
/// ```ignore
/// .with_config(|config, _| {
///     config.section_mut::<SwordSettings>().cache_capacity = 256;
/// })
/// ```
///
/// Values given to the provider itself ([`SwordServiceProvider::with_cache_capacity`] and
/// `dump`) win over this section.
#[derive(Debug, Clone, Section)]
pub struct SwordSettings {
    /// Maximum number of cached templates (`SWORD_CACHE_CAPACITY`), capped at
    /// [`MAX_CACHE_CAPACITY`](crate::MAX_CACHE_CAPACITY); zero disables caching.
    #[env("SWORD_CACHE_CAPACITY", default = 128)]
    pub cache_capacity: usize,
    /// Whether `@dump` is enabled (`SWORD_DUMP`). It does nothing unless the `dump` Cargo
    /// feature is on, and it stops the application booting outside a `local` or `testing`
    /// environment.
    #[env("SWORD_DUMP", default = false)]
    pub dump: bool,
}

/// Registers the Sword engine for `.sword.html` views.
///
/// Each provider owns its cache and its typed components, so two applications in one
/// process share nothing. Settings come from [`SwordSettings`]; builder methods override them.
///
/// ```ignore
/// providers.add(SwordServiceProvider::new().component::<Alert>("alert")?);
/// ```
#[derive(Debug, Clone)]
pub struct SwordServiceProvider {
    cache: std::sync::Arc<crate::cache::Cache>,
    components: std::sync::Arc<crate::component::Components>,
    capacity: Option<usize>,
    dump: Option<bool>,
}

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

impl SwordServiceProvider {
    /// A provider with the default 128-entry cache and no typed components.
    pub fn new() -> Self {
        let components = std::sync::Arc::new(crate::component::Components::default());
        Self {
            cache: std::sync::Arc::new(crate::cache::Cache::new(128, components.clone())),
            components,
            capacity: None,
            dump: None,
        }
    }

    /// Enable `@dump`, a development tool; see [`Config::dump`](crate::Config::dump). It still
    /// renders nothing unless the application's environment is `local` or `testing`.
    #[cfg(feature = "dump")]
    pub fn dump(mut self, enabled: bool) -> Self {
        self.dump = Some(enabled);
        self
    }

    /// Set the maximum number of cached templates, capped at
    /// [`MAX_CACHE_CAPACITY`](crate::MAX_CACHE_CAPACITY); zero disables caching.
    pub fn with_cache_capacity(mut self, capacity: usize) -> Self {
        let capacity = capacity.min(crate::MAX_CACHE_CAPACITY);
        self.cache =
            std::sync::Arc::new(crate::cache::Cache::new(capacity, self.components.clone()));
        self.capacity = Some(capacity);
        self
    }

    /// Register a typed component, as [`Sword::with_component`](crate::Sword::with_component)
    /// does. This clears the provider's cache.
    pub fn component<T: crate::Component>(
        mut self,
        name: &str,
    ) -> Result<Self, crate::ComponentError> {
        let mut components = (*self.components).clone();
        components.register::<T>(name)?;
        self.components = std::sync::Arc::new(components);
        self.cache = std::sync::Arc::new(crate::cache::Cache::new(
            self.cache.stats().capacity,
            self.components.clone(),
        ));
        Ok(self)
    }

    /// Return statistics for this provider's in-memory cache.
    pub fn cache_stats(&self) -> crate::CacheStats {
        self.cache.stats()
    }
}

impl SwordServiceProvider {
    /// Whether `@dump` was asked for, by the builder or by the final settings.
    fn dump_requested(&self, config: &Config) -> bool {
        self.dump
            .unwrap_or_else(|| config.section::<SwordSettings>().dump)
    }
}

impl ServiceProvider for SwordServiceProvider {
    fn config(&self, config: &mut Config, env: &Env) {
        config.discover(env!("CARGO_CRATE_NAME"), env);
    }

    fn register(&self, app: &mut Registrar) {
        if self.capacity.is_none() {
            let wanted = app.config().section::<SwordSettings>().cache_capacity;
            self.cache
                .set_capacity(wanted.min(crate::MAX_CACHE_CAPACITY));
        }
        let dump = self.dump_requested(app.config());
        app.views().engine(
            "sword.html",
            SwordEngine {
                cache: self.cache.clone(),
                dump,
            },
        );
    }

    /// Refuse to start with `@dump` enabled outside a development environment, rather than
    /// silently rendering nothing.
    async fn boot(&self, app: &Container) -> laravel::Result<()> {
        #[cfg(feature = "dump")]
        {
            let config = app.config();
            let environment = config.app.env.as_str();
            if self.dump_requested(config) && !crate::dump::development(environment) {
                return Err(laravel::abort_with(
                    500,
                    format!(
                        "@dump is enabled but the environment is `{environment}`; \
                         it only runs in `local` or `testing`. Disable it (SWORD_DUMP or \
                         SwordServiceProvider::dump) outside development."
                    ),
                ));
            }
        }
        #[cfg(not(feature = "dump"))]
        let _ = app;
        Ok(())
    }
}

/// The environment, session and context of the request being rendered.
struct LaravelHost {
    environment: String,
    session: Option<laravel::session::Session>,
}

impl crate::host::Host for LaravelHost {
    fn environment(&self) -> &str {
        &self.environment
    }

    fn session(&self, key: &str) -> Result<Option<serde_json::Value>, String> {
        self.session
            .as_ref()
            .map(|session| session.get::<serde_json::Value>(key))
            .ok_or_else(|| {
                "this route has no session; routes in the `web` group start one".to_owned()
            })
    }

    fn context(&self, key: &str) -> Result<Option<serde_json::Value>, String> {
        if laravel::context::Context::current().is_none() {
            return Err("no context is available outside the application".to_owned());
        }
        Ok(laravel::context::get::<serde_json::Value>(key))
    }

    fn vite(&self, entries: &[String]) -> Result<String, String> {
        if laravel::context::Context::current().is_none() {
            return Err("@vite needs the application, which is not running".to_owned());
        }
        Ok(laravel::view::vite(entries).into_string())
    }

    fn vite_react_refresh(&self) -> Result<String, String> {
        if laravel::context::Context::current().is_none() {
            return Err("@viteReactRefresh needs the application, which is not running".to_owned());
        }
        Ok(laravel::view::vite_react_refresh().into_string())
    }
}

struct SwordEngine {
    cache: std::sync::Arc<crate::cache::Cache>,
    dump: bool,
}
impl SwordEngine {
    /// Whether `@dump` may run: compiled in, enabled, and in a development environment.
    fn dump_allowed(&self, environment: &str) -> bool {
        #[cfg(feature = "dump")]
        {
            self.dump && crate::dump::development(environment)
        }
        #[cfg(not(feature = "dump"))]
        {
            let _ = (self.dump, environment);
            false
        }
    }
}

impl Engine for SwordEngine {
    fn render(&self, template: &Template<'_>) -> laravel::Result<Html> {
        let source = template.source()?;
        if template.is_plain_text() {
            return Err(TemplateError::new(
                "Sword does not support plain-text rendering",
                template.path(),
            )
            .into());
        }
        let mut data = template.data();
        data.remove("__sword_csrf");
        if let Some(session) = template.session() {
            data.insert("__sword_csrf".into(), session.token().into());
        }
        let finder = template.finder().clone();
        let cache = self.cache.clone();
        // `View::with_html` markup arrives as strings in the merged data and must not be escaped.
        let trusted: Vec<String> = template
            .data_layers()
            .markup
            .iter()
            .map(|(name, _)| name.clone())
            .collect();
        let span = tracing::debug_span!("sword.render", view = template.name(), source = "laravel");
        let _entered = span.enter();
        let started = std::time::Instant::now();
        let job = crate::backend::Job {
            name: template.name(),
            source: &source,
            root_path: Some(template.path().to_path_buf()),
            trusted: &trusted,
            fragment: template.block(),
            dump: self.dump_allowed(template.config().app.env.as_str()),
            host: std::sync::Arc::new(LaravelHost {
                environment: template.config().app.env.as_str().to_owned(),
                session: template.session().cloned(),
            }),
        };
        let rendered = crate::backend::render_with_loader(job, &data, cache, move |name| {
            let file = match finder.find_with(name, &["sword.html"]) {
                Ok(file) => file,
                // A missing view is an answer, not a failure: `@includeIf` and
                // `@includeFirst` ask for it, and a plain `@include` reports it.
                Err(laravel::view::ViewError::NotFound { .. }) => return Ok(None),
                Err(e) => {
                    return Err(minijinja::Error::new(
                        minijinja::ErrorKind::TemplateNotFound,
                        e.to_string(),
                    ));
                }
            };
            let path = file.path.clone();
            file.contents()
                .map(|source| {
                    Some(crate::backend::TemplateSource {
                        text: source.into_owned(),
                        path: Some(path),
                    })
                })
                .map_err(|e| {
                    minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string())
                })
        })
        .inspect(|html| crate::record_success(html, started))
        .inspect_err(|error| crate::record_failure(error, started))
        .map_err(|error| {
            let (failed_name, line) = match &error {
                crate::Error::Syntax { template, line, .. }
                | crate::Error::Render { template, line, .. } => {
                    (Some(template.as_str()), Some(*line))
                }
                crate::Error::RenderUnlocated { template, .. } => (Some(template.as_str()), None),
                _ => (None, None),
            };
            let dependency = failed_name
                .filter(|name| *name != template.name())
                .and_then(|name| template.finder().find_with(name, &["sword.html"]).ok());
            let path = dependency
                .as_ref()
                .map_or_else(|| template.path().to_path_buf(), |file| file.path.clone());
            let contents = dependency
                .and_then(|file| file.contents().ok())
                .unwrap_or_else(|| source.clone());
            let mut mapped = TemplateError::new(error.to_string(), path).contents(contents);
            if let Some(line) = line {
                mapped = mapped.line(line);
            }
            mapped.caused_by(error)
        })?;
        Ok(Html::raw(rendered))
    }
}