use axum::{ extract::State, http::StatusCode, Json, }; use serde::{Deserialize, Serialize}; use std::process::Command; use std::time::Duration; use tokio::time::sleep; use crate::api::types::AppState; // ─── Request/Response types ────────────────────────────────────────────────── #[derive(Debug, Deserialize)] pub struct ServiceStartRequest { pub name: String, #[serde(default)] pub model: Option, #[serde(default = "default_port")] pub port: u16, } fn default_port() -> u16 { 8080 } #[derive(Debug, Deserialize)] pub struct ServiceStopRequest { pub name: String, /// If true, clean up temp files and stale data before stopping. #[serde(default)] pub cleanup: Option, } #[derive(Debug, Serialize)] pub struct ServiceResponse { pub result: String, #[serde(skip_serializing_if = "Option::is_none")] pub pid: Option, #[serde(skip_serializing_if = "Option::is_none")] pub error: Option, } #[derive(Debug, Serialize)] pub struct MbeHealthResponse { pub status: String, #[serde(skip_serializing_if = "Option::is_none")] pub model: Option, #[serde(skip_serializing_if = "Option::is_none")] pub uptime: Option, } // ─── Service registry (mirrors proxy.rs svc_def) ──────────────────────────── /// Known services with their default port and launchd label. /// `launchd_label = None` means the service is managed manually (not via launchd). fn svc_def(name: &str) -> Option<(&'static str, u16, Option<&'static str>)> { let key = name.to_lowercase().replace(' ', ""); let def: (&'static str, u16, Option<&'static str>) = match key.as_str() { "core" | "coreapi" | "api" => ("core", 3002, Some("com.momentry.server")), "markbase" | "mb" => ("markbase", 11438, Some("com.momentry.markbase")), "mbe" | "markbaseengine" | "vlm" => ("mbe", 8082, Some("com.momentry.llm")), // MBE = markbaseengine service; spawns VLM llama-server (8082) "chat" | "llama" => ("chat", 8080, Some("com.momentry.chat-llamacpp")), // Chat llama-server instance (8080) "embedding" => ("embedding", 11437, Some("com.momentry.embedding-gguf")), "proxy" => ("proxy", 8888, Some("com.momentry.proxy")), "worker" => ("worker", 0, Some("com.momentry.worker")), "postgres" | "postgresql" | "pg" => ("postgres", 5432, Some("com.momentry.postgresql")), // NOTE: the redis actually serving 127.0.0.1:6379 is brew-services' launchd agent, // not com.momentry.redis (which can't bind while brew's owns the port). "redis" => ("redis", 6379, Some("sh.brew.redis")), "qdrant" => ("qdrant", 6333, Some("com.momentry.qdrant")), _ => return None, }; Some(def) } // ─── Process helpers ──────────────────────────────────────────────────────── fn is_port_in_use(port: u16) -> bool { use std::net::TcpStream; let addr = format!("127.0.0.1:{}", port); TcpStream::connect(&addr).is_ok() } /// Wait until a port is accepting connections (or timeout). Ports of 0 (worker, /// which has no listener) resolve immediately after a short grace pause. async fn wait_for_port_ready(port: u16, max_secs: u64) -> bool { if port == 0 { sleep(Duration::from_secs(2)).await; return true; } for i in 0..max_secs { if is_port_in_use(port) { if i > 0 { tracing::info!("[Service] port {} ready after {}s", port, i); } return true; } sleep(Duration::from_secs(1)).await; } tracing::warn!("[Service] port {} not ready within {}s", port, max_secs); false } fn get_port_pid(port: u16) -> Option { let output = Command::new("/usr/sbin/lsof") .args(["-nP", &format!("-iTCP:{}", port), "-sTCP:LISTEN", "-t"]) .output().ok()?; if output.status.success() && !output.stdout.is_empty() { // lsof -t may return multiple PIDs (one per line) — take the first (listener) String::from_utf8_lossy(&output.stdout) .split_whitespace() .next() .and_then(|s| s.parse::().ok()) } else { None } } fn kill_process(pid: u32) -> bool { Command::new("kill").arg(pid.to_string()).output() .map(|o| o.status.success()).unwrap_or(false) } // ─── launchctl helpers ─────────────────────────────────────────────────────── /// Get the current user's UID as a string for launchd domain targeting. fn uid_str() -> String { // Primary: use `id -u` command (most reliable) let out = Command::new("id").arg("-u").output(); if let Ok(o) = out { let uid = String::from_utf8_lossy(&o.stdout).trim().to_string(); if !uid.is_empty() { return uid; } } // Fallback: env var or default std::env::var("UID") .ok() .filter(|s| !s.is_empty()) .unwrap_or_else(|| "501".to_string()) } /// Build a launchd service target: "gui//