Files
leleka/desktop-core/src/node.rs
T
Pavlo Ratushnyi 7bfd821019 STRA-338 size-fn2: desktop-core production functions within the limits (hardware::inventory, node respond, node_connection::session, node_proxy::respond, planner::plan, Pool::new, ToolResponse::complete/preflight; desktop-core fn>30 20 -> 0, cx>10 -> 0, wide 13 -> 0); validate() of the Responses request split into one check per field
Each helper does one action and is named verb+object (sample_host, add_nvidia_accelerators, check_pool_bounds, index_groups,
subscribe, publish_ready, follow_updates, respond_request, refusal_status, read_headers, relay_body, build_response,
publish_text, publish_call, terminal_status, total_tokens, call_size ...). New modules: node/respond.rs, runtime_tool_response/preflight.rs.
Behaviour unchanged (same error texts and order). The remote probe script wraps its nvidia-smi line with a shell line
continuation (same command).
2026-11-06 21:11:51 +01:00

350 lines
13 KiB
Rust

//! Shared local/SSH node boundary. Never retries an inference request.
use crate::{gateway::Gateway, hardware, planner};
mod respond;
use axum::{Router, body::Body, http};
use futures_util::Stream;
use respond::{response_frames, response_headers};
use std::{net::SocketAddr, pin::Pin, sync::Arc, time::Duration};
use subtle::ConstantTimeEq;
use tokio::sync::{Mutex, Semaphore, watch};
use tokio_stream::wrappers::TcpListenerStream;
use tonic::{
Request, Response, Status,
transport::{Channel, Endpoint, Server},
};
use tower::ServiceExt;
pub mod proto {
tonic::include_proto!("strata.node.v1");
}
use proto::{
node_server::{Node, NodeServer},
*,
};
pub const MAX_MESSAGE: usize = 2 * 1024 * 1024 + 1024;
type RpcStream<T> = Pin<Box<dyn Stream<Item = Result<T, Status>> + Send>>;
#[derive(Clone)]
pub struct Agent(Arc<Inner>);
struct Inner {
token: String,
router: Option<Router>,
manager: Option<crate::managed_worker::Manager>,
state: watch::Sender<Snapshot>,
observers: Arc<Semaphore>,
responses: Arc<Semaphore>,
hardware: Mutex<Option<(std::time::Instant, hardware::Hardware)>>,
}
/// A node credential is 32..4096 printable ASCII bytes and, when there is a gateway, the gateway's own.
fn check_credential(token: &str, gateway: Option<&Gateway>) -> Result<(), String> {
if token.len() < 32 || token.len() > 4096 || !token.bytes().all(|b| b.is_ascii_graphic()) {
return Err("node credential must be 32..4096 printable ASCII bytes".into());
}
if gateway.is_some_and(|g| !g.matches_credential(token)) {
return Err("gateway and node credentials must match".into());
}
Ok(())
}
/// The capabilities an agent advertises, by what it has been given.
fn capabilities(gateway: bool, manager: Option<&crate::managed_worker::Manager>) -> Vec<String> {
let mut capabilities = vec!["hardware.v1".into(), "plan.v1".into(), "snapshot.v1".into()];
if gateway {
capabilities.push("responses.gateway.v1".into());
}
if manager.is_some_and(|m| m.durable()) {
capabilities.push("worker.journal.v1".into());
}
if manager.is_some() {
capabilities.push("worker.lifecycle.v1".into());
}
capabilities
}
impl Agent {
pub fn managed(token: String, profile: crate::managed_worker::Profile) -> Result<Self, String> {
Self::managed_journal(token, profile, None)
}
pub fn managed_journal(
token: String,
profile: crate::managed_worker::Profile,
path: Option<&std::path::Path>,
) -> Result<Self, String> {
let gateway = profile.gateway(token.clone())?;
let manager = crate::managed_worker::Manager::with_journal(profile, gateway.clone(), path)?;
Self::build(token, Some(gateway), Some(manager))
}
pub fn new(token: String, gateway: Option<Gateway>) -> Result<Self, String> {
Self::build(token, gateway, None)
}
fn build(
token: String,
gateway: Option<Gateway>,
manager: Option<crate::managed_worker::Manager>,
) -> Result<Self, String> {
check_credential(&token, gateway.as_ref())?;
let capabilities = capabilities(gateway.is_some(), manager.as_ref());
let (state, _) = watch::channel(Snapshot {
protocol_version: 1,
agent_epoch: uuid::Uuid::new_v4().to_string(),
sequence: 1,
capabilities,
active_responses: 0,
full_snapshot: true,
});
Ok(Self(Arc::new(Inner {
token,
manager,
router: gateway.map(|g| g.router()),
state,
observers: Arc::new(Semaphore::new(16)),
responses: Arc::new(Semaphore::new(64)),
hardware: Mutex::new(None),
})))
}
fn auth<T>(&self, r: &Request<T>) -> Result<(), Status> {
let token = r
.metadata()
.get("authorization")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.unwrap_or("");
if bool::from(token.as_bytes().ct_eq(self.0.token.as_bytes())) {
Ok(())
} else {
Err(Status::unauthenticated("node credential required"))
}
}
async fn inventory(&self, refresh: bool) -> Result<hardware::Hardware, Status> {
let mut cached = self
.0
.hardware
.try_lock()
.map_err(|_| Status::resource_exhausted("inventory already in progress"))?;
if refresh
|| cached
.as_ref()
.is_none_or(|(at, _)| at.elapsed() > Duration::from_secs(5))
{
*cached = Some((std::time::Instant::now(), hardware::inventory().await));
}
Ok(cached.as_ref().expect("inventory populated").1.clone())
}
fn snapshot(&self) -> Snapshot {
self.0.state.borrow().clone()
}
fn count(&self, entering: bool) {
self.0.state.send_modify(|s| {
s.sequence += 1;
if entering {
s.active_responses += 1
} else {
s.active_responses -= 1
}
});
}
async fn dispatch(
&self,
path: &str,
body: Vec<u8>,
) -> Result<axum::response::Response, Status> {
let router = self
.0
.router
.clone()
.ok_or_else(|| Status::failed_precondition("no inference gateway configured"))?;
let req = http::Request::builder()
.method(if path == "/v1/models" { "GET" } else { "POST" })
.uri(path)
.header("authorization", format!("Bearer {}", self.0.token))
.header("content-type", "application/json")
.body(Body::from(body))
.map_err(|_| Status::internal("request construction failed"))?;
Ok(router
.oneshot(req)
.await
.expect("Router errors are Infallible"))
}
pub async fn serve(
self,
listener: tokio::net::TcpListener,
shutdown: impl Future<Output = ()> + Send + 'static,
) -> Result<(), Box<dyn std::error::Error>> {
if !listener.local_addr()?.ip().is_loopback() {
return Err("node must bind loopback".into());
}
Server::builder()
.max_concurrent_streams(128)
.add_service(
NodeServer::new(self)
.max_decoding_message_size(MAX_MESSAGE)
.max_encoding_message_size(MAX_MESSAGE),
)
.serve_with_incoming_shutdown(TcpListenerStream::new(listener), shutdown)
.await?;
Ok(())
}
}
struct Active(Agent);
impl Drop for Active {
fn drop(&mut self) {
self.0.count(false)
}
}
#[tonic::async_trait]
impl Node for Agent {
async fn worker_status(&self, r: Request<Empty>) -> Result<Response<WorkerState>, Status> {
self.auth(&r)?;
Ok(Response::new(
self.0
.manager
.as_ref()
.ok_or_else(|| Status::failed_precondition("no managed profile"))?
.state(),
))
}
async fn control_worker(
&self,
r: Request<WorkerCommand>,
) -> Result<Response<WorkerOperation>, Status> {
self.auth(&r)?;
if !r.get_ref().expected_epoch.is_empty()
&& r.get_ref().expected_epoch != self.snapshot().agent_epoch
{
return Err(Status::failed_precondition("node epoch changed"));
}
self.0
.manager
.as_ref()
.ok_or_else(|| Status::failed_precondition("no managed profile"))?
.submit(r.into_inner())
.map(Response::new)
}
async fn operation_status(
&self,
r: Request<OperationQuery>,
) -> Result<Response<WorkerOperation>, Status> {
self.auth(&r)?;
self.0
.manager
.as_ref()
.ok_or_else(|| Status::failed_precondition("no managed profile"))?
.operation(&r.get_ref().operation_id)
.map(Response::new)
}
async fn handshake(&self, r: Request<Hello>) -> Result<Response<Snapshot>, Status> {
self.auth(&r)?;
if r.get_ref().protocol_version != 1 {
return Err(Status::failed_precondition("unsupported protocol version"));
}
Ok(Response::new(self.snapshot()))
}
async fn hardware(&self, r: Request<Empty>) -> Result<Response<JsonDocument>, Status> {
self.auth(&r)?;
let h = self.inventory(true).await?;
document(&h).map(Response::new)
}
async fn plan(&self, r: Request<JsonDocument>) -> Result<Response<JsonDocument>, Status> {
self.auth(&r)?;
if r.get_ref().json.len() > 1024 * 1024 {
return Err(Status::resource_exhausted("plan exceeds 1 MiB"));
}
let requirements = serde_json::from_slice(&r.get_ref().json)
.map_err(|_| Status::invalid_argument("invalid requirements"))?;
let h = self.inventory(false).await?;
let plan = planner::plan(&h, &requirements)
.map_err(|_| Status::invalid_argument("invalid memory requirements"))?;
document(&plan).map(Response::new)
}
type WatchStream = RpcStream<Snapshot>;
async fn watch(&self, r: Request<Cursor>) -> Result<Response<Self::WatchStream>, Status> {
self.auth(&r)?;
if r.get_ref().agent_epoch.len() > 128 {
return Err(Status::invalid_argument("invalid cursor"));
}
let permit = self
.0
.observers
.clone()
.try_acquire_owned()
.map_err(|_| Status::resource_exhausted("observer limit"))?;
let mut receiver = self.0.state.subscribe();
// Full snapshot is authoritative even for future cursors or a replaced epoch.
let stream = async_stream::try_stream! {
let _permit = permit;
loop {
let snapshot = receiver.borrow_and_update().clone();
yield snapshot;
if receiver.changed().await.is_err() {break}
}
};
Ok(Response::new(Box::pin(stream)))
}
async fn models(&self, r: Request<Empty>) -> Result<Response<JsonDocument>, Status> {
self.auth(&r)?;
let response = self.dispatch("/v1/models", vec![]).await?;
if !response.status().is_success() {
return Err(Status::internal("gateway model listing failed"));
}
let json = axum::body::to_bytes(response.into_body(), 1024 * 1024)
.await
.map_err(|_| Status::resource_exhausted("model listing limit"))?
.to_vec();
Ok(Response::new(JsonDocument { json }))
}
type RespondStream = RpcStream<ResponseFrame>;
async fn respond(
&self,
r: Request<ResponseRequest>,
) -> Result<Response<Self::RespondStream>, Status> {
self.auth(&r)?;
self.check_respond_admission(&r)?;
let permit = self
.0
.responses
.clone()
.try_acquire_owned()
.map_err(|_| Status::resource_exhausted("response limit"))?;
self.count(true);
let active = Active(self.clone());
let response = self.dispatch("/v1/responses", r.into_inner().json).await?;
let header = response_headers(&response);
let body = response.into_body().into_data_stream();
Ok(Response::new(response_frames(header, body, permit, active)))
}
}
fn document(value: &impl serde::Serialize) -> Result<JsonDocument, Status> {
let json = serde_json::to_vec(value).map_err(|_| Status::internal("serialization failed"))?;
if json.len() > MAX_MESSAGE - 1024 {
return Err(Status::resource_exhausted("document limit"));
}
Ok(JsonDocument { json })
}
/// Same client for local listener or an SSH-forwarded local port. No inference retries.
pub async fn connect(
address: SocketAddr,
) -> Result<proto::node_client::NodeClient<Channel>, Box<dyn std::error::Error>> {
if !address.ip().is_loopback() {
return Err("node connection must use loopback or SSH tunnel".into());
}
let channel = Endpoint::from_shared(format!("http://{address}"))?
.connect_timeout(Duration::from_secs(5))
.connect()
.await?;
Ok(proto::node_client::NodeClient::new(channel)
.max_decoding_message_size(MAX_MESSAGE)
.max_encoding_message_size(MAX_MESSAGE))
}
pub fn authorized<T>(message: T, token: &str) -> Result<Request<T>, Status> {
let mut r = Request::new(message);
r.metadata_mut().insert(
"authorization",
format!("Bearer {token}")
.parse()
.map_err(|_| Status::invalid_argument("invalid credential"))?,
);
Ok(r)
}