webserver-base
Shared logic for Todd Everett Griffin's web servers, as feature-gated kits. Part of
toddstack; the TypeScript half is
@todd/webserver-base.
This library is deliberately opinionated. Most of what it does is not
configurable, because most of it has exactly one correct answer — the <head>,
the sitemap shape, where the icons come from. A knob that can only ever hold one
value is not flexibility, it is surface area. Projects supply the things that
genuinely differ (their name, their pages, their design) and inherit the rest.
This document is the reference. Every feature the library offers is described here; if something is missing from this file, it is a documentation bug. Read the code for low-level detail — it is always the source of truth.
Install
[]
= { = "0.2", = ["pages", "observability", "preset"] }
Nothing is enabled by default.
Every crate whose types appear in this library's API is re-exported from its
root — webserver_base::{axum, axum_extra, chrono, handlebars, serde_json, tokio, tracing, reqwest, sentry}, each behind the feature that uses it — so a project builds
against the same version the library does, and never adds one just to call it.
Three keep a direct dependency when their macros are used, because those macros name the crate by its absolute path, which a re-export cannot satisfy:
| crate | keep it direct when the project uses | expands to |
|---|---|---|
serde |
#[derive(Serialize, Deserialize)] |
::serde::… |
tracing |
#[instrument] |
::tracing::… |
tokio |
#[tokio::main] / #[tokio::test] (a dev-dependency suffices for tests) |
::tokio::… |
Everything else — including tracing::info! and friends, which resolve through
$crate — works through the re-export.
| feature | what it gives you |
|---|---|
templates |
the Handlebars registry, the embedded base layout, the template-data types |
analytics |
first-party proxies for Plausible and the Sentry browser SDK |
sitemap |
sitemap index and url-set generation |
feed |
RSS 2.0, Atom 1.0 and JSON Feed for a site's content stream |
observability |
Sentry + tracing, initialised in the one order that works |
telegram |
outbound Telegram Bot API notifier |
webserver |
the server builder, shared state, bootstrap, the static-asset pipeline |
pages |
page declarations producing routes and sitemap entries — implies webserver, templates, sitemap, analytics, feed |
preset |
Todd Everett Griffin's identity defaults, including the shared humans.txt |
full |
all of the above |
The Rust library
A complete server
use ;
use ;
use ;
That is the whole file. There is no Environment::from_env, no Observability
wiring, and no 404 routing, because those are identical in every project —
bootstrap and frontend
own them.
WebServer
A server needs only a host, a port and an [Environment]. Everything else is
opt-in, so a sidecar serving one health check is a valid server.
| method | effect |
|---|---|
new / with_state |
explicit host, port and environment; with_state carries app state reachable as state.app() |
from_env / from_env_with_state |
reads WSB_ENVIRONMENT (required), WSB_HOST (defaults 127.0.0.1 locally, 0.0.0.0 in production) and WSB_PORT (defaults 8080) |
body_limit |
request body cap, default 256 KiB — raise it for uploads |
without_compression |
turns response compression off; see Response compression |
root_dir |
where html/, static/ and cache-buster.json are read from, default the working directory — see Testing |
nest / merge / nest_service |
your own routes |
frontend |
declares this server a website; see below |
run |
binds, serves, drains, and runs the state's AppShutdown cleanup |
into_router |
everything run does before binding: the finished Router, for oneshot tests or embedding |
Always on, no method to enable them: response compression (opt out with without_compression), GET /api/v1/health, the /api/v1 prefix
itself, and the graceful-drain window.
On the shutdown signal the server stops accepting connections and returns as
soon as the last in-flight request finishes — with nothing in flight, that is
immediate. DEFAULT_DRAIN_TIMEOUT is the ceiling on that wait, not a pause: it
exists because a WebSocket never closes on its own, and reaching it logs a
warning and drops what remained.
AppShutdown — draining your own state
Anything your state holds that would be lost at exit — a queued notifier, a
spooled writer, a connection pool — has to be drained while the runtime is still
alive. run therefore requires S: AppShutdown:
It is a bound, not a hook you remember to attach. Adding state without an implementation is a compile error, which is the point: forgetting cleanup is otherwise invisible until the deploy where the notification you needed never arrives. A server with no state gets a blanket no-op and writes nothing.
The library owns the sequencing, so there is no ordering to get wrong and no result to hold across it. Cleanup starts the moment the signal arrives, concurrently with the connection drain and under the same ceiling — so the process leaves in the longer of the two, never their sum, and a slow drain cannot eat the cleanup's budget. That matters: the drain ceiling is already 10 seconds, which is also Docker's default kill grace, so anything running after the drain would be killed rather than run.
Overrunning the ceiling is ordinary cancellation — the future is dropped at its
last .await — and it is reported at error! by the server, not by your hook.
Your hook cannot report it, because being cancelled is precisely what stops it
running. That is also why on_shutdown takes no deadline argument: there is
only ever one ceiling, and it belongs to the library.
It must be idempotent. It runs once per server holding the state, so a
binary running several servers off one Arc<AppState> calls it once per server.
The library cannot deduplicate that — each WebServer builds its own
WebServerState, and only your application knows what they share. Guard
anything that would misbehave twice behind a OnceCell of your own.
Static assets are presence-detected: if a static/ directory exists under
root_dir the server serves /static and loads the manifest; if not, it does
neither. There is no .assets() call.
Response compression
On by default, for every route including the ones you merge in. The client's
Accept-Encoding picks zstd, brotli or gzip; Vary: Accept-Encoding is added to
every body it considers for compression, whether or not this client accepted an
encoding (not to 304s, tiny bodies, ranges, already-encoded or exempt streams); Content-Length and Accept-Ranges is dropped from compressed
bodies; an ETag is left as the handler set it (the weak/strong pair is not
worth breaking If-None-Match over).
Not compressed: bodies under 32 bytes, images (SVG excepted), gRPC, anything
already carrying Content-Encoding, 206 range responses, text/event-stream
and application/x-ndjson / application/jsonl, so those streams keep
flushing each event or line. WebSocket upgrades pass through untouched.
A route that streams any other content type (chunked text, say) would sit in
the encoder until it fills: give it an exempt Content-Type, or turn compression
off with without_compression().
Every algorithm runs at level 3. Measured on one core, per response:
| payload | gzip 3 | brotli 3 | zstd 3 | brotli 11 (library default) |
|---|---|---|---|---|
| 10 KB JSON | 28% / 42 us | 25% / 51 us | 25% / 23 us | 22% / 8 ms |
| 100 KB JSON | 25% / 0.48 ms | 23% / 0.52 ms | 23% / 0.15 ms | 19% / 84 ms |
| 24 KB HTML | 6.7% / 42 us | 4.3% / 0.11 ms | 5.0% / 21 us | 3.7% / 23 ms |
| 73 KB minified JS | 37% / 0.52 ms | 37% / 0.57 ms | 37% / 0.15 ms | 31% / 51 ms |
(size as a share of the original / CPU time.) Higher levels buy a few points of size for several times the CPU; the library default for brotli costs tens of milliseconds per response, which is why the level is pinned.
Turn it off with without_compression() when a proxy in front already
compresses and origin CPU matters more than origin bandwidth. Hashed /static
files are compressed per request, not precompressed at build time: with a CDN
in front they are fetched once per edge, so the saved CPU is not worth a build
step.
Testing with into_router
into_router(shutdown) returns exactly the Router that run serves — pages,
the 404, the well-known documents, the cache policy, tracing and the body limit
— without binding a socket. Drive it with tower::ServiceExt::oneshot:
const BIN: &str = concat!;
let server: WebServer = new.root_dir;
let router: Router = web_server.into_router?;
let response: Response = router.oneshot.await?;
- Boot validation still runs, so
Okmeansrunwould have started. A frontend test therefore needs the built site: pointroot_dirat what your asset build produces (bin/, above, from a workspace member) and build the assets beforecargo test. There is no lenient test mode — it would pass exactly the misconfiguration the boot check exists to catch. root_diris per server, not per process.cargo testruns from the crate's own directory, and parallel tests can each point at their own tree; changing the working directory could do neither.- Put the builder in your library, not
main. A binary-only crate's tests cannot reachmain, so they would test a copy of the builder chain. Exposefn web_server(server: WebServer, settings: Settings) -> WebServer:mainpassesWebServer::from_env()?and a test passes one withroot_dir. Keep environment reads inmain, so a test buildsSettingsas plain data instead of mutating process-wide variables.template_web_serveris the worked example. - A handler needs no fixtures. A server without
frontendboots from any root, soWebServer::with_state(..).merge(routes).into_router(..)hands the handler a realWebServerState. There is deliberately no public constructor for one: the only state a test can see is oneruncould have built. - Not covered: the drain window and
AppShutdown::on_shutdownnever run.shutdown.trigger()reaches only handlers listening onstate.shutdown(). - A
.layer()added to the returned router is outside what the library guarantees.
frontend — the line between a site and a service
WebServer::frontend says "this server returns HTML to humans." Everything a
website needs then follows automatically, and every required input is an
argument to FrontendParams::new(base, pages, analytics, sentry_browser_dsn), so
forgetting one is a compile error rather than a page that silently ships without
a share card.
| argument | why it is required |
|---|---|
base |
site identity: name, description, origin, social image, theme, copyright |
pages |
the routes, which are also the sitemap |
analytics |
the Plausible site; blank or AnalyticsConfig::disabled() turns it off, and it is always off locally |
sentry_browser_dsn |
browser errors, separate from the server's DSN |
Calling it gives you, with no further code: the embedded base layout, the
generated icon set, site.webmanifest, robots.txt, the sitemap index and its
url sets, first-party analytics, the Sentry browser tunnel, and the pre-paint
theme script.
FrontendParams::from_env(base, pages) reads the analytics id and browser DSN
for you. Two optional builders follow either constructor:
| builder | default | for |
|---|---|---|
with_not_found(NotFound::with(…)) |
NotFound::none() |
the fallback 404's {{app}} |
with_helper(name, helper) |
none | a Handlebars helper of the project's own |
The 404
How a 404 behaves is not a per-project decision; how it looks, and what it
shows, is. The library guarantees every frontend a 404 that renders
html/pages/404.hbs at the requested URL with a real 404 status, noindex, follow, and never a redirect — the soft 404 that Search Console penalises.
Its data works like any other page's: {{site}} is always there, and {{app}}
is yours to supply, two ways.
// Unmatched URLs: computed per request, from the URI. Keep it cheap — bots
// probe for 404s. Unserializable data is reported and rendered as `null`.
from_env?
.with_not_found
// A matched route whose resource is missing: the same page, your own data.
async
state.not_found never runs the fallback hook. A failed render is a 500, and on
a server with no frontend it is a bare 404. Every 404 is served never-cached,
so one seen mid-deploy cannot outlive it. A miss under /static is always a
bare, never-cached 404: nothing displays an <img>'s error body.
What a frontend must ship
Each of these is a boot error, because a site missing one is broken in a way no test catches:
| requirement | why |
|---|---|
html/pages/*.hbs, at least one |
a frontend with no pages is not a frontend |
html/pages/404.hbs |
every frontend serves a 404 |
| one icon source — see Icons | the whole set derives from it |
| every declared asset present in the manifest | see below |
Boot-time asset validation
Every asset a page will reference — site-wide and per-page stylesheets and scripts, the social image, and all four generated icons — is proved to resolve before the server binds, and every miss is reported at once.
Resolving a missing asset to its un-hashed path would produce a link that 404s for the visitor and reports nothing to you: invisible from the inside. Failing at boot rather than per-request is the safer half of that trade — a failed request means someone sees a broken page, a failed boot means the deploy never cuts over and the previous container keeps serving.
Absolute URLs are exempt: a CDN stylesheet will never be in the manifest, and that is the one legitimate reason for a path to be absent. Assets a handler looks up dynamically at request time cannot be enumerated at boot and remain yours to get right.
Templates
Templates live in html/{layouts,pages,partials} — a fixed convention, not a
setting. A template's name is its file stem, so pages/home.hbs is {{> home}};
stems must be unique across all three directories.
The base layout is embedded
base ships inside this crate. No project owns a copy, and a project file
that would shadow it is a boot error naming the offender. You may add any other
layout; you may not add this one.
That is the whole point. The <head> is pure function — spec conformance, Open
Graph, JSON-LD, icons, resource hints — so it is solved once here and inherited
everywhere, rather than copy-pasted eight times and left to drift.
A page supplies one block and extends it:
{{#*inline "body"}}
<main class="page-home">
<h1>{{project}}</h1>
</main>
{{> footer}}
{{/inline}}
{{> base}}
The block is named body, not main, because it is everything inside
<body> — your header, your <main>, your footer. The layout contributes no
chrome at all: <body> is bare, and what a page looks like is entirely yours.
What the layout emits
<meta charset> first, then viewport, title and description — the highest-value
crawler signals as high in the document as they go. Then robots and
canonical; color-scheme and one theme-color per scheme; the full Open Graph
block with an absolute, content-hashed og:image plus its real width, height
and MIME type; four X/Twitter tags (the rest provably fall back to Open Graph);
the icon set and manifest link; JSON-LD; the pre-paint theme script; auto-derived
preconnect hints; the Plausible and Sentry loaders; then stylesheets. Scripts go
at the end of <body>.
Nothing in <head> blocks parsing except the stylesheets and the tiny inline
theme script, which must run before first paint. Both third-party loaders are
defer: Sentry's sentryOnLoad hook is defined inline just before its loader,
and deferred scripts run in document order, so Sentry is initialised before any of
the page's module scripts run. The inline scripts sit above the stylesheets on
purpose: an inline script after a stylesheet waits for that stylesheet to load.
Template data
Three types, split by lifetime.
BaseTemplateData — per-server, what is true of every page. Built once, held
in server state. BaseTemplateDataParams names every field so two cannot be
transposed. with_*, replace_* and extend_* methods override afterwards.
with_site(data) adds the project's own site-wide data — a nav tree, a phone
number, opening hours — as {{site.…}} on every page, the 404 included.
Declare it once here rather than re-passing it in each page's {{app}}, and a
shared partial can read it on any page. It is serialized at boot; data that
cannot be is a boot panic, never a per-request one.
A leading slash on social_image is stripped on the way in, so it keys into the
cache-buster map exactly like the stylesheet and script paths beside it.
PageTemplateData — per-render, what this page is. new(template, page_name, page_url) plus optional overrides:
| method | effect |
|---|---|
with_description / with_social_image / with_social_image_alt |
override the site default for this page |
with_robots |
see the robots module for named directives |
with_jsonld |
attach a schema.org document; merged with the library's own |
with_article |
mark the page an article — this is what sets og:type and emits the article:* tags |
replace_style_sheets / extend_style_sheets |
and the scripts equivalents |
TemplateData — what Handlebars actually sees, assembled from both plus your
own data. Your data is namespaced under {{app.…}}; pass () for none.
Computed for you: display_name ("{page_name} | {project}", the only way to
influence <title>), canonical_url, locale, social_image_url,
copyright_end (per render, so a long-running server does not keep claiming last
year), preconnect, color_scheme and theme_colors.
Strict mode is on: a field a template asks for and the data does not supply is a
render error, not an empty string. A blank <title> is a bug that ships; a
failed render is one that gets fixed.
Helpers available in any template: join (comma-joins a list), pretty_date
(January 15, 1990), has_key (whether a map holds a key), and is_active
(whether a nav link is the current page's section):
{{#each site.nav}}
<a href="{{href}}"{{#if (is_active href ../page_url)}} aria-current="page"{{/if}}>{{label}}</a>
{{/each}}
/ is active only on /; any other href on itself and every page beneath it,
by path segment — /stats is active on /stats/one, not on /statsheet.
A project adds its own with FrontendParams::with_helper, defined through the
re-exported webserver_base::handlebars::handlebars_helper!. A name Handlebars
or the library already uses is a boot error, never a silent override. A helper
that several projects reimplement belongs in the library.
ThemeColor
Browser-chrome colour and supported schemes are one type, because they have to
agree — color-scheme: light dark with a single theme colour gives a dark page a
light address bar.
light // color-scheme: light
dark // color-scheme: dark
light_dark // color-scheme: light dark, two media-scoped tags
Use the page background per scheme, so the chrome reads as continuous with the page rather than as an accent stripe above it.
The theme script
BaseTemplateData carries a theme_fallback beside its colours, and the library
builds the script from it — there is nothing to construct or pass.
It is inline, blocking and pre-paint, so a page never flashes the wrong theme. Three states, and the middle one matters:
- the reader chose a theme → stamp
data-themeon<html>; - the reader chose nothing but the OS states a preference → stamp nothing, so your media queries stay live and follow the OS mid-session;
- neither states anything → stamp
theme_fallback.
The storage key is always theme. What [data-theme="dark"] means is entirely
your CSS; this library owns only the handshake.
SiteEntity
Who or what the site is, for the JSON-LD entity node. SiteEntity::person(..) or
SiteEntity::organization(..) — a band is not a person, and search engines
reconcile this claim against the wider web. The goddtriffin preset defaults to
Person; a project that is a business or a band overrides it with
with_site_entity.
Todd's social profiles
GODDTRIFFIN_SOCIALS (preset) is the one list of Todd's social profiles, in
display order: each Social has a label, an href and an icon (SVG path data
for a 0 0 24 24 view box, drawn in currentColor). GODDTRIFFIN_SEE_ALSO, the
preset's og:see_also, is derived from it (the site, then these URLs), so a
project's icon row and its metadata cannot drift. Pass it to templates as site
data and render each entry as <svg viewBox="0 0 24 24"><path d="{{icon}}"/></svg>.
Adding, dropping or reordering a network is an edit here only.
JSON-LD
On the home page only — Google requires WebSite markup at the domain root —
the library emits a @graph containing WebSite and your SiteEntity, with
sameAs populated from see_also and logo from the social image.
A page's own with_jsonld is merged, not replaced. Nodes match by @id
(falling back to @type); a matching node has its properties shallow-merged over
the default, so naming one property does not discard the rest, and a node
matching nothing is appended. Documents are hex-escaped, so a </script> inside
a string value cannot break out of the block.
Pages
Pages declares routes and the sitemap together, so they cannot disagree.
new
.static_page
.dynamic_page
.extend_images
.with_last_modified
.unlisted // route it, keep it out of the sitemap
There is no 404 page to declare — the library routes it; see The 404.
extend_images, with_last_modified and unlisted apply to the page declared
immediately before them.
Trailing slashes
Every page also answers its other trailing-slash form with a 308 to the
path exactly as declared, keeping the query and the method: /blog/?page=2
goes to /blog?page=2, and /docs goes to /docs/ if that is what you
declared. The sitemap and <link rel="canonical"> only ever name the declared
form.
- The redirect matches the route pattern, before any layer on the page's method
router. A guard still answers at the canonical URL. A handler that returns
state.not_foundgets the redirect first and then the 404, so the two forms never disagree. /and wildcard paths (/files/{*path}) get no alias: one has no other form, and the other already matches it.- Declaring two pages that differ only by a trailing slash, or the same path
twice, fails the boot with
WebServerError::DuplicatePagePath. - Your own
.merge/.nestroutes are ordinary axum and are not aliased. Opt one in withwebserver_base::axum_extra::routing::RouterExt::route_with_tsr.
Sitemaps
/sitemap.xml is always a <sitemapindex>, naming one or more
/sitemap-N.xml url sets — on a three-page site and a three-million-page one
alike. robots.txt and any Search Console submission therefore point at one URL
forever; a site that outgrows the protocol's 50,000-URL limit simply gains
another url set inside the index, and nothing outside the server changes.
Chunking respects both the URL count and a serialized-byte budget, because
sitemap-rs enforces only the former and image-heavy entries can pass that check
while still exceeding 50 MB.
<changefreq> and <priority> are not emitted: Google ignores both. <lastmod>
is the newest modification time across html/, static/ and the binary —
stable across restarts, moving only when something that determines the output
actually changed. If that value is implausible (an epoch-normalised build, a
skewed clock) the tag is omitted and an error! is logged, because Google
uses lastmod only when it is consistently and verifiably accurate and one bad
pattern discredits the whole file.
Sitemaps are held in memory and served from there. Nothing is written to disk.
Feeds
A site may declare one feed, served in all three formats at fixed paths:
/rss.xml, /atom.xml and /feed.json. WebServer::feed is omittable — a
site with no stream serves no feed documents and emits no autodiscovery links.
Calling it without frontend fails the boot rather than silently serving
nothing.
from_env?
.frontend
.feed
.run
Entries are passed in, not derived: a blog is a dynamic_page_group, and a
dynamic page builds its template data per request, so there is nothing to read
at boot. Supply them in any order and in any number — the library sorts
newest-first and keeps 20. Deduplicate however suits your data; the library
reports a repeated path but will not silently drop one.
FeedEntry is a named-field struct rather than a builder so that shipping a
teaser feed is something you type (content_html: None) rather than something
you forget.
Post content is rewritten, not copied. A reader renders your entry on
feedly.com, so every relative src and href is cache-busted and then made
absolute, and a bare #fragment is resolved against the post rather than
against the reader's own page. Rewriting is confined to real elements, so a post
that merely shows markup in a code fence is left alone. srcset fails the
boot instead of being half-rewritten.
Everything else is derived from what the site already declares — author, language, icons, copyright, self and alternate links — so there is nothing to restate and nothing to drift.
Caching
Feeds are the most-polled document a site serves, so unlike the other generated
documents they are not served no-store. Each carries
Cache-Control: public, max-age=1800, a strong ETag computed at boot, and
Last-Modified; a conditional request gets a bodiless 304.
That only works because the documents are byte-stable: <lastBuildDate> and
<updated> come from the newest entry rather than the clock, and entries
sharing an instant break the tie on path, so a HashMap upstream cannot move
the bytes. A redeploy that changed no post re-sends nothing.
Discovery
Three rel="alternate" links go in every page's <head>, not only the page the
feed mirrors, so a reader handed any URL on the site finds the stream. They are
ordered RSS, Atom, JSON: a reader that takes the first rather than offering a
choice is far more likely to be RSS-only than Atom-only.
robots.txt gains exactly one line — Sitemap: {base_url}/atom.xml. Google
accepts an RSS or Atom file as a sitemap and recommends one alongside a full
sitemap: the sitemap is the inventory, the feed is the recency signal. Atom is
the one listed because it has a genuine per-entry <updated>, so a revised post
looks revised; RSS carries publication dates only. JSON Feed is not a supported
sitemap format.
What fails the boot, and what only shouts
Refused outright: an entry with no title, summary or rooted path; srcset in
content; a page_url that is not a declared page; a declared image absent
from the manifest.
Logged at error! and served anyway: a feed with no entries, a repeated path,
a future published, a modified earlier than its published, an image inside
content that the manifest does not know, and any character stripped because XML
1.0 cannot represent it.
Static assets
Hashing happens at build time, never at startup.
gen_css → static/stylesheet/main.css
gen_static_assets → derive the icon set from favicon.svg; hash every non-script
asset; write cache-buster.json and the TypeScript module
gen_js → the bundler inlines that module
gen_static_scripts → hash the built JavaScript
server boot → read the manifest. No hashing, no writes.
Two phases, because the JavaScript contents depend on the manifest while the JavaScript files can only be hashed once they exist. Scripts never need their own hash — the layout reads that from the manifest.
Both commands are subcommands of your own server binary, so no project needs a shim binary or a line of glue:
They exit before the runtime or error monitoring start. They do still read
WSB_ENVIRONMENT, because main resolves it before calling in — set it to
local in your build stage.
Everything under static/ is hashed, including the icons, because /static/*
is served immutable-for-a-year and every byte in it must therefore be
content-addressed. Well-known root routes (/favicon.ico, /robots.txt, …)
serve the same bytes never-cached, where the URL cannot change. A miss under
/static is a plain 404 and is never cached: a hashed URL requested a moment
before its file is deployed must not stay a 404 for a year.
cache-buster.json and static/script/generated/cache-buster.ts are build
outputs — gitignore both. Add this to every consuming project:
cache-buster.json
static/script/generated/
Icons
A project authors exactly one source, and everything else is generated:
static/image/favicon/favicon.svg— preferred. You also get<link rel="icon" type="image/svg+xml">and, if the SVG carries its ownprefers-color-schemerules, a dark-mode-adaptive tab icon.static/image/favicon/favicon-512.png— exactly 512×512, for art that cannot be vectorised. A photograph is the obvious case: autotracing a face yields either a posterised caricature or a multi-megabyte pile of paths. The size is in the filename so the requirement is hard to miss. No SVG link is emitted in this case, because linking a file that does not exist is worse than not linking one.
favicon.ico (32), apple-touch-icon.png (180), icon-192.png and
icon-512.png derive from whichever you provide. Every derived size is a
downscale from 512, which is faithful; upscaling never is, so a source smaller
than 512 is refused.
The icon directory is a closed set. It may contain only the source and the four derived files:
static/image/favicon/
favicon.svg | favicon-512.png <- exactly one of these
favicon.ico <- generated
apple-touch-icon.png <- generated
icon-192.png <- generated
icon-512.png <- generated
Boot errors: neither source present; both present (two sources drift the
moment one is updated); a PNG that is not exactly 512×512; a derived icon that
is absent or the wrong size; or any other file in the directory. A stale
favicon-16.png from a previous design is invisible until the wrong picture
turns up in a browser tab, so it fails the boot instead.
A file already present is left alone, so a hand-tuned 32×32 .ico — the one
size where a naive downscale of a detailed mark really does look muddy — still
wins.
An SVG must not rely on system fonts; convert text to paths.
Analytics and error monitoring
Both vendors' origins are on blocklists, and a blocked request is a visitor you never counted or an error you never saw. This library serves both from your own origin, which Plausible themselves recommend — they put the cost of not doing it at 5–25% of visitors.
Routes are derived from the project name, never configured: Plausible advises
against their documented default paths (blocklists target them) and against
words like "analytics" or "stats". A per-project name also means no single filter
rule can take out every one of your sites at once. The shape — name-hash.js —
is what every bundler already emits.
GET /script/{project}-{hash}.js → the Plausible script
POST /api/v1/{project}-{hash} → events, with the real visitor IP forwarded
GET /script/{project}-{hash2}.js → the Sentry browser loader
POST /api/v1/{project}-{hash2} → Sentry envelopes
Both are byte relays. Nothing is parsed or re-reported — which matters most for Sentry: a server that interpreted a client error and re-raised it through its own SDK would file a browser problem as a server one, with the wrong stack. The tunnel's destination comes from the configured DSN, not the envelope, so it cannot be used as an open relay.
The two scripts are cached in memory (ScriptRelay), so the vendor's CDN is
never on a page's critical path. After the first fetch every request is answered
from memory, with the vendor's Content-Type, Cache-Control and ETag
(If-None-Match gets a 304). A copy older than five minutes is refreshed in
the background; a failed refresh keeps serving the last good copy, and only
reaches Sentry if the copy is a day old. A cold cache fetches inline.
Script fetches are retried; events and envelopes are not. A script fetch is a
read, so a connect error, a timeout, a 429 or a 5xx is retried: three
attempts, two seconds each, full-jitter exponential backoff (200 ms doubling, at
most 1 s), a Retry-After of up to 2 s honoured (a longer one is not waited
for), and no retry started after 4 s. Events and envelopes are writes, sent once:
a retried write that had in fact landed is a duplicate pageview or error.
X-Forwarded-For carries the true client IP (resolved through the usual proxy
headers); without it Plausible's bot filter rejects proxied events outright.
Server-side and browser-side Sentry are complementary, not alternatives: the Rust SDK catches panics and handler errors, the browser SDK catches JavaScript exceptions. Use two Sentry projects — Sentry recommends one per language and per deployable, and it isolates rate limits.
| variable | what it is |
|---|---|
WSB_ANALYTICS_ID |
the Plausible script id, e.g. pa-1qi0TQ… (Site Settings → Site Installation). Optional: unset or empty turns analytics off |
WSB_SENTRY_SERVER_DSN |
the Rust server's DSN |
WSB_SENTRY_BROWSER_DSN |
the browser's DSN — required for a frontend |
The two DSNs are required in every environment, local included. A DSN exercised only in production is a DSN nobody has proved works; point local runs at development projects.
Analytics is off when WSB_ENVIRONMENT=local, or when WSB_ANALYTICS_ID is
unset or empty. Then no script tag is rendered, the script and event routes
are not mounted (they 404), nothing is fetched from or forwarded to Plausible,
and startup logs analytics disabled once. A local run ignores an id even if
one is set, so a laptop can never pour into production's numbers. Production with
an id behaves as before. Sentry is unaffected: it stays on in every environment.
In code, AnalyticsConfig::disabled() and AnalyticsConfig::is_enabled() expose
the same state, and Frontend applies the local rule whatever config it is given.
Upgrading to 0.3.5: response compression is now on by default for every
route, with no code change. Responses a client accepts compressed gain
Content-Encoding and Vary: Accept-Encoding and lose Content-Length. Opt out
with WebServer::without_compression() (see Response compression).
A route streaming anything but SSE or NDJSON must set an exempt type or opt out.
Upgrading to 0.3.4: AnalyticsConfig::from_env() (and so
FrontendParams::from_env) now also reads WSB_ENVIRONMENT and fails when it is
unset, blank or invalid. An id is trimmed, and a blank one disables analytics.
AnalyticsConfig::script_id() and upstream_script_url() keep their types but
return an empty string when analytics is disabled; prefer
script_id_if_enabled() and upstream_script_url_if_enabled(), which return
Option. In production with no id, startup logs a warn.
⚠️ Plausible's script disables itself on localhost, so a local pageview will
not register no matter what you configure. To exercise it end to end, add your
development domain as its own Plausible site and map it to 127.0.0.1 in
/etc/hosts.
Observability
bootstrap owns this. It resolves WSB_ENVIRONMENT, builds observability from
WSB_SENTRY_SERVER_DSN, and initialises it on the main thread before the
runtime — so the Sentry hub reaches the runtime's workers — then drops the guard
after the drain so errors raised during shutdown are still flushed. No project
writes any of that.
bootstrap! also owns the build-tool subcommands, checking them before it
touches the environment at all, so gen-static-assets needs no configuration.
It is a macro, not a function, and that is load-bearing. Sentry attributes
issues to a release, and the release has to name your application. Resolving it
inside this library — which is what sentry::release_name!() would do — makes
every project report webserver-base@x.y.z, so Sentry cannot tell one site's
deploys from another's and regression detection stops working. The macro expands
CARGO_PKG_NAME and CARGO_PKG_VERSION at your call site, so the release is
correct with nothing to configure.
Logging
Format follows the environment, because a human reads one and a machine reads the other:
local INFO request{method=GET path=/robots.txt version=HTTP/1.1 request_id=…}:
finished processing request latency=0 ms status=200
production {"timestamp":"…","level":"INFO","message":"finished processing request",
"span":{"name":"request","method":"GET","path":"/robots.txt","request_id":"…"},
"status":200,"latency":"0 ms","target":"tower_http::trace::on_response"}
Production JSON is flatten_evented with the current span attached, so method,
path, request_id, status and latency are queryable fields rather than a
string to grep. The span logs the path, never the query string: query strings
carry one-time codes and tokens (OAuth callbacks), and every line of the request
would repeat them.
ANSI colour is off there too — a log driver stores escape codes verbatim and
nothing downstream strips them.
Note the request span is created at INFO. tower-http defaults it to DEBUG,
which under an INFO filter means the span never exists and every request logs a
status and a latency with no way to tell which route it was.
One line at boot names the running build — the one thing no other log can tell you when an incident starts:
INFO starting release=my-project@1.2.3 environment=production log_filter=info
RUST_LOG is honoured and stays unprefixed, being an ecosystem convention;
with_log_filter sets the fallback.
Cache tiers are named at boot
Every served resource is logged once at startup with the tier it falls under and the URL it is actually reachable at:
INFO immutable 1y /static/stylesheet/main.css -> /static/stylesheet/main.a1b2c3d4.css
INFO uncached /robots.txt
INFO cached 30m /atom.xml (etag "4f2a9c1e")
Deliberately at boot rather than per request. A request for an immutable asset arriving at the origin is indistinguishable from a first-time visitor, a bot, a hard refresh or an evicted entry — only one of those is a fault, so a cache-miss log could not tell you anything. What is decidable, and decided exactly once, is whether each tier was wired up at all: if the immutable lines are missing, caching is broken, and you can see it in the first screen of a deploy's logs. To check the tier is being honoured beyond your origin, read the response headers at the edge rather than inferring it from volume here.
Severity policy. sentry-tracing maps error! to a Sentry event and
warn! to a mere breadcrumb, so a warning with no subsequent error is never
seen. Therefore: a boot failure for misconfiguration that makes the site wrong;
error! for "boots, but a feature is silently degraded"; warn!/info! only
for things nobody needs to act on.
Request ids and metrics
On for every server; nothing to configure.
Request ids. Each request gets an X-Request-ID: the one nginx sent (the id
of its access-log line), or a fresh UUID when none came or it isn't 1 to 64
characters of [A-Za-z0-9_-]. It is put on the request span, so every log line
of the request carries request_id, and echoed on the response. Search one id
to see the nginx line and everything the app logged for it.
Metrics. In production, /metrics (Prometheus text format) is served on
METRICS_PORT (9000), a second listener that is never published: each
container has its own network, so the fixed port never collides, and only a
scraper on the host can reach it. Not served locally, where two projects running
at once would collide. Every server exports:
| metric | labels |
|---|---|
http_requests_total |
method, route, status |
http_request_duration_seconds (histogram, 5 ms to 10 s) |
method, route |
http_requests_in_flight |
|
build_info (always 1) |
release (my-project@1.2.3), webserver_base |
route is the route pattern (/blog/{slug}), never the raw path, and every
unmatched path shares unmatched, so a crawler cannot grow the series count.
Unusual methods share other for the same reason.
Your own metrics use the re-exported metrics crate
and appear on the same endpoint:
use counter;
counter!.increment;
Label values must come from a small fixed set (a game, a mode), never from user
input or ids: each distinct value is a new series. A /metrics port that cannot
be bound is reported to Sentry and the site keeps serving.
Telegram
telegram is an outbound Bot API notifier, send-only on purpose: no polling, no
webhooks, no update handling, because no consuming project receives anything. It
replaces the hand-rolled sendMessage calls that had been copied between
projects, each missing a different subset of the hard parts.
let settings: TelegramSettings = builder.build?;
let telegram: ReqwestTelegram = new?;
telegram.send;
| type | what it is for |
|---|---|
Telegram |
the trait to depend on — send, and send_text for the unformatted case |
ReqwestTelegram |
the real implementation; new(settings, None) builds its own client. Adds flush and queued, which are inherent to it, not on the trait |
MockTelegram |
the test double: sent, sent_to, texts, len, clear |
Message / MessageBuilder |
Message::text for the plain case, Message::builder for formatting |
Style, Entity, EntityKind |
the formatting primitives the builder emits |
Media, FileSource |
photo, video and document sends, with a caption |
ChatId |
Id(i64) or Username(String) |
TelegramSettings |
builder(token), then queue capacity, chunk cap, timeouts |
SendOptions |
per-send overrides: disable_notification, protect_content, disable_link_preview, message_thread_id, reply_to_message_id |
TelegramError, BotToken |
errors, and the token type that redacts itself |
send returns immediately. It queues; a background task chunks, paces,
retries and delivers. That is why it takes &self and cannot fail — the
failure surfaces in the logs, not the call site.
Formatting emits entities, not parse_mode markup. Telegram's own docs
describe entities as what a Markdown or HTML parser is converted into, so
nothing is lost by skipping that step — and because no markup is ever embedded
in the text, interpolated values never need escaping. This is the whole
reason the builder exists: a filename containing * or _ cannot corrupt a
message or inject formatting.
Chunking counts UTF-16 code units, because that is what Telegram's 4096
(text) and 1024 (caption) limits count. Entities are clamped and rebased onto
each piece. A message that would exceed the configured chunk cap is truncated
and the truncation is logged at error!, because a silently shortened
notification is worse than a loud one.
flush(timeout) waits for the queue to drain so the last notifications —
usually the ones that matter — are not lost. It returns false and logs at
error! if the queue did not empty in time.
Call it from AppShutdown, not by
hand. Hold the notifier in your app state and flush it there: send returns
immediately, so whatever is still queued when the process exits is gone, and
that typically includes the notification about whatever caused the exit. Doing
it in the trait is what makes forgetting a compile error rather than a silence
you discover in production.
Bot tokens redact themselves structurally in Debug, errors and logs, so a
token cannot reach Sentry by being interpolated into a message.
Environment
Every variable this crate reads is prefixed WSB_ so it cannot collide with
yours. Environment::from_env reads WSB_ENVIRONMENT (local or production).
The env module offers required, optional and parse_or for your own.
Conventions a consuming project inherits
html/
pages/ at least one .hbs, and 404.hbs — both required
partials/ your chrome
layouts/ optional; `base` is reserved
static/
image/favicon/favicon.svg (or favicon-512.png at 512x512) — the rest is generated
image/ script/ stylesheet/ scss/
cache-buster.json build output — gitignored
static/script/generated/ build output — gitignored
Where that tree lives is root_dir, defaulting to the working directory — the
build pipeline itself always runs in the working directory.
Fixed and not configurable: the html/ and static/ directory names, the
/api/v1 prefix, the theme storage key, the sitemap route shape, the derived
proxy paths, <meta charset="utf-8">, the viewport string, and the entire
<head>.