| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
use self::cargo::{cargo_test, clippy, fmt_check, hardening_test, supply_chain}; |
| 22 |
use self::code_smoke::code_smoke; |
| 23 |
use self::migration::migration_dry_run; |
| 24 |
use self::probes::{boot_smoke, node_health, page_smoke}; |
| 25 |
use crate::config::AppConfig; |
| 26 |
use crate::domain::{AppId, GateKind, GateRunId, TierId, Version}; |
| 27 |
use crate::events::{self, Event, EventTx}; |
| 28 |
use crate::outcome::{GateBlocker, GateFailure, GateOutcome, LogRef, PassNote}; |
| 29 |
use crate::topology::Gate; |
| 30 |
use anyhow::Result; |
| 31 |
use chrono::Utc; |
| 32 |
use sqlx::SqlitePool; |
| 33 |
use std::collections::HashMap; |
| 34 |
use std::path::Path; |
| 35 |
use std::path::PathBuf; |
| 36 |
use std::sync::Arc; |
| 37 |
|
| 38 |
mod cargo; |
| 39 |
mod code_smoke; |
| 40 |
mod log; |
| 41 |
mod migration; |
| 42 |
mod pg; |
| 43 |
mod probes; |
| 44 |
#[cfg(test)] |
| 45 |
mod testkit; |
| 46 |
|
| 47 |
pub use pg::preflight_scratch_privileges; |
| 48 |
pub(crate) use pg::{reset_scratch, run_migrator}; |
| 49 |
|
| 50 |
pub struct GateCtx { |
| 51 |
pub pool: SqlitePool, |
| 52 |
pub cfg: Arc<AppConfig>, |
| 53 |
pub tier: TierId, |
| 54 |
pub version: Version, |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
pub worktree: Option<PathBuf>, |
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
pub bundle: Option<PathBuf>, |
| 67 |
pub events: EventTx, |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
pub nodes: Vec<NodeProbe>, |
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
pub build_id: Option<i64>, |
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
pub aux_dirs: HashMap<String, PathBuf>, |
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
pub public_url: Option<String>, |
| 89 |
} |
| 90 |
|
| 91 |
impl GateCtx { |
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
pub fn log_scope(&self) -> String { |
| 103 |
self.build_id |
| 104 |
.map_or_else(|| self.version.to_string(), |id| id.to_string()) |
| 105 |
} |
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
pub fn log_ref(&self, gate: GateKind) -> LogRef { |
| 110 |
LogRef::new(&self.log_scope(), gate) |
| 111 |
} |
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
pub fn log_path(&self, gate: GateKind) -> PathBuf { |
| 117 |
self.cfg |
| 118 |
.logs_root |
| 119 |
.join(self.log_scope()) |
| 120 |
.join(format!("{}.log", gate.as_str())) |
| 121 |
} |
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
pub fn target_dir(&self, target: &crate::config::TestTarget) -> Option<PathBuf> { |
| 132 |
match target.aux_repo.as_deref() { |
| 133 |
None => Some(self.worktree.as_ref()?.join(&target.dir)), |
| 134 |
Some(name) => Some(self.aux_dirs.get(name)?.join(&target.dir)), |
| 135 |
} |
| 136 |
} |
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
pub fn worktree_for(&self, gate: GateKind) -> std::result::Result<&Path, GateOutcome> { |
| 146 |
self.worktree.as_deref().ok_or_else(|| { |
| 147 |
GateOutcome::failed(GateFailure::NeedsSource { |
| 148 |
gate, |
| 149 |
artifact: self.bundle.as_ref().map_or_else( |
| 150 |
|| "an artifact built elsewhere".into(), |
| 151 |
|b| b.display().to_string(), |
| 152 |
), |
| 153 |
}) |
| 154 |
}) |
| 155 |
} |
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
pub fn migrations_dir(&self, dir: &Path) -> Option<PathBuf> { |
| 167 |
if let Some(bundle) = &self.bundle { |
| 168 |
let in_bundle = bundle.join(dir); |
| 169 |
if in_bundle.is_dir() { |
| 170 |
return Some(in_bundle); |
| 171 |
} |
| 172 |
} |
| 173 |
let in_worktree = self.worktree.as_ref()?.join(dir); |
| 174 |
in_worktree.is_dir().then_some(in_worktree) |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
pub struct NodeProbe { |
| 182 |
pub node: crate::domain::NodeId, |
| 183 |
pub service: String, |
| 184 |
pub health_url: Option<String>, |
| 185 |
pub executor: Arc<dyn ops_exec::Executor>, |
| 186 |
} |
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
pub async fn run(ctx: &GateCtx, gate: &Gate) -> Result<GateOutcome> { |
| 191 |
let kind = gate.kind(); |
| 192 |
let started_at = Utc::now().to_rfc3339(); |
| 193 |
|
| 194 |
let id: i64 = sqlx::query_scalar( |
| 195 |
"INSERT INTO gate_runs (app, version, tier, gate_kind, started_at, build_id) |
| 196 |
VALUES (?, ?, ?, ?, ?, ?) |
| 197 |
RETURNING id", |
| 198 |
) |
| 199 |
.bind(&ctx.cfg.id) |
| 200 |
.bind(&ctx.version) |
| 201 |
.bind(&ctx.tier) |
| 202 |
.bind(kind) |
| 203 |
.bind(&started_at) |
| 204 |
.bind(ctx.build_id) |
| 205 |
.fetch_one(&ctx.pool) |
| 206 |
.await?; |
| 207 |
let run_id = GateRunId(id); |
| 208 |
|
| 209 |
tracing::info!( |
| 210 |
run_id = %run_id, tier = %ctx.tier, version = %ctx.version, gate = %kind, |
| 211 |
"gate start", |
| 212 |
); |
| 213 |
events::emit( |
| 214 |
&ctx.events, |
| 215 |
Event::GateStart { |
| 216 |
run_id, |
| 217 |
tier: ctx.tier.clone(), |
| 218 |
version: ctx.version.clone(), |
| 219 |
gate: kind, |
| 220 |
}, |
| 221 |
); |
| 222 |
|
| 223 |
let outcome = match gate { |
| 224 |
|
| 225 |
Gate::CargoTest => cargo_test(ctx, run_id).await, |
| 226 |
|
| 227 |
Gate::HardeningTest => hardening_test(ctx, run_id).await, |
| 228 |
|
| 229 |
|
| 230 |
Gate::Clippy => clippy(ctx, run_id).await, |
| 231 |
Gate::Fmt => fmt_check(ctx, run_id).await, |
| 232 |
Gate::CargoAudit => supply_chain(ctx, run_id, GateKind::CargoAudit).await, |
| 233 |
Gate::CargoDeny => supply_chain(ctx, run_id, GateKind::CargoDeny).await, |
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
Gate::MigrationDryRun => { |
| 238 |
let ceiling = std::time::Duration::from_secs(ctx.cfg.gate_timeout_secs); |
| 239 |
match tokio::time::timeout(ceiling, migration_dry_run(ctx, run_id)).await { |
| 240 |
Ok(res) => res, |
| 241 |
Err(_elapsed) => Ok(GateOutcome::failed(GateFailure::Timeout { |
| 242 |
gate: GateKind::MigrationDryRun, |
| 243 |
after_s: ctx.cfg.gate_timeout_secs as u32, |
| 244 |
}) |
| 245 |
.with_log_ref(ctx.log_ref(GateKind::MigrationDryRun))), |
| 246 |
} |
| 247 |
} |
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
Gate::CodeSmoke => { |
| 254 |
let ceiling = std::time::Duration::from_secs(ctx.cfg.gate_timeout_secs); |
| 255 |
match tokio::time::timeout(ceiling, code_smoke(ctx, run_id)).await { |
| 256 |
Ok(res) => res, |
| 257 |
Err(_elapsed) => Ok(GateOutcome::failed(GateFailure::Timeout { |
| 258 |
gate: GateKind::CodeSmoke, |
| 259 |
after_s: ctx.cfg.gate_timeout_secs as u32, |
| 260 |
}) |
| 261 |
.with_log_ref(ctx.log_ref(GateKind::CodeSmoke))), |
| 262 |
} |
| 263 |
} |
| 264 |
Gate::BootSmoke => boot_smoke(ctx, run_id).await, |
| 265 |
Gate::NodeHealth => node_health(ctx).await, |
| 266 |
Gate::PageSmoke => page_smoke(ctx).await, |
| 267 |
Gate::BurnIn { hours } => burn_in(ctx, *hours).await, |
| 268 |
Gate::ManualConfirm => manual_confirm(ctx).await, |
| 269 |
}; |
| 270 |
|
| 271 |
let outcome = outcome.unwrap_or_else(|e| { |
| 272 |
GateOutcome::failed(GateFailure::Unclassified { |
| 273 |
legacy_detail: Some(format!("gate runner errored: {e}")), |
| 274 |
}) |
| 275 |
}); |
| 276 |
|
| 277 |
let outcome_json = serde_json::to_string(&outcome) |
| 278 |
.unwrap_or_else(|e| format!("{{\"_serialize_error\":{e:?}}}")); |
| 279 |
sqlx::query( |
| 280 |
"UPDATE gate_runs |
| 281 |
SET finished_at = ?, status = ?, outcome_json = ?, log_ref = ? |
| 282 |
WHERE id = ?", |
| 283 |
) |
| 284 |
.bind(Utc::now().to_rfc3339()) |
| 285 |
.bind(outcome.status_str()) |
| 286 |
.bind(&outcome_json) |
| 287 |
.bind(outcome.log_ref.as_ref().map(super::outcome::LogRef::as_str)) |
| 288 |
.bind(id) |
| 289 |
.execute(&ctx.pool) |
| 290 |
.await?; |
| 291 |
|
| 292 |
tracing::info!( |
| 293 |
tier = %ctx.tier, version = %ctx.version, gate = %kind, |
| 294 |
status = outcome.status_str(), "gate done", |
| 295 |
); |
| 296 |
events::emit( |
| 297 |
&ctx.events, |
| 298 |
Event::GateDone { |
| 299 |
run_id, |
| 300 |
tier: ctx.tier.clone(), |
| 301 |
version: ctx.version.clone(), |
| 302 |
gate: kind, |
| 303 |
outcome: outcome.clone(), |
| 304 |
}, |
| 305 |
); |
| 306 |
|
| 307 |
Ok(outcome) |
| 308 |
} |
| 309 |
|
| 310 |
|
| 311 |
|
| 312 |
|
| 313 |
|
| 314 |
|
| 315 |
|
| 316 |
|
| 317 |
|
| 318 |
|
| 319 |
pub async fn run_all(ctx: &GateCtx, gates: &[Gate]) -> Result<Vec<GateKind>> { |
| 320 |
let mut failed = Vec::new(); |
| 321 |
for g in gates { |
| 322 |
let o = run(ctx, g).await?; |
| 323 |
if !o.is_passed() { |
| 324 |
failed.push(g.kind()); |
| 325 |
} |
| 326 |
} |
| 327 |
Ok(failed) |
| 328 |
} |
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
pub async fn burn_in_satisfied( |
| 336 |
pool: &SqlitePool, |
| 337 |
app: &AppId, |
| 338 |
tier: &TierId, |
| 339 |
hours: u32, |
| 340 |
) -> Result<bool> { |
| 341 |
let started: Option<String> = |
| 342 |
sqlx::query_scalar("SELECT burn_in_started_at FROM tier_state WHERE app = ? AND tier = ?") |
| 343 |
.bind(app) |
| 344 |
.bind(tier) |
| 345 |
.fetch_optional(pool) |
| 346 |
.await? |
| 347 |
.flatten(); |
| 348 |
let Some(started) = started else { |
| 349 |
return Ok(false); |
| 350 |
}; |
| 351 |
let started = chrono::DateTime::parse_from_rfc3339(&started)?.with_timezone(&Utc); |
| 352 |
Ok(Utc::now() - started >= chrono::Duration::hours(hours as i64)) |
| 353 |
} |
| 354 |
|
| 355 |
async fn burn_in(ctx: &GateCtx, hours: u32) -> Result<GateOutcome> { |
| 356 |
|
| 357 |
|
| 358 |
|
| 359 |
let started: Option<String> = |
| 360 |
sqlx::query_scalar("SELECT burn_in_started_at FROM tier_state WHERE app = ? AND tier = ?") |
| 361 |
.bind(&ctx.cfg.id) |
| 362 |
.bind(&ctx.tier) |
| 363 |
.fetch_optional(&ctx.pool) |
| 364 |
.await? |
| 365 |
.flatten(); |
| 366 |
let Some(started) = started else { |
| 367 |
return Ok(GateOutcome::blocked(GateBlocker::BurnInClockNotStarted)); |
| 368 |
}; |
| 369 |
let started = chrono::DateTime::parse_from_rfc3339(&started)?.with_timezone(&Utc); |
| 370 |
let elapsed = Utc::now() - started; |
| 371 |
let needed = chrono::Duration::hours(hours as i64); |
| 372 |
if elapsed >= needed { |
| 373 |
Ok(GateOutcome::passed(PassNote::BurnInElapsed { |
| 374 |
hours: elapsed.num_hours() as u32, |
| 375 |
})) |
| 376 |
} else { |
| 377 |
let remaining = (needed - elapsed).num_hours().max(0) as u32; |
| 378 |
Ok(GateOutcome::blocked(GateBlocker::BurnInRemaining { |
| 379 |
hours_remaining: remaining, |
| 380 |
hours_total: hours, |
| 381 |
})) |
| 382 |
} |
| 383 |
} |
| 384 |
|
| 385 |
async fn manual_confirm(ctx: &GateCtx) -> Result<GateOutcome> { |
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
let prior_at: Option<String> = sqlx::query_scalar( |
| 391 |
"SELECT finished_at FROM gate_runs |
| 392 |
WHERE app = ? AND tier = ? AND version = ? AND gate_kind = 'manual_confirm' |
| 393 |
AND status = 'passed' |
| 394 |
ORDER BY id DESC LIMIT 1", |
| 395 |
) |
| 396 |
.bind(&ctx.cfg.id) |
| 397 |
.bind(&ctx.tier) |
| 398 |
.bind(&ctx.version) |
| 399 |
.fetch_optional(&ctx.pool) |
| 400 |
.await?; |
| 401 |
match prior_at { |
| 402 |
Some(at_str) => { |
| 403 |
let at = chrono::DateTime::parse_from_rfc3339(&at_str) |
| 404 |
.map_or_else(|_| Utc::now(), |d| d.with_timezone(&Utc)); |
| 405 |
Ok(GateOutcome::passed(PassNote::OperatorConfirmed { at })) |
| 406 |
} |
| 407 |
None => Ok(GateOutcome::blocked( |
| 408 |
GateBlocker::AwaitingOperatorConfirmation, |
| 409 |
)), |
| 410 |
} |
| 411 |
} |
| 412 |
|
| 413 |
#[cfg(test)] |
| 414 |
mod tests { |
| 415 |
use super::*; |
| 416 |
use crate::gates::testkit::{aux_target, resolving_ctx, target}; |
| 417 |
use sqlx::sqlite::SqlitePoolOptions; |
| 418 |
|
| 419 |
#[tokio::test] |
| 420 |
async fn a_plain_target_resolves_under_the_worktree() { |
| 421 |
let ctx = resolving_ctx("/w/abc123", &[]); |
| 422 |
assert_eq!( |
| 423 |
ctx.target_dir(&target("shared/tagtree")), |
| 424 |
Some(PathBuf::from("/w/abc123/shared/tagtree")), |
| 425 |
); |
| 426 |
} |
| 427 |
|
| 428 |
#[tokio::test] |
| 429 |
async fn an_aux_target_resolves_beside_the_worktree_not_under_it() { |
| 430 |
|
| 431 |
|
| 432 |
let ctx = resolving_ctx("/w/abc123", &[("docengine", "/w/Libraries/docengine")]); |
| 433 |
assert_eq!( |
| 434 |
ctx.target_dir(&aux_target("", "docengine")), |
| 435 |
Some(PathBuf::from("/w/Libraries/docengine")), |
| 436 |
); |
| 437 |
|
| 438 |
assert_eq!( |
| 439 |
ctx.target_dir(&aux_target("crates/inner", "docengine")), |
| 440 |
Some(PathBuf::from("/w/Libraries/docengine/crates/inner")), |
| 441 |
); |
| 442 |
} |
| 443 |
|
| 444 |
#[tokio::test] |
| 445 |
async fn an_aux_target_with_no_checkout_this_run_resolves_to_nothing() { |
| 446 |
|
| 447 |
|
| 448 |
|
| 449 |
|
| 450 |
let ctx = resolving_ctx("/w/abc123", &[]); |
| 451 |
assert_eq!(ctx.target_dir(&aux_target("", "docengine")), None); |
| 452 |
} |
| 453 |
|
| 454 |
#[test] |
| 455 |
fn labels_name_the_repo_an_aux_target_lives_in() { |
| 456 |
assert_eq!(target("server").label(), "server"); |
| 457 |
assert_eq!(aux_target("", "docengine").label(), "docengine (aux)"); |
| 458 |
assert_eq!( |
| 459 |
aux_target("crates/inner", "docengine").label(), |
| 460 |
"docengine/crates/inner (aux)", |
| 461 |
); |
| 462 |
} |
| 463 |
|
| 464 |
#[test] |
| 465 |
fn every_gate_kind_round_trips_through_its_wire_string() { |
| 466 |
|
| 467 |
|
| 468 |
|
| 469 |
for k in [ |
| 470 |
GateKind::CargoTest, |
| 471 |
GateKind::HardeningTest, |
| 472 |
GateKind::Clippy, |
| 473 |
GateKind::Fmt, |
| 474 |
GateKind::CargoAudit, |
| 475 |
GateKind::CargoDeny, |
| 476 |
GateKind::MigrationDryRun, |
| 477 |
GateKind::CodeSmoke, |
| 478 |
GateKind::BootSmoke, |
| 479 |
GateKind::NodeHealth, |
| 480 |
GateKind::BurnIn, |
| 481 |
GateKind::ManualConfirm, |
| 482 |
] { |
| 483 |
assert_eq!( |
| 484 |
k.as_str().parse::<GateKind>().unwrap(), |
| 485 |
k, |
| 486 |
"round trip for {k:?}" |
| 487 |
); |
| 488 |
} |
| 489 |
} |
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
|
| 494 |
#[tokio::test] |
| 495 |
async fn burn_in_blocked_persists_typed_outcome() { |
| 496 |
let pool = SqlitePoolOptions::new() |
| 497 |
.max_connections(1) |
| 498 |
.connect("sqlite::memory:") |
| 499 |
.await |
| 500 |
.unwrap(); |
| 501 |
crate::db::migrate(&pool).await.unwrap(); |
| 502 |
|
| 503 |
sqlx::query("INSERT INTO tiers (name, ord, provisioned, canary) VALUES ('host', 0, 0, 'sequential')") |
| 504 |
.execute(&pool).await.unwrap(); |
| 505 |
sqlx::query("INSERT INTO tier_state (tier) VALUES ('host')") |
| 506 |
.execute(&pool) |
| 507 |
.await |
| 508 |
.unwrap(); |
| 509 |
|
| 510 |
sqlx::query("INSERT INTO versions (version, git_sha, built_at, artifact_path) VALUES ('0.1.0', 'abc1234', '2026-01-01T00:00:00Z', '/tmp/x')") |
| 511 |
.execute(&pool).await.unwrap(); |
| 512 |
|
| 513 |
let cfg = std::sync::Arc::new(crate::config::AppConfig::for_tests()); |
| 514 |
let ctx = GateCtx { |
| 515 |
public_url: None, |
| 516 |
pool: pool.clone(), |
| 517 |
cfg, |
| 518 |
tier: TierId::new("host"), |
| 519 |
version: "0.1.0".parse().unwrap(), |
| 520 |
worktree: Some(std::path::PathBuf::from("/tmp/unused")), |
| 521 |
bundle: None, |
| 522 |
events: events::channel(), |
| 523 |
nodes: Vec::new(), |
| 524 |
build_id: None, |
| 525 |
aux_dirs: HashMap::new(), |
| 526 |
}; |
| 527 |
let out = run(&ctx, &Gate::BurnIn { hours: 24 }).await.unwrap(); |
| 528 |
assert_eq!(out.status_str(), "blocked"); |
| 529 |
assert!(!out.is_passed()); |
| 530 |
|
| 531 |
|
| 532 |
let row: (Option<String>, Option<String>) = |
| 533 |
sqlx::query_as("SELECT status, outcome_json FROM gate_runs ORDER BY id DESC LIMIT 1") |
| 534 |
.fetch_one(&pool) |
| 535 |
.await |
| 536 |
.unwrap(); |
| 537 |
assert_eq!(row.0.as_deref(), Some("blocked"), "typed status"); |
| 538 |
let json: serde_json::Value = serde_json::from_str(row.1.as_deref().unwrap()).unwrap(); |
| 539 |
assert_eq!(json["status"]["kind"], "blocked"); |
| 540 |
assert_eq!( |
| 541 |
json["status"]["blocker"]["kind"], |
| 542 |
"burn_in_clock_not_started" |
| 543 |
); |
| 544 |
} |
| 545 |
} |
| 546 |
|