use std::collections::{HashMap, VecDeque};
use std::fmt;
use std::pin::{Pin, pin};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, Weak};
use std::time::{Duration, Instant};
use bytes::{Bytes, BytesMut};
use tokio::sync::{Notify, oneshot};
use weida_core::{Error, Limits, LossCause, PeerIdentity, TraceContext};
use weida_protocol::{
FlowHeader, FrameKind, LOCAL_MAX_DATAGRAM, codes, decode_varint, encode_frame, encode_varint,
flow_prefix, split_flow_datagram, varint,
};
use crate::PathStats;
use crate::conn::{ConnHandle, Wanted, refusal_for, violation};
use crate::listener::Route;
use crate::stream::{Incoming, PeerShared};
use crate::transport::{RecvHalf, SendHalf};
#[derive(Clone, Debug, Default)]
pub struct FlowMeta {
content_type: Option<String>,
trace: Option<TraceContext>,
topic: Option<String>,
}
impl FlowMeta {
pub fn with_content_type(mut self, content_type: impl Into<String>) -> FlowMeta {
self.content_type = Some(content_type.into());
self
}
pub fn with_trace(mut self, trace: TraceContext) -> FlowMeta {
self.trace = Some(trace);
self
}
pub fn with_topic(mut self, topic: impl Into<String>) -> FlowMeta {
self.topic = Some(topic.into());
self
}
}
#[derive(Clone, Debug)]
pub struct FlowInfo {
pub endpoint: String,
pub topic: Option<String>,
pub content_type: Option<String>,
pub trace: Option<TraceContext>,
pub peer: Option<PeerIdentity>,
pub peer_chain: Option<crate::PeerChain>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct FlowStats {
pub sent: u64,
pub too_large: u64,
pub discarded: u64,
pub not_live: u64,
pub received: u64,
pub overflow: u64,
}
#[derive(Default)]
struct Counters {
sent: AtomicU64,
too_large: AtomicU64,
discarded: AtomicU64,
not_live: AtomicU64,
received: AtomicU64,
overflow: AtomicU64,
}
impl Counters {
fn add(counter: &AtomicU64, n: u64) {
if n > 0 {
counter.fetch_add(n, Ordering::Relaxed);
}
}
fn snapshot(&self) -> FlowStats {
FlowStats {
sent: self.sent.load(Ordering::Relaxed),
too_large: self.too_large.load(Ordering::Relaxed),
discarded: self.discarded.load(Ordering::Relaxed),
not_live: self.not_live.load(Ordering::Relaxed),
received: self.received.load(Ordering::Relaxed),
overflow: self.overflow.load(Ordering::Relaxed),
}
}
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
const ENTRY_OVERHEAD: usize = std::mem::size_of::<Bytes>();
struct Ring {
items: VecDeque<Bytes>,
bytes: usize,
cap: usize,
}
impl Ring {
fn new(cap: usize) -> Ring {
Ring {
items: VecDeque::new(),
bytes: 0,
cap,
}
}
fn push(&mut self, datagram: Bytes) -> u64 {
let cost = datagram.len() + ENTRY_OVERHEAD;
if cost > self.cap {
return 1;
}
let mut dropped = 0;
while self.bytes + cost > self.cap {
let Some(old) = self.items.pop_front() else {
break;
};
self.bytes -= old.len() + ENTRY_OVERHEAD;
dropped += 1;
}
self.bytes += cost;
self.items.push_back(datagram);
dropped
}
fn pop(&mut self) -> Option<Bytes> {
let datagram = self.items.pop_front()?;
self.bytes -= datagram.len() + ENTRY_OVERHEAD;
Some(datagram)
}
}
const EARLY_OVERHEAD: usize = std::mem::size_of::<(Instant, u64, Bytes)>();
struct EarlyRing {
items: VecDeque<(Instant, u64, Bytes)>,
bytes: usize,
cap: usize,
hold: Duration,
}
impl EarlyRing {
fn new(cap: usize, hold: Duration) -> EarlyRing {
EarlyRing {
items: VecDeque::new(),
bytes: 0,
cap,
hold,
}
}
fn pop_front(&mut self) {
if let Some((_, _, old)) = self.items.pop_front() {
self.bytes -= old.len() + EARLY_OVERHEAD;
}
}
fn evict(&mut self, now: Instant) -> u64 {
let mut evicted = 0;
while let Some((at, _, _)) = self.items.front() {
if now.saturating_duration_since(*at) <= self.hold {
break;
}
self.pop_front();
evicted += 1;
}
evicted
}
fn push(&mut self, now: Instant, id: u64, datagram: Bytes) -> u64 {
let mut dropped = self.evict(now);
let cost = datagram.len() + EARLY_OVERHEAD;
if cost > self.cap {
return dropped + 1;
}
while self.bytes + cost > self.cap && !self.items.is_empty() {
self.pop_front();
dropped += 1;
}
self.bytes += cost;
self.items.push_back((now, id, datagram));
dropped
}
fn adopt(&mut self, now: Instant, id: u64) -> (Vec<Bytes>, u64) {
let evicted = self.evict(now);
let mut adopted = Vec::new();
let mut kept = VecDeque::with_capacity(self.items.len());
for (at, owner, datagram) in self.items.drain(..) {
if owner == id {
self.bytes -= datagram.len() + EARLY_OVERHEAD;
adopted.push(datagram);
} else {
kept.push_back((at, owner, datagram));
}
}
self.items = kept;
(adopted, evicted)
}
}
struct Inbound {
ring: Mutex<Ring>,
ready: Notify,
ended: AtomicBool,
stop: Mutex<Option<u64>>,
stop_signal: Notify,
counters: Counters,
}
impl Inbound {
fn new(cap: usize) -> Inbound {
Inbound {
ring: Mutex::new(Ring::new(cap)),
ready: Notify::new(),
ended: AtomicBool::new(false),
stop: Mutex::new(None),
stop_signal: Notify::new(),
counters: Counters::default(),
}
}
fn push(&self, datagram: Bytes) {
let dropped = lock(&self.ring).push(datagram);
Counters::add(&self.counters.received, 1);
Counters::add(&self.counters.overflow, dropped);
self.ready.notify_waiters();
}
fn end(&self) {
self.ended.store(true, Ordering::Release);
self.ready.notify_waiters();
}
fn request_stop(&self, code: u64) {
let mut stop = lock(&self.stop);
if stop.is_none() {
*stop = Some(code);
drop(stop);
self.stop_signal.notify_waiters();
}
}
async fn stop_requested(&self) -> u64 {
loop {
let mut notified = pin!(self.stop_signal.notified());
notified.as_mut().enable();
if let Some(code) = *lock(&self.stop) {
return code;
}
notified.await;
}
}
}
#[derive(Clone, Copy, Debug)]
enum End {
Stopped(u64),
Lost(LossCause),
NotConnected,
}
impl End {
fn from_error(error: &Error) -> End {
match error {
Error::Rejected => End::Stopped(codes::REJECTED),
Error::UnknownEndpoint => End::Stopped(codes::UNKNOWN_ENDPOINT),
Error::Unsupported => End::Stopped(codes::UNSUPPORTED),
Error::LimitExceeded => End::Stopped(codes::LIMIT_EXCEEDED),
Error::Canceled => End::Stopped(codes::CANCELED),
Error::ConnectionLost(cause) => End::Lost(*cause),
Error::NotConnected => End::NotConnected,
_ => End::Lost(LossCause::TransportError),
}
}
fn to_error(self) -> Error {
match self {
End::Stopped(code) => codes::stop_reason(code).into(),
End::Lost(cause) => Error::ConnectionLost(cause),
End::NotConnected => Error::NotConnected,
}
}
}
pub(crate) struct FlowTable {
next_id: AtomicU64,
inbound: Mutex<HashMap<u64, Arc<Inbound>>>,
early: Mutex<EarlyRing>,
unknown: AtomicU64,
limits: Limits,
}
enum Refused {
Full,
Duplicate,
}
impl FlowTable {
pub(crate) fn new(limits: &Limits) -> FlowTable {
FlowTable {
next_id: AtomicU64::new(0),
inbound: Mutex::new(HashMap::new()),
early: Mutex::new(EarlyRing::new(
limits.flow_early_bytes,
limits.flow_early_hold,
)),
unknown: AtomicU64::new(0),
limits: *limits,
}
}
fn count_unknown(&self, n: u64) {
if n > 0 {
let total = self.unknown.fetch_add(n, Ordering::Relaxed) + n;
tracing::trace!(total, "datagrams for no live flow dropped");
}
}
fn deliver(&self, datagram: Bytes) {
let Some((id, offset)) = split_flow_datagram(&datagram) else {
self.count_unknown(1);
return;
};
let payload = datagram.slice(offset..);
let inbound = lock(&self.inbound);
if let Some(flow) = inbound.get(&id) {
let flow = Arc::clone(flow);
drop(inbound);
flow.push(payload);
return;
}
let dropped = lock(&self.early).push(Instant::now(), id, payload);
drop(inbound);
self.count_unknown(dropped);
}
fn register(&self, id: u64) -> Result<Arc<Inbound>, Refused> {
let mut inbound = lock(&self.inbound);
if inbound.contains_key(&id) {
return Err(Refused::Duplicate);
}
if inbound.len() >= self.limits.max_flows {
return Err(Refused::Full);
}
let flow = Arc::new(Inbound::new(self.limits.flow_queue_bytes));
let (early, evicted) = lock(&self.early).adopt(Instant::now(), id);
for datagram in early {
flow.push(datagram);
}
inbound.insert(id, Arc::clone(&flow));
drop(inbound);
self.count_unknown(evicted);
Ok(flow)
}
fn remove(&self, id: u64, flow: &Arc<Inbound>) {
let mut inbound = lock(&self.inbound);
if inbound.get(&id).is_some_and(|live| Arc::ptr_eq(live, flow)) {
inbound.remove(&id);
}
}
}
pub struct Flow {
binding: Arc<Mutex<Option<Binding>>>,
counters: Arc<Counters>,
redial: Option<Arc<Redial>>,
}
struct Redial {
peer: Arc<PeerShared>,
meta: FlowMeta,
running: AtomicBool,
failed: OnceLock<End>,
}
async fn reregister(slot: Weak<Mutex<Option<Binding>>>, redial: Arc<Redial>) {
let bound = async {
let (conn, path) = redial.peer.pick().await?;
bind(&conn, &path, &redial.meta).await
}
.await;
match bound {
Ok(binding) => {
if let Some(slot) = slot.upgrade() {
*lock(&slot) = Some(binding);
}
}
Err(e) => {
let _ = redial.failed.set(End::from_error(&e));
}
}
redial.running.store(false, Ordering::Release);
}
struct Binding {
conn: ConnHandle,
prefix: ([u8; varint::MAX_ENCODED_LEN], usize),
end: Arc<OnceLock<End>>,
carrier: Carrier,
_done: oneshot::Sender<()>,
}
enum Carrier {
Quic(SendHalf),
Local(Arc<SendRing>),
}
#[derive(Clone, Copy)]
enum Close {
Finish,
Abort,
}
enum Next {
Datagram(Bytes),
Close(Close),
}
struct SendRing {
state: Mutex<(Ring, Option<Close>)>,
ready: Notify,
}
impl SendRing {
fn push(&self, datagram: Bytes) -> u64 {
let dropped = lock(&self.state).0.push(datagram);
self.ready.notify_one();
dropped
}
fn close(&self, close: Close) {
let mut state = lock(&self.state);
if !matches!(state.1, Some(Close::Abort)) {
state.1 = Some(close);
}
drop(state);
self.ready.notify_one();
}
async fn next(&self) -> Next {
loop {
let notified = self.ready.notified();
{
let mut state = lock(&self.state);
if let Some(Close::Abort) = state.1 {
return Next::Close(Close::Abort);
}
if let Some(datagram) = state.0.pop() {
return Next::Datagram(datagram);
}
if let Some(close) = state.1 {
return Next::Close(close);
}
}
notified.await;
}
}
}
async fn local_writer(mut send: SendHalf, ring: Arc<SendRing>, end: Arc<OnceLock<End>>) {
let mut record = Vec::with_capacity(varint::MAX_ENCODED_LEN + LOCAL_MAX_DATAGRAM);
loop {
match ring.next().await {
Next::Datagram(datagram) => {
record.clear();
encode_varint(datagram.len() as u64, &mut record)
.expect("a local datagram is at most 1200 bytes");
record.extend_from_slice(&datagram);
if let Err(e) = send.write_all(&record).await {
let _ = end.set(End::from_error(&e));
return;
}
}
Next::Close(Close::Finish) => {
let _ = send.finish();
return;
}
Next::Close(Close::Abort) => {
send.reset(codes::CANCELED);
return;
}
}
}
}
type Stopped = Pin<Box<dyn Future<Output = Result<Option<u64>, Error>> + Send + Sync>>;
async fn watch(
conn: ConnHandle,
stopped: Stopped,
end: Arc<OnceLock<End>>,
mut done: oneshot::Receiver<()>,
) {
let first = tokio::select! {
_ = &mut done => return,
receipt = stopped => match receipt {
Ok(Some(code)) => Some(End::Stopped(code)),
_ => None,
},
reason = conn.conn.closed() => Some(End::from_error(&reason)),
};
let ended = match first {
Some(ended) => ended,
None => tokio::select! {
_ = &mut done => return,
reason = conn.conn.closed() => End::from_error(&reason),
},
};
let _ = end.set(ended);
}
pub(crate) async fn open_flow_on(
conn: &ConnHandle,
path: &str,
meta: &FlowMeta,
) -> Result<Flow, Error> {
let binding = bind(conn, path, meta).await?;
Ok(Flow {
binding: Arc::new(Mutex::new(Some(binding))),
counters: Arc::new(Counters::default()),
redial: None,
})
}
pub(crate) async fn open_flow_via(peer: &Arc<PeerShared>, meta: FlowMeta) -> Result<Flow, Error> {
let (conn, path) = peer.pick().await?;
let binding = bind(&conn, &path, &meta).await?;
Ok(Flow {
binding: Arc::new(Mutex::new(Some(binding))),
counters: Arc::new(Counters::default()),
redial: Some(Arc::new(Redial {
peer: Arc::clone(peer),
meta,
running: AtomicBool::new(false),
failed: OnceLock::new(),
})),
})
}
async fn bind(conn: &ConnHandle, path: &str, meta: &FlowMeta) -> Result<Binding, Error> {
if !conn.negotiated().await?.datagrams {
return Err(Error::DatagramsUnavailable);
}
let id = conn.flows.next_id.fetch_add(1, Ordering::Relaxed);
let header = FlowHeader {
content_type: meta.content_type.clone(),
traceparent: meta.trace.map(|t| t.to_traceparent()),
tracestate: None,
topic: meta.topic.clone(),
..FlowHeader::new(path, id)
};
let mut send = conn.open_uni().await?;
send.write_all(&encode_frame(FrameKind::Flow, &header.encode()))
.await?;
let end = Arc::new(OnceLock::new());
let (done_tx, done_rx) = oneshot::channel();
conn.exec.spawn(watch(
ConnHandle::clone(conn),
send.stopped(),
Arc::clone(&end),
done_rx,
));
let carrier = if conn.conn.is_quic() {
Carrier::Quic(send)
} else {
let ring = Arc::new(SendRing {
state: Mutex::new((Ring::new(conn.limits.datagram_send_bytes), None)),
ready: Notify::new(),
});
conn.exec
.spawn(local_writer(send, Arc::clone(&ring), Arc::clone(&end)));
Carrier::Local(ring)
};
Ok(Binding {
conn: ConnHandle::clone(conn),
prefix: flow_prefix(id),
end,
carrier,
_done: done_tx,
})
}
impl Binding {
fn max_payload(&self) -> Option<usize> {
match self.carrier {
Carrier::Quic(_) => self
.conn
.conn
.max_datagram_size()
.map(|max| max.saturating_sub(self.prefix.1)),
Carrier::Local(_) => Some(LOCAL_MAX_DATAGRAM),
}
}
fn close(mut self, how: Close) {
if let Close::Abort = how {
match &mut self.carrier {
Carrier::Quic(send) => send.reset(codes::CANCELED),
Carrier::Local(ring) => ring.close(Close::Abort),
}
}
}
}
impl Drop for Carrier {
fn drop(&mut self) {
match self {
Carrier::Quic(send) => {
let _ = send.finish();
}
Carrier::Local(ring) => ring.close(Close::Finish),
}
}
}
impl Flow {
pub fn send(&self, payload: impl Into<Bytes>) -> Result<(), Error> {
let payload = payload.into();
let mut binding = lock(&self.binding);
if let Some(redial) = &self.redial {
if let Some(end) = redial.failed.get() {
return Err(end.to_error());
}
let live = binding
.as_ref()
.is_some_and(|b| b.conn.conn.close_reason().is_none());
if !live {
binding.take();
drop(binding);
Counters::add(&self.counters.not_live, 1);
if !redial.running.swap(true, Ordering::AcqRel) {
redial.peer.exec().spawn(reregister(
Arc::downgrade(&self.binding),
Arc::clone(redial),
));
}
return Ok(());
}
}
let Some(binding) = binding.as_ref() else {
return Err(Error::Canceled);
};
if let Some(end) = binding.end.get() {
return Err(end.to_error());
}
let Some(max) = binding.max_payload() else {
return Err(Error::DatagramsUnavailable);
};
if payload.len() > max {
Counters::add(&self.counters.too_large, 1);
return Err(Error::TooLarge { max });
}
match &binding.carrier {
Carrier::Quic(_) => {
let (prefix, len) = binding.prefix;
let mut datagram = BytesMut::with_capacity(len + payload.len());
datagram.extend_from_slice(&prefix[..len]);
datagram.extend_from_slice(&payload);
binding.conn.conn.send_datagram(datagram.freeze())?;
}
Carrier::Local(ring) => {
Counters::add(&self.counters.discarded, ring.push(payload));
}
}
Counters::add(&self.counters.sent, 1);
Ok(())
}
pub fn max_payload(&self) -> Option<usize> {
lock(&self.binding).as_ref()?.max_payload()
}
pub fn stats(&self) -> FlowStats {
self.counters.snapshot()
}
pub fn path_stats(&self) -> Option<PathStats> {
let path = lock(&self.binding)
.as_ref()?
.conn
.conn
.transport_stats()?
.path;
Some(path)
}
pub fn close(self) {
drop(self);
}
pub fn abort(self) {
if let Some(binding) = lock(&self.binding).take() {
binding.close(Close::Abort);
}
}
}
impl Drop for Flow {
fn drop(&mut self) {
if let Some(binding) = lock(&self.binding).take() {
binding.close(Close::Finish);
}
}
}
impl fmt::Debug for Flow {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Flow")
.field("stats", &self.stats())
.finish_non_exhaustive()
}
}
pub struct IncomingFlow {
info: FlowInfo,
inbound: Arc<Inbound>,
conn: ConnHandle,
}
impl IncomingFlow {
pub fn info(&self) -> &FlowInfo {
&self.info
}
pub async fn recv(&self) -> Option<Bytes> {
loop {
let mut notified = pin!(self.inbound.ready.notified());
notified.as_mut().enable();
if let Some(datagram) = self.try_recv() {
return Some(datagram);
}
if self.inbound.ended.load(Ordering::Acquire) {
return self.try_recv();
}
notified.await;
}
}
pub fn try_recv(&self) -> Option<Bytes> {
lock(&self.inbound.ring).pop()
}
pub fn stats(&self) -> FlowStats {
self.inbound.counters.snapshot()
}
pub fn path_stats(&self) -> Option<PathStats> {
self.conn.conn.transport_stats().map(|t| t.path)
}
pub fn refuse(self) {
self.inbound.request_stop(codes::REJECTED);
}
}
impl Drop for IncomingFlow {
fn drop(&mut self) {
self.inbound.request_stop(codes::CANCELED);
}
}
impl fmt::Debug for IncomingFlow {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("IncomingFlow")
.field("info", &self.info)
.field("stats", &self.stats())
.finish_non_exhaustive()
}
}
pub(crate) async fn datagram_reader(ctx: ConnHandle) {
while let Ok(datagram) = ctx.conn.read_datagram().await {
ctx.flows.deliver(datagram);
}
}
pub(crate) async fn handle_flow(
ctx: &ConnHandle,
mut stream: RecvHalf,
header: &[u8],
) -> Result<(), Error> {
if !ctx.negotiated().await?.datagrams {
return violation(ctx, "FLOW without the datagram capability");
}
let header = match FlowHeader::decode(header) {
Ok(header) => header,
Err(e) => return violation(ctx, &e.to_string()),
};
let route = ctx.namespace.lookup(&header.endpoint);
if let Some(refusal) = refusal_for(route.as_ref(), Wanted::Flow) {
tracing::debug!(
path = header.endpoint,
?refusal,
"the path does not serve a flow"
);
stream.stop(refusal.stop);
return Ok(());
}
let inbound = match ctx.flows.register(header.flow) {
Ok(inbound) => inbound,
Err(Refused::Full) => {
stream.stop(codes::LIMIT_EXCEEDED);
return Ok(());
}
Err(Refused::Duplicate) => return violation(ctx, "FLOW names a live flow id"),
};
let flow = IncomingFlow {
info: FlowInfo {
endpoint: header.endpoint.clone(),
topic: header.topic,
content_type: header.content_type,
trace: header
.traceparent
.as_deref()
.and_then(|v| TraceContext::parse_traceparent(v).ok()),
peer: ctx.peer.clone(),
peer_chain: ctx.peer_chain.clone(),
},
inbound: Arc::clone(&inbound),
conn: ConnHandle::clone(ctx),
};
match route {
Some(Route::Raw(queue)) => {
if queue.send(Incoming::Flow(flow)).await.is_err() {
tracing::debug!(
path = header.endpoint,
"acceptor went away while dispatching"
);
}
}
Some(Route::Dish(route)) => {
ctx.exec.spawn(crate::radio::pump_flow(route, flow));
}
_ => unreachable!("refusal_for serves a flow on a raw acceptor or a dish only"),
}
let outcome = run_stream(ctx, &mut stream, &inbound).await;
ctx.flows.remove(header.flow, &inbound);
inbound.end();
outcome
}
async fn run_stream(
ctx: &ConnHandle,
stream: &mut RecvHalf,
inbound: &Inbound,
) -> Result<(), Error> {
if ctx.conn.is_quic() {
let mut byte = [0u8; 1];
return tokio::select! {
read = stream.read(&mut byte) => match read {
Ok(Some(_)) => violation(ctx, "bytes after a FLOW header"),
Ok(None) | Err(_) => Ok(()),
},
code = inbound.stop_requested() => {
stream.stop(code);
Ok(())
}
};
}
let mut pending: Vec<u8> = Vec::new();
let mut scratch = vec![0u8; 4096];
loop {
while let Ok((len, used)) = decode_varint(&pending) {
if len > LOCAL_MAX_DATAGRAM as u64 {
return violation(ctx, "FLOW record longer than 1200 bytes");
}
let end = used + len as usize;
if pending.len() < end {
break;
}
inbound.push(Bytes::copy_from_slice(&pending[used..end]));
pending.drain(..end);
}
tokio::select! {
read = stream.read(&mut scratch) => match read {
Ok(Some(n)) => pending.extend_from_slice(&scratch[..n]),
Ok(None) if pending.is_empty() => return Ok(()),
Ok(None) => return violation(ctx, "FLOW record truncated at FIN"),
Err(_) => return Ok(()),
},
code = inbound.stop_requested() => {
stream.stop(code);
return Ok(());
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_unknown_id_allocates_nothing_beyond_the_early_ring() {
let limits = Limits {
flow_early_bytes: 4096,
flow_early_hold: Duration::from_millis(50),
..Limits::default()
};
let mut ring = EarlyRing::new(limits.flow_early_bytes, limits.flow_early_hold);
let start = Instant::now();
let mut dropped = 0;
for i in 0..1000u64 {
dropped += ring.push(start, i, Bytes::from(vec![0u8; 100]));
assert!(
ring.bytes <= limits.flow_early_bytes,
"{} bytes",
ring.bytes
);
}
assert_eq!(dropped + ring.items.len() as u64, 1000);
let later = start + Duration::from_millis(51);
let held = ring.items.len() as u64;
assert_eq!(ring.push(later, 0, Bytes::from_static(b"x")), held);
assert_eq!(ring.items.len(), 1);
}
#[test]
fn a_full_ring_drops_its_oldest() {
let mut ring = Ring::new(3 * (10 + ENTRY_OVERHEAD));
for i in 0..5u8 {
ring.push(Bytes::from(vec![i; 10]));
}
assert_eq!(ring.pop().unwrap()[0], 2);
assert_eq!(ring.pop().unwrap()[0], 3);
assert_eq!(ring.pop().unwrap()[0], 4);
assert!(ring.pop().is_none());
}
}