1use 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
31pub struct Rainier {
47 base_path: PathBuf,
48 env: Env,
49 config: Config,
50 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 #[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 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 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 pub fn env(&self) -> &Env {
126 &self.env
127 }
128
129 pub fn config(&self) -> &Config {
131 &self.config
132 }
133
134 pub fn configure(self, adjust: impl FnOnce(&Config)) -> Self {
136 adjust(&self.config);
137 self
138 }
139
140 pub fn with_events(self, register: impl FnOnce(&Dispatcher)) -> Self {
142 register(&self.events);
143 self
144 }
145
146 pub fn with_middleware(self, register: impl FnOnce(&MiddlewareRegistry)) -> Self {
148 register(&self.middleware);
149 self
150 }
151
152 pub fn with_routes(mut self, declare: impl FnOnce(&mut Router)) -> Self {
154 declare(&mut self.router);
155 self
156 }
157
158 pub fn with_views(mut self, engine: Arc<dyn ViewEngine>) -> Self {
161 self.views = Some(engine);
162 self
163 }
164
165 pub fn with_database(mut self, database: Database) -> Self {
167 self.database = Some(database);
168 self
169 }
170
171 pub fn with_queue(mut self, queue: QueueManager) -> Self {
173 self.queue = Some(queue);
174 self
175 }
176
177 pub fn with_mailer(mut self, mailer: Mailer) -> Self {
179 self.mailer = Some(mailer);
180 self
181 }
182
183 pub fn with_sessions(mut self, sessions: SessionManager) -> Self {
189 self.sessions = Some(sessions);
190 self
191 }
192
193 pub fn with_cache(mut self, cache: CacheManager) -> Self {
198 self.cache = Some(cache);
199 self
200 }
201
202 pub fn with_notifier(mut self, notifier: rainier_notify::Notifier) -> Self {
216 self.notifier = Some(notifier);
217 self
218 }
219
220 pub fn with_broadcasting(mut self, broadcasting: rainier_broadcast::Broadcasting) -> Self {
236 self.broadcasting = Some(broadcasting);
237 self
238 }
239
240 pub fn with_websockets(mut self, routes: rainier_websocket::WebSocketRoutes) -> Self {
252 self.websockets = Some(routes);
253 self
254 }
255
256 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 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 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 pub fn with_storage(mut self, storage: Storage) -> Self {
297 self.storage = Some(storage);
298 self
299 }
300
301 pub fn with_encryption(mut self, crypt: Encryption) -> Self {
307 self.crypt = Some(crypt);
308 self
309 }
310
311 pub fn with_provider(mut self, provider: impl ServiceProvider) -> Self {
313 self.providers.push(Arc::new(provider));
314 self
315 }
316
317 pub fn without_facades(mut self) -> Self {
322 self.install_facades = false;
323 self
324 }
325
326 pub fn without_tracing(mut self) -> Self {
328 self.install_tracing = false;
329 self
330 }
331
332 pub async fn boot(self) -> Result<Arc<Application>> {
338 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 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 app.instance(rainier_cache::LockManager::new(Arc::clone(cache.store())));
380 app.instance(cache);
381
382 app.instance(self.schedule.unwrap_or_default());
385
386 for bind in self.instances {
389 bind(&app);
390 }
391
392 app.instance(self.websockets.unwrap_or_default());
395
396 app.instance(self.broadcasting.unwrap_or_else(rainier_broadcast::Broadcasting::log));
400
401 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 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 for provider in self.providers {
432 app.register_arc(provider)?;
433 }
434
435 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
460fn 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
502fn 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 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
539fn default_middleware() -> MiddlewareRegistry {
547 let registry = MiddlewareRegistry::new();
548
549 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 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 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 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 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 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 assert!(app.resolve::<Encryption>().unwrap().decrypt(&sealed).is_err());
792
793 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 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 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 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}