//! 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; /// 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, /// `enabled`, `disabled`, `static`, ... if known. pub unit_file_state: Option, pub active_enter_time: Option, pub active_exit_time: Option, /// Service only. pub main_pid: Option, /// Service only: exit status of the main process. pub exec_main_status: Option, /// Service only: automatic restart count. pub n_restarts: Option, /// Service only: `success`, `exit-code`, `signal`, `timeout`, ... pub result: Option, } /// 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, pub last_trigger: Option, } #[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, AppError>; /// List `.timer` units with their schedule. async fn list_timers(&self) -> Result, AppError>; /// Status of one unit. Read-only: never asks systemd to load a unit, so a /// unit that is not loaded (or unknown) is `AppError::NotFound`. async fn unit_status(&self, name: &str) -> Result; } /// 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::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 { let t = s.trim().to_ascii_lowercase(); if let Ok(n) = t.parse::() { 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(&self, s: S) -> Result { s.serialize_str(self.name()) } } impl<'de> Deserialize<'de> for Priority { fn deserialize>(d: D) -> Result { #[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, /// Include entries at this severity or more severe (numerically `<=`). pub priority: Option, /// Maximum entries (snapshot) or backlog entries (follow). `None` means the /// default of 100. Always capped by `limits.max_lines`. pub lines: Option, /// Only entries at or after this time. pub since: Option, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] pub struct JournalEntry { pub timestamp: Timestamp, pub priority: Option, /// `_SYSTEMD_UNIT`, falling back to `UNIT`. pub unit: Option, /// `SYSLOG_IDENTIFIER`. pub identifier: Option, pub pid: Option, pub hostname: Option, /// `MESSAGE`, lossily decoded as UTF-8. pub message: String, /// Opaque journal cursor. pub cursor: Option, } #[async_trait] pub trait JournalSource: Send + Sync { /// Snapshot: the most recent matching entries, in chronological order. async fn query(&self, q: &JournalQuery) -> Result, 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, AppError>; } #[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, pub created: Option, pub started_at: Option, /// Seconds since `started_at`, for running containers. pub uptime_seconds: Option, pub restart_count: Option, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] pub struct ContainerStatus { #[serde(flatten)] pub summary: ContainerSummary, pub finished_at: Option, pub exit_code: Option, pub oom_killed: Option, /// Last health check output, if any. pub health_output: Option, } #[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, 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, pub since: Option, } #[async_trait] pub trait DockerSource: Send + Sync { /// List containers. `all = false` returns running containers only. async fn ps(&self, all: bool) -> Result, AppError>; /// Status by name or id. Unknown is `AppError::NotFound`. async fn container_status(&self, name: &str) -> Result; /// Snapshot of the last `opts.tail` lines, chronological. async fn logs(&self, name: &str, opts: &LogOptions) -> Result, AppError>; /// Backlog (`opts.tail`) followed by new lines as they arrive. async fn follow_logs( &self, name: &str, opts: &LogOptions, ) -> Result, AppError>; } /// 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, cap: usize) -> usize { requested.unwrap_or(DEFAULT_LINES).min(cap) } #[cfg(test)] mod tests { use super::*; #[test] fn priority_parse() { assert_eq!("err".parse::().unwrap(), Priority::Err); assert_eq!("3".parse::().unwrap(), Priority::Err); assert_eq!("WARN".parse::().unwrap(), Priority::Warning); assert!("8".parse::().is_err()); assert!("loud".parse::().is_err()); } #[test] fn priority_serde() { assert_eq!(serde_json::to_string(&Priority::Crit).unwrap(), "\"crit\""); assert_eq!( serde_json::from_str::("4").unwrap(), Priority::Warning ); assert_eq!( serde_json::from_str::("\"info\"").unwrap(), Priority::Info ); assert!(serde_json::from_str::("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); } }