webserver-base 0.4.2

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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
# webserver-base

[![Crates.io](https://img.shields.io/crates/v/webserver-base)](https://crates.io/crates/webserver-base)
[![JSR](https://jsr.io/badges/@todd/webserver-base)](https://jsr.io/@todd/webserver-base)

Shared logic for Todd Everett Griffin's web servers, as feature-gated **kits**. Part of
[toddstack](https://github.com/goddtriffin/toddstack); the TypeScript half is
[`@todd/webserver-base`](https://github.com/goddtriffin/toddstack/tree/main/typescript).

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

```toml
[dependencies]
webserver-base = { version = "0.2", features = ["pages", "observability", "preset"] }
```

Nothing is enabled by default.

Every date and time in the API is a [`jiff::Timestamp`](https://docs.rs/jiff) (an instant, always UTC); the
crate replaced `chrono`, which is unmaintained (RUSTSEC-2026-0543).

Every crate whose types appear in this library's API is re-exported from its
root — `webserver_base::{axum, axum_extra, handlebars, jiff, 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

```rust
use webserver_base::templates::{
    BaseTemplateData, Fallback, GoddtriffinParams, PageTemplateData, ThemeColor,
};
use webserver_base::webserver::{FrontendParams, Pages, WebServer, WebServerError};
use webserver_base::{bootstrap, env};

fn main() -> Result<(), WebServerError> {
    bootstrap!(|shutdown| async move {
        WebServer::from_env()?
            .frontend(FrontendParams::from_env(
                BaseTemplateData::goddtriffin(GoddtriffinParams {
                    project: env::required("MY_PROJECT")?,
                    description: env::required("MY_DESCRIPTION")?,
                    base_url: env::required("MY_BASE_URL")?,
                    social_image: String::from("static/image/social/card.webp"),
                    theme_color: ThemeColor::light_dark("#fafafa", "#121212"),
                    theme_fallback: Fallback::Dark,
                    copyright_start: String::from("1998"),
                    style_sheets: vec![String::from("static/stylesheet/main.css")],
                    scripts: vec![String::from("static/script/main.js")],
                }),
                Pages::new().static_page(PageTemplateData::new("home", "Home", "/"), ()),
            )?)
            .run(shutdown)
            .await
    })
}
```

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`](#bootstrap) and [`frontend`](#frontend--the-line-between-a-site-and-a-service)
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]#response-compression |
| `root_dir` | where `html/`, `static/` and `cache-buster.json` are read from, default the working directory — see [Testing]#testing-with-into_router |
| `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`:

```rust
impl AppShutdown for AppState {
    async fn on_shutdown(&self) {
        self.telegram.flush(Duration::from_secs(5)).await;
    }
}
```

**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.

#### Precompressed `/static` files

For a few large, hot files, level 3 leaves bytes on the table that a build-time
level 11 recovers (measured on a 334 KB wasm and a 1.15 MB word list: 67 KB and
75 KB smaller than level 3, about 0.7 s off a throttled cold load; level 11 per
request costs ~1.3 s a file, so it must happen at build time).

`/static` serves a sibling beside the file when the client accepts its encoding:
`<file>.br`, `<file>.zst` or `<file>.gz` next to `<file>` (preference br, zstd,
gzip). It is sent as-is with the original's `Content-Type`, the matching
`Content-Encoding` and `Vary: Accept-Encoding`, and the compression layer
leaves it alone (it never re-encodes a response that has `Content-Encoding`).
No sibling, or a client that does not accept it, falls back to the file plus
runtime compression. `HEAD` works the same.

Producing the siblings is **your build's job, and it must run after
`gen-static-assets`**: siblings are named after the *hashed* file
(`main.<hash>.wasm.br`) and are not in `cache-buster.json`. A `.br` made before
hashing would itself be hashed and renamed, and no longer sit beside its file.
The library does not generate them (that would pull a brotli encoder into every
consumer); for example `brotli -f -q 11 static/data/words.<hash>.bdw`. Only
precompress what is large and compressible: images and other already-compressed
formats gain nothing.

### 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`:

```rust
const BIN: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../bin");

let server: WebServer = WebServer::new("127.0.0.1", 0, Environment::Local).root_dir(BIN);
let router: Router = web_server(server, settings).into_router(Shutdown::manual())?;
let response: Response = router.oneshot(Request::get("/").body(Body::empty())?).await?;
```

- **Boot validation still runs**, so `Ok` means `run` would have started. A
  frontend test therefore needs the *built* site: point `root_dir` at what your
  asset build produces (`bin/`, above, from a workspace member) and build the
  assets before `cargo test`. There is no lenient test mode — it would pass
  exactly the misconfiguration the boot check exists to catch.
- **`root_dir` is per server, not per process.** `cargo test` runs 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 reach `main`, so they would test a copy of the builder chain. Expose
  `fn web_server(server: WebServer, settings: Settings) -> WebServer`: `main`
  passes `WebServer::from_env()?` and a test passes one with `root_dir`. Keep
  environment reads in `main`, so a test builds `Settings` as plain data instead
  of mutating process-wide variables. `template_web_server` is the worked
  example.
- **A handler needs no fixtures.** A server without `frontend` boots from any
  root, so `WebServer::with_state(..).merge(routes).into_router(..)` hands the
  handler a real `WebServerState`. There is deliberately no public constructor
  for one: the only state a test can see is one `run` could have built.
- **Not covered:** the drain window and `AppShutdown::on_shutdown` never run.
  `shutdown.trigger()` reaches only handlers listening on `state.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 |

Optional: `.with_browser_traces_sample_rate(rate)` (see
[Tracing](#tracing)), `.with_not_found(..)`, `.with_helper(..)`,
`.with_browser_release(release)` (the Sentry `release` in the browser init, JSON-escaped; pass the string given to
`bootstrap_with_release` so browser and server events share a release; omitted, the init has no `release`).

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.

```rust
// Unmatched URLs: computed per request, from the URI. Keep it cheap — bots
// probe for 404s. Unserializable data is reported and rendered as `null`.
FrontendParams::from_env(base, pages)?
    .with_not_found(NotFound::with(|state: WebServerState<App>, uri: Uri| async move {
        DidYouMean { closest: state.app().posts.closest(uri.path()) }
    }))

// A matched route whose resource is missing: the same page, your own data.
async fn post(State(state): Ctx, Path(slug): Path<String>) -> Response {
    let Some(post) = state.app().posts.get(&slug) else {
        return state.not_found(MissingPost { slug });
    };
    // …
}
```

`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]#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:

```handlebars
{{#*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 scripts; 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 scripts are
`defer`: Sentry's `init` sits in an inline `<script type="module">` right after
its bundle, and deferred scripts and inline modules run in document order, so
Sentry is initialised before any of the page's own 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):

```handlebars
{{#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.

```rust
ThemeColor::light("#fafafa")                  // color-scheme: light
ThemeColor::dark("#121212")                   // color-scheme: dark
ThemeColor::light_dark("#fafafa", "#121212")  // 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:

1. the reader chose a theme → stamp `data-theme` on `<html>`;
2. the reader chose nothing but the OS states a preference → stamp **nothing**,
   so your media queries stay live and follow the OS mid-session;
3. 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.

```rust
Pages::new()
    .static_page(PageTemplateData::new("home", "Home", "/"), ())
    .dynamic_page("/blog/{slug}", handler)
    .extend_images(["/static/image/social/card.webp"])
    .with_last_modified(post.updated_at)
    .unlisted()                                   // route it, keep it out of the sitemap
```

There is no 404 page to declare — the library routes it; see
[The 404](#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_found` gets 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`/`.nest` routes are ordinary axum and are not aliased. Opt
  one in with `webserver_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.

```rust
WebServer::from_env()?
    .frontend(params)
    .feed(Feed {
        title: String::from("Blog | Todd Everett Griffin"),   // what a reader lists you as
        description: String::from("Writing on Rust and WebGPU."),
        page_url: String::from("/blog"),                      // must be a declared page
        entries: posts.iter().map(|post| FeedEntry {
            path: format!("/blog/{}", post.slug),             // also the permanent id
            title: post.title.clone(),
            summary: post.description.clone(),
            content_html: Some(post.content.clone()),         // `None` ships a teaser
            published: post.published,
            modified: post.updated,
            tags: post.tags.clone(),
            image: Some(post.card.clone()),
        }).collect(),
    })
    .run(shutdown)
```

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:

```sh
my-server gen-static-assets
my-server gen-static-scripts
my-server                      # serve
```

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:

```gitignore
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 own
  `prefers-color-scheme` rules, 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 bundle (pinned)
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.6:** Sentry tracing is now configured by this library, not by
each Sentry project's dashboard toggle, and it is **on by default**: the browser
traces 20% of page loads and the server 0.1% of dynamic requests (both
placeholders; see [Tracing](#tracing)). Nothing has to change to compile, but
spans now count against your Sentry quota. To keep tracing off for a site, pass
`TracesSampleRate::OFF` for each side. The browser no longer uses Sentry's
per-project Loader Script (whose bundle the dashboard picked); it serves a
pinned bundle from your own origin, and `SentryDsn::upstream_script_url` and
`SENTRY_CDN_HOST` are gone (`SentryDsn::upstream_bundle_url` and
`SENTRY_BROWSER_CDN_HOST` replace them). Errors thrown before the bundle runs
(before first paint) are no longer buffered. If you wrote your own
`sentryOnLoad` or init, remove it: the layout initialises Sentry. An upstream 5xx
on the analytics or Sentry proxy is relayed to the browser unchanged but now logs
at `warn`, not `error`, so it no longer files a Sentry event.

**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](#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`.

## Tracing

Sentry tracing is set per project, in code, for the browser and the server
separately. A rate runs from `0.0` (off: nothing loaded, started or sent) to
`1.0`, and is a `TracesSampleRate`, which refuses anything else.

```rust
// browser: a share of page loads
FrontendParams::from_env(base, pages)?
    .with_browser_traces_sample_rate(TracesSampleRate::new(0.1).expect("0 to 1"))
// server: a share of dynamic requests
bootstrap!(
    |observability| observability.with_traces_sample_rate(TracesSampleRate::new(0.05).expect("0 to 1")),
    |shutdown| async move { /* ... */ }
)
```

Without these a site gets `DEFAULT_BROWSER_TRACES_SAMPLE_RATE` (0.2) and
`DEFAULT_SERVER_TRACES_SAMPLE_RATE` (0.01), placeholders until real traffic sets
them. Budget as traffic × rate × spans per sample: measured on the template
site, a sampled page load is about 14 spans (a fixed ~9 plus one per resource it
loads) and a sampled request 3 (the request, the cache middleware, the render).

**Browser.** The Sentry project's dashboard toggle no longer matters. Its Loader
Script serves whichever bundle the toggle names, and with tracing off that is an
errors-only bundle where `browserTracingIntegration()` does nothing but warn; it
also fetches that bundle from Sentry's origin, past your proxy. So the site
proxies a **pinned bundle** (`SENTRY_BROWSER_SDK_VERSION`, bumped in one place)
from its own origin: errors-only at rate 0 (about 32 KB over brotli), the tracing
bundle above it (about 52 KB), served at a path that changes with the version and
whether tracing is on, so the year-long cache can never serve a stale one. Tracing adds
page-load spans and web vitals.

A page script adds a child span to its own page load:

```js
window.webserverBase.span({
  name: "bdg.core.ready", op: "bdg",
  start: t0, end: performance.now(), // performance.now() milliseconds
  attributes: { wasm: true },
});
```

It does nothing when tracing is off, or once the page load's trace has ended
(about a second after the last resource), and never starts a transaction of its
own. Call it from a script that runs during load.

**Server.** Each request to a route the site owns is one transaction, named by
route pattern (`GET /blog/{slug}`). Never traced, at any rate: static assets,
icons, `robots.txt`, the manifest, sitemaps, feeds, the health check, the
analytics and Sentry proxies, and anything that matched no route (a 404 is a
scanner). Any other root span (a background task) is dropped too, so the quota
holds only what was budgeted. The rate is the server's own: a request carrying
the browser's `sentry-trace` continues that trace's id but its sampled flag is
ignored. Honouring it would send every request of every sampled page load, at the
browser's rate instead of the server's.

## 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_event`ed 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`](https://docs.rs/metrics) crate
and appear on the same endpoint:

```rust
use webserver_base::metrics::counter;

counter!("games_played_total", "game" => "sokoban").increment(1);
```

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.

```rust
let settings: TelegramSettings = TelegramSettings::builder("123456789:AA...").build()?;
let telegram: ReqwestTelegram = ReqwestTelegram::new(settings, None)?;

telegram.send(
    ChatId::Id(1234),
    Message::builder()
        .text("🎨 ")
        .bold("New pattern")
        .text("\nInput: ")
        .code(untrusted_filename) // no escaping, ever
        .build(),
);
```

| 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`](#appshutdown--draining-your-own-state), 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>`.