C: C1 peer status routes

This commit is contained in:
ari committed 2026-10-19 22:35:51 -04:00
1 parent b1338fdc36
commit bec0ab5736
3 files changed
+227 -4

No files matched your search

+18
View File
@@ -17,6 +17,8 @@ Base: `http://127.0.0.1:1984`. Errors are `{"error":{"code","message"}}`.
| `GET /api/v1/docker/ps` | `503` when Docker is unavailable |
| `GET /api/v1/docker/containers/{name}` | |
| `GET /api/v1/docker/containers/{name}/logs?tail=&since=&follow=0\|1` | JSON, or SSE with events `stdout`/`stderr` |
| `GET /api/v1/peers` | consolidator only; sorted status list; absent when peers are disabled |
| `GET /api/v1/peers/{peer}` | one peer's status object; unknown name is 404 |
```sh
TOKEN=slinuxm_...
@@ -24,6 +26,22 @@ curl -H "Authorization: Bearer $TOKEN" 'http://127.0.0.1:1984/api/v1/systemd/uni
curl -N -H "Authorization: Bearer $TOKEN" 'http://127.0.0.1:1984/api/v1/journal/follow?priority=err'
```
### Peers
Present only when `[peers] enabled = true`. The same inbound token as the rest of `/api/v1` is required. `GET /api/v1/peers` returns `{"peers":[...]}` sorted by name, including disabled peers. `GET /api/v1/peers/{peer}` returns one object, not wrapped:
```json
{
"name": "beta",
"enabled": true,
"url": "http://beta:1984",
"server": { "up": true, "since": "2026-10-19T10:00:00Z", "last_checked": "2026-10-19T10:00:09Z", "last_error": null, "latency_ms": 1 },
"api": { "up": true, "since": "2026-10-19T10:00:00Z", "last_checked": "2026-10-19T10:00:05Z", "last_error": null, "latency_ms": 7, "auth": "ok", "peer_version": "0.1.0" }
}
```
`server` is the TCP check and `api` is the authenticated ping. `auth` is `ok`, `rejected` or `unknown`. Before the first check, `up` is false, `auth` is `unknown` and the timestamps are null. An unknown name is `404` `{"error":{"code":"not_found","message":"peer <name>: unknown peer"}}`.
## MCP
Endpoint: `http://127.0.0.1:1984/mcp` (Streamable HTTP). Eight tools (`list_systemd_units`, `get_systemd_unit`, `list_systemd_timers`, `get_journal_logs`, `tail_journal`, `list_containers`, `get_container`, `get_container_logs`), two prompts (`diagnose_unit`, `container_health_report`) two resources (`systemd://units/failed`, `docker://containers`) and two resource templates (`systemd://unit/{name}`, `docker://container/{name}`, same JSON as `get_systemd_unit` and `get_container`; percent-encode unusual characters in the name). Log content is untrusted data and is labelled as such in tool results.
+49 -1
View File
@@ -1,4 +1,4 @@
//! Cross-cutting API tests: SSE lifecycle, 405 shape, name validation.
//! Cross-cutting API tests: SSE lifecycle, 405 shape, name validation, peers.
use std::sync::Arc;
use std::time::Duration;
@@ -14,6 +14,8 @@ use super::router;
use super::testutil::{get, json};
use crate::config::Config;
use crate::error::AppError;
use crate::peers::testing::{fake_state_with_peers, static_registry};
use crate::peers::types::{ApiStatus, AuthState, PeerName, PeerStatus, ServerStatus};
use crate::sources::fake::fake_state;
use crate::sources::{
ContainerStatus, ContainerSummary, DockerSource, JournalEntry, JournalQuery, JournalSource,
@@ -227,3 +229,49 @@ async fn invalid_names_and_state_are_400() {
let (s, _) = get(&app, "/docker/containers/ok").await;
assert_eq!(s, StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn peer_status_routes_follow_the_registry_snapshot() {
let peer = |name: &str| PeerStatus {
name: PeerName::parse(name).unwrap(),
enabled: true,
url: format!("http://{name}:1984"),
server: ServerStatus {
up: true,
..ServerStatus::default()
},
api: ApiStatus {
up: true,
auth: AuthState::Ok,
..ApiStatus::default()
},
};
let app = router(fake_state_with_peers(
Config::default(),
static_registry(vec![peer("gamma"), peer("beta")]),
));
let (s, b) = get(&app, "/peers").await;
assert_eq!(s, StatusCode::OK);
let body = json(&b);
let names: Vec<_> = body["peers"]
.as_array()
.unwrap()
.iter()
.map(|p| p["name"].as_str().unwrap().to_owned())
.collect();
assert_eq!(names, ["beta", "gamma"]);
let (s, b) = get(&app, "/peers/beta").await;
assert_eq!(s, StatusCode::OK);
assert_eq!(json(&b)["server"]["up"], true);
assert_eq!(json(&b)["api"]["auth"], "ok");
let (s, b) = get(&app, "/peers/nope").await;
assert_eq!(s, StatusCode::NOT_FOUND);
assert!(json(&b)["error"]["message"]
.as_str()
.unwrap()
.contains("nope"));
let bare = router(fake_state(Config::default()));
let (s, _) = get(&bare, "/peers").await;
assert_eq!(s, StatusCode::NOT_FOUND);
}
+160 -3
View File
@@ -1,12 +1,169 @@
//! Peer status and GET-only pass-through routes.
//!
//! Handlers are added here; the module is merged only when `state.peers` is
//! set, so a peer-less instance has no peers routes at all.
//! Merged only when `state.peers` is set, so a peer-less instance has no
//! peers routes at all. Pass-through lives in `crate::peers::proxy` so MCP
//! calls the same code.
use axum::Router;
use axum::extract::{Path, State};
use axum::routing::get;
use axum::{Json, Router};
use serde::Serialize;
use crate::error::AppError;
use crate::peers::types::PeerStatus;
use crate::state::AppState;
pub fn routes() -> Router<AppState> {
Router::new()
.route("/peers", get(list))
.route("/peers/{peer}", get(one))
}
#[derive(Serialize)]
struct PeerList {
peers: Vec<PeerStatus>,
}
fn registry(st: &AppState) -> Result<&crate::peers::PeerRegistry, AppError> {
st.peers
.as_deref()
.ok_or_else(|| AppError::NotFound("no such route".into()))
}
async fn list(State(st): State<AppState>) -> Result<Json<PeerList>, AppError> {
let peers = registry(&st)?.snapshot();
Ok(Json(PeerList { peers }))
}
async fn one(
State(st): State<AppState>,
Path(peer): Path<String>,
) -> Result<Json<PeerStatus>, AppError> {
Ok(Json(registry(&st)?.status(&peer)?))
}
#[cfg(test)]
mod tests {
use axum::http::StatusCode;
use super::super::router;
use super::super::testutil::{get, json};
use crate::config::Config;
use crate::peers::testing::{fake_state_with_peers, static_registry};
use crate::peers::types::{ApiStatus, AuthState, PeerName, PeerStatus, ServerStatus};
use crate::sources::fake::fake_state;
fn status(name: &str, enabled: bool, up: bool, auth: AuthState) -> PeerStatus {
PeerStatus {
name: PeerName::parse(name).unwrap(),
enabled,
url: format!("http://{name}:1984"),
server: ServerStatus {
up,
since: Some("2026-10-19T10:00:00Z".parse().unwrap()),
last_checked: Some("2026-10-19T10:00:09Z".parse().unwrap()),
last_error: None,
latency_ms: Some(1),
},
api: ApiStatus {
up,
since: Some("2026-10-19T10:00:00Z".parse().unwrap()),
last_checked: Some("2026-10-19T10:00:05Z".parse().unwrap()),
last_error: None,
latency_ms: Some(7),
auth,
peer_version: Some("0.1.0".into()),
},
}
}
fn app(statuses: Vec<PeerStatus>) -> axum::Router {
router(fake_state_with_peers(
Config::default(),
static_registry(statuses),
))
}
#[tokio::test]
async fn list_is_sorted_and_shaped() {
let app = app(vec![
status("gamma", false, false, AuthState::Unknown),
status("beta", true, true, AuthState::Ok),
]);
let (s, b) = get(&app, "/peers").await;
assert_eq!(s, StatusCode::OK);
let v = json(&b);
let peers = v["peers"].as_array().unwrap();
assert_eq!(peers.len(), 2);
assert_eq!(peers[0]["name"], "beta");
assert_eq!(peers[1]["name"], "gamma");
assert_eq!(peers[0]["enabled"], true);
assert_eq!(peers[1]["enabled"], false);
assert_eq!(peers[0]["url"], "http://beta:1984");
assert_eq!(peers[0]["server"]["up"], true);
assert_eq!(peers[0]["server"]["since"], "2026-10-19T10:00:00Z");
assert_eq!(peers[0]["server"]["last_checked"], "2026-10-19T10:00:09Z");
assert_eq!(peers[0]["server"]["last_error"], serde_json::Value::Null);
assert_eq!(peers[0]["server"]["latency_ms"], 1);
assert_eq!(peers[0]["api"]["up"], true);
assert_eq!(peers[0]["api"]["auth"], "ok");
assert_eq!(peers[0]["api"]["peer_version"], "0.1.0");
assert_eq!(peers[1]["api"]["auth"], "unknown");
assert_eq!(peers[1]["server"]["up"], false);
}
#[tokio::test]
async fn one_peer_is_the_object_not_a_list() {
let app = app(vec![status("beta", true, true, AuthState::Rejected)]);
let (s, b) = get(&app, "/peers/beta").await;
assert_eq!(s, StatusCode::OK);
let v = json(&b);
assert!(v.get("peers").is_none());
assert_eq!(v["name"], "beta");
assert_eq!(v["server"]["up"], true);
assert_eq!(v["api"]["up"], true);
assert_eq!(v["api"]["auth"], "rejected");
}
#[tokio::test]
async fn unknown_peer_is_not_found() {
let app = app(vec![status("beta", true, true, AuthState::Ok)]);
for name in ["nope", "Beta", "-beta"] {
let (s, b) = get(&app, &format!("/peers/{name}")).await;
assert_eq!(s, StatusCode::NOT_FOUND, "{name}");
assert_eq!(json(&b)["error"]["code"], "not_found");
assert_eq!(
json(&b)["error"]["message"],
format!("peer {name}: unknown peer")
);
}
}
#[tokio::test]
async fn empty_registry_lists_nothing() {
let (s, b) = get(&app(vec![]), "/peers").await;
assert_eq!(s, StatusCode::OK);
assert_eq!(json(&b)["peers"].as_array().unwrap().len(), 0);
}
#[tokio::test]
async fn routes_are_absent_when_peers_are_disabled() {
let app = router(fake_state(Config::default()));
for path in ["/peers", "/peers/beta"] {
let (s, b) = get(&app, path).await;
assert_eq!(s, StatusCode::NOT_FOUND, "{path}");
assert_eq!(json(&b)["error"]["code"], "not_found");
}
let (s, _) = get(&app, "/systemd/units").await;
assert_eq!(s, StatusCode::OK);
}
#[tokio::test]
async fn local_routes_stay_available() {
let app = app(vec![status("beta", true, true, AuthState::Ok)]);
let (s, _) = get(&app, "/systemd/units").await;
assert_eq!(s, StatusCode::OK);
let (s, _) = get(&app, "/journal").await;
assert_eq!(s, StatusCode::OK);
}
}