ntex 4.7.0

Framework for composable network services
Documentation
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
#![recursion_limit = "256"]
use std::{sync::mpsc, thread, time::Duration};

#[cfg(feature = "openssl")]
use tls_openssl::ssl::SslAcceptorBuilder;

#[cfg(feature = "rustls")]
mod rustls_utils;

use ntex::http::HttpServiceConfig;
#[cfg(feature = "openssl")]
use ntex::web::WebAppConfig;
use ntex::web::{self, App, HttpResponse, HttpServer};
use ntex::{SharedCfg, io::IoConfig, server::Affinity, server::TestServer, time::Seconds};
#[cfg(unix)]
use ntex::{rt, time::sleep};
use ntex_tls::TlsConfig;

/// STATEMENT: A configured `HttpServer` accepts HTTP requests and can be stopped.
///
/// HOW:
/// - Start a one-worker bound server with connection, TLS-handshake, keepalive, and timeout settings in another system thread.
/// - Send GET, assert success, then stop the server and system.
#[ntex::test]
async fn test_run() {
    let addr = TestServer::unused_addr();
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);

        sys.run(move || {
            let srv = HttpServer::new(async |_| {
                App::new().service(
                    web::resource("/").route(web::to(async || HttpResponse::Ok().body("test"))),
                )
            })
            .workers(1)
            .backlog(1)
            .max_connections(10)
            .max_tls_handshakes(10)
            .server_hostname("localhost")
            .stop_runtime()
            .disable_signals()
            .bind(
                format!("{addr}"),
                ntex::SharedCfg::new("WEB")
                    .add(
                        HttpServiceConfig::new()
                            .set_keepalive(10)
                            .set_client_timeout(Seconds(5)),
                    )
                    .add(IoConfig::new().set_shutdown_timeout(Seconds(1)))
                    .add(TlsConfig::new().set_handshake_timeout(Seconds(1))),
            )
            .unwrap()
            .run();
            let _ = tx.send((srv, ntex::rt::System::current()));
            Ok(())
        })
    });
    let (srv, sys) = rx.recv().unwrap();

    use ntex::client;

    let client = client::Client::with_config(
        ntex::SharedCfg::new("DBG").add(IoConfig::new().set_connect_timeout(30)),
    );

    let host = format!("http://{addr}");
    let response = client.get(host.clone()).send().await.unwrap();
    assert!(response.status().is_success());

    // stop
    srv.stop(false).await;

    thread::sleep(Duration::from_millis(25));
    sys.stop();
}

#[cfg(feature = "openssl")]
fn ssl_acceptor() -> std::io::Result<SslAcceptorBuilder> {
    use tls_openssl::ssl::{SslAcceptor, SslFiletype, SslMethod, SslVerifyMode};
    // load ssl keys
    let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
    builder.set_verify(SslVerifyMode::NONE);
    builder
        .set_private_key_file("./tests/key.pem", SslFiletype::PEM)
        .unwrap();
    builder
        .set_certificate_chain_file("./tests/cert.pem")
        .unwrap();
    Ok(builder)
}

#[cfg(feature = "openssl")]
async fn client() -> ntex::client::Client {
    use tls_openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
    let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
    builder.set_verify(SslVerifyMode::NONE);
    let _ = builder
        .set_alpn_protos(b"\x02h2\x08http/1.1")
        .map_err(|e| log::error!("Cannot set alpn protocol: {e:?}"));

    ntex::client::Client::builder()
        .openssl(builder.build())
        .build(
            SharedCfg::new("TEST")
                .add(IoConfig::new().set_connect_timeout(30))
                .add(ntex::client::ClientConfig::new().set_response_timeout(Seconds(30))),
        )
}

/// STATEMENT: An OpenSSL-bound `HttpServer` exposes secure app configuration to handlers.
///
/// HOW:
/// - Start `bind_openssl` with `WebAppConfig::set_secure` and assert `req.app_config().secure()` in the route.
/// - Send HTTPS GET with the OpenSSL client, assert success, and stop the server.
#[ntex::test]
#[cfg(feature = "openssl")]
async fn test_openssl() {
    use ntex::web::HttpRequest;

    let addr = TestServer::unused_addr();
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);
        let builder = ssl_acceptor().unwrap();

        sys.run(move || {
            let srv = HttpServer::new(async |_| {
                App::new().service(web::resource("/").route(web::to(
                    async move |req: HttpRequest| {
                        assert!(req.app_config().secure());
                        HttpResponse::Ok().body("test")
                    },
                )))
            })
            .workers(1)
            .graceful_shutdown_timeout(Seconds(1))
            .stop_runtime()
            .disable_signals()
            .bind_openssl(
                format!("{addr}"),
                builder,
                SharedCfg::new("WEB").add(WebAppConfig::new().set_secure()),
            )
            .unwrap()
            .run();
            let _ = tx.send((srv, ntex::rt::System::current()));
            Ok(())
        })
    });
    let (srv, sys) = rx.recv().unwrap();
    thread::sleep(Duration::from_millis(100));

    let client = client().await;
    let host = format!("https://{addr}");
    let response = client.get(host.clone()).send().await.unwrap();
    assert!(response.status().is_success());

    // stop
    srv.stop(false).await;

    thread::sleep(Duration::from_millis(25));
    sys.stop();
}

/// STATEMENT: A rustls-bound `HttpServer` exposes secure app configuration to handlers.
///
/// HOW:
/// - Start `bind_rustls` with secure app configuration and assert `req.app_config().secure()` in the route.
/// - Send HTTPS GET with the OpenSSL client, assert success, and stop the server.
#[ntex::test]
#[cfg(all(unix, feature = "rustls", feature = "openssl"))]
async fn test_rustls() {
    use ntex::web::HttpRequest;

    let addr = TestServer::unused_addr();
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);
        let config = rustls_utils::tls_acceptor();

        sys.run(move || {
            let srv = HttpServer::new(async |_| {
                App::new().service(web::resource("/").route(web::to(async |req: HttpRequest| {
                    assert!(req.app_config().secure());
                    HttpResponse::Ok().body("test")
                })))
            })
            .workers(1)
            .graceful_shutdown_timeout(Seconds(1))
            .stop_runtime()
            .disable_signals()
            .bind_rustls(
                format!("{addr}"),
                &config,
                SharedCfg::new("WEB").add(WebAppConfig::new().set_secure()),
            )
            .unwrap()
            .run();
            let _ = tx.send((srv, ntex::rt::System::current()));
            Ok(())
        })
    });
    let (srv, sys) = rx.recv().unwrap();

    let client = client().await;
    let host = format!("https://localhost:{}", addr.port());
    let response = client.get(host).send().await.unwrap();
    assert!(response.status().is_success());

    // stop
    srv.stop(false).await;

    sleep(Duration::from_millis(25)).await;
    sys.stop();
}

/// STATEMENT: `HttpServer::bind_uds` serves HTTP over a Unix-domain socket.
///
/// HOW:
/// - Bind a Unix-domain endpoint and configure a client connector using `rt::unix_connect`.
/// - Send GET through that connector, assert success, then stop the server and system.
#[ntex::test]
#[cfg(unix)]
async fn test_bind_uds() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);

        sys.run(move || {
            let srv = HttpServer::new(async |_| {
                App::new().service(
                    web::resource("/").route(web::to(async || HttpResponse::Ok().body("test"))),
                )
            })
            .workers(1)
            .graceful_shutdown_timeout(Seconds(1))
            .stop_runtime()
            .disable_signals()
            .bind_uds("/tmp/uds-test", SharedCfg::default())
            .unwrap()
            .run();
            let _ = tx.send((srv, ntex::rt::System::current()));
            Ok(())
        })
    });
    let (srv, sys) = rx.recv().unwrap();

    use ntex::client;

    let client = client::Client::builder()
        .connector(async |st: &SharedCfg, _| {
            Ok(rt::unix_connect("/tmp/uds-test", st.clone())
                .await
                .map_err(ntex::connect::ConnectError::from)?)
        })
        .build(SharedCfg::default());
    let response = client.get("http://localhost").send().await.unwrap();
    assert!(response.status().is_success());

    // stop
    srv.stop(false).await;

    sleep(Duration::from_millis(25)).await;
    sys.stop();
}

/// Returns the sorted names of this process's accept threads for server `name`.
#[cfg(target_os = "linux")]
fn accept_threads(name: &str) -> Vec<String> {
    let prefix = format!("{name}:accept");
    let mut names: Vec<String> = std::fs::read_dir("/proc/self/task")
        .unwrap()
        .filter_map(|e| std::fs::read_to_string(e.ok()?.path().join("comm")).ok())
        .map(|s| s.trim().to_string())
        .filter(|s| s.starts_with(&prefix))
        .collect();
    names.sort();
    names
}

/// STATEMENT: `HttpServer::acceptors` sets the number of accept threads of the underlying
/// server, and the server keeps serving HTTP with several of them.
///
/// HOW:
/// - Start a one-worker `HttpServer` with `acceptors(3)` in a system named `wacc`.
/// - On Linux, check that three `wacc:accept*` threads run.
/// - Send several GET requests, assert each succeeds, then stop the server and system.
#[ntex::test]
async fn test_acceptors() {
    let addr = TestServer::unused_addr();
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let sys = ntex::rt::System::new("wacc", ntex::rt::DefaultRuntime);

        sys.run(move || {
            let srv = HttpServer::new(async |_| {
                App::new().service(
                    web::resource("/").route(web::to(async || HttpResponse::Ok().body("test"))),
                )
            })
            .workers(1)
            .acceptors(3)
            .disable_signals()
            .bind(format!("{addr}"), SharedCfg::new("WEB"))
            .unwrap()
            .run();
            let _ = tx.send((srv, ntex::rt::System::current()));
            Ok(())
        })
    });
    let (srv, sys) = rx.recv().unwrap();

    #[cfg(target_os = "linux")]
    assert_eq!(
        accept_threads("wacc"),
        ["wacc:accept", "wacc:accept1", "wacc:accept2"]
    );

    let client = ntex::client::Client::with_config(
        SharedCfg::new("DBG").add(IoConfig::new().set_connect_timeout(30)),
    );
    for _ in 0..8 {
        let response = client.get(format!("http://{addr}")).send().await.unwrap();
        assert!(response.status().is_success());
    }

    srv.stop(false).await;
    thread::sleep(Duration::from_millis(25));
    sys.stop();
}

/// STATEMENT: `HttpServer::listen_uds` serves HTTP from a supplied Unix listener.
///
/// HOW:
/// - Create a `UnixListener`, pass it to the server, and configure a client using `rt::unix_connect`.
/// - Send GET through the Unix socket, assert success, then stop the server and system.
#[ntex::test]
#[cfg(unix)]
async fn test_listen_uds() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);

        sys.run(move || {
            let _ = std::fs::remove_file("/tmp/uds-test2");
            let lst = std::os::unix::net::UnixListener::bind("/tmp/uds-test2").unwrap();

            let srv = HttpServer::new(async |_| {
                App::new().service(
                    web::resource("/").route(web::to(async || HttpResponse::Ok().body("test"))),
                )
            })
            .workers(1)
            .graceful_shutdown_timeout(Seconds(1))
            .stop_runtime()
            .disable_signals()
            .listen_uds(lst, SharedCfg::default())
            .unwrap()
            .run();
            let _ = tx.send((srv, ntex::rt::System::current()));
            Ok(())
        })
    });
    let (srv, sys) = rx.recv().unwrap();

    use ntex::client;

    let client = client::Client::builder()
        .connector(async |st: &SharedCfg, _| {
            Ok(rt::unix_connect("/tmp/uds-test2", st.clone())
                .await
                .map_err(ntex::connect::ConnectError::from)?)
        })
        .build(SharedCfg::default());
    let response = client.get("http://localhost").send().await.unwrap();
    assert!(response.status().is_success());

    // stop
    srv.stop(false).await;

    sleep(Duration::from_millis(25)).await;
    sys.stop();
}

#[derive(Clone)]
struct Counter(usize);

impl web::State for Counter {
    type Error = web::DefaultError;
}

struct CounterConfig;

impl ntex::server::ServerAppConfig for CounterConfig {
    type State = Counter;

    async fn create(&self) -> std::io::Result<Counter> {
        Ok(Counter(42))
    }
}

/// STATEMENT: `server_with_config` provides initialized application state to factories and handlers.
///
/// HOW:
/// - Use `CounterConfig` to construct `Counter(42)` and assert the factory receives `42`.
/// - Send GET to a state-aware route, assert success and body `42`, then stop the server.
#[ntex::test]
async fn test_with_config() {
    let addr = TestServer::unused_addr();
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);

        sys.run(move || {
            let srv = web::server_with_config(CounterConfig, async |st: &Counter| {
                assert_eq!(st.0, 42);
                App::new().service(web::resource("/").route(web::get().to_with_state(
                    async |st: &Counter, _: ()| HttpResponse::Ok().body(format!("{}", st.0)),
                )))
            })
            .workers(1)
            .stop_on_panic()
            .affinity(Affinity::Core)
            .graceful_shutdown()
            .stop_runtime()
            .disable_signals()
            .bind(format!("{addr}"), SharedCfg::default())
            .unwrap()
            .run();
            let _ = tx.send((srv, ntex::rt::System::current()));
            Ok(())
        })
    });
    let (srv, sys) = rx.recv().unwrap();

    let client = ntex::client::Client::new();
    let response = client.get(format!("http://{addr}")).send().await.unwrap();
    assert!(response.status().is_success());
    assert_eq!(response.body().await.unwrap(), "42");

    srv.stop(false).await;
    thread::sleep(Duration::from_millis(25));
    sys.stop();
}

/// STATEMENT: `HttpServer::bind` reports occupied and empty address inputs distinctly.
///
/// HOW:
/// - Keep a TCP listener open and attempt to bind a server to its address.
/// - Assert `AddrInUse`, then bind an empty address slice and assert `InvalidInput`.
#[ntex::test]
async fn test_bind_error() {
    let lst = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = lst.local_addr().unwrap();

    let res = HttpServer::new(async |_| {
        App::new().service(web::resource("/").to(async || HttpResponse::Ok()))
    })
    .disable_signals()
    .bind(addr, SharedCfg::default());
    assert_eq!(
        res.err().unwrap().kind(),
        std::io::ErrorKind::AddrInUse,
        "address is in use"
    );

    let res = HttpServer::new(async |_| {
        App::new().service(web::resource("/").to(async || HttpResponse::Ok()))
    })
    .disable_signals()
    .bind(&[][..] as &[std::net::SocketAddr], SharedCfg::default());
    assert_eq!(
        res.err().unwrap().kind(),
        std::io::ErrorKind::InvalidInput,
        "no addresses"
    );
}

#[cfg(feature = "openssl")]
async fn client_alpn(protos: &[u8]) -> ntex::client::Client {
    use tls_openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
    let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
    builder.set_verify(SslVerifyMode::NONE);
    builder.set_alpn_protos(protos).unwrap();

    ntex::client::Client::builder()
        .openssl(builder.build())
        .build(SharedCfg::default())
}

/// STATEMENT: An OpenSSL listener negotiates supported ALPN and falls back to HTTP/1.1 for unknown protocols.
///
/// HOW:
/// - Serve the request version from a supplied OpenSSL TCP listener.
/// - Offer HTTP/2 plus HTTP/1.1, HTTP/1.1 only, and an unknown protocol; assert successful responses with versions HTTP/2, HTTP/1.1, and HTTP/1.1 respectively.
#[ntex::test]
#[cfg(feature = "openssl")]
async fn test_listen_openssl() {
    let lst = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = lst.local_addr().unwrap();
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);
        let builder = ssl_acceptor().unwrap();

        sys.run(move || {
            let srv = HttpServer::new(async |_| {
                App::new().service(web::resource("/").route(web::to(
                    async |req: web::HttpRequest| {
                        HttpResponse::Ok().body(format!("{:?}", req.version()))
                    },
                )))
            })
            .workers(1)
            .stop_runtime()
            .disable_signals()
            .listen_openssl(lst, SharedCfg::default(), builder)
            .unwrap()
            .run();
            let _ = tx.send((srv, ntex::rt::System::current()));
            Ok(())
        })
    });
    let (srv, sys) = rx.recv().unwrap();

    let host = format!("https://{addr}");
    for (protos, version) in [
        (&b"\x02h2\x08http/1.1"[..], "HTTP/2.0"),
        (&b"\x08http/1.1"[..], "HTTP/1.1"),
        // unknown protocol, server does not select alpn protocol
        (&b"\x06spdy/1"[..], "HTTP/1.1"),
    ] {
        let client = client_alpn(protos).await;
        let response = client.get(host.clone()).send().await.unwrap();
        assert!(response.status().is_success());
        assert_eq!(response.body().await.unwrap(), version);
    }

    srv.stop(false).await;
    thread::sleep(Duration::from_millis(25));
    sys.stop();
}

/// STATEMENT: `HttpServer::listen_rustls` serves HTTPS from a supplied TCP listener.
///
/// HOW:
/// - Start a rustls server using an existing listener and its TLS configuration.
/// - Send HTTPS GET with an OpenSSL client, assert success, and stop the server and system.
#[ntex::test]
#[cfg(all(feature = "rustls", feature = "openssl"))]
async fn test_listen_rustls() {
    let lst = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = lst.local_addr().unwrap();
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);
        let config = rustls_utils::tls_acceptor();

        sys.run(move || {
            let srv = HttpServer::new(async |_| {
                App::new().service(
                    web::resource("/").route(web::to(async || HttpResponse::Ok().body("test"))),
                )
            })
            .workers(1)
            .stop_runtime()
            .disable_signals()
            .listen_rustls(lst, SharedCfg::default(), config)
            .unwrap()
            .run();
            let _ = tx.send((srv, ntex::rt::System::current()));
            Ok(())
        })
    });
    let (srv, sys) = rx.recv().unwrap();

    let client = client().await;
    let response = client.get(format!("https://{addr}")).send().await.unwrap();
    assert!(response.status().is_success());

    srv.stop(false).await;
    thread::sleep(Duration::from_millis(25));
    sys.stop();
}