Files
leleka/control-plane/src/serve.rs
T
Pavlo Ratushnyi 3530208024 STRA-338 S7: AppState in four groups, app/ routes split by role, main.rs becomes a dispatcher plus the composition root
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).
2026-11-05 20:22:10 +01:00

285 lines
12 KiB
Rust

//! `strata-next serve`: the composition root. It reads the config, builds the adapters behind the gateway ports
//! (response history, MCP hub, vision encoder, engine channel, workers) and runs the HTTP server until shutdown.
use std::{path::Path, sync::Arc, time::Duration};
use tokio::sync::{mpsc, watch};
use strata_control::{BoxError, app, config::Config, tokenizer, worker};
pub async fn serve(config_path: Option<&Path>) -> Result<(), BoxError> {
let mut config = Config::load_with_path(config_path)?;
let history_dir = config.response_history_dir.clone();
let response_history = tokio::task::spawn_blocking(move || {
strata_control::responses::ResponseHistory::open(history_dir.as_deref())
})
.await??;
config.check_host().await?;
let _embedded = match config.worker.as_mut() {
Some(worker) => {
let embedded = strata_control::embedded_engine::resolve(&worker.executable)?;
if let Some(engine) = &embedded {
worker.executable = engine.executable.clone().into_os_string();
}
embedded
}
None => None,
};
config.provision().await?;
let listener = tokio::net::TcpListener::bind(config.bind).await?;
let mut settings = strata_control::settings::Settings::new(config.sampling.clone())
.with_reasoning_budget(config.reasoning_budget_tokens.clone());
if let Some(path) = config.shared_settings_file.clone() {
settings = settings.with_shared_file(path);
}
let mut state = app::AppState {
lifecycle: strata_control::lifecycle::Lifecycle::new(config.max_in_flight_requests)?,
engine: app::EngineLink {
queue_timeout: config.queue_timeout,
..Default::default()
},
http: app::HttpPolicy {
api_key: config.api_key.clone(),
cors: Arc::new(leleka_serving_policy::cors::Cors::new(
config.cors_origins.clone(),
)),
trusted_origins: Arc::new(config.trusted_origins.clone()),
},
model: app::ModelView {
name: config.model.clone(),
aliases: Arc::new(config.aliases.clone()),
..Default::default()
},
services: app::Services {
responses: strata_control::responses::HistoryResponseStore::shared(response_history),
settings: Arc::new(settings),
monitor: Arc::new(strata_control::request_monitor::RequestMonitor::new(
config.api_monitor,
)),
..Default::default()
},
};
if !config.mcp_servers.is_empty() {
let hub = Arc::new(strata_control::mcp::Hub::new(
std::mem::take(&mut config.mcp_servers),
config.mcp_settings.clone(),
));
state.services.mcp = Some(hub.clone());
// Servers start in the background (npx may download a package first); GET /mcp shows progress.
tokio::spawn(async move { hub.start().await });
}
if config.cors_origins.iter().any(|o| o == "*") && config.api_key.is_none() {
strata_control::elog!(
"CORS on /v1/*: WARNING: any web page may use the model (no API key)"
);
}
if let Some(path) = config.tokenizer_dir.as_deref() {
state.model.tokenizer = Some(Arc::new(strata_control::codec::qwen_codec(
tokenizer::Tokenizer::from_assets(path)?,
)));
state.model.chat_template = std::fs::read_to_string(path.join("chat_template.jinja"))
.ok()
.map(Arc::from);
}
if let Some(path) = config.gptoss_gguf.as_deref() {
state.model.tokenizer = Some(Arc::new(
strata_control::harmony_family::GptOssCodec::from_gguf(path)?,
));
}
// The image encoder starts before the engine: a GPU encoder takes its VRAM first, and the engine sizes its
// cache from what is left.
let mut vision_process = None;
if let Some(vision) = config.vision.take() {
strata_control::elog!("loading the vision encoder ...");
let process = strata_control::vision::Vision::start(vision).await?;
state.model.vision = Some(process.clone());
vision_process = Some(process);
}
let (shutdown_tx, shutdown_rx) = watch::channel(false);
if config.prompt_date != strata_control::responses::PromptDate::Utc {
strata_control::elog!(
"prompt date {:?} (the system message's Current date line; experimental unless a fixed date)",
config.prompt_date
);
}
strata_control::responses::set_prompt_date(config.prompt_date.clone());
if config.tool_call_recovery {
strata_control::elog!(
"tool_call_recovery is ON (experimental): a declared tool's call written in a drifted form is run as that call; see docs/api-contract.md"
);
}
strata_control::responses::set_tool_call_recovery(config.tool_call_recovery);
let runtime_task = match config.runtime.take() {
Some(runtime) => {
// The runtime backend is the Qwen path: the gpt-oss family has no runtime block (config rejects the mix).
let tokenizer = state
.model
.tokenizer
.as_ref()
.and_then(|codec| codec.qwen())
.cloned()
.ok_or("runtime requires the tokenizer assets (runtime.tokenizer_dir)")?;
let receiver = state.attach_engine(16);
let (control_sender, control_receiver) = mpsc::channel(16);
state.engine.control = Some(control_sender);
state.engine.worker.write().await.known_max_context = Some(runtime.max_context);
let backend = leleka_runtime_client::backend::GrpcBackend::new(
tokio::runtime::Handle::current(),
runtime.address,
runtime.token,
);
let worker_config = strata_control::backend_worker::BackendWorkerConfig {
tokenizer,
model: runtime.model,
runtime: runtime.runtime,
max_context: runtime.max_context,
max_output_tokens: runtime.max_output_tokens,
generation_timeout: runtime.generation_timeout,
stall_timeout: runtime.stall_timeout,
attach_retry: runtime.attach_retry,
health_interval: runtime.health_interval,
cancel_drain_timeout: Duration::from_secs(20),
prefix_view: Some(state.model.prefix_cache.clone()),
memory_view: Some(state.model.memory.clone()),
};
Some(tokio::spawn(
strata_control::backend_worker::run_backend_worker(
Box::new(backend),
worker_config,
state.engine.worker.clone(),
shutdown_rx.clone(),
receiver,
control_receiver,
),
))
}
None => None,
};
let extra_workers = std::mem::take(&mut config.extra_workers);
let mut dispatcher = None;
let worker_tasks: Vec<_> = match config.worker {
None => Vec::new(),
Some(mut main) if extra_workers.is_empty() => {
main.vision = vision_process.clone();
let receiver = state.attach_engine(16);
let (control_sender, control_receiver) = mpsc::channel(16);
state.engine.control = Some(control_sender);
vec![tokio::spawn(worker::run_supervised(
main,
state.engine.worker.clone(),
shutdown_rx,
receiver,
control_receiver,
))]
}
Some(main) => {
// several workers behind one channel (experimental): the first reports the service status and metrics.
// The pool has no administrative channel (no load/unload/control vector) and no vision: config rejects
// those combinations.
let receiver = state.attach_engine(16);
let mut members = Vec::new();
let mut tasks = Vec::new();
for (index, config) in std::iter::once(main).chain(extra_workers).enumerate() {
let status = if index == 0 {
state.engine.worker.clone()
} else {
Arc::new(tokio::sync::RwLock::new(worker::WorkerStatus::default()))
};
state.engine.pool.push(status.clone());
let (requests, received) = mpsc::channel(1);
tasks.push(tokio::spawn(worker::run_with_requests(
config,
status.clone(),
shutdown_rx.clone(),
received,
)));
members.push(strata_control::pool::Member { requests, status });
}
strata_control::elog!("{} workers in a pool", members.len());
dispatcher = Some(tokio::spawn(strata_control::pool::dispatch(
receiver, members,
)));
tasks
}
};
if let (Some(idle), true) = (config.idle_unload, state.engine.control.is_some()) {
strata_control::elog!(
"the model unloads after {} s without requests",
idle.as_secs_f64()
);
let poll = Duration::from_secs_f64(leleka_serving_policy::idle::poll_interval_s(
idle.as_secs_f64(),
));
tokio::spawn(strata_control::server_api::idle_unload_loop(
state.clone(),
idle,
poll,
));
}
strata_control::elog!("strata-control listening on {}", listener.local_addr()?);
let server_shutdown = shutdown_tx.clone();
let state_mcp = state.services.mcp.clone();
let lifecycle = state.lifecycle.clone();
let shutdown_grace = config.shutdown_grace;
// TCP_NODELAY: SSE events and small responses must not wait for the peer's delayed ACK (Nagle's algorithm).
use axum::serve::ListenerExt as _;
let listener = listener.tap_io(|tcp| {
let _ = tcp.set_nodelay(true);
});
let result = axum::serve(listener, app::router(state))
.with_graceful_shutdown(async move {
shutdown_signal().await;
lifecycle.begin_shutdown();
if !shutdown_grace.is_zero() && !lifecycle.wait_drained(shutdown_grace).await {
strata_control::elog!("Shutdown admission grace expired; stopping worker");
}
let _ = server_shutdown.send(true);
})
.await;
let _ = shutdown_tx.send(true);
if let Some(hub) = &state_mcp {
hub.close().await;
}
if let Some(vision) = &vision_process {
vision.close().await;
}
for task in worker_tasks {
task.await?;
}
if let Some(dispatcher) = dispatcher {
// its workers have stopped; requests still held by API handlers must not keep it waiting
dispatcher.abort();
}
if let Some(task) = runtime_task {
task.await?;
}
result?;
Ok(())
}
async fn shutdown_signal() {
#[cfg(unix)]
{
use tokio::signal::unix::{SignalKind, signal};
let mut terminate = signal(SignalKind::terminate()).expect("install SIGTERM handler");
tokio::select! {
_ = tokio::signal::ctrl_c() => {},
_ = terminate.recv() => {},
}
}
#[cfg(windows)]
{
// Ctrl-Break is how `leleka run` stops its children on Windows (they run in their own process groups).
let mut break_signal =
tokio::signal::windows::ctrl_break().expect("install Ctrl-Break handler");
tokio::select! {
result = tokio::signal::ctrl_c() => { result.expect("install Ctrl-C handler"); },
_ = break_signal.recv() => {},
}
}
#[cfg(not(any(unix, windows)))]
tokio::signal::ctrl_c()
.await
.expect("install Ctrl-C handler");
}