1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
#![deny(missing_docs)] //! This crate provides a simple Dependency Injection framework for `actix-web`. //! //! ## Example //! //! Note that the following example is heavily minified. Files names don't really matter. For a //! more involved example, please see the [`coi-actix-sample`] repository. //! //! [`coi-actix-sample`]: https://github.com/Nashenas88/coi-actix-sample //! //! In your main binary: //! ```rust,ignore //! use crate::infrastructure::{RepositoryProvider, PoolProvider}; //! use crate::service::ServiceProvider; //! use coi::container; //! use actix_web::{App, HttpServer}; //! //! mod traits; //! mod infrastructure; //! mod routes; //! mod service; //! //! # let _s = " //! fn main() { //! # "; //! // container! only expects identifiers, so construct this provider outside //! let postgres_pool = PoolProvider::<NoTls>::new(/* construct actual pool */); //! //! // Build your container //! let container = container! { //! pool => postgres_pool.singleton, //! service => ServiceProvider.scoped, //! repository => RepositoryProvider.scoped, //! }; //! //! HttpServer::new(move || { //! App::new() //! // Make sure to assign it to `app_data` and not `data` //! .app_data(container.clone()) //! .configure(routes::data::route_config) //! }) //! ... //! # let _ = " //! } //! # "; //! ``` //! //! `traits.rs`: //! ```rust,ignore //! use coi::Inject; //! //! // Ensure all of your traits inherit from `Inject` //! pub trait IService: Inject { //! ... //! } //! //! pub trait IRepository: Inject { //! ... //! } //! ``` //! //! `service.rs` //! ```rust,ignore //! use crate::traits::IService; //! use coi::Inject; //! use std::sync::Arc; //! //! // derive `Inject` for all structs that will provide the injectable traits. //! #[derive(Inject)] //! #[coi(provides pub dyn IService with Service::new(repository))] //! struct Service { //! #[coi(inject)] //! repository: Arc<dyn IRepository>, //! } //! //! impl IService for Service { //! ... //! } //! ``` //! //! > **Note**: See [`coi::Inject`] for more examples on how to use `#[derive(Inject)]` //! //! [`coi::Inject`]: derive.Inject.html //! //! `infrastructure.rs` //! ```rust,ignore //! use crate::traits::IRepository; //! use coi::Inject; //! use ...::PostgresPool; //! #[cfg(feature = "notls")] //! use ...::NoTls; //! #[cfg(not(feature = "notls"))] //! use ...::Tls; //! //! #[derive(Inject)] //! #[coi(provides pub dyn IRepository with Repository::new(pool))] //! struct Repository { //! #[cfg(feature = "notls")] //! #[coi(inject)] //! pool: PostgresPool<NoTls>, //! //! #[cfg(not(feature = "notls"))] //! #[coi(inject)] //! pool: PostgresPool<Tls>, //! } //! //! impl IRepository for Repository { //! ... //! } //! //! #[derive(Inject)] //! struct Pool<T> where T: ... { //! pool: PostgresPool<T> //! } //! //! #[derive(Provide)] //! #[coi(provides pub Pool<T> with Pool::new(self.0.pool))] //! struct PoolProvider<T> where T: ... { //! pool: PostgresPool<T> //! } //! //! impl<T> PoolProvider<T> where T: ... { //! fn new(PostgresPool<T>) -> Self { ... } //! } //! ``` //! //! `routes.rs` //! ```rust,ignore //! use crate::service::IService; //! use actix_web::{ //! web::{self, HttpResponse, ServiceConfig}, //! Responder, //! }; //! use coi_actix_web::inject; //! use std::sync::Arc; //! //! #[inject(coi_crate = "coi")] //! async fn get( //! id: web::Path<i64>, //! #[inject] service: Arc<dyn IService>, //! ) -> Result<impl Responder, ()> { //! let name: String = service.get(*id).await.map_err(|e| log::error!("{}", e))?; //! Ok(HttpResponse::Ok().json(name)) //! } //! //! #[inject(coi_crate = "coi")] //! async fn get_all(#[inject] service: Arc<dyn IService>) -> Result<impl Responder, ()> { //! let data: Vec<String> = service.get_all().await.map_err(|e| log::error!("{}", e))?; //! Ok(HttpResponse::Ok().json(data)) //! } //! //! pub fn route_config(config: &mut ServiceConfig) { //! config.service( //! web::scope("/data") //! .route("", web::get().to(get_all)) //! .route("/", web::get().to(get_all)) //! .route("/{id}", web::get().to(get)), //! ); //! } //! ``` use actix_http::error::Error; use actix_service::ServiceFactory; use actix_web::dev::*; /// Extensions to `actix-web`'s `App` struct pub trait AppExt { /// A helper extension method to ensure the `Container` is /// properly registered to work with the `inject` attribute macro. /// /// # Examples /// /// ```no_run /// use coi_actix_web::AppExt as _; /// /// // Your general server setup in "main". The name here is different /// #[actix_rt::main] /// async fn main() -> std::io::Result<()> { /// use actix_web::{App, HttpServer}; /// use coi::container; /// /// // Construct your coi container with your keys and providers /// // See the coi crate for more details /// let container = container!{ /// service => ServiceImplProvider; scoped /// }; /// /// HttpServer::new(move || { /// App::new() /// .register_container(container.clone()) /// // ^^^^^^^^^^^^^^^^ /// .service(get) /// }) /// .bind("127.0.0.1:8000")? /// .run() /// .await /// } /// /// # use coi::{Container, Inject, Provide}; /// # use std::sync::Arc; /// # /// # struct ServiceImpl; /// # /// # impl Inject for ServiceImpl {} /// # /// # struct ServiceImplProvider; /// # /// # impl Provide for ServiceImplProvider { /// # /// # type Output = ServiceImpl; /// # /// # fn provide(&self, _: &Container) -> coi::Result<Arc<Self::Output>> { /// # Ok(Arc::new(ServiceImpl)) /// # } /// # } /// # /// # use actix_web::{get, web, HttpResponse, Responder}; /// # /// # // Add the `inject` attribute to the function you want to inject /// # #[get("/{id}")] /// # #[coi_actix_web::inject] /// # async fn get( /// # id: web::Path<u64>, /// # // Add the `inject` field attribute to each attribute you want /// # // injected /// # #[inject] service: Arc<ServiceImpl> /// # ) -> Result<impl Responder, ()> { /// # let _ = service; /// # Ok(HttpResponse::Ok()) /// # } /// /// ``` fn register_container(self, container: Container) -> Self; } impl<S, T> AppExt for actix_web::App<S, T> where S: ServiceFactory< Config = (), Request = ServiceRequest, Response = ServiceResponse<T>, Error = Error, InitError = (), >, T: MessageBody, { fn register_container(self, container: Container) -> Self { self.app_data(container) } } use coi::{Container, Inject}; pub use coi_actix_web_derive::*; use actix_web::{ dev::Payload, error::{Error as WebError, ErrorInternalServerError, Result as WebResult}, FromRequest, HttpRequest, }; use futures::future::{err, ok, ready, Ready}; use std::{marker::PhantomData, sync::Arc}; #[doc(hidden)] pub trait ContainerKey<T> where T: Inject + ?Sized, { const KEY: &'static str; } #[doc(hidden)] pub struct Injected<T, K>(pub T, pub PhantomData<K>); impl<T, K> Injected<T, K> { #[doc(hidden)] pub fn new(injected: T) -> Self { Self(injected, PhantomData) } } impl<T, K> FromRequest for Injected<Arc<T>, K> where T: Inject + ?Sized, K: ContainerKey<T>, { type Error = WebError; type Future = Ready<WebResult<Self, Self::Error>>; type Config = (); fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { match req.app_data::<Container>() { Some(container) => { let container = container.scoped(); ready( container .resolve::<T>(K::KEY) .map(Injected::new) .map_err(|e| { log::error!("{}", e); ErrorInternalServerError("huh") }), ) } None => { log::error!("Container not registered"); err(ErrorInternalServerError("huh2")) } } } } macro_rules! injected_tuples { ($(($T:ident, $K:ident)),+) => { impl<$($T, $K),+> FromRequest for Injected<($(Arc<$T>),+), ($($K),+)> where $( $T: Inject + ?Sized, $K: ContainerKey<$T>, )+ { type Error = WebError; type Future = Ready<WebResult<Self, Self::Error>>; type Config = (); fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { match req.app_data::<Container>() { Some(container) => { let container = container.scoped(); ok(Injected::new(($( { let resolved = container.resolve::<$T>(<$K as ContainerKey<$T>>::KEY) .map_err(ErrorInternalServerError); match resolved { Ok(r) => r, Err(e) => return err(e), } }, )+))) }, None => err(ErrorInternalServerError("Container not registered")) } } } } } injected_tuples!((TA, KA), (TB, KB)); injected_tuples!((TA, KA), (TB, KB), (TC, KC)); injected_tuples!((TA, KA), (TB, KB), (TC, KC), (TD, KD)); injected_tuples!((TA, KA), (TB, KB), (TC, KC), (TD, KD), (TE, KE)); injected_tuples!((TA, KA), (TB, KB), (TC, KC), (TD, KD), (TE, KE), (TF, KF)); injected_tuples!( (TA, KA), (TB, KB), (TC, KC), (TD, KD), (TE, KE), (TF, KF), (TG, KG) ); injected_tuples!( (TA, KA), (TB, KB), (TC, KC), (TD, KD), (TE, KE), (TF, KF), (TG, KG), (TH, KH) ); injected_tuples!( (TA, KA), (TB, KB), (TC, KC), (TD, KD), (TE, KE), (TF, KF), (TG, KG), (TH, KH), (TI, KI) ); injected_tuples!( (TA, KA), (TB, KB), (TC, KC), (TD, KD), (TE, KE), (TF, KF), (TG, KG), (TH, KH), (TI, KI), (TJ, KJ) ); injected_tuples!( (TA, KA), (TB, KB), (TC, KC), (TD, KD), (TE, KE), (TF, KF), (TG, KG), (TH, KH), (TI, KI), (TJ, KJ), (TK, KK) );