Skip to main content

ntex/http/h1/
control.rs

1use std::{cell::Cell, fmt, io, rc::Rc};
2
3use crate::http::message::CurrentIo;
4use crate::http::{Request, Response, ResponseError, body::Body, h1::Codec};
5use crate::io::{Filter, Io, IoBoxed, IoRef};
6
7/// A lifecycle event sent to an HTTP/1 control service.
8///
9/// Return [`Control::ack`] to accept the default action, or use the methods on
10/// the individual message type to reject or take ownership of the operation.
11pub enum Control<F, Err> {
12    /// A transport connection has been accepted.
13    Connect(Connection<F>),
14    /// A complete request head has been decoded.
15    Request(NewRequest),
16    /// A request asks to upgrade the HTTP/1 connection.
17    Upgrade(Upgrade<F>),
18    /// A request contains `Expect: 100-continue`.
19    Expect(Expect),
20    /// The connection is preparing to stop.
21    Disconnect(Reason<Err>),
22}
23
24#[derive(Debug)]
25/// Reason supplied with an HTTP/1 disconnect notification.
26pub enum Reason<Err> {
27    /// The HTTP service initiated the disconnect.
28    Service(ServiceDisconnect),
29    /// The application service returned an error.
30    Error(Error<Err>),
31    /// HTTP/1 decoding, encoding, or timeout processing failed.
32    ProtocolError(ProtocolError),
33    /// The peer closed the connection or an I/O error occurred.
34    PeerGone(PeerGone),
35    /// The keep-alive timer expired.
36    KeepAlive(KeepAlive),
37}
38
39/// The reason the HTTP service is disconnecting.
40#[derive(Copy, Clone, Debug, PartialEq, Eq)]
41pub enum ServiceDisconnectReason {
42    /// The server is shutting down.
43    Shutdown,
44    /// The HTTP/1 dispatcher relinquished the connection after an upgrade was
45    /// handed to the application or control service.
46    UpgradeHandled,
47    /// Upgrade handling failed.
48    UpgradeFailed,
49    /// Expectation handling failed.
50    ExpectFailed,
51    /// The application dropped an unread request payload, preventing reuse of
52    /// the connection.
53    PayloadDropped,
54}
55
56/// The control service's response to an HTTP/1 lifecycle event.
57#[derive(Debug)]
58pub struct ControlAck<F> {
59    pub(super) result: ControlResult<F>,
60}
61
62#[derive(Debug)]
63pub(super) enum ControlResult<F> {
64    /// Continue
65    Connect(Io<F>),
66    /// Continue
67    Continue(Request),
68    /// handle request expect
69    Expect(Request),
70    /// handle request upgrade
71    Upgrade(Request),
72    /// upgrade acked
73    UpgradeAck(Request),
74    /// upgrade handled
75    UpgradeHandled,
76    /// forward request to publish service
77    Publish(Request),
78    /// send response
79    Response(Response<()>, Body),
80    /// service error
81    Error(Response<()>, Body),
82    /// protocol error
83    ProtocolError(Response<()>, Body),
84    /// upgrade handling failed
85    UpgradeFailed(Response<()>, Body),
86    /// expect handling failed
87    ExpectFailed(Response<()>, Body),
88    /// stop connection
89    Stop,
90}
91
92impl<F, Err> Control<F, Err> {
93    pub(super) fn connect(id: usize, io: Io<F>) -> Self {
94        Control::Connect(Connection { id, io })
95    }
96
97    pub(super) fn request(req: Request) -> Self {
98        Control::Request(NewRequest(req))
99    }
100
101    pub(super) fn upgrade(req: Request, io: Rc<Io<F>>, codec: Codec) -> Self {
102        Control::Upgrade(Upgrade { req, io, codec })
103    }
104
105    pub(super) fn expect(req: Request) -> Self {
106        Control::Expect(Expect(req))
107    }
108
109    pub(super) fn err(err: Err) -> Self
110    where
111        Err: ResponseError,
112    {
113        Control::Disconnect(Reason::Error(Error::new(err)))
114    }
115
116    pub(super) fn peer_gone(err: Option<io::Error>) -> Self {
117        Control::Disconnect(Reason::PeerGone(PeerGone(err)))
118    }
119
120    pub(super) fn proto_err(err: super::ProtocolError) -> Self {
121        Control::Disconnect(Reason::ProtocolError(ProtocolError(err)))
122    }
123
124    pub(super) fn keepalive(enabled: bool) -> Self {
125        Control::Disconnect(Reason::KeepAlive(KeepAlive::new(enabled)))
126    }
127
128    pub(super) fn svc_disconnect(reason: ServiceDisconnectReason) -> Self {
129        Control::Disconnect(Reason::Service(ServiceDisconnect::new(reason)))
130    }
131
132    #[inline]
133    /// Accepts the event and applies its default action.
134    pub fn ack(self) -> ControlAck<F>
135    where
136        F: Filter,
137        Err: ResponseError,
138    {
139        match self {
140            Control::Connect(msg) => msg.ack(),
141            Control::Request(msg) => msg.ack(),
142            Control::Upgrade(msg) => msg.ack(),
143            Control::Expect(msg) => msg.ack(),
144            Control::Disconnect(msg) => msg.ack(),
145        }
146    }
147}
148
149impl<F, Err> fmt::Debug for Control<F, Err>
150where
151    Err: fmt::Debug,
152{
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        match self {
155            Control::Connect(_) => f.debug_tuple("Control::Connect").finish(),
156            Control::Request(msg) => f.debug_tuple("Control::Request").field(msg).finish(),
157            Control::Upgrade(msg) => f.debug_tuple("Control::Upgrade").field(msg).finish(),
158            Control::Expect(msg) => f.debug_tuple("Control::Expect").field(msg).finish(),
159            Control::Disconnect(msg) => f.debug_tuple("Control::Disconnect").field(msg).finish(),
160        }
161    }
162}
163
164impl<Err: ResponseError> Reason<Err> {
165    /// Acknowledges the disconnect notification and stops the connection.
166    pub fn ack<F>(self) -> ControlAck<F> {
167        match self {
168            Reason::Error(msg) => msg.ack(),
169            Reason::ProtocolError(msg) => msg.ack(),
170            Reason::PeerGone(msg) => msg.ack(),
171            Reason::KeepAlive(msg) => msg.ack(),
172            Reason::Service(msg) => msg.ack(),
173        }
174    }
175}
176
177/// Notification that a connection has been accepted.
178#[derive(Debug)]
179pub struct Connection<F> {
180    id: usize,
181    io: Io<F>,
182}
183
184impl<F> Connection<F> {
185    #[inline]
186    /// Returns the connection identifier.
187    pub fn id(&self) -> usize {
188        self.id
189    }
190
191    #[inline]
192    /// Returns the connection I/O object.
193    pub fn get_ref(&self) -> &Io<F> {
194        &self.io
195    }
196
197    #[inline]
198    /// Returns mutable access to the connection I/O object.
199    pub fn get_mut(&mut self) -> &mut Io<F> {
200        &mut self.io
201    }
202
203    #[inline]
204    /// Accepts the connection and starts HTTP request processing.
205    pub fn ack(self) -> ControlAck<F> {
206        ControlAck {
207            result: ControlResult::Connect(self.io),
208        }
209    }
210}
211
212/// Notification that a complete request head has been received.
213#[derive(Debug)]
214pub struct NewRequest(Request);
215
216impl NewRequest {
217    #[inline]
218    /// Returns the HTTP request.
219    pub fn get_ref(&self) -> &Request {
220        &self.0
221    }
222
223    #[inline]
224    /// Returns mutable access to the HTTP request.
225    pub fn get_mut(&mut self) -> &mut Request {
226        &mut self.0
227    }
228
229    #[inline]
230    /// Accepts the request and continues with expectation handling, upgrade
231    /// handling, or the application service as appropriate.
232    pub fn ack<F>(self) -> ControlAck<F> {
233        let result = if self.0.head().expect() {
234            ControlResult::Expect(self.0)
235        } else if self.0.upgrade() {
236            ControlResult::Upgrade(self.0)
237        } else {
238            ControlResult::Publish(self.0)
239        };
240        ControlAck { result }
241    }
242
243    #[inline]
244    /// Rejects the request with the response generated from `err`.
245    pub fn fail<E: ResponseError, F>(self, err: E) -> ControlAck<F> {
246        let res: Response = (&err).into();
247        let (res, body) = res.into_parts();
248
249        ControlAck {
250            result: ControlResult::Response(res, body.into()),
251        }
252    }
253
254    #[inline]
255    /// Rejects the request with a custom response.
256    pub fn fail_with<F>(self, res: Response) -> ControlAck<F> {
257        let (res, body) = res.into_parts();
258
259        ControlAck {
260            result: ControlResult::Response(res, body.into()),
261        }
262    }
263}
264
265/// A request to upgrade the HTTP/1 connection.
266pub struct Upgrade<F> {
267    req: Request,
268    io: Rc<Io<F>>,
269    codec: Codec,
270}
271
272struct RequestIoAccess<F> {
273    io: Rc<Io<F>>,
274    // `get()` must not borrow `io`, it is taken through a shared reference
275    ioref: IoRef,
276    codec: Codec,
277    taken: Cell<bool>,
278}
279
280impl<F> fmt::Debug for RequestIoAccess<F> {
281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        f.debug_struct("RequestIoAccess")
283            .field("io", &self.ioref)
284            .field("codec", &self.codec)
285            .finish()
286    }
287}
288
289impl<F: Filter> crate::http::message::IoAccess for RequestIoAccess<F> {
290    fn get(&self) -> Option<&IoRef> {
291        if self.taken.get() { None } else { Some(&self.ioref) }
292    }
293
294    fn take(&self) -> Option<(IoBoxed, Codec)> {
295        if self.ioref.is_in_filter_callbacks() || self.taken.replace(true) {
296            None
297        } else {
298            // SAFETY: `io` is shared with the dispatcher only, which borrows it
299            // only within its own calls into the io; filter callbacks run inside
300            // such calls and are rejected above, `get()` borrows the separate `ioref`
301            let io = unsafe { self.io.take() };
302            Some((io.into(), self.codec.clone()))
303        }
304    }
305}
306
307impl<F: Filter> Upgrade<F> {
308    #[inline]
309    /// Returns the connection I/O object.
310    pub fn io(&self) -> &Io<F> {
311        &self.io
312    }
313
314    #[inline]
315    /// Returns the upgrade request.
316    pub fn get_ref(&self) -> &Request {
317        &self.req
318    }
319
320    #[inline]
321    /// Returns mutable access to the upgrade request.
322    pub fn get_mut(&mut self) -> &mut Request {
323        &mut self.req
324    }
325
326    #[inline]
327    /// Passes the upgrade request to the application service.
328    ///
329    /// The application can take ownership of the connection and codec through
330    /// [`RequestHead::take_io`](crate::http::RequestHead::take_io).
331    pub fn ack(mut self) -> ControlAck<F> {
332        // Move io into request
333        let io = Rc::new(RequestIoAccess {
334            ioref: self.io.get_ref(),
335            io: self.io,
336            codec: self.codec,
337            taken: Cell::new(false),
338        });
339        self.req.head_mut().io = CurrentIo::new(io);
340
341        ControlAck {
342            result: ControlResult::UpgradeAck(self.req),
343        }
344    }
345
346    #[inline]
347    /// Takes ownership of the connection, request, and codec.
348    ///
349    /// Returning this acknowledgement tells the dispatcher that the control
350    /// service is responsible for the upgraded connection.
351    pub fn handle(self) -> (ControlAck<F>, Io<F>, Request, Codec) {
352        // SAFETY: `handle` consumes `self`, borrows from `io()` are gone and
353        // the dispatcher does not keep borrows of its `io`
354        let io = unsafe { self.io.take() };
355        (
356            ControlAck {
357                result: ControlResult::UpgradeHandled,
358            },
359            io,
360            self.req,
361            self.codec,
362        )
363    }
364
365    #[inline]
366    /// Rejects the upgrade with the response generated from `err`.
367    pub fn fail<E: ResponseError>(self, err: E) -> ControlAck<F> {
368        let res: Response = (&err).into();
369        let (res, body) = res.into_parts();
370
371        ControlAck {
372            result: ControlResult::UpgradeFailed(res, body.into()),
373        }
374    }
375
376    #[inline]
377    /// Rejects the upgrade with a custom response.
378    pub fn fail_with(self, res: Response) -> ControlAck<F> {
379        let (res, body) = res.into_parts();
380
381        ControlAck {
382            result: ControlResult::UpgradeFailed(res, body.into()),
383        }
384    }
385}
386
387impl<F> fmt::Debug for Upgrade<F> {
388    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389        f.debug_struct("Upgrade")
390            .field("req", &self.req)
391            .field("io", &self.io)
392            .field("codec", &self.codec)
393            .finish()
394    }
395}
396
397/// Notification that the server is closing the connection.
398#[derive(Debug)]
399pub struct ServiceDisconnect(ServiceDisconnectReason);
400
401impl ServiceDisconnect {
402    fn new(reason: ServiceDisconnectReason) -> Self {
403        Self(reason)
404    }
405
406    #[inline]
407    /// Returns why the connection is being closed.
408    pub fn reason(&self) -> ServiceDisconnectReason {
409        self.0
410    }
411
412    #[inline]
413    /// Acknowledges the notification and closes the connection.
414    pub fn ack<F>(self) -> ControlAck<F> {
415        ControlAck {
416            result: ControlResult::Stop,
417        }
418    }
419}
420
421/// Notification that a keep-alive connection is being closed.
422#[derive(Debug)]
423pub struct KeepAlive {
424    enabled: bool,
425}
426
427impl KeepAlive {
428    pub(super) fn new(enabled: bool) -> Self {
429        Self { enabled }
430    }
431
432    #[inline]
433    /// Returns whether keep-alive was enabled for the connection.
434    pub fn is_enabled(&self) -> bool {
435        self.enabled
436    }
437
438    #[inline]
439    /// Acknowledges the notification and closes the connection.
440    pub fn ack<F>(self) -> ControlAck<F> {
441        ControlAck {
442            result: ControlResult::Stop,
443        }
444    }
445}
446
447/// An application service error and its generated response.
448#[derive(Debug)]
449pub struct Error<Err> {
450    err: Err,
451    pkt: Response,
452}
453
454impl<Err: ResponseError> Error<Err> {
455    fn new(err: Err) -> Self {
456        Self {
457            pkt: err.error_response(),
458            err,
459        }
460    }
461
462    #[inline]
463    /// Returns the application service error.
464    pub fn get_ref(&self) -> &Err {
465        &self.err
466    }
467
468    #[inline]
469    /// Returns mutable access to the application service error.
470    pub fn get_mut(&mut self) -> &mut Err {
471        &mut self.err
472    }
473
474    #[inline]
475    /// Sends the response generated from the service error.
476    pub fn ack<F>(self) -> ControlAck<F> {
477        let (res, body) = self.pkt.into_parts();
478        ControlAck {
479            result: ControlResult::Error(res, body.into()),
480        }
481    }
482
483    #[inline]
484    /// Replaces the generated response with a response produced from `err`.
485    pub fn fail<E: ResponseError, F>(self, err: E) -> ControlAck<F> {
486        let res: Response = (&err).into();
487        let (res, body) = res.into_parts();
488
489        ControlAck {
490            result: ControlResult::Error(res, body.into()),
491        }
492    }
493
494    #[inline]
495    /// Replaces the generated response with a custom response.
496    pub fn fail_with<F>(self, res: Response) -> ControlAck<F> {
497        let (res, body) = res.into_parts();
498
499        ControlAck {
500            result: ControlResult::Error(res, body.into()),
501        }
502    }
503}
504
505/// A protocol error reported to the control service.
506#[derive(Debug)]
507pub struct ProtocolError(super::ProtocolError);
508
509impl ProtocolError {
510    #[inline]
511    /// Returns the protocol error.
512    pub fn get_ref(&self) -> &super::ProtocolError {
513        &self.0
514    }
515
516    #[inline]
517    /// Sends the response generated from the protocol error.
518    pub fn ack<F>(self) -> ControlAck<F> {
519        let (res, body) = self.0.error_response().into_parts();
520
521        ControlAck {
522            result: ControlResult::ProtocolError(res, body.into()),
523        }
524    }
525
526    #[inline]
527    /// Replaces the generated response with a response produced from `err`.
528    pub fn fail<E: ResponseError, F>(self, err: E) -> ControlAck<F> {
529        let res: Response = (&err).into();
530        let (res, body) = res.into_parts();
531
532        ControlAck {
533            result: ControlResult::ProtocolError(res, body.into()),
534        }
535    }
536
537    #[inline]
538    /// Replaces the generated response with a custom response.
539    pub fn fail_with<F>(self, res: Response) -> ControlAck<F> {
540        let (res, body) = res.into_parts();
541
542        ControlAck {
543            result: ControlResult::ProtocolError(res, body.into()),
544        }
545    }
546}
547
548/// Notification that the peer closed the connection.
549///
550/// A clean peer close in the middle of a request head or body carries an
551/// [`io::ErrorKind::UnexpectedEof`] error, so a truncated request is not
552/// reported as a clean disconnect.
553#[derive(Debug)]
554pub struct PeerGone(Option<io::Error>);
555
556impl PeerGone {
557    #[inline]
558    /// Returns the underlying I/O error, if one was reported.
559    pub fn get_ref(&self) -> Option<&io::Error> {
560        self.0.as_ref()
561    }
562
563    #[inline]
564    /// Returns mutable access to the underlying I/O error, if one was reported.
565    pub fn get_mut(&mut self) -> Option<&mut io::Error> {
566        self.0.as_mut()
567    }
568
569    #[inline]
570    /// Takes the underlying I/O error, if one was reported.
571    pub fn take(&mut self) -> Option<io::Error> {
572        self.0.take()
573    }
574
575    #[inline]
576    /// Acknowledges the notification and stops the connection.
577    pub fn ack<F>(self) -> ControlAck<F> {
578        ControlAck {
579            result: ControlResult::Stop,
580        }
581    }
582}
583
584/// A request containing an `Expect: 100-continue` header.
585#[derive(Debug)]
586pub struct Expect(Request);
587
588impl Expect {
589    #[inline]
590    /// Returns the HTTP request.
591    pub fn get_ref(&self) -> &Request {
592        &self.0
593    }
594
595    #[inline]
596    /// Returns mutable access to the HTTP request.
597    pub fn get_mut(&mut self) -> &mut Request {
598        &mut self.0
599    }
600
601    #[inline]
602    /// Sends `100 Continue` and passes the request to the application service.
603    pub fn ack<F>(self) -> ControlAck<F> {
604        ControlAck {
605            result: ControlResult::Continue(self.0),
606        }
607    }
608
609    #[inline]
610    /// Rejects the expectation with the response generated from `err`.
611    pub fn fail<E: ResponseError, F>(self, err: E) -> ControlAck<F> {
612        let res: Response = (&err).into();
613        let (res, body) = res.into_parts();
614
615        ControlAck {
616            result: ControlResult::ExpectFailed(res, body.into()),
617        }
618    }
619
620    #[inline]
621    /// Rejects the expectation with a custom response.
622    pub fn fail_with<F>(self, res: Response) -> ControlAck<F> {
623        let (res, body) = res.into_parts();
624
625        ControlAck {
626            result: ControlResult::ExpectFailed(res, body.into()),
627        }
628    }
629}
630
631#[cfg(test)]
632mod tests {
633    use super::*;
634    use crate::http::HttpServiceConfig;
635    use crate::http::message::IoAccess;
636    use crate::service::cfg::SharedCfg;
637    use crate::testing::IoTest;
638
639    /// STATEMENT: Request transport access can be taken once while previously obtained references remain valid.
640    ///
641    /// HOW:
642    /// - Obtain a reference, take and drop the transport, then check the reference tag and rejected subsequent accesses.
643    /// - Check diagnostics retain the I/O state and codec connection ID after the transport has been taken.
644    #[crate::rt_test]
645    async fn request_io_access_is_one_shot() {
646        let (_, server) = IoTest::create();
647        let cfg: SharedCfg = SharedCfg::new("TEST").add(HttpServiceConfig::new()).into();
648        let io = Rc::new(Io::new(server, cfg.clone()));
649        let access = RequestIoAccess {
650            ioref: io.get_ref(),
651            io,
652            codec: Codec::new(1, cfg.get()),
653            taken: Cell::new(false),
654        };
655
656        let ioref = access.get().unwrap();
657        let debug = format!("{access:?}");
658        assert!(debug.starts_with("RequestIoAccess { io: IoRef { state: "));
659        assert!(debug.contains("codec: h1::Codec { con_id: 1,"));
660        let (io, _) = access.take().unwrap();
661        drop(io);
662        let debug = format!("{access:?}");
663        assert!(debug.starts_with("RequestIoAccess { io: IoRef { state: "));
664        assert!(debug.contains("codec: h1::Codec { con_id: 1,"));
665        // `get()` result does not borrow the taken io
666        assert_eq!(ioref.tag(), "TEST");
667        assert!(access.get().is_none());
668        assert!(access.take().is_none());
669    }
670
671    /// STATEMENT: Request transport access cannot be taken from filter callbacks, which run while the dispatcher borrows the transport.
672    ///
673    /// HOW:
674    /// - Register a filter callback that tries to take the transport, then run the callbacks through the shared `Io`.
675    /// - Check the take in the callback returned `None` and left access in place, and that a later take outside callbacks succeeds.
676    #[crate::rt_test]
677    async fn request_io_access_rejects_take_in_filter_callbacks() {
678        struct Cb(Rc<RequestIoAccess<crate::io::Base>>, Rc<Cell<Option<bool>>>);
679        impl crate::io::IoCallbacks for Cb {
680            fn before_processing(&self, _: &IoRef) {
681                self.1.set(Some(self.0.take().is_none()));
682            }
683            fn after_processing(&self, _: &IoRef) {}
684        }
685
686        let (_, server) = IoTest::create();
687        let cfg: SharedCfg = SharedCfg::new("TEST").add(HttpServiceConfig::new()).into();
688        let io = Rc::new(Io::new(server, cfg.clone()));
689        let access = Rc::new(RequestIoAccess {
690            ioref: io.get_ref(),
691            io,
692            codec: Codec::new(1, cfg.get()),
693            taken: Cell::new(false),
694        });
695        let rejected = Rc::new(Cell::new(None));
696        access
697            .io
698            .register_filter_callbacks(Cb(access.clone(), rejected.clone()));
699
700        access.io.with_buf(|_| ()).unwrap();
701        assert_eq!(rejected.get(), Some(true));
702        assert!(access.get().is_some());
703        let (io, _) = access.take().unwrap();
704        drop(io);
705        assert!(access.take().is_none());
706    }
707
708    type Ctl = Control<crate::io::Base, io::Error>;
709
710    fn io() -> Io {
711        let (_, server) = IoTest::create();
712        let cfg: SharedCfg = SharedCfg::new("TEST").add(HttpServiceConfig::new()).into();
713        Io::new(server, cfg)
714    }
715
716    /// STATEMENT: Control debug output distinguishes requests, expectations, and disconnect reasons.
717    ///
718    /// HOW:
719    /// - Format request, expectation, keepalive, and error controls and inspect their variant labels.
720    #[test]
721    fn debug_fmt() {
722        let s = format!("{:?}", Ctl::request(Request::new()));
723        assert!(s.starts_with("Control::Request(NewRequest("), "{s}");
724        let s = format!("{:?}", Ctl::expect(Request::new()));
725        assert!(s.starts_with("Control::Expect(Expect("), "{s}");
726        let s = format!("{:?}", Ctl::keepalive(true));
727        assert!(s.contains("Control::Disconnect(KeepAlive("), "{s}");
728        let s = format!("{:?}", Ctl::err(io::Error::other("err")));
729        assert!(s.contains("Control::Disconnect(Error("), "{s}");
730    }
731
732    /// STATEMENT: Transport-bearing control messages have distinct connect and upgrade debug representations.
733    ///
734    /// HOW:
735    /// - Construct both message kinds with test transports and inspect their formatted output.
736    #[crate::rt_test]
737    async fn debug_fmt_io() {
738        let s = format!("{:?}", Ctl::connect(1, io()));
739        assert_eq!(s, "Control::Connect");
740
741        let cfg: SharedCfg = SharedCfg::new("TEST").add(HttpServiceConfig::new()).into();
742        let msg = Ctl::upgrade(Request::new(), Rc::new(io()), Codec::new(1, cfg.get()));
743        let s = format!("{msg:?}");
744        assert!(s.starts_with("Control::Upgrade(Upgrade"), "{s}");
745    }
746
747    /// STATEMENT: Connection controls expose their ID and transport before acknowledging connection acceptance.
748    ///
749    /// HOW:
750    /// - Inspect mutable and shared transport access, then verify acknowledgment produces a connect result.
751    #[crate::rt_test]
752    async fn connection() {
753        let Control::Connect(mut msg) = Ctl::connect(7, io()) else {
754            panic!()
755        };
756        assert_eq!(msg.id(), 7);
757        assert_eq!(msg.get_ref().tag(), "TEST");
758        assert_eq!(msg.get_mut().tag(), "TEST");
759        assert!(matches!(msg.ack().result, ControlResult::Connect(_)));
760    }
761
762    /// STATEMENT: New-request controls allow mutation and either publication or an error response.
763    ///
764    /// HOW:
765    /// - Change a request method and acknowledge publication, then fail another with a slow-request timeout.
766    /// - Verify the failure response has request-timeout status.
767    #[test]
768    fn new_request() {
769        let Control::Request(mut msg) = Ctl::request(Request::new()) else {
770            panic!()
771        };
772        msg.get_mut().head_mut().method = crate::http::Method::POST;
773        assert_eq!(msg.get_ref().method(), &crate::http::Method::POST);
774        assert!(matches!(
775            msg.ack::<crate::io::Base>().result,
776            ControlResult::Publish(_)
777        ));
778
779        let Control::Request(msg) = Ctl::request(Request::new()) else {
780            panic!()
781        };
782        let ControlResult::Response(res, _) = msg
783            .fail::<_, crate::io::Base>(super::super::ProtocolError::SlowRequestTimeout)
784            .result
785        else {
786            panic!()
787        };
788        assert_eq!(res.status(), crate::http::StatusCode::REQUEST_TIMEOUT);
789    }
790
791    /// STATEMENT: Expectation controls retain request mutations and acknowledge continuation.
792    ///
793    /// HOW:
794    /// - Change the request method, inspect it through shared access, and check the continuation result.
795    #[test]
796    fn expect() {
797        let Control::Expect(mut msg) = Ctl::expect(Request::new()) else {
798            panic!()
799        };
800        msg.get_mut().head_mut().method = crate::http::Method::PUT;
801        assert_eq!(msg.get_ref().method(), &crate::http::Method::PUT);
802        assert!(matches!(
803            msg.ack::<crate::io::Base>().result,
804            ControlResult::Continue(_)
805        ));
806    }
807
808    /// STATEMENT: Disconnect controls preserve reason-specific details and produce the appropriate stop or error acknowledgment.
809    ///
810    /// HOW:
811    /// - Exercise service, keepalive, mutable error, protocol-error, and peer-gone controls.
812    /// - Inspect their details and acknowledgment variants, including an internal-server-error response.
813    #[test]
814    fn disconnect_reasons() {
815        let Control::Disconnect(Reason::Service(msg)) =
816            Ctl::svc_disconnect(ServiceDisconnectReason::PayloadDropped)
817        else {
818            panic!()
819        };
820        assert_eq!(msg.reason(), ServiceDisconnectReason::PayloadDropped);
821        assert!(matches!(
822            msg.ack::<crate::io::Base>().result,
823            ControlResult::Stop
824        ));
825
826        for enabled in [true, false] {
827            let Control::Disconnect(Reason::KeepAlive(msg)) = Ctl::keepalive(enabled) else {
828                panic!()
829            };
830            assert_eq!(msg.is_enabled(), enabled);
831            assert!(matches!(
832                msg.ack::<crate::io::Base>().result,
833                ControlResult::Stop
834            ));
835        }
836
837        let Control::Disconnect(Reason::Error(mut msg)) = Ctl::err(io::Error::other("err")) else {
838            panic!()
839        };
840        *msg.get_mut() = io::Error::other("changed");
841        assert_eq!(msg.get_ref().to_string(), "changed");
842        let ControlResult::Error(res, _) = msg.ack::<crate::io::Base>().result else {
843            panic!()
844        };
845        assert_eq!(res.status(), crate::http::StatusCode::INTERNAL_SERVER_ERROR);
846
847        let Control::Disconnect(Reason::ProtocolError(msg)) =
848            Ctl::proto_err(super::super::ProtocolError::SlowPayloadTimeout)
849        else {
850            panic!()
851        };
852        assert!(matches!(
853            msg.get_ref(),
854            super::super::ProtocolError::SlowPayloadTimeout
855        ));
856
857        let Control::Disconnect(Reason::PeerGone(mut msg)) = Ctl::peer_gone(None) else {
858            panic!()
859        };
860        assert!(msg.get_ref().is_none());
861        assert!(msg.get_mut().is_none());
862        assert!(msg.take().is_none());
863        assert!(matches!(
864            msg.ack::<crate::io::Base>().result,
865            ControlResult::Stop
866        ));
867    }
868}