Skip to main content

schedr_bin/
app.rs

1//! Running a parsed command: loading the configuration and dispatching to the command.
2
3use std::collections::BTreeMap;
4use std::io::{self, Write};
5use std::path::Path;
6
7use schedr_config::{Config, ConfigError, FileSource, Override, config_file, load};
8use schedr_db::{Database, DbError, SchemaStatus, redact_password};
9
10use crate::cli::{ClientArgs, Command, DagsCommand, DbCommand};
11use crate::client::{Auth, Client, ClientError, HttpTransport, POLL_INTERVAL};
12use crate::interpreter::{Host, apply};
13use crate::times::local_zone;
14use crate::user::{Output, run_dags, run_runs, run_tasks, run_workers};
15
16#[cfg(test)]
17mod tests;
18
19/// Why a command failed; the binary prints it and exits with [`AppError::exit_code`].
20#[derive(Debug, thiserror::Error)]
21pub enum AppError {
22    /// The configuration file named by `--config` or `SCHEDR_CONFIG_FILE` can't be read.
23    #[error("can't read the configuration file `{path}`: {reason}")]
24    ReadConfig {
25        /// The file.
26        path: String,
27        /// The I/O error.
28        reason: String,
29    },
30    /// The configuration is invalid.
31    #[error(transparent)]
32    Config(#[from] ConfigError),
33    /// A database operation failed.
34    #[error(transparent)]
35    Db(#[from] DbError),
36    /// The command needs a database and none is configured.
37    #[error("no database configured: set `SCHEDR_CONFIG__DATABASE__URL` (or [database] url)")]
38    NoDatabase,
39    /// The command exists but isn't implemented in this version yet.
40    #[error("`schedr {command}` isn't implemented yet (milestone {milestone})")]
41    NotImplemented {
42        /// The command's name.
43        command: &'static str,
44        /// The milestone that brings it (archive/PROJECT.md, Roadmap).
45        milestone: &'static str,
46    },
47    /// Talking to the schedr server failed, or the master rejected the command.
48    #[error(transparent)]
49    Client(#[from] ClientError),
50    /// An argument doesn't read (e.g. a `--for` time).
51    #[error("{0}")]
52    BadArgument(String),
53    /// The command did its job and the answer is "no": checks found errors, a run didn't
54    /// succeed.
55    #[error("{0}")]
56    Failed(String),
57    /// Writing the command's output failed.
58    #[error("can't write output: {0}")]
59    Output(#[from] io::Error),
60}
61
62impl AppError {
63    /// The process exit code: always 1 (2 is reserved for wrong usage, reported by the
64    /// argument parser).
65    #[must_use]
66    pub const fn exit_code(&self) -> u8 {
67        1
68    }
69}
70
71/// Loads the configuration: chooses the file, reads it with `read`, and layers the
72/// environment on top. A missing default file is fine; a missing explicit one is an error.
73///
74/// # Errors
75///
76/// Returns [`AppError::ReadConfig`] if an explicitly named file can't be read, or
77/// [`AppError::Config`] if the configuration is invalid.
78pub fn load_config(
79    flag: Option<&Path>,
80    env: &BTreeMap<String, String>,
81    read: impl Fn(&Path) -> io::Result<String>,
82) -> Result<Config, AppError> {
83    load_config_with(flag, env, read, &[])
84}
85
86/// As [`load_config`], with the command's options over the file and the environment.
87///
88/// # Errors
89///
90/// As [`load_config`].
91pub fn load_config_with(
92    flag: Option<&Path>,
93    env: &BTreeMap<String, String>,
94    read: impl Fn(&Path) -> io::Result<String>,
95    overrides: &[Override],
96) -> Result<Config, AppError> {
97    let file = config_file(flag, env);
98    let contents = match read(file.path()) {
99        Ok(contents) => Some(contents),
100        Err(e) if e.kind() == io::ErrorKind::NotFound && !file.is_required() => None,
101        Err(e) => {
102            return Err(AppError::ReadConfig {
103                path: file.path().display().to_string(),
104                reason: e.to_string(),
105            });
106        }
107    };
108    let source = contents.as_deref().map(|contents| FileSource {
109        path: file.path(),
110        contents,
111    });
112    Ok(load(source, env, overrides)?)
113}
114
115/// A human-readable description of a schema status.
116#[must_use]
117pub fn describe_status(status: &SchemaStatus) -> String {
118    match status {
119        SchemaStatus::Uninitialized => "uninitialized: run `schedr db migrate`".to_owned(),
120        SchemaStatus::UpToDate => "up to date".to_owned(),
121        SchemaStatus::Outdated { missing } => {
122            format!(
123                "outdated: {} migration(s) missing; run `schedr db migrate`",
124                missing.len()
125            )
126        }
127        SchemaStatus::Modified { changed } => format!(
128            "created by an earlier schedr: {} migration(s) differ from this one's, so it needs a fresh database (see the CHANGELOG)",
129            changed.len()
130        ),
131        SchemaStatus::Newer { unknown } => format!(
132            "newer than this schedr ({} unknown migration(s)); usable within the same major version",
133            unknown.len()
134        ),
135    }
136}
137
138/// Runs a `schedr db` command against the configured database.
139///
140/// # Errors
141///
142/// Returns [`AppError::NoDatabase`] without a database URL, or [`AppError::Db`] if
143/// connecting or migrating fails.
144pub async fn run_db(
145    command: DbCommand,
146    config: &Config,
147    out: &mut impl Write,
148) -> Result<(), AppError> {
149    let url = config.database.url.as_deref().ok_or(AppError::NoDatabase)?;
150    match command {
151        DbCommand::Migrate { wait } => {
152            crate::roles::migrate_leased(
153                url,
154                config.timings.query_timeout,
155                (config.timings.lease_period, wait),
156                config.database.change_notifications,
157            )
158            .await?;
159            writeln!(out, "migrated {}: schema up to date", redact_password(url))?;
160        }
161        DbCommand::Status => {
162            let status = Database::connect(url).await?.schema_status().await?;
163            writeln!(
164                out,
165                "{}: {}",
166                redact_password(url),
167                describe_status(&status)
168            )?;
169        }
170    }
171    Ok(())
172}
173
174/// Runs a parsed command.
175///
176/// # Errors
177///
178/// Returns the command's [`AppError`]; commands of later milestones return
179/// [`AppError::NotImplemented`].
180pub async fn execute(
181    command: &Command,
182    config: &Config,
183    env: &BTreeMap<String, String>,
184    out: &mut impl Write,
185    err: &mut impl Write,
186) -> Result<(), AppError> {
187    match (command, command.milestone()) {
188        (Command::Db { command }, _) => run_db(*command, config, out).await,
189        // Boxed, as the roles are: it would make every command's future large.
190        (Command::Secrets { command }, _) => {
191            let mut stdin = io::stdin().lock();
192            Box::pin(crate::secrets::run(command, config, env, &mut stdin, out)).await
193        }
194        // Boxed: the roles' futures are large, and only one of them ever runs.
195        (
196            Command::Standalone {
197                listen,
198                migrate,
199                no_ui,
200                ..
201            },
202            None,
203        ) => {
204            Box::pin(crate::standalone::command(
205                &local_config(config, env)?,
206                env,
207                *listen,
208                (*migrate, *no_ui),
209            ))
210            .await
211        }
212        (Command::Master { migrate }, None) => {
213            Box::pin(crate::roles::master(config, *migrate)).await
214        }
215        (Command::Webserver, None) => Box::pin(crate::roles::webserver(config)).await,
216        (Command::Ui, None) => Box::pin(crate::roles::ui(config)).await,
217        (Command::Worker, None) => Box::pin(crate::roles::worker(config, env)).await,
218        (
219            Command::Dags {
220                client,
221                command: command @ (DagsCommand::Check { .. } | DagsCommand::Test { .. }),
222            },
223            None,
224        ) => {
225            let config = local_config(config, env)?;
226            Box::pin(crate::local::run_local(command, &config, env, client, out)).await
227        }
228        (Command::Dags { client, command }, None) => {
229            let (api, output) = connect(client, env);
230            run_dags(command, &api, &output, out).await
231        }
232        (Command::Connections { client, command }, None) => {
233            let (api, output) = connect(client, env);
234            crate::user::run_connections(command, &api, &output, out).await
235        }
236        (Command::Workers { client, command }, None) => workers(command, client, env, out).await,
237        (Command::Sensors { client, command }, None) => sensors(command, client, env, out).await,
238        (Command::Triggers { client, command }, None) => triggers(command, client, env, out).await,
239        (Command::Resources { client, command }, None) => {
240            resources(command, client, env, out).await
241        }
242        (Command::Events { client, command }, None) => events(command, client, env, out, err).await,
243        (Command::Runs { client, command }, None) => {
244            let (api, output) = connect(client, env);
245            run_runs(command, &api, &output, out, err).await
246        }
247        (Command::Tasks { client, command }, None) => {
248            let (api, output) = connect(client, env);
249            run_tasks(command, &api, &output, out).await
250        }
251        (Command::DagCtx { command }, None) => {
252            crate::ctx::run_dag_ctx(command, env, crate::VERSION, out).map_err(AppError::Failed)
253        }
254        (Command::TaskCtx { command }, None) => {
255            crate::ctx::run_task_ctx(command, env, crate::VERSION, (out, err))
256                .map_err(AppError::Failed)
257        }
258        (other, milestone) => Err(AppError::NotImplemented {
259            command: other.name(),
260            milestone: milestone.unwrap_or("unknown"),
261        }),
262    }
263}
264
265/// The configuration of a local command (`standalone`, `dags check`, `dags test`): the built-in
266/// `python` interpreter looked for from here (see [`crate::interpreter`]).
267///
268/// # Errors
269///
270/// [`AppError::BadArgument`] if a pyenv shim can't be resolved.
271pub fn local_config(config: &Config, env: &BTreeMap<String, String>) -> Result<Config, AppError> {
272    role_config(config, env, true)
273}
274
275/// The configuration with the built-in `python` interpreter looked for (see
276/// [`crate::interpreter::apply`]): `project` on for the local commands, off for a worker.
277///
278/// # Errors
279///
280/// [`AppError::BadArgument`] if a pyenv shim can't be resolved.
281pub fn role_config(
282    config: &Config,
283    env: &BTreeMap<String, String>,
284    project: bool,
285) -> Result<Config, AppError> {
286    let mut config = config.clone();
287    let cwd = std::env::current_dir().ok();
288    let exe = std::env::current_exe().ok();
289    let host = Host {
290        env,
291        cwd: cwd.as_deref(),
292        exe: exe.as_deref(),
293    };
294    apply(&mut config, &host, project).map_err(|e| AppError::BadArgument(e.to_string()))?;
295    Ok(config)
296}
297
298/// The API client for `url`: the CLI's credentials and the same poll, wait, connect and
299/// request timeouts as every other server command.
300///
301/// Bearer (`--token`) wins over HTTP Basic (`--user`, password from `SCHEDR_PASSWORD`).
302#[must_use]
303pub fn connect_to(
304    url: &str,
305    args: &ClientArgs,
306    env: &BTreeMap<String, String>,
307) -> Client<HttpTransport> {
308    let auth = Auth::from_cli(
309        args.token.as_deref(),
310        args.user.as_deref(),
311        env.get("SCHEDR_PASSWORD").map(String::as_str),
312    );
313    Client::new(
314        HttpTransport::new(url, auth).with_timeouts(args.timeouts),
315        POLL_INTERVAL,
316        args.timeouts.command_wait,
317    )
318}
319
320/// The client and output settings of a user CLI command: the server ([`connect_to`]),
321/// credentials (the password from `SCHEDR_PASSWORD`), `--json` and the local zone (`TZ`, else
322/// the system's).
323#[must_use]
324pub fn connect(
325    args: &ClientArgs,
326    env: &BTreeMap<String, String>,
327) -> (Client<HttpTransport>, Output) {
328    let client = connect_to(&args.server, args, env);
329    let output = Output {
330        json: args.json,
331        local: local_zone(env.get("TZ").map(String::as_str)),
332    };
333    (client, output)
334}
335
336async fn sensors(
337    command: &crate::cli::SensorsCommand,
338    client: &crate::cli::ClientArgs,
339    env: &BTreeMap<String, String>,
340    out: &mut impl Write,
341) -> Result<(), AppError> {
342    let (api, output) = connect(client, env);
343    crate::user::run_sensors(command, &api, &output, out).await
344}
345
346async fn workers(
347    command: &crate::cli::WorkersCommand,
348    client: &crate::cli::ClientArgs,
349    env: &BTreeMap<String, String>,
350    out: &mut impl Write,
351) -> Result<(), AppError> {
352    let (api, output) = connect(client, env);
353    run_workers(command, &api, &output, out).await
354}
355
356async fn triggers(
357    command: &crate::cli::TriggersCommand,
358    client: &crate::cli::ClientArgs,
359    env: &BTreeMap<String, String>,
360    out: &mut impl Write,
361) -> Result<(), AppError> {
362    let (api, output) = connect(client, env);
363    crate::user::run_triggers(command, &api, &output, out).await
364}
365
366async fn events(
367    command: &crate::cli::EventsCommand,
368    client: &crate::cli::ClientArgs,
369    env: &BTreeMap<String, String>,
370    out: &mut impl Write,
371    err: &mut impl Write,
372) -> Result<(), AppError> {
373    let (api, output) = connect(client, env);
374    crate::user::run_events(command, &api, &output, out, err).await
375}
376
377async fn resources(
378    command: &crate::cli::ResourcesCommand,
379    client: &crate::cli::ClientArgs,
380    env: &BTreeMap<String, String>,
381    out: &mut impl Write,
382) -> Result<(), AppError> {
383    let (api, output) = connect(client, env);
384    crate::user::run_resources(command, &api, &output, out).await
385}