The request middleware, the backend worker and the metrics handler now share one RequestMetrics value that Services holds, so the LazyLock registry of request_log.rs and its architecture.json exception are gone. The middleware gets it through Observe, the worker through BackendWorkerConfig, and prometheus::render takes it as an argument; the counters, histograms, labels and log lines are unchanged, and the unit tests now count into a registry of their own instead of one shared by the whole test process.
146 lines
5.7 KiB
Rust
146 lines
5.7 KiB
Rust
//! The state every handler shares, grouped by responsibility (STRA-338 S7). A group is a small struct of
|
|
//! related handles; ports (`crate::ports`) are held as trait objects, never as the concrete adapter.
|
|
|
|
use std::{sync::Arc, time::SystemTime};
|
|
|
|
use tokio::sync::{RwLock, mpsc};
|
|
|
|
use crate::{
|
|
adapters::{ChannelEngine, SystemClock},
|
|
codec::TextCodec,
|
|
ports::{SharedClock, SharedEngine, SharedResponseStore, SharedToolHub, SharedVisionEncoder},
|
|
responses,
|
|
worker::{Control, GenerationCommand, WorkerStatus},
|
|
};
|
|
|
|
#[derive(Clone, Default)]
|
|
pub struct AppState {
|
|
/// Admission, drain and the in-flight count (also the `/v1/responses` admission middleware).
|
|
pub lifecycle: crate::lifecycle::Lifecycle,
|
|
/// The engine side: where generations go, how it is doing, and how to load/unload it.
|
|
pub engine: EngineLink,
|
|
/// Who may call the API: the key, the browser origins.
|
|
pub http: HttpPolicy,
|
|
/// The model as clients see it: its names, tokenizer, template and the engine's published views of it.
|
|
pub model: ModelView,
|
|
/// Stores and process-wide services: stored Responses, the request monitor, MCP, settings, the clock.
|
|
pub services: Services,
|
|
}
|
|
|
|
/// The engine side of the gateway.
|
|
#[derive(Clone)]
|
|
pub struct EngineLink {
|
|
/// The port generations are submitted to; `None` until a worker is configured.
|
|
pub client: Option<SharedEngine>,
|
|
/// Administrative channel to the worker supervisor (load/unload); `None` without a worker.
|
|
pub control: Option<mpsc::Sender<Control>>,
|
|
pub worker: Arc<RwLock<WorkerStatus>>,
|
|
/// With a worker pool, the status of every member (the first is `worker`); empty otherwise.
|
|
pub pool: Vec<Arc<RwLock<WorkerStatus>>>,
|
|
/// Longest a request may wait for the engine to claim it (`queue_timeout` in the config).
|
|
pub queue_timeout: Option<std::time::Duration>,
|
|
}
|
|
|
|
/// Who may call the API.
|
|
#[derive(Clone)]
|
|
pub struct HttpPolicy {
|
|
pub api_key: Option<Arc<crate::auth::ApiKey>>,
|
|
/// Browser pages of these origins may call `/v1/*`.
|
|
pub cors: Arc<leleka_serving_policy::cors::Cors>,
|
|
/// Origins that count as this server's own page for `/settings` and `/v1/load|unload`.
|
|
pub trusted_origins: Arc<Vec<String>>,
|
|
}
|
|
|
|
/// The model as clients see it.
|
|
#[derive(Clone)]
|
|
pub struct ModelView {
|
|
pub name: Option<String>,
|
|
/// Other names of the model (`aliases` in the config), answered like the model's own.
|
|
pub aliases: Arc<Vec<String>>,
|
|
pub tokenizer: Option<Arc<dyn TextCodec>>,
|
|
/// Source of the model's chat template, served by `/props`.
|
|
pub chat_template: Option<Arc<str>>,
|
|
/// The resident image encoder (`vision` in the config); `None`: this server cannot read images.
|
|
pub vision: Option<SharedVisionEncoder>,
|
|
/// The engine's prefix-cache summary for a pool router (`GET /v1/status`, `POST /v1/prefix_match`).
|
|
pub prefix_cache: Arc<crate::prefix_view::PrefixView>,
|
|
/// The engine's memory-governor report: the pressure gate and the numbers behind `GET /v1/status` `memory`.
|
|
pub memory: Arc<crate::memory_view::MemoryView>,
|
|
/// What a gpt-oss system message says about the date (`prompt_date` in the config).
|
|
pub prompt_date: crate::responses::PromptDate,
|
|
}
|
|
|
|
/// Stores and process-wide services.
|
|
#[derive(Clone)]
|
|
pub struct Services {
|
|
/// Stored Responses (`store`, `previous_response_id`, `GET/DELETE /v1/responses/{id}`).
|
|
pub responses: SharedResponseStore,
|
|
/// The API request monitor (`api_monitor` in the config; off by default): `GET /api/requests`.
|
|
pub monitor: Arc<crate::request_monitor::RequestMonitor>,
|
|
/// The MCP servers configured for the operator (`GET /mcp`).
|
|
pub mcp: Option<SharedToolHub>,
|
|
pub settings: Arc<crate::settings::Settings>,
|
|
/// The request counters and histograms that `/metrics` renders: written by the request middleware and the worker.
|
|
pub request_metrics: Arc<crate::request_log::RequestMetrics>,
|
|
/// Wall and monotonic time: queue deadlines, uptime, response timestamps.
|
|
pub clock: SharedClock,
|
|
pub started_at: SystemTime,
|
|
}
|
|
|
|
impl AppState {
|
|
/// Give the state a command channel of `capacity` places as its engine; the worker side reads the receiver.
|
|
pub fn attach_engine(&mut self, capacity: usize) -> mpsc::Receiver<GenerationCommand> {
|
|
let (client, receiver) = ChannelEngine::channel(capacity, self.services.clock.clone());
|
|
self.engine.client = Some(client);
|
|
receiver
|
|
}
|
|
}
|
|
|
|
impl Default for EngineLink {
|
|
fn default() -> Self {
|
|
Self {
|
|
client: None,
|
|
control: None,
|
|
worker: Arc::new(RwLock::new(WorkerStatus::default())),
|
|
pool: Vec::new(),
|
|
queue_timeout: None,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Default for HttpPolicy {
|
|
fn default() -> Self {
|
|
Self { api_key: None, cors: Arc::new(Default::default()), trusted_origins: Arc::new(Vec::new()) }
|
|
}
|
|
}
|
|
|
|
impl Default for ModelView {
|
|
fn default() -> Self {
|
|
Self {
|
|
name: None,
|
|
aliases: Arc::new(Vec::new()),
|
|
tokenizer: None,
|
|
chat_template: None,
|
|
vision: None,
|
|
prefix_cache: Arc::new(Default::default()),
|
|
memory: Arc::new(Default::default()),
|
|
prompt_date: crate::responses::PromptDate::Utc,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Default for Services {
|
|
fn default() -> Self {
|
|
let clock = SystemClock::shared();
|
|
Self {
|
|
responses: responses::HistoryResponseStore::shared(responses::ResponseHistory::default()),
|
|
monitor: Arc::new(Default::default()),
|
|
mcp: None,
|
|
settings: Arc::new(crate::settings::Settings::default()),
|
|
request_metrics: Arc::default(),
|
|
started_at: clock.system_time(),
|
|
clock,
|
|
}
|
|
}
|
|
}
|