1use std::{cell::RefCell, mem, rc::Rc};
2
3use actix_http::Request;
4use actix_router::{Path, ResourceDef, Router, Url};
5use actix_service::{boxed, fn_service, Service, ServiceFactory};
6use futures_core::future::LocalBoxFuture;
7use futures_util::future::join_all;
8
9use crate::{
10 body::BoxBody,
11 config::{AppConfig, AppService},
12 data::FnDataFactory,
13 dev::Extensions,
14 guard::Guard,
15 request::{HttpRequest, HttpRequestPool},
16 rmap::ResourceMap,
17 service::{
18 AppServiceFactory, BoxedHttpService, BoxedHttpServiceFactory, ServiceRequest,
19 ServiceResponse,
20 },
21 Error, HttpResponse,
22};
23
24pub struct AppInit<T, B>
28where
29 T: ServiceFactory<
30 ServiceRequest,
31 Config = (),
32 Response = ServiceResponse<B>,
33 Error = Error,
34 InitError = (),
35 >,
36{
37 pub(crate) endpoint: T,
38 pub(crate) extensions: RefCell<Option<Extensions>>,
39 pub(crate) async_data_factories: Rc<[FnDataFactory]>,
40 pub(crate) services: Rc<RefCell<Vec<Box<dyn AppServiceFactory>>>>,
41 pub(crate) default: Option<Rc<BoxedHttpServiceFactory>>,
42 pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
43 pub(crate) external: RefCell<Vec<ResourceDef>>,
44 #[cfg(feature = "experimental-introspection")]
45 pub(crate) introspector: Rc<RefCell<crate::introspection::IntrospectionCollector>>,
46}
47
48impl<T, B> ServiceFactory<Request> for AppInit<T, B>
49where
50 T: ServiceFactory<
51 ServiceRequest,
52 Config = (),
53 Response = ServiceResponse<B>,
54 Error = Error,
55 InitError = (),
56 >,
57 T::Future: 'static,
58{
59 type Response = ServiceResponse<B>;
60 type Error = T::Error;
61 type Config = AppConfig;
62 type Service = AppInitService<T::Service, B>;
63 type InitError = T::InitError;
64 type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
65
66 fn new_service(&self, config: AppConfig) -> Self::Future {
67 let default = self.default.clone().unwrap_or_else(|| {
70 Rc::new(boxed::factory(fn_service(|req: ServiceRequest| async {
71 Ok(req.into_response(HttpResponse::NotFound()))
72 })))
73 });
74
75 let mut config = AppService::new(config, Rc::clone(&default));
77 #[cfg(feature = "experimental-introspection")]
78 {
79 config.introspector = Rc::clone(&self.introspector);
80 }
81
82 mem::take(&mut *self.services.borrow_mut())
84 .into_iter()
85 .for_each(|mut srv| srv.register(&mut config));
86
87 let mut rmap = ResourceMap::new(ResourceDef::prefix(""));
88
89 #[cfg(feature = "experimental-introspection")]
90 let (config, services, _) = config.into_services();
91 #[cfg(not(feature = "experimental-introspection"))]
92 let (config, services) = config.into_services();
93
94 *self.factory_ref.borrow_mut() = Some(AppRoutingFactory {
96 default,
97 services: services
98 .into_iter()
99 .map(|(mut rdef, srv, guards, nested)| {
100 rmap.add(&mut rdef, nested);
101 (rdef, srv, RefCell::new(guards))
102 })
103 .collect::<Vec<_>>()
104 .into_boxed_slice()
105 .into(),
106 });
107
108 for mut rdef in mem::take(&mut *self.external.borrow_mut()) {
110 #[cfg(feature = "experimental-introspection")]
111 {
112 self.introspector.borrow_mut().register_external(&rdef, "/");
113 }
114 rmap.add(&mut rdef, None);
115 }
116
117 let rmap = Rc::new(rmap);
119 ResourceMap::finish(&rmap);
120
121 let factory_futs = join_all(self.async_data_factories.iter().map(|f| f()));
123
124 let endpoint_fut = self.endpoint.new_service(());
126 #[cfg(feature = "experimental-introspection")]
127 let introspector = Rc::clone(&self.introspector);
128
129 let mut app_data = self.extensions.borrow_mut().take().unwrap_or_default();
131
132 Box::pin(async move {
133 let async_data_factories = factory_futs
135 .await
136 .into_iter()
137 .collect::<Result<Vec<_>, _>>()
138 .map_err(|_| ())?;
139
140 let service = endpoint_fut.await?;
142
143 for factory in &async_data_factories {
145 factory.create(&mut app_data);
146 }
147
148 #[cfg(feature = "experimental-introspection")]
149 {
150 let tree = introspector.borrow_mut().finalize();
151 app_data.insert(crate::web::Data::new(tree));
152 }
153
154 Ok(AppInitService {
155 service,
156 app_data: Rc::new(app_data),
157 app_state: AppInitServiceState::new(rmap, config),
158 })
159 })
160 }
161}
162
163pub struct AppInitService<T, B>
167where
168 T: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
169{
170 service: T,
171 app_data: Rc<Extensions>,
172 app_state: Rc<AppInitServiceState>,
173}
174
175pub(crate) struct AppInitServiceState {
177 rmap: Rc<ResourceMap>,
178 config: AppConfig,
179 pool: HttpRequestPool,
180}
181
182impl AppInitServiceState {
183 pub(crate) fn new(rmap: Rc<ResourceMap>, config: AppConfig) -> Rc<Self> {
185 Rc::new(AppInitServiceState {
186 rmap,
187 config,
188 pool: HttpRequestPool::default(),
189 })
190 }
191
192 #[inline]
194 pub(crate) fn rmap(&self) -> &ResourceMap {
195 &self.rmap
196 }
197
198 #[inline]
200 pub(crate) fn config(&self) -> &AppConfig {
201 &self.config
202 }
203
204 #[inline]
206 pub(crate) fn pool(&self) -> &HttpRequestPool {
207 &self.pool
208 }
209}
210
211impl<T, B> Service<Request> for AppInitService<T, B>
212where
213 T: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
214{
215 type Response = ServiceResponse<B>;
216 type Error = T::Error;
217 type Future = T::Future;
218
219 actix_service::forward_ready!(service);
220
221 fn call(&self, mut req: Request) -> Self::Future {
222 let extensions = Rc::new(RefCell::new(req.take_req_data()));
223 let conn_data = req.take_conn_data();
224 let (head, payload) = req.into_parts();
225
226 let req = match self.app_state.pool().pop() {
227 Some(mut req) => {
228 let inner = Rc::get_mut(&mut req.inner).unwrap();
229 inner.path.get_mut().update(&head.uri);
230 inner.path.reset();
231 inner.head = head;
232 inner.conn_data = conn_data;
233 inner.extensions = extensions;
234 req
235 }
236
237 None => HttpRequest::new(
238 Path::new(Url::new(head.uri.clone())),
239 head,
240 Rc::clone(&self.app_state),
241 Rc::clone(&self.app_data),
242 conn_data,
243 extensions,
244 ),
245 };
246
247 self.service.call(ServiceRequest::new(req, payload))
248 }
249}
250
251impl<T, B> Drop for AppInitService<T, B>
252where
253 T: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
254{
255 fn drop(&mut self) {
256 self.app_state.pool().clear();
257 }
258}
259
260pub struct AppRoutingFactory {
261 #[allow(clippy::type_complexity)]
262 services: Rc<
263 [(
264 ResourceDef,
265 BoxedHttpServiceFactory,
266 RefCell<Option<Vec<Box<dyn Guard>>>>,
267 )],
268 >,
269 default: Rc<BoxedHttpServiceFactory>,
270}
271
272impl ServiceFactory<ServiceRequest> for AppRoutingFactory {
273 type Response = ServiceResponse;
274 type Error = Error;
275 type Config = ();
276 type Service = AppRouting;
277 type InitError = ();
278 type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
279
280 fn new_service(&self, _: ()) -> Self::Future {
281 let factory_fut = join_all(self.services.iter().map(|(path, factory, guards)| {
283 let path = path.clone();
284 let guards = guards.borrow_mut().take().unwrap_or_default();
285 let factory_fut = factory.new_service(());
286 async move {
287 factory_fut
288 .await
289 .map(move |service| (path, guards, service))
290 }
291 }));
292
293 let default_fut = self.default.new_service(());
295
296 Box::pin(async move {
297 let default = default_fut.await?;
298
299 let router = factory_fut
301 .await
302 .into_iter()
303 .collect::<Result<Vec<_>, _>>()?
304 .drain(..)
305 .fold(Router::build(), |mut router, (path, guards, service)| {
306 router.push(path, service, guards);
307 router
308 })
309 .finish();
310
311 Ok(AppRouting { router, default })
312 })
313 }
314}
315
316pub struct AppRouting {
318 router: Router<BoxedHttpService, Vec<Box<dyn Guard>>>,
319 default: BoxedHttpService,
320}
321
322impl Service<ServiceRequest> for AppRouting {
323 type Response = ServiceResponse<BoxBody>;
324 type Error = Error;
325 type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
326
327 actix_service::always_ready!();
328
329 fn call(&self, mut req: ServiceRequest) -> Self::Future {
330 let res = self.router.recognize_fn(&mut req, |req, guards| {
331 let guard_ctx = req.guard_ctx();
332 guards.iter().all(|guard| guard.check(&guard_ctx))
333 });
334
335 if let Some((srv, _info)) = res {
336 srv.call(req)
337 } else {
338 self.default.call(req)
339 }
340 }
341}
342
343pub struct AppEntry {
345 factory: Rc<RefCell<Option<AppRoutingFactory>>>,
346}
347
348impl AppEntry {
349 pub fn new(factory: Rc<RefCell<Option<AppRoutingFactory>>>) -> Self {
350 AppEntry { factory }
351 }
352}
353
354impl ServiceFactory<ServiceRequest> for AppEntry {
355 type Response = ServiceResponse;
356 type Error = Error;
357 type Config = ();
358 type Service = AppRouting;
359 type InitError = ();
360 type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
361
362 fn new_service(&self, _: ()) -> Self::Future {
363 self.factory.borrow_mut().as_mut().unwrap().new_service(())
364 }
365}
366
367#[cfg(test)]
368mod tests {
369 use std::sync::{
370 atomic::{AtomicBool, Ordering},
371 Arc,
372 };
373
374 use actix_service::Service;
375
376 use crate::{
377 test::{init_service, TestRequest},
378 web, App, HttpResponse,
379 };
380
381 struct DropData(Arc<AtomicBool>);
382
383 impl Drop for DropData {
384 fn drop(&mut self) {
385 self.0.store(true, Ordering::Relaxed);
386 }
387 }
388
389 #[allow(deprecated)]
391 #[actix_rt::test]
392 async fn test_drop_data() {
393 let data = Arc::new(AtomicBool::new(false));
394
395 {
396 let app = init_service(
397 App::new()
398 .data(DropData(data.clone()))
399 .service(web::resource("/test").to(HttpResponse::Ok)),
400 )
401 .await;
402 let req = TestRequest::with_uri("/test").to_request();
403 let _ = app.call(req).await.unwrap();
404 }
405 assert!(data.load(Ordering::Relaxed));
406 }
407}