ntex 4.9.2

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
#[cfg(unix)]
use std::io::{Read, Write};
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
use std::{net, sync::Arc, sync::mpsc, thread, time};

use ntex::server::{TestServer, build, build_with_config};
use ntex::service::{cfg::SharedCfg, fn_service};
use ntex::{codec::BytesCodec, io::Io, util::Bytes};

/// STATEMENT: A server built with `bind` accepts TCP connections.
///
/// HOW:
/// - Start a one-worker server on an unused address in a separate system thread.
/// - Assert a TCP connection succeeds, then stop the system and join the thread.
#[test]
fn test_bind() {
    let addr = TestServer::unused_addr();
    let (tx, rx) = mpsc::channel();

    let h = thread::spawn(move || {
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);
        sys.run(move || {
            let srv = build()
                .workers(1)
                .disable_signals()
                .bind("test", addr, SharedCfg::default(), async move |_| {
                    async |_| Ok::<_, ()>(())
                })
                .unwrap()
                .run();
            let _ = tx.send((srv, ntex::rt::System::current()));
            Ok(())
        })
    });
    let (_, sys) = rx.recv().unwrap();

    thread::sleep(time::Duration::from_millis(300));
    assert!(net::TcpStream::connect(addr).is_ok());
    sys.stop();
    let _ = h.join();
}

/// STATEMENT: A server accepts connections from a supplied TCP listener and supports graceful stop.
///
/// HOW:
/// - Pass a bound `TcpListener` to `listen` and start a one-worker server.
/// - Assert a TCP connection succeeds, await `stop(true)`, and stop and join the system.
#[ntex::test]
async fn test_listen() {
    let addr = TestServer::unused_addr();
    let (tx, rx) = mpsc::channel();

    let h = thread::spawn(move || {
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);
        let lst = net::TcpListener::bind(addr).unwrap();
        let _ = sys.run(move || {
            let srv = build()
                .disable_signals()
                .workers(1)
                .listen("test", lst, SharedCfg::default(), async move |_| {
                    async |_| Ok::<_, ()>(())
                })
                .unwrap()
                .run();
            let _ = tx.send((srv, ntex::rt::System::current()));
            Ok(())
        });
    });
    let (srv, sys) = rx.recv().unwrap();

    thread::sleep(time::Duration::from_millis(500));
    assert!(net::TcpStream::connect(addr).is_ok());

    srv.stop(true).await;
    sys.stop();
    let _ = h.join();
}

/// STATEMENT: Server pause, resume, and stop control connection processing.
///
/// HOW:
/// - Start a server sending `test` and assert the bytes are received.
/// - Pause and confirm a read times out, resume and confirm connections and response bytes succeed, then stop and assert new connections fail.
#[ntex::test]
#[cfg(unix)]
#[allow(clippy::unused_io_amount)]
async fn test_run() {
    let addr = TestServer::unused_addr();
    let (tx, rx) = mpsc::channel();

    let h = thread::spawn(move || {
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);
        sys.run(move || {
            let srv = build()
                .backlog(100)
                .workers(1)
                .disable_signals()
                .bind("test", addr, SharedCfg::new("SRV"), async move |_| {
                    async move |io: Io| {
                        let _ = io.send(Bytes::from_static(b"test"), &BytesCodec).await;
                        Ok::<_, ()>(())
                    }
                })
                .unwrap()
                .run();
            let _ = tx.send((srv, ntex::rt::System::current()));
            Ok(())
        })
    });
    let (srv, sys) = rx.recv().unwrap();

    let mut buf = [1u8; 4];
    let mut conn = net::TcpStream::connect(addr).unwrap();
    conn.write(&b"test"[..]).unwrap();
    let _ = conn.read_exact(&mut buf);
    assert_eq!(buf, b"test"[..]);

    // pause
    srv.pause().await;
    thread::sleep(time::Duration::from_millis(200));
    let mut conn = net::TcpStream::connect(addr).unwrap();
    conn.set_read_timeout(Some(time::Duration::from_millis(100)))
        .unwrap();
    let res = conn.read_exact(&mut buf);
    assert!(res.is_err());

    // resume
    srv.resume().await;
    thread::sleep(time::Duration::from_millis(100));
    assert!(net::TcpStream::connect(addr).is_ok());
    assert!(net::TcpStream::connect(addr).is_ok());
    assert!(net::TcpStream::connect(addr).is_ok());

    let mut buf = [0u8; 4];
    let mut conn = net::TcpStream::connect(addr).unwrap();
    let _ = conn.read_exact(&mut buf);
    assert_eq!(buf, b"test"[..]);

    // stop
    srv.stop(false).await;
    thread::sleep(time::Duration::from_millis(100));
    assert!(net::TcpStream::connect(addr).is_err());

    thread::sleep(time::Duration::from_millis(100));
    sys.stop();
    let _ = h.join();
}

/// STATEMENT: Worker-start initialization runs once for multiple configured listeners.
///
/// HOW:
/// - Configure two bound addresses and one existing listener, registering services and incrementing a counter in `on_worker_start`.
/// - Start one worker, connect to all three addresses, and assert the initialization counter is `1`.
#[test]
fn test_on_worker_start() {
    use std::io;

    let addr1 = TestServer::unused_addr();
    let addr2 = TestServer::unused_addr();
    let addr3 = TestServer::unused_addr();
    let (tx, rx) = mpsc::channel();
    let num = Arc::new(AtomicUsize::new(0));
    let num2 = num.clone();

    let h = thread::spawn(move || {
        let num = num2.clone();
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);
        let _ = sys.run(move || {
            let num = num.clone();
            ntex::rt::spawn(async move {
                let num = num.clone();
                let srv =
                    build()
                        .disable_signals()
                        .configure(async move |cfg| {
                            let num = num.clone();
                            let lst = net::TcpListener::bind(addr3).unwrap();
                            cfg.bind("addr1", addr1)
                                .unwrap()
                                .bind("addr2", addr2)
                                .unwrap()
                                .listen("addr3", lst)
                                .on_worker_start(async move |rt| {
                                    let num = num.clone();
                                    rt.service("addr1", SharedCfg::default(), async |_| {
                                        Ok::<_, ()>(())
                                    });
                                    rt.service("addr3", SharedCfg::default(), async |_| {
                                        Ok::<_, ()>(())
                                    });
                                    let _ = num.fetch_add(1, Relaxed);
                                    Ok::<_, io::Error>(())
                                });
                            Ok::<_, io::Error>(())
                        })
                        .await
                        .unwrap()
                        .workers(1)
                        .run();
                let _ = tx.send((srv, ntex::rt::System::current()));
            });
            Ok::<_, io::Error>(())
        });
    });
    let (_, sys) = rx.recv().unwrap();
    thread::sleep(time::Duration::from_millis(500));

    assert!(net::TcpStream::connect(addr1).is_ok());
    assert!(net::TcpStream::connect(addr2).is_ok());
    assert!(net::TcpStream::connect(addr3).is_ok());
    assert_eq!(num.load(Relaxed), 1);
    sys.stop();
    let _ = h.join();
}

/// STATEMENT: Asynchronous server configuration initializes services once per worker.
///
/// HOW:
/// - Configure two bound sockets and a supplied listener, checking the `ServiceRuntime` debug label during worker initialization.
/// - Connect to each address and assert the initialization counter is `1` before stopping.
#[test]
fn test_configure() {
    use std::io;

    let addr1 = TestServer::unused_addr();
    let addr2 = TestServer::unused_addr();
    let addr3 = TestServer::unused_addr();
    let (tx, rx) = mpsc::channel();
    let num = Arc::new(AtomicUsize::new(0));
    let num2 = num.clone();

    let h = thread::spawn(move || {
        let num = num2.clone();
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);
        let _ = sys.run(move || {
            ntex_rt::spawn(async move {
                let srv = build()
                    .disable_signals()
                    .configure(async move |cfg| {
                        let num = num.clone();
                        let lst = net::TcpListener::bind(addr3).unwrap();
                        cfg.bind("addr1", addr1)
                            .unwrap()
                            .bind("addr2", addr2)
                            .unwrap()
                            .listen("addr3", lst)
                            .on_worker_start(async move |rt| {
                                assert!(format!("{:?}", rt).contains("ServiceRuntime"));
                                let num = num.clone();
                                rt.service(
                                    "addr1",
                                    SharedCfg::new("srv-addr1"),
                                    fn_service(async |_| Ok::<_, ()>(())),
                                );
                                rt.service(
                                    "addr3",
                                    SharedCfg::default(),
                                    fn_service(async |_| Ok::<_, ()>(())),
                                );
                                let _ = num.fetch_add(1, Relaxed);
                                Ok::<_, io::Error>(())
                            });
                        Ok::<_, io::Error>(())
                    })
                    .await
                    .unwrap()
                    .workers(1)
                    .run();
                let _ = tx.send((srv.clone(), ntex::rt::System::current()));
                let _ = srv.await;
            });
            Ok::<_, io::Error>(())
        });
    });
    let (_, sys) = rx.recv().unwrap();

    thread::sleep(time::Duration::from_millis(500));

    assert!(net::TcpStream::connect(addr1).is_ok());
    assert!(net::TcpStream::connect(addr2).is_ok());
    assert!(net::TcpStream::connect(addr3).is_ok());
    assert_eq!(num.load(Relaxed), 1);
    sys.stop();
    let _ = h.join();
}

/// STATEMENT: A server replaces panicked Tokio workers and continues handling connections.
///
/// HOW:
/// - Start one worker whose service increments a counter and panics for each accepted connection.
/// - Connect repeatedly across worker restarts and assert the counter advances from `1` to `3`.
#[test]
#[cfg(feature = "tokio")]
#[allow(unreachable_code)]
fn test_panic_in_worker() {
    let counter = Arc::new(AtomicUsize::new(0));
    let counter2 = counter.clone();

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

    let h = thread::spawn(move || {
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);
        let counter = counter2.clone();
        sys.run(move || {
            let counter = counter.clone();
            let srv = build()
                .workers(1)
                .disable_signals()
                .bind("test", addr, SharedCfg::default(), async move |_| {
                    let counter = counter.clone();
                    async move |_| {
                        counter.fetch_add(1, Relaxed);
                        panic!();
                        Ok::<_, ()>(())
                    }
                })
                .unwrap()
                .run();
            let _ = tx.send((srv.clone(), ntex::rt::System::current()));
            ntex::rt::spawn(async move {
                let _ = srv.await;
            });
            Ok(())
        })
    });
    let (_, sys) = rx.recv().unwrap();

    thread::sleep(time::Duration::from_millis(200));
    assert!(net::TcpStream::connect(addr).is_ok());
    thread::sleep(time::Duration::from_millis(100));
    assert_eq!(counter.load(Relaxed), 1);

    // first connect get dropped, because there is no workers
    assert!(net::TcpStream::connect(addr).is_ok());
    thread::sleep(time::Duration::from_millis(300));
    assert!(net::TcpStream::connect(addr).is_ok());
    thread::sleep(time::Duration::from_millis(500));
    assert_eq!(counter.load(Relaxed), 3);

    sys.stop();
    let _ = h.join();
}

/// STATEMENT: Configured server state is supplied to each connection service.
///
/// HOW:
/// - Build state containing a shared counter and increment it from a state-aware connection handler.
/// - Open three connections and assert the state counter reaches `3`.
#[test]
fn test_server_state() {
    let addr = TestServer::unused_addr();
    let (tx, rx) = mpsc::channel();
    let num = Arc::new(AtomicUsize::new(0));
    let num2 = num.clone();

    #[derive(Clone)]
    struct St(Arc<AtomicUsize>);

    let h = thread::spawn(move || {
        let num = num2.clone();
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);
        sys.run(move || {
            let srv = build_with_config(async move || Ok(St(num.clone())))
                .disable_signals()
                .bind("test", addr, SharedCfg::default(), async move |_| {
                    async move |st: &St, io: Io| {
                        let _ = st.0.fetch_add(1, Relaxed);
                        let _ = io.send(Bytes::from_static(b"test"), &BytesCodec).await;
                        Ok::<_, ()>(())
                    }
                })
                .unwrap()
                .workers(1)
                .run();
            let _ = tx.send((srv, ntex::rt::System::current()));
            Ok(())
        })
    });
    let (_, sys) = rx.recv().unwrap();

    assert!(net::TcpStream::connect(addr).is_ok());
    assert!(net::TcpStream::connect(addr).is_ok());
    assert!(net::TcpStream::connect(addr).is_ok());
    thread::sleep(time::Duration::from_millis(250));
    assert_eq!(num.load(Relaxed), 3);
    sys.stop();
    let _ = h.join();
}

/// STATEMENT: `stop_on_panic` completes the server future after a worker panics.
///
/// HOW:
/// - Start a one-worker server with `stop_on_panic` and a panicking connection service.
/// - Connect to trigger the panic and assert the server future returns and sends its completion marker.
#[cfg(not(any(feature = "tokio", feature = "compio")))]
#[test]
fn test_stop_on_panic() {
    let addr = TestServer::unused_addr();
    let (tx, rx) = mpsc::channel();
    let h = thread::spawn(move || {
        let sys = ntex::rt::System::new("test", ntex::rt::DefaultRuntime);
        sys.block_on(async move {
            let _ = build()
                .stop_on_panic()
                .graceful_shutdown()
                .workers(1)
                .disable_signals()
                .bind("test", addr, SharedCfg::default(), async move |_| {
                    #[allow(unreachable_code)]
                    fn_service(async move |_| {
                        panic!("test");
                        Ok::<_, ()>(())
                    })
                })
                .unwrap()
                .run()
                .await;
            let _ = tx.send("test");
        });
    });

    thread::sleep(time::Duration::from_millis(300));
    assert!(net::TcpStream::connect(addr).is_ok());

    let res = rx.recv().unwrap();
    assert_eq!(res, "test");
    let _ = h.join();
}