use super::{body::ExchangeBody, observed::ObservedBody};
use crate::telemetry::Metrics;
use axum::{
body::{Body, Bytes},
http::StatusCode,
};
use http_body::{Body as HttpBody, Frame};
use http_body_util::BodyExt;
use std::{
future::Future,
pin::Pin,
sync::Arc,
task::{Context, Poll},
time::Duration,
};
use tokio::{
sync::{Barrier, Semaphore, oneshot},
time::Instant,
};
struct GatedBody {
release: oneshot::Receiver<()>,
sent: bool,
}
impl HttpBody for GatedBody {
type Data = Bytes;
type Error = std::convert::Infallible;
fn poll_frame(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Bytes>, Self::Error>>> {
if self.sent {
return Poll::Ready(None);
}
match Pin::new(&mut self.release).poll(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(_) => {
self.sent = true;
Poll::Ready(Some(Ok(Frame::data(Bytes::from_static(b"done")))))
}
}
}
}
#[test]
fn cancellation_and_body_completion_conserve_ownership_across_threads() {
for threads in [2, 4] {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(threads)
.enable_all()
.build()
.unwrap()
.block_on(async {
for _ in 0..32 {
let metrics = Arc::new(Metrics::new());
let capacity = Arc::new(Semaphore::new(1));
let (release, released) = oneshot::channel();
let body = ExchangeBody::new(
Body::new(GatedBody {
release: released,
sent: false,
}),
capacity.clone().try_acquire_owned().unwrap(),
Instant::now() + Duration::from_secs(2),
);
let body = ObservedBody::new(body, metrics.begin(), StatusCode::OK);
let collection = tokio::spawn(async move { body.collect().await });
let gate = Arc::new(Barrier::new(2));
let sender_gate = gate.clone();
let sender = tokio::spawn(async move {
sender_gate.wait().await;
let _ = release.send(());
});
gate.wait().await;
collection.abort();
let _ = collection.await;
sender.await.unwrap();
assert_eq!(capacity.available_permits(), 1);
let counts = metrics.render();
assert!(counts.contains("servlet_exchanges_admitted_total 1\n"));
assert!(counts.contains("servlet_exchanges_finished_total 1\n"));
assert!(counts.contains("servlet_exchanges_active 0\n"));
assert!(counts.contains("outcome=\"failed\"} 0\n"));
assert!(counts.contains("outcome=\"timed_out\"} 0\n"));
}
});
}
}