|
| 1 | +use super::TEMPLATE_DATA; |
| 2 | +use crate::error::Result; |
| 3 | +use arc_swap::ArcSwap; |
| 4 | +use serde_json::Value; |
| 5 | +use std::collections::HashMap; |
| 6 | +use tera::{Result as TeraResult, Tera}; |
| 7 | + |
| 8 | +/// Holds all data relevant to templating |
| 9 | +pub(crate) struct TemplateData { |
| 10 | + /// The actual templates, stored in an `ArcSwap` so that they're hot-swappable |
| 11 | + // TODO: Conditional compilation so it's not always wrapped, the `ArcSwap` is unneeded overhead for prod |
| 12 | + pub templates: ArcSwap<Tera>, |
| 13 | + /// The current global alert, serialized into a json value |
| 14 | + global_alert: Value, |
| 15 | + /// The version of docs.rs, serialized into a json value |
| 16 | + docsrs_version: Value, |
| 17 | + /// The current resource suffix of rustc, serialized into a json value |
| 18 | + resource_suffix: Value, |
| 19 | +} |
| 20 | + |
| 21 | +impl TemplateData { |
| 22 | + pub fn new() -> Result<Self> { |
| 23 | + log::trace!("Loading templates"); |
| 24 | + |
| 25 | + let data = Self { |
| 26 | + templates: ArcSwap::from_pointee(load_templates()?), |
| 27 | + global_alert: serde_json::to_value(crate::GLOBAL_ALERT)?, |
| 28 | + docsrs_version: Value::String(crate::BUILD_VERSION.to_owned()), |
| 29 | + resource_suffix: Value::String(load_rustc_resource_suffix().unwrap_or_else(|err| { |
| 30 | + log::error!("Failed to load rustc resource suffix: {:?}", err); |
| 31 | + String::from("???") |
| 32 | + })), |
| 33 | + }; |
| 34 | + |
| 35 | + log::trace!("Finished loading templates"); |
| 36 | + |
| 37 | + Ok(data) |
| 38 | + } |
| 39 | + |
| 40 | + pub fn start_template_reloading() { |
| 41 | + use std::{sync::Arc, thread, time::Duration}; |
| 42 | + |
| 43 | + thread::spawn(|| loop { |
| 44 | + match load_templates() { |
| 45 | + Ok(templates) => { |
| 46 | + log::info!("Reloaded templates"); |
| 47 | + TEMPLATE_DATA.templates.swap(Arc::new(templates)); |
| 48 | + thread::sleep(Duration::from_secs(10)); |
| 49 | + } |
| 50 | + |
| 51 | + Err(err) => { |
| 52 | + log::info!("Error Loading Templates:\n{}", err); |
| 53 | + thread::sleep(Duration::from_secs(5)); |
| 54 | + } |
| 55 | + } |
| 56 | + }); |
| 57 | + } |
| 58 | + |
| 59 | + /// Used to initialize a `TemplateData` instance in a `lazy_static`. |
| 60 | + /// Loading tera takes a second, so it's important that this is done before any |
| 61 | + /// requests start coming in |
| 62 | + pub fn poke(&self) -> Result<()> { |
| 63 | + Ok(()) |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +// TODO: Is there a reason this isn't fatal? If the rustc version is incorrect (Or "???" as used by default), then |
| 68 | +// all pages will be served *really* weird because they'll lack all CSS |
| 69 | +fn load_rustc_resource_suffix() -> Result<String> { |
| 70 | + let conn = crate::db::connect_db()?; |
| 71 | + |
| 72 | + let res = conn.query( |
| 73 | + "SELECT value FROM config WHERE name = 'rustc_version';", |
| 74 | + &[], |
| 75 | + )?; |
| 76 | + if res.is_empty() { |
| 77 | + failure::bail!("missing rustc version"); |
| 78 | + } |
| 79 | + |
| 80 | + if let Some(Ok(vers)) = res.get(0).get_opt::<_, Value>("value") { |
| 81 | + if let Some(vers_str) = vers.as_str() { |
| 82 | + return Ok(crate::utils::parse_rustc_version(vers_str)?); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + failure::bail!("failed to parse the rustc version"); |
| 87 | +} |
| 88 | + |
| 89 | +pub(super) fn load_templates() -> TeraResult<Tera> { |
| 90 | + let mut tera = Tera::new("templates/**/*")?; |
| 91 | + |
| 92 | + // Custom functions |
| 93 | + tera.register_function("global_alert", global_alert); |
| 94 | + tera.register_function("docsrs_version", docsrs_version); |
| 95 | + tera.register_function("rustc_resource_suffix", rustc_resource_suffix); |
| 96 | + |
| 97 | + // Custom filters |
| 98 | + tera.register_filter("timeformat", timeformat); |
| 99 | + tera.register_filter("dbg", dbg); |
| 100 | + tera.register_filter("dedent", dedent); |
| 101 | + |
| 102 | + Ok(tera) |
| 103 | +} |
| 104 | + |
| 105 | +/// Returns an `Option<GlobalAlert>` in json form for templates |
| 106 | +fn global_alert(args: &HashMap<String, Value>) -> TeraResult<Value> { |
| 107 | + debug_assert!(args.is_empty(), "global_alert takes no args"); |
| 108 | + |
| 109 | + Ok(TEMPLATE_DATA.global_alert.clone()) |
| 110 | +} |
| 111 | + |
| 112 | +/// Returns the version of docs.rs, takes the `safe` parameter which can be `true` to get a url-safe version |
| 113 | +fn docsrs_version(args: &HashMap<String, Value>) -> TeraResult<Value> { |
| 114 | + debug_assert!( |
| 115 | + args.is_empty(), |
| 116 | + "docsrs_version only takes no args, to get a safe version use `docsrs_version() | slugify`", |
| 117 | + ); |
| 118 | + |
| 119 | + Ok(TEMPLATE_DATA.docsrs_version.clone()) |
| 120 | +} |
| 121 | + |
| 122 | +/// Returns the current rustc resource suffix |
| 123 | +fn rustc_resource_suffix(args: &HashMap<String, Value>) -> TeraResult<Value> { |
| 124 | + debug_assert!(args.is_empty(), "rustc_resource_suffix takes no args"); |
| 125 | + |
| 126 | + Ok(TEMPLATE_DATA.resource_suffix.clone()) |
| 127 | +} |
| 128 | + |
| 129 | +/// Prettily format a timestamp |
| 130 | +// TODO: This can be replaced by chrono |
| 131 | +fn timeformat(value: &Value, args: &HashMap<String, Value>) -> TeraResult<Value> { |
| 132 | + let fmt = if let Some(Value::Bool(true)) = args.get("relative") { |
| 133 | + let value = time::strptime(value.as_str().unwrap(), "%Y-%m-%dT%H:%M:%S%z").unwrap(); |
| 134 | + |
| 135 | + super::super::duration_to_str(value.to_timespec()) |
| 136 | + } else { |
| 137 | + const TIMES: &[&str] = &["seconds", "minutes", "hours"]; |
| 138 | + |
| 139 | + let mut value = value.as_f64().unwrap(); |
| 140 | + let mut chosen_time = &TIMES[0]; |
| 141 | + |
| 142 | + for time in &TIMES[1..] { |
| 143 | + if value / 60.0 >= 1.0 { |
| 144 | + chosen_time = time; |
| 145 | + value /= 60.0; |
| 146 | + } else { |
| 147 | + break; |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + // TODO: This formatting section can be optimized, two string allocations aren't needed |
| 152 | + let mut value = format!("{:.1}", value); |
| 153 | + if value.ends_with(".0") { |
| 154 | + value.truncate(value.len() - 2); |
| 155 | + } |
| 156 | + |
| 157 | + format!("{} {}", value, chosen_time) |
| 158 | + }; |
| 159 | + |
| 160 | + Ok(Value::String(fmt)) |
| 161 | +} |
| 162 | + |
| 163 | +/// Print a tera value to stdout |
| 164 | +fn dbg(value: &Value, _args: &HashMap<String, Value>) -> TeraResult<Value> { |
| 165 | + println!("{:?}", value); |
| 166 | + |
| 167 | + Ok(value.clone()) |
| 168 | +} |
| 169 | + |
| 170 | +/// Dedent a string by removing all leading whitespace |
| 171 | +fn dedent(value: &Value, _args: &HashMap<String, Value>) -> TeraResult<Value> { |
| 172 | + let string = value.as_str().expect("dedent takes a string"); |
| 173 | + |
| 174 | + Ok(Value::String( |
| 175 | + string |
| 176 | + .lines() |
| 177 | + .map(|l| l.trim_start()) |
| 178 | + .collect::<Vec<&str>>() |
| 179 | + .join("\n"), |
| 180 | + )) |
| 181 | +} |
| 182 | + |
| 183 | +#[cfg(test)] |
| 184 | +mod tests { |
| 185 | + use super::*; |
| 186 | + |
| 187 | + #[test] |
| 188 | + fn test_templates_are_valid() { |
| 189 | + let tera = load_templates().unwrap(); |
| 190 | + tera.check_macro_files().unwrap(); |
| 191 | + } |
| 192 | +} |
0 commit comments