agentmux_srv/server/live_facts/
handler.rs1use std::collections::HashMap;
10
11use axum::extract::{Query, State};
12use axum::http::StatusCode;
13use axum::response::{IntoResponse, Response};
14use axum::Json;
15use serde_json::{json, Value};
16
17use super::query::{apply, status, Params};
18use crate::server::AppState;
19
20fn bad_request(message: String) -> Response {
21 (StatusCode::BAD_REQUEST, Json(json!({ "error": message }))).into_response()
22}
23
24pub(crate) fn is_status_view(query: &HashMap<String, String>) -> Result<bool, String> {
26 match query.get("view").map(|v| v.trim()) {
27 None | Some("") | Some("list") => Ok(false),
28 Some("status") => Ok(true),
29 Some(other) => Err(format!("unknown view {other:?}: use list or status")),
30 }
31}
32
33pub(crate) async fn answer(state: &AppState, query: &HashMap<String, String>) -> Result<Value, String> {
36 let params = Params::from_map(query, &state.hostname)?;
37 let compact = is_status_view(query)?;
38 let Json(mut body) = crate::server::http_health::handle_discovery(State(state.clone())).await;
39 let rows: Vec<Value> = match body.pointer_mut("/host/agents").map(Value::take) {
41 Some(Value::Array(rows)) => rows,
42 _ => Vec::new(),
43 };
44 let now_ms = agentmux_common::time::now_ms_u64();
45 let worker = state.clone();
46 let all_hosts = params.all_hosts;
47 let mut out = if compact {
48 tokio::task::spawn_blocking(move || status(&worker, rows, ¶ms, now_ms)).await.map_err(|e| e.to_string())?
49 } else {
50 let (agents, page) = tokio::task::spawn_blocking(move || apply(&worker, rows, ¶ms, now_ms)).await.map_err(|e| e.to_string())?;
51 body["host"]["agents"] = Value::Array(agents);
52 body["host"]["page"] = page;
53 body
54 };
55 if all_hosts {
56 out["peers"] = json!(state.lan_discovery.get_instances());
57 }
58 Ok(out)
59}
60
61pub(crate) async fn handle(State(state): State<AppState>, Query(query): Query<HashMap<String, String>>) -> Response {
62 match answer(&state, &query).await {
63 Ok(body) => Json(body).into_response(),
64 Err(e) => bad_request(e),
65 }
66}