glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Reloading in development: templates whose text changed, and the
//! browser.
//!
//! Under `glacier server` (which sets `GLACIER_RELOAD`), a debug build's
//! templates read their static text from their files as they render, so
//! a change to markup, classes or wording shows on the next request
//! without a rebuild. The CLI rebuilds only when a template's code
//! changes (an expression, an `if`, a component's attributes): the
//! file's *skeleton*, which each compiled template carries, no longer
//! matches, and the compiled text is used until the new build is up.
//!
//! The page reloads itself, too: HTML responses get a small script that
//! long-polls `/__glacier/reload` and reloads when the CLI says something
//! changed, or when the server comes back after a rebuild.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant, SystemTime};

/// Where a compiled template came from: its file and its skeleton.
#[doc(hidden)]
pub struct Source {
    pub path: &'static str,
    pub skeleton: u64,
}

/// What `glacier server` sets: reload templates, and pages.
const ENV: &str = "GLACIER_RELOAD";

/// Whether this process reloads: under `glacier server`, in a debug build.
pub fn enabled() -> bool {
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| cfg!(debug_assertions) && std::env::var_os(ENV).is_some())
}

/// A file's blocks as last read, and when it was checked.
struct Entry {
    modified: Option<SystemTime>,
    checked: Instant,
    /// The file's static text by block, when its skeleton matches the
    /// compiled one; `None` to use the compiled text.
    blocks: Option<HashMap<String, &'static [&'static str]>>,
}

/// How often a template's file is looked at again.
const RECHECK: Duration = Duration::from_millis(100);

/// A block's static text: from the template's file when it's been
/// edited without changing its code, else as compiled. Called by
/// compiled templates in debug builds.
#[doc(hidden)]
pub fn statics(
    source: &'static Source,
    key: &str,
    compiled: &'static [&'static str],
) -> &'static [&'static str] {
    if !enabled() {
        return compiled;
    }
    static FILES: OnceLock<Mutex<HashMap<&'static str, Entry>>> = OnceLock::new();
    let mut files = FILES
        .get_or_init(Default::default)
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let entry = files.entry(source.path).or_insert_with(|| Entry {
        modified: None,
        checked: Instant::now() - RECHECK,
        blocks: None,
    });
    if entry.checked.elapsed() >= RECHECK {
        entry.checked = Instant::now();
        let modified = std::fs::metadata(source.path)
            .and_then(|m| m.modified())
            .ok();
        if modified != entry.modified {
            entry.modified = modified;
            entry.blocks = read(source);
        }
    }
    entry
        .blocks
        .as_ref()
        .and_then(|blocks| blocks.get(key))
        .copied()
        .filter(|statics| statics.len() == compiled.len())
        .unwrap_or(compiled)
}

/// The file's blocks, if it parses and its skeleton is the compiled one.
fn read(source: &Source) -> Option<HashMap<String, &'static [&'static str]>> {
    let code = std::fs::read_to_string(source.path).ok()?;
    let nodes = glacier_template::parse::parse(&code).ok()?;
    if glacier_template::skeleton(&nodes) != source.skeleton {
        return None;
    }
    // Leaked: a few kilobytes per edit, in development only.
    Some(
        glacier_template::statics(&nodes)
            .into_iter()
            .map(|(key, texts)| {
                let texts: Vec<&'static str> = texts
                    .into_iter()
                    .map(|t| &*Box::leak(t.into_boxed_str()))
                    .collect();
                (key, &*Box::leak(texts.into_boxed_slice()))
            })
            .collect(),
    )
}

/// The file `glacier server` writes when the page should reload without a
/// restart (a template's text, a stylesheet, a file in `public/`): its
/// path, from `GLACIER_RELOAD`.
fn signal_file() -> Option<PathBuf> {
    std::env::var_os(ENV).map(PathBuf::from)
}

/// What the page compares: this process's start, and the CLI's count of
/// changes since. A restart or a change makes it differ.
pub(crate) fn version() -> String {
    static BOOT: OnceLock<u128> = OnceLock::new();
    let boot = BOOT.get_or_init(|| {
        SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_or(0, |d| d.as_millis())
    });
    let count = signal_file()
        .and_then(|path| std::fs::read_to_string(path).ok())
        .unwrap_or_default();
    format!("{boot}-{}", count.trim())
}

/// `/__glacier/reload?v=…`: answers once the version differs from the
/// page's (or after 25 seconds, for the page to ask again).
pub(crate) async fn wait(seen: &str) -> String {
    let deadline = Instant::now() + Duration::from_secs(25);
    loop {
        let now = version();
        if now != seen || Instant::now() >= deadline {
            return now;
        }
        tokio::time::sleep(Duration::from_millis(150)).await;
    }
}

/// `/__glacier/reload?v=…`, in development.
pub(crate) async fn endpoint(ctx: crate::Context) -> crate::Response {
    #[derive(serde::Deserialize, Default)]
    struct Query {
        #[serde(default)]
        v: String,
    }
    let seen = ctx.query::<Query>().unwrap_or_default().v;
    crate::Response::text(wait(&seen).await)
}

/// The script added before `</body>` of HTML pages.
pub(crate) fn script() -> String {
    format!(
        "<script>(function(){{var v={:?};function poll(){{fetch('/__glacier/reload?v='+encodeURIComponent(v)).then(function(r){{return r.text()}}).then(function(n){{if(n!==v){{location.reload()}}else{{poll()}}}},function(){{setTimeout(poll,300)}})}}poll()}})();</script>",
        version()
    )
}