A0: contract stubs types, transport, fake and registry seams
Land the shared peer contracts: types, error mapping, transport trait, fake transport and fixtures, registry/proxy/health skeletons, the AppState.peers and Config.peers seams, the ping and peers route stubs, and unit plus integration tests. No loops, no network, feature off by default.
This commit is contained in:
1 parent
746b389a2b
commit
4bfb097be6
22 files changed
+1781
-1
No files matched your search
@@ -0,0 +1,319 @@
|
||||
//! Types shared by peer configuration, the registry, proxying and fixtures.
|
||||
|
||||
use std::fmt;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use jiff::Timestamp;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use url::Url;
|
||||
|
||||
use crate::config::ConfigError;
|
||||
|
||||
/// Upper bound on configured peers; keeps health loops and snapshots bounded.
|
||||
pub const MAX_PEERS: usize = 64;
|
||||
|
||||
/// Validated peer name, `^[a-z0-9][a-z0-9_-]{0,31}$`.
|
||||
///
|
||||
/// Names end up in URLs, MCP arguments and metric attributes, so the
|
||||
/// character set is deliberately narrow.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct PeerName(String);
|
||||
|
||||
impl PeerName {
|
||||
pub fn parse(s: &str) -> Result<Self, ConfigError> {
|
||||
let valid = !s.is_empty()
|
||||
&& s.len() <= 32
|
||||
&& s.bytes().enumerate().all(|(i, b)| match b {
|
||||
b'a'..=b'z' | b'0'..=b'9' => true,
|
||||
b'_' | b'-' => i > 0,
|
||||
_ => false,
|
||||
});
|
||||
if !valid {
|
||||
return Err(ConfigError::Invalid(format!(
|
||||
"peer name {s:?} must match ^[a-z0-9][a-z0-9_-]{{0,31}}$"
|
||||
)));
|
||||
}
|
||||
Ok(Self(s.to_owned()))
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for PeerName {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for PeerName {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for PeerName {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let s = String::deserialize(d)?;
|
||||
Self::parse(&s).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
/// A token value that must never reach logs, `Debug` output or serialized
|
||||
/// config. Only the transport may read it.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct Secret(String);
|
||||
|
||||
impl Secret {
|
||||
pub fn new(value: impl Into<String>) -> Self {
|
||||
Self(value.into())
|
||||
}
|
||||
|
||||
pub fn expose(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Secret {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("Secret(***)")
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Secret {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("***")
|
||||
}
|
||||
}
|
||||
|
||||
/// One validated `[[peers.peer]]` entry. The token itself is not held here;
|
||||
/// only the path of the externally managed file.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PeerConfig {
|
||||
pub name: PeerName,
|
||||
pub url: Url,
|
||||
pub token_file: PathBuf,
|
||||
pub ca_file: Option<PathBuf>,
|
||||
pub allow_plain_http: bool,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
impl PeerConfig {
|
||||
/// Display form for REST and MCP output. `Url` normalizes an empty path
|
||||
/// to `/`; drop it so `http://beta:1984` does not render as `.../`.
|
||||
pub fn display_url(&self) -> String {
|
||||
let s = self.url.as_str();
|
||||
if self.url.path() == "/" {
|
||||
s.strip_suffix('/').unwrap_or(s).to_owned()
|
||||
} else {
|
||||
s.to_owned()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `[peers]` config section. Defaults keep the feature off.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct PeersConfig {
|
||||
pub enabled: bool,
|
||||
pub tcp_interval_secs: u64,
|
||||
pub tcp_timeout_secs: u64,
|
||||
pub api_interval_secs: u64,
|
||||
pub api_timeout_secs: u64,
|
||||
pub fail_threshold: u32,
|
||||
pub request_timeout_secs: u64,
|
||||
pub max_response_bytes: u64,
|
||||
pub max_concurrent_per_peer: usize,
|
||||
pub max_concurrent_total: usize,
|
||||
pub deny_cidrs: Vec<String>,
|
||||
pub peer: Vec<PeerConfig>,
|
||||
}
|
||||
|
||||
impl Default for PeersConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
tcp_interval_secs: 10,
|
||||
tcp_timeout_secs: 3,
|
||||
api_interval_secs: 30,
|
||||
api_timeout_secs: 5,
|
||||
fail_threshold: 2,
|
||||
request_timeout_secs: 10,
|
||||
max_response_bytes: 8 * 1024 * 1024,
|
||||
max_concurrent_per_peer: 4,
|
||||
max_concurrent_total: 16,
|
||||
deny_cidrs: vec!["169.254.0.0/16".into(), "0.0.0.0/8".into()],
|
||||
peer: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Registry snapshot entry, serialized as-is by REST and MCP.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct PeerStatus {
|
||||
pub name: PeerName,
|
||||
pub enabled: bool,
|
||||
pub url: String,
|
||||
pub server: ServerStatus,
|
||||
pub api: ApiStatus,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default, Serialize)]
|
||||
pub struct ServerStatus {
|
||||
pub up: bool,
|
||||
/// Last change; `None` until the first check and reset on restart.
|
||||
pub since: Option<Timestamp>,
|
||||
pub last_checked: Option<Timestamp>,
|
||||
pub last_error: Option<String>,
|
||||
pub latency_ms: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default, Serialize)]
|
||||
pub struct ApiStatus {
|
||||
pub up: bool,
|
||||
pub since: Option<Timestamp>,
|
||||
pub last_checked: Option<Timestamp>,
|
||||
pub last_error: Option<String>,
|
||||
pub latency_ms: Option<u64>,
|
||||
pub auth: AuthState,
|
||||
pub peer_version: Option<String>,
|
||||
}
|
||||
|
||||
/// `Ok` and `Rejected` refer to our credential; `Unknown` is used before the
|
||||
/// first check and for peers without the authenticated ping endpoint.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AuthState {
|
||||
Ok,
|
||||
Rejected,
|
||||
#[default]
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Coarse outcome of a check; the precise cause is in [`crate::peers::error::PeerError`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CheckClass {
|
||||
Ok,
|
||||
Unauthorized,
|
||||
HttpError,
|
||||
Timeout,
|
||||
Unreachable,
|
||||
TlsError,
|
||||
}
|
||||
|
||||
impl CheckClass {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Ok => "ok",
|
||||
Self::Unauthorized => "unauthorized",
|
||||
Self::HttpError => "http_error",
|
||||
Self::Timeout => "timeout",
|
||||
Self::Unreachable => "unreachable",
|
||||
Self::TlsError => "tls_error",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn peer(name: &str, url: &str) -> PeerConfig {
|
||||
PeerConfig {
|
||||
name: PeerName::parse(name).unwrap(),
|
||||
url: Url::parse(url).unwrap(),
|
||||
token_file: PathBuf::from(format!("/run/peers/{name}.token")),
|
||||
ca_file: None,
|
||||
allow_plain_http: false,
|
||||
enabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_name_accepts_and_rejects() {
|
||||
assert!(PeerName::parse("a").is_ok());
|
||||
assert!(PeerName::parse("minipc1").is_ok());
|
||||
assert!(PeerName::parse("a_b-c9").is_ok());
|
||||
assert!(PeerName::parse(&"a".repeat(32)).is_ok());
|
||||
for bad in ["", "-a", "_a", "Beta", "beta!", "a b", &"a".repeat(33)] {
|
||||
assert!(PeerName::parse(bad).is_err(), "{bad:?} should be rejected");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_name_serde_roundtrip_and_validation() {
|
||||
let n = PeerName::parse("beta").unwrap();
|
||||
let json = serde_json::to_string(&n).unwrap();
|
||||
assert_eq!(json, "\"beta\"");
|
||||
assert_eq!(serde_json::from_str::<PeerName>(&json).unwrap(), n);
|
||||
assert!(serde_json::from_str::<PeerName>("\"Beta\"").is_err());
|
||||
assert_eq!(n.to_string(), "beta");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secret_redacts_debug_and_display() {
|
||||
let s = Secret::new("slinuxm_super_secret");
|
||||
assert_eq!(s.expose(), "slinuxm_super_secret");
|
||||
assert!(!format!("{s:?}").contains("super"));
|
||||
assert!(!format!("{s}").contains("super"));
|
||||
assert_eq!(format!("{s:?}"), "Secret(***)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_defaults_are_off() {
|
||||
let c = PeersConfig::default();
|
||||
assert!(!c.enabled);
|
||||
assert!(c.peer.is_empty());
|
||||
assert_eq!(c.tcp_interval_secs, 10);
|
||||
assert_eq!(c.request_timeout_secs, 10);
|
||||
assert_eq!(c.max_response_bytes, 8 * 1024 * 1024);
|
||||
assert_eq!(c.deny_cidrs, vec!["169.254.0.0/16", "0.0.0.0/8"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_toml_keeps_defaults() {
|
||||
let c: PeersConfig = toml::from_str("enabled = true\napi_interval_secs = 7\n").unwrap();
|
||||
assert!(c.enabled);
|
||||
assert_eq!(c.api_interval_secs, 7);
|
||||
assert_eq!(c.tcp_interval_secs, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_url_drops_normalized_root_path() {
|
||||
assert_eq!(
|
||||
peer("beta", "http://beta:1984").display_url(),
|
||||
"http://beta:1984"
|
||||
);
|
||||
assert_eq!(
|
||||
peer("beta", "https://beta:1984/").display_url(),
|
||||
"https://beta:1984"
|
||||
);
|
||||
assert_eq!(
|
||||
peer("beta", "https://beta:1984/base").display_url(),
|
||||
"https://beta:1984/base"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_json_shape() {
|
||||
let st = PeerStatus {
|
||||
name: PeerName::parse("beta").unwrap(),
|
||||
enabled: true,
|
||||
url: "http://beta:1984".into(),
|
||||
server: ServerStatus::default(),
|
||||
api: ApiStatus::default(),
|
||||
};
|
||||
let v = serde_json::to_value(&st).unwrap();
|
||||
assert_eq!(v["name"], "beta");
|
||||
assert_eq!(v["server"]["up"], serde_json::json!(false));
|
||||
assert_eq!(v["server"]["since"], serde_json::Value::Null);
|
||||
assert_eq!(v["api"]["auth"], "unknown");
|
||||
assert_eq!(
|
||||
serde_json::to_value(CheckClass::TlsError).unwrap(),
|
||||
"tls_error"
|
||||
);
|
||||
assert_eq!(serde_json::to_value(AuthState::Ok).unwrap(), "ok");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user