Files
momentry_core/src/api/service_management.rs
T

2147 lines
87 KiB
Rust

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<String>,
#[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<bool>,
}
#[derive(Debug, Serialize)]
pub struct ServiceResponse {
pub result: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub pid: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct MbeHealthResponse {
pub status: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub uptime: Option<u64>,
}
// ─── 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<u32> {
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::<u32>().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/<uid>/<label>"
fn svc_target(label: &str) -> String {
format!("gui/{}/{}", uid_str(), label)
}
/// Execute a launchctl command, returning (success, stdout, stderr).
fn launchctl(args: &[&str]) -> (bool, String, String) {
let out = Command::new("launchctl").args(args).output();
match out {
Ok(o) => {
let ok = o.status.success();
let stdout = String::from_utf8_lossy(&o.stdout).trim().to_string();
let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
(ok, stdout, stderr)
}
Err(e) => (false, String::new(), e.to_string()),
}
}
/// Check if a launchd service is running (non-zero PID in launchctl list).
fn launchd_is_running(label: &str) -> bool {
let target = svc_target(label);
let (_, stdout, _) = launchctl(&["list", &target]);
// Output is like: "12345\t0\tcom.momentry.api" or "-\t78\tcom.momentry.api"
stdout.split('\t').next() != Some("-")
}
/// Stop a launchd-managed service (bootout to fully unload).
fn launchd_stop(label: &str) -> Result<(), String> {
let target = svc_target(label);
tracing::info!("[Service] launchd_stop: label={} target={}", label, target);
let (ok, _out, err) = launchctl(&["bootout", &target]);
if ok {
tracing::info!("[Service] launchctl bootout {} succeeded", target);
Ok(())
} else {
// bootout may fail if already stopped — that's OK
if err.contains("No such process") || err.contains("not currently loaded") || err.contains("Could not find service") {
tracing::info!("[Service] {} already stopped or not loaded", label);
Ok(())
} else {
Err(format!("launchctl bootout {}: {}", target, err))
}
}
}
/// Start a launchd-managed service. Uses bootstrap (load from plist) because
/// bootout fully unloads the service, making kickstart unable to find it.
fn launchd_start(label: &str) -> Result<(), String> {
let uid = uid_str();
let domain = format!("gui/{}", uid);
let plist = format!("{}/Library/LaunchAgents/{}.plist",
std::env::var("HOME").unwrap_or_else(|_| "/Users/accusys".to_string()),
label
);
// First try bootstrap (load from plist)
let (ok, _out, err) = launchctl(&["bootstrap", &domain, &plist]);
if ok {
tracing::info!("[Service] launchctl bootstrap {} succeeded", plist);
return Ok(());
}
// If bootstrap fails with "already loaded" (or launchd's cryptic I/O error
// for an existing service), fall back to kickstart
if err.contains("already loaded") || err.contains("service is already running") || err.contains("Input/output error") || err.contains("already bootstrapped") {
let target = format!("{}/{}", domain, label);
let (ok2, _out2, err2) = launchctl(&["kickstart", "-k", &target]);
if ok2 {
tracing::info!("[Service] launchctl kickstart {} succeeded (fallback)", target);
Ok(())
} else {
Err(format!("launchctl kickstart {}: {}", target, err2))
}
} else {
Err(format!("launchctl bootstrap {}: {}", plist, err))
}
}
/// Get PID from launchctl list for a service.
fn launchd_pid(label: &str) -> Option<u32> {
let (_, stdout, _) = launchctl(&["list", label]);
// Legacy tab format: "12345\t0\tcom.momentry.api"
if let Some(first_field) = stdout.split('\t').next() {
if let Ok(p) = first_field.parse::<u32>() {
return Some(p);
}
}
// Modern dict format: "PID" = 17606;
for line in stdout.lines() {
let line = line.trim();
if let Some(rest) = line.strip_prefix("\"PID\"") {
let num: String = rest.chars().filter(|c| c.is_ascii_digit()).collect();
if let Ok(p) = num.parse::<u32>() {
return Some(p);
}
}
}
None
}
// ─── MBE (llama-server) — unchanged from original ───────────────────────────
async fn start_llama_server(port: u16, model: Option<String>) -> Result<u32, String> {
if is_port_in_use(port) {
if let Some(pid) = get_port_pid(port) {
tracing::info!("[Service] Port {} occupied by PID {}, stopping", port, pid);
kill_process(pid);
sleep(Duration::from_secs(2)).await;
}
}
let model_path = model.unwrap_or_else(|| {
"/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf".to_string()
});
let mmproj_path = "/Users/accusys/models/mmproj-F16.gguf";
let llama_binary = "/Users/accusys/llama.cpp/build/bin/llama-server";
tracing::info!("[Service] Spawning llama-server: {} port {} model {}", llama_binary, port, model_path);
let mut cmd = Command::new(llama_binary);
cmd.args([
"-m", &model_path,
"--mmproj", mmproj_path,
"--host", "0.0.0.0",
"--port", &port.to_string(),
"-ngl", "99",
"-c", "8192",
"--temp", "0.1",
"-b", "4096",
"-ub", "4096",
]);
cmd.env("PATH", "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin");
// Route stdout/stderr to the standard per-instance log files
// (8080 = chat instance → chat-llamacpp.log, 8082 = VLM instance → vlm-llamacpp.log)
let log_name = if port == 8082 { "vlm-llamacpp.log" } else { "chat-llamacpp.log" };
let log_path = crate::core::path_utils::momentry_root().join("log").join(log_name);
if let Some(parent) = log_path.parent() {
let _ = std::fs::create_dir_all(parent);
}
match std::fs::OpenOptions::new().create(true).append(true).open(&log_path) {
Ok(out_file) => {
use std::process::Stdio;
cmd.stdout(Stdio::from(out_file.try_clone().expect("clone log file")));
cmd.stderr(Stdio::from(out_file));
}
Err(e) => {
tracing::warn!("[Service] cannot open {} for llama-server output: {}", log_path.display(), e);
}
}
let mut child = cmd.spawn()
.map_err(|e| format!("Failed to start llama-server: {}", e))?;
let pid = child.id();
std::mem::forget(child);
// Wait for ready
for i in 0..30 {
sleep(Duration::from_secs(2)).await;
if is_port_in_use(port) {
let url = format!("http://127.0.0.1:{}/v1/models", port);
if let Ok(r) = reqwest::get(&url).await {
if r.status().is_success() {
tracing::info!("[Service] llama-server ready after {}s", i * 2);
return Ok(pid);
}
}
}
}
Err("llama-server failed to start within 60s".to_string())
}
fn stop_llama_server(port: u16) -> Result<(), String> {
if let Some(pid) = get_port_pid(port) {
tracing::info!("[Service] Killing llama-server port {} PID {}", port, pid);
if kill_process(pid) { Ok(()) } else { Err(format!("Failed to kill PID {}", pid)) }
} else {
Err(format!("No service on port {}", port))
}
}
// ─── Cleanup helpers ─────────────────────────────────────────────────────────
/// Clean up temp files and stale data for a service restart.
/// Returns a summary of what was cleaned.
fn cleanup_service_temp(key: &str) -> Vec<String> {
let mut details = Vec::new();
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
match key {
// Core API / Worker: clean stale .tmp files, orphaned outputs, temp videos
"core" | "worker" => {
// Clean stale .json.tmp files in output dir (older than 1 hour)
if let Ok(entries) = std::fs::read_dir(output_dir) {
let mut cleaned = 0;
for entry in entries.flatten() {
let path = entry.path();
if let Some(ext) = path.extension() {
if ext == "tmp" {
let stale = path.metadata().ok()
.and_then(|m| m.modified().ok())
.map(|t| std::time::SystemTime::now().duration_since(t).map(|d| d.as_secs() > 3600).unwrap_or(false))
.unwrap_or(false);
if stale {
let _ = std::fs::remove_file(&path);
cleaned += 1;
}
}
}
}
if cleaned > 0 {
details.push(format!("Cleaned {} stale .tmp files", cleaned));
}
}
// Clean /tmp/momentry_* and /tmp/bbox_*, /tmp/trace_*, /tmp/chunk_*, etc.
// NOTE: launchd processes have TMPDIR=/var/folders/…/T — scan both /tmp and temp_dir()
let tmp_patterns = ["momentry_", "bbox_", "trace_", "chunk_", "stranger_", "vf_"];
let mut tmp_cleaned = 0;
let mut tmp_dirs = vec![std::path::PathBuf::from("/tmp")];
let env_tmp = std::env::temp_dir();
if env_tmp != tmp_dirs[0] {
tmp_dirs.push(env_tmp);
}
for tmp_dir in &tmp_dirs {
if let Ok(entries) = std::fs::read_dir(tmp_dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if tmp_patterns.iter().any(|p| name.starts_with(p)) {
let _ = std::fs::remove_file(&path);
tmp_cleaned += 1;
}
}
}
}
}
if tmp_cleaned > 0 {
details.push(format!("Cleaned {} temp files", tmp_cleaned));
}
// Clean /tmp/ffmpeg_last_error.txt
let ffmpeg_err = std::path::PathBuf::from("/tmp/ffmpeg_last_error.txt");
if ffmpeg_err.exists() {
let _ = std::fs::remove_file(&ffmpeg_err);
details.push("Cleaned ffmpeg error log".to_string());
}
}
// Redis: flush all data for clean restart
"redis" => {
// Try to FLUSHALL via HTTP (if Redis HTTP interface available)
// or via CLI
let result = std::process::Command::new("redis-cli")
.args(["-a", "accusys", "FLUSHALL"])
.output();
match result {
Ok(out) if out.status.success() => {
details.push("Redis FLUSHALL completed".to_string());
}
_ => {
// Fallback: try without password
let result2 = std::process::Command::new("redis-cli")
.arg("FLUSHALL")
.output();
if result2.map(|o| o.status.success()).unwrap_or(false) {
details.push("Redis FLUSHALL completed".to_string());
} else {
details.push("Redis flush skipped (redis-cli unavailable)".to_string());
}
}
}
}
// Qdrant: clean snapshot temp files
"qdrant" => {
let qdrant_data = crate::core::path_utils::momentry_root().join("var/qdrant");
if let Ok(entries) = std::fs::read_dir(&qdrant_data) {
let mut cleaned = 0;
for entry in entries.flatten() {
let path = entry.path();
// Clean .snapshot or .tmp files
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if name.contains(".snapshot") || name.ends_with(".tmp") {
let _ = std::fs::remove_dir_all(&path).or_else(|_| std::fs::remove_file(&path));
cleaned += 1;
}
}
}
if cleaned > 0 {
details.push(format!("Cleaned {} Qdrant temp files", cleaned));
}
}
}
// Postgres: clean WAL archives if any (but NOT data dir!)
"postgres" => {
// We intentionally do NOT clean PG data - only note that
// stale connections will be cleared on restart
details.push("PG connections will be cleared on restart".to_string());
}
// LLM servers: clean any cached temp files
"mbe" | "chat_llm" | "embedding" => {
// llama-server may leave temp files in /tmp (scan both /tmp and temp_dir())
let mut tmp_cleaned = 0;
let mut tmp_dirs = vec![std::path::PathBuf::from("/tmp")];
let env_tmp = std::env::temp_dir();
if env_tmp != tmp_dirs[0] {
tmp_dirs.push(env_tmp);
}
for tmp_dir in &tmp_dirs {
if let Ok(entries) = std::fs::read_dir(tmp_dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if name.starts_with("llama") || name.starts_with("ggml") {
let _ = std::fs::remove_file(&path);
tmp_cleaned += 1;
}
}
}
}
}
if tmp_cleaned > 0 {
details.push(format!("Cleaned {} LLM temp files", tmp_cleaned));
}
}
_ => {}
}
details
}
// ─── API Handlers ────────────────────────────────────────────────────────────
/// POST /api/v2/service/start
/// Supports all registered services. MBE uses llama-server spawn; others use launchctl.
pub async fn start_service(
State(_state): State<AppState>,
Json(req): Json<ServiceStartRequest>,
) -> Result<Json<ServiceResponse>, StatusCode> {
tracing::info!("[Service] Start request: {:?}", req);
let Some((key, port, label)) = svc_def(&req.name) else {
tracing::error!("[Service] Unknown service: {}", req.name);
return Err(StatusCode::BAD_REQUEST);
};
// Port used for stray-process cleanup / readiness checks. 0 = worker (no port).
let check_port = if port == 0 { 0 } else { port };
// ── launchd-managed services (primary path) ──
if let Some(l) = label {
// Clear any stray process squatting on the service port that launchd
// doesn't own (e.g. a hand-spawned llama-server from a fallback run).
if check_port > 0 && launchd_pid(l).is_none() && is_port_in_use(check_port) {
if let Some(pid) = get_port_pid(check_port) {
tracing::info!("[Service] Stray PID {} on port {}; killing before launchd start", pid, check_port);
kill_process(pid);
sleep(Duration::from_secs(2)).await;
}
}
match launchd_start(l) {
Ok(()) => {
wait_for_port_ready(check_port, 20).await;
let pid = launchd_pid(l);
tracing::info!("[Service] {} started (pid={:?})", l, pid);
Ok(Json(ServiceResponse {
result: "started".into(),
pid,
error: None,
}))
}
Err(e) => {
// MBE fallback: launchd unavailable → spawn llama-server manually
if key == "mbe" {
let spawn_port = if port == 0 { req.port } else { port };
return match start_llama_server(spawn_port, req.model).await {
Ok(pid) => Ok(Json(ServiceResponse { result: "started".into(), pid: Some(pid), error: None })),
Err(e2) => Ok(Json(ServiceResponse { result: "failed".into(), pid: None, error: Some(format!("{} / {}", e, e2)) })),
};
}
tracing::error!("[Service] launchctl start {} failed: {}", l, e);
Ok(Json(ServiceResponse { result: "failed".into(), pid: None, error: Some(e) }))
}
}
}
// ── No launchd label and not MBE ──
else {
tracing::warn!("[Service] Service '{}' has no launchd label and is not MBE — cannot auto-start", req.name);
Ok(Json(ServiceResponse {
result: "unsupported".into(),
pid: None,
error: Some("No launchd label configured".into()),
}))
}
}
/// POST /api/v2/service/stop
/// launchd services: bootout. MBE fallback: kill llama-server by port.
pub async fn stop_service(
State(_state): State<AppState>,
Json(req): Json<ServiceStopRequest>,
) -> Result<Json<ServiceResponse>, StatusCode> {
tracing::info!("[Service] Stop request: {:?}", req);
let Some((key, port, label)) = svc_def(&req.name) else {
return Err(StatusCode::BAD_REQUEST);
};
// ── Core: this server IS the target. Delay the bootout slightly so the
// HTTP response has a chance to flush to the client before we die. ──
if key == "core" {
if let Some(l) = label {
let target = svc_target(l);
let _ = std::process::Command::new("sh")
.arg("-c")
.arg(format!("(sleep 1; launchctl bootout '{}' >/dev/null 2>&1) &", target
.replace('\'', "")))
.spawn();
}
tracing::info!("[Service] Core stop scheduled (delayed bootout)");
return Ok(Json(ServiceResponse { result: "stopped".into(), pid: None, error: None }));
}
// ── Postgres: bootout the label (releases KeepAlive), then SIGINT the
// postmaster ourselves. pg_ctl -m fast stop can hang waiting on the
// respawn, and bootout's SIGTERM triggers a smart shutdown that stalls
// forever while idle client connections keep the postmaster waiting. ──
if key == "postgres" {
if let Some(l) = label {
let _ = launchctl(&["bootout", &svc_target(l)]);
}
let pid = get_port_pid(5432)
.or_else(|| {
let out = std::process::Command::new("pgrep").args(["-f", "bin/postgres -D"]).output().ok()?;
String::from_utf8_lossy(&out.stdout).lines().next()?.trim().parse::<u32>().ok()
});
if let Some(p) = pid {
let _ = std::process::Command::new("kill").args(["-INT", &p.to_string()]).output();
// Wait up to 15s for the postmaster to exit
for _ in 0..15 {
let gone = std::process::Command::new("sh")
.args(["-c", &format!("! kill -0 {} 2>/dev/null", p)])
.status().map(|s| s.success()).unwrap_or(false);
if gone { break; }
sleep(Duration::from_secs(1)).await;
}
tracing::info!("[Service] postgres stop: postmaster {} signalled", p);
} else {
tracing::info!("[Service] postgres stop: no postmaster found (already stopped)");
}
return Ok(Json(ServiceResponse { result: "stopped".into(), pid: None, error: None }));
}
// ── launchd-managed services ──
if let Some(l) = label {
match launchd_stop(l) {
Ok(()) => {
Ok(Json(ServiceResponse { result: "stopped".into(), pid: None, error: None }))
}
Err(e) => {
// MBE fallback: kill llama-server by port
if key == "mbe" {
return match stop_llama_server(port) {
Ok(()) => Ok(Json(ServiceResponse { result: "stopped".into(), pid: None, error: None })),
Err(e2) => Ok(Json(ServiceResponse { result: "failed".into(), pid: None, error: Some(format!("{} / {}", e, e2)) })),
};
}
tracing::error!("[Service] launchctl stop {} failed: {}", l, e);
Ok(Json(ServiceResponse { result: "failed".into(), pid: None, error: Some(e) }))
}
}
} else {
Ok(Json(ServiceResponse {
result: "unsupported".into(),
pid: None,
error: Some("No launchd label configured".into()),
}))
}
}
/// GET /api/v1/mbe/health
pub async fn mbe_health(
State(_state): State<AppState>,
) -> Result<Json<MbeHealthResponse>, StatusCode> {
let port = 8082u16;
match check_mbe_health(port).await {
Ok(h) => Ok(Json(h)),
Err(e) => {
tracing::warn!("[Service] MBE health check: {}", e);
Ok(Json(MbeHealthResponse { status: "offline".into(), model: None, uptime: None }))
}
}
}
async fn check_mbe_health(port: u16) -> Result<MbeHealthResponse, String> {
if !is_port_in_use(port) {
return Err("Port not in use".into());
}
let url = format!("http://127.0.0.1:{}/v1/models", port);
let resp = reqwest::get(&url).await.map_err(|e| format!("HTTP request: {}", e))?;
if !resp.status().is_success() {
return Err(format!("HTTP {}", resp.status()));
}
let json: serde_json::Value = resp.json().await.map_err(|e| format!("Parse: {}", e))?;
let model = json["models"][0]["name"]
.as_str()
.map(|s| s.split('/').last().unwrap_or(s).to_string());
Ok(MbeHealthResponse { status: "ok".into(), model, uptime: Some(0) })
}
// ─── Service Status Probe ────────────────────────────────────────────────────
#[derive(Debug, Serialize)]
pub struct ServiceStatusResponse {
pub running: bool,
pub pid: Option<u32>,
pub managed_by: Option<String>,
pub healthy: Option<bool>,
pub uptime: Option<u64>,
}
/// GET /api/v1/admin/services/status?name=postgres
pub async fn service_status(
State(_state): State<AppState>,
axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
) -> Result<Json<ServiceStatusResponse>, StatusCode> {
let name = params.get("name").ok_or(StatusCode::BAD_REQUEST)?;
let Some((key, port, label)) = svc_def(name) else {
return Err(StatusCode::BAD_REQUEST);
};
let pid = get_port_pid(port).or_else(|| {
if let Some(l) = label {
launchd_pid(l)
} else {
None
}
});
let running = pid.is_some() || (port > 0 && is_port_in_use(port));
let managed_by = label.map(|s| s.to_string());
// Health check based on service type
let healthy = match key {
"postgres" => {
// pg_isready may not be in PATH (libpq keg-only) — try PATH first, then known location
let probe = |bin: &str| {
std::process::Command::new(bin)
.arg("-h").arg("127.0.0.1")
.arg("-p").arg(&port.to_string())
.output().ok()
.map(|o| o.status.success())
};
probe("pg_isready").filter(|h| *h).or_else(|| probe("/opt/homebrew/opt/libpq/bin/pg_isready"))
}
"redis" => {
std::process::Command::new("redis-cli")
.args(["-a", "accusys", "PING"])
.env_remove("REDISCLI_AUTH")
.output().ok()
.and_then(|o| {
if o.status.success() {
String::from_utf8(o.stdout).ok().map(|s| s.trim() == "PONG")
} else { None }
})
}
"qdrant" => {
let rt = tokio::runtime::Handle::current();
match reqwest::get("http://localhost:6333/healthz").await {
Ok(r) => Some(r.status().is_success()),
Err(_) => Some(false),
}
}
_ => None,
};
// Calculate uptime from process start time
let uptime = pid.map(|p| {
let output = std::process::Command::new("ps")
.args(["-o", "etime=", "-p", &p.to_string()])
.output();
if let Ok(o) = output {
let etime = String::from_utf8_lossy(&o.stdout).trim().to_string();
// Parse etime format: [[DD-]HH:]MM:SS
parse_uptime(&etime)
} else {
None
}
}).flatten();
Ok(Json(ServiceStatusResponse {
running,
pid,
managed_by,
healthy,
uptime,
}))
}
fn parse_uptime(etime: &str) -> Option<u64> {
let parts: Vec<&str> = etime.split(|c: char| !c.is_ascii_digit()).filter(|s| !s.is_empty()).collect();
let nums: Vec<u64> = parts.iter().filter_map(|s| s.parse().ok()).collect();
match nums.len() {
1 => Some(nums[0]), // SS
2 => Some(nums[0] * 60 + nums[1]), // MM:SS
3 => Some(nums[0] * 3600 + nums[1] * 60 + nums[2]), // HH:MM:SS
4 => Some(nums[0] * 86400 + nums[1] * 3600 + nums[2] * 60 + nums[3]), // DD-HH:MM:SS
_ => None,
}
}
// ─── Service Log ─────────────────────────────────────────────────────────────
#[derive(Debug, Serialize)]
pub struct ServiceLogResponse {
pub path: String,
pub exists: bool,
pub content: String,
pub tail_lines: usize,
}
/// GET /api/v1/admin/services/log?name=core&tailLines=200&filter=
pub async fn service_log(
State(_state): State<AppState>,
axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
) -> Result<Json<ServiceLogResponse>, StatusCode> {
let name = params.get("name").ok_or(StatusCode::BAD_REQUEST)?;
let tail_lines: usize = params.get("tailLines")
.and_then(|s| s.parse().ok())
.unwrap_or(200);
let filter = params.get("filter").cloned().unwrap_or_default();
let error_log = params.get("errorLog")
.map(|s| s == "1" || s.eq_ignore_ascii_case("true"))
.unwrap_or(false);
let log_path = resolve_log_path_for(name, error_log);
let exists = log_path.exists();
let content = if exists {
// Read last N lines
let output = std::process::Command::new("tail")
.args(["-n", &tail_lines.to_string(), &log_path.to_string_lossy()])
.output();
match output {
Ok(o) => {
let text = String::from_utf8_lossy(&o.stdout).to_string();
let lines: Vec<&str> = text.lines().collect();
let normalized = normalize_log_lines(lines);
if !filter.is_empty() {
normalized.into_iter()
.filter(|line| line.contains(&filter))
.collect::<Vec<_>>()
.join("\n")
} else {
normalized.join("\n")
}
}
Err(_) => String::from("Failed to read log file"),
}
} else {
String::from("Log file not found")
};
Ok(Json(ServiceLogResponse {
path: log_path.to_string_lossy().to_string(),
exists,
content,
tail_lines,
}))
}
fn resolve_log_path(name: &str) -> std::path::PathBuf {
resolve_log_path_for(name, false)
}
/// Resolve a service log path. `error_log = true` selects the stderr log.
/// Priority: unified standard path (~/momentry/logs/{service}[.error].log)
/// first, then legacy paths as fallback.
fn resolve_log_path_for(name: &str, error_log: bool) -> std::path::PathBuf {
let (stdout_candidates, error_candidates) = resolve_log_path_candidates(name);
let candidates = if error_log { &error_candidates } else { &stdout_candidates };
let fallback = candidates.first().cloned().unwrap_or_else(|| {
let momentry_root = crate::core::path_utils::momentry_root();
momentry_root.join(format!("log/{}.log", name))
});
candidates.iter().find(|p| p.exists()).cloned().unwrap_or(fallback)
}
/// Canonical unified log name for each service key (under ~/momentry/logs/).
fn standard_log_name(name: &str) -> String {
match name.to_lowercase().as_str() {
"core" | "coreapi" | "api" => "core_api",
"worker" => "worker",
"proxy" => "proxy",
"markbase" | "mb" => "markbase",
"mbe" | "markbaseengine" | "vlm" => "mbe",
"chat" | "llama" => "chat_llm",
"embedding" | "emb" => "embedding",
"postgres" | "postgresql" | "pg" => "postgresql",
"redis" => "redis",
"qdrant" => "qdrant",
"sftpgo" => "sftpgo",
"gitea" => "gitea",
"update" | "update-server" | "updateserver" => "update_server",
"studio" => "studio",
"people-proxy" | "peopleproxy" => "people-proxy",
other => other,
}
.to_string()
}
/// Return (stdout_candidates, error_candidates) for a service, each in
/// priority order. The unified standard path (~/momentry/logs/) always comes
/// first; legacy paths (~/momentry/log/, brew logs) follow as fallback so
/// machines that haven't been restarted yet still show their logs.
fn resolve_log_path_candidates(name: &str) -> (Vec<std::path::PathBuf>, Vec<std::path::PathBuf>) {
let momentry_root = crate::core::path_utils::momentry_root();
let std_name = standard_log_name(name);
// Legacy per-service paths (pre-unification), stdout only.
let legacy_out: Vec<std::path::PathBuf> = match name.to_lowercase().as_str() {
"core" | "api" => vec![
momentry_root.join("log/momentry_api.log"),
momentry_root.join("logs/momentry_api.log"),
],
"worker" => vec![
momentry_root.join("log/momentry_worker.log"),
momentry_root.join("logs/momentry_worker.log"),
],
"markbase" | "mb" => vec![
momentry_root.join("log/markbase-web.log"),
momentry_root.join("log/markbase.log"),
momentry_root.join("logs/markbase.log"),
momentry_root.join("logs/markbaseengine.log"),
],
"mbe" | "vlm" => vec![
momentry_root.join("log/vlm-llamacpp.log"),
momentry_root.join("log/llama-server.log"),
momentry_root.join("logs/llama-server.log"),
momentry_root.join("logs/llm_8080.log"),
momentry_root.join("logs/vlm-llamacpp.log"),
momentry_root.join("logs/markbaseengine.log"),
momentry_root.join("logs/llm_chat.log"),
],
"chat" => vec![
momentry_root.join("log/chat-llamacpp.log"),
momentry_root.join("logs/chat-llamacpp.log"),
],
"embedding" | "emb" => vec![
momentry_root.join("log/embedding.log"),
momentry_root.join("logs/embedding.log"),
],
"proxy" => vec![
momentry_root.join("log/proxy.error.log"),
momentry_root.join("log/momentry_proxy.log"),
momentry_root.join("logs/momentry_proxy.log"),
momentry_root.join("logs/proxy.log"),
],
"postgres" | "pg" => vec![
std::path::PathBuf::from("/opt/homebrew/var/log/postgresql@18.log"),
std::path::PathBuf::from("/opt/homebrew/var/log/postgresql.log"),
std::path::PathBuf::from("/Users/accusys/opt_pgsql/logs/postgres.log"),
std::path::PathBuf::from("/Users/accusys/opt_pgsql/data/log/postgresql.log"),
std::path::PathBuf::from("/usr/local/var/postgres/server.log"),
],
"redis" => vec![
std::path::PathBuf::from("/opt/homebrew/var/log/redis.log"),
std::path::PathBuf::from("/Users/accusys/opt_redis/logs/redis.log"),
std::path::PathBuf::from("/usr/local/var/log/redis.log"),
],
"qdrant" => vec![
momentry_root.join("log/qdrant.log"),
momentry_root.join("logs/qdrant.log"),
],
_ => vec![
momentry_root.join(format!("log/{}.log", name)),
momentry_root.join(format!("logs/{}.log", name)),
],
};
// Unified standard paths always take priority.
let mut stdout_candidates = vec![
momentry_root.join(format!("logs/{}.log", std_name)),
];
stdout_candidates.extend(legacy_out);
// Error candidates: standard .error.log first, then every stdout
// candidate with `.log` swapped for `.error.log` (launchd convention),
// then the stdout file itself (some services log everything to one file).
let mut error_candidates = vec![
momentry_root.join(format!("logs/{}.error.log", std_name)),
];
for p in &stdout_candidates {
let s = p.to_string_lossy().to_string();
if let Some(stripped) = s.strip_suffix(".log") {
error_candidates.push(std::path::PathBuf::from(format!("{}.error.log", stripped)));
}
}
for p in &stdout_candidates {
error_candidates.push(p.clone());
}
(stdout_candidates, error_candidates)
}
/// Normalize log lines to ensure they all have timestamps.
/// Strips ANSI escape codes and adds timestamps to lines that lack them.
fn normalize_log_lines(lines: Vec<&str>) -> Vec<String> {
let now = chrono::Local::now();
let mut result = Vec::new();
for (i, line) in lines.into_iter().enumerate() {
// Strip ANSI escape codes
let clean = strip_ansi(line);
if clean.is_empty() {
continue;
}
// Check if line already has a REAL timestamp near the start of the line
// (first digit within 1 char of the start, so "[2026-...]" brackets also count)
let digit_start = clean.find(|c: char| c.is_ascii_digit()).unwrap_or(usize::MAX);
let has_timestamp = digit_start <= 1 && extract_timestamp(&clean).is_some()
// Redis: 11 Nov 2026 10:38:21 (month name near the start)
|| digit_start <= 2 && clean[digit_start..].chars().take(20).any(|c| c == ':')
&& clean.get(digit_start..digit_start+20).map(|h| {
["Nov","Oct","Dec","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep"]
.iter().any(|m| h.contains(m))
}).unwrap_or(false);
if has_timestamp {
result.push(clean);
} else {
// Add timestamp prefix
// Use the timestamp from the previous line if available, otherwise use current time
let ts = if !result.is_empty() {
// Try to extract timestamp from previous result line
extract_timestamp(&result.last().cloned().unwrap_or_default())
.unwrap_or_else(|| now.format("%Y-%m-%d %H:%M:%S%.3f").to_string())
} else {
now.format("%Y-%m-%d %H:%M:%S%.3f").to_string()
};
result.push(format!("[{}] {}", ts, clean));
}
}
result
}
/// Strip ANSI escape codes from a string
fn strip_ansi(s: &str) -> String {
let mut result = String::with_capacity(s.len());
let mut in_escape = false;
for c in s.chars() {
if c == '\x1b' {
in_escape = true;
} else if in_escape {
if c == 'm' || c == 'H' || c == 'J' || c == 'K' || c == 'A' || c == 'B' || c == 'C' || c == 'D' {
in_escape = false;
}
} else {
result.push(c);
}
}
// Also handle bracket escape sequences like \x1b[0m
let mut result2 = String::with_capacity(result.len());
let mut chars = result.chars().peekable();
while let Some(c) = chars.next() {
if c == '\x1b' && chars.peek() == Some(&'[') {
chars.next(); // consume '['
// consume until 'm' or letter
while let Some(ch) = chars.next() {
if ch.is_ascii_alphabetic() {
break;
}
}
} else {
result2.push(c);
}
}
result2
}
/// Try to extract a timestamp from a log line
fn extract_timestamp(line: &str) -> Option<String> {
let bytes = line.as_bytes();
let n = bytes.len();
let mut i = 0;
while i < n {
if bytes[i].is_ascii_digit() && i + 10 <= n {
// Match date part: YYYY-MM-DD
let is_date = bytes[i + 4] == b'-'
&& bytes[i + 7] == b'-'
&& bytes[i..i + 4].iter().all(|b| b.is_ascii_digit())
&& bytes[i + 5..i + 7].iter().all(|b| b.is_ascii_digit())
&& bytes[i + 8..i + 10].iter().all(|b| b.is_ascii_digit());
if is_date {
let mut end = i + 10;
// Optional time part: "T" or " " followed by HH:MM:SS(.mmm)
let sep = bytes.get(end).copied();
let time_start = if matches!(sep, Some(b'T')) {
Some(end + 1)
} else if matches!(sep, Some(b' '))
&& end + 8 <= n
&& bytes[end + 1].is_ascii_digit()
{
Some(end + 1)
} else {
None
};
if let Some(ts) = time_start {
let mut j = ts;
while j < n
&& (bytes[j].is_ascii_digit() || bytes[j] == b':' || bytes[j] == b'.')
{
j += 1;
}
if j > ts + 5 {
end = j;
if bytes.get(end) == Some(&b'Z') {
end += 1;
}
}
}
return Some(line[i..end].to_string());
}
}
i += 1;
}
None
}
// ─── Router ──────────────────────────────────────────────────────────────────
pub fn router() -> axum::Router<AppState> {
axum::Router::new()
.route("/api/v2/service/start", axum::routing::post(start_service))
.route("/api/v2/service/stop", axum::routing::post(stop_service))
.route("/api/v1/admin/rebuild-embeddings", axum::routing::post(rebuild_embeddings))
// NOTE: /api/v1/mbe/health is already registered in server.rs (line 192)
}
/// GET /api/v1/admin/services/test-embedding — real embedding test
/// Tests the actual embedding pipeline: generates vectors, checks dimension,
/// verifies semantic similarity, and reports which server/model is used.
pub async fn test_embedding(
State(_state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
use crate::core::embedding::Embedder;
let embedder = Embedder::new("embeddinggemma-300m".to_string());
let url = std::env::var("MOMENTRY_EMBED_URL")
.unwrap_or_else(|_| "http://localhost:11437".to_string());
// Detect server type from URL port
let server_type = if url.contains("11437") {
"llama.cpp GGUF Q8"
} else if url.contains("11436") {
"Python Flask (safetensors fp32)"
} else {
"unknown"
};
let mut result = serde_json::json!({
"url": url,
"server_type": server_type,
"model": "embeddinggemma-300m",
});
// Test 1: Basic embedding (dimension check)
let start = std::time::Instant::now();
match embedder.embed_text("hello embedding test").await {
Ok(vec) => {
let elapsed_ms = start.elapsed().as_millis();
result["ok"] = serde_json::json!(true);
result["dimension"] = serde_json::json!(vec.len());
result["dimension_ok"] = serde_json::json!(vec.len() == 768);
result["latency_ms"] = serde_json::json!(elapsed_ms);
}
Err(e) => {
result["ok"] = serde_json::json!(false);
result["error"] = serde_json::json!(format!("{}", e));
return Ok(Json(result));
}
}
// Test 2: Semantic similarity (similar vs different)
let doc_guitar = "A man is playing guitar on stage in front of an audience";
let doc_cooking = "Someone is cooking pasta in the kitchen with tomatoes";
let query_guitar = "guitar music performance";
let query_cooking = "cooking food recipe";
let (dg, dc, qg, qc) = match (
embedder.embed_document(doc_guitar).await,
embedder.embed_document(doc_cooking).await,
embedder.embed_query(query_guitar).await,
embedder.embed_query(query_cooking).await,
) {
(Ok(a), Ok(b), Ok(c), Ok(d)) => (a, b, c, d),
_ => {
result["similarity_test"] = serde_json::json!("failed to generate embeddings");
return Ok(Json(result));
}
};
let cos = |a: &[f32], b: &[f32]| -> f32 {
let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
let na: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
let nb: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
if na > 0.0 && nb > 0.0 { dot / (na * nb) } else { 0.0 }
};
let sim_match = cos(&dg, &qg); // guitar doc vs guitar query
let sim_cross = cos(&dg, &qc); // guitar doc vs cooking query
let sim_match2 = cos(&dc, &qc); // cooking doc vs cooking query
result["similarity"] = serde_json::json!({
"guitar_match": format!("{:.3}", sim_match),
"cooking_match": format!("{:.3}", sim_match2),
"cross_mismatch": format!("{:.3}", sim_cross),
"separation_ok": sim_match > sim_cross + 0.05,
});
// Test 3: Chinese support
let zh_doc = "這部影片展示了一個人在廚房烹飪美食";
let zh_query = "有人在廚房做菜";
if let (Ok(zd), Ok(zq)) = (
embedder.embed_document(zh_doc).await,
embedder.embed_query(zh_query).await,
) {
let sim_zh = cos(&zd, &zq);
result["chinese_ok"] = serde_json::json!(sim_zh > 0.3);
result["chinese_similarity"] = serde_json::json!(format!("{:.3}", sim_zh));
}
// Test 4: Consistency (same text = same vector)
let e1 = embedder.embed_text("consistency test").await;
let e2 = embedder.embed_text("consistency test").await;
if let (Ok(a), Ok(b)) = (e1, e2) {
let sim = cos(&a, &b);
result["consistency_ok"] = serde_json::json!(sim > 0.999);
}
Ok(Json(result))
}
/// GET /api/v1/admin/services/test-chat — real chat LLM test
/// Sends an actual prompt and verifies a text response is generated.
pub async fn test_chat(
State(_state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()
.unwrap();
let chat_url = std::env::var("MOMENTRY_LLM_CHAT_URL")
.unwrap_or_else(|_| "http://localhost:8080/v1/chat/completions".to_string());
let model = std::env::var("MOMENTRY_LLM_CHAT_MODEL")
.unwrap_or_else(|_| "gemma-4-12b-it".to_string());
let mut result = serde_json::json!({
"url": chat_url,
"model": model,
});
// Test 1: Health check
let base_url = chat_url.replace("/v1/chat/completions", "");
let health = client.get(format!("{}/health", base_url)).send().await;
match health {
Ok(resp) if resp.status().is_success() => {
let body: serde_json::Value = resp.json().await.unwrap_or_default();
result["health"] = serde_json::json!("ok");
if let Some(status) = body.get("status").and_then(|s| s.as_str()) {
result["health_detail"] = serde_json::json!(status);
}
}
Ok(resp) => {
result["ok"] = serde_json::json!(false);
result["error"] = serde_json::json!(format!("health check failed: HTTP {}", resp.status()));
return Ok(Json(result));
}
Err(e) => {
result["ok"] = serde_json::json!(false);
result["error"] = serde_json::json!(format!("connection failed: {}", e));
return Ok(Json(result));
}
}
// Test 2: Real text generation
let start = std::time::Instant::now();
let body = serde_json::json!({
"model": model,
"messages": [
{"role": "user", "content": "Reply with exactly: OK"}
],
"max_tokens": 100,
"temperature": 0.1,
});
match client.post(&chat_url).json(&body).send().await {
Ok(resp) if resp.status().is_success() => {
let data: serde_json::Value = resp.json().await.unwrap_or_default();
let elapsed_ms = start.elapsed().as_millis();
// Check content first, fallback to reasoning_content (gemma-4 reasoning format)
let text = data
.pointer("/choices/0/message/content")
.and_then(|c| c.as_str())
.filter(|s| !s.is_empty())
.or_else(|| {
data.pointer("/choices/0/message/reasoning_content")
.and_then(|c| c.as_str())
})
.unwrap_or("");
let tokens = data.pointer("/usage/total_tokens").and_then(|t| t.as_i64()).unwrap_or(0);
result["ok"] = serde_json::json!(!text.is_empty());
result["response_text"] = serde_json::json!(text.trim());
result["latency_ms"] = serde_json::json!(elapsed_ms);
result["total_tokens"] = serde_json::json!(tokens);
}
Ok(resp) => {
result["ok"] = serde_json::json!(false);
result["error"] = serde_json::json!(format!("generation failed: HTTP {}", resp.status()));
}
Err(e) => {
result["ok"] = serde_json::json!(false);
result["error"] = serde_json::json!(format!("generation error: {}", e));
}
}
Ok(Json(result))
}
/// GET /api/v1/admin/services/test-vlm — real vision (multimodal) test
/// Sends a 64x64 dual-color image (top red, bottom blue) and verifies
/// the model can identify both colors — proving true multimodal capability.
pub async fn test_vlm(
State(_state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(120))
.build()
.unwrap();
let vlm_url = std::env::var("MOMENTRY_LLM_VISION_URL")
.unwrap_or_else(|_| "http://localhost:8080/v1/chat/completions".to_string());
let model = std::env::var("MOMENTRY_LLM_VISION_MODEL")
.unwrap_or_else(|_| "gemma-4-12b-it".to_string());
let mut result = serde_json::json!({
"url": vlm_url,
"model": model,
});
// 64x64 PNG: top half red (#e00000), bottom half blue (#0000e0)
// Tests actual multimodal capability — model must SEE the image
let test_image = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAAeElEQVR4nO3PAQkAQAyAwPVP+VE+xAYiCAY4582o4wUNyOMFDcjjBQ3I4wUNyOMFDcjjBQ3I4wUNyOMFDcjjBQ3I4wUNyOMF2wEacLCACxqQxwsakMcLGpDHCxqQxwsakMcLGpDHCxqQxwsakMcLGpDHCxqQxwtWffudANN+uHrLAAAAAElFTkSuQmCC";
let start = std::time::Instant::now();
let body = serde_json::json!({
"model": model,
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "What are the two colors in this image? Answer briefly."},
{"type": "image_url", "image_url": {"url": format!("data:image/png;base64,{}", test_image)}}
]
}],
"max_tokens": 500,
"temperature": 0.1,
});
match client.post(&vlm_url).json(&body).send().await {
Ok(resp) if resp.status().is_success() => {
let data: serde_json::Value = resp.json().await.unwrap_or_default();
let elapsed_ms = start.elapsed().as_millis();
// gemma-4 reasoning format: check content first, then reasoning_content
let text = data
.pointer("/choices/0/message/content")
.and_then(|c| c.as_str())
.filter(|s| !s.is_empty())
.or_else(|| {
data.pointer("/choices/0/message/reasoning_content")
.and_then(|c| c.as_str())
})
.unwrap_or("");
let lower = text.to_lowercase();
// Multimodal verification: model must identify BOTH colors
let sees_red = lower.contains("red") || lower.contains("赤");
let sees_blue = lower.contains("blue") || lower.contains("青");
let finish_reason = data.pointer("/choices/0/finish_reason")
.and_then(|f| f.as_str())
.unwrap_or("");
let tokens = data.pointer("/usage/total_tokens")
.and_then(|t| t.as_i64())
.unwrap_or(0);
result["ok"] = serde_json::json!(!text.is_empty());
result["multimodal_ok"] = serde_json::json!(sees_red && sees_blue);
result["sees_red"] = serde_json::json!(sees_red);
result["sees_blue"] = serde_json::json!(sees_blue);
result["response_text"] = serde_json::json!(text.trim());
result["latency_ms"] = serde_json::json!(elapsed_ms);
result["total_tokens"] = serde_json::json!(tokens);
result["finish_reason"] = serde_json::json!(finish_reason);
}
Ok(resp) => {
result["ok"] = serde_json::json!(false);
result["error"] = serde_json::json!(format!("VLM failed: HTTP {}", resp.status()));
}
Err(e) => {
result["ok"] = serde_json::json!(false);
result["error"] = serde_json::json!(format!("VLM error: {}", e));
}
}
Ok(Json(result))
}
/// GET /api/v1/admin/services/test-markbase — real MarkBase API test
pub async fn test_markbase(
State(_state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(15))
.build()
.unwrap();
let markbase_url = std::env::var("MARKBASE_URL")
.unwrap_or_else(|_| "http://localhost:11438".to_string());
let mut result = serde_json::json!({
"url": markbase_url,
});
// Test 1: Health via /api/v2/health (MarkBase's actual health endpoint)
match client.get(format!("{}/api/v2/health", markbase_url)).send().await {
Ok(resp) if resp.status().is_success() => {
result["health"] = serde_json::json!("ok");
let body: serde_json::Value = resp.json().await.unwrap_or_default();
if !body.is_null() {
result["health_detail"] = serde_json::json!(body.to_string().chars().take(100).collect::<String>());
}
}
Ok(resp) => {
// Fallback: try /status
match client.get(format!("{}/status", markbase_url)).send().await {
Ok(r) if r.status().is_success() => {
result["health"] = serde_json::json!("ok");
result["health_detail"] = serde_json::json!("/status");
}
_ => {
result["ok"] = serde_json::json!(false);
result["error"] = serde_json::json!(format!("health failed: HTTP {}", resp.status()));
return Ok(Json(result));
}
}
}
Err(e) => {
result["ok"] = serde_json::json!(false);
result["error"] = serde_json::json!(format!("connection failed: {}", e));
return Ok(Json(result));
}
}
// Test 2: Web UI responds (MarkBase serves a web interface)
let start = std::time::Instant::now();
match client.get(&markbase_url).send().await {
Ok(resp) if resp.status().is_success() => {
let elapsed_ms = start.elapsed().as_millis();
let body = resp.text().await.unwrap_or_default();
let has_html = body.contains("<html") || body.contains("<!DOCTYPE");
let has_app = body.contains("MarkBase") || body.contains("markbase") || body.contains("app");
result["ok"] = serde_json::json!(has_html);
result["web_ui"] = serde_json::json!(has_html);
result["latency_ms"] = serde_json::json!(elapsed_ms);
if has_app {
result["app_detected"] = serde_json::json!(true);
}
}
Ok(resp) => {
result["ok"] = serde_json::json!(false);
result["error"] = serde_json::json!(format!("web UI failed: HTTP {}", resp.status()));
}
Err(e) => {
result["ok"] = serde_json::json!(false);
result["error"] = serde_json::json!(format!("web UI error: {}", e));
}
}
Ok(Json(result))
}
/// GET /api/v1/admin/services/test-proxy — real reverse-proxy functional test.
/// Verifies every route of the proxy (8888) actually round-trips:
/// 1. /health → proxy alive
/// 2. / (static SPA) → dist/index.html served with fallback
/// 3. /api/v1/health (via proxy) → forwarded to Core API 3002
/// 4. /api/v2/health (via proxy) → forwarded to MarkBase 11438
/// 5. /update-api/api/v1/gitea/latest (via proxy) → forwarded to update server 3100
/// 6. /api/v1/system-stats → local handler (CPU/mem/disk)
/// 7. /api/v1/admin/services/status → proxy's own service-status endpoint
pub async fn test_proxy(
State(_state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let proxy_base = std::env::var("MOMENTRY_PROXY_URL")
.unwrap_or_else(|_| "http://127.0.0.1:8888".to_string());
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(20))
.build()
.unwrap();
let mut result = serde_json::json!({});
let mut all_ok = true;
// ── 1. Health ──
let t = std::time::Instant::now();
let health_ok = client.get(format!("{}/health", proxy_base))
.send().await
.map(|r| r.status().is_success())
.unwrap_or(false);
result["health"] = serde_json::json!({ "ok": health_ok, "latency_ms": t.elapsed().as_millis() });
if !health_ok { all_ok = false; }
// ── 2. Static SPA (index.html served, SPA fallback works) ──
let t = std::time::Instant::now();
let (static_ok, static_len) = match client.get(format!("{}/", proxy_base)).send().await {
Ok(r) => {
let body = r.text().await.unwrap_or_default();
(body.contains("<!DOCTYPE html") || body.contains("<html"), body.len())
}
Err(_) => (false, 0),
};
result["static"] = serde_json::json!({ "ok": static_ok, "html_bytes": static_len, "latency_ms": t.elapsed().as_millis() });
if !static_ok { all_ok = false; }
// ── 3. /api/* → Core API 3002 (login round-trip: proxy must forward to
// core postgres accounts + JWT, not intercept locally) ──
let t = std::time::Instant::now();
let core_ok = match client
.post(format!("{}/api/v1/auth/login", proxy_base))
.json(&serde_json::json!({ "username": "demo", "password": "demo123" }))
.send()
.await
{
Ok(r) if r.status().is_success() => {
let j: serde_json::Value = r.json().await.unwrap_or_default();
j.get("success").and_then(|s| s.as_bool()).unwrap_or(false)
&& j.get("token").and_then(|s| s.as_str()).map(|s| !s.is_empty()).unwrap_or(false)
}
_ => false,
};
result["core"] = serde_json::json!({ "ok": core_ok, "note": "login→core round-trip", "latency_ms": t.elapsed().as_millis() });
if !core_ok { all_ok = false; }
// ── 4. /api/v2/* → MarkBase 11438 ──
let t = std::time::Instant::now();
let mb_ok = match client.get(format!("{}/api/v2/health", proxy_base)).send().await {
Ok(r) if r.status().is_success() => {
let j: serde_json::Value = r.json().await.unwrap_or_default();
j.get("service").and_then(|s| s.as_str()).is_some()
}
_ => false,
};
result["markbase"] = serde_json::json!({ "ok": mb_ok, "latency_ms": t.elapsed().as_millis() });
if !mb_ok { all_ok = false; }
// ── 5. /update-api/* → Update server 3100 ──
let t = std::time::Instant::now();
let upd_ok = match client.get(format!("{}/update-api/api/v1/gitea/latest", proxy_base)).send().await {
Ok(r) if r.status().is_success() => {
let j: serde_json::Value = r.json().await.unwrap_or_default();
j.get("repos").and_then(|r| r.as_array()).map(|a| !a.is_empty()).unwrap_or(false)
}
_ => false,
};
result["update_server"] = serde_json::json!({ "ok": upd_ok, "latency_ms": t.elapsed().as_millis() });
if !upd_ok { all_ok = false; }
// ── 6. /api/v1/system-stats (proxy local handler) ──
let t = std::time::Instant::now();
let stats_ok = match client.get(format!("{}/api/v1/system-stats", proxy_base)).send().await {
Ok(r) if r.status().is_success() => {
let j: serde_json::Value = r.json().await.unwrap_or_default();
j.get("cpu_used_percent").is_some()
}
_ => false,
};
result["system_stats"] = serde_json::json!({ "ok": stats_ok, "latency_ms": t.elapsed().as_millis() });
if !stats_ok { all_ok = false; }
// ── 7. Proxy's own service-status endpoint ──
let t = std::time::Instant::now();
let svc_ok = match client.get(format!("{}/api/v1/admin/services/status?name=core", proxy_base)).send().await {
Ok(r) if r.status().is_success() => {
let j: serde_json::Value = r.json().await.unwrap_or_default();
j.get("running").and_then(|r| r.as_bool()).unwrap_or(false)
}
_ => false,
};
result["service_status"] = serde_json::json!({ "ok": svc_ok, "latency_ms": t.elapsed().as_millis() });
if !svc_ok { all_ok = false; }
result["ok"] = serde_json::json!(all_ok);
result["proxy_url"] = serde_json::json!(proxy_base);
Ok(Json(result))
}
/// GET /api/v1/admin/services/test-core — real Core API functional test
/// Tests the momentry server's key endpoints: DB, files, search, Qdrant.
pub async fn test_core(
State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let mut result = serde_json::json!({});
let mut all_ok = true;
// ── 1. Health check (basic liveness) ──
result["health"] = serde_json::json!("ok"); // if we got here, server is running
// ── 2. Database: count videos ──
let db_start = std::time::Instant::now();
let video_count: i64 = sqlx::query_scalar(
&format!("SELECT COUNT(*) FROM {}", crate::core::db::schema::table_name("videos")),
)
.fetch_one(state.db.pool())
.await
.unwrap_or(-1);
let db_ok = video_count >= 0;
let db_ms = db_start.elapsed().as_millis();
result["database"] = serde_json::json!({
"ok": db_ok,
"video_count": video_count,
"latency_ms": db_ms,
});
if !db_ok { all_ok = false; }
// ── 3. Files listing (verifies API + DB pipeline) ──
let files_start = std::time::Instant::now();
let chunk_count: i64 = sqlx::query_scalar(
&format!("SELECT COUNT(*) FROM {}", crate::core::db::schema::table_name("chunk")),
)
.fetch_one(state.db.pool())
.await
.unwrap_or(-1);
let files_ok = chunk_count >= 0;
let files_ms = files_start.elapsed().as_millis();
result["chunks"] = serde_json::json!({
"ok": files_ok,
"chunk_count": chunk_count,
"latency_ms": files_ms,
});
if !files_ok { all_ok = false; }
// ── 4. Qdrant: check collections ──
let qdrant_start = std::time::Instant::now();
let qdrant_url = std::env::var("QDRANT_URL")
.unwrap_or_else(|_| "http://localhost:6333".to_string());
let qdrant_key = std::env::var("QDRANT_API_KEY").unwrap_or_default();
let mut qdrant_ok = false;
let mut qdrant_points = 0i64;
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(5))
.build()
.unwrap();
for collection in ["momentry_rule1", "_faces"] {
let url = format!("{}/collections/{}", qdrant_url, collection);
let mut req = client.get(&url);
if !qdrant_key.is_empty() {
req = req.header("api-key", &qdrant_key);
}
if let Ok(resp) = req.send().await {
if resp.status().is_success() {
qdrant_ok = true;
if let Ok(data) = resp.json::<serde_json::Value>().await {
if let Some(count) = data.pointer("/result/points_count").and_then(|c| c.as_i64()) {
qdrant_points += count;
}
}
}
}
}
let qdrant_ms = qdrant_start.elapsed().as_millis();
result["qdrant"] = serde_json::json!({
"ok": qdrant_ok,
"total_points": qdrant_points,
"latency_ms": qdrant_ms,
});
if !qdrant_ok { all_ok = false; }
// ── 5. Embedding service (quick ping) ──
let embed_url = std::env::var("MOMENTRY_EMBED_URL")
.unwrap_or_else(|_| "http://localhost:11436".to_string());
let embed_base = embed_url
.replace("/v1/embeddings", "")
.replace("/v1/chat/completions", "");
let embed_ok = client
.get(format!("{}/health", embed_base))
.send()
.await
.map(|r| r.status().is_success())
.unwrap_or(false);
result["embedding_service"] = serde_json::json!({
"ok": embed_ok,
"url": embed_base,
});
// ── 6. Output completeness (verifies pipeline data) ──
let complete_count: i64 = sqlx::query_scalar(
&format!(
"SELECT COUNT(*) FROM {} WHERE status = 'completed' AND file_type = 'video'",
crate::core::db::schema::table_name("videos")
),
)
.fetch_one(state.db.pool())
.await
.unwrap_or(0);
result["completed_videos"] = serde_json::json!(complete_count);
// ── 7. Processor results (pipeline health) ──
let processor_count: i64 = sqlx::query_scalar(
&format!(
"SELECT COUNT(*) FROM {} WHERE status = 'completed'",
crate::core::db::schema::table_name("processor_results")
),
)
.fetch_one(state.db.pool())
.await
.unwrap_or(0);
result["completed_processors"] = serde_json::json!(processor_count);
// ── Summary ──
result["ok"] = serde_json::json!(all_ok);
result["version"] = serde_json::json!(env!("BUILD_VERSION"));
result["summary"] = serde_json::json!({
"videos": video_count,
"completed": complete_count,
"chunks": chunk_count,
"qdrant_points": qdrant_points,
"processors_done": processor_count,
});
Ok(Json(result))
}
/// POST /api/v1/admin/rebuild-embeddings — rebuild text/scene embeddings
/// with the current (possibly updated) embedding model.
///
/// Body: `{ "collection": "momentry_rule1" | "_scenes" | "all", "file_uuid": "optional" }`
/// Uses the Rust `Embedder` (same code path as production).
pub async fn rebuild_embeddings(
State(state): State<AppState>,
Json(body): Json<serde_json::Value>,
) -> Result<Json<serde_json::Value>, StatusCode> {
use crate::core::embedding::Embedder;
use crate::core::db::{schema, QdrantDb};
let collection = body.get("collection").and_then(|v| v.as_str()).unwrap_or("all");
let file_uuid = body.get("file_uuid").and_then(|v| v.as_str());
let embedder = Embedder::new("embeddinggemma-300m".to_string());
let qdrant = QdrantDb::new();
let chunk_table = schema::table_name("chunk");
let scenes_table = schema::table_name("scenes");
let mut results = serde_json::json!({});
let t0 = std::time::Instant::now();
// ── Rebuild text chunks (sentence) → momentry_rule1 ──
if collection == "all" || collection == "momentry_rule1" {
let mut ok = 0usize;
let mut fail = 0usize;
// Clear existing points for this file_uuid (or all if no filter)
if let Some(uuid) = file_uuid {
let _ = qdrant.delete_points_by_filter("momentry_rule1", serde_json::json!({
"must": [{"key": "file_uuid", "match": {"value": uuid}}]
})).await;
} else {
// Delete all in collection: use empty filter to match everything
let _ = qdrant.delete_points_by_filter("momentry_rule1", serde_json::json!({})).await;
}
// Query chunks that need re-embedding
let query = if let Some(uuid) = file_uuid {
format!(
"SELECT chunk_id, text_content, start_frame, end_frame, start_time, end_time, chunk_type, file_uuid \
FROM {} WHERE chunk_type = 'sentence' AND text_content IS NOT NULL AND text_content != '' AND file_uuid = $1 \
ORDER BY id",
chunk_table
)
} else {
format!(
"SELECT chunk_id, text_content, start_frame, end_frame, start_time, end_time, chunk_type, file_uuid \
FROM {} WHERE chunk_type = 'sentence' AND text_content IS NOT NULL AND text_content != '' \
ORDER BY id",
chunk_table
)
};
let rows: Vec<(String, String, i64, i64, f64, f64, String, String)> = if file_uuid.is_some() {
sqlx::query_as(&query)
.bind(file_uuid.unwrap())
.fetch_all(state.db.pool())
.await
.unwrap_or_default()
} else {
sqlx::query_as(&query)
.fetch_all(state.db.pool())
.await
.unwrap_or_default()
};
let total = rows.len();
for (chunk_id, text, start_frame, end_frame, start_time, end_time, chunk_type, fuuid) in &rows {
match embedder.embed_document(text).await {
Ok(vector) => {
// Update PG embedding column
let vector_json = serde_json::to_string(&vector).unwrap_or_default();
let _ = sqlx::query(&format!(
"UPDATE {} SET embedding = $1::vector WHERE chunk_id = $2 AND file_uuid = $3",
chunk_table
))
.bind(&vector_json)
.bind(chunk_id)
.bind(fuuid)
.execute(state.db.pool())
.await;
// Upsert to Qdrant
let payload = crate::core::db::VectorPayload {
file_uuid: fuuid.clone(),
chunk_id: chunk_id.clone(),
chunk_type: chunk_type.clone(),
start_frame: *start_frame,
end_frame: *end_frame,
start_time: *start_time,
end_time: *end_time,
text: Some(text.clone()),
};
if qdrant.upsert_vector(chunk_id, &vector, payload).await.is_ok() {
ok += 1;
} else {
fail += 1;
}
}
Err(e) => {
tracing::error!("[rebuild-embed] Failed to embed {}: {}", chunk_id, e);
fail += 1;
}
}
}
results["momentry_rule1"] = serde_json::json!({
"total": total,
"ok": ok,
"fail": fail,
});
}
// ── Rebuild scene embeddings → _scenes ──
if collection == "all" || collection == "_scenes" {
let mut ok = 0usize;
let mut fail = 0usize;
// Clear existing scene points
if let Some(uuid) = file_uuid {
let _ = qdrant.delete_points_by_filter("_scenes", serde_json::json!({
"must": [{"key": "file_uuid", "match": {"value": uuid}}]
})).await;
} else {
// Delete all in _scenes: use empty filter to match everything
let _ = qdrant.delete_points_by_filter("_scenes", serde_json::json!({})).await;
}
// Query scenes with VLM descriptions
let query = if let Some(uuid) = file_uuid {
format!(
"SELECT id, file_uuid, scene_index, timestamp_sec, frame_number, \
COALESCE(vlm_description_localized, vlm_description) as description \
FROM {} WHERE file_uuid = $1 AND (vlm_description_localized IS NOT NULL OR vlm_description IS NOT NULL) \
ORDER BY id",
scenes_table
)
} else {
format!(
"SELECT id, file_uuid, scene_index, timestamp_sec, frame_number, \
COALESCE(vlm_description_localized, vlm_description) as description \
FROM {} WHERE vlm_description_localized IS NOT NULL OR vlm_description IS NOT NULL \
ORDER BY id",
scenes_table
)
};
let rows: Vec<(i64, String, i32, f64, i64, String)> = if file_uuid.is_some() {
sqlx::query_as(&query)
.bind(file_uuid.unwrap())
.fetch_all(state.db.pool())
.await
.unwrap_or_default()
} else {
sqlx::query_as(&query)
.fetch_all(state.db.pool())
.await
.unwrap_or_default()
};
let total = rows.len();
for (scene_id, fuuid, scene_index, timestamp_sec, frame_number, description) in &rows {
match embedder.embed_document(description).await {
Ok(vector) => {
let point_id_str = format!("{}_s{}", fuuid, scene_index);
let point_id = {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
point_id_str.hash(&mut hasher);
hasher.finish()
};
if qdrant.upsert_scene_embedding(
point_id,
&vector,
fuuid,
*scene_index as usize,
*timestamp_sec,
*frame_number as u32,
description,
None,
&[],
&[],
).await.is_ok() {
ok += 1;
} else {
fail += 1;
}
}
Err(e) => {
tracing::error!("[rebuild-embed] Failed to embed scene {}: {}", scene_id, e);
fail += 1;
}
}
}
results["_scenes"] = serde_json::json!({
"total": total,
"ok": ok,
"fail": fail,
});
}
results["elapsed_ms"] = serde_json::json!(t0.elapsed().as_millis());
results["collection"] = serde_json::json!(collection);
results["file_uuid"] = serde_json::json!(file_uuid);
Ok(Json(results))
}
/// GET /api/v1/admin/components — full component registry with versions
/// Returns all system components: binaries, tools, scripts, dists, externals
/// Each with current file hash, size, repo mapping, and latest Gitea commit.
pub async fn components_registry(
State(_state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
use std::os::unix::fs::MetadataExt;
// Read component registry
let registry_path = "/Users/accusys/momentry-update/config/components.json";
let registry_content = match std::fs::read_to_string(registry_path) {
Ok(c) => c,
Err(e) => {
return Ok(Json(serde_json::json!({
"error": format!("Cannot read {}: {}", registry_path, e),
})));
}
};
let registry: serde_json::Value = match serde_json::from_str(&registry_content) {
Ok(v) => v,
Err(e) => {
return Ok(Json(serde_json::json!({
"error": format!("Invalid JSON in components.json: {}", e),
})));
}
};
let components = registry.get("components")
.and_then(|c| c.as_array())
.cloned()
.unwrap_or_default();
let mut result_components = Vec::new();
for comp in &components {
let name = comp.get("name").and_then(|n| n.as_str()).unwrap_or("");
let path = comp.get("path").and_then(|p| p.as_str()).unwrap_or("");
let comp_type = comp.get("type").and_then(|t| t.as_str()).unwrap_or("");
let repo = comp.get("repo").and_then(|r| r.as_str()).unwrap_or("");
let mut entry = comp.clone();
// Check file existence and get version info
let file_meta = std::fs::metadata(path);
match &file_meta {
Ok(meta) => {
entry["exists"] = serde_json::json!(true);
entry["size_bytes"] = serde_json::json!(meta.len());
// Get MD5 hash (first 8 chars) for binary/tool/script files
if comp_type != "dist" {
let hash_output = std::process::Command::new("/sbin/md5")
.arg("-q")
.arg(path)
.output();
if let Ok(out) = hash_output {
let hash = String::from_utf8_lossy(&out.stdout).trim().to_string();
if !hash.is_empty() {
entry["file_hash"] = serde_json::json!(hash[..8.min(hash.len())]);
}
}
}
// Last modified
if let Ok(modified) = meta.modified() {
let secs = modified
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64;
if let Some(dt) = chrono::DateTime::from_timestamp(secs, 0) {
let local = dt.with_timezone(&chrono::Local);
entry["last_modified"] = serde_json::json!(local.format("%Y-%m-%d %H:%M").to_string());
}
}
// For dist type, hash the index.html
if comp_type == "dist" {
let index_path = format!("{}/index.html", path.trim_end_matches('/'));
if let Ok(out) = std::process::Command::new("/sbin/md5").arg("-q").arg(&index_path).output() {
let hash = String::from_utf8_lossy(&out.stdout).trim().to_string();
if !hash.is_empty() {
entry["file_hash"] = serde_json::json!(hash[..8.min(hash.len())]);
}
}
// Count files in dist
if let Ok(entries) = std::fs::read_dir(path) {
let count = entries.filter_map(|e| e.ok()).count();
entry["file_count"] = serde_json::json!(count);
}
}
}
Err(_) => {
entry["exists"] = serde_json::json!(false);
}
}
result_components.push(entry);
}
// Fetch Gitea commits from update server (localhost, avoids TCC Local Network blocks)
// The update server (port 3100) already proxies Gitea commits
let update_server_url = "http://127.0.0.1:3100";
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(10))
.build()
.unwrap();
// Get unique repos
let mut repos: std::collections::HashSet<String> = std::collections::HashSet::new();
for comp in &components {
if let Some(r) = comp.get("repo").and_then(|r| r.as_str()) {
repos.insert(r.to_string());
}
}
let mut repo_commits = serde_json::Map::new();
// Fetch all repo commits from update server in one call
let gitea_latest_url = format!("{}/api/v1/gitea/latest", update_server_url);
if let Ok(resp) = client.get(&gitea_latest_url).send().await {
if resp.status().is_success() {
if let Ok(gitea_data) = resp.json::<serde_json::Value>().await {
if let Some(gitea_repos) = gitea_data.get("repos").and_then(|r| r.as_array()) {
for r in gitea_repos {
let repo_name = r.get("repo").and_then(|r| r.as_str()).unwrap_or("");
let commit = r.get("commit").and_then(|c| c.as_str()).unwrap_or("");
let date = r.get("date").and_then(|d| d.as_str()).unwrap_or("");
if !repo_name.is_empty() && !commit.is_empty() {
repo_commits.insert(repo_name.to_string(), serde_json::json!({
"commit": commit,
"date": date,
"message": "", // update server doesn't provide message
}));
}
}
}
}
}
}
// For repos not in update server's list, try fetching message from Gitea directly
// (only works if TCC allows; silently skip on failure)
if repo_commits.is_empty() {
// Fallback: try direct Gitea access (may fail due to TCC)
let update_config_path = "/Users/accusys/momentry-update/config/update_server.json";
let (gitea_url, gitea_token) = if let Ok(cfg_content) = std::fs::read_to_string(update_config_path) {
if let Ok(cfg) = serde_json::from_str::<serde_json::Value>(&cfg_content) {
(
cfg.get("gitea_url").and_then(|u| u.as_str()).unwrap_or("http://192.168.110.210:3000").to_string(),
cfg.get("gitea_token").and_then(|t| t.as_str()).unwrap_or("").to_string(),
)
} else {
("http://192.168.110.210:3000".to_string(), String::new())
}
} else {
("http://192.168.110.210:3000".to_string(), String::new())
};
for repo in &repos {
let url = format!("{}/api/v1/repos/{}/commits?limit=1&sha=main", gitea_url, repo);
let mut req = client.get(&url);
if !gitea_token.is_empty() {
req = req.header("Authorization", format!("token {}", gitea_token));
}
if let Ok(resp) = req.send().await {
if resp.status().is_success() {
if let Ok(commits) = resp.json::<serde_json::Value>().await {
if let Some(first) = commits.as_array().and_then(|a| a.first()) {
let sha = first.get("sha").and_then(|s| s.as_str()).unwrap_or("");
let msg = first.pointer("/commit/message")
.and_then(|m| m.as_str())
.unwrap_or("")
.lines()
.next()
.unwrap_or("");
let date = first.pointer("/commit/committer/date")
.and_then(|d| d.as_str())
.unwrap_or("");
if !sha.is_empty() {
repo_commits.insert(repo.clone(), serde_json::json!({
"commit": sha,
"message": msg,
"date": date,
}));
}
}
}
}
}
}
}
// Add repo commit info to each component
for entry in result_components.iter_mut() {
if let Some(repo) = entry.get("repo").and_then(|r| r.as_str()) {
if let Some(commit_info) = repo_commits.get(repo) {
entry["gitea_commit"] = commit_info["commit"].clone();
entry["gitea_message"] = commit_info["message"].clone();
entry["gitea_date"] = commit_info["date"].clone();
}
}
}
// Group by type for organized display
let mut by_type: std::collections::BTreeMap<String, Vec<&serde_json::Value>> = std::collections::BTreeMap::new();
for entry in &result_components {
let t = entry.get("type").and_then(|t| t.as_str()).unwrap_or("other");
by_type.entry(t.to_string()).or_default().push(entry);
}
let mut grouped = serde_json::Map::new();
for (t, comps) in by_type {
grouped.insert(t, serde_json::json!(comps));
}
Ok(Json(serde_json::json!({
"ok": true,
"components": result_components,
"by_type": grouped,
"total": result_components.len(),
})))
}
/// Public routes (no auth required) for service status and log probing
pub fn public_routes() -> axum::Router<AppState> {
axum::Router::new()
.route("/api/v1/admin/services/status", axum::routing::get(service_status))
.route("/api/v1/admin/services/log", axum::routing::get(service_log))
.route("/api/v1/admin/services/test-embedding", axum::routing::get(test_embedding))
.route("/api/v1/admin/services/test-chat", axum::routing::get(test_chat))
.route("/api/v1/admin/services/test-vlm", axum::routing::get(test_vlm))
.route("/api/v1/admin/services/test-markbase", axum::routing::get(test_markbase))
.route("/api/v1/admin/services/test-proxy", axum::routing::get(test_proxy))
.route("/api/v1/admin/services/test-core", axum::routing::get(test_core))
.route("/api/v1/admin/components", axum::routing::get(components_registry))
}