Files
leleka/control-plane/src/server_api/model_busy.rs
T
Pavlo Ratushnyi 705125f858 STRA-338 S21: Clock in three more handlers, gateway-track report and ports doc
server_api::{ensure_loaded, model_busy, load_post} stamp last_activity from state.services.clock instead of
tokio::time::Instant::now() (instant-now:strata-control 34 -> 31; SystemClock returns the same value). The baseline is
tightened. docs/experiments/stra-338-gateway-track.md records the commands, the per-step test-outcome comparison (Linux:
597 ok before, 615 ok after, 0 changed, 0 missing), the gate movement and what was not done;
docs/architecture/gateway-ports.md shows the AppState groups and the domain crate.
2026-11-05 20:49:47 +01:00

205 lines
7.7 KiB
Rust

//! Moved out of the parent module by STRA-338: fn model_busy, fn v1_unload, fn v1_load, fn v1_reconfigure, fn api_requests, fn not_found ....
#[allow(unused_imports)]
use super::*;
pub(super) fn model_busy() -> Response {
reply(
StatusCode::CONFLICT,
error_body(Some("model_busy"), "a request is running or queued"),
)
}
pub async fn v1_unload(State(state): State<AppState>, headers: HeaderMap, body: Bytes) -> Response {
if let Err(response) = model_control_prelude(&state, &headers, &body) {
return *response;
}
let outcome = unload(&state, None).await;
if outcome == Outcome::Busy {
return model_busy();
}
let mut value = status_value(&state).await;
value["status"] = json!(outcome.as_str());
reply(StatusCode::OK, value)
}
pub async fn v1_load(State(state): State<AppState>, headers: HeaderMap, body: Bytes) -> Response {
if let Err(response) = model_control_prelude(&state, &headers, &body) {
return *response;
}
{
let worker = state.engine.worker.read().await;
if is_busy(&state, &worker) {
return model_busy();
}
}
state.engine.worker.write().await.last_activity = Some(state.services.clock.now());
if state.engine.worker.read().await.state != WorkerState::Ready
&& let Err(error) = load(&state).await
{
return load_error_response(&error);
}
let mut value = status_value(&state).await;
value["status"] = json!("loaded");
reply(StatusCode::OK, value)
}
/// `POST /v1/reconfigure`: change the inference settings of the running engine without reloading the model (context length,
/// prefix cache, prefill chunk, CPU workers...). The body is a JSON object with any of: `context_tokens`, `prefill_capacity`,
/// `kv_resident` (only the value in force), `prefix_cache_mib`, `prefix_cache_tail`, `prefix_cache_block`, `prefix_retention_min`,
/// `cpu_workers` (1..=15), `spec_min_p`. The call waits for the request in flight, the engine reopens its serve stack (about 7 s on
/// the 5090; requests meanwhile wait in the queue) and the answer carries the effective settings; a refused change leaves the
/// previous settings in place.
pub async fn v1_reconfigure(
State(state): State<AppState>,
headers: HeaderMap,
body: Bytes,
) -> Response {
if let Err(response) = own_page_check(&state, &headers, "the engine settings can be changed") {
return *response;
}
let parsed: Result<Value, _> = serde_json::from_slice(&body);
let Ok(settings) = parsed else {
return reply(
StatusCode::BAD_REQUEST,
error_body(
Some("invalid_request_error"),
"send a JSON object of settings",
),
);
};
if !settings.is_object() {
return reply(
StatusCode::BAD_REQUEST,
error_body(
Some("invalid_request_error"),
"send a JSON object of settings",
),
);
}
let Some(control) = &state.engine.control else {
return reply(
StatusCode::NOT_IMPLEMENTED,
error_body(None, "this server has no engine to reconfigure"),
);
};
let (answer, response) = tokio::sync::oneshot::channel();
if control
.send(Control::Reconfigure {
settings: settings.to_string(),
reply: answer,
})
.await
.is_err()
{
return reply(
StatusCode::SERVICE_UNAVAILABLE,
error_body(None, "the worker is gone"),
);
}
match tokio::time::timeout(std::time::Duration::from_secs(1900), response).await {
Ok(Ok(Ok(effective))) => {
let settings: Value = serde_json::from_str(&effective).unwrap_or(Value::Null);
reply(
StatusCode::OK,
json!({"status": "reconfigured", "settings": settings}),
)
}
Ok(Ok(Err((status, message)))) => reply(
StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
error_body(Some("reconfigure_refused"), &message),
),
_ => reply(
StatusCode::GATEWAY_TIMEOUT,
error_body(None, "the engine did not answer the reconfigure in time"),
),
}
}
/// `GET /api/requests`: the request monitor (`api_monitor` in the config; 404 while it is off, as in the Original). Without
/// `id` the retained requests, newest first, without prompts and answers; with `?id=` one whole record, or 404 once evicted.
pub async fn api_requests(State(state): State<AppState>, RawQuery(query): RawQuery) -> Response {
if !state.services.monitor.enabled() {
return not_found().await;
}
let id = query.as_deref().and_then(|query| {
query
.split('&')
.find_map(|pair| pair.strip_prefix("id=").map(|id| id.to_owned()))
});
if let Some(id) = id {
return match state.services.monitor.detail(&id) {
Some(record) => reply(StatusCode::OK, record),
None => reply(
StatusCode::NOT_FOUND,
error_body(None, "request no longer retained"),
),
};
}
let worker = *state.engine.worker.read().await;
reply(
StatusCode::OK,
json!({"requests": state.services.monitor.summaries(), "retention": crate::request_monitor::RETENTION, "persistent": false,
"loaded": is_loaded(&worker), "auto_load": state.engine.control.is_some()}),
)
}
/// Unknown paths: a JSON error, like the Original's `{"error": {"message": "not found"}}`.
pub async fn not_found() -> Response {
reply(StatusCode::NOT_FOUND, error_body(None, "not found"))
}
// ------------------------------------------------------------------------------------------------ CORS
/// CORS for `/v1/*` (config `cors_origins`) and the preflight: the outermost layer, so a browser's
/// credential-less `OPTIONS` is answered before authentication, as the Original does.
pub async fn cors_layer(State(cors): State<Arc<Cors>>, request: Request, next: Next) -> Response {
let target = request.uri().path_and_query().map_or_else(
|| request.uri().path().to_owned(),
|p| p.as_str().to_owned(),
);
let headers = cors.headers(
&target,
header_str(request.headers(), "origin"),
header_str(request.headers(), "access-control-request-headers"),
);
let mut response = if request.method() == Method::OPTIONS {
let mut response = StatusCode::NO_CONTENT.into_response();
response
.headers_mut()
.insert(header::CONTENT_LENGTH, HeaderValue::from_static("0"));
response
} else {
next.run(request).await
};
for (name, value) in headers {
if let (Ok(name), Ok(value)) = (
HeaderName::from_bytes(name.as_bytes()),
HeaderValue::from_str(&value),
) {
response.headers_mut().insert(name, value);
}
}
response
}
/// `GET /mcp`: the configured MCP servers, their state and tools (empty when there are none).
pub async fn mcp_status(State(state): State<AppState>) -> Response {
let body = match &state.services.mcp {
Some(hub) => hub.status().await,
None => json!({"servers": [], "tools": 0}),
};
reply(StatusCode::OK, body)
}
/// `machine` of `GET /v1/status`: the engine's telemetry (GPU load and VRAM, RAM, CPU cores, throughput, cache hits, context)
/// when it reports any; the legacy `{at, gpu, ram}` shape with nulls otherwise.
pub(super) fn machine_view(memory: &crate::memory_view::MemoryView) -> Value {
let mut view = memory.telemetry_status();
if !view.is_object() {
return json!({"at": now_s(), "gpu": null, "ram": null});
}
view["at"] = json!(now_s());
view
}