Skip to main content

webserver_base/webserver/
frontend.rs

1//! What it takes to serve HTML to humans.
2//!
3//! `WebServer::frontend` is the line between a site and a service. Everything a
4//! frontend *must* have is a field here, so omitting one is a compile error
5//! rather than a page that quietly ships without a share card. A server that
6//! never calls it — a sidecar, a JSON API — needs none of it and boots clean.
7
8use crate::analytics::{AnalyticsConfig, SENTRY_BROWSER_SDK_VERSION, SentryDsn};
9use crate::assets::CacheBuster;
10use crate::feed::{ATOM_PATH, Feed, FeedSet, FeedSite, JSON_PATH, RSS_PATH, build_feeds};
11use crate::sitemap::{SitemapSet, SitemapUrl, build_sitemaps};
12use handlebars::HelperDef;
13
14use crate::templates::{
15    AnalyticsPaths, BaseTemplateData, FeedLinks, FrontendRuntime, SentryBrowser,
16    SocialImageMetadata,
17};
18use crate::{Environment, TracesSampleRate, env};
19
20use super::error::WebServerError;
21use super::not_found::NotFound;
22use super::pages::Pages;
23
24/// Everything a frontend requires, plus what it may add.
25///
26/// The four required inputs are constructor arguments, so omitting one is a
27/// compile error; each has its own type, so none can be passed in another's
28/// place. The optional ones are `with_*` builders with a working default.
29pub struct FrontendParams<S = ()> {
30    /// What is true of every page on the site.
31    pub(super) base: BaseTemplateData,
32    /// The pages themselves, which become both routes and sitemap entries.
33    pub(super) pages: Pages<S>,
34    /// Which Plausible site this frontend reports to.
35    pub(super) analytics: AnalyticsConfig,
36    /// The browser Sentry DSN — separate from the server's, because Sentry
37    /// recommends a project per language and per deployable, and mixing Rust
38    /// panics with JavaScript exceptions in one stream helps nobody.
39    pub(super) sentry_browser_dsn: String,
40    /// The share of page loads that send a trace.
41    pub(super) browser_traces_sample_rate: TracesSampleRate,
42    /// The browser Sentry `release`; `None` sends none.
43    pub(super) browser_release: Option<String>,
44    /// The router-fallback 404's `{{app}}`.
45    pub(super) not_found: NotFound<S>,
46    /// The project's own Handlebars helpers.
47    pub(super) helpers: Vec<(String, Box<dyn HelperDef + Send + Sync + 'static>)>,
48}
49
50impl<S> FrontendParams<S>
51where
52    S: Clone + Send + Sync + 'static,
53{
54    /// A frontend from its four required inputs.
55    #[must_use]
56    pub fn new(
57        base: BaseTemplateData,
58        pages: Pages<S>,
59        analytics: AnalyticsConfig,
60        sentry_browser_dsn: impl Into<String>,
61    ) -> Self {
62        Self {
63            base,
64            pages,
65            analytics,
66            sentry_browser_dsn: sentry_browser_dsn.into(),
67            browser_traces_sample_rate: TracesSampleRate::BROWSER_DEFAULT,
68            browser_release: None,
69            not_found: NotFound::none(),
70            helpers: Vec::new(),
71        }
72    }
73
74    /// Reads the analytics script id and browser DSN from the environment.
75    /// Analytics is off when `WSB_ENVIRONMENT` is `local` or the id is unset
76    /// or blank.
77    ///
78    /// # Errors
79    ///
80    /// [`WebServerError::Env`] if `WSB_ENVIRONMENT` or the browser DSN is
81    /// unset, blank or invalid.
82    pub fn from_env(base: BaseTemplateData, pages: Pages<S>) -> Result<Self, WebServerError> {
83        Ok(Self::new(
84            base,
85            pages,
86            AnalyticsConfig::from_env().map_err(WebServerError::Env)?,
87            env::required(crate::analytics::ENV_SENTRY_BROWSER_DSN).map_err(WebServerError::Env)?,
88        ))
89    }
90
91    /// The share of page loads that send a trace (the page load's own spans
92    /// and web vitals). Defaults to [`TracesSampleRate::BROWSER_DEFAULT`];
93    /// [`TracesSampleRate::OFF`] serves the smaller errors-only bundle.
94    #[must_use]
95    pub const fn with_browser_traces_sample_rate(
96        mut self,
97        browser_traces_sample_rate: TracesSampleRate,
98    ) -> Self {
99        self.browser_traces_sample_rate = browser_traces_sample_rate;
100        self
101    }
102
103    /// The Sentry `release` the browser reports, so browser events group with
104    /// the server's. Pass the same string given to `bootstrap_with_release`.
105    /// Defaults to none: the init carries no `release`.
106    #[must_use]
107    pub fn with_browser_release(mut self, release: impl Into<String>) -> Self {
108        self.browser_release = Some(release.into());
109        self
110    }
111
112    /// What the router-fallback 404 shows as `{{app}}`. Defaults to
113    /// [`NotFound::none`].
114    #[must_use]
115    pub fn with_not_found(mut self, not_found: NotFound<S>) -> Self {
116        self.not_found = not_found;
117        self
118    }
119
120    /// Registers a Handlebars helper of the project's own, under `name`.
121    ///
122    /// A name the library or Handlebars already uses is a boot error, never a
123    /// silent override. A helper several projects reimplement belongs in the
124    /// library instead.
125    #[must_use]
126    pub fn with_helper(
127        mut self,
128        name: impl Into<String>,
129        helper: impl HelperDef + Send + Sync + 'static,
130    ) -> Self {
131        self.helpers.push((name.into(), Box::new(helper)));
132        self
133    }
134}
135
136/// The well-known documents a frontend serves, held in memory.
137///
138/// None of these is written to disk. They are generated (robots, sitemaps, the
139/// web manifest) or embedded (humans.txt), they are served at fixed never-cached
140/// routes where a content hash would mean nothing, and keeping them in memory is
141/// what lets a production image be read-only.
142#[derive(Debug, Clone)]
143pub struct WellKnown {
144    pub robots_txt: String,
145    pub humans_txt: String,
146    pub webmanifest: String,
147    pub sitemaps: SitemapSet,
148    /// The three feed documents, when the site declared a feed. Unlike the rest
149    /// of this struct these are *not* served uncached: a feed is the most-polled
150    /// document a site has, and stripping its validators would re-send every
151    /// byte on every poll.
152    pub feeds: Option<FeedSet>,
153}
154
155/// A frontend, assembled.
156pub struct Frontend<S> {
157    /// The browser bundle's tracing setting, which picks the bundle served.
158    pub browser_traces_sample_rate: TracesSampleRate,
159    pub pages: Pages<S>,
160    pub base: BaseTemplateData,
161    pub runtime: FrontendRuntime,
162    pub well_known: WellKnown,
163    pub analytics: AnalyticsConfig,
164    pub sentry_dsn: SentryDsn,
165    /// The router-fallback 404's `{{app}}`.
166    pub not_found: NotFound<S>,
167    /// Whether an SVG icon exists to link.
168    pub has_svg_icon: bool,
169}
170
171/// The bytes of Todd Everett Griffin's humans.txt, shared by every project that
172/// enables `preset` so it is written once and never drifts.
173#[cfg(feature = "preset")]
174const PRESET_HUMANS_TXT: &str = include_str!("../../assets/humans.txt");
175
176impl<S> Frontend<S>
177where
178    S: Clone + Send + Sync + 'static,
179{
180    /// Builds a frontend: derives the proxy paths, probes the social image,
181    /// and renders the well-known documents.
182    ///
183    /// # Errors
184    ///
185    /// [`WebServerError::SentryDsn`] if the browser DSN is malformed, or
186    /// [`WebServerError::Sitemap`] if the sitemaps cannot be built.
187    pub fn build(
188        params: FrontendParams<S>,
189        feed: Option<Feed>,
190        cache_buster: &CacheBuster,
191        environment: Environment,
192    ) -> Result<Self, WebServerError> {
193        let sentry_dsn: SentryDsn =
194            SentryDsn::parse(&params.sentry_browser_dsn).map_err(WebServerError::SentryDsn)?;
195
196        // Every asset a page will reference is proved to resolve before the
197        // server binds. Falling back to an un-hashed path would produce a link
198        // that 404s for the visitor and reports nothing to us.
199        let mut declared: Vec<String> = Vec::new();
200        declared.extend(params.base.style_sheets().iter().cloned());
201        declared.extend(params.base.scripts().iter().cloned());
202        declared.push(params.base.social_image().to_string());
203        declared.extend(params.pages.declared_assets());
204        crate::assets::validate_declared(cache_buster, &declared)?;
205
206        let icon_source: crate::assets::IconSource = crate::assets::validate_icons(cache_buster)?;
207
208        // Local runs never reach Plausible, whatever id was configured.
209        let analytics: AnalyticsConfig = params.analytics.clone().for_environment(environment);
210        log_analytics(&analytics, environment);
211
212        let paths: ProxyPaths = ProxyPaths::derive(
213            params.base.project(),
214            &sentry_bundle_key(params.browser_traces_sample_rate),
215        );
216        let social_image: SocialImageMetadata = probe_social_image(&params.base, cache_buster);
217
218        if !social_image.is_large_enough() {
219            // Boots, but every X share renders a thumbnail instead of the wide
220            // card the layout declares — exactly the kind of silent degradation
221            // that must reach Sentry, and `warn!` never does.
222            tracing::error!(
223                "the social image is {}x{}, below the 600x314 floor for a \
224                 `summary_large_image` card; shares will degrade to a thumbnail",
225                social_image.width.unwrap_or_default(),
226                social_image.height.unwrap_or_default(),
227            );
228        }
229
230        // Images are declared logically but served hashed; the sitemap has to
231        // name the URL that actually resolves.
232        let sitemap_urls: Vec<SitemapUrl> = params
233            .pages
234            .sitemap_urls()?
235            .into_iter()
236            .map(|url| url.map_images(|image| cache_buster.get_file(image)))
237            .collect();
238        let last_modified: Option<jiff::Timestamp> =
239            crate::assets::content_modified_in(cache_buster.root(), &["html", "static"]);
240        let sitemaps: SitemapSet =
241            build_sitemaps(params.base.base_url(), &sitemap_urls, last_modified)
242                .map_err(WebServerError::Sitemap)?;
243
244        let feed_title: Option<String> = feed.as_ref().map(|feed| feed.title.clone());
245        let feeds: Option<FeedSet> = match feed {
246            None => None,
247            Some(feed) => {
248                if !params.pages.paths().contains(&feed.page_url.as_str()) {
249                    return Err(WebServerError::Feed(
250                        crate::feed::FeedError::PageNotDeclared {
251                            page_url: feed.page_url.clone(),
252                        },
253                    ));
254                }
255                let site: FeedSite = feed_site(&params.base, cache_buster);
256                Some(
257                    build_feeds(&site, &feed, |path: &str| {
258                        cache_buster
259                            .is_hashed(path)
260                            .then(|| cache_buster.get_file(path))
261                    })
262                    .map_err(WebServerError::Feed)?,
263                )
264            }
265        };
266
267        let feed_links: Option<FeedLinks> = feed_title.map(|title| FeedLinks {
268            title,
269            rss: format!("{}{RSS_PATH}", params.base.base_url()),
270            atom: format!("{}{ATOM_PATH}", params.base.base_url()),
271            json: format!("{}{JSON_PATH}", params.base.base_url()),
272        });
273
274        let well_known: WellKnown = WellKnown {
275            robots_txt: robots_txt(params.base.base_url(), &sitemaps, feeds.is_some()),
276            humans_txt: humans_txt(&params.base),
277            webmanifest: webmanifest(&params.base),
278            sitemaps,
279            feeds,
280        };
281
282        let runtime: FrontendRuntime = FrontendRuntime {
283            theme_script: params.base.theme_script().source(),
284            social_image,
285            has_svg_icon: icon_source.is_vector(),
286            analytics: analytics.is_enabled().then(|| AnalyticsPaths {
287                script_path: paths.analytics_script.clone(),
288                event_path: paths.analytics_event.clone(),
289            }),
290            sentry_browser: sentry_browser(
291                &paths,
292                &sentry_dsn,
293                params.browser_traces_sample_rate,
294                environment,
295                params.browser_release.as_deref(),
296            ),
297            feed: feed_links,
298        };
299
300        Ok(Self {
301            pages: params.pages,
302            base: params.base,
303            runtime,
304            well_known,
305            analytics,
306            sentry_dsn,
307            browser_traces_sample_rate: params.browser_traces_sample_rate,
308            not_found: params.not_found,
309            has_svg_icon: icon_source.is_vector(),
310        })
311    }
312}
313
314fn log_analytics(analytics: &AnalyticsConfig, environment: Environment) {
315    if analytics.is_enabled() {
316        tracing::info!("analytics enabled");
317    } else if environment.is_local() {
318        tracing::info!("analytics disabled: WSB_ENVIRONMENT is local");
319    } else {
320        tracing::warn!("analytics disabled in production: WSB_ANALYTICS_ID is unset or empty");
321    }
322}
323
324/// Which browser bundle a Sentry script path serves, for [`ProxyPaths`].
325fn sentry_bundle_key(rate: TracesSampleRate) -> String {
326    let kind: &str = if rate.is_on() { "tracing" } else { "errors" };
327    format!("{SENTRY_BROWSER_SDK_VERSION}:{kind}")
328}
329
330/// What the layout needs to initialise browser Sentry.
331fn sentry_browser(
332    paths: &ProxyPaths,
333    dsn: &SentryDsn,
334    rate: TracesSampleRate,
335    environment: Environment,
336    release: Option<&str>,
337) -> SentryBrowser {
338    SentryBrowser {
339        script_path: paths.sentry_script.clone(),
340        dsn: dsn.as_str().to_string(),
341        traces_sample_rate: rate.is_on().then(|| rate.to_string()),
342        tunnel_path: paths.sentry_tunnel.clone(),
343        environment: environment.to_string(),
344        release_js: release.map(js_string),
345    }
346}
347
348/// `value` as a JavaScript string literal safe inside an inline `<script>`.
349///
350/// JSON escapes quotes and control characters but not `<`, so `</script>` in a
351/// release would end the script; `<` and the line separators are `\u`-escaped.
352fn js_string(value: &str) -> String {
353    serde_json::to_string(value)
354        .expect("a string serializes")
355        .replace('<', "\\u003c")
356        .replace('\u{2028}', "\\u2028")
357        .replace('\u{2029}', "\\u2029")
358}
359
360/// Where the first-party proxies live on this origin.
361///
362/// Derived from the project name, never configured. Plausible's guidance is to
363/// avoid their documented default paths because blocklists target them, and to
364/// avoid words like "analytics" or "stats". A per-project name also means no
365/// single filter rule can take out every site at once, which a shared
366/// library-wide constant would invite. The shape — `name-hash.js` — is what
367/// every bundler on the web already emits.
368#[derive(Debug, Clone, PartialEq, Eq)]
369struct ProxyPaths {
370    analytics_script: String,
371    analytics_event: String,
372    sentry_script: String,
373    sentry_tunnel: String,
374}
375
376impl ProxyPaths {
377    /// `sentry_bundle` names which browser bundle the script path serves
378    /// (version and kind). It is hashed into that path: the bundle is cached
379    /// for a year, so a path that outlived a version bump or a tracing change
380    /// would keep serving visitors the old one.
381    fn derive(project: &str, sentry_bundle: &str) -> Self {
382        let slug: String = slugify(project);
383        let analytics: String = short_hash(project);
384        // A second, unrelated hash, so the two scripts do not visibly belong to
385        // one another.
386        let sentry: String = short_hash(&format!("{project}:sentry"));
387        let sentry_script: String = short_hash(&format!("{project}:sentry:{sentry_bundle}"));
388
389        Self {
390            analytics_script: format!("/script/{slug}-{analytics}.js"),
391            analytics_event: format!("{}/{slug}-{analytics}", super::server::API_PREFIX),
392            sentry_script: format!("/script/{slug}-{sentry_script}.js"),
393            sentry_tunnel: format!("{}/{slug}-{sentry}", super::server::API_PREFIX),
394        }
395    }
396}
397
398/// `Boggledygook!` → `boggledygook`.
399fn slugify(project: &str) -> String {
400    let mut slug: String = String::with_capacity(project.len());
401    let mut previous_dash: bool = true;
402    for character in project.chars() {
403        if character.is_ascii_alphanumeric() {
404            slug.push(character.to_ascii_lowercase());
405            previous_dash = false;
406        } else if !previous_dash {
407            slug.push('-');
408            previous_dash = true;
409        }
410    }
411    String::from(slug.trim_matches('-'))
412}
413
414/// Eight hex characters: enough to be unguessable, short enough to look like
415/// ordinary bundler output.
416fn short_hash(input: &str) -> String {
417    format!("{:x}", md5::compute(input.as_bytes()))
418        .chars()
419        .take(8)
420        .collect()
421}
422
423/// Channel metadata for the feed, derived rather than configured a second time.
424///
425/// Everything here already exists on [`BaseTemplateData`] or in the generated
426/// icon set; asking a project to restate it would be one more pair of values
427/// free to drift apart.
428fn feed_site(base: &BaseTemplateData, cache_buster: &CacheBuster) -> FeedSite {
429    let absolute = |path: &str| format!("{}{path}", base.base_url());
430    let year: i32 = i32::from(
431        jiff::Timestamp::now()
432            .to_zoned_datetime(jiff::tz::TimeZone::UTC)
433            .year(),
434    );
435
436    FeedSite {
437        base_url: String::from(base.base_url()),
438        author: String::from(base.author()),
439        // RFC 5646 wants a hyphen where `og:locale` wants an underscore.
440        language: format!("{}-{}", base.language_code(), base.country_code()),
441        icon_url: cache_buster
442            .is_hashed("static/image/favicon/favicon-512.png")
443            .then(|| absolute("/icon-512.png")),
444        favicon_url: cache_buster
445            .is_hashed("static/image/favicon/favicon.ico")
446            .then(|| absolute("/favicon.ico")),
447        copyright: format!("© {}–{year} {}", base.copyright_start(), base.author()),
448    }
449}
450
451/// Resolves and measures the social card image on disk.
452fn probe_social_image(base: &BaseTemplateData, cache_buster: &CacheBuster) -> SocialImageMetadata {
453    crate::assets::probe_social_image(cache_buster.file(base.social_image()))
454}
455
456/// `robots.txt`, naming the sitemap index, then the feed, then every url set.
457///
458/// Order is deliberate: Google discards a robots.txt past 500 KiB and
459/// truncation is positional, so the lines that must survive go at the top.
460///
461/// Only Atom is listed, and only once. Google accepts an RSS 2.0 or Atom 1.0
462/// file as a sitemap and recommends submitting one *alongside* a full sitemap —
463/// the sitemap is the inventory, the feed is the recency signal. Atom wins
464/// because it has a real per-entry `<updated>`; RSS carries publication dates
465/// only, so a revised post looks untouched. Listing both would report the same
466/// URLs twice for nothing, and JSON Feed is not a supported sitemap format at
467/// all. The feed outranks the `sitemap-N.xml` lines for survival because those
468/// are already named by the index above them.
469fn robots_txt(base_url: &str, sitemaps: &SitemapSet, has_feed: bool) -> String {
470    /// Well under Google's 500 KiB ceiling, with room for the directives above.
471    const BUDGET: usize = 400 * 1024;
472
473    let mut paths: Vec<String> = sitemaps.paths();
474    if has_feed {
475        paths.insert(1, String::from(ATOM_PATH));
476    }
477
478    let mut robots: String = String::from("User-agent: *\nAllow: /\n\n");
479    let mut omitted: usize = 0;
480    for path in paths {
481        let line: String = format!("Sitemap: {base_url}{path}\n");
482        if robots.len() + line.len() > BUDGET {
483            omitted += 1;
484            continue;
485        }
486        robots.push_str(&line);
487    }
488
489    if omitted > 0 {
490        // Silent truncation is the failure mode this whole design avoids, so
491        // the generator must not commit it either.
492        tracing::error!(
493            "omitted {omitted} sitemap line(s) from robots.txt to stay under \
494             Google's 500 KiB limit; the index is still listed first"
495        );
496    }
497
498    robots
499}
500
501/// The site's humans.txt: the author's own, written once and inherited by every
502/// project that enables `preset`.
503#[cfg(feature = "preset")]
504fn humans_txt(_base: &BaseTemplateData) -> String {
505    String::from(PRESET_HUMANS_TXT)
506}
507
508/// A minimal humans.txt, so the layout's `rel="author"` link never 404s on a
509/// project that does not use the author's own.
510#[cfg(not(feature = "preset"))]
511fn humans_txt(base: &BaseTemplateData) -> String {
512    format!(
513        "/* TEAM */\n\nName: {}\nSite: {}\n",
514        base.author(),
515        base.base_url()
516    )
517}
518
519/// The web app manifest.
520///
521/// `minimal-ui` rather than `standalone`: an installed multi-page content site
522/// with no back button strands the reader. It still satisfies the installability
523/// bar, so nothing is given up.
524fn webmanifest(base: &BaseTemplateData) -> String {
525    const ICONS: [(&str, &str); 2] = [("/icon-192.png", "192x192"), ("/icon-512.png", "512x512")];
526
527    let icons: Vec<String> = ICONS
528        .iter()
529        .map(|(source, sizes)| {
530            format!(
531                "{{ \"src\": \"{source}\", \"sizes\": \"{sizes}\", \"type\": \"image/png\", \"purpose\": \"any maskable\" }}"
532            )
533        })
534        .collect();
535
536    let color: &str = base.theme_color().primary();
537
538    format!(
539        "{{\n  \"name\": {name:?},\n  \"short_name\": {name:?},\n  \"description\": {description:?},\n  \"start_url\": \"/\",\n  \"scope\": \"/\",\n  \"display\": \"minimal-ui\",\n  \"theme_color\": {color:?},\n  \"background_color\": {color:?},\n  \"icons\": [\n    {icons}\n  ]\n}}\n",
540        name = base.project(),
541        description = base.description(),
542        icons = icons.join(",\n    "),
543    )
544}
545
546#[cfg(test)]
547mod tests {
548    use super::{ProxyPaths, short_hash, slugify};
549
550    #[test]
551    fn a_project_name_becomes_a_lowercase_dashed_slug() {
552        assert_eq!(String::from("boggledygook"), slugify("Boggledygook"));
553        assert_eq!(String::from("eat-out"), slugify("Eat Out"));
554        assert_eq!(
555            String::from("template-web-server"),
556            slugify("Template Web Server")
557        );
558        assert_eq!(
559            String::from("palms-small-engine"),
560            slugify("Palms  Small!Engine")
561        );
562    }
563
564    #[test]
565    fn the_proxy_paths_look_like_ordinary_bundler_output() {
566        let paths: ProxyPaths = ProxyPaths::derive("Boggledygook", "1:errors");
567
568        assert!(paths.analytics_script.starts_with("/script/boggledygook-"));
569        assert!(
570            std::path::Path::new(&paths.analytics_script)
571                .extension()
572                .is_some_and(|extension| extension.eq_ignore_ascii_case("js"))
573        );
574        assert!(paths.analytics_event.starts_with("/api/v1/boggledygook-"));
575
576        // None of Plausible's forbidden words appear anywhere.
577        for path in [&paths.analytics_script, &paths.analytics_event] {
578            for forbidden in ["plausible", "analytics", "tracking", "stats"] {
579                assert!(!path.contains(forbidden), "`{path}` contains `{forbidden}`");
580            }
581        }
582    }
583
584    #[test]
585    fn the_two_proxies_do_not_share_a_hash() {
586        let paths: ProxyPaths = ProxyPaths::derive("Boggledygook", "1:errors");
587
588        assert_ne!(paths.analytics_script, paths.sentry_script);
589        assert_ne!(paths.analytics_event, paths.sentry_tunnel);
590    }
591
592    #[test]
593    fn a_new_bundle_version_or_kind_changes_the_script_path_and_not_the_tunnel() {
594        let old: ProxyPaths = ProxyPaths::derive("Boggledygook", "1:errors");
595
596        for changed in ["2:errors", "1:tracing"] {
597            let new: ProxyPaths = ProxyPaths::derive("Boggledygook", changed);
598            assert_ne!(old.sentry_script, new.sentry_script, "{changed}");
599            assert_eq!(old.sentry_tunnel, new.sentry_tunnel, "{changed}");
600            assert_eq!(old.analytics_script, new.analytics_script, "{changed}");
601        }
602    }
603
604    #[test]
605    fn two_projects_never_share_a_path_so_one_filter_rule_cannot_block_both() {
606        let first: ProxyPaths = ProxyPaths::derive("Boggledygook", "1:errors");
607        let second: ProxyPaths = ProxyPaths::derive("Eat Out", "1:errors");
608
609        assert_ne!(first.analytics_script, second.analytics_script);
610    }
611
612    #[test]
613    fn the_derived_hash_is_stable_across_runs() {
614        let expected: String = short_hash("Boggledygook");
615        let actual: String = short_hash("Boggledygook");
616        assert_eq!(expected, actual);
617
618        let expected: usize = 8;
619        let actual: usize = short_hash("Boggledygook").len();
620        assert_eq!(expected, actual);
621    }
622}