rustlavel 0.5.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
//! 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>,
    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())),
            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())),
            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,
        }
    }

    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>()`.
    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(mut self, plugin: impl Plugin) -> Self {
        let name = plugin.name();
        let mut setup =
            Setup { router: &mut self.router, config: &self.config, context: &mut self.context };
        Box::new(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.
        #[cfg(feature = "view")]
        if self.root.join(self.config.string("view.root", rustlavel_view::DEFAULT_ROOT)).is_dir() {
            let engine = crate::view::engine_from_config(&self.config, &self.root);
            self.context = Some(self.context.take().expect("context builder").state(engine));
        }

        let context = self.context.take().expect("context builder").build();
        (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);
                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(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());

        let (router, context) = self.finish();
        Server::new(router, context).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.
fn print_route_table(router: &Router) {
    let width = router.routes().iter().map(|r| r.pattern.len()).max().unwrap_or(4).max(4);

    println!("\n  {:<8}{:<width$}  NAME", "METHOD", "URI");
    for route in router.routes() {
        println!(
            "  {:<8}{:<width$}  {}",
            route.method.as_str(),
            route.pattern,
            route.name.as_deref().unwrap_or("")
        );
    }
    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())));
    }
}