ntex 4.8.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
//! `WebSockets` protocol support
use std::fmt;

pub use crate::ws::{CloseCode, CloseReason, Frame, Message, WsSink};

use crate::http::{ConnectionType, body::BodySize, error::ResponseError, h1, header};
use crate::io::{DispatchItem, IoConfig, Reason};
use crate::service::{Ctx, IntoService, Pipeline, Service, apply_fn};
use crate::web::HttpRequest;
use crate::ws::{self, error::HandshakeError, error::WsError, handshake};
use crate::{SharedCfg, rt, time::Seconds};

thread_local! {
    static CFG: SharedCfg = SharedCfg::new("WS")
        .add(IoConfig::new().set_keepalive_timeout(Seconds::ZERO))
        .into();
}

/// Returns an iterator over the subprotocols requested by the client
/// in the `Sec-Websocket-Protocol` header.
///
/// # Example
///
/// ```rust
/// use ntex::web::{self, HttpRequest, ws};
///
/// async fn service(frame: ws::Frame) -> Result<Option<ws::Message>, std::io::Error> {
///     // handle incoming frames
///     Ok(None)
/// }
///
/// async fn handler(req: HttpRequest) {
///     let chosen = ws::subprotocols(&req)
///         .find(|p| *p == "my-subprotocol");
///
///     if let Err(err) = ws::start(&req, chosen, service).await {
///         eprintln!("WebSocket error: {err:?}");
///     }
/// }
///
/// let app = web::App::default().route("/ws", web::get().to(handler));
/// ```
pub fn subprotocols(req: &HttpRequest) -> impl Iterator<Item = &str> {
    req.headers()
        .get_all(header::SEC_WEBSOCKET_PROTOCOL)
        .flat_map(|val| {
            val.to_str()
                .ok()
                .into_iter()
                .flat_map(|s| s.split(',').map(str::trim).filter(|s| !s.is_empty()))
        })
}

/// Start websocket service handling Frame messages, including the chosen
/// subprotocol in the response.
///
/// If `subprotocol` is `Some`, the `Sec-Websocket-Protocol` header will be included
/// in the response with the chosen protocol. The protocol must be a valid HTTP
/// token offered by the client. If `None`, the header is omitted.
///
/// If the handshake fails for an upgrade request, the handshake error response
/// is sent and the connection is closed.
///
/// With the `compress` feature, the `permessage-deflate` extension is accepted
/// if it is enabled with
/// [`HttpServiceConfig::set_ws_deflate()`](crate::http::HttpServiceConfig::set_ws_deflate).
///
/// Control frames are passed to the service too. If it returns `None` for
/// a ping and hasn't sent a pong through a sink meanwhile, a pong with the
/// same payload is sent. If it returns `None` for the peer's close frame,
/// a close echoing the peer's code is sent. No automatic reply is sent once
/// a close message has been sent through a sink. After the peer's close frame
/// is handled, the connection is closed. Dispatcher control and stop events
/// are handled by `start()`, a service error sends a close frame with
/// [`CloseCode::Away`].
///
/// # Example
///
/// ```rust
/// use ntex::web::{self, HttpRequest, ws};
///
/// async fn service(frame: ws::Frame) -> Result<Option<ws::Message>, std::io::Error> {
///     // handle incoming frames
///     Ok(None)
/// }
///
/// async fn handler(req: HttpRequest) {
///     let chosen = ws::subprotocols(&req)
///         .find(|p| *p == "graphql-ws" || *p == "graphql-transport-ws");
///
///     if let Err(err) = ws::start(&req, chosen, service).await {
///         eprintln!("WebSocket error: {err:?}");
///     }
/// }
///
/// let app = web::App::default().route("/ws", web::get().to(handler));
/// ```
pub async fn start<S>(
    req: &HttpRequest,
    subprotocol: Option<&str>,
    f: impl IntoService<S, WsSink, Frame>,
) -> Result<(), WsError<S::Error>>
where
    S: Service<WsSink, Frame, Res = Option<Message>> + 'static,
    S::Error: fmt::Debug,
{
    start_with(
        req,
        subprotocol,
        DispatchService {
            svc: f.into_service(),
        },
    )
    .await
}

/// Start websocket service handling raw `DispatchItem` messages requiring manual control/stop logic,
/// including the chosen subprotocol in the response.
///
/// Unlike [`start()`], pings and close frames are not answered automatically.
///
/// If `subprotocol` is `Some`, the `Sec-Websocket-Protocol` header will be included
/// in the response with the chosen protocol. The protocol must be a valid HTTP
/// token offered by the client. If `None`, the header is omitted.
///
/// If the handshake fails for an upgrade request, the handshake error response
/// is sent and the connection is closed.
///
/// With the `compress` feature, the `permessage-deflate` extension is accepted
/// if it is enabled with
/// [`HttpServiceConfig::set_ws_deflate()`](crate::http::HttpServiceConfig::set_ws_deflate).
pub async fn start_with<S, Err>(
    req: &HttpRequest,
    subprotocol: Option<&str>,
    f: impl IntoService<S, WsSink, DispatchItem<WsSink>>,
) -> Result<(), WsError<Err>>
where
    S: Service<WsSink, DispatchItem<WsSink>, Res = Option<Message>, Error = WsError<Err>> + 'static,
    S::Error: fmt::Debug,
    Err: 'static,
{
    log::trace!("Start ws handshake verification for {:?}", req.path());

    // ws handshake
    #[allow(unused_mut)]
    let mut res = match handshake_response(req, subprotocol) {
        Ok(res) => res,
        Err(err) => {
            reject(req, err).await;
            return Err(err.into());
        }
    };

    // extract io
    let item = req
        .head()
        .take_io()
        .ok_or(HandshakeError::NoWebsocketUpgrade)?;
    let io = item.0;
    let codec = item.1;

    #[allow(unused_mut)]
    let mut ws_codec = ws::Codec::new();
    #[cfg(feature = "compress")]
    if let Some((agreed, value)) = io
        .shared()
        .get::<crate::http::HttpServiceConfig>()
        .ws_deflate
        .as_ref()
        .and_then(|deflate| deflate.negotiate(req.headers()))
    {
        log::trace!("Ws permessage-deflate is accepted {agreed:?}");
        res.headers_mut()
            .insert(header::SEC_WEBSOCKET_EXTENSIONS, value);
        ws_codec = ws_codec.set_deflate(agreed);
    }

    io.encode(h1::Message::Item((res, BodySize::Empty)), &codec)
        .map_err(|_| HandshakeError::NoWebsocketUpgrade)?;
    log::trace!("Ws handshake verification completed for {:?}", req.path());

    // create sink, it is also the dispatcher's codec
    let sink = WsSink::new(io.get_ref(), ws_codec, io.shared().get());

    // create ws service
    // SAFETY: the HTTP dispatcher has transferred ownership of `io` to this
    // upgrade path, and no borrowed reference from `io.cfg()` is retained.
    unsafe {
        io.set_config(CFG.with(Clone::clone));
    }

    // the h1 dispatcher may have started a headers-read timer on this IO;
    // cancel it so DSP_TIMEOUT doesn't fire on the new WS dispatcher
    io.stop_timer();

    // start websockets service dispatcher
    let timeout_sink = sink.clone();
    let service = apply_fn(f.into_service(), async move |req, svc| {
        let result = svc.call(req).await;
        if matches!(&result, Ok(Some(Message::Close(_)))) {
            timeout_sink.start_close_timeout();
        }
        result
    });
    let result = crate::io::Dispatcher::new(io, sink.clone(), Pipeline::new(sink, service)).await;
    log::trace!("Ws handler is terminated: {result:?}");

    result
}

fn handshake_response(
    req: &HttpRequest,
    subprotocol: Option<&str>,
) -> Result<crate::http::Response<()>, HandshakeError> {
    let mut res = handshake(req.head())?;
    if let Some(protocol) = subprotocol {
        if !ws::is_token(protocol) || !subprotocols(req).any(|offered| offered == protocol) {
            return Err(HandshakeError::BadWebsocketProtocol);
        }
        res.set_header(header::SEC_WEBSOCKET_PROTOCOL, protocol);
    }
    Ok(res.build().into_parts().0)
}

/// Sends the handshake error response and closes the connection.
///
/// The I/O stream of an upgrade request belongs to the handler, a response
/// returned by the handler is not sent.
async fn reject(req: &HttpRequest, err: HandshakeError) {
    if let Some((io, codec)) = req.head().take_io() {
        let mut res = err.error_response().into_parts().0;
        res.head_mut().set_connection_type(ConnectionType::Close);
        if io
            .encode(h1::Message::Item((res, BodySize::Empty)), &codec)
            .is_ok()
        {
            let _ = io.shutdown().await;
        }
    }
}

/// Just a wrapper over a service handling WebSocket messages and propagating shutdown
struct DispatchService<S> {
    svc: S,
}

impl<S, E> Service<WsSink, DispatchItem<WsSink>> for DispatchService<S>
where
    S: Service<WsSink, Frame, Res = Option<Message>, Error = E>,
    E: fmt::Debug,
{
    type Res = Option<Message>;
    type Error = WsError<E>;

    crate::forward!(WsSink, svc, map_err = WsError::Service);

    async fn call(
        &self,
        req: DispatchItem<WsSink>,
        ctx: Ctx<'_, Self, WsSink>,
    ) -> Result<Self::Res, Self::Error> {
        match req {
            DispatchItem::Item(item) => {
                let sink = ctx.st();
                let close = matches!(item, Frame::Close(_));
                let reply = sink.codec().auto_reply(&item);
                let result = ctx
                    .call(&self.svc, item)
                    .await
                    .map(|res| sink.codec().unanswered(res, reply))
                    .map_err(WsError::Service);
                if close {
                    let s = sink.clone();
                    rt::spawn_detached(async move { s.io().close() });
                }
                result
            }
            // a clean disconnect is not an error
            DispatchItem::Control(_) | DispatchItem::Stop(Reason::Io(None)) => Ok(None),
            DispatchItem::Stop(Reason::Service) => {
                Ok(Some(Message::Close(Some(ws::CloseReason {
                    code: ws::CloseCode::Away,
                    description: None,
                }))))
            }
            DispatchItem::Stop(Reason::KeepAlive) => Err(WsError::KeepAlive),
            DispatchItem::Stop(Reason::ReadTimeout) => Err(WsError::ReadTimeout),
            DispatchItem::Stop(Reason::WriteTimeout) => Err(WsError::WriteTimeout),
            DispatchItem::Stop(Reason::Decoder(e)) => {
                let sink = ctx.st();
                if !sink.is_closed() {
                    let reason = ws::CloseReason::from(ws::CloseCode::Protocol);
                    let _ = sink.send(Message::Close(Some(reason))).await;
                }
                Err(WsError::Protocol(e))
            }
            DispatchItem::Stop(Reason::Encoder(e)) => Err(WsError::Protocol(e)),
            DispatchItem::Stop(Reason::Io(e)) => Err(WsError::Disconnected(e)),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::io;

    use super::*;
    use crate::io::{Control, Io, testing::IoTest};
    use crate::service::fn_service;
    use crate::ws::error::ProtocolError;

    /// STATEMENT: WebSocket dispatch maps frames, controls, and stop reasons to responses and errors.
    ///
    /// HOW:
    /// - Dispatch ping/text frames and backpressure control, checking service results and no-op handling.
    /// - Assert stop reasons yield the expected close message, timeout, protocol, or disconnect outcome.
    /// - Trigger decoder errors twice and assert the sink closes; dispatch close and await I/O closure.
    #[crate::rt_test]
    async fn dispatch_service() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1 << 20);
        let io = Io::from(server);
        let sink = WsSink::new(io.get_ref(), ws::Codec::new(), crate::Cfg::default());
        let svc = Pipeline::new(
            sink.clone(),
            DispatchService {
                svc: fn_service(async |frame: Frame| match frame {
                    Frame::Text(_) => Err(io::Error::other("text")),
                    _ => Ok(Some(Message::Pong("pong".into()))),
                }),
            },
        );

        let res = svc.call(DispatchItem::Item(Frame::Ping("p".into()))).await;
        assert!(matches!(res, Ok(Some(Message::Pong(_)))));
        let res = svc.call(DispatchItem::Item(Frame::Text("t".into()))).await;
        assert!(matches!(res, Err(WsError::Service(_))));
        let res = svc
            .call(DispatchItem::Control(Control::WBackPressureEnabled))
            .await;
        assert!(matches!(res, Ok(None)));
        let res = svc.call(DispatchItem::Stop(Reason::Io(None))).await;
        assert!(matches!(res, Ok(None)));
        let res = svc.call(DispatchItem::Stop(Reason::Service)).await;
        assert!(matches!(
            res,
            Ok(Some(Message::Close(Some(ws::CloseReason {
                code: ws::CloseCode::Away,
                ..
            }))))
        ));
        let res = svc.call(DispatchItem::Stop(Reason::KeepAlive)).await;
        assert!(matches!(res, Err(WsError::KeepAlive)));
        let res = svc.call(DispatchItem::Stop(Reason::ReadTimeout)).await;
        assert!(matches!(res, Err(WsError::ReadTimeout)));
        let res = svc.call(DispatchItem::Stop(Reason::WriteTimeout)).await;
        assert!(matches!(res, Err(WsError::WriteTimeout)));
        let res = svc
            .call(DispatchItem::Stop(Reason::Encoder(
                ProtocolError::UnmaskedFrame,
            )))
            .await;
        assert!(matches!(
            res,
            Err(WsError::Protocol(ProtocolError::UnmaskedFrame))
        ));
        let res = svc
            .call(DispatchItem::Stop(Reason::Io(Some(io::Error::other("io")))))
            .await;
        assert!(matches!(res, Err(WsError::Disconnected(Some(_)))));

        // decoder error sends close frame
        assert!(!sink.is_closed());
        let res = svc
            .call(DispatchItem::Stop(Reason::Decoder(
                ProtocolError::MaskedFrame,
            )))
            .await;
        assert!(matches!(
            res,
            Err(WsError::Protocol(ProtocolError::MaskedFrame))
        ));
        assert!(sink.is_closed());
        let res = svc
            .call(DispatchItem::Stop(Reason::Decoder(
                ProtocolError::MaskedFrame,
            )))
            .await;
        assert!(matches!(res, Err(WsError::Protocol(_))));

        // close frame closes io
        let res = svc.call(DispatchItem::Item(Frame::Close(None))).await;
        assert!(matches!(res, Ok(Some(Message::Pong(_)))));
        io.on_disconnect().await;
        assert!(io.is_closed());
    }

    /// STATEMENT: `start()` answers pings and the peer's close when the frame service returns `None`, without duplicating replies.
    ///
    /// HOW:
    /// - Dispatch frames to a service that returns `None`, or a text reply for ping `"own"`, or sends a pong through the sink for ping `"sink"`.
    /// - Expect a pong with the ping payload, the service's own reply, no reply after the sink pong but a pong for the next ping; text gets no reply.
    /// - Expect the peer's close code to be echoed, an extension close to be answered with a normal close, and no reply once a close has been sent.
    #[crate::rt_test]
    async fn dispatch_service_auto_replies() {
        let (client, server) = IoTest::create();
        client.remote_buffer_cap(1 << 20);
        let io = Io::from(server);
        let sink = WsSink::new(io.get_ref(), ws::Codec::new(), crate::Cfg::default());
        let sink2 = sink.clone();
        let svc = Pipeline::new(
            sink.clone(),
            DispatchService {
                svc: fn_service(async move |frame: Frame| match frame {
                    Frame::Ping(p) if p == "own" => Ok(Some(Message::Text("own".into()))),
                    Frame::Ping(p) if p == "sink" => {
                        sink2.send(Message::Pong(p)).await.unwrap();
                        Ok(None)
                    }
                    _ => Ok::<_, io::Error>(None),
                }),
            },
        );

        let res = svc.call(DispatchItem::Item(Frame::Ping("p".into()))).await;
        assert_eq!(res.unwrap(), Some(Message::Pong("p".into())));
        let res = svc
            .call(DispatchItem::Item(Frame::Ping("own".into())))
            .await;
        assert_eq!(res.unwrap(), Some(Message::Text("own".into())));
        let res = svc
            .call(DispatchItem::Item(Frame::Ping("sink".into())))
            .await;
        assert_eq!(res.unwrap(), None);
        let res = svc.call(DispatchItem::Item(Frame::Ping("p2".into()))).await;
        assert_eq!(res.unwrap(), Some(Message::Pong("p2".into())));
        let res = svc.call(DispatchItem::Item(Frame::Text("t".into()))).await;
        assert_eq!(res.unwrap(), None);

        // the peer's close code is echoed, servers cannot send the extension code
        let close = Frame::Close(Some(ws::CloseCode::Away.into()));
        let res = svc.call(DispatchItem::Item(close)).await;
        assert_eq!(
            res.unwrap(),
            Some(Message::Close(Some(ws::CloseCode::Away.into())))
        );
        let close = Frame::Close(Some(ws::CloseCode::Extension.into()));
        let res = svc.call(DispatchItem::Item(close)).await;
        assert_eq!(
            res.unwrap(),
            Some(Message::Close(Some(ws::CloseCode::Normal.into())))
        );

        // nothing is sent after a close
        sink.send(Message::Close(None)).await.unwrap();
        let res = svc.call(DispatchItem::Item(Frame::Ping("p".into()))).await;
        assert_eq!(res.unwrap(), None);
        let close = Frame::Close(Some(ws::CloseCode::Away.into()));
        let res = svc.call(DispatchItem::Item(close)).await;
        assert_eq!(res.unwrap(), None);
    }
}