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,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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user