[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
File diff suppressed because it is too large Load Diff
+467
View File
@@ -0,0 +1,467 @@
// 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/.
//! The REST + JSON API on loopback (`/api/v1`), with its OpenAPI document generated from the
//! handlers (utoipa).
//!
//! Every request: the `Host` header must name this server (against DNS rebinding); a browser
//! write without `X-Ianitor-UI: 1` is refused (CSRF); a valid `Authorization: Bearer` API
//! token is required (nothing else identifies the caller: control trusts no `Remote-*`
//! header); 120 requests a minute per token. Bodies are at most 64 KiB, JSON, with no
//! unknown fields. Errors are one typed envelope with a plain-English message. Logs show
//! method, route template, status and time only.
// An error answer is built once per failed request; boxing it buys nothing.
#![allow(clippy::result_large_err)]
pub mod handlers;
pub mod views;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use axum::Router;
use axum::body::{Body as AxumBody, Bytes};
use axum::extract::{DefaultBodyLimit, FromRequest, MatchedPath, Request, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post};
use serde::de::DeserializeOwned;
use utoipa::OpenApi;
pub use views::health_state;
use crate::engine::{Control, Fail};
use crate::messages::{self, Params, message};
use crate::tokens::Refusal;
use crate::util::{hex, now, random, rfc3339, sha256_hex};
use views::{ErrorBody, ErrorEnvelope};
pub const MAX_BODY: usize = 64 * 1024;
const RATE_PER_MINUTE: u32 = 120;
/// Who is calling: the API token's id and name.
#[derive(Debug, Clone)]
pub struct Actor {
pub token_id: String,
pub name: String,
}
pub enum Stored {
Apply(String),
Json(u16, serde_json::Value),
}
pub struct AppState {
pub ctl: Arc<Control>,
idem: Mutex<HashMap<String, (String, Stored, u64)>>,
rate: Mutex<HashMap<String, (u64, u32)>>,
}
impl AppState {
pub fn new(ctl: Arc<Control>) -> Arc<AppState> {
Arc::new(AppState {
ctl,
idem: Mutex::new(HashMap::new()),
rate: Mutex::new(HashMap::new()),
})
}
/// Count one request against `bucket`; `Err(seconds to wait)` over the limit.
pub fn limit(&self, bucket: &str, per_window: u32, window: u64) -> Result<(), u64> {
let Ok(mut m) = self.rate.lock() else {
return Ok(());
};
let t = now();
let slot = t / window;
if m.len() > 10_000 {
m.retain(|_, (s, _)| *s + 1 >= slot);
}
let e = m.entry(bucket.to_owned()).or_insert((slot, 0));
if e.0 != slot {
*e = (slot, 0);
}
if e.1 >= per_window {
return Err((slot + 1) * window - t);
}
e.1 += 1;
Ok(())
}
/// Look up an Idempotency-Key. `Ok(Some)` replays, `Err` when the key was used for
/// another request.
pub fn idem_get(&self, key: &str, fingerprint: &str) -> Result<Option<Stored>, ApiError> {
let Ok(m) = self.idem.lock() else {
return Ok(None);
};
match m.get(key) {
Some((fp, _, _)) if fp != fingerprint => Err(ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY,
"request.idempotency",
Params::new(),
)),
Some((_, Stored::Apply(id), _)) => Ok(Some(Stored::Apply(id.clone()))),
Some((_, Stored::Json(s, v), _)) => Ok(Some(Stored::Json(*s, v.clone()))),
None => Ok(None),
}
}
pub fn idem_put(&self, key: &str, fingerprint: &str, s: Stored) {
if let Ok(mut m) = self.idem.lock() {
let t = now();
m.retain(|_, (_, _, at)| t.saturating_sub(*at) < 86_400);
if m.len() >= 2000 {
return;
}
m.insert(key.to_owned(), (fingerprint.to_owned(), s, t));
}
}
}
// ---------------------------------------------------------------- errors
#[derive(Debug)]
pub struct ApiError {
pub status: StatusCode,
pub body: ErrorBody,
pub errors: Vec<ErrorBody>,
}
impl ApiError {
pub fn new(status: StatusCode, code: &str, params: Params) -> ApiError {
ApiError {
status,
body: ErrorBody {
code: code.into(),
message: message(code, &params),
field: params.get("field").cloned(),
params,
retry_after_s: None,
detail: None,
},
errors: Vec::new(),
}
}
pub fn internal(detail: impl Into<String>) -> ApiError {
let mut e = ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal", Params::new());
e.body.detail = Some(detail.into());
e
}
pub fn retry(mut self, secs: u64) -> ApiError {
self.body.retry_after_s = Some(secs);
self.body.params.insert("seconds".into(), secs.to_string());
self.body.message = message(&self.body.code, &self.body.params);
self
}
}
impl From<Fail> for ApiError {
fn from(f: Fail) -> ApiError {
ApiError {
status: StatusCode::from_u16(f.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
body: ErrorBody::from(&f.reason),
errors: f.errors.iter().map(ErrorBody::from).collect(),
}
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let retry = self.body.retry_after_s;
let env = ErrorEnvelope {
error: self.body,
errors: self.errors,
request_id: String::new(),
};
let mut r = (self.status, axum::Json(env)).into_response();
if let Some(s) = retry
&& let Ok(v) = HeaderValue::from_str(&s.to_string())
{
r.headers_mut().insert(header::RETRY_AFTER, v);
}
r
}
}
// ---------------------------------------------------------------- JSON bodies
/// A JSON request body: at most 64 KiB, no unknown fields, errors that never echo values.
pub struct Body<T> {
pub value: T,
pub raw: Bytes,
}
impl<T: DeserializeOwned, S: Send + Sync> FromRequest<S> for Body<T> {
type Rejection = ApiError;
async fn from_request(req: Request, state: &S) -> Result<Self, ApiError> {
let json_type = req
.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.starts_with("application/json"));
let raw = Bytes::from_request(req, state).await.map_err(|_| {
ApiError::new(
StatusCode::PAYLOAD_TOO_LARGE,
"request.too_large",
Params::new(),
)
})?;
let text: &[u8] = if raw.is_empty() { b"{}" } else { &raw };
if !raw.is_empty() && !json_type {
return Err(ApiError::new(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"request.body",
messages::params([("problem", "send it as application/json.".into())]),
));
}
match serde_json::from_slice::<T>(text) {
Ok(value) => Ok(Body { value, raw }),
Err(e) => Err(body_error(&e)),
}
}
}
fn body_error(e: &serde_json::Error) -> ApiError {
let m = e.to_string();
let quoted = |prefix: &str| -> Option<String> {
let rest = m.split(prefix).nth(1)?;
Some(rest.split('`').next()?.to_owned())
};
if let Some(f) = quoted("unknown field `") {
let mut err = ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY,
"request.body_unknown_field",
messages::params([("field", f.clone())]),
);
err.body.field = Some(f);
return err;
}
if let Some(f) = quoted("missing field `") {
return ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY,
"request.body",
messages::params([
("problem", format!("the field \"{f}\" is missing.")),
("field", f),
]),
);
}
// Other serde messages can quote the value sent; say only where the problem is.
let what = match e.classify() {
serde_json::error::Category::Syntax | serde_json::error::Category::Eof => "it is not JSON",
_ => "a value has the wrong type or form",
};
ApiError::new(
StatusCode::BAD_REQUEST,
"request.body",
messages::params([(
"problem",
format!("{what} (line {}, column {}).", e.line(), e.column()),
)]),
)
}
// ---------------------------------------------------------------- middleware
fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
let Some(host) = headers.get(header::HOST).and_then(|h| h.to_str().ok()) else {
return false;
};
let port = ctl.cfg.listen.port();
let ok = [
ctl.cfg.listen.to_string(),
format!("localhost:{port}"),
format!("127.0.0.1:{port}"),
format!("[::1]:{port}"),
];
ok.iter().any(|o| o.eq_ignore_ascii_case(host))
|| ctl
.cfg
.allowed_hosts
.iter()
.any(|a| a.eq_ignore_ascii_case(host))
}
/// Host check, CSRF check, token, rate limit; logs method, route template, status, time.
async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) -> Response {
let started = Instant::now();
let method = req.method().clone();
let route = req
.extensions()
.get::<MatchedPath>()
.map(|p| p.as_str().to_owned())
.unwrap_or_else(|| "(no route)".into());
let resp = async {
if !host_allowed(&st.ctl, req.headers()) {
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"request.host",
Params::new(),
));
}
let browser = req.headers().contains_key(header::ORIGIN)
|| req.headers().contains_key("sec-fetch-site");
let write = !matches!(method.as_str(), "GET" | "HEAD" | "OPTIONS");
let ui = req
.headers()
.get("x-ianitor-ui")
.is_some_and(|v| v.as_bytes() == b"1");
if browser && write && !ui {
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"request.csrf",
Params::new(),
));
}
let auth = req
.headers()
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok());
let tok = st.ctl.tokens.check(auth).map_err(|r| {
let (code, params) = match r {
Refusal::Missing => ("token.missing", Params::new()),
Refusal::Unknown => ("token.unknown", Params::new()),
Refusal::Expired(t) => (
"token.expired",
messages::params([("date", ianitor_core::time::long_date(t))]),
),
Refusal::Revoked(t) => (
"token.revoked",
messages::params([("date", ianitor_core::time::long_date(t))]),
),
};
ApiError::new(StatusCode::UNAUTHORIZED, code, params)
})?;
st.limit(&format!("token:{}", tok.id), RATE_PER_MINUTE, 60)
.map_err(|s| {
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
})?;
req.extensions_mut().insert(Actor {
token_id: tok.id,
name: tok.name,
});
Ok(next.run(req).await)
}
.await;
let resp = resp.unwrap_or_else(IntoResponse::into_response);
log::info!(target: "ianitor::api", "{method} {route} {} {} ms", resp.status().as_u16(), started.elapsed().as_millis());
resp
}
/// Adds `server_time` to every JSON object answer and `request_id` to error envelopes.
async fn finish(req: Request, next: Next) -> Response {
let request_id = random::<8>().map(|b| hex(&b)).unwrap_or_default();
let resp = next.run(req).await;
let json = resp
.headers()
.get(header::CONTENT_TYPE)
.is_some_and(|v| v.as_bytes().starts_with(b"application/json"));
let (mut parts, body) = resp.into_parts();
if let Ok(v) = HeaderValue::from_str(&request_id) {
parts.headers.insert("x-request-id", v);
}
if !json {
return Response::from_parts(parts, body);
}
let Ok(bytes) = axum::body::to_bytes(body, 16 << 20).await else {
return Response::from_parts(parts, AxumBody::empty());
};
let out = match serde_json::from_slice::<serde_json::Value>(&bytes) {
Ok(serde_json::Value::Object(mut m)) => {
m.insert("server_time".into(), rfc3339(now()).into());
if m.contains_key("error") {
m.insert("request_id".into(), request_id.into());
}
serde_json::to_vec(&m).unwrap_or_else(|_| bytes.to_vec())
}
_ => bytes.to_vec(),
};
parts.headers.remove(header::CONTENT_LENGTH);
Response::from_parts(parts, AxumBody::from(out))
}
async fn not_found() -> ApiError {
ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
}
async fn method_not_allowed() -> ApiError {
ApiError::new(
StatusCode::METHOD_NOT_ALLOWED,
"request.method",
Params::new(),
)
}
pub fn fingerprint(method: &str, path: &str, raw: &[u8]) -> String {
sha256_hex(format!("{method} {path} {}", sha256_hex(raw)).as_bytes())
}
pub fn router(st: Arc<AppState>) -> Router {
use handlers as h;
let api = Router::new()
.route("/api/v1/overview", get(h::overview))
.route("/api/v1/hosts", get(h::list_hosts).post(h::create_host))
.route("/api/v1/hosts/validate", post(h::validate_host))
.route(
"/api/v1/hosts/{hostname}",
get(h::get_host)
.put(h::update_host)
.patch(h::patch_host)
.delete(h::delete_host),
)
.route(
"/api/v1/hosts/{hostname}/share-links",
post(h::mint_share_link),
)
.route(
"/api/v1/hosts/{hostname}/certificate/retry",
post(h::retry_certificate),
)
.route("/api/v1/applies", get(h::list_applies))
.route(
"/api/v1/applies/{id}",
get(h::get_apply).delete(h::cancel_apply),
)
.route("/api/v1/history", get(h::history))
.route("/api/v1/history/{change_id}", get(h::history_entry))
.route(
"/api/v1/history/{change_id}/restore-preview",
get(h::restore_preview),
)
.route("/api/v1/undo", get(h::get_undo).post(h::undo))
.route("/api/v1/restore", post(h::restore))
.route("/api/v1/repo/push", post(h::push_now))
.route("/api/v1/settings", get(h::settings))
.route("/api/v1/tokens", get(h::list_tokens).post(h::create_token))
.route(
"/api/v1/tokens/{id}",
delete(h::revoke_token).patch(h::rename_token),
)
.route("/api/v1/share-links", get(h::list_share_links))
.route(
"/api/v1/share-links/stop-all",
post(h::stop_all_share_links),
)
.route("/api/v1/share-links/{id}", delete(h::stop_share_link))
.route("/api/v1/health", get(h::health))
.route("/api/v1/openapi.json", get(h::openapi))
.method_not_allowed_fallback(method_not_allowed)
.fallback(not_found)
.layer(middleware::from_fn_with_state(st.clone(), guard))
.layer(DefaultBodyLimit::max(MAX_BODY))
.with_state(st);
api.layer(middleware::from_fn(finish))
}
/// The OpenAPI document.
pub fn openapi_json() -> String {
handlers::ApiDoc::openapi()
.to_pretty_json()
.unwrap_or_else(|_| "{}".into())
}
+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,
}