docgen_server/lib.rs
1//! `docgen-server` is the **dev-only** server behind `docgen dev`: an axum app
2//! (bound to `127.0.0.1` only) that serves the built site, watches `docs/` for
3//! changes (debounced), rebuilds via [`docgen_build::build_site`], pushes a
4//! live-reload signal over SSE, and exposes a path-guarded markdown write
5//! endpoint for the in-browser editor.
6//!
7//! Nothing in this crate ships in a static `docgen build` dist: the editor UI,
8//! the reload client, the write/SSE endpoints, and the vendored CodeMirror
9//! assets exist ONLY while this server runs.
10
11mod handlers;
12mod watch;
13
14use std::path::{Path, PathBuf};
15use std::sync::atomic::{AtomicU64, Ordering};
16use std::sync::Arc;
17use std::time::{Duration, Instant};
18
19use axum::Router;
20use tokio::sync::broadcast;
21
22/// Window after an editor-initiated write during which a watcher event for the
23/// same on-disk change is treated as a duplicate and skipped. Must comfortably
24/// cover the 200ms watcher debounce.
25const SELF_WRITE_SUPPRESS: Duration = Duration::from_millis(750);
26
27/// Dev-server configuration.
28pub struct DevOptions {
29 pub project_root: PathBuf,
30 /// Loopback port. Default 4321.
31 pub port: u16,
32 /// Open a browser on start (off in tests/CI). Default false.
33 pub open: bool,
34}
35
36/// One live-reload signal. Carried over the SSE channel.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum ReloadEvent {
39 /// A rebuild finished; browsers should reload.
40 Reload,
41 /// The server is shutting down (Ctrl+C). Tells each live-reload SSE stream to
42 /// END, so axum's graceful shutdown can drain the otherwise-eternal keep-alive
43 /// connections instead of hanging on them.
44 Shutdown,
45}
46
47/// Shared, cheaply-clonable state behind every handler. `Clone` bumps the
48/// `Arc`/broadcast handle.
49#[derive(Clone)]
50pub struct AppState {
51 pub project_root: PathBuf,
52 pub out_dir: PathBuf,
53 /// Canonicalized `docs/` dir — the write-guard root.
54 pub docs_dir: PathBuf,
55 /// Site `base` path (e.g. `/docs`), normalized to a leading-slash, no-trailing-slash
56 /// form; empty when the site is served at the root. The built HTML prefixes every
57 /// asset/nav/wikilink URL with this, so the dev server must strip it off incoming
58 /// request paths before resolving them against `out_dir`.
59 pub base: String,
60 /// The loopback port the server is bound to. Used by the Host-header
61 /// allowlist to defeat DNS-rebinding (see `handlers::loopback_guard`).
62 pub port: u16,
63 pub reload_tx: broadcast::Sender<ReloadEvent>,
64 /// Shared "last editor write" clock (millis since `epoch`) used to suppress
65 /// the duplicate watcher rebuild after an in-browser save. `0` = never.
66 self_write_at_ms: Arc<AtomicU64>,
67 /// Monotonic reference instant for `self_write_at_ms`.
68 epoch: Instant,
69}
70
71impl AppState {
72 /// Construct an `AppState`. Initializes the self-write suppression clock.
73 pub fn new(
74 project_root: PathBuf,
75 out_dir: PathBuf,
76 docs_dir: PathBuf,
77 port: u16,
78 reload_tx: broadcast::Sender<ReloadEvent>,
79 ) -> Self {
80 Self {
81 project_root,
82 out_dir,
83 docs_dir,
84 base: String::new(),
85 port,
86 reload_tx,
87 self_write_at_ms: Arc::new(AtomicU64::new(0)),
88 epoch: Instant::now(),
89 }
90 }
91
92 /// Set the site `base` path, normalized to a leading-slash, no-trailing-slash
93 /// form (`docs` / `/docs/` / `docs/` all become `/docs`; empty stays empty).
94 /// Builder-style so the existing `new()` call sites stay untouched.
95 pub fn with_base(mut self, base: &str) -> Self {
96 self.base = normalize_base(base);
97 self
98 }
99
100 /// Record that the editor just wrote a doc on disk. The watcher will skip
101 /// the next change it sees within [`SELF_WRITE_SUPPRESS`] as a duplicate.
102 pub fn note_self_write(&self) {
103 // Store elapsed + 1 so the "never written" sentinel (0) is unambiguous
104 // even when the write happens at elapsed == 0.
105 let ms = self.epoch.elapsed().as_millis() as u64 + 1;
106 self.self_write_at_ms.store(ms, Ordering::SeqCst);
107 }
108
109 /// Whether a watcher event right now should be suppressed as the echo of a
110 /// recent editor write. Consumes the marker so only one rebuild is skipped.
111 pub fn take_self_write_suppression(&self) -> bool {
112 let marked = self.self_write_at_ms.swap(0, Ordering::SeqCst);
113 if marked == 0 {
114 return false;
115 }
116 let now = self.epoch.elapsed().as_millis() as u64 + 1;
117 now.saturating_sub(marked) <= SELF_WRITE_SUPPRESS.as_millis() as u64
118 }
119}
120
121/// Normalize a configured `base` into a leading-slash, no-trailing-slash form
122/// for prefix matching: `""` -> `""`, `"docs"` / `"/docs/"` / `"docs/"` -> `"/docs"`.
123pub fn normalize_base(base: &str) -> String {
124 let trimmed = base.trim().trim_matches('/');
125 if trimmed.is_empty() {
126 String::new()
127 } else {
128 format!("/{trimmed}")
129 }
130}
131
132/// Strip the site `base` prefix from a (already percent-decoded) request path so
133/// it can be resolved against `out_dir`. `base` must be normalized
134/// (`normalize_base`). A request that does not fall under `base` is returned
135/// unchanged — the caller then resolves it normally (and likely 404s), matching
136/// production where the host only routes in-base requests to the site.
137///
138/// `/docs/x.css` -> `/x.css`; `/docs` and `/docs/` -> `/`; `/other` -> `/other`.
139pub fn strip_base<'a>(path: &'a str, base: &str) -> &'a str {
140 if base.is_empty() {
141 return path;
142 }
143 match path.strip_prefix(base) {
144 Some("") => "/",
145 Some(rest) if rest.starts_with('/') => rest,
146 _ => path,
147 }
148}
149
150/// Errors from [`resolve_doc_path`]; each maps to an HTTP status (see `handlers`).
151#[derive(Debug, PartialEq, Eq)]
152pub enum PathGuardError {
153 /// Not a `.md` path. (400)
154 NotMarkdown,
155 /// Absolute path or leading `/`. (400)
156 Absolute,
157 /// `..` component, backslash, or a realpath that escapes `docs/`. (403)
158 Traversal,
159 /// Resolves to something that is not a regular file. (400)
160 NotAFile,
161 /// In-bounds but the file does not exist. (404)
162 NotFound,
163}
164
165/// Resolve a client-supplied doc-relative path (e.g. `"guide/intro.md"`) to a
166/// canonical absolute path strictly inside `docs_dir`, or reject. `docs_dir`
167/// MUST already be canonicalized by the caller. Layered checks mirror the
168/// original `validateRepoDocPath`:
169///
170/// 1. backslash -> `Traversal`; absolute / leading `/` -> `Absolute`.
171/// 2. strip leading `./`; any `..` component -> `Traversal`; empty -> `Traversal`.
172/// 3. require a `.md` suffix -> else `NotMarkdown`.
173/// 4. lexical: `docs_dir.join(rel)` must stay under `docs_dir`.
174/// 5. `canonicalize()`: missing -> `NotFound`; realpath escaping `docs_dir`
175/// (symlink escape) -> `Traversal`.
176/// 6. the canonical target must be a regular file -> else `NotAFile`.
177pub fn resolve_doc_path(docs_dir: &Path, rel: &str) -> Result<PathBuf, PathGuardError> {
178 // (1) gross-shape rejections.
179 if rel.contains('\\') {
180 return Err(PathGuardError::Traversal);
181 }
182 if rel.starts_with('/') || Path::new(rel).is_absolute() {
183 return Err(PathGuardError::Absolute);
184 }
185
186 // (2) normalize + component scan.
187 let trimmed = rel.strip_prefix("./").unwrap_or(rel);
188 if trimmed.is_empty() {
189 return Err(PathGuardError::Traversal);
190 }
191 let mut kept: Vec<&str> = Vec::new();
192 for comp in trimmed.split('/') {
193 match comp {
194 "" | "." => continue, // collapse `//` and `.` segments
195 ".." => return Err(PathGuardError::Traversal),
196 other => kept.push(other),
197 }
198 }
199 if kept.is_empty() {
200 return Err(PathGuardError::Traversal);
201 }
202 let normalized = kept.join("/");
203
204 // (3) extension whitelist (markdown-only; the TS guard also allowed `.svx`,
205 // which the Rust rewrite does not support).
206 if !normalized.ends_with(".md") {
207 return Err(PathGuardError::NotMarkdown);
208 }
209
210 // (4) lexical containment.
211 let candidate = docs_dir.join(&normalized);
212 if !candidate.starts_with(docs_dir) {
213 return Err(PathGuardError::Traversal);
214 }
215
216 // (5) realpath check (catches symlink escapes).
217 // Any canonicalize failure (missing path, permission, etc.) is reported as
218 // NotFound for a dev write endpoint — the client cannot act on finer detail.
219 let canonical = match candidate.canonicalize() {
220 Ok(p) => p,
221 Err(_) => return Err(PathGuardError::NotFound),
222 };
223 if !canonical.starts_with(docs_dir) {
224 return Err(PathGuardError::Traversal);
225 }
226
227 // (6) must be a regular file (not a dir, not a symlink-to-dir).
228 let meta = match std::fs::symlink_metadata(&canonical) {
229 Ok(m) => m,
230 Err(_) => return Err(PathGuardError::NotFound),
231 };
232 if !meta.is_file() {
233 return Err(PathGuardError::NotAFile);
234 }
235
236 Ok(canonical)
237}
238
239/// The dev-only HTML injected before `</body>` of every served page: the editor
240/// css, a tiny inline script that inserts the dev-only edit icon into the
241/// topbar's `.docgen-btn-strip` (next to the diff/full-width controls — so the
242/// static `docgen build` output never contains it), the editor island panel
243/// element, the vendored CodeMirror UMD scripts (loaded in dependency order:
244/// core -> xml mode -> overlay addon -> markdown mode), the editor island JS,
245/// and the live-reload client.
246///
247/// These non-`defer` scripts execute at parse time — before the page's deferred
248/// Alpine script fires `alpine:init` — so `editor.js`'s `docgen.island(...)`
249/// registration lands before Alpine runs the registry. Injected ONLY by the dev
250/// server (`inject_dev_html`); never written to disk by `docgen build`.
251const DEV_HTML: &str = r#"
252<script>(function(){
253 var strip=document.querySelector('.docgen-btn-strip');
254 if(!strip)return;
255 // The full-page CM6 editor lives at /edit/<slug>; the pencil links to it.
256 var slug=location.pathname.replace(/^\/+|\/+$/g,'');
257 if(slug==='')slug='index';
258 var a=document.createElement('a');
259 a.className='icon-only docgen-ctl--edit';
260 a.setAttribute('href','/edit/'+slug);
261 a.setAttribute('aria-label','Edit this page');
262 a.setAttribute('title','Edit this page (dev)');
263 a.innerHTML='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>';
264 var fw=strip.querySelector('.docgen-ctl--fullwidth');
265 if(fw)strip.insertBefore(a,fw);else strip.appendChild(a);
266})();</script>
267<script src="/__docgen/livereload.js"></script>
268"#;
269
270/// Post-process a served HTML body: inject the reload-client script + editor
271/// toggle + editor island scripts/styles immediately before `</body>`. Dev-only;
272/// never run by `docgen build`. Pure string fn so it is unit-testable.
273pub fn inject_dev_html(html: &str) -> String {
274 match html.rfind("</body>") {
275 Some(i) => {
276 let mut s = String::with_capacity(html.len() + DEV_HTML.len());
277 s.push_str(&html[..i]);
278 s.push_str(DEV_HTML);
279 s.push_str(&html[i..]);
280 s
281 }
282 // Graceful: append if there is no closing body tag.
283 None => format!("{html}{DEV_HTML}"),
284 }
285}
286
287/// The loopback bind address for the dev server. NEVER `0.0.0.0` — the dev
288/// server (editor + write endpoint) must not be reachable off-host.
289pub fn dev_bind_addr(port: u16) -> std::net::SocketAddr {
290 std::net::SocketAddr::from(([127, 0, 0, 1], port))
291}
292
293/// Build the axum router (NO listener) for the given state. Split out so handler
294/// tests can `oneshot` requests without binding a port.
295pub fn router(state: AppState) -> Router {
296 handlers::router(state)
297}
298
299/// Rebuild the site into `state.out_dir` (Dev mode + dev-asset emission), then
300/// broadcast a reload. Called on every debounced fs change AND after a successful
301/// editor write. Returns `Err` only on a hard build failure; the caller logs and
302/// keeps serving the last good build. This guarantee holds because
303/// [`docgen_build::build_site`] is atomic — it stages into a temp dir and only
304/// swaps `out_dir` on full success, so a failed rebuild leaves the served dir
305/// (the previous good build) untouched rather than torn down.
306pub fn rebuild_and_reload(state: &AppState) -> anyhow::Result<()> {
307 let start = std::time::Instant::now();
308 let outcome = docgen_build::build_site(&docgen_build::BuildOptions {
309 project_root: &state.project_root,
310 out_dir: &state.out_dir,
311 mode: docgen_build::BuildMode::Dev,
312 })?;
313 // The dev-only extra step build_site never performs: emit CodeMirror + the
314 // editor island + the reload client into the served dir.
315 docgen_assets::emit(&docgen_assets::dev_assets(), &state.out_dir)?;
316
317 // Ignore "no subscribers" — a reload with nobody listening is fine.
318 let _ = state.reload_tx.send(ReloadEvent::Reload);
319 tracing::info!(
320 pages = outcome.page_count,
321 elapsed_ms = start.elapsed().as_millis(),
322 "rebuilt + reloaded"
323 );
324 Ok(())
325}
326
327/// Run the dev server: initial build, spawn the debounced watcher, bind
328/// `127.0.0.1`, serve until Ctrl-C. Blocking entry point the `docgen dev` CLI
329/// arm calls. Owns its own tokio runtime so the `docgen` bin's `main` stays a
330/// plain `fn main() -> Result<()>`.
331pub fn serve(opts: DevOptions) -> anyhow::Result<()> {
332 // Idempotent: a second `serve` in-process (tests) won't panic.
333 let _ = tracing_subscriber::fmt()
334 .with_env_filter(
335 tracing_subscriber::EnvFilter::try_from_default_env()
336 .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
337 )
338 .try_init();
339
340 let runtime = tokio::runtime::Builder::new_multi_thread()
341 .enable_all()
342 .build()?;
343 runtime.block_on(serve_async(opts))
344}
345
346async fn serve_async(opts: DevOptions) -> anyhow::Result<()> {
347 let project_root = opts.project_root.clone();
348 let docs_dir = project_root.join("docs");
349 let docs_canon = docs_dir.canonicalize().unwrap_or_else(|_| docs_dir.clone());
350
351 // A process-owned output dir; kept alive for the whole run, auto-cleaned.
352 let out_tmp = tempfile::tempdir()?;
353 let out_dir = out_tmp.path().to_path_buf();
354
355 // The built HTML prefixes every URL with the configured `base`; the server
356 // must strip it off incoming requests. A malformed config here is non-fatal
357 // for serving (the build step reports it) — fall back to "served at root".
358 let base = docgen_config::load(&project_root)
359 .map(|c| c.base)
360 .unwrap_or_default();
361
362 let (reload_tx, _rx) = broadcast::channel(16);
363 let state = AppState::new(
364 project_root,
365 out_dir,
366 docs_canon.clone(),
367 opts.port,
368 reload_tx,
369 )
370 .with_base(&base);
371
372 // Initial build (Dev mode + dev assets).
373 rebuild_and_reload(&state)?;
374
375 // Spawn the debounced fs watcher; it rebuilds + reloads on every change.
376 let _watcher = watch::spawn_watcher(state.clone(), &docs_canon)?;
377
378 let addr = dev_bind_addr(opts.port);
379 let listener = tokio::net::TcpListener::bind(addr).await?;
380 tracing::info!("docgen dev server: http://{addr}");
381 if opts.open {
382 let _ = open_browser(&format!("http://{addr}"));
383 }
384
385 // Clone the reload sender before `state` moves into the router; the shutdown
386 // hook uses it to terminate the open live-reload SSE streams so the graceful
387 // drain can complete (otherwise the 15s keep-alive holds the process open).
388 let shutdown_tx = state.reload_tx.clone();
389 axum::serve(listener, router(state))
390 .with_graceful_shutdown(async move {
391 let _ = tokio::signal::ctrl_c().await;
392 let _ = shutdown_tx.send(ReloadEvent::Shutdown);
393 })
394 .await?;
395 Ok(())
396}
397
398/// Best-effort browser open (dev convenience; failures are non-fatal).
399fn open_browser(url: &str) -> std::io::Result<()> {
400 #[cfg(target_os = "macos")]
401 let cmd = "open";
402 #[cfg(all(unix, not(target_os = "macos")))]
403 let cmd = "xdg-open";
404 #[cfg(windows)]
405 let cmd = "explorer";
406 std::process::Command::new(cmd).arg(url).spawn().map(|_| ())
407}
408
409#[cfg(test)]
410mod tests {
411 use super::*;
412
413 #[test]
414 fn inject_dev_html_inserts_before_body() {
415 let out = inject_dev_html("<html><body><p>hi</p></body></html>");
416 // Reload client + the edit pencil (a link to the /edit/<slug> CM6 editor).
417 for marker in ["__docgen/livereload.js", "docgen-ctl--edit", "/edit/"] {
418 assert!(out.contains(marker), "missing injected marker {marker}");
419 }
420 // Every injected marker precedes the closing body tag.
421 let body = out.rfind("</body>").unwrap();
422 for marker in ["__docgen/livereload.js", "docgen-ctl--edit"] {
423 assert!(
424 out.find(marker).unwrap() < body,
425 "{marker} not before </body>"
426 );
427 }
428 // The static build never contains the dev edit affordance.
429 assert!(!"<html><body></body></html>".contains("docgen-ctl--edit"));
430 }
431
432 #[test]
433 fn inject_dev_html_no_body_appends() {
434 let out = inject_dev_html("<p>no body tag here</p>");
435 assert!(out.contains("__docgen/livereload.js"));
436 assert!(out.contains("docgen-ctl--edit"));
437 }
438
439 #[test]
440 fn self_write_suppression_is_one_shot() {
441 let (tx, _rx) = broadcast::channel(4);
442 let state = AppState::new(
443 PathBuf::from("/x"),
444 PathBuf::from("/x/out"),
445 PathBuf::from("/x/docs"),
446 4321,
447 tx,
448 );
449 // No write yet -> nothing to suppress.
450 assert!(!state.take_self_write_suppression());
451 // After a self-write, exactly one watcher event is suppressed.
452 state.note_self_write();
453 assert!(state.take_self_write_suppression());
454 assert!(!state.take_self_write_suppression());
455 }
456
457 #[test]
458 fn normalize_base_canonicalizes() {
459 assert_eq!(normalize_base(""), "");
460 assert_eq!(normalize_base("/"), "");
461 assert_eq!(normalize_base("docs"), "/docs");
462 assert_eq!(normalize_base("/docs"), "/docs");
463 assert_eq!(normalize_base("/docs/"), "/docs");
464 assert_eq!(normalize_base("docs/"), "/docs");
465 assert_eq!(normalize_base("/a/b"), "/a/b");
466 }
467
468 #[test]
469 fn strip_base_handles_prefix_and_misses() {
470 // Empty base: everything passes through unchanged.
471 assert_eq!(strip_base("/docgen.css", ""), "/docgen.css");
472 // In-base requests get the prefix removed.
473 assert_eq!(strip_base("/docs/docgen.css", "/docs"), "/docgen.css");
474 assert_eq!(strip_base("/docs/guide/intro", "/docs"), "/guide/intro");
475 // The base root itself maps to "/".
476 assert_eq!(strip_base("/docs", "/docs"), "/");
477 assert_eq!(strip_base("/docs/", "/docs"), "/");
478 // A path that merely shares a textual prefix is NOT in-base.
479 assert_eq!(strip_base("/docsxyz", "/docs"), "/docsxyz");
480 // Out-of-base requests are returned unchanged.
481 assert_eq!(strip_base("/other", "/docs"), "/other");
482 }
483
484 #[test]
485 fn bind_addr_is_loopback() {
486 assert!(dev_bind_addr(4321).ip().is_loopback());
487 assert_eq!(dev_bind_addr(4321).port(), 4321);
488 }
489}