Files
leleka/desktop-core/tests/node_contract/support.rs
T

132 lines
4.1 KiB
Rust

//! Servers, the fake worker and the HTTP proxy of the node contract tests.
use axum::{Router, body::Body, routing::post};
use std::{collections::BTreeMap, time::Duration};
use strata_desktop_core::{
gateway,
node::{self, proto::*},
};
use tokio::net::TcpListener;
pub const TOKEN: &str = "synthetic-test-credential-32-bytes-only";
pub struct Server {
pub address: std::net::SocketAddr,
task: tokio::task::JoinHandle<()>,
}
impl Drop for Server {
fn drop(&mut self) {
self.task.abort();
}
}
pub async fn server(gateway: Option<gateway::Gateway>) -> Server {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let agent = node::Agent::new(TOKEN.into(), gateway).unwrap();
let task =
tokio::spawn(async move { agent.serve(listener, std::future::pending()).await.unwrap() });
Server { address, task }
}
pub fn req<T>(message: T) -> tonic::Request<T> {
node::authorized(message, TOKEN).unwrap()
}
pub fn hello() -> tonic::Request<Hello> {
req(Hello {
protocol_version: 1,
})
}
fn sse_router(body: &'static str, delay: bool) -> Router {
Router::new().route(
"/v1/responses",
post(move || async move {
let stream = async_stream::stream! {
if delay {
tokio::time::sleep(Duration::from_millis(150)).await;
}
for bytes in body.as_bytes().chunks(3) {
yield Ok::<_, std::io::Error>(bytes.to_vec());
}
};
axum::response::Response::builder()
.header("content-type", "text/event-stream")
.body(Body::from_stream(stream))
.unwrap()
}),
)
}
fn gateway_config(address: std::net::SocketAddr) -> gateway::Config {
gateway::Config {
schema_version: 1,
listen: "127.0.0.1:0".parse().unwrap(),
token_env: "UNUSED".into(),
queue_limit: 4,
queue_timeout_ms: 1000,
request_timeout_ms: 3000,
groups: vec![gateway::Group {
id: "local".into(),
slots: 1,
available_bytes: 100,
}],
deployments: vec![gateway::Deployment {
id: "test".into(),
model: "test".into(),
endpoint: format!("http://{address}"),
token_env: None,
group: "local".into(),
slots: 1,
request_bytes: 1,
capabilities: vec!["responses".into(), "tools".into()],
}],
aliases: BTreeMap::new(),
}
}
pub async fn fake(body: &'static str, delay: bool) -> (Server, gateway::Gateway) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let router = sse_router(body, delay);
let task = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
let g = gateway::Gateway::with_token(gateway_config(address), TOKEN.into()).unwrap();
(Server { address, task }, g)
}
/// An HTTP proxy in front of `node`, speaking gRPC to it with the test credential.
pub async fn serve_proxy(node: &Server) -> Server {
let proxy = strata_desktop_core::node_proxy::Proxy::connect(node.address, TOKEN.into())
.await
.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let task = tokio::spawn(async move { axum::serve(listener, proxy.router()).await.unwrap() });
Server { address, task }
}
/// Polls the handshake until no response is active any more.
pub async fn wait_until_no_active_response(
client: &mut node_client::NodeClient<tonic::transport::Channel>,
) {
tokio::time::timeout(Duration::from_secs(2), async {
loop {
if client
.handshake(hello())
.await
.unwrap()
.into_inner()
.active_responses
== 0
{
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
}