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.
231 lines
7.8 KiB
Rust
231 lines
7.8 KiB
Rust
//! Moved out of the parent module by STRA-338: fn error_body, fn reply, fn now_s, fn header_str, fn is_loaded, fn is_busy ....
|
|
|
|
#[allow(unused_imports)]
|
|
use super::*;
|
|
|
|
pub(super) fn error_body(kind: Option<&str>, message: &str) -> Value {
|
|
match kind {
|
|
Some(kind) => json!({"error": {"type": kind, "message": message}}),
|
|
None => json!({"error": {"message": message}}),
|
|
}
|
|
}
|
|
|
|
pub(super) fn reply(status: StatusCode, body: Value) -> Response {
|
|
(status, Json(body)).into_response()
|
|
}
|
|
|
|
pub(super) fn now_s() -> u64 {
|
|
SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.map_or(0, |d| d.as_secs())
|
|
}
|
|
|
|
pub(super) fn header_str<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
|
|
headers.get(name).and_then(|v| v.to_str().ok())
|
|
}
|
|
|
|
pub(super) fn is_loaded(worker: &WorkerStatus) -> bool {
|
|
worker.state == WorkerState::Ready
|
|
}
|
|
|
|
/// Whether a request is running or waiting for the engine.
|
|
pub(super) fn is_busy(state: &AppState, worker: &WorkerStatus) -> bool {
|
|
worker.metrics.active_since.is_some() || state.lifecycle.snapshot().generation_jobs > 0
|
|
}
|
|
|
|
pub(super) fn context_of(worker: &WorkerStatus) -> usize {
|
|
worker.max_context.or(worker.known_max_context).unwrap_or(0)
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------ loading
|
|
|
|
/// Start the engine if it is unloaded (the Original's `Service.load`, called at the start of every
|
|
/// request). Stamps the activity time so the idle timer does not unload between this and the
|
|
/// request's own start. `Err` is a ready-made error response.
|
|
pub async fn ensure_loaded(state: &AppState) -> Result<(), Box<Response>> {
|
|
let unloaded = {
|
|
let mut worker = state.engine.worker.write().await;
|
|
worker.last_activity = Some(state.services.clock.now());
|
|
worker.state == WorkerState::Unloaded
|
|
};
|
|
if !unloaded {
|
|
return Ok(());
|
|
}
|
|
match load(state).await {
|
|
Ok(()) => Ok(()),
|
|
Err(error) => Err(Box::new(load_error_response(&error))),
|
|
}
|
|
}
|
|
|
|
/// Ask the supervisor to load and wait until it is ready.
|
|
pub async fn load(state: &AppState) -> Result<(), LoadError> {
|
|
let Some(control) = &state.engine.control else {
|
|
return Err(LoadError::Failed(
|
|
"the engine cannot be loaded on demand".into(),
|
|
));
|
|
};
|
|
let (answer, received) = oneshot::channel();
|
|
control
|
|
.send(Control::Load { reply: answer })
|
|
.await
|
|
.map_err(|_| LoadError::Failed("the server is shutting down".into()))?;
|
|
received
|
|
.await
|
|
.map_err(|_| LoadError::Failed("the server is shutting down".into()))?
|
|
}
|
|
|
|
/// `POST /unload`'s core (also the idle thread): the outcome string of the Original.
|
|
pub async fn unload(state: &AppState, idle_for: Option<Duration>) -> Outcome {
|
|
let Some(control) = &state.engine.control else {
|
|
return Outcome::Unsupported;
|
|
};
|
|
{
|
|
let worker = state.engine.worker.read().await;
|
|
if is_loaded(&worker) && is_busy(state, &worker) {
|
|
return Outcome::Busy;
|
|
}
|
|
}
|
|
let (answer, received) = oneshot::channel();
|
|
if control
|
|
.send(Control::Unload {
|
|
idle_for,
|
|
reply: answer,
|
|
})
|
|
.await
|
|
.is_err()
|
|
{
|
|
return Outcome::NotLoaded;
|
|
}
|
|
received.await.unwrap_or(Outcome::NotLoaded)
|
|
}
|
|
|
|
pub(super) fn load_error_response(error: &LoadError) -> Response {
|
|
let message = match error {
|
|
LoadError::GpuBusy(m) | LoadError::Failed(m) => m,
|
|
};
|
|
api_server_error(message)
|
|
}
|
|
|
|
pub(super) fn api_server_error(message: &str) -> Response {
|
|
reply(
|
|
StatusCode::SERVICE_UNAVAILABLE,
|
|
error_body(Some("server_error"), message),
|
|
)
|
|
}
|
|
|
|
/// The idle thread of `--idle-unload`: every `poll` seconds, give the engine back if no request ran
|
|
/// within `idle`. Returns when the control channel closes.
|
|
pub async fn idle_unload_loop(state: AppState, idle: Duration, poll: Duration) {
|
|
loop {
|
|
tokio::time::sleep(poll).await;
|
|
if state
|
|
.engine
|
|
.control
|
|
.as_ref()
|
|
.is_none_or(mpsc::Sender::is_closed)
|
|
{
|
|
return;
|
|
}
|
|
let outcome = unload(&state, Some(idle)).await;
|
|
if outcome == Outcome::Unloaded {
|
|
crate::elog!(
|
|
"model unloaded after {:.0} s idle; the next request loads it again",
|
|
idle.as_secs_f64()
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------ handlers
|
|
|
|
/// `GET /api/health` (the Python server's `/health`): who answers and whether the engine is loaded.
|
|
pub async fn api_health(State(state): State<AppState>) -> Response {
|
|
let worker = *state.engine.worker.read().await;
|
|
reply(
|
|
StatusCode::OK,
|
|
json!({"status": "ok", "max_context": context_of(&worker), "model": state.model.name,
|
|
"images": state.model.vision.is_some(), "api_key": state.http.api_key.is_some(),
|
|
"loaded": is_loaded(&worker), "service": "strata"}),
|
|
)
|
|
}
|
|
|
|
pub(super) fn model_names(state: &AppState) -> Vec<String> {
|
|
state
|
|
.model
|
|
.name
|
|
.iter()
|
|
.cloned()
|
|
.chain(state.model.aliases.iter().cloned())
|
|
.collect()
|
|
}
|
|
|
|
/// The first non-blank value of `name` (Python's `parse_qs` drops blank values).
|
|
pub(super) fn query_param(query: Option<&str>, name: &str) -> Option<String> {
|
|
query?.split('&').find_map(|pair| {
|
|
let (key, value) = pair.split_once('=')?;
|
|
(percent_decode(key) == name && !value.is_empty()).then(|| percent_decode(value))
|
|
})
|
|
}
|
|
|
|
pub(super) fn percent_decode(text: &str) -> String {
|
|
let bytes = text.as_bytes();
|
|
let mut out = Vec::with_capacity(bytes.len());
|
|
let mut i = 0;
|
|
while i < bytes.len() {
|
|
match bytes[i] {
|
|
b'+' => out.push(b' '),
|
|
b'%' if i + 2 < bytes.len() => {
|
|
match std::str::from_utf8(&bytes[i + 1..i + 3])
|
|
.ok()
|
|
.and_then(|hex| u8::from_str_radix(hex, 16).ok())
|
|
{
|
|
Some(byte) => {
|
|
out.push(byte);
|
|
i += 2;
|
|
}
|
|
None => out.push(b'%'),
|
|
}
|
|
}
|
|
byte => out.push(byte),
|
|
}
|
|
i += 1;
|
|
}
|
|
String::from_utf8_lossy(&out).into_owned()
|
|
}
|
|
|
|
/// `GET /props` (llama-server compatible): the default generation settings, the chat template and
|
|
/// what this server can do.
|
|
pub async fn props(State(state): State<AppState>, request: Request) -> Response {
|
|
let asked = query_param(request.uri().query(), "model")
|
|
.or_else(|| state.model.name.clone())
|
|
.unwrap_or_default();
|
|
if !model_names(&state).contains(&asked) {
|
|
return reply(StatusCode::NOT_FOUND, error_body(None, "model not found"));
|
|
}
|
|
let worker = *state.engine.worker.read().await;
|
|
if !is_loaded(&worker) && worker.state != WorkerState::Unloaded {
|
|
return reply(
|
|
StatusCode::SERVICE_UNAVAILABLE,
|
|
error_body(None, "the engine is not running"),
|
|
);
|
|
}
|
|
let merged = state.services.settings.merged();
|
|
let shared = state.services.settings.shared();
|
|
reply(
|
|
StatusCode::OK,
|
|
json!({
|
|
"default_generation_settings": {
|
|
"n_ctx": context_of(&worker),
|
|
"params": merged.props_params(&shared),
|
|
},
|
|
"total_slots": 1,
|
|
"model_alias": state.model.name,
|
|
"chat_template": state.model.chat_template.as_deref().unwrap_or(DEFAULT_CHAT_TEMPLATE),
|
|
"modalities": {"vision": state.model.vision.is_some()},
|
|
"models_autoload": state.engine.control.is_some(),
|
|
"is_sleeping": !is_loaded(&worker),
|
|
"build_info": format!("Strata Next {}", env!("CARGO_PKG_VERSION")),
|
|
}),
|
|
)
|
|
}
|