Skip to main content

ntex_io/
flags.rs

1use std::{cell::Cell, fmt};
2
3/// What the connection is currently doing.
4///
5/// A connection only ever moves forward through these states.
6///
7/// Later states are not necessarily passed *through*: the transport can report
8/// the connection as gone at any point, taking it straight from
9/// [`Phase::Active`] to [`Phase::Stopped`].
10#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
11enum Phase {
12    /// Io is in active state.
13    Active,
14    /// The filter chain is shutting down.
15    FiltersStopping(Manner),
16    /// The filters are done and the transport is draining buffered output.
17    TransportShutdown(Manner),
18    /// The backend released the socket, transport teardown is complete.
19    ///
20    /// Keeps how the connection ended, so it can still be told apart once
21    /// the connection is gone. A connection the transport reported as gone
22    /// without a close having been started ended `Graceful`.
23    Stopped(Manner),
24}
25
26impl Phase {
27    /// Position in the progression, ignoring how the connection ends.
28    fn stage(self) -> u8 {
29        match self {
30            Phase::Active => 0,
31            Phase::FiltersStopping(_) => 1,
32            Phase::TransportShutdown(_) => 2,
33            Phase::Stopped(_) => 3,
34        }
35    }
36
37    /// Checks whether this is at least as far along as `other`.
38    fn reached(self, other: Phase) -> bool {
39        self.stage() >= other.stage()
40    }
41
42    /// How the connection is ending or ended, `Graceful` while it is active.
43    fn manner(self) -> Manner {
44        match self {
45            Phase::FiltersStopping(m) | Phase::TransportShutdown(m) | Phase::Stopped(m) => m,
46            Phase::Active => Manner::Graceful,
47        }
48    }
49}
50
51/// How the connection is being ended.
52///
53///  Ordered by severity, so raising it can never downgrade an abort that is already in progress.
54#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
55enum Manner {
56    /// Ending normally, buffered output is still delivered.
57    Graceful,
58    /// A failure or an expired deadline is tearing the connection down.
59    Terminating,
60    /// The application asked for a force close through `IoRef::terminate()`.
61    ForceClosed,
62}
63
64pub struct Flags {
65    bits: Cell<FlagsKind>,
66    phase: Cell<Phase>,
67}
68
69bitflags::bitflags! {
70    #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
71    pub struct FlagsKind: u32 {
72        /// filter callbacks are running
73        const IN_CALLBACKS        = 1 << 0;
74        /// pause io read
75        const RD_PAUSED           = 1 << 1;
76        /// read backpressure
77        const RD_BACKPRESSURE     = 1 << 2;
78        /// transport read side reached clean EOF
79        const RD_EOF              = 1 << 3;
80
81        /// a `read_notify()` waiter wants to hear about the next transport read
82        const RD_NOTIFY           = 1 << 4;
83        /// a transport read completed while `RD_NOTIFY` was set
84        const RD_NOTIFIED         = 1 << 5;
85
86        /// read paused, output a filter produced while reading filled the write buffer
87        const RD_WR_BACKPRESSURE  = 1 << 6;
88        /// read paused, the filter chain is not ready for more input
89        const FILTER_PAUSED       = 1 << 7;
90        /// the filter chain failed, it is not called again
91        const FILTER_FAILED       = 1 << 12;
92
93        /// new data is available in read buffer
94        const BUF_R_READY         = 1 << 8;
95
96        /// flush write buf
97        const WR_FLUSH            = 1 << 9;
98        /// write task paused
99        const WR_PAUSED           = 1 << 10;
100        /// write op is scheduled
101        const WR_SEND_OP          = 1 << 11;
102
103        /// timeout occurred
104        const DSP_TIMEOUT         = 1 << 13;
105        /// write buffer is full
106        const DSP_W_BACKPRESSURE  = 1 << 14;
107        /// is direct-write enabled
108        const DIRECT_WR_SUP       = 1 << 15;
109
110        /// the filter chain is the base filter and no filter callbacks are
111        /// registered, filter processing is a no-op
112        const PLAIN_FILTER        = 1 << 16;
113    }
114}
115
116impl Clone for Flags {
117    fn clone(&self) -> Self {
118        Self {
119            bits: Cell::new(self.bits.get()),
120            phase: Cell::new(self.phase.get()),
121        }
122    }
123}
124
125impl Flags {
126    pub(crate) fn new(direct_wr: bool) -> Self {
127        let bits = if direct_wr {
128            FlagsKind::WR_PAUSED | FlagsKind::PLAIN_FILTER | FlagsKind::DIRECT_WR_SUP
129        } else {
130            FlagsKind::WR_PAUSED | FlagsKind::PLAIN_FILTER
131        };
132        Self {
133            bits: Cell::new(bits),
134            phase: Cell::new(Phase::Active),
135        }
136    }
137
138    pub(crate) fn new_stopped() -> Self {
139        Self {
140            bits: Cell::new(FlagsKind::empty()),
141            phase: Cell::new(Phase::Stopped(Manner::Graceful)),
142        }
143    }
144
145    fn contains(&self, f: FlagsKind) -> bool {
146        self.bits.get().contains(f)
147    }
148
149    fn intersects(&self, f: FlagsKind) -> bool {
150        self.bits.get().intersects(f)
151    }
152
153    fn insert(&self, f: FlagsKind) {
154        let mut flags = self.bits.get();
155        flags.insert(f);
156        self.bits.set(flags);
157    }
158
159    fn remove(&self, f: FlagsKind) {
160        let mut flags = self.bits.get();
161        flags.remove(f);
162        self.bits.set(flags);
163    }
164
165    fn reached(&self, phase: Phase) -> bool {
166        self.phase.get().reached(phase)
167    }
168
169    fn ending_at_least(&self, manner: Manner) -> bool {
170        self.phase.get().manner() >= manner
171    }
172
173    /// Checks whether the connection stopped exchanging data with the peer.
174    ///
175    /// Unlike [`is_active`](Self::is_active) this excludes the filter
176    /// shutdown phase, during which the filter chain may still produce output
177    /// that has to reach the peer.
178    pub(crate) fn is_peer_gone(&self) -> bool {
179        self.is_closed()
180            || self.reached(Phase::TransportShutdown(Manner::Graceful))
181            || self.is_terminating()
182    }
183
184    /// Checks whether the backend released the socket.
185    pub(crate) fn is_closed(&self) -> bool {
186        matches!(self.phase.get(), Phase::Stopped(_))
187    }
188
189    /// Checks whether the connection is aborting or already gone.
190    ///
191    /// Unlike [`is_peer_gone`](Self::is_peer_gone) this does not cover the graceful
192    /// transport shutdown phase, during which buffered output is still written
193    /// out.
194    pub(crate) fn is_aborted(&self) -> bool {
195        self.is_closed() || self.is_terminating()
196    }
197
198    /// Checks whether the connection reached transport shutdown.
199    ///
200    /// This stays set once backend teardown completes, including for a
201    /// connection the transport reported as gone without a shutdown having
202    /// been started.
203    pub(crate) fn is_stopping(&self) -> bool {
204        self.reached(Phase::TransportShutdown(Manner::Graceful))
205    }
206
207    /// Checks whether the connection is ending, or ended, through the
208    /// force-termination path.
209    ///
210    /// This stays set once backend teardown completes.
211    pub(crate) fn is_terminating(&self) -> bool {
212        self.ending_at_least(Manner::Terminating)
213    }
214
215    /// Checks whether the application asked for a force close.
216    ///
217    /// Only [`IoRef::terminate`](crate::IoRef::terminate) sets this. A
218    /// transport failure or an expired shutdown deadline terminate the
219    /// connection as well, but they close it gracefully rather than aborting
220    /// it.
221    ///
222    /// This stays set once backend teardown completes.
223    pub(crate) fn is_force_closing(&self) -> bool {
224        self.ending_at_least(Manner::ForceClosed)
225    }
226
227    pub(crate) fn is_stopping_or_terminating(&self) -> bool {
228        self.is_stopping() || self.is_terminating()
229    }
230
231    /// Checks whether the connection is still in its active state.
232    ///
233    /// False from the moment any kind of close starts, and for a connection
234    /// the transport reported as gone without a shutdown having been started.
235    pub(crate) fn is_active(&self) -> bool {
236        self.phase.get() == Phase::Active
237    }
238
239    pub(crate) fn is_stopping_filters(&self) -> bool {
240        self.reached(Phase::FiltersStopping(Manner::Graceful))
241    }
242
243    pub(crate) fn is_write_flush(&self) -> bool {
244        self.intersects(FlagsKind::WR_FLUSH)
245    }
246
247    /// Checks whether the filter chain is the stage currently shutting down.
248    ///
249    /// Unlike [`is_stopping_filters`](Self::is_stopping_filters) this is only
250    /// true while that stage is the current one, so it goes false once the
251    /// transport shutdown starts or the connection ends.
252    pub(crate) fn is_shutting_down_filters(&self) -> bool {
253        self.phase.get() == Phase::FiltersStopping(Manner::Graceful)
254    }
255
256    pub(crate) fn is_direct_wr_enabled(&self) -> bool {
257        self.contains(FlagsKind::DIRECT_WR_SUP)
258    }
259
260    pub(crate) fn set_direct_wr_enabled(&self, enabled: bool) {
261        if enabled {
262            self.insert(FlagsKind::DIRECT_WR_SUP);
263        } else {
264            self.remove(FlagsKind::DIRECT_WR_SUP);
265        }
266    }
267
268    pub(crate) fn is_read_paused(&self) -> bool {
269        self.contains(FlagsKind::RD_PAUSED)
270    }
271
272    pub(crate) fn is_write_paused(&self) -> bool {
273        self.contains(FlagsKind::WR_PAUSED)
274    }
275
276    pub(crate) fn is_read_ready(&self) -> bool {
277        self.contains(FlagsKind::BUF_R_READY)
278    }
279
280    pub(crate) fn is_read_notify(&self) -> bool {
281        self.contains(FlagsKind::RD_NOTIFY)
282    }
283
284    #[cfg(test)]
285    pub(crate) fn is_read_notified(&self) -> bool {
286        self.contains(FlagsKind::RD_NOTIFIED)
287    }
288
289    pub(crate) fn is_rd_backpressure(&self) -> bool {
290        self.contains(FlagsKind::RD_BACKPRESSURE)
291    }
292
293    pub(crate) fn is_read_eof(&self) -> bool {
294        self.contains(FlagsKind::RD_EOF)
295    }
296
297    pub(crate) fn is_wr_backpressure(&self) -> bool {
298        self.contains(FlagsKind::DSP_W_BACKPRESSURE)
299    }
300
301    pub(crate) fn is_wr_send_scheduled(&self) -> bool {
302        self.contains(FlagsKind::WR_SEND_OP)
303    }
304
305    pub(crate) fn is_read_wr_backpressure(&self) -> bool {
306        self.contains(FlagsKind::RD_WR_BACKPRESSURE)
307    }
308
309    pub(crate) fn set_read_wr_backpressure(&self) {
310        self.insert(FlagsKind::RD_WR_BACKPRESSURE);
311    }
312
313    pub(crate) fn unset_read_wr_backpressure(&self) {
314        self.remove(FlagsKind::RD_WR_BACKPRESSURE);
315    }
316
317    pub(crate) fn is_filter_paused(&self) -> bool {
318        self.contains(FlagsKind::FILTER_PAUSED)
319    }
320
321    pub(crate) fn set_filter_paused(&self) {
322        self.insert(FlagsKind::FILTER_PAUSED);
323    }
324
325    pub(crate) fn unset_filter_paused(&self) {
326        self.remove(FlagsKind::FILTER_PAUSED);
327    }
328
329    pub(crate) fn is_filter_failed(&self) -> bool {
330        self.contains(FlagsKind::FILTER_FAILED)
331    }
332
333    pub(crate) fn set_filter_failed(&self) {
334        self.insert(FlagsKind::FILTER_FAILED);
335    }
336
337    /// Checks whether filter processing is skipped, the filter chain is
338    /// plain or has failed.
339    #[inline]
340    pub(crate) fn is_filter_skipped(&self) -> bool {
341        self.intersects(FlagsKind::PLAIN_FILTER | FlagsKind::FILTER_FAILED)
342    }
343
344    /// Records that a filter or filter callbacks were installed, it is never
345    /// set again.
346    pub(crate) fn unset_plain_filter(&self) {
347        self.remove(FlagsKind::PLAIN_FILTER);
348    }
349
350    pub(crate) fn is_in_callbacks(&self) -> bool {
351        self.contains(FlagsKind::IN_CALLBACKS)
352    }
353
354    pub(crate) fn set_in_callbacks(&self) {
355        self.insert(FlagsKind::IN_CALLBACKS);
356    }
357
358    pub(crate) fn unset_in_callbacks(&self) {
359        self.remove(FlagsKind::IN_CALLBACKS);
360    }
361
362    pub(crate) fn is_read_paused_or_backpressure(&self) -> bool {
363        self.intersects(FlagsKind::RD_PAUSED | FlagsKind::RD_BACKPRESSURE)
364    }
365
366    pub(crate) fn set_read_paused(&self) {
367        self.insert(FlagsKind::RD_PAUSED);
368    }
369
370    pub(crate) fn set_write_paused(&self) {
371        self.insert(FlagsKind::WR_PAUSED);
372    }
373
374    pub(crate) fn set_wr_send_scheduled(&self) {
375        self.insert(FlagsKind::WR_SEND_OP);
376    }
377
378    /// Returns whether write backpressure was not enabled before.
379    pub(crate) fn set_wr_backpressure(&self) -> bool {
380        let enabled = !self.contains(FlagsKind::DSP_W_BACKPRESSURE);
381        self.insert(FlagsKind::DSP_W_BACKPRESSURE);
382        enabled
383    }
384
385    /// Starts a graceful shutdown with the filter chain.
386    pub(crate) fn enter_filters_stopping(&self) {
387        if self.phase.get() == Phase::Active {
388            self.phase.set(Phase::FiltersStopping(Manner::Graceful));
389        }
390    }
391
392    /// Moves the connection onto the termination path.
393    ///
394    /// `force` marks an abort requested through
395    /// [`IoRef::terminate`](crate::IoRef::terminate), which the transport turns
396    /// into a reset rather than a graceful close.
397    ///
398    /// Returns whether this call started the termination, so that the caller
399    /// runs the one-off teardown work exactly once. An already terminating
400    /// connection still has its manner escalated, so a force close is honoured
401    /// even when a graceful termination got there first; a connection the
402    /// transport already reported as gone is left alone.
403    pub(crate) fn begin_terminate(&self, force: bool) -> bool {
404        let manner = if force {
405            Manner::ForceClosed
406        } else {
407            Manner::Terminating
408        };
409        let phase = self.phase.get();
410        let started = phase.manner() < Manner::Terminating;
411        self.phase.set(match phase {
412            Phase::Stopped(_) => return false,
413            Phase::Active => Phase::FiltersStopping(manner),
414            Phase::FiltersStopping(m) => Phase::FiltersStopping(m.max(manner)),
415            Phase::TransportShutdown(m) => Phase::TransportShutdown(m.max(manner)),
416        });
417
418        if started {
419            self.insert(FlagsKind::BUF_R_READY);
420        }
421        started
422    }
423
424    pub(crate) fn set_stopped(&self) {
425        let manner = self.phase.get().manner();
426        self.phase.set(Phase::Stopped(manner));
427    }
428
429    pub(crate) fn set_wants_write_flush(&self) {
430        self.insert(FlagsKind::WR_FLUSH);
431    }
432
433    pub(crate) fn set_read_notify(&self) {
434        self.insert(FlagsKind::RD_NOTIFY);
435    }
436
437    pub(crate) fn set_read_notified(&self) {
438        self.insert(FlagsKind::RD_NOTIFIED);
439    }
440
441    pub(crate) fn set_read_ready(&self) {
442        self.insert(FlagsKind::BUF_R_READY);
443    }
444
445    /// Returns whether read backpressure was not enabled before.
446    pub(crate) fn set_read_ready_and_backpressure(&self) -> bool {
447        let enabled = !self.contains(FlagsKind::RD_BACKPRESSURE);
448        self.insert(FlagsKind::RD_PAUSED | FlagsKind::BUF_R_READY | FlagsKind::RD_BACKPRESSURE);
449        enabled
450    }
451
452    pub(crate) fn set_read_eof(&self) {
453        self.insert(FlagsKind::RD_EOF);
454    }
455
456    /// Moves on to transport shutdown, keeping how the connection ends.
457    pub(crate) fn enter_transport_shutdown(&self) {
458        match self.phase.get() {
459            Phase::Active => self.phase.set(Phase::TransportShutdown(Manner::Graceful)),
460            Phase::FiltersStopping(m) => self.phase.set(Phase::TransportShutdown(m)),
461            Phase::TransportShutdown(_) | Phase::Stopped(_) => {}
462        }
463    }
464
465    pub(crate) fn unset_write_paused(&self) {
466        self.remove(FlagsKind::WR_PAUSED);
467    }
468
469    pub(crate) fn unset_wr_send_scheduled(&self) {
470        self.remove(FlagsKind::WR_SEND_OP);
471    }
472
473    /// Returns whether write backpressure was enabled.
474    pub(crate) fn unset_wr_backpressure(&self) -> bool {
475        let disabled = self.contains(FlagsKind::DSP_W_BACKPRESSURE);
476        self.remove(FlagsKind::DSP_W_BACKPRESSURE);
477        disabled
478    }
479
480    /// Returns whether write backpressure was enabled.
481    pub(crate) fn unset_wr_backpressure_and_flush(&self) -> bool {
482        let disabled = self.contains(FlagsKind::DSP_W_BACKPRESSURE);
483        self.remove(FlagsKind::DSP_W_BACKPRESSURE | FlagsKind::WR_FLUSH);
484        disabled
485    }
486
487    /// `RD_PAUSED` is deliberately left set, even though
488    /// `set_read_ready_and_backpressure()` installs it. Callers rely on the
489    /// pause surviving so that they can detect it and wake the read task.
490    ///
491    /// Returns whether read backpressure was enabled.
492    pub(crate) fn unset_read_ready_and_backpressure(&self) -> bool {
493        let disabled = self.contains(FlagsKind::RD_BACKPRESSURE);
494        self.remove(FlagsKind::BUF_R_READY | FlagsKind::RD_BACKPRESSURE);
495        disabled
496    }
497
498    pub(crate) fn unset_read_ready(&self) {
499        self.remove(FlagsKind::BUF_R_READY);
500    }
501
502    pub(crate) fn unset_read_paused(&self) {
503        self.remove(FlagsKind::RD_PAUSED);
504    }
505
506    /// Reports whether a transport read completed for the `read_notify()`
507    /// waiter, and ends that wait by clearing both `RD_NOTIFY` and
508    /// `RD_NOTIFIED`.
509    pub(crate) fn take_read_notified(&self) -> bool {
510        if self.contains(FlagsKind::RD_NOTIFIED) {
511            self.remove(FlagsKind::RD_NOTIFY | FlagsKind::RD_NOTIFIED);
512            true
513        } else {
514            false
515        }
516    }
517
518    /// Checks `DSP_TIMEOUT` and unsets
519    pub(crate) fn check_dispatcher_timeout(&self) -> bool {
520        if self.contains(FlagsKind::DSP_TIMEOUT) {
521            self.remove(FlagsKind::DSP_TIMEOUT);
522            true
523        } else {
524            false
525        }
526    }
527
528    /// Checks `DSP_TIMEOUT` and sets
529    pub(crate) fn check_dispatcher_timeout_unset(&self) -> bool {
530        if self.contains(FlagsKind::DSP_TIMEOUT) {
531            false
532        } else {
533            self.insert(FlagsKind::DSP_TIMEOUT);
534            true
535        }
536    }
537}
538
539impl fmt::Debug for Flags {
540    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
541        write!(f, "{:?} | {:?}", self.bits.get(), self.phase.get())
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use super::*;
548
549    /// STATEMENT: `Flags` debug output identifies the connection state and `FlagsKind` bits.
550    ///
551    /// HOW:
552    /// - Format stopped and active `Flags`; expect `Stopped` and `Active`.
553    /// - Format `FlagsKind::RD_EOF`; expect the `RD_EOF` bit name.
554    #[test]
555    fn flags() {
556        assert!(format!("{:?}", Flags::new_stopped()).contains("Stopped"));
557        assert!(format!("{:?}", Flags::new(false)).contains("Active"));
558        assert!(format!("{:?}", FlagsKind::RD_EOF).contains("RD_EOF"));
559    }
560
561    /// STATEMENT: Every `FlagsKind` occupies a distinct bit.
562    ///
563    /// HOW:
564    /// - Compare the number of set bits in all flags with the number of iterated flag kinds.
565    #[test]
566    fn flag_bits_are_distinct() {
567        let all = FlagsKind::all().bits();
568        assert_eq!(
569            all.count_ones() as usize,
570            FlagsKind::all().iter().count(),
571            "two flags share a bit"
572        );
573    }
574
575    /// STATEMENT: Shutdown phases never move backward and stopped connections remain closed.
576    ///
577    /// HOW:
578    /// - Advance through filter and transport shutdown, retry earlier transitions, then stop.
579    /// - Check phase predicates and verify subsequent transitions cannot reopen the connection.
580    #[test]
581    fn shutdown_phase_only_moves_forward() {
582        let f = Flags::new(false);
583        assert!(!f.is_stopping_filters());
584        assert!(!f.is_stopping());
585
586        f.enter_filters_stopping();
587        assert!(f.is_stopping_filters());
588        assert!(f.is_shutting_down_filters());
589        assert!(!f.is_stopping());
590
591        f.enter_transport_shutdown();
592        assert!(f.is_stopping());
593        // the earlier stage stays reported, and is no longer the current one
594        assert!(f.is_stopping_filters());
595        assert!(!f.is_shutting_down_filters());
596
597        // an earlier stage cannot pull the connection back
598        f.enter_filters_stopping();
599        assert!(f.is_stopping());
600
601        // stopped is terminal
602        f.set_stopped();
603        f.enter_filters_stopping();
604        f.enter_transport_shutdown();
605        assert!(f.is_closed());
606    }
607
608    /// STATEMENT: Stopping reaches the terminal phase even when earlier shutdown stages are skipped.
609    ///
610    /// HOW:
611    /// - Stop one connection after graceful shutdown stages and another directly from active.
612    /// - Check both report all earlier stages reached, without ongoing filter shutdown.
613    #[test]
614    fn stopped_is_the_last_state_whichever_route_reached_it() {
615        // walked the whole shutdown
616        let graceful = Flags::new(false);
617        graceful.enter_filters_stopping();
618        graceful.enter_transport_shutdown();
619        graceful.set_stopped();
620
621        // the transport reported the connection gone while it was still active
622        let hup = Flags::new(false);
623        hup.set_stopped();
624
625        for f in [&graceful, &hup] {
626            assert!(f.is_closed());
627            assert!(!f.is_active());
628            assert!(f.is_stopping());
629            assert!(f.is_stopping_filters());
630            // nothing is in progress anymore
631            assert!(!f.is_shutting_down_filters());
632        }
633    }
634
635    /// STATEMENT: A stopped transport is gone without implying a termination or force-close request.
636    ///
637    /// HOW:
638    /// - Stop an active connection and check closed, peer-gone, and aborted predicates.
639    /// - Verify it is neither active, terminating, nor force-closing.
640    #[test]
641    fn a_stopped_connection_is_gone_without_having_been_aborted() {
642        let f = Flags::new(false);
643        f.set_stopped();
644        assert!(f.is_closed());
645        assert!(f.is_peer_gone());
646        assert!(f.is_aborted());
647        assert!(!f.is_active());
648        // the transport reported it gone, nothing asked for an abort
649        assert!(!f.is_terminating());
650        assert!(!f.is_force_closing());
651    }
652
653    /// STATEMENT: Termination starts teardown once but later requests can escalate to force-close.
654    ///
655    /// HOW:
656    /// - Begin termination repeatedly and check only the first call requests teardown.
657    /// - Escalate to force-close and verify termination, filter-stage, and readiness flags.
658    #[test]
659    fn terminate_runs_teardown_once_and_force_still_escalates() {
660        let f = Flags::new(false);
661        assert!(f.begin_terminate(false));
662        assert!(f.is_terminating());
663        assert!(!f.is_force_closing());
664        // reaching the filter stage is implied by terminating
665        assert!(f.is_stopping_filters());
666        assert!(f.is_read_ready());
667
668        // second call does not repeat the teardown work
669        assert!(!f.begin_terminate(false));
670
671        // but a force close still escalates how the connection ends
672        assert!(!f.begin_terminate(true));
673        assert!(f.is_force_closing());
674        assert!(f.is_terminating());
675    }
676
677    /// STATEMENT: Graceful termination cannot downgrade an existing force-close request.
678    ///
679    /// HOW:
680    /// - Begin forceful termination, then request graceful termination and check force-close remains.
681    #[test]
682    fn force_close_is_never_downgraded() {
683        let f = Flags::new(false);
684        assert!(f.begin_terminate(true));
685        assert!(f.is_force_closing());
686        f.begin_terminate(false);
687        assert!(
688            f.is_force_closing(),
689            "graceful terminate downgraded an abort"
690        );
691    }
692
693    /// STATEMENT: The shutdown state machine reaches exactly its ten representable states.
694    ///
695    /// HOW:
696    /// - Enumerate operation sequences up to five transitions, respecting transport prerequisites.
697    /// - Compare visited phases with active and every shutdown phase/manner combination.
698    #[test]
699    fn every_representable_state_is_reachable() {
700        const OPS: usize = 5;
701        let mut seen = std::collections::HashSet::new();
702
703        for len in 1..=5u32 {
704            for mut code in 0..OPS.pow(len) {
705                let f = Flags::new(false);
706                for _ in 0..len {
707                    let op = code % OPS;
708                    code /= OPS;
709                    match op {
710                        0 => f.enter_filters_stopping(),
711                        // only reachable from inside filter shutdown
712                        1 => {
713                            if f.is_stopping_filters() {
714                                f.enter_transport_shutdown();
715                            }
716                        }
717                        2 => {
718                            f.begin_terminate(false);
719                        }
720                        3 => {
721                            f.begin_terminate(true);
722                        }
723                        _ => f.set_stopped(),
724                    }
725                    seen.insert(f.phase.get());
726                }
727            }
728        }
729
730        let manners = [Manner::Graceful, Manner::Terminating, Manner::ForceClosed];
731        let expected: std::collections::HashSet<_> = [Phase::Active]
732            .into_iter()
733            .chain(manners.map(Phase::FiltersStopping))
734            .chain(manners.map(Phase::TransportShutdown))
735            .chain(manners.map(Phase::Stopped))
736            .collect();
737        assert_eq!(seen.len(), 10);
738        assert_eq!(seen, expected);
739    }
740
741    /// STATEMENT: Transitioning from filter to transport shutdown preserves the termination manner.
742    ///
743    /// HOW:
744    /// - Begin graceful and forceful termination, advance to transport shutdown, and compare manners.
745    #[test]
746    fn finishing_the_filters_keeps_how_the_connection_ends() {
747        for (force, manner) in [(false, Manner::Terminating), (true, Manner::ForceClosed)] {
748            let f = Flags::new(false);
749            f.begin_terminate(force);
750            assert_eq!(f.phase.get(), Phase::FiltersStopping(manner));
751            f.enter_transport_shutdown();
752            assert_eq!(f.phase.get(), Phase::TransportShutdown(manner));
753            assert_eq!(f.is_force_closing(), force);
754        }
755    }
756
757    /// STATEMENT: Stopping preserves graceful, terminating, and force-closed shutdown manners.
758    ///
759    /// HOW:
760    /// - Stop terminating connections during filter and transport shutdown and check their manners.
761    /// - Complete a clean shutdown and verify it remains graceful rather than terminating.
762    #[test]
763    fn a_stopped_connection_remembers_how_it_ended() {
764        for (force, manner) in [(false, Manner::Terminating), (true, Manner::ForceClosed)] {
765            // stopped during filter shutdown
766            let f = Flags::new(false);
767            f.begin_terminate(force);
768            f.set_stopped();
769            assert_eq!(f.phase.get(), Phase::Stopped(manner));
770
771            // stopped during transport shutdown
772            let f = Flags::new(false);
773            f.begin_terminate(force);
774            f.enter_transport_shutdown();
775            f.set_stopped();
776            assert_eq!(f.phase.get(), Phase::Stopped(manner));
777            assert!(f.is_closed() && f.is_terminating());
778            assert_eq!(f.is_force_closing(), force);
779        }
780
781        // a clean close stays clean
782        let f = Flags::new(false);
783        f.enter_filters_stopping();
784        f.enter_transport_shutdown();
785        f.set_stopped();
786        assert_eq!(f.phase.get(), Phase::Stopped(Manner::Graceful));
787        assert!(!f.is_terminating());
788    }
789
790    /// STATEMENT: A force-close request does not change an already stopped connection.
791    ///
792    /// HOW:
793    /// - Stop an active connection, request forceful termination, and check no teardown or escalation.
794    #[test]
795    fn a_terminated_connection_is_left_alone() {
796        let f = Flags::new(false);
797        f.set_stopped();
798        assert!(!f.begin_terminate(true));
799        assert!(!f.is_force_closing());
800        assert!(!f.is_terminating());
801    }
802}