diff --git a/docs/json-api.md b/docs/json-api.md index 6154ada..e890ce0 100644 --- a/docs/json-api.md +++ b/docs/json-api.md @@ -1,20 +1,51 @@ # JSON output reference -Every command that prints data accepts a global `--json` flag. Machine -output always is a single JSON object on stdout, one line, ending in a -newline. +Use `--json` to read command results from a script. Put it before the scheduling +separator, for example `atx --json 30s -- echo hello`. Anything after `--` belongs +to the command being scheduled. + +Successful data commands print one compact JSON object to stdout, followed by a +newline. Command errors print an error envelope to stderr and leave stdout empty. +Warnings and other diagnostics also use stderr. Check the exit status before +reading stdout. See [the CLI guide](cli.md) for exit codes. + +`completions`, `--help`, and the built-in `--version` print text, not JSON. +Use the `version` subcommand for machine-readable version information. The optional +`man` command writes manual files rather than a JSON result. ## Envelope +Every success envelope has these fields: + +| Field | Type | Meaning | +| --- | --- | --- | +| `schema_version` | integer | JSON contract version, currently `1` | +| `ok` | boolean | `true` for a result, `false` for a command error | +| `data` | object or array | command-specific result, present only on success | + +Errors replace `data` with an `error` object: + +| Field | Type | Meaning | +| --- | --- | --- | +| `code` | string | stable error code, such as `JOB_NOT_FOUND` or `INVALID_ARGUMENT` | +| `message` | string | explanation for the user, not a value to match in scripts | +| `remediation` | string, optional | suggested next step; omitted when absent | + +Consumers must ignore unknown fields. Adding a field does not change +`schema_version`; removing a field or changing its meaning does. Fields marked +`null` below remain present when they have no value. Optional fields are omitted. + +### Version example + +`atx --json version` prints: + ```json -{ - "schema_version": 1, - "ok": true, - "data": { } -} +{"schema_version":1,"ok":true,"data":{"version":"0.1.1"}} ``` -Errors swap `data` for `error`: +### Error example + +With no saved database, `atx --json show nosuch` exits `3` and writes this to stderr: ```json { @@ -22,98 +53,263 @@ Errors swap `data` for `error`: "ok": false, "error": { "code": "JOB_NOT_FOUND", - "message": "no job matches prefix 'nosuch'", + "message": "job or run not found", "remediation": "Run `atx list` to inspect job IDs." } } ``` -- `schema_version` is `1` today. It increases when a field changes meaning - or is removed; additive new fields do not bump it. -- `remediation` is optional and may be added to any error at any time. -- Unknown fields must be ignored by consumers. -- Diagnostics and warnings always go to stderr; stdout carries only the - envelope. Exit codes are documented in the CLI guide. +The example is expanded for readability. The binary prints it on one line. ## Commands +All commands in this table accept `--json`. + | Command | `data` shape | | --- | --- | -| `list --json` | array of job objects | -| `show JOB --json` | one job object | -| `history [JOB] --json` | array of run objects | -| `output RUN --json` | run-output object | -| `ps --json` | array of process objects | +| scheduling, including `--dry-run` and `--every` | submission object | +| `list` | array of job objects | +| `show JOB` | job object | +| `cancel JOB` | job object after cancellation | +| `rm JOB` | removed job object | +| `run JOB` | job object prepared for another run | +| `history [JOB]` | array of run objects | +| `output RUN` | run-output object | +| `ps` | array of process objects | +| `doctor` | doctor report | +| `version` | object with a `version` string | +| `service status` | service-status object | +| `service install`, `service uninstall` | service-change object | -## Object shapes +Empty `list`, unfiltered `history`, and `ps` results are arrays, `[]`, including +when no database exists yet. `run` returns the prepared job, not a completed run. +Read `history` or `output` to learn how the command finished. -Job object (`list`, `show`): +## Shared values -| Field | Type | Notes | +Job and run IDs are 26-character lowercase Crockford Base32 strings derived from +UUIDv7, not hyphenated UUID strings. Their alphabet is +`0123456789abcdefghjkmnpqrstvwxyz`; the first character is between `0` and `7`. +They sort lexicographically in UUID order. For example, an ID looks like +`01m4n2rkfzedssxyfwgcag90fn`. CLI prefixes may use either case. + +Timestamps are RFC 3339 strings in UTC, ending in `Z`. They may contain fractional +seconds. Durations are strings, not counts of seconds. ATX formats them with +ordered `h`, `m`, and `s` components and omits zero components, such as `30s`, `2m`, +or `1h2m3s`. + +JSON enum values use snake case: + +- Job states are `scheduled`, `waiting`, `starting`, `running`, `cancel_requested`, + `succeeded`, `failed`, `cancelled`, `interrupted`, and `missed`. +- Run states are `starting`, `running`, `cancel_requested`, `succeeded`, `failed`, + `cancelled`, and `interrupted`. +- Runtime tiers are `session` and `durable`. +- Execution modes are `direct` and `shell`. + +These are JSON values. CLI option values may use different spelling, such as +`--missed run-latest`. The missed-deadline policy is not part of the job JSON object. + +## Submission object + +| Field | Type | Meaning | +| --- | --- | --- | +| `job_id` | string | full job ID | +| `state` | string | job state | +| `schedule` | object | schedule variant below | +| `next_due_utc` | string | next deadline in UTC | +| `runtime_tier` | string | `session` or `durable` | +| `supervised` | boolean | submission received supervision acknowledgement | +| `dry_run` | boolean | validated without saving or running the job | + +## Job object + +| Field | Type | Meaning | | --- | --- | --- | -| `job_id` | string | full UUID | -| `name` | string \| null | | -| `description` | string \| null | | -| `schedule` | object | one of `one_shot_relative`, `one_shot_absolute`, `recurring_interval` | -| `next_due_utc` | string | RFC 3339 UTC timestamp | -| `remaining_seconds` | integer | negative once due | -| `state` | string | see state names below | +| `job_id` | string | full job ID | +| `name` | string or null | optional display name | +| `description` | string or null | optional note | +| `schedule` | object | schedule variant below | +| `next_due_utc` | string | next deadline in UTC | +| `remaining_seconds` | integer | signed seconds until due, truncated toward zero | +| `state` | string | job state | +| `runtime_tier` | string | `session` or `durable` | +| `execution` | object | execution settings below | +| `active_run_id` | string or null | currently always null; use `ps` or `history` for runs | + +The last run's outcome is not part of the job object. Read it from `history` or +`output`. `remaining_seconds` can be zero just after the deadline and becomes +negative once the job is at least one second overdue. -| `runtime_tier` | string | `Session` or `Durable` | -| `execution` | object | see below | -| `active_run_id` | string \| null | | +### Execution object + +| Field | Type | Meaning | +| --- | --- | --- | +| `mode` | string | `direct` or `shell` | +| `argv` | array of strings | saved command arguments | +| `working_directory` | string | canonical absolute working directory | +| `environment_keys` | array of strings | saved environment keys, never their values | +| `shell_path` | string or null | shell executable in `shell` mode; null in `direct` mode | -The last run's outcome is not part of the job object; read it from -`history` or `output`. +### Schedule variants -Job states: `scheduled`, `waiting`, `starting`, `running`, -`cancel_requested`, `succeeded`, `failed`, `cancelled`, `interrupted`, -`missed`. +Each schedule has a `kind` string and the fields listed for that kind. -Execution object: +`one_shot_relative`: -| Field | Type | Notes | +| Field | Type | Meaning | | --- | --- | --- | -| `mode` | string | `Direct` or `Shell` | -| `argv` | array of strings | | -| `working_directory` | string | | -| `environment_keys` | array of strings | keys only, never values | -| `shell_path` | string \| null | `Shell` mode only | +| `duration` | string | canonical duration, such as `30s` | +| `persisted_due_utc` | string | saved UTC deadline | -Run object (`history`): +`one_shot_absolute`: -| Field | Type | Notes | +| Field | Type | Meaning | | --- | --- | --- | -| `run_id` | string | full UUID | -| `job_id` | string | | -| `sequence` | integer | per-job, starts at 1 | -| `scheduled_for_utc` | string | RFC 3339 UTC timestamp | -| `started_at_utc` | string \| null | | -| `finished_at_utc` | string \| null | | -| `state` | string | see run states below | -| `outcome` | string \| null | terminal runs only | +| `original_input` | string | submitted calendar expression | +| `timezone` | string | resolved timezone name, such as `UTC` or `Europe/London` | +| `timezone_database_version` | string | bundled timezone data version used to resolve the input | +| `resolved_due_utc` | string | resolved UTC deadline | +| `dst_resolution` | string | `reject`, `earlier`, or `later` | -Run states: `starting`, `running`, `cancel_requested`, `succeeded`, -`failed`, `cancelled`, `interrupted`. -| `stdout_path` / `stderr_path` | string \| null | paths under the state directory | +`recurring_interval`: -Run-output object (`output RUN --json`): +| Field | Type | Meaning | +| --- | --- | --- | +| `interval` | string | canonical duration, such as `2m` | +| `persisted_anchor_utc` | string | saved fixed-rate UTC anchor | + +## Run object -| Field | Type | Notes | +| Field | Type | Meaning | | --- | --- | --- | -| `run_id`, `job_id` | string | | -| `state` | string | | -| `outcome` | string \| null | | -| `stdout_truncated` / `stderr_truncated` | boolean | true once the capture cap cut the stream | -| `stdout` / `stderr` | string | captured bytes decoded as UTF-8; invalid sequences become U+FFFD | +| `run_id` | string | full run ID | +| `job_id` | string | full job ID | +| `sequence` | integer | positive per-job sequence, starting at `1` | +| `scheduled_for_utc` | string | intended UTC deadline | +| `started_at_utc` | string or null | UTC start time, if started | +| `finished_at_utc` | string or null | UTC finish time, if finished | +| `state` | string | run state | +| `outcome` | object or null | terminal outcome below; null while unfinished | +| `stdout_path` | string or null | raw stdout file under the state directory, if available | +| `stderr_path` | string or null | raw stderr file under the state directory, if available | -Captured streams are stored raw on disk under the logged -`stdout_path`/`stderr_path`; only this JSON view applies lossy UTF-8 -decoding. Binary output should be read from those files, not from JSON. +### Outcome object -Process object (`ps --json`): `job_id`, `run_id`, `role` (`monitor` or -`command`), `pid`, `process_group_id`, `state`. +Outcomes are tagged objects with `kind` and `value`, not strings. + +| `kind` | `value` type | Meaning | +| --- | --- | --- | +| `exit` | integer | command exit code; `0` means success | +| `signal` | integer | signal that terminated the command | +| `failure` | string | failure explanation, such as an execution setup error | +| `interrupted` | string | explanation when the outcome cannot be established | +| `cancelled` | string | cancellation explanation | -Submission object (scheduling commands like `atx 30s -- cmd --json`): -`job_id`, `state`, `schedule`, `next_due_utc`, `runtime_tier`, -`supervised` (boolean), `dry_run` (boolean). +### Outcome examples + +These examples show all five variants. Explanation text is not a stable code. + +```json +[ + {"kind": "exit", "value": 0}, + {"kind": "signal", "value": 15}, + {"kind": "failure", "value": "command could not start"}, + {"kind": "interrupted", "value": "outcome unknown after restart"}, + {"kind": "cancelled", "value": "cancelled by user"} +] +``` + +## Run-output object + +| Field | Type | Meaning | +| --- | --- | --- | +| `run_id` | string | full run ID | +| `job_id` | string | full job ID | +| `state` | string | run state | +| `outcome` | object or null | same outcome object as `history` | +| `stdout_truncated` | boolean | capture cap cut the stdout stream | +| `stderr_truncated` | boolean | capture cap cut the stderr stream | +| `stdout` | string | captured stdout decoded as UTF-8 | +| `stderr` | string | captured stderr decoded as UTF-8 | + +Invalid UTF-8 becomes U+FFFD in this view. ATX stores the captured bytes unchanged +in the files named by `stdout_path` and `stderr_path`. Read those files rather than +JSON for binary output. + +## Process object + +`ps` lists the processes for active runs. It does not list the supervisor. + +| Field | Type | Meaning | +| --- | --- | --- | +| `job_id` | string | full job ID | +| `run_id` | string | full run ID | +| `role` | string | `monitor` or `command` | +| `pid` | integer | positive process ID | +| `process_group_id` | integer | process group ID | +| `state` | string | run state | + +## Doctor report + +`doctor` can return a success envelope with `ok: true` and still exit nonzero when +the report is unhealthy. `ok` says a report was produced; `healthy` describes its +checks. Warnings alone do not make the report unhealthy. + +| Field | Type | Meaning | +| --- | --- | --- | +| `healthy` | boolean | false if any check has status `fail` | +| `checks` | array of check objects | diagnostic results | +| `tzdb_version` | string | bundled timezone data version | +| `schema_version` | integer or null | SQLite schema version, null when no database exists | +| `durable_available` | boolean | durable service is available and running | +| `config` | object | effective configuration without environment values | + +The report's `schema_version` is the SQLite schema version, not the envelope's +JSON contract version. + +### Check object + +| Field | Type | Meaning | +| --- | --- | --- | +| `name` | string | check name | +| `status` | string | `pass`, `warning`, or `fail` | +| `message` | string | diagnostic explanation | +| `remediation` | string, optional | suggested next step; omitted when absent | + +Check messages and names are diagnostic text. Do not match them as stable codes. + +### Effective configuration object + +| Field | Type | Meaning | +| --- | --- | --- | +| `cancel_grace` | string | canonical cancellation grace duration | +| `color` | string | `auto`, `always`, or `never` | +| `default_runtime` | string | `session` or `durable` | +| `default_shell` | string | default shell path | +| `default_timezone` | string | timezone setting, such as `local` | +| `history_days` | integer | run-history retention period | +| `max_log_bytes_per_stream` | integer | byte cap for each captured stream | +| `terminal_job_days` | integer | terminal-job retention period | +| `verbosity` | string | `quiet`, `normal`, or `verbose` | + +## Service objects + +### Service-status object + +| Field | Type | Meaning | +| --- | --- | --- | +| `manager` | string | platform service manager name | +| `availability` | string | `available` or `unavailable` | +| `installed` | boolean | service files are installed | +| `running` | boolean | service is running | +| `files` | array of strings | platform service file paths | +| `guarantee` | string | explanation of the platform's durable behavior | +| `detail` | string | current status explanation | + +### Service-change object + +| Field | Type | Meaning | +| --- | --- | --- | +| `changed` | boolean | install or uninstall changed the service | +| `status` | object | service-status object after the operation | diff --git a/src/cli/json.rs b/src/cli/json.rs index d6fa774..29cabdd 100644 --- a/src/cli/json.rs +++ b/src/cli/json.rs @@ -55,6 +55,194 @@ mod tests { #![allow(clippy::expect_used)] use super::{error, success}; + use crate::application::{ + DiagnosticCheck, DiagnosticStatus, DoctorReport, ServiceAvailability, ServiceChange, + ServiceStatus, + }; + use crate::domain::{ + DstResolution, ExecutionMode, JobState, RunOutcome, RunState, RuntimeTier, + }; + use crate::infrastructure::config::{ColorMode, Verbosity}; + + #[test] + fn public_enum_strings_are_stable() { + fn expect_strings(values: &impl serde::Serialize, expected: &[&str]) { + assert_eq!( + serde_json::to_value(values).expect("enum JSON"), + serde_json::json!(expected) + ); + } + expect_strings( + &JobState::ALL, + &[ + "scheduled", + "waiting", + "starting", + "running", + "cancel_requested", + "succeeded", + "failed", + "cancelled", + "interrupted", + "missed", + ], + ); + expect_strings( + &RunState::ALL, + &[ + "starting", + "running", + "cancel_requested", + "succeeded", + "failed", + "cancelled", + "interrupted", + ], + ); + expect_strings( + &[RuntimeTier::Session, RuntimeTier::Durable], + &["session", "durable"], + ); + expect_strings( + &[ExecutionMode::Direct, ExecutionMode::Shell], + &["direct", "shell"], + ); + expect_strings( + &[ + DstResolution::Reject, + DstResolution::Earlier, + DstResolution::Later, + ], + &["reject", "earlier", "later"], + ); + expect_strings( + &[ + DiagnosticStatus::Pass, + DiagnosticStatus::Warning, + DiagnosticStatus::Fail, + ], + &["pass", "warning", "fail"], + ); + expect_strings( + &[ + ServiceAvailability::Available, + ServiceAvailability::Unavailable, + ], + &["available", "unavailable"], + ); + expect_strings( + &[ColorMode::Auto, ColorMode::Always, ColorMode::Never], + &["auto", "always", "never"], + ); + expect_strings( + &[Verbosity::Quiet, Verbosity::Normal, Verbosity::Verbose], + &["quiet", "normal", "verbose"], + ); + } + + #[test] + fn outcome_examples_match_all_tagged_variants() { + let outcomes = [ + RunOutcome::Exit(0), + RunOutcome::Signal(15), + RunOutcome::Failure("command could not start".to_owned()), + RunOutcome::Interrupted("outcome unknown after restart".to_owned()), + RunOutcome::Cancelled("cancelled by user".to_owned()), + ]; + let docs = include_str!("../../docs/json-api.md"); + let section = docs + .split("### Outcome examples") + .nth(1) + .expect("outcome section"); + let example = section + .split("```json\n") + .nth(1) + .expect("JSON example") + .split("```") + .next() + .expect("example end"); + let expected: serde_json::Value = + serde_json::from_str(example).expect("documented outcomes"); + let actual = serde_json::to_value(&outcomes).expect("outcomes"); + assert_eq!(actual, expected); + assert_eq!( + serde_json::from_value::>(actual).expect("round trip"), + outcomes + ); + for value in [i32::MIN, -1, 1, i32::MAX] { + assert_eq!( + serde_json::to_value(RunOutcome::Exit(value)).expect("exit"), + serde_json::json!({"kind":"exit", "value":value}) + ); + } + } + + #[test] + fn doctor_schema_version_and_optional_remediation_keep_their_types() { + for schema_version in [None, Some(42)] { + let report = DoctorReport { + healthy: false, + checks: vec![DiagnosticCheck { + name: "SQLite".to_owned(), + status: DiagnosticStatus::Fail, + message: "database is unreadable".to_owned(), + remediation: None, + }], + tzdb_version: "2026c".to_owned(), + schema_version, + durable_available: false, + config: serde_json::json!({}), + }; + let actual: serde_json::Value = + serde_json::from_str(&success(&report).expect("report envelope")).expect("JSON"); + assert_eq!( + actual, + serde_json::json!({ + "schema_version":1, "ok":true, + "data":{ + "healthy":false, + "checks":[{"name":"SQLite", "status":"fail", "message":"database is unreadable"}], + "tzdb_version":"2026c", "schema_version":schema_version, + "durable_available":false, "config":{}, + }, + }) + ); + } + } + + #[test] + fn service_change_payload_has_a_boolean_and_status_object() { + for (availability, expected) in [ + (ServiceAvailability::Available, "available"), + (ServiceAvailability::Unavailable, "unavailable"), + ] { + for changed in [false, true] { + let change = ServiceChange { + changed, + status: ServiceStatus { + manager: "test manager".to_owned(), + availability, + installed: true, + running: false, + files: vec!["/tmp/test.service".into()], + guarantee: "test guarantee".to_owned(), + detail: "test detail".to_owned(), + }, + }; + assert_eq!( + serde_json::to_value(change).expect("service change"), + serde_json::json!({ + "changed":changed, + "status":{ + "manager":"test manager", "availability":expected, "installed":true, + "running":false, "files":["/tmp/test.service"], + "guarantee":"test guarantee", "detail":"test detail", + }, + }) + ); + } + } + } #[test] fn envelopes_keep_schema_version_and_channels_stable() { diff --git a/tests/cli_human_output.rs b/tests/cli_human_output.rs index ad7bafd..be44307 100644 --- a/tests/cli_human_output.rs +++ b/tests/cli_human_output.rs @@ -29,10 +29,249 @@ fn tools(root: &std::path::Path) -> Command { fn json_output(command: &mut Command) -> (Value, Output) { let output = command.output().expect("run atx"); - let value = serde_json::from_slice(&output.stdout).expect("JSON envelope"); + assert!( + output.stdout.ends_with(b"\n"), + "JSON must end in a newline: {output:?}" + ); + let value = json_line(&output.stdout); (value, output) } +fn json_line(bytes: &[u8]) -> Value { + let line = bytes.strip_suffix(b"\n").expect("JSON newline"); + assert!(!line.contains(&b'\n'), "JSON must fit on one line"); + serde_json::from_slice(line).expect("JSON envelope") +} + +fn expect_keys(value: &Value, expected: &[&str]) { + let mut actual: Vec<&str> = value + .as_object() + .expect("object") + .keys() + .map(String::as_str) + .collect(); + actual.sort_unstable(); + assert_eq!(actual, expected); +} + +fn expect_identifier(value: &Value) { + let id = value.as_str().expect("identifier string"); + assert_eq!(id.len(), 26); + assert!( + id.bytes() + .all(|byte| b"0123456789abcdefghjkmnpqrstvwxyz".contains(&byte)) + ); + assert!(id.as_bytes()[0] <= b'7', "identifier exceeds 128 bits"); +} + +fn expect_timestamp(value: &Value) { + let timestamp = value.as_str().expect("timestamp string"); + timestamp + .parse::() + .expect("RFC 3339 timestamp"); + assert!(timestamp.ends_with('Z'), "timestamp must be UTC"); +} + +#[test] +fn json_v1_values_and_types_are_stable() { + let root = tempdir().expect("root"); + let (dry, output) = + json_output(tools(root.path()).args(["--json", "--dry-run", "30s", "--", "/usr/bin/true"])); + assert!(output.status.success(), "{output:?}"); + assert_eq!(dry["schema_version"], 1); + assert_eq!(dry["ok"], true); + let submitted = &dry["data"]; + expect_identifier(&submitted["job_id"]); + expect_timestamp(&submitted["next_due_utc"]); + assert_eq!(submitted["state"], "scheduled"); + assert_eq!(submitted["runtime_tier"], "session"); + assert_eq!(submitted["supervised"], false); + assert_eq!(submitted["dry_run"], true); + assert_eq!(submitted["schedule"]["kind"], "one_shot_relative"); + assert_eq!(submitted["schedule"]["duration"], "30s"); + expect_keys( + &submitted["schedule"], + &["duration", "kind", "persisted_due_utc"], + ); + expect_timestamp(&submitted["schedule"]["persisted_due_utc"]); + + let (job_id, run_id) = finished_job(root.path()); + let (job, _) = json_output(tools(root.path()).args(["--json", "show", &job_id])); + let job = &job["data"]; + expect_identifier(&job["job_id"]); + expect_timestamp(&job["next_due_utc"]); + assert!(job["remaining_seconds"].is_i64()); + assert_eq!(job["state"], "succeeded"); + assert_eq!(job["runtime_tier"], "session"); + assert!(job["name"].is_null()); + assert!(job["description"].is_null()); + assert!(job["active_run_id"].is_null()); + assert!(job.get("outcome").is_none()); + assert_eq!(job["execution"]["mode"], "direct"); + assert!( + job["execution"]["argv"] + .as_array() + .expect("argv") + .iter() + .all(Value::is_string) + ); + assert!( + std::path::Path::new( + job["execution"]["working_directory"] + .as_str() + .expect("working directory") + ) + .is_absolute() + ); + assert!( + job["execution"]["environment_keys"] + .as_array() + .expect("keys") + .iter() + .all(Value::is_string) + ); + assert!(job["execution"]["shell_path"].is_null()); + + let (history, _) = json_output(tools(root.path()).args(["--json", "history", &job_id])); + let run = &history["data"][0]; + expect_identifier(&run["job_id"]); + expect_identifier(&run["run_id"]); + assert_eq!(run["sequence"], 1); + for field in ["scheduled_for_utc", "started_at_utc", "finished_at_utc"] { + expect_timestamp(&run[field]); + } + assert_eq!(run["state"], "succeeded"); + assert_eq!(run["outcome"], serde_json::json!({"kind":"exit","value":0})); + assert!(run["stdout_path"].is_string()); + assert!(run["stderr_path"].is_string()); + let (captured, _) = json_output(tools(root.path()).args(["--json", "output", &run_id])); + assert_eq!(captured["data"]["outcome"], run["outcome"]); + for field in ["stdout", "stderr"] { + assert!(captured["data"][field].is_string()); + } + for field in ["stdout_truncated", "stderr_truncated"] { + assert!(captured["data"][field].is_boolean()); + } + let (doctor, output) = json_output(tools(root.path()).args(["--json", "doctor"])); + assert!(output.status.success(), "{output:?}"); + assert!( + doctor["data"]["schema_version"] + .as_u64() + .is_some_and(|version| version > 0) + ); +} + +fn documented_example(heading: &str) -> Value { + let docs = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/docs/json-api.md")) + .expect("JSON guide"); + let section = docs + .split(heading) + .nth(1) + .expect("documented example section"); + let example = section + .split("```json\n") + .nth(1) + .expect("JSON example") + .split("```") + .next() + .expect("example end"); + serde_json::from_str(example).expect("valid documented JSON") +} + +#[test] +fn documented_version_example_matches_the_binary() { + let expected = documented_example("### Version example"); + let (actual, output) = json_output(atx().args(["--json", "version"])); + assert!(output.status.success()); + assert_eq!(actual, expected); +} + +#[test] +fn documented_error_example_matches_the_binary() { + let root = tempdir().expect("root"); + let output = tools(root.path()) + .args(["--json", "show", "nosuch"]) + .output() + .expect("missing job"); + assert_eq!(output.status.code(), Some(3)); + assert!(output.stdout.is_empty()); + let actual = json_line(&output.stderr); + assert_eq!(actual, documented_example("### Error example")); + + let invalid = tools(root.path()) + .args(["--json", "0s", "--", "true"]) + .output() + .expect("invalid duration"); + assert_eq!(invalid.status.code(), Some(2)); + assert!(invalid.stdout.is_empty()); + let invalid = json_line(&invalid.stderr); + expect_keys(&invalid, &["error", "ok", "schema_version"]); + expect_keys(&invalid["error"], &["code", "message"]); + assert_eq!(invalid["schema_version"], 1); + assert_eq!(invalid["ok"], false); + assert_eq!(invalid["error"]["code"], "INVALID_ARGUMENT"); + assert!(invalid["error"]["message"].is_string()); +} + +#[test] +fn json_schedule_variants_keep_their_field_types() { + let root = tempdir().expect("root"); + let (absolute, output) = json_output(tools(root.path()).args([ + "--json", + "--dry-run", + "--tz", + "Europe/London", + "--dst", + "later", + "2099-01-02T03:04:05", + "--", + "true", + ])); + assert!(output.status.success(), "{output:?}"); + assert_eq!(absolute["data"]["runtime_tier"], "session"); + let schedule = &absolute["data"]["schedule"]; + expect_keys( + schedule, + &[ + "dst_resolution", + "kind", + "original_input", + "resolved_due_utc", + "timezone", + "timezone_database_version", + ], + ); + assert_eq!(schedule["kind"], "one_shot_absolute"); + assert_eq!(schedule["original_input"], "2099-01-02T03:04:05"); + assert_eq!(schedule["timezone"], "Europe/London"); + assert!(schedule["timezone_database_version"].is_string()); + assert_eq!(schedule["resolved_due_utc"], "2099-01-02T03:04:05Z"); + assert_eq!(schedule["dst_resolution"], "later"); + assert_eq!( + absolute["data"]["next_due_utc"], + schedule["resolved_due_utc"] + ); + + let (recurring, output) = json_output(tools(root.path()).args([ + "--json", + "--dry-run", + "--every", + "120s", + "--", + "true", + ])); + assert!(output.status.success(), "{output:?}"); + let schedule = &recurring["data"]["schedule"]; + expect_keys(schedule, &["interval", "kind", "persisted_anchor_utc"]); + assert_eq!(schedule["kind"], "recurring_interval"); + assert_eq!(schedule["interval"], "2m"); + expect_timestamp(&schedule["persisted_anchor_utc"]); + assert_eq!( + recurring["data"]["next_due_utc"], + schedule["persisted_anchor_utc"] + ); +} + fn wait_for(predicate: impl Fn() -> bool, what: &str) { let deadline = std::time::Instant::now() + Duration::from_secs(10); while !predicate() { @@ -131,6 +370,81 @@ fn lifecycle_commands_render_human_envelopes() { assert!(removal.contains(&job_id), "{removal}"); } +#[test] +fn json_doctor_report_has_stable_keys_and_types() { + let root = tempdir().expect("root"); + let (doctor_json, output) = json_output(tools(root.path()).args(["--json", "doctor"])); + assert!(output.status.success(), "{output:?}"); + expect_keys(&doctor_json, &["data", "ok", "schema_version"]); + let data = &doctor_json["data"]; + expect_keys( + data, + &[ + "checks", + "config", + "durable_available", + "healthy", + "schema_version", + "tzdb_version", + ], + ); + assert_eq!(doctor_json["ok"], true); + assert_eq!(doctor_json["schema_version"], 1); + assert_eq!(data["healthy"], true); + assert!(data["durable_available"].is_boolean()); + assert!(data["schema_version"].is_null()); + let checks = data["checks"].as_array().expect("checks"); + assert!(!checks.is_empty()); + for check in checks { + let keys = if check.get("remediation").is_some() { + &["message", "name", "remediation", "status"][..] + } else { + &["message", "name", "status"][..] + }; + expect_keys(check, keys); + assert!(check["name"].is_string()); + assert!(check["message"].is_string()); + assert!(matches!( + check["status"].as_str(), + Some("pass" | "warning" | "fail") + )); + if let Some(remediation) = check.get("remediation") { + assert!(remediation.is_string()); + } + } + expect_keys( + &data["config"], + &[ + "cancel_grace", + "color", + "default_runtime", + "default_shell", + "default_timezone", + "history_days", + "max_log_bytes_per_stream", + "terminal_job_days", + "verbosity", + ], + ); + for field in [ + "cancel_grace", + "color", + "default_runtime", + "default_shell", + "default_timezone", + "verbosity", + ] { + assert!(data["config"][field].is_string(), "{field}"); + } + for field in [ + "history_days", + "max_log_bytes_per_stream", + "terminal_job_days", + ] { + assert!(data["config"][field].is_u64(), "{field}"); + } +} + #[test] fn doctor_service_version_and_completions_render() { let root = tempdir().expect("root"); @@ -159,6 +473,36 @@ fn doctor_service_version_and_completions_render() { service_json_output.status.success(), "{service_json_output:?}" ); + let data = &service_json["data"]; + expect_keys( + data, + &[ + "availability", + "detail", + "files", + "guarantee", + "installed", + "manager", + "running", + ], + ); + assert!(matches!( + data["availability"].as_str(), + Some("available" | "unavailable") + )); + for field in ["detail", "guarantee", "manager"] { + assert!(data[field].is_string()); + } + for field in ["installed", "running"] { + assert!(data[field].is_boolean()); + } + assert!( + data["files"] + .as_array() + .expect("service files") + .iter() + .all(Value::is_string) + ); let service = tools(root.path()) .args(["service", "status"]) .output() @@ -294,17 +638,6 @@ fn finished_job(root: &std::path::Path) -> (String, String) { /// docs/json-api.md promises. A new field must land in both places. #[test] fn json_job_payloads_expose_the_documented_key_sets() { - fn expect_keys(value: &Value, expected: &[&str]) { - let mut actual: Vec<&str> = value - .as_object() - .expect("payload") - .keys() - .map(String::as_str) - .collect(); - actual.sort_unstable(); - assert_eq!(actual, expected); - } - let root = tempdir().expect("root"); let (submission, _) = json_output(tools(root.path()).args(["--json", "30m", "--", "/bin/true"])); @@ -367,21 +700,40 @@ fn json_job_payloads_expose_the_documented_key_sets() { .cloned() .collect(); assert_eq!(shown_keys, listed_keys); -} -#[test] -fn json_run_payloads_expose_the_documented_key_sets() { - fn expect_keys(value: &Value, expected: &[&str]) { - let mut actual: Vec<&str> = value + let (cancelled, output) = json_output(tools(root.path()).args(["--json", "cancel", &job_id])); + assert!(output.status.success(), "{output:?}"); + assert_eq!( + cancelled["data"] .as_object() - .expect("payload") + .expect("cancelled job") .keys() - .map(String::as_str) - .collect(); - actual.sort_unstable(); - assert_eq!(actual, expected); - } + .collect::>(), + job.as_object() + .expect("listed job") + .keys() + .collect::>() + ); + let (removed, output) = json_output(tools(root.path()).args(["--json", "rm", &job_id])); + assert!(output.status.success(), "{output:?}"); + assert_eq!(removed["data"]["job_id"], cancelled["data"]["job_id"]); + assert_eq!(removed["data"]["state"], cancelled["data"]["state"]); + assert_eq!( + removed["data"] + .as_object() + .expect("removed job") + .keys() + .collect::>(), + cancelled["data"] + .as_object() + .expect("cancelled job") + .keys() + .collect::>() + ); +} +#[test] +fn json_run_payloads_expose_the_documented_key_sets() { let root = tempdir().expect("root"); let (job_id, run_id) = finished_job(root.path()); @@ -418,8 +770,71 @@ fn json_run_payloads_expose_the_documented_key_sets() { ], ); - let (processes, _) = json_output(tools(root.path()).args(["--json", "ps"])); - if let Some(process) = processes["data"].as_array().and_then(|p| p.first()) { + assert!( + history["data"] + .as_array() + .expect("runs") + .iter() + .all(|run| run["job_id"] == job_id) + ); + + let (rerun, output) = json_output(tools(root.path()).args(["--json", "run", &job_id, "--yes"])); + assert!(output.status.success(), "{output:?}"); + expect_keys( + &rerun["data"], + &[ + "active_run_id", + "description", + "execution", + "job_id", + "name", + "next_due_utc", + "remaining_seconds", + "runtime_tier", + "schedule", + "state", + ], + ); + assert_eq!(rerun["data"]["job_id"], job_id); +} + +#[test] +fn json_processes_describe_a_live_command_and_monitor() { + let root = tempdir().expect("root"); + let ready = root.path().join("ready"); + let release = root.path().join("release"); + let (submitted, output) = json_output(tools(root.path()).args([ + "--json", + "--shell", + "--name", + "held", + "--description", + "contract test", + "1s", + "--", + &format!( + "touch '{}'; while [ ! -f '{}' ]; do sleep 1; done", + ready.display(), + release.display() + ), + ])); + assert!(output.status.success(), "{output:?}"); + let job_id = submitted["data"]["job_id"].as_str().expect("job id"); + wait_for(|| ready.exists(), "the held command to start"); + wait_for( + || { + let (history, output) = + json_output(tools(root.path()).args(["--json", "history", job_id])); + output.status.success() && history["data"][0]["state"] == "running" + }, + "the running identities to be saved", + ); + let (processes, output) = json_output(tools(root.path()).args(["--json", "ps"])); + assert!(output.status.success(), "{output:?}"); + let processes = processes["data"].as_array().expect("processes"); + assert_eq!(processes.len(), 2, "{processes:?}"); + let mut roles = Vec::new(); + for process in processes { expect_keys( process, &[ @@ -431,12 +846,39 @@ fn json_run_payloads_expose_the_documented_key_sets() { "state", ], ); + expect_identifier(&process["job_id"]); + expect_identifier(&process["run_id"]); + assert_eq!(process["job_id"], job_id); + assert!( + process["pid"] + .as_u64() + .is_some_and(|pid| pid > 0 && u32::try_from(pid).is_ok()) + ); + assert!( + process["process_group_id"] + .as_i64() + .is_some_and(|pgid| pgid > 0 && i32::try_from(pgid).is_ok()) + ); + assert_eq!(process["state"], "running"); + roles.push(process["role"].as_str().expect("role")); } - assert!( - history["data"] - .as_array() - .expect("runs") - .iter() - .all(|run| run["job_id"] == job_id) - ); + roles.sort_unstable(); + assert_eq!(roles, ["command", "monitor"]); + let (history, output) = json_output(tools(root.path()).args(["--json", "history", job_id])); + assert!(output.status.success(), "{output:?}"); + let run = &history["data"][0]; + assert_eq!(run["state"], "running"); + assert!(run["outcome"].is_null()); + assert!(run["finished_at_utc"].is_null()); + expect_timestamp(&run["started_at_utc"]); + let (job, output) = json_output(tools(root.path()).args(["--json", "show", job_id])); + assert!(output.status.success(), "{output:?}"); + assert_eq!(job["data"]["name"], "held"); + assert_eq!(job["data"]["description"], "contract test"); + assert_eq!(job["data"]["execution"]["mode"], "shell"); + assert_eq!(job["data"]["execution"]["shell_path"], "/bin/sh"); + assert!(job["data"]["active_run_id"].is_null()); + let (_, output) = + json_output(tools(root.path()).args(["--json", "cancel", job_id, "--grace", "1s"])); + assert!(output.status.success(), "{output:?}"); } diff --git a/tests/config_effective.rs b/tests/config_effective.rs index cdf72e2..3f35a66 100644 --- a/tests/config_effective.rs +++ b/tests/config_effective.rs @@ -112,8 +112,8 @@ fn configured_log_cap_bounds_stored_streams() { } /// Supervisor startup applies the operator's retention window instead of a -/// hardcoded default: an ancient terminal job is purged when the configured -/// window is one day. +/// hardcoded default: a two-day-old terminal job survives the default window +/// and is purged when the configured window is one day. #[test] fn configured_retention_purges_old_terminal_jobs_at_startup() { let root = tempdir().expect("root"); @@ -130,48 +130,50 @@ fn configured_retention_purges_old_terminal_jobs_at_startup() { "job to reach a terminal state", ); - // Backdate every row of that job beyond any default window. - let db = state.join("atx.db"); - let ancient = "2020-01-01T00:00:00Z"; - for statement in [ - format!("UPDATE runs SET finished_at_utc = '{ancient}' WHERE job_id = '{job_id}';"), - format!("UPDATE transitions SET occurred_at_utc = '{ancient}' WHERE job_id = '{job_id}';"), - format!("UPDATE jobs SET updated_at_utc = '{ancient}' WHERE id = '{job_id}';"), - ] { - let result = Command::new("sqlite3") - .arg(&db) - .arg(statement) - .output() - .expect("sqlite3 available"); - assert!( - result.status.success(), - "backdate failed: {}", - String::from_utf8_lossy(&result.stderr) - ); - } + let original_job = json(&state, &["show", &job_id]); + let original_history = json(&state, &["history", &job_id]); + root.stop_background() + .expect("stop the original session supervisor"); + support::age_stopped_terminal_job(&state, &job_id, 2).expect("age a valid terminal timeline"); + let aged = json(&state, &["show", &job_id]); + assert_eq!(aged["job_id"], job_id); + assert_eq!(aged["state"], original_job["state"]); + assert_aged_timestamps(&original_job, &aged, &["next_due_utc"]); + let history = json(&state, &["history", &job_id]); + assert_eq!(history[0]["outcome"], original_history[0]["outcome"]); + assert_eq!( + history.as_array().expect("aged history").len(), + original_history.as_array().expect("original history").len() + ); + assert_aged_timestamps( + &original_history[0], + &history[0], + &["scheduled_for_utc", "started_at_utc", "finished_at_utc"], + ); + + let runtime = state.join("runtime"); + let log = root.path().join("daemon.err"); + let mut daemon = spawn_retention_daemon(&state, &runtime, &log); + support::wait_for_service(&mut daemon, &state, &runtime, &log) + .expect("default service readiness"); + let _ = json(&state, &["30m", "--", "/bin/true"]); + assert_eq!( + json(&state, &["show", &job_id])["state"], + original_job["state"] + ); + assert!(daemon.try_wait().expect("default daemon status").is_none()); + daemon.kill().expect("stop the default-retention daemon"); + daemon.wait().expect("reap the default-retention daemon"); - // A one-day retention window deletes the ancient job on next startup. fs::write( state.join("config.toml"), "history_days = 1\nterminal_job_days = 1\n", ) .expect("write config"); - - let runtime = root.path().join("runtime"); - let stderr_log = fs::File::create(root.path().join("daemon.err")).expect("daemon log"); - let mut daemon = Command::new(env!("CARGO_BIN_EXE_atx")) - .arg("__supervisor") - .arg("--state-dir") - .arg(&state) - .arg("--runtime-dir") - .arg(&runtime) - .arg("--service-managed") - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(stderr_log) - .spawn() - .expect("start service-managed supervisor"); - + let mut daemon = spawn_retention_daemon(&state, &runtime, &log); + support::wait_for_service(&mut daemon, &state, &runtime, &log) + .expect("configured service readiness"); + let _ = json(&state, &["30m", "--", "/bin/true"]); wait_for( || { let output = atx() @@ -181,11 +183,64 @@ fn configured_retention_purges_old_terminal_jobs_at_startup() { .args(["show", &job_id]) .output() .expect("show"); - !output.status.success() + if output.status.success() { + return false; + } + assert_eq!(output.status.code(), Some(3), "{output:?}"); + let error: serde_json::Value = + serde_json::from_slice(&output.stderr).expect("purge error"); + assert_eq!(error["error"]["code"], "JOB_NOT_FOUND"); + true }, - "retention to purge the ancient terminal job", + "configured retention to purge the two-day-old terminal job", ); - daemon.kill().expect("stop daemon"); daemon.wait().expect("reap daemon"); } + +fn assert_aged_timestamps(original: &serde_json::Value, aged: &serde_json::Value, fields: &[&str]) { + for field in fields { + let before = original.get(field).expect("original timestamp field"); + let after = aged.get(field).expect("aged timestamp field"); + if before.is_null() { + assert!(after.is_null()); + } else { + let before = before + .as_str() + .expect("original timestamp") + .parse::() + .expect("valid timestamp"); + let after = after + .as_str() + .expect("aged timestamp") + .parse::() + .expect("valid timestamp"); + assert_eq!( + after, + before + .checked_sub(jiff::SignedDuration::from_secs(172_800)) + .expect("shift") + ); + } + } +} + +fn spawn_retention_daemon( + state: &std::path::Path, + runtime: &std::path::Path, + log: &std::path::Path, +) -> std::process::Child { + let stderr = fs::File::create(log).expect("daemon log"); + atx() + .arg("__supervisor") + .arg("--state-dir") + .arg(state) + .arg("--runtime-dir") + .arg(runtime) + .arg("--service-managed") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(stderr) + .spawn() + .expect("start service-managed supervisor") +} diff --git a/tests/process_lifecycle.rs b/tests/process_lifecycle.rs index 4332874..7d9bcbe 100644 --- a/tests/process_lifecycle.rs +++ b/tests/process_lifecycle.rs @@ -319,6 +319,114 @@ fn unwind_stops_supervisor_monitor_and_command_processes() { ); } +#[test] +fn service_readiness_requires_a_healthy_initialized_database() { + let ready = serde_json::json!({ + "schema_version":1, "ok":true, + "data":{"healthy":true, "schema_version":1}, + }); + assert!(support::service_report_is_ready(&ready)); + for database_schema in [ + serde_json::Value::Null, + serde_json::json!(0), + serde_json::json!("1"), + ] { + let mut report = ready.clone(); + report["data"]["schema_version"] = database_schema; + assert!(!support::service_report_is_ready(&report)); + } + let mut failed = ready.clone(); + failed["data"]["healthy"] = serde_json::json!(false); + assert!(!support::service_report_is_ready(&failed)); + failed = ready; + failed["ok"] = serde_json::json!(false); + assert!(!support::service_report_is_ready(&failed)); + assert!(!support::service_report_is_ready(&serde_json::json!({}))); +} + +#[test] +fn service_readiness_reports_early_exit_and_reaps_the_child() { + let root = tempdir().expect("root"); + let state = root.path().join("state"); + let log = root.path().join("daemon.err"); + let mut child = std::process::Command::new("/bin/sh") + .args(["-c", "echo startup-fault >&2; exit 9"]) + .stderr(fs::File::create(&log).expect("log")) + .spawn() + .expect("failing service"); + let error = support::wait_for_service(&mut child, &state, &state.join("runtime"), &log) + .expect_err("early service exit"); + assert!(error.contains("startup-fault"), "{error}"); + assert!(error.contains("exited before readiness"), "{error}"); + assert_eq!( + child + .try_wait() + .expect("reaped child") + .expect("exit") + .code(), + Some(9) + ); +} + +#[test] +fn terminal_aging_rejects_live_and_unclaimed_fixtures_without_changes() { + let root = tempdir().expect("root"); + let state = root.path().join("state"); + let job_id = submit(&state, "30m", &["/bin/true"]); + assert!(support::age_stopped_terminal_job(&state, &job_id, 2).is_err()); + assert!(support::age_stopped_terminal_job(&state, &job_id, 0).is_err()); + root.stop_background().expect("stop fixture"); + let before = fs::read(state.join("atx.db")).expect("database"); + assert!(support::age_stopped_terminal_job(&state, &job_id, 2).is_err()); + assert_eq!( + fs::read(state.join("atx.db")).expect("database after guard"), + before + ); +} + +#[test] +fn service_readiness_timeout_is_bounded_and_does_not_signal_the_child() { + let root = tempdir().expect("root"); + let state = root.path().join("state"); + let log = root.path().join("daemon.err"); + let mut child = std::process::Command::new("/bin/sh") + .args(["-c", "read token"]) + .stdin(std::process::Stdio::piped()) + .stderr(fs::File::create(&log).expect("log")) + .spawn() + .expect("held service"); + let started = Instant::now(); + let result = support::wait_for_service_with_timeout( + &mut child, + &state, + &state.join("runtime"), + &log, + Duration::from_millis(1), + ); + let elapsed = started.elapsed(); + let still_running = child.try_wait().expect("child status").is_none(); + if still_running { + child.kill().expect("stop held child"); + child.wait().expect("reap held child"); + } + assert!(still_running); + assert!(elapsed < Duration::from_secs(2), "{elapsed:?}"); + assert!( + result + .expect_err("readiness timeout") + .contains("readiness timed out") + ); +} + +#[test] +fn terminal_aging_never_creates_a_missing_database() { + let root = tempdir().expect("root"); + let state = root.path().join("state"); + fs::create_dir(&state).expect("state directory"); + assert!(support::age_stopped_terminal_job(&state, "00000000000000000000000000", 2).is_err()); + assert!(!state.join("atx.db").exists()); +} + fn assert_supervisor_reaps_monitors(service_managed: bool) { let root = tempdir().expect("root"); let state = root.path().join("state"); @@ -337,11 +445,14 @@ fn assert_supervisor_reaps_monitors(service_managed: bool) { .spawn() .expect("start service supervisor") }); - if service_managed { - wait_for( - || state.join("runtime/supervisor.sock").exists(), - "service supervisor socket", - ); + if let Some(daemon) = daemon.as_mut() { + support::wait_for_service( + daemon, + &state, + &state.join("runtime"), + &root.path().join("daemon.err"), + ) + .expect("service supervisor readiness"); } submit(&state, "30m", &["/bin/true"]); let supervisor = supervisor_pid(&state); diff --git a/tests/service_daemon.rs b/tests/service_daemon.rs index 21581ad..d68327c 100644 --- a/tests/service_daemon.rs +++ b/tests/service_daemon.rs @@ -13,7 +13,9 @@ use std::process::{Command, Stdio}; use std::time::Duration; use rustix::process::{Pid, Signal, kill_process}; -use tempfile::tempdir; +mod support; + +use support::tempdir; fn atx() -> Command { Command::new(env!("CARGO_BIN_EXE_atx")) @@ -62,24 +64,13 @@ fn service_managed_daemon_executes_due_jobs_and_stops_cleanly_on_sigterm() { let mut daemon = spawn_daemon(root.path()); let socket = runtime_directory(root.path()).join("supervisor.sock"); - // The socket binds before the database finishes migrating; wait for both - // so submission cannot race first-time initialization and its Wake is - // guaranteed to reach this daemon rather than a replacement supervisor. - wait_for( - || { - socket.exists() - && atx() - .arg("--json") - .arg("--state-dir") - .arg(root.path().join("state")) - .arg("list") - .output() - .expect("probe list") - .status - .success() - }, - "daemon to finish initializing", - ); + support::wait_for_service( + &mut daemon, + &root.path().join("state"), + &runtime_directory(root.path()), + &root.path().join("daemon.err"), + ) + .expect("service supervisor readiness"); let marker = root.path().join("state").join("daemon-ran.marker"); let script = format!("'/usr/bin/touch' '{}'", marker.display()); @@ -140,22 +131,13 @@ fn service_managed_daemon_executes_due_jobs_and_stops_cleanly_on_sigterm() { fn service_managed_daemon_survives_a_broken_store_at_execution_time() { let root = tempdir().expect("root"); let mut daemon = spawn_daemon(root.path()); - let socket = runtime_directory(root.path()).join("supervisor.sock"); - wait_for( - || { - socket.exists() - && atx() - .arg("--json") - .arg("--state-dir") - .arg(root.path().join("state")) - .arg("list") - .output() - .expect("probe list") - .status - .success() - }, - "daemon to finish initializing", - ); + support::wait_for_service( + &mut daemon, + &root.path().join("state"), + &runtime_directory(root.path()), + &root.path().join("daemon.err"), + ) + .expect("service supervisor readiness"); // Submit while the store is healthy so the Wake is acknowledged, then // destroy the store before the deadline fires. The live daemon keeps its diff --git a/tests/support/mod.rs b/tests/support/mod.rs index 65aaffd..9d7f47a 100644 --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -245,6 +245,90 @@ pub(crate) fn tempdir_in(parent: &Path) -> io::Result { tempfile::tempdir_in(parent).map(|inner| TestRoot { inner }) } +#[allow(dead_code)] +pub(crate) fn service_report_is_ready(report: &serde_json::Value) -> bool { + report["schema_version"] == 1 + && report["ok"] == true + && report["data"]["healthy"] == true + && report["data"]["schema_version"] + .as_u64() + .is_some_and(|version| version > 0) +} + +/// Wait for a live service identity and an initialized database, retaining failure details. +#[allow(dead_code)] +pub(crate) fn wait_for_service( + daemon: &mut std::process::Child, + state: &Path, + runtime: &Path, + stderr_log: &Path, +) -> Result<(), String> { + wait_for_service_with_timeout(daemon, state, runtime, stderr_log, Duration::from_secs(10)) +} + +#[allow(dead_code)] +pub(crate) fn wait_for_service_with_timeout( + daemon: &mut std::process::Child, + state: &Path, + runtime: &Path, + stderr_log: &Path, + timeout: Duration, +) -> Result<(), String> { + let deadline = Instant::now() + .checked_add(timeout) + .ok_or("service timeout overflow")?; + let mut last_probe = "no published identity".to_owned(); + loop { + if let Some(status) = daemon.try_wait().map_err(|error| error.to_string())? { + return Err(format!( + "service exited before readiness: {status}; {}", + fs::read_to_string(stderr_log).unwrap_or_else(|error| error.to_string()) + )); + } + match read_identity_if_present(&runtime.join("supervisor.lock")) { + Ok(Some(identity)) + if identity.pid == daemon.id() && runtime.join("supervisor.sock").exists() => + { + let output = Command::new(env!("CARGO_BIN_EXE_atx")) + .arg("--json") + .arg("--state-dir") + .arg(state) + .arg("doctor") + .output() + .map_err(|error| error.to_string())?; + if output.status.success() + && serde_json::from_slice(&output.stdout) + .is_ok_and(|report| service_report_is_ready(&report)) + && supervisor_matches( + &identity, + runtime, + Some(state), + state.parent().unwrap_or(state), + )? + { + return Ok(()); + } + last_probe = format!( + "doctor {:?}: stdout={}, stderr={}", + output.status, + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + } + Ok(Some(_)) => "identity or socket not ready".clone_into(&mut last_probe), + Ok(None) => {} + Err(error) => last_probe = error, + } + if Instant::now() >= deadline { + return Err(format!( + "service readiness timed out: {last_probe}; {}", + fs::read_to_string(stderr_log).unwrap_or_else(|error| error.to_string()) + )); + } + std::thread::sleep(Duration::from_millis(25)); + } +} + /// Abruptly stop the session supervisor owned by `state` for crash tests. #[allow(dead_code)] pub(crate) fn kill_session_supervisor(state: &Path) -> Result<(), String> { @@ -372,6 +456,145 @@ pub(crate) fn age_stopped_one_shot(state: &Path, job_id: &str) -> Result<(), Str transaction.commit().map_err(|error| error.to_string()) } +/// Age a completed one-shot's entire timeline while no fixture process is alive. +#[allow(dead_code)] +pub(crate) fn age_stopped_terminal_job( + state: &Path, + job_id: &str, + days: u32, +) -> Result<(), String> { + if days == 0 || fixture_process_count(state.parent().unwrap_or(state))? != 0 { + return Err("terminal aging requires a positive age and a stopped fixture".into()); + } + let flags = rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE + | rusqlite::OpenFlags::SQLITE_OPEN_FULL_MUTEX + | rusqlite::OpenFlags::SQLITE_OPEN_NOFOLLOW; + let database = fs::canonicalize(state) + .map_err(|error| error.to_string())? + .join("atx.db"); + let mut connection = rusqlite::Connection::open_with_flags(database, flags) + .map_err(|error| error.to_string())?; + let transaction = connection + .transaction() + .map_err(|error| error.to_string())?; + let (due, schedule, state_name): (String, String, String) = transaction + .query_row( + "SELECT next_due_utc, schedule_json, state FROM jobs WHERE id = ?1", + [job_id], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .map_err(|error| error.to_string())?; + let (runs, active): (i64, i64) = transaction.query_row( + "SELECT count(*), coalesce(sum(state IN ('starting', 'running', 'cancel_requested')), 0) + FROM runs WHERE job_id = ?1", [job_id], |row| Ok((row.get(0)?, row.get(1)?)), + ).map_err(|error| error.to_string())?; + if !matches!( + state_name.as_str(), + "succeeded" | "failed" | "cancelled" | "interrupted" + ) || runs == 0 + || active != 0 + { + return Err("terminal aging requires a completed job and only terminal runs".into()); + } + let shift = SignedDuration::from_secs(i64::from(days) * 86_400); + let old_due = due + .parse::() + .map_err(|error| error.to_string())?; + let new_due = shift_fixture_timestamp(&due, shift)?; + let schedule = shift_one_shot_schedule(&schedule, old_due, &new_due)?; + for table in [ + FixtureTimeTable::Jobs, + FixtureTimeTable::Runs, + FixtureTimeTable::Transitions, + ] { + shift_fixture_rows(&transaction, table, job_id, shift)?; + } + transaction + .execute( + "UPDATE jobs SET schedule_json = ?1 WHERE id = ?2", + rusqlite::params![schedule, job_id], + ) + .map_err(|error| error.to_string())?; + transaction.commit().map_err(|error| error.to_string()) +} + +#[derive(Clone, Copy)] +enum FixtureTimeTable { + Jobs, + Runs, + Transitions, +} + +fn shift_fixture_rows( + transaction: &rusqlite::Transaction<'_>, + table: FixtureTimeTable, + job_id: &str, + shift: SignedDuration, +) -> Result<(), String> { + let (table, key, fields): (&str, &str, &[&str]) = match table { + FixtureTimeTable::Jobs => ( + "jobs", + "id", + &["next_due_utc", "created_at_utc", "updated_at_utc"], + ), + FixtureTimeTable::Runs => ( + "runs", + "job_id", + &[ + "scheduled_for_utc", + "created_at_utc", + "started_at_utc", + "finished_at_utc", + ], + ), + FixtureTimeTable::Transitions => ("transitions", "job_id", &["occurred_at_utc"]), + }; + let rows: Vec<(i64, Vec>)> = { + let mut statement = transaction + .prepare(&format!( + "SELECT rowid, {} FROM {table} WHERE {key} = ?1", + fields.join(", ") + )) + .map_err(|error| error.to_string())?; + statement + .query_map([job_id], |row| { + let timestamps = (1..=fields.len()) + .map(|index| row.get(index)) + .collect::>()?; + Ok((row.get(0)?, timestamps)) + }) + .map_err(|error| error.to_string())? + .collect::>() + .map_err(|error| error.to_string())? + }; + let assignments = fields + .iter() + .enumerate() + .map(|(index, field)| format!("{field} = ?{}", index + 2)) + .collect::>() + .join(", "); + let mut update = transaction + .prepare(&format!( + "UPDATE {table} SET {assignments} WHERE rowid = ?1" + )) + .map_err(|error| error.to_string())?; + for (id, timestamps) in rows { + let mut parameters = vec![rusqlite::types::Value::Integer(id)]; + for timestamp in timestamps { + parameters.push(match timestamp { + Some(value) => { + rusqlite::types::Value::Text(shift_fixture_timestamp(&value, shift)?) + } + None => rusqlite::types::Value::Null, + }); + } + update + .execute(rusqlite::params_from_iter(parameters)) + .map_err(|error| error.to_string())?; + } + Ok(()) +} + fn shift_one_shot_schedule(raw: &str, old_due: Timestamp, new_due: &str) -> Result { let mut schedule: serde_json::Value = serde_json::from_str(raw).map_err(|error| error.to_string())?; @@ -495,6 +718,11 @@ impl TestRoot { pub(crate) fn path(&self) -> &Path { self.inner.path() } + + #[allow(dead_code)] + pub(crate) fn stop_background(&self) -> Result<(), String> { + cleanup_root(self.path()) + } } impl Drop for TestRoot {