P0: config, DTOs, source traits, fakes, error, state and module stubs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
aa9b0da962
commit
1802f97d94
22 files changed
+1736
No files matched your search
@@ -0,0 +1,354 @@
|
||||
//! Fixture-backed in-memory sources for tests and for developing surfaces
|
||||
//! without systemd, journald or Docker (DEC-2).
|
||||
//!
|
||||
//! `fake_state(config)` returns a ready `AppState`. Each fake exposes its
|
||||
//! fixtures as public fields so tests can replace them.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use jiff::Timestamp;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::{
|
||||
clamp_count, ContainerStatus, ContainerSummary, DockerSource, JournalEntry, JournalQuery,
|
||||
JournalSource, LogLine, LogOptions, LogStream, Priority, SystemdSource, TimerInfo, UnitStatus,
|
||||
UnitSummary,
|
||||
};
|
||||
use crate::config::Config;
|
||||
use crate::error::AppError;
|
||||
use crate::state::AppState;
|
||||
|
||||
fn ts(s: &str) -> Timestamp {
|
||||
s.parse().expect("valid fixture timestamp")
|
||||
}
|
||||
|
||||
/// An `AppState` backed by the fakes, without a DB pool.
|
||||
pub fn fake_state(config: Config) -> AppState {
|
||||
let shutdown = CancellationToken::new();
|
||||
AppState {
|
||||
config: Arc::new(config),
|
||||
systemd: Arc::new(FakeSystemd::default()),
|
||||
journal: Arc::new(FakeJournal::new(shutdown.clone())),
|
||||
docker: Arc::new(FakeDocker::new(shutdown.clone())),
|
||||
db: None,
|
||||
shutdown,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- systemd
|
||||
|
||||
pub struct FakeSystemd {
|
||||
pub units: Vec<UnitStatus>,
|
||||
pub timers: Vec<TimerInfo>,
|
||||
}
|
||||
|
||||
impl Default for FakeSystemd {
|
||||
fn default() -> Self {
|
||||
let unit = |name: &str, desc: &str, active: &str, sub: &str, service: bool| UnitStatus {
|
||||
name: name.into(),
|
||||
description: desc.into(),
|
||||
load_state: "loaded".into(),
|
||||
active_state: active.into(),
|
||||
sub_state: sub.into(),
|
||||
fragment_path: Some(format!("/etc/systemd/system/{name}")),
|
||||
unit_file_state: Some("enabled".into()),
|
||||
active_enter_time: Some(ts("2026-10-15T08:00:00Z")),
|
||||
active_exit_time: None,
|
||||
main_pid: service.then_some(1234),
|
||||
exec_main_status: service.then_some(if active == "failed" { 1 } else { 0 }),
|
||||
n_restarts: service.then_some(if active == "failed" { 5 } else { 0 }),
|
||||
result: service.then(|| {
|
||||
if active == "failed" {
|
||||
"exit-code"
|
||||
} else {
|
||||
"success"
|
||||
}
|
||||
.into()
|
||||
}),
|
||||
};
|
||||
Self {
|
||||
units: vec![
|
||||
unit("sshd.service", "OpenSSH Daemon", "active", "running", true),
|
||||
unit(
|
||||
"nginx.service",
|
||||
"Nginx web server",
|
||||
"failed",
|
||||
"failed",
|
||||
true,
|
||||
),
|
||||
unit(
|
||||
"logrotate.timer",
|
||||
"Daily rotation of log files",
|
||||
"active",
|
||||
"waiting",
|
||||
false,
|
||||
),
|
||||
],
|
||||
timers: vec![TimerInfo {
|
||||
name: "logrotate.timer".into(),
|
||||
unit: "logrotate.service".into(),
|
||||
active_state: "active".into(),
|
||||
next_elapse: Some(ts("2026-10-16T00:00:00Z")),
|
||||
last_trigger: Some(ts("2026-10-15T00:00:00Z")),
|
||||
}],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SystemdSource for FakeSystemd {
|
||||
async fn list_units(&self, state: Option<&str>) -> Result<Vec<UnitSummary>, AppError> {
|
||||
Ok(self
|
||||
.units
|
||||
.iter()
|
||||
.filter(|u| state.is_none_or(|s| u.active_state == s))
|
||||
.map(|u| UnitSummary {
|
||||
name: u.name.clone(),
|
||||
description: u.description.clone(),
|
||||
load_state: u.load_state.clone(),
|
||||
active_state: u.active_state.clone(),
|
||||
sub_state: u.sub_state.clone(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn list_timers(&self) -> Result<Vec<TimerInfo>, AppError> {
|
||||
Ok(self.timers.clone())
|
||||
}
|
||||
|
||||
async fn unit_status(&self, name: &str) -> Result<UnitStatus, AppError> {
|
||||
self.units
|
||||
.iter()
|
||||
.find(|u| u.name == name)
|
||||
.cloned()
|
||||
.ok_or_else(|| AppError::NotFound(format!("unit {name}")))
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- journal
|
||||
|
||||
pub struct FakeJournal {
|
||||
pub entries: Vec<JournalEntry>,
|
||||
shutdown: CancellationToken,
|
||||
}
|
||||
|
||||
impl FakeJournal {
|
||||
pub fn new(shutdown: CancellationToken) -> Self {
|
||||
let e = |t: &str, p: Priority, unit: &str, msg: &str| JournalEntry {
|
||||
timestamp: ts(t),
|
||||
priority: Some(p),
|
||||
unit: Some(unit.into()),
|
||||
identifier: Some(unit.trim_end_matches(".service").into()),
|
||||
pid: Some(1234),
|
||||
hostname: Some("fakehost".into()),
|
||||
message: msg.into(),
|
||||
cursor: Some(format!("s={t}")),
|
||||
};
|
||||
Self {
|
||||
entries: vec![
|
||||
e(
|
||||
"2026-10-15T08:00:01Z",
|
||||
Priority::Info,
|
||||
"sshd.service",
|
||||
"Server listening on 0.0.0.0 port 22.",
|
||||
),
|
||||
e(
|
||||
"2026-10-15T08:05:00Z",
|
||||
Priority::Err,
|
||||
"nginx.service",
|
||||
"bind() to 0.0.0.0:80 failed",
|
||||
),
|
||||
e(
|
||||
"2026-10-15T08:05:01Z",
|
||||
Priority::Crit,
|
||||
"nginx.service",
|
||||
"nginx.service: Failed with result 'exit-code'.",
|
||||
),
|
||||
],
|
||||
shutdown,
|
||||
}
|
||||
}
|
||||
|
||||
fn matching(&self, q: &JournalQuery) -> Vec<JournalEntry> {
|
||||
self.entries
|
||||
.iter()
|
||||
.filter(|e| {
|
||||
q.unit
|
||||
.as_deref()
|
||||
.is_none_or(|u| e.unit.as_deref() == Some(u))
|
||||
})
|
||||
.filter(|e| {
|
||||
q.priority
|
||||
.is_none_or(|p| e.priority.is_some_and(|ep| ep <= p))
|
||||
})
|
||||
.filter(|e| q.since.is_none_or(|s| e.timestamp >= s))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl JournalSource for FakeJournal {
|
||||
async fn query(&self, q: &JournalQuery) -> Result<Vec<JournalEntry>, AppError> {
|
||||
let all = self.matching(q);
|
||||
let n = clamp_count(q.lines, usize::MAX);
|
||||
let skip = all.len().saturating_sub(n);
|
||||
Ok(all.into_iter().skip(skip).collect())
|
||||
}
|
||||
|
||||
/// Sends the matching backlog, then idles until the receiver is dropped
|
||||
/// or shutdown fires.
|
||||
async fn follow(&self, q: &JournalQuery) -> Result<mpsc::Receiver<JournalEntry>, AppError> {
|
||||
let backlog = self.query(q).await?;
|
||||
let (tx, rx) = mpsc::channel(64);
|
||||
let shutdown = self.shutdown.clone();
|
||||
tokio::spawn(async move {
|
||||
for e in backlog {
|
||||
if tx.send(e).await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
tokio::select! {
|
||||
() = tx.closed() => {}
|
||||
() = shutdown.cancelled() => {}
|
||||
}
|
||||
});
|
||||
Ok(rx)
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------- docker
|
||||
|
||||
pub struct FakeDocker {
|
||||
pub containers: Vec<ContainerStatus>,
|
||||
pub logs: Vec<LogLine>,
|
||||
shutdown: CancellationToken,
|
||||
}
|
||||
|
||||
impl FakeDocker {
|
||||
pub fn new(shutdown: CancellationToken) -> Self {
|
||||
let c = |id: &str, name: &str, state: &str, health: Option<&str>| ContainerStatus {
|
||||
summary: ContainerSummary {
|
||||
id: id.into(),
|
||||
name: name.into(),
|
||||
image: format!("{name}:latest"),
|
||||
state: state.into(),
|
||||
health: health.map(Into::into),
|
||||
created: Some(ts("2026-10-14T00:00:00Z")),
|
||||
started_at: Some(ts("2026-10-14T00:00:05Z")),
|
||||
uptime_seconds: (state == "running").then_some(3600),
|
||||
restart_count: Some(0),
|
||||
},
|
||||
finished_at: None,
|
||||
exit_code: None,
|
||||
oom_killed: Some(false),
|
||||
health_output: health.map(|h| format!("probe says {h}")),
|
||||
};
|
||||
Self {
|
||||
containers: vec![
|
||||
c("aaaa1111", "web", "running", Some("healthy")),
|
||||
c("bbbb2222", "db", "running", None),
|
||||
c("cccc3333", "job", "exited", None),
|
||||
],
|
||||
logs: vec![
|
||||
LogLine {
|
||||
stream: LogStream::Stdout,
|
||||
ts: Some(ts("2026-10-15T09:00:00Z")),
|
||||
message: "ready".into(),
|
||||
},
|
||||
LogLine {
|
||||
stream: LogStream::Stderr,
|
||||
ts: Some(ts("2026-10-15T09:00:01Z")),
|
||||
message: "warning: slow query".into(),
|
||||
},
|
||||
],
|
||||
shutdown,
|
||||
}
|
||||
}
|
||||
|
||||
fn find(&self, name: &str) -> Result<&ContainerStatus, AppError> {
|
||||
self.containers
|
||||
.iter()
|
||||
.find(|c| c.summary.name == name || c.summary.id == name)
|
||||
.ok_or_else(|| AppError::NotFound(format!("container {name}")))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl DockerSource for FakeDocker {
|
||||
async fn ps(&self, all: bool) -> Result<Vec<ContainerSummary>, AppError> {
|
||||
Ok(self
|
||||
.containers
|
||||
.iter()
|
||||
.filter(|c| all || c.summary.state == "running")
|
||||
.map(|c| c.summary.clone())
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn container_status(&self, name: &str) -> Result<ContainerStatus, AppError> {
|
||||
self.find(name).cloned()
|
||||
}
|
||||
|
||||
async fn logs(&self, name: &str, opts: &LogOptions) -> Result<Vec<LogLine>, AppError> {
|
||||
self.find(name)?;
|
||||
let n = clamp_count(opts.tail, usize::MAX);
|
||||
let skip = self.logs.len().saturating_sub(n);
|
||||
Ok(self.logs.iter().skip(skip).cloned().collect())
|
||||
}
|
||||
|
||||
async fn follow_logs(
|
||||
&self,
|
||||
name: &str,
|
||||
opts: &LogOptions,
|
||||
) -> Result<mpsc::Receiver<LogLine>, AppError> {
|
||||
let backlog = self.logs(name, opts).await?;
|
||||
let (tx, rx) = mpsc::channel(64);
|
||||
let shutdown = self.shutdown.clone();
|
||||
tokio::spawn(async move {
|
||||
for l in backlog {
|
||||
if tx.send(l).await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
tokio::select! {
|
||||
() = tx.closed() => {}
|
||||
() = shutdown.cancelled() => {}
|
||||
}
|
||||
});
|
||||
Ok(rx)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn fakes_behave() {
|
||||
let st = fake_state(Config::default());
|
||||
assert_eq!(
|
||||
st.systemd.list_units(Some("failed")).await.unwrap().len(),
|
||||
1
|
||||
);
|
||||
assert!(matches!(
|
||||
st.systemd.unit_status("nope.service").await,
|
||||
Err(AppError::NotFound(_))
|
||||
));
|
||||
let q = JournalQuery {
|
||||
priority: Some(Priority::Err),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(st.journal.query(&q).await.unwrap().len(), 2);
|
||||
assert_eq!(st.docker.ps(false).await.unwrap().len(), 2);
|
||||
let mut rx = st
|
||||
.docker
|
||||
.follow_logs("web", &LogOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(rx.recv().await.is_some());
|
||||
st.shutdown.cancel();
|
||||
while rx.recv().await.is_some() {}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user