diff --git a/pkgs/fleet/Cargo.lock b/pkgs/fleet/Cargo.lock index 4b08b320a6..aad02f940c 100644 --- a/pkgs/fleet/Cargo.lock +++ b/pkgs/fleet/Cargo.lock @@ -244,6 +244,7 @@ version = "0.1.0" dependencies = [ "fleet-config", "fleet-dispatch", + "fleet-dispatch-test", "fleet-proxy", "fleet-proxy-proto", "fleet-queue", @@ -273,6 +274,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "fleet-dispatch-test" +version = "0.1.0" +dependencies = [ + "fleet-config", + "fleet-secrets", + "serde", + "serde_json", + "ureq", +] + [[package]] name = "fleet-proxy" version = "0.1.0" diff --git a/pkgs/fleet/Cargo.toml b/pkgs/fleet/Cargo.toml index 0efee1b94c..a5e3f5b3d0 100644 --- a/pkgs/fleet/Cargo.toml +++ b/pkgs/fleet/Cargo.toml @@ -19,6 +19,7 @@ members = [ "crates/fleet-proxy-proto", "crates/fleet-queue", "crates/fleet-dispatch", + "crates/fleet-dispatch-test", "crates/fleet-proxy", "crates/fleet-search", "crates/fleet", @@ -38,6 +39,7 @@ fleet-secrets = { path = "crates/fleet-secrets" } fleet-proxy-proto = { path = "crates/fleet-proxy-proto" } fleet-queue = { path = "crates/fleet-queue" } fleet-dispatch = { path = "crates/fleet-dispatch" } +fleet-dispatch-test = { path = "crates/fleet-dispatch-test" } fleet-proxy = { path = "crates/fleet-proxy" } fleet-search = { path = "crates/fleet-search" } serde = { version = "1", features = ["derive"] } diff --git a/pkgs/fleet/crates/fleet-config/src/lib.rs b/pkgs/fleet/crates/fleet-config/src/lib.rs index 400c0e0d8c..fb18015294 100644 --- a/pkgs/fleet/crates/fleet-config/src/lib.rs +++ b/pkgs/fleet/crates/fleet-config/src/lib.rs @@ -102,6 +102,31 @@ pub const PORT_DISPATCH: u16 = 4879; /// only. pub const DEFAULT_DISPATCH_TOKEN_NAME: &str = "pm-dispatch.api-token"; +/// The fleet-secrets name the dispatch-test domain resolves its +/// GitHub token by (design developing-today/code#6580). +pub const DEFAULT_DISPATCH_TEST_TOKEN_NAME: &str = "github.ghcr-classic-pat"; + +/// The fleet-secrets name the dispatch-test domain resolves its +/// Turso jobs-store token by. +pub const DEFAULT_DISPATCH_TEST_TURSO_TOKEN_NAME: &str = "turso.fleet-dispatch-jobs-token"; + +/// The Turso jobs store the dispatch-test domain records jobs in. +pub const DEFAULT_DISPATCH_TEST_TURSO_URL: &str = + "https://fleet-dispatch-jobs-dezren39.aws-us-east-1.turso.io"; + +/// The default Actions-capacity threshold for dispatch-test scope +/// selection: a scope is eligible below this many active jobs. +pub const DEFAULT_DISPATCH_TEST_THRESHOLD: u64 = 40; + +/// The default dispatch-test scope repos, in selection order. +pub const DEFAULT_DISPATCH_TEST_SCOPES: &[&str] = &[ + "developing-today/code", + "developing-today-forks/opencode", + "developing-today-forks/openchamber", + "dezren39/darwin-nix", + "dezren39/hatch", +]; + #[derive(Debug, Clone, Default, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct Config { @@ -110,6 +135,8 @@ pub struct Config { pub proxy: ProxyConfig, pub secrets: SecretsConfig, pub dispatch: DispatchConfig, + #[serde(rename = "dispatch-test")] + pub dispatch_test: DispatchTestConfig, pub search: SearchConfig, } @@ -191,6 +218,31 @@ pub struct DispatchConfig { pub port: Option, } +/// `[dispatch-test]` — the dispatch-test domain's view +/// (developing-today/code#6580). All optional: the defaults name +/// the live GitHub token, the Turso jobs store, and the scope +/// repos used for capacity-based selection. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct DispatchTestConfig { + /// The fleet-secrets name the GitHub token resolves by + /// (default [`DEFAULT_DISPATCH_TEST_TOKEN_NAME`]). + pub token_name: Option, + /// The fleet-secrets name the Turso token resolves by + /// (default [`DEFAULT_DISPATCH_TEST_TURSO_TOKEN_NAME`]). + pub turso_token_name: Option, + /// The Turso database URL (default + /// [`DEFAULT_DISPATCH_TEST_TURSO_URL`]). + pub turso_url: Option, + /// Actions-capacity threshold (default + /// [`DEFAULT_DISPATCH_TEST_THRESHOLD`]). + pub threshold: Option, + /// Scope repos, in selection order. Empty means the built-in + /// list ([`DEFAULT_DISPATCH_TEST_SCOPES`]). + #[serde(default)] + pub scopes: Vec, +} + #[derive(Debug)] pub enum ConfigError { /// The config file exists but does not parse. Carries the path and @@ -511,6 +563,52 @@ impl Config { self.dispatch.port.unwrap_or(PORT_DISPATCH) } + /// The fleet-secrets name the dispatch-test GitHub token + /// resolves by. + pub fn dispatch_test_token_name(&self) -> &str { + self.dispatch_test + .token_name + .as_deref() + .unwrap_or(DEFAULT_DISPATCH_TEST_TOKEN_NAME) + } + + /// The fleet-secrets name the dispatch-test Turso token + /// resolves by. + pub fn dispatch_test_turso_token_name(&self) -> &str { + self.dispatch_test + .turso_token_name + .as_deref() + .unwrap_or(DEFAULT_DISPATCH_TEST_TURSO_TOKEN_NAME) + } + + /// The dispatch-test Turso jobs-store URL. + pub fn dispatch_test_turso_url(&self) -> &str { + self.dispatch_test + .turso_url + .as_deref() + .unwrap_or(DEFAULT_DISPATCH_TEST_TURSO_URL) + } + + /// The dispatch-test Actions-capacity threshold. + pub fn dispatch_test_threshold(&self) -> u64 { + self.dispatch_test + .threshold + .unwrap_or(DEFAULT_DISPATCH_TEST_THRESHOLD) + } + + /// The dispatch-test scope repos, in selection order: the + /// configured list, or the built-in defaults when unset/empty. + pub fn dispatch_test_scopes(&self) -> Vec { + if self.dispatch_test.scopes.is_empty() { + DEFAULT_DISPATCH_TEST_SCOPES + .iter() + .map(|s| s.to_string()) + .collect() + } else { + self.dispatch_test.scopes.clone() + } + } + /// The search domain's routing preference from `[search] via` /// ("service" | "standalone"), when configured. pub fn search_via(&self) -> Option { diff --git a/pkgs/fleet/crates/fleet-dispatch-test/Cargo.toml b/pkgs/fleet/crates/fleet-dispatch-test/Cargo.toml new file mode 100644 index 0000000000..ccd24a2d94 --- /dev/null +++ b/pkgs/fleet/crates/fleet-dispatch-test/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "fleet-dispatch-test" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "The fleet dispatch-test domain: explicit-dispatch CI test — scan fleet repos for free GitHub Actions capacity, submit a job to the Turso-backed jobs store, dispatch the pilot workflow, and track the job's stored status." + +[dependencies] +fleet-config = { workspace = true } +fleet-secrets = { workspace = true } +serde = { workspace = true } +# preserve_order, as in fleet-dispatch: stored-row JSON key order is +# the schema's column order, part of the output shape agents consume. +serde_json = { version = "1", features = ["preserve_order"] } +# Same pin as fleet-search / fleet-queue. +ureq = { version = "3", features = ["rustls", "json"] } diff --git a/pkgs/fleet/crates/fleet-dispatch-test/src/lib.rs b/pkgs/fleet/crates/fleet-dispatch-test/src/lib.rs new file mode 100644 index 0000000000..cd860da9e2 --- /dev/null +++ b/pkgs/fleet/crates/fleet-dispatch-test/src/lib.rs @@ -0,0 +1,1114 @@ +//! fleet-dispatch-test — the dispatch-test domain of the fleet +//! multicall binary (design: developing-today/code#6580). +//! +//! An explicit-dispatch CI test surface over GitHub Actions: +//! +//! fleet dispatch-test scan count active Actions jobs in each +//! scope repo and name the first one +//! with free capacity + the pilot +//! workflow present +//! fleet dispatch-test submit store a job row in the Turso jobs +//! store, then dispatch the pilot +//! workflow (fleet-dispatch-test.yml) +//! in the chosen repo with the job id +//! fleet dispatch-test status print one stored job row as JSON +//! +//! Nothing here is trigger-driven: every verb runs only when a +//! caller invokes it, and `submit` dispatches a workflow_dispatch +//! run explicitly. No Actions triggers are enabled by this crate. +//! +//! Capacity counting (scan): for each scope repo, ACTIVE JOBS = +//! (jobs with status in_progress or queued across all in_progress +//! runs) + (queued runs, counted as 1 active unit each). Queued +//! runs have not started and expose no jobs yet, so the queued-run +//! term is an approximation: a queued run counts once no matter how +//! many jobs it will eventually fan out to. +//! +//! Auth: both tokens resolve **by name** through fleet-secrets — +//! the GitHub token (`[dispatch-test] token_name`, default +//! `github.ghcr-classic-pat`) and the Turso token +//! (`[dispatch-test] turso_token_name`, default +//! `turso.fleet-dispatch-jobs-token`). Values enter exactly one +//! Authorization header per request; they are never printed, +//! logged, or stored. +//! +//! Exit codes follow the workspace conventions: 0 ok · 2 usage · +//! 3 transport down / credentials unresolved or no eligible scope · +//! 4 an HTTP error status from GitHub or Turso (including an +//! unknown job id on `status`). + +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use fleet_config::Config; +use fleet_secrets::{Resolver, SecretValue}; +use serde_json::{Map, Value, json}; + +const EXIT_OK: i32 = 0; +const EXIT_USAGE: i32 = 2; +const EXIT_TRANSPORT: i32 = 3; +const EXIT_HTTP: i32 = 4; + +const GITHUB_API_BASE: &str = "https://api.github.com"; +const WORKFLOW_FILE: &str = "fleet-dispatch-test.yml"; +const DEFAULT_SCRIPT: &str = + "set -eux; echo dispatch-test smoke; uname -a; git rev-parse HEAD || true"; + +// --------------------------------------------------------------------------- +// Errors +// --------------------------------------------------------------------------- + +#[derive(Debug)] +enum DtError { + Usage(String), + Transport(String), + Http { status: u16, message: String }, +} + +impl DtError { + fn exit_code(&self) -> i32 { + match self { + DtError::Usage(_) => EXIT_USAGE, + DtError::Transport(_) => EXIT_TRANSPORT, + DtError::Http { .. } => EXIT_HTTP, + } + } + fn message(&self) -> String { + match self { + DtError::Usage(m) | DtError::Transport(m) => m.clone(), + DtError::Http { status, message } => format!("HTTP {status}: {message}"), + } + } +} + +type Result = std::result::Result; + +fn usage(msg: impl Into) -> DtError { + DtError::Usage(msg.into()) +} + +fn transport_err(msg: impl Into) -> DtError { + DtError::Transport(msg.into()) +} + +fn http_err(status: u16, message: impl Into) -> DtError { + DtError::Http { + status, + message: message.into(), + } +} + +// --------------------------------------------------------------------------- +// Time + job ids (pure) +// --------------------------------------------------------------------------- + +/// RFC3339 UTC for a unix-seconds timestamp, seconds precision +/// (e.g. `2026-11-06T17:00:00Z`). Hand-rolled: this crate carries no +/// date dependency. +fn rfc3339_utc(unix_secs: i64) -> String { + let days = unix_secs.div_euclid(86_400); + let secs = unix_secs.rem_euclid(86_400); + let (year, month, day) = civil_from_days(days); + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", + secs / 3600, + (secs % 3600) / 60, + secs % 60 + ) +} + +/// Howard Hinnant's civil-from-days algorithm. +fn civil_from_days(z: i64) -> (i64, u32, u32) { + let z = z + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = (z - era * 146_097) as u64; // [0, 146096] + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399] + let y = yoe as i64 + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365] + let mp = (5 * doy + 2) / 153; // [0, 11] + let d = (doy - (153 * mp + 2) / 5 + 1) as u32; // [1, 31] + let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; // [1, 12] + (if m <= 2 { y + 1 } else { y }, m, d) +} + +fn now_unix_secs() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} + +fn now_rfc3339() -> String { + rfc3339_utc(now_unix_secs()) +} + +fn base36(mut n: u128) -> String { + if n == 0 { + return "0".to_string(); + } + let digits = b"0123456789abcdefghijklmnopqrstuvwxyz"; + let mut out = Vec::new(); + while n > 0 { + out.push(digits[(n % 36) as usize]); + n /= 36; + } + out.reverse(); + String::from_utf8(out).unwrap_or_default() +} + +/// 4 hex chars from /dev/urandom (2 bytes, read_exact — urandom +/// never EOFs, so an unbounded read would never return). +fn random_hex4() -> Result { + use std::io::Read; + let mut b = [0u8; 2]; + std::fs::File::open("/dev/urandom") + .and_then(|mut f| f.read_exact(&mut b)) + .map_err(|e| transport_err(format!("cannot read /dev/urandom: {e}")))?; + Ok(format!("{:02x}{:02x}", b[0], b[1])) +} + +/// Job id shape: `dt--<4 hex chars>`. +fn job_id_at(unix_millis: u128, hex4: &str) -> String { + format!("dt-{}-{}", base36(unix_millis), hex4) +} + +fn generate_job_id() -> Result { + let millis = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0); + Ok(job_id_at(millis, &random_hex4()?)) +} + +// --------------------------------------------------------------------------- +// Arg parsing (fleet-dispatch's workspace-style minimal parser) +// --------------------------------------------------------------------------- + +struct Args { + values: Map, + flags: Map, +} + +fn parse_args(args: &[String], value_flags: &[&str], bool_flags: &[&str]) -> Result { + let mut values = Map::new(); + let mut flags = Map::new(); + let mut i = 0; + while i < args.len() { + let arg = &args[i]; + let Some(long) = arg.strip_prefix("--") else { + return Err(usage(format!("unexpected argument {arg:?}"))); + }; + let (name, inline) = match long.split_once('=') { + Some((n, v)) => (n, Some(v.to_string())), + None => (long, None), + }; + if bool_flags.contains(&name) { + if inline.is_some() { + return Err(usage(format!("--{name} takes no value"))); + } + flags.insert(name.to_string(), Value::Bool(true)); + } else if value_flags.contains(&name) { + let value = match inline { + Some(v) => v, + None => { + i += 1; + args.get(i) + .cloned() + .ok_or_else(|| usage(format!("--{name} needs a value")))? + } + }; + values.insert(name.to_string(), Value::String(value)); + } else { + return Err(usage(format!("unknown option --{name}"))); + } + i += 1; + } + Ok(Args { values, flags }) +} + +impl Args { + fn get(&self, name: &str) -> Option<&str> { + self.values.get(name).and_then(|v| v.as_str()) + } + fn flag(&self, name: &str) -> bool { + self.flags + .get(name) + .and_then(|v| v.as_bool()) + .unwrap_or(false) + } +} + +fn parse_threshold(raw: Option<&str>, config: &Config) -> Result { + match raw { + None => Ok(config.dispatch_test_threshold()), + Some(v) => v.parse::().map_err(|_| { + usage(format!( + "--threshold must be a non-negative integer, got {v:?}" + )) + }), + } +} + +// --------------------------------------------------------------------------- +// Secrets (by name, through fleet-secrets — the one path) +// --------------------------------------------------------------------------- + +fn resolve_named(config: &Config, name: &str) -> Result { + Resolver::default_chain(config) + .resolve(name) + .map_err(|e| transport_err(e.to_string())) +} + +fn agent() -> ureq::Agent { + ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_secs(60))) + .timeout_connect(Some(Duration::from_secs(10))) + .http_status_as_error(false) + .build() + .into() +} + +// --------------------------------------------------------------------------- +// GitHub API +// --------------------------------------------------------------------------- + +struct Github { + token: String, + agent: ureq::Agent, +} + +impl Github { + fn new(config: &Config) -> Result { + let token = resolve_named(config, config.dispatch_test_token_name())?; + Ok(Github { + token: token.expose().to_string(), + agent: agent(), + }) + } + + /// One GitHub exchange. 2xx returns the parsed body (empty body + /// → Null, e.g. the 204 from a workflow dispatch); any other + /// status is an Http error carrying GitHub's `message` field. + fn exchange(&self, method: &str, path: &str, body: Option<&Value>) -> Result { + let url = format!("{GITHUB_API_BASE}{path}"); + let auth = format!("Bearer {}", self.token); + let mut resp = match method { + "GET" => self + .agent + .get(&url) + .header("Authorization", &auth) + .header("Accept", "application/vnd.github+json") + .header("X-GitHub-Api-Version", "2022-11-28") + .header("User-Agent", "fleet-dispatch-test") + .call() + .map_err(|e| transport_err(format!("GitHub API unreachable: {e}")))?, + _ => self + .agent + .post(&url) + .header("Authorization", &auth) + .header("Accept", "application/vnd.github+json") + .header("X-GitHub-Api-Version", "2022-11-28") + .header("User-Agent", "fleet-dispatch-test") + .header("Content-Type", "application/json") + .send( + serde_json::to_string(body.unwrap_or(&Value::Null)) + .unwrap_or_default() + .as_str(), + ) + .map_err(|e| transport_err(format!("GitHub API unreachable: {e}")))?, + }; + let status = resp.status().as_u16(); + let text = resp + .body_mut() + .read_to_string() + .map_err(|e| transport_err(format!("cannot read GitHub response: {e}")))?; + if (200..300).contains(&status) { + if text.trim().is_empty() { + return Ok(Value::Null); + } + return serde_json::from_str(&text) + .map_err(|e| transport_err(format!("GitHub answered a non-JSON body: {e}"))); + } + let message = serde_json::from_str::(&text) + .ok() + .and_then(|v| { + v.get("message") + .and_then(|m| m.as_str()) + .map(str::to_string) + }) + .unwrap_or_else(|| { + let snippet: String = text.chars().take(300).collect(); + if snippet.is_empty() { + "no message".to_string() + } else { + snippet + } + }); + Err(http_err(status, format!("GitHub API: {message}"))) + } + + fn get(&self, path: &str) -> Result { + self.exchange("GET", path, None) + } + + fn post(&self, path: &str, body: &Value) -> Result { + self.exchange("POST", path, Some(body)) + } +} + +// --------------------------------------------------------------------------- +// Scan (pure counting over GitHub response shapes, then the live walk) +// --------------------------------------------------------------------------- + +/// Run ids from a `GET .../actions/runs` body. +fn run_ids(runs_body: &Value) -> Vec { + runs_body + .get("workflow_runs") + .and_then(|v| v.as_array()) + .map(|runs| { + runs.iter() + .filter_map(|r| r.get("id").and_then(|id| id.as_u64())) + .collect() + }) + .unwrap_or_default() +} + +/// `total_count` from a list body (0 when absent/malformed). +fn total_count(body: &Value) -> u64 { + body.get("total_count") + .and_then(|v| v.as_u64()) + .unwrap_or(0) +} + +/// Jobs in a `GET .../runs/{id}/jobs` body that occupy capacity: +/// status `in_progress` or `queued`. +fn count_active_jobs(jobs_body: &Value) -> u64 { + jobs_body + .get("jobs") + .and_then(|v| v.as_array()) + .map(|jobs| { + jobs.iter() + .filter(|j| { + matches!( + j.get("status").and_then(|s| s.as_str()), + Some("in_progress") | Some("queued") + ) + }) + .count() as u64 + }) + .unwrap_or(0) +} + +/// Whether the workflows list names an active workflow whose path +/// ends with the pilot workflow file. +fn workflow_present(workflows_body: &Value) -> bool { + workflows_body + .get("workflows") + .and_then(|v| v.as_array()) + .map(|wfs| { + wfs.iter().any(|w| { + let active = w + .get("state") + .and_then(|s| s.as_str()) + .map(|s| s == "active") + .unwrap_or(true); + let path_hit = w + .get("path") + .and_then(|p| p.as_str()) + .map(|p| p.ends_with(WORKFLOW_FILE)) + .unwrap_or(false); + active && path_hit + }) + }) + .unwrap_or(false) +} + +fn eligible(active: u64, threshold: u64, workflow: bool) -> bool { + workflow && active < threshold +} + +#[derive(Debug, Clone)] +struct RepoScan { + repo: String, + active: u64, + workflow: bool, +} + +impl RepoScan { + fn eligible(&self, threshold: u64) -> bool { + eligible(self.active, threshold, self.workflow) + } + fn to_json(&self, threshold: u64) -> Value { + json!({ + "repo": self.repo, + "active": self.active, + "workflow": self.workflow, + "eligible": self.eligible(threshold), + }) + } +} + +/// The live capacity walk for one repo (see crate docs for the +/// counting rule and the queued-run approximation). +fn scan_repo(github: &Github, repo: &str) -> Result { + let mut active: u64 = 0; + let in_progress = github.get(&format!( + "/repos/{repo}/actions/runs?status=in_progress&per_page=100" + ))?; + for run_id in run_ids(&in_progress) { + let jobs = github.get(&format!( + "/repos/{repo}/actions/runs/{run_id}/jobs?per_page=100" + ))?; + active += count_active_jobs(&jobs); + } + let queued = github.get(&format!( + "/repos/{repo}/actions/runs?status=queued&per_page=100" + ))?; + active += total_count(&queued); + let workflows = github.get(&format!("/repos/{repo}/actions/workflows?per_page=100"))?; + Ok(RepoScan { + repo: repo.to_string(), + active, + workflow: workflow_present(&workflows), + }) +} + +fn scan_scopes(github: &Github, scopes: &[String]) -> Result> { + scopes.iter().map(|r| scan_repo(github, r)).collect() +} + +fn choose(scans: &[RepoScan], threshold: u64) -> Option<&RepoScan> { + scans.iter().find(|s| s.eligible(threshold)) +} + +// --------------------------------------------------------------------------- +// Turso jobs store (HTTPS pipeline, hrana-over-HTTP v2 shape) +// --------------------------------------------------------------------------- + +// Integer args are part of the pipeline protocol (values encoded +// as JSON strings, #6580) and are exercised by the unit tests; the +// current verbs bind text/null only. +#[allow(dead_code)] +#[derive(Debug, Clone, PartialEq)] +enum TursoArg { + Text(String), + Integer(i64), + Null, +} + +impl TursoArg { + fn to_json(&self) -> Value { + match self { + TursoArg::Text(v) => json!({"type": "text", "value": v}), + TursoArg::Integer(v) => json!({"type": "integer", "value": v.to_string()}), + TursoArg::Null => json!({"type": "null"}), + } + } +} + +/// The pipeline request body for one execute + close. +fn pipeline_body(sql: &str, args: &[TursoArg]) -> Value { + json!({ + "requests": [ + { + "type": "execute", + "stmt": { + "sql": sql, + "args": args.iter().map(|a| a.to_json()).collect::>(), + } + }, + {"type": "close"} + ] + }) +} + +/// One Turso result set: column names + rows of typed cells already +/// converted to JSON values. +#[derive(Debug)] +struct TursoRows { + cols: Vec, + rows: Vec>, +} + +fn cell_to_json(cell: &Value) -> Value { + let ty = cell.get("type").and_then(|t| t.as_str()).unwrap_or("null"); + let raw = cell.get("value"); + match ty { + "text" => raw + .and_then(|v| v.as_str()) + .map(|s| Value::String(s.to_string())) + .unwrap_or(Value::Null), + "integer" => raw + .and_then(|v| v.as_str()) + .and_then(|s| s.parse::().ok()) + .map(|n| json!(n)) + .unwrap_or(Value::Null), + "float" => raw + .and_then(|v| v.as_str()) + .and_then(|s| s.parse::().ok()) + .and_then(|n| serde_json::Number::from_f64(n)) + .map(Value::Number) + .unwrap_or(Value::Null), + "blob" => raw.cloned().unwrap_or(Value::Null), + _ => Value::Null, + } +} + +/// Pull the first execute result out of a pipeline response body. +/// +/// Failure shapes (proven live, #6580): a request-level failure is +/// a top-level `{"error": ...}` with no usable results at all, and +/// a per-request failure is `results[i].type == "error"`. Only +/// `results[i].type == "ok"` carries a result set — anything else +/// is a transport-class failure, never an empty result. +fn parse_pipeline_rows(body: &Value) -> Result { + if let Some(err) = body.get("error") { + let msg = match err { + Value::String(s) => s.clone(), + other => other + .get("message") + .and_then(|m| m.as_str()) + .map(str::to_string) + .unwrap_or_else(|| other.to_string()), + }; + return Err(transport_err(format!("Turso pipeline error: {msg}"))); + } + let first = body + .get("results") + .and_then(|r| r.as_array()) + .and_then(|a| a.first()) + .ok_or_else(|| transport_err("Turso pipeline response has no results"))?; + if first.get("type").and_then(|t| t.as_str()) != Some("ok") { + let msg = first + .get("error") + .and_then(|e| match e { + Value::String(s) => Some(s.clone()), + other => other + .get("message") + .and_then(|m| m.as_str()) + .map(str::to_string), + }) + .unwrap_or_else(|| "unknown Turso error".to_string()); + return Err(transport_err(format!("Turso pipeline error: {msg}"))); + } + let result = first + .get("response") + .and_then(|r| r.get("result")) + .ok_or_else(|| transport_err("Turso pipeline response has no result"))?; + let cols = result + .get("cols") + .and_then(|c| c.as_array()) + .map(|cols| { + cols.iter() + .map(|c| { + c.get("name") + .and_then(|n| n.as_str()) + .unwrap_or("") + .to_string() + }) + .collect() + }) + .unwrap_or_default(); + let rows = result + .get("rows") + .and_then(|r| r.as_array()) + .map(|rows| { + rows.iter() + .map(|row| { + row.as_array() + .map(|cells| cells.iter().map(cell_to_json).collect()) + .unwrap_or_default() + }) + .collect() + }) + .unwrap_or_default(); + Ok(TursoRows { cols, rows }) +} + +struct Turso { + url: String, + token: String, + agent: ureq::Agent, +} + +impl Turso { + fn new(config: &Config) -> Result { + let token = resolve_named(config, config.dispatch_test_turso_token_name())?; + Ok(Turso { + url: config + .dispatch_test_turso_url() + .trim_end_matches('/') + .to_string(), + token: token.expose().to_string(), + agent: agent(), + }) + } + + fn execute(&self, sql: &str, args: &[TursoArg]) -> Result { + let url = format!("{}/v2/pipeline", self.url); + let auth = format!("Bearer {}", self.token); + let body = pipeline_body(sql, args); + let mut resp = self + .agent + .post(&url) + .header("Authorization", &auth) + .header("Content-Type", "application/json") + .send(serde_json::to_string(&body).unwrap_or_default().as_str()) + .map_err(|e| transport_err(format!("Turso store unreachable: {e}")))?; + let status = resp.status().as_u16(); + let text = resp + .body_mut() + .read_to_string() + .map_err(|e| transport_err(format!("cannot read Turso response: {e}")))?; + if !(200..300).contains(&status) { + let snippet: String = text.chars().take(300).collect(); + return Err(http_err(status, format!("Turso store: {snippet}"))); + } + let parsed: Value = serde_json::from_str(&text) + .map_err(|e| transport_err(format!("Turso answered a non-JSON body: {e}")))?; + parse_pipeline_rows(&parsed) + } +} + +// --------------------------------------------------------------------------- +// Verbs +// --------------------------------------------------------------------------- + +const SCAN_USAGE: &str = "\ +Usage: fleet dispatch-test scan [--threshold N] [--json] + +For each scope repo (config [dispatch-test] scopes, in order): +count ACTIVE JOBS via the GitHub API — jobs with status +in_progress or queued across in_progress runs, plus queued runs +counted as 1 active unit each (approximation: a queued run has +not started and exposes no jobs, so it counts once regardless of +its eventual fan-out). Also probe whether the pilot workflow +(fleet-dispatch-test.yml) is present and active. + +Prints one line per scope: + active= workflow= eligible= +and a final 'chosen: ' line — the first scope with +active < threshold (default 40) AND the workflow present. +--json prints the same facts as JSON."; + +fn verb_scan(config: &Config, args: &[String]) -> Result<()> { + if args.iter().any(|a| a == "--help" || a == "-h") { + println!("{SCAN_USAGE}"); + return Ok(()); + } + let parsed = parse_args(args, &["threshold"], &["json"])?; + let threshold = parse_threshold(parsed.get("threshold"), config)?; + let github = Github::new(config)?; + let scopes = config.dispatch_test_scopes(); + let scans = scan_scopes(&github, &scopes)?; + let chosen = choose(&scans, threshold).map(|s| s.repo.clone()); + if parsed.flag("json") { + let doc = json!({ + "threshold": threshold, + "scopes": scans.iter().map(|s| s.to_json(threshold)).collect::>(), + "chosen": chosen, + }); + println!( + "{}", + serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "null".to_string()) + ); + } else { + for s in &scans { + println!( + "{} active={} workflow={} eligible={}", + s.repo, + s.active, + if s.workflow { "yes" } else { "no" }, + if s.eligible(threshold) { "yes" } else { "no" } + ); + } + println!("chosen: {}", chosen.as_deref().unwrap_or("none")); + } + Ok(()) +} + +const SUBMIT_USAGE: &str = "\ +Usage: fleet dispatch-test submit [--threshold N] [--repo owner/name] + [--ref REF] [--name TEXT] + [--script TEXT | --script-file PATH] + +Store a job in the Turso jobs store (status queued), pick a scope +(--repo forces one; otherwise the scan rule: first scope with +active < threshold and the pilot workflow present), mark the row +dispatched, and dispatch fleet-dispatch-test.yml in that repo +with the job id as its only input. + + --threshold N capacity threshold (default: config, else 40) + --repo owner/name force this repo instead of scanning scopes + --ref REF checkout ref recorded on the job (default: + the string HEAD — the pilot's default checkout) + --name TEXT job name recorded on the row + --script TEXT the script the pilot runs for this job + --script-file PATH read the script from a file + (default script: a trivial smoke script) + +Prints JSON: {job_id, repo, active_at_scan, threshold, status}."; + +fn verb_submit(config: &Config, args: &[String]) -> Result { + if args.iter().any(|a| a == "--help" || a == "-h") { + println!("{SUBMIT_USAGE}"); + return Ok(Value::Null); + } + let parsed = parse_args( + args, + &["threshold", "repo", "ref", "name", "script", "script-file"], + &[], + )?; + if parsed.get("script").is_some() && parsed.get("script-file").is_some() { + return Err(usage("--script and --script-file are mutually exclusive")); + } + let threshold = parse_threshold(parsed.get("threshold"), config)?; + let script = match parsed.get("script-file") { + Some(path) => std::fs::read_to_string(path) + .map_err(|e| usage(format!("cannot read script file {path}: {e}")))?, + None => parsed + .get("script") + .map(str::to_string) + .unwrap_or_else(|| DEFAULT_SCRIPT.to_string()), + }; + let target_ref = parsed.get("ref").unwrap_or("HEAD").to_string(); + let name = parsed.get("name").map(str::to_string); + if let Some(repo) = parsed.get("repo") { + let parts: Vec<&str> = repo.split('/').collect(); + if parts.len() != 2 || parts.iter().any(|p| p.is_empty()) { + return Err(usage(format!("--repo must be owner/name, got {repo:?}"))); + } + } + + let github = Github::new(config)?; + let turso = Turso::new(config)?; + + // (a) job id, (b) INSERT as queued. + let id = generate_job_id()?; + let created = now_rfc3339(); + turso.execute( + "INSERT INTO jobs (id, created_at, name, target_repo, target_ref, script, status, \ + run_id, run_url, exit_code, output_tail, updated_at) \ + VALUES (?, ?, ?, NULL, ?, ?, 'queued', NULL, NULL, NULL, NULL, ?)", + &[ + TursoArg::Text(id.clone()), + TursoArg::Text(created.clone()), + name.map(TursoArg::Text).unwrap_or(TursoArg::Null), + TursoArg::Text(target_ref), + TursoArg::Text(script), + TursoArg::Text(created.clone()), + ], + )?; + + // (c) pick the scope. + let (repo, active_at_scan) = if let Some(forced) = parsed.get("repo") { + let scan = scan_repo(&github, forced)?; + (forced.to_string(), scan.active) + } else { + let scopes = config.dispatch_test_scopes(); + let scans = scan_scopes(&github, &scopes)?; + match choose(&scans, threshold) { + Some(s) => (s.repo.clone(), s.active), + None => { + return Err(transport_err(format!( + "no eligible scope: no scope repo has active < {threshold} with the \ + pilot workflow present (job {id} remains queued in the store)" + ))); + } + } + }; + + // (d) UPDATE the row: target repo + dispatched. + turso.execute( + "UPDATE jobs SET target_repo = ?, status = 'dispatched', updated_at = ? WHERE id = ?", + &[ + TursoArg::Text(repo.clone()), + TursoArg::Text(now_rfc3339()), + TursoArg::Text(id.clone()), + ], + )?; + + // (e) dispatch the pilot workflow at the repo's default branch. + let repo_body = github.get(&format!("/repos/{repo}"))?; + let default_branch = repo_body + .get("default_branch") + .and_then(|b| b.as_str()) + .ok_or_else(|| transport_err(format!("GitHub repo {repo} has no default_branch")))?; + github.post( + &format!("/repos/{repo}/actions/workflows/{WORKFLOW_FILE}/dispatches"), + &json!({ + "ref": default_branch, + "inputs": {"job_id": id}, + }), + )?; + + // (f) report. + Ok(json!({ + "job_id": id, + "repo": repo, + "active_at_scan": active_at_scan, + "threshold": threshold, + "status": "dispatched", + })) +} + +const STATUS_USAGE: &str = "\ +Usage: fleet dispatch-test status + +Print the stored jobs row for as pretty JSON (all +columns). An unknown id is an error (exit 4)."; + +fn verb_status(config: &Config, args: &[String]) -> Result { + if args.iter().any(|a| a == "--help" || a == "-h") { + println!("{STATUS_USAGE}"); + return Ok(Value::Null); + } + if args.len() != 1 { + return Err(usage(format!( + "status takes exactly one job id\n\n{STATUS_USAGE}" + ))); + } + let id = &args[0]; + let turso = Turso::new(config)?; + let result = turso.execute( + "SELECT id, created_at, name, target_repo, target_ref, script, status, \ + run_id, run_url, exit_code, output_tail, updated_at FROM jobs WHERE id = ?", + &[TursoArg::Text(id.clone())], + )?; + let row = result + .rows + .first() + .ok_or_else(|| http_err(404, format!("job {id} not found in the jobs store")))?; + let mut obj = Map::new(); + for (i, col) in result.cols.iter().enumerate() { + obj.insert(col.clone(), row.get(i).cloned().unwrap_or(Value::Null)); + } + Ok(Value::Object(obj)) +} + +// --------------------------------------------------------------------------- +// Entry point +// --------------------------------------------------------------------------- + +const USAGE: &str = "\ +Usage: fleet dispatch-test [args...] + +Explicit-dispatch CI test (developing-today/code#6580): scan +fleet repos for free GitHub Actions capacity, submit a job to +the Turso-backed jobs store and dispatch the pilot workflow, +then track the job's stored status. + + scan [--threshold N] [--json] capacity + workflow scan of the scope repos + submit [options] store a job and dispatch the pilot workflow + status print one stored job row as JSON + +Run 'fleet dispatch-test --help' for a verb's options. +Note: queued runs count as 1 active unit each in scan — a queued +run exposes no jobs yet, so that term is an approximation."; + +fn print_json(v: &Value) { + println!( + "{}", + serde_json::to_string_pretty(v).unwrap_or_else(|_| "null".to_string()) + ); +} + +/// The dispatch-test domain's entry point (the bin crate routes +/// here once the capability checks have passed). Mirrors +/// fleet-dispatch's run signature and exit-code conventions. +pub fn run(config: &Config, args: &[String]) -> i32 { + let verb = args.first().map(|s| s.as_str()); + let rest: &[String] = if args.is_empty() { &[][..] } else { &args[1..] }; + let result: Result> = match verb { + Some("scan") => verb_scan(config, rest).map(|_| None), + Some("submit") => verb_submit(config, rest).map(Some), + Some("status") => verb_status(config, rest).map(Some), + Some(other) => Err(usage(format!( + "unknown dispatch-test command {other:?}\n\n{USAGE}" + ))), + None => Err(usage(USAGE.to_string())), + }; + match result { + Ok(Some(Value::Null)) | Ok(None) => EXIT_OK, + Ok(Some(body)) => { + print_json(&body); + EXIT_OK + } + Err(e) => { + eprintln!("fleet dispatch-test: {}", e.message()); + e.exit_code() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_jobs() -> Value { + json!({ + "total_count": 4, + "jobs": [ + {"id": 1, "status": "in_progress"}, + {"id": 2, "status": "queued"}, + {"id": 3, "status": "completed"}, + {"id": 4, "status": "in_progress"} + ] + }) + } + + #[test] + fn active_jobs_count_only_running_and_queued() { + assert_eq!(count_active_jobs(&sample_jobs()), 3); + assert_eq!(count_active_jobs(&json!({"jobs": []})), 0); + assert_eq!(count_active_jobs(&json!({})), 0); + } + + #[test] + fn run_ids_and_total_count_parse() { + let body = json!({ + "total_count": 2, + "workflow_runs": [{"id": 111}, {"id": 222}, {"name": "no-id"}] + }); + assert_eq!(run_ids(&body), vec![111, 222]); + assert_eq!(total_count(&body), 2); + assert_eq!(total_count(&json!({})), 0); + } + + #[test] + fn workflow_presence_needs_active_and_path_suffix() { + let yes = json!({"workflows": [ + {"path": ".github/workflows/other.yml", "state": "active"}, + {"path": ".github/workflows/fleet-dispatch-test.yml", "state": "active"} + ]}); + assert!(workflow_present(&yes)); + let disabled = json!({"workflows": [ + {"path": ".github/workflows/fleet-dispatch-test.yml", "state": "disabled_manually"} + ]}); + assert!(!workflow_present(&disabled)); + assert!(!workflow_present(&json!({"workflows": []}))); + } + + #[test] + fn eligibility_is_threshold_and_workflow() { + assert!(eligible(39, 40, true)); + assert!(!eligible(40, 40, true)); + assert!(!eligible(0, 40, false)); + } + + #[test] + fn job_id_shape() { + let id = job_id_at(1_762_000_000_000, "0a9f"); + assert!(id.starts_with("dt-")); + assert!(id.ends_with("-0a9f")); + let mid = &id[3..id.len() - 5]; + assert!(!mid.is_empty()); + assert!( + mid.chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) + ); + let live = generate_job_id().unwrap(); + let suffix = live.rsplit('-').next().unwrap(); + assert_eq!(suffix.len(), 4); + assert!(suffix.chars().all(|c| c.is_ascii_hexdigit())); + } + + #[test] + fn rfc3339_known_instants() { + assert_eq!(rfc3339_utc(0), "1970-01-01T00:00:00Z"); + assert_eq!(rfc3339_utc(1_735_689_600), "2025-01-01T00:00:00Z"); + assert_eq!(rfc3339_utc(1_735_689_600 + 3661), "2025-01-01T01:01:01Z"); + } + + #[test] + fn pipeline_body_shape() { + let body = pipeline_body( + "INSERT INTO jobs (id, run_id) VALUES (?, ?)", + &[TursoArg::Text("dt-x".to_string()), TursoArg::Integer(42)], + ); + assert_eq!(body["requests"][0]["type"], "execute"); + assert_eq!( + body["requests"][0]["stmt"]["sql"], + "INSERT INTO jobs (id, run_id) VALUES (?, ?)" + ); + assert_eq!( + body["requests"][0]["stmt"]["args"][0], + json!({"type": "text", "value": "dt-x"}) + ); + assert_eq!( + body["requests"][0]["stmt"]["args"][1], + json!({"type": "integer", "value": "42"}) + ); + assert_eq!(body["requests"][1]["type"], "close"); + let null_body = pipeline_body("SELECT ?", &[TursoArg::Null]); + assert_eq!( + null_body["requests"][0]["stmt"]["args"][0], + json!({"type": "null"}) + ); + } + + #[test] + fn pipeline_rows_parse_typed_cells() { + let body = json!({ + "results": [{ + "type": "ok", + "response": { + "type": "execute", + "result": { + "cols": [{"name": "id"}, {"name": "run_id"}, {"name": "name"}], + "rows": [[ + {"type": "text", "value": "dt-abc"}, + {"type": "integer", "value": "123"}, + {"type": "null"} + ]] + } + } + }] + }); + let rows = parse_pipeline_rows(&body).unwrap(); + assert_eq!(rows.cols, vec!["id", "run_id", "name"]); + assert_eq!(rows.rows[0][0], json!("dt-abc")); + assert_eq!(rows.rows[0][1], json!(123)); + assert_eq!(rows.rows[0][2], Value::Null); + } + + #[test] + fn pipeline_error_shapes_are_failures_not_empty_rows() { + // Top-level error (the raw-integer-arg failure mode, #6580). + let top = json!({"error": "JSON parse error: invalid type: integer `42`, expected a borrowed string"}); + let err = parse_pipeline_rows(&top).unwrap_err(); + assert_eq!(err.exit_code(), EXIT_TRANSPORT); + assert!(err.message().contains("JSON parse error")); + // Per-request error result. + let per = json!({"results": [{ + "type": "error", + "error": {"message": "no such table: jobs", "code": "SQLITE_ERROR"} + }]}); + let err = parse_pipeline_rows(&per).unwrap_err(); + assert_eq!(err.exit_code(), EXIT_TRANSPORT); + assert!(err.message().contains("no such table")); + } + + #[test] + fn exit_code_conventions() { + assert_eq!(usage("x").exit_code(), 2); + assert_eq!(transport_err("x").exit_code(), 3); + assert_eq!(http_err(404, "x").exit_code(), 4); + } + + #[test] + fn help_needs_no_credentials() { + // Help returns before any token resolution, so these calls + // double as no-network pins. + let config = Config::default(); + assert_eq!( + run(&config, &["scan".to_string(), "--help".to_string()]), + EXIT_OK + ); + assert_eq!( + verb_status(&config, &["a".to_string(), "b".to_string()]) + .unwrap_err() + .exit_code(), + EXIT_USAGE + ); + } +} diff --git a/pkgs/fleet/crates/fleet-registry/src/lib.rs b/pkgs/fleet/crates/fleet-registry/src/lib.rs index d2af2efc0d..ca7222badf 100644 --- a/pkgs/fleet/crates/fleet-registry/src/lib.rs +++ b/pkgs/fleet/crates/fleet-registry/src/lib.rs @@ -43,6 +43,8 @@ pub enum Capability { SearchServe, /// `fleet dispatch …` — thin client over pm-stack dispatch. Dispatch, + /// `fleet dispatch-test …` — explicit-dispatch CI test surface. + DispatchTest, /// `fleet laptop-agent …` — client for the (Python) laptop-agent daemon. LaptopAgent, /// `fleet secrets …` — resolve secrets by name (step 6, #5554): @@ -63,6 +65,7 @@ impl Capability { Capability::Search => "search", Capability::SearchServe => "search-serve", Capability::Dispatch => "dispatch", + Capability::DispatchTest => "dispatch-test", Capability::LaptopAgent => "laptop-agent", Capability::Secrets => "secrets", } @@ -79,6 +82,7 @@ impl Capability { Capability::Search, Capability::SearchServe, Capability::Dispatch, + Capability::DispatchTest, Capability::LaptopAgent, Capability::Secrets, ]; @@ -249,6 +253,14 @@ pub const DOMAINS: &[Domain] = &[ aliases: &[], subcommands: &["status", "launch", "enqueue"], }, + Domain { + name: "dispatch-test", + summary: "Explicit-dispatch CI test: scan fleet repos for free Actions capacity, submit a job, track its stored status.", + capabilities: &[Capability::DispatchTest], + primary: Capability::DispatchTest, + aliases: &[], + subcommands: &["scan", "submit", "status"], + }, Domain { name: "secrets", summary: "Resolve secrets by name: the laptop secrets-broker first, Bitwarden as fallback.", diff --git a/pkgs/fleet/crates/fleet/Cargo.toml b/pkgs/fleet/crates/fleet/Cargo.toml index 13722c749f..30bb8eeef3 100644 --- a/pkgs/fleet/crates/fleet/Cargo.toml +++ b/pkgs/fleet/crates/fleet/Cargo.toml @@ -16,6 +16,7 @@ fleet-config = { workspace = true } fleet-proxy-proto = { workspace = true } fleet-queue = { workspace = true, optional = true } fleet-dispatch = { workspace = true, optional = true } +fleet-dispatch-test = { workspace = true, optional = true } fleet-search = { workspace = true, optional = true } # The proxy CLIENT is part of every variant's registry (the # connect capability ships in all three builds); only the broker @@ -46,6 +47,7 @@ full = [ "search", "search-serve", "dispatch", + "dispatch-test", "laptop-agent", "secrets", ] @@ -74,6 +76,7 @@ secrets-broker = [ search = ["dep:fleet-search"] search-serve = ["dep:fleet-secrets"] dispatch = ["dep:fleet-dispatch"] +dispatch-test = ["dep:fleet-dispatch-test"] # The secrets verb (step 6, #5554): in full and serve (§2 puts the # secrets platform in both), never in connect ("nothing else"). secrets = ["dep:fleet-secrets"] diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index 00409a0119..723b89e8c6 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -77,6 +77,9 @@ fn compiled_capabilities() -> CapabilitySet { if cfg!(feature = "dispatch") { caps.insert(Capability::Dispatch); } + if cfg!(feature = "dispatch-test") { + caps.insert(Capability::DispatchTest); + } if cfg!(feature = "laptop-agent") { caps.insert(Capability::LaptopAgent); } @@ -361,6 +364,7 @@ fn print_domain_help(surface: &Surface, d: &Domain) { CapState::Available => match d.name { "queue" => "included in this build", "dispatch" => "included in this build", + "dispatch-test" => "included in this build", "secrets" => "included in this build", "search" => "included in this build", "proxy" => "included in this build", @@ -496,6 +500,13 @@ fn run_domain(surface: &Surface, d: &Domain, args: &[String], invoked_as: &str) if d.name == "dispatch" { return fleet_dispatch::run(&surface.config, args); } + // The dispatch-test domain (developing-today/code#6580): + // explicit-dispatch CI test over GitHub Actions + the + // Turso jobs store (full build only). + #[cfg(feature = "dispatch-test")] + if d.name == "dispatch-test" { + return fleet_dispatch_test::run(&surface.config, args); + } // Step 6 (#5554): the secrets domain runs for real — // the fleet-secrets resolver chain as a verb. #[cfg(feature = "secrets")]