rustlavel 0.9.1

A Laravel-inspired full-stack web framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! The application builder.

use rustlavel_core::{Config, Context, ContextBuilder, Result};
use rustlavel_http::plugin::{Plugin, Setup};
use rustlavel_http::{Files, Handler, Middleware, Request, Response, Router, Server, TestClient};
use std::path::PathBuf;

/// The entry point of every rustlavel application.
///
/// ```ignore
/// App::new()?
///     .routes(routes::web::routes)
///     .plugin(Telescope::default())
///     .serve()
///     .await
/// ```
pub struct App {
    router: Router,
    config: Config,
    context: Option<ContextBuilder>,
    /// Run once the listener has stopped and requests have drained.
    on_shutdown: Vec<rustlavel_http::OnShutdown>,
    root: PathBuf,
    public: Option<PathBuf>,
    /// Where the generated API document is served, when it is enabled.
    #[cfg(feature = "openapi")]
    openapi: Option<(rustlavel_openapi::Info, String)>,
    /// The migration list the CLI generated, so `rustlavel migrate` can run it.
    #[cfg(feature = "db")]
    migrations: Vec<&'static dyn rustlavel_db::Migration>,
    #[cfg(feature = "db")]
    seeders: Vec<&'static dyn rustlavel_db::Seeder>,
    #[cfg(feature = "queue")]
    queue: Option<std::sync::Arc<dyn rustlavel_queue::Queue>>,
    #[cfg(feature = "queue")]
    jobs: Option<std::sync::Arc<rustlavel_queue::JobRegistry>>,
    #[cfg(feature = "queue")]
    scheduler: Option<rustlavel_queue::Scheduler>,
}

impl App {
    /// Boot from the current directory: load `.env`, then `config/*.json`.
    pub fn new() -> Result<Self> {
        App::from_root(std::env::current_dir()?)
    }

    /// Boot from an explicit project root. Tests use this to point at a fixture.
    pub fn from_root(root: impl Into<PathBuf>) -> Result<Self> {
        let root = root.into();
        let config = rustlavel_core::boot(&root)?;
        let public = root.join("public");

        Ok(App {
            router: Router::new(),
            context: Some(Context::builder().config(config.clone())),
            on_shutdown: Vec::new(),
            config,
            public: public.is_dir().then_some(public),
            root,
            #[cfg(feature = "openapi")]
            openapi: None,
            #[cfg(feature = "db")]
            migrations: Vec::new(),
            #[cfg(feature = "db")]
            seeders: Vec::new(),
            #[cfg(feature = "queue")]
            queue: None,
            #[cfg(feature = "queue")]
            jobs: None,
            #[cfg(feature = "queue")]
            scheduler: None,
        })
    }

    /// Build an application with no filesystem behind it, for unit tests.
    pub fn bare() -> Self {
        let config = Config::with_defaults();
        App {
            router: Router::new(),
            context: Some(Context::builder().config(config.clone())),
            on_shutdown: Vec::new(),
            config,
            root: PathBuf::from("."),
            public: None,
            #[cfg(feature = "openapi")]
            openapi: None,
            #[cfg(feature = "db")]
            migrations: Vec::new(),
            #[cfg(feature = "db")]
            seeders: Vec::new(),
            #[cfg(feature = "queue")]
            queue: None,
            #[cfg(feature = "queue")]
            jobs: None,
            #[cfg(feature = "queue")]
            scheduler: None,
        }
    }

    /// Something the application registered with [`App::state`], before it
    /// runs. The console commands read the database this way.
    pub fn registered<T: Send + Sync + 'static>(&self) -> Option<&T> {
        self.context.as_ref().and_then(|builder| builder.registered::<T>())
    }

    pub fn config(&self) -> &Config {
        &self.config
    }

    pub fn root(&self) -> &std::path::Path {
        &self.root
    }

    #[cfg(feature = "db")]
    pub(crate) fn registered_migrations(&self) -> Vec<&'static dyn rustlavel_db::Migration> {
        self.migrations.clone()
    }

    #[cfg(feature = "db")]
    pub(crate) fn registered_seeders(&self) -> Vec<&'static dyn rustlavel_db::Seeder> {
        self.seeders.clone()
    }

    #[cfg(feature = "queue")]
    pub(crate) fn registered_queue(&self) -> Option<std::sync::Arc<dyn rustlavel_queue::Queue>> {
        self.queue.clone()
    }

    #[cfg(feature = "queue")]
    pub(crate) fn registered_jobs(&self) -> Option<std::sync::Arc<rustlavel_queue::JobRegistry>> {
        self.jobs.clone()
    }

    /// Takes the scheduler, because running it consumes it — and nothing else
    /// wants it afterwards.
    #[cfg(feature = "queue")]
    pub(crate) fn take_scheduler(&mut self) -> Option<rustlavel_queue::Scheduler> {
        self.scheduler.take()
    }

    /// Register routes — this is what loads `routes/web.rs`.
    pub fn routes(mut self, define: impl FnOnce(&mut Router)) -> Self {
        define(&mut self.router);
        self
    }

    /// Add middleware that runs for every request.
    pub fn middleware(mut self, middleware: impl Middleware) -> Self {
        self.router.middleware(middleware);
        self
    }

    /// Register a service that handlers resolve with `req.state::<T>()`.
    /// Run something on the way down, after in-flight requests have drained.
    ///
    /// What a service registered with a discovery server uses to say goodbye —
    /// the difference between a clean deploy and thirty seconds of requests
    /// routed to a process that has exited.
    ///
    /// ```ignore
    /// let registrar = Arc::new(Registrar::new(nodes, instance));
    /// Arc::clone(&registrar).start();
    ///
    /// app.on_shutdown(move || Box::pin(async move {
    ///     let _ = registrar.deregister().await;
    /// }))
    /// ```
    pub fn on_shutdown(
        mut self,
        work: impl FnOnce() -> rustlavel_http::BoxFuture<()> + Send + Sync + 'static,
    ) -> Self {
        self.on_shutdown.push(Box::new(work));
        self
    }

    pub fn state<T: Send + Sync + 'static>(mut self, value: T) -> Self {
        self.context = Some(self.context.take().expect("context builder").state(value));
        self
    }

    /// Enable an optional package.
    pub fn plugin(self, plugin: impl Plugin) -> Self {
        self.plugin_boxed(Box::new(plugin))
    }

    /// The same, for a plugin chosen at runtime.
    ///
    /// `plugin` takes a concrete type, which is right when `main.rs` names each
    /// one. An application that keeps its features in a list — a module per
    /// feature, registered by walking the list — has `Box<dyn Plugin>` instead,
    /// and had no way in.
    pub fn plugin_boxed(mut self, plugin: Box<dyn Plugin>) -> Self {
        let name = plugin.name();
        let mut setup =
            Setup { router: &mut self.router, config: &self.config, context: &mut self.context };
        plugin.register(&mut setup);
        rustlavel_core::debug!("plugin registered: {name}");
        self
    }

    /// Register the template engine, so handlers can call `req.view(...)`.
    #[cfg(feature = "view")]
    pub fn views(self, engine: rustlavel_view::Engine) -> Self {
        self.state(engine)
    }

    /// Serve a generated OpenAPI document, and a page that reads it.
    ///
    /// The document is built after every route is registered, which is why
    /// this records the intent rather than mounting immediately: a document
    /// generated now would describe an empty API.
    #[cfg(feature = "openapi")]
    pub fn openapi(mut self, info: rustlavel_openapi::Info) -> Self {
        self.openapi = Some((info, "/openapi.json".to_string()));
        self
    }

    /// Register the migrations `rustlavel migrate` should run.
    ///
    /// A compiled program cannot list a directory into types, so the CLI keeps
    /// this list generated beside the migration files: `database::migrations::all()`.
    #[cfg(feature = "db")]
    pub fn migrations(mut self, migrations: Vec<&'static dyn rustlavel_db::Migration>) -> Self {
        self.migrations = migrations;
        self
    }

    #[cfg(feature = "db")]
    pub fn seeders(mut self, seeders: Vec<&'static dyn rustlavel_db::Seeder>) -> Self {
        self.seeders = seeders;
        self
    }

    /// The queue `rustlavel queue:work` should drain.
    #[cfg(feature = "queue")]
    pub fn queue(mut self, queue: impl rustlavel_queue::Queue + 'static) -> Self {
        self.queue = Some(std::sync::Arc::new(queue));
        self
    }

    /// The registry that turns a job name back into something runnable.
    #[cfg(feature = "queue")]
    pub fn jobs(mut self, registry: rustlavel_queue::JobRegistry) -> Self {
        self.jobs = Some(std::sync::Arc::new(registry));
        self
    }

    #[cfg(feature = "queue")]
    pub fn schedule(mut self, scheduler: rustlavel_queue::Scheduler) -> Self {
        self.scheduler = Some(scheduler);
        self
    }

    /// Replace the default 404 handler.
    pub fn fallback(mut self, handler: impl Handler) -> Self {
        self.router.fallback(handler);
        self
    }

    /// Serve static files from a directory. `public/` is used automatically
    /// when it exists, so this is only needed for a different location.
    pub fn public(mut self, dir: impl Into<PathBuf>) -> Self {
        self.public = Some(dir.into());
        self
    }

    fn finish(mut self) -> (Router, Context) {
        // A health endpoint every deployment can rely on, unless the app
        // defined its own.
        if !self.router.routes().iter().any(|route| route.pattern == "/up") {
            self.router.get("/up", |_req: Request| async {
                Response::json(rustlavel_core::Json::object([("status", "ok".into())]))
            });
        }

        // Generated last but one, so the document sees the application's
        // routes and the health endpoint, but not the static-file fallback.
        #[cfg(feature = "openapi")]
        if let Some((info, path)) = self.openapi.take() {
            rustlavel_openapi::mount(&mut self.router, &info, &path);
        }

        // Static files answer only what no route claimed.
        if let Some(dir) = self.public.clone()
            && self.router.routes().iter().all(|route| route.pattern != "/{path:*}") {
                self.router.fallback(Files::new(dir));
            }

        // A `resources/views` directory is enough to turn views on, the way a
        // `public` directory turns on static files — **unless the application
        // built its own engine**. It used to register one either way, which
        // meant `.views(...)` silently did nothing for any application that had
        // a views directory, which is every application that has views. An
        // engine carrying a translator was replaced by one that could not
        // translate, and `@lang` rendered its keys.
        #[cfg(feature = "view")]
        if self.root.join(self.config.string("view.root", rustlavel_view::DEFAULT_ROOT)).is_dir()
            && !self
                .context
                .as_ref()
                .expect("context builder")
                .has_state::<rustlavel_view::Engine>()
        {
            let engine = crate::view::engine_from_config(&self.config, &self.root);
            self.context = Some(self.context.take().expect("context builder").state(engine));
        }

        // The named routes, for `@route` in a template and for a handler that
        // wants to send somebody to a route by name rather than by path.
        //
        // Registered here because this is the first moment both exist: the
        // router is complete, and the context has not been sealed. The engine
        // is handed the same table through a cell rather than a field, because
        // an application may have built its own engine with `.views(...)` long
        // before a single route was declared.
        let named = self.router.named_routes();
        self.context =
            Some(self.context.take().expect("context builder").state(named.clone()));

        let context = self.context.take().expect("context builder").build();

        #[cfg(feature = "view")]
        if let Some(engine) = context.state::<rustlavel_view::Engine>() {
            let _ = engine
                .routes_cell()
                .set(std::sync::Arc::new(crate::view::RouteTable::new(named)));
        }

        (self.router, context)
    }

    /// The application's entry point: serve, or run the command the CLI
    /// forwarded to this binary.
    ///
    /// `rustlavel route:list` cannot answer on its own — in a compiled language
    /// only the built application knows its routes — so the CLI re-invokes this
    /// binary with the command as an argument.
    pub async fn run(self) -> Result<()> {
        let args: Vec<String> = std::env::args().skip(1).collect();

        match args.first().map(String::as_str) {
            None | Some("serve") => self.serve().await,
            Some("route:list") => {
                // Finish first, so the listing includes the routes the
                // framework and any plugin add.
                let (router, _) = self.finish();
                print_route_table(&router, &args[1..]);
                Ok(())
            }
            // Everything else the CLI forwards is answered by the console,
            // which is where the commands needing the application itself live.
            Some(other) => {
                let rest: Vec<String> = args.iter().skip(1).cloned().collect();
                crate::console::Console::dispatch(self, other, &rest).await
            }
        }
    }

    /// Bind and serve until Ctrl-C.
    pub async fn serve(mut self) -> Result<()> {
        let host = self.config.string("server.host", "127.0.0.1");
        let port = self.config.int("server.port", 8000);
        let name = self.config.string("app.name", "Rustlavel");
        let environment = self.config.environment();

        rustlavel_core::info!("{name} [{environment}]");

        // Query bindings are what make a slow-query log useful, and also where
        // a password ends up. They stay out of the event stream in production.
        #[cfg(feature = "db")]
        rustlavel_db::set_log_bindings(!self.config.is_production());

        // Last, so the injector sees the response after every other middleware
        // has had its say; compression, if on, then applies to the tagged body.
        if crate::live_reload::requested(self.config.is_production()) {
            crate::live_reload::install(&mut self.router, &self.root);
            rustlavel_core::info!("live reload on");
        }

        let on_shutdown = std::mem::take(&mut self.on_shutdown);
        let (router, context) = self.finish();

        // Telemetry that is only sent on a timer loses its last few seconds at
        // exactly the moment somebody was watching — a restart. Flushed after
        // the requests have drained, so the lines about the drain go too.
        #[allow(unused_mut)]
        let mut flushes: Vec<rustlavel_http::OnShutdown> = Vec::new();
        #[cfg(feature = "search")]
        if let Some(shipper) = context.state::<rustlavel_search::LogShipper>() {
            let shipper = shipper.clone();
            flushes.push(Box::new(move || Box::pin(async move { shipper.shutdown().await })));
        }
        #[cfg(feature = "otel")]
        if let Some(exporter) = context.state::<rustlavel_otel::Exporter>() {
            let exporter = exporter.clone();
            flushes.push(Box::new(move || Box::pin(async move { exporter.shutdown().await })));
        }

        let mut server = Server::new(router, context);
        for work in on_shutdown.into_iter().chain(flushes) {
            server = server.on_shutdown(work);
        }
        server.listen(format!("{host}:{port}")).await
    }

    /// The finished router and context, for serving on a listener of the
    /// caller's own. Tests that need a real socket use this.
    pub fn take_parts(self) -> (Router, Context) {
        self.finish()
    }

    /// A test client for this application, without binding a port.
    pub fn test_client(self) -> TestClient {
        let (router, context) = self.finish();
        TestClient::new(router).with_context(context)
    }

    /// The routes as `rustlavel route:list` prints them.
    pub fn route_table(&self) -> Vec<(String, String, String)> {
        self.router
            .routes()
            .iter()
            .map(|route| {
                (
                    route.method.to_string(),
                    route.pattern.clone(),
                    route.name.clone().unwrap_or_default(),
                )
            })
            .collect()
    }
}

/// Print the route table, the way `php artisan route:list` does.
/// `route:list`, and the filters that make it readable past fifty routes.
///
/// An application of any size lists more than fits a screen, and the answer to
/// "where is the route for X" should not be piping this through `grep` — which
/// works, and loses the header row that says what the columns are.
///
/// ```text
/// route:list --path admin      only paths containing `admin`
/// route:list --method post     only POSTs (any case)
/// route:list --name auth       only named routes matching `auth`
/// ```
fn matching_routes<'a>(
    router: &'a Router,
    filters: &[String],
) -> Vec<&'a rustlavel_http::router::Route> {
    let value_of = |flag: &str| -> Option<String> {
        filters
            .iter()
            .position(|argument| argument == flag)
            .and_then(|at| filters.get(at + 1))
            .map(|value| value.to_lowercase())
    };

    let path = value_of("--path");
    let method = value_of("--method");
    let name = value_of("--name");

    router
        .routes()
        .iter()
        .filter(|route| {
            path.as_ref().is_none_or(|want| route.pattern.to_lowercase().contains(want))
                && method
                    .as_ref()
                    .is_none_or(|want| route.method.as_str().eq_ignore_ascii_case(want))
                && name.as_ref().is_none_or(|want| {
                    route.name.as_deref().is_some_and(|had| had.to_lowercase().contains(want))
                })
        })
        .collect()
}

fn print_route_table(router: &Router, filters: &[String]) {
    let value_of = |flag: &str| -> Option<String> {
        filters
            .iter()
            .position(|argument| argument == flag)
            .and_then(|at| filters.get(at + 1))
            .map(|value| value.to_lowercase())
    };

    let path = value_of("--path");
    let method = value_of("--method");
    let name = value_of("--name");

    let matching = matching_routes(router, filters);
    let _ = (&path, &method, &name);

    let width = matching.iter().map(|r| r.pattern.len()).max().unwrap_or(4).max(4);

    println!("\n  {:<8}{:<width$}  NAME", "METHOD", "URI");
    for route in &matching {
        println!(
            "  {:<8}{:<width$}  {}",
            route.method.as_str(),
            route.pattern,
            route.name.as_deref().unwrap_or("")
        );
    }

    // The count, and — when a filter hid some — what it hid, so a search that
    // finds nothing says so rather than printing an empty table.
    let total = router.routes().len();
    match matching.len() {
        0 => println!("\n  no route matches, out of {total}"),
        shown if shown == total => println!("\n  {shown} routes"),
        shown => println!("\n  {shown} of {total} routes"),
    }
    println!();
}

#[cfg(test)]
mod tests {
    use super::*;
    use rustlavel_core::Json;

    #[tokio::test]
    async fn serves_registered_routes() {
        let client = App::bare()
            .routes(|r| {
                r.get("/", |_req: Request| async { "home" });
            })
            .test_client();

        client.get("/").await.assert_ok().assert_see("home");
    }

    #[tokio::test]
    async fn adds_a_health_endpoint_by_default() {
        let client = App::bare().test_client();

        client.get("/up").await.assert_ok().assert_json("status", "ok");
    }

    #[tokio::test]
    async fn an_application_route_wins_over_the_default_health_endpoint() {
        let client = App::bare()
            .routes(|r| {
                r.get("/up", |_req: Request| async { "custom" });
            })
            .test_client();

        client.get("/up").await.assert_see("custom");
    }

    #[tokio::test]
    async fn state_is_resolvable_from_a_handler() {
        struct Greeting(&'static str);

        let client = App::bare()
            .state(Greeting("hello from state"))
            .routes(|r| {
                r.get("/", |req: Request| async move {
                    req.state::<Greeting>().unwrap().0.to_string()
                });
            })
            .test_client();

        client.get("/").await.assert_see("hello from state");
    }

    #[tokio::test]
    async fn a_plugin_can_add_routes_and_state() {
        struct Counter(usize);
        struct CounterPlugin;

        impl Plugin for CounterPlugin {
            fn name(&self) -> &'static str {
                "counter"
            }

            fn register(self: Box<Self>, setup: &mut Setup<'_>) {
                setup.state(Counter(7));
                setup.router.get("/counter", |req: Request| async move {
                    Json::object([("count", (req.state::<Counter>().unwrap().0 as i64).into())])
                });
            }
        }

        let client = App::bare().plugin(CounterPlugin).test_client();

        client.get("/counter").await.assert_ok().assert_json("count", 7);
    }

    #[test]
    fn route_table_lists_names() {
        let app = App::bare().routes(|r| {
            r.get("/users/{id}", |_req: Request| async { "u" }).name("users.show");
        });

        let table = app.route_table();
        assert!(table.contains(&("GET".into(), "/users/{id}".into(), "users.show".into())));
    }

    /// A hundred routes do not fit a screen, and `grep` loses the header.
    #[test]
    fn route_list_filters_by_path_method_and_name() {
        use rustlavel_http::router::Router;

        let mut router = Router::new();
        router.get("/admin/users", |_req: Request| async { "" }).name("admin.users");
        router.post("/admin/users", |_req: Request| async { "" });
        router.get("/login", |_req: Request| async { "" }).name("login");

        let matching = |filters: &[&str]| {
            let filters: Vec<String> = filters.iter().map(|f| f.to_string()).collect();
            super::matching_routes(&router, &filters)
                .iter()
                .map(|r| format!("{} {}", r.method.as_str(), r.pattern))
                .collect::<Vec<_>>()
        };

        assert_eq!(matching(&[]).len(), 3, "no filter lists everything");
        assert_eq!(matching(&["--path", "admin"]).len(), 2);
        assert_eq!(matching(&["--method", "POST"]), ["POST /admin/users"]);
        // Case does not matter: nobody remembers whether they typed `post`.
        assert_eq!(matching(&["--method", "post"]), ["POST /admin/users"]);
        assert_eq!(matching(&["--name", "login"]), ["GET /login"]);
        // Filters narrow together rather than replacing one another.
        assert_eq!(matching(&["--path", "admin", "--method", "get"]), ["GET /admin/users"]);
        assert!(matching(&["--path", "nowhere"]).is_empty());
    }
}