use std::sync::Arc;
use atproto_identity::resolve::{HickoryDnsResolver, InnerIdentityResolver};
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use crate::cache::BlobCache;
use crate::context::{Limits, ServerContext};
use crate::proto::RequestKey;
use crate::proto::serve::RequestCtx;
use crate::proto::writer;
#[must_use]
pub fn create_test_resolver() -> InnerIdentityResolver {
InnerIdentityResolver {
dns_resolver: Arc::new(HickoryDnsResolver::create_resolver(&[])),
http_client: crate::context::identity_client(&test_guard()).expect("identity client"),
plc_hostname: "plc.directory".to_string(),
}
}
#[must_use]
pub fn test_guard() -> crate::context::AddressGuard {
crate::context::AddressGuard::for_config(true, "plc.directory")
}
pub fn test_request_client() -> reqwest::Client {
crate::context::request_client(&test_guard()).expect("request client")
}
#[must_use]
pub fn test_limits() -> Limits {
Limits {
blob_max_inline_bytes: 1024,
allow_insecure_endpoints: true,
..Limits::default()
}
}
#[must_use]
pub fn test_context() -> Arc<ServerContext> {
build_context(Arc::new(BlobCache::new(None, 0)), test_limits())
}
#[must_use]
pub fn test_context_with_cache() -> Arc<ServerContext> {
test_context_with_cache_and_limits(test_limits())
}
#[must_use]
pub fn test_context_with_cache_and_limits(limits: Limits) -> Arc<ServerContext> {
test_context_with_cache_budget(limits, crate::context::DEFAULT_BLOB_CACHE_MAX_BYTES)
}
#[must_use]
pub fn test_context_with_cache_budget(limits: Limits, cache_max_bytes: u64) -> Arc<ServerContext> {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let dir = std::env::temp_dir().join(format!(
"atpmcp-test-{}-{}",
std::process::id(),
COUNTER.fetch_add(1, Ordering::Relaxed)
));
build_context(Arc::new(BlobCache::new(Some(dir), cache_max_bytes)), limits)
}
fn build_context(cache: Arc<BlobCache>, limits: Limits) -> Arc<ServerContext> {
let (tx, rx) = mpsc::channel::<writer::Outgoing>(writer::CHANNEL_CAPACITY);
std::mem::forget(rx);
Arc::new(
ServerContext::new(Arc::new(create_test_resolver()), cache, limits, tx).expect("context"),
)
}
#[must_use]
pub fn test_request() -> RequestCtx {
RequestCtx {
key: RequestKey::Num(1),
id: serde_json::json!(1),
meta: crate::proto::meta::Meta {
protocol_version: crate::proto::PROTOCOL_VERSION.to_string(),
client_capabilities: serde_json::json!({}),
client_info: None,
progress_token: None,
},
cancel: CancellationToken::new(),
progress: None,
}
}
pub async fn one_shot_server(status: u16, body: Vec<u8>, declare_length: bool) -> String {
one_shot_server_typed(
status,
body,
declare_length,
Some("application/octet-stream"),
)
.await
}
pub async fn one_shot_server_typed(
status: u16,
body: Vec<u8>,
declare_length: bool,
content_type: Option<&str>,
) -> String {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
let addr = listener.local_addr().expect("addr");
let content_type = content_type.map(str::to_string);
tokio::spawn(async move {
let Ok((mut socket, _)) = listener.accept().await else {
return;
};
let mut raw = Vec::new();
let mut buffer = [0u8; 4096];
loop {
let Ok(read) = socket.read(&mut buffer).await else {
return;
};
if read == 0 {
break;
}
raw.extend_from_slice(&buffer[..read]);
if raw.windows(4).any(|w| w == b"\r\n\r\n") {
break;
}
}
let mut response = format!("HTTP/1.1 {status} X\r\n");
if let Some(content_type) = &content_type {
response.push_str(&format!("Content-Type: {content_type}\r\n"));
}
if declare_length {
response.push_str(&format!("Content-Length: {}\r\n", body.len()));
}
response.push_str("Connection: close\r\n\r\n");
let _ = socket.write_all(response.as_bytes()).await;
let _ = socket.write_all(&body).await;
let _ = socket.shutdown().await;
});
format!("http://{addr}")
}
#[derive(Clone)]
pub struct Route {
pub path: &'static str,
pub status: u16,
pub headers: Vec<(&'static str, String)>,
pub body: Vec<u8>,
}
impl Route {
#[must_use]
pub fn ok(path: &'static str, content_type: &str, body: impl Into<Vec<u8>>) -> Self {
Self {
path,
status: 200,
headers: vec![("Content-Type", content_type.to_string())],
body: body.into(),
}
}
}
pub async fn route_server(routes: Vec<Route>) -> String {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
let addr = listener.local_addr().expect("addr");
let routes = Arc::new(routes);
tokio::spawn(async move {
while let Ok((mut socket, _)) = listener.accept().await {
let routes = Arc::clone(&routes);
tokio::spawn(async move {
let mut raw = Vec::new();
let mut buffer = [0u8; 4096];
loop {
let Ok(read) = socket.read(&mut buffer).await else {
return;
};
if read == 0 {
break;
}
raw.extend_from_slice(&buffer[..read]);
if raw.windows(4).any(|w| w == b"\r\n\r\n") {
break;
}
}
let request = String::from_utf8_lossy(&raw);
let path = request.split_whitespace().nth(1).unwrap_or("/");
let route = routes.iter().find(|route| route.path == path);
let (status, headers, body) = match route {
Some(route) => (route.status, route.headers.clone(), route.body.clone()),
None => (404, Vec::new(), b"not found".to_vec()),
};
let mut response = format!("HTTP/1.1 {status} X\r\n");
for (name, value) in headers {
response.push_str(&format!("{name}: {value}\r\n"));
}
response.push_str(&format!(
"Content-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
));
let _ = socket.write_all(response.as_bytes()).await;
let _ = socket.write_all(&body).await;
let _ = socket.shutdown().await;
});
}
});
format!("http://{addr}")
}