rift-mock-core 0.25.0

Rift core engine: imposter lifecycle, matching, behaviors, scripting and flow-state — usable in-process without the CLI or admin server.
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
//! Real connection-level TCP faults for `_rift.fault.tcp` (issue #239).
//!
//! A normal `Response` is framed and sent by hyper, so it can never reproduce a transport-level
//! failure. Instead, the matched fault is recorded in a per-connection `FaultCell` (set by the
//! request handler via a `Response` extension) and applied by `FaultIo`, a thin wrapper around
//! the connection's `TcpStream`: on the next write hyper attempts (the response), `FaultIo`
//! performs the fault on the raw socket and returns an error so hyper aborts the connection. The
//! client then observes a genuine reset / empty / malformed / random-data failure, matching
//! WireMock's `Fault` semantics.

use std::io;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::{Context, Poll, ready};
use std::time::Duration;

use hyper::{Response, Version};
use parking_lot::Mutex;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::net::TcpStream;
use tokio::time::{Instant, Sleep};
use tracing::debug;

use super::probe::{FaultLayer, Point, ProbeHandle, fire};

// Lingering-close bounds (issue #1460): total drain time, the longest silence between reads, and
// the most a client may send before the listener stops discarding it. Time, not size, is the real
// bound: draining costs bandwidth, never memory.
const LINGER_DEADLINE: Duration = Duration::from_secs(2);
const LINGER_IDLE: Duration = Duration::from_secs(1);
const LINGER_MAX_BYTES: usize = 64 * 1024 * 1024;
const LINGER_SCRATCH: usize = 16 * 1024;

/// The four WireMock-equivalent connection faults.
///
/// Public because it is the authoritative signal a TCP-fault carrier response carries: the serve
/// loop's `FaultIo` reads exactly this extension, and an in-process embedder that calls
/// [`handle_imposter_request`](crate::imposter::handle_imposter_request) directly receives the
/// carrier the serve loop would have replaced with a socket abort (issue #965). Matching on the
/// kind beats re-deriving one from a string; [`tcp_fault_carrier`] is the string form.
///
/// `#[non_exhaustive]`: an embedder `match`es on this, and a fifth transport fault must not break
/// every one of them — the same reasoning
/// [`StubPlacement`](crate::recording::StubPlacement) carries. Match with a `_` arm
/// and treat an unknown kind as "the connection was aborted somehow" rather than guessing which.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum TcpFaultKind {
    /// Reset the connection (client sees `ECONNRESET`).
    Reset,
    /// Close the connection after the request with no response bytes.
    Empty,
    /// Send random bytes then close (client sees a protocol error).
    RandomData,
    /// Send a status line + a malformed chunked body then close.
    MalformedChunk,
}

impl TcpFaultKind {
    /// Every spelling and the kind it names: each kind's canonical WireMock name and Rift's short
    /// aliases. [`Self::parse`] reads this table and [`Self::SPELLINGS`] is its first column, so
    /// there is one list, not two to keep in step (issue #1342).
    const TABLE: [(&'static str, Self); 9] = [
        ("reset", Self::Reset),
        ("CONNECTION_RESET_BY_PEER", Self::Reset),
        ("empty", Self::Empty),
        ("EMPTY_RESPONSE", Self::Empty),
        ("garbage", Self::RandomData),
        ("random", Self::RandomData),
        ("RANDOM_DATA_THEN_CLOSE", Self::RandomData),
        ("malformed", Self::MalformedChunk),
        ("MALFORMED_RESPONSE_CHUNK", Self::MalformedChunk),
    ];

    /// Every spelling [`Self::parse`] accepts, the list `rift-lint` and the JSON Schema enumerate.
    pub const SPELLINGS: [&'static str; 9] = {
        let mut spellings = [""; 9];
        let mut i = 0;
        while i < spellings.len() {
            spellings[i] = Self::TABLE[i].0;
            i += 1;
        }
        spellings
    };

    /// Parse a `_rift.fault.tcp` string. Accepts the WireMock names and Rift's short aliases.
    #[must_use]
    pub(crate) fn parse(value: &str) -> Option<Self> {
        Self::TABLE
            .iter()
            .find(|(spelling, _)| *spelling == value)
            .map(|(_, kind)| *kind)
    }

    /// The canonical name for this fault — the WireMock-style name the docs present as canonical,
    /// with `reset`/`empty`/`garbage`/`malformed` as its aliases (`docs/features/fault-injection.md`).
    ///
    /// Deliberately not the string the config author wrote: the `x-rift-fault` header echoes that
    /// raw input, which is why a consumer had to mirror the whole alias table to interpret it. One
    /// name per kind is what lets that table be deleted.
    #[must_use]
    pub fn canonical_name(self) -> &'static str {
        match self {
            Self::Reset => "CONNECTION_RESET_BY_PEER",
            Self::Empty => "EMPTY_RESPONSE",
            Self::RandomData => "RANDOM_DATA_THEN_CLOSE",
            Self::MalformedChunk => "MALFORMED_RESPONSE_CHUNK",
        }
    }
}

/// Classify a response as a TCP-fault *carrier*: the placeholder a fault stub produces, which the
/// serve loop's `FaultIo` discards in favour of a real socket abort, so a client over TCP never
/// sees it.
///
/// Returns the fault's [canonical name](TcpFaultKind::canonical_name), or `None` for an ordinary
/// response. An embedder answering a request in-process (rift-cluster #344) receives the carrier
/// itself and needs this to render "the connection would have been aborted" rather than presenting
/// the carrier's `502` as the imposter's answer.
///
/// Reads the extension, not the `x-rift-fault` header, because the header is neither necessary nor
/// sufficient: a v2 script `reset()` carrier historically set no header at all (issue #357), while
/// an `_rift.fault.error` response sets `x-rift-fault: error` and is a real response the client
/// does receive. Generic over the body so classification need not precede a body transformation.
#[must_use]
pub fn tcp_fault_carrier<B>(response: &Response<B>) -> Option<&'static str> {
    response
        .extensions()
        .get::<TcpFaultKind>()
        .map(|kind| kind.canonical_name())
}

/// Per-connection slot for a TCP fault: armed when a request's response is a carrier, read by
/// [`FaultIo`] on that connection's next write.
///
/// Public so a listener other than the imposter's own serve loop — the admin API's `/__rift/`
/// gateway, the front door, or an embedder's listener — can apply a carrier as the real transport
/// fault (issue #1234): wrap the accepted stream in [`FaultIo::new`] with a fresh cell, then arm
/// the cell from the service (`rift_http_proxy::gateway::apply_tcp_fault` does both halves of the
/// decision). A newtype so the lock type stays out of the public API. Cloning shares the slot.
///
/// It also carries the connection's lingering-close request (issue #1460, [`Self::arm_linger`]).
#[derive(Clone, Debug, Default)]
pub struct FaultCell(Arc<CellState>);

#[derive(Default)]
struct CellState {
    fault: Mutex<Option<TcpFaultKind>>,
    linger: AtomicBool,
    /// `formal/faultio`'s probe, `None` in production. It fires only where a fault or a linger is
    /// actually armed or taken, so an unarmed connection never reads it.
    probe: ProbeHandle,
}

impl std::fmt::Debug for CellState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CellState")
            .field("fault", &self.fault)
            .field("linger", &self.linger)
            .finish_non_exhaustive()
    }
}

impl FaultCell {
    /// An empty (un-armed) slot.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// An empty slot that reports to `probe` (`formal/faultio/README.md`).
    pub(crate) fn probed(probe: ProbeHandle) -> Self {
        Self(Arc::new(CellState {
            probe,
            ..CellState::default()
        }))
    }

    /// Arm the slot: the connection's next write performs `kind` instead of writing.
    ///
    /// Only meaningful on an HTTP/1 connection, where the next write is this request's response.
    /// On HTTP/2 the next write may belong to another stream, and the abort would take down every
    /// stream on the connection.
    pub fn arm(&self, kind: TcpFaultKind) {
        *self.0.fault.lock() = Some(kind);
        fire(&self.0.probe, Point::FaultArmed { kind });
    }

    /// Ask for a lingering close: when hyper shuts this connection down, [`FaultIo`] shuts the
    /// write side, then reads and discards whatever the client is still sending — for at most 2 s,
    /// 1 s of silence or 64 MiB — before letting it close.
    ///
    /// The drain is timed with `tokio::time`, so the connection must be driven on a Tokio runtime
    /// with its time driver enabled (a disarmed `FaultIo` needs none). It can hold a graceful
    /// shutdown or imposter delete for up to the 2 s deadline.
    ///
    /// For a response refused with the request body unread (issue #1460). Closing a socket with
    /// unread data makes the kernel send a RST, and a client still writing that body then sees
    /// "connection reset" instead of the refusal. Only arm it on HTTP/1, where the close follows
    /// this response; [`arm_linger_if_requested`] makes that decision from the response.
    pub fn arm_linger(&self) {
        self.0.linger.store(true, Ordering::Relaxed);
        fire(&self.0.probe, Point::LingerArmed);
    }

    fn linger_armed(&self) -> bool {
        self.0.linger.load(Ordering::Relaxed)
    }

    /// Take (not just read) the armed fault so it fires exactly once. `FaultIo` only.
    fn take(&self) -> Option<TcpFaultKind> {
        let taken = self.0.fault.lock().take();
        if let Some(kind) = taken {
            let layer = FaultLayer::RawSocket;
            fire(&self.0.probe, Point::FaultTaken { kind, layer });
        }
        taken
    }

    /// Take the armed fault only if it is a payload kind (random data, malformed chunk), leaving a
    /// reset or empty close armed for the raw-socket [`FaultIo`] beneath TLS (issue #1600).
    ///
    /// Returns the kind with the bytes it writes.
    pub(crate) fn take_payload(&self) -> Option<(TcpFaultKind, &'static [u8])> {
        let mut slot = self.0.fault.lock();
        let armed = (*slot).and_then(|kind| payload(kind).map(|bytes| (kind, bytes)));
        if let Some((kind, _)) = armed {
            *slot = None;
            let layer = FaultLayer::AboveTls;
            fire(&self.0.probe, Point::FaultTaken { kind, layer });
        }
        armed
    }
}

/// The bytes a payload fault writes before closing, or `None` for a fault that writes nothing
/// (reset, empty close). One table, so http and https send the same bytes (issue #1600).
fn payload(kind: TcpFaultKind) -> Option<&'static [u8]> {
    match kind {
        TcpFaultKind::Reset | TcpFaultKind::Empty => None,
        TcpFaultKind::RandomData => Some(b"\x00\xff\xfe\xfd\x13\x37\xde\xad\xbe\xef"),
        TcpFaultKind::MalformedChunk => Some(
            b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nZZZZZ not a valid chunk size\r\n",
        ),
    }
}

/// Response extension: the listener should close this connection with a lingering close
/// (issue #1460, [`FaultCell::arm_linger`]).
///
/// Set on a refusal written while the request body is still unread — the `413`/`503` body-limit
/// doors. The response also says `connection: close`; this marker is what tells the listener the
/// close must not discard the answer.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LingerOnClose;

/// Arm `cell`'s lingering close if `response` carries [`LingerOnClose`] and the connection is
/// HTTP/1. Each listener that wraps its connections in [`FaultIo`] calls this on every response.
///
/// HTTP/2 is left alone: a refused stream is reset on its own while the connection carries on, so
/// there is no close to linger on.
pub fn arm_linger_if_requested<B>(response: &Response<B>, version: Version, cell: &FaultCell) {
    if response.extensions().get::<LingerOnClose>().is_some()
        && matches!(
            version,
            Version::HTTP_09 | Version::HTTP_10 | Version::HTTP_11
        )
    {
        cell.arm_linger();
    }
}

/// The error an injected TCP fault surfaces as: the `io::Error` [`FaultIo`] returns to abort the
/// connection wraps it, and a listener's HTTP/2 service returns it to reset one stream.
///
/// A listener tells an injected fault from a real connection failure with [`is_injected_fault`],
/// so the fault the config asked for is not logged as a server error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InjectedFault(pub TcpFaultKind);

impl std::fmt::Display for InjectedFault {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("rift: injected _rift.fault.tcp")
    }
}

impl std::error::Error for InjectedFault {}

/// Apply a TCP-fault carrier on the connection it is about to be written to (issue #1234).
///
/// For an ordinary response this returns it unchanged. For a carrier (see
/// [`tcp_fault_carrier`]):
///
/// - **HTTP/1**: arms `cell` and hands the carrier back. The listener must have wrapped the
///   connection in [`FaultIo::new`] with this `cell`; `FaultIo` then performs
///   the fault on hyper's write of the carrier, exactly as on the imposter's own port.
/// - **HTTP/2**: returns `Err`, and the service returns it, so hyper resets that one stream
///   (`RST_STREAM`, `INTERNAL_ERROR`) for every fault kind. The cell is never armed: the next write
///   may belong to another stream, and a socket abort would kill every stream on the connection.
///
/// `version` is the request's, read before the request is consumed. Never return the `Err` on
/// HTTP/1 instead: hyper would close without writing, `FaultIo` would never trip, and every kind
/// would degrade to an empty close.
pub fn apply_tcp_fault<B>(
    response: Response<B>,
    version: Version,
    cell: &FaultCell,
) -> Result<Response<B>, InjectedFault> {
    let Some(kind) = response.extensions().get::<TcpFaultKind>().copied() else {
        return Ok(response);
    };
    if matches!(
        version,
        Version::HTTP_09 | Version::HTTP_10 | Version::HTTP_11
    ) {
        cell.arm(kind);
        Ok(response)
    } else {
        Err(InjectedFault(kind))
    }
}

/// Whether `err`, or anything in its source chain, is an [`InjectedFault`].
///
/// Not a plain `source()` walk: `io::Error::source()` returns the *inner* error's source, not the
/// inner error, so a walk through the `io::Error` [`FaultIo`] returns steps straight over the
/// marker. Each `io::Error` in the chain is therefore also opened with `get_ref()`.
#[must_use]
pub fn is_injected_fault(err: &(dyn std::error::Error + 'static)) -> bool {
    let mut current = Some(err);
    while let Some(e) = current {
        if e.is::<InjectedFault>() {
            return true;
        }
        if let Some(inner) = e.downcast_ref::<io::Error>().and_then(io::Error::get_ref)
            && is_injected_fault(inner)
        {
            return true;
        }
        current = e.source();
    }
    false
}

/// A `TcpStream` wrapper that, when its [`FaultCell`] is armed, applies a connection fault on the
/// next write instead of forwarding hyper's response. Reads and (un-armed) writes pass straight
/// through, so it can wrap every accepted connection at no cost to ordinary traffic.
///
/// It also performs the cell's lingering close (issue #1460) in `poll_shutdown`.
#[derive(Debug)]
pub struct FaultIo {
    inner: TcpStream,
    fault: FaultCell,
    linger: Linger,
}

/// Where an armed lingering close has got to. Created on the first armed `poll_shutdown`.
enum Linger {
    NotStarted,
    /// Write side being shut down: the client is to see the response, then a FIN.
    ShuttingWrite,
    Draining(Box<Drain>),
    Done,
}

struct Drain {
    deadline: Pin<Box<Sleep>>,
    idle: Pin<Box<Sleep>>,
    discarded: usize,
    scratch: Box<[u8; LINGER_SCRATCH]>,
}

impl std::fmt::Debug for Linger {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotStarted => f.write_str("NotStarted"),
            Self::ShuttingWrite => f.write_str("ShuttingWrite"),
            Self::Draining(drain) => write!(f, "Draining({} bytes)", drain.discarded),
            Self::Done => f.write_str("Done"),
        }
    }
}

impl Drain {
    fn new() -> Self {
        Self {
            deadline: Box::pin(tokio::time::sleep(LINGER_DEADLINE)),
            idle: Box::pin(tokio::time::sleep(LINGER_IDLE)),
            discarded: 0,
            scratch: Box::new([0; LINGER_SCRATCH]),
        }
    }

    /// Read and discard until EOF, a read error, the byte backstop or a timer. Never fails: the
    /// connection is closing either way, and a read error only means it closed sooner.
    fn poll(&mut self, inner: &mut TcpStream, cx: &mut Context<'_>) -> Poll<()> {
        loop {
            if self.deadline.as_mut().poll(cx).is_ready() || self.idle.as_mut().poll(cx).is_ready()
            {
                return Poll::Ready(());
            }
            let mut buf = ReadBuf::new(&mut self.scratch[..]);
            match ready!(Pin::new(&mut *inner).poll_read(cx, &mut buf)) {
                Ok(()) if !buf.filled().is_empty() => {
                    self.discarded += buf.filled().len();
                    if self.discarded >= LINGER_MAX_BYTES {
                        return Poll::Ready(());
                    }
                    self.idle.as_mut().reset(Instant::now() + LINGER_IDLE);
                }
                Ok(()) => return Poll::Ready(()),
                Err(e) => {
                    debug!("lingering close: read ended the drain: {e}");
                    return Poll::Ready(());
                }
            }
        }
    }
}

impl FaultIo {
    /// Wrap an accepted connection. Wrap before any protocol sniffing or TLS so the fault lands on
    /// the raw socket.
    #[must_use]
    pub fn new(inner: TcpStream, fault: FaultCell) -> Self {
        Self {
            inner,
            fault,
            linger: Linger::NotStarted,
        }
    }

    /// Apply the fault to the raw socket. Returns the error used to abort the hyper connection so
    /// the socket is dropped (and closed) immediately afterwards. The raw socket calls are
    /// best-effort: on failure the connection still breaks, but the *observed* fault may degrade
    /// (e.g. a failed `set_zero_linger` reset becomes a graceful close), so each failure is logged.
    fn trip(&self, kind: TcpFaultKind) -> io::Error {
        match kind {
            // SO_LINGER(0): dropping the socket now emits RST rather than a graceful FIN.
            TcpFaultKind::Reset => {
                if let Err(e) = self.inner.set_zero_linger() {
                    debug!(
                        "rift fault reset: set_zero_linger failed, degraded to graceful close: {e}"
                    );
                }
            }
            // An empty close writes nothing; a payload kind is a best-effort raw write, then a
            // graceful close delivers the bytes before EOF. On an https imposter a payload kind never
            // gets here: `TlsPayloadFault` above the TLS layer takes it first (issue #1600).
            TcpFaultKind::Empty | TcpFaultKind::RandomData | TcpFaultKind::MalformedChunk => {
                if let Some(bytes) = payload(kind)
                    && let Err(e) = self.inner.try_write(bytes)
                {
                    debug!(
                        "rift fault {}: write failed, degraded to empty close: {e}",
                        kind.canonical_name()
                    );
                }
            }
        }
        io::Error::other(InjectedFault(kind))
    }
}

impl AsyncRead for FaultIo {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        Pin::new(&mut self.inner).poll_read(cx, buf)
    }
}

impl AsyncWrite for FaultIo {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        if let Some(kind) = self.fault.take() {
            return Poll::Ready(Err(self.trip(kind)));
        }
        Pin::new(&mut self.inner).poll_write(cx, buf)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.inner).poll_flush(cx)
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let this = &mut *self;
        if matches!(this.linger, Linger::NotStarted) {
            if !this.fault.linger_armed() {
                return Pin::new(&mut this.inner).poll_shutdown(cx);
            }
            this.linger = Linger::ShuttingWrite;
        }
        loop {
            match &mut this.linger {
                Linger::NotStarted | Linger::ShuttingWrite => {
                    ready!(Pin::new(&mut this.inner).poll_shutdown(cx))?;
                    fire(&this.fault.0.probe, Point::LingerFinSent);
                    this.linger = Linger::Draining(Box::new(Drain::new()));
                }
                Linger::Draining(drain) => {
                    ready!(drain.poll(&mut this.inner, cx));
                    let discarded = drain.discarded;
                    fire(&this.fault.0.probe, Point::LingerDrained { discarded });
                    this.linger = Linger::Done;
                }
                Linger::Done => return Poll::Ready(Ok(())),
            }
        }
    }
}

/// The payload faults' layer above TLS (issue #1600): on an https imposter, random data and a
/// malformed chunk are written *through* the TLS stream, so the client completes the handshake,
/// decrypts the bytes and fails to parse HTTP — as with Mountebank, which writes them on the
/// `TLSSocket`. Written beneath TLS, they reached the client as a non-record and it reported a TLS
/// error instead.
///
/// Reset and empty close stay beneath TLS, in the raw-socket [`FaultIo`] that shares this
/// [`FaultCell`]: a reset needs the socket's `SO_LINGER`, and [`FaultCell::take_payload`] leaves
/// those kinds armed for it. So on a write the order is: hyper, then this layer (takes a payload
/// kind or passes through), then rustls, then `FaultIo` (takes reset/empty or passes through),
/// then the socket.
///
/// After writing the payload it flushes, so rustls emits the records, and returns the
/// [`InjectedFault`] error hyper aborts on. It sends no `close_notify`, as Mountebank's
/// `socket.destroy()` sends none: once tripped, flush and shutdown fail with the same error rather
/// than reaching the TLS stream's shutdown.
#[derive(Debug)]
pub(crate) struct TlsPayloadFault<S> {
    inner: S,
    fault: FaultCell,
    trip: Option<Trip>,
}

/// Where a taken payload fault has got to.
#[derive(Debug)]
enum Trip {
    /// The payload bytes not yet accepted by the TLS stream.
    Writing {
        kind: TcpFaultKind,
        rest: &'static [u8],
    },
    /// All bytes accepted; flushing so rustls writes the records to the socket.
    Flushing(TcpFaultKind),
    /// The payload is out (or its write failed): every further call aborts.
    Tripped(TcpFaultKind),
}

impl Trip {
    /// Drive the payload out, then yield the abort error. A write or flush error degrades the
    /// fault to an empty close: the connection still aborts, so it is logged, not returned.
    fn poll<S: AsyncWrite + Unpin>(
        &mut self,
        inner: &mut S,
        cx: &mut Context<'_>,
    ) -> Poll<io::Error> {
        loop {
            match self {
                Self::Writing { kind, rest } => {
                    let (kind, bytes) = (*kind, *rest);
                    match ready!(Pin::new(&mut *inner).poll_write(cx, bytes)) {
                        Ok(0) => {
                            debug!(
                                "rift fault {}: TLS write accepted no bytes, degraded to empty close",
                                kind.canonical_name()
                            );
                            *self = Self::Tripped(kind);
                        }
                        Ok(n) if n >= bytes.len() => *self = Self::Flushing(kind),
                        Ok(n) => *rest = &bytes[n..],
                        Err(e) => {
                            debug!(
                                "rift fault {}: TLS write failed, degraded to empty close: {e}",
                                kind.canonical_name()
                            );
                            *self = Self::Tripped(kind);
                        }
                    }
                }
                Self::Flushing(kind) => {
                    let kind = *kind;
                    if let Err(e) = ready!(Pin::new(&mut *inner).poll_flush(cx)) {
                        debug!(
                            "rift fault {}: TLS flush failed, payload may be cut short: {e}",
                            kind.canonical_name()
                        );
                    }
                    *self = Self::Tripped(kind);
                }
                Self::Tripped(kind) => return Poll::Ready(io::Error::other(InjectedFault(*kind))),
            }
        }
    }
}

impl<S> TlsPayloadFault<S> {
    /// Wrap the TLS stream of a connection whose raw socket is in a [`FaultIo`] sharing `fault`.
    pub(crate) fn new(inner: S, fault: FaultCell) -> Self {
        Self {
            inner,
            fault,
            trip: None,
        }
    }
}

impl<S: AsyncWrite + Unpin> TlsPayloadFault<S> {
    /// On a write: take an armed payload fault, if any, and drive it. `None` means pass through.
    fn poll_fault_on_write(&mut self, cx: &mut Context<'_>) -> Option<Poll<io::Error>> {
        if self.trip.is_none() {
            let (kind, rest) = self.fault.take_payload()?;
            self.trip = Some(Trip::Writing { kind, rest });
        }
        self.poll_trip(cx)
    }

    /// Drive a payload fault already taken; `None` when there is none.
    fn poll_trip(&mut self, cx: &mut Context<'_>) -> Option<Poll<io::Error>> {
        let trip = self.trip.as_mut()?;
        Some(trip.poll(&mut self.inner, cx))
    }
}

impl<S: AsyncRead + Unpin> AsyncRead for TlsPayloadFault<S> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        Pin::new(&mut self.inner).poll_read(cx, buf)
    }
}

impl<S: AsyncWrite + Unpin> AsyncWrite for TlsPayloadFault<S> {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        let this = &mut *self;
        if let Some(poll) = this.poll_fault_on_write(cx) {
            return poll.map(Err);
        }
        Pin::new(&mut this.inner).poll_write(cx, buf)
    }

    fn poll_write_vectored(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        bufs: &[io::IoSlice<'_>],
    ) -> Poll<io::Result<usize>> {
        let this = &mut *self;
        if let Some(poll) = this.poll_fault_on_write(cx) {
            return poll.map(Err);
        }
        Pin::new(&mut this.inner).poll_write_vectored(cx, bufs)
    }

    fn is_write_vectored(&self) -> bool {
        self.inner.is_write_vectored()
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let this = &mut *self;
        if let Some(poll) = this.poll_trip(cx) {
            return poll.map(Err);
        }
        Pin::new(&mut this.inner).poll_flush(cx)
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let this = &mut *self;
        // Tripped: no `close_notify` (see the type's docs); the abort drops the connection.
        if let Some(poll) = this.poll_trip(cx) {
            return poll.map(Err);
        }
        Pin::new(&mut this.inner).poll_shutdown(cx)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bytes::Bytes;
    use http_body_util::Full;

    /// The table behind `SPELLINGS` and `parse`: every spelling parses to the kind beside it, every
    /// kind's canonical name is one of its spellings, and the lookup is case-sensitive.
    #[test]
    fn spellings_parse_to_their_kind() {
        for (spelling, kind) in TcpFaultKind::TABLE {
            assert_eq!(TcpFaultKind::parse(spelling), Some(kind), "{spelling}");
            assert!(TcpFaultKind::SPELLINGS.contains(&spelling));
            assert!(
                TcpFaultKind::SPELLINGS.contains(&kind.canonical_name()),
                "{kind:?}"
            );
        }
        assert!(
            TcpFaultKind::parse("RESET").is_none(),
            "spellings are case-sensitive"
        );
        assert!(TcpFaultKind::parse("").is_none());
    }

    #[test]
    fn parses_wiremock_names_and_aliases() {
        assert_eq!(
            TcpFaultKind::parse("CONNECTION_RESET_BY_PEER"),
            Some(TcpFaultKind::Reset)
        );
        assert_eq!(TcpFaultKind::parse("reset"), Some(TcpFaultKind::Reset));
        assert_eq!(
            TcpFaultKind::parse("EMPTY_RESPONSE"),
            Some(TcpFaultKind::Empty)
        );
        assert_eq!(TcpFaultKind::parse("empty"), Some(TcpFaultKind::Empty));
        assert_eq!(
            TcpFaultKind::parse("RANDOM_DATA_THEN_CLOSE"),
            Some(TcpFaultKind::RandomData)
        );
        assert_eq!(
            TcpFaultKind::parse("garbage"),
            Some(TcpFaultKind::RandomData)
        );
        assert_eq!(
            TcpFaultKind::parse("random"),
            Some(TcpFaultKind::RandomData)
        );
        assert_eq!(
            TcpFaultKind::parse("malformed"),
            Some(TcpFaultKind::MalformedChunk)
        );
        assert_eq!(
            TcpFaultKind::parse("MALFORMED_RESPONSE_CHUNK"),
            Some(TcpFaultKind::MalformedChunk)
        );
        assert_eq!(TcpFaultKind::parse("nonsense"), None);
    }

    /// The names the docs call canonical (`docs/features/fault-injection.md`,
    /// `docs/configuration/native.md`: "canonical name or short alias") — literal, so a rename of
    /// the wire vocabulary has to come here and be deliberate.
    #[test]
    fn canonical_name_returns_the_documented_wiremock_name() {
        assert_eq!(
            TcpFaultKind::Reset.canonical_name(),
            "CONNECTION_RESET_BY_PEER"
        );
        assert_eq!(TcpFaultKind::Empty.canonical_name(), "EMPTY_RESPONSE");
        assert_eq!(
            TcpFaultKind::RandomData.canonical_name(),
            "RANDOM_DATA_THEN_CLOSE"
        );
        assert_eq!(
            TcpFaultKind::MalformedChunk.canonical_name(),
            "MALFORMED_RESPONSE_CHUNK"
        );
    }

    /// Distinct names per kind: a classifier that collapsed two kinds onto one string would let an
    /// embedder render an empty-close as a reset while every individual assertion above still held.
    #[test]
    fn canonical_names_are_distinct_across_kinds() {
        let names = [
            TcpFaultKind::Reset.canonical_name(),
            TcpFaultKind::Empty.canonical_name(),
            TcpFaultKind::RandomData.canonical_name(),
            TcpFaultKind::MalformedChunk.canonical_name(),
        ];
        let unique: std::collections::BTreeSet<&str> = names.iter().copied().collect();
        assert_eq!(unique.len(), 4, "each kind needs its own name: {names:?}");
    }

    /// Every kind round-trips through the extension the serve loop itself reads.
    #[test]
    fn tcp_fault_carrier_reports_the_kind_in_the_extension() {
        for (kind, expected) in [
            (TcpFaultKind::Reset, "CONNECTION_RESET_BY_PEER"),
            (TcpFaultKind::Empty, "EMPTY_RESPONSE"),
            (TcpFaultKind::RandomData, "RANDOM_DATA_THEN_CLOSE"),
            (TcpFaultKind::MalformedChunk, "MALFORMED_RESPONSE_CHUNK"),
        ] {
            let mut response = Response::new(Full::new(Bytes::new()));
            response.extensions_mut().insert(kind);
            assert_eq!(tcp_fault_carrier(&response), Some(expected));
        }
    }

    #[test]
    fn tcp_fault_carrier_ignores_an_ordinary_response() {
        let response = Response::new(Full::new(Bytes::from_static(b"hello")));
        assert_eq!(tcp_fault_carrier(&response), None);
    }

    /// The false positive a header-based classifier hits today: `_rift.fault.error` stamps
    /// `x-rift-fault: error` and attaches no extension, so it is an ordinary HTTP response that
    /// the client really does receive — never a carrier.
    #[test]
    fn tcp_fault_carrier_ignores_the_error_fault_marker_header() {
        let mut response = Response::new(Full::new(Bytes::new()));
        response.headers_mut().insert(
            "x-rift-fault",
            hyper::header::HeaderValue::from_static("error"),
        );
        assert_eq!(tcp_fault_carrier(&response), None);
    }

    /// An outer error whose `source()` is the given `io::Error` — the shape hyper's connection
    /// error takes around the `io::Error` `FaultIo` returns.
    #[derive(Debug)]
    struct Outer(io::Error);

    impl std::fmt::Display for Outer {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("connection error")
        }
    }

    impl std::error::Error for Outer {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            Some(&self.0)
        }
    }

    /// Issue #1234: the marker is found through an `io::Error` nested in an outer error.
    #[test]
    fn is_injected_fault_sees_through_a_wrapped_io_error() {
        let err = Outer(io::Error::other(InjectedFault(TcpFaultKind::Reset)));
        assert!(is_injected_fault(&err));
        // Directly, and as the bare io::Error too.
        assert!(is_injected_fault(&InjectedFault(TcpFaultKind::Empty)));
        assert!(is_injected_fault(&io::Error::other(InjectedFault(
            TcpFaultKind::MalformedChunk
        ))));
    }

    /// The trap the implementation avoids: `io::Error::source()` skips its own inner error, so a
    /// plain `source()` walk never reaches the marker. Pinned so a "simplification" to that walk
    /// fails here rather than silently re-logging every injected fault as a server error.
    #[test]
    fn a_naive_source_walk_misses_the_marker() {
        fn naive(err: &(dyn std::error::Error + 'static)) -> bool {
            let mut current = Some(err);
            while let Some(e) = current {
                if e.is::<InjectedFault>() {
                    return true;
                }
                current = e.source();
            }
            false
        }
        let err = Outer(io::Error::other(InjectedFault(TcpFaultKind::Reset)));
        assert!(!naive(&err), "the naive walk steps over the marker");
        assert!(is_injected_fault(&err));
    }

    #[test]
    fn is_injected_fault_rejects_an_ordinary_io_error() {
        let reset = io::Error::from(io::ErrorKind::ConnectionReset);
        assert!(!is_injected_fault(&reset));
        assert!(!is_injected_fault(&Outer(reset)));
        assert!(!is_injected_fault(&Outer(io::Error::other("boom"))));
    }

    /// Armed once, fires once; clones share the slot (the listener keeps one, `FaultIo` the other).
    #[test]
    fn fault_cell_is_shared_and_taken_once() {
        let cell = FaultCell::new();
        let other = cell.clone();
        assert_eq!(other.take(), None);
        cell.arm(TcpFaultKind::RandomData);
        assert_eq!(other.take(), Some(TcpFaultKind::RandomData));
        assert_eq!(cell.take(), None);
    }

    /// Issue #1600: the layer above TLS takes only the payload kinds; a reset or empty close stays
    /// armed for the raw-socket `FaultIo` beneath TLS.
    #[test]
    fn take_payload_takes_only_the_payload_kinds() {
        let cell = FaultCell::new();
        assert_eq!(cell.take_payload(), None, "nothing armed");
        for kind in [TcpFaultKind::Reset, TcpFaultKind::Empty] {
            cell.arm(kind);
            assert_eq!(cell.take_payload(), None, "{kind:?} is not a payload");
            assert_eq!(cell.take(), Some(kind), "{kind:?} stays armed for FaultIo");
        }
        for kind in [TcpFaultKind::RandomData, TcpFaultKind::MalformedChunk] {
            cell.arm(kind);
            let (taken, bytes) = cell.take_payload().expect("a payload kind is taken");
            assert_eq!(taken, kind);
            assert_eq!(Some(bytes), payload(kind));
            assert!(!bytes.is_empty());
            assert_eq!(cell.take(), None, "{kind:?} fires once");
        }
    }

    /// The layer writes the payload through the inner stream, flushes, then aborts with the
    /// injected-fault error; later flush and shutdown abort too, so no `close_notify` follows.
    #[tokio::test]
    async fn tls_payload_fault_writes_the_payload_then_aborts() {
        use tokio::io::AsyncWriteExt;
        let cell = FaultCell::new();
        let (inner, mut peer) = tokio::io::duplex(4);
        let mut io = TlsPayloadFault::new(inner, cell.clone());

        io.write_all(b"ok")
            .await
            .expect("unarmed writes pass through");
        cell.arm(TcpFaultKind::RandomData);
        let reader = tokio::spawn(async move {
            use tokio::io::AsyncReadExt;
            let mut got = Vec::new();
            peer.read_to_end(&mut got).await.expect("read");
            got
        });
        // The duplex buffer is smaller than the payload, so the write is driven across several
        // polls.
        let err = io
            .write(b"response")
            .await
            .expect_err("an armed write aborts");
        assert!(is_injected_fault(&err), "{err}");
        assert!(is_injected_fault(&io.flush().await.expect_err("tripped")));
        assert!(is_injected_fault(
            &io.shutdown().await.expect_err("tripped")
        ));
        drop(io);
        let mut expected = b"ok".to_vec();
        expected.extend_from_slice(payload(TcpFaultKind::RandomData).expect("a payload kind"));
        assert_eq!(reader.await.expect("task"), expected);
    }

    /// A reset armed on the cell passes straight through the layer, for `FaultIo` to take.
    #[tokio::test]
    async fn tls_payload_fault_passes_a_reset_through() {
        use tokio::io::AsyncWriteExt;
        let cell = FaultCell::new();
        let (inner, _peer) = tokio::io::duplex(64);
        let mut io = TlsPayloadFault::new(inner, cell.clone());
        cell.arm(TcpFaultKind::Reset);
        assert_eq!(io.write(b"response").await.expect("passes through"), 8);
        assert_eq!(cell.take(), Some(TcpFaultKind::Reset));
    }

    async fn connected_pair() -> (TcpStream, TcpStream) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind");
        let client = TcpStream::connect(listener.local_addr().expect("addr"))
            .await
            .expect("connect");
        let (server, _) = listener.accept().await.expect("accept");
        (server, client)
    }

    #[test]
    fn linger_is_armed_through_any_clone_and_only_for_http1() {
        let mut response = Response::new(());
        response.extensions_mut().insert(LingerOnClose);
        let h2 = FaultCell::new();
        arm_linger_if_requested(&response, Version::HTTP_2, &h2);
        assert!(!h2.linger_armed(), "HTTP/2 has no close to linger on");

        let cell = FaultCell::new();
        arm_linger_if_requested(&Response::new(()), Version::HTTP_11, &cell);
        assert!(!cell.linger_armed(), "only a response that asks arms it");
        arm_linger_if_requested(&response, Version::HTTP_11, &cell.clone());
        assert!(cell.linger_armed());
    }

    /// Issue #1460: an armed shutdown sends the FIN first, then discards what the peer sends until
    /// it closes, so nothing is left unread to turn the close into a RST.
    #[tokio::test]
    async fn an_armed_shutdown_sends_fin_then_drains_to_eof() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let (server, mut client) = connected_pair().await;
        let cell = FaultCell::new();
        cell.arm_linger();
        let mut io = FaultIo::new(server, cell);
        let shutdown = tokio::spawn(async move { io.shutdown().await });

        let mut sink = [0u8; 1];
        assert_eq!(
            client.read(&mut sink).await.expect("read"),
            0,
            "the FIN comes before the drain"
        );
        client
            .write_all(&[b'x'; 256 * 1024])
            .await
            .expect("drained");
        client.shutdown().await.expect("client FIN");
        let result = tokio::time::timeout(Duration::from_secs(1), shutdown)
            .await
            .expect("EOF ends the drain at once")
            .expect("task");
        assert!(result.is_ok());
    }

    /// The drain is bounded by its idle timer when the peer goes quiet without closing.
    #[tokio::test(start_paused = true)]
    async fn an_armed_shutdown_stops_draining_a_silent_peer() {
        use tokio::io::AsyncWriteExt;
        let (server, _client) = connected_pair().await;
        let cell = FaultCell::new();
        cell.arm_linger();
        let mut io = FaultIo::new(server, cell);
        let started = Instant::now();
        io.shutdown().await.expect("shutdown");
        assert!(started.elapsed() >= LINGER_IDLE);
        assert!(started.elapsed() < LINGER_DEADLINE);
    }

    /// Unarmed, shutdown is the plain socket shutdown: it never waits on the peer.
    #[tokio::test(start_paused = true)]
    async fn an_unarmed_shutdown_does_not_wait_for_the_peer() {
        use tokio::io::AsyncWriteExt;
        let (server, _client) = connected_pair().await;
        let mut io = FaultIo::new(server, FaultCell::new());
        let started = Instant::now();
        io.shutdown().await.expect("shutdown");
        assert_eq!(started.elapsed(), Duration::ZERO);
    }

    /// Body-agnostic: an embedder classifies whatever body type it is holding, so classification
    /// never has to happen before a body transformation.
    #[test]
    fn tcp_fault_carrier_is_generic_over_the_body() {
        let mut response: Response<()> = Response::new(());
        response.extensions_mut().insert(TcpFaultKind::Empty);
        assert_eq!(tcp_fault_carrier(&response), Some("EMPTY_RESPONSE"));
    }
}