use std::{
pin::Pin,
sync::Arc,
task::{Context, Poll},
time::Duration,
};
use axum::body::{Body, Bytes};
use http_body::{Body as HttpBody, Frame};
use http_body_util::BodyExt;
use tokio::{sync::Semaphore, time::Instant};
use super::ExchangeBody;
struct PendingBody;
impl HttpBody for PendingBody {
type Data = Bytes;
type Error = std::convert::Infallible;
fn poll_frame(
self: Pin<&mut Self>,
_: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Bytes>, Self::Error>>> {
Poll::Pending
}
}
#[tokio::test]
async fn capacity_is_held_until_body_completion_or_drop() {
let capacity = Arc::new(Semaphore::new(1));
let permit = capacity.clone().try_acquire_owned().unwrap();
let body = ExchangeBody::new(
Body::from("hello"),
permit,
Instant::now() + Duration::from_secs(1),
);
assert_eq!(capacity.available_permits(), 0);
assert_eq!(body.collect().await.unwrap().to_bytes(), "hello");
assert_eq!(capacity.available_permits(), 1);
let permit = capacity.clone().try_acquire_owned().unwrap();
let body = ExchangeBody::new(
Body::new(PendingBody),
permit,
Instant::now() + Duration::from_secs(1),
);
assert_eq!(capacity.available_permits(), 0);
drop(body);
assert_eq!(capacity.available_permits(), 1);
}
#[tokio::test(start_paused = true)]
async fn an_absolute_body_deadline_fails_the_stream_and_reclaims_capacity() {
let capacity = Arc::new(Semaphore::new(1));
let permit = capacity.clone().try_acquire_owned().unwrap();
let body = ExchangeBody::new(
Body::new(PendingBody),
permit,
Instant::now() + Duration::from_secs(1),
);
assert!(
body.collect()
.await
.unwrap_err()
.to_string()
.contains("deadline")
);
assert_eq!(capacity.available_permits(), 1);
}