ferri-pdf 0.3.0

HTML and CSS to PDF renderer for print, in pure Rust
Documentation
//! Jinja templates expanded into the HTML a render parses. The templates a template names
//! load through the render's resolver against its base, under the same file and network
//! policy as the document's other resources: content from a remote template reads no local
//! file.
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, Mutex, PoisonError};

use minijinja::value::{Serde, ValueKind};
use minijinja::{AutoEscape, Environment, ErrorKind, Value};
use serde::Serialize;

use crate::resources::{FILE_SCHEME, ResourceError};
use crate::{Error, ResourceBase, ResourceResolver};

/// The name errors give the template passed to the render, as Jinja2 names one from a string.
const ROOT_NAME: &str = "<template>";
const BYTE_ORDER_MARK: char = '\u{FEFF}';
const NOT_UTF8: &str = "not UTF-8";

/// A template's text and the data it renders with.
pub(crate) struct Template<'a> {
    source: &'a str,
    data: Value,
}

/// A template another one named, by the outcome of resolving that name.
enum Named {
    /// Named by the last render and not yet resolved.
    Requested,
    /// The text, and whether it was read from a remote base.
    Loaded {
        text: String,
        remote: bool,
    },
    Unavailable(String),
}

/// What the renders of one template have named so far.
#[derive(Default)]
struct Loading {
    named: BTreeMap<String, Named>,
    /// Names a remote template gave, whose content is remote whatever base it resolved to,
    /// as a `data:` URL's is.
    named_by_remote: BTreeSet<String>,
    /// The first local file a remote template named, which fails the render.
    refused: Option<String>,
}

impl Loading {
    fn is_remote(&self, name: &str) -> bool {
        self.named_by_remote.contains(name)
            || matches!(
                self.named.get(name),
                Some(Named::Loaded { remote: true, .. })
            )
    }

    /// Records `name` given by the template `parent`, refusing a local file if the parent
    /// is remote.
    fn join(&mut self, name: &str, parent: &str, base: &ResourceBase) {
        if !self.is_remote(parent) {
            return;
        }
        match base.resolve(name) {
            Ok(url) if url.scheme() == FILE_SCHEME => {
                self.refused.get_or_insert_with(|| {
                    format!(
                        "{parent} names {name}: {}",
                        ResourceError::LocalFromRemote(url)
                    )
                });
            }
            _ => {
                self.named_by_remote.insert(name.to_owned());
            }
        }
    }
}

type SharedLoading = Arc<Mutex<Loading>>;

impl<'a> Template<'a> {
    pub(crate) fn new<T: Serialize + ?Sized>(source: &'a str, data: &T) -> Self {
        Self {
            source,
            data: Value::from(Serde(data)),
        }
    }

    /// The HTML the template renders to. A render stops at the first template it names that
    /// is not resolved yet, or passes over it with `ignore missing`; what it named is resolved
    /// against `base` and it renders again, until it names nothing new.
    pub(crate) fn expand(
        &self,
        base: &ResourceBase,
        resolver: &dyn ResourceResolver,
    ) -> Result<String, Error> {
        if self.data.kind() != ValueKind::Map {
            return Err(Error::Template(format!(
                "data must be a map of names to values, not {}",
                self.data.kind()
            )));
        }
        let loading = SharedLoading::default();
        let mut environment = Environment::new();
        environment.set_auto_escape_callback(|_| AutoEscape::Html);
        environment.set_path_join_callback({
            let loading = Arc::clone(&loading);
            let base = base.clone();
            move |name, parent| {
                lock(&loading).join(name, parent, &base);
                Cow::Borrowed(name)
            }
        });
        environment.set_loader({
            let loading = Arc::clone(&loading);
            move |name| Ok(load(&loading, name))
        });
        environment
            .add_template(ROOT_NAME, self.source)
            .map_err(|error| template_error(&error, &lock(&loading).named))?;
        loop {
            let rendered = environment
                .get_template(ROOT_NAME)
                .and_then(|template| template.render(&self.data));
            if let Some(refused) = lock(&loading).refused.take() {
                return Err(Error::Template(refused));
            }
            let requested: Vec<String> = lock(&loading)
                .named
                .iter()
                .filter(|(_, template)| matches!(template, Named::Requested))
                .map(|(name, _)| name.clone())
                .collect();
            if requested.is_empty() {
                if resolver.interrupts() {
                    return Err(Error::Interrupted);
                }
                return rendered.map_err(|error| template_error(&error, &lock(&loading).named));
            }
            for name in requested {
                let template = match resolver.resolve(&name, base) {
                    Ok(resource) => match String::from_utf8(resource.bytes) {
                        Ok(text) => Named::Loaded {
                            text: match text.strip_prefix(BYTE_ORDER_MARK) {
                                Some(text) => text.to_owned(),
                                None => text,
                            },
                            remote: resource.base.is_remote(),
                        },
                        Err(_) => Named::Unavailable(NOT_UTF8.to_owned()),
                    },
                    Err(error) => Named::Unavailable(error.to_string()),
                };
                lock(&loading).named.insert(name, template);
            }
        }
    }
}

fn lock(loading: &SharedLoading) -> std::sync::MutexGuard<'_, Loading> {
    loading.lock().unwrap_or_else(PoisonError::into_inner)
}

/// The loader's answer for `name`: an unresolved name is recorded and, for now, not found.
fn load(loading: &SharedLoading, name: &str) -> Option<String> {
    let named = &mut lock(loading).named;
    match named.get(name) {
        Some(Named::Loaded { text, .. }) => Some(text.clone()),
        Some(Named::Unavailable(_) | Named::Requested) => None,
        None => {
            named.insert(name.to_owned(), Named::Requested);
            None
        }
    }
}

/// The error with its causes, which name the included template that failed. Jinja reports a
/// missing template without its loader's reason, so a template not found also gives the
/// reasons the named templates that did not resolve were unavailable.
fn template_error(error: &minijinja::Error, named: &BTreeMap<String, Named>) -> Error {
    let causes: Vec<&dyn std::error::Error> =
        std::iter::successors(Some(error as &dyn std::error::Error), |error| {
            error.source()
        })
        .collect();
    let not_found = causes.iter().any(|cause| {
        cause
            .downcast_ref::<minijinja::Error>()
            .is_some_and(|cause| cause.kind() == ErrorKind::TemplateNotFound)
    });
    let message = causes
        .iter()
        .map(ToString::to_string)
        .collect::<Vec<_>>()
        .join(": ");
    let reasons = named.iter().filter_map(|(name, template)| match template {
        Named::Unavailable(reason) if not_found => {
            Some(format!("; {name} is unavailable: {reason}"))
        }
        _ => None,
    });
    Error::Template(std::iter::once(message).chain(reasons).collect())
}