#![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;
#[derive(Debug, Clone)]
pub struct Sword {
config: Config,
cache: std::sync::Arc<cache::Cache>,
components: std::sync::Arc<component::Components>,
}
impl Sword {
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,
}
}
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)
}
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
}
pub fn cache_stats(&self) -> CacheStats {
self.cache.stats()
}
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(),
})
}
pub fn render_source(
&self,
name: &str,
source: &str,
data: &impl Serialize,
) -> Result<String, Error> {
self.render_source_inner(name, source, None, data)
}
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
}
pub fn render(&self, name: &str, data: &impl Serialize) -> Result<String, Error> {
self.render_view(name, None, data)
}
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()))
}
}
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"));
}