Skip to main content

larust_core/
application.rs

1use crate::{
2    debug, dev_reload, error, error_pages, lifecycle, AppError, AppPaths, AppState, Config,
3    ErrorPages, GracefulShutdown,
4};
5use axum::http::{header, HeaderName, HeaderValue, StatusCode};
6use axum::response::{IntoResponse, Response};
7use axum::Router;
8use std::any::Any;
9use std::net::SocketAddr;
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::sync::Arc;
12use tower_http::catch_panic::CatchPanicLayer;
13use tower_http::services::ServeDir;
14use tower_http::set_header::SetResponseHeaderLayer;
15
16/// Upper bound on how long a restart-handoff replacement gets to report
17/// readiness (see `lifecycle::handoff`) before this process gives up on
18/// that attempt and keeps serving normally. Deliberately generous
19/// compared to `GracefulShutdown::drain_timeout` - a slow build/startup
20/// shouldn't fail a restart outright the way a stuck in-flight request
21/// should eventually force an exit.
22const HANDOFF_READY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
23
24/// Drain timeout used automatically under `LARUST_DEV_RELOAD`, when the
25/// app itself never opted into graceful shutdown explicitly - deliberately
26/// much shorter than `GracefulShutdown::default()`'s own 30s. `dev_reload`'s
27/// `/__larust_dev` endpoint is an SSE stream that never completes by
28/// design (`Never` + `KeepAlive`, forever), so a graceful drain can never
29/// finish *naturally* for it - the only thing that ever actually closes
30/// that connection is this timeout's own hard backstop
31/// (`tokio::time::sleep(drain_timeout)` → `std::process::exit(0)`,
32/// further down in `serve()`). Since the browser's reload detection is
33/// "the SSE connection dropped and reconnected," reload latency is
34/// directly bounded by whatever this constant is set to - a
35/// production-sized timeout here would make reload noticeably *slower*
36/// than the plain hard-kill behavior this replaces, the opposite of what
37/// this feature is for.
38const DEV_DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
39
40/// Warns once, at startup, if [`Config::session_driver`] resolved to
41/// anything other than the two real, supported values (`"database"`,
42/// `"file"`). Originally this field didn't exist at all - `SESSION_DRIVER`
43/// was silently never read anywhere in this codebase, reported directly as
44/// a real production confusion (a `.env` value that looked like it should
45/// matter turning out to have done nothing, with no error, no log line,
46/// nothing). Once support for `"file"` was added, that exact same silent-
47/// no-op shape became newly possible again for anyone who sets
48/// `SESSION_DRIVER` to a typo, or to a Laravel value this framework
49/// doesn't implement (`"array"`, `"redis"`, `"cookie"`, ...) - so this
50/// still warns for those, even though the field itself is real now.
51/// Checking the *resolved* `Config` value (not the raw environment, unlike
52/// this function's own predecessor) is deliberate: it's the one thing that
53/// actually determines behavior, and it's already been through the exact
54/// `env_or("SESSION_DRIVER", "database")` resolution every other config
55/// field uses, so there's no separate "did the user actually set this"
56/// check to duplicate here the way `default_log_channel_to_file_if_
57/// stdio_detached` needs for its own, different reason.
58fn warn_if_session_driver_is_unsupported(config: &Config) {
59    if !is_supported_session_driver(&config.session_driver) {
60        tracing::warn!(
61            session_driver = %config.session_driver,
62            "SESSION_DRIVER is set to an unsupported value - Larust only supports \"database\" \
63             (the default) or \"file\". Falling back to \"database\". See \
64             docs/the-basics/middleware-sessions-and-csrf.md for what each one means."
65        );
66    }
67}
68
69/// The two real values [`Config::session_driver`]/`SESSION_DRIVER` accept -
70/// pulled out as its own pure function (rather than inlined into
71/// `warn_if_session_driver_is_unsupported`'s own `if`) specifically so a
72/// test can check the actual list of supported values directly, without
73/// needing to capture a `tracing::warn!` call to prove anything about it.
74/// `larust_http::session::session_layer`'s own driver dispatch is the
75/// other, independent place this same two-value split matters - kept as a
76/// literal `match` there rather than calling this (a `larust-core` type
77/// calling back into `larust-http` would be a dependency cycle), so if a
78/// third driver is ever added, both places need the identical update.
79fn is_supported_session_driver(value: &str) -> bool {
80    matches!(value, "database" | "file")
81}
82
83/// Set only on the child `xr deploy --run`'s `start_detached` spawns
84/// (`crates/larust-cli/src/deploy.rs`) - never on a plain `cargo run`/
85/// `xr dev` boot. Bare string literal, not a shared `pub const`, matching
86/// `LARUST_DEV_RELOAD`'s own precedent just above for the identical
87/// reason: a CLI-sets/core-reads marker that only ever needs to agree by
88/// name within this one workspace, not a real cross-crate API contract.
89const STDIO_DETACHED_ENV: &str = "LARUST_STDIO_DETACHED";
90
91/// Defaults [`Config::log_channel`] to `"file"` instead of its own
92/// built-in `"stdout"` default, but *only* when both are true: the user
93/// never explicitly set `LOG_CHANNEL` at all, and this process's
94/// stdout/stderr were permanently redirected to the null device by `xr
95/// deploy --run`'s `start_detached`. Closes a real, silent failure mode,
96/// reported directly from a production app: `start_detached` sets
97/// `Stdio::null()` on the very first generation's stdout/stderr (needed so
98/// the detached child doesn't print into `xr deploy`'s own terminal), and
99/// every later zero-downtime restart-handoff replacement inherits its own
100/// stdout from its immediate predecessor (`lifecycle::handoff::
101/// spawn_replacement_and_wait_for_ready`'s own `Stdio::inherit()`) - so
102/// that null redirection propagates down an app's *entire* production
103/// lifetime, the same way [`STDIO_DETACHED_ENV`] itself does (`Command`
104/// inherits its parent's environment by default, and nothing here ever
105/// clears it). With `LOG_CHANNEL` left at its default, that combination
106/// produces zero log output, ever, for as long as that app runs - not an
107/// error, just total silence, which is far more dangerous than a
108/// merely-suboptimal default: this fixes it automatically, with no action
109/// required from whoever's operating the app, rather than only warning
110/// about it (see `docs/deployment-and-desktop-apps.md`'s own warning,
111/// which still explains the mechanism for anyone who *does* want plain
112/// `stdout` and reads why they can't have it silently here).
113///
114/// Checks the *real* environment (`std::env::var`), not `config.
115/// log_channel` itself, deliberately: by the time `Config::from_value` has
116/// run, `Config`'s own built-in default and an explicit, redundant
117/// `LOG_CHANNEL=stdout` in `.env` both resolve to the identical string -
118/// only the raw environment can tell "the user never touched this" apart
119/// from "the user explicitly chose the same value the default already
120/// was," and only the former should ever be overridden here.
121fn default_log_channel_to_file_if_stdio_detached(config: &mut Config) {
122    let user_set_log_channel = std::env::var("LOG_CHANNEL").is_ok();
123    let stdio_is_detached = std::env::var_os(STDIO_DETACHED_ENV).is_some();
124    if !user_set_log_channel && stdio_is_detached {
125        config.log_channel = "file".to_string();
126    }
127}
128
129pub struct Application {
130    config: Config,
131    paths: AppPaths,
132    state: AppState,
133    router: Router,
134    graceful_shutdown: Option<GracefulShutdown>,
135    health_route: Option<String>,
136    /// Keeps `logging::init`'s background file-writer thread alive for the
137    /// whole process - see that function's own doc comment. Never read,
138    /// only held; dropping `Application` (process exit) is what eventually
139    /// flushes and stops it.
140    _log_guard: Option<tracing_appender::non_blocking::WorkerGuard>,
141}
142
143impl Application {
144    /// Loads config, initializes logging, flips the process-wide debug flag
145    /// (`crate::debug`) that gates descriptive error pages, and publishes
146    /// config process-wide (`crate::config::config()`, used by
147    /// `larust_support::url()`/`asset()`/`config()`).
148    ///
149    /// `config` is the app's own generated `config/app.rs`'s `pub fn
150    /// config() -> serde_json::Value` (e.g. `my_app::config::app::config`) -
151    /// a plain function item, not a closure, so every real caller can
152    /// just pass the function itself. Called *after* `.env` is loaded (see
153    /// `with_paths` below), so its own `env`/`env_bool`/`env_or` calls
154    /// (`larust_support::config_env`) see whatever `.env` set.
155    ///
156    /// This does a small amount of synchronous filesystem I/O (loading
157    /// `.env`) even when called from inside an async runtime. That's
158    /// intentional: it runs once at startup, before any other async work is
159    /// scheduled, so the blocking cost is negligible - not worth the
160    /// complexity of `spawn_blocking` for a few KB of env file.
161    pub fn new(config: fn() -> serde_json::Value) -> Result<Self, AppError> {
162        Self::with_paths(AppPaths::default(), config)
163    }
164
165    /// Creates an application rooted at `root`, independent of the process
166    /// working directory. New binaries should prefer this over `new()`.
167    pub fn at_root(
168        root: impl Into<std::path::PathBuf>,
169        config: fn() -> serde_json::Value,
170    ) -> Result<Self, AppError> {
171        Self::with_paths(AppPaths::new(root), config)
172    }
173
174    fn with_paths(paths: AppPaths, config: fn() -> serde_json::Value) -> Result<Self, AppError> {
175        dotenvy::from_path(paths.env()).ok();
176        let mut config = Config::from_value(&config())?;
177        default_log_channel_to_file_if_stdio_detached(&mut config);
178        let log_guard = crate::logging::init(&config, &paths);
179        warn_if_session_driver_is_unsupported(&config);
180        debug::set(config.app_debug);
181        config.clone().publish();
182        paths.clone().publish();
183        let state = AppState::new(config.clone(), paths.clone());
184
185        Ok(Self {
186            config,
187            paths,
188            state,
189            router: Router::new(),
190            graceful_shutdown: None,
191            health_route: None,
192            _log_guard: log_guard,
193        })
194    }
195
196    /// Sets the router that will handle incoming requests.
197    pub fn router(mut self, router: Router) -> Self {
198        self.router = router;
199        self
200    }
201
202    pub fn config(&self) -> &Config {
203        &self.config
204    }
205
206    /// Explicit application state suitable for application-owned Axum state.
207    pub fn state(&self) -> AppState {
208        self.state.clone()
209    }
210
211    pub fn paths(&self) -> &AppPaths {
212        &self.paths
213    }
214
215    /// Opts into graceful shutdown: on Ctrl+C (or, on Unix, SIGTERM),
216    /// `serve()` stops accepting new connections and waits for in-flight
217    /// ones to finish (bounded by `config.drain_timeout`) before exiting,
218    /// instead of exiting instantly. See [`GracefulShutdown`]'s own doc
219    /// comment for why this is opt-in rather than the default.
220    pub fn with_graceful_shutdown(mut self, config: GracefulShutdown) -> Self {
221        self.graceful_shutdown = Some(config);
222        self
223    }
224
225    /// Registers Laravel-style health routing. Laravel applications use
226    /// `'/up'` by default, so generated Larust applications should call
227    /// `.with_health_route("/up")` during bootstrap.
228    ///
229    /// The endpoint is deliberately opt-in so applications keep control of
230    /// their route namespace. It returns `200 OK` once Larust has completed
231    /// bootstrap; a future diagnostic registry can add dependency checks
232    /// without changing the route contract.
233    pub fn with_health_route(mut self, path: impl Into<String>) -> Self {
234        let path = path.into();
235        assert!(
236            path.starts_with('/'),
237            "health route must start with '/'; received {path:?}"
238        );
239        self.health_route = Some(path);
240        self
241    }
242
243    /// Registers the app's 404/500 pages, rendered once here (not per
244    /// request - see `ErrorPages`' own doc comment) and used by every
245    /// `AppError::NotFound`/`Internal`/`Config`/caught-panic response for
246    /// the rest of the process's life. Entirely optional - `AppError`'s own
247    /// `into_response()` falls back to Larust's built-in default pages if
248    /// this is never called, so an app that skips this still gets styled
249    /// error pages, just not the option to override them.
250    pub fn with_error_pages(self, pages: ErrorPages) -> Self {
251        error_pages::set(pages);
252        self
253    }
254
255    /// Binds to `config.app_port` on localhost and serves until the process
256    /// is terminated.
257    pub async fn serve(self) -> Result<(), AppError> {
258        let addr = SocketAddr::from(([127, 0, 0, 1], self.config.app_port));
259        tracing::info!(%addr, app = %self.config.app_name, env = %self.config.app_env, "starting server");
260
261        // Set only on the child process `xr dev` spawns itself - never on
262        // a plain `cargo run`, and never touched by any generated app
263        // code (see the fuller explanation further down, at the route-
264        // mounting site that originally introduced this check).
265        let is_dev_reload = std::env::var_os("LARUST_DEV_RELOAD").is_some();
266
267        // Auto-enables graceful shutdown (short, dev-appropriate timeout)
268        // plus the restart-admin-channel specifically under `xr dev`'s own
269        // reload flag - never for a plain production app, and never
270        // overriding an app author's own explicit `.with_graceful_shutdown
271        // (...)` call (that app just keeps today's kill-based dev
272        // behavior, a documented, acceptable edge case: someone testing
273        // their own production graceful-shutdown config locally under
274        // `xr dev` gets what they asked for, not this override). This is
275        // what lets `xr dev` perform a real zero-downtime handoff on every
276        // rebuild instead of hard-killing the previous process first.
277        let graceful_shutdown = self.graceful_shutdown.or_else(|| {
278            is_dev_reload.then_some(GracefulShutdown {
279                drain_timeout: DEV_DRAIN_TIMEOUT,
280                restart_channel: true,
281            })
282        });
283        let app_name = self.config.app_name.clone();
284
285        // A process spawned as a restart-handoff replacement (see
286        // `lifecycle::handoff`) inherits the *same* listening socket its
287        // predecessor was already using, read from its own stdin as one
288        // line of encoded text, instead of binding `addr` fresh - the
289        // whole point of the handoff being able to start serving with no
290        // gap at all. Ordinary startup (a plain `cargo run`/`xr dev`, or
291        // any generated app not using the restart-handoff feature) never
292        // sets this env var and binds fresh exactly as before this
293        // feature existed.
294        let is_handoff_replacement =
295            std::env::var_os(lifecycle::listener::INHERIT_LISTENER_ENV).is_some();
296        if is_handoff_replacement {
297            // Arms this process's own death-signal delivery (Linux) /
298            // relies on already having inherited job-object membership
299            // (Windows) - see `lifecycle::supervisor`'s own doc comment
300            // for why this now happens *here*, inside the already-exec'd
301            // replacement, rather than via a `Command::pre_exec` hook run
302            // by the parent between `fork()` and `exec()` (that design's
303            // real, confirmed bug).
304            lifecycle::supervisor::arm_pdeathsig();
305        }
306        let std_listener = if is_handoff_replacement {
307            let mut line = String::new();
308            tokio::io::AsyncBufReadExt::read_line(
309                &mut tokio::io::BufReader::new(tokio::io::stdin()),
310                &mut line,
311            )
312            .await
313            .map_err(|source| AppError::Internal(Box::new(source)))?;
314            lifecycle::listener::inherit(&line)
315                .map_err(|source| AppError::Internal(Box::new(source)))?
316        } else {
317            lifecycle::listener::bind(addr)
318                .map_err(|source| AppError::Internal(Box::new(source)))?
319        };
320        // Kept as a plain std listener, separate from the tokio-wrapped
321        // one below - the restart-handoff machinery (`lifecycle::admin`,
322        // `lifecycle::handoff`) works with std sockets directly (it needs
323        // the raw fd/socket handle, not an async wrapper around one), and
324        // needs its own independent handle to the same underlying kernel
325        // socket regardless of whether graceful shutdown/the admin
326        // channel end up being configured at all.
327        let admin_listener = std_listener
328            .try_clone()
329            .map_err(|source| AppError::Internal(Box::new(source)))?;
330        std_listener
331            .set_nonblocking(true)
332            .map_err(|source| AppError::Internal(Box::new(source)))?;
333        let listener = tokio::net::TcpListener::from_std(std_listener)
334            .map_err(|source| AppError::Internal(Box::new(source)))?;
335
336        // `.route(...)` panics on an exact-path collision with a route the
337        // app already registered - acceptable here given how unlikely a
338        // real app is to independently choose the `__larust_dev` path, but
339        // worth knowing if this route's name ever needs to change.
340        let router = if is_dev_reload {
341            self.router
342                .route("/__larust_dev", axum::routing::get(dev_reload::handler))
343        } else {
344            self.router
345        };
346
347        let router = if let Some(path) = self.health_route {
348            router.route(&path, axum::routing::get(health))
349        } else {
350            router
351        };
352
353        // Served at the URL root (`public/logo.png` → `/logo.png`), not
354        // under a `/public` prefix - matching Laravel's own convention,
355        // where `public/` *is* the webserver's docroot. A registered route
356        // wins over a same-path file for any *literal* request path:
357        // `fallback_service` is only ever consulted when axum's own router
358        // finds no match. That precedence is per byte, not per resolved
359        // path, though - axum matches on the raw, undecoded request path,
360        // while `ServeDir` percent-decodes before resolving a file, so a
361        // percent-encoded request (`/app%2Ejs`) can reach a file the
362        // registered route at `/app.js` would otherwise have handled. Not
363        // a traversal/disclosure risk (it can only ever reach content
364        // that's already sitting in `public/`), just worth knowing the
365        // "route always wins" framing isn't byte-for-byte absolute. A
366        // missing `public/` directory isn't an error here - `ServeDir`
367        // checks the filesystem per-request, not at construction, so
368        // every request just 404s until the directory exists.
369        //
370        // `.not_found_service(...)` (not a bare `ServeDir`) so a request
371        // matching *neither* a registered route *nor* a real file gets
372        // Larust's own styled 404 (default or app-overridden, see
373        // `ErrorPages`) instead of `ServeDir`'s own bare, empty-body one -
374        // this is the only path a genuinely dead URL a visitor hits ever
375        // takes; `AppError::NotFound` is otherwise only ever constructed by
376        // a handler explicitly returning it (e.g. a failed route-model-
377        // binding lookup). Scoped precisely to `ServeDir`'s own not-found
378        // response - a handler elsewhere in the app that builds its own
379        // `(StatusCode::NOT_FOUND, ...)` response directly is untouched.
380        let router = router.fallback_service(ServeDir::new(self.paths.public()).not_found_service(
381            tower::service_fn(|_req: axum::extract::Request| async {
382                Ok::<_, std::convert::Infallible>(AppError::NotFound.into_response())
383            }),
384        ));
385
386        // Applies to every response, not just `public/`'s - `nosniff` is a
387        // broadly-correct default (OWASP baseline), but it matters
388        // specifically here: `ServeDir` infers a served file's Content-Type
389        // from its *extension* alone (via `mime_guess`), never its actual
390        // bytes, so anything written into `public/` under an
391        // extension-spoofed name (e.g. an app that validates an upload's
392        // declared MIME type but not its real bytes) would otherwise be
393        // subject to the browser's own content-sniffing - this header is
394        // what keeps a browser from second-guessing the declared type.
395        let router = router.layer(SetResponseHeaderLayer::overriding(
396            header::X_CONTENT_TYPE_OPTIONS,
397            HeaderValue::from_static("nosniff"),
398        ));
399        // Safe defaults which do not depend on whether TLS is terminated by
400        // this process or a reverse proxy. Applications can set a stricter
401        // CSP/HSTS policy at their own edge, where their asset and proxy
402        // topology is known.
403        let router = router.layer(SetResponseHeaderLayer::if_not_present(
404            HeaderName::from_static("referrer-policy"),
405            HeaderValue::from_static("strict-origin-when-cross-origin"),
406        ));
407        let router = router.layer(SetResponseHeaderLayer::if_not_present(
408            HeaderName::from_static("x-frame-options"),
409            HeaderValue::from_static("DENY"),
410        ));
411
412        install_backtrace_capturing_panic_hook();
413        let router = router.layer(CatchPanicLayer::custom(handle_panic));
414
415        // Signals the predecessor process (see `lifecycle::handoff`) that
416        // this replacement is genuinely about to start accepting
417        // connections on the inherited listener - the predecessor is
418        // waiting on exactly this line before it begins its own graceful
419        // shutdown. A no-op on any ordinary boot.
420        if is_handoff_replacement {
421            lifecycle::readiness::announce_ready();
422            // From this exact point on, the predecessor exiting is the
423            // expected, successful conclusion of this handoff, not
424            // something to react to - see `lifecycle::supervisor::linux::
425            // disarm_pdeathsig`'s own doc comment for the real bug
426            // leaving this armed past this point caused (a brand-new
427            // replacement receiving its predecessor's own death signal
428            // and mistakenly starting to drain itself).
429            lifecycle::supervisor::disarm_pdeathsig();
430        }
431
432        let Some(graceful_shutdown) = graceful_shutdown else {
433            // Today's exact behavior, byte-for-byte unchanged apart from
434            // `into_make_service_with_connect_info`: a bare `axum::serve`
435            // that exits the instant the process is killed.
436            axum::serve(
437                listener,
438                router.into_make_service_with_connect_info::<SocketAddr>(),
439            )
440            .await
441            .map_err(|source| AppError::Internal(Box::new(source)))?;
442            return Ok(());
443        };
444
445        // `shutdown_tx` fires once, on Ctrl+C/SIGTERM - `with_graceful_shutdown`
446        // then stops accepting new connections and waits for in-flight ones
447        // to finish. The `drain_timeout` sleep in this same spawned task is
448        // a hard backstop: if the graceful drain hasn't finished naturally
449        // by then (a stuck connection, a hung upstream call), force the
450        // process to exit anyway rather than hang a deploy forever. If the
451        // drain finishes first, `serve()` below returns `Ok(())`, the
452        // process exits normally, and this still-sleeping task is simply
453        // dropped along with it - nothing to clean up either way.
454        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
455        let drain_timeout = graceful_shutdown.drain_timeout;
456        let restart_channel_enabled = graceful_shutdown.restart_channel;
457        // Set right before `shutdown_tx.send(())`, only on the `Handoff`
458        // arm below - checked after `axum::serve()` returns to decide
459        // whether the `std::process::exit(0)` bypass further down applies.
460        // See that bypass's own doc comment for the Windows hang this
461        // exists to sidestep: it used to key off `is_dev_reload` instead
462        // of this, which was too narrow - a production app calling
463        // `.with_graceful_shutdown(GracefulShutdown { restart_channel:
464        // true, .. })` directly (never setting `LARUST_DEV_RELOAD`, e.g.
465        // via `xr restart`) hits the *exact same* hang on a successful
466        // handoff, and `is_dev_reload` being false meant the bypass never
467        // fired for it - confirmed by reproducing this exact hang via
468        // `tests/stale_binary_path.rs`, which uses this precise
469        // configuration. "Did this process hand off a child that outlives
470        // it" is the condition that actually matters, not which caller
471        // happened to enable the restart channel.
472        let handed_off_child = Arc::new(AtomicBool::new(false));
473        tokio::spawn({
474            let handed_off_child = Arc::clone(&handed_off_child);
475            async move {
476                if restart_channel_enabled {
477                    let address = lifecycle::admin::channel_address(&app_name);
478                    tokio::select! {
479                        _ = lifecycle::wait_for_termination() => {
480                            tracing::info!(
481                                ?drain_timeout,
482                                "shutdown signal received; draining in-flight requests"
483                            );
484                        }
485                        outcome = lifecycle::admin::run_until_command(
486                            &address,
487                            &admin_listener,
488                            HANDOFF_READY_TIMEOUT,
489                        ) => {
490                            match outcome {
491                                lifecycle::admin::AdminOutcome::Handoff(child) => {
492                                    // Dropping this handle does *not* kill the
493                                    // child - `tokio::process::Command` only
494                                    // does that with `.kill_on_drop(true)`,
495                                    // which this code path never sets. It's
496                                    // already running and serving on the
497                                    // listener this process just handed off;
498                                    // nothing further needs doing with the
499                                    // handle itself - see the forced
500                                    // `std::process::exit(0)` after
501                                    // `axum::serve()` below for *why* dropping
502                                    // it here (rather than awaiting its exit)
503                                    // is not just sufficient but necessary.
504                                    tracing::info!(
505                                        pid = child.id(),
506                                        ?drain_timeout,
507                                        "restart handoff succeeded; draining in-flight requests"
508                                    );
509                                    handed_off_child.store(true, Ordering::SeqCst);
510                                }
511                                lifecycle::admin::AdminOutcome::Stop => {
512                                    tracing::info!(
513                                        ?drain_timeout,
514                                        "stop command received; draining in-flight requests"
515                                    );
516                                }
517                            }
518                        }
519                    }
520                } else {
521                    lifecycle::wait_for_termination().await;
522                    tracing::info!(
523                        ?drain_timeout,
524                        "shutdown signal received; draining in-flight requests"
525                    );
526                }
527                let _ = shutdown_tx.send(());
528                tokio::time::sleep(drain_timeout).await;
529                tracing::warn!(
530                    "drain timeout elapsed; forcing exit with any remaining connections dropped"
531                );
532                std::process::exit(0);
533            }
534        });
535
536        axum::serve(
537            listener,
538            router.into_make_service_with_connect_info::<SocketAddr>(),
539        )
540        .with_graceful_shutdown(async move {
541            let _ = shutdown_rx.await;
542        })
543        .await
544        .map_err(|source| AppError::Internal(Box::new(source)))?;
545
546        // A restart-handoff replacement's `Child` handle (see the
547        // `AdminOutcome::Handoff` arm above) is deliberately dropped, not
548        // awaited - the whole point is that the replacement outlives this
549        // process. But on Windows, that leaves an outstanding exit-watch
550        // registration on the (still-running, by design) replacement's
551        // process handle, and confirmed empirically (not from docs -
552        // reproduced directly via instrumented tracing before landing this
553        // fix): the ordinary return-from-`main()` path hangs on it. Once
554        // `axum::serve()` returns here, the `#[tokio::main]`-generated
555        // wrapper's own `Runtime` gets dropped as `serve()`'s `Ok(())`
556        // unwinds back through `main()`, and that drop blocks the whole
557        // process from ever actually exiting until every outstanding
558        // Windows blocking-pool wait completes - including that
559        // replacement's exit-watch, which by definition won't resolve
560        // until the replacement itself exits, i.e. for the rest of the
561        // dev session. The result: this process never actually terminates
562        // - it just stops serving and lingers as an invisible zombie,
563        // still holding the Windows Job Object it created to supervise
564        // *its own* handoff target (`lifecycle::supervisor`) open. If that
565        // zombie (or an earlier one in the same chain, or `xr dev` itself)
566        // is ever force-killed later, `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`
567        // cascades the kill down through every subsequent generation,
568        // taking out the *currently serving* process as collateral
569        // damage - this is what an earlier investigation session
570        // mistakenly diagnosed as "generation N vanished." Calling
571        // `std::process::exit` here - a real OS-level termination, no
572        // destructors, no waiting for anything - sidesteps that hang
573        // entirely; safe specifically because this whole method already
574        // only reaches this point after a real (not stuck) graceful
575        // drain, so there's nothing left this process still needs to do.
576        //
577        // Keyed on `handed_off_child` (set only on the `Handoff` arm
578        // above), **not** `is_dev_reload` - a real, previously-unfixed gap
579        // this comment used to describe as intentional ("a production app
580        // without the restart-admin-channel enabled never hands off a
581        // `Child` in the first place"), which conflated two different
582        // conditions: `is_dev_reload` (this process was spawned by `xr
583        // dev`) and "this process actually handed off a child that
584        // outlives it" (true whenever a `RESTART` command produces a
585        // successful handoff, via `xr dev` *or* `xr restart` against a
586        // plain production app with `GracefulShutdown { restart_channel:
587        // true, .. }` - the exact configuration `tests/
588        // stale_binary_path.rs`'s own fixture uses, confirmed to reproduce
589        // this exact hang before this fix). A `STOP` command or a plain
590        // OS shutdown signal never sets `handed_off_child`, so this stays
591        // a no-op for every path that never spawned a still-running
592        // child - the ordinary `Ok(())` return below is already correct
593        // for those. See `docs/GOTCHAS.md`.
594        if handed_off_child.load(Ordering::SeqCst) {
595            std::process::exit(0);
596        }
597
598        Ok(())
599    }
600}
601
602async fn health() -> Response {
603    // Laravel's built-in `/up` endpoint presents a deliberately small
604    // browser-friendly status page. Keep ours entirely self-contained: a
605    // health check should not depend on a CDN, font provider, database, or
606    // application template being available in order to report bootstrap
607    // success to a load balancer.
608    let html = r#"<!doctype html>
609<html lang="en">
610<head>
611  <meta charset="utf-8">
612  <meta name="viewport" content="width=device-width, initial-scale=1">
613  <title>Application</title>
614  <style>
615    :root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
616    body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f3f4f6; color: #111827; }
617    main { width: min(36rem, calc(100% - 3rem)); padding: 1.5rem; }
618    article { display: flex; gap: 1.25rem; align-items: flex-start; padding: 1.5rem; border-radius: .75rem; background: #fff; box-shadow: 0 20px 45px rgb(17 24 39 / .15); }
619    .status { position: relative; flex: 0 0 auto; width: .75rem; height: .75rem; margin-top: .38rem; border-radius: 999px; background: #4ade80; }
620    .status::before { content: ""; position: absolute; inset: 0; border-radius: inherit; background: #4ade80; animation: pulse 1.5s ease-out infinite; }
621    h1 { margin: 0; font-size: 1.25rem; }
622    p { margin: .5rem 0 0; color: #6b7280; font-size: .875rem; }
623    @keyframes pulse { from { transform: scale(1); opacity: .8; } to { transform: scale(2.4); opacity: 0; } }
624    @media (prefers-color-scheme: dark) { body { background: #111827; color: #f9fafb; } article { background: #1f2937; } p { color: #9ca3af; } }
625    @media (prefers-reduced-motion: reduce) { .status::before { animation: none; } }
626  </style>
627</head>
628<body>
629  <main>
630    <article role="status" aria-live="polite">
631      <span class="status" aria-hidden="true"></span>
632      <div>
633        <h1>Application up</h1>
634        <p>HTTP request received. Response rendered in <span id="response-time">--</span>.</p>
635      </div>
636    </article>
637  </main>
638  <script>
639    const responseTime = document.getElementById('response-time');
640    responseTime.textContent = `${Math.max(0, Math.round(performance.now()))}ms`;
641  </script>
642</body>
643</html>"#
644        .to_string();
645    (
646        StatusCode::OK,
647        [
648            (header::CONTENT_TYPE, "text/html; charset=utf-8"),
649            (header::CACHE_CONTROL, "no-store"),
650        ],
651        html,
652    )
653        .into_response()
654}
655
656thread_local! {
657    /// Set by `install_backtrace_capturing_panic_hook`'s own hook, read
658    /// (and cleared) by `handle_panic` right after - see that function's
659    /// own doc comment for why a thread-local is sound here despite
660    /// running on a shared tokio worker thread: nothing else can run on
661    /// this exact OS thread between the hook firing and `handle_panic`
662    /// reading it back, since `tower_http::catch_panic`'s own
663    /// `ResponseFuture` calls `handle_panic` *synchronously*, within the
664    /// very same `poll()` that caught the panic via `catch_unwind` -
665    /// there's no `.await` point, and therefore no scheduling opportunity
666    /// for the executor to run a *different* task on this thread, anywhere
667    /// in between.
668    static LAST_PANIC_BACKTRACE: std::cell::RefCell<Option<error::PanicBacktrace>> =
669        const { std::cell::RefCell::new(None) };
670}
671
672/// Installs a custom panic hook that captures a backtrace at the exact
673/// moment a panic happens, for `handle_panic` (below) to pick up and hand
674/// to `error::render_panic` - capturing *after* `std::panic::catch_unwind`
675/// returns (inside `handle_panic` itself) would be useless, since the stack
676/// has already unwound back up to `tower_http::catch_panic`'s own catching
677/// frame by then; a `Backtrace::capture()` taken there would just show
678/// *that* frame, not the real panic site several frames further down that
679/// no longer exist on the stack at all.
680///
681/// Guarded by `Once` so installing it is safe to call on every `serve()`
682/// (including more than one `Application` in the same process, e.g. in
683/// tests) without stacking an unbounded chain of hooks each wrapping the
684/// last - `std::panic::set_hook` replaces whatever hook is currently
685/// installed, so without this guard, a *second* `serve()` call would wrap
686/// an already-wrapped hook in another layer forever.
687///
688/// Calling `std::backtrace::Backtrace::capture()` unconditionally, on
689/// *every* panic regardless of debug mode, is deliberate and cheap: per
690/// its own documentation, it only actually walks the stack when
691/// `RUST_BACKTRACE`/`RUST_LIB_BACKTRACE` is set at all - otherwise this is
692/// just one cached atomic read, the identical cost Rust's own default
693/// panic hook already pays on every panic regardless of whether anything
694/// downstream of it cares. Production mode still never *shows* whatever
695/// was captured here (`render_panic` only renders it when `debug::
696/// is_enabled()`), so this adds no new information disclosure risk - only
697/// debug mode's own already-privileged detail gets an extra section.
698fn install_backtrace_capturing_panic_hook() {
699    static INSTALLED: std::sync::Once = std::sync::Once::new();
700    INSTALLED.call_once(|| {
701        let previous = std::panic::take_hook();
702        std::panic::set_hook(Box::new(move |info| {
703            use std::backtrace::{Backtrace, BacktraceStatus};
704            let backtrace = Backtrace::capture();
705            let captured = match backtrace.status() {
706                BacktraceStatus::Captured => error::PanicBacktrace::Captured(backtrace.to_string()),
707                BacktraceStatus::Unsupported => error::PanicBacktrace::Unsupported,
708                // `Disabled`, and any future non-exhaustive variant alike -
709                // the same "degrade to the always-safe default" precedent
710                // `logging::init`'s own unrecognized-`LOG_CHANNEL` handling
711                // already uses.
712                _ => error::PanicBacktrace::Disabled,
713            };
714            LAST_PANIC_BACKTRACE.with(|cell| *cell.borrow_mut() = Some(captured));
715            // Preserves whatever the previous hook did (Rust's own default -
716            // printing to stderr - unless something else already replaced
717            // it) - this hook adds a capture, it doesn't replace existing
718            // panic-reporting behavior.
719            previous(info);
720        }));
721    });
722}
723
724/// Converts a panicking handler into a response instead of dropping the
725/// connection with nothing - before this, a panic anywhere in a handler
726/// meant that one request just failed silently, with no framework-level
727/// response at all.
728fn handle_panic(payload: Box<dyn Any + Send + 'static>) -> Response {
729    // `downcast` (consuming) rather than `downcast_ref` + `.clone()` for the
730    // `String` case - avoids cloning a payload that's about to be dropped
731    // anyway; the panic path is cold, but there's no reason to allocate
732    // twice when ownership is right there.
733    let message = match payload.downcast::<String>() {
734        Ok(s) => *s,
735        Err(payload) => match payload.downcast_ref::<&str>() {
736            Some(s) => s.to_string(),
737            None => "unknown panic payload".to_string(),
738        },
739    };
740    // Falls back to `Disabled` if the hook never ran at all (e.g. a test
741    // that calls `handle_panic` directly without ever installing it) -
742    // the same safe default the hook itself falls back to for an
743    // unrecognized `BacktraceStatus`.
744    let backtrace = LAST_PANIC_BACKTRACE
745        .with(|cell| cell.borrow_mut().take())
746        .unwrap_or(error::PanicBacktrace::Disabled);
747    error::render_panic(&message, backtrace)
748}
749
750#[cfg(test)]
751mod tests {
752    use super::*;
753    use axum::body::Body;
754    use axum::http::{Request, StatusCode};
755    use axum::routing::get;
756    use tower::ServiceExt;
757
758    /// A unit test (not an integration test under `tests/`) specifically
759    /// because `handle_panic` is private - only code inside this crate can
760    /// reach it directly. This compiles to its own isolated test binary
761    /// (there are no other `src/`-local unit tests in this crate today),
762    /// so it doesn't race `debug::set()`'s `OnceLock` against the
763    /// `tests/error_response_*.rs` integration tests, which each run in
764    /// their own separate process anyway.
765    ///
766    /// Only covers the production-mode (default, unset) branch - flipping
767    /// to debug mode here would permanently commit this test binary's
768    /// `OnceLock` for any test added later in this file. The debug-mode
769    /// rendering path (the same `debug_page` helper `AppError::Internal`
770    /// already exercises in `tests/error_response_debug_mode.rs`) was
771    /// verified live against a real running app instead: a deliberately
772    /// panicking handler correctly rendered the panic message as HTML with
773    /// `APP_DEBUG=true`, and the server kept serving subsequent requests
774    /// afterward.
775    #[tokio::test]
776    async fn panicking_handler_is_caught_and_rendered_instead_of_dropping_the_connection() {
777        async fn always_panics() -> &'static str {
778            panic!("boom");
779        }
780
781        let router = Router::new()
782            .route("/panic", get(always_panics))
783            .layer(CatchPanicLayer::custom(handle_panic));
784
785        let response = router
786            .oneshot(Request::get("/panic").body(Body::empty()).unwrap())
787            .await
788            .unwrap();
789
790        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
791        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
792            .await
793            .unwrap();
794        let body = String::from_utf8(bytes.to_vec()).unwrap();
795        // No `error_pages::set()` call anywhere in this test binary, so
796        // this exercises (and pins) the built-in default page, not an
797        // app-registered override - see `error_pages::default_internal_html`.
798        assert_eq!(body, crate::default_internal_html());
799        assert!(
800            !body.contains("boom"),
801            "panic message must not leak: {body}"
802        );
803    }
804
805    #[tokio::test]
806    async fn laravel_style_health_handler_returns_a_status_page() {
807        let response = health().await;
808        assert_eq!(response.status(), StatusCode::OK);
809        assert_eq!(
810            response.headers().get(header::CONTENT_TYPE).unwrap(),
811            "text/html; charset=utf-8"
812        );
813        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
814            .await
815            .unwrap();
816        let body = String::from_utf8(body.to_vec()).unwrap();
817        assert!(body.contains("Application up"));
818        assert!(body.contains("HTTP request received. Response rendered in"));
819        assert!(body.contains("performance.now()"));
820    }
821
822    /// Exercises the exact `.fallback_service(ServeDir::new(...)
823    /// .not_found_service(...))` pattern `serve()` wires up - against a
824    /// `tempfile::tempdir()` rather than the real, hardcoded `"public"`
825    /// path (relative to the process's CWD, not something a unit test
826    /// should depend on), so this proves the underlying tower-http
827    /// integration behaves correctly without needing to touch the real
828    /// filesystem convention. Only covers the literal, byte-identical-path
829    /// case - see the comment above `fallback_service` in `serve()` for the
830    /// percent-encoded-path caveat this doesn't (and can't easily) pin
831    /// without depending on tower-http/axum internals more closely than a
832    /// unit test here should.
833    #[tokio::test]
834    async fn fallback_service_serves_static_files_but_registered_routes_still_win() {
835        let dir = tempfile::tempdir().unwrap();
836        std::fs::write(dir.path().join("logo.png"), b"fake-image-bytes").unwrap();
837        std::fs::write(
838            dir.path().join("app.js"),
839            b"real file, should lose to the route",
840        )
841        .unwrap();
842
843        async fn app_js_route() -> &'static str {
844            "handled by a registered route"
845        }
846
847        let router = Router::new()
848            .route("/app.js", get(app_js_route))
849            .fallback_service(
850                ServeDir::new(dir.path()).not_found_service(tower::service_fn(
851                    |_req: axum::extract::Request| async {
852                        Ok::<_, std::convert::Infallible>(AppError::NotFound.into_response())
853                    },
854                )),
855            );
856
857        // A path with no registered route, but a real file on disk, is
858        // served directly from that file.
859        let logo_response = router
860            .clone()
861            .oneshot(Request::get("/logo.png").body(Body::empty()).unwrap())
862            .await
863            .unwrap();
864        assert_eq!(logo_response.status(), StatusCode::OK);
865        let logo_bytes = axum::body::to_bytes(logo_response.into_body(), usize::MAX)
866            .await
867            .unwrap();
868        assert_eq!(logo_bytes, "fake-image-bytes".as_bytes());
869
870        // A path that exists as *both* a registered route and a real file
871        // is handled by the route - `fallback_service` is only ever
872        // consulted when nothing else matched.
873        let app_js_response = router
874            .clone()
875            .oneshot(Request::get("/app.js").body(Body::empty()).unwrap())
876            .await
877            .unwrap();
878        let app_js_bytes = axum::body::to_bytes(app_js_response.into_body(), usize::MAX)
879            .await
880            .unwrap();
881        assert_eq!(app_js_bytes, "handled by a registered route".as_bytes());
882
883        // A path matching neither a route nor a file now gets Larust's own
884        // styled 404 (via `AppError::NotFound`), not `ServeDir`'s bare,
885        // empty-body one - the real gap this whole change closes.
886        let missing_response = router
887            .oneshot(
888                Request::get("/does-not-exist.css")
889                    .body(Body::empty())
890                    .unwrap(),
891            )
892            .await
893            .unwrap();
894        assert_eq!(missing_response.status(), StatusCode::NOT_FOUND);
895        let missing_bytes = axum::body::to_bytes(missing_response.into_body(), usize::MAX)
896            .await
897            .unwrap();
898        assert_eq!(
899            String::from_utf8(missing_bytes.to_vec()).unwrap(),
900            crate::default_not_found_html()
901        );
902    }
903
904    /// Guards every test below that reads or sets `LOG_CHANNEL`/
905    /// `LARUST_STDIO_DETACHED` - real process-wide state, not per-test
906    /// isolated, which `cargo test`'s default parallel execution would
907    /// otherwise race (same reasoning, same `OnceLock`-backed `std::sync::
908    /// Mutex` pattern, as `dev_reload.rs`'s own `test_lock` - see that
909    /// module's doc comment for the fuller explanation of why a bare
910    /// `std::sync::Mutex` is fine here specifically because these tests
911    /// hold the guard across no `.await` point at all).
912    fn env_lock() -> &'static std::sync::Mutex<()> {
913        static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
914        LOCK.get_or_init(|| std::sync::Mutex::new(()))
915    }
916
917    #[test]
918    fn defaults_log_channel_to_file_when_stdio_is_detached_and_the_user_never_set_one() {
919        let _guard = env_lock()
920            .lock()
921            .unwrap_or_else(std::sync::PoisonError::into_inner);
922        std::env::remove_var("LOG_CHANNEL");
923        std::env::set_var(STDIO_DETACHED_ENV, "1");
924
925        let mut config = Config::from_value(&serde_json::json!({})).unwrap();
926        assert_eq!(
927            config.log_channel, "stdout",
928            "sanity check on Config's own default"
929        );
930        default_log_channel_to_file_if_stdio_detached(&mut config);
931        assert_eq!(config.log_channel, "file");
932
933        std::env::remove_var(STDIO_DETACHED_ENV);
934    }
935
936    /// The actual reason this checks the real environment instead of
937    /// trusting `config.log_channel` - see `default_log_channel_to_file_if_
938    /// stdio_detached`'s own doc comment. An explicit `LOG_CHANNEL=stdout`
939    /// happens to be the same string `Config`'s own default already
940    /// produces, but the user's explicit choice must still win.
941    #[test]
942    fn does_not_override_an_explicitly_set_log_channel_even_if_it_matches_the_default() {
943        let _guard = env_lock()
944            .lock()
945            .unwrap_or_else(std::sync::PoisonError::into_inner);
946        std::env::set_var("LOG_CHANNEL", "stdout");
947        std::env::set_var(STDIO_DETACHED_ENV, "1");
948
949        let mut config = Config::from_value(&serde_json::json!({})).unwrap();
950        default_log_channel_to_file_if_stdio_detached(&mut config);
951        assert_eq!(config.log_channel, "stdout");
952
953        std::env::remove_var("LOG_CHANNEL");
954        std::env::remove_var(STDIO_DETACHED_ENV);
955    }
956
957    #[test]
958    fn does_nothing_on_an_ordinary_boot_where_stdio_was_never_detached() {
959        let _guard = env_lock()
960            .lock()
961            .unwrap_or_else(std::sync::PoisonError::into_inner);
962        std::env::remove_var("LOG_CHANNEL");
963        std::env::remove_var(STDIO_DETACHED_ENV);
964
965        let mut config = Config::from_value(&serde_json::json!({})).unwrap();
966        default_log_channel_to_file_if_stdio_detached(&mut config);
967        assert_eq!(
968            config.log_channel, "stdout",
969            "an ordinary cargo run/xr dev boot must be completely unaffected"
970        );
971    }
972
973    #[test]
974    fn is_supported_session_driver_accepts_exactly_the_two_real_values() {
975        assert!(is_supported_session_driver("database"));
976        assert!(is_supported_session_driver("file"));
977    }
978
979    #[test]
980    fn is_supported_session_driver_rejects_a_laravel_value_this_framework_does_not_implement() {
981        // Real Laravel `SESSION_DRIVER` values this codebase deliberately
982        // doesn't support - see `larust_http::session`'s own module doc
983        // comment for why there's still no in-memory ("array") option even
984        // now that "file" is real.
985        for unsupported in ["array", "redis", "cookie", "memcached", "dynamodb"] {
986            assert!(
987                !is_supported_session_driver(unsupported),
988                "{unsupported:?} must not be treated as a supported driver"
989            );
990        }
991    }
992
993    #[test]
994    fn is_supported_session_driver_rejects_an_empty_or_typo_d_value() {
995        assert!(!is_supported_session_driver(""));
996        assert!(!is_supported_session_driver("Database")); // wrong case
997        assert!(!is_supported_session_driver("fiel")); // typo
998    }
999}