1use 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#[derive(Debug, thiserror::Error)]
21pub enum AppError {
22 #[error("can't read the configuration file `{path}`: {reason}")]
24 ReadConfig {
25 path: String,
27 reason: String,
29 },
30 #[error(transparent)]
32 Config(#[from] ConfigError),
33 #[error(transparent)]
35 Db(#[from] DbError),
36 #[error("no database configured: set `SCHEDR_CONFIG__DATABASE__URL` (or [database] url)")]
38 NoDatabase,
39 #[error("`schedr {command}` isn't implemented yet (milestone {milestone})")]
41 NotImplemented {
42 command: &'static str,
44 milestone: &'static str,
46 },
47 #[error(transparent)]
49 Client(#[from] ClientError),
50 #[error("{0}")]
52 BadArgument(String),
53 #[error("{0}")]
56 Failed(String),
57 #[error("can't write output: {0}")]
59 Output(#[from] io::Error),
60}
61
62impl AppError {
63 #[must_use]
66 pub const fn exit_code(&self) -> u8 {
67 1
68 }
69}
70
71pub 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
86pub 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#[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
138pub 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
174pub 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 (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 (
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
265pub fn local_config(config: &Config, env: &BTreeMap<String, String>) -> Result<Config, AppError> {
272 role_config(config, env, true)
273}
274
275pub 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#[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#[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}