Files
leleka/control-plane/tests/http_surface.rs
T

335 lines
13 KiB
Rust

#![cfg(unix)] // the engine stand-in is a /bin/sh script
//! The operational HTTP surface (`/props`, `/slots`, `/settings`, `/load`, `/unload`, `/v1/load`,
//! `/v1/unload`, `/v1/status`, `/api/health`, CORS, own-page guard) against the real Python
//! handlers: every scenario in `tests/fixtures/golden/http_surface.json` was recorded from
//! `engine/strata/serve/server.py` by `tests/golden/gen_goldens.py http`, and is replayed here
//! against the Rust router with a real worker supervisor and the mock engine.
//!
//! Deliberate differences, skipped in the comparison: the chat template text, the build/version
//! strings, wall-clock fields, JSON parser error wording, the extra `/v1/responses` dialect, and
//! `x-api-key` (the Rust server accepts it on the Messages routes only).
use std::{path::PathBuf, sync::Arc, time::Duration};
use leleka_serving_policy::{cors::Cors, shared::sampling_defaults_from_config};
use serde_json::{Value, json};
use strata_control::{
app::{AppState, router},
lifecycle::Guard,
settings::Settings,
worker::{WorkerConfig, WorkerState, WorkerStatus, run_supervised},
};
use tokio::sync::{RwLock, mpsc, watch};
struct Harness {
base: String,
state: AppState,
stop: watch::Sender<bool>,
worker: tokio::task::JoinHandle<()>,
server: tokio::task::JoinHandle<()>,
dir: PathBuf,
_guards: Vec<Guard>,
}
impl Harness {
async fn start(name: &str, setup: &Value) -> Self {
let dir = std::env::temp_dir().join(format!("strata-http-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let context = setup["max_context"].as_u64().unwrap_or(4096);
let loaded = setup["loaded"].as_bool().unwrap_or(true);
let engine =
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mock_engine.sh");
let config = WorkerConfig {
executable: engine.into_os_string(),
args: vec![
"lifecycle".into(),
dir.to_string_lossy().into_owned(),
context.to_string(),
"--max-context".into(),
context.to_string(),
],
startup_timeout: Duration::from_secs(10),
lazy: !loaded,
..Default::default()
};
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop, stop_rx) = watch::channel(false);
let (requests, requests_rx) = mpsc::channel(4);
let (control, control_rx) = mpsc::channel(4);
let worker = tokio::spawn(run_supervised(
config,
status.clone(),
stop_rx,
requests_rx,
control_rx,
));
let config_sampling =
sampling_defaults_from_config(setup.get("config_sampling").unwrap_or(&Value::Null))
.unwrap();
let settings = Settings::new(config_sampling);
if let Some(shared) = setup.get("shared") {
settings.set_shared(shared).unwrap();
}
let strings = |key: &str| -> Vec<String> {
setup[key]
.as_array()
.map(|a| a.iter().map(|v| v.as_str().unwrap().to_owned()).collect())
.unwrap_or_default()
};
let api_key = setup["api_key"]
.as_str()
.filter(|k| !k.is_empty())
.map(|key| {
let path = dir.join("api-key");
std::fs::write(&path, key).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
.unwrap();
}
Arc::new(strata_control::auth::ApiKey::from_file(&path).unwrap())
});
let state = AppState {
model: Some(setup["model"].as_str().unwrap_or("strata-test").to_owned()),
worker: status,
generation: Some(requests),
control: Some(control),
settings: Arc::new(settings),
aliases: Arc::new(strings("aliases")),
cors: Arc::new(Cors::new(strings("cors_origins"))),
trusted_origins: Arc::new(strings("trusted_origins")),
api_key,
..Default::default()
};
// The Python scenarios mark a request as running/queued through its status dict.
let mut guards = Vec::new();
if let Some(status_setup) = setup.get("status") {
let busy = status_setup["busy"].as_bool().unwrap_or(false);
let queued = status_setup["queued"].as_u64().unwrap_or(0);
if busy {
state.worker.write().await.metrics.start();
}
for _ in 0..(queued + u64::from(busy)) {
guards.push(state.lifecycle.generation());
}
}
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let app = router(state.clone());
let server = tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
let wanted = if loaded {
WorkerState::Ready
} else {
WorkerState::Unloaded
};
tokio::time::timeout(Duration::from_secs(10), async {
while state.worker.read().await.state != wanted {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("worker state");
Self {
base,
state,
stop,
worker,
server,
dir,
_guards: guards,
}
}
async fn finish(self) {
self.server.abort();
self.stop.send(true).unwrap();
let _ = tokio::time::timeout(Duration::from_secs(25), self.worker).await;
let _ = std::fs::remove_dir_all(self.dir);
}
}
fn fixture() -> Value {
serde_json::from_str(include_str!("fixtures/golden/http_surface.json")).unwrap()
}
/// Remove what is allowed to differ and return the rest.
fn normalized(path: &str, mut value: Value) -> Value {
let path = path.split('?').next().unwrap();
let remove = |value: &mut Value, keys: &[&str]| {
if let Some(map) = value.as_object_mut() {
for key in keys {
map.remove(*key);
}
}
};
match path {
// Both servers list the model and its aliases; the Python records carry llama-server extras.
"/v1/models" | "/models" => {
let reduced: Vec<Value> = value["data"]
.as_array()
.into_iter()
.flatten()
.map(|record| {
json!({"id": record["id"], "alias_of": record["alias_of"],
"aliases": record["aliases"],
"status": record["status"]["value"].as_str().unwrap_or("loaded")})
})
.collect();
value = json!({"data": reduced});
}
// `/health` stays the minimal liveness body of the existing smoke contract; `/api/health`
// carries the Python fields.
"/health" => value = json!({"status": value["status"]}),
"/props" => remove(&mut value, &["chat_template", "build_info", "model_path"]),
"/v1/status" | "/v1/load" | "/v1/unload" => {
remove(
&mut value,
&[
"engine",
"started",
"uptime_s",
"machine",
"dialects",
"last_timings",
// Rust-only extensions (docs/prefix-cache.md, docs/memory-safety.md)
"prefix_cache",
"memory",
],
);
if let Some(activity) = value.get_mut("activity") {
remove(activity, &["last_request_at"]);
}
}
_ => {}
}
value
}
/// The Python server forwards its JSON parser's message; the Rust parser words it differently.
fn is_parser_message(status: u64, body: &Value) -> bool {
status == 400
&& body["error"]["message"]
.as_str()
.is_some_and(|m| m.contains("line 1 column") || m.contains("Expecting"))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_rust_surface_answers_like_the_python_server() {
let fixture = fixture();
let scenarios = fixture["scenarios"].as_object().unwrap();
assert!(scenarios.len() >= 17);
let client = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap();
let mut compared = 0;
let mut skipped = 0;
for (name, scenario) in scenarios {
let harness = Harness::start(name, &scenario["setup"]).await;
for (index, step) in scenario["steps"].as_array().unwrap().iter().enumerate() {
let request = &step["request"];
let method = request["method"].as_str().unwrap();
let path = request["path"].as_str().unwrap();
let context = format!("{name} step {index}: {method} {path}");
let headers = request["headers"].as_object().cloned().unwrap_or_default();
if headers.keys().any(|k| k.eq_ignore_ascii_case("x-api-key")) {
skipped += 1;
continue;
}
let mut builder = client.request(
reqwest::Method::from_bytes(method.as_bytes()).unwrap(),
format!("{}{path}", harness.base),
);
let mut has_content_type = false;
for (key, value) in &headers {
has_content_type |= key.eq_ignore_ascii_case("content-type");
builder = builder.header(key.as_str(), value.as_str().unwrap());
}
match &request["body"] {
Value::Null => {}
Value::String(raw) => builder = builder.body(raw.clone()),
other => {
if !has_content_type {
builder = builder.header("content-type", "application/json");
}
builder = builder.body(other.to_string());
}
}
let response = builder
.send()
.await
.unwrap_or_else(|e| panic!("{context}: {e}"));
let status = response.status().as_u16();
let got_headers: Vec<(String, String)> = response
.headers()
.iter()
.filter(|(k, _)| k.as_str().starts_with("access-control-") || k.as_str() == "vary")
.map(|(k, v)| (k.as_str().to_owned(), v.to_str().unwrap().to_owned()))
.collect();
let text = response.text().await.unwrap();
let got_body: Value = if text.is_empty() {
Value::Null
} else {
serde_json::from_str(&text).unwrap_or(Value::String(text))
};
assert_eq!(
u64::from(status),
step["status"].as_u64().unwrap(),
"{context}: {got_body}"
);
let want_headers = step["headers"].as_object().unwrap();
assert_eq!(
got_headers.len(),
want_headers.len(),
"{context}: {got_headers:?}"
);
for (key, value) in want_headers {
assert!(
got_headers
.iter()
.any(|(k, v)| k == key && v == value.as_str().unwrap()),
"{context}: header {key}: {got_headers:?}"
);
}
if status == 401 {
// The Rust server's authentication body is its own (OpenAI-style code and message).
assert_eq!(
got_body["error"]["type"], step["body"]["error"]["type"],
"{context}"
);
} else if is_parser_message(step["status"].as_u64().unwrap(), &step["body"]) {
assert_eq!(
got_body["error"]["type"], step["body"]["error"]["type"],
"{context}"
);
skipped += 1;
} else {
let want_path = path.split('?').next().unwrap();
let want_body = normalized(want_path, step["body"].clone());
let got_body = normalized(want_path, got_body);
assert_eq!(got_body, want_body, "{context}");
}
let loaded = harness.state.worker.read().await.state == WorkerState::Ready;
assert_eq!(
loaded,
step["state"]["loaded"].as_bool().unwrap(),
"{context}: loaded"
);
assert_eq!(
harness.state.settings.shared().to_json(),
step["state"]["shared"],
"{context}: shared settings"
);
compared += 1;
}
harness.finish().await;
}
assert!(compared > 120, "{compared} compared, {skipped} skipped");
}