#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::collections::VecDeque;
use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::task::{Context, Poll};
use std::time::Duration;
use bytes::Bytes;
use futures::StreamExt;
use futures::future::BoxFuture;
use hyper::body::{Body, Frame, Incoming, SizeHint};
use parking_lot::Mutex;
use tokio::sync::Notify;
use tokio::time::Instant;
use crate::error::ModelError;
use crate::http::{BodyStream, HttpClient};
pub const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Debug, Clone)]
pub struct RecordedRequest {
pub method: String,
pub url: String,
pub path: String,
pub query: Option<String>,
pub headers: http::HeaderMap,
pub body: Bytes,
pub at: Instant,
}
impl RecordedRequest {
pub fn path_and_query(&self) -> String {
match &self.query {
Some(q) => format!("{}?{q}", self.path),
None => self.path.clone(),
}
}
pub fn header(&self, name: &str) -> String {
self.headers
.get(name)
.map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned())
.unwrap_or_default()
}
pub fn header_values(&self, name: &str) -> Vec<String> {
self.headers
.get_all(name)
.iter()
.map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned())
.collect()
}
pub fn json(&self) -> serde_json::Value {
serde_json::from_slice(&self.body).unwrap_or(serde_json::Value::Null)
}
pub fn is_stream(&self) -> bool {
self.json().get("stream") == Some(&serde_json::Value::Bool(true))
}
pub fn body_text(&self) -> String {
String::from_utf8_lossy(&self.body).into_owned()
}
fn from_parts(url: String, parts: &http::request::Parts, body: Bytes) -> Self {
Self {
method: parts.method.as_str().to_string(),
url,
path: parts.uri.path().to_string(),
query: parts.uri.query().map(str::to_string),
headers: parts.headers.clone(),
body,
at: Instant::now(),
}
}
}
#[derive(Debug, Clone)]
pub enum BodyStep {
Chunk(Bytes),
Delay(Duration),
Fail(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BodyEnd {
Finish,
Hang,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Respond,
Never,
Reset(String),
}
#[derive(Debug, Clone)]
pub struct FakeResponse {
pub status: u16,
pub headers: Vec<(String, String)>,
pub header_delay: Option<Duration>,
pub steps: Vec<BodyStep>,
pub end: BodyEnd,
pub outcome: Outcome,
}
impl FakeResponse {
pub fn new(status: u16) -> Self {
Self {
status,
headers: Vec::new(),
header_delay: None,
steps: Vec::new(),
end: BodyEnd::Finish,
outcome: Outcome::Respond,
}
}
pub fn json(body: impl Into<String>) -> Self {
Self::json_status(200, body)
}
pub fn json_status(status: u16, body: impl Into<String>) -> Self {
Self::new(status)
.header("Content-Type", "application/json")
.chunk(body.into())
}
pub fn sse(body: impl Into<String>) -> Self {
Self::new(200)
.header("Content-Type", "text/event-stream")
.chunk(body.into())
}
pub fn sse_chunks<I, S>(events: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
let mut resp = Self::new(200).header("Content-Type", "text/event-stream");
for ev in events {
resp = resp.chunk(ev.into());
}
resp
}
pub fn never() -> Self {
Self {
outcome: Outcome::Never,
..Self::new(200)
}
}
pub fn reset(message: impl Into<String>) -> Self {
Self {
outcome: Outcome::Reset(message.into()),
..Self::new(200)
}
}
pub fn status(mut self, status: u16) -> Self {
self.status = status;
self
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
pub fn chunk(mut self, data: impl Into<Bytes>) -> Self {
self.steps.push(BodyStep::Chunk(data.into()));
self
}
pub fn delay(mut self, d: Duration) -> Self {
self.steps.push(BodyStep::Delay(d));
self
}
pub fn fail(mut self, message: impl Into<String>) -> Self {
self.steps.push(BodyStep::Fail(message.into()));
self
}
pub fn delay_headers(mut self, d: Duration) -> Self {
self.header_delay = Some(d);
self
}
pub fn hang(mut self) -> Self {
self.end = BodyEnd::Hang;
self
}
pub fn body_bytes(&self) -> Bytes {
let mut out = Vec::new();
for step in &self.steps {
if let BodyStep::Chunk(b) = step {
out.extend_from_slice(b);
}
}
Bytes::from(out)
}
}
pub type Handler = Arc<dyn Fn(RecordedRequest) -> BoxFuture<'static, FakeResponse> + Send + Sync>;
fn sync_handler<F>(f: F) -> Handler
where
F: Fn(&RecordedRequest) -> FakeResponse + Send + Sync + 'static,
{
Arc::new(move |req: RecordedRequest| {
let resp = f(&req);
Box::pin(async move { resp }) as BoxFuture<'static, FakeResponse>
})
}
fn async_handler<F, Fut>(f: F) -> Handler
where
F: Fn(RecordedRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = FakeResponse> + Send + 'static,
{
Arc::new(move |req: RecordedRequest| Box::pin(f(req)) as BoxFuture<'static, FakeResponse>)
}
fn sequence_handler(responses: Vec<FakeResponse>) -> Handler {
assert!(
!responses.is_empty(),
"sequence needs at least one response"
);
let queue = Mutex::new(VecDeque::from(responses));
sync_handler(move |_| {
let mut q = queue.lock();
if q.len() > 1 {
q.pop_front().unwrap()
} else {
q.front().cloned().unwrap()
}
})
}
struct Shared {
handler: Handler,
requests: Mutex<Vec<RecordedRequest>>,
hits: AtomicUsize,
drops: AtomicUsize,
changed: Notify,
}
impl Shared {
fn new(handler: Handler) -> Arc<Self> {
Arc::new(Self {
handler,
requests: Mutex::new(Vec::new()),
hits: AtomicUsize::new(0),
drops: AtomicUsize::new(0),
changed: Notify::new(),
})
}
fn record(&self, req: RecordedRequest) {
self.requests.lock().push(req);
self.hits.fetch_add(1, Ordering::SeqCst);
self.changed.notify_waiters();
}
fn dropped(&self) {
self.drops.fetch_add(1, Ordering::SeqCst);
self.changed.notify_waiters();
}
fn requests(&self) -> Vec<RecordedRequest> {
self.requests.lock().clone()
}
fn hits(&self) -> usize {
self.hits.load(Ordering::SeqCst)
}
fn drops(&self) -> usize {
self.drops.load(Ordering::SeqCst)
}
async fn wait_until(&self, what: &str, cond: impl Fn(&Self) -> bool) {
let wait = async {
loop {
let notified = self.changed.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if cond(self) {
return;
}
notified.await;
}
};
if tokio::time::timeout(WAIT_TIMEOUT, wait).await.is_err() {
panic!(
"timed out after {WAIT_TIMEOUT:?} waiting for {what} (hits = {}, drops = {})",
self.hits(),
self.drops()
);
}
}
async fn respond(self: &Arc<Self>, req: RecordedRequest) -> Result<FakeResponse, String> {
let guard = DropGuard::new(self.clone());
let resp = (self.handler)(req).await;
match &resp.outcome {
Outcome::Respond => {}
Outcome::Never => std::future::pending::<()>().await,
Outcome::Reset(msg) => {
guard.disarm();
return Err(msg.clone());
}
}
if let Some(d) = resp.header_delay {
tokio::time::sleep(d).await;
}
guard.disarm();
Ok(resp)
}
}
struct DropGuard {
shared: Option<Arc<Shared>>,
}
impl DropGuard {
fn new(shared: Arc<Shared>) -> Self {
Self {
shared: Some(shared),
}
}
fn disarm(mut self) {
self.shared = None;
}
}
impl Drop for DropGuard {
fn drop(&mut self) {
if let Some(shared) = self.shared.take() {
shared.dropped();
}
}
}
struct ScriptedBody {
steps: VecDeque<BodyStep>,
end: BodyEnd,
sleep: Option<Pin<Box<tokio::time::Sleep>>>,
shared: Arc<Shared>,
finished: bool,
exact_len: Option<u64>,
}
impl ScriptedBody {
fn new(resp: &FakeResponse, shared: Arc<Shared>) -> Self {
let only_chunks = resp.end == BodyEnd::Finish
&& resp.steps.iter().all(|s| matches!(s, BodyStep::Chunk(_)));
Self {
steps: resp.steps.iter().cloned().collect(),
end: resp.end,
sleep: None,
shared,
finished: resp.end == BodyEnd::Finish && resp.steps.is_empty(),
exact_len: only_chunks.then(|| resp.body_bytes().len() as u64),
}
}
fn poll_chunk(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, String>>> {
loop {
if let Some(sleep) = self.sleep.as_mut() {
if sleep.as_mut().poll(cx).is_pending() {
return Poll::Pending;
}
self.sleep = None;
}
match self.steps.pop_front() {
Some(BodyStep::Chunk(b)) => {
if self.steps.is_empty() && self.end == BodyEnd::Finish {
self.finished = true;
}
return Poll::Ready(Some(Ok(b)));
}
Some(BodyStep::Delay(d)) => self.sleep = Some(Box::pin(tokio::time::sleep(d))),
Some(BodyStep::Fail(msg)) => {
self.steps.clear();
self.end = BodyEnd::Finish;
self.finished = true;
return Poll::Ready(Some(Err(msg)));
}
None => {
return match self.end {
BodyEnd::Finish => {
self.finished = true;
Poll::Ready(None)
}
BodyEnd::Hang => Poll::Pending,
};
}
}
}
}
}
impl Drop for ScriptedBody {
fn drop(&mut self) {
if !self.finished {
self.shared.dropped();
}
}
}
impl Body for ScriptedBody {
type Data = Bytes;
type Error = std::io::Error;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Bytes>, std::io::Error>>> {
self.get_mut()
.poll_chunk(cx)
.map(|chunk| chunk.map(|r| r.map(Frame::data).map_err(std::io::Error::other)))
}
fn is_end_stream(&self) -> bool {
self.finished
}
fn size_hint(&self) -> SizeHint {
match self.exact_len {
Some(n) => SizeHint::with_exact(n),
None => SizeHint::default(),
}
}
}
fn build_response<B>(resp: &FakeResponse, body: B) -> http::Response<B> {
let mut builder = http::Response::builder().status(resp.status);
for (k, v) in &resp.headers {
builder = builder.header(k.as_str(), v.as_str());
}
builder.body(body).expect("valid scripted response head")
}
fn transport_error(message: String) -> ModelError {
ModelError::Transport(Box::new(std::io::Error::other(message)))
}
pub struct FakeServer {
addr: SocketAddr,
shared: Arc<Shared>,
tasks: Arc<Mutex<Vec<tokio::task::AbortHandle>>>,
}
impl FakeServer {
pub fn start<F>(handler: F) -> Self
where
F: Fn(&RecordedRequest) -> FakeResponse + Send + Sync + 'static,
{
Self::with_handler(sync_handler(handler))
}
pub fn start_async<F, Fut>(handler: F) -> Self
where
F: Fn(RecordedRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = FakeResponse> + Send + 'static,
{
Self::with_handler(async_handler(handler))
}
pub fn always(resp: FakeResponse) -> Self {
Self::start(move |_| resp.clone())
}
pub fn json(body: impl Into<String>) -> Self {
Self::always(FakeResponse::json(body))
}
pub fn sequence(responses: Vec<FakeResponse>) -> Self {
Self::with_handler(sequence_handler(responses))
}
pub fn with_handler(handler: Handler) -> Self {
let std_listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind 127.0.0.1:0");
std_listener.set_nonblocking(true).expect("set_nonblocking");
let addr = std_listener.local_addr().expect("local_addr");
let listener = tokio::net::TcpListener::from_std(std_listener).expect("tokio listener");
let shared = Shared::new(handler);
let tasks: Arc<Mutex<Vec<tokio::task::AbortHandle>>> = Arc::default();
let base = format!("http://{addr}");
let (acc_shared, acc_tasks) = (shared.clone(), tasks.clone());
let accept = tokio::spawn(async move {
loop {
let Ok((stream, _)) = listener.accept().await else {
tokio::time::sleep(Duration::from_millis(10)).await;
continue;
};
let (shared, base) = (acc_shared.clone(), base.clone());
let service = hyper::service::service_fn(move |req| {
let (shared, base) = (shared.clone(), base.clone());
async move { serve(shared, base, req).await }
});
let conn = tokio::spawn(async move {
let _ = hyper::server::conn::http1::Builder::new()
.serve_connection(hyper_util::rt::TokioIo::new(stream), service)
.await;
});
acc_tasks.lock().push(conn.abort_handle());
}
});
tasks.lock().push(accept.abort_handle());
Self {
addr,
shared,
tasks,
}
}
pub fn url(&self) -> String {
format!("http://{}", self.addr)
}
pub fn addr(&self) -> SocketAddr {
self.addr
}
pub fn requests(&self) -> Vec<RecordedRequest> {
self.shared.requests()
}
pub fn last_request(&self) -> RecordedRequest {
self.requests()
.pop()
.expect("the fake server received no request")
}
pub fn hits(&self) -> usize {
self.shared.hits()
}
pub fn drops(&self) -> usize {
self.shared.drops()
}
pub async fn wait_for_hits(&self, n: usize) {
self.shared
.wait_until(&format!("{n} request(s)"), |s| s.hits() >= n)
.await;
}
pub async fn wait_for_drops(&self, n: usize) {
self.shared
.wait_until(&format!("{n} dropped response(s)"), |s| s.drops() >= n)
.await;
}
}
impl Drop for FakeServer {
fn drop(&mut self) {
for task in self.tasks.lock().drain(..) {
task.abort();
}
}
}
async fn read_incoming(mut body: Incoming) -> Result<Bytes, hyper::Error> {
let mut out = Vec::new();
while let Some(frame) = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await {
if let Ok(data) = frame?.into_data() {
out.extend_from_slice(&data);
}
}
Ok(Bytes::from(out))
}
async fn serve(
shared: Arc<Shared>,
base: String,
req: http::Request<Incoming>,
) -> Result<http::Response<ScriptedBody>, std::io::Error> {
let (parts, body) = req.into_parts();
let body = read_incoming(body).await.map_err(std::io::Error::other)?;
let path_and_query = parts
.uri
.path_and_query()
.map(|p| p.as_str().to_string())
.unwrap_or_default();
let recorded = RecordedRequest::from_parts(format!("{base}{path_and_query}"), &parts, body);
shared.record(recorded.clone());
let resp = shared
.respond(recorded)
.await
.map_err(std::io::Error::other)?;
let body = ScriptedBody::new(&resp, shared.clone());
Ok(build_response(&resp, body))
}
pub struct ScriptedClient {
shared: Arc<Shared>,
}
impl ScriptedClient {
pub fn new<F>(handler: F) -> Arc<Self>
where
F: Fn(&RecordedRequest) -> FakeResponse + Send + Sync + 'static,
{
Self::with_handler(sync_handler(handler))
}
pub fn new_async<F, Fut>(handler: F) -> Arc<Self>
where
F: Fn(RecordedRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = FakeResponse> + Send + 'static,
{
Self::with_handler(async_handler(handler))
}
pub fn always(resp: FakeResponse) -> Arc<Self> {
Self::new(move |_| resp.clone())
}
pub fn json(body: impl Into<String>) -> Arc<Self> {
Self::always(FakeResponse::json(body))
}
pub fn sequence(responses: Vec<FakeResponse>) -> Arc<Self> {
Self::with_handler(sequence_handler(responses))
}
pub fn with_handler(handler: Handler) -> Arc<Self> {
Arc::new(Self {
shared: Shared::new(handler),
})
}
pub fn requests(&self) -> Vec<RecordedRequest> {
self.shared.requests()
}
pub fn last_request(&self) -> RecordedRequest {
self.requests()
.pop()
.expect("the scripted client got no request")
}
pub fn hits(&self) -> usize {
self.shared.hits()
}
pub fn drops(&self) -> usize {
self.shared.drops()
}
pub fn gap(&self, i: usize) -> Duration {
let requests = self.shared.requests.lock();
requests[i + 1].at - requests[i].at
}
pub async fn wait_for_hits(&self, n: usize) {
self.shared
.wait_until(&format!("{n} request(s)"), |s| s.hits() >= n)
.await;
}
pub async fn wait_for_drops(&self, n: usize) {
self.shared
.wait_until(&format!("{n} dropped response(s)"), |s| s.drops() >= n)
.await;
}
}
#[async_trait::async_trait]
impl HttpClient for ScriptedClient {
async fn send(
&self,
req: http::Request<Bytes>,
) -> Result<http::Response<BodyStream>, ModelError> {
let (parts, body) = req.into_parts();
let recorded = RecordedRequest::from_parts(parts.uri.to_string(), &parts, body);
self.shared.record(recorded.clone());
let resp = self
.shared
.respond(recorded)
.await
.map_err(transport_error)?;
let mut body = ScriptedBody::new(&resp, self.shared.clone());
let stream: BodyStream = futures::stream::poll_fn(move |cx| {
body.poll_chunk(cx)
.map(|c| c.map(|r| r.map_err(transport_error)))
})
.boxed();
Ok(build_response(&resp, stream))
}
}
pub fn sse_event(name: &str, data: &str) -> String {
format!("event: {name}\ndata: {data}\n\n")
}
pub fn sse_lines(lines: &[&str]) -> String {
lines.join("\n")
}
#[derive(Debug)]
struct FixedHeaders(http::HeaderMap);
impl google_cloud_auth::credentials::CredentialsProvider for FixedHeaders {
async fn headers(
&self,
_extensions: http::Extensions,
) -> Result<
google_cloud_auth::credentials::CacheableResource<http::HeaderMap>,
google_cloud_auth::errors::CredentialsError,
> {
Ok(google_cloud_auth::credentials::CacheableResource::New {
entity_tag: google_cloud_auth::credentials::EntityTag::new(),
data: self.0.clone(),
})
}
async fn universe_domain(&self) -> Option<String> {
None
}
}
pub fn fixed_header_credentials(
headers: http::HeaderMap,
) -> google_cloud_auth::credentials::Credentials {
google_cloud_auth::credentials::Credentials::from(FixedHeaders(headers))
}
pub fn bearer_credentials(token: &str) -> google_cloud_auth::credentials::Credentials {
fixed_header_credentials(http::HeaderMap::from_iter([(
http::header::AUTHORIZATION,
http::HeaderValue::from_str(&format!("Bearer {token}")).expect("ASCII token"),
)]))
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
use crate::gcp_auth::credential_headers;
use crate::http::collect_body;
#[tokio::test]
async fn bearer_credentials_send_a_fixed_token() {
let headers = credential_headers(&bearer_credentials("t")).await.unwrap();
assert_eq!(headers.len(), 1);
assert_eq!(headers[http::header::AUTHORIZATION], "Bearer t");
let custom = http::HeaderMap::from_iter([(
http::header::HeaderName::from_static("x-goog-user-project"),
http::HeaderValue::from_static("p"),
)]);
assert_eq!(
credential_headers(&fixed_header_credentials(custom.clone()))
.await
.unwrap(),
custom
);
}
const MSG: &str = r#"{"id":"msg_1","text":"ok"}"#;
#[tokio::test]
async fn server_records_request_and_answers_json() {
let srv = FakeServer::json(MSG);
let resp = reqwest::Client::new()
.post(format!("{}/v1/messages?beta=true", srv.url()))
.header("X-Api-Key", "k")
.header("anthropic-version", "2023-06-01")
.body(r#"{"model":"m","stream":true}"#)
.send()
.await
.unwrap();
assert_eq!(resp.status(), 200);
assert_eq!(resp.headers()["content-type"], "application/json");
assert_eq!(resp.text().await.unwrap(), MSG);
assert_eq!(srv.hits(), 1);
let req = srv.last_request();
assert_eq!(req.method, "POST");
assert_eq!(req.path, "/v1/messages");
assert_eq!(req.query.as_deref(), Some("beta=true"));
assert_eq!(req.path_and_query(), "/v1/messages?beta=true");
assert_eq!(req.url, format!("{}/v1/messages?beta=true", srv.url()));
assert_eq!(req.header("x-api-key"), "k");
assert_eq!(req.header("Anthropic-Version"), "2023-06-01");
assert_eq!(req.header("authorization"), "");
assert_eq!(req.json()["model"], "m");
assert!(req.is_stream());
assert_eq!(req.body_text(), r#"{"model":"m","stream":true}"#);
}
#[tokio::test]
async fn server_streams_chunks_with_delays() {
let events = [
sse_event("message_start", r#"{"type":"message_start"}"#),
sse_event("message_stop", r#"{"type":"message_stop"}"#),
];
let resp = FakeResponse::sse_chunks(events.clone())
.delay(Duration::from_millis(20))
.chunk("event: ping\ndata: {}\n\n");
let srv = FakeServer::always(resp);
let resp = reqwest::get(srv.url()).await.unwrap();
assert_eq!(resp.headers()["content-type"], "text/event-stream");
let mut body = resp.bytes_stream();
let mut got = Vec::new();
while let Some(chunk) = body.next().await {
got.extend_from_slice(&chunk.unwrap());
}
assert_eq!(
String::from_utf8(got).unwrap(),
format!("{}{}event: ping\ndata: {{}}\n\n", events[0], events[1])
);
assert_eq!(srv.drops(), 0);
}
#[tokio::test]
async fn server_fully_read_fixed_length_bodies_are_not_drops() {
let srv = FakeServer::json(MSG);
let client = reqwest::Client::new();
for _ in 0..2 {
let resp = client.post(srv.url()).body("{}").send().await.unwrap();
assert!(resp.headers().contains_key("content-length"));
assert!(resp.text().await.unwrap().contains("msg_1"));
}
tokio::time::sleep(Duration::from_millis(100)).await;
assert_eq!((srv.hits(), srv.drops()), (2, 0));
}
#[tokio::test]
async fn server_fully_read_empty_body_is_not_a_drop() {
let srv = FakeServer::always(FakeResponse::new(204));
let resp = reqwest::get(srv.url()).await.unwrap();
assert_eq!(resp.status(), 204);
assert!(resp.bytes().await.unwrap().is_empty());
tokio::time::sleep(Duration::from_millis(100)).await;
assert_eq!((srv.hits(), srv.drops()), (1, 0));
}
#[tokio::test]
async fn server_observes_client_drop_mid_body() {
let srv = FakeServer::always(
FakeResponse::sse(sse_event("message_start", "{}"))
.delay(Duration::from_millis(10))
.hang(),
);
let resp = reqwest::get(srv.url()).await.unwrap();
let mut body = resp.bytes_stream();
let first = body.next().await.unwrap().unwrap();
assert_eq!(&first[..], b"event: message_start\ndata: {}\n\n");
drop(body);
srv.wait_for_drops(1).await;
assert_eq!(srv.drops(), 1);
}
#[tokio::test]
async fn server_observes_drop_of_unanswered_request() {
let srv = FakeServer::always(FakeResponse::never());
let url = srv.url();
let client = tokio::spawn(async move { reqwest::get(url).await });
srv.wait_for_hits(1).await;
assert_eq!(srv.drops(), 0);
client.abort();
srv.wait_for_drops(1).await;
}
#[tokio::test]
async fn server_async_handler_waits_for_release() {
let release = Arc::new(Notify::new());
let gate = release.clone();
let srv = FakeServer::start_async(move |req| {
let gate = gate.clone();
async move {
gate.notified().await;
FakeResponse::json(format!(r#"{{"path":"{}"}}"#, req.path))
}
});
let url = format!("{}/v1/messages", srv.url());
let client = tokio::spawn(async move { reqwest::get(url).await.unwrap().text().await });
srv.wait_for_hits(1).await;
release.notify_one();
assert_eq!(client.await.unwrap().unwrap(), r#"{"path":"/v1/messages"}"#);
}
#[tokio::test]
async fn server_sequence_status_headers_and_reset() {
let srv = FakeServer::sequence(vec![
FakeResponse::json_status(529, r#"{"error":"overloaded"}"#)
.header("Retry-After-Ms", "1"),
FakeResponse::reset("connection reset by script"),
FakeResponse::json("{}").delay_headers(Duration::from_millis(5)),
]);
let client = reqwest::Client::new();
let first = client.get(srv.url()).send().await.unwrap();
assert_eq!(first.status(), 529);
assert_eq!(first.headers()["retry-after-ms"], "1");
assert!(client.get(srv.url()).send().await.is_err());
for _ in 0..2 {
let ok = client.get(srv.url()).send().await.unwrap();
assert_eq!(ok.status(), 200);
assert_eq!(ok.text().await.unwrap(), "{}");
}
assert_eq!(srv.hits(), 4);
}
#[tokio::test]
async fn server_body_failure_aborts_the_body() {
let srv = FakeServer::always(
FakeResponse::sse("data: a\n\n")
.delay(Duration::from_millis(20))
.fail("unexpected EOF"),
);
let resp = reqwest::get(srv.url()).await.unwrap();
let mut body = resp.bytes_stream();
let mut got = Vec::new();
let mut failed = false;
while let Some(chunk) = body.next().await {
match chunk {
Ok(c) => got.extend_from_slice(&c),
Err(_) => failed = true,
}
}
assert!(failed, "the body must fail");
assert_eq!(&got[..], b"data: a\n\n");
assert_eq!(srv.drops(), 0);
}
fn request(uri: &str, body: &'static [u8]) -> http::Request<Bytes> {
http::Request::builder()
.method("POST")
.uri(uri)
.header("x-api-key", "k")
.body(Bytes::from_static(body))
.unwrap()
}
#[tokio::test]
async fn scripted_client_records_and_streams() {
let client = ScriptedClient::always(
FakeResponse::sse_chunks(["a", "b"])
.delay(Duration::from_millis(5))
.chunk("c"),
);
let resp = client
.send(request(
"https://api.anthropic.com/v1/messages",
br#"{"stream":true}"#,
))
.await
.unwrap();
assert_eq!(resp.status(), 200);
assert_eq!(resp.headers()["content-type"], "text/event-stream");
let body = collect_body(resp.into_body()).await.unwrap();
assert_eq!(&body[..], b"abc");
let rec = client.last_request();
assert_eq!(rec.url, "https://api.anthropic.com/v1/messages");
assert_eq!(rec.path, "/v1/messages");
assert_eq!(rec.header("X-Api-Key"), "k");
assert!(rec.is_stream());
assert_eq!((client.hits(), client.drops()), (1, 0));
}
#[tokio::test]
async fn scripted_client_reset_and_drop() {
let client = ScriptedClient::sequence(vec![
FakeResponse::reset("boom"),
FakeResponse::sse("x").hang(),
]);
match client.send(request("http://h/", b"")).await {
Err(ModelError::Transport(e)) => assert_eq!(e.to_string(), "boom"),
other => panic!("want transport error, got {:?}", other.map(|r| r.status())),
}
let resp = client.send(request("http://h/", b"")).await.unwrap();
let mut body = resp.into_body();
assert_eq!(&body.next().await.unwrap().unwrap()[..], b"x");
drop(body);
assert_eq!(client.drops(), 1);
client.wait_for_drops(1).await;
}
#[tokio::test]
async fn scripted_client_body_failure_ends_the_body() {
let client = ScriptedClient::always(
FakeResponse::json("{")
.fail("unexpected EOF")
.chunk("never sent"),
);
let resp = client.send(request("http://h/", b"")).await.unwrap();
let mut body = resp.into_body();
assert_eq!(&body.next().await.unwrap().unwrap()[..], b"{");
match body.next().await {
Some(Err(ModelError::Transport(e))) => assert_eq!(e.to_string(), "unexpected EOF"),
other => panic!("want a transport body error, got {other:?}"),
}
assert!(body.next().await.is_none());
drop(body);
assert_eq!(client.drops(), 0, "a scripted failure is not a client drop");
}
#[tokio::test(start_paused = true)]
async fn scripted_client_never_counts_a_drop_and_gap_measures_tokio_time() {
let client =
ScriptedClient::sequence(vec![FakeResponse::never(), FakeResponse::json("{}")]);
let first = tokio::time::timeout(
Duration::from_secs(3),
client.send(request("http://h/", b"")),
)
.await;
assert!(first.is_err(), "never answered");
assert_eq!(client.drops(), 1);
tokio::time::sleep(Duration::from_secs(2)).await;
client.send(request("http://h/", b"")).await.unwrap();
assert_eq!(client.gap(0), Duration::from_secs(5));
assert_eq!(client.requests().len(), 2);
}
#[test]
fn sse_builders_match_go_layout() {
assert_eq!(
sse_event("message_stop", r#"{"type":"message_stop"}"#),
"event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"
);
assert_eq!(
sse_lines(&["event: a", "data: {}", "", "event: b", "data: {}", ""]),
"event: a\ndata: {}\n\nevent: b\ndata: {}\n"
);
}
#[test]
fn fake_response_builders() {
let r = FakeResponse::json_status(429, "{}")
.header("Retry-After", "1")
.delay(Duration::from_secs(1))
.chunk("x")
.fail("eof")
.status(503)
.delay_headers(Duration::from_secs(2))
.hang();
assert_eq!(r.status, 503);
assert_eq!(
r.headers,
vec![
("Content-Type".to_string(), "application/json".to_string()),
("Retry-After".to_string(), "1".to_string()),
]
);
assert_eq!(r.header_delay, Some(Duration::from_secs(2)));
assert_eq!(r.end, BodyEnd::Hang);
assert_eq!(r.outcome, Outcome::Respond);
assert_eq!(&r.body_bytes()[..], b"{}x");
assert!(matches!(r.steps[3], BodyStep::Fail(ref m) if m == "eof"));
assert_eq!(FakeResponse::never().outcome, Outcome::Never);
assert_eq!(
FakeResponse::reset("x").outcome,
Outcome::Reset("x".to_string())
);
}
}