Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
404 lines
12 KiB
Rust
404 lines
12 KiB
Rust
use axum::{
|
|
Json, Router,
|
|
body::{Body, Bytes},
|
|
extract::State,
|
|
routing::post,
|
|
};
|
|
use futures_util::StreamExt;
|
|
use serde_json::{Value, json};
|
|
use std::{
|
|
collections::BTreeMap,
|
|
sync::{
|
|
Arc,
|
|
atomic::{AtomicUsize, Ordering},
|
|
},
|
|
time::Duration,
|
|
};
|
|
use strata_desktop_core::gateway::{Config, Deployment, Gateway, Group};
|
|
use tokio::{
|
|
sync::{Notify, Semaphore},
|
|
task::JoinHandle,
|
|
};
|
|
const TOKEN: &str = "synthetic-test-token-no-secret";
|
|
struct Server {
|
|
url: String,
|
|
task: JoinHandle<()>,
|
|
}
|
|
impl Drop for Server {
|
|
fn drop(&mut self) {
|
|
self.task.abort();
|
|
}
|
|
}
|
|
async fn server(router: Router) -> Server {
|
|
let socket = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
let url = format!("http://{}", socket.local_addr().unwrap());
|
|
let task = tokio::spawn(async move {
|
|
axum::serve(socket, router).await.unwrap();
|
|
});
|
|
Server { url, task }
|
|
}
|
|
fn config(nodes: &[&Server]) -> Config {
|
|
Config {
|
|
schema_version: 1,
|
|
listen: "127.0.0.1:0".parse().unwrap(),
|
|
token_env: "UNUSED".into(),
|
|
queue_limit: 2,
|
|
queue_timeout_ms: 1000,
|
|
request_timeout_ms: 3000,
|
|
groups: nodes
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(i, _)| Group {
|
|
id: format!("g{i}"),
|
|
slots: 1,
|
|
available_bytes: 100,
|
|
})
|
|
.collect(),
|
|
deployments: nodes
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(i, n)| Deployment {
|
|
id: format!("d{i}"),
|
|
model: format!("m{i}"),
|
|
endpoint: n.url.clone(),
|
|
token_env: None,
|
|
group: format!("g{i}"),
|
|
slots: 1,
|
|
request_bytes: 100,
|
|
capabilities: vec!["responses".into(), "tools".into()],
|
|
})
|
|
.collect(),
|
|
aliases: BTreeMap::from([(
|
|
"pool".into(),
|
|
(0..nodes.len()).map(|i| format!("d{i}")).collect(),
|
|
)]),
|
|
}
|
|
}
|
|
fn request(client: &reqwest::Client, g: &Server, value: Value) -> reqwest::RequestBuilder {
|
|
client
|
|
.post(format!("{}/v1/responses", g.url))
|
|
.bearer_auth(TOKEN)
|
|
.header("content-type", "application/json")
|
|
.body(value.to_string())
|
|
}
|
|
async fn status(client: &reqwest::Client, g: &Server) -> Value {
|
|
let text = client
|
|
.get(format!("{}/pool/status", g.url))
|
|
.bearer_auth(TOKEN)
|
|
.send()
|
|
.await
|
|
.unwrap()
|
|
.text()
|
|
.await
|
|
.unwrap();
|
|
serde_json::from_str(&text).unwrap()
|
|
}
|
|
struct Counting {
|
|
started: AtomicUsize,
|
|
notify: Notify,
|
|
release: Semaphore,
|
|
}
|
|
async fn held(State(c): State<Arc<Counting>>, Json(v): Json<Value>) -> Json<Value> {
|
|
let id = c.started.fetch_add(1, Ordering::SeqCst);
|
|
c.notify.notify_one();
|
|
c.release.acquire().await.unwrap().forget();
|
|
Json(
|
|
json!({"id":format!("response-{id}"),"status":"completed","model":v["model"],"output":v["input"]}),
|
|
)
|
|
}
|
|
async fn wait_started(c: &Counting, n: usize) {
|
|
tokio::time::timeout(Duration::from_secs(2), async {
|
|
loop {
|
|
let notified = c.notify.notified();
|
|
if c.started.load(Ordering::SeqCst) >= n {
|
|
return;
|
|
}
|
|
notified.await;
|
|
}
|
|
})
|
|
.await
|
|
.unwrap();
|
|
}
|
|
#[tokio::test]
|
|
async fn three_http_requests_overlap_fourth_queues_and_affinity_is_preserved() {
|
|
let c = Arc::new(Counting {
|
|
started: AtomicUsize::new(0),
|
|
notify: Notify::new(),
|
|
release: Semaphore::new(0),
|
|
});
|
|
let a = server(
|
|
Router::new()
|
|
.route("/v1/responses", post(held))
|
|
.with_state(c.clone()),
|
|
)
|
|
.await;
|
|
let b = server(
|
|
Router::new()
|
|
.route("/v1/responses", post(held))
|
|
.with_state(c.clone()),
|
|
)
|
|
.await;
|
|
let d = server(
|
|
Router::new()
|
|
.route("/v1/responses", post(held))
|
|
.with_state(c.clone()),
|
|
)
|
|
.await;
|
|
let gateway = Gateway::with_token(config(&[&a, &b, &d]), TOKEN.into()).unwrap();
|
|
let g = server(gateway.router()).await;
|
|
let client = reqwest::Client::new();
|
|
let mut jobs = Vec::new();
|
|
for i in 0..3 {
|
|
let r = request(
|
|
&client,
|
|
&g,
|
|
json!({"model":"pool","input":format!("job-{i}")}),
|
|
);
|
|
jobs.push(tokio::spawn(async move {
|
|
r.send().await.unwrap().text().await.unwrap()
|
|
}));
|
|
}
|
|
wait_started(&c, 3).await;
|
|
assert_eq!(status(&client, &g).await["pool"]["active"], 3);
|
|
let r = request(&client, &g, json!({"model":"pool","input":"fourth"}));
|
|
let fourth = tokio::spawn(async move { r.send().await.unwrap().text().await.unwrap() });
|
|
tokio::time::timeout(Duration::from_secs(1), async {
|
|
while status(&client, &g).await["pool"]["queued"] != 1 {
|
|
tokio::task::yield_now().await;
|
|
}
|
|
})
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(c.started.load(Ordering::SeqCst), 3);
|
|
c.release.add_permits(4);
|
|
let mut models = std::collections::HashSet::new();
|
|
let mut first = None;
|
|
for (i, j) in jobs.into_iter().enumerate() {
|
|
let v: Value = serde_json::from_str(&j.await.unwrap()).unwrap();
|
|
assert_eq!(v["output"], format!("job-{i}"));
|
|
models.insert(v["model"].as_str().unwrap().to_owned());
|
|
first = Some(v);
|
|
}
|
|
assert_eq!(models.len(), 3);
|
|
assert!(fourth.await.unwrap().contains("fourth"));
|
|
let old = first.unwrap();
|
|
c.release.add_permits(1);
|
|
let next = request(
|
|
&client,
|
|
&g,
|
|
json!({"model":"pool","input":"continuation","previous_response_id":old["id"]}),
|
|
)
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
let next: Value = serde_json::from_str(&next.text().await.unwrap()).unwrap();
|
|
assert_eq!(next["model"], old["model"]);
|
|
let denied = request(
|
|
&client,
|
|
&g,
|
|
json!({"model":"pool","previous_response_id":"unknown","input":"x"}),
|
|
)
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(denied.status(), 409);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn fragmented_sse_tool_arguments_are_byte_identical() {
|
|
let wire = "event: response.output_item.done\ndata: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"function_call\",\"call_id\":\"c1\",\"name\":\"test\",\"arguments\":\"{\\\"a\\\":1}\"}}\n\nevent: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"stream-1\",\"status\":\"completed\"}}\n\n";
|
|
let a = server(Router::new().route(
|
|
"/v1/responses",
|
|
post(move |Json(v): Json<Value>| async move {
|
|
assert_eq!(v["model"], "m0");
|
|
assert_eq!(v["tools"][0]["name"], "test");
|
|
let chunks: Vec<_> = wire
|
|
.as_bytes()
|
|
.chunks(3)
|
|
.map(Bytes::copy_from_slice)
|
|
.map(Ok::<_, std::io::Error>)
|
|
.collect();
|
|
(
|
|
[("content-type", "text/event-stream")],
|
|
Body::from_stream(futures_util::stream::iter(chunks)),
|
|
)
|
|
}),
|
|
))
|
|
.await;
|
|
let g = server(
|
|
Gateway::with_token(config(&[&a]), TOKEN.into())
|
|
.unwrap()
|
|
.router(),
|
|
)
|
|
.await;
|
|
let client = reqwest::Client::new();
|
|
let r=request(&client,&g,json!({"model":"pool","stream":true,"input":"x","tools":[{"type":"function","name":"test","parameters":{"type":"object"}}]})).send().await.unwrap();
|
|
assert_eq!(r.headers()["x-strata-deployment"], "d0");
|
|
assert_eq!(r.text().await.unwrap(), wire);
|
|
let s = status(&client, &g).await;
|
|
assert_eq!(s["pool"]["active"], 0);
|
|
assert_eq!(s["pool"]["workers"][0]["ready"], true);
|
|
}
|
|
#[tokio::test]
|
|
async fn auth_capabilities_and_queue_saturation_fail_explicitly() {
|
|
let c = Arc::new(Counting {
|
|
started: AtomicUsize::new(0),
|
|
notify: Notify::new(),
|
|
release: Semaphore::new(0),
|
|
});
|
|
let a = server(
|
|
Router::new()
|
|
.route("/v1/responses", post(held))
|
|
.with_state(c.clone()),
|
|
)
|
|
.await;
|
|
let mut cfg = config(&[&a]);
|
|
cfg.queue_limit = 1;
|
|
cfg.queue_timeout_ms = 100;
|
|
let g = server(Gateway::with_token(cfg, TOKEN.into()).unwrap().router()).await;
|
|
let client = reqwest::Client::new();
|
|
assert_eq!(
|
|
client
|
|
.get(format!("{}/v1/models", g.url))
|
|
.send()
|
|
.await
|
|
.unwrap()
|
|
.status(),
|
|
401
|
|
);
|
|
assert_eq!(
|
|
request(
|
|
&client,
|
|
&g,
|
|
json!({"model":"pool","input":[{"type":"input_image","image_url":"x"}]})
|
|
)
|
|
.send()
|
|
.await
|
|
.unwrap()
|
|
.status(),
|
|
409
|
|
);
|
|
let r = request(&client, &g, json!({"model":"d0","input":"hold"}));
|
|
let hold = tokio::spawn(async move { r.send().await.unwrap() });
|
|
wait_started(&c, 1).await;
|
|
let r = request(&client, &g, json!({"model":"d0","input":"wait"}));
|
|
let wait = tokio::spawn(async move { r.send().await.unwrap() });
|
|
tokio::time::timeout(Duration::from_secs(1), async {
|
|
while status(&client, &g).await["pool"]["queued"] != 1 {
|
|
tokio::task::yield_now().await;
|
|
}
|
|
})
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(
|
|
request(&client, &g, json!({"model":"d0","input":"overflow"}))
|
|
.send()
|
|
.await
|
|
.unwrap()
|
|
.status(),
|
|
429
|
|
);
|
|
assert_eq!(wait.await.unwrap().status(), 504);
|
|
c.release.add_permits(1);
|
|
assert_eq!(hold.await.unwrap().status(), 200);
|
|
}
|
|
#[tokio::test]
|
|
async fn interrupted_upstream_is_quarantined_without_stalling_other_nodes() {
|
|
let a = server(Router::new().route(
|
|
"/v1/responses",
|
|
post(|| async {
|
|
(
|
|
[("content-type", "text/event-stream")],
|
|
"data: {\"type\":\"response.created\"}\n\n",
|
|
)
|
|
}),
|
|
))
|
|
.await;
|
|
let b = server(Router::new().route(
|
|
"/v1/responses",
|
|
post(|| async { Json(json!({"id":"healthy","status":"completed"})) }),
|
|
))
|
|
.await;
|
|
let g = server(
|
|
Gateway::with_token(config(&[&a, &b]), TOKEN.into())
|
|
.unwrap()
|
|
.router(),
|
|
)
|
|
.await;
|
|
let client = reqwest::Client::new();
|
|
let r = request(&client, &g, json!({"model":"d0","stream":true,"input":"x"}))
|
|
.send()
|
|
.await;
|
|
if let Ok(r) = r {
|
|
assert!(r.text().await.is_err());
|
|
}
|
|
let s = status(&client, &g).await;
|
|
assert_eq!(s["pool"]["workers"][0]["ready"], false);
|
|
assert_eq!(s["pool"]["active"], 0);
|
|
assert_eq!(
|
|
request(&client, &g, json!({"model":"pool","input":"healthy"}))
|
|
.send()
|
|
.await
|
|
.unwrap()
|
|
.status(),
|
|
200
|
|
);
|
|
}
|
|
#[tokio::test]
|
|
async fn rejects_public_endpoint_bind_and_duplicate_endpoints() {
|
|
let fixture = server(Router::new()).await;
|
|
let mut c = config(&[&fixture]);
|
|
c.listen = "0.0.0.0:1234".parse().unwrap();
|
|
assert!(Gateway::with_token(c, TOKEN.into()).is_err());
|
|
let mut c = config(&[&fixture]);
|
|
c.deployments[0].endpoint = "http://192.0.2.1:80".into();
|
|
assert!(Gateway::with_token(c, TOKEN.into()).is_err());
|
|
let c = config(&[&fixture, &fixture]);
|
|
assert!(Gateway::with_token(c, TOKEN.into()).is_err());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn client_disconnect_quarantines_worker_until_verified_recovery() {
|
|
let a = server(Router::new().route(
|
|
"/v1/responses",
|
|
post(|| async {
|
|
let initial = futures_util::stream::once(async {
|
|
Ok::<_, std::io::Error>(Bytes::from_static(
|
|
b"data: {\"type\":\"response.created\"}\n\n",
|
|
))
|
|
});
|
|
(
|
|
[("content-type", "text/event-stream")],
|
|
Body::from_stream(initial.chain(futures_util::stream::pending())),
|
|
)
|
|
}),
|
|
))
|
|
.await;
|
|
let g = server(
|
|
Gateway::with_token(config(&[&a]), TOKEN.into())
|
|
.unwrap()
|
|
.router(),
|
|
)
|
|
.await;
|
|
let client = reqwest::Client::new();
|
|
let r = request(&client, &g, json!({"model":"d0","stream":true,"input":"x"}))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
let mut stream = r.bytes_stream();
|
|
assert!(stream.next().await.unwrap().is_ok());
|
|
drop(stream);
|
|
tokio::time::timeout(Duration::from_secs(2), async {
|
|
loop {
|
|
let s = status(&client, &g).await;
|
|
if s["pool"]["workers"][0]["ready"] == false {
|
|
assert_eq!(s["pool"]["active"], 0);
|
|
break;
|
|
}
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
|
}
|
|
})
|
|
.await
|
|
.unwrap();
|
|
}
|