#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::future::Future;
use std::sync::Arc;
use http::{HeaderMap, HeaderName, HeaderValue};
use parking_lot::Mutex;
use serde_json::Value;
use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
use tokio::task::{JoinHandle, JoinSet};
#[derive(Debug, Clone)]
pub struct RecordedRequest {
pub method: String,
pub path: String,
pub query: Option<String>,
pub headers: HeaderMap,
pub body: Vec<u8>,
}
impl RecordedRequest {
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.get(name).and_then(|v| v.to_str().ok())
}
pub fn json(&self) -> Value {
serde_json::from_slice(&self.body).unwrap_or_else(|e| {
panic!(
"request body is not JSON ({e}): {}",
String::from_utf8_lossy(&self.body)
)
})
}
}
#[derive(Debug, Clone)]
pub struct Reply {
pub status: u16,
pub headers: Vec<(String, String)>,
pub body: Vec<u8>,
}
impl Reply {
pub fn ok(body: impl Into<Vec<u8>>) -> Self {
Self::status(200, body)
}
pub fn status(status: u16, body: impl Into<Vec<u8>>) -> Self {
Self {
status,
headers: Vec::new(),
body: body.into(),
}
}
pub fn json(body: impl Into<Vec<u8>>) -> Self {
Self::ok(body).with_header("Content-Type", "application/json")
}
pub fn redirect(location: impl Into<String>, status: u16) -> Self {
Self::status(status, Vec::new()).with_header("Location", location)
}
pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
}
pub struct TestServer {
url: String,
requests: Arc<Mutex<Vec<RecordedRequest>>>,
accept: JoinHandle<()>,
}
impl TestServer {
pub async fn start<F, Fut>(handler: F) -> TestServer
where
F: Fn(RecordedRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Reply> + Send + 'static,
{
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("bind 127.0.0.1:0");
let url = format!("http://{}", listener.local_addr().expect("local addr"));
let requests = Arc::new(Mutex::new(Vec::new()));
let recorded = requests.clone();
let handler = Arc::new(handler);
let accept = tokio::spawn(async move {
let mut conns = JoinSet::new();
loop {
let Ok((stream, _)) = listener.accept().await else {
return;
};
while conns.try_join_next().is_some() {}
conns.spawn(serve(stream, handler.clone(), recorded.clone()));
}
});
TestServer {
url,
requests,
accept,
}
}
pub async fn replying(reply: Reply) -> TestServer {
Self::start(move |_req| {
let reply = reply.clone();
async move { reply }
})
.await
}
pub fn url(&self) -> &str {
&self.url
}
pub fn requests(&self) -> Vec<RecordedRequest> {
self.requests.lock().clone()
}
pub fn calls(&self) -> usize {
self.requests.lock().len()
}
}
impl Drop for TestServer {
fn drop(&mut self) {
self.accept.abort();
}
}
async fn serve<F, Fut>(
stream: TcpStream,
handler: Arc<F>,
recorded: Arc<Mutex<Vec<RecordedRequest>>>,
) where
F: Fn(RecordedRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Reply> + Send + 'static,
{
let (read, mut write) = stream.into_split();
let mut reader = BufReader::new(read);
let Some(req) = read_request(&mut reader).await else {
return;
};
recorded.lock().push(req.clone());
let reply = handler(req).await;
let _ = write.write_all(&encode_reply(&reply)).await;
let _ = write.shutdown().await;
}
async fn read_line<R: AsyncBufRead + Unpin>(r: &mut R) -> Option<Vec<u8>> {
let mut line = Vec::new();
if r.read_until(b'\n', &mut line).await.ok()? == 0 {
return None;
}
while matches!(line.last(), Some(b'\n' | b'\r')) {
line.pop();
}
Some(line)
}
async fn read_request<R: AsyncBufRead + Unpin>(r: &mut R) -> Option<RecordedRequest> {
let start = String::from_utf8(read_line(r).await?).ok()?;
let mut parts = start.splitn(3, ' ');
let method = parts.next()?.to_string();
let target = parts.next()?.to_string();
let (path, query) = match target.split_once('?') {
Some((p, q)) => (p.to_string(), Some(q.to_string())),
None => (target, None),
};
let mut headers = HeaderMap::new();
loop {
let line = read_line(r).await?;
if line.is_empty() {
break;
}
let colon = line.iter().position(|&b| b == b':')?;
let name = HeaderName::from_bytes(line[..colon].trim_ascii()).ok()?;
let value = HeaderValue::from_bytes(line[colon + 1..].trim_ascii()).ok()?;
headers.append(name, value);
}
let len = headers
.get(http::header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.trim().parse::<usize>().ok())
.unwrap_or(0);
let mut body = vec![0; len];
r.read_exact(&mut body).await.ok()?;
Some(RecordedRequest {
method,
path,
query,
headers,
body,
})
}
fn encode_reply(reply: &Reply) -> Vec<u8> {
let reason = http::StatusCode::from_u16(reply.status)
.ok()
.and_then(|s| s.canonical_reason())
.unwrap_or("Status");
let mut head = format!("HTTP/1.1 {} {reason}\r\n", reply.status);
for (name, value) in &reply.headers {
if name.eq_ignore_ascii_case("content-length") || name.eq_ignore_ascii_case("connection") {
continue;
}
head.push_str(&format!("{name}: {value}\r\n"));
}
head.push_str(&format!(
"Content-Length: {}\r\nConnection: close\r\n\r\n",
reply.body.len()
));
let mut out = head.into_bytes();
out.extend_from_slice(&reply.body);
out
}