Files
leleka/desktop-core/src/managed_worker.rs
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

477 lines
16 KiB
Rust

//! One trusted local profile. RPC supplies actions, never commands or paths.
use crate::operation_journal::{Entries, Journal};
use crate::{
gateway::{self, Gateway},
node::proto::{WorkerCommand, WorkerOperation, WorkerState},
};
use serde::{Deserialize, Serialize};
use std::{
collections::BTreeMap,
net::{IpAddr, SocketAddr},
path::PathBuf,
process::Stdio,
sync::{Arc, Mutex},
time::Duration,
};
use tokio::{
process::{Child, Command},
sync::{mpsc, watch},
task::JoinHandle,
};
use tonic::Status;
#[derive(Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Profile {
pub schema_version: u32,
pub id: String,
pub model: String,
pub executable: PathBuf,
pub args: Vec<String>,
pub endpoint: SocketAddr,
pub startup_timeout_ms: u64,
/// Verified adapter capabilities, never inferred from the model name.
#[serde(default = "default_capabilities")]
pub capabilities: Vec<String>,
}
fn default_capabilities() -> Vec<String> {
vec!["responses".into()]
}
impl Profile {
pub fn validate(&self) -> Result<(), String> {
if self.schema_version != 1
|| self.id.is_empty()
|| self.id.len() > 128
|| !self
.id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|| self.capabilities.is_empty()
|| self.capabilities.len() > 16
|| !self.capabilities.iter().any(|c| c == "responses")
|| self.capabilities.iter().any(|c| {
![
"responses",
"tools",
"reasoning",
"structured_output",
"image",
"audio",
"file",
]
.contains(&c.as_str())
})
|| self.model.is_empty()
|| self.model.len() > 256
|| self.model.chars().any(char::is_control)
|| !self.executable.is_absolute()
|| !self.executable.is_file()
|| self.args.len() > 256
|| self.args.iter().any(|a| a.len() > 4096 || a.contains('\0'))
|| self.args.iter().map(String::len).sum::<usize>() > 32768
|| !self.endpoint.ip().is_loopback()
|| self.endpoint.port() < 1024
|| !(100..=3600000).contains(&self.startup_timeout_ms)
{
return Err("invalid managed worker profile".into());
}
Ok(())
}
pub fn gateway(&self, token: String) -> Result<Gateway, String> {
self.validate()?;
let gateway = Gateway::with_token(
gateway::Config {
schema_version: 1,
listen: SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 0),
token_env: "UNUSED".into(),
queue_limit: 16,
queue_timeout_ms: 1000,
request_timeout_ms: 3600000,
groups: vec![gateway::Group {
id: self.id.clone(),
slots: 1,
available_bytes: 1,
}],
deployments: vec![gateway::Deployment {
id: self.id.clone(),
model: self.model.clone(),
endpoint: format!("http://{}", self.endpoint),
token_env: None,
group: self.id.clone(),
slots: 1,
request_bytes: 1,
capabilities: self.capabilities.clone(),
}],
aliases: BTreeMap::new(),
},
token,
)?;
gateway.set_managed_ready(false);
Ok(gateway)
}
}
#[derive(Clone)]
pub struct Manager(Arc<Owner>);
struct Owner {
tx: mpsc::Sender<WorkerCommand>,
records: Records,
state: watch::Receiver<WorkerState>,
task: JoinHandle<()>,
gateway: Gateway,
}
impl Drop for Owner {
fn drop(&mut self) {
self.task.abort();
}
}
impl Manager {
pub fn new(profile: Profile, gateway: Gateway) -> Result<Self, String> {
Self::with_journal(profile, gateway, None)
}
pub fn with_journal(
profile: Profile,
gateway: Gateway,
path: Option<&std::path::Path>,
) -> Result<Self, String> {
profile.validate()?;
gateway.set_managed_ready(false);
let (journal, entries) = if let Some(path) = path {
let (j, e) = Journal::open(path, &profile)?;
(Some(j), e)
} else {
(None, Entries::new())
};
let blocked = entries.values().any(|(_, r)| r.status == "indeterminate");
let (state_tx, state) = watch::channel(WorkerState {
profile_id: profile.id.clone(),
model: profile.model.clone(),
phase: "stopped".into(),
pid: 0,
reason: String::new(),
});
let records = Arc::new(Mutex::new(History {
entries,
journal,
blocked,
}));
let (tx, rx) = mpsc::channel(8);
let task = tokio::spawn(run(profile, gateway.clone(), state_tx, records.clone(), rx));
Ok(Self(Arc::new(Owner {
tx,
records,
state,
task,
gateway,
})))
}
pub fn durable(&self) -> bool {
self.0.records.lock().unwrap().journal.is_some()
}
pub fn state(&self) -> WorkerState {
let mut state = self.0.state.borrow().clone();
if self.0.records.lock().unwrap().blocked {
state.phase = "failed".into();
state.reason = "reconciliation_required".into();
}
state
}
pub fn operation(&self, id: &str) -> Result<WorkerOperation, Status> {
self.0
.records
.lock()
.unwrap()
.entries
.get(
&uuid::Uuid::parse_str(id)
.map_err(|_| Status::invalid_argument("operation UUID required"))?
.to_string(),
)
.map(|(_, r)| r.clone())
.ok_or_else(|| Status::not_found("unknown operation for this epoch"))
}
pub fn submit(&self, mut c: WorkerCommand) -> Result<WorkerOperation, Status> {
c.operation_id = uuid::Uuid::parse_str(&c.operation_id)
.map_err(|_| Status::invalid_argument("operation UUID required"))?
.to_string();
if !(1..=2).contains(&c.action)
|| c.drain_timeout_ms > 30000
|| (c.action == 1 && c.drain_timeout_ms != 0)
|| c.expected_epoch.len() > 128
{
return Err(Status::invalid_argument(
"invalid worker action or drain timeout",
));
}
let mut records = self.0.records.lock().unwrap();
if let Some((old, result)) = records.entries.get(&c.operation_id) {
return if old.action == c.action && old.drain_timeout_ms == c.drain_timeout_ms {
Ok(result.clone())
} else {
Err(Status::already_exists(
"operation ID has different parameters",
))
};
}
if records.blocked {
return Err(Status::failed_precondition(
"journal reconciliation required",
));
}
if records.entries.len() >= 256 {
return Err(Status::resource_exhausted(
"operation history full; reconcile before new epoch",
));
}
let permit = self
.0
.tx
.try_reserve()
.map_err(|_| Status::resource_exhausted("worker command queue full"))?;
let result = WorkerOperation {
operation_id: c.operation_id.clone(),
status: "accepted".into(),
reason: String::new(),
};
if records.persist(&c, &result).is_err() {
self.0.gateway.set_managed_ready(false);
return Err(Status::internal("journal unavailable; reconcile operation"));
}
records
.entries
.insert(c.operation_id.clone(), (c.clone(), result.clone()));
permit.send(c);
Ok(result)
}
}
fn state(tx: &watch::Sender<WorkerState>, phase: &str, pid: u32, reason: &str) {
tx.send_modify(|s| {
s.phase = phase.into();
s.pid = pid;
s.reason = reason.into();
});
}
async fn healthy(client: &reqwest::Client, profile: &Profile) -> bool {
let Ok(response) = client
.get(format!("http://{}/health", profile.endpoint))
.send()
.await
else {
return false;
};
if !response.status().is_success() {
return false;
}
let mut response = response;
let mut data = vec![];
loop {
match response.chunk().await {
Ok(Some(b)) if data.len() + b.len() <= 65536 => data.extend(b),
Ok(None) => break,
_ => return false,
}
}
let Ok(value) = serde_json::from_slice::<serde_json::Value>(&data) else {
return false;
};
value["status"] == "ok" && value["loaded"] == true && value["model"] == profile.model
}
async fn terminate(child: &mut Option<Child>) -> Result<(), &'static str> {
if let Some(c) = child {
c.start_kill().map_err(|_| "stop_failed")?;
tokio::time::timeout(Duration::from_secs(5), c.wait())
.await
.map_err(|_| "stop_timeout")?
.map_err(|_| "wait_failed")?;
}
*child = None;
Ok(())
}
async fn start(
profile: &Profile,
gateway: &Gateway,
tx: &watch::Sender<WorkerState>,
child: &mut Option<Child>,
client: &reqwest::Client,
) -> Result<(), &'static str> {
if let Some(c) = child.as_mut()
&& c.try_wait().map_err(|_| "wait_failed")?.is_some()
{
*child = None;
}
if child.is_some() {
return if tx.borrow().phase == "ready" {
Ok(())
} else {
Err("stop_existing_owned_worker_first")
};
}
gateway.set_managed_ready(false);
// Binding a temporary listener proves the endpoint was free before spawn.
let listener = tokio::net::TcpListener::bind(profile.endpoint)
.await
.map_err(|_| "endpoint_occupied")?;
drop(listener);
gateway.clear_response_owners();
state(tx, "starting", 0, "");
let mut command = Command::new(&profile.executable);
command.args(&profile.args).env_clear();
for key in [
"PATH",
"HOME",
"USER",
"TMPDIR",
"TEMP",
"TMP",
"SystemRoot",
"WINDIR",
"LD_LIBRARY_PATH",
"DYLD_LIBRARY_PATH",
"CUDA_VISIBLE_DEVICES",
] {
if let Some(value) = std::env::var_os(key) {
// Even a nonstandard token variable must not leak through the allowlist.
if !gateway.matches_credential(&value.to_string_lossy()) {
command.env(key, value);
}
}
}
command
.env("STRATA_WORKER_ENDPOINT", profile.endpoint.to_string())
.env("STRATA_WORKER_MODEL", &profile.model);
let process = command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(|_| "spawn_failed")?;
let pid = process.id().unwrap_or(0);
*child = Some(process);
state(tx, "starting", pid, "");
let deadline = tokio::time::Instant::now() + Duration::from_millis(profile.startup_timeout_ms);
while tokio::time::Instant::now() < deadline {
if child
.as_mut()
.unwrap()
.try_wait()
.map_err(|_| "wait_failed")?
.is_some()
{
*child = None;
return Err("worker_exited");
}
if healthy(client, profile).await
&& child
.as_mut()
.unwrap()
.try_wait()
.map_err(|_| "wait_failed")?
.is_none()
{
gateway.set_managed_ready(true);
state(tx, "ready", pid, "");
return Ok(());
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
terminate(child).await?;
Err("startup_timeout")
}
async fn stop(
gateway: &Gateway,
tx: &watch::Sender<WorkerState>,
child: &mut Option<Child>,
grace: u32,
) -> Result<(), &'static str> {
gateway.set_managed_ready(false);
state(
tx,
"draining",
child.as_ref().and_then(Child::id).unwrap_or(0),
"",
);
let deadline = tokio::time::Instant::now() + Duration::from_millis(grace as u64);
while !gateway.idle() {
if tokio::time::Instant::now() >= deadline {
return Err("drain_timeout");
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
terminate(child).await?;
state(tx, "stopped", 0, "");
Ok(())
}
struct History {
entries: Entries,
journal: Option<Journal>,
blocked: bool,
}
impl History {
fn persist(&mut self, c: &WorkerCommand, r: &WorkerOperation) -> Result<(), ()> {
if self.blocked {
return Err(());
}
if let Some(j) = self.journal.as_mut()
&& j.append(c, r).is_err()
{
self.blocked = true;
return Err(());
}
Ok(())
}
fn update(&mut self, c: &WorkerCommand, status: &str, reason: &str) -> Result<(), ()> {
let r = WorkerOperation {
operation_id: c.operation_id.clone(),
status: status.into(),
reason: reason.into(),
};
if self.persist(c, &r).is_err() {
if let Some((_, old)) = self.entries.get_mut(&c.operation_id) {
old.status = "indeterminate".into();
old.reason = "journal_unavailable".into();
}
return Err(());
}
self.entries.insert(c.operation_id.clone(), (c.clone(), r));
Ok(())
}
}
type Records = Arc<Mutex<History>>;
async fn run(
profile: Profile,
gateway: Gateway,
tx: watch::Sender<WorkerState>,
records: Records,
mut rx: mpsc::Receiver<WorkerCommand>,
) {
let client = reqwest::Client::builder()
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_millis(500))
.build()
.expect("HTTP client");
let mut child: Option<Child> = None;
let mut tick = tokio::time::interval(Duration::from_millis(200));
loop {
tokio::select! {
command=rx.recv()=>{
let Some(command)=command else{break};
if records.lock().unwrap().update(&command,"running","").is_err(){gateway.set_managed_ready(false);continue}
let result=if command.action==1 {start(&profile,&gateway,&tx,&mut child,&client).await}else{stop(&gateway,&tx,&mut child,command.drain_timeout_ms).await};
if let Err(reason)=result {gateway.set_managed_ready(false);state(&tx,"failed",child.as_ref().and_then(Child::id).unwrap_or(0),reason);}
if records.lock().unwrap().update(&command,if result.is_ok(){"succeeded"}else{"failed"},result.err().unwrap_or("")).is_err(){gateway.set_managed_ready(false);}
},
_=tick.tick()=>{
if let Some(c)=child.as_mut() {
match c.try_wait() {
Ok(Some(_))=>{child=None;gateway.set_managed_ready(false);state(&tx,"failed",0,"worker_exited");},
Err(_)=>{gateway.set_managed_ready(false);state(&tx,"failed",c.id().unwrap_or(0),"wait_failed");},
Ok(None)=>{}
}
}
}
}
}
gateway.set_managed_ready(false);
let _ = terminate(&mut child).await;
}