Skip to main content

schedr_bin/
cli.rs

1//! The command-line interface: the server roles, `db`, the user CLI and the in-task CLI
2//! (see archive/PROJECT.md, Web UI and CLI; In-task CLI).
3
4use std::path::{Component, Path, PathBuf};
5
6use clap::{Args, Parser, Subcommand};
7use schedr_config::{Override, OverrideValue};
8
9#[cfg(test)]
10mod tests;
11
12/// The `schedr` command line.
13#[derive(Debug, Parser)]
14#[command(
15    name = "schedr",
16    version,
17    about = "A job scheduler for Python scripts, Bash and DAGs."
18)]
19pub struct Cli {
20    /// The configuration file (otherwise `SCHEDR_CONFIG_FILE`, then /etc/schedr/config.toml).
21    #[arg(long, global = true, value_name = "PATH")]
22    pub config: Option<PathBuf>,
23    /// What to do.
24    #[command(subcommand)]
25    pub command: Command,
26}
27
28/// The top-level commands.
29#[derive(Debug, Subcommand)]
30pub enum Command {
31    /// Run the master: scheduling loop, state in the database, internal API for workers.
32    Master {
33        /// Migrate the database at start, holding the master's lease, when its schema isn't up
34        /// to date, instead of refusing it: for a deployment that can't migrate as a step of
35        /// its own (e.g. an init container without a mesh's sidecar).
36        #[arg(long)]
37        migrate: bool,
38    },
39    /// Run a worker agent.
40    Worker,
41    /// Run the webserver: the REST API used by the web UI and the CLI.
42    Webserver,
43    /// Run the web UI over webservers' APIs (`[ui] deployments`).
44    Ui,
45    /// Run every role in one process (SQLite or Postgres): local development, or one pod in
46    /// production.
47    Standalone {
48        /// The address the REST API listens on (default 127.0.0.1); e.g. 0.0.0.0 in a pod
49        /// behind a Service. The master's gRPC stays on loopback.
50        #[arg(long, value_name = "ADDRESS")]
51        listen: Option<std::net::IpAddr>,
52        /// Migrate the database at start (as `schedr db migrate` does) instead of refusing a
53        /// schema that isn't up to date: for a laptop. In production, migrate as a step of its
54        /// own (the Helm chart's init container).
55        #[arg(long)]
56        migrate: bool,
57        /// Serve only the API on its port, not the web UI: one deployment of a `schedr ui`
58        /// elsewhere (a federation of standalones).
59        #[arg(long)]
60        no_ui: bool,
61        /// A folder of DAG files, repeated for more; `.` is the working folder. Given, these
62        /// are the DAG roots instead of `SCHEDR_DAG_PATH` and `[dags] path`, each named after
63        /// its folder.
64        #[arg(long = "dag-path", value_name = "PATH")]
65        dag_path: Vec<PathBuf>,
66        /// A folder of scripts, repeated for more; `.` is the working folder. Given, these are
67        /// the script roots instead of `SCHEDR_SCRIPT_PATH` and `[scripts] path`.
68        #[arg(long = "script-path", value_name = "PATH")]
69        script_path: Vec<PathBuf>,
70    },
71    /// Manage the database schema.
72    Db {
73        /// The database command.
74        #[command(subcommand)]
75        command: DbCommand,
76    },
77    /// Set, list, read and export the secrets of standalone's `db` storage (straight in the
78    /// database, as `db` is; values encrypted under `SCHEDR_SECRET_KEY`).
79    Secrets {
80        /// The secrets command.
81        #[command(subcommand)]
82        command: SecretsCommand,
83    },
84    /// List, pause, check and test DAGs.
85    Dags {
86        /// How to reach the server.
87        #[command(flatten)]
88        client: ClientArgs,
89        /// The DAG command.
90        #[command(subcommand)]
91        command: DagsCommand,
92    },
93    /// Trigger, list, show, cancel and backfill runs.
94    Runs {
95        /// How to reach the server.
96        #[command(flatten)]
97        client: ClientArgs,
98        /// The run command.
99        #[command(subcommand)]
100        command: RunsCommand,
101    },
102    /// Cancel or retry single tasks of a run, or read their attempts, logs and outputs.
103    Tasks {
104        /// How to reach the server.
105        #[command(flatten)]
106        client: ClientArgs,
107        /// The task command.
108        #[command(subcommand)]
109        command: TasksCommand,
110    },
111    /// Check a deployment's connections, or test one, on a worker.
112    Connections {
113        /// How to reach the server.
114        #[command(flatten)]
115        client: ClientArgs,
116        /// The connections command.
117        #[command(subcommand)]
118        command: ConnectionsCommand,
119    },
120    /// Wait steps switched off for getting their host killed.
121    Sensors {
122        /// How to reach the server.
123        #[command(flatten)]
124        client: ClientArgs,
125        /// The sensor command.
126        #[command(subcommand)]
127        command: SensorsCommand,
128    },
129    /// Event triggers: see them, and start them again.
130    Triggers {
131        /// How to reach the server.
132        #[command(flatten)]
133        client: ClientArgs,
134        /// The sensor command.
135        #[command(subcommand)]
136        command: TriggersCommand,
137    },
138    /// Events posted for `EventNamed` triggers and waiting steps (decision 354).
139    Events {
140        /// How to reach the server.
141        #[command(flatten)]
142        client: ClientArgs,
143        /// The events command.
144        #[command(subcommand)]
145        command: EventsCommand,
146    },
147    /// A run's resources.
148    Resources {
149        /// How to reach the server.
150        #[command(flatten)]
151        client: ClientArgs,
152        /// The resource command.
153        #[command(subcommand)]
154        command: ResourcesCommand,
155    },
156    /// Drain and resume workers.
157    Workers {
158        /// How to reach the server.
159        #[command(flatten)]
160        client: ClientArgs,
161        /// The worker command.
162        #[command(subcommand)]
163        command: WorkersCommand,
164    },
165    /// Inside a running task: cleanup handles, resource values, declared secrets.
166    TaskCtx {
167        /// The task context command.
168        #[command(subcommand)]
169        command: TaskCtxCommand,
170    },
171    /// Inside a running task: the run's parameters and run information.
172    DagCtx {
173        /// The DAG context command.
174        #[command(subcommand)]
175        command: DagCtxCommand,
176    },
177    /// Internal, started by a worker: caps the process's data (`RLIMIT_DATA`) and runs the
178    /// task's program in its place (`hard_memory_limit=True`, decisions 50, 438).
179    #[command(hide = true)]
180    TaskExec {
181        /// The cap, in bytes.
182        #[arg(long)]
183        data_limit: u64,
184        /// The program and its arguments, after `--`.
185        #[arg(last = true, required = true, value_parser = clap::value_parser!(std::ffi::OsString))]
186        command: Vec<std::ffi::OsString>,
187    },
188}
189
190/// `schedr db ...`.
191#[derive(Debug, Clone, Copy, PartialEq, Eq, Subcommand)]
192pub enum DbCommand {
193    /// Apply the migrations not applied yet, holding the master's lease (refused while a
194    /// master holds it).
195    Migrate {
196        /// Wait until no master holds the lease (one stopped, or dead and its lease expiring)
197        /// instead of refusing.
198        #[arg(long)]
199        wait: bool,
200    },
201    /// Show whether the schema fits this version of schedr.
202    Status,
203}
204
205/// `schedr secrets ...`: the `db` secret storage (see archive/PROJECT.md, Secret storage). Only
206/// `get` prints a value.
207#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
208pub enum SecretsCommand {
209    /// Set keys of the secret at PATH (made if there is none); its other keys are kept.
210    Set {
211        /// The secret's path, e.g. `etl/db`.
212        path: String,
213        /// `key=value`; `key=@FILE` for a file's content (exactly), `key=-` for standard input
214        /// (one trailing newline dropped). A value starting with `@` is set with `-`.
215        #[arg(required = true, value_name = "KEY=VALUE")]
216        values: Vec<String>,
217    },
218    /// List the secrets' paths and key names (never the values).
219    List {
220        /// Only the paths starting with it, e.g. `etl/`.
221        prefix: Option<String>,
222    },
223    /// Print one value (`path#key`), or a whole secret as a JSON object (`path`).
224    Get {
225        /// `path#key` or `path`.
226        secret: String,
227    },
228    /// Delete the secret at PATH, all its keys.
229    Delete {
230        /// The secret's path.
231        path: String,
232    },
233    /// Write every secret for Vault: `DIR/<path>.json` each (mode 0600), loaded with `vault
234    /// kv put secret/<path> @DIR/<path>.json`. DIR must be empty or missing.
235    Export {
236        /// The directory to write (made if missing).
237        #[arg(long, value_name = "DIR")]
238        to: PathBuf,
239    },
240    /// Print a new random key for `SCHEDR_SECRET_KEY`.
241    NewKey,
242}
243
244/// How the user CLI reaches the webserver (credentials are only sent, never validated here).
245#[derive(Debug, Clone, PartialEq, Eq, Args)]
246pub struct ClientArgs {
247    /// The webserver's URL.
248    #[arg(
249        long,
250        env = "SCHEDR_SERVER",
251        default_value = "http://localhost:8080",
252        global = true
253    )]
254    pub server: String,
255    /// A bearer token (e.g. from Keycloak).
256    #[arg(long, env = "SCHEDR_TOKEN", global = true, hide_env_values = true)]
257    pub token: Option<String>,
258    /// A user name for HTTP Basic (the password comes from `SCHEDR_PASSWORD`).
259    #[arg(long, env = "SCHEDR_USER", global = true)]
260    pub user: Option<String>,
261    /// Print JSON instead of human-readable output.
262    #[arg(long, global = true)]
263    pub json: bool,
264    /// How long it waits for the webserver: from the configuration once it is read
265    /// (`SCHEDR_HIDDEN__CLIENT__*`), never a flag.
266    #[arg(skip)]
267    pub timeouts: schedr_client::Timeouts,
268}
269
270/// `schedr dags ...`.
271#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
272#[expect(
273    clippy::large_enum_variant,
274    reason = "parsed once, at the start of a command"
275)]
276pub enum DagsCommand {
277    /// List DAGs.
278    List,
279    /// Stop the scheduler creating runs of a DAG.
280    Pause {
281        /// The DAG's ID.
282        dag: String,
283    },
284    /// Let the scheduler create runs of a DAG again.
285    Unpause {
286        /// The DAG's ID.
287        dag: String,
288    },
289    /// Parse DAG files and `schedr.toml` files locally and report errors.
290    Check {
291        /// A file or directory.
292        path: PathBuf,
293        /// Fail if an active worker at this server runs an older schedr (major.minor) than this
294        /// one.
295        #[arg(long, value_name = "SERVER_URL")]
296        against: Option<String>,
297    },
298    /// Run one real run of a DAG locally and report each task (no server).
299    Test {
300        /// The DAG's ID.
301        dag: String,
302        /// The moment the run is for (UTC without an offset).
303        #[arg(long = "for", value_name = "TIME")]
304        planned_for: Option<String>,
305        /// A run parameter: `key=value` or `key:=json`.
306        #[arg(short = 'p', long = "param", value_name = "FIELD")]
307        params: Vec<String>,
308        /// All run parameters as one JSON object.
309        #[arg(long = "params", value_name = "JSON", conflicts_with = "params")]
310        params_json: Option<String>,
311        /// A secret value for the run: `path#key=value`.
312        #[arg(long = "secret", value_name = "SECRET")]
313        secrets: Vec<String>,
314        /// For a DAG a trigger starts: the event's key.
315        #[arg(long, value_name = "KEY")]
316        event_key: Option<String>,
317        /// And its data: JSON, or `@file.json`.
318        #[arg(long, value_name = "JSON", requires = "event_key")]
319        event_data: Option<String>,
320        /// And when it happened (as `--for`); the run's moment otherwise.
321        #[arg(long, value_name = "TIME", requires = "event_key")]
322        event_at: Option<String>,
323        /// A connection's values for the run, given instead of its own: `name={"param":
324        /// value}` (stored JSON); its function runs with them.
325        #[arg(long = "connection", value_name = "CONNECTION")]
326        connections: Vec<String>,
327        /// Run only this task and its upstream tasks.
328        #[arg(long, value_name = "TASK_ID")]
329        task: Option<String>,
330        /// The DAG files: a directory (a DAG root) or one file; default: the configured DAG
331        /// roots (`SCHEDR_DAG_PATH`), else the current directory.
332        #[arg(long, value_name = "PATH")]
333        path: Option<PathBuf>,
334    },
335}
336
337/// `schedr runs ...`.
338#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
339pub enum RunsCommand {
340    /// Trigger a manual run.
341    Trigger {
342        /// The DAG's ID.
343        dag: String,
344        /// The moment the run is for (UTC without an offset); default: now.
345        #[arg(long = "for", value_name = "TIME")]
346        planned_for: Option<String>,
347        /// A run parameter: `key=value` or `key:=json`.
348        #[arg(short = 'p', long = "param", value_name = "FIELD")]
349        params: Vec<String>,
350        /// All run parameters as one JSON object.
351        #[arg(long = "params", value_name = "JSON", conflicts_with = "params")]
352        params_json: Option<String>,
353        /// For a DAG a trigger starts: run again an event it found, by key.
354        #[arg(long, value_name = "KEY", conflicts_with_all = ["event_key", "event_data", "event_at"])]
355        event: Option<String>,
356        /// Or give an event: its key. It is never stored as an event.
357        #[arg(long, value_name = "KEY")]
358        event_key: Option<String>,
359        /// And its data: JSON, or `@file.json`.
360        #[arg(long, value_name = "JSON", requires = "event_key")]
361        event_data: Option<String>,
362        /// And when it happened (as `--for`); the run's moment otherwise.
363        #[arg(long, value_name = "TIME", requires = "event_key")]
364        event_at: Option<String>,
365    },
366    /// List the runs of a DAG.
367    List {
368        /// The DAG's ID.
369        dag: String,
370        /// Only the runs for this moment.
371        #[arg(long = "for", value_name = "TIME")]
372        planned_for: Option<String>,
373    },
374    /// Show a run and its tasks (a mapped task's instances as `fetch[0]`, `fetch[1]`, ...).
375    Show {
376        /// The run's ID.
377        run_id: String,
378    },
379    /// Cancel a run, or what's left of a backfill.
380    #[command(group(clap::ArgGroup::new("target").required(true).args(["run_id", "backfill"])))]
381    Cancel {
382        /// The run's ID.
383        run_id: Option<String>,
384        /// Cancel the remaining runs of this backfill instead.
385        #[arg(long, value_name = "BACKFILL_ID")]
386        backfill: Option<String>,
387    },
388    /// Create one run per fire time in a range.
389    Backfill {
390        /// The DAG's ID.
391        dag: String,
392        /// The range's first moment (inclusive; UTC without an offset).
393        #[arg(long, value_name = "TIME")]
394        from: String,
395        /// Its last moment (inclusive); default: now, and a later one ends at now.
396        #[arg(long, value_name = "TIME")]
397        to: Option<String>,
398        /// A run for every fire time, also those with a successful, queued or running run.
399        #[arg(long)]
400        all: bool,
401        /// A run parameter, for every run: `key=value` or `key:=json`.
402        #[arg(short = 'p', long = "param", value_name = "FIELD")]
403        params: Vec<String>,
404        /// All run parameters as one JSON object.
405        #[arg(long = "params", value_name = "JSON", conflicts_with = "params")]
406        params_json: Option<String>,
407        /// Only count the fire times and the runs it would create.
408        #[arg(long)]
409        dry_run: bool,
410    },
411}
412
413/// The task a `schedr tasks` command acts on.
414#[derive(Debug, Clone, PartialEq, Eq, Args)]
415pub struct TaskTarget {
416    /// The run's ID.
417    pub run_id: String,
418    /// The task's ID.
419    pub task_id: String,
420    /// The instance of a mapped task.
421    #[arg(long, value_name = "N")]
422    pub map_index: Option<u32>,
423}
424
425/// `schedr tasks logs ...`.
426#[derive(Debug, Clone, PartialEq, Eq, Args)]
427pub struct LogsArgs {
428    /// The task.
429    #[command(flatten)]
430    pub target: TaskTarget,
431    /// The attempt's try number (the latest by default).
432    #[arg(long = "try", value_name = "N")]
433    pub try_number: Option<u32>,
434    /// Keep printing the log while the task runs.
435    #[arg(long, short)]
436    pub follow: bool,
437}
438
439/// `schedr tasks ...`.
440#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
441pub enum TasksCommand {
442    /// Cancel one running task.
443    Cancel(TaskTarget),
444    /// Retry an `unschedulable` task of an unfinished run.
445    Retry(TaskTarget),
446    /// Print an attempt's log, read from the worker that ran it.
447    Logs(LogsArgs),
448    /// List a task's attempts (of one instance, for a mapped task).
449    Attempts(TaskTarget),
450    /// Print a task's output (a mapped task's gathered list, or one instance's).
451    Output(TaskTarget),
452}
453
454/// `schedr connections ...` (decisions 174, 193, 198-200): run on a worker, through the
455/// master.
456#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
457pub enum ConnectionsCommand {
458    /// Render every connection of a root (all roots if none is given) with the worker's
459    /// storages: each secret present or missing, never a value. Fails when one isn't.
460    Check {
461        /// The root; every root with connections if not given.
462        root: Option<String>,
463        /// Only this connection.
464        #[arg(long)]
465        name: Option<String>,
466        /// The worker to run it on; one having the root's current code otherwise.
467        #[arg(long)]
468        worker: Option<String>,
469    },
470    /// Open a connection on a worker and run its check (or open and close it, without one).
471    /// Fails when it doesn't work.
472    Test {
473        /// The connection.
474        name: String,
475        /// Its root, when several define one by that name.
476        #[arg(long)]
477        root: Option<String>,
478        /// The worker to run it on; one having the root's current code otherwise.
479        #[arg(long)]
480        worker: Option<String>,
481        /// How long it may take (`30s`, `2m`); `[webserver] connection_test_timeout` if not
482        /// given.
483        #[arg(long, value_parser = test_timeout)]
484        timeout: Option<std::time::Duration>,
485    },
486}
487
488fn test_timeout(text: &str) -> Result<std::time::Duration, String> {
489    let timeout = schedr_config::units::parse_duration(text).map_err(|e| e.to_string())?;
490    let most = std::time::Duration::from_millis(schedr_model::commands::MAX_CONNECTION_TEST_MS);
491    if timeout.is_zero() || timeout > most {
492        return Err(format!("1 ms to {} s", most.as_secs()));
493    }
494    Ok(timeout)
495}
496
497/// `schedr triggers ...` (decision 340's reasons: they are not tasks).
498#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
499pub enum TriggersCommand {
500    /// List every DAG's trigger.
501    List,
502    /// Show a DAG's trigger.
503    Show {
504        /// Its DAG.
505        dag: String,
506    },
507    /// List what a DAG's trigger found, newest first.
508    Events {
509        /// Its DAG.
510        dag: String,
511        /// How many at most.
512        #[arg(long, default_value_t = 50)]
513        limit: u32,
514    },
515    /// Start a DAG's trigger again from its bookmark, whatever stopped it.
516    Restart {
517        /// Its DAG.
518        dag: String,
519    },
520    /// Pass the run an `@trigger(wait_for=...)` keeps failing on: it is called for the next.
521    Skip {
522        /// Its DAG.
523        dag: String,
524    },
525    /// Switch a DAG's trigger back on, forgetting its strikes.
526    SwitchOn {
527        /// Its DAG.
528        dag: String,
529    },
530}
531
532/// `schedr events ...` (decision 354).
533#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
534pub enum EventsCommand {
535    /// Post an event: a trigger on its name starts a run per key, a step waiting for it in a
536    /// run goes on.
537    Post {
538        /// Its name, written as a DAG ID is.
539        name: String,
540        /// Its key.
541        #[arg(long)]
542        key: String,
543        /// Its data: JSON, or `@file.json`.
544        #[arg(long, value_name = "JSON")]
545        data: Option<String>,
546        /// When it happened (UTC without an offset); now otherwise.
547        #[arg(long, value_name = "TIME")]
548        at: Option<String>,
549    },
550    /// List the events posted, newest first.
551    List {
552        /// Only those of this name.
553        #[arg(long)]
554        name: Option<String>,
555        /// How many at most.
556        #[arg(long, default_value_t = 50)]
557        limit: u32,
558    },
559}
560
561/// `schedr sensors ...` (decision 338).
562#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
563pub enum SensorsCommand {
564    /// List the wait steps switched off.
565    SwitchedOff,
566    /// Switch a wait step back on, forgetting its strikes.
567    SwitchOn {
568        /// Its DAG.
569        dag: String,
570        /// The wait step's task ID.
571        sensor: String,
572    },
573}
574
575/// `schedr resources ...` (decision 340).
576#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
577pub enum ResourcesCommand {
578    /// List a run's resources.
579    List {
580        /// The run.
581        run: String,
582    },
583}
584
585/// `schedr workers ...`.
586#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
587pub enum WorkersCommand {
588    /// List the workers the master has seen, with their state (gone ones included).
589    List,
590    /// Drain a worker for maintenance: it finishes its tasks and stays idle.
591    Drain {
592        /// The worker's ID.
593        worker: String,
594    },
595    /// Let a drained worker take tasks again.
596    Resume {
597        /// The worker's ID.
598        worker: String,
599    },
600}
601
602/// A `--field NAME` option of the in-task CLI: print raw values instead of JSON.
603#[derive(Debug, Clone, PartialEq, Eq, Args)]
604pub struct FieldArg {
605    /// Print this field's raw values, one per line.
606    #[arg(long, value_name = "NAME")]
607    pub field: Option<String>,
608}
609
610/// `schedr task-ctx ...`.
611#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
612pub enum TaskCtxCommand {
613    /// Cleanup handles of the running attempt.
614    Cleanup {
615        /// The cleanup command.
616        #[command(subcommand)]
617        command: CleanupCommand,
618    },
619    /// The value of the resource this setup creates, or this cleanup cleans up.
620    Resource {
621        /// The resource command.
622        #[command(subcommand)]
623        command: ResourceCommand,
624    },
625    /// Secrets declared in the task's `secrets=`.
626    Secret {
627        /// The secret command.
628        #[command(subcommand)]
629        command: SecretCommand,
630    },
631    /// A connection the task declares (`connections=`): its values, its secrets filled in.
632    Connection(ConnectionArgs),
633    /// A request to schedr's REST API, made as this task (open to tasks: `POST` and `GET
634    /// /api/v1/events`); prints the answer's JSON, fails on an error status.
635    Api {
636        /// `GET`, `POST`, ...
637        method: String,
638        /// The path and its query, e.g. `/api/v1/events?name=paid`.
639        path: String,
640        /// The body, JSON.
641        #[arg(long, value_name = "JSON")]
642        data: Option<String>,
643        /// Sent again with the same key, the request is the one made the first time.
644        #[arg(long, value_name = "KEY")]
645        idempotency_key: Option<String>,
646    },
647    /// Events (`EventNamed`), posted and listed as this task.
648    Events {
649        /// The events command.
650        #[command(subcommand)]
651        command: TaskEventsCommand,
652    },
653    /// Sends a message to a notification channel of the task's DAG (or a server one); the
654    /// master fills the channel's body and delivers it later.
655    Notify {
656        /// The channel's name.
657        channel: String,
658        /// Its text (the `text` placeholder; schedr's summary otherwise).
659        #[arg(long)]
660        text: Option<String>,
661        /// Its data (the `data` placeholder): JSON, or `@file.json`.
662        #[arg(long, value_name = "JSON")]
663        data: Option<String>,
664    },
665}
666
667/// `schedr task-ctx events ...`: as `schedr events`, made as the task.
668#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
669pub enum TaskEventsCommand {
670    /// Post an event; prints it as stored, as one line of JSON.
671    Post {
672        /// Its name, written as a DAG ID is.
673        name: String,
674        /// Its key: a trigger starts one run per key, a waiting step matches its own.
675        #[arg(long)]
676        key: String,
677        /// Its data: JSON, or `@file.json`.
678        #[arg(long, value_name = "JSON")]
679        data: Option<String>,
680        /// When it happened (UTC without an offset); now otherwise.
681        #[arg(long, value_name = "TIME")]
682        at: Option<String>,
683        /// Sent again with the same key (a retried task), it is the event stored the first
684        /// time.
685        #[arg(long, value_name = "KEY")]
686        idempotency_key: Option<String>,
687    },
688    /// List the events posted, newest first, one line of JSON each.
689    List {
690        /// Only those of this name.
691        #[arg(long)]
692        name: Option<String>,
693        /// How many at most (500 at most).
694        #[arg(long, default_value_t = 50)]
695        limit: u32,
696    },
697}
698
699/// `schedr task-ctx cleanup ...`.
700#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
701pub enum CleanupCommand {
702    /// Register a handle (`key=value`, `key:=json`), before the work it cleans up after.
703    Add {
704        /// The handle's type name, e.g. `ExportJob`.
705        handle_type: String,
706        /// The handle's fields.
707        fields: Vec<String>,
708        /// The whole handle as one JSON object.
709        #[arg(long, value_name = "JSON")]
710        json: Option<String>,
711    },
712    /// List the handles, in a cleanup.
713    List {
714        /// Only handles of this type.
715        handle_type: Option<String>,
716        /// How to print them.
717        #[command(flatten)]
718        field: FieldArg,
719    },
720}
721
722/// `schedr task-ctx resource ...`.
723#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
724pub enum ResourceCommand {
725    /// Report the resource's value, in its setup.
726    Set {
727        /// The value's fields (`key=value`, `key:=json`).
728        fields: Vec<String>,
729        /// The whole value as JSON, of any type (`--json 7`).
730        #[arg(long, value_name = "JSON")]
731        json: Option<String>,
732    },
733    /// Read the resource's value, in its cleanup.
734    Get {
735        /// How to print it.
736        #[command(flatten)]
737        field: FieldArg,
738    },
739}
740
741/// `schedr task-ctx secret ...`.
742#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
743pub enum SecretCommand {
744    /// Print a declared secret: a key's value as it is, with no trailing newline; a whole
745    /// secret (`path` without `#key`) as one line of JSON.
746    Get {
747        /// `path#key`, or `path` for the whole secret.
748        secret: String,
749        /// The secret storage, if not the default one.
750        #[arg(long, value_name = "NAME")]
751        storage: Option<String>,
752    },
753}
754
755/// `schedr task-ctx connection NAME [--env PREFIX | --json]`.
756#[derive(Debug, Clone, PartialEq, Eq, clap::Args)]
757pub struct ConnectionArgs {
758    /// The connection's name (its function's).
759    pub name: String,
760    /// Print `export PREFIX_PARAM='value'` lines for `eval`, one per parameter (the
761    /// parameter's name in capitals; a value that isn't text as JSON).
762    #[arg(long, value_name = "PREFIX")]
763    pub env: Option<String>,
764    /// Print the values as one line of JSON (the default).
765    #[arg(long, conflicts_with = "env")]
766    pub json: bool,
767}
768
769/// `schedr dag-ctx ...`.
770#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
771pub enum DagCtxCommand {
772    /// The run's parameters.
773    Params {
774        /// The parameters command.
775        #[command(subcommand)]
776        command: GetCommand,
777    },
778    /// The run information (`id`, `kind`, `planned_for`, `since`, ...).
779    Run {
780        /// The run information command.
781        #[command(subcommand)]
782        command: GetCommand,
783    },
784}
785
786/// A `get` subcommand.
787#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
788pub enum GetCommand {
789    /// Print the values as JSON, or one field's raw value.
790    Get {
791        /// How to print them.
792        #[command(flatten)]
793        field: FieldArg,
794    },
795}
796
797impl Command {
798    /// The configuration its options give, over the file and the environment: `standalone`'s
799    /// `--dag-path` and `--script-path` (decision 488), each path as [`root_path`] makes it.
800    ///
801    /// # Errors
802    ///
803    /// A path that isn't UTF-8, naming the flag: the configuration's paths are text, and a
804    /// lossy copy could name another folder (Codex's review of M5.1n).
805    pub fn overrides(&self, cwd: &Path) -> Result<Vec<Override>, String> {
806        let Self::Standalone {
807            dag_path,
808            script_path,
809            ..
810        } = self
811        else {
812            return Ok(Vec::new());
813        };
814        let mut overrides = Vec::new();
815        for (key, flag, paths) in [
816            ("dags.path", "--dag-path", dag_path),
817            ("scripts.path", "--script-path", script_path),
818        ] {
819            if paths.is_empty() {
820                continue;
821            }
822            let mut list = Vec::new();
823            for path in paths {
824                let root = root_path(cwd, path);
825                let text = root.to_str().ok_or_else(|| {
826                    format!(
827                        "{flag}: `{}` isn't UTF-8; rename the folder",
828                        root.display()
829                    )
830                })?;
831                list.push(text.to_owned());
832            }
833            overrides.push(Override {
834                key: key.to_owned(),
835                value: OverrideValue::List(list),
836                flag: flag.to_owned(),
837            });
838        }
839        Ok(overrides)
840    }
841
842    /// Its webserver client's arguments, for a command reaching one.
843    pub const fn client_args_mut(&mut self) -> Option<&mut ClientArgs> {
844        match self {
845            Self::Dags { client, .. }
846            | Self::Runs { client, .. }
847            | Self::Tasks { client, .. }
848            | Self::Connections { client, .. }
849            | Self::Sensors { client, .. }
850            | Self::Triggers { client, .. }
851            | Self::Events { client, .. }
852            | Self::Resources { client, .. }
853            | Self::Workers { client, .. } => Some(client),
854            _ => None,
855        }
856    }
857
858    /// The milestone in which this command starts working (see archive/PROJECT.md, Roadmap), or
859    /// `None` if it works already.
860    #[must_use]
861    pub const fn milestone(&self) -> Option<&'static str> {
862        match self {
863            Self::Db { .. }
864            | Self::Secrets { .. }
865            | Self::Dags { .. }
866            | Self::Runs { .. }
867            | Self::Standalone { .. }
868            | Self::Master { .. }
869            | Self::Worker
870            | Self::Webserver
871            | Self::Ui
872            | Self::Tasks { .. }
873            | Self::Workers { .. }
874            | Self::Sensors { .. }
875            | Self::Triggers { .. }
876            | Self::Events { .. }
877            | Self::Resources { .. }
878            | Self::Connections { .. }
879            | Self::DagCtx { .. }
880            | Self::TaskExec { .. }
881            | Self::TaskCtx { .. } => None,
882        }
883    }
884
885    /// The command's name as typed, e.g. `master` or `runs`, for messages.
886    #[must_use]
887    pub const fn name(&self) -> &'static str {
888        match self {
889            Self::Master { .. } => "master",
890            Self::Worker => "worker",
891            Self::Webserver => "webserver",
892            Self::Ui => "ui",
893            Self::Standalone { .. } => "standalone",
894            Self::Db { .. } => "db",
895            Self::Secrets { .. } => "secrets",
896            Self::Dags { .. } => "dags",
897            Self::Runs { .. } => "runs",
898            Self::Tasks { .. } => "tasks",
899            Self::Workers { .. } => "workers",
900            Self::Sensors { .. } => "sensors",
901            Self::Triggers { .. } => "triggers",
902            Self::Events { .. } => "events",
903            Self::Resources { .. } => "resources",
904            Self::Connections { .. } => "connections",
905            Self::TaskCtx { .. } => "task-ctx",
906            Self::DagCtx { .. } => "dag-ctx",
907            Self::TaskExec { .. } => "task-exec",
908        }
909    }
910}
911
912/// The root a `--dag-path` names: the path as given (its `.` components dropped), as the
913/// variable's entries are, so a rename in `[dags.roots]` matches it; only a path with no name of
914/// its own is resolved: `.` is `cwd`, and one ending in `..` its real path on the filesystem (a
915/// lexical `..` would be wrong past a symbolic link; a missing one is left, and refused unnamed).
916#[must_use]
917pub fn root_path(cwd: &Path, path: &Path) -> PathBuf {
918    let kept: PathBuf = path
919        .components()
920        .filter(|c| !matches!(c, Component::CurDir))
921        .collect();
922    match kept.components().next_back() {
923        None => cwd.to_path_buf(),
924        Some(Component::ParentDir) => {
925            let joined = cwd.join(&kept);
926            std::fs::canonicalize(&joined).unwrap_or(joined)
927        }
928        Some(_) => kept,
929    }
930}