//! 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 = Pin> + Send>>; #[derive(Clone)] pub struct Agent(Arc); struct Inner { token: String, router: Option, manager: Option, state: watch::Sender, observers: Arc, responses: Arc, hardware: Mutex>, } /// 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 { 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::managed_journal(token, profile, None) } pub fn managed_journal( token: String, profile: crate::managed_worker::Profile, path: Option<&std::path::Path>, ) -> Result { 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) -> Result { Self::build(token, gateway, None) } fn build( token: String, gateway: Option, manager: Option, ) -> Result { 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(&self, r: &Request) -> 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 { 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, ) -> Result { 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 + Send + 'static, ) -> Result<(), Box> { 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) -> Result, 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, ) -> Result, 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, ) -> Result, 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) -> Result, 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) -> Result, Status> { self.auth(&r)?; let h = self.inventory(true).await?; document(&h).map(Response::new) } async fn plan(&self, r: Request) -> Result, 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; async fn watch(&self, r: Request) -> Result, 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) -> Result, 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; async fn respond( &self, r: Request, ) -> Result, 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 { 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, Box> { 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(message: T, token: &str) -> Result, 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) }