AppState (app/state.rs) is now lifecycle + EngineLink (client port, control channel, worker status, pool, queue timeout) + HttpPolicy (api key, CORS, trusted origins) + ModelView (name, aliases, tokenizer, template, vision port, prefix-cache and memory views) + Services (response store, monitor, MCP port, settings, clock, started_at). Field uses were rewritten mechanically (state.worker -> state.engine.worker, ...); no handler logic changed. The old impl_default_for_appstate.rs, which held the route table and the admin handlers, is app/routes.rs, app/admin_routes.rs and app/readiness.rs. main.rs (1156 lines: an 840-line argument match, the serve function, two helpers) is now 8 lines. The argument match is split into command groups under src/cli/ (operations, model_fetch, model_inspect, model_ensure, model_prepare, kar_inspect, kar_verify, kar_overlay, model_text; each owns its arms in their old order and answers Ok(false) for a line it does not own), serve() and shutdown_signal() are src/serve.rs (the composition root), the usage text is cli/usage.rs. The binary name and every command line are unchanged. Architecture gate: control-plane/src/main.rs leaves the oversize list (1156 -> 8). --allow-increase was used because the type change forces the AppState struct literals in seven already-oversize test/example files to nest by group: cp_replay.rs +7, responses/tests.rs +11, backend_worker_http.rs +14, mcp_hub.rs +3, memory_gate_http.rs +7, vision_http.rs +6, desktop-core api_over_runtime.rs +6 (55 lines in all, against 1148 lines removed from main.rs). Test outcomes are unchanged (597 ok / 2 ignored before and after, 14 new tests from S16).
346 lines
14 KiB
Rust
346 lines
14 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, EngineLink, HttpPolicy, ModelView, Services, 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 {
|
|
engine: EngineLink {
|
|
worker: status,
|
|
client: Some(strata_control::adapters::ChannelEngine::shared(requests)),
|
|
control: Some(control),
|
|
..Default::default()
|
|
},
|
|
http: HttpPolicy {
|
|
cors: Arc::new(Cors::new(strings("cors_origins"))),
|
|
trusted_origins: Arc::new(strings("trusted_origins")),
|
|
api_key,
|
|
},
|
|
model: ModelView {
|
|
name: Some(setup["model"].as_str().unwrap_or("strata-test").to_owned()),
|
|
aliases: Arc::new(strings("aliases")),
|
|
..Default::default()
|
|
},
|
|
services: Services {
|
|
settings: Arc::new(settings),
|
|
..Default::default()
|
|
},
|
|
..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.engine.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.engine.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.engine.worker.read().await.state == WorkerState::Ready;
|
|
assert_eq!(
|
|
loaded,
|
|
step["state"]["loaded"].as_bool().unwrap(),
|
|
"{context}: loaded"
|
|
);
|
|
assert_eq!(
|
|
harness.state.services.settings.shared().to_json(),
|
|
step["state"]["shared"],
|
|
"{context}: shared settings"
|
|
);
|
|
compared += 1;
|
|
}
|
|
harness.finish().await;
|
|
}
|
|
assert!(compared > 120, "{compared} compared, {skipped} skipped");
|
|
}
|