[control] Phase 2 control plane: routes repo via git, journaled apply with trial/watch/revert, undo and restore, push with retry, share links, API tokens, REST API with OpenAPI, --dev

This commit is contained in:
2026-11-07 18:17:06 +01:00
parent 56209cc595
commit aa0f66b5ac
20 changed files with 7165 additions and 13 deletions
+797
View File
@@ -0,0 +1,797 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Response shapes (docs/ui-api.md §1, §2), built from control's state. Times are RFC 3339
//! UTC; every JSON object answer also gets `server_time` from the API layer.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::edgelink::{EdgeStatus, HostStatus};
use crate::engine::Control;
use crate::hostspec::HostSpec;
use crate::messages::{self, message};
use crate::records::{ApplyRecord, FieldError, Reason, Step, WatchHost};
use crate::util::{now, rfc3339};
fn t(x: Option<u64>) -> Option<String> {
x.map(rfc3339)
}
fn short(id: &Option<String>) -> Option<String> {
id.as_ref().map(|c| c.chars().take(7).collect())
}
/// One error, as the UI shows it (docs/ui-api.md §0).
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ErrorBody {
/// Stable code, e.g. `host.upstream.no_port`.
pub code: String,
/// Plain English, shown as is.
pub message: String,
/// The form field, e.g. `upstreams[0]`.
pub field: Option<String>,
pub params: BTreeMap<String, String>,
pub retry_after_s: Option<u64>,
/// Technical detail, behind "Show details". Never a secret.
pub detail: Option<String>,
}
impl From<&FieldError> for ErrorBody {
fn from(e: &FieldError) -> Self {
ErrorBody {
code: e.code.clone(),
message: e.message.clone(),
field: e.field.clone(),
params: e.params.clone(),
retry_after_s: None,
detail: e.detail.clone(),
}
}
}
impl From<&Reason> for ErrorBody {
fn from(r: &Reason) -> Self {
ErrorBody {
code: r.code.clone(),
message: r.message.clone(),
field: r.field.clone(),
params: r.params.clone(),
retry_after_s: None,
detail: r.detail.clone(),
}
}
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ErrorEnvelope {
pub error: ErrorBody,
pub errors: Vec<ErrorBody>,
pub request_id: String,
}
// ---------------------------------------------------------------- applies
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct WaitingFor {
pub apply_id: String,
pub summary: String,
pub seconds_left: Option<u64>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct QueueView {
pub position: usize,
pub waiting_for: Option<WaitingFor>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct WatchView {
pub ends_at: String,
pub seconds_left: u64,
pub hosts: Vec<WatchHost>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct PushView {
/// `pushed`, `pending` or `failed`.
pub state: String,
pub at: Option<String>,
pub error_code: Option<String>,
pub next_try_at: Option<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ApplyView {
pub id: String,
pub change_id: String,
/// `add`, `edit`, `remove`, `undo`, `restore` or `share_links`.
pub kind: String,
pub summary: String,
pub hosts: Vec<String>,
/// `queued`, `validating`, `applying`, `watching`, `kept`, `reverted`, `failed` or
/// `needs_attention`.
pub state: String,
pub created_at: String,
pub started_at: Option<String>,
pub finished_at: Option<String>,
pub steps: Vec<Step>,
pub queue: Option<QueueView>,
pub watch: Option<WatchView>,
pub reason: Option<Reason>,
pub errors: Vec<ErrorBody>,
pub commit_short: Option<String>,
pub commit: Option<String>,
pub push: Option<PushView>,
pub undo_of: Option<String>,
pub restore_of: Option<String>,
pub effect: Option<String>,
pub attempted_host: Option<HostSpec>,
pub actor: String,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ApplyAccepted {
pub apply: ApplyView,
}
pub fn apply_view(c: &Control, r: &ApplyRecord) -> ApplyView {
let n = now();
let queue = (r.state == "queued").then(|| {
let position = c.queue_position(&r.id).unwrap_or(1);
let running = c.records().into_iter().rev().find(|x| x.is_running());
QueueView {
position,
waiting_for: running.map(|x| WaitingFor {
apply_id: x.id.clone(),
summary: x.summary.clone(),
seconds_left: x.watch.as_ref().map(|w| w.ends.saturating_sub(n)),
}),
}
});
let push = (r.state == "kept" && r.commit.is_some()).then(|| {
let p = c.push_state();
let step = r
.steps
.iter()
.find(|s| s.key == "push")
.map(|s| s.state.as_str())
.unwrap_or("pending");
PushView {
state: match step {
"done" => "pushed",
"failed" => "failed",
_ if c.cfg.routes.remote.is_none() => "pending",
_ if p.error_code.is_some() => "failed",
_ => "pending",
}
.into(),
at: t(p.last_push_at),
error_code: p.error_code.clone(),
next_try_at: t(p.next_try_at),
}
});
ApplyView {
id: r.id.clone(),
change_id: r.id.clone(),
kind: r.kind.clone(),
summary: r.summary.clone(),
hosts: r.hosts.clone(),
state: r.state.clone(),
created_at: rfc3339(r.created),
started_at: t(r.started),
finished_at: t(r.finished),
steps: r.steps.clone(),
queue,
watch: r.watch.as_ref().map(|w| WatchView {
ends_at: rfc3339(w.ends),
seconds_left: if r.state == "watching" {
w.ends.saturating_sub(n)
} else {
0
},
hosts: w.hosts.clone(),
}),
reason: r.reason.clone(),
errors: r.errors.iter().map(ErrorBody::from).collect(),
commit_short: short(&r.commit),
commit: r.commit.clone(),
push,
undo_of: r.undo_of.clone(),
restore_of: r.restore_of.clone(),
effect: r.effect.clone(),
attempted_host: r.attempted_host.clone(),
actor: r.actor.clone(),
}
}
// ---------------------------------------------------------------- health
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct Failure {
pub kind: String,
pub upstream: String,
pub count: u32,
pub of: u32,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct UpstreamHealth {
pub url: String,
/// `healthy`, `down` or `pending`.
pub state: String,
pub last_check_at: Option<String>,
pub latency_ms: Option<u64>,
pub failure_kind: Option<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct HealthView {
/// `healthy`, `degraded`, `down`, `unknown` or `pending`.
pub state: String,
pub last_check_at: Option<String>,
pub latency_ms: Option<u64>,
pub since: Option<String>,
pub failure: Option<Failure>,
pub upstreams: Vec<UpstreamHealth>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct CertView {
/// `ok`, `pending` or `failed`.
pub state: String,
pub not_after: Option<String>,
pub error_code: Option<String>,
}
/// The health word for a host (docs/ui-api.md §1.1): `unknown` without a health check,
/// `pending` before the first check, `healthy` when every upstream passed its last check and
/// its recent ones, `degraded` when some fail or results are mixed, `down` when none passed.
pub fn health_state(h: &HostStatus) -> &'static str {
if !h.health_check {
return "unknown";
}
let checks: Vec<Vec<&crate::edgelink::Check>> = h
.upstreams
.iter()
.map(|u| {
u.checks
.iter()
.filter(|c| c.source == "health_check")
.collect()
})
.collect();
if checks.iter().all(|c| c.is_empty()) {
return "pending";
}
let last_ok: Vec<bool> = checks
.iter()
.map(|c| c.last().is_some_and(|x| x.ok))
.collect();
if !last_ok.iter().any(|x| *x) {
return "down";
}
let mixed = checks
.iter()
.any(|c| c.iter().any(|x| x.ok) && c.iter().any(|x| !x.ok));
if last_ok.iter().all(|x| *x) && !mixed {
"healthy"
} else {
"degraded"
}
}
fn scheme_url(spec: Option<&HostSpec>, address: &str) -> String {
let scheme = spec
.and_then(|s| s.upstreams.first())
.and_then(|u| u.split_once("://").map(|(s, _)| s.to_owned()))
.unwrap_or_else(|| "http".into());
format!("{scheme}://{address}")
}
pub fn health_view(
status: Option<&HostStatus>,
spec: Option<&HostSpec>,
since: Option<(&'static str, u64)>,
) -> HealthView {
let Some(h) = status else {
return HealthView {
state: if spec.is_some_and(|s| s.health_check.is_none()) {
"unknown"
} else {
"pending"
}
.into(),
last_check_at: None,
latency_ms: None,
since: None,
failure: None,
upstreams: Vec::new(),
};
};
let state = health_state(h);
let mut last_at = None;
let mut latency = None;
let mut failure: Option<Failure> = None;
let ups = h
.upstreams
.iter()
.map(|u| {
let checks: Vec<_> = u
.checks
.iter()
.filter(|c| c.source == "health_check")
.collect();
let last = checks.last();
if let Some(l) = last {
last_at = last_at.max(Some(l.at));
if l.ok {
latency = match (latency, l.latency_ms) {
(Some(a), Some(b)) => Some(u64::min(a, b)),
(a, b) => a.or(b),
};
} else if failure.is_none() {
failure = Some(Failure {
kind: l.kind.clone().unwrap_or_else(|| "bad_answer".into()),
upstream: scheme_url(spec, &u.address),
count: checks.iter().filter(|c| !c.ok).count() as u32,
of: checks.len() as u32,
});
}
}
UpstreamHealth {
url: scheme_url(spec, &u.address),
state: match last {
None => "pending",
Some(l) if l.ok => "healthy",
Some(_) => "down",
}
.into(),
last_check_at: last.map(|l| rfc3339(l.at)),
latency_ms: last.and_then(|l| l.latency_ms),
failure_kind: last.and_then(|l| l.kind.clone()),
}
})
.collect();
HealthView {
state: state.into(),
last_check_at: t(last_at),
latency_ms: latency,
since: since
.filter(|(s, _)| *s == state)
.map(|(_, at)| rfc3339(at)),
failure: if matches!(state, "down" | "degraded") {
failure
} else {
None
},
upstreams: if h.health_check { ups } else { Vec::new() },
}
}
pub fn cert_view(status: Option<&HostStatus>, spec: Option<&HostSpec>) -> CertView {
match status {
Some(h) => CertView {
state: h.certificate.state.clone(),
not_after: h
.certificate
.not_after
.and_then(|x| u64::try_from(x).ok())
.map(rfc3339),
error_code: (h.certificate.state == "failed").then(|| "cert.failed".into()),
},
None => CertView {
state: if spec.is_some_and(|s| s.tls == "domi") {
"ok"
} else {
"pending"
}
.into(),
not_after: None,
error_code: None,
},
}
}
// ---------------------------------------------------------------- hosts and overview
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct HostRow {
pub hostname: String,
pub upstreams: Vec<String>,
pub tls: String,
pub auth: String,
pub websockets: bool,
pub share_links: bool,
pub added_at: Option<String>,
pub health: HealthView,
pub certificate: CertView,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct HostDetail {
pub host: HostSpec,
/// The routes commit this was read from; send it back as `base_rev`.
pub rev: String,
/// The host file as committed.
pub toml: String,
pub health: HealthView,
pub certificate: CertView,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct HostList {
pub rev: String,
pub hosts: Vec<HostRow>,
}
#[derive(Debug, Clone, Default, Serialize, ToSchema)]
pub struct Counts {
pub hosts: usize,
pub healthy: usize,
pub degraded: usize,
pub down: usize,
pub unknown: usize,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct EngineView {
/// `pingora` (the Caddy switch waits on Mark, ROADMAP §10 (b)).
pub running: String,
/// `running` or `stopped` (control cannot reach it).
pub state: String,
pub since: Option<String>,
#[schema(value_type = Option<Object>)]
pub fallback_ready: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct UndoTarget {
pub change_id: String,
pub summary: String,
pub kept_at: Option<String>,
pub commit_short: Option<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct Blocked {
pub code: String,
pub message: String,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct UndoView {
pub available: bool,
pub target: Option<UndoTarget>,
/// What Undo does, e.g. "Removes recipes.home.example".
pub effect: Option<String>,
pub blocked: Option<Blocked>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ActiveApply {
pub id: String,
pub state: String,
pub summary: String,
pub seconds_left: Option<u64>,
pub queued: usize,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct RepoView {
pub name: String,
pub last_push_at: Option<String>,
pub unpushed: u64,
pub push_error_code: Option<String>,
pub remote_configured: bool,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct SiteView {
pub forward_auth_configured: bool,
pub acme_configured: bool,
pub secrets: Vec<String>,
pub watch_seconds: u64,
pub share_links_available: bool,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct Overview {
pub counts: Counts,
pub hosts: Vec<HostRow>,
pub engine: EngineView,
pub last_apply: Option<ApplyView>,
pub undo: UndoView,
pub active_apply: Option<ActiveApply>,
pub repo: Option<RepoView>,
/// The Domi intermediate; arrives in phase 3.
#[schema(value_type = Option<Object>)]
pub intermediate: Option<serde_json::Value>,
pub site: Option<SiteView>,
pub paused: Option<Blocked>,
/// Set when control cannot read health from edge (`health.unavailable`).
pub health_error: Option<Blocked>,
pub rev: Option<String>,
}
pub fn added_at(c: &Control, hostname: &str) -> Option<String> {
c.records()
.iter()
.find(|r| r.kind == "add" && r.state == "kept" && r.hosts.iter().any(|h| h == hostname))
.and_then(|r| r.finished)
.map(rfc3339)
}
pub fn undo_view(c: &Control) -> UndoView {
let blocked = if let Some(p) = c.paused() {
Some(Blocked {
code: "undo.paused".into(),
message: message("undo.paused", &messages::Params::new()) + " " + &p.message,
})
} else {
c.records()
.iter()
.rev()
.find(|r| r.is_running() && r.kind == "undo")
.map(|r| {
let left = r
.watch
.as_ref()
.map(|w| w.ends.saturating_sub(now()))
.unwrap_or(0);
Blocked {
code: "undo.watching".into(),
message: message(
"undo.watching",
&messages::params([("seconds", left.to_string())]),
),
}
})
};
match c.undo_target() {
None => UndoView {
available: false,
target: None,
effect: None,
blocked: Some(blocked.unwrap_or(Blocked {
code: "undo.nothing".into(),
message: message("undo.nothing", &messages::Params::new()),
})),
},
Some(t) => {
let effect = undo_effect(c, &t);
UndoView {
available: blocked.is_none(),
target: Some(UndoTarget {
change_id: t.id.clone(),
summary: t.summary.clone(),
kept_at: t.finished.map(rfc3339),
commit_short: short(&t.commit),
}),
effect,
blocked,
}
}
}
}
/// What undoing `t` would do: from its tree back to the tree before it.
pub fn undo_effect(c: &Control, t: &ApplyRecord) -> Option<String> {
let (commit, base) = (t.commit.as_ref()?, t.base.as_ref()?);
let from = c.repo.tree(commit).ok()?;
let to = c.repo.tree(base).ok()?;
let mut parts = Vec::new();
let mut names: std::collections::BTreeSet<String> = from.hostnames().into_iter().collect();
names.extend(to.hostnames());
for h in names {
match (from.host(&h), to.host(&h)) {
(Some(a), Some(b)) if a != b => parts.push(format!("Changes {h} back")),
(Some(_), None) => parts.push(format!("Removes {h}")),
(None, Some(_)) => parts.push(format!("Adds {h} back")),
_ => {}
}
}
Some(if parts.is_empty() {
"Changes the site settings back".into()
} else {
parts.join("; ")
})
}
pub fn host_rows(
c: &Control,
tree: &crate::repo::RouteTree,
status: Option<&EdgeStatus>,
since: &std::collections::HashMap<String, (&'static str, u64)>,
) -> Vec<HostRow> {
tree.hostnames()
.into_iter()
.map(|h| {
let spec = tree.host(&h).and_then(|t| HostSpec::from_toml(t).ok());
let st = status.and_then(|s| s.hosts.iter().find(|x| x.hostname == h));
HostRow {
upstreams: spec
.as_ref()
.map(|s| s.upstreams.clone())
.unwrap_or_default(),
tls: spec.as_ref().map(|s| s.tls.clone()).unwrap_or_default(),
auth: spec.as_ref().map(|s| s.auth.clone()).unwrap_or_default(),
websockets: spec.as_ref().is_none_or(|s| s.websockets),
share_links: spec.as_ref().is_some_and(|s| s.share_links),
added_at: added_at(c, &h),
health: health_view(st, spec.as_ref(), since.get(&h).copied()),
certificate: cert_view(st, spec.as_ref()),
hostname: h,
}
})
.collect()
}
// ---------------------------------------------------------------- history
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct HistoryEntry {
pub change_id: String,
pub summary: String,
pub kind: String,
pub state: String,
pub at: String,
pub commit_short: Option<String>,
pub hosts: Vec<String>,
pub reason_short: Option<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct History {
pub entries: Vec<HistoryEntry>,
/// Pass as `before` for older entries.
pub next_before: Option<String>,
}
pub fn history_row(r: &ApplyRecord) -> HistoryEntry {
HistoryEntry {
change_id: r.id.clone(),
summary: r.summary.clone(),
kind: r.kind.clone(),
state: r.state.clone(),
at: rfc3339(r.finished.unwrap_or(r.created)),
commit_short: short(&r.commit),
hosts: r.hosts.clone(),
reason_short: r.reason.as_ref().filter(|_| r.state != "kept").map(|x| {
x.params
.get("kind")
.cloned()
.unwrap_or_else(|| x.code.rsplit('.').next().unwrap_or("").replace('_', " "))
}),
}
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct FieldChange {
pub field: String,
pub from: String,
pub to: String,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct HostChange {
pub hostname: String,
/// `added`, `removed` or `changed`.
pub effect: String,
pub fields: Vec<FieldChange>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct RestorePreview {
pub restorable: bool,
pub same_as_current: bool,
pub changes: Vec<HostChange>,
pub blocked: Option<Blocked>,
}
// ---------------------------------------------------------------- tokens, shares, settings
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct TokenView {
pub id: String,
pub name: String,
pub created_at: String,
pub last_used_at: Option<String>,
pub expires_at: Option<String>,
pub revoked_at: Option<String>,
}
impl From<&crate::tokens::TokenRecord> for TokenView {
fn from(r: &crate::tokens::TokenRecord) -> Self {
TokenView {
id: r.id.clone(),
name: r.name.clone(),
created_at: rfc3339(r.created_at),
last_used_at: t(r.last_used_at),
expires_at: t(r.expires_at),
revoked_at: t(r.revoked_at),
}
}
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct TokenList {
pub items: Vec<TokenView>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct CreatedToken {
pub id: String,
pub name: String,
/// Shown once; Ianitor keeps only its hash.
pub token: String,
pub expires_at: Option<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ShareLinkView {
pub id: String,
pub hostname: String,
pub path_prefix: String,
pub created_at: String,
pub expires_at: String,
pub has_password: bool,
/// `active`, `expired` or `stopped`.
pub state: String,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ShareLinkList {
pub items: Vec<ShareLinkView>,
pub epoch: u32,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct MintedLink {
pub id: String,
/// Contains the token; shown once.
pub url: String,
pub expires_at: String,
pub path_prefix: String,
pub has_password: bool,
/// `host.share.no_signin` when the host needs no sign-in anyway.
pub warning: Option<Blocked>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct StoppedAll {
pub epoch: u32,
pub message: String,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct Settings {
pub repo: RepoView,
pub watch_seconds: u64,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct EdgeHealth {
pub attached: bool,
pub reachable: bool,
pub config_sha256: Option<String>,
pub trial_running: bool,
pub error: Option<String>,
pub read_at: Option<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct HealthReport {
pub edge: EdgeHealth,
pub paused: Option<Blocked>,
pub queued: usize,
pub hosts: Vec<HostRow>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct Done {
pub message: String,
}