G: F2 reflect peer status schemas from JsonSchema derives

This commit is contained in:
ari committed 2026-10-20 15:54:13 -04:00
1 parent 1506af11fc
commit d2917b2483
3 files changed
+155 -184

No files matched your search

+113 -21
View File
@@ -964,19 +964,19 @@
"schemas": { "schemas": {
"ApiStatus": { "ApiStatus": {
"type": "object", "type": "object",
"description": "\"API running\": an authenticated `GET /api/v1/ping`. `up` is true also when the peer answered 401, so a revoked token reads as `auth = rejected` rather than as an outage.",
"required": [ "required": [
"up", "up",
"since", "auth"
"last_checked",
"last_error",
"latency_ms",
"auth",
"peer_version"
], ],
"properties": { "properties": {
"auth": { "auth": {
"$ref": "#/components/schemas/AuthState" "type": "string",
"description": "State of the consolidator's credential on the peer.",
"enum": [
"ok",
"rejected",
"unknown"
]
}, },
"last_checked": { "last_checked": {
"type": [ "type": [
@@ -997,6 +997,7 @@
"integer", "integer",
"null" "null"
], ],
"format": "uint64",
"minimum": 0 "minimum": 0
}, },
"peer_version": { "peer_version": {
@@ -1012,7 +1013,7 @@
"null" "null"
], ],
"format": "date-time", "format": "date-time",
"description": "Time of the last state change; null until the first check and reset on restart." "description": "Last change; `None` until the first check and reset on restart."
}, },
"up": { "up": {
"type": "boolean" "type": "boolean"
@@ -1021,7 +1022,7 @@
}, },
"AuthState": { "AuthState": {
"type": "string", "type": "string",
"description": "State of the consolidator's credential on the peer: `ok`, `rejected` or `unknown`.", "description": "`Ok` and `Rejected` refer to our credential; `Unknown` is used before the\nfirst check and for peers without the authenticated ping endpoint.",
"enum": [ "enum": [
"ok", "ok",
"rejected", "rejected",
@@ -1360,7 +1361,7 @@
}, },
"PeerStatus": { "PeerStatus": {
"type": "object", "type": "object",
"description": "One configured peer and the last result of both health checks.", "description": "Registry snapshot entry, serialized as-is by REST and MCP.",
"required": [ "required": [
"name", "name",
"enabled", "enabled",
@@ -1370,7 +1371,63 @@
], ],
"properties": { "properties": {
"api": { "api": {
"$ref": "#/components/schemas/ApiStatus" "type": "object",
"description": "\"API running\": an authenticated `GET /api/v1/ping`.",
"required": [
"up",
"auth"
],
"properties": {
"auth": {
"type": "string",
"description": "State of the consolidator's credential on the peer.",
"enum": [
"ok",
"rejected",
"unknown"
]
},
"last_checked": {
"type": [
"string",
"null"
],
"format": "date-time"
},
"last_error": {
"type": [
"string",
"null"
],
"description": "Failure class such as `http_500` or `token_file`; never a URL or a secret."
},
"latency_ms": {
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 0
},
"peer_version": {
"type": [
"string",
"null"
],
"description": "Version the peer reported, when it has the ping route."
},
"since": {
"type": [
"string",
"null"
],
"format": "date-time",
"description": "Last change; `None` until the first check and reset on restart."
},
"up": {
"type": "boolean"
}
}
}, },
"enabled": { "enabled": {
"type": "boolean", "type": "boolean",
@@ -1378,10 +1435,49 @@
}, },
"name": { "name": {
"type": "string", "type": "string",
"description": "Configured peer name, `^[a-z0-9][a-z0-9_-]{0,31}$`." "description": "Configured peer name."
}, },
"server": { "server": {
"$ref": "#/components/schemas/ServerStatus" "type": "object",
"description": "\"Server up\": a TCP connect to the peer's host and port.",
"required": [
"up"
],
"properties": {
"last_checked": {
"type": [
"string",
"null"
],
"format": "date-time"
},
"last_error": {
"type": [
"string",
"null"
],
"description": "Failure class such as `timeout` or `unreachable`; never a URL or a secret."
},
"latency_ms": {
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 0
},
"since": {
"type": [
"string",
"null"
],
"format": "date-time",
"description": "Last change; `None` until the first check and reset on restart."
},
"up": {
"type": "boolean"
}
}
}, },
"url": { "url": {
"type": "string", "type": "string",
@@ -1391,13 +1487,8 @@
}, },
"ServerStatus": { "ServerStatus": {
"type": "object", "type": "object",
"description": "\"Server up\": a TCP connect to the peer's host and port.",
"required": [ "required": [
"up", "up"
"since",
"last_checked",
"last_error",
"latency_ms"
], ],
"properties": { "properties": {
"last_checked": { "last_checked": {
@@ -1419,6 +1510,7 @@
"integer", "integer",
"null" "null"
], ],
"format": "uint64",
"minimum": 0 "minimum": 0
}, },
"since": { "since": {
@@ -1427,7 +1519,7 @@
"null" "null"
], ],
"format": "date-time", "format": "date-time",
"description": "Time of the last state change; null until the first check and reset on restart." "description": "Last change; `None` until the first check and reset on restart."
}, },
"up": { "up": {
"type": "boolean" "type": "boolean"
+26 -158
View File
@@ -6,13 +6,12 @@
//! collected by `ApiDoc`; the MCP tools come from the tool router's own //! collected by `ApiDoc`; the MCP tools come from the tool router's own
//! schemars schemas. Nothing here talks to D-Bus, journald or Docker. //! schemars schemas. Nothing here talks to D-Bus, journald or Docker.
//! //!
//! Response DTOs already derive `schemars::JsonSchema` for the MCP surface, so //! Response DTOs derive `schemars::JsonSchema` for the MCP surface, so their
//! their spec schemas are reflected from that derive rather than declared a //! spec schemas are reflected from that derive rather than declared a second
//! second time: a field added to a DTO appears in the document without an //! time: a field added to a DTO appears in the document without an edit here.
//! edit here. The exceptions are payloads that exist only as `serde_json` //! The only hand-written schemas are payloads that exist as `serde_json`
//! literals (the error body, health) and the peer status types, which are //! literals (the error body and health); the tests compare them with the JSON
//! described by hand; the tests compare both with the JSON the server really //! the server really produces, so a field cannot go missing quietly.
//! produces, so a field cannot go missing quietly.
use std::borrow::Cow; use std::borrow::Cow;
use std::sync::{Arc, OnceLock}; use std::sync::{Arc, OnceLock};
@@ -28,7 +27,7 @@ use utoipa::openapi::schema::{
use utoipa::openapi::security::{HttpAuthScheme, HttpBuilder, SecurityScheme}; use utoipa::openapi::security::{HttpAuthScheme, HttpBuilder, SecurityScheme};
use utoipa::openapi::tag::TagBuilder; use utoipa::openapi::tag::TagBuilder;
use utoipa::openapi::{ use utoipa::openapi::{
Info, InfoBuilder, License, OpenApi, Ref, RefOr, SecurityRequirement, ServerBuilder, Info, InfoBuilder, License, OpenApi, RefOr, SecurityRequirement, ServerBuilder,
}; };
use utoipa::{OpenApi as OpenApiDoc, PartialSchema, ToSchema}; use utoipa::{OpenApi as OpenApiDoc, PartialSchema, ToSchema};
@@ -286,6 +285,7 @@ macro_rules! reflected_schema {
reflected_schema!(UnitSummary, UnitStatus, TimerInfo, JournalEntry); reflected_schema!(UnitSummary, UnitStatus, TimerInfo, JournalEntry);
reflected_schema!(ContainerSummary, ContainerStatus, LogLine); reflected_schema!(ContainerSummary, ContainerStatus, LogLine);
reflected_schema!(PeerStatus, ServerStatus, ApiStatus, AuthState);
/// Translate one JSON Schema 2020-12 object into utoipa's model. /// Translate one JSON Schema 2020-12 object into utoipa's model.
/// ///
@@ -500,152 +500,6 @@ handwritten_schema!(
.into() .into()
); );
handwritten_schema!(
AuthState,
"AuthState",
ObjectBuilder::new()
.description(Some(
"State of the consolidator's credential on the peer: `ok`, `rejected` or `unknown`.",
))
.schema_type(Type::String)
.enum_values(Some(
["ok", "rejected", "unknown"].into_iter().map(Value::from)
))
.into()
);
handwritten_schema!(
ServerStatus,
"ServerStatus",
check_properties(
ObjectBuilder::new()
.description(Some(
"\"Server up\": a TCP connect to the peer's host and port."
))
.required("up")
.required("since")
.required("last_checked")
.required("last_error")
.required("latency_ms"),
"Failure class such as `timeout` or `unreachable`; never a URL or a secret.",
)
.into()
);
handwritten_schema!(
ApiStatus,
"ApiStatus",
check_properties(
ObjectBuilder::new()
.description(Some(
"\"API running\": an authenticated `GET /api/v1/ping`. `up` is true also when the \
peer answered 401, so a revoked token reads as `auth = rejected` rather than as an \
outage.",
))
.required("up")
.required("since")
.required("last_checked")
.required("last_error")
.required("latency_ms")
.required("auth")
.required("peer_version"),
"Failure class such as `http_500` or `token_file`; never a URL or a secret.",
)
.property("auth", Ref::from_schema_name("AuthState"))
.property(
"peer_version",
nullable(Type::String).description(Some(
"Version the peer reported, when it has the ping route."
)),
)
.into()
);
handwritten_schema!(
PeerStatus,
"PeerStatus",
ObjectBuilder::new()
.description(Some(
"One configured peer and the last result of both health checks."
))
.required("name")
.required("enabled")
.required("url")
.required("server")
.required("api")
.property(
"name",
ObjectBuilder::new()
.schema_type(Type::String)
.description(Some("Configured peer name, `^[a-z0-9][a-z0-9_-]{0,31}$`.")),
)
.property(
"enabled",
ObjectBuilder::new()
.schema_type(Type::Boolean)
.description(Some(
"`false` for a peer kept in configuration but not checked."
)),
)
.property(
"url",
ObjectBuilder::new()
.schema_type(Type::String)
.description(Some(
"Display form of the configured URL; never carries credentials.",
)),
)
.property("server", Ref::from_schema_name("ServerStatus"))
.property("api", Ref::from_schema_name("ApiStatus"))
.into()
);
/// Shared by both checks; the registry resets it on restart.
const SINCE_DOC: &str =
"Time of the last state change; null until the first check and reset on restart.";
/// `{"type": ["<scalar>", "null"]}`, how JSON Schema 2020-12 marks an
/// optional value. utoipa renders a two-type `SchemaType` the same way.
fn nullable(ty: Type) -> ObjectBuilder {
ObjectBuilder::new().schema_type(
[ty, Type::Null]
.into_iter()
.collect::<Vec<Type>>()
.into_iter()
.collect::<SchemaType>(),
)
}
fn date_time() -> SchemaFormat {
SchemaFormat::Custom("date-time".into())
}
/// The properties both peer checks share: `up`, `since` and `last_checked`
/// (described by [`SINCE_DOC`]), `last_error` with its check-specific wording
/// and `latency_ms`. Added in document order so the keys stay where they were.
fn check_properties(builder: ObjectBuilder, last_error: &str) -> ObjectBuilder {
builder
.property("up", ObjectBuilder::new().schema_type(Type::Boolean))
.property(
"since",
nullable(Type::String)
.format(Some(date_time()))
.description(Some(SINCE_DOC)),
)
.property(
"last_checked",
nullable(Type::String).format(Some(date_time())),
)
.property(
"last_error",
nullable(Type::String).description(Some(last_error)),
)
.property(
"latency_ms",
nullable(Type::Integer).minimum(Some(utoipa::Number::UInt(0))),
)
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -682,17 +536,25 @@ mod tests {
JournalEntry, JournalEntry,
ContainerSummary, ContainerSummary,
ContainerStatus, ContainerStatus,
LogLine LogLine,
PeerStatus,
ServerStatus,
ApiStatus,
AuthState
); );
} }
/// Compare the properties of a schema object with the keys of a JSON /// Compare a schema object with a JSON instance in both directions: every
/// instance; a field added to the type fails the test. /// serialized key must be documented, and every documented property must
/// be serialized. A renamed field fails both ways and no stale property
/// survives.
fn assert_covers(schema: &Value, instance: &Value, what: &str) { fn assert_covers(schema: &Value, instance: &Value, what: &str) {
if instance.is_null() {
return;
}
let (schema, instance) = match (schema, instance) { let (schema, instance) = match (schema, instance) {
(Value::Object(schema), Value::Object(instance)) => (schema, instance), (Value::Object(schema), Value::Object(instance)) => (schema, instance),
// A `$ref` points at a component covered by another assertion. // A `$ref` points at a component covered by another assertion.
(_, Value::Null) => return,
_ => panic!("{what}: expected object schemas and instances"), _ => panic!("{what}: expected object schemas and instances"),
}; };
if let Some(reference) = schema.get("$ref").and_then(Value::as_str) { if let Some(reference) = schema.get("$ref").and_then(Value::as_str) {
@@ -703,6 +565,12 @@ mod tests {
.get("properties") .get("properties")
.and_then(Value::as_object) .and_then(Value::as_object)
.unwrap_or_else(|| panic!("{what}: no properties")); .unwrap_or_else(|| panic!("{what}: no properties"));
for key in properties.keys() {
assert!(
instance.contains_key(key),
"{what}: documented property {key} is not serialized"
);
}
for (key, value) in instance { for (key, value) in instance {
let property = properties let property = properties
.get(key) .get(key)
+16 -5
View File
@@ -16,7 +16,8 @@ pub const MAX_PEERS: usize = 64;
/// ///
/// Names end up in URLs, MCP arguments and metric attributes, so the /// Names end up in URLs, MCP arguments and metric attributes, so the
/// character set is deliberately narrow. /// character set is deliberately narrow.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, schemars::JsonSchema)]
#[schemars(transparent)]
pub struct PeerName(String); pub struct PeerName(String);
impl PeerName { impl PeerName {
@@ -160,39 +161,49 @@ impl Default for PeersConfig {
} }
/// Registry snapshot entry, serialized as-is by REST and MCP. /// Registry snapshot entry, serialized as-is by REST and MCP.
#[derive(Debug, Clone, PartialEq, Serialize)] #[derive(Debug, Clone, PartialEq, Serialize, schemars::JsonSchema)]
pub struct PeerStatus { pub struct PeerStatus {
/// Configured peer name.
pub name: PeerName, pub name: PeerName,
/// `false` for a peer kept in configuration but not checked.
pub enabled: bool, pub enabled: bool,
/// Display form of the configured URL; never carries credentials.
pub url: String, pub url: String,
/// "Server up": a TCP connect to the peer's host and port.
pub server: ServerStatus, pub server: ServerStatus,
/// "API running": an authenticated `GET /api/v1/ping`.
pub api: ApiStatus, pub api: ApiStatus,
} }
#[derive(Debug, Clone, PartialEq, Default, Serialize)] #[derive(Debug, Clone, PartialEq, Default, Serialize, schemars::JsonSchema)]
pub struct ServerStatus { pub struct ServerStatus {
pub up: bool, pub up: bool,
/// Last change; `None` until the first check and reset on restart. /// Last change; `None` until the first check and reset on restart.
pub since: Option<Timestamp>, pub since: Option<Timestamp>,
pub last_checked: Option<Timestamp>, pub last_checked: Option<Timestamp>,
/// Failure class such as `timeout` or `unreachable`; never a URL or a secret.
pub last_error: Option<String>, pub last_error: Option<String>,
pub latency_ms: Option<u64>, pub latency_ms: Option<u64>,
} }
#[derive(Debug, Clone, PartialEq, Default, Serialize)] #[derive(Debug, Clone, PartialEq, Default, Serialize, schemars::JsonSchema)]
pub struct ApiStatus { pub struct ApiStatus {
pub up: bool, pub up: bool,
/// Last change; `None` until the first check and reset on restart.
pub since: Option<Timestamp>, pub since: Option<Timestamp>,
pub last_checked: Option<Timestamp>, pub last_checked: Option<Timestamp>,
/// Failure class such as `http_500` or `token_file`; never a URL or a secret.
pub last_error: Option<String>, pub last_error: Option<String>,
pub latency_ms: Option<u64>, pub latency_ms: Option<u64>,
/// State of the consolidator's credential on the peer.
pub auth: AuthState, pub auth: AuthState,
/// Version the peer reported, when it has the ping route.
pub peer_version: Option<String>, pub peer_version: Option<String>,
} }
/// `Ok` and `Rejected` refer to our credential; `Unknown` is used before the /// `Ok` and `Rejected` refer to our credential; `Unknown` is used before the
/// first check and for peers without the authenticated ping endpoint. /// first check and for peers without the authenticated ping endpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
pub enum AuthState { pub enum AuthState {
Ok, Ok,