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);
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        let cache = self.cache.unwrap_or_else(CacheManager::memory);
375
376        // The locks behind `without_overlapping` and `on_one_server` — and
377        // anything else that needs one. Bound from the same cache the
378        // application uses, so "shared" means the same thing for both.
379        app.instance(rainier_cache::LockManager::new(Arc::clone(cache.store())));
380        app.instance(cache);
381
382        // An empty schedule, so `schedule:list` and `schedule:run` work on a
383        // fresh clone. An application replaces it in a provider.
384        app.instance(self.schedule.unwrap_or_default());
385
386        // Whatever the application handed over, before the providers run so
387        // one of them can resolve it.
388        for bind in self.instances {
389            bind(&app);
390        }
391
392        // No socket routes unless the application declares some, and an
393        // upgrade then falls through to the router like any other GET.
394        app.instance(self.websockets.unwrap_or_default());
395
396        // Broadcasts default to the log, for the same reason notifications do
397        // — except the risk here is the reverse one: publishing a private
398        // channel to a relay the application never meant to reach.
399        app.instance(self.broadcasting.unwrap_or_else(rainier_broadcast::Broadcasting::log));
400
401        // Notifications default to the log channel. Not to mail: a default that
402        // can reach a real person is a default that reaches one from staging.
403        app.instance(
404            self.notifier.unwrap_or_else(|| {
405                rainier_notify::Notifier::new().with(rainier_notify::LogChannel)
406            }),
407        );
408        app.instance(
409            self.storage
410                .unwrap_or_else(|| Storage::local(self.base_path.join("storage").join("app"))),
411        );
412
413        if let Some(database) = self.database {
414            app.instance(database);
415        }
416        if let Some(queue) = self.queue {
417            // Given the same locks as everything else, so `unique_id` is
418            // enforced against the cache the application actually shares.
419            // Without this a job declaring one is dispatched anyway, with a
420            // warning — degraded rather than silently broken.
421            app.instance(queue.with_locks(rainier_cache::LockManager::new(Arc::clone(
422                app.resolve::<CacheManager>()?.store(),
423            ))));
424        }
425        if let Some(mailer) = self.mailer {
426            app.instance(mailer);
427        }
428
429        // Providers register before the router compiles, so a middleware that
430        // resolves a service gets one a provider bound.
431        for provider in self.providers {
432            app.register_arc(provider)?;
433        }
434
435        // Compiled once and shared: the kernel serves it, and the container
436        // holds the same table so `route:list` can describe what is actually
437        // being served rather than a second compilation of it.
438        //
439        // This is also where every `resolved`/`deferred` middleware stage is
440        // built, which is why it happens after the providers and before the
441        // server starts.
442        let compiled = Arc::new(self.router.compile(&app)?);
443        let urls = UrlGenerator::from_routes(compiled.named_routes())
444            .with_base(app.resolve::<Config>()?.get_or(keys::APP_URL, String::new()));
445
446        let kernel =
447            Kernel::from_shared(Arc::clone(&compiled), self.middleware.global_stack(&app)?)
448                .with_debug(app.resolve::<Config>()?.get_or(keys::APP_DEBUG, false));
449
450        app.instance_arc(compiled);
451        app.instance(urls);
452        app.instance(self.middleware);
453        app.instance(kernel);
454
455        app.boot().await?;
456        Ok(app)
457    }
458}
459
460/// The configuration every application starts with, read from the environment.
461///
462/// Fails only on a driver name outside its [closed
463/// set](rainier_support::Setting) — `QUEUE_DRIVER=databse` is a deployment
464/// mistake, and running on the default instead of the driver somebody asked for
465/// is not a recovery. Everything else here has a total parse: a `SERVER_PORT`
466/// that is not a number falls back, because the alternative is refusing to boot
467/// over a trailing space.
468fn default_config(env: &Env, base_path: &std::path::Path) -> Result<Config> {
469    let config = Config::new();
470
471    config.set(keys::APP_NAME, env.string("APP_NAME", "Rainier"))?;
472    config.set(keys::APP_ENV, env.setting("APP_ENV")?)?;
473    config.set(keys::APP_DEBUG, env.bool("APP_DEBUG", false))?;
474    config.set(keys::APP_URL, env.string("APP_URL", "http://localhost:8000"))?;
475    config.set(keys::APP_BASE_PATH, base_path.to_string_lossy().into_owned())?;
476
477    config.set(keys::SERVER_HOST, env.string("SERVER_HOST", "127.0.0.1"))?;
478    config.set(keys::SERVER_PORT, env.int("SERVER_PORT", 8000) as u16)?;
479    config.set(keys::SERVER_MAX_BODY_BYTES, env.int("SERVER_MAX_BODY", 2 * 1024 * 1024) as u64)?;
480
481    config.set(keys::DATABASE_URL, env.string("DATABASE_URL", "sqlite::memory:"))?;
482
483    config.set(keys::CACHE_DRIVER, env.setting("CACHE_DRIVER")?)?;
484    config.set(keys::CACHE_REDIS_URL, env.string("REDIS_URL", "redis://127.0.0.1:6379/"))?;
485    config.set(keys::CACHE_MEMCACHED_URL, env.string("MEMCACHED_URL", "127.0.0.1:11211"))?;
486
487    config.set(keys::SESSION_DRIVER, env.setting("SESSION_DRIVER")?)?;
488    config.set(keys::SESSION_LIFETIME, env.int("SESSION_LIFETIME", 7200))?;
489    config.set(keys::SESSION_COOKIE, env.string("SESSION_COOKIE", "rainier_session"))?;
490    config.set(keys::SESSION_SECURE, env.bool("SESSION_SECURE", false))?;
491
492    config.set(keys::QUEUE_DRIVER, env.setting("QUEUE_DRIVER")?)?;
493    config.set(keys::QUEUE_DEFAULT, env.string("QUEUE_DEFAULT", "default"))?;
494
495    config.set(keys::MAIL_DRIVER, env.setting("MAIL_DRIVER")?)?;
496    config.set(keys::MAIL_FROM_ADDRESS, env.string("MAIL_FROM", "hello@example.com"))?;
497    config.set(keys::MAIL_FROM_NAME, env.string("MAIL_FROM_NAME", "Rainier"))?;
498
499    Ok(config)
500}
501
502/// The keys encryption and signing use.
503///
504/// `APP_KEY` is the current key; `APP_PREVIOUS_KEYS` is a comma-separated list
505/// of retired ones, still needed to read what they wrote. See
506/// [`rainier_crypt`].
507fn app_keys(env: &Env) -> KeyRing {
508    let previous: Vec<String> =
509        env.get("APP_PREVIOUS_KEYS").unwrap_or_default().split(',').map(str::to_string).collect();
510
511    match env.get("APP_KEY").filter(|key| !key.trim().is_empty()) {
512        Some(key) => match KeyRing::from_base64(&key, &previous) {
513            Ok(ring) => ring,
514            Err(e) => {
515                // Falling back to a random key would "work" and quietly make
516                // every existing encrypted value unreadable, so say plainly
517                // what is wrong instead of hiding it in a decrypt failure
518                // three screens later.
519                tracing::error!(
520                    error = %e.message(),
521                    "APP_KEY is not usable; generating a temporary key. Encrypted values \
522                     written before this boot cannot be read, and values written now cannot \
523                     be read after a restart."
524                );
525                KeyRing::new(Key::generate())
526            }
527        },
528        None => {
529            tracing::warn!(
530                "APP_KEY is not set; generating a temporary key. Set one with \
531                 `APP_KEY={}` or nothing encrypted will survive a restart.",
532                Key::generate().to_base64()
533            );
534            KeyRing::new(Key::generate())
535        }
536    }
537}
538
539/// The middleware every application starts with.
540///
541/// Only the input normalisers are **global**, because they are the ones whose
542/// absence produces confusing bugs rather than missing features. Everything
543/// else is registered as an **alias** and opted into per route, since applying
544/// CORS, throttling, sessions or authentication everywhere by default is
545/// nearly always wrong.
546fn default_middleware() -> MiddlewareRegistry {
547    let registry = MiddlewareRegistry::new();
548
549    // Input normalisation only. Everything else — CORS, throttling, sessions,
550    // authentication — is opted into per route or per group, because applying
551    // any of it everywhere by default is how an API ends up allocating session
552    // rows nobody reads.
553    //
554    // The groups Rainier ships are functions in [`crate::groups`], not entries
555    // here: there is nothing to look them up by.
556    registry.global(crate::groups::normalise_input());
557
558    registry
559}
560
561fn install_tracing(env: &Env) {
562    use tracing_subscriber::{fmt, EnvFilter};
563
564    let filter = env.string("RUST_LOG", "info");
565    // A second subscriber would panic, and an application that installs its
566    // own should keep it — so a failure here is expected and ignored.
567    let _ = fmt()
568        .with_env_filter(EnvFilter::try_new(&filter).unwrap_or_else(|_| EnvFilter::new("info")))
569        .try_init();
570}
571
572#[cfg(test)]
573mod tests {
574    use super::*;
575    use crate::groups;
576    use rainier_http::{Method, Request, StatusCode};
577    use rainier_session::SessionRequestExt as _;
578    use rainier_session::StartSession;
579
580    async fn app() -> Arc<Application> {
581        Rainier::new(".")
582            .without_facades()
583            .without_tracing()
584            .with_routes(|router| {
585                router.get("/", || async { "home" }).name("home");
586                router.get("/posts/{post}", || async { "post" }).name("posts.show");
587            })
588            .boot()
589            .await
590            .expect("boots")
591    }
592
593    #[tokio::test]
594    async fn booting_binds_the_core_services() {
595        let app = app().await;
596
597        assert!(app.resolve::<Config>().is_ok());
598        assert!(app.resolve::<Dispatcher>().is_ok());
599        assert!(app.resolve::<Views>().is_ok());
600        assert!(app.resolve::<Kernel>().is_ok());
601        assert!(app.resolve::<UrlGenerator>().is_ok());
602        assert!(app.resolve::<MiddlewareRegistry>().is_ok());
603        assert!(app.is_booted());
604    }
605
606    #[tokio::test]
607    async fn the_kernel_serves_the_declared_routes() {
608        let app = app().await;
609        let kernel = app.resolve::<Kernel>().unwrap();
610
611        let response =
612            kernel.handle_request(Request::builder().method(Method::GET).uri("/").build()).await;
613        assert_eq!(response.status(), StatusCode::OK);
614    }
615
616    #[tokio::test]
617    async fn named_routes_reach_the_url_generator() {
618        let app = app().await;
619        let urls = app.resolve::<UrlGenerator>().unwrap();
620
621        assert_eq!(urls.route("posts.show", &[("post", "7")]).unwrap(), "/posts/7");
622    }
623
624    #[tokio::test]
625    async fn the_default_config_comes_from_the_environment() {
626        let app = app().await;
627        let config = app.resolve::<Config>().unwrap();
628
629        assert_eq!(config.get(keys::APP_NAME).as_deref(), Some("Rainier"));
630        assert_eq!(config.get(keys::SERVER_PORT), Some(8000));
631        assert_eq!(config.get(keys::APP_DEBUG), Some(false));
632    }
633
634    #[test]
635    fn the_default_drivers_are_the_ones_that_need_no_infrastructure() {
636        // What a fresh clone gets, and the reason `cargo run -- serve` works
637        // with an empty `.env`.
638        let config = default_config(&Env::new(), std::path::Path::new(".")).unwrap();
639
640        assert_eq!(config.setting(keys::APP_ENV).unwrap(), rainier_config::AppEnv::Production);
641        assert_eq!(config.setting(keys::CACHE_DRIVER).unwrap(), rainier_cache::CacheDriver::Memory);
642        assert_eq!(
643            config.setting(keys::SESSION_DRIVER).unwrap(),
644            rainier_session::SessionDriver::Memory
645        );
646        assert_eq!(config.setting(keys::QUEUE_DRIVER).unwrap(), rainier_queue::QueueDriver::Sync);
647        assert_eq!(config.setting(keys::MAIL_DRIVER).unwrap(), rainier_mail::MailDriver::Log);
648    }
649
650    #[test]
651    fn a_driver_written_as_its_wire_spelling_reads_back_as_the_enum() {
652        let env = Env::parse("CACHE_DRIVER=redis-cluster\nQUEUE_DRIVER=database\nAPP_ENV=local");
653        let config = default_config(&env, std::path::Path::new(".")).unwrap();
654
655        assert_eq!(
656            config.setting(keys::CACHE_DRIVER).unwrap(),
657            rainier_cache::CacheDriver::RedisCluster
658        );
659        assert_eq!(
660            config.setting(keys::QUEUE_DRIVER).unwrap(),
661            rainier_queue::QueueDriver::Database
662        );
663        assert!(config.setting(keys::APP_ENV).unwrap().is_developing());
664    }
665
666    #[test]
667    fn a_misspelled_driver_is_a_configuration_error_not_a_fallback() {
668        // The bug this whole layer exists to prevent: `redys` used to boot on
669        // an in-process cache and stay that way until someone noticed the rate
670        // limiter letting through N× its limit.
671        let env = Env::parse("CACHE_DRIVER=redys");
672        let err = default_config(&env, std::path::Path::new(".")).unwrap_err();
673
674        assert!(err.message().contains("CACHE_DRIVER"), "{}", err.message());
675        assert!(err.message().contains("`redys`"), "{}", err.message());
676        assert!(err.message().contains("`redis-cluster`"), "{}", err.message());
677    }
678
679    #[tokio::test]
680    async fn a_misspelled_driver_fails_the_boot_rather_than_being_deferred_forever() {
681        // `Rainier::new` cannot return a `Result`, so the error waits on the
682        // builder. It must not be possible to reach a running application
683        // without seeing it.
684        let mut builder = Rainier::new(".").without_facades().without_tracing();
685        builder.deferred = Some(Error::internal("`QUEUE_DRIVER`: nope"));
686
687        let err = builder.boot().await.unwrap_err();
688        assert!(err.message().contains("QUEUE_DRIVER"), "{}", err.message());
689    }
690
691    #[tokio::test]
692    async fn configuration_can_be_adjusted_while_building() {
693        let app = Rainier::new(".")
694            .without_facades()
695            .without_tracing()
696            .configure(|config| {
697                config.set("app.name", "Custom").unwrap();
698            })
699            .boot()
700            .await
701            .unwrap();
702
703        assert_eq!(app.resolve::<Config>().unwrap().string("app.name").as_deref(), Some("Custom"));
704    }
705
706    #[tokio::test]
707    async fn the_default_middleware_normalises_input() {
708        let app = Rainier::new(".")
709            .without_facades()
710            .without_tracing()
711            .with_routes(|router| {
712                router.post("/echo", |request: rainier_routing::Req| async move {
713                    request.input_or("name", "(absent)")
714                });
715            })
716            .boot()
717            .await
718            .unwrap();
719
720        let response = app
721            .resolve::<Kernel>()
722            .unwrap()
723            .handle_request(
724                Request::builder()
725                    .method(Method::POST)
726                    .uri("/echo")
727                    .json(&serde_json::json!({ "name": "  Ada  " }))
728                    .build(),
729            )
730            .await;
731
732        let body = response.into_http().into_body().collect().await.unwrap();
733        assert_eq!(body, "Ada", "TrimStrings should be global");
734    }
735
736    #[tokio::test]
737    async fn the_shipped_groups_all_build() {
738        // Each of these is a stack an application may attach without wiring
739        // anything. The one that can fail is `web`, whose session stage is
740        // resolved from the container — so this is really asserting that the
741        // builder binds a `SessionManager` before it compiles the router.
742        let app = Rainier::new(".")
743            .without_facades()
744            .without_tracing()
745            .with_routes(|router| {
746                router.get("/a", || async { "a" }).middleware(groups::api());
747                router.get("/b", || async { "b" }).middleware(groups::web());
748                router.get("/c", || async { "c" }).middleware(groups::api_throttled(5));
749                router.get("/d", || async { "d" }).middleware(groups::session());
750                router.get("/e", || async { "e" }).middleware(groups::trust_local_proxies());
751                router.get("/f", || async { "f" }).middleware(groups::normalise_input());
752            })
753            .boot()
754            .await;
755
756        assert!(app.is_ok(), "{:?}", app.err().map(|e| e.message().to_string()));
757    }
758
759    #[tokio::test]
760    async fn booting_binds_encryption_and_sessions() {
761        let app = app().await;
762
763        assert!(app.resolve::<Encryption>().is_ok());
764        assert!(app.resolve::<SessionManager>().is_ok());
765        assert_eq!(app.resolve::<SessionManager>().unwrap().driver(), "memory");
766    }
767
768    #[tokio::test]
769    async fn encryption_round_trips_through_the_container() {
770        let app = app().await;
771        let crypt = app.resolve::<Encryption>().unwrap();
772
773        let sealed = crypt.encrypt("a secret").unwrap();
774        assert_eq!(crypt.decrypt(&sealed).unwrap(), "a secret");
775    }
776
777    #[tokio::test]
778    async fn an_app_key_from_the_environment_is_used() {
779        let key = Key::generate();
780        let sealed = Encryption::from_keys(KeyRing::new(key.clone())).encrypt("before").unwrap();
781
782        let app = Rainier::new(".")
783            .without_facades()
784            .without_tracing()
785            .configure(|_| {})
786            .boot()
787            .await
788            .unwrap();
789
790        // The default boot has no APP_KEY here, so it must *not* read that.
791        assert!(app.resolve::<Encryption>().unwrap().decrypt(&sealed).is_err());
792
793        // With the key on the ring, it must.
794        let with_key = Rainier::new(".")
795            .without_facades()
796            .without_tracing()
797            .with_encryption(Encryption::from_keys(KeyRing::new(key)))
798            .boot()
799            .await
800            .unwrap();
801
802        assert_eq!(with_key.resolve::<Encryption>().unwrap().decrypt(&sealed).unwrap(), "before");
803    }
804
805    #[tokio::test]
806    async fn the_session_middleware_gives_a_route_a_session() {
807        let app = Rainier::new(".")
808            .without_facades()
809            .without_tracing()
810            .with_routes(|router| {
811                router
812                    .get("/count", |request: rainier_routing::Req| async move {
813                        let session = request.session().expect("StartSession ran");
814                        let seen: u64 = session.get("seen").unwrap_or(0);
815                        session.put("seen", seen + 1).unwrap();
816                        format!("{seen}")
817                    })
818                    .middleware(groups::session());
819            })
820            .boot()
821            .await
822            .unwrap();
823
824        let kernel = app.resolve::<Kernel>().unwrap();
825        let response = kernel
826            .handle_request(Request::builder().method(Method::GET).uri("/count").build())
827            .await;
828
829        assert!(response.header("set-cookie").is_some(), "the session should be persisted");
830        let body = response.into_http().into_body().collect().await.unwrap();
831        assert_eq!(body, "0");
832    }
833
834    #[tokio::test]
835    async fn a_route_without_the_session_middleware_has_no_session() {
836        let app = Rainier::new(".")
837            .without_facades()
838            .without_tracing()
839            .with_routes(|router| {
840                router.get("/plain", |request: rainier_routing::Req| async move {
841                    format!("{}", request.session().is_some())
842                });
843            })
844            .boot()
845            .await
846            .unwrap();
847
848        let response = app
849            .resolve::<Kernel>()
850            .unwrap()
851            .handle_request(Request::builder().method(Method::GET).uri("/plain").build())
852            .await;
853
854        let body = response.into_http().into_body().collect().await.unwrap();
855        assert_eq!(body, "false");
856    }
857
858    #[tokio::test]
859    async fn middleware_that_needs_an_unbound_service_fails_at_boot() {
860        // The only way a route's middleware can now fail to attach. A
861        // misspelled name is not on the list, because there is no name.
862        struct NeverBound;
863
864        let result = Rainier::new(".")
865            .without_facades()
866            .without_tracing()
867            .with_routes(|router| {
868                router.get("/a", || async { "a" }).middleware(
869                    rainier_middleware::MiddlewareStack::new().resolved(|_: Arc<NeverBound>| {
870                        StartSession::new(Arc::new(MemorySessionStore::default()))
871                    }),
872                );
873            })
874            .boot()
875            .await;
876
877        let err = result.err().expect("boot should fail");
878        assert!(err.message().contains("/a"), "{}", err.message());
879        assert!(err.message().contains("NeverBound"), "{}", err.message());
880    }
881
882    #[tokio::test]
883    async fn a_route_attaches_middleware_by_value() {
884        // The headline of the whole design: the middleware itself, no name.
885        let app = Rainier::new(".")
886            .without_facades()
887            .without_tracing()
888            .with_routes(|router| {
889                router
890                    .get("/guarded", || async { "ok" })
891                    .middleware(rainier_middleware::AddHeaders::security_defaults());
892            })
893            .boot()
894            .await
895            .unwrap();
896
897        let response = app
898            .resolve::<Kernel>()
899            .unwrap()
900            .handle_request(Request::builder().method(Method::GET).uri("/guarded").build())
901            .await;
902
903        assert!(response.header("x-content-type-options").is_some());
904    }
905
906    #[tokio::test]
907    async fn a_provider_registers_before_the_router_compiles() {
908        struct AliasProvider;
909        impl ServiceProvider for AliasProvider {
910            fn register(&self, app: &Application) -> Result<()> {
911                app.instance(42u32);
912                Ok(())
913            }
914        }
915
916        let app = Rainier::new(".")
917            .without_facades()
918            .without_tracing()
919            .with_provider(AliasProvider)
920            .boot()
921            .await
922            .unwrap();
923
924        assert_eq!(*app.resolve::<u32>().unwrap(), 42);
925    }
926
927    #[tokio::test]
928    async fn listeners_registered_while_building_survive_into_the_dispatcher() {
929        struct Ping;
930
931        let app = Rainier::new(".")
932            .without_facades()
933            .without_tracing()
934            .with_events(|events| {
935                events.listen(|_: Arc<Ping>| async { Ok(()) });
936            })
937            .boot()
938            .await
939            .unwrap();
940
941        assert!(app.resolve::<Dispatcher>().unwrap().has_listeners::<Ping>());
942    }
943}
944
945#[cfg(test)]
946mod storage_tests {
947    use super::*;
948    use rainier_cache::CacheExt as _;
949    use rainier_filesystem::{FilesystemExt as _, MemoryFilesystem};
950
951    async fn app() -> Arc<Application> {
952        Rainier::new(".")
953            .without_facades()
954            .without_tracing()
955            .with_storage(Storage::new(Arc::new(MemoryFilesystem::new())))
956            .boot()
957            .await
958            .expect("boots")
959    }
960
961    #[tokio::test]
962    async fn booting_binds_a_cache_and_a_storage() {
963        let app = app().await;
964
965        assert_eq!(app.resolve::<CacheManager>().unwrap().driver(), "memory");
966        assert_eq!(app.resolve::<Storage>().unwrap().driver(), "memory");
967    }
968
969    #[tokio::test]
970    async fn the_default_storage_is_local_under_the_base_path() {
971        // A fresh clone should have working storage without configuring one.
972        let app = Rainier::new(".").without_facades().without_tracing().boot().await.unwrap();
973
974        assert_eq!(app.resolve::<Storage>().unwrap().driver(), "local");
975    }
976
977    #[tokio::test]
978    async fn the_cache_round_trips_through_the_container() {
979        let app = app().await;
980        let cache = app.resolve::<CacheManager>().unwrap();
981
982        cache.put_string("k", "v", None).await.unwrap();
983        assert_eq!(cache.get_string("k").await.unwrap().as_deref(), Some("v"));
984    }
985
986    #[tokio::test]
987    async fn storage_round_trips_through_the_container() {
988        let app = app().await;
989        let storage = app.resolve::<Storage>().unwrap();
990
991        storage.put_string("uploads/a.txt", "hello").await.unwrap();
992        assert_eq!(storage.get_string("uploads/a.txt").await.unwrap().as_deref(), Some("hello"));
993    }
994
995    #[tokio::test]
996    async fn a_traversal_through_the_container_is_still_refused() {
997        let storage = app().await.resolve::<Storage>().unwrap();
998        assert!(storage.get("../../etc/passwd").await.is_err());
999    }
1000}