webserver-base 0.2.5

A Rust library which contains shared logic for all of my webserver projects.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//! The Handlebars registry.

use std::fs;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;

use chrono::{DateTime, Utc};
use handlebars::{Handlebars, HelperDef, handlebars_helper};
use serde::Serialize;
use serde_json::Value;
use tracing::instrument;

use super::error::TemplateError;
use super::page::PageTemplateData;
use super::robots;

/// The subdirectories scanned, in order. A template's name is its file stem, so
/// `pages/home.hbs` is `{{> home}}`; stems must be unique across all three.
pub const TEMPLATE_DIRECTORIES: [&str; 3] = ["layouts", "pages", "partials"];

/// Where a project's templates live. Not configurable: every project uses this
/// layout, and a knob that can only correctly hold one value is not a knob.
pub const TEMPLATE_ROOT: &str = "html";

/// The name of the embedded layout every page extends.
pub const BASE_TEMPLATE_NAME: &str = "base";

/// The 404 template every frontend must provide.
///
/// Its declaration is not a per-project decision — every site wants the same
/// page name, the same `/404` URL and the same `noindex, follow` — so the
/// library makes it. What it *looks* like, and what data it shows, are the
/// project's.
pub const NOT_FOUND_TEMPLATE_NAME: &str = "404";

/// The 404's page declaration, shared by the router fallback and
/// `WebServerState::not_found` so the two cannot drift.
static NOT_FOUND_PAGE: LazyLock<PageTemplateData> = LazyLock::new(|| {
    PageTemplateData::new(NOT_FOUND_TEMPLATE_NAME, "404", "/404")
        .with_robots(robots::NOINDEX_FOLLOW)
});

/// The 404's page declaration. Not a per-project decision; see
/// [`NOT_FOUND_TEMPLATE_NAME`].
#[must_use]
pub fn not_found_page() -> &'static PageTemplateData {
    &NOT_FOUND_PAGE
}

/// The layout itself, compiled into the crate.
///
/// Shipping it here rather than copying it into each project is the whole
/// point: the `<head>` is pure function — spec conformance, Open Graph, JSON-LD
/// — and solving it once means no project can drift into a stale or subtly
/// wrong version of it.
const BASE_TEMPLATE: &str = include_str!("../../assets/html/layouts/base.hbs");

/// Every helper name a project may not register: Handlebars' own built-ins,
/// then this library's. Kept by hand because Handlebars offers no lookup.
const RESERVED_HELPERS: [&str; 21] = [
    "if",
    "unless",
    "each",
    "with",
    "lookup",
    "raw",
    "log",
    "eq",
    "ne",
    "gt",
    "gte",
    "lt",
    "lte",
    "and",
    "or",
    "not",
    "len",
    "join",
    "pretty_date",
    "has_key",
    "is_active",
];

// Comma-joins a list of strings, for `<meta name="keywords">`.
handlebars_helper!(join: |list: Vec<String>| list.join(","));

// Renders a UTC date as "January 15, 1990".
handlebars_helper!(pretty_date: |date: DateTime<Utc>| date.format("%B %e, %Y").to_string());

// True when a nav link's `href` should be highlighted on the page at
// `page_url`: `/` only on the home page, any other href on itself and on every
// page beneath it. Segment-aware, so `/stats` is not active on `/statsheet`.
handlebars_helper!(is_active: |href: str, page_url: str| {
    let href: &str = href.trim_end_matches('/');
    if href.is_empty() {
        page_url == "/"
    } else {
        page_url
            .strip_prefix(href)
            .is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
    }
});

// True when an object has the given key.
handlebars_helper!(has_key: |object: Value, key: str| {
    object.as_object().is_some_and(|object| object.contains_key(key))
});

/// Every Handlebars template the server can render.
#[derive(Clone)]
pub struct TemplateRegistry<'a> {
    handlebars: Handlebars<'a>,
}

impl<'a> TemplateRegistry<'a> {
    /// A registry holding only the embedded `base` layout, plus the built-in
    /// helpers and strict mode. Touches no files.
    ///
    /// # Panics
    ///
    /// Never in practice: the only template registered is compiled into the
    /// binary, so a failure here means this crate shipped a layout that does
    /// not parse, which its own tests would have caught.
    #[must_use]
    pub fn empty() -> Self {
        let mut handlebars: Handlebars<'a> = Handlebars::new();

        handlebars.register_helper("join", Box::new(join));
        handlebars.register_helper("pretty_date", Box::new(pretty_date));
        handlebars.register_helper("has_key", Box::new(has_key));
        handlebars.register_helper("is_active", Box::new(is_active));

        // A missing field becomes an error rather than an empty string: a blank
        // `<title>` is a bug that ships, a failed render is one that gets fixed.
        handlebars.set_strict_mode(true);

        handlebars
            .register_template_string(BASE_TEMPLATE_NAME, BASE_TEMPLATE)
            .expect("the embedded base layout compiles");

        Self { handlebars }
    }

    /// Loads every template under `root`'s `layouts`, `pages` and `partials`,
    /// on top of the embedded `base` layout.
    ///
    /// # Errors
    ///
    /// [`TemplateError::ReadDirectory`] if `root` or a subdirectory is
    /// unreadable, [`TemplateError::ReservedName`] if a file would shadow the
    /// embedded layout, [`TemplateError::NoPages`] if no page templates exist,
    /// or [`TemplateError::Compile`] if a template does not compile.
    #[instrument(skip_all)]
    pub fn from_dir(root: impl AsRef<Path>) -> Result<Self, TemplateError> {
        let root: &Path = root.as_ref();
        let mut registry: Self = Self::empty();
        let mut pages: usize = 0;

        if !root.is_dir() {
            return Err(TemplateError::ReadDirectory {
                path: root.to_path_buf(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "a frontend needs a template directory",
                ),
            });
        }

        for directory in TEMPLATE_DIRECTORIES {
            let path: PathBuf = root.join(directory);
            if !path.is_dir() {
                // A site with no partials is a site, not a misconfiguration.
                continue;
            }

            let entries: fs::ReadDir =
                fs::read_dir(&path).map_err(|source| TemplateError::ReadDirectory {
                    path: path.clone(),
                    source,
                })?;

            for entry in entries {
                let entry: fs::DirEntry = entry.map_err(|source| TemplateError::ReadDirectory {
                    path: path.clone(),
                    source,
                })?;
                let file: PathBuf = entry.path();
                if file.is_dir() {
                    continue;
                }
                let Some(name) = file.file_stem().and_then(|stem| stem.to_str()) else {
                    continue;
                };

                // Silently letting a project's file win would disable the
                // embedded `<head>` and nobody would notice until the SEO tags
                // went missing in production.
                if name == BASE_TEMPLATE_NAME {
                    return Err(TemplateError::ReservedName {
                        name: BASE_TEMPLATE_NAME,
                        path: file,
                    });
                }

                if directory == "pages" {
                    pages += 1;
                }

                registry
                    .handlebars
                    .register_template_file(name, &file)
                    .map_err(|source| TemplateError::Compile {
                        name: name.to_string(),
                        source: Box::new(source),
                    })?;
            }
        }

        if pages == 0 {
            return Err(TemplateError::NoPages {
                path: root.join("pages"),
            });
        }

        if !registry.has_template(NOT_FOUND_TEMPLATE_NAME) {
            return Err(TemplateError::MissingNotFoundPage {
                path: root.join("pages").join("404.hbs"),
            });
        }

        Ok(registry)
    }

    /// Registers a project's own helper, refusing any name already taken.
    ///
    /// # Errors
    ///
    /// [`TemplateError::ReservedHelper`] if the name belongs to a library or
    /// Handlebars built-in helper. Letting a project's win would silently
    /// change what every template using the built-in renders, the embedded
    /// layout included.
    pub fn register_project_helper(
        &mut self,
        name: &str,
        helper: Box<dyn HelperDef + Send + Sync + 'a>,
    ) -> Result<(), TemplateError> {
        if RESERVED_HELPERS.contains(&name) {
            return Err(TemplateError::ReservedHelper {
                name: name.to_string(),
            });
        }
        self.handlebars.register_helper(name, helper);
        Ok(())
    }

    /// Registers an extra helper, for a project that needs one.
    pub fn register_helper(&mut self, name: &str, helper: Box<dyn HelperDef + Send + Sync + 'a>) {
        self.handlebars.register_helper(name, helper);
    }

    /// Whether a template with this name is registered.
    #[must_use]
    pub fn has_template(&self, name: &str) -> bool {
        self.handlebars.has_template(name)
    }

    /// Renders `name` against `data`.
    ///
    /// # Errors
    ///
    /// [`TemplateError::Render`], most often because strict mode caught a field
    /// the template asked for and the data did not supply.
    #[instrument(skip_all)]
    pub fn render<T>(&self, name: &str, data: &T) -> Result<String, TemplateError>
    where
        T: Serialize,
    {
        self.handlebars
            .render(name, data)
            .map_err(|source| TemplateError::Render {
                name: name.to_string(),
                source: Box::new(source),
            })
    }
}

impl std::fmt::Debug for TemplateRegistry<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut names: Vec<&String> = self.handlebars.get_templates().keys().collect();
        names.sort();
        f.debug_struct("TemplateRegistry")
            .field("templates", &names)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::path::PathBuf;

    use serde_json::json;

    use super::TemplateRegistry;
    use crate::templates::error::TemplateError;

    #[test]
    fn a_registry_holds_the_embedded_layout_before_it_touches_any_file() {
        let registry: TemplateRegistry<'_> = TemplateRegistry::empty();

        let expected: bool = true;
        let actual: bool = registry.has_template(super::BASE_TEMPLATE_NAME);
        assert_eq!(expected, actual);
    }

    #[test]
    fn a_registry_holding_only_the_layout_has_no_pages() {
        let registry: TemplateRegistry<'_> = TemplateRegistry::empty();

        let expected: bool = false;
        let actual: bool = registry.has_template("home");
        assert_eq!(expected, actual);
    }

    #[test]
    fn strict_mode_turns_a_missing_field_into_an_error() {
        let mut registry: TemplateRegistry<'_> = TemplateRegistry::empty();
        registry
            .handlebars
            .register_template_string("greet", "hello {{name}}")
            .expect("valid template");

        let error: TemplateError = registry
            .render("greet", &json!({ "other": "field" }))
            .expect_err("strict mode rejects a missing field");
        assert!(matches!(error, TemplateError::Render { ref name, .. } if name == "greet"));
    }

    #[test]
    fn the_join_helper_comma_delimits_for_the_keywords_tag() {
        let mut registry: TemplateRegistry<'_> = TemplateRegistry::empty();
        registry
            .handlebars
            .register_template_string("keywords", "{{join words}}")
            .expect("valid template");

        let expected: String = String::from("boggle,word-game,scrabble");
        let actual: String = registry
            .render(
                "keywords",
                &json!({ "words": ["boggle", "word-game", "scrabble"] }),
            )
            .expect("renders");
        assert_eq!(expected, actual);
    }

    #[test]
    fn the_has_key_helper_distinguishes_present_from_absent() {
        let mut registry: TemplateRegistry<'_> = TemplateRegistry::empty();
        registry
            .handlebars
            .register_template_string("check", "{{#if (has_key map 'a')}}yes{{else}}no{{/if}}")
            .expect("valid template");

        let expected_present: String = String::from("yes");
        let actual_present: String = registry
            .render("check", &json!({ "map": { "a": 1 } }))
            .expect("renders");
        assert_eq!(expected_present, actual_present);

        let expected_absent: String = String::from("no");
        let actual_absent: String = registry
            .render("check", &json!({ "map": { "b": 1 } }))
            .expect("renders");
        assert_eq!(expected_absent, actual_absent);
    }

    #[test]
    fn is_active_matches_home_exactly_and_every_other_link_by_path_segment() {
        let mut registry: TemplateRegistry<'_> = TemplateRegistry::empty();
        registry
            .handlebars
            .register_template_string("nav", "{{#if (is_active href page)}}on{{else}}off{{/if}}")
            .expect("valid template");
        let active = |href: &str, page: &str| -> String {
            registry
                .render("nav", &json!({ "href": href, "page": page }))
                .expect("renders")
        };

        // Home would otherwise be active everywhere, since every path starts
        // with `/`.
        assert_eq!("on", active("/", "/"));
        assert_eq!("off", active("/", "/stats"));

        assert_eq!("on", active("/stats", "/stats"));
        assert_eq!("on", active("/stats", "/stats/chapter-one"));
        assert_eq!("on", active("/stats/", "/stats/chapter-one"));
        assert_eq!("off", active("/stats", "/statsheet"));
        assert_eq!("off", active("/stats", "/"));
    }

    #[test]
    fn a_project_helper_may_not_take_a_built_in_name() {
        let mut registry: TemplateRegistry<'_> = TemplateRegistry::empty();

        for name in ["eq", "each", "is_active"] {
            let error: TemplateError = registry
                .register_project_helper(name, Box::new(super::join))
                .expect_err("a built-in name is reserved");
            assert!(
                matches!(error, TemplateError::ReservedHelper { name: ref taken } if taken == name),
                "{error}"
            );
        }

        registry
            .register_project_helper("money", Box::new(super::join))
            .expect("an unused name is free");
    }

    #[test]
    fn a_frontend_without_a_template_root_cannot_start() {
        let error: TemplateError = TemplateRegistry::from_dir("/tmp/wsb-nonexistent-template-root")
            .expect_err("a frontend needs templates");
        assert!(matches!(error, TemplateError::ReadDirectory { .. }));
    }

    #[test]
    fn a_project_layout_named_base_is_refused_rather_than_silently_winning() {
        let root: PathBuf = PathBuf::from("/tmp/wsb-reserved-name/html");
        fs::create_dir_all(root.join("layouts")).expect("temp dirs");
        fs::create_dir_all(root.join("pages")).expect("temp dirs");
        fs::write(root.join("pages/home.hbs"), "hi").expect("temp file");
        fs::write(root.join("pages/404.hbs"), "nope").expect("temp file");
        fs::write(root.join("layouts/base.hbs"), "<html></html>").expect("temp file");

        let error: TemplateError =
            TemplateRegistry::from_dir(&root).expect_err("`base` is reserved");
        assert!(matches!(error, TemplateError::ReservedName { name, .. } if name == "base"));

        fs::remove_dir_all("/tmp/wsb-reserved-name").ok();
    }

    #[test]
    fn a_project_may_add_any_other_layout() {
        let root: PathBuf = PathBuf::from("/tmp/wsb-other-layout/html");
        fs::create_dir_all(root.join("layouts")).expect("temp dirs");
        fs::create_dir_all(root.join("pages")).expect("temp dirs");
        fs::write(root.join("pages/home.hbs"), "hi").expect("temp file");
        fs::write(root.join("pages/404.hbs"), "nope").expect("temp file");
        fs::write(root.join("layouts/chapter.hbs"), "shell").expect("temp file");

        let registry: TemplateRegistry<'_> =
            TemplateRegistry::from_dir(&root).expect("a non-reserved layout is fine");

        let expected: bool = true;
        let actual: bool = registry.has_template("chapter");
        assert_eq!(expected, actual);

        fs::remove_dir_all("/tmp/wsb-other-layout").ok();
    }

    #[test]
    fn a_frontend_with_no_pages_cannot_start() {
        let root: PathBuf = PathBuf::from("/tmp/wsb-no-pages/html");
        fs::create_dir_all(root.join("partials")).expect("temp dirs");
        fs::write(root.join("partials/footer.hbs"), "<footer></footer>").expect("temp file");

        let error: TemplateError =
            TemplateRegistry::from_dir(&root).expect_err("a frontend must serve a page");
        assert!(matches!(error, TemplateError::NoPages { .. }));

        fs::remove_dir_all("/tmp/wsb-no-pages").ok();
    }

    #[test]
    fn a_frontend_without_a_404_template_cannot_start() {
        let root: PathBuf = PathBuf::from("/tmp/wsb-no-404/html");
        fs::create_dir_all(root.join("pages")).expect("temp dirs");
        fs::write(root.join("pages/home.hbs"), "hi").expect("temp file");

        let error: TemplateError =
            TemplateRegistry::from_dir(&root).expect_err("every frontend serves a 404");
        assert!(matches!(error, TemplateError::MissingNotFoundPage { .. }));

        fs::remove_dir_all("/tmp/wsb-no-404").ok();
    }
}