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
use std::{any::Any, any::TypeId, cell::UnsafeCell, net::SocketAddr, rc::Rc};
use urly::Url;
use crate::service::cfg::{CfgContext, Configuration};
use crate::{router::ResourceDef, util::ByteString, util::HashMap};
use super::httprequest::{HttpRequest, HttpRequestInner};
use super::service::{AppServiceFactory, ServiceFactoryWrapper, WebServiceFactory};
use super::{Resource, Route, State};
/// Application configuration
#[derive(Debug)]
pub struct WebAppConfig {
name: ByteString,
secure: bool,
host: String,
addr: SocketAddr,
config: CfgContext,
state: HashMap<TypeId, Box<dyn Any + Sync + Send>>,
pub(super) pool_size: usize,
}
impl Default for WebAppConfig {
fn default() -> Self {
WebAppConfig::new()
}
}
impl Configuration for WebAppConfig {
const NAME: &str = "Web app configuration";
fn ctx(&self) -> &CfgContext {
&self.config
}
fn set_ctx(&mut self, ctx: CfgContext) {
self.config = ctx;
}
}
impl WebAppConfig {
#[must_use]
/// Create an default `WebAppConfig` instance.
pub fn new() -> Self {
WebAppConfig::with(
"ntex:web",
false,
"127.0.0.1:8080".parse().unwrap(),
"localhost:8080".to_owned(),
)
}
#[must_use]
/// Create an `WebAppConfig` instance.
pub fn with(name: &str, secure: bool, addr: SocketAddr, host: String) -> Self {
WebAppConfig {
secure,
host,
addr,
name: name.into(),
pool_size: 128,
state: HashMap::default(),
config: CfgContext::default(),
}
}
/// Server name
pub fn name(&self) -> &ByteString {
&self.name
}
/// Server host name
///
/// Host name is used by application router as a hostname for url generation.
/// Check [`ConnectionInfo::host()`](crate::web::dev::ConnectionInfo::host)
/// documentation for more information.
///
/// By default host name is set to a "localhost:8080" value.
pub fn host(&self) -> &str {
&self.host
}
/// Returns true if connection is secure(https)
pub fn secure(&self) -> bool {
self.secure
}
/// Returns the socket address of the local half of this TCP connection
pub fn local_addr(&self) -> SocketAddr {
self.addr
}
/// Get an application state object stored with `.set_state()` method.
pub fn state<T: 'static>(&self) -> Option<&T> {
self.state
.get(&TypeId::of::<T>())
.and_then(|boxed| boxed.downcast_ref())
}
#[must_use]
/// Set server host name.
///
/// By default host name is set to a "localhost:8080" value.
pub fn set_host(mut self, host: String) -> Self {
self.host = host;
self
}
#[must_use]
/// Connection is secure(https).
pub fn set_secure(mut self) -> Self {
self.secure = true;
self
}
#[must_use]
/// Set the socket address of the local half of the TCP connection.
pub fn set_local_addr(mut self, addr: SocketAddr) -> Self {
self.addr = addr;
self
}
#[must_use]
/// Set size of `HttpRequest` pool size.
///
/// By default pool size is 128.
pub fn set_pool_size(mut self, size: usize) -> Self {
self.pool_size = size;
self
}
#[must_use]
/// Set application level arbitrary state item.
///
/// Application state stored with `.set_state()` method is available
/// via `HttpRequest::app_state()` method at runtime.
pub fn set_state<T: Send + Sync + 'static>(mut self, val: T) -> Self {
self.state
.insert(TypeId::of::<T>(), Box::new(val))
.and_then(|item| item.downcast::<T>().map(|boxed| *boxed).ok());
self
}
/// Get message from the pool.
pub(crate) fn get_request(&self) -> Option<HttpRequest> {
CACHE.with(|cache| cache.with(self.config.id(), |cache| cache.pop().map(HttpRequest)))
}
}
/// Put message from the pool.
pub(crate) fn put_request(id: usize, pool_size: usize, req: &mut Rc<HttpRequestInner>) {
CACHE.with(|cache| {
cache.with(id, |cache| {
if cache.len() < pool_size
&& let Some(inner) = Rc::get_mut(req)
{
// the head and the path may share the connection read buffer,
// a pooled request must not keep it alive
inner.head.clear();
inner.path.set(Url::new());
cache.push(req.clone());
}
});
});
}
/// Service config is used for external configuration.
///
/// Part of application configuration could be offloaded
/// to set of external methods. This could help with
/// modularization of big application configuration.
///
/// `St` is the application state and defaults to `()`. Use
/// `ServiceConfig<AppState<T>>` for a stateful application, or a generic
/// `fn config<St: web::State>(cfg: &mut ServiceConfig<St>)` for a module that
/// works with any state.
#[derive(derive_more::Debug)]
#[debug("ServiceConfig")]
pub struct ServiceConfig<St = (), In = ()> {
pub(super) services: Vec<Box<dyn AppServiceFactory<St, In>>>,
pub(super) external: Vec<ResourceDef>,
}
impl<St: State, In: 'static> ServiceConfig<St, In> {
/// Create a service configuration with the given external resources.
pub fn new(external: Vec<ResourceDef>) -> Self {
Self {
external,
services: Vec::new(),
}
}
/// Register a route for an application path.
///
/// This has the same behavior as [`App::route()`]: it creates a separate
/// resource containing the route and promotes the route's method and custom
/// guards to resource guards.
///
/// [`App::route()`]: super::App::route
pub fn route(&mut self, path: &str, mut route: Route<St, In>) -> &mut Self {
self.service(
Resource::new(path)
.add_guards(route.take_guards())
.route(route),
)
}
/// Registers a web service with the current application or scope.
///
/// This has the same routing behavior as [`App::service()`]. The service
/// can be a resource, scope, attribute-macro handler, or custom
/// [`WebServiceFactory`]. When this configuration is used by a scope, the
/// service is registered below that scope's path prefix.
///
/// ```rust
/// use ntex::web::{self, App, ServiceConfig};
///
/// fn configure(cfg: &mut ServiceConfig<()>) {
/// cfg.service(
/// web::resource("/health").to(async || "OK"),
/// );
/// }
///
/// App::default().configure(configure);
/// ```
///
/// [`App::service()`]: super::App::service
pub fn service<F>(&mut self, factory: F) -> &mut Self
where
F: WebServiceFactory<St, In> + 'static,
{
self.services
.push(Box::new(ServiceFactoryWrapper::new(factory)));
self
}
/// Register an external resource.
///
/// External resources are useful for URL generation purposes only
/// and are never considered for matching at request time. Calls to
/// `HttpRequest::url_for()` will work as expected.
///
/// This is same as `App::external_resource()` method.
pub fn external_resource(&mut self, name: impl AsRef<str>, url: impl AsRef<str>) -> &mut Self {
let mut rdef = ResourceDef::new(url.as_ref());
rdef.set_name(name.as_ref());
self.external.push(rdef);
self
}
}
thread_local! {
static CACHE: LocalCache = LocalCache::new();
}
/// Request's objects pool
struct LocalCache {
cache: UnsafeCell<Vec<Vec<Rc<HttpRequestInner>>>>,
}
impl LocalCache {
fn new() -> Self {
Self {
cache: UnsafeCell::new(Vec::with_capacity(16)),
}
}
fn with<F, R>(&self, idx: usize, f: F) -> R
where
F: FnOnce(&mut Vec<Rc<HttpRequestInner>>) -> R,
{
let cache = unsafe { &mut *self.cache.get() };
while cache.len() <= idx {
cache.push(Vec::new());
}
f(&mut cache[idx])
}
}
#[cfg(test)]
#[allow(clippy::assert_is_empty)]
mod tests {
use super::*;
use crate::http::{Method, StatusCode};
use crate::util::Bytes;
use crate::web::test::{TestRequest, call_service, init_service, read_body};
use crate::web::{self, App, HttpRequest, HttpResponse};
/// STATEMENT: `WebAppConfig` retains explicit settings and exposes its default identity.
///
/// HOW:
/// - Set the host, local address, and pool size and assert their stored values.
/// - Check the default name and insecure mode, then enable and assert secure mode.
#[crate::rt_test]
async fn test_webappconfig() {
let cfg = WebAppConfig::default()
.set_host("www.example.org".to_string())
.set_local_addr("127.0.0.1:8080".parse().unwrap())
.set_pool_size(256);
assert_eq!(cfg.host(), "www.example.org");
assert_eq!(cfg.local_addr(), "127.0.0.1:8080".parse().unwrap());
assert_eq!(cfg.pool_size, 256);
assert_eq!(cfg.name(), "ntex:web");
assert!(!cfg.secure());
assert!(cfg.set_secure().secure());
}
/// STATEMENT: An external resource registered through `configure` supports URL generation.
///
/// HOW:
/// - Configure a named YouTube resource and return its generated URL from `/test`.
/// - Call the service and assert an OK response containing the substituted video URL.
#[crate::rt_test]
async fn test_configure_external_resource() {
let srv = init_service(
App::new()
.configure(|cfg| {
cfg.external_resource("youtube", "https://youtube.com/watch/{video_id}");
})
.route(
"/test",
web::get().to(async move |req: HttpRequest| {
HttpResponse::Ok()
.body(format!("{}", req.url_for("youtube", ["12345"]).unwrap()))
}),
),
)
.await;
let req = TestRequest::with_uri("/test").to_request();
let resp = call_service(&srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
let body = read_body(resp).await;
assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345"));
}
/// STATEMENT: `ServiceConfig` registers both resources and direct routes in an application.
///
/// HOW:
/// - Configure a resource returning `Created` and a direct route returning `Ok`.
/// - Send GET requests to both paths and assert their distinct response statuses.
#[crate::rt_test]
async fn test_configure_service() {
let srv = init_service(App::new().configure(|cfg| {
cfg.service(
web::resource("/test").route(web::get().to(async || HttpResponse::Created())),
)
.route("/index.html", web::get().to(async || HttpResponse::Ok()));
}))
.await;
let req = TestRequest::with_uri("/test")
.method(Method::GET)
.to_request();
let resp = call_service(&srv, req).await;
assert_eq!(resp.status(), StatusCode::CREATED);
let req = TestRequest::with_uri("/index.html")
.method(Method::GET)
.to_request();
let resp = call_service(&srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
}
/// STATEMENT: A fresh `ServiceConfig` contains no services or external resources.
///
/// HOW:
/// - Construct `ServiceConfig::new` with an empty vector.
/// - Assert both registration collections are empty.
#[test]
fn test_new_service_config() {
let cfg: ServiceConfig<(), ()> = ServiceConfig::new(Vec::new());
assert!(cfg.services.is_empty());
assert!(cfg.external.is_empty());
}
}