WS-E: review follow-ups (JSON 405, SSE end frame, lifecycle and validation tests)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YShymaPrXmc3KYRUg2HMSs
This commit is contained in:
1 parent
6130e01b92
commit
e63fc25907
3 files changed
+270
-9
No files matched your search
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user