Merge branch 'ws-e/rest-api' into integration/phase1
This commit is contained in:
commit
f65520f797
7 files changed
+798
-22
No files matched your search
@@ -64,15 +64,15 @@ Design: [`plan.md`](plan.md) · Review fixes: [`plan/review.md`](plan/review.md)
|
||||
## Phase 2 — Surfaces (parallel)
|
||||
|
||||
### WS-E REST API · [card](plan/workstreams/WS-E-rest.md)
|
||||
- [ ] **E1** `api::router(state)` using axum 0.8 `{name}` path syntax
|
||||
- [ ] **E2** `GET /systemd/units?state=`, `/systemd/units/{name}`, `/systemd/timers`
|
||||
- [ ] **E3** `GET /journal?unit=&priority=&lines=` with validation
|
||||
- [ ] **E4** `GET /journal/follow` SSE with keep-alive. Ends on disconnect or shutdown.
|
||||
- [ ] **E5** `GET /docker/ps`, `/docker/containers/{name}`, `/docker/containers/{name}/logs` (JSON, or SSE with `follow=1`)
|
||||
- [ ] **E6** `GET /healthz` on the public router
|
||||
- [ ] **E7** Consistent JSON error body from `AppError`
|
||||
- [ ] **E8** Handler tests against fake sources (`tower::ServiceExt::oneshot`)
|
||||
- [ ] **E9** Docker unavailable returns 503 on docker routes only
|
||||
- [x] **E1** `api::router(state)` using axum 0.8 `{name}` path syntax
|
||||
- [x] **E2** `GET /systemd/units?state=`, `/systemd/units/{name}`, `/systemd/timers`
|
||||
- [x] **E3** `GET /journal?unit=&priority=&lines=` with validation
|
||||
- [x] **E4** `GET /journal/follow` SSE with keep-alive. Ends on disconnect or shutdown.
|
||||
- [x] **E5** `GET /docker/ps`, `/docker/containers/{name}`, `/docker/containers/{name}/logs` (JSON, or SSE with `follow=1`)
|
||||
- [x] **E6** `GET /healthz` on the public router
|
||||
- [x] **E7** Consistent JSON error body from `AppError`
|
||||
- [x] **E8** Handler tests against fake sources (`tower::ServiceExt::oneshot`). Name/state validation is tested via a validating stub, not the fakes.
|
||||
- [x] **E9** Docker unavailable returns 503 on docker routes only
|
||||
|
||||
### WS-F MCP · [card](plan/workstreams/WS-F-mcp.md)
|
||||
- [ ] **F1** `TrackerService` with `#[tool_router]` and 8 tools
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
| Field | Value |
|
||||
|---|---|
|
||||
| Status | Backlog |
|
||||
| Status | Done (pending merge) |
|
||||
| Owner | — |
|
||||
| Phase | 2 (parallel) |
|
||||
| Depends on | P0 to start (fakes). A, B, C, D to finish. |
|
||||
@@ -48,3 +48,4 @@ Tick these in [`TODO.md`](../../TODO.md).
|
||||
## Log
|
||||
|
||||
- 2026-10-15: Card created.
|
||||
- 2026-10-15: Implemented on branch `ws-e/rest-api`. E1-E9 done. Query errors, missing routes and source errors all use the `AppError` JSON shape. `lines`/`tail` are rejected at 0 and clamped to `limits.max_*`; `priority` parsed via `Priority::from_str`; `state` validated by the source (400). SSE ends on disconnect, `state.shutdown`, or `limits.max_follow_secs`. Journal SSE event name is `journal`; docker is `stdout`/`stderr`; data is the JSON DTO. `api::healthz` is public for P3 to mount at `/healthz`. `follow` and `all` accept 0/1/true/false.
|
||||
@@ -0,0 +1,229 @@
|
||||
//! Cross-cutting API tests: SSE lifecycle, 405 shape, name validation.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use axum::body::{to_bytes, Body};
|
||||
use axum::http::{Request, StatusCode};
|
||||
use tokio::sync::{mpsc, Notify};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tower::ServiceExt;
|
||||
|
||||
use super::router;
|
||||
use super::testutil::{get, json};
|
||||
use crate::config::Config;
|
||||
use crate::error::AppError;
|
||||
use crate::sources::fake::fake_state;
|
||||
use crate::sources::{
|
||||
ContainerStatus, ContainerSummary, DockerSource, JournalEntry, JournalQuery, JournalSource,
|
||||
LogLine, LogOptions, SystemdSource, TimerInfo, UnitStatus, UnitSummary,
|
||||
};
|
||||
|
||||
/// Journal source whose producer sends one entry and then never closes,
|
||||
/// signalling `closed` when the receiver is dropped.
|
||||
struct Endless {
|
||||
closed: Arc<Notify>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl JournalSource for Endless {
|
||||
async fn query(&self, _: &JournalQuery) -> Result<Vec<JournalEntry>, AppError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
async fn follow(&self, _: &JournalQuery) -> Result<mpsc::Receiver<JournalEntry>, AppError> {
|
||||
let (tx, rx) = mpsc::channel(4);
|
||||
let closed = self.closed.clone();
|
||||
tokio::spawn(async move {
|
||||
let e = JournalEntry {
|
||||
timestamp: "2026-10-15T08:00:00Z".parse().unwrap(),
|
||||
priority: None,
|
||||
unit: None,
|
||||
identifier: None,
|
||||
pid: None,
|
||||
hostname: None,
|
||||
message: "one".into(),
|
||||
cursor: None,
|
||||
};
|
||||
let _ = tx.send(e).await;
|
||||
tx.closed().await;
|
||||
closed.notify_one();
|
||||
});
|
||||
Ok(rx)
|
||||
}
|
||||
}
|
||||
|
||||
fn endless_app(max_secs: u64) -> (axum::Router, Arc<Notify>, CancellationToken) {
|
||||
let mut cfg = Config::default();
|
||||
cfg.limits.max_follow_secs = max_secs;
|
||||
let mut st = fake_state(cfg);
|
||||
let closed = Arc::new(Notify::new());
|
||||
st.journal = Arc::new(Endless {
|
||||
closed: closed.clone(),
|
||||
});
|
||||
let token = st.shutdown.clone();
|
||||
(router(st), closed, token)
|
||||
}
|
||||
|
||||
async fn follow_body(app: &axum::Router) -> String {
|
||||
let (s, b) = tokio::time::timeout(Duration::from_secs(5), get(app, "/journal/follow"))
|
||||
.await
|
||||
.expect("stream must end");
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
b
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sse_ends_on_shutdown_with_end_frame() {
|
||||
let (app, _, token) = endless_app(60);
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(150)).await;
|
||||
token.cancel();
|
||||
});
|
||||
let b = follow_body(&app).await;
|
||||
assert!(b.contains("event: journal"), "{b}");
|
||||
assert!(b.contains("event: end\ndata: shutdown"), "{b}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sse_ends_at_deadline() {
|
||||
let (app, _, _t) = endless_app(1);
|
||||
let start = std::time::Instant::now();
|
||||
let b = follow_body(&app).await;
|
||||
assert!(start.elapsed() >= Duration::from_millis(900));
|
||||
assert!(b.contains("event: end\ndata: deadline"), "{b}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_body_drops_receiver() {
|
||||
let (app, closed, _t) = endless_app(60);
|
||||
let resp = app
|
||||
.oneshot(Request::get("/journal/follow").body(Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
drop(resp);
|
||||
tokio::time::timeout(Duration::from_secs(5), closed.notified())
|
||||
.await
|
||||
.expect("producer must observe receiver drop");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wrong_method_is_json_405() {
|
||||
let app = router(fake_state(Config::default()));
|
||||
for m in ["POST", "PUT"] {
|
||||
let resp = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method(m)
|
||||
.uri("/systemd/units")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
|
||||
let b = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
|
||||
let v = json(std::str::from_utf8(&b).unwrap());
|
||||
assert_eq!(v["error"]["code"], "method_not_allowed");
|
||||
}
|
||||
}
|
||||
|
||||
/// Stub that validates names and states like the real sources do. The fakes
|
||||
/// do not validate; real validation is covered by the source unit tests
|
||||
/// (WS-A/B/C). These tests prove the handlers surface the source's 400 and
|
||||
/// that percent-encoded `/` and `;` reach the source intact.
|
||||
struct Strict;
|
||||
|
||||
fn ok_name(n: &str) -> Result<(), AppError> {
|
||||
let ok = !n.is_empty()
|
||||
&& n.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || "._-@:".contains(c))
|
||||
&& n != "..";
|
||||
if ok {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(AppError::BadRequest(format!("invalid name '{n}'")))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SystemdSource for Strict {
|
||||
async fn list_units(&self, state: Option<&str>) -> Result<Vec<UnitSummary>, AppError> {
|
||||
match state {
|
||||
None | Some("active" | "inactive" | "failed") => Ok(vec![]),
|
||||
Some(s) => Err(AppError::BadRequest(format!("unknown state '{s}'"))),
|
||||
}
|
||||
}
|
||||
async fn list_timers(&self) -> Result<Vec<TimerInfo>, AppError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
async fn unit_status(&self, name: &str) -> Result<UnitStatus, AppError> {
|
||||
ok_name(name)?;
|
||||
Err(AppError::NotFound(name.into()))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl JournalSource for Strict {
|
||||
async fn query(&self, q: &JournalQuery) -> Result<Vec<JournalEntry>, AppError> {
|
||||
if let Some(u) = &q.unit {
|
||||
ok_name(u)?;
|
||||
}
|
||||
Ok(vec![])
|
||||
}
|
||||
async fn follow(&self, q: &JournalQuery) -> Result<mpsc::Receiver<JournalEntry>, AppError> {
|
||||
self.query(q).await?;
|
||||
Ok(mpsc::channel(1).1)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl DockerSource for Strict {
|
||||
async fn ps(&self, _: bool) -> Result<Vec<ContainerSummary>, AppError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
async fn container_status(&self, name: &str) -> Result<ContainerStatus, AppError> {
|
||||
ok_name(name)?;
|
||||
Err(AppError::NotFound(name.into()))
|
||||
}
|
||||
async fn logs(&self, name: &str, _: &LogOptions) -> Result<Vec<LogLine>, AppError> {
|
||||
ok_name(name)?;
|
||||
Ok(vec![])
|
||||
}
|
||||
async fn follow_logs(
|
||||
&self,
|
||||
name: &str,
|
||||
_: &LogOptions,
|
||||
) -> Result<mpsc::Receiver<LogLine>, AppError> {
|
||||
ok_name(name)?;
|
||||
Ok(mpsc::channel(1).1)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_names_and_state_are_400() {
|
||||
let mut st = fake_state(Config::default());
|
||||
st.systemd = Arc::new(Strict);
|
||||
st.journal = Arc::new(Strict);
|
||||
st.docker = Arc::new(Strict);
|
||||
let app = router(st);
|
||||
for u in [
|
||||
"/systemd/units?state=bogus",
|
||||
"/systemd/units/a%3Bb.service",
|
||||
"/systemd/units/..",
|
||||
"/journal?unit=../x",
|
||||
"/journal/follow?unit=a;b",
|
||||
"/docker/containers/a%3Bb",
|
||||
"/docker/containers/a%2Fb",
|
||||
"/docker/containers/a%3Bb/logs",
|
||||
"/docker/containers/a%2Fb/logs?follow=1",
|
||||
] {
|
||||
let (s, b) = get(&app, u).await;
|
||||
assert_eq!(s, StatusCode::BAD_REQUEST, "{u}: {b}");
|
||||
assert_eq!(json(&b)["error"]["code"], "bad_request");
|
||||
}
|
||||
let (s, _) = get(&app, "/docker/containers/ok").await;
|
||||
assert_eq!(s, StatusCode::NOT_FOUND);
|
||||
}
|
||||
+214
-2
@@ -1,3 +1,215 @@
|
||||
//! GET /api/v1/docker/* handlers (WS-E)
|
||||
//!
|
||||
//! Placeholder created in P0 so the owning workstream only edits its own files.
|
||||
|
||||
use axum::extract::rejection::QueryRejection;
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::response::sse::Event;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
use jiff::Timestamp;
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::{query, sse_from};
|
||||
use crate::error::AppError;
|
||||
use crate::sources::{ContainerStatus, ContainerSummary, LogLine, LogOptions, LogStream};
|
||||
use crate::state::AppState;
|
||||
|
||||
pub fn routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/docker/ps", get(ps))
|
||||
.route("/docker/containers/{name}", get(container))
|
||||
.route("/docker/containers/{name}/logs", get(logs))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PsParams {
|
||||
all: Option<String>,
|
||||
}
|
||||
|
||||
/// Accepts `1|0|true|false`.
|
||||
fn parse_bool(name: &str, v: Option<&str>) -> Result<bool, AppError> {
|
||||
match v {
|
||||
None => Ok(false),
|
||||
Some("1" | "true") => Ok(true),
|
||||
Some("0" | "false") => Ok(false),
|
||||
Some(o) => Err(AppError::BadRequest(format!(
|
||||
"{name} must be 0, 1, true or false, got '{o}'"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
async fn ps(
|
||||
State(st): State<AppState>,
|
||||
q: Result<Query<PsParams>, QueryRejection>,
|
||||
) -> Result<Json<Vec<ContainerSummary>>, AppError> {
|
||||
let all = parse_bool("all", query(q)?.all.as_deref())?;
|
||||
Ok(Json(st.docker.ps(all).await?))
|
||||
}
|
||||
|
||||
async fn container(
|
||||
State(st): State<AppState>,
|
||||
Path(name): Path<String>,
|
||||
) -> Result<Json<ContainerStatus>, AppError> {
|
||||
Ok(Json(st.docker.container_status(&name).await?))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct LogParams {
|
||||
tail: Option<usize>,
|
||||
since: Option<Timestamp>,
|
||||
follow: Option<String>,
|
||||
}
|
||||
|
||||
async fn logs(
|
||||
State(st): State<AppState>,
|
||||
Path(name): Path<String>,
|
||||
q: Result<Query<LogParams>, QueryRejection>,
|
||||
) -> Result<Response, AppError> {
|
||||
let p = query(q)?;
|
||||
let follow = parse_bool("follow", p.follow.as_deref())?;
|
||||
if p.tail == Some(0) {
|
||||
return Err(AppError::BadRequest("tail must be at least 1".into()));
|
||||
}
|
||||
let opts = LogOptions {
|
||||
tail: p.tail.map(|n| n.min(st.config.limits.max_tail)),
|
||||
since: p.since,
|
||||
};
|
||||
if !follow {
|
||||
return Ok(Json(st.docker.logs(&name, &opts).await?).into_response());
|
||||
}
|
||||
let rx = st.docker.follow_logs(&name, &opts).await?;
|
||||
Ok(sse_from(
|
||||
rx,
|
||||
st.shutdown.clone(),
|
||||
st.config.limits.max_follow_secs,
|
||||
|l: &LogLine| {
|
||||
let ev = match l.stream {
|
||||
LogStream::Stdout => "stdout",
|
||||
LogStream::Stderr => "stderr",
|
||||
};
|
||||
Event::default()
|
||||
.event(ev)
|
||||
.json_data(l)
|
||||
.unwrap_or_else(|_| Event::default().comment("serialize error"))
|
||||
},
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use axum::http::StatusCode;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::api::router;
|
||||
use crate::api::testutil::{get, json};
|
||||
use crate::config::Config;
|
||||
use crate::error::AppError;
|
||||
use crate::sources::fake::fake_state;
|
||||
use crate::sources::{ContainerStatus, ContainerSummary, DockerSource, LogLine, LogOptions};
|
||||
|
||||
fn app() -> axum::Router {
|
||||
router(fake_state(Config::default()))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ps_and_detail() {
|
||||
let (s, b) = get(&app(), "/docker/ps").await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
assert_eq!(json(&b).as_array().unwrap().len(), 2);
|
||||
let (_, b) = get(&app(), "/docker/ps?all=1").await;
|
||||
assert_eq!(json(&b).as_array().unwrap().len(), 3);
|
||||
let (s, b) = get(&app(), "/docker/containers/web").await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
assert_eq!(json(&b)["health"], "healthy");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn errors_400_404() {
|
||||
let (s, _) = get(&app(), "/docker/containers/nope").await;
|
||||
assert_eq!(s, StatusCode::NOT_FOUND);
|
||||
let (s, _) = get(&app(), "/docker/containers/nope/logs").await;
|
||||
assert_eq!(s, StatusCode::NOT_FOUND);
|
||||
for u in [
|
||||
"/docker/ps?all=maybe",
|
||||
"/docker/containers/web/logs?tail=abc",
|
||||
"/docker/containers/web/logs?tail=0",
|
||||
"/docker/containers/web/logs?follow=2",
|
||||
"/docker/containers/web/logs?since=nonsense",
|
||||
] {
|
||||
let (s, b) = get(&app(), u).await;
|
||||
assert_eq!(s, StatusCode::BAD_REQUEST, "{u}");
|
||||
assert_eq!(json(&b)["error"]["code"], "bad_request");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn logs_json() {
|
||||
let (s, b) = get(&app(), "/docker/containers/web/logs?follow=0").await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
assert_eq!(json(&b).as_array().unwrap().len(), 2);
|
||||
let (_, b) = get(&app(), "/docker/containers/web/logs?tail=1").await;
|
||||
assert_eq!(json(&b)[0]["stream"], "stderr");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn logs_sse_ends_on_shutdown() {
|
||||
let st = fake_state(Config::default());
|
||||
let token = st.shutdown.clone();
|
||||
let app = router(st);
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||
token.cancel();
|
||||
});
|
||||
let (s, b) = get(&app, "/docker/containers/web/logs?follow=1").await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
assert!(b.contains("event: stdout"), "{b}");
|
||||
assert!(b.contains("event: stderr"), "{b}");
|
||||
}
|
||||
|
||||
struct Down;
|
||||
|
||||
#[async_trait]
|
||||
impl DockerSource for Down {
|
||||
async fn ps(&self, _: bool) -> Result<Vec<ContainerSummary>, AppError> {
|
||||
Err(AppError::Unavailable("docker socket".into()))
|
||||
}
|
||||
async fn container_status(&self, _: &str) -> Result<ContainerStatus, AppError> {
|
||||
Err(AppError::Unavailable("docker socket".into()))
|
||||
}
|
||||
async fn logs(&self, _: &str, _: &LogOptions) -> Result<Vec<LogLine>, AppError> {
|
||||
Err(AppError::Unavailable("docker socket".into()))
|
||||
}
|
||||
async fn follow_logs(
|
||||
&self,
|
||||
_: &str,
|
||||
_: &LogOptions,
|
||||
) -> Result<mpsc::Receiver<LogLine>, AppError> {
|
||||
Err(AppError::Unavailable("docker socket".into()))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn docker_unavailable_isolated() {
|
||||
let mut st = fake_state(Config::default());
|
||||
st.docker = Arc::new(Down);
|
||||
let app = router(st);
|
||||
for u in [
|
||||
"/docker/ps",
|
||||
"/docker/containers/web",
|
||||
"/docker/containers/web/logs",
|
||||
"/docker/containers/web/logs?follow=1",
|
||||
] {
|
||||
let (s, b) = get(&app, u).await;
|
||||
assert_eq!(s, StatusCode::SERVICE_UNAVAILABLE, "{u}");
|
||||
assert_eq!(json(&b)["error"]["code"], "unavailable");
|
||||
}
|
||||
for u in ["/systemd/units", "/systemd/timers", "/journal"] {
|
||||
let (s, _) = get(&app, u).await;
|
||||
assert_eq!(s, StatusCode::OK, "{u}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+131
-2
@@ -1,3 +1,132 @@
|
||||
//! GET /api/v1/journal and /journal/follow handlers (WS-E)
|
||||
//!
|
||||
//! Placeholder created in P0 so the owning workstream only edits its own files.
|
||||
|
||||
use std::convert::Infallible;
|
||||
|
||||
use axum::extract::rejection::QueryRejection;
|
||||
use axum::extract::{Query, State};
|
||||
use axum::response::sse::{Event, Sse};
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
use futures::Stream;
|
||||
use jiff::Timestamp;
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::{query, sse_from};
|
||||
use crate::error::AppError;
|
||||
use crate::sources::{JournalEntry, JournalQuery};
|
||||
use crate::state::AppState;
|
||||
|
||||
pub fn routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/journal", get(snapshot))
|
||||
.route("/journal/follow", get(follow))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct JournalParams {
|
||||
unit: Option<String>,
|
||||
priority: Option<String>,
|
||||
lines: Option<usize>,
|
||||
since: Option<Timestamp>,
|
||||
}
|
||||
|
||||
impl JournalParams {
|
||||
/// Parse priority and clamp `lines` to the configured cap. `lines=0` is
|
||||
/// rejected.
|
||||
fn into_query(self, st: &AppState) -> Result<JournalQuery, AppError> {
|
||||
if self.lines == Some(0) {
|
||||
return Err(AppError::BadRequest("lines must be at least 1".into()));
|
||||
}
|
||||
let priority = self.priority.as_deref().map(str::parse).transpose()?;
|
||||
Ok(JournalQuery {
|
||||
unit: self.unit,
|
||||
priority,
|
||||
lines: self.lines.map(|n| n.min(st.config.limits.max_lines)),
|
||||
since: self.since,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn snapshot(
|
||||
State(st): State<AppState>,
|
||||
q: Result<Query<JournalParams>, QueryRejection>,
|
||||
) -> Result<Json<Vec<JournalEntry>>, AppError> {
|
||||
let q = query(q)?.into_query(&st)?;
|
||||
Ok(Json(st.journal.query(&q).await?))
|
||||
}
|
||||
|
||||
async fn follow(
|
||||
State(st): State<AppState>,
|
||||
q: Result<Query<JournalParams>, QueryRejection>,
|
||||
) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, AppError> {
|
||||
let q = query(q)?.into_query(&st)?;
|
||||
let rx = st.journal.follow(&q).await?;
|
||||
Ok(sse_from(
|
||||
rx,
|
||||
st.shutdown.clone(),
|
||||
st.config.limits.max_follow_secs,
|
||||
|e: &JournalEntry| {
|
||||
Event::default()
|
||||
.event("journal")
|
||||
.json_data(e)
|
||||
.unwrap_or_else(|_| Event::default().comment("serialize error"))
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use axum::http::StatusCode;
|
||||
|
||||
use crate::api::router;
|
||||
use crate::api::testutil::{get, json};
|
||||
use crate::config::Config;
|
||||
use crate::sources::fake::fake_state;
|
||||
|
||||
#[tokio::test]
|
||||
async fn snapshot_filters() {
|
||||
let app = router(fake_state(Config::default()));
|
||||
let (s, b) = get(&app, "/journal").await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
assert_eq!(json(&b).as_array().unwrap().len(), 3);
|
||||
for p in ["err", "3"] {
|
||||
let (s, b) = get(&app, &format!("/journal?priority={p}&unit=nginx.service")).await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
assert_eq!(json(&b).as_array().unwrap().len(), 2);
|
||||
}
|
||||
let (_, b) = get(&app, "/journal?lines=1&priority=err").await;
|
||||
assert_eq!(json(&b).as_array().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bad_input_is_400() {
|
||||
let app = router(fake_state(Config::default()));
|
||||
for u in [
|
||||
"/journal?priority=loud",
|
||||
"/journal?priority=9",
|
||||
"/journal?lines=abc",
|
||||
"/journal?lines=0",
|
||||
"/journal?since=yesterday",
|
||||
"/journal/follow?priority=loud",
|
||||
] {
|
||||
let (s, b) = get(&app, u).await;
|
||||
assert_eq!(s, StatusCode::BAD_REQUEST, "{u}");
|
||||
assert_eq!(json(&b)["error"]["code"], "bad_request");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn follow_streams_then_ends_on_shutdown() {
|
||||
let st = fake_state(Config::default());
|
||||
let token = st.shutdown.clone();
|
||||
let app = router(st);
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||
token.cancel();
|
||||
});
|
||||
let (s, b) = get(&app, "/journal/follow?priority=err").await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
assert_eq!(b.matches("event: journal").count(), 2, "{b}");
|
||||
assert!(b.contains("bind() to 0.0.0.0:80 failed"));
|
||||
}
|
||||
}
|
||||
+121
-6
@@ -1,18 +1,133 @@
|
||||
//! REST layer (WS-E owns `src/api/`).
|
||||
//!
|
||||
//! STUB: signature is final. Uses axum 0.8 `{name}` path syntax. The router
|
||||
//! contains `/api/v1/*` only; `/healthz`, auth and `/mcp` are merged by
|
||||
//! `main.rs` (P3 I1) so `/healthz` stays public.
|
||||
//! The router contains `/api/v1/*` handlers only (paths are relative; P3
|
||||
//! nests it). `healthz` is public and mounted outside auth by `main.rs`.
|
||||
//! Handlers are thin: parse, call the source, serialize. All errors render
|
||||
//! through `AppError` as `{"error":{"code","message"}}`.
|
||||
|
||||
#[cfg(test)]
|
||||
mod behaviour_tests;
|
||||
pub mod docker;
|
||||
pub mod journal;
|
||||
pub mod systemd;
|
||||
|
||||
use axum::Router;
|
||||
use std::convert::Infallible;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::rejection::QueryRejection;
|
||||
use axum::extract::Query;
|
||||
use axum::response::sse::{Event, KeepAlive, Sse};
|
||||
use axum::{Json, Router};
|
||||
use futures::Stream;
|
||||
use serde::de::DeserializeOwned;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::state::AppState;
|
||||
|
||||
/// Routes under `/api/v1`, already bound to `state`.
|
||||
pub fn router(_state: AppState) -> Router {
|
||||
todo!("WS-E E1")
|
||||
pub fn router(state: AppState) -> Router {
|
||||
Router::new()
|
||||
.merge(systemd::routes())
|
||||
.merge(journal::routes())
|
||||
.merge(docker::routes())
|
||||
.fallback(not_found)
|
||||
.method_not_allowed_fallback(method_not_allowed)
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
/// Public liveness handler: `{"status":"ok","version":"…"}`.
|
||||
pub async fn healthz() -> Json<serde_json::Value> {
|
||||
Json(serde_json::json!({
|
||||
"status": "ok",
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Route-level 404 in the common error shape.
|
||||
pub async fn not_found() -> AppError {
|
||||
AppError::NotFound("no such route".into())
|
||||
}
|
||||
|
||||
/// 405 in the common error shape (`AppError` has no 405 variant, so this
|
||||
/// renders the same JSON body with the right status).
|
||||
pub async fn method_not_allowed() -> axum::response::Response {
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
(
|
||||
StatusCode::METHOD_NOT_ALLOWED,
|
||||
Json(serde_json::json!({"error": {
|
||||
"code": "method_not_allowed",
|
||||
"message": "method not allowed",
|
||||
}})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// Query extraction that reports failures as `AppError::BadRequest`.
|
||||
pub(crate) fn query<T: DeserializeOwned>(
|
||||
q: Result<Query<T>, QueryRejection>,
|
||||
) -> Result<T, AppError> {
|
||||
q.map(|Query(v)| v)
|
||||
.map_err(|e| AppError::BadRequest(e.body_text()))
|
||||
}
|
||||
|
||||
/// Build an SSE response from a source receiver. `to_event` maps an item to
|
||||
/// an event. The stream ends when the producer closes the channel, the
|
||||
/// shutdown token fires, or `max_secs` elapses. Dropping the response (client
|
||||
/// disconnect) drops the receiver, which stops the producer.
|
||||
pub(crate) fn sse_from<T: Send + 'static>(
|
||||
rx: mpsc::Receiver<T>,
|
||||
shutdown: CancellationToken,
|
||||
max_secs: u64,
|
||||
to_event: fn(&T) -> Event,
|
||||
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(max_secs);
|
||||
let stream = futures::stream::unfold(
|
||||
(rx, shutdown, false),
|
||||
move |(mut rx, shutdown, done)| async move {
|
||||
if done {
|
||||
return None;
|
||||
}
|
||||
// `Err(reason)` ends the stream with a final `event: end` frame
|
||||
// so clients can tell a server-side cutoff from a failure.
|
||||
let next: Result<T, &'static str> = tokio::select! {
|
||||
() = shutdown.cancelled() => Err("shutdown"),
|
||||
() = tokio::time::sleep_until(deadline) => Err("deadline"),
|
||||
item = rx.recv() => item.ok_or("closed"),
|
||||
};
|
||||
match next {
|
||||
Ok(item) => Some((Ok(to_event(&item)), (rx, shutdown, false))),
|
||||
Err(reason) => {
|
||||
let ev = Event::default().event("end").data(reason);
|
||||
Some((Ok(ev), (rx, shutdown, true)))
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
Sse::new(stream).keep_alive(KeepAlive::default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod testutil {
|
||||
use axum::body::{to_bytes, Body};
|
||||
use axum::http::{Request, StatusCode};
|
||||
use axum::Router;
|
||||
use tower::ServiceExt;
|
||||
|
||||
pub async fn get(app: &Router, uri: &str) -> (StatusCode, String) {
|
||||
let resp = app
|
||||
.clone()
|
||||
.oneshot(Request::get(uri).body(Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let status = resp.status();
|
||||
let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
|
||||
(status, String::from_utf8(body.to_vec()).unwrap())
|
||||
}
|
||||
|
||||
pub fn json(s: &str) -> serde_json::Value {
|
||||
serde_json::from_str(s).unwrap()
|
||||
}
|
||||
}
|
||||
+92
-2
@@ -1,3 +1,93 @@
|
||||
//! GET /api/v1/systemd/* handlers (WS-E)
|
||||
//!
|
||||
//! Placeholder created in P0 so the owning workstream only edits its own files.
|
||||
|
||||
use axum::extract::rejection::QueryRejection;
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::query;
|
||||
use crate::error::AppError;
|
||||
use crate::sources::{TimerInfo, UnitStatus, UnitSummary};
|
||||
use crate::state::AppState;
|
||||
|
||||
pub fn routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/systemd/units", get(units))
|
||||
.route("/systemd/units/{name}", get(unit))
|
||||
.route("/systemd/timers", get(timers))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct UnitsQuery {
|
||||
state: Option<String>,
|
||||
}
|
||||
|
||||
async fn units(
|
||||
State(st): State<AppState>,
|
||||
q: Result<Query<UnitsQuery>, QueryRejection>,
|
||||
) -> Result<Json<Vec<UnitSummary>>, AppError> {
|
||||
let q = query(q)?;
|
||||
Ok(Json(st.systemd.list_units(q.state.as_deref()).await?))
|
||||
}
|
||||
|
||||
async fn unit(
|
||||
State(st): State<AppState>,
|
||||
Path(name): Path<String>,
|
||||
) -> Result<Json<UnitStatus>, AppError> {
|
||||
Ok(Json(st.systemd.unit_status(&name).await?))
|
||||
}
|
||||
|
||||
async fn timers(State(st): State<AppState>) -> Result<Json<Vec<TimerInfo>>, AppError> {
|
||||
Ok(Json(st.systemd.list_timers().await?))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use axum::http::StatusCode;
|
||||
|
||||
use crate::api::testutil::{get, json};
|
||||
use crate::api::{healthz, router};
|
||||
use crate::config::Config;
|
||||
use crate::sources::fake::fake_state;
|
||||
|
||||
fn app() -> axum::Router {
|
||||
router(fake_state(Config::default()))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_and_filter() {
|
||||
let (s, b) = get(&app(), "/systemd/units").await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
assert!(json(&b).as_array().unwrap().len() >= 2);
|
||||
let (s, b) = get(&app(), "/systemd/units?state=failed").await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
assert_eq!(json(&b)[0]["name"], "nginx.service");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unit_detail_and_404() {
|
||||
let (s, b) = get(&app(), "/systemd/units/sshd.service").await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
assert_eq!(json(&b)["main_pid"], 1234);
|
||||
let (s, b) = get(&app(), "/systemd/units/nope.service").await;
|
||||
assert_eq!(s, StatusCode::NOT_FOUND);
|
||||
assert_eq!(json(&b)["error"]["code"], "not_found");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn timers_ok_and_unknown_route() {
|
||||
let (s, _) = get(&app(), "/systemd/timers").await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
let (s, b) = get(&app(), "/nope").await;
|
||||
assert_eq!(s, StatusCode::NOT_FOUND);
|
||||
assert_eq!(json(&b)["error"]["code"], "not_found");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn healthz_shape() {
|
||||
let v = healthz().await.0;
|
||||
assert_eq!(v["status"], "ok");
|
||||
assert!(v["version"].is_string());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user