use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant, SystemTime};
#[doc(hidden)]
pub struct Source {
pub path: &'static str,
pub skeleton: u64,
}
const ENV: &str = "GLACIER_RELOAD";
pub fn enabled() -> bool {
static ENABLED: OnceLock<bool> = OnceLock::new();
*ENABLED.get_or_init(|| cfg!(debug_assertions) && std::env::var_os(ENV).is_some())
}
struct Entry {
modified: Option<SystemTime>,
checked: Instant,
blocks: Option<HashMap<String, &'static [&'static str]>>,
}
const RECHECK: Duration = Duration::from_millis(100);
#[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)
}
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;
}
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(),
)
}
fn signal_file() -> Option<PathBuf> {
std::env::var_os(ENV).map(PathBuf::from)
}
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())
}
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;
}
}
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)
}
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()
)
}