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:
ariandClaude Sonnet 5.5 committed 2026-10-15 17:23:17 -04:00
1 parent aa9b0da962
commit 1802f97d94
22 files changed
+1736

No files matched your search

+46
View File
@@ -0,0 +1,46 @@
//! Docker source over the unix socket via `bollard` (WS-C owns this file).
//!
//! STUB: signatures are final, bodies are `todo!()`.
//! Notes for WS-C: build the client lazily. A missing or denied socket maps to
//! `AppError::Unavailable` per request and never fails startup (review G9).
use async_trait::async_trait;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use super::{ContainerStatus, ContainerSummary, DockerSource, LogLine, LogOptions};
use crate::config::Config;
use crate::error::AppError;
pub struct BollardDocker {}
impl BollardDocker {
/// Must not fail or block. Reads `sources.docker_socket` and
/// `limits.max_tail` from `config`. Follow tasks stop on `shutdown`.
pub fn new(_config: &Config, _shutdown: CancellationToken) -> Self {
Self {}
}
}
#[async_trait]
impl DockerSource for BollardDocker {
async fn ps(&self, _all: bool) -> Result<Vec<ContainerSummary>, AppError> {
todo!("WS-C C2")
}
async fn container_status(&self, _name: &str) -> Result<ContainerStatus, AppError> {
todo!("WS-C C3")
}
async fn logs(&self, _name: &str, _opts: &LogOptions) -> Result<Vec<LogLine>, AppError> {
todo!("WS-C C4")
}
async fn follow_logs(
&self,
_name: &str,
_opts: &LogOptions,
) -> Result<mpsc::Receiver<LogLine>, AppError> {
todo!("WS-C C4")
}
}
+354
View File
@@ -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() {}
}
}
+36
View File
@@ -0,0 +1,36 @@
//! journald source over libsystemd (WS-B owns this file).
//!
//! STUB: signatures are final, bodies are `todo!()`.
//! Notes for WS-B: `systemd::journal::Journal` is neither `Send` nor `Sync`.
//! Open it inside `spawn_blocking` and never move it across threads or hold it
//! across an `.await`. Namespaces need `OpenOptions::open_namespace`
//! (feature `systemd_v245`, already enabled).
use async_trait::async_trait;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use super::{JournalEntry, JournalQuery, JournalSource};
use crate::config::Config;
use crate::error::AppError;
pub struct SdJournal {}
impl SdJournal {
/// Must not fail or block. Reads `sources.journal_namespace` and
/// `limits.max_lines` from `config`. Follow tasks stop on `shutdown`.
pub fn new(_config: &Config, _shutdown: CancellationToken) -> Self {
Self {}
}
}
#[async_trait]
impl JournalSource for SdJournal {
async fn query(&self, _q: &JournalQuery) -> Result<Vec<JournalEntry>, AppError> {
todo!("WS-B B2")
}
async fn follow(&self, _q: &JournalQuery) -> Result<mpsc::Receiver<JournalEntry>, AppError> {
todo!("WS-B B3")
}
}
+381
View File
@@ -0,0 +1,381 @@
//! Source traits and shared DTOs.
//!
//! `sources` is the only layer that talks to D-Bus, journald or Docker. REST,
//! MCP and OTel are thin projections over these traits. All reads are live.
//!
//! Conventions:
//! - Timestamps are `jiff::Timestamp`, serialized as RFC3339.
//! - Follow methods return a `tokio::sync::mpsc::Receiver`. The producer stops
//! when the receiver is dropped or the shutdown token fires. Errors that
//! occur after the stream started end the stream and are logged.
//! - Missing or denied backends map to `AppError::Unavailable`.
pub mod docker;
pub mod fake;
pub mod journal;
pub mod systemd;
use std::fmt;
use std::str::FromStr;
use async_trait::async_trait;
use jiff::Timestamp;
use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use tokio::sync::mpsc;
use crate::error::AppError;
// ---------------------------------------------------------------- systemd
/// One row of `ListUnits`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct UnitSummary {
/// Full unit name, e.g. `sshd.service`.
pub name: String,
pub description: String,
/// `loaded`, `not-found`, `masked`, `error`, ...
pub load_state: String,
/// `active`, `inactive`, `failed`, `activating`, `deactivating`, `reloading`.
pub active_state: String,
/// Type-specific detail, e.g. `running`, `exited`, `dead`, `waiting`.
pub sub_state: String,
}
/// Detailed status of one unit. Service-only fields are `None` for other types.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct UnitStatus {
pub name: String,
pub description: String,
pub load_state: String,
pub active_state: String,
pub sub_state: String,
/// Path to the unit file, if any.
pub fragment_path: Option<String>,
/// `enabled`, `disabled`, `static`, ... if known.
pub unit_file_state: Option<String>,
pub active_enter_time: Option<Timestamp>,
pub active_exit_time: Option<Timestamp>,
/// Service only.
pub main_pid: Option<u32>,
/// Service only: exit status of the main process.
pub exec_main_status: Option<i32>,
/// Service only: automatic restart count.
pub n_restarts: Option<u32>,
/// Service only: `success`, `exit-code`, `signal`, `timeout`, ...
pub result: Option<String>,
}
/// A `.timer` unit and its schedule.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct TimerInfo {
/// Timer unit name, e.g. `logrotate.timer`.
pub name: String,
/// Unit the timer activates.
pub unit: String,
pub active_state: String,
/// `None` when not scheduled (property is 0 or `u64::MAX`).
pub next_elapse: Option<Timestamp>,
pub last_trigger: Option<Timestamp>,
}
#[async_trait]
pub trait SystemdSource: Send + Sync {
/// List loaded units. `state`, when given, filters on `active_state`.
async fn list_units(&self, state: Option<&str>) -> Result<Vec<UnitSummary>, AppError>;
/// List `.timer` units with their schedule.
async fn list_timers(&self) -> Result<Vec<TimerInfo>, AppError>;
/// Status of one unit. Unknown unit is `AppError::NotFound`.
async fn unit_status(&self, name: &str) -> Result<UnitStatus, AppError>;
}
// ---------------------------------------------------------------- journal
/// Syslog severity, 0 (most severe) to 7.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum Priority {
Emerg = 0,
Alert = 1,
Crit = 2,
Err = 3,
Warning = 4,
Notice = 5,
Info = 6,
Debug = 7,
}
impl Priority {
pub const ALL: [Priority; 8] = [
Priority::Emerg,
Priority::Alert,
Priority::Crit,
Priority::Err,
Priority::Warning,
Priority::Notice,
Priority::Info,
Priority::Debug,
];
pub fn as_u8(self) -> u8 {
self as u8
}
pub fn name(self) -> &'static str {
match self {
Priority::Emerg => "emerg",
Priority::Alert => "alert",
Priority::Crit => "crit",
Priority::Err => "err",
Priority::Warning => "warning",
Priority::Notice => "notice",
Priority::Info => "info",
Priority::Debug => "debug",
}
}
pub fn from_u8(n: u8) -> Option<Self> {
Self::ALL.get(usize::from(n)).copied()
}
}
impl fmt::Display for Priority {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
impl FromStr for Priority {
type Err = AppError;
/// Accepts `0`..`7` or a name (`err`, `error`, `warn`, `warning`, ...).
fn from_str(s: &str) -> Result<Self, AppError> {
let t = s.trim().to_ascii_lowercase();
if let Ok(n) = t.parse::<u8>() {
return Priority::from_u8(n)
.ok_or_else(|| AppError::BadRequest(format!("priority {n} out of range 0-7")));
}
Ok(match t.as_str() {
"emerg" | "emergency" | "panic" => Priority::Emerg,
"alert" => Priority::Alert,
"crit" | "critical" => Priority::Crit,
"err" | "error" => Priority::Err,
"warning" | "warn" => Priority::Warning,
"notice" => Priority::Notice,
"info" => Priority::Info,
"debug" => Priority::Debug,
_ => return Err(AppError::BadRequest(format!("unknown priority '{s}'"))),
})
}
}
impl Serialize for Priority {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.name())
}
}
impl<'de> Deserialize<'de> for Priority {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Raw {
Num(u8),
Str(String),
}
match Raw::deserialize(d)? {
Raw::Num(n) => Priority::from_u8(n)
.ok_or_else(|| serde::de::Error::custom(format!("priority {n} out of range 0-7"))),
Raw::Str(s) => s
.parse()
.map_err(|e: AppError| serde::de::Error::custom(e.message().to_owned())),
}
}
}
impl JsonSchema for Priority {
fn schema_name() -> std::borrow::Cow<'static, str> {
"Priority".into()
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"description": "Syslog severity. Name (emerg, alert, crit, err, warning, notice, info, debug) or number 0-7. Serialized as the name.",
"oneOf": [
{ "type": "string", "enum": ["emerg", "alert", "crit", "err", "warning", "notice", "info", "debug"] },
{ "type": "integer", "minimum": 0, "maximum": 7 }
]
})
}
}
/// Journal filter, shared by snapshot and follow.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct JournalQuery {
/// Match `_SYSTEMD_UNIT` (or `UNIT` for coredump-style entries). Unit names are validated.
pub unit: Option<String>,
/// Include entries at this severity or more severe (numerically `<=`).
pub priority: Option<Priority>,
/// Maximum entries (snapshot) or backlog entries (follow). `None` means the
/// default of 100. Always capped by `limits.max_lines`.
pub lines: Option<usize>,
/// Only entries at or after this time.
pub since: Option<Timestamp>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct JournalEntry {
pub timestamp: Timestamp,
pub priority: Option<Priority>,
/// `_SYSTEMD_UNIT`, falling back to `UNIT`.
pub unit: Option<String>,
/// `SYSLOG_IDENTIFIER`.
pub identifier: Option<String>,
pub pid: Option<u32>,
pub hostname: Option<String>,
/// `MESSAGE`, lossily decoded as UTF-8.
pub message: String,
/// Opaque journal cursor.
pub cursor: Option<String>,
}
#[async_trait]
pub trait JournalSource: Send + Sync {
/// Snapshot: the most recent matching entries, in chronological order.
async fn query(&self, q: &JournalQuery) -> Result<Vec<JournalEntry>, AppError>;
/// Backlog (`q.lines`) followed by new entries as they arrive.
///
/// The returned receiver ends when the producer stops: receiver dropped,
/// shutdown token fired, or a journal error.
async fn follow(&self, q: &JournalQuery) -> Result<mpsc::Receiver<JournalEntry>, AppError>;
}
// ----------------------------------------------------------------- docker
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ContainerSummary {
/// Full container id.
pub id: String,
/// Name without the leading slash.
pub name: String,
pub image: String,
/// `created`, `running`, `paused`, `restarting`, `exited`, `dead`.
pub state: String,
/// Health check status: `healthy`, `unhealthy`, `starting`. `None` if no health check.
pub health: Option<String>,
pub created: Option<Timestamp>,
pub started_at: Option<Timestamp>,
/// Seconds since `started_at`, for running containers.
pub uptime_seconds: Option<u64>,
pub restart_count: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ContainerStatus {
#[serde(flatten)]
pub summary: ContainerSummary,
pub finished_at: Option<Timestamp>,
pub exit_code: Option<i64>,
pub oom_killed: Option<bool>,
/// Last health check output, if any.
pub health_output: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum LogStream {
Stdout,
Stderr,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct LogLine {
pub stream: LogStream,
/// Docker-provided timestamp, if available.
pub ts: Option<Timestamp>,
pub message: String,
}
/// Options for container log reads.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct LogOptions {
/// Last N lines. `None` means the default of 100. Capped by `limits.max_tail`.
pub tail: Option<usize>,
pub since: Option<Timestamp>,
}
#[async_trait]
pub trait DockerSource: Send + Sync {
/// List containers. `all = false` returns running containers only.
async fn ps(&self, all: bool) -> Result<Vec<ContainerSummary>, AppError>;
/// Status by name or id. Unknown is `AppError::NotFound`.
async fn container_status(&self, name: &str) -> Result<ContainerStatus, AppError>;
/// Snapshot of the last `opts.tail` lines, chronological.
async fn logs(&self, name: &str, opts: &LogOptions) -> Result<Vec<LogLine>, AppError>;
/// Backlog (`opts.tail`) followed by new lines as they arrive.
async fn follow_logs(
&self,
name: &str,
opts: &LogOptions,
) -> Result<mpsc::Receiver<LogLine>, AppError>;
}
// ---------------------------------------------------------------- helpers
/// Default value of `JournalQuery.lines` and `LogOptions.tail`.
pub const DEFAULT_LINES: usize = 100;
/// Resolve a requested count against the default and the configured cap.
pub fn clamp_count(requested: Option<usize>, cap: usize) -> usize {
requested.unwrap_or(DEFAULT_LINES).min(cap)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn priority_parse() {
assert_eq!("err".parse::<Priority>().unwrap(), Priority::Err);
assert_eq!("3".parse::<Priority>().unwrap(), Priority::Err);
assert_eq!("WARN".parse::<Priority>().unwrap(), Priority::Warning);
assert!("8".parse::<Priority>().is_err());
assert!("loud".parse::<Priority>().is_err());
}
#[test]
fn priority_serde() {
assert_eq!(serde_json::to_string(&Priority::Crit).unwrap(), "\"crit\"");
assert_eq!(
serde_json::from_str::<Priority>("4").unwrap(),
Priority::Warning
);
assert_eq!(
serde_json::from_str::<Priority>("\"info\"").unwrap(),
Priority::Info
);
assert!(serde_json::from_str::<Priority>("9").is_err());
}
#[test]
fn timestamps_are_rfc3339() {
let ts: Timestamp = "2026-10-15T12:00:00Z".parse().unwrap();
let line = LogLine {
stream: LogStream::Stderr,
ts: Some(ts),
message: "x".into(),
};
let v = serde_json::to_value(&line).unwrap();
assert_eq!(v["ts"], "2026-10-15T12:00:00Z");
assert_eq!(v["stream"], "stderr");
}
#[test]
fn clamp() {
assert_eq!(clamp_count(None, 1000), 100);
assert_eq!(clamp_count(Some(5000), 1000), 1000);
assert_eq!(clamp_count(None, 50), 50);
}
}
+38
View File
@@ -0,0 +1,38 @@
//! systemd source over D-Bus (WS-A owns this file).
//!
//! STUB: signatures are final, bodies are `todo!()`.
//! Notes for WS-A: use `zbus_systemd::systemd1::{ManagerProxy, UnitProxy,
//! ServiceProxy, TimerProxy}`. There is no `ListTimers` method; list `*.timer`
//! units and read `TimerProxy` properties (see plan/review.md R1, R2).
use async_trait::async_trait;
use tokio_util::sync::CancellationToken;
use super::{SystemdSource, TimerInfo, UnitStatus, UnitSummary};
use crate::config::Config;
use crate::error::AppError;
pub struct DbusSystemd {}
impl DbusSystemd {
/// Must not fail or block: connect to the bus lazily on first use and map
/// connection errors to `AppError::Unavailable`.
pub fn new(_config: &Config, _shutdown: CancellationToken) -> Self {
Self {}
}
}
#[async_trait]
impl SystemdSource for DbusSystemd {
async fn list_units(&self, _state: Option<&str>) -> Result<Vec<UnitSummary>, AppError> {
todo!("WS-A A2")
}
async fn list_timers(&self) -> Result<Vec<TimerInfo>, AppError> {
todo!("WS-A A3")
}
async fn unit_status(&self, _name: &str) -> Result<UnitStatus, AppError> {
todo!("WS-A A4")
}
}