Skip to main content

rainier_framework/
bootstrap.rs

1//! Bootstrapping — [`Rainier`], the builder that assembles an application.
2//!
3//! Wiring a framework by hand means binding a dozen services in the right
4//! order before anything works. This builder does the parts every application
5//! wants the same way — environment, config, events, views, logging, the
6//! middleware registry, the facades — and leaves the parts that differ (the
7//! database, the queue driver, the routes) to explicit calls.
8
9use std::path::PathBuf;
10use std::sync::Arc;
11
12use rainier_cache::CacheManager;
13use rainier_config::{Config, Env};
14use rainier_container::{Application, ServiceProvider};
15use rainier_crypt::{Encryption, Key, KeyRing};
16use rainier_database::Database;
17use rainier_events::Dispatcher;
18use rainier_filesystem::Storage;
19use rainier_mail::Mailer;
20use rainier_middleware::MiddlewareRegistry;
21use rainier_queue::QueueManager;
22use rainier_routing::{Router, UrlGenerator};
23use rainier_server::Kernel;
24use rainier_session::{MemorySessionStore, SessionManager};
25use rainier_support::{Error, Result};
26use rainier_view::{BladeEngine, ViewEngine};
27
28use crate::facades::Views;
29use crate::keys;
30
31/// Assembles an [`Application`].
32///
33/// ```no_run
34/// use rainier_framework::Rainier;
35///
36/// # #[tokio::main] async fn main() -> rainier_support::Result<()> {
37/// let app = Rainier::new(".")
38///     .with_routes(|router| {
39///         router.get("/", || async { "Hello from Rainier" });
40///     })
41///     .boot()
42///     .await?;
43/// # let _ = app;
44/// # Ok(()) }
45/// ```
46pub struct Rainier {
47    base_path: PathBuf,
48    env: Env,
49    config: Config,
50    /// A configuration error from [`Rainier::new`], surfaced by
51    /// [`boot`](Rainier::boot).
52    ///
53    /// `new` cannot return a `Result` without putting a `?` in the middle of
54    /// every builder chain, and an unreadable `CACHE_DRIVER` must not be
55    /// swallowed. So it waits here.
56    deferred: Option<Error>,
57    events: Dispatcher,
58    middleware: MiddlewareRegistry,
59    router: Router,
60    views: Option<Arc<dyn ViewEngine>>,
61    database: Option<Database>,
62    queue: Option<QueueManager>,
63    mailer: Option<Mailer>,
64    sessions: Option<SessionManager>,
65    crypt: Option<Encryption>,
66    cache: Option<CacheManager>,
67    notifier: Option<rainier_notify::Notifier>,
68    broadcasting: Option<rainier_broadcast::Broadcasting>,
69    websockets: Option<rainier_websocket::WebSocketRoutes>,
70    /// Values bound as-is, in declaration order.
71    #[allow(clippy::type_complexity, reason = "one boxed closure per bound value")]
72    instances: Vec<Box<dyn Fn(&Application)>>,
73    schedule: Option<rainier_scheduler::Schedule>,
74    storage: Option<Storage>,
75    providers: Vec<Arc<dyn ServiceProvider>>,
76    install_facades: bool,
77    install_tracing: bool,
78}
79
80impl Rainier {
81    /// Start from `base_path`, reading `.env` from it if there is one.
82    ///
83    /// Infallible so the builder chain reads as one expression. A driver name
84    /// the environment got wrong is held in `deferred` and returned from
85    /// [`boot`](Self::boot) — the error still stops the application, it just
86    /// does not force a `?` into the middle of the chain.
87    pub fn new(base_path: impl Into<PathBuf>) -> Self {
88        let base_path = base_path.into();
89        let env = Env::load_or_default(base_path.join(".env"));
90        let (config, deferred) = match default_config(&env, &base_path) {
91            Ok(config) => (config, None),
92            // Carry on with an empty tree so `with_*` calls still apply; `boot`
93            // returns the error before any of it is used.
94            Err(e) => (Config::new(), Some(e)),
95        };
96
97        Self {
98            base_path,
99            env,
100            config,
101            deferred,
102            events: Dispatcher::new(),
103            middleware: default_middleware(),
104            router: Router::new(),
105            views: None,
106            database: None,
107            queue: None,
108            mailer: None,
109            sessions: None,
110            crypt: None,
111            cache: None,
112            notifier: None,
113            broadcasting: None,
114            websockets: None,
115            instances: Vec::new(),
116            schedule: None,
117            storage: None,
118            providers: Vec::new(),
119            install_facades: true,
120            install_tracing: true,
121        }
122    }
123
124    /// The environment, for reading deployment values while building.
125    pub fn env(&self) -> &Env {
126        &self.env
127    }
128
129    /// The configuration, for adding to it while building.
130    pub fn config(&self) -> &Config {
131        &self.config
132    }
133
134    /// Adjust the configuration.
135    pub fn configure(self, adjust: impl FnOnce(&Config)) -> Self {
136        adjust(&self.config);
137        self
138    }
139
140    /// Register event listeners.
141    pub fn with_events(self, register: impl FnOnce(&Dispatcher)) -> Self {
142        register(&self.events);
143        self
144    }
145
146    /// Register middleware aliases and groups.
147    pub fn with_middleware(self, register: impl FnOnce(&MiddlewareRegistry)) -> Self {
148        register(&self.middleware);
149        self
150    }
151
152    /// Declare routes.
153    pub fn with_routes(mut self, declare: impl FnOnce(&mut Router)) -> Self {
154        declare(&mut self.router);
155        self
156    }
157
158    /// Use a specific view engine. Defaults to a [`BladeEngine`] over
159    /// `<base>/resources/views`.
160    pub fn with_views(mut self, engine: Arc<dyn ViewEngine>) -> Self {
161        self.views = Some(engine);
162        self
163    }
164
165    /// Use this database.
166    pub fn with_database(mut self, database: Database) -> Self {
167        self.database = Some(database);
168        self
169    }
170
171    /// Use this queue.
172    pub fn with_queue(mut self, queue: QueueManager) -> Self {
173        self.queue = Some(queue);
174        self
175    }
176
177    /// Use this mailer.
178    pub fn with_mailer(mut self, mailer: Mailer) -> Self {
179        self.mailer = Some(mailer);
180        self
181    }
182
183    /// Use this session store, and register the `session` middleware alias.
184    ///
185    /// Without this, sessions default to an in-process store — right for
186    /// development and wrong the moment there are two instances. See
187    /// [`SessionManager`].
188    pub fn with_sessions(mut self, sessions: SessionManager) -> Self {
189        self.sessions = Some(sessions);
190        self
191    }
192
193    /// Use this cache.
194    ///
195    /// Defaults to an in-process one, which is right for development and wrong
196    /// the moment a second instance exists — see [`CacheManager`].
197    pub fn with_cache(mut self, cache: CacheManager) -> Self {
198        self.cache = Some(cache);
199        self
200    }
201
202    /// Use these notification channels.
203    ///
204    /// Without it, notifications go to the log — which delivers nothing, and is
205    /// the right thing to have by accident: a misconfigured deployment logs
206    /// them rather than emailing real people from a copy of production data.
207    ///
208    /// ```ignore
209    /// Rainier::new(".").with_notifier(
210    ///     Notifier::new()
211    ///         .with(MailChannel::new(mailer))
212    ///         .with(DatabaseChannel::new(database)),
213    /// )
214    /// ```
215    pub fn with_notifier(mut self, notifier: rainier_notify::Notifier) -> Self {
216        self.notifier = Some(notifier);
217        self
218    }
219
220    /// Use this broadcast driver.
221    ///
222    /// Without it, broadcasts go to the log — they reach no browser, which is
223    /// the right accident to have: an application that has not configured a
224    /// relay logs what it would have published instead of failing requests.
225    ///
226    /// The **channel table** is not set here, because it is generic over your
227    /// user model. Bind a `ChannelRegistry<User>` in a provider; until you do,
228    /// every private channel is denied.
229    ///
230    /// ```ignore
231    /// Rainier::new(".").with_broadcasting(Broadcasting::new(Arc::new(
232    ///     RedisBroadcaster::connect(&connector).await?.with_pusher_auth(auth),
233    /// )))
234    /// ```
235    pub fn with_broadcasting(mut self, broadcasting: rainier_broadcast::Broadcasting) -> Self {
236        self.broadcasting = Some(broadcasting);
237        self
238    }
239
240    /// Serve these WebSocket routes.
241    ///
242    /// On the **same port** as HTTP: a socket connection begins as a `GET`
243    /// asking to upgrade, so there is no second listener to start and nothing
244    /// to run alongside anything.
245    ///
246    /// ```ignore
247    /// Rainier::new(".").with_websockets(
248    ///     WebSocketRoutes::new().add("/ws/rooms/{room}", Chat::new(rooms)),
249    /// )
250    /// ```
251    pub fn with_websockets(mut self, routes: rainier_websocket::WebSocketRoutes) -> Self {
252        self.websockets = Some(routes);
253        self
254    }
255
256    /// Bind a value you already have.
257    ///
258    /// The gap the typed `with_*` methods leave: an application often holds
259    /// something the framework has never heard of — a
260    /// [`Rooms`](rainier_websocket::Rooms) registry, a feature-flag client, an
261    /// HTTP client with a pool — and it needs to be resolvable without a
262    /// provider whose whole body is one `instance` call.
263    ///
264    /// A provider is still the right answer when the value has to be *built*
265    /// from other bound services; this is for one that already exists.
266    pub fn with_instance<T: Send + Sync + 'static>(mut self, value: T) -> Self {
267        let value = Arc::new(value);
268        self.instances.push(Box::new(move |app| app.instance_arc(Arc::clone(&value))));
269        self
270    }
271
272    /// Bind something already shared, keeping your handle to it.
273    pub fn with_instance_arc<T: Send + Sync + 'static>(mut self, value: Arc<T>) -> Self {
274        self.instances.push(Box::new(move |app| app.instance_arc(Arc::clone(&value))));
275        self
276    }
277
278    /// Declare the scheduled tasks.
279    ///
280    /// ```ignore
281    /// Rainier::new(".").with_schedule(routes::console::schedule)
282    /// ```
283    ///
284    /// Bound in the container, so `schedule:run` and `schedule:list` find it.
285    pub fn with_schedule(mut self, declare: impl FnOnce(&mut rainier_scheduler::Schedule)) -> Self {
286        let mut schedule = self.schedule.take().unwrap_or_default();
287        declare(&mut schedule);
288        self.schedule = Some(schedule);
289        self
290    }
291
292    /// Use this file storage.
293    ///
294    /// Defaults to `<base>/storage/app`, so `Storage::instance()` works on a
295    /// fresh clone without configuration.
296    pub fn with_storage(mut self, storage: Storage) -> Self {
297        self.storage = Some(storage);
298        self
299    }
300
301    /// Use these keys for encryption and signing.
302    ///
303    /// Defaults to `APP_KEY` from the environment. With neither, a random key
304    /// is generated per boot — which works, and silently invalidates every
305    /// encrypted value the last boot produced, so it warns.
306    pub fn with_encryption(mut self, crypt: Encryption) -> Self {
307        self.crypt = Some(crypt);
308        self
309    }
310
311    /// Register a service provider.
312    pub fn with_provider(mut self, provider: impl ServiceProvider) -> Self {
313        self.providers.push(Arc::new(provider));
314        self
315    }
316
317    /// Do not install the facades' global application.
318    ///
319    /// Two applications in one process would otherwise fight over it — which
320    /// is exactly what a test suite building an app per test does.
321    pub fn without_facades(mut self) -> Self {
322        self.install_facades = false;
323        self
324    }
325
326    /// Do not install a tracing subscriber.
327    pub fn without_tracing(mut self) -> Self {
328        self.install_tracing = false;
329        self
330    }
331
332    /// Build and boot the application.
333    ///
334    /// Compiling the router here is what makes an unknown middleware alias or
335    /// a duplicate route name a **boot** failure rather than a surprise on the
336    /// first request that hits it.
337    pub async fn boot(self) -> Result<Arc<Application>> {
338        // Before anything is installed, and before tracing: a `.env` the
339        // process cannot read is not a state to start serving in.
340        if let Some(error) = self.deferred {
341            return Err(error);
342        }
343
344        if self.install_tracing {
345            install_tracing(&self.env, &self.config);
346        }
347
348        let environment = self.config.get(keys::APP_ENV).unwrap_or_default().to_string();
349        let app = Arc::new(Application::new(self.base_path.clone()).with_environment(&environment));
350
351        // Installed *before* anything else runs, not at the end. A service
352        // provider's `boot`, and a middleware alias factory resolved while the
353        // router compiles, both legitimately reach for a facade — and both
354        // happen during this call. Installing last would make them panic.
355        if self.install_facades {
356            rainier_container::set_facade_application(Arc::clone(&app));
357        }
358
359        let views = self.views.unwrap_or_else(|| {
360            Arc::new(BladeEngine::new(self.base_path.join("resources").join("views")))
361        });
362
363        let crypt = self.crypt.unwrap_or_else(|| Encryption::from_keys(app_keys(&self.env)));
364        let sessions = self
365            .sessions
366            .unwrap_or_else(|| SessionManager::new(Arc::new(MemorySessionStore::default())));
367
368        app.instance(self.config);
369        app.instance(self.env);
370        app.instance(self.events);
371        app.instance(Views::new(views));
372        app.instance(crypt);
373        app.instance(sessions);
374        // Nobody handed one over, so this is the in-process default. If the
375        // configuration asked for Redis, that is a gap between what the
376        // deployment believes and what it has — and the symptom otherwise is a
377        // rate limiter that counts to `N ×` its limit with nothing logged.
378        let cache = match self.cache {
379            Some(cache) => cache,
380            None => {
381                if let Ok(driver) = app.resolve::<Config>()?.setting(keys::CACHE_DRIVER) {
382                    if driver.is_shared() {
383                        tracing::warn!(
384                            configured = %driver,
385                            "CACHE_DRIVER asks for a shared cache but none was built, so \
386                             this process is using the in-process one — locks, rate limits \
387                             and anything else cached for correctness are per-instance. \
388                             Build the store and pass it to `Rainier::with_cache`."
389                        );
390                    }
391                }
392                CacheManager::memory()
393            }
394        };
395
396        // The locks behind `without_overlapping` and `on_one_server` — and
397        // anything else that needs one. Bound from the same cache the
398        // application uses, so "shared" means the same thing for both.
399        app.instance(rainier_cache::LockManager::new(Arc::clone(cache.store())));
400        app.instance(cache);
401
402        // An empty schedule, so `schedule:list` and `schedule:run` work on a
403        // fresh clone. An application replaces it in a provider.
404        app.instance(self.schedule.unwrap_or_default());
405
406        // Whatever the application handed over, before the providers run so
407        // one of them can resolve it.
408        for bind in self.instances {
409            bind(&app);
410        }
411
412        // No socket routes unless the application declares some, and an
413        // upgrade then falls through to the router like any other GET.
414        app.instance(self.websockets.unwrap_or_default());
415
416        // Broadcasts default to the log, for the same reason notifications do
417        // — except the risk here is the reverse one: publishing a private
418        // channel to a relay the application never meant to reach.
419        app.instance(self.broadcasting.unwrap_or_else(rainier_broadcast::Broadcasting::log));
420
421        // Notifications default to the log channel. Not to mail: a default that
422        // can reach a real person is a default that reaches one from staging.
423        app.instance(
424            self.notifier.unwrap_or_else(|| {
425                rainier_notify::Notifier::new().with(rainier_notify::LogChannel)
426            }),
427        );
428        app.instance(
429            self.storage
430                .unwrap_or_else(|| Storage::local(self.base_path.join("storage").join("app"))),
431        );
432
433        if let Some(database) = self.database {
434            app.instance(database);
435        }
436        if let Some(queue) = self.queue {
437            // Given the same locks as everything else, so `unique_id` is
438            // enforced against the cache the application actually shares.
439            // Without this a job declaring one is dispatched anyway, with a
440            // warning — degraded rather than silently broken.
441            app.instance(queue.with_locks(rainier_cache::LockManager::new(Arc::clone(
442                app.resolve::<CacheManager>()?.store(),
443            ))));
444        }
445        if let Some(mailer) = self.mailer {
446            app.instance(mailer);
447        }
448
449        // Providers register before the router compiles, so a middleware that
450        // resolves a service gets one a provider bound.
451        for provider in self.providers {
452            app.register_arc(provider)?;
453        }
454
455        // Compiled once and shared: the kernel serves it, and the container
456        // holds the same table so `route:list` can describe what is actually
457        // being served rather than a second compilation of it.
458        //
459        // This is also where every `resolved`/`deferred` middleware stage is
460        // built, which is why it happens after the providers and before the
461        // server starts.
462        let compiled = Arc::new(self.router.compile(&app)?);
463        let urls = UrlGenerator::from_routes(compiled.named_routes())
464            .with_base(app.resolve::<Config>()?.get_or(keys::APP_URL, String::new()));
465
466        let mut global = self.middleware.global_stack(&app)?;
467        let settings = app.resolve::<Config>()?;
468
469        // Outside everything the application registered, so it compresses
470        // whatever any of it produced.
471        if settings.get_or(keys::SERVER_COMPRESSION, false) {
472            global.insert(0, Arc::new(rainier_middleware::Compress::new()));
473        }
474
475        // Outside even that: a timeout that sits inside the throttle cannot
476        // cancel time spent in the throttle.
477        let timeout_secs = settings.get_or(keys::SERVER_REQUEST_TIMEOUT_SECS, 0u64);
478        if timeout_secs > 0 {
479            global.insert(0, Arc::new(rainier_middleware::Timeout::seconds(timeout_secs)));
480        }
481
482        let kernel = Kernel::from_shared(Arc::clone(&compiled), global)
483            .with_debug(app.resolve::<Config>()?.get_or(keys::APP_DEBUG, false));
484
485        app.instance_arc(compiled);
486        app.instance(urls);
487        app.instance(self.middleware);
488        app.instance(kernel);
489
490        app.boot().await?;
491
492        // Last, because a provider's `boot` can still add scheduled tasks. A
493        // task declaring `on_one_server` over an in-process lock is a
494        // guarantee that is not one, and every process gets told — but only
495        // `schedule:run` refuses, because that is the one whose guarantees are
496        // at stake. A web container refusing to serve HTTP over a scheduling
497        // concern would be a larger outage than the one being prevented.
498        crate::scheduling::warn_if_locks_are_not_shared(&app);
499
500        Ok(app)
501    }
502}
503
504/// The configuration every application starts with, read from the environment.
505///
506/// Fails only on a driver name outside its [closed
507/// set](rainier_support::Setting) — `QUEUE_DRIVER=databse` is a deployment
508/// mistake, and running on the default instead of the driver somebody asked for
509/// is not a recovery. Everything else here has a total parse: a `SERVER_PORT`
510/// that is not a number falls back, because the alternative is refusing to boot
511/// over a trailing space.
512fn default_config(env: &Env, base_path: &std::path::Path) -> Result<Config> {
513    let config = Config::new();
514
515    config.set(keys::APP_NAME, env.string("APP_NAME", "Rainier"))?;
516    config.set(keys::APP_ENV, env.setting("APP_ENV")?)?;
517    config.set(keys::APP_DEBUG, env.bool("APP_DEBUG", false))?;
518    config.set(keys::APP_URL, env.string("APP_URL", "http://localhost:8000"))?;
519    // A closed set, like the drivers: `LOG_FORMAT=jsn` on a production box
520    // would otherwise log prose into something that wanted objects, and say
521    // nothing.
522    config.set(keys::LOG_FORMAT, env.setting("LOG_FORMAT")?)?;
523    config.set(keys::APP_BASE_PATH, base_path.to_string_lossy().into_owned())?;
524
525    config.set(keys::SERVER_HOST, env.string("SERVER_HOST", "127.0.0.1"))?;
526    config.set(keys::SERVER_PORT, env.int("SERVER_PORT", 8000) as u16)?;
527    config.set(keys::SERVER_MAX_BODY_BYTES, env.int("SERVER_MAX_BODY", 2 * 1024 * 1024) as u64)?;
528    config.set(
529        keys::SERVER_REQUEST_TIMEOUT_SECS,
530        env.int("SERVER_REQUEST_TIMEOUT", 0).max(0) as u64,
531    )?;
532    config.set(keys::SERVER_COMPRESSION, env.bool("SERVER_COMPRESSION", false))?;
533
534    config.set(keys::DATABASE_URL, env.string("DATABASE_URL", "sqlite::memory:"))?;
535
536    config.set(keys::CACHE_DRIVER, env.setting("CACHE_DRIVER")?)?;
537    config.set(keys::CACHE_REDIS_URL, env.string("REDIS_URL", "redis://127.0.0.1:6379/"))?;
538    config.set(keys::CACHE_MEMCACHED_URL, env.string("MEMCACHED_URL", "127.0.0.1:11211"))?;
539
540    config.set(keys::SESSION_DRIVER, env.setting("SESSION_DRIVER")?)?;
541    config.set(keys::SESSION_LIFETIME, env.int("SESSION_LIFETIME", 7200))?;
542    config.set(keys::SESSION_COOKIE, env.string("SESSION_COOKIE", "rainier_session"))?;
543    config.set(keys::SESSION_SECURE, env.bool("SESSION_SECURE", false))?;
544
545    config.set(keys::QUEUE_DRIVER, env.setting("QUEUE_DRIVER")?)?;
546    config.set(keys::QUEUE_DEFAULT, env.string("QUEUE_DEFAULT", "default"))?;
547
548    config.set(keys::MAIL_DRIVER, env.setting("MAIL_DRIVER")?)?;
549    config.set(keys::MAIL_FROM_ADDRESS, env.string("MAIL_FROM", "hello@example.com"))?;
550    config.set(keys::MAIL_FROM_NAME, env.string("MAIL_FROM_NAME", "Rainier"))?;
551
552    Ok(config)
553}
554
555/// The keys encryption and signing use.
556///
557/// `APP_KEY` is the current key; `APP_PREVIOUS_KEYS` is a comma-separated list
558/// of retired ones, still needed to read what they wrote. See
559/// [`rainier_crypt`].
560fn app_keys(env: &Env) -> KeyRing {
561    let previous: Vec<String> =
562        env.get("APP_PREVIOUS_KEYS").unwrap_or_default().split(',').map(str::to_string).collect();
563
564    match env.get("APP_KEY").filter(|key| !key.trim().is_empty()) {
565        Some(key) => match KeyRing::from_base64(&key, &previous) {
566            Ok(ring) => ring,
567            Err(e) => {
568                // Falling back to a random key would "work" and quietly make
569                // every existing encrypted value unreadable, so say plainly
570                // what is wrong instead of hiding it in a decrypt failure
571                // three screens later.
572                tracing::error!(
573                    error = %e.message(),
574                    "APP_KEY is not usable; generating a temporary key. Encrypted values \
575                     written before this boot cannot be read, and values written now cannot \
576                     be read after a restart."
577                );
578                KeyRing::new(Key::generate())
579            }
580        },
581        None => {
582            tracing::warn!(
583                "APP_KEY is not set; generating a temporary key. Set one with \
584                 `APP_KEY={}` or nothing encrypted will survive a restart.",
585                Key::generate().to_base64()
586            );
587            KeyRing::new(Key::generate())
588        }
589    }
590}
591
592/// The middleware every application starts with.
593///
594/// Only the input normalisers are **global**, because they are the ones whose
595/// absence produces confusing bugs rather than missing features. Everything
596/// else is registered as an **alias** and opted into per route, since applying
597/// CORS, throttling, sessions or authentication everywhere by default is
598/// nearly always wrong.
599fn default_middleware() -> MiddlewareRegistry {
600    let registry = MiddlewareRegistry::new();
601
602    // Input normalisation only. Everything else — CORS, throttling, sessions,
603    // authentication — is opted into per route or per group, because applying
604    // any of it everywhere by default is how an API ends up allocating session
605    // rows nobody reads.
606    //
607    // The groups Rainier ships are functions in [`crate::groups`], not entries
608    // here: there is nothing to look them up by.
609    registry.global(crate::groups::normalise_input());
610
611    registry
612}
613
614fn install_tracing(env: &Env, config: &Config) {
615    let environment = config.get(keys::APP_ENV).unwrap_or_default().to_string();
616
617    // A second subscriber would panic, and an application that installs its
618    // own should keep it — so a failure here is expected and ignored.
619    crate::observability::TelemetrySettings::from_config(config)
620        .install_logging(&environment, &env.string("RUST_LOG", "info"));
621}
622
623#[cfg(test)]
624mod tests {
625    use super::*;
626    use crate::groups;
627    use rainier_http::{Method, Request, StatusCode};
628    use rainier_session::SessionRequestExt as _;
629    use rainier_session::StartSession;
630
631    async fn app() -> Arc<Application> {
632        Rainier::new(".")
633            .without_facades()
634            .without_tracing()
635            .with_routes(|router| {
636                router.get("/", || async { "home" }).name("home");
637                router.get("/posts/{post}", || async { "post" }).name("posts.show");
638            })
639            .boot()
640            .await
641            .expect("boots")
642    }
643
644    #[tokio::test]
645    async fn booting_binds_the_core_services() {
646        let app = app().await;
647
648        assert!(app.resolve::<Config>().is_ok());
649        assert!(app.resolve::<Dispatcher>().is_ok());
650        assert!(app.resolve::<Views>().is_ok());
651        assert!(app.resolve::<Kernel>().is_ok());
652        assert!(app.resolve::<UrlGenerator>().is_ok());
653        assert!(app.resolve::<MiddlewareRegistry>().is_ok());
654        assert!(app.is_booted());
655    }
656
657    #[tokio::test]
658    async fn the_kernel_serves_the_declared_routes() {
659        let app = app().await;
660        let kernel = app.resolve::<Kernel>().unwrap();
661
662        let response =
663            kernel.handle_request(Request::builder().method(Method::GET).uri("/").build()).await;
664        assert_eq!(response.status(), StatusCode::OK);
665    }
666
667    #[tokio::test]
668    async fn named_routes_reach_the_url_generator() {
669        let app = app().await;
670        let urls = app.resolve::<UrlGenerator>().unwrap();
671
672        assert_eq!(urls.route("posts.show", &[("post", "7")]).unwrap(), "/posts/7");
673    }
674
675    #[tokio::test]
676    async fn the_default_config_comes_from_the_environment() {
677        let app = app().await;
678        let config = app.resolve::<Config>().unwrap();
679
680        assert_eq!(config.get(keys::APP_NAME).as_deref(), Some("Rainier"));
681        assert_eq!(config.get(keys::SERVER_PORT), Some(8000));
682        assert_eq!(config.get(keys::APP_DEBUG), Some(false));
683    }
684
685    #[test]
686    fn the_default_drivers_are_the_ones_that_need_no_infrastructure() {
687        // What a fresh clone gets, and the reason `cargo run -- serve` works
688        // with an empty `.env`.
689        let config = default_config(&Env::new(), std::path::Path::new(".")).unwrap();
690
691        assert_eq!(config.setting(keys::APP_ENV).unwrap(), rainier_config::AppEnv::Production);
692        assert_eq!(config.setting(keys::CACHE_DRIVER).unwrap(), rainier_cache::CacheDriver::Memory);
693        assert_eq!(
694            config.setting(keys::SESSION_DRIVER).unwrap(),
695            rainier_session::SessionDriver::Memory
696        );
697        assert_eq!(config.setting(keys::QUEUE_DRIVER).unwrap(), rainier_queue::QueueDriver::Sync);
698        assert_eq!(config.setting(keys::MAIL_DRIVER).unwrap(), rainier_mail::MailDriver::Log);
699    }
700
701    #[test]
702    fn a_driver_written_as_its_wire_spelling_reads_back_as_the_enum() {
703        let env = Env::parse("CACHE_DRIVER=redis-cluster\nQUEUE_DRIVER=database\nAPP_ENV=local");
704        let config = default_config(&env, std::path::Path::new(".")).unwrap();
705
706        assert_eq!(
707            config.setting(keys::CACHE_DRIVER).unwrap(),
708            rainier_cache::CacheDriver::RedisCluster
709        );
710        assert_eq!(
711            config.setting(keys::QUEUE_DRIVER).unwrap(),
712            rainier_queue::QueueDriver::Database
713        );
714        assert!(config.setting(keys::APP_ENV).unwrap().is_developing());
715    }
716
717    #[test]
718    fn a_misspelled_driver_is_a_configuration_error_not_a_fallback() {
719        // The bug this whole layer exists to prevent: `redys` used to boot on
720        // an in-process cache and stay that way until someone noticed the rate
721        // limiter letting through N× its limit.
722        let env = Env::parse("CACHE_DRIVER=redys");
723        let err = default_config(&env, std::path::Path::new(".")).unwrap_err();
724
725        assert!(err.message().contains("CACHE_DRIVER"), "{}", err.message());
726        assert!(err.message().contains("`redys`"), "{}", err.message());
727        assert!(err.message().contains("`redis-cluster`"), "{}", err.message());
728    }
729
730    #[tokio::test]
731    async fn a_misspelled_driver_fails_the_boot_rather_than_being_deferred_forever() {
732        // `Rainier::new` cannot return a `Result`, so the error waits on the
733        // builder. It must not be possible to reach a running application
734        // without seeing it.
735        let mut builder = Rainier::new(".").without_facades().without_tracing();
736        builder.deferred = Some(Error::internal("`QUEUE_DRIVER`: nope"));
737
738        let err = builder.boot().await.unwrap_err();
739        assert!(err.message().contains("QUEUE_DRIVER"), "{}", err.message());
740    }
741
742    #[tokio::test]
743    async fn configuration_can_be_adjusted_while_building() {
744        let app = Rainier::new(".")
745            .without_facades()
746            .without_tracing()
747            .configure(|config| {
748                config.set("app.name", "Custom").unwrap();
749            })
750            .boot()
751            .await
752            .unwrap();
753
754        assert_eq!(app.resolve::<Config>().unwrap().string("app.name").as_deref(), Some("Custom"));
755    }
756
757    #[tokio::test]
758    async fn the_default_middleware_normalises_input() {
759        let app = Rainier::new(".")
760            .without_facades()
761            .without_tracing()
762            .with_routes(|router| {
763                router.post("/echo", |request: rainier_routing::Req| async move {
764                    request.input_or("name", "(absent)")
765                });
766            })
767            .boot()
768            .await
769            .unwrap();
770
771        let response = app
772            .resolve::<Kernel>()
773            .unwrap()
774            .handle_request(
775                Request::builder()
776                    .method(Method::POST)
777                    .uri("/echo")
778                    .json(&serde_json::json!({ "name": "  Ada  " }))
779                    .build(),
780            )
781            .await;
782
783        let body = response.into_http().into_body().collect().await.unwrap();
784        assert_eq!(body, "Ada", "TrimStrings should be global");
785    }
786
787    #[tokio::test]
788    async fn the_shipped_groups_all_build() {
789        // Each of these is a stack an application may attach without wiring
790        // anything. The one that can fail is `web`, whose session stage is
791        // resolved from the container — so this is really asserting that the
792        // builder binds a `SessionManager` before it compiles the router.
793        let app = Rainier::new(".")
794            .without_facades()
795            .without_tracing()
796            .with_routes(|router| {
797                router.get("/a", || async { "a" }).middleware(groups::api());
798                router.get("/b", || async { "b" }).middleware(groups::web());
799                router.get("/c", || async { "c" }).middleware(groups::api_throttled(5));
800                router.get("/d", || async { "d" }).middleware(groups::session());
801                router.get("/e", || async { "e" }).middleware(groups::trust_local_proxies());
802                router.get("/f", || async { "f" }).middleware(groups::normalise_input());
803            })
804            .boot()
805            .await;
806
807        assert!(app.is_ok(), "{:?}", app.err().map(|e| e.message().to_string()));
808    }
809
810    #[tokio::test]
811    async fn booting_binds_encryption_and_sessions() {
812        let app = app().await;
813
814        assert!(app.resolve::<Encryption>().is_ok());
815        assert!(app.resolve::<SessionManager>().is_ok());
816        assert_eq!(app.resolve::<SessionManager>().unwrap().driver(), "memory");
817    }
818
819    #[tokio::test]
820    async fn encryption_round_trips_through_the_container() {
821        let app = app().await;
822        let crypt = app.resolve::<Encryption>().unwrap();
823
824        let sealed = crypt.encrypt("a secret").unwrap();
825        assert_eq!(crypt.decrypt(&sealed).unwrap(), "a secret");
826    }
827
828    #[tokio::test]
829    async fn an_app_key_from_the_environment_is_used() {
830        let key = Key::generate();
831        let sealed = Encryption::from_keys(KeyRing::new(key.clone())).encrypt("before").unwrap();
832
833        let app = Rainier::new(".")
834            .without_facades()
835            .without_tracing()
836            .configure(|_| {})
837            .boot()
838            .await
839            .unwrap();
840
841        // The default boot has no APP_KEY here, so it must *not* read that.
842        assert!(app.resolve::<Encryption>().unwrap().decrypt(&sealed).is_err());
843
844        // With the key on the ring, it must.
845        let with_key = Rainier::new(".")
846            .without_facades()
847            .without_tracing()
848            .with_encryption(Encryption::from_keys(KeyRing::new(key)))
849            .boot()
850            .await
851            .unwrap();
852
853        assert_eq!(with_key.resolve::<Encryption>().unwrap().decrypt(&sealed).unwrap(), "before");
854    }
855
856    #[tokio::test]
857    async fn the_session_middleware_gives_a_route_a_session() {
858        let app = Rainier::new(".")
859            .without_facades()
860            .without_tracing()
861            .with_routes(|router| {
862                router
863                    .get("/count", |request: rainier_routing::Req| async move {
864                        let session = request.session().expect("StartSession ran");
865                        let seen: u64 = session.get("seen").unwrap_or(0);
866                        session.put("seen", seen + 1).unwrap();
867                        format!("{seen}")
868                    })
869                    .middleware(groups::session());
870            })
871            .boot()
872            .await
873            .unwrap();
874
875        let kernel = app.resolve::<Kernel>().unwrap();
876        let response = kernel
877            .handle_request(Request::builder().method(Method::GET).uri("/count").build())
878            .await;
879
880        assert!(response.header("set-cookie").is_some(), "the session should be persisted");
881        let body = response.into_http().into_body().collect().await.unwrap();
882        assert_eq!(body, "0");
883    }
884
885    #[tokio::test]
886    async fn a_route_without_the_session_middleware_has_no_session() {
887        let app = Rainier::new(".")
888            .without_facades()
889            .without_tracing()
890            .with_routes(|router| {
891                router.get("/plain", |request: rainier_routing::Req| async move {
892                    format!("{}", request.session().is_some())
893                });
894            })
895            .boot()
896            .await
897            .unwrap();
898
899        let response = app
900            .resolve::<Kernel>()
901            .unwrap()
902            .handle_request(Request::builder().method(Method::GET).uri("/plain").build())
903            .await;
904
905        let body = response.into_http().into_body().collect().await.unwrap();
906        assert_eq!(body, "false");
907    }
908
909    #[tokio::test]
910    async fn middleware_that_needs_an_unbound_service_fails_at_boot() {
911        // The only way a route's middleware can now fail to attach. A
912        // misspelled name is not on the list, because there is no name.
913        struct NeverBound;
914
915        let result = Rainier::new(".")
916            .without_facades()
917            .without_tracing()
918            .with_routes(|router| {
919                router.get("/a", || async { "a" }).middleware(
920                    rainier_middleware::MiddlewareStack::new().resolved(|_: Arc<NeverBound>| {
921                        StartSession::new(Arc::new(MemorySessionStore::default()))
922                    }),
923                );
924            })
925            .boot()
926            .await;
927
928        let err = result.err().expect("boot should fail");
929        assert!(err.message().contains("/a"), "{}", err.message());
930        assert!(err.message().contains("NeverBound"), "{}", err.message());
931    }
932
933    #[tokio::test]
934    async fn a_route_attaches_middleware_by_value() {
935        // The headline of the whole design: the middleware itself, no name.
936        let app = Rainier::new(".")
937            .without_facades()
938            .without_tracing()
939            .with_routes(|router| {
940                router
941                    .get("/guarded", || async { "ok" })
942                    .middleware(rainier_middleware::AddHeaders::security_defaults());
943            })
944            .boot()
945            .await
946            .unwrap();
947
948        let response = app
949            .resolve::<Kernel>()
950            .unwrap()
951            .handle_request(Request::builder().method(Method::GET).uri("/guarded").build())
952            .await;
953
954        assert!(response.header("x-content-type-options").is_some());
955    }
956
957    #[tokio::test]
958    async fn a_provider_registers_before_the_router_compiles() {
959        struct AliasProvider;
960        impl ServiceProvider for AliasProvider {
961            fn register(&self, app: &Application) -> Result<()> {
962                app.instance(42u32);
963                Ok(())
964            }
965        }
966
967        let app = Rainier::new(".")
968            .without_facades()
969            .without_tracing()
970            .with_provider(AliasProvider)
971            .boot()
972            .await
973            .unwrap();
974
975        assert_eq!(*app.resolve::<u32>().unwrap(), 42);
976    }
977
978    #[tokio::test]
979    async fn listeners_registered_while_building_survive_into_the_dispatcher() {
980        struct Ping;
981
982        let app = Rainier::new(".")
983            .without_facades()
984            .without_tracing()
985            .with_events(|events| {
986                events.listen(|_: Arc<Ping>| async { Ok(()) });
987            })
988            .boot()
989            .await
990            .unwrap();
991
992        assert!(app.resolve::<Dispatcher>().unwrap().has_listeners::<Ping>());
993    }
994}
995
996#[cfg(test)]
997mod storage_tests {
998    use super::*;
999    use rainier_cache::CacheExt as _;
1000    use rainier_filesystem::{FilesystemExt as _, MemoryFilesystem};
1001
1002    async fn app() -> Arc<Application> {
1003        Rainier::new(".")
1004            .without_facades()
1005            .without_tracing()
1006            .with_storage(Storage::new(Arc::new(MemoryFilesystem::new())))
1007            .boot()
1008            .await
1009            .expect("boots")
1010    }
1011
1012    #[tokio::test]
1013    async fn booting_binds_a_cache_and_a_storage() {
1014        let app = app().await;
1015
1016        assert_eq!(app.resolve::<CacheManager>().unwrap().driver(), "memory");
1017        assert_eq!(app.resolve::<Storage>().unwrap().driver(), "memory");
1018    }
1019
1020    #[tokio::test]
1021    async fn the_default_storage_is_local_under_the_base_path() {
1022        // A fresh clone should have working storage without configuring one.
1023        let app = Rainier::new(".").without_facades().without_tracing().boot().await.unwrap();
1024
1025        assert_eq!(app.resolve::<Storage>().unwrap().driver(), "local");
1026    }
1027
1028    #[tokio::test]
1029    async fn the_cache_round_trips_through_the_container() {
1030        let app = app().await;
1031        let cache = app.resolve::<CacheManager>().unwrap();
1032
1033        cache.put_string("k", "v", None).await.unwrap();
1034        assert_eq!(cache.get_string("k").await.unwrap().as_deref(), Some("v"));
1035    }
1036
1037    #[tokio::test]
1038    async fn storage_round_trips_through_the_container() {
1039        let app = app().await;
1040        let storage = app.resolve::<Storage>().unwrap();
1041
1042        storage.put_string("uploads/a.txt", "hello").await.unwrap();
1043        assert_eq!(storage.get_string("uploads/a.txt").await.unwrap().as_deref(), Some("hello"));
1044    }
1045
1046    #[tokio::test]
1047    async fn a_traversal_through_the_container_is_still_refused() {
1048        let storage = app().await.resolve::<Storage>().unwrap();
1049        assert!(storage.get("../../etc/passwd").await.is_err());
1050    }
1051}