Skip to main content

navree_http/
module.rs

1//! [`HttpModule`], the [`HttpServer`] provider and the `serve`, `routes`,
2//! `down` and `up` commands.
3
4use std::net::SocketAddr;
5use std::sync::Arc;
6
7use navree_config::{Config, ModuleBuilderConfigExt};
8use navree_kernel::{
9    AppContext, BoxError, BoxFuture, CommandSpec, ConfiguredModule, Factory, Injectable,
10    KernelError, Lifecycle, Module, ModuleBuilder, ProviderKey, Resolver,
11};
12use tokio::sync::watch;
13
14use crate::body::BodyError;
15use crate::declared::{AccessDeclarations, routes_and_mounts};
16use crate::extract::rejection;
17use crate::maintenance::{MaintenanceInfo, MaintenanceMode};
18use crate::mount::mount_table;
19use crate::{
20    AppError, HttpOptions, ModuleBuilderHttpExt, RouteErrors, RouteMeta, UrlSigner, build_router,
21    route_table,
22};
23
24/// The HTTP module: the server, default layer stack, JSON errors,
25/// controllers. Global; provides and exports [`HttpOptions`], [`HttpServer`]
26/// and [`UrlSigner`]; registers the commands `serve`, `routes`, `down` and
27/// `up`; and checks every route and every mount at boot (access
28/// declarations, duplicate routes, a mount's prefix and what it overlaps,
29/// missing authenticator or authorizer), before `serve` binds a port.
30///
31/// ```no_run
32/// use navree_http::{HttpModule, HttpOptions};
33/// use navree_kernel::Navree;
34///
35/// # fn main() -> Result<(), navree_kernel::BoxError> {
36/// Navree::app()
37///     .module(HttpModule::for_root(HttpOptions::default()))
38///     .run()
39/// # }
40/// ```
41///
42/// Used plainly (`.module(HttpModule)`) or through
43/// [`from_config`](HttpModule::from_config), it reads the `http`
44/// configuration section, so the app must include `ConfigModule`.
45#[derive(Clone, Copy, Debug, Default)]
46pub struct HttpModule;
47
48impl HttpModule {
49    /// The module with explicit options (configure it once, in the app root).
50    pub fn for_root(options: HttpOptions) -> impl Module {
51        ConfiguredModule::<HttpModule, _>::for_root(options, register)
52    }
53
54    /// The module configured from the `http` section of `Config` at boot.
55    pub fn from_config() -> impl Module {
56        ConfiguredModule::<HttpModule, HttpOptions>::from_config(register)
57    }
58}
59
60impl Module for HttpModule {
61    fn register(&self, m: &mut ModuleBuilder) {
62        register(m, None);
63    }
64}
65
66fn register(m: &mut ModuleBuilder, options: Option<HttpOptions>) {
67    m.global();
68    match options {
69        Some(options) => m.value(options),
70        None => m.config::<HttpOptions>(),
71    };
72    m.exports::<HttpOptions>()
73        .provider::<HttpServer>()
74        .exports::<HttpServer>()
75        .lifecycle::<HttpServer>()
76        .factory(
77            Factory::<UrlSigner>::new(|r: Resolver| async move {
78                let options = r.get::<HttpOptions>().await?;
79                let config = r.app().try_get::<Config>().await;
80                Ok(Arc::new(url_signer(&options, config.as_deref())))
81            })
82            .deps(vec![ProviderKey::of::<HttpOptions>()]),
83        )
84        .exports::<UrlSigner>()
85        .map_error::<rejection::JsonRejection>(|r| Some(r.to_app_error()))
86        .map_error::<rejection::FormRejection>(|r| Some(r.to_app_error()))
87        .map_error::<rejection::QueryRejection>(|r| Some(r.to_app_error()))
88        .map_error::<rejection::PathRejection>(|r| Some(r.to_app_error()))
89        .map_error::<rejection::ExtensionRejection>(|r| Some(r.to_app_error()))
90        .map_error::<rejection::MultipartRejection>(|r| Some(r.to_app_error()))
91        .map_error::<rejection::MultipartError>(|r| Some(r.to_app_error()))
92        .map_error::<rejection::WebSocketRejection>(|r| Some(r.to_app_error()))
93        .map_error::<BodyError>(|r| Some(AppError::rejection(r.status(), r.to_string())))
94        // What the routes and the mounts declare, for the boot checks that read every
95        // handler's access.
96        .contribute(AccessDeclarations::new(routes_and_mounts))
97        .command(CommandSpec::new(
98            "serve",
99            "Start the HTTP server ([--addr HOST:PORT])",
100            serve,
101        ))
102        .command(CommandSpec::new(
103            "routes",
104            "List every route with its access declaration ([--json])",
105            routes,
106        ))
107        .command(CommandSpec::new(
108            "down",
109            "Put the app into maintenance mode ([--retry SECS] [--message TEXT])",
110            down,
111        ))
112        .command(CommandSpec::new(
113            "up",
114            "Bring the app out of maintenance mode",
115            up,
116        ));
117}
118
119/// The signer for `http.signing_key`; else a key derived from the app key
120/// (`app.key`, i.e. `APP_KEY`), so signed URLs survive restarts; else a
121/// random per-process key.
122fn url_signer(options: &HttpOptions, config: Option<&Config>) -> UrlSigner {
123    let app_key = || config?.app_key().map(|key| key.expose().clone());
124    if let Some(key) = options.signing_key.as_ref().map(|k| k.expose().as_str())
125        && !key.is_empty()
126    {
127        return UrlSigner::new(key.as_bytes());
128    }
129    match app_key() {
130        Some(app_key) => UrlSigner::derived_from_app_key(&app_key),
131        None => {
132            tracing::debug!(
133                target: "navree::http",
134                "neither http.signing_key nor app.key is set; signed URLs use a random key and stop working after a restart"
135            );
136            let mut key = Vec::with_capacity(32);
137            key.extend_from_slice(uuid::Uuid::new_v4().as_bytes());
138            key.extend_from_slice(uuid::Uuid::new_v4().as_bytes());
139            UrlSigner::new(&key)
140        }
141    }
142}
143
144/// The HTTP server state shared by the commands and the pipeline: options,
145/// maintenance mode and the address `serve` is bound to.
146pub struct HttpServer {
147    options: Arc<HttpOptions>,
148    pub(crate) maintenance: Arc<MaintenanceMode>,
149    bound: watch::Sender<Option<SocketAddr>>,
150}
151
152impl HttpServer {
153    /// The HTTP options.
154    pub fn options(&self) -> &HttpOptions {
155        &self.options
156    }
157
158    /// The maintenance-mode state.
159    pub fn maintenance(&self) -> &MaintenanceMode {
160        &self.maintenance
161    }
162
163    /// The address `serve` listens on, while it runs.
164    pub fn local_addr(&self) -> Option<SocketAddr> {
165        *self.bound.borrow()
166    }
167
168    /// Waits until `serve` is listening and returns its address (useful with
169    /// `addr = "127.0.0.1:0"`).
170    pub async fn wait_bound(&self) -> SocketAddr {
171        let mut receiver = self.bound.subscribe();
172        loop {
173            if let Some(addr) = *receiver.borrow_and_update() {
174                return addr;
175            }
176            if receiver.changed().await.is_err() {
177                std::future::pending::<()>().await;
178            }
179        }
180    }
181
182    fn set_bound(&self, addr: Option<SocketAddr>) {
183        self.bound.send_replace(addr);
184    }
185}
186
187impl std::fmt::Debug for HttpServer {
188    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189        f.debug_struct("HttpServer")
190            .field("options", &self.options)
191            .field("local_addr", &self.local_addr())
192            .finish_non_exhaustive()
193    }
194}
195
196impl Injectable for HttpServer {
197    fn dependencies() -> Vec<ProviderKey> {
198        vec![ProviderKey::of::<HttpOptions>()]
199    }
200
201    fn construct(r: Resolver) -> BoxFuture<'static, Result<Self, KernelError>> {
202        Box::pin(async move {
203            let options = r.get::<HttpOptions>().await?;
204            if let Err(errors) = options.check() {
205                return Err(KernelError::Construction {
206                    provider: std::any::type_name::<HttpOptions>().to_owned(),
207                    source: errors.join("; ").into(),
208                });
209            }
210            Ok(Self {
211                maintenance: Arc::new(MaintenanceMode::new(options.maintenance_file.clone())),
212                options,
213                bound: watch::Sender::new(None),
214            })
215        })
216    }
217}
218
219/// Builds the router once at boot, so route mistakes fail the boot. Before that, a plugin's
220/// mapping of another crate's errors stops the boot too: only the app answers its errors.
221impl Lifecycle for HttpServer {
222    fn on_bootstrap(&self, ctx: AppContext) -> BoxFuture<'_, Result<(), BoxError>> {
223        Box::pin(async move {
224            let refused = crate::error::mappers_of_plugins(&ctx);
225            if !refused.is_empty() {
226                return Err(RouteErrors(refused).into());
227            }
228            build_router(&ctx).await.map(drop)
229        })
230    }
231}
232
233/// The value of `--name VALUE` (or `--name=VALUE`) in `args`.
234fn flag(args: &[String], name: &str) -> Result<Option<String>, BoxError> {
235    let mut iter = args.iter();
236    while let Some(arg) = iter.next() {
237        if arg == name {
238            return iter
239                .next()
240                .cloned()
241                .map(Some)
242                .ok_or_else(|| format!("{name} needs a value").into());
243        }
244        if let Some(value) = arg
245            .strip_prefix(name)
246            .and_then(|rest| rest.strip_prefix('='))
247        {
248            return Ok(Some(value.to_owned()));
249        }
250    }
251    Ok(None)
252}
253
254/// `serve [--addr HOST:PORT]`: serves until the app's shutdown token is
255/// cancelled, then drains in-flight requests for up to `shutdown_grace_secs`.
256async fn serve(ctx: AppContext, args: Vec<String>) -> Result<(), BoxError> {
257    let server = ctx.get::<HttpServer>().await?;
258    let addr = flag(&args, "--addr")?.unwrap_or_else(|| server.options().addr.clone());
259    let router = build_router(&ctx).await?;
260    let listener = tokio::net::TcpListener::bind(&addr)
261        .await
262        .map_err(|error| format!("cannot listen on {addr}: {error}"))?;
263    let local = listener.local_addr()?;
264    server.set_bound(Some(local));
265    tracing::info!(target: "navree::http", addr = %local, "listening on http://{local}");
266
267    let result = crate::serve(listener, router)
268        .options(server.options())
269        .with_graceful_shutdown(ctx.shutdown_token().cancelled_owned())
270        .await;
271    server.set_bound(None);
272    tracing::info!(target: "navree::http", "server stopped");
273    Ok(result?)
274}
275
276/// `routes [--json]`: prints the route table, mounts included.
277async fn routes(ctx: AppContext, args: Vec<String>) -> Result<(), BoxError> {
278    let routes = route_table(&ctx).await?;
279    let mounts = mount_table(&ctx);
280    if args.iter().any(|a| a == "--json") {
281        println!(
282            "{}",
283            serde_json::to_string_pretty(&routes_json(&routes, &mounts))?
284        );
285    } else {
286        print!("{}", render_routes(&routes, &mounts));
287    }
288    Ok(())
289}
290
291/// The route table as text columns: method, path, name, access, module.
292/// Mounts (method `*` or their methods, path `{prefix}/{*rest}`) are rows
293/// among the routes, and the count after them names them apart.
294pub(crate) fn render_routes(routes: &[RouteMeta], mounts: &[RouteMeta]) -> String {
295    let mut rows: Vec<[String; 5]> = routes
296        .iter()
297        .chain(mounts)
298        .map(|r| {
299            [
300                r.method.clone(),
301                r.full_path.clone(),
302                r.name.clone().unwrap_or_default(),
303                r.access.describe(),
304                r.module.unwrap_or("").to_owned(),
305            ]
306        })
307        .collect();
308    rows.sort_by(|a, b| (&a[1], &a[0]).cmp(&(&b[1], &b[0])));
309    let header = ["METHOD", "PATH", "NAME", "ACCESS", "MODULE"].map(str::to_owned);
310    let mut widths = header.clone().map(|h| h.len());
311    for row in &rows {
312        for (width, cell) in widths.iter_mut().zip(row) {
313            *width = (*width).max(cell.len());
314        }
315    }
316    let mut out = String::new();
317    for row in std::iter::once(&header).chain(&rows) {
318        let line: Vec<String> = row
319            .iter()
320            .zip(widths)
321            .map(|(cell, width)| format!("{cell:width$}"))
322            .collect();
323        out.push_str(line.join("  ").trim_end());
324        out.push('\n');
325    }
326    if mounts.is_empty() {
327        out.push_str(&format!("\n{} routes\n", routes.len()));
328    } else {
329        out.push_str(&format!(
330            "\n{} routes, {} mounts\n",
331            routes.len(),
332            mounts.len()
333        ));
334    }
335    out
336}
337
338/// The route table as JSON: the routes, then the mounts, each marked
339/// `"mount": true`.
340fn routes_json(routes: &[RouteMeta], mounts: &[RouteMeta]) -> serde_json::Value {
341    let mut listed: Vec<serde_json::Value> = routes.iter().map(route_json).collect();
342    listed.extend(mounts.iter().map(|mount| {
343        let mut json = route_json(mount);
344        if let Some(object) = json.as_object_mut() {
345            object.insert("mount".to_owned(), serde_json::Value::Bool(true));
346        }
347        json
348    }));
349    serde_json::Value::Array(listed)
350}
351
352/// One row of [`routes_json`].
353fn route_json(r: &RouteMeta) -> serde_json::Value {
354    serde_json::json!({
355        "method": r.method,
356        "path": r.full_path,
357        "name": r.name,
358        "access": r.access.describe(),
359        "module": r.module,
360        "handler": r.handler,
361        "throttle": r.throttle.map(|t| serde_json::json!({"limit": t.limit, "per_secs": t.per.as_secs_f64()})),
362        "timeout_ms": r.timeout.map(|t| t.as_millis() as u64),
363        "body_limit": r.body_limit,
364        "transactional": r.transactional,
365        "audit": r.audit_action,
366        "guards": r.guards.len(),
367        "page": r.kind == crate::RouteKind::Page,
368    })
369}
370
371/// `down [--retry SECS] [--message TEXT]`.
372async fn down(ctx: AppContext, args: Vec<String>) -> Result<(), BoxError> {
373    let server = ctx.get::<HttpServer>().await?;
374    let retry = flag(&args, "--retry")?
375        .map(|v| v.parse::<u64>())
376        .transpose()
377        .map_err(|_| "--retry must be a number of seconds")?;
378    let info = MaintenanceInfo {
379        time: Some(chrono::Utc::now().timestamp()),
380        retry,
381        message: flag(&args, "--message")?,
382    };
383    server.maintenance().down(info).await?;
384    println!(
385        "The application is in maintenance mode ({}).",
386        server.maintenance().path().display()
387    );
388    Ok(())
389}
390
391/// `up`.
392async fn up(ctx: AppContext, _args: Vec<String>) -> Result<(), BoxError> {
393    let server = ctx.get::<HttpServer>().await?;
394    server.maintenance().up().await?;
395    println!("The application is up.");
396    Ok(())
397}
398
399#[cfg(test)]
400mod tests {
401    use super::*;
402
403    fn args(list: &[&str]) -> Vec<String> {
404        list.iter().map(|s| (*s).to_owned()).collect()
405    }
406
407    #[test]
408    fn route_table_renders_sorted_aligned_columns() {
409        let route = |method: &str, path: &str, name: Option<&str>, public: bool| {
410            let mut meta = RouteMeta {
411                method: method.to_owned(),
412                full_path: path.to_owned(),
413                name: name.map(str::to_owned),
414                module: Some("DealsModule"),
415                ..RouteMeta::default()
416            };
417            meta.access.public = public;
418            if !public {
419                meta.access.roles = vec!["admin".to_owned()];
420            }
421            meta
422        };
423        let text = render_routes(
424            &[
425                route("POST", "/api/v1/deals", Some("deals.store"), false),
426                route("GET", "/api/v1/deals", None, true),
427                route("DELETE", "/api/v1/deals/{id}", None, false),
428            ],
429            &[],
430        );
431        let lines: Vec<&str> = text.lines().collect();
432        assert_eq!(
433            lines,
434            [
435                "METHOD  PATH                NAME         ACCESS       MODULE",
436                "GET     /api/v1/deals                    public       DealsModule",
437                "POST    /api/v1/deals       deals.store  roles:admin  DealsModule",
438                "DELETE  /api/v1/deals/{id}               roles:admin  DealsModule",
439                "",
440                "3 routes",
441            ]
442        );
443        let json = routes_json(&[route("GET", "/x", None, true)], &[]);
444        assert_eq!(json[0]["path"], "/x");
445        assert_eq!(json[0]["access"], "public");
446        assert_eq!(json[0]["handler"], serde_json::Value::Null);
447        let mut handled = route("GET", "/y", None, true);
448        handled.handler = Some("DealsController::index".to_owned());
449        assert_eq!(
450            routes_json(&[handled], &[])[0]["handler"],
451            "DealsController::index"
452        );
453        assert_eq!(json[0]["page"], false);
454        let mut page = route("GET", "/z", None, true);
455        page.kind = crate::RouteKind::Page;
456        assert_eq!(routes_json(&[page], &[])[0]["page"], true);
457    }
458
459    #[test]
460    fn mounts_are_listed_with_their_access_after_the_routes() {
461        let mut deals = RouteMeta {
462            method: "GET".into(),
463            full_path: "/api/v1/deals".into(),
464            module: Some("DealsModule"),
465            ..RouteMeta::default()
466        };
467        deals.access.public = true;
468        let mut khata = RouteMeta {
469            method: "*".into(),
470            full_path: "/khata/{*rest}".into(),
471            module: Some("LedgerModule"),
472            ..RouteMeta::default()
473        };
474        khata.access.authenticated = true;
475        let text = render_routes(std::slice::from_ref(&deals), std::slice::from_ref(&khata));
476        let rows: Vec<Vec<&str>> = text
477            .lines()
478            .map(|line| line.split_whitespace().collect())
479            .collect();
480        assert_eq!(rows[1], ["GET", "/api/v1/deals", "public", "DealsModule"]);
481        assert_eq!(rows[2], ["*", "/khata/{*rest}", "auth", "LedgerModule"]);
482        assert_eq!(text.lines().last(), Some("1 routes, 1 mounts"));
483        let json = routes_json(&[deals], &[khata]);
484        assert!(json[0].get("mount").is_none());
485        assert_eq!(
486            (json[1]["path"].as_str(), json[1]["mount"].as_bool()),
487            (Some("/khata/{*rest}"), Some(true))
488        );
489    }
490
491    #[test]
492    fn flags_accept_both_forms() {
493        assert_eq!(
494            flag(&args(&["--addr", "0.0.0.0:1"]), "--addr").unwrap(),
495            Some("0.0.0.0:1".to_owned())
496        );
497        assert_eq!(
498            flag(&args(&["--retry=5"]), "--retry").unwrap(),
499            Some("5".to_owned())
500        );
501        assert_eq!(flag(&args(&["--json"]), "--addr").unwrap(), None);
502        assert!(flag(&args(&["--addr"]), "--addr").is_err());
503    }
504}