asupersync 0.3.0

Spec-first, cancel-correct, capability-secure async runtime for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
//! WebSocket close handshake protocol (RFC 6455 Section 7).
//!
//! The close handshake ensures clean connection termination with proper
//! status code propagation. The protocol is:
//!
//! 1. Initiator sends Close frame with optional status code and reason
//! 2. Receiver replies with a Close frame, typically echoing the peer's
//!    status code when it is valid for transmission
//! 3. Both sides enter closed state
//!
//! # Cancel-Safety
//!
//! Close operations are designed to be cancel-safe:
//! - Bounded timeout prevents hanging on unresponsive peers
//! - Cancellation uses GoingAway (1001) status code
//! - Partial close is handled gracefully
//!
//! # Example
//!
//! ```ignore
//! use asupersync::net::websocket::{CloseReason, CloseCode};
//!
//! // Parse close frame payload
//! let reason = CloseReason::parse(&payload)?;
//! println!("Close code: {:?}, reason: {:?}", reason.code, reason.text);
//!
//! // Create close response
//! let response = CloseReason::new(CloseCode::Normal, None);
//! ```

use super::{CloseCode, Frame, Opcode, WsError};
use crate::bytes::Bytes;
use std::time::Duration;

/// Parsed close frame payload.
///
/// A close frame may contain:
/// - No payload (empty)
/// - 2 bytes: status code only
/// - 2+ bytes: status code followed by UTF-8 reason text
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CloseReason {
    /// Close status code (if present).
    pub code: Option<CloseCode>,
    /// Raw close status code from wire payload, including custom codes.
    pub raw_code: Option<u16>,
    /// Close reason text (if present).
    pub text: Option<String>,
}

impl CloseReason {
    /// Create a new close reason.
    #[must_use]
    pub fn new(code: CloseCode, text: Option<&str>) -> Self {
        let raw = u16::from(code);
        Self {
            code: Some(code),
            raw_code: Some(raw),
            text: text.map(String::from),
        }
    }

    /// Create an empty close reason (no code or text).
    #[must_use]
    pub fn empty() -> Self {
        Self {
            code: None,
            raw_code: None,
            text: None,
        }
    }

    /// Create a close reason for normal closure.
    #[must_use]
    pub fn normal() -> Self {
        Self::new(CloseCode::Normal, None)
    }

    /// Create a close reason for going away (cancellation).
    #[must_use]
    pub fn going_away() -> Self {
        Self::new(CloseCode::GoingAway, None)
    }

    /// Create a close reason with text.
    #[must_use]
    pub fn with_text(code: CloseCode, text: &str) -> Self {
        Self::new(code, Some(text))
    }

    /// Parse a close frame payload.
    ///
    /// # Payload Format
    ///
    /// - Empty: No code or reason
    /// - 2 bytes: Big-endian status code
    /// - 2+ bytes: Status code + UTF-8 reason text
    ///
    /// # Errors
    ///
    /// Returns `WsError::InvalidClosePayload` if:
    /// - Payload is exactly 1 byte (invalid)
    /// - Status code is invalid/reserved for wire use
    /// - Reason text is not valid UTF-8
    pub fn parse(payload: &[u8]) -> Result<Self, WsError> {
        match payload.len() {
            0 => Ok(Self::empty()),
            1 => Err(WsError::InvalidClosePayload),
            _ => {
                let code_raw = u16::from_be_bytes([payload[0], payload[1]]);
                if !CloseCode::is_valid_received_code(code_raw) {
                    return Err(WsError::InvalidClosePayload);
                }
                let code = CloseCode::from_u16(code_raw);

                let text = if payload.len() > 2 {
                    let text_bytes = &payload[2..];
                    let text_str = std::str::from_utf8(text_bytes)
                        .map_err(|_| WsError::InvalidClosePayload)?;
                    Some(text_str.to_string())
                } else {
                    None
                };

                Ok(Self {
                    code,
                    raw_code: Some(code_raw),
                    text,
                })
            }
        }
    }

    /// Encode this close reason into a frame payload.
    #[must_use]
    pub fn encode(&self) -> Bytes {
        match self.outbound_payload_parts() {
            (DropReasonText::No, code, text) => Self::encode_parts(code, text),
            (DropReasonText::Yes, code, _) => Self::encode_parts(code, None),
        }
    }

    fn encode_parts(code: Option<u16>, text: Option<&str>) -> Bytes {
        match (code, text) {
            (None, None) => Bytes::new(),
            (None, Some(_text)) => Bytes::new(),
            (Some(code_val), None) => Bytes::copy_from_slice(&code_val.to_be_bytes()),
            (Some(code_val), Some(text)) => {
                let mut buf = Vec::with_capacity(2 + text.len());
                buf.extend_from_slice(&code_val.to_be_bytes());
                buf.extend_from_slice(text.as_bytes());
                Bytes::from(buf)
            }
        }
    }

    /// Convert to a close frame.
    #[must_use]
    pub fn to_frame(&self) -> Frame {
        match self.outbound_payload_parts() {
            (DropReasonText::No, code, text) => Frame::close(code, text),
            (DropReasonText::Yes, code, _) => Frame::close(code, None),
        }
    }

    /// Returns the outbound wire close code when this reason can be sent
    /// without violating RFC 6455's send-side close-code rules.
    #[must_use]
    fn outbound_wire_code(&self) -> Option<u16> {
        match self.raw_code {
            Some(code) if CloseCode::is_valid_code(code) => Some(code),
            Some(_) => None,
            None => self
                .code
                .map(u16::from)
                .filter(|code| CloseCode::is_valid_code(*code)),
        }
    }

    /// Returns the code/text pair to place on the wire.
    ///
    /// A parsed peer code may be valid to receive but forbidden to send
    /// (for example 1016-2999). In that case we downgrade to an empty close
    /// frame instead of inventing a different status code.
    #[must_use]
    fn outbound_payload_parts(&self) -> (DropReasonText, Option<u16>, Option<&str>) {
        let code = self.outbound_wire_code();
        let drop_text = (self.raw_code.is_some() || self.code.is_some()) && code.is_none();
        (
            if drop_text {
                DropReasonText::Yes
            } else {
                DropReasonText::No
            },
            code,
            self.text.as_deref(),
        )
    }

    /// Check if this represents a normal closure.
    #[must_use]
    pub fn is_normal(&self) -> bool {
        self.wire_code() == Some(u16::from(CloseCode::Normal))
    }

    /// Check if this represents a protocol error.
    #[must_use]
    pub fn is_error(&self) -> bool {
        matches!(
            self.code,
            Some(
                CloseCode::ProtocolError
                    | CloseCode::InvalidPayload
                    | CloseCode::PolicyViolation
                    | CloseCode::InternalError
            )
        )
    }

    /// Returns the wire close code (including custom codes).
    #[must_use]
    pub const fn wire_code(&self) -> Option<u16> {
        match (self.raw_code, self.code) {
            (Some(code), _) => Some(code),
            (None, Some(code)) => Some(code as u16),
            (None, None) => None,
        }
    }
}

impl Default for CloseReason {
    fn default() -> Self {
        Self::empty()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DropReasonText {
    No,
    Yes,
}

/// State of the close handshake.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CloseState {
    /// Connection is open (normal operation).
    #[default]
    Open,
    /// We sent a close frame, waiting for peer's close frame.
    CloseSent,
    /// We received a close frame, need to send response.
    CloseReceived,
    /// Close handshake complete, connection can be terminated.
    Closed,
}

impl CloseState {
    /// Check if the connection is still open for data.
    #[must_use]
    pub const fn is_open(self) -> bool {
        matches!(self, Self::Open)
    }

    /// Check if the close handshake is complete.
    #[must_use]
    pub const fn is_closed(self) -> bool {
        matches!(self, Self::Closed)
    }

    /// Check if we're in the process of closing.
    #[must_use]
    pub const fn is_closing(self) -> bool {
        matches!(self, Self::CloseSent | Self::CloseReceived)
    }
}

/// Configuration for close handshake behavior.
#[derive(Debug, Clone)]
pub struct CloseConfig {
    /// Timeout for waiting for close response from peer.
    pub close_timeout: Duration,
    /// Whether to send close frame on drop if still open.
    pub close_on_drop: bool,
    /// Default close code for cancellation.
    pub cancellation_code: CloseCode,
}

impl Default for CloseConfig {
    fn default() -> Self {
        Self {
            close_timeout: Duration::from_secs(5),
            close_on_drop: true,
            cancellation_code: CloseCode::GoingAway,
        }
    }
}

impl CloseConfig {
    /// Create a new close configuration.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the close timeout.
    #[must_use]
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.close_timeout = timeout;
        self
    }

    /// Set whether to send close on drop.
    #[must_use]
    pub fn with_close_on_drop(mut self, enabled: bool) -> Self {
        self.close_on_drop = enabled;
        self
    }

    /// Set the cancellation close code.
    #[must_use]
    pub fn with_cancellation_code(mut self, code: CloseCode) -> Self {
        self.cancellation_code = code;
        self
    }
}

/// Close handshake state machine.
///
/// Tracks the state of the WebSocket close handshake and provides
/// methods for transitioning through the handshake phases.
#[derive(Debug)]
pub struct CloseHandshake {
    /// Current state of the handshake.
    state: CloseState,
    /// Configuration.
    config: CloseConfig,
    /// Our close reason (if we initiated).
    our_reason: Option<CloseReason>,
    /// Peer's close reason (if they initiated).
    peer_reason: Option<CloseReason>,
}

impl CloseHandshake {
    /// Create a new close handshake tracker.
    #[must_use]
    pub fn new() -> Self {
        Self::with_config(CloseConfig::default())
    }

    /// Create with custom configuration.
    #[must_use]
    pub fn with_config(config: CloseConfig) -> Self {
        Self {
            state: CloseState::Open,
            config,
            our_reason: None,
            peer_reason: None,
        }
    }

    /// Get the current state.
    #[must_use]
    pub const fn state(&self) -> CloseState {
        self.state
    }

    /// Check if the connection is open.
    #[must_use]
    pub const fn is_open(&self) -> bool {
        self.state.is_open()
    }

    /// Check if the close handshake is complete.
    #[must_use]
    pub const fn is_closed(&self) -> bool {
        self.state.is_closed()
    }

    /// Get our close reason (if we initiated).
    #[must_use]
    pub fn our_reason(&self) -> Option<&CloseReason> {
        self.our_reason.as_ref()
    }

    /// Get peer's close reason (if they initiated).
    #[must_use]
    pub fn peer_reason(&self) -> Option<&CloseReason> {
        self.peer_reason.as_ref()
    }

    /// Get the close timeout.
    #[must_use]
    pub const fn close_timeout(&self) -> Duration {
        self.config.close_timeout
    }

    /// Initiate a close handshake.
    ///
    /// Returns the close frame to send, or `None` if already closing/closed.
    ///
    /// # State Transitions
    ///
    /// - `Open` โ†’ `CloseSent`: Returns close frame
    /// - `CloseReceived` โ†’ `CloseReceived`: Returns close frame (response)
    ///   and waits for [`mark_response_sent`](Self::mark_response_sent)
    ///   before completing the handshake
    /// - `CloseSent` | `Closed`: Returns `None`
    pub fn initiate(&mut self, reason: CloseReason) -> Option<Frame> {
        match self.state {
            CloseState::Open => {
                self.state = CloseState::CloseSent;
                let frame = reason.to_frame();
                self.our_reason = Some(reason);
                Some(frame)
            }
            CloseState::CloseReceived => {
                // We're responding to their close. The handshake is not
                // complete until the response frame is actually sent.
                let frame = reason.to_frame();
                self.our_reason = Some(reason);
                Some(frame)
            }
            CloseState::CloseSent | CloseState::Closed => None,
        }
    }

    /// Handle a received close frame.
    ///
    /// Returns the close frame to send in response, or `None` if no response needed.
    ///
    /// # State Transitions
    ///
    /// - `Open` โ†’ `CloseReceived`: Stores peer reason, returns response frame
    /// - `CloseSent` โ†’ `Closed`: Stores peer reason, returns `None` (handshake complete)
    /// - `CloseReceived` | `Closed`: Returns `None` (duplicate/unexpected)
    pub fn receive_close(&mut self, frame: &Frame) -> Result<Option<Frame>, WsError> {
        if frame.opcode != Opcode::Close {
            return Err(WsError::InvalidOpcode(frame.opcode as u8));
        }

        let reason = CloseReason::parse(&frame.payload)?;

        match self.state {
            CloseState::Open => {
                // Peer initiated close - we need to respond
                self.state = CloseState::CloseReceived;

                // Echo the peer's status code only when it is valid for
                // transmission. Receive-only reserved codes (1016-2999) must
                // be accepted during parsing but must not be sent back.
                let response_code = reason.outbound_wire_code();
                self.peer_reason = Some(reason);
                let response = if let Some(response_code) = response_code {
                    Frame::close(Some(response_code), None)
                } else {
                    Frame::close(None, None)
                };
                Ok(Some(response))
            }
            CloseState::CloseSent => {
                // We sent close, peer is responding - handshake complete
                self.state = CloseState::Closed;
                self.peer_reason = Some(reason);
                Ok(None)
            }
            CloseState::CloseReceived | CloseState::Closed => {
                // Duplicate or unexpected close frame - ignore
                Ok(None)
            }
        }
    }

    /// Mark that the close response frame has been successfully sent.
    ///
    /// Transitions `CloseReceived` -> `Closed`. In all other states this is a no-op.
    pub fn mark_response_sent(&mut self) {
        if self.state == CloseState::CloseReceived {
            self.state = CloseState::Closed;
        }
    }

    /// Force transition to closed state.
    ///
    /// Use this when the connection is terminated without proper handshake
    /// (timeout, error, etc.).
    pub fn force_close(&mut self, reason: CloseReason) {
        self.state = CloseState::Closed;
        if self.our_reason.is_none() {
            self.our_reason = Some(reason);
        }
    }

    /// Reset to open state.
    ///
    /// This should only be used for testing or connection reuse.
    #[cfg(test)]
    pub fn reset(&mut self) {
        self.state = CloseState::Open;
        self.our_reason = None;
        self.peer_reason = None;
    }
}

impl Default for CloseHandshake {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn close_reason_parse_empty() {
        let reason = CloseReason::parse(&[]).unwrap();
        assert_eq!(reason.code, None);
        assert_eq!(reason.raw_code, None);
        assert_eq!(reason.text, None);
    }

    #[test]
    fn close_reason_parse_code_only() {
        let payload = 1000u16.to_be_bytes();
        let reason = CloseReason::parse(&payload).unwrap();
        assert_eq!(reason.code, Some(CloseCode::Normal));
        assert_eq!(reason.raw_code, Some(1000));
        assert_eq!(reason.text, None);
    }

    #[test]
    fn close_reason_parse_code_and_text() {
        let mut payload = Vec::new();
        payload.extend_from_slice(&1001u16.to_be_bytes());
        payload.extend_from_slice(b"Going away");

        let reason = CloseReason::parse(&payload).unwrap();
        assert_eq!(reason.code, Some(CloseCode::GoingAway));
        assert_eq!(reason.raw_code, Some(1001));
        assert_eq!(reason.text.as_deref(), Some("Going away"));
    }

    #[test]
    fn close_reason_parse_custom_code_preserves_raw_code() {
        let mut payload = Vec::new();
        payload.extend_from_slice(&3001u16.to_be_bytes());
        payload.extend_from_slice(b"custom");

        let reason = CloseReason::parse(&payload).unwrap();
        assert_eq!(reason.code, None);
        assert_eq!(reason.raw_code, Some(3001));
        assert_eq!(reason.wire_code(), Some(3001));
        assert_eq!(reason.text.as_deref(), Some("custom"));
    }

    #[test]
    fn close_reason_parse_invalid_single_byte() {
        let result = CloseReason::parse(&[0x00]);
        assert!(result.is_err());
    }

    #[test]
    fn close_reason_parse_invalid_utf8() {
        let mut payload = Vec::new();
        payload.extend_from_slice(&1000u16.to_be_bytes());
        payload.extend_from_slice(&[0xFF, 0xFE]); // Invalid UTF-8

        let result = CloseReason::parse(&payload);
        assert!(result.is_err());
    }

    #[test]
    fn close_reason_parse_invalid_reserved_code() {
        let payload = 1004u16.to_be_bytes();
        let result = CloseReason::parse(&payload);
        assert!(matches!(result, Err(WsError::InvalidClosePayload)));
    }

    #[test]
    fn close_reason_parse_unassigned_code_accepted() {
        // 1016 is unassigned โ€” RFC 6455 ยง7.4.2 requires endpoints to accept them
        let payload = 1016u16.to_be_bytes();
        let result = CloseReason::parse(&payload).unwrap();
        assert_eq!(result.code, None);
        assert_eq!(result.raw_code, Some(1016));
    }

    #[test]
    fn close_reason_parse_iana_registered_1012_accepted() {
        let payload = 1012u16.to_be_bytes();
        let result = CloseReason::parse(&payload);
        assert!(result.is_ok(), "IANA-registered code 1012 must parse");
    }

    #[test]
    fn close_reason_encode_empty() {
        let reason = CloseReason::empty();
        let encoded = reason.encode();
        assert!(encoded.is_empty());
    }

    #[test]
    fn close_reason_encode_code_only() {
        let reason = CloseReason::new(CloseCode::Normal, None);
        let encoded = reason.encode();
        assert_eq!(encoded.as_ref(), &1000u16.to_be_bytes());
    }

    #[test]
    fn close_reason_encode_code_and_text() {
        let reason = CloseReason::with_text(CloseCode::GoingAway, "bye");
        let encoded = reason.encode();

        let mut expected = Vec::new();
        expected.extend_from_slice(&1001u16.to_be_bytes());
        expected.extend_from_slice(b"bye");

        assert_eq!(encoded.as_ref(), expected.as_slice());
    }

    #[test]
    fn close_reason_roundtrip() {
        let original = CloseReason::with_text(CloseCode::Normal, "goodbye");
        let encoded = original.encode();
        let parsed = CloseReason::parse(&encoded).unwrap();

        assert_eq!(original.code, parsed.code);
        assert_eq!(original.raw_code, parsed.raw_code);
        assert_eq!(original.text, parsed.text);
    }

    #[test]
    fn close_reason_unsendable_received_code_encodes_as_empty_close() {
        let payload = 2000u16.to_be_bytes();
        let reason = CloseReason::parse(&payload).unwrap();

        assert_eq!(reason.raw_code, Some(2000));
        assert!(reason.encode().is_empty());
        assert!(reason.to_frame().payload.is_empty());
    }

    #[test]
    fn close_reason_without_code_drops_text_on_encode() {
        let reason = CloseReason {
            code: None,
            raw_code: None,
            text: Some("text without code".to_string()),
        };

        assert!(reason.encode().is_empty());
        assert!(reason.to_frame().payload.is_empty());
    }

    #[test]
    fn close_code_valid_ranges() {
        assert!(CloseCode::is_valid_code(1000));
        assert!(CloseCode::is_valid_code(1003));
        assert!(CloseCode::is_valid_code(1007));
        assert!(CloseCode::is_valid_code(1011));
        assert!(CloseCode::is_valid_code(3000));
        assert!(CloseCode::is_valid_code(4999));

        assert!(!CloseCode::is_valid_code(1004)); // Reserved
        assert!(!CloseCode::is_valid_code(1005)); // NoStatusReceived
        assert!(!CloseCode::is_valid_code(1006)); // Abnormal
        assert!(!CloseCode::is_valid_code(999)); // Below valid range
        assert!(!CloseCode::is_valid_code(5000)); // Above valid range
    }

    #[test]
    fn close_state_transitions() {
        assert!(CloseState::Open.is_open());
        assert!(!CloseState::Open.is_closed());
        assert!(!CloseState::Open.is_closing());

        assert!(!CloseState::CloseSent.is_open());
        assert!(!CloseState::CloseSent.is_closed());
        assert!(CloseState::CloseSent.is_closing());

        assert!(!CloseState::Closed.is_open());
        assert!(CloseState::Closed.is_closed());
        assert!(!CloseState::Closed.is_closing());
    }

    #[test]
    fn handshake_initiate_from_open() {
        let mut handshake = CloseHandshake::new();
        let frame = handshake.initiate(CloseReason::normal());

        assert!(frame.is_some());
        assert_eq!(handshake.state(), CloseState::CloseSent);
        assert!(handshake.our_reason().is_some());
    }

    #[test]
    fn handshake_initiate_when_already_closing() {
        let mut handshake = CloseHandshake::new();
        handshake.initiate(CloseReason::normal());

        // Second initiate should return None
        let frame = handshake.initiate(CloseReason::normal());
        assert!(frame.is_none());
    }

    #[test]
    fn handshake_receive_close_from_open() {
        let mut handshake = CloseHandshake::new();
        let close_frame = Frame::close(Some(1000), Some("bye"));

        let response = handshake.receive_close(&close_frame).unwrap();

        assert!(response.is_some());
        assert_eq!(handshake.state(), CloseState::CloseReceived);
        assert!(handshake.peer_reason().is_some());
    }

    #[test]
    fn handshake_receive_close_echoes_custom_code() {
        let mut handshake = CloseHandshake::new();
        let close_frame = Frame::close(Some(3001), Some("custom"));

        let response = handshake.receive_close(&close_frame).unwrap().unwrap();
        assert_eq!(response.opcode, Opcode::Close);
        assert_eq!(&response.payload[..2], &3001u16.to_be_bytes());
        assert_eq!(handshake.peer_reason().unwrap().wire_code(), Some(3001));
        assert_eq!(handshake.state(), CloseState::CloseReceived);
    }

    #[test]
    fn handshake_receive_close_rejects_rfc6455_tls_handshake_code_1015() {
        let mut handshake = CloseHandshake::new();
        let close_frame = Frame {
            fin: true,
            rsv1: false,
            rsv2: false,
            rsv3: false,
            opcode: Opcode::Close,
            masked: false,
            mask_key: None,
            payload: Bytes::copy_from_slice(&1015u16.to_be_bytes()),
        };

        let err = handshake.receive_close(&close_frame).unwrap_err();
        assert!(matches!(err, WsError::InvalidClosePayload));
        assert_eq!(handshake.state(), CloseState::Open);
        assert!(handshake.peer_reason().is_none());
    }

    #[test]
    fn handshake_receive_empty_close_keeps_response_payload_empty() {
        let mut handshake = CloseHandshake::new();
        let close_frame = Frame::close(None, None);

        let response = handshake.receive_close(&close_frame).unwrap().unwrap();

        assert_eq!(response.opcode, Opcode::Close);
        assert!(response.payload.is_empty());
        assert_eq!(handshake.peer_reason(), Some(&CloseReason::empty()));
        assert_eq!(handshake.state(), CloseState::CloseReceived);
    }

    #[test]
    fn handshake_receive_close_after_sent() {
        let mut handshake = CloseHandshake::new();
        handshake.initiate(CloseReason::normal());

        let close_frame = Frame::close(Some(1000), None);
        let response = handshake.receive_close(&close_frame).unwrap();

        assert!(response.is_none()); // No response needed
        assert_eq!(handshake.state(), CloseState::Closed);
    }

    #[test]
    fn handshake_complete_flow_initiator() {
        let mut handshake = CloseHandshake::new();

        // 1. We initiate close
        let frame = handshake.initiate(CloseReason::normal());
        assert!(frame.is_some());
        assert_eq!(handshake.state(), CloseState::CloseSent);

        // 2. We receive peer's close response
        let peer_close = Frame::close(Some(1000), None);
        let response = handshake.receive_close(&peer_close).unwrap();
        assert!(response.is_none()); // Handshake complete, no response
        assert_eq!(handshake.state(), CloseState::Closed);
    }

    #[test]
    fn handshake_complete_flow_receiver() {
        let mut handshake = CloseHandshake::new();

        // 1. We receive peer's close
        let peer_close = Frame::close(Some(1000), Some("goodbye"));
        let response = handshake.receive_close(&peer_close).unwrap();
        assert!(response.is_some());
        assert_eq!(handshake.state(), CloseState::CloseReceived);

        // 2. We prepare our close response
        let frame = handshake.initiate(CloseReason::normal());
        assert!(frame.is_some());
        assert_eq!(handshake.state(), CloseState::CloseReceived);

        // 3. The handshake only completes after the response is sent
        handshake.mark_response_sent();
        assert_eq!(handshake.state(), CloseState::Closed);
    }

    #[test]
    fn handshake_response_initiation_does_not_complete_before_send() {
        let mut handshake = CloseHandshake::new();

        let peer_close = Frame::close(Some(1000), Some("goodbye"));
        let response = handshake.receive_close(&peer_close).unwrap();
        assert!(response.is_some());
        assert_eq!(handshake.state(), CloseState::CloseReceived);

        let frame = handshake.initiate(CloseReason::with_text(CloseCode::Normal, "ack"));
        assert!(frame.is_some());
        assert_eq!(handshake.state(), CloseState::CloseReceived);
        assert!(!handshake.is_open());
        assert!(!handshake.is_closed());
    }

    #[test]
    fn handshake_mark_response_sent_closes_after_receiving_peer_close() {
        let mut handshake = CloseHandshake::new();

        let peer_close = Frame::close(Some(1000), Some("bye"));
        let response = handshake.receive_close(&peer_close).unwrap();
        assert!(response.is_some());
        assert_eq!(handshake.state(), CloseState::CloseReceived);

        handshake.mark_response_sent();
        assert_eq!(handshake.state(), CloseState::Closed);
        assert!(handshake.is_closed());
    }

    #[test]
    fn handshake_force_close() {
        let mut handshake = CloseHandshake::new();
        handshake.force_close(CloseReason::new(CloseCode::Abnormal, None));

        assert_eq!(handshake.state(), CloseState::Closed);
        assert!(handshake.our_reason().is_some());
    }

    #[test]
    fn handshake_force_close_preserves_supplied_reason() {
        let mut handshake = CloseHandshake::new();
        let reason = CloseReason::with_text(CloseCode::GoingAway, "cancelled by region close");

        handshake.force_close(reason.clone());

        assert_eq!(handshake.state(), CloseState::Closed);
        assert_eq!(handshake.our_reason(), Some(&reason));
        assert!(handshake.peer_reason().is_none());
    }

    #[test]
    fn close_config_builder() {
        let config = CloseConfig::new()
            .with_timeout(Duration::from_secs(10))
            .with_close_on_drop(false)
            .with_cancellation_code(CloseCode::InternalError);

        assert_eq!(config.close_timeout, Duration::from_secs(10));
        assert!(!config.close_on_drop);
        assert_eq!(config.cancellation_code, CloseCode::InternalError);
    }

    // =========================================================================
    // Wave 56 โ€“ pure data-type trait coverage
    // =========================================================================

    #[test]
    fn close_reason_debug_clone_eq() {
        let r = CloseReason::normal();
        let dbg = format!("{r:?}");
        assert!(dbg.contains("CloseReason"), "{dbg}");
        let cloned = r.clone();
        assert_eq!(r, cloned);
    }

    #[test]
    fn close_state_debug_clone_copy_eq_default() {
        let s = CloseState::default();
        let dbg = format!("{s:?}");
        assert!(dbg.contains("Open"), "{dbg}");
        let copied = s;
        let cloned = s;
        assert_eq!(copied, cloned);
        assert_ne!(s, CloseState::CloseSent);
    }

    #[test]
    fn close_config_debug_clone() {
        let cfg = CloseConfig::new();
        let dbg = format!("{cfg:?}");
        assert!(dbg.contains("CloseConfig"), "{dbg}");
        let cloned = cfg.clone();
        assert_eq!(cfg.close_timeout, cloned.close_timeout);
    }

    #[test]
    fn handshake_receive_close_does_not_echo_unassigned_code() {
        // RFC 6455 ยง7.4.2: unassigned codes (1016-2999) must be accepted when
        // received, but RFC 6455 endpoints must not send them.
        let mut handshake = CloseHandshake::new();

        let close_frame = Frame {
            fin: true,
            rsv1: false,
            rsv2: false,
            rsv3: false,
            opcode: Opcode::Close,
            masked: false,
            mask_key: None,
            payload: Bytes::copy_from_slice(&1016u16.to_be_bytes()),
        };

        let response = handshake.receive_close(&close_frame).unwrap().unwrap();
        assert_eq!(response.opcode, Opcode::Close);
        assert!(response.payload.is_empty());
        assert_eq!(handshake.state(), CloseState::CloseReceived);
    }

    #[test]
    fn to_frame_with_unassigned_raw_code_does_not_panic() {
        // A CloseReason parsed from a peer with an unassigned code must not
        // panic if higher layers serialize it back out.
        let payload = 2000u16.to_be_bytes();
        let reason = CloseReason::parse(&payload).unwrap();
        assert_eq!(reason.raw_code, Some(2000));
        let frame = reason.to_frame();
        assert_eq!(frame.opcode, Opcode::Close);
        assert!(frame.payload.is_empty());
    }

    #[test]
    fn close_reason_code_falls_back_when_raw_code_is_absent() {
        let reason = CloseReason {
            code: Some(CloseCode::Normal),
            raw_code: None,
            text: None,
        };

        assert_eq!(reason.wire_code(), Some(1000));
        assert!(reason.is_normal());
        assert_eq!(reason.encode().as_ref(), &1000u16.to_be_bytes());
        assert_eq!(reason.to_frame().payload.as_ref(), &1000u16.to_be_bytes());
    }

    #[test]
    fn typed_unsendable_close_code_fails_closed_without_panicking() {
        let reason = CloseReason {
            code: Some(CloseCode::Abnormal),
            raw_code: None,
            text: None,
        };

        assert_eq!(reason.wire_code(), Some(1006));
        assert!(reason.encode().is_empty());
        let frame = reason.to_frame();
        assert_eq!(frame.opcode, Opcode::Close);
        assert!(frame.payload.is_empty());
    }

    #[test]
    fn typed_unsendable_close_code_drops_reason_text_instead_of_synthesizing_normal_close() {
        let reason = CloseReason {
            code: Some(CloseCode::NoStatusReceived),
            raw_code: None,
            text: Some("must not hit wire".to_string()),
        };

        assert_eq!(reason.wire_code(), Some(1005));
        assert!(reason.encode().is_empty());
        let frame = reason.to_frame();
        assert_eq!(frame.opcode, Opcode::Close);
        assert!(frame.payload.is_empty());
    }
}