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};
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;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum TcpFaultKind {
Reset,
Empty,
RandomData,
MalformedChunk,
}
impl TcpFaultKind {
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),
];
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
};
#[must_use]
pub(crate) fn parse(value: &str) -> Option<Self> {
Self::TABLE
.iter()
.find(|(spelling, _)| *spelling == value)
.map(|(_, kind)| *kind)
}
#[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",
}
}
}
#[must_use]
pub fn tcp_fault_carrier<B>(response: &Response<B>) -> Option<&'static str> {
response
.extensions()
.get::<TcpFaultKind>()
.map(|kind| kind.canonical_name())
}
#[derive(Clone, Debug, Default)]
pub struct FaultCell(Arc<CellState>);
#[derive(Default)]
struct CellState {
fault: Mutex<Option<TcpFaultKind>>,
linger: AtomicBool,
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 {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub(crate) fn probed(probe: ProbeHandle) -> Self {
Self(Arc::new(CellState {
probe,
..CellState::default()
}))
}
pub fn arm(&self, kind: TcpFaultKind) {
*self.0.fault.lock() = Some(kind);
fire(&self.0.probe, Point::FaultArmed { kind });
}
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)
}
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
}
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
}
}
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",
),
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LingerOnClose;
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();
}
}
#[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 {}
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))
}
}
#[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
}
#[derive(Debug)]
pub struct FaultIo {
inner: TcpStream,
fault: FaultCell,
linger: Linger,
}
enum Linger {
NotStarted,
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]),
}
}
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 {
#[must_use]
pub fn new(inner: TcpStream, fault: FaultCell) -> Self {
Self {
inner,
fault,
linger: Linger::NotStarted,
}
}
fn trip(&self, kind: TcpFaultKind) -> io::Error {
match kind {
TcpFaultKind::Reset => {
if let Err(e) = self.inner.set_zero_linger() {
debug!(
"rift fault reset: set_zero_linger failed, degraded to graceful close: {e}"
);
}
}
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(())),
}
}
}
}
#[derive(Debug)]
pub(crate) struct TlsPayloadFault<S> {
inner: S,
fault: FaultCell,
trip: Option<Trip>,
}
#[derive(Debug)]
enum Trip {
Writing {
kind: TcpFaultKind,
rest: &'static [u8],
},
Flushing(TcpFaultKind),
Tripped(TcpFaultKind),
}
impl Trip {
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> {
pub(crate) fn new(inner: S, fault: FaultCell) -> Self {
Self {
inner,
fault,
trip: None,
}
}
}
impl<S: AsyncWrite + Unpin> TlsPayloadFault<S> {
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)
}
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;
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;
#[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);
}
#[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"
);
}
#[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:?}");
}
#[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);
}
#[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);
}
#[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)
}
}
#[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));
assert!(is_injected_fault(&InjectedFault(TcpFaultKind::Empty)));
assert!(is_injected_fault(&io::Error::other(InjectedFault(
TcpFaultKind::MalformedChunk
))));
}
#[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"))));
}
#[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);
}
#[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");
}
}
#[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
});
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);
}
#[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());
}
#[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());
}
#[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);
}
#[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);
}
#[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"));
}
}